language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 13,894 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import datetime
import json
import os
from typing import Optional
import click
import pandas as pd
import requests
import seaborn as sns
from gender_guesser.detector import Detector
from matplotlib import pyplot as plt
from tqdm import tqdm
HERE = os.path.abspath(os.path.dirname(__file__))
FIGSHARE_DIRECTORY = os.path.join(HERE, 'figshare')
os.makedirs(FIGSHARE_DIRECTORY, exist_ok=True)
token_option = click.option('--token')
directory_option = click.option('--directory', default=HERE, type=click.Path(file_okay=False, dir_okay=True))
class FigshareClient:
"""Handle FigShare API requests, using an access token.
Adapted from https://github.com/fxcoudert/tools/blob/master/chemRxiv/chemRxiv.py.
"""
base = 'https://api.figshare.com/v2'
def __init__(self, token: Optional[str] = None, page_size: Optional[int] = None):
if token is None:
with open(os.path.expanduser('~/.config/figshare/chemrxiv.txt'), 'r') as file:
token = file.read().strip()
self.page_size = page_size or 500
self.token = token
self.headers = {'Authorization': f'token {self.token}'}
r = requests.get(f'{self.base}/account', headers=self.headers)
r.raise_for_status()
#: Got from https://docs.figshare.com/#private_institution_details
institution_details = self.query('account/institution')
self.institution = institution_details['id']
self.institution_name = institution_details['name']
self.institution_directory = os.path.join(FIGSHARE_DIRECTORY, self.institution_name.lower())
self.articles_short_directory = os.path.join(self.institution_directory, 'articles_short')
self.articles_long_directory = os.path.join(self.institution_directory, 'articles_long')
@classmethod
def get_institution_name(cls, token=None) -> str:
return cls(token=token).institution_name
def request(self, url, *, params=None):
"""Send a FigShare API request."""
return requests.get(url, headers=self.headers, params=params)
def query(self, query, *, params=None):
"""Perform a direct query."""
r = self.request(f'{self.base}/{query.lstrip("/")}', params=params)
r.raise_for_status()
return r.json()
def query_generator(self, query, params=None):
"""Query for a list of items, with paging. Returns a generator."""
if params is None:
params = {}
page = 1
while True:
params.update({'page_size': self.page_size, 'page': page})
r = self.request(f'{self.base}/{query}', params=params)
if r.status_code == 400:
raise ValueError(r.json()['message'])
r.raise_for_status()
r = r.json()
# Special case if a single item, not a list, was returned
if not isinstance(r, list):
yield r
return
# If we have no more results, bail out
if len(r) == 0:
return
yield from r
page += 1
def all_preprints(self):
"""Return a generator to all the chemRxiv articles_short.
.. seealso:: https://docs.figshare.com/#articles_list
"""
return self.query_generator('articles', params={'institution': self.institution})
def preprint(self, article_id):
"""Information on a given preprint.
.. seealso:: https://docs.figshare.com/#public_article
"""
return self.query(f'articles/{article_id}')
def download_short(self) -> None:
os.makedirs(self.articles_short_directory, exist_ok=True)
for preprint in tqdm(self.all_preprints(), desc='Getting all articles_short'):
preprint_id = preprint['id']
path = os.path.join(self.articles_short_directory, f'{preprint_id}.json')
if os.path.exists(path):
continue
with open(path, 'w') as file:
json.dump(preprint, file, indent=2)
def download_full(self) -> None:
os.makedirs(self.articles_long_directory, exist_ok=True)
for filename in tqdm(os.listdir(self.articles_short_directory)):
preprint_id = int(filename[:-len('.json')])
path = os.path.join(self.articles_long_directory, f'{preprint_id}.json')
if os.path.exists(path):
continue
preprint = self.preprint(preprint_id)
with open(path, 'w') as file:
json.dump(preprint, file, indent=2)
def process_articles(self):
detector = Detector(case_sensitive=False)
# Possible gender determination alternatives:
# - https://gender-api.com/ (reference from https://twitter.com/AdamSci12/status/1323977415677382656)
# - https://genderize.io/
rows = []
for filename in tqdm(os.listdir(self.articles_long_directory)):
path = os.path.join(self.articles_long_directory, filename)
with open(path) as file:
j = json.load(file)
orcid = None
for custom_field in j.get('custom_fields', []):
if custom_field['name'] == 'ORCID For Submitting Author':
orcid = custom_field['value']
first_author_name = j['authors'][0]['full_name']
first_author_inferred_gender = detector.get_gender(first_author_name.split(' ')[0])
rows.append(dict(
id=j['id'],
title=j['title'],
posted=j['timeline']['posted'],
license=j['license']['name'],
orcid=orcid,
first_author_name=first_author_name,
first_author_inferred_gender=first_author_inferred_gender,
))
df = pd.DataFrame(rows).sort_values('id')
df.to_csv(os.path.join(self.institution_directory, 'articles_summary.tsv'), sep='\t', index=False)
def get_df(self):
return get_df(self.institution_directory)
def get_df(directory: str, exclude_current_month: bool = False) -> pd.DataFrame:
df = pd.read_csv(os.path.join(directory, 'articles_summary.tsv'), sep='\t')
null_orcid_idx = df.orcid.isna()
df = df[~null_orcid_idx]
df['orcid'] = df['orcid'].map(clean_orcid)
bad_orcid_idx = ~df.orcid.str.startswith('0000')
df = df[~bad_orcid_idx]
df['year'] = df.posted.map(lambda x: int(x.split('-')[0]))
df['month'] = df.posted.map(lambda x: int(x.split('-')[1]))
df['time'] = [f'{a - 2000}-{b:02}' for a, b in df[['year', 'month']].values]
if exclude_current_month:
df = remove_current_month(df)
return df
def remove_current_month(df: pd.DataFrame) -> pd.DataFrame:
today = datetime.date.today()
df = df[df['time'] != f'{today.year - 2000}-{today.month:02}']
return df
def prepare_genders(df: pd.DataFrame) -> pd.DataFrame:
df = remove_current_month(df)
df.loc[df['first_author_inferred_gender'] == 'mostly_male', 'first_author_inferred_gender'] = 'male'
df.loc[df['first_author_inferred_gender'] == 'mostly_female', 'first_author_inferred_gender'] = 'female'
return df
def assign_andy(df):
x = (df['first_author_inferred_gender'] == 'andy').count()
counter = 0
def _assign_andy(s: str) -> str:
if s != 'andy':
return s
if counter < x // 2:
return 'male'
return 'female'
df['first_author_inferred_gender'] = df['first_author_inferred_gender'].map(_assign_andy)
def clean_orcid(x: str) -> str:
x = x.strip().replace(' ', '').replace(';', '')
if '-' not in x:
print('PROBLEM with ORCiD', x)
if x.startswith('000-'):
return f'0{x}'
for p in ('orcid.org/', 'https://orcid.org/', 'http://orcid.org/'):
if x.startswith(p):
return x[len(p):]
return x
def plot_papers_by_month(df, directory, institution_name, figsize=(10, 6)):
# How many papers each month?
articles_by_month = df.groupby('time')['id'].count().reset_index()
plt.figure(figsize=figsize)
sns.barplot(data=articles_by_month, x='time', y='id')
plt.title(f'{institution_name} Articles per Month')
plt.xlabel('Month')
plt.ylabel('Articles')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig(os.path.join(directory, 'articles_per_month.png'), dpi=300)
def plot_unique_authors_per_month(df, directory, institution_name, figsize=(10, 6)):
# How many unique first authors each month?
unique_authors_per_month = (
df.groupby(['time', 'orcid'])
.count()
.reset_index().groupby('time')['id']
.count()
.reset_index()
)
plt.figure(figsize=figsize)
sns.barplot(data=unique_authors_per_month, x='time', y='id')
plt.title(f'{institution_name} Monthly Unique First Authorship')
plt.xlabel('Month')
plt.ylabel('Unique First Authors')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig(os.path.join(directory, 'unique_authors_per_month.png'), dpi=300)
def plot_x(df, directory, institution_name, figsize=(10, 6)):
rows = []
articles_by_month = remove_current_month(df).groupby('time')['id'].count().reset_index()
unique_authors_by_month = df.groupby(['time', 'orcid']).count().reset_index().groupby('time')['id'].count()
for (d1, c1), (_d2, c2) in zip(unique_authors_by_month.reset_index().values, articles_by_month.values):
rows.append((d1, 100 * (1 - c1 / c2)))
data = pd.DataFrame(rows, columns=['time', 'percent'])
plt.figure(figsize=figsize)
sns.lineplot(data=data, x='time', y='percent')
plt.title(f'{institution_name} Percent Duplicate First Authors Each Month')
plt.xlabel('Month')
plt.ylabel('Percent Duplicate First Authors')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig(os.path.join(directory, 'percent_duplicate_authors_per_month.png'), dpi=300)
def plot_first_time_first_authors_by_month(df, directory, institution_name, figsize=(10, 6)):
data = df.groupby('orcid')['time'].min().reset_index().groupby('time')['orcid'].count().reset_index()
plt.figure(figsize=figsize)
sns.barplot(data=data, x='time', y='orcid')
plt.title(f'{institution_name} First Time First Authors per Month')
plt.xlabel('Month')
plt.ylabel('First Time First Authors')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig(os.path.join(directory, 'first_time_first_authors_per_month.png'), dpi=300)
def plot_prolific_authors(df, directory, institution_name, figsize=(10, 6)):
# Who's prolific in this institution?
plt.figure(figsize=figsize)
author_frequencies = df.groupby('orcid')['id'].count().sort_values(ascending=False).reset_index()
sns.histplot(author_frequencies, y='id', kde=False, binwidth=4)
plt.title(f'{institution_name} First Author Prolificness')
plt.ylabel('First Author Frequency')
plt.xlabel('Number of Articles Submitted')
plt.xscale('log')
plt.tight_layout()
plt.savefig(os.path.join(directory, 'author_prolificness.png'), dpi=300)
def plot_cumulative_authors(df, directory, institution_name, figsize=(10, 6)):
# Cumulative number of unique authors over time. First, group by orcid and get first time
author_first_submission = df.groupby('orcid')['time'].min()
unique_historical_authors = author_first_submission.reset_index().groupby('time')['orcid'].count().cumsum()
plt.figure(figsize=figsize)
sns.lineplot(data=unique_historical_authors)
plt.xticks(rotation=45)
plt.title(f'{institution_name} Historical Unique First Time First Authorship')
plt.ylabel('Cumulative Unique First Time First Authorship')
plt.xlabel('Month')
plt.tight_layout()
plt.savefig(os.path.join(directory, 'historical_authorship.png'), dpi=300)
def plot_cumulative_licenses(df, directory, institution_name, figsize=(10, 6)):
# Cumulative number of licenses over time. First, group by orcid and get first time
fig, ax = plt.subplots(1, 1, figsize=figsize)
for license, sdf in df.groupby('license'):
historical_licenses = sdf.groupby('time').count()['id'].cumsum()
sns.lineplot(data=historical_licenses, ax=ax, label=license)
plt.xticks(rotation=45)
plt.title(f'{institution_name} Historical Licenses')
plt.ylabel('Cumulative Articles')
plt.xlabel('Month')
plt.tight_layout()
plt.savefig(os.path.join(directory, 'historical_licenses.png'), dpi=300)
def plot_gender_evolution(df, directory, institution_name, figsize=(10, 6)):
plt.figure(figsize=figsize)
df = prepare_genders(df)
assign_andy(df)
data = df.groupby(['time', 'first_author_inferred_gender']).count()['id'].reset_index()
sns.lineplot(data=data, x='time', y='id', hue='first_author_inferred_gender')
plt.xticks(rotation=45)
plt.title(f'{institution_name} Inferred First Author Genders')
plt.ylabel('Articles')
plt.xlabel('Month')
plt.tight_layout()
plt.savefig(os.path.join(directory, 'genders_by_month.png'), dpi=300)
def plot_gender_male_percentage(df, directory, institution_name, figsize=(10, 6)):
plt.figure(figsize=figsize)
df = prepare_genders(df)
nd = df.groupby(['time', 'first_author_inferred_gender']).count()['id'].reset_index().pivot(
index='time',
columns='first_author_inferred_gender',
values='id'
).fillna(0).astype(int)
nd['ratio'] = (nd['male'] + 0.5 * nd['andy']) / (nd['male'] + nd['female'] + nd['andy'])
sns.lineplot(data=nd, x='time', y='ratio')
plt.xticks(rotation=45)
plt.title(f'{institution_name} Inferred First Author Male Percentage')
plt.ylabel('Male Percentage')
plt.xlabel('Month')
plt.tight_layout()
plt.savefig(os.path.join(directory, 'male_percentage_by_month.png'), dpi=300)
|
Python | UTF-8 | 1,297 | 2.78125 | 3 | [
"MIT"
] | permissive | # data는 e9t(Lucy Park)님께서 github에 공유해주신 네이버 영화평점 데이터를 사용하였습니다.
# https://github.com/e9t/nsmc
from collections import defaultdict
import torch
from torch.autograd import Variable
class DataSetUp(object):
def __init__(self):
self.w2i_dict = defaultdict(lambda : len(self.w2i_dict))
self.pad = self.w2i_dict['<PAD>']
def read_txt(self,path_to_file):
txt_ls = []
label_ls = []
with open(path_to_file) as f:
for i, line in enumerate(f.readlines()[1:]):
id_num, txt, label = line.split('\t')
txt_ls.append(txt)
label_ls.append(int(label.replace('\n','')))
return txt_ls, label_ls
def convert_word_to_idx(self,sents):
for sent in sents:
yield [self.w2i_dict[word] for word in sent.split(' ')]
return
def add_padding(self, sents, max_len):
for i, sent in enumerate(sents):
if len(sent)< max_len:
sents[i] += [self.pad] * (max_len - len(sent))
elif len(sent) > max_len:
sents[i] = sent[:max_len]
return sents
def convert_to_variable(self, sents):
var = Variable(torch.LongTensor(sents))
return var
|
Java | UTF-8 | 6,026 | 1.90625 | 2 | [] | no_license | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* 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.
*/
package com.orientechnologies.orient.core.index;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.orientechnologies.orient.core.hook.ODocumentHookAbstract;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* Handles indexing when records change.
*
* @author Luca Garulli
*
*/
public class OPropertyIndexManager extends ODocumentHookAbstract {
@Override
public boolean onRecordBeforeCreate(final ODocument iRecord) {
checkIndexedProperties(iRecord);
return false;
}
@Override
public boolean onRecordAfterCreate(final ODocument iRecord) {
final Map<OProperty, Object> indexedProperties = getIndexedProperties(iRecord);
if (indexedProperties != null)
for (Entry<OProperty, Object> propEntry : indexedProperties.entrySet()) {
// SAVE A COPY TO AVOID PROBLEM ON RECYCLING OF THE RECORD
propEntry.getKey().getIndex().getUnderlying().put(propEntry.getValue(), iRecord.placeholder());
}
return false;
}
@Override
public boolean onRecordBeforeUpdate(final ODocument iRecord) {
checkIndexedProperties(iRecord);
return false;
}
@Override
public boolean onRecordAfterUpdate(final ODocument iRecord) {
final Map<OProperty, Object> indexedProperties = getIndexedProperties(iRecord);
if (indexedProperties != null) {
final String[] dirtyFields = iRecord.getDirtyFields();
if (dirtyFields.length > 0) {
// REMOVE INDEX OF ENTRIES FOR THE OLD VALUES
Object originalValue = null;
OIndex index;
for (Entry<OProperty, Object> propEntry : indexedProperties.entrySet()) {
for (String f : dirtyFields)
if (f.equals(propEntry.getKey().getName())) {
// REMOVE IT
originalValue = iRecord.getOriginalValue(propEntry.getKey().getName());
index = propEntry.getKey().getIndex().getUnderlying();
index.remove(originalValue, iRecord);
index.lazySave();
break;
}
}
// ADD INDEX OF ENTRIES FOR THE CHANGED ONLY VALUES
for (Entry<OProperty, Object> propEntry : indexedProperties.entrySet()) {
for (String f : dirtyFields)
if (f.equals(propEntry.getKey().getName())) {
index = propEntry.getKey().getIndex().getUnderlying();
// SAVE A COPY TO AVOID PROBLEM ON RECYCLING OF THE RECORD
index.put(propEntry.getValue(), iRecord.placeholder());
index.lazySave();
break;
}
}
}
}
if (iRecord.isTrackingChanges()) {
iRecord.setTrackingChanges(false);
iRecord.setTrackingChanges(true);
}
return false;
}
@Override
public boolean onRecordAfterDelete(final ODocument iRecord) {
final Map<OProperty, Object> indexedProperties = getIndexedProperties(iRecord);
if (indexedProperties != null) {
final String[] dirtyFields = iRecord.getDirtyFields();
OIndex index;
if (dirtyFields.length > 0) {
// REMOVE INDEX OF ENTRIES FOR THE OLD VALUES
for (Entry<OProperty, Object> propEntry : indexedProperties.entrySet()) {
for (String f : dirtyFields)
if (f.equals(propEntry.getKey().getName())) {
// REMOVE IT
index = propEntry.getKey().getIndex().getUnderlying();
index.remove(propEntry.getValue(), iRecord);
index.lazySave();
break;
}
}
}
// REMOVE INDEX OF ENTRIES FOR THE CHANGED ONLY VALUES
for (Entry<OProperty, Object> propEntry : indexedProperties.entrySet()) {
if (iRecord.containsField(propEntry.getKey().getName())) {
boolean found = false;
for (String f : dirtyFields)
if (f.equals(propEntry.getKey().getName())) {
found = true;
break;
}
if (!found) {
index = propEntry.getKey().getIndex().getUnderlying();
index.remove(propEntry.getValue(), iRecord);
index.lazySave();
}
}
}
}
if (iRecord.isTrackingChanges()) {
iRecord.setTrackingChanges(false);
iRecord.setTrackingChanges(true);
}
return false;
}
protected void checkIndexedProperties(final ODocument iRecord) {
final OClass cls = iRecord.getSchemaClass();
if (cls == null)
return;
OPropertyIndex index;
for (OProperty prop : cls.getIndexedProperties()) {
index = prop.getIndex();
if (index != null)
index.checkEntry(iRecord);
}
}
protected Map<OProperty, Object> getIndexedProperties(final ODocument iRecord) {
final ORecordSchemaAware<?> record = iRecord;
final OClass cls = record.getSchemaClass();
if (cls == null)
return null;
OPropertyIndex index;
Object fieldValue;
Map<OProperty, Object> indexedProperties = null;
for (OProperty prop : cls.getIndexedProperties()) {
index = prop.getIndex();
if (index != null) {
if (prop.getType() == OType.LINK)
// GET THE RID TO AVOID LOADING
fieldValue = record.field(prop.getName(), OType.LINK);
else
fieldValue = record.field(prop.getName());
if (fieldValue != null) {
// PUSH THE PROPERTY IN THE SET TO BE WORKED BY THE EXTERNAL
if (indexedProperties == null)
indexedProperties = new HashMap<OProperty, Object>();
indexedProperties.put(prop, fieldValue);
}
}
}
return indexedProperties;
}
} |
Python | UTF-8 | 168 | 2.84375 | 3 | [] | no_license | import fractions
n = int(input())
t = [int(input()) for _ in range(n)]
for i in range(1, n):
t[i] = t[i] * t[i - 1] // fractions.gcd(t[i], t[i - 1])
print(t[-1])
|
Java | UTF-8 | 864 | 2.0625 | 2 | [
"MIT"
] | permissive | package com.sun.jna.win32;
import com.sun.jna.FromNativeContext;
import com.sun.jna.StringArray;
import com.sun.jna.ToNativeContext;
import com.sun.jna.TypeConverter;
import com.sun.jna.WString;
class W32APITypeMapper$1 implements TypeConverter {
// $FF: synthetic field
final W32APITypeMapper this$0;
W32APITypeMapper$1(W32APITypeMapper this$0) {
this.this$0 = this$0;
}
public Object toNative(Object value, ToNativeContext context) {
if (value == null) {
return null;
} else {
return value instanceof String[] ? new StringArray((String[])((String[])value), true) : new WString(value.toString());
}
}
public Object fromNative(Object value, FromNativeContext context) {
return value == null ? null : value.toString();
}
public Class nativeType() {
return WString.class;
}
}
|
C# | UTF-8 | 2,765 | 2.765625 | 3 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Prism.Logging;
using Prism.Services;
namespace PrismSample.Logging
{
public class LogGenerator
{
private ILogger _logger { get; }
private IDeviceService _deviceService { get; }
public LogGenerator(ILogger logger, IDeviceService deviceService)
{
_logger = logger;
_deviceService = deviceService;
Messages = new ObservableCollection<string>();
}
public ObservableCollection<string> Messages { get; }
int logCount;
public void GenerateLogs()
{
logCount = 0;
Messages.Clear();
_deviceService.StartTimer(TimeSpan.FromSeconds(1.5), GenerateLog);
}
private bool GenerateLog()
{
bool trackEvent = false;
string message = null;
if (logCount == 0)
{
message = "Starting Test Log Run";
trackEvent = true;
}
else if (logCount % 3 == 1)
{
GracefulException();
}
else if(logCount % 2 == 0)
{
message = "ViewA";
trackEvent = true;
}
else
{
message = "User did something fun...";
}
if(!string.IsNullOrEmpty(message))
{
if(trackEvent)
{
_logger.TrackEvent(message, new Dictionary<string, string>
{
{ "loggerType", _logger.GetType().Name }
});
}
else
{
_logger.Info(message, new Dictionary<string, string>
{
{ "loggerType", _logger.GetType().Name }
});
}
Messages.Add(message);
}
return logCount++ < 14;
}
private void GracefulException()
{
try
{
var foo = new FooService();
foo.DangerousApi();
}
catch (Exception ex)
{
_logger.Report(ex, new Dictionary<string, string>
{
{ "loggerType", _logger.GetType().Name }
});
Messages.Add($"{ex.GetType().Name}: {ex.Message}");
}
}
private class FooService
{
public void DangerousApi()
{
throw new Exception("Whoops this Dangerous Api did something terrible");
}
}
}
}
|
Markdown | UTF-8 | 8,208 | 2.625 | 3 | [] | no_license | # Моделирование оттока для сети фитнес-центров.
Яндекс.Практикум, Анализ Данных, Проект 9: ML, sklearn, классификация: logistic regression, random forest classifier; кластеризация: distance matrix, dendrogram, K-Means.
__Attention:__ Иногда GitHub капризничает и не открывает файлы .ipynb, но проект всегда можно посмотреть в Jupyter NBViewer по ссылке: https://nbviewer.jupyter.org/github/curlylocks1987/yandex.praktikum-projects/blob/main/ML_Churn_model_for_gym_%28project_9%29/Project_9_ML.ipynb
## Данные
- `'Churn'` — факт оттока в текущем месяце;
- Текущие поля в датасете:
- Данные клиента за предыдущий до проверки факта оттока месяц:
- `'gender'` — пол;
- `'Near_Location'` — проживание или работа в районе, где находится фитнес-центр;
- `'Partner'` — сотрудник компании-партнёра клуба (сотрудничество с компаниями, чьи сотрудники могут получать скидки на абонемент — в таком случае фитнес-центр хранит информацию о работодателе клиента);
- `'Promo_friends'` — факт первоначальной записи в рамках акции «приведи друга» (использовал промо-код от знакомого при оплате первого абонемента);
- `'Phone'` — наличие контактного телефона;
- `'Age'` — возраст;
- `'Lifetime'` — время с момента первого обращения в фитнес-центр (в месяцах).
- Информация на основе журнала посещений, покупок и информация о текущем статусе абонемента клиента:
- `'Contract_period'` — длительность текущего действующего абонемента (месяц, 3 месяца, 6 месяцев, год);
- `'Month_to_end_contract'` — срок до окончания текущего действующего абонемента (в месяцах);
- `'Group_visits'` — факт посещения групповых занятий;
- `'Avg_class_frequency_total'` — средняя частота посещений в неделю за все время с начала действия абонемента;
- `'Avg_class_frequency_current_month'` — средняя частота посещений в неделю за предыдущий месяц;
- `'Avg_additional_charges_total'` — суммарная выручка от других услуг фитнес-центра: кафе, спорт-товары, косметический и массажный салон.
## Задача
- научиться прогнозировать вероятность оттока (на уровне следующего месяца) для каждого клиента;
- сформировать типичные портреты клиентов: выделить несколько наиболее ярких групп и охарактеризовать их основные свойства;
- проанализировать основные признаки, наиболее сильно влияющие на отток;
- сформулировать основные выводы и разработать рекомендации по повышению качества работы с клиентами:
1. выделить целевые группы клиентов;
2. предложить меры по снижению оттока;
3. определить другие особенности взаимодействия с клиентами.
## Используемые библиотеки
*pandas*, *seaborn*, *Matplotlib*, *numpy*, *sklearn*, *skipy.cluster.hierarchy*
## Основные этапы работы
- Загрузили и обработали данные, заменили названия столбцов.
- В ходе EDA расчитали средние и стандартные отклонения признаков, посмотрели на распределения, построили матрицу корреляции, выявили и убрали из рассмотрения заведомо линейно зависимые признаки. В итоге осталось 11 значимых признаков.
- Разбили выборку в соотношении 80:20 на обучающую и валидационную. Обучили две модели: логистическую регрессию и случайный лес. По метрикам (accuracy, precision, recall) поняли, что логистическая регрессия лучше. Наибольшее влиятние на отток в данной модели оказывают признаки age, lifetime и contract_period.
- Осуществили кластеризацию, сначала при помощи дерева расстояний, а затем при помощи алгоритма K-Means. В итоге разбили признаки на 5 кластеров, которые однозначно дифференцируются по убыванию среднего оттока. Основные признаки, отрицательно коррелирующие с процентом оттока те же, что и в логистической регрессии: age, lifetime, contract_period. К ним можно также добавить доп. расходы, посещение групповых занятий и среднее число посещений в неделю.
## Основные выводы
Как модель логистической регрессии, так и алгоритм кластеризации K-Means показывают сильное влияние признаков __возраст, lifetime, продолжительность контракта__ на отток. Чем они выше, тем отток меньше.
В рамках кластеризации выделились 5 групп пользователей:
- __Кластеры 1 и 4__ похожи, средний отток в них составляет не меньше 40%. Это много. Всего в этих кластерах 44% нашей выборки. Для этих кластеров характерен средний возраст ниже 29 лет, средний lifetime меньше 3 месяцев, средний период контракта меньше 3 месяцев.
- __Кластеры 0 и 3__ - пограничные. Отток в них 27% и 13%, возраст 29-30 лет, lifetime 3-4 месяца, период контракта 5-7 месяцев. Вместе эти кластеры составляют около 35% выборки.
- __Кластер 2__ - "золотой фонд". Отток в нем всего 1%. Возраст старше 30, lifetime 5-6 месяцев, контракт 7 месяцев. Для данной выборки в этот кластер попали 21% клиентов.
При переходе __рубежа 30 лет, lifetime - 5 месяцев, контракт - 7 месяцев, отток резко снижается__.
Из менее значимых признаков, которые все же стоит мониторить менеджерам, можно отметить сумму дополнительных расходов, частоту посещений в неделю, посещение групповых занятий.
|
Java | UTF-8 | 325 | 2.40625 | 2 | [] | no_license | package org.demo.pattern.singleton;
/**
*
* @author
* @date 2011-5-20
* @file org.demo.pattern.singleton.Singleton.java
*/
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
|
Python | UTF-8 | 3,621 | 3.203125 | 3 | [
"BSD-3-Clause"
] | permissive | import numpy as np
import tables as pt
from PositionModel import PositionModel
class Position:
def __init__(self):
self.position = np.array([])
def addPosition(self,timestamp,symbol,shares,purchase_price):
'''
Adds a new position
timestamp: the time the position was entered
symbol: the ticker of the stock
shares: the number of shares
purchase_price: the price per share (excludes any additional costs such as commission or impact)
'''
row = {}
row['timestamp'] = timestamp
row['symbol'] = symbol
row['shares'] = shares
row['purchase_price'] = purchase_price
self.position = np.append(self.position, row)
def removePosition(self, symbol, shares):
'''
Removes/modifies positions until the total number of shares have been removed
symbol: the ticker of the stock
shares: the number of shares to remove
NOTE: Method assumes that verification of valid sell has already been completed
'''
debug = False
rowIndexes = []
rows = []
if debug:
print 'REMOVING POSITIONS'
print 'REMOVE:',symbol,shares
for row in self.position:
print 'CURRROWS:', row
#get all rows for the correct stock
idx = 0
for row in self.position:
if(row['symbol']==symbol):
row["keyIndex"]=idx
rows.append(row)
idx+=1
if debug:
print 'POSSIBLE ROWS TO REMOVE: ',rows
i = len(rows)-1 #sets i to last row
row = rows[i]
if debug:
print "LIFO",row
#gets info from last row's position
posShares = row['shares']
posShares = abs(posShares) #account for shorts (make positive)
#determines number of positions to remove
while(shares>posShares):
shares-=posShares
i-=1
row = rows[i]
posShares = row['shares']
posShares = abs(posShares)
#modifies changed row
newRow = self.position[ rows[i]['keyIndex'] ]
newShares = posShares-shares
newRow['shares'] = newShares
if debug:
print 'UPDATEDROW(LIFO):', newRow
#removes old rows
removes = []
#remove updated row if it has 0 shares now
if newShares == 0:
removes.append(rows[i]['keyIndex'])
#remove the rest of the rows
cnt = len(rows)-1
while cnt>i:
row = rows[cnt]
removes.append(row['keyIndex'])
cnt-=1
if debug:
for idx in removes:
print 'ROWREMOVED:', self.position[idx]
self.position = np.delete(self.position,removes)
for row in rows:
del row['keyIndex']
def fillTable(self):
'''
Converts the arrays into HDF5 tables for post simulation review
'''
self.positionFile = pt.openFile('PositionModel.h5', mode = "w")
self.position = self.positionFile.createTable('/', 'position', PositionModel)
for arrRow in self.position:
row = self.position.row
row['timestamp'] = arrRow['timestamp']
row['symbol'] = arrRow['symbol']
row['shares'] = arrRow['shares']
row['purchase_price'] = arrRow['purchase_price']
row.append()
self.position.flush()
self.positionFile.close()
def close(self):
self.fillTable()
|
JavaScript | UTF-8 | 230 | 3.359375 | 3 | [] | no_license | function bubbleSort (array) {
for(var i=0;i<array.length;i++){
for(var j=0;j<array.length;j++){
if(array[i] < array[j]){
var lesser = array[j];
array[j] = array[i];
array[i] = lesser;
}
}
}
return array
} |
TypeScript | UTF-8 | 693 | 3.203125 | 3 | [] | no_license | interface Persona {
id: number,
nombre: string,
edad: number,
fechaIngreso?: Date
}
var personas: Persona[] = [];
const crearPersonas = (total: number) => {
for (let i = 1; i <= total; i++) {
personas.push({
id: i,
nombre: `Persona ${i}`,
edad: 4 + (i * 3)
});
}
};
const saludarPersonas = () => {
const content = document.getElementById('content');
personas.forEach(persona => {
console.log(`Hola ${persona.nombre}`);
const p = document.createElement('p');
p.textContent = `Hola ${persona.nombre}`;
content?.appendChild(p)
});
};
crearPersonas(15);
saludarPersonas(); |
Java | UTF-8 | 819 | 2.796875 | 3 | [] | no_license | package com.ai.common.enums;
public enum TemplateParamCategoryEnum {
MAIN(1, "固定->在页面上固定"), DYNAMIC(2, "连动->根据项不同显示不同对象");
int key;
String value;
TemplateParamCategoryEnum(int key, String value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public static TemplateParamCategoryEnum getEnumByKey(Integer key) {
if (key == null) {
return MAIN;
}
for (TemplateParamCategoryEnum objEnum : TemplateParamCategoryEnum
.values()) {
if (key == objEnum.getKey()) {
return objEnum;
}
}
return MAIN;
}
}
|
Python | UTF-8 | 305 | 3.453125 | 3 | [] | no_license | f = open('a.txt','w')
f.write("hello world1\n")
f.write("hello world2")
f.close()
'''
f = open('a.txt','r')
content = f.read(3)
print(content)
f.close()
'''
f = open('a.txt','r')
content = f.readlines()
#print(type(content))
i = 1
for temp in content:
print("%d:%s"%(i,temp))
i+=1
f.close()
|
Python | UTF-8 | 2,559 | 4 | 4 | [] | no_license |
class Stack(object):
def __init__(self, size):
self.size = size # 初始化数组的大小
self.array = list()
self.cur_size = 0 # 代表当前数组的大小
def push(self, num):
if self.size <= self.cur_size:
print('can not push')
return
self.array.append(num)
self.cur_size += 1
def pop(self):
if self.cur_size == 0:
print('can not pop')
return
self.cur_size -= 1
return self.array.pop()
class Queue(object):
def __init__(self, size):
self.array = list()
self.size = size
self.cur_size = 0 # 代表当前数组的大小
self.add = 0 # 指向添加的位置
self.delete = 0 # 指向弹出的位置
def push(self, num):
if self.size <= self.cur_size:
print('can not push')
return
self.array.append(num)
self.cur_size += 1
# 当add位置到达边界时,返回0位置
self.add = 0 if self.add == self.size - 1 else self.add + 1
def pop(self):
if self.cur_size == 0:
print('can not pop')
return
tmp = self.array[self.delete] # 这里不要将数pop,这样会减少数组的长度,导致原本指针指向的位置不存在
self.cur_size -= 1
self.delete = 0 if self.delete == self.size - 1 else self.delete + 1
return tmp
# 单链表
class SingleNode:
def __init__(self, data):
self.data = data
self.next = None
class Linked:
"""链表"""
def __init__(self) -> None:
self.head = None
def push(self, data):
node = SingleNode(data)
if self.head is None:
self.head = node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = node
def display(self):
cur = self.head
_list = []
while cur:
_list.append(str(cur.data))
cur = cur.next
return ' > '.join(_list)
def reverse_linked_list(head):
"""翻转单链表
用两个指针交替走过链表,每走一步就将前后两个节点的指向翻转
next_node = cur.next + cur.next = prev 这两步翻转下一个指针的指向
prev = cur + cur = next_node 这两步将两个指针向前推进
"""
prev = None
cur = head
while cur:
next_node = cur.next
cur.next = prev
prev = cur
cur = next_node
return prev
|
Python | UTF-8 | 604 | 3.578125 | 4 | [] | no_license | # Copyright(C) 2018 刘珅珅
# Environment: python 3.6.4
# Date: 2018.5.6
# 类树
def class_tree(cls, indent):
print('.' * indent + cls.__name__)
for super_cls in cls.__bases__: # 查找超类
class_tree(super_cls, indent + 3)
def instance_tree(inst):
print('Tree of {0}'.format(inst))
class_tree(inst.__class__, 3) # __class__实例的类
def test():
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
class E: pass
class F(D, E): pass
instance_tree(B())
instance_tree(F())
if __name__ == '__main__':
test()
|
JavaScript | UTF-8 | 1,559 | 3.59375 | 4 | [] | no_license | console.log("=======SLIDE 7 PROTOTYPES =====")
var simpleObj = function(c){
this.city=c;
}
var live1= new simpleObj("Brooklyn");
var live2= new simpleObj("Bronx");
simpleObj.prototype.state ="New York";//prototype applied
console.log(live1);//simpleObj { city: 'Brooklyn' }
console.log(live2);//simpleObj { city: 'Bronx' }
console.log(live2.prototype===live1.prototype);//true
console.log(live1.state);//New York
console.log(live2.state);//New York
console.log("=======SLIDE 6 PROTOTYPES =====")
var Book=function(title,authorFullName,yearPublication){
this.authorFullName=authorFullName;
this.title=title;
this.yearPublication=yearPublication;
this.description="";
this.printBookObj = function(){
//console.log(this.title,
//this.authorFullName,
//this.yearPublication,
//this.description);
console.log(this);}
this.printlabel=function(){
console.log(" Title: ",this.title);
console.log(" Author: ",this.authorFullName);
console.log(" Year: ",this.yearPublication);
console.log("Description: ",this.description);}
}
var jsBook = new Book("Intro to JS","Cathy",2019);
var book1=new Book("aaa","nnn",2018);
var book2=new Book("bbb","ddd",2019);
book1.totalPages =999;
console.log(book1);
console.log(book2);
/*Book {
authorFullName: 'nnn',
title: 'aaa',
yearPublication: 2018,
description: '',
printBookObj: [Function],
printlabel: [Function],
totalPages: 999 }
Book {
authorFullName: 'ddd',
title: 'bbb',
yearPublication: 2019,
description: '',
printBookObj: [Function],
printlabel: [Function] }
*/ |
PHP | UTF-8 | 4,763 | 2.78125 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | <?php
namespace artjom\ToDoListBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Choice;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;
use artjom\ToDoListBundle\Form\Extension\Type\TaskStatusChoices;
/**
* Task
*
* @ORM\Table()
* @ORM\Entity
*/
class Task
{
const OPEN = 1;
const PROGRESS = 2;
const CLOSE = 3;
const MIN_TITLE_LENGTH = 3;
const MAX_TITLE_LENGTH = 64;
const MAX_DESCRIPTION_LENGTH = 256;
const DATETIME_FORMAT = 'dd-mm-yyyy hh:ii';
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=100)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
private $description = null;
/**
* @var \DateTime
*
* @ORM\Column(name="start_date", type="datetime")
*/
private $start_date;
/**
* @var \DateTime
*
* @ORM\Column(name="end_date", type="datetime")
*/
private $end_date;
/**
* @var integer
*
* @ORM\Column(name="status", type="integer")
*/
private $status;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('title', new Assert\NotBlank());
$metadata->addPropertyConstraint('title', new Length(array('min' => self::MIN_TITLE_LENGTH, 'max' => self::MAX_TITLE_LENGTH)));
$metadata->addPropertyConstraint('status', new Assert\NotBlank());
$metadata->addPropertyConstraint('status', new Choice(array('choices' => TaskStatusChoices::getChoicesKeys())));
$metadata->addConstraint(new Assert\Callback('validate'));
$metadata->addPropertyConstraint('start_date', new Assert\NotBlank());
$metadata->addPropertyConstraint('start_date', new Assert\DateTime());
$metadata->addPropertyConstraint('end_date', new Assert\NotBlank());
$metadata->addPropertyConstraint('end_date', new Assert\DateTime());
$metadata->addPropertyConstraint('description', new Length(array('max' => self::MAX_DESCRIPTION_LENGTH)));
}
/**
* Extra validation
*
*/
public function validate(ExecutionContextInterface $context)
{
//validate that start_date is not bigger than end_date
if($this->start_date && $this->end_date){
if($this->start_date->getTimestamp() > $this->end_date->getTimestamp()){
$context->addViolationAt(
'start_date',
'The starting date must be anterior than the ending date',
array(),
null
);
}
}
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
* @return Task
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* @param string $description
* @return Task
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set start_date
*
* @param \DateTime $startDate
* @return Task
*/
public function setStartDate($startDate)
{
$this->start_date = $startDate;
return $this;
}
/**
* Get start_date
*
* @return \DateTime
*/
public function getStartDate()
{
return $this->start_date;
}
/**
* Set end_date
*
* @param \DateTime $endDate
* @return Task
*/
public function setEndDate($endDate)
{
$this->end_date = $endDate;
return $this;
}
/**
* Get end_date
*
* @return \DateTime
*/
public function getEndDate()
{
return $this->end_date;
}
/**
* Set status
*
* @param integer $status
* @return Task
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return integer
*/
public function getStatus()
{
return $this->status;
}
}
|
Java | UTF-8 | 549 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | package com.whut.demo.common.constant;
public class PayConstant {
public enum PayRespConstant{
SUCCESS(0,"支付成功"),FAILED(1,"支付失败"),
SECOND_PAY(2,"重复支付"),ORDER_NON_EXIST(3,"订单不存在");
private int code;
private String msg;
PayRespConstant(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
}
|
C++ | UTF-8 | 1,040 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using std::cout;
using std::endl;
using std::vector;
using std::min;
#define infinite 100
vector<vector<int>> Floyd_Warshall_algorithm(vector<vector<int>> &W)
{
int row = W.size();
vector<vector<int>> D_zero = W;
vector<vector<vector<int>>> D_vec;
D_vec.push_back(D_zero);
for (int k = 0; k != row; ++k)
{
vector<vector<int>> D_k;
for (int i = 0; i != row; ++i)
{
vector<int> v(row);
D_k.push_back(v);
}
for (int i = 0; i != row; ++i)
for (int j = 0; j != row; ++j)
{
vector<vector<int>> D_k_1 = D_vec[k];
D_k[i][j] = min(D_k_1[i][j], (D_k_1[i][k] + D_k_1[k][j]));
}
D_vec.push_back(D_k);
}
return D_vec[row - 1];
}
int main()
{
vector<vector<int>> W =
{
{ 0, 3, 8, infinite, -4 },
{ infinite, 0, infinite, 1, 7 },
{ infinite, 4, 0, infinite, infinite },
{ 2, infinite, -5, 0, infinite },
{ infinite, infinite, infinite, 6, 0 }
};
vector<vector<int>> path = Floyd_Warshall_algorithm(W);
system("pause");
return 0;
} |
Python | UTF-8 | 299 | 2.828125 | 3 | [] | no_license | # input: [1,2,3,4,5,2,3,1] -> output: 5
# input: [4,1,2,1,2] -> Output: 4
# Input: [1]-> Output: 1
class Solution:
def singleNumber(self, nums: List[int]) -> int:
if nums:
res = 0
for i in nums:
res ^= i
return res
return None |
C | UTF-8 | 3,042 | 3.546875 | 4 | [] | no_license | /*
* disk.c
*
* Created on: 28-Jan-2018
* Author: rishabh
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "disk.h"
static int num_blocks = 0; // This will increase when the block is completely full
static int nreads = 0; // This will keep track of number of reads.
static int nwrites = 0; // This will keep track of number of writes to disk.
static int num_data_block = NUM_INODE_BLOCKS+1; // start of data block
void sanity_check(int block_index, char * data){
/* *
* Sanity Check functionality for error checking for parameters.*
* */
if(block_index < 0){
printf("ERROR: block number (%d) is less than 0", block_index);
return;
}
if(block_index >= NUM_BLOCKS){
printf("ERROR: block number (%d) is greater than disk capacity", block_index);
return;
}
if(!data){
printf("ERROR: null pointer to data!\n");
return;
}
}
void disk_init(char *filename, char *mode){
/*
Initialize a new disk by allocating some memory and setting up the flags.
*/
if(disk == NULL){
disk = fopen(filename, mode);
memcpy(file_name, filename, strlen(filename));
file_name[strlen(filename)] = '\0';
}
else{
fclose(disk);
disk = NULL;
disk = fopen(filename, mode);
}
if(!disk) {
fprintf(stderr, "Failed to initialize the disk!\n");
return ;
}
fseek(disk, 0L, SEEK_END);
int size = ftell(disk);
fseek(disk, 0L, SEEK_SET);
if(size == 0)
ftruncate(fileno(disk), NUM_BLOCKS*DISK_BLK_SIZE);
num_blocks = NUM_BLOCKS;
}
void disk_mount(){
/*
Set the flag to indicate that disk has been mounted and its ready for use.
*/
disk_mounted = TRUE;
}
int reset_stats(){
/*
Reset stats maintained for the disks.
*/
num_blocks = 0;
nreads = 0;
nwrites = 0;
num_data_block = NUM_INODE_BLOCKS + 1;
return 1;
}
void disk_unmount(){
/*
Unmount the disk. Disk is not in use.
*/
disk_mounted = FALSE;
}
void disk_close(){
/*
Closes the disk.
*/
if(!disk){
return ;
}
fprintf(stdout, "%d disk block reads\n",nreads);
fprintf(stdout, "%d disk block writes\n",nwrites);
fclose(disk);
disk = NULL;
reset_stats();
}
int disk_size(){
/*
Return Remaining disk size
*/
return num_blocks;
}
void disk_read(int block_num, char * data){
/*
Disk Read fuctionality
*/
sanity_check(block_num, data);
fseek(disk, block_num*DISK_BLK_SIZE, SEEK_SET);
if(fread(data, DISK_BLK_SIZE, 1, disk) == 1){
nreads++;
}
else{
fprintf(stderr, "Error: reading from the disk at the disk block number %d\n", block_num);
}
}
int disk_write(int block_num, char* data){
/*
Disk Write Functionality
*/
sanity_check(block_num, data);
fseek(disk, block_num*DISK_BLK_SIZE, SEEK_SET);
if(fwrite(data, DISK_BLK_SIZE, 1, disk)){
nwrites++;
num_blocks--;
}
else{
fprintf(stderr, "Error: writing to the disk at the disk block number %d\n", block_num);
return 0;
}
return 1;
}
|
Markdown | UTF-8 | 3,454 | 2.625 | 3 | [] | no_license | #Steps to run the project :
> This project is java maven project so once you unzip the directory. Please follow the below steps:
-----------------------------------------------------------------------------------------------------------------------
#####Step 1. Open terminal and goto the basediretory :
cd /path/to/project/webapp
for listing the files in the directory.
ls
Output :
You will get the following structure:
pom.xml
src
target
------------------------------------------------------------------------------------------------------------------------
#####Step 2.
#####a. Using Java :
You must to have java installed on your machine :
If java is not installed, use https://www.java.com/en/download/help/download_options.xml to install.
If java is already installed :
java -jar target/webapp-0.0.1-SNAPSHOT.jar
#####OR
#####b. Using Maven :
You much have maven installed on your machine :
If maven is not installed, use https://maven.apache.org/install.html to install.
If maven is already installed :
mvn spring-boot:run
Output:
Last line on the terminal will look like similar to the below line :
INFO 28729 --- [ main] d.i.webapp.WebApplication : Started WebApplication in 14.232 seconds (JVM running for 14.732)
------------------------------------------------------------------------------------------------------------------------
#####Step 3. to check whether REST APIs of application is working or not. Open browser and go to below url:
http://localhost:8080/api/v1/hello
Output:
You will get below text as response.
Hello Engineer @ ImmobilienScout 24
Hurray !
Application is ready to use.
------------------------------------------------------------------------------------------------------------------------
#####Step 4: to check the front-end of web application with the perspective of end user. Open browser and go to below url:
http://localhost:8080 or http://localhost:8080/index or http://localhost:8080/index.html
Output:
All the above link will redirect to analysis page where you need to put url in the text field and press analyse button or hit enter.
------------------------------------------------------------------------------------------------------------------------
#####Step 5 : To check, the REST apis of web application. Open browser and go to below url :
http://localhost:8080/s or http://localhost:8080/swagger or http://localhost:8080/swagger-ui.html
------------------------------------------------------------------------------------------------------------------------
#####Step 6 : To run the test of the application :
a. First stop the application(assuming you were already running the application using above steps) using following keys :
ctrl+c
b. As this project is Maven project. If you run project using maven commands, test will automatically starts while running the application. Using following commands on terminal to run application via maven.
mvn clean install spring-boot:run
Output :
This command also builds the project and runs test cases and followed by start the web application too.
Results :
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
…
INFO 28729 --- [ main] d.i.webapp.WebApplication : Started WebApplication in 14.232 seconds (JVM running for 14.732)
------------------------------------------------------------------------------------------------------------------------
|
Markdown | UTF-8 | 7,860 | 2.5625 | 3 | [] | no_license |
# Monorepo Nix Expressions
Now it's time to put our haskell code to work.
Each of our haskell packages has to have a corresponding nix expression describing how to build it.
The process of writing Nix expressions for haskell packages is error-prone and they would likely fall
out of sync so we would like to generate those Nix files.
To achieve this I use a very simple bash script that expects a directory as an argument.
It will first search for all the cabal files in the directory and it will generate one nix expression file for each of them using the `cabal2nix` utility.
```bash
$ cd monorepo
$ tree .
.
├── code
│ ├── hello-world
│ │ ├── exe
│ │ │ └── Main.hs
│ │ └── hello-world.cabal
│ └── universe
│ ├── src
│ │ └── Universe
│ │ └── World.hs
│ └── universe.cabal
└── nix
├── generate-packages.sh
├── pinned-nixpkgs.nix
└── release.nix
$ cd nix
$ ./generate-packages.sh ../code
Clearing folder /Users/fghibellini/code/nix-haskell-monorepo/monorepo-nix-expressions/monorepo/nix/packages
Reading packages in /Users/fghibellini/code/nix-haskell-monorepo/monorepo-nix-expressions/monorepo/code
Generating Nix expression for package: hello-world (dir: /Users/fghibellini/code/nix-haskell-monorepo/monorepo-nix-expressions/monorepo/code/hello-world)
Generating Nix expression for package: universe (dir: /Users/fghibellini/code/nix-haskell-monorepo/monorepo-nix-expressions/monorepo/code/universe)
$ cd ..
$ tree .
.
├── code
│ ├── hello-world
│ │ ├── exe
│ │ │ └── Main.hs
│ │ └── hello-world.cabal
│ └── universe
│ ├── src
│ │ └── Universe
│ │ └── World.hs
│ └── universe.cabal
└── nix
├── generate-packages.sh
├── hydra.nix
├── packages
│ ├── hello-world.nix
│ └── universe.nix
├── packages.nix
├── pinned-nixpkgs.nix
└── release.nix
$ cat nix/packages/hello-world.nix
{ mkDerivation, aeson, base, stdenv, universe }:
mkDerivation {
pname = "hello-world";
version = "0.1.0.0";
src = ../../code/hello-world;
isLibrary = false;
isExecutable = true;
executableHaskellDepends = [ aeson base universe ];
license = stdenv.lib.licenses.unfree;
hydraPlatforms = stdenv.lib.platforms.none;
}
$ cat nix/packages.nix
# DO NOT MODIFY ! - this file is generated by generate-packages.sh
{
hello-world = import ./packages/hello-world.nix;
universe = import ./packages/universe.nix;
}
```
As you can see it also generated a `packages.nix` file that just imports all of the above files and bundles them in an attribute set for easier consumption.
This file is not strictly necessary as Nix allows you to scan directories for files but I find it makes the expressions more readable.
Assuming our packages really do depend only on each other or their dependencies can be satisfied with packages from our pinned nixpkgs, we can already take them for a spin.
We will build our packages by inserting them into the haskell package set of Nixpkgs.
Nixpkgs accepts a config argument that (among other things) allows us to override packages in a functional (non-destructive) manner.
We override `haskellPackages` to be the package set for `ghc844` but before assigning it we also modify the set by adding our own packages.
```nix
# release.nix
let
nixpkgs = import (import ./pinned-nixpkgs.nix) { inherit config; };
monorepo-pkgs = import ./packages.nix;
config = {
allowUnfree = true;
packageOverrides = pkgs: rec {
haskellPackages = pkgs.haskell.packages.ghc844.override {
overrides = self: super: builtins.mapAttrs (name: value: super.callPackage value {}) monorepo-pkgs;
};
};
};
in nixpkgs
```
The `nixpkgs` value we return now from `release.nix` is the exact same package set as before,
but instead of having `haskellPackages` pointing to a pristine package set for `ghc-8.6.4` <sup>[1](#footnote-1)</sup>, it points to our
modified package set for ghc-8.4.4. `haskell.packages.ghc844` still points to the pristine package set for `ghc-8.4.4` - just compare:
```bash
$ cd nix
$ nix-instantiate --eval -E '(import ./release.nix).haskellPackages.hello-world.pname'
"hello-world"
$ nix-instantiate --eval -E '(import ./release.nix).haskell.packages.ghc844.hello-world.pname'
error: attribute 'hello-world' missing, at (string):1:1
(use '--show-trace' to show detailed location information)
```
Now we can build and execute our package by running:
```bash
$ nix-build -A hello-world ./hydra.nix
$ ./result/bin/hello-world-exe
Hello WORLD!!!
```
Or in an ephemeral shell environment:
```bash
$ nix-shell -p '((import ./release.nix).haskellPackages.hello-world)' --command hello-world-exe
Hello WORLD!!!
```
Or use it as a haskell dependency:
```bash
$ nix-shell -p '((import ./release.nix).haskellPackages.ghcWithPackages (pkgs: [ pkgs.universe ]))' --command "bash -c 'ghc-pkg list | grep universe'"
universe-0.2.0.0
```
# Gitignore files
You might get the following warning when building your projects:
```
warning: dumping very large path (> 256 MiB); this may run out of memory
```
This is caused by the `src` attribute in our packages' expressions:
```
{ mkDerivation, aeson, base, stdenv, universe }:
mkDerivation {
pname = "hello-world";
version = "0.1.0.0";
src = ../../code/hello-world; # <----- THIS ATTRIBUTE
isLibrary = false;
isExecutable = true;
```
When Nix evaluates the expression for your package, it will force the attribute `src` which is a Nix path.
Nix paths are copied into the Nix store and they evaluate to the store path. Before performing the
copying though it will compute the SHA hash of the whole tree and check if it's not already present (if this was the case the path would be reused).
This is problematic for 2 reasons:
1. currently there is a [bug](https://github.com/NixOS/nix/issues/358) that causes the SHA computation to run in non-constant memory space
2. any files in the source tree that don't really represent source code are also taken into account.
An example are `.stack-work` folders, you might potentially have one for each package and they are typically huge, as they contain all build artefacts.
A way to mitigate this is modifying the `src` attribute to take only the desired files into account.
We can patch the output of `cabal2nix` to apply [nix-gitignore](https://github.com/siers/nix-gitignore) on the `src` attribute.
Sed is our friend in such situations:
```bash
# this prepends the path in a Nix expression's `src` attribute with a call to `nix-gitignore.gitignoreSourcePure`
# while also adding nix-gitignore as a dependency
function gitignore-src() {
sed -i '1s/{ /{ nix-gitignore, / ; /^\s*src = / s/src = /src = nix-gitignore.gitignoreSourcePure [ ..\/..\/..\/.gitignore ] /' "$1"
}
```
This will transform the `hello-world` expression to:
```
{ nix-gitignore, mkDerivation, aeson, base, stdenv, universe }:
mkDerivation {
pname = "hello-world";
version = "0.1.0.0";
src = nix-gitignore.gitignoreSourcePure [ ../../../.gitignore ] .././code/hello-world;
isLibrary = false;
isExecutable = true;
executableHaskellDepends = [ aeson base universe ];
license = stdenv.lib.licenses.unfree;
hydraPlatforms = stdenv.lib.platforms.none;
}
```
In the [next chapter](../extra-deps) we will see how to override third-party haskell dependencies.
<a id="footnote-1"><b>[1]</b></a> You can check the default by running `nix-instantiate --eval -E '(import (import ./pinned-nixpkgs.nix) {}).haskellPackages.ghc.version'`
|
Markdown | UTF-8 | 2,828 | 3.046875 | 3 | [] | no_license | ---
layout: default
nav_order: 3
title: Resources
---
# Resources
{: .no_toc }
Here, I have a list of resources for different kinds of things that I learned in grad school including things like how to set up Jupyter on cloud, how to download NGS data efficiently etc. I still come back to these for a refresher sometimes. If you are just getting started in the field of bioinformatics and data science, some of these may be helpful.
---
- TOC
{:toc}
---
### Linux
New to linux? Start with this simple [tutorial](https://ryanstutorials.net/linuxtutorial/) that goes over the basics in short amount of time. Ryan also has tutorials on other topics such as HTML, CSS etc. Here are two cheatsheets that I sometimes refer to - [Cheatsheet 1](https://wiki.bits.vib.be/index.php/Linux_Beginner%27s_Shell_Cheat_page) and [Cheatsheet 2](https://wiki.bits.vib.be/index.php/The_practical_command_line_cheat_sheet).
### Git
There are a lot of resources for Git out there and I don't have any favorites. My suggestion would be to pick one and get started. Start with the
basics and learn more as you need to instead of trying to learn it all at once.
[Here](https://kbroman.org/github_tutorial/) is a simple guide to get started.
### Regular Expressions
[Here](https://www.youtube.com/watch?v=DRR9fOXkfRE&feature=youtu.be) is a quick youtube video to get started with regular expressions.
### Python
Having the right directory structure for your code is key. Understanding how import statements work (the difference between relative and absolute imports etc.) in Python can make structuring the repo a lot easier and more maintainable. This [page](https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html) explains how import statements work. A highly recommended read. If you like reading books, check out this short [book](https://www.amazon.com/Python-Tricks-Buffet-Awesome-Features-ebook/dp/B0785Q7GSY) on some of the cool Python features.
### Jupyter on Google Cloud Platform
Jupyter notebooks are amazing for exploratory data analysis and much more. For bigger datasets and high compute tasks you may want to run the notebook on a cloud server. [This post](https://jeffdelaney.me/blog/running-jupyter-notebook-google-cloud-platform/) will get you started if you use Google Cloud. If you want GPU-enabled notebooks on AWS, have a look at [this](https://course.fast.ai/start_aws).
### Downloading bulk NGS Data efficiently
Here are two posts that really helped me when I wanted to download hundreds of immunosequencing datasets for one of my PhD projects ([Post 1](https://www.michaelgerth.net/news--blog/how-to-efficiently-bulk-download-ngs-data-from-sequence-read-databases) and [Post 2](https://www.biostars.org/p/325010/)). The download speeds were much faster than using the SRA toolkit. |
JavaScript | UTF-8 | 3,044 | 2.828125 | 3 | [] | no_license | import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { addUser } from '../redux/actions/userActions';
/*
* Renders User Registration form
*/
function UserForm() {
const dispatch = useDispatch();
const history = useHistory();
const [state, setState] = useState({
name: '',
email: '',
mobile: '',
password: ''
});
const [error, setError] = useState('');
const handleChange = event => {
const name = event.target.name;
const value = event.target.value;
setState({ ...state, [name]: value });
};
// Validate User inputs
const validate = () => {
const regex_email = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
const regex_mobile = /^([+]\d{2})?\d{10}$/;
if (!state.name) {
setError('Name is mandatory');
} else if (state.name.trim().length < 3) {
setError('Name should be minimum length of 3');
} else if (state.mobile !== '' && !regex_mobile.test(state.mobile)) {
setError('Invalid Mobile Number');
} else if (!regex_email.test(state.email)) {
setError('Invalid Email');
} else if (state.password.trim().length < 6) {
setError('Password should be minimum length of 6 characters');
} else {
setError('');
return true;
}
return false;
};
function handleSubmit(event) {
event.preventDefault();
if (validate()) {
const postData =
state.mobile !== ''
? {
name: state.name,
mobile: state.mobile,
email: state.email,
password: state.password
}
: {
name: state.name,
email: state.email,
password: state.password
};
dispatch(addUser(postData, history));
}
}
return (
<div className='user-wrapper'>
<h1 className='heading'>Create your account</h1>
<div className='user'>
<form onSubmit={handleSubmit}>
<label>Name:</label>
<input
type='text'
name='name'
placeholder='Name'
value={state.name}
onChange={handleChange}
/>
<label>Email:</label>
<input
type='text'
name='email'
placeholder='Email'
value={state.email}
onChange={handleChange}
/>
<label>Mobile number:</label>
<input
type='text'
name='mobile'
placeholder='Mobile Number'
value={state.mobile}
onChange={handleChange}
/>
<label>Password:</label>
<input
type='password'
name='password'
placeholder='Password'
value={state.password}
onChange={handleChange}
/>
<h4>{error}</h4>
<button className='submit'>Submit</button>
</form>
</div>
</div>
);
}
export default UserForm;
|
JavaScript | UTF-8 | 710 | 3.140625 | 3 | [] | no_license | module.exports = function(name, pw){
let callback = {
result: false,
message:''
}
const reg = new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/)
if(name == ''|| name == null)
callback.message = '请填写用户名'
else if( pw == '' || pw == null)
callback.message = '请填写密码'
else if ( name.length < 3)
callback.message = '用户名不得小于三个字符'
else if ( pw.length < 6 || pw.length >= 16)
callback.message = '密码长度6~16个字符'
else if (!reg.test(pw))
callback.message = '密码需包含数字和字母'
else{
callback.message = '用户名和密码合法!'
callback.result = true
}
return callback
}
//注册时检测合法性
|
Java | UTF-8 | 1,117 | 2.765625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package analisisLexico;
/**
*
* @author Caili
*/
public enum TokenType {
// basic types
ID, // [a-zA-Z][a-zA-Z0-9_]*
INT_CONST, // [0-9]+
EOF, // input stream has been consumed
UNKNOWN, // character/token could not be processed
// binary operators
AND, // &&
LT, // <
PLUS, // +
MINUS, // -
TIMES, // *
// reserved words (case-sensitive)
CLASS, // class
PUBLIC, // public
STATIC, // static
VOID, // void
MAIN, // main - relegate as ID (?)
STRING, // String - relegate as ID (?)
EXTENDS, // extends
RETURN, // return
INT, // int
BOOLEAN, // boolean
IF, // if
ELSE, // else
WHILE, // while
TRUE, // true
FALSE, // false
THIS, // this
NEW, // new
// punctuation
LPAREN, // (
RPAREN, // )
LBRACKET, // [
RBRACKET, // ]
LBRACE, // {
RBRACE, // }
SEMI, // ;
COMMA, // ,
DOT, // .
ASSIGN, // =
BANG, // !
// for error reporting
STATEMENT,
EXPRESSION,
OPERATOR,
TYPE
}
|
Shell | UTF-8 | 1,080 | 3.546875 | 4 | [
"BSD-3-Clause"
] | permissive | #!/bin/bash
# Using a shell script for now, because it's not clear that Maven's release plugin
# exactly fits the bill....
version="$1"
if [ ! -n "$version" ]; then
echo "ERROR: specify version"
exit 1
fi
sxml_home="$(dirname "$0")"/..
cd "$sxml_home"
if [ $(svn status | wc -l) -gt 0 ]; then
svn status
echo
echo 'ERROR: uncommitted work'
echo
exit 1
fi
./housekeeping/bundle-dist.sh "$version" || exit 1
echo
echo "Ready to release version: $version"
echo
echo -n "Press enter to proceed: "
read
cd "$sxml_home"
./housekeeping/maven-delpoy.sh || exit 1
./housekeeping/maven-repository-bundle.sh || exit 1
svn copy \
. \
"https://sweetxml.googlecode.com/svn/tags/release/$version" \
-m "Tagging release $version" || exit 1
# cd /tmp
# curl 'http://support.googlecode.com/svn/trunk/scripts/googlecode-upload.py' >/tmp/google-upload.py
# for f in "sweetxml-$version.zip" "sweetxml-$version.tar.gz"; do
# python /tmp/google-upload.py -s "SweetXML $version" -p sweetxml -l Featured -u paul.cantrell "$f" || exit 1
# done
|
JavaScript | UTF-8 | 2,502 | 2.546875 | 3 | [] | no_license | function BasicTreeMap() {
var BasicTreeMap = new mantis.ViewBase("BasicTreeMap", "hierarchical");
BasicTreeMap.create_layout = function () {
// Initializing some basic width
var margin = {top: 20, right: 10, bottom: 10, left: 10};
var width = d3.select(this.container).style('width').replace('px', '') - margin.left - margin.right;
var height = d3.select(this.container).style('height').replace('px', '') - margin.top - margin.bottom;
var color = d3.scale.category20();
var treemap = d3.layout.treemap()
.size([width, height])
.sticky(true)
.value(function(d) { return d.value;});
d3.select(this.container)
.append('div')
.attr('class', 'basicTreeMap');
var base_element = d3.select('.basicTreeMap')
.append('div')
.style('position', "relative")
.style('width', (width + margin.right) + 'px')
.style('height', (height + margin.bottom) + 'px')
.style('left', margin.left + 'px')
.style('top', margin.top + 'px');
this.width = width;
this.height = height;
this.color = color;
this.treemap = treemap;
this.canvas = base_element;
}
function position() {
this.style("left", function (d) { return d.x + "px";})
.style("top", function(d) { return d.y + "px";})
.style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
.style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
}
BasicTreeMap.render_boxes = function (data) {
var canvas = this.canvas;
// Cleaning contents
canvas.html('');
var width = this.width;
var color = this.color;
var treemap = this.treemap;
var node = canvas.datum(data)
.selectAll(".basicTreeMapnodes")
.data(treemap.nodes)
.enter()
.append('div')
.attr('class', 'basicTreeMapNodes')
.call(position)
.style('background', function(d) {return d.children ? color(d.name): null;})
.text(function(d) { return d.children ? null: d.name;})
.on('click' , function(d) {
if (d.link) {
window.open("http://www."+d.link);
}
});
}
BasicTreeMap.message_handler[mantis.MessageType.SOURCE_UPDATE] = function (data) {
d3.select(this.container).html('');
this.create_layout();
this.render_boxes(data);
};
BasicTreeMap.message_handler[mantis.MessageType.VIEW_INIT] = function (data) {
// Clean Container before drawing
this.message_handler[mantis.MessageType.SOURCE_UPDATE].call(this, data);
};
return BasicTreeMap;
};
|
Java | UTF-8 | 677 | 2.09375 | 2 | [] | no_license | package com.srnpr.xmaspay.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import com.srnpr.xmaspay.response.WechatUnifyResponse;
/**
* 微信交易取消
* @author pang_jhui
*
*/
public interface IWechatTradeCancelAspect {
/**
* 交易取消响应前
*/
public void doBefore(JoinPoint joinPoint);
/**
* 环绕交易取消
* @param joinPoint
* @throws Throwable
*/
public WechatUnifyResponse doAround(ProceedingJoinPoint joinPoint) throws Throwable;
/**
* 环绕交易取消之后
* @param response
* 接口响应信息
*/
public void doAfter(String orderCode, WechatUnifyResponse response);
}
|
Java | UTF-8 | 177 | 1.8125 | 2 | [] | no_license | package dcc.evaluation.computation.model;
public class TestArray {
public static void main(String[] args) {
double a = 0;
System.out.println(Math.abs(a)<1.0e-300);
}
}
|
Java | UTF-8 | 794 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | package ru.job4j.collections;
import org.junit.Test;
import javax.jws.soap.SOAPBinding;
import java.util.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by admin on 12.05.2017.
*/
public class UserConverTest {
@Test
public void TestHashMap() {
User[] users = new User[3];
users[0] = new User("name", 13, "city");
users[1] = new User("name2", 132, "city2");
users[2] = new User("name3", 133, "city3");
ArrayList<User> arrayList = new ArrayList<User>(Arrays.asList(users));
Map<Integer, User> map = new UserConvert().process(arrayList);
assertThat(String.format("%s %s", "name", "city"), is(map.get(13).toString()));
assertThat(map.containsKey(13), is(true));
}
}
|
Java | UTF-8 | 934 | 3.40625 | 3 | [] | no_license | package ft.ufam.ptr.semaforo.model;
/** Objeto que representa um carro.
* @see Veiculo
* @author Felipe André
* @author Paulo Henrique
* @version 3.0, 02/08/2015 */
public class Carro implements Veiculo {
/* Atributos da classe */
private Local origem, destino;
/** Instancia um objeto Carro.
* @param origem - Constante da via de origem do veículo
* @param destino - Constante da via de destino do veículo
* @see Local */
public Carro(Local origem, Local destino) {
this.origem = origem;
this.destino = destino;
}
@Override
public Local getOrigem() {
return origem;
}
@Override
public Local getDestino() {
return destino;
}
@Override
public void setOrigem(Local origem) {
this.origem = origem;
}
@Override
public void setDestino(Local destino) {
this.destino = destino;
}
@Override
public void printInfos() {
System.err.println("Origem: " + origem + " - Destino: " + destino);
}
}
|
Java | UTF-8 | 15,348 | 2.265625 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package project.tools.students;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
/**
*
* @author Clarissa
*/
public class StudentTable {
private final SimpleIntegerProperty studentTableStudentID;
private final SimpleStringProperty studentTableStudentFname;
private final SimpleStringProperty studentTableStudentMname;
private final SimpleStringProperty studentTableStudentLname;
private final SimpleStringProperty studentTableStudentLevel;
private final SimpleStringProperty studentTableStudentCourse;
private final SimpleStringProperty studentTableDataStudentDateofBirth;
private final SimpleStringProperty studentTableDataStudentAge;
private final SimpleStringProperty studentTableDataStudentGender;
private final SimpleStringProperty studentTableDataStudentLandPhone;
private final SimpleStringProperty studentTableDataStudentMobileNo;
private final SimpleStringProperty studentTableDataStudentStreet;
private final SimpleStringProperty studentTableDataStudentCity;
private final SimpleStringProperty studentTableDataStudentPostal;
private final SimpleStringProperty studentTableDataStudentEmail;
private final SimpleIntegerProperty studentTableDataStudentSubject;
private final SimpleIntegerProperty studentTableDataStudentRepeatedSubjects;
private final SimpleIntegerProperty studentTableDataStudentTuition;
private final SimpleIntegerProperty studentTableDataStudentTuitionRep;
private final SimpleIntegerProperty studentTableDataStudentAmountPaid;
private final SimpleIntegerProperty studentTableDataStudentTotalFee;
private final SimpleIntegerProperty studentTableDataStudentRemainingBalance;
public StudentTable(int studentTableStudentID, String studentTableStudentFname, String studentTableStudentMname, String studentTableStudentLname,String studentTableStudentLevel, String studentTableStudentCourse, String studentTableDataStudentDateofBirth, String studentTableDataStudentAge, String studentTableDataStudentGender, String studentTableDataStudentLandPhone, String studentTableDataStudentMobileNo, String studentTableDataStudentStreet, String studentTableDataStudentCity, String studentTableDataStudentPostal, String studentTableDataStudentEmail, int studentTableDataStudentSubject,int studentTableDataStudentRepeatedSubjects, int studentTableDataStudentTuition, int studentTableDataStudentTuitionRep, int studentTableDataStudentAmountPaid,int studentTableDataStudentTotalFee, int studentTableDataStudentRemainingBalance) {
this.studentTableStudentID = new SimpleIntegerProperty(studentTableStudentID);
this.studentTableStudentFname = new SimpleStringProperty(studentTableStudentFname);
this.studentTableStudentMname = new SimpleStringProperty(studentTableStudentMname);
this.studentTableStudentLname = new SimpleStringProperty(studentTableStudentLname);
this.studentTableStudentLevel = new SimpleStringProperty(studentTableStudentLevel);
this.studentTableStudentCourse = new SimpleStringProperty(studentTableStudentCourse);
this.studentTableDataStudentDateofBirth = new SimpleStringProperty(studentTableDataStudentDateofBirth);
this.studentTableDataStudentAge = new SimpleStringProperty(studentTableDataStudentAge);
this.studentTableDataStudentGender = new SimpleStringProperty(studentTableDataStudentGender);
this.studentTableDataStudentLandPhone = new SimpleStringProperty(studentTableDataStudentLandPhone);
this.studentTableDataStudentMobileNo = new SimpleStringProperty(studentTableDataStudentMobileNo);
this.studentTableDataStudentStreet = new SimpleStringProperty(studentTableDataStudentStreet);
this.studentTableDataStudentCity = new SimpleStringProperty(studentTableDataStudentCity);
this.studentTableDataStudentPostal = new SimpleStringProperty(studentTableDataStudentPostal);
this.studentTableDataStudentEmail = new SimpleStringProperty(studentTableDataStudentEmail);
this.studentTableDataStudentSubject = new SimpleIntegerProperty(studentTableDataStudentSubject);
this.studentTableDataStudentRepeatedSubjects = new SimpleIntegerProperty(studentTableDataStudentRepeatedSubjects);
this.studentTableDataStudentTuition = new SimpleIntegerProperty(studentTableDataStudentTuition);
this.studentTableDataStudentTuitionRep = new SimpleIntegerProperty(studentTableDataStudentTuitionRep);
this.studentTableDataStudentAmountPaid = new SimpleIntegerProperty(studentTableDataStudentAmountPaid);
this.studentTableDataStudentTotalFee = new SimpleIntegerProperty(studentTableDataStudentTotalFee);
this.studentTableDataStudentRemainingBalance = new SimpleIntegerProperty(studentTableDataStudentRemainingBalance);
}
//STUDENT_ID
public Integer getStudentTableStudentID() {
return studentTableStudentID.get();
}
public SimpleIntegerProperty studentTableStudentIDProperty() {
return studentTableStudentID;
}
public void setStudentTableStudentID(Integer studentTableStudentID) {
this.studentTableStudentID.set(studentTableStudentID);
}
//FNAME
public String getStudentTableStudentFname(){
return studentTableStudentFname.get();
}
public SimpleStringProperty studentTableStudentFnameProperty() {
return studentTableStudentFname;
}
public void setStudentTableStudentFname(String studentTableStudentFname) {
this.studentTableStudentFname.set(studentTableStudentFname);
}
//MNAME
public String getStudentTableStudentMname() {
return studentTableStudentMname.get();
}
public SimpleStringProperty studentTableStudentMnameProperty() {
return studentTableStudentMname;
}
public void setStudentTableStudentMname(String studentTableStudentMname) {
this.studentTableStudentMname.set(studentTableStudentMname);
}
//Lname
public String getStudentTableStudentLname() {
return studentTableStudentLname.get();
}
public SimpleStringProperty studentTableStudentLnameProperty() {
return studentTableStudentLname;
}
public void setStudentTableStudentLname(String studentTableStudentLname) {
this.studentTableStudentLname.set(studentTableStudentLname);
}
//LEVEL
public String getStudentTableStudentLevel() {
return studentTableStudentLevel.get();
}
public SimpleStringProperty studentTableStudentLevelProperty() {
return studentTableStudentLevel;
}
public void setStudentTableStudentLevel(String studentTableStudentLevel) {
this.studentTableStudentLevel.set(studentTableStudentLevel);
}
//Course
public String getStudentTableStudentCourse() {
return studentTableStudentCourse.get();
}
public SimpleStringProperty studentTableStudentCourseProperty() {
return studentTableStudentCourse;
}
public void setStudentTableStudentCourse(String studentTableStudentCourse) {
this.studentTableStudentCourse.set(studentTableStudentCourse);
}
//DateofBirth
public String getStudentTableDataStudentDateofBirth() {
return studentTableDataStudentDateofBirth.get();
}
public SimpleStringProperty studentTableDataStudentDateofBirthProperty() {
return studentTableDataStudentDateofBirth;
}
public void setStudentTableDataStudentDateofBirth(String studentTableDataStudentDateofBirth) {
this.studentTableDataStudentDateofBirth.set(studentTableDataStudentDateofBirth);
}
//AGE
public String getStudentTableDataStudentAge() {
return studentTableDataStudentAge.get();
}
public SimpleStringProperty studentTableDataStudentAgeProperty() {
return studentTableDataStudentAge;
}
public void setStudentTableDataStudentAge(String studentTableDataStudentAge) {
this.studentTableDataStudentAge.set(studentTableDataStudentAge);
}
//GENDER
public String getStudentTableDataStudentGender() {
return studentTableDataStudentGender.get();
}
public SimpleStringProperty studentTableDataStudentGenderProperty() {
return studentTableDataStudentGender;
}
public void setStudentTableDataStudentGender(String studentTableDataStudentGender) {
this.studentTableDataStudentGender.set(studentTableDataStudentGender);
}
//LANDPHONE
public SimpleStringProperty studentTableDataStudentLandPhoneProperty() {
return studentTableDataStudentLandPhone;
}
public void setStudentTableDataStudentLandPhone(String studentTableDataStudentLandPhone) {
this.studentTableDataStudentLandPhone.set(studentTableDataStudentLandPhone);
}
public String getStudentTableDataStudentLandPhone() {
return studentTableDataStudentLandPhone.get();
}
//Mobile
public String getStudentTableDataStudentMobileNo() {
return studentTableDataStudentMobileNo.get();
}
public SimpleStringProperty studentTableDataStudentMobileNoProperty() {
return studentTableDataStudentMobileNo;
}
public void setStudentTableDataStudentMobileNo(String studentTableDataStudentMobileNo) {
this.studentTableDataStudentMobileNo.set(studentTableDataStudentMobileNo);
}
//Street
public String getStudentTableDataStudentStreet() {
return studentTableDataStudentStreet.get();
}
public SimpleStringProperty studentTableDataStudentStreetProperty() {
return studentTableDataStudentStreet;
}
public void setStudentTableDataStudentStreet(String studentTableDataStudentStreet) {
this.studentTableDataStudentStreet.set(studentTableDataStudentStreet);
}
//City
public String getStudentTableDataStudentCity() {
return studentTableDataStudentCity.get();
}
public SimpleStringProperty studentTableDataStudentCityProperty() {
return studentTableDataStudentCity;
}
public void setStudentTableDataStudentCity(String studentTableDataStudentCity) {
this.studentTableDataStudentCity.set(studentTableDataStudentCity);
}
//Postal
public String getStudentTableDataStudentPostal() {
return studentTableDataStudentPostal.get();
}
public SimpleStringProperty studentTableDataStudentPostalProperty() {
return studentTableDataStudentPostal;
}
public void setStudentTableDataStudentPostal(String studentTableDataStudentPostal) {
this.studentTableDataStudentPostal.set(studentTableDataStudentPostal);
}
//Email
public String getStudentTableDataStudentEmail() {
return studentTableDataStudentEmail.get();
}
public SimpleStringProperty studentTableDataStudentEmailProperty() {
return studentTableDataStudentEmail;
}
public void setStudentTableDataStudentEmail(String studentTableDataStudentEmail) {
this.studentTableDataStudentEmail.set(studentTableDataStudentEmail);
}
public Integer getStudentTableDataStudentSubject() {
return studentTableDataStudentSubject.get();
}
public SimpleIntegerProperty studentTableDataStudentSubjectProperty() {
return studentTableDataStudentSubject;
}
public void setStudentTableDataStudentSubject(Integer studentTableDataStudentSubject) {
this.studentTableDataStudentSubject.set(studentTableDataStudentSubject);
}
//REPSUB
public Integer getStudentTableDataStudentRepeatedSubjects() {
return studentTableDataStudentRepeatedSubjects.get();
}
public SimpleIntegerProperty studentTableDataStudentRepeatedSubjectsProperty() {
return studentTableDataStudentRepeatedSubjects;
}
public void setStudentTableDataStudentRepeatedSubjects(Integer studentTableDataStudentRepeatedSubjects) {
this.studentTableDataStudentRepeatedSubjects.set(studentTableDataStudentRepeatedSubjects);
}
//TUITION
public Integer getStudentTableDataStudentTuition() {
return studentTableDataStudentTuition.get();
}
public SimpleIntegerProperty studentTableDataStudentTuitionProperty() {
return studentTableDataStudentTuition;
}
public void setStudentTableDataStudentTuition(Integer studentTableDataStudentTuition){
this.studentTableDataStudentTuition.set(studentTableDataStudentTuition);
}
//TUITIONREP
public Integer getStudentTableDataStudentTuitionRep() {
return studentTableDataStudentTuitionRep.get();
}
public SimpleIntegerProperty studentTableDataStudentTuitionRepProperty() {
return studentTableDataStudentTuitionRep;
}
public void setStudentTableDataStudentTuitionRep(Integer studentTableDataStudentTuitionRep){
this.studentTableDataStudentTuitionRep.set(studentTableDataStudentTuitionRep);
}
//AMOUNTPAID
public Integer getStudentTableDataStudentAmountPaid() {
return studentTableDataStudentAmountPaid.get();
}
public SimpleIntegerProperty studentTableDataStudentAmountPaidProperty() {
return studentTableDataStudentAmountPaid;
}
public void setStudentTableDataStudentAmountPaid(Integer studentTableDataStudentAmountPaid){
this.studentTableDataStudentAmountPaid.set(studentTableDataStudentAmountPaid);
}
//TOTAL
public Integer getStudentTableDataStudentTotalFeed() {
return studentTableDataStudentTotalFee.get();
}
public SimpleIntegerProperty studentTableDataStudentTotalFeeProperty() {
return studentTableDataStudentTotalFee;
}
public void setStudentTableDataStudentTotalFee(Integer studentTableDataStudentTotalFee){
this.studentTableDataStudentTotalFee.set(studentTableDataStudentTotalFee);
}
//REMAINING BALANCE
public Integer getStudentTableDataStudentRemainingBalance() {
return studentTableDataStudentRemainingBalance.get();
}
public SimpleIntegerProperty studentTableDataStudentRemainingBalanceProperty() {
return studentTableDataStudentRemainingBalance;
}
public void setStudentTableDataStudentRemainingBalance(Integer studentTableDataStudentRemainingBalance){
this.studentTableDataStudentRemainingBalance.set(studentTableDataStudentRemainingBalance);
}
} |
Python | UTF-8 | 536 | 2.859375 | 3 | [] | no_license | #! /usr/bin/env/python
import os
baseFileName = raw_input("Enter base folder name: ")
myPwd = os.getcwd()
for index in range(0, 50):
if not os.path.exists(baseFileName + str(index)):
os.makedirs(baseFileName + str(index))
os.chdir(myPwd + '/' + baseFileName + str(index))
myPwd = os.getcwd()
for fileNameIdx in range(0, 100):
fileOpen = open(baseFileName + str(index) + "_" + str(fileNameIdx), "w+")
fileOpen.write("abcdefghijklmnopqrstuvwxy")
fileOpen.close
|
Java | UTF-8 | 1,933 | 2.265625 | 2 | [] | no_license | package lexcom.app;
import java.io.Serializable;
import java.util.Date;
public class Recordatorio_List implements Serializable {
private static final long serialVersionUID = 1L;
private Integer indice;
private String actor;
private String deudor;
private Date fecha_ingreso;
private Date alerta;
private String estado_promesa;
private Double monto;
public Recordatorio_List(Integer indice, String actor, String deudor, Date fecha_ingreso, Date alerta, String estado_promesa, Double monto) {
this.indice = indice;
this.actor = actor;
this.deudor = deudor;
this.fecha_ingreso = fecha_ingreso;
this.alerta = alerta;
this.estado_promesa = estado_promesa;
this.monto = monto;
}
public Integer getIndice() {
return indice;
}
public void setIndice(Integer indice) {
this.indice = indice;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
public String getDeudor() {
return deudor;
}
public void setDeudor(String deudor) {
this.deudor = deudor;
}
public Date getFecha_ingreso() {
return fecha_ingreso;
}
public void setFecha_ingreso(Date fecha_ingreso) {
this.fecha_ingreso = fecha_ingreso;
}
public Date getAlerta() {
return alerta;
}
public void setAlerta(Date alerta) {
this.alerta = alerta;
}
public String getEstado_promesa() {
return estado_promesa;
}
public void setEstado_promesa(String estado_promesa) {
this.estado_promesa = estado_promesa;
}
public Double getMonto() {
return monto;
}
public void setMonto(Double monto) {
this.monto = monto;
}
}
|
C | UTF-8 | 791 | 3.8125 | 4 | [] | no_license | #include <stdio.h>
/**
* L'entrée standard (0) [stdin]
* Sortie standard (1) [stdout]
* Sortie d'erreur (2) [stderr]
*/
int main() {
FILE * fp = fopen("2/README.md", "r");
printf("Position du curseur: %ld\n", ftell(fp));
char c = fgetc(fp); // Le curseur se déplace de 1
printf("Position du curseur: %ld\n", ftell(fp));
// Positionner le curseur à la fin du fichier
fseek(fp, 0, SEEK_END); // SEEK_SET, SEEK_END, SEEK_CUR
printf("Position du curseur: %ld\n", ftell(fp));
// Position depuis le début du fichier
int k = 5;
fseek(fp, k, SEEK_SET);
printf("Caractère à la position %d : 0x%hhx\n", k, fgetc(fp));
fseek(fp, -k, SEEK_END);
printf("Caractère à la position %d depuis la fin du fichier : 0x%hhx\n", k, fgetc(fp));
}
|
Python | UTF-8 | 3,267 | 3.3125 | 3 | [] | no_license | # -*- coding:utf-8 -*-
def read_single_file_2_lines(filepath):
print('Reading from:' +filepath + '\n')
file_object = open(filepath, 'r')
contents = file_object.read() # get contents from the path
contents_lines = contents.split('\n')
return contents_lines
#获取with as 子句中所有子句的名称以及被调用的次数
def get_with_table_names(line_list):
contents_lines = line_list
with_name = []
with_name_count = {}
total_lines = ' '.join(contents_lines)\
.lower()\
.strip()
words_list = total_lines.split()
index = 0
while index < len(words_list) :
if ( words_list[index] == 'with' ): #if 语句处理每个with子句,以‘;’为结束标志;
with_name.append(words_list[index + 1] )
flag = 0
index +=2
while 1 == 1 :
if words_list[index].startswith('(') :
flag += 1
if words_list[index].endswith(')') or words_list[index].endswith('),') :
flag -= 1
if flag == 0 and ( words_list[index].endswith(',') or words_list[index].endswith('),') ) :
with_name.append(words_list[index + 1])
index += 1
if index >= len(words_list) or words_list[index ].endswith(';') : #若果遇到‘;’ 表示子句结束,跳出此次子循环;
break
index += 1
for name in with_name:
with_name_count[name] = words_list.count(name) + \
words_list.count(name + ')' ) +\
words_list.count(name + ';') +\
words_list.count(name + ');') +\
words_list.count(name + '),') + \
words_list.count(name + ',')
return with_name_count
#返回所有的view 名称以及该名称出现的次数
def get_view_name_count(line_list):
contents_lines = line_list
with_name = get_with_table_names(contents_lines)
total_lines = ' '.join(contents_lines)
view_names = []
view_name_count = {}
words_list = ' '.join(contents_lines)\
.lower()\
.strip()\
.split()
for index in range(len(words_list)):
if index < len(words_list) -2 and words_list[index] == 'view' and words_list[index - 1].endswith('create') :
view_names.append(words_list[index + 1])
for name in view_names:
view_name_count[name] = words_list.count(name) + \
words_list.count(name + ')' ) +\
words_list.count(name + ';') +\
words_list.count(name + ');') +\
words_list.count(name + '),') + \
words_list.count(name + ',')
return view_name_count
contents_lines = read_single_file_2_lines('demo.sql')
view_name_count = get_view_name_count(contents_lines)
with_name_count = get_with_table_names(contents_lines)
print view_name_count
print with_name_count
#print total_lines
#print with_name
#print "sql analytics"
|
Python | UTF-8 | 362 | 2.5625 | 3 | [] | no_license | from mcpi.minecraft import Minecraft
import random
import time
mc = Minecraft.create("10.183.3.38",4711)
def Wool(a,b,c):
x, y, z = mc.player.getPos()
b = random.randint(0,15)
mc.setBlock(x,y,z, 35,b)
time.sleep(.25)
mc.setBlock(x,y,z, 0)
if __name__ == "__main__":
x, y, z = mc.player.getPos()
a = 1
while a == 1:
Wool(x,y,z)
time.sleep(.001)
|
JavaScript | UTF-8 | 563 | 3.359375 | 3 | [] | no_license | var longestCommonPrefix = function(strs) {
if (strs.length <= 0) { return '' }
let i = 0
while (strs.every(s => s[i] && s[i] === strs[0][i])) {
i++
}
return strs[0].slice(0, i)
};
var longestCommonPrefix = function (strs) {
if (strs.length > 0) {
let minLen = Math.min(...strs.map(s => s.length))
const anyStr = strs[0]
while (minLen) {
const prefix = anyStr.slice(0, minLen--)
if (strs.every(s => s.startsWith(prefix))) {
return prefix
}
}
}
return ''
}; |
Python | UTF-8 | 904 | 2.5625 | 3 | [
"MIT"
] | permissive | import os
import sys
import time
from shutil import copyfile, rmtree
from config.logger import logger
quiet = True # set this to false if you're having issues installing to debug stuff
if quiet:
quiet = "-q"
else:
quiet = ""
logger.info("Installing requirements...")
response = os.system(
'{} -m pip install -r requirements.txt {}'.format(sys.executable, quiet))
if response != 0:
logger.error(
"Failed to instal system wide (we recommend a venv if you're not!")
logger.info("Attempting to install as a user package")
response = os.system(
'{} -m pip install -r requirements.txt {} --user'.format(sys.executable, quiet))
if response == 0:
logger.info("Requirements installed! Go have some fun!")
sys.exit(0)
else:
logger.info(
"Something went wrong while installing requirements. Check your python setup and permissions.")
sys.exit(1)
|
Java | UTF-8 | 6,142 | 2.359375 | 2 | [] | no_license | package com.primeton.liuzhichao.demo.redis;
import java.lang.reflect.Method;
import java.util.Set;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MemberSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
@Aspect
@Component
public class RedisCacheAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JedisClientPool jedisClientPool;
@Pointcut("@annotation(RedisCache)")
public void redisCachePointcut() {
}
@Pointcut("@annotation(RedisDel)")
public void redisDelPointcut() {
}
@Around("redisCachePointcut()")
public Object redisCachePointcut(ProceedingJoinPoint joinPoint) throws Throwable {
//得到类名、方法名和参数
String redisResult = "";
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
//根据类名,方法名和参数生成key
String key = genKey(className,methodName,args);
logger.info("生成的key[{}]",key);
//得到被代理的方法
Signature signature = joinPoint.getSignature();
if(!(signature instanceof MemberSignature)){
throw new IllegalArgumentException();
}
MethodSignature methodSignature = (MethodSignature) signature;
Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),methodSignature.getParameterTypes());
//得到被代理的方法上的注解
Object result = null;
//判断方法上是否有加入缓存的注解
if (method.isAnnotationPresent(RedisCache.class)){
String keyName = method.getAnnotation(RedisCache.class).keyName();
int cacheTime = method.getAnnotation(RedisCache.class).cacheTime();
logger.info("cacheTime:"+cacheTime);
if (keyName != null && !keyName.equals("")){
key = keyName+":"+key;
}
if(!jedisClientPool.exists(key)) {
logger.info("缓存未命中");
//缓存不存在,则调用原方法,并将结果放入缓存中
result = joinPoint.proceed(args);
redisResult = JSON.toJSONString(result);
if (cacheTime==-1){
jedisClientPool.set(key,redisResult);
}else {
jedisClientPool.set(key,redisResult,cacheTime);
}
} else{
//缓存命中
logger.info("缓存命中");
redisResult = jedisClientPool.get(key);
//得到被代理方法的返回值类型
Class returnType = method.getReturnType();
result = JSON.parseObject(redisResult,returnType);
logger.info("redis缓存命中返回数据:"+JSON.toJSONString(result));
}
}else {
//执行方法。返回
result = joinPoint.proceed(args);
}
return result;
}
@Around("redisDelPointcut()")
public Object redisDelPointcut(ProceedingJoinPoint joinPoint) throws Throwable {
//得到类名、方法名和参数
String redisResult = "";
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
//根据类名,方法名和参数生成key
String key = genKey(className,methodName,args);
logger.info("生成的key[{}]",key);
//得到被代理的方法
Signature signature = joinPoint.getSignature();
if(!(signature instanceof MemberSignature)){
throw new IllegalArgumentException();
}
MethodSignature methodSignature = (MethodSignature) signature;
Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getName(),methodSignature.getParameterTypes());
//得到被代理的方法上的注解
Object result = null;
//判断方法是否有删除缓存的注解
if (method.isAnnotationPresent(RedisDel.class)){
result = joinPoint.proceed(args);
RedisDel redisDel = method.getAnnotation(RedisDel.class);
//是否删除所有
// boolean all = redisDel.all();
boolean all = false;
String keyName = redisDel.keyName();
System.out.println("删除缓存方法s:"+keyName);
if (all){
Set<String> keys = jedisClientPool.keys(keyName);
for (String s1:keys){
jedisClientPool.del(s1);
}
}else {
if (keyName != null && !keyName.equals("")){
key = keyName+":"+key;
}
System.out.println("删除缓存方法key:"+key);
jedisClientPool.del(keyName);
}
}else {
//执行方法。返回
result = joinPoint.proceed(args);
}
return result;
}
/**
* 生成key
* @param className 目标类名称
* @param methodName 目标类的方法名
* @param args 目标类的参数
* @return className.methodName_args[i]
*/
private String genKey(String className, String methodName, Object[] args) {
StringBuilder sb = new StringBuilder("");
sb.append(className);
sb.append(".");
sb.append(methodName);
for (Object object: args) {
logger.info("obj:"+object);
if(object!=null) {
sb.append("_");
sb.append(object+"");
}
}
return sb.toString();
}
}
|
C# | UTF-8 | 1,993 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | using Azure.Sdk.Tools.TestProxy.Common;
using System;
using System.Text;
namespace Azure.Sdk.Tools.TestProxy.Sanitizers
{
/// <summary>
/// This sanitizer operates on a RecordSession entry and applies itself to the Request and Response bodies contained therein. It ONLY operates on the request/response bodies. Not header or URIs.
/// </summary>
public class BodyRegexSanitizer : RecordedTestSanitizer
{
private string _newValue;
private string _regexValue = null;
private string _groupForReplace = null;
/// <summary>
/// This sanitizer offers regex replace within a returned body. Specifically, this means regex applying to the raw JSON. If you are attempting to simply
/// replace a specific key, the BodyKeySanitizer is probably the way to go. Regardless, there are examples present in SanitizerTests.cs.
/// to
/// </summary>
/// <param name="value">The substitution value.</param>
/// <param name="regex">A regex. Can be defined as a simple regex replace OR if groupForReplace is set, a subsitution operation.</param>
/// <param name="groupForReplace">The capture group that needs to be operated upon. Do not set if you're invoking a simple replacement operation.</param>
public BodyRegexSanitizer(string value = "Sanitized", string regex = null, string groupForReplace = null)
{
_newValue = value;
_regexValue = regex;
_groupForReplace = groupForReplace;
}
public override string SanitizeTextBody(string contentType, string body)
{
return StringSanitizer.SanitizeValue(body, _newValue, _regexValue, _groupForReplace);
}
public override byte[] SanitizeBody(string contentType, byte[] body)
{
return Encoding.UTF8.GetBytes(StringSanitizer.SanitizeValue(Encoding.UTF8.GetString(body), _newValue, _regexValue, _groupForReplace));
}
}
}
|
Markdown | UTF-8 | 812 | 2.78125 | 3 | [] | no_license | [TOC]
# 计算收益率
## 收益率RATE:PV/FV/PMT公式
已知求未知,五大要素知其四可求另一

PV(present value):现值,2034年的十万,相当于2014年的多少钱。(算现值)
FV:终值,2014年的十万,相当于2034年的多少钱
PMT:年金,现在开始存钱,每个月存多少钱,30年后我会有多少钱
## 内部收益率:IRR公式,计算相同时间间隔的年化收益率
假如贷款10000,分12月,每月手续费0.66%,每月还本金83.33(不算手续费),看似年化手续费7.92%。实际上,输入到EXCEL,计算年化为14.31%

## XIRR:不同时间间隔的年化收益率
输入,注意时间格式和投资、收益的正负

|
Python | UTF-8 | 534 | 3.625 | 4 | [] | no_license | import math
import sys
def calculate_fuel(value):
return math.floor(value / 3) - 2
input = sys.stdin.readlines()
values = [];
for line in input:
values.append(calculate_fuel(int(line.strip())))
print("Part 1: " + str(sum(values)))
fuels = [];
def calculate_module_fuel(value):
fuel_for_value = calculate_fuel(value)
if fuel_for_value <= 0:
return 0
return fuel_for_value + calculate_module_fuel(fuel_for_value)
print("Part 2: " + str(sum(map(lambda x: x + calculate_module_fuel(x), values))))
|
Java | UTF-8 | 1,370 | 2.390625 | 2 | [] | no_license | package com.journeyos.freshday.base;
import android.app.Activity;
import android.os.Bundle;
import butterknife.ButterKnife;
/**
* Desc: 基础父类
* Date: 2017/3/2 10:21
* Email: frank.xiong@coolpad.com
*/
public abstract class BaseActivity extends Activity {
public abstract void initData();
public void initView(){}
//布局文件ID
protected abstract int getContentViewId();
//布局中fragment的ID
protected int getFragmentContentId() {
return 0;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
ButterKnife.bind(this);
initView();
initData();
}
//添加fragment
protected void addFragment(com.journeyos.freshday.base.BaseFragment fragment) {
if (fragment != null) {
getFragmentManager().beginTransaction().replace(getFragmentContentId(), fragment
, fragment.getClass().getSimpleName()).addToBackStack(fragment.getClass().getSimpleName())
.commitAllowingStateLoss();
}
}
//移除fragment
protected void removeFragment() {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
finish();
}
}
}
|
Python | UTF-8 | 4,920 | 2.890625 | 3 | [] | no_license | # General
import pandas as pd
import numpy as np
# Statistics
import statistics as st
# Image processing
import matplotlib.pyplot as plt
# Multinomial Logit
from sklearn.linear_model import LogisticRegression
# Support Vector Machine
from sklearn.svm import SVC
# Neural Networks
from sklearn.neural_network import MLPClassifier
# Parameter tuning
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.model_selection import train_test_split
# Load dataset of handwritten digits from URL (takes approx. 30 secs)
import seaborn as sn
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import scale
import cv2
from sklearn.model_selection import cross_validate, cross_val_predict, cross_val_score
from sklearn import metrics
from sklearn import svm
data_set = pd.read_csv("mnist.csv")
mnist_data = data_set.values
# Get useful variables
labels = mnist_data[:, 0]
digits = mnist_data[:, 1:]
img_size = 28
resized_digits = []
for index in range(len(digits)):
resized_digits.append(cv2.resize(np.array(digits[index], dtype='uint8'), (14,14), interpolation = cv2.INTER_AREA))
X_train, X_test, y_train, y_test = train_test_split(digits, labels, test_size=0.88095)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
c_values = [0.001, 0.005, 0.01, 0.015, 0.02, 0.03]
model_scores = []
seed = 0
# Fit models with all C values and determine best accuracy and best C value
# Best value is 0.005
"""
for c in c_values:
log = LogisticRegression(penalty='l1', C=c, solver='liblinear', random_state=seed, max_iter=7600)
log.fit(X_train, y_train)
cv_results = cross_validate(log, X_train, y_train, cv=5)
#log_score = log.score(X_test, y_test)
model_scores.append(cv_results)
print("Multinomial logit model with C =", c, "scored", str(cv_results['test_score']))
print("Average: " + str(sum(cv_results['test_score']) / 5.0))
"""
log = LogisticRegression(penalty='l1', C=0.005, solver='liblinear', random_state=seed, max_iter=7600)
log.fit(X_train, y_train)
log_preds = log.predict(X_test)
log_cm = confusion_matrix(y_test, log_preds)
plt.figure(figsize = (10,7))
sn.heatmap(log_cm, annot=True)
plt.show()
print("R2 score for log model:" + str(log.score(X_test, y_test)))
print("Accuracy score for log model: " + str(metrics.accuracy_score(y_test, log_preds)))
"""
cv_results = cross_validate(log, X_train, y_train, cv=8)
print(cv_results.keys())
print(cv_results['test_score'])
print("Score of model: " + str(log.fit(X_train, y_train).score(X_test, y_test)))
log_preds = log.predict(X_test)
log_cm = confusion_matrix(y_test, log_preds)
plt.figure(figsize = (10,7))
sn.heatmap(log_cm, annot=True)
plt.show()
"""
svm_model = svm.SVC(kernel='poly', C=1, gamma=0.1, random_state=seed, max_iter=7600)
svm_model.fit(X_train, y_train)
cv_results = cross_validate(svm_model, X_train, y_train, cv=5)
model_scores.append(cv_results)
print("SVM model scored", str(cv_results['test_score']))
print("Average: " + str(sum(cv_results['test_score']) / 5.0))
svm_model = svm.SVC(kernel='poly', C=1000000, gamma=1, random_state=seed, max_iter=7600)
svm_model.fit(X_train, y_train)
cv_results = cross_validate(svm_model, X_train, y_train, cv=5)
model_scores.append(cv_results)
print("SVM model scored", str(cv_results['test_score']))
print("Average: " + str(sum(cv_results['test_score']) / 5.0))
model_scores = []
c_values = [ 10**x for x in range(10) ]
g_values = [0.0001, 0.001, 0.01, 0.1, 0.5, 0.7, 0.9, 1.0]
kernel_values = ['linear', 'poly', 'rbf', 'sigmoid']
param_grid = {'C': [0.1,1, 10, 100], 'gamma': [1,0.1,0.01,0.001],'kernel': ['rbf', 'poly', 'sigmoid']}
#grid = GridSearchCV(SVC(),param_grid,refit=True,verbose=2)
#grid.fit(X_train,y_train)
#print(grid.best_estimator_)
svm_model = svm.SVC(kernel='poly', gamma=1, C=0.1, random_state=seed, max_iter=7600)
svm_model.fit(X_train, y_train)
cv_results = cross_validate(svm_model, X_train, y_train, cv=5)
print("SVM model scored", str(cv_results['test_score']))
print("Average: " + str(sum(cv_results['test_score']) / 5.0))
y_preds = svm_model.predict(X_train)
print("Accuracy: ", svm_model.score(X_test, y_test))
"""
for c in c_values:
for g in g_values:
svm_model = svm.SVC(kernel='poly', gamma=g, C=c, random_state=seed, max_iter=7600)
svm_model.fit(X_train, y_train)
cv_results = cross_validate(svm_model, X_train, y_train, cv=5)
model_scores.append(cv_results)
print("SVM model with C =", c, ",", g, "scored", str(cv_results['test_score']))
print("Average: " + str(sum(cv_results['test_score']) / 5.0))
"""
#svm_model = svm.SVC(kernel='rbf', gamma=0.1, C=0.001)
#svm_model.fit(X_train, y_train)
#svm_preds = svm_model.predict(X_test)
#print("R2 score for svm model:" + str(svm_model.score(X_test, y_test)))
#print("Accuracy score for svm model: " + str(metrics.accuracy_score(y_test, svm_preds))) |
Python | UTF-8 | 1,573 | 3.296875 | 3 | [] | no_license | #!/usr/bin/env python3
from pprint import pprint
from typing import Dict, Set, Tuple
# INPUT_FILE_NAME: str = "test-input"
INPUT_FILE_NAME: str = "input"
Cell = Tuple[int, int, int]
actives: Set[Cell] = set()
with open(INPUT_FILE_NAME, "r") as input_file:
z = 0
y = 0
for line in input_file:
actives.update([(x, y, z) for x, val in enumerate(line.strip()) if val == "#"])
y += 1
def get_neighbours(cell: Cell) -> Set[Cell]:
neighbours: Set[Cell] = set(
[
(cell[0] + dx, cell[1] + dy, cell[2] + dz)
for dx in [-1, 0, 1]
for dy in [-1, 0, 1]
for dz in [-1, 0, 1]
if (dx != 0 or dy != 0 or dz != 0)
]
)
return neighbours
def step(active_cells: Set[Cell]) -> Set[Cell]:
active_neighbour_count: Dict[Cell, int] = {}
for active in active_cells:
for neighbour in get_neighbours(active):
if neighbour not in active_neighbour_count:
active_neighbour_count[neighbour] = 0
active_neighbour_count[neighbour] += 1
new_actives: Set[Cell] = set()
for cell, cnt in active_neighbour_count.items():
if cell in active_cells and cnt in (2, 3):
new_actives.add(cell)
elif cell not in active_cells and cnt == 3:
new_actives.add(cell)
return new_actives
print("cycle=0")
# pprint(actives)
print(f"Count: {len(actives)}")
for cycle in range(1, 7):
actives = step(actives)
print(f"cycle={cycle}")
# pprint(actives)
print(f"Count: {len(actives)}")
|
Java | UTF-8 | 359 | 2.09375 | 2 | [] | no_license | package xyz.incraft.SimpleAnnotation.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by Михаил on 20.01.2016.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ShowMethod {
}
|
Java | UTF-8 | 956 | 2.125 | 2 | [] | no_license | package com.ggiit.easyblog.project.system.role.entity;
import com.ggiit.easyblog.framework.web.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 角色实体类
*
* @author gao
* @date 2019.5.8
*/
@Entity
@Table(name = "T_SYS_ROLE")
@Data
@EqualsAndHashCode(callSuper = true)
public class Role extends BaseEntity {
/**
* 角色名称
*/
@Column(name = "NAME_", nullable = false, length = 50)
private String name;
/**
* 角色权限字符串标识
*/
@Column(name = "KEY_", nullable = false, length = 50)
private String key;
/**
* 显示顺序
*/
@Column(name = "SORT_", nullable = false)
private Integer sort;
/**
* 角色状态:1正常、0停用
*/
@Column(name = "STATE_", nullable = false, length = 1)
private Boolean state;
}
|
C | UTF-8 | 1,425 | 3.03125 | 3 | [] | no_license | #include "head.h"
/***创建目录文件链表,区分文件类型***/
INFO* create_file_link()
{
DIR *dir = opendir("./");
if (NULL == dir)
{
perror("fail open rootdir /\n");
return NULL;
}
struct dirent *info_d;
INFO *head = NULL;
while (NULL != (info_d = readdir(dir)))
{
char namebuf[256] = {0};
strcpy(namebuf,info_d->d_name);
//printf("name[%s]\n",namebuf);
/**将.和..还有.开头的隐藏文件跳过*/
if ('.' == namebuf[0])
continue;
char *p = NULL;
p = strtok(namebuf,".");
p = strtok(NULL,"\0");
//printf("p[%s]\n",p);
if (p != NULL &&0 == strcmp(p,"mp4")) {
head = create(head,info_d->d_name,3);
}
else if (DT_REG == info_d->d_type) {
head = create(head,info_d->d_name,1);
}
else if (DT_DIR == info_d->d_type) {
head = create(head,info_d->d_name,2);
}
#if 0
/**区分.h和.c文件*/
char *p = namebuf;
while (*p != '\0')
{
if (*p == '.') {
p++;
if (*p == 'c')
head = create(head,info_d->d_name,10);
else if (*p == 'h')
head = create(head,info_d->d_name,11);
}
p++;
}
#endif
}
return head;
}
/**返回上一级目录**/
void back_pre_dir()
{
char buf[100] = {0};
chdir("../");
getcwd(buf,100);
printf("%s\n",buf);
}
/**进入目录函数****/
void into_file(char *name)
{
char path[1024] = {0};
char buf[] = "./";
sprintf(path,"%s%s",buf,name);
printf("%s\n",path);
chdir(path);
}
|
Java | UTF-8 | 1,274 | 2.421875 | 2 | [] | no_license | package me.matzhilven.war.commands.subcommands.spawn;
import me.matzhilven.war.WARPlugin;
import me.matzhilven.war.commands.SubCommand;
import me.matzhilven.war.utils.StringUtils;
import me.matzhilven.war.war.spawns.Spawn;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import java.util.Optional;
public class RemoveSpawnSubCommand implements SubCommand {
private final WARPlugin main;
public RemoveSpawnSubCommand(WARPlugin main) {
this.main = main;
}
@Override
public void onCommand(Player sender, Command command, String[] args) {
if (args.length != 2) {
StringUtils.sendMessage(sender, main.getMessages().getStringList("usage-spawns"));
return;
}
Optional<Spawn> spawn = main.getSpawnManager().byName(args[1]);
if (!spawn.isPresent()) {
StringUtils.sendMessage(sender, main.getMessages().getString("invalid-spawn"));
return;
}
main.getSpawnManager().removeSpawn(spawn.get());
StringUtils.sendMessage(sender, main.getMessages().getString("removed-spawn")
.replace("%spawn%", spawn.get().getName()));
}
@Override
public String getPermission() {
return "war.admin";
}
}
|
JavaScript | UTF-8 | 420 | 2.984375 | 3 | [] | no_license | const handleEvent = (event) => {
event.preventDefault();
const data = new FormData(event.target);
const objeto = Object.fromEntries(data.entries());
objeto.optionsCheckbox = data.getAll("optionsCheckbox");
console.log(objeto);
};
const formListener = () => {
const myForm = document.querySelector("form");
myForm.addEventListener("submit", handleEvent);
};
function main() {
formListener();
}
main();
|
C | UTF-8 | 37,349 | 3.375 | 3 | [] | no_license | #include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "infinite_int.h"
/**
* Perform some tests on cleans.c
**/
void infint_test_cleans(void)
{
t_inf_int *ptr;
t_inf_int *n;
ptr = NULL;
printf("Enter in %s\n", __FUNCTION__);
printf("Test infinit_free :\n");
printf("NULL pointer\n");
infint_free(NULL);
printf("Pointer on NULL pointer\n");
infint_free(&ptr);
printf("Pointer on valid number\n");
n = infint_new();
infint_free(&n);
assert(n == NULL);
printf("\n");
printf("Test infinit_free_storage :\n");
printf("NULL pointer\n");
infint_free_storage(NULL);
printf("NULL storage\n");
n = infint_new_empty();
infint_free_storage(n);
infint_free(&n);
printf("Pointer on valid number\n");
n = infint_new();
infint_free_storage(n);
assert(n != NULL && n->nb == NULL);
infint_free(&n);
printf("\n");
printf("Test infinit_clear :\n");
printf("NULL pointer\n");
infint_clear(NULL);
printf("Pointer on valid number\n");
n = infint_new();
infint_clear(n);
assert(n != NULL && n->nb == NULL && n->sign == 0 && n->carry == 0 && n->size == 0);
infint_free(&n);
printf("\n");
printf("Test infinit_reset :\n");
printf("NULL pointer\n");
infint_reset(NULL);
printf("Pointer on valid number\n");
n = infint_new();
n = infint_reset(n);
assert(n != NULL && n->nb != NULL && *n->nb == 0 && n->sign == INF_INT_POSITIVE && n->carry == 0 && n->size == 1);
infint_free(&n);
printf("\n");
printf("Test infinit_init :\n");
printf("NULL pointer\n");
infint_init(NULL);
printf("Valid number\n");
n = infint_new();
free(n->nb);
infint_init(n);
assert(n != NULL && n->nb == NULL && n->sign == 0 && n->carry == 0 && n->size == 0);
infint_free(&n);
printf("\n");
printf("Exit from %s\n", __FUNCTION__);
}
/**
* Perform some tests on operations.c
**/
void infint_test_operations(void)
{
t_inf_int *a;
t_inf_int *b;
t_inf_int *r;
t_inf_int *t;
printf("Enter in %s\n", __FUNCTION__);
printf("Test infint_add :\n");
a = infint_new();
b = infint_new();
printf("Invalid a\n");
assert(infint_add(NULL, b) == NULL);
printf("Invalid b\n");
assert(infint_add(a, NULL) == NULL);
printf("3 + 2\n");
*a->nb = 3;
*b->nb = 2;
r = infint_add(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_positive(r));
infint_free(&r);
printf("3 + -2\n");
infint_invert(b);
r = infint_add(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("-3 + -2\n");
infint_invert(a);
r = infint_add(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_negative(r));
infint_free(&r);
printf("-3 + 2\n");
infint_invert(b);
r = infint_add(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("2 + 3\n");
infint_invert(a);
r = infint_add(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_positive(r));
infint_free(&r);
printf("2 + -3\n");
infint_invert(a);
r = infint_add(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("-2 + -3\n");
infint_invert(b);
r = infint_add(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_negative(r));
infint_free(&r);
printf("-2 + 3\n");
infint_invert(a);
r = infint_add(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("%ju + 1\n", UINTMAX_MAX);
*a->nb = UINTMAX_MAX;
infint_invert(b);
r = infint_add(a, b);
assert(r != NULL && r->nb != NULL && r->size == 2 && *r->nb == 1 && r->nb[1] == 1 && infint_is_positive(r));
printf("Prev + 2\n");
infint_free(&a);
a = r;
r = infint_add(a, b);
assert(r != NULL && r->nb != NULL && r->size == 2 && *r->nb == 3 && r->nb[1] == 1 && infint_is_positive(r));
infint_free(&r);
infint_free(&a);
infint_free(&b);
printf("\n");
printf("Test infint_sub :\n");
a = infint_new();
b = infint_new();
printf("Invalid a\n");
assert(infint_sub(NULL, b) == NULL);
printf("Invalid b\n");
assert(infint_sub(a, NULL) == NULL);
printf("3 - 2\n");
*a->nb = 3;
*b->nb = 2;
r = infint_sub(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("3 - -2\n");
infint_invert(b);
r = infint_sub(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_positive(r));
infint_free(&r);
printf("-3 - -2\n");
infint_invert(a);
r = infint_sub(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("-3 - 2\n");
infint_invert(b);
r = infint_sub(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_negative(r));
infint_free(&r);
printf("2 - 3\n");
infint_invert(a);
r = infint_sub(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("2 - -3\n");
infint_invert(a);
r = infint_sub(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_positive(r));
infint_free(&r);
printf("-2 - -3\n");
infint_invert(b);
r = infint_sub(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("-2 - 3\n");
infint_invert(a);
r = infint_sub(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 5 && infint_is_negative(r));
infint_free(&r);
printf("1024 - 1\n");
*a->nb = 1024;
infint_invert(b);
*b->nb = 1;
r = infint_sub(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1023 && infint_is_positive(r));
infint_free(&r);
printf("(%ju + 2) - 1\n", UINTMAX_MAX);
*a->nb = UINTMAX_MAX;
*b->nb = 2;
r = infint_add(a, b);
infint_free(&a);
a = r;
*b->nb = 1;
r = infint_sub(a, b);
assert(r != NULL && r->nb != NULL && r->size == 2 && *r->nb == 0 && r->nb[1] == 1 && infint_is_positive(r));
printf("Prev - 1\n");
infint_free(&a);
a = r;
r = infint_sub(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == UINTMAX_MAX && infint_is_positive(r));
infint_free(&r);
infint_free(&a);
infint_free(&b);
printf("\n");
printf("Test infint_mul :\n");
a = infint_new();
b = infint_new();
printf("Invalid a\n");
assert(infint_mul(NULL, b) == NULL);
printf("Invalid b\n");
assert(infint_mul(a, NULL) == NULL);
printf("0 * 2\n");
*b->nb = 2;
r = infint_mul(a, b);
assert(infint_is_zero(r) == 1);
infint_free(&r);
printf("2 * 0\n");
r = infint_mul(b, a);
assert(infint_is_zero(r) == 1);
infint_free(&r);
printf("1245 * 678\n");
*a->nb = 1245;
*b->nb = 678;
r = infint_mul(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 844110 && infint_is_positive(r));
infint_free(&r);
printf("-678 * 1245\n");
infint_invert(b);
r = infint_mul(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 844110 && infint_is_negative(r));
infint_free(&r);
printf("-1245 * -678\n");
infint_invert(a);
r = infint_mul(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 844110 && infint_is_positive(r));
infint_free(&r);
printf("678 * -1245\n");
infint_invert(b);
r = infint_mul(b, a);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 844110 && infint_is_negative(r));
infint_free(&r);
printf("%ju * 3\n", UINTMAX_MAX);
infint_invert(a);
*a->nb = UINTMAX_MAX;
*b->nb = 3;
r = infint_mul(b, a);
assert(r != NULL && r->nb != NULL && r->size == 2 && *r->nb == UINTMAX_MAX - 2 && r->nb[1] == 2 && infint_is_positive(r));
infint_free(&r);
infint_free(&a);
infint_free(&b);
printf("\n");
printf("Test infint_pow :\n");
a = infint_new();
b = infint_new();
printf("Invalid a\n");
assert(infint_pow(NULL, b) == NULL);
printf("Invalid b\n");
assert(infint_pow(a, NULL) == NULL);
printf("Negative b\n");
*b->nb = 2;
infint_invert(b);
assert(infint_pow(a, b) == NULL);
printf("3 ^ 0\n");
*a->nb = 3;
infint_invert(b);
*b->nb = 0;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("3 ^ 1\n");
*b->nb = 1;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 3 && infint_is_positive(r));
infint_free(&r);
printf("3 ^ 12\n");
*b->nb = 12;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 531441 && infint_is_positive(r));
infint_free(&r);
printf("3 ^ 41\n");
*b->nb = 41;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 2 && *r->nb == (uintmax_t)18026252303461234787UL && r->nb[1] == 1 && infint_is_positive(r));
infint_free(&r);
printf("-3 ^ 0\n");
infint_invert(a);
*b->nb = 0;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("-3 ^ 1\n");
*b->nb = 1;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 3 && infint_is_negative(r));
infint_free(&r);
printf("-3 ^ 12\n");
*b->nb = 12;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 531441 && infint_is_positive(r));
infint_free(&r);
printf("-3 ^ 41\n");
*b->nb = 41;
r = infint_pow(a, b);
assert(r != NULL && r->nb != NULL && r->size == 2 && *r->nb == (uintmax_t)18026252303461234787UL && r->nb[1] == 1 && infint_is_negative(r));
infint_free(&r);
infint_free(&a);
infint_free(&b);
printf("\n");
printf("Test infint_shift_left :\n");
printf("Invalid nb\n");
assert(infint_shift_left(NULL, 1) == NULL);
printf("0 << 0\n");
a = infint_new();
r = infint_shift_left(a, 0);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0);
infint_free(&r);
printf("0 << 128\n");
r = infint_shift_left(a, 128);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0);
infint_free(&r);
printf("1 << 0\n");
*a->nb = 1;
r = infint_shift_left(a, 0);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1);
infint_free(&r);
printf("1 << 128\n");
r = infint_shift_left(a, 128);
assert(r != NULL && r->nb != NULL && r->size == 3 && *r->nb == 0 && r->nb[1] == 0 && r->nb[2] == 1);
infint_free(&r);
infint_free(&a);
printf("\n");
printf("Test infint_shift_right :\n");
printf("Invalid nb\n");
assert(infint_shift_right(NULL, 1) == NULL);
printf("0 >> 0\n");
a = infint_new();
r = infint_shift_right(a, 0);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0);
infint_free(&r);
printf("0 >> 128\n");
r = infint_shift_right(a, 128);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0);
infint_free(&r);
printf("1 >> 1\n");
*a->nb = 1;
r = infint_shift_right(a, 1);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0);
infint_free(&r);
printf("(1 << 128) >> 64\n");
b = infint_shift_left(a, 128);
r = infint_shift_right(b, 64);
assert(r != NULL && r->nb != NULL && r->size == 2 && *r->nb == 0 && r->nb[1] == 1);
infint_free(&r);
printf("(1 << 128) >> 128\n");
r = infint_shift_right(b, 128);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1);
infint_free(&r);
infint_free(&a);
infint_free(&b);
printf("\n");
printf("Test infint_div :\n");
a = infint_new_with_value(3, INF_INT_POSITIVE);
b = infint_new_with_value(0, INF_INT_POSITIVE);
printf("Invalid a\n");
assert(infint_div(NULL, b) == NULL);
printf("Invalid b\n");
assert(infint_div(a, NULL) == NULL);
printf("3 / 0\n");
assert(infint_div(a, b) == NULL);
printf("3 / 2\n");
*b->nb = 2;
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("3 / -2\n");
infint_invert(b);
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 2 && infint_is_negative(r));
infint_free(&r);
printf("-3 / -2\n");
infint_invert(a);
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("-3 / 2\n");
infint_invert(b);
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 2 && infint_is_negative(r));
infint_free(&r);
printf("2 / 3\n");
infint_invert(a);
*a->nb = 2;
*b->nb = 3;
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0 && infint_is_positive(r));
infint_free(&r);
printf("2 / -3\n");
infint_invert(b);
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("-2 / -3\n");
infint_invert(a);
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0 && infint_is_positive(r));
infint_free(&r);
printf("-2 / 3\n");
infint_invert(b);
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("%ju / 3\n", UINTMAX_MAX);
infint_invert(a);
*a->nb = UINTMAX_MAX;
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 6148914691236517205 && infint_is_positive(r));
infint_free(&r);
printf("(%ju + 1) / 3\n", UINTMAX_MAX);
t = infint_new_with_value(1, INF_INT_POSITIVE);
r = infint_add(a, t);
infint_free(&t);
infint_free(&a);
a = r;
r = infint_div(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 6148914691236517205 && infint_is_positive(r));
infint_free(&r);
infint_free(&a);
infint_free(&b);
printf("\n");
printf("Test infint_mod :\n");
a = infint_new_with_value(3, INF_INT_POSITIVE);
b = infint_new_with_value(0, INF_INT_POSITIVE);
printf("Invalid a\n");
assert(infint_mod(NULL, b) == NULL);
printf("Invalid b\n");
assert(infint_mod(a, NULL) == NULL);
printf("3 %% 0\n");
assert(infint_mod(a, b) == NULL);
printf("3 %% 2\n");
*b->nb = 2;
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("3 %% -2\n");
infint_invert(b);
r = infint_mod(a, b);
printf("r : %p\n-> r->nb : %p\n-->r->size : %ju / *r->nb : %c%ju\n", r, r->nb, r->size, (infint_is_positive(r)) ? '+' : '-', *r->nb);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("-3 %% -2\n");
infint_invert(a);
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("-3 %% 2\n");
infint_invert(b);
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("2 %% 3\n");
infint_invert(a);
*a->nb = 2;
*b->nb = 3;
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 2 && infint_is_positive(r));
infint_free(&r);
printf("2 %% -3\n");
infint_invert(b);
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_negative(r));
infint_free(&r);
printf("-2 %% -3\n");
infint_invert(a);
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 2 && infint_is_negative(r));
infint_free(&r);
printf("-2 %% 3\n");
infint_invert(b);
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
printf("%ju %% 3\n", UINTMAX_MAX);
infint_invert(a);
*a->nb = UINTMAX_MAX;
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 0 && infint_is_positive(r));
infint_free(&r);
printf("(%ju + 1) %% 3\n", UINTMAX_MAX);
t = infint_new_with_value(1, INF_INT_POSITIVE);
r = infint_add(a, t);
infint_free(&t);
infint_free(&a);
a = r;
r = infint_mod(a, b);
assert(r != NULL && r->nb != NULL && r->size == 1 && *r->nb == 1 && infint_is_positive(r));
infint_free(&r);
infint_free(&a);
infint_free(&b);
printf("\n");
printf("Exit from %s\n", __FUNCTION__);
}
/**
* Perform some tests on utilities.c
**/
void infint_test_utilities(void)
{
int8_t i8_cnt;
uint8_t u8_cnt;
void *back;
char *s;
t_inf_int n;
t_inf_int *a;
n.nb = NULL;
printf("Enter in %s\n", __FUNCTION__);
u8_cnt = 0;
printf("Test infinit_is_valid_base :\n");
while (1)
{
printf("%d\n", u8_cnt);
assert(infint_is_valid_base(u8_cnt) == ((u8_cnt >= INF_INT_BASE_MIN && u8_cnt <= INF_INT_BASE_MAX) ? 1 : 0));
if (++u8_cnt == 0)
break;
}
printf("\n");
i8_cnt = INT8_MIN;
printf("Test infinit_is_valid_sign :\n");
while (1)
{
printf("%d\n", i8_cnt);
assert(infint_is_valid_sign(i8_cnt) == ((i8_cnt == INF_INT_POSITIVE || i8_cnt == INF_INT_NEGATIVE) ? 1 : 0));
if (++i8_cnt == INT8_MIN)
break;
}
printf("\n");
printf("Test infinit_is_zero :\n");
infint_reset(&n);
n.sign = INF_INT_NEGATIVE;
n.size = 0;
printf("Invalid number\n");
assert(infint_is_zero(&n) == 0);
printf("Number stored with two elements but with 0 values\n");
infint_reset(&n);
infint_update_size(&n, 2);
assert(infint_is_zero(&n) == 1);
n.size = 1;
*n.nb = 1;
printf("Number stored with one element of value non zero\n");
assert(infint_is_zero(&n) == 0);
*n.nb = 0;
printf("Number stored with one element of value 0\n");
assert(infint_is_zero(&n) == 1 && n.sign == INF_INT_POSITIVE);
infint_clear(&n);
free(n.nb);
printf("\n");
printf("Test infinit_is_valid_nb :\n");
infint_reset(&n);
printf("NULL pointer\n");
assert(infint_is_valid_nb(NULL) == 0);
n.sign = 0;
printf("Invalid sign\n");
assert(infint_is_valid_nb(&n) == 0);
n.sign = INF_INT_POSITIVE;
n.size = 0;
printf("Invalid size\n");
assert(infint_is_valid_nb(&n) == 0);
n.size = 1;
back = n.nb;
n.nb = NULL;
printf("NULL storage pointer\n");
assert(infint_is_valid_nb(&n) == 0);
n.nb = back;
printf("Valid number\n");
assert(infint_is_valid_nb(&n) == 1);
infint_clear(&n);
free(n.nb);
printf("\n");
printf("Test infint_is_odd : \n");
printf("Invalid number\n");
assert(infint_is_odd(NULL) == 0);
printf("0\n");
infint_reset(&n);
assert(infint_is_odd(&n) == 0);
printf("1\n");
*n.nb = 1;
assert(infint_is_odd(&n) == 1);
infint_clear(&n);
printf("\n");
printf("Test infint_is_even : \n");
printf("Invalid number\n");
assert(infint_is_even(NULL) == 0);
printf("0\n");
infint_reset(&n);
assert(infint_is_even(&n) == 1);
printf("1\n");
*n.nb = 1;
assert(infint_is_even(&n) == 0);
infint_clear(&n);
printf("\n");
printf("Test infint_is_positive : \n");
printf("Invalid number\n");
assert(infint_is_positive(NULL) == 0);
printf("+0\n");
infint_reset(&n);
assert(infint_is_positive(&n) == 1);
printf("-0\n");
n.sign = INF_INT_NEGATIVE;
assert(infint_is_positive(&n) == 1);
printf("-5\n");
*n.nb = 5;
n.sign = INF_INT_NEGATIVE;
assert(infint_is_positive(&n) == 0);
printf("+5\n");
n.sign = INF_INT_POSITIVE;
assert(infint_is_positive(&n) == 1);
infint_clear(&n);
printf("\n");
printf("Test infint_is_negative : \n");
printf("Invalid number\n");
assert(infint_is_negative(NULL) == 0);
printf("+0\n");
infint_reset(&n);
assert(infint_is_negative(&n) == 0);
printf("-0\n");
n.sign = INF_INT_NEGATIVE;
assert(infint_is_negative(&n) == 0);
printf("-5\n");
*n.nb = 5;
n.sign = INF_INT_NEGATIVE;
assert(infint_is_negative(&n) == 1);
printf("+5\n");
n.sign = INF_INT_POSITIVE;
assert(infint_is_negative(&n) == 0);
infint_clear(&n);
printf("\n");
printf("Test infint_invert :\n");
printf("Invalid number\n");
infint_invert(NULL);
infint_reset(&n);
printf("+0\n");
infint_invert(&n);
assert(n.sign == INF_INT_POSITIVE);
printf("-0\n");
n.sign = INF_INT_NEGATIVE;
infint_invert(&n);
assert(n.sign == INF_INT_POSITIVE);
printf("+5\n");
n.sign = INF_INT_POSITIVE;
*n.nb = 5;
infint_invert(&n);
assert(n.sign == INF_INT_NEGATIVE);
printf("-5\n");
infint_invert(&n);
assert(n.sign == INF_INT_POSITIVE);
infint_clear(&n);
printf("\n");
printf("Test infint_to_string :\n");
a = infint_new();
printf("Invalid number\n");
assert(infint_to_string(NULL, 10) == NULL);
printf("Invalid base (< 2)\n");
assert(infint_to_string(a, 1) == NULL);
printf("Invalid base (> 36)\n");
assert(infint_to_string(a, 40) == NULL);
printf("0 base 2\n");
s = infint_to_string(a, 2);
assert(s != NULL && strcmp(s, "0") == 0);
free(s);
printf("0 base 10\n");
s = infint_to_string(a, 10);
assert(s != NULL && strcmp(s, "0") == 0);
free(s);
printf("0 base 16\n");
s = infint_to_string(a, 16);
assert(s != NULL && strcmp(s, "0") == 0);
free(s);
printf("0 base 31\n");
s = infint_to_string(a, 31);
assert(s != NULL && strcmp(s, "0") == 0);
free(s);
printf("1664 base 2\n");
*a->nb = 1664;
s = infint_to_string(a, 2);
assert(s != NULL && strcmp(s, "11010000000") == 0);
free(s);
printf("1664 base 10\n");
s = infint_to_string(a, 10);
assert(s != NULL && strcmp(s, "1664") == 0);
free(s);
printf("1664 base 16\n");
s = infint_to_string(a, 16);
assert(s != NULL && strcmp(s, "680") == 0);
free(s);
printf("1664 base 31\n");
s = infint_to_string(a, 31);
assert(s != NULL && strcmp(s, "1ML") == 0);
free(s);
printf("-1664 base 2\n");
infint_invert(a);
s = infint_to_string(a, 2);
assert(s != NULL && strcmp(s, "-11010000000") == 0);
free(s);
printf("-1664 base 10\n");
s = infint_to_string(a, 10);
assert(s != NULL && strcmp(s, "-1664") == 0);
free(s);
printf("-1664 base 16\n");
s = infint_to_string(a, 16);
assert(s != NULL && strcmp(s, "-680") == 0);
free(s);
printf("-1664 base 31\n");
s = infint_to_string(a, 31);
assert(s != NULL && strcmp(s, "-1ML") == 0);
free(s);
printf("(2 ** 256) base 2\n");
infint_invert(a);
infint_update_size(a, 5);
a->nb[0] = 0;
a->nb[1] = 0;
a->nb[2] = 0;
a->nb[3] = 0;
a->nb[4] = 1;
s = infint_to_string(a, 2);
assert(s != NULL && strcmp(s, "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") == 0);
free(s);
printf("(2 ** 256) base 10\n");
s = infint_to_string(a, 10);
assert(s != NULL && strcmp(s, "115792089237316195423570985008687907853269984665640564039457584007913129639936") == 0);
free(s);
printf("(2 ** 256) base 16\n");
s = infint_to_string(a, 16);
assert(s != NULL && strcmp(s, "10000000000000000000000000000000000000000000000000000000000000000") == 0);
free(s);
printf("(2 ** 256) base 31\n");
s = infint_to_string(a, 31);
assert(s != NULL && strcmp(s, "A313GILNOEIIEKT9559BQU7H8PBH49N65LT9EK54EO1C67N06B92") == 0);
free(s);
infint_free(&a);
printf("\n");
printf("Exit from %s\n", __FUNCTION__);
}
/**
* Perform some tests on comparisons.c
**/
void infint_test_comparisons(void)
{
t_inf_int a;
t_inf_int b;
a.nb = NULL;
b.nb = NULL;
printf("Enter in %s\n", __FUNCTION__);
printf("Test infint_is_equal (==) :\n");
infint_reset(&a);
infint_reset(&b);
a.size = 0;
printf("Invalid a\n");
assert(infint_is_equal(&a, &b) == 0);
a.size = 1;
b.size = 0;
printf("Invalid b\n");
assert(infint_is_equal(&a, &b) == 0);
b.size = 1;
b.sign = INF_INT_NEGATIVE;
printf("a = +0 / b = -0\n");
assert(infint_is_equal(&a, &b) == 1);
b.sign = INF_INT_NEGATIVE;
*a.nb = 5;
*b.nb = 5;
printf("a = +5 / b = -5\n");
assert(infint_is_equal(&a, &b) == 0);
b.sign = INF_INT_POSITIVE;
infint_update_size(&a, 2);
a.nb[1] = 1;
printf("Storage size of a = 2 / storage size of b = 1\n");
assert(infint_is_equal(&a, &b) == 0);
infint_update_size(&a, 1);
*b.nb = 4;
printf("a = 5 / b = 4\n");
assert(infint_is_equal(&a, &b) == 0);
*b.nb = 5;
printf("a = 5 / b = 5\n");
assert(infint_is_equal(&a, &b) == 1);
printf("\n");
printf("Test infint_is_nequal (!=) :\n");
infint_reset(&a);
infint_reset(&b);
a.size = 0;
printf("Invalid a\n");
assert(infint_is_nequal(&a, &b) == 0);
a.size = 1;
b.size = 0;
printf("Invalid b\n");
assert(infint_is_nequal(&a, &b) == 0);
b.size = 1;
b.sign = INF_INT_NEGATIVE;
printf("a = +0 / b = -0\n");
assert(infint_is_nequal(&a, &b) == 0);
b.sign = INF_INT_NEGATIVE;
*a.nb = 5;
*b.nb = 5;
printf("a = +5 / b = -5\n");
assert(infint_is_nequal(&a, &b) == 1);
b.sign = INF_INT_POSITIVE;
infint_update_size(&a, 2);
printf("Storage size of a = 2 / storage size of b = 1 / but with same value\n");
assert(infint_is_nequal(&a, &b) == 0);
infint_update_size(&a, 1);
*b.nb = 4;
printf("a = 5 / b = 4\n");
assert(infint_is_nequal(&a, &b) == 1);
*b.nb = 5;
printf("a = 5 / b = 5\n");
assert(infint_is_nequal(&a, &b) == 0);
printf("\n");
printf("Test infint_is_greater (>) :\n");
infint_reset(&a);
infint_reset(&b);
a.size = 0;
printf("Invalid a\n");
assert(infint_is_greater(&a, &b) == 0);
a.size = 1;
b.size = 0;
printf("Invalid b\n");
assert(infint_is_greater(&a, &b) == 0);
b.size = 1;
b.sign = INF_INT_NEGATIVE;
printf("a = +0 / b = -0\n");
assert(infint_is_greater(&a, &b) == 0);
b.sign = INF_INT_NEGATIVE;
*a.nb = 5;
*b.nb = 5;
printf("a = +5 / b = -5\n");
assert(infint_is_greater(&a, &b) == 1);
b.sign = INF_INT_POSITIVE;
infint_update_size(&a, 2);
a.nb[1] = 1;
printf("Storage size of +a = 2 / storage size of +b = 1\n");
assert(infint_is_greater(&a, &b) == 1);
a.sign = INF_INT_NEGATIVE;
b.sign = INF_INT_NEGATIVE;
printf("Storage size of -a = 2 / storage size of -b = 1\n");
assert(infint_is_greater(&a, &b) == 0);
infint_update_size(&a, 1);
*b.nb = 4;
printf("a = -5 / b = -4\n");
assert(infint_is_greater(&a, &b) == 0);
a.sign = INF_INT_POSITIVE;
b.sign = INF_INT_POSITIVE;
printf("a = 5 / b = 4\n");
assert(infint_is_greater(&a, &b) == 1);
*b.nb = 7;
printf("a = 5 / b = 7\n");
assert(infint_is_greater(&a, &b) == 0);
*b.nb = 5;
printf("a = 5 / b = 5\n");
assert(infint_is_greater(&a, &b) == 0);
printf("\n");
printf("Test infint_is_smaller_equal (<=) :\n");
infint_reset(&a);
infint_reset(&b);
a.size = 0;
printf("Invalid a\n");
assert(infint_is_smaller_equal(&a, &b) == 0);
a.size = 1;
b.size = 0;
printf("Invalid b\n");
assert(infint_is_smaller_equal(&a, &b) == 0);
b.size = 1;
b.sign = INF_INT_NEGATIVE;
printf("a = +0 / b = -0\n");
assert(infint_is_smaller_equal(&a, &b) == 1);
b.sign = INF_INT_NEGATIVE;
*a.nb = 5;
*b.nb = 5;
printf("a = +5 / b = -5\n");
assert(infint_is_smaller_equal(&a, &b) == 0);
b.sign = INF_INT_NEGATIVE;
infint_update_size(&a, 2);
printf("Storage size of a = 2 / storage size of b = 1\n");
assert(infint_is_smaller_equal(&a, &b) == 0);
infint_update_size(&a, 1);
b.sign = INF_INT_POSITIVE;
*b.nb = 4;
printf("a = 5 / b = 4\n");
assert(infint_is_smaller_equal(&a, &b) == 0);
*b.nb = 7;
printf("a = 5 / b = 7\n");
assert(infint_is_smaller_equal(&a, &b) == 1);
printf("\n");
printf("Test infint_is_smaller (<) :\n");
infint_reset(&a);
infint_reset(&b);
a.size = 0;
printf("Invalid a\n");
assert(infint_is_smaller(&a, &b) == 0);
a.size = 1;
b.size = 0;
printf("Invalid b\n");
assert(infint_is_smaller(&a, &b) == 0);
b.size = 1;
b.sign = INF_INT_NEGATIVE;
printf("a = +0 / b = -0\n");
assert(infint_is_smaller(&a, &b) == 0);
b.sign = INF_INT_NEGATIVE;
*a.nb = 5;
*b.nb = 5;
printf("a = +5 / b = -5\n");
assert(infint_is_smaller(&a, &b) == 0);
b.sign = INF_INT_POSITIVE;
infint_update_size(&a, 2);
a.nb[1] = 1;
printf("Storage size of +a = 2 / storage size of +b = 1\n");
assert(infint_is_smaller(&a, &b) == 0);
a.sign = INF_INT_NEGATIVE;
b.sign = INF_INT_NEGATIVE;
printf("Storage size of -a = 2 / storage size of -b = 1\n");
assert(infint_is_smaller(&a, &b) == 1);
infint_update_size(&a, 1);
*b.nb = 4;
printf("a = -5 / b = -4\n");
assert(infint_is_smaller(&a, &b) == 1);
a.sign = INF_INT_POSITIVE;
b.sign = INF_INT_POSITIVE;
printf("a = 5 / b = 4\n");
assert(infint_is_smaller(&a, &b) == 0);
*b.nb = 7;
printf("a = 5 / b = 7\n");
assert(infint_is_smaller(&a, &b) == 1);
*b.nb = 5;
printf("a = 5 / b = 5\n");
assert(infint_is_smaller(&a, &b) == 0);
printf("\n");
printf("Test infint_is_greater_equal (>=) :\n");
infint_reset(&a);
infint_reset(&b);
a.size = 0;
printf("Invalid a\n");
assert(infint_is_greater_equal(&a, &b) == 0);
a.size = 1;
b.size = 0;
printf("Invalid b\n");
assert(infint_is_greater_equal(&a, &b) == 0);
b.size = 1;
b.sign = INF_INT_NEGATIVE;
printf("a = +0 / b = -0\n");
assert(infint_is_greater_equal(&a, &b) == 1);
b.sign = INF_INT_NEGATIVE;
*a.nb = 5;
*b.nb = 5;
printf("a = +5 / b = -5\n");
assert(infint_is_greater_equal(&a, &b) == 1);
b.sign = INF_INT_POSITIVE;
infint_update_size(&a, 2);
printf("Storage size of a = 2 / storage size of b = 1\n");
assert(infint_is_greater_equal(&a, &b) == 1);
infint_update_size(&a, 1);
*b.nb = 4;
printf("a = 5 / b = 4\n");
assert(infint_is_greater_equal(&a, &b) == 1);
*b.nb = 7;
printf("a = 5 / b = 7\n");
assert(infint_is_greater_equal(&a, &b) == 0);
printf("\n");
infint_free_storage(&a);
infint_free_storage(&b);
printf("Exit from %s\n", __FUNCTION__);
}
/**
* Perform some tests on allocations.c
**/
void infint_test_allocations(void)
{
int i;
char *s;
t_inf_int *n;
t_inf_int *clone;
int proof;
printf("Enter in %s\n", __FUNCTION__);
printf("Test infint_new_empty :\n");
n = infint_new_empty();
assert(n != NULL && n->sign == 0 && n->carry == 0 && n->size == 0 && n->nb == NULL);
infint_free(&n);
printf("\n");
printf("Test infint_new :\n");
n = infint_new();
assert(n != NULL && n->sign == INF_INT_POSITIVE && n->carry == 0 && n->size == 1 && n->nb != NULL && *n->nb == 0);
infint_free(&n);
printf("\n");
printf("Test infint_new_with_size :\n");
printf("Size = 0\n");
n = infint_new_with_size(0);
assert(n != NULL && n->sign == 0 && n->carry == 0 && n->size == 0 && n->nb == NULL);
infint_free(&n);
printf("Size > 0\n");
n = infint_new_with_size(100);
proof = 0;
if (n && n->nb && *n->nb == 0)
{
i = 0;
proof = 1;
while (i < 100)
proof = (proof && (n->nb[i++] == 0));
}
assert(n != NULL && n->sign == INF_INT_POSITIVE && n->carry == 0 && n->size == 100 && n->nb != NULL && proof);
infint_free(&n);
printf("\n");
printf("Test infint_new_with_value :\n");
printf("Invalid sign\n");
n = infint_new_with_value(0, 0);
assert(n == NULL);
printf("Value = +0\n");
n = infint_new_with_value(0, INF_INT_POSITIVE);
assert(n != NULL && n->sign == INF_INT_POSITIVE && n->carry == 0 && n->size == 1 && n->nb != NULL && *n->nb == 0);
infint_free(&n);
printf("Value = -9876543210\n");
n = infint_new_with_value(9876543210L, INF_INT_NEGATIVE);
assert(n != NULL && n->sign == INF_INT_NEGATIVE && n->carry == 0 && n->size == 1 && n->nb != NULL && *n->nb == 9876543210L);
infint_free(&n);
printf("\n");
printf("Test infint_clone :\n");
printf("Invalid number\n");
assert(infint_clone(NULL) == NULL);
printf("Valid number\n");
n = infint_new();
clone = infint_clone(n);
assert(clone != NULL && clone->nb != NULL && clone->sign == n->sign && clone->size == n->size && *clone->nb == *n->nb);
infint_free(&n);
infint_free(&clone);
printf("\n");
printf("Test infint_copy :\n");
printf("Invalid number\n");
assert(infint_copy(NULL, NULL) == NULL);
printf("Valid number\n");
n = infint_new();
clone = infint_new_empty();
clone = infint_copy(clone, n);
assert(clone != NULL && clone->sign == n->sign && clone->size == n->size && clone->nb == n->nb);
infint_free(&n);
clone->nb = NULL;
infint_free(&clone);
printf("\n");
printf("Test infint_update_size :\n");
printf("Invalid number\n");
assert(infint_update_size(NULL, 2) == NULL);
printf("Size = 0\n");
n = infint_new();
assert(infint_update_size(n, 0) == NULL);
printf("Equal size\n");
*n->nb = 42;
n = infint_update_size(n, n->size);
assert(n != NULL && n->nb != NULL && n->size == 1 && *n->nb == 42);
printf("Greater size\n");
n = infint_update_size(n, n->size + 1);
assert(n != NULL && n->nb != NULL && n->size == 2 && *n->nb == 42 && n->nb[1] == 0);
printf("Smaller size\n");
n = infint_update_size(n, n->size - 1);
assert(n != NULL && n->nb != NULL && n->size == 1 && *n->nb == 42);
infint_free(&n);
printf("\n");
printf("Test infint_from_string :\n");
printf("Wrong alphabet\n");
assert(infint_new_from_string("12345;4", 10) == NULL);
printf("Just a sign\n");
assert(infint_new_from_string("-", 10) == NULL);
printf("Bad sign format\n");
assert(infint_new_from_string("1+23454", 10) == NULL);
printf("Wrong base (< 2)\n");
assert(infint_new_from_string("123454", 1) == NULL);
printf("Wrong base (> 36)\n");
assert(infint_new_from_string("123454", 40) == NULL);
printf("Alphabet and base not matching\n");
assert(infint_new_from_string("123454", 5) == NULL);
printf("+0 base 2\n");
n = infint_new_from_string("+0", 2);
s = infint_to_string(n, 10);
assert(n != NULL && strcmp(s, "0") == 0);
free(s);
infint_free(&n);
printf("-0 base 10\n");
n = infint_new_from_string("-0", 10);
s = infint_to_string(n, 10);
assert(n != NULL && strcmp(s, "0") == 0);
free(s);
infint_free(&n);
printf("0 base 16\n");
n = infint_new_from_string("0", 16);
s = infint_to_string(n, 10);
assert(n != NULL && strcmp(s, "0") == 0);
free(s);
infint_free(&n);
printf("123456789 base 31\n");
n = infint_new_from_string("123456789", 31);
s = infint_to_string(n, 10);
assert(n != NULL && strcmp(s, "910698096645") == 0);
free(s);
infint_free(&n);
printf("-765128761926112 base 10\n");
n = infint_new_from_string("-765128761926112", 10);
s = infint_to_string(n, 10);
assert(n != NULL && strcmp(s, "-765128761926112") == 0);
free(s);
infint_free(&n);
printf("1234567890ABCDEFGHIJKLMnopqrstuvwxyz base 36\n");
n = infint_new_from_string("1234567890ABCDEFGHIJKLMnopqrstuvwxyz", 36);
s = infint_to_string(n, 10);
assert(n != NULL && strcmp(s, "3126485650002806059265235559620383787531710118313327355") == 0);
free(s);
infint_free(&n);
printf("\n");
printf("Exit from %s\n", __FUNCTION__);
}
|
Markdown | UTF-8 | 6,460 | 2.515625 | 3 | [] | no_license | Yii 2 Basic Project Template with Deployer.php support.
==========================================================
Yii 2 Basic Project Template with Deployer.php support is a skeleton [Yii 2](http://www.yiiframework.com/) application for
rapidly creating projects.
The template contains the basic features including user login/logout and a contact page.
It includes all commonly used configurations that would allow you to focus on adding new
features to your application.
HOW IS THIS DIFFERENT FROM STANDARD BASIC APP?
----------------------------------------------
* This project can be deployed by Deployer
* `config/db.php` and `yii` is generated automatically
* An `.htaccess` is added to the `web` folder and *FollowSymlinks* is turned on.
* Project can be served directly from source on the development machine, but this requires manual setup - namely creating `yii` and `config/db.php`.
DIRECTORY STRUCTURE
-------------------
assets/ contains assets definition
commands/ contains console commands (controllers)
config/ contains application configurations
controllers/ contains Web controller classes
deployer/recipe contains Deployer recipes
deployer/templates contains templates configured by Deployer
deployer/stage contains configuration file for Deployer
mail/ contains view files for e-mails
migrations/ contains migrations
models/ contains model classes
tests/ contains various tests for the application
vendor/ contains dependent 3rd-party packages
views/ contains view files for the Web application
web/ contains the entry script and Web resources
REQUIREMENTS
------------
The minimum requirement by this project template that your Web server supports PHP 5.4.0.
Getting Start for deployer https://deployer.org/
=====================================================
Step 1 : Install Deployer
-------------------------
Run the following commands in the console:
```
curl -LO https://deployer.org/deployer.phar
mv deployer.phar /usr/local/bin/dep
chmod +x /usr/local/bin/dep
```
Or you can install it with composer:
```
composer require deployer/deployer
```
Step 2 : Initalize Deployer
---------------------------
Now you can use Deployer via the dep command. Open up a terminal in your project directory and run the following command:
```
dep init
```
This command will create deploy.php file in current directory. It is called recipe and contains configuration and tasks for deployment. By default all recipes extends common recipe.
Step 3 : Remotely
-----------------
You need to set the web root of your site to use current/web:
```
/home/yourname/yoursite.com/current/web
```
How Deployer works
------------------
Deployer makes use of three directories on the server:
releases - contains a number of releases (by default 3).
current - symlink to latest release.
shared - this directory contains files/dirs that are shared between releases.
When the deploy script is run, a new release is created on the server. When the deployment has been completed successfully, the symlink current is updated to point to the latest release.
Recipes
---------
With Deployer, we create our deploy script using modular blocks of code called 'recipes'.
Deployer ships with recipes for common frameworks: deployer/tree/master/recipe
In addition, there is a repository for third-party recipes here: https://github.com/deployphp/recipes
for app advance https://github.com/tejrajs/yii2-app-advance-deploy-recipe
for app basic https://github.com/tejrajs/yii2-app-basic-deploy-recipe
Yii2 app basic recipe
-------------------------
#deploy.php
```
<?php
require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
//require_once __DIR__ . '/deployer/recipe/in-place.php';
if (!file_exists (__DIR__ . '/deployer/stage/servers.yml')) {
die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');
set('default_stage', 'production');
set('keep_releases', 2);
set('writable_use_sudo', false); // Using sudo in writable commands?
set('shared_files', [
'config/db.php'
]);
task('deploy:configure_composer', function () {
$stage = env('app.stage');
if($stage == 'dev') {
env('composer_options', 'install --verbose --no-progress --no-interaction');
}
})->desc('Configure composer');
// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');
before('deploy:vendors', 'deploy:configure_composer');
before('deploy:vendors', 'deploy:configure_composer');
before('deploy:shared', 'deploy:configure');
```
#Servers.yml
The deploy script loads configuration values from deployer/stage/servers.yml:
```
# list servers
# -------------
prod_1:
host: hostname
user: username
password: password
stage: production
repository: https://github.com/user/repository.git
deploy_path: /var/www
app:
stage: 'prod'
mysql:
host: db_server
username: dbuser
password: dbpassword
dbname: dbname
dev_1:
local: true
host: localhost
user: username
password: password
stage: local
repository: https://github.com/user/repository.git
deploy_path: /home/user/www
app:
stage: 'dev'
mysql:
host: localhost
username: dbuser
password: dbpassword
dbname: dbname
```
Deployment
--------------
In order to deploy our project, we need to create servers.yml in deployer/stage.
Copy the contents of stage/servers-sample.yml as a template to get you started.
Once that is done, we can finally deploy our project using the following command:
```
dep deploy production
```
If we want to see more of what the deploy script is doing, we can pass it the v option:
```
dep deploy production -v
```
If you want even more, add -vv - and for everything, add -vvv
If something goes wrong, we can roll back:
```
dep rollback production
```
We can also deploy locally, provided that one of the servers in the server list has the local flag set (see above):
dep deploy local |
Java | UTF-8 | 633 | 2.703125 | 3 | [] | no_license | package fr.soat.client.util;
import fr.soat.shared.Person;
public class PersonData {
private Person person;
/**
* Liste civilités
*/
private String[] civilites;
/**
* Constructeur pour civilités
*/
public PersonData() {
civilites = new String[]{"Mlle", "Mme", "Mr"};
}
/**
*
* @return String[]
*/
public String[] getCivilites() {
return civilites;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public void setCivilites(String[] civilites) {
this.civilites = civilites;
}
}
|
Python | UTF-8 | 1,031 | 2.84375 | 3 | [] | no_license | import sys
from j_scraper import j_scraper
from graphql_wrapper import graphql_wrapper
"""
This script will kick off the process to scrape a user specified
number of games from j_archive.
How to run:
python __main__.py <start_game_id> [<end_game_id>]
"""
if __name__ == "__main__":
start_game_id = int(sys.argv[1])
end_game_id = start_game_id+1
if len(sys.argv) == 3:
end_game_id = int(sys.argv[2])+1
for game_id in range(start_game_id, end_game_id):
j_scraper_obj = j_scraper(game_id)
j_scraper_obj.preprocess()
# Fall 2001 is when point values changed, we will only use games starting from 2002
if j_scraper_obj.episode_year >= 2002:
j_scraper_obj.process_clues()
graphql = graphql_wrapper()
graphql.send_game(j_scraper_obj)
print(f'Completed processing for id: {game_id}')
else:
print(f'Game id {game_id} is from year: {j_scraper_obj.episode_year}, and will not be processed.')
print('done') |
Java | UTF-8 | 641 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package com.github.czyzby.context;
/** This class will be used to start component scanning. All annotated classes in this package and any child package
* will be detected and initiated. This is just a utility to mark context location, it should not be used otherwise.
*
* @author MJ */
// Note: normally you could use your Core class equivalent for this, but since this example uses the same package as my
// libraries, I'd rather not risk breaking stuff. Just accept the fact that some (any) class has to mark the scanning
// root of your application - and you can choose multiple scanning roots, for that matter.
public class Root {
}
|
Python | UTF-8 | 2,590 | 3.0625 | 3 | [] | no_license | # skip test or selective test, custom markers
# execution command - pytest test_math_selective.py -v
# execution command - py.test test_math_selective.py -v
# execution command - py.test -v -rxs
""" -k "method name "- only run tests which match the given substring expression. An expression is a python evaluatable
expression where all names are substring-matched
against test names and their parent classes. Example:
-k 'test_method or test_other' matches all test
functions and classes whose name contains
'test_method' or 'test_other', while -k 'not
test_method' matches those that don't contain
'test_method' in their names. Additionally keywords
are matched to classes and functions containing extra
names in their 'extra_keyword_matches' set, as well as
functions which have names assigned directly to them."""
from pytest import mark
import unittest
import base_code
import sys
class TestMathSample1(unittest.TestCase):
def test_add(self):
result = base_code.add(5, 2)
self.assertEqual(result, 7, "Failed test message")
@mark.skip(reason='Not implemented method or predicted method')
def test_add(self):
self.assertEqual(base_code.add(5, 2), 7)
self.assertEqual(base_code.add(-5, 2), -3)
self.assertEqual(base_code.add(-5, -2), -7)
@mark.skipif(sys.platform == 'win32', reason='OS dependency')
def test_subtract(self):
self.assertEqual(base_code.subtract(5, 1), 4)
self.assertEqual(base_code.subtract(-1, 2), -3)
self.assertEqual(base_code.subtract(-1, -10), 9)
@mark.debian
# py.test -v -rxs -m debian
def test_debian(self):
self.assertEqual(base_code.multiply(5, 2), 10)
self.assertEqual(base_code.multiply(-2, 2), -4)
self.assertEqual(base_code.multiply(-5, -5), 25)
@mark.win
def test_divide(self):
self.assertEqual(base_code.divide(8, 2), 4)
self.assertEqual(base_code.divide(-8, 2), -4)
self.assertEqual(base_code.divide(-8, -1), 8)
self.assertEqual(base_code.divide(-8, -1), 8.0) # Check it with // dividing
self.assertRaises(AssertionError, base_code.divide, 8, 0) # 1 way to test raised error
with self.assertRaises(AssertionError): # 2 way to test raised error
base_code.divide(8, 0)
if __name__ == "__main__":
unittest.main()
|
PHP | UTF-8 | 983 | 2.5625 | 3 | [] | no_license | <?php
/*
* 关键字统计(发现、海报、店铺)
*/
class CountController extends CommonController {
public function _initialize(){
header('Content-Type:text/html; charset=UTF-8');
//header('Content-Type:application/json; charset=UTF-8');
}
/*
* 添加统计
* @param string $str 搜索关键词
* @param string $type 类型(1发现、2海报、3店铺)
* @author Jine <luxikun@andlisoft.com>
*/
public function index($str='',$type){
if(!empty($str) || strlen($str)>0){
switch($type){
case 1:
$keywords = D('CountKeywordsFound');
break;
case 2:
$keywords = D('CountKeywordsPoster');
break;
case 3:
$keywords = D('CountKeywordsShop');
break;
}
$map['keywords'] = $str;
$re = $keywords->selData($map);
if(empty($re)){//新增
$map['addTime'] = time();
$re = $keywords->addData($map);
}else{//加一
$re = $keywords->setColunm($map,'number',1);
}
}
}
} |
Java | UTF-8 | 61,836 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package panda.lang.reflect;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import panda.lang.Arrays;
import panda.lang.Asserts;
import panda.lang.Classes;
/**
* Static methods for working with types.
*
*/
public abstract class Types {
public static final Type[] EMPTY_TYPE_ARRAY = new Type[] {};
/**
* Return the castable class name of the given class, usually wrap
* the class name: "int" -> "Integer".
* @param type the class
* @return the castable class name
*/
public static String getCastableClassName(Type type) {
if (type instanceof Class) {
return Classes.getCastableClassName((Class)type);
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)type;
// I'm not exactly sure why getRawType() returns Type instead of Class.
// Neal isn't either but suspects some pathological case related
// to nested classes exists.
Type rawType = parameterizedType.getRawType();
Type[] typeArguments = parameterizedType.getActualTypeArguments();
StringBuilder sb = new StringBuilder(30 * (typeArguments.length + 1));
sb.append(getCastableClassName(rawType));
if (typeArguments.length == 0) {
return sb.toString();
}
sb.append("<").append(getCastableClassName(typeArguments[0]));
for (int i = 1; i < typeArguments.length; i++) {
sb.append(", ").append(getCastableClassName(typeArguments[i]));
}
return sb.append(">").toString();
}
return Classes.getCanonicalClassName(type.toString());
}
public static Type getDefaultImplType(Type type) {
if (isAbstractType(type)) {
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType)type;
Type rawType = getDefaultImplType(pt.getRawType());
type = paramTypeOfOwner(pt.getOwnerType(), rawType, pt.getActualTypeArguments());
}
else {
if (Types.isAssignable(type, List.class)) {
type = ArrayList.class;
}
else if (Types.isAssignable(type, Map.class)) {
type = LinkedHashMap.class;
}
else if (Types.isAssignable(type, Set.class)) {
type = LinkedHashSet.class;
}
}
}
return type;
}
/**
* get declared field type
* @param owner owner type
* @param name field name
* @return field type
*/
public static Type getDeclaredFieldType(Type owner, String name) {
return getDeclaredFieldType(owner, name, null);
}
/**
* get declared field type
* @param owner owner type
* @param name field name
* @param deft default type
* @return field type
*/
public static Type getDeclaredFieldType(Type owner, String name, Type deft) {
Type type = deft;
try {
Class beanClazz = Types.getRawType(owner);
Type gtype = beanClazz.getDeclaredField(name).getGenericType();
if (deft == null || Types.isAssignable(deft, gtype)) {
type = gtype;
}
}
catch (SecurityException e) {
}
catch (NoSuchFieldException e) {
}
return type;
}
@SuppressWarnings("unchecked")
public static <T> T newInstance(Type type) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
return (T)getRawType(type).getDeclaredConstructor().newInstance();
}
/**
* new instance by the type
* @param type type
* @return object instance
*/
public static <T> T born(Type type) {
try {
return newInstance(type);
}
catch (Exception e) {
throw new RuntimeException("Failed to create instance of " + type, e);
}
}
/**
* recursively find ParameterizedType arguments type, if the cls is not ParameterizedType, return null.
* @param cls the class
* @return the type array
*/
public static Type[] getDeclaredGenericTypeParams(Class<?> cls) {
if (cls == null) {
return null;
}
// check super class
Type sc = cls.getGenericSuperclass();
if (sc != null && sc instanceof ParameterizedType) {
return ((ParameterizedType)sc).getActualTypeArguments();
}
// check interface
Type[] interfaces = cls.getGenericInterfaces();
for (Type inf : interfaces) {
if (inf instanceof ParameterizedType) {
return ((ParameterizedType)inf).getActualTypeArguments();
}
}
return getDeclaredGenericTypeParams(cls.getSuperclass());
}
/**
* recursively find ParameterizedType argument type, if the cls is not ParameterizedType, return null.
*
* @param klass class
* @param index argument index
* @return the argument type
*/
public static Type getDeclaredGenericTypeParam(Class<?> klass, int index) {
Type[] types = getDeclaredGenericTypeParams(klass);
if (types == null) {
return null;
}
if (index < 0 || index >= types.length) {
return null;
}
return types[index];
}
/**
* <pre>
* class Test {
* List<String> list;
*
* void test() {
* // return "java.lang.String";
* Types.getGenericFieldParameterTypes(Test.class, "list");
* }
* }
* </pre>
*
* @param owner owner type
* @param fieldName field name
* @return element types
* @throws SecurityException if an security error occurs
* @throws NoSuchFieldException if a field with the specified name is not found.
*/
public static Type[] getGenericFieldParameterTypes(Type owner, String fieldName)
throws SecurityException, NoSuchFieldException {
Class<?> clazz = getRawType(owner);
Field field = clazz.getDeclaredField(fieldName);
Class type = field.getType();
if (type.isArray()) {
return new Type[] { type.getComponentType() };
}
Type ptype = field.getGenericType();
if (ptype instanceof ParameterizedType) {
return ((ParameterizedType)ptype).getActualTypeArguments();
}
return EMPTY_TYPE_ARRAY;
}
/**
* check the type is a interface or abstract
* @param type the type to be checked
* @return <code>true</code> if <code>type</code> is a interface or abstract class
*/
public static boolean isAbstractType(Type type) {
Class clazz = getRawType(type);
return clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers());
}
/**
* Learn whether the specified type denotes an array type.
*
* @param type the type to be checked
* @return <code>true</code> if <code>type</code> is an array class or a
* {@link GenericArrayType}.
*/
public static boolean isArrayType(Type type) {
return type instanceof GenericArrayType || type instanceof Class<?> && ((Class<?>)type).isArray();
}
/**
* The immutable type is:
* enum, primitive type, primitive wrapper, all class inherit from
* CharSequence, Date, Calendar, Number
*
* @param type the type to be checked
* @return true if the class is a immutable type
*/
public static boolean isImmutableType(Type type) {
Class clazz = getRawType(type);
return Classes.isImmutable(clazz);
}
/**
* Determines if the specified {@code Class} object represents a
* primitive type.
*
* <p> There are nine predefined {@code Class} objects to represent
* the eight primitive types and void. These are created by the Java
* Virtual Machine, and have the same names as the primitive types that
* they represent, namely {@code boolean}, {@code byte},
* {@code char}, {@code short}, {@code int},
* {@code long}, {@code float}, and {@code double}.
*
* <p> These objects may only be accessed via the following public static
* final variables, and are the only {@code Class} objects for which
* this method returns {@code true}.
*
* @param type the type
* @return true if and only if this class represents a primitive type
*/
public static boolean isPrimitiveType(Type type) {
Class clazz = getRawType(type);
return Classes.isPrimitiveType(clazz);
}
/**
* Get the array component type of <code>type</code>.
*
* @param type the type to be checked
* @return component type or null if type is not an array type
*/
public static Type getArrayComponentType(Type type) {
if (type instanceof Class<?>) {
Class<?> clazz = (Class<?>)type;
return clazz.isArray() ? clazz.getComponentType() : null;
}
if (type instanceof GenericArrayType) {
return ((GenericArrayType)type).getGenericComponentType();
}
return null;
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type following the Java
* generics rules. If both types are {@link Class} objects, the method returns the result of
* {@link Classes#isAssignable(Class, Class)}.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toType the target type
* @return <code>true</code> if <code>type</code> is assignable to <code>toType</code>.
*/
public static boolean isAssignable(Type type, Type toType) {
return isAssignable(type, toType, null, true);
}
public static boolean isAssignable(Type type, Type toType, boolean autoBoxing) {
return isAssignable(type, toType, null, autoBoxing);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type following the Java
* generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toType the target type
* @param typeVarAssigns optional map of type variable assignments
* @return <code>true</code> if <code>type</code> is assignable to <code>toType</code>.
*/
private static boolean isAssignable(Type type, Type toType,
Map<TypeVariable<?>, Type> typeVarAssigns, boolean autoBoxing) {
if (toType == null || toType instanceof Class<?>) {
return isAssignable(type, (Class<?>)toType, autoBoxing);
}
if (toType instanceof ParameterizedType) {
return isAssignable(type, (ParameterizedType)toType, typeVarAssigns, autoBoxing);
}
if (toType instanceof GenericArrayType) {
return isAssignable(type, (GenericArrayType)toType, typeVarAssigns, autoBoxing);
}
if (toType instanceof WildcardType) {
return isAssignable(type, (WildcardType)toType, typeVarAssigns, autoBoxing);
}
// *
if (toType instanceof TypeVariable<?>) {
return isAssignable(type, (TypeVariable<?>)toType, typeVarAssigns, autoBoxing);
}
// */
throw new IllegalStateException("found an unhandled type: " + toType);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target class following the Java
* generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toClass the target class
* @return true if <code>type</code> is assignable to <code>toClass</code>.
*/
private static boolean isAssignable(Type type, Class<?> toClass, boolean autoBoxing) {
if (type == null) {
// consistency with ClassUtils.isAssignable() behavior
return toClass == null || !toClass.isPrimitive();
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toClass == null) {
return false;
}
// all types are assignable to themselves
if (toClass.equals(type)) {
return true;
}
if (type instanceof Class<?>) {
// just comparing two classes
return Classes.isAssignable((Class<?>)type, toClass, autoBoxing);
}
if (type instanceof ParameterizedType) {
// only have to compare the raw type to the class
return isAssignable(getRawType((ParameterizedType)type), toClass, autoBoxing);
}
// *
if (type instanceof TypeVariable<?>) {
// if any of the bounds are assignable to the class, then the
// type is assignable to the class.
for (Type bound : ((TypeVariable<?>)type).getBounds()) {
if (isAssignable(bound, toClass, autoBoxing)) {
return true;
}
}
return false;
}
// the only classes to which a generic array type can be assigned
// are class Object and array classes
if (type instanceof GenericArrayType) {
return toClass.equals(Object.class)
|| toClass.isArray()
&& isAssignable(((GenericArrayType)type).getGenericComponentType(),
toClass.getComponentType(), autoBoxing);
}
// wildcard types are not assignable to a class (though one would think
// "? super Object" would be assignable to Object)
if (type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target parameterized type following
* the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toParameterizedType the target parameterized type
* @param typeVarAssigns a map with type variables
* @return true if <code>type</code> is assignable to <code>toType</code>.
*/
private static boolean isAssignable(Type type, ParameterizedType toParameterizedType,
Map<TypeVariable<?>, Type> typeVarAssigns, boolean autoBoxing) {
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toParameterizedType == null) {
return false;
}
// all types are assignable to themselves
if (toParameterizedType.equals(type)) {
return true;
}
// get the target type's raw type
Class<?> toClass = getRawType(toParameterizedType);
// get the subject type's type arguments including owner type arguments
// and supertype arguments up to and including the target class.
Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null);
// null means the two types are not compatible
if (fromTypeVarAssigns == null) {
return false;
}
// compatible types, but there's no type arguments. this is equivalent
// to comparing Map< ?, ? > to Map, and raw types are always assignable
// to parameterized types.
if (fromTypeVarAssigns.isEmpty()) {
return true;
}
// get the target type's type arguments including owner type arguments
Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(toParameterizedType,
toClass, typeVarAssigns);
// now to check each type argument
for (Map.Entry<TypeVariable<?>, Type> entry : toTypeVarAssigns.entrySet()) {
Type toTypeArg = entry.getValue();
Type fromTypeArg = fromTypeVarAssigns.get(entry.getKey());
// parameters must either be absent from the subject type, within
// the bounds of the wildcard type, or be an exact match to the
// parameters of the target type.
if (fromTypeArg != null
&& !toTypeArg.equals(fromTypeArg)
&& !(toTypeArg instanceof WildcardType && isAssignable(fromTypeArg, toTypeArg,
typeVarAssigns, autoBoxing))) {
return false;
}
}
return true;
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target generic array type following
* the Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toGenericArrayType the target generic array type
* @param typeVarAssigns a map with type variables
* @return true if <code>type</code> is assignable to <code>toGenericArrayType</code>.
*/
private static boolean isAssignable(Type type, GenericArrayType toGenericArrayType,
Map<TypeVariable<?>, Type> typeVarAssigns, boolean autoBoxing) {
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toGenericArrayType == null) {
return false;
}
// all types are assignable to themselves
if (toGenericArrayType.equals(type)) {
return true;
}
Type toComponentType = toGenericArrayType.getGenericComponentType();
if (type instanceof Class<?>) {
Class<?> cls = (Class<?>)type;
// compare the component types
return cls.isArray()
&& isAssignable(cls.getComponentType(), toComponentType, typeVarAssigns, autoBoxing);
}
if (type instanceof GenericArrayType) {
// compare the component types
return isAssignable(((GenericArrayType)type).getGenericComponentType(),
toComponentType, typeVarAssigns, autoBoxing);
}
if (type instanceof WildcardType) {
// so long as one of the upper bounds is assignable, it's good
for (Type bound : getImplicitUpperBounds((WildcardType)type)) {
if (isAssignable(bound, toGenericArrayType, autoBoxing)) {
return true;
}
}
return false;
}
if (type instanceof TypeVariable<?>) {
// probably should remove the following logic and just return false.
// type variables cannot specify arrays as bounds.
for (Type bound : getImplicitBounds((TypeVariable<?>)type)) {
if (isAssignable(bound, toGenericArrayType, autoBoxing)) {
return true;
}
}
return false;
}
if (type instanceof ParameterizedType) {
// the raw type of a parameterized type is never an array or
// generic array, otherwise the declaration would look like this:
// Collection[]< ? extends String > collection;
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target wildcard type following the
* Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toWildcardType the target wildcard type
* @param typeVarAssigns a map with type variables
* @return true if <code>type</code> is assignable to <code>toWildcardType</code>.
*/
private static boolean isAssignable(Type type, WildcardType toWildcardType,
Map<TypeVariable<?>, Type> typeVarAssigns, boolean autoBoxing) {
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toWildcardType == null) {
return false;
}
// all types are assignable to themselves
if (toWildcardType.equals(type)) {
return true;
}
Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType);
Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType);
if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType)type;
Type[] upperBounds = getImplicitUpperBounds(wildcardType);
Type[] lowerBounds = getImplicitLowerBounds(wildcardType);
for (Type toBound : toUpperBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
toBound = substituteTypeVariables(toBound, typeVarAssigns);
// each upper bound of the subject type has to be assignable to
// each
// upper bound of the target type
for (Type bound : upperBounds) {
if (!isAssignable(bound, toBound, typeVarAssigns, autoBoxing)) {
return false;
}
}
}
for (Type toBound : toLowerBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
toBound = substituteTypeVariables(toBound, typeVarAssigns);
// each lower bound of the target type has to be assignable to
// each
// lower bound of the subject type
for (Type bound : lowerBounds) {
if (!isAssignable(toBound, bound, typeVarAssigns, autoBoxing)) {
return false;
}
}
}
return true;
}
for (Type toBound : toUpperBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
if (!isAssignable(type, substituteTypeVariables(toBound, typeVarAssigns),
typeVarAssigns, autoBoxing)) {
return false;
}
}
for (Type toBound : toLowerBounds) {
// if there are assignments for unresolved type variables,
// now's the time to substitute them.
if (!isAssignable(substituteTypeVariables(toBound, typeVarAssigns), type,
typeVarAssigns, autoBoxing)) {
return false;
}
}
return true;
}
/**
* <p>
* Checks if the subject type may be implicitly cast to the target type variable following the
* Java generics rules.
* </p>
*
* @param type the subject type to be assigned to the target type
* @param toTypeVariable the target type variable
* @param typeVarAssigns a map with type variables
* @return true if <code>type</code> is assignable to <code>toTypeVariable</code>.
*/
private static boolean isAssignable(Type type, TypeVariable<?> toTypeVariable,
Map<TypeVariable<?>, Type> typeVarAssigns, boolean autoBoxing) {
if (type == null) {
return true;
}
// only a null type can be assigned to null type which
// would have cause the previous to return true
if (toTypeVariable == null) {
return false;
}
// all types are assignable to themselves
if (toTypeVariable.equals(type)) {
return true;
}
if (type instanceof TypeVariable<?>) {
// a type variable is assignable to another type variable, if
// and only if the former is the latter, extends the latter, or
// is otherwise a descendant of the latter.
Type[] bounds = getImplicitBounds((TypeVariable<?>)type);
for (Type bound : bounds) {
if (isAssignable(bound, toTypeVariable, typeVarAssigns, autoBoxing)) {
return true;
}
}
}
if (type instanceof Class<?> || type instanceof ParameterizedType
|| type instanceof GenericArrayType || type instanceof WildcardType) {
return false;
}
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* </p>
*
* @param type the type to be replaced
* @param typeVarAssigns the map with type variables
* @return the replaced type
* @throws IllegalArgumentException if the type cannot be substituted
*/
private static Type substituteTypeVariables(Type type, Map<TypeVariable<?>, Type> typeVarAssigns) {
if (type instanceof TypeVariable<?> && typeVarAssigns != null) {
Type replacementType = typeVarAssigns.get(type);
if (replacementType == null) {
throw new IllegalArgumentException("missing assignment type for type variable "
+ type);
}
return replacementType;
}
return type;
}
/**
* <p>
* Retrieves all the type arguments for this parameterized type including owner hierarchy
* arguments such as <code>
* Outer<K,V>.Inner<T>.DeepInner<E></code> . The arguments are returned in a {@link Map}
* specifying the argument type for each {@link TypeVariable}.
* </p>
*
* @param type specifies the subject parameterized type from which to harvest the parameters.
* @return a map of the type arguments to their respective type variables.
*/
public static Map<TypeVariable<?>, Type> getTypeArguments(ParameterizedType type) {
return getTypeArguments(type, getRawType(type), null);
}
/**
* <p>
* Gets the type arguments of a class/interface based on a subtype. For instance, this method
* will determine that both of the parameters for the interface {@link Map} are {@link Object}
* for the subtype {@link java.util.Properties Properties} even though the subtype does not
* directly implement the <code>Map</code> interface.
* <p>
* </p>
* This method returns <code>null</code> if <code>type</code> is not assignable to
* <code>toClass</code>. It returns an empty map if none of the classes or interfaces in its
* inheritance hierarchy specify any type arguments. </p>
* <p>
* A side-effect of this method is that it also retrieves the type arguments for the classes and
* interfaces that are part of the hierarchy between <code>type</code> and <code>toClass</code>.
* So with the above example, this method will also determine that the type arguments for
* {@link java.util.Hashtable Hashtable} are also both <code>Object</code>. In cases where the
* interface specified by <code>toClass</code> is (indirectly) implemented more than once (e.g.
* where <code>toClass</code> specifies the interface {@link java.lang.Iterable Iterable} and
* <code>type</code> specifies a parameterized type that implements both {@link java.util.Set
* Set} and {@link java.util.Collection Collection}), this method will look at the inheritance
* hierarchy of only one of the implementations/subclasses; the first interface encountered that
* isn't a subinterface to one of the others in the <code>type</code> to <code>toClass</code>
* hierarchy.
* </p>
*
* @param type the type from which to determine the type parameters of <code>toClass</code>
* @param toClass the class whose type parameters are to be determined based on the subtype
* <code>type</code>
* @return a map of the type assignments for the type variables in each type in the inheritance
* hierarchy from <code>type</code> to <code>toClass</code> inclusive.
*/
public static Map<TypeVariable<?>, Type> getTypeArguments(Type type, Class<?> toClass) {
return getTypeArguments(type, toClass, null);
}
/**
* <p>
* Return a map of the type arguments of <code>type</code> in the context of
* <code>toClass</code>.
* </p>
*
* @param type the type in question
* @param toClass the class
* @param subtypeVarAssigns a map with type variables
* @return the map with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(Type type, Class<?> toClass,
Map<TypeVariable<?>, Type> subtypeVarAssigns) {
if (type instanceof Class<?>) {
return getTypeArguments((Class<?>)type, toClass, subtypeVarAssigns);
}
if (type instanceof ParameterizedType) {
return getTypeArguments((ParameterizedType)type, toClass, subtypeVarAssigns);
}
if (type instanceof GenericArrayType) {
return getTypeArguments(((GenericArrayType)type).getGenericComponentType(),
toClass.isArray() ? toClass.getComponentType() : toClass, subtypeVarAssigns);
}
// since wildcard types are not assignable to classes, should this just
// return null?
if (type instanceof WildcardType) {
for (Type bound : getImplicitUpperBounds((WildcardType)type)) {
// find the first bound that is assignable to the target class
if (isAssignable(bound, toClass)) {
return getTypeArguments(bound, toClass, subtypeVarAssigns);
}
}
return null;
}
// *
if (type instanceof TypeVariable<?>) {
for (Type bound : getImplicitBounds((TypeVariable<?>)type)) {
// find the first bound that is assignable to the target class
if (isAssignable(bound, toClass)) {
return getTypeArguments(bound, toClass, subtypeVarAssigns);
}
}
return null;
}
// */
throw new IllegalStateException("found an unhandled type: " + type);
}
/**
* <p>
* Return a map of the type arguments of a parameterized type in the context of
* <code>toClass</code>.
* </p>
*
* @param parameterizedType the parameterized type
* @param toClass the class
* @param subtypeVarAssigns a map with type variables
* @return the map with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(ParameterizedType parameterizedType,
Class<?> toClass, Map<TypeVariable<?>, Type> subtypeVarAssigns) {
Class<?> cls = getRawType(parameterizedType);
// make sure they're assignable
if (!isAssignable(cls, toClass)) {
return null;
}
Type ownerType = parameterizedType.getOwnerType();
Map<TypeVariable<?>, Type> typeVarAssigns;
if (ownerType instanceof ParameterizedType) {
// get the owner type arguments first
ParameterizedType parameterizedOwnerType = (ParameterizedType)ownerType;
typeVarAssigns = getTypeArguments(parameterizedOwnerType,
getRawType(parameterizedOwnerType), subtypeVarAssigns);
}
else {
// no owner, prep the type variable assignments map
typeVarAssigns = subtypeVarAssigns == null ? new HashMap<TypeVariable<?>, Type>() : new HashMap<TypeVariable<?>, Type>(
subtypeVarAssigns);
}
// get the subject parameterized type's arguments
Type[] typeArgs = parameterizedType.getActualTypeArguments();
// and get the corresponding type variables from the raw class
TypeVariable<?>[] typeParams = cls.getTypeParameters();
// map the arguments to their respective type variables
for (int i = 0; i < typeParams.length; i++) {
Type typeArg = typeArgs[i];
typeVarAssigns.put(typeParams[i],
typeVarAssigns.containsKey(typeArg) ? typeVarAssigns.get(typeArg) : typeArg);
}
if (toClass.equals(cls)) {
// target class has been reached. Done.
return typeVarAssigns;
}
// walk the inheritance hierarchy until the target class is reached
return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
}
/**
* <p>
* Return a map of the type arguments of a class in the context of <code>toClass</code>.
* </p>
*
* @param cls the class in question
* @param toClass the context class
* @param subtypeVarAssigns a map with type variables
* @return the map with type arguments
*/
private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls, Class<?> toClass,
Map<TypeVariable<?>, Type> subtypeVarAssigns) {
// make sure they're assignable
if (!isAssignable(cls, toClass)) {
return null;
}
// can't work with primitives
if (cls.isPrimitive()) {
// both classes are primitives?
if (toClass.isPrimitive()) {
// dealing with widening here. No type arguments to be
// harvested with these two types.
return new HashMap<TypeVariable<?>, Type>();
}
// work with wrapper the wrapper class instead of the primitive
cls = Classes.primitiveToWrapper(cls);
}
// create a copy of the incoming map, or an empty one if it's null
HashMap<TypeVariable<?>, Type> typeVarAssigns = subtypeVarAssigns == null ? new HashMap<TypeVariable<?>, Type>() : new HashMap<TypeVariable<?>, Type>(
subtypeVarAssigns);
// no arguments for the parameters, or target class has been reached
if (cls.getTypeParameters().length > 0 || toClass.equals(cls)) {
return typeVarAssigns;
}
// walk the inheritance hierarchy until the target class is reached
return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
}
/**
* <p>
* Tries to determine the type arguments of a class/interface based on a super parameterized
* type's type arguments. This method is the inverse of {@link #getTypeArguments(Type, Class)}
* which gets a class/interface's type arguments based on a subtype. It is far more limited in
* determining the type arguments for the subject class's type variables in that it can only
* determine those parameters that map from the subject {@link Class} object to the supertype.
* </p>
* <p>
* Example: {@link java.util.TreeSet TreeSet} sets its parameter as the parameter for
* {@link java.util.NavigableSet NavigableSet}, which in turn sets the parameter of
* {@link java.util.SortedSet}, which in turn sets the parameter of {@link Set}, which in turn
* sets the parameter of {@link java.util.Collection}, which in turn sets the parameter of
* {@link java.lang.Iterable}. Since <code>TreeSet</code>'s parameter maps (indirectly) to
* <code>Iterable</code>'s parameter, it will be able to determine that based on the super type
* <code>Iterable<? extends
* Map<Integer,? extends Collection<?>>></code>, the parameter of <code>TreeSet</code> is
* <code>? extends Map<Integer,? extends
* Collection<?>></code>.
* </p>
*
* @param cls the class whose type parameters are to be determined
* @param superType the super type from which <code>cls</code>'s type arguments are to be
* determined
* @return a map of the type assignments that could be determined for the type variables in each
* type in the inheritance hierarchy from <code>type</code> to <code>toClass</code>
* inclusive.
*/
public static Map<TypeVariable<?>, Type> determineTypeArguments(Class<?> cls,
ParameterizedType superType) {
Class<?> superClass = getRawType(superType);
// compatibility check
if (!isAssignable(cls, superClass)) {
return null;
}
if (cls.equals(superClass)) {
return getTypeArguments(superType, superClass, null);
}
// get the next class in the inheritance hierarchy
Type midType = getClosestParentType(cls, superClass);
// can only be a class or a parameterized type
if (midType instanceof Class<?>) {
return determineTypeArguments((Class<?>)midType, superType);
}
ParameterizedType midParameterizedType = (ParameterizedType)midType;
Class<?> midClass = getRawType(midParameterizedType);
// get the type variables of the mid class that map to the type
// arguments of the super class
Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(midClass, superType);
// map the arguments of the mid type to the class type variables
mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns);
return typeVarAssigns;
}
/**
* <p>
* Performs a mapping of type variables.
* </p>
*
* @param <T> the generic type of the class in question
* @param cls the class in question
* @param parameterizedType the parameterized type
* @param typeVarAssigns the map to be filled
*/
private static <T> void mapTypeVariablesToArguments(Class<T> cls,
ParameterizedType parameterizedType, Map<TypeVariable<?>, Type> typeVarAssigns) {
// capture the type variables from the owner type that have assignments
Type ownerType = parameterizedType.getOwnerType();
if (ownerType instanceof ParameterizedType) {
// recursion to make sure the owner's owner type gets processed
mapTypeVariablesToArguments(cls, (ParameterizedType)ownerType, typeVarAssigns);
}
// parameterizedType is a generic interface/class (or it's in the owner
// hierarchy of said interface/class) implemented/extended by the class
// cls. Find out which type variables of cls are type arguments of
// parameterizedType:
Type[] typeArgs = parameterizedType.getActualTypeArguments();
// of the cls's type variables that are arguments of parameterizedType,
// find out which ones can be determined from the super type's arguments
TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters();
// use List view of type parameters of cls so the contains() method can be used:
List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls.getTypeParameters());
for (int i = 0; i < typeArgs.length; i++) {
TypeVariable<?> typeVar = typeVars[i];
Type typeArg = typeArgs[i];
// argument of parameterizedType is a type variable of cls
if (typeVarList.contains(typeArg)
// type variable of parameterizedType has an assignment in
// the super type.
&& typeVarAssigns.containsKey(typeVar)) {
// map the assignment to the cls's type variable
typeVarAssigns.put((TypeVariable<?>)typeArg, typeVarAssigns.get(typeVar));
}
}
}
/**
* <p>
* Closest parent type? Closest to what? The closest parent type to the super class specified by
* <code>superClass</code>.
* </p>
*
* @param cls the class in question
* @param superClass the super class
* @return the closes parent type
*/
private static Type getClosestParentType(Class<?> cls, Class<?> superClass) {
// only look at the interfaces if the super class is also an interface
if (superClass.isInterface()) {
// get the generic interfaces of the subject class
Type[] interfaceTypes = cls.getGenericInterfaces();
// will hold the best generic interface match found
Type genericInterface = null;
// find the interface closest to the super class
for (Type midType : interfaceTypes) {
Class<?> midClass = null;
if (midType instanceof ParameterizedType) {
midClass = getRawType((ParameterizedType)midType);
}
else if (midType instanceof Class<?>) {
midClass = (Class<?>)midType;
}
else {
throw new IllegalStateException("Unexpected generic"
+ " interface type found: " + midType);
}
// check if this interface is further up the inheritance chain
// than the previously found match
if (isAssignable(midClass, superClass)
&& isAssignable(genericInterface, (Type)midClass)) {
genericInterface = midType;
}
}
// found a match?
if (genericInterface != null) {
return genericInterface;
}
}
// none of the interfaces were descendants of the target class, so the
// super class has to be one, instead
return cls.getGenericSuperclass();
}
/**
* <p>
* Checks if the given value can be assigned to the target type following the Java generics
* rules.
* </p>
*
* @param value the value to be checked
* @param type the target type
* @return true of <code>value</code> is an instance of <code>type</code>.
*/
public static boolean isInstance(Object value, Type type) {
if (type == null) {
return false;
}
return value == null ? !(type instanceof Class<?>) || !((Class<?>)type).isPrimitive() : isAssignable(
value.getClass(), type, null, false);
}
/**
* <p>
* This method strips out the redundant upper bound types in type variable types and wildcard
* types (or it would with wildcard types if multiple upper bounds were allowed).
* </p>
* <p>
* Example: with the variable type declaration:
*
* <pre>
* <K extends java.util.Collection<String> &
* java.util.List<String>>
* </pre>
*
* since <code>List</code> is a subinterface of <code>Collection</code>, this method will return
* the bounds as if the declaration had been:
*
* <pre>
* <K extends java.util.List<String>>
* </pre>
*
* </p>
*
* @param bounds an array of types representing the upper bounds of either
* <code>WildcardType</code> or <code>TypeVariable</code>.
* @return an array containing the values from <code>bounds</code> minus the redundant types.
*/
public static Type[] normalizeUpperBounds(Type[] bounds) {
// don't bother if there's only one (or none) type
if (bounds.length < 2) {
return bounds;
}
Set<Type> types = new HashSet<Type>(bounds.length);
for (Type type1 : bounds) {
boolean subtypeFound = false;
for (Type type2 : bounds) {
if (type1 != type2 && isAssignable(type2, type1, null, false)) {
subtypeFound = true;
break;
}
}
if (!subtypeFound) {
types.add(type1);
}
}
return types.toArray(new Type[types.size()]);
}
/**
* <p>
* Returns an array containing the sole type of {@link Object} if
* {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it returns the result of
* <code>TypeVariable.getBounds()</code> passed into {@link #normalizeUpperBounds}.
* </p>
*
* @param typeVariable the subject type variable
* @return a non-empty array containing the bounds of the type variable.
*/
public static Type[] getImplicitBounds(TypeVariable<?> typeVariable) {
Type[] bounds = typeVariable.getBounds();
return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
}
/**
* <p>
* Returns an array containing the sole value of {@link Object} if
* {@link WildcardType#getUpperBounds()} returns an empty array. Otherwise, it returns the
* result of <code>WildcardType.getUpperBounds()</code> passed into
* {@link #normalizeUpperBounds}.
* </p>
*
* @param wildcardType the subject wildcard type
* @return a non-empty array containing the upper bounds of the wildcard type.
*/
public static Type[] getImplicitUpperBounds(WildcardType wildcardType) {
Type[] bounds = wildcardType.getUpperBounds();
return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
}
/**
* <p>
* Returns an array containing a single value of <code>null</code> if
* {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise, it returns the
* result of <code>WildcardType.getLowerBounds()</code>.
* </p>
*
* @param wildcardType the subject wildcard type
* @return a non-empty array containing the lower bounds of the wildcard type.
*/
public static Type[] getImplicitLowerBounds(WildcardType wildcardType) {
Type[] bounds = wildcardType.getLowerBounds();
return bounds.length == 0 ? new Type[] { null } : bounds;
}
/**
* <p>
* Determines whether or not specified types satisfy the bounds of their mapped type variables.
* When a type parameter extends another (such as <code><T, S extends T></code>), uses another
* as a type parameter (such as <code><T, S extends Comparable<T></code>), or otherwise depends
* on another type variable to be specified, the dependencies must be included in
* <code>typeVarAssigns</code>.
* </p>
*
* @param typeVarAssigns specifies the potential types to be assigned to the type variables.
* @return whether or not the types can be assigned to their respective type variables.
*/
public static boolean typesSatisfyVariables(Map<TypeVariable<?>, Type> typeVarAssigns) {
// all types must be assignable to all the bounds of the their mapped
// type variable.
for (Map.Entry<TypeVariable<?>, Type> entry : typeVarAssigns.entrySet()) {
TypeVariable<?> typeVar = entry.getKey();
Type type = entry.getValue();
for (Type bound : getImplicitBounds(typeVar)) {
if (!isAssignable(type, substituteTypeVariables(bound, typeVarAssigns),
typeVarAssigns, false)) {
return false;
}
}
}
return true;
}
/**
* Returns a new parameterized type, applying {@code typeArguments} to {@code rawType}.
*
* @param rawType the raw type
* @param typeArguments the type arguments
* @return a {@link java.io.Serializable serializable} parameterized type.
*/
public static ParameterizedType paramTypeOf(Type rawType, Type... typeArguments) {
return new ParameterizedTypeImpl(null, rawType, typeArguments);
}
/**
* Returns a new parameterized type, applying {@code typeArguments} to {@code rawType} and
* enclosed by {@code ownerType}.
*
* @param ownerType the owner type
* @param rawType the raw type
* @param typeArguments the type arguments
* @return a {@link java.io.Serializable serializable} parameterized type.
*/
public static ParameterizedType paramTypeOfOwner(Type ownerType, Type rawType,
Type... typeArguments) {
return new ParameterizedTypeImpl(ownerType, rawType, typeArguments);
}
/**
* Returns an array type whose elements are all instances of {@code componentType}.
*
* @param componentType the component type
* @return a {@link java.io.Serializable serializable} generic array type.
*/
public static GenericArrayType arrayTypeOf(Type componentType) {
return new GenericArrayTypeImpl(componentType);
}
/**
* Returns a type that represents an unknown type that extends {@code bound}. For example, if
* {@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If
* {@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for
* {@code ? extends Object}.
*
* @param bound the bound type
* @return the WildCardType
*/
public static WildcardType subTypeOf(Type bound) {
return new WildcardTypeImpl(new Type[] { bound }, EMPTY_TYPE_ARRAY);
}
/**
* Returns a type that represents an unknown supertype of {@code bound}. For example, if
* {@code bound} is {@code String.class}, this returns {@code ?
* super String}.
*
* @param bound the bound type
* @return the WildCardType
*/
public static WildcardType superTypeOf(Type bound) {
return new WildcardTypeImpl(new Type[] { Object.class }, new Type[] { bound });
}
/**
* Returns a type that is functionally equal but not necessarily equal according to
* {@link Object#equals(Object) Object.equals()}. The returned type is
* {@link java.io.Serializable}.
*
* @param type the type
* @return the canonicalized type
*/
public static Type canonicalize(Type type) {
if (type instanceof Class) {
Class<?> c = (Class<?>)type;
return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c;
}
if (type instanceof ParameterizedType) {
ParameterizedType p = (ParameterizedType)type;
return new ParameterizedTypeImpl(p.getOwnerType(), p.getRawType(),
p.getActualTypeArguments());
}
if (type instanceof GenericArrayType) {
GenericArrayType g = (GenericArrayType)type;
return new GenericArrayTypeImpl(g.getGenericComponentType());
}
if (type instanceof WildcardType) {
WildcardType w = (WildcardType)type;
return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());
}
// type is either serializable as-is or unsupported
return type;
}
public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
// type is a normal class.
return (Class<?>)type;
}
else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)type;
// I'm not exactly sure why getRawType() returns Type instead of Class.
// Neal isn't either but suspects some pathological case related
// to nested classes exists.
Type rawType = parameterizedType.getRawType();
Asserts.isTrue(rawType instanceof Class);
return (Class<?>)rawType;
}
else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType)type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
}
else if (type instanceof TypeVariable) {
// we could use the variable's bounds, but that won't work if there are multiple.
// having a raw type that's more general than necessary is okay
return Object.class;
}
else if (type instanceof WildcardType) {
return getRawType(((WildcardType)type).getUpperBounds()[0]);
}
else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
}
static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* @param a the type
* @param b the type
* @return true if {@code a} and {@code b} are equal.
*/
public static boolean equals(Type a, Type b) {
if (a == b) {
// also handles (a == null && b == null)
return true;
}
else if (a instanceof Class) {
// Class already specifies equals().
return a.equals(b);
}
else if (a instanceof ParameterizedType) {
if (!(b instanceof ParameterizedType)) {
return false;
}
// TODO: save a .clone() call
ParameterizedType pa = (ParameterizedType)a;
ParameterizedType pb = (ParameterizedType)b;
return equal(pa.getOwnerType(), pb.getOwnerType())
&& pa.getRawType().equals(pb.getRawType())
&& Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
}
else if (a instanceof GenericArrayType) {
if (!(b instanceof GenericArrayType)) {
return false;
}
GenericArrayType ga = (GenericArrayType)a;
GenericArrayType gb = (GenericArrayType)b;
return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
}
else if (a instanceof WildcardType) {
if (!(b instanceof WildcardType)) {
return false;
}
WildcardType wa = (WildcardType)a;
WildcardType wb = (WildcardType)b;
return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
&& Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
}
else if (a instanceof TypeVariable) {
if (!(b instanceof TypeVariable)) {
return false;
}
TypeVariable<?> va = (TypeVariable<?>)a;
TypeVariable<?> vb = (TypeVariable<?>)b;
return va.getGenericDeclaration() == vb.getGenericDeclaration()
&& va.getName().equals(vb.getName());
}
else {
// This isn't a type we support. Could be a generic array type, wildcard type, etc.
return false;
}
}
private static int hashCodeOrZero(Object o) {
return o != null ? o.hashCode() : 0;
}
public static String toString(Type type) {
return type instanceof Class ? ((Class<?>)type).getName() : type.toString();
}
/**
* Returns the generic supertype for {@code supertype}. For example, given a class
* {@code IntegerSet}, the result for when supertype is {@code Set.class} is
* {@code Set<Integer>} and the result when the supertype is {@code Collection.class} is
* {@code Collection<Integer>}.
*/
static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
if (toResolve == rawType) {
return context;
}
// we skip searching through interfaces if unknown is an interface
if (toResolve.isInterface()) {
Class<?>[] interfaces = rawType.getInterfaces();
for (int i = 0, length = interfaces.length; i < length; i++) {
if (interfaces[i] == toResolve) {
return rawType.getGenericInterfaces()[i];
}
else if (toResolve.isAssignableFrom(interfaces[i])) {
return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i],
toResolve);
}
}
}
// check our supertypes
if (!rawType.isInterface()) {
while (rawType != Object.class) {
Class<?> rawSupertype = rawType.getSuperclass();
if (rawSupertype == toResolve) {
return rawType.getGenericSuperclass();
}
else if (toResolve.isAssignableFrom(rawSupertype)) {
return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype,
toResolve);
}
rawType = rawSupertype;
}
}
// we can't resolve this further
return toResolve;
}
/**
* Returns the generic form of {@code supertype}. For example, if this is
* {@code ArrayList<String>}, this returns {@code Iterable<String>} given the input
* {@code Iterable.class}.
*
* @param supertype a superclass of, or interface implemented by, this.
*/
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
Asserts.isTrue(supertype.isAssignableFrom(contextRawType));
return resolve(context, contextRawType,
Types.getGenericSupertype(context, contextRawType, supertype));
}
private static final Type[] OBJECTS = new Type[] { Object.class };
/**
* Returns the element type of this collection type.
*
* @param context the type
* @param contextRawType type raw type
* @return the collection element type
* @throws IllegalArgumentException if this type is not a collection.
*/
public static Type getCollectionElementType(Type context, Class<?> contextRawType) {
Type collectionType = getSupertype(context, contextRawType, Collection.class);
if (collectionType instanceof WildcardType) {
collectionType = ((WildcardType)collectionType).getUpperBounds()[0];
}
if (collectionType instanceof ParameterizedType) {
Type eType = ((ParameterizedType)collectionType).getActualTypeArguments()[0];
if (eType instanceof TypeVariable && Arrays.equals(OBJECTS, ((TypeVariable)eType).getBounds())) {
eType = Object.class;
}
return eType;
}
return Object.class;
}
public static Type getCollectionElementType(Type type) {
TypeToken typeToken = TypeToken.get(type);
return getCollectionElementType(typeToken);
}
public static Type getCollectionElementType(TypeToken typeToken) {
Type type = typeToken.getType();
Class rawType = typeToken.getRawType();
if (!Collection.class.isAssignableFrom(rawType)) {
return null;
}
return getCollectionElementType(type, rawType);
}
public static Type getArrayElementType(Type type) {
if (Types.isArrayType(type)) {
return Types.getArrayComponentType(type);
}
return Types.getCollectionElementType(type);
}
/**
* Returns a two element array containing this map's key and value types in positions 0 and 1
* respectively.
*
* @param context the type
* @param contextRawType the raw type
* @return the key/value types
*/
public static Type[] getMapKeyAndValueTypes(Type context, Class<?> contextRawType) {
/*
* Work around a problem with the declaration of java.util.Properties. That class should
* extend Hashtable<String, String>, but it's declared to extend Hashtable<Object, Object>.
*/
if (context == Properties.class) {
return new Type[] { String.class, String.class }; // TODO: test subclasses of
// Properties!
}
Type mapType = getSupertype(context, contextRawType, Map.class);
// TODO: strip wildcards?
if (mapType instanceof ParameterizedType) {
ParameterizedType mapParameterizedType = (ParameterizedType)mapType;
return mapParameterizedType.getActualTypeArguments();
}
return new Type[] { Object.class, Object.class };
}
public static Type[] getMapKeyAndValueTypes(TypeToken typeToken) {
Type type = typeToken.getType();
Class rawType = typeToken.getRawType();
if (!Map.class.isAssignableFrom(rawType)) {
return null;
}
Class<?> rawTypeOfSrc = getRawType(type);
return getMapKeyAndValueTypes(type, rawTypeOfSrc);
}
public static Type[] getMapKeyAndValueTypes(Type type) {
if (type instanceof ParameterizedType) {
TypeToken typeToken = TypeToken.get(type);
return getMapKeyAndValueTypes(typeToken);
}
return new Type[] { Object.class, Object.class };
}
public static Type resolve(Type context, Class<?> contextRawType, Type toResolve) {
// this implementation is made a little more complicated in an attempt to avoid
// object-creation
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>)toResolve;
toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
if (toResolve == typeVariable) {
return toResolve;
}
}
else if (toResolve instanceof Class && ((Class<?>)toResolve).isArray()) {
Class<?> original = (Class<?>)toResolve;
Type componentType = original.getComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
return componentType == newComponentType ? original : arrayTypeOf(newComponentType);
}
else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType)toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolve(context, contextRawType, componentType);
return componentType == newComponentType ? original : arrayTypeOf(newComponentType);
}
else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType)toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolve(context, contextRawType, ownerType);
boolean changed = newOwnerType != ownerType;
Type[] args = original.getActualTypeArguments();
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument = resolve(context, contextRawType, args[t]);
if (resolvedTypeArgument != args[t]) {
if (!changed) {
args = args.clone();
changed = true;
}
args[t] = resolvedTypeArgument;
}
}
return changed ? paramTypeOfOwner(newOwnerType, original.getRawType(),
args) : original;
}
else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType)toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound = resolve(context, contextRawType, originalLowerBound[0]);
if (lowerBound != originalLowerBound[0]) {
return superTypeOf(lowerBound);
}
}
else if (originalUpperBound.length == 1) {
Type upperBound = resolve(context, contextRawType, originalUpperBound[0]);
if (upperBound != originalUpperBound[0]) {
return subTypeOf(upperBound);
}
}
return original;
}
else {
return toResolve;
}
}
}
static Type resolveTypeVariable(Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
Class<?> declaredByRaw = declaringClassOf(unknown);
// we can't reduce this further
if (declaredByRaw == null) {
return unknown;
}
Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw);
if (declaredBy instanceof ParameterizedType) {
int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
return ((ParameterizedType)declaredBy).getActualTypeArguments()[index];
}
return unknown;
}
private static int indexOf(Object[] array, Object toFind) {
for (int i = 0; i < array.length; i++) {
if (toFind.equals(array[i])) {
return i;
}
}
throw new NoSuchElementException();
}
/**
* Returns the declaring class of {@code typeVariable}, or {@code null} if it was not declared
* by a class.
*/
private static Class<?> declaringClassOf(TypeVariable<?> typeVariable) {
GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
return genericDeclaration instanceof Class ? (Class<?>)genericDeclaration : null;
}
private static void checkNotPrimitive(Type type) {
Asserts.isTrue(!(type instanceof Class<?>) || !((Class<?>)type).isPrimitive());
}
private static final class ParameterizedTypeImpl implements ParameterizedType, Serializable {
private final Type ownerType;
private final Type rawType;
private final Type[] typeArguments;
public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
// require an owner type if the raw type needs it
if (rawType instanceof Class<?>) {
Class<?> rawTypeAsClass = (Class<?>)rawType;
Asserts.isTrue(ownerType != null || rawTypeAsClass.getEnclosingClass() == null);
Asserts.isTrue(ownerType == null || rawTypeAsClass.getEnclosingClass() != null);
}
this.ownerType = ownerType == null ? null : canonicalize(ownerType);
this.rawType = canonicalize(rawType);
this.typeArguments = typeArguments.clone();
for (int t = 0; t < this.typeArguments.length; t++) {
Asserts.notNull(this.typeArguments[t]);
checkNotPrimitive(this.typeArguments[t]);
this.typeArguments[t] = canonicalize(this.typeArguments[t]);
}
}
public Type[] getActualTypeArguments() {
return typeArguments.clone();
}
public Type getRawType() {
return rawType;
}
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object other) {
return other instanceof ParameterizedType
&& Types.equals(this, (ParameterizedType)other);
}
@Override
public int hashCode() {
return Arrays.hashCode(typeArguments) ^ rawType.hashCode() ^ hashCodeOrZero(ownerType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(30 * (typeArguments.length + 1));
sb.append(Types.toString(rawType));
if (typeArguments.length == 0) {
return sb.toString();
}
sb.append("<").append(Types.toString(typeArguments[0]));
for (int i = 1; i < typeArguments.length; i++) {
sb.append(", ").append(Types.toString(typeArguments[i]));
}
return sb.append(">").toString();
}
private static final long serialVersionUID = 0;
}
private static final class GenericArrayTypeImpl implements GenericArrayType, Serializable {
private final Type componentType;
public GenericArrayTypeImpl(Type componentType) {
this.componentType = canonicalize(componentType);
}
public Type getGenericComponentType() {
return componentType;
}
@Override
public boolean equals(Object o) {
return o instanceof GenericArrayType && Types.equals(this, (GenericArrayType)o);
}
@Override
public int hashCode() {
return componentType.hashCode();
}
@Override
public String toString() {
return Types.toString(componentType) + "[]";
}
private static final long serialVersionUID = 0;
}
/**
* The WildcardType interface supports multiple upper bounds and multiple lower bounds. We only
* support what the Java 6 language needs - at most one bound. If a lower bound is set, the
* upper bound must be Object.class.
*/
private static final class WildcardTypeImpl implements WildcardType, Serializable {
private final Type upperBound;
private final Type lowerBound;
public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds) {
Asserts.isTrue(lowerBounds.length <= 1);
Asserts.isTrue(upperBounds.length == 1);
if (lowerBounds.length == 1) {
Asserts.notNull(lowerBounds[0]);
checkNotPrimitive(lowerBounds[0]);
Asserts.isTrue(upperBounds[0] == Object.class);
this.lowerBound = canonicalize(lowerBounds[0]);
this.upperBound = Object.class;
}
else {
Asserts.notNull(upperBounds[0]);
checkNotPrimitive(upperBounds[0]);
this.lowerBound = null;
this.upperBound = canonicalize(upperBounds[0]);
}
}
public Type[] getUpperBounds() {
return new Type[] { upperBound };
}
public Type[] getLowerBounds() {
return lowerBound != null ? new Type[] { lowerBound } : EMPTY_TYPE_ARRAY;
}
@Override
public boolean equals(Object other) {
return other instanceof WildcardType && Types.equals(this, (WildcardType)other);
}
@Override
public int hashCode() {
// this equals Arrays.hashCode(getLowerBounds()) ^ Arrays.hashCode(getUpperBounds());
return (lowerBound != null ? 31 + lowerBound.hashCode() : 1)
^ (31 + upperBound.hashCode());
}
@Override
public String toString() {
if (lowerBound != null) {
return "? super " + Types.toString(lowerBound);
}
else if (upperBound == Object.class) {
return "?";
}
else {
return "? extends " + Types.toString(upperBound);
}
}
private static final long serialVersionUID = 0;
}
}
|
Shell | UTF-8 | 295 | 3.3125 | 3 | [] | no_license | #!/bin/sh
. ./bin/utils.sh
# Yarn installs node for you. Mercurial is necessary for vim.
formulae=(zsh git tmux mercurial vim yarn n ack mongodb heroku)
main()
{
print 'Installing brew formulae...'
for i in ${formulae[@]} ; do
echo "Installing $i"
brew install $i
done
}
main
|
Python | UTF-8 | 2,551 | 2.90625 | 3 | [
"MIT"
] | permissive | import toml
from .base import Base
class StackOffsetType:
BINJA = 0
IDA = 1
GHIDRA = 2
ANGR = 3
class StackVariable(Base):
"""
Describes a stack variable for a given function.
"""
__slots__ = (
"func_addr",
"name",
"stack_offset",
"stack_offset_type",
"size",
"type",
"last_change"
)
def __init__(self, stack_offset, offset_type, name, type_, size, func_addr, last_change=-1):
self.stack_offset = stack_offset # type: int
self.stack_offset_type = offset_type # type: int
self.name = name # type: str
self.type = type_ # type: str
self.size = size # type: int
self.func_addr = func_addr # type: int
self.last_change = last_change
def __getstate__(self):
return dict(
(k, getattr(self, k)) for k in self.__slots__
)
def __setstate__(self, state):
for k in self.__slots__:
setattr(self, k, state[k])
def __eq__(self, other):
# ignore time and offset type
if isinstance(other, StackVariable):
return other.stack_offset == self.stack_offset \
and other.name == self.name \
and other.type == self.type \
and other.size == self.size \
and other.func_addr == self.func_addr
return False
def get_offset(self, offset_type):
if offset_type == self.stack_offset_type:
return self.stack_offset
# conversion required
if self.stack_offset_type in (StackOffsetType.IDA, StackOffsetType.BINJA):
off = self.stack_offset
else:
raise NotImplementedError()
if offset_type in (StackOffsetType.IDA, StackOffsetType.BINJA):
return off
else:
raise NotImplementedError()
def dump(self):
return toml.dumps(self.__getstate__())
@classmethod
def parse(cls, s):
sv = StackVariable(None, None, None, None, None, None)
sv.__setstate__(toml.loads(s))
return sv
@classmethod
def load_many(cls, svs_toml):
for sv_toml in svs_toml.values():
sv = StackVariable(None, None, None, None, None, None)
sv.__setstate__(sv_toml)
yield sv
@classmethod
def dump_many(cls, svs):
d = { }
for v in sorted(svs.values(), key=lambda x: x.stack_offset):
d["%x" % v.stack_offset] = v.__getstate__()
return d
|
Java | UTF-8 | 3,080 | 2.109375 | 2 | [] | no_license | package demo.example.com.myradarapplication;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
//加载网络头像
public class RadarViewitem extends LinearLayout {
DisplayImageOptions options;
public RadarViewitem(Context context) {
super(context);
// TODO Auto-generated constructor stub
init(context);
}
public RadarViewitem(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init(context);
}
public RadarViewitem(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private TextView tv;
private ImageView iv;
// DisplayImageOptions options;
private void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.radar_item, this);
tv = (TextView) findViewById(R.id.tv);
iv = (ImageView) findViewById(R.id.iv);
options = new DisplayImageOptions.Builder()
// // 设置图片在下载期间显示的图片
// .showImageOnLoading(icon)
// // 设置图片Uri为空或是错误的时候显示的图片
// .showImageForEmptyUri(icon)
// // 设置图片加载/解码过程中错误时候显示的图片
// .showImageOnFail(icon)
.cacheInMemory(true)
// 设置下载的图片是否缓存在内存中
.cacheOnDisk(true)
// 设置下载的图片是否缓存在SD卡中
.considerExifParams(true)
// 列表中用IN_SAMPLE_POWER_OF_2
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)// 设置图片以如何的编码方式显示
.bitmapConfig(Bitmap.Config.ARGB_8888)// 设置图片的解码类型
// .decodingOptions(android.graphics.BitmapFactory.Options
// decodingOptions)//设置图片的解码配置
.considerExifParams(true)
// 设置图片下载前的延迟
.delayBeforeLoading(300)// int
// delayInMillis为你设置的延迟时间
// 设置图片加入缓存前,对bitmap进行设置
// .preProcessor(BitmapProcessor preProcessor)
// .resetViewBeforeLoading(true)// 设置图片在下载前是否重置,复位
.displayer(new CircleBitmapDisplayer(Color.WHITE, 5))// 是否设置为圆角,弧度为多少
// .displayer(new FadeInBitmapDisplayer(500))// 淡入
.build();
// setSpimg("ww");
// setName("sss");
}
//加载图片
public void setSpimg(String urlpath) {
if (iv != null) {
ImageLoader.getInstance().displayImage(urlpath, iv, options);
}
}
public void setName(String name) {
if (tv != null) {
tv.setText(name);
}
}
}
|
Python | UTF-8 | 1,198 | 3.9375 | 4 | [] | no_license | class Queue():
def __init__(self):
self.items=[]
self.num_elements=0
def enqueue(self,element):
self.items.insert(0,element)
self.num_elements+=1
def dequeue(self):
if self.num_elements!=0:
top=self.items[-1]
self.items[-1:]=[]
self.num_elements-=1
return top
return None
def front(self):
if self.num_elements!=0:
return self.items[-1]
return None
def is_empty(self):
if self.num_elements==0:
return True
return False
def size(self):
return self.num_elements
def __iter__(self):
for i in range(-1,-(len(self.items)+1),-1):
yield self.items[i]
# Setup
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(list(q))
# Test size
print ("Pass" if (q.size() == 3) else "Fail")
# Test dequeue
print ("Pass" if (q.dequeue() == 1) else "Fail")
# Test enqueue
q.enqueue(4)
print(list(q))
print ("Pass" if (q.dequeue() == 2) else "Fail")
print ("Pass" if (q.dequeue() == 3) else "Fail")
print ("Pass" if (q.dequeue() == 4) else "Fail")
q.enqueue(5)
print ("Pass" if (q.size() == 1) else "Fail")
|
JavaScript | UTF-8 | 4,691 | 2.5625 | 3 | [
"MIT"
] | permissive | import jQuery from 'jquery';
import abstrax from '../src/index.js';
describe('abstrax', () => {
let myModel = null;
const ajaxArgsFromCall = () => jQuery.ajax.calls.mostRecent().args[0];
const expectFakeHeader = (request, value) => {
myModel[request]();
expect(ajaxArgsFromCall().headers['Fake-Header']).toEqual(value);
};
beforeEach(() => {
myModel = abstrax({
requests: {
getThings: {
url: '/api/things',
headers: {
'Fake-Header': 'bar'
}
},
getUsers: {
url: '/api/users'
},
createUser: {
url: '/api/users',
method: 'POST'
},
getUser: {
url: '/api/users/${userId}'
},
updateUser: {
url: '/api/users/${userId}',
method: 'PATCH'
}
},
defaults: {
headers: {
'Fake-Header': 'foo'
}
}
});
});
it('loads the function', () => expect(abstrax).toBeDefined());
it('defines the request methods', () => {
expect(myModel.getThings).toBeDefined();
expect(myModel.getUsers).toBeDefined();
expect(myModel.createUser).toBeDefined();
expect(myModel.getUser).toBeDefined();
expect(myModel.updateUser).toBeDefined();
});
it('requires a url for each request definition', () => {
const badModel = abstrax({
requests: {
getSomething: {
method: 'GET'
},
getElse: {
url: '/else'
}
}
});
expect(badModel.getSomething).toBeUndefined();
expect(typeof badModel.getElse).toBeDefined();
});
describe('calling a request method', () => {
beforeEach(() => {
const responseData = {
status: 200,
contentType: 'application/json',
responseText: 'JSON user list'
},
ajaxFake = () => {
const d = jQuery.Deferred();
d.resolve(responseData.responseText, responseData.status, responseData);
return d.promise();
};
spyOn(jQuery, 'ajax').and.callFake(ajaxFake);
});
it('uses the global default settings', () => {
expectFakeHeader('getUsers', 'foo');
});
it('overrides the global settings with settings defined per request', () => {
expectFakeHeader('getThings', 'bar');
});
it('returns the ajax request object', (done) => {
const request = myModel.getUsers(),
mostRecentArgs = ajaxArgsFromCall();
expect(mostRecentArgs.url).toEqual('/api/users');
expect(mostRecentArgs.method).toEqual('GET');
request.then((data) => {
expect(data).toEqual('JSON user list');
done();
});
});
describe('with a payload', () => {
it('calls jQuery.ajax with the correct data value', () => {
const payload = {
email: 'john@example.com',
password: 'abcd1234'
};
myModel.createUser(payload);
const mostRecentArgs = ajaxArgsFromCall();
expect(mostRecentArgs.url).toEqual('/api/users');
expect(mostRecentArgs.method).toEqual('POST');
expect(mostRecentArgs.data).toEqual(JSON.stringify(payload));
});
});
describe('without necessary url keys', () => {
it('throws an error', () => {
expect(myModel.getUser).toThrow(new Error('Must supply url keys before calling fulfill'));
});
});
describe('with url keys', () => {
it('calls jQuery.ajax with the correctly keyed url', () => {
myModel.getUser.for({userId: '123'})();
const mostRecentArgs = ajaxArgsFromCall();
expect(mostRecentArgs.url).toEqual('/api/users/123');
expect(mostRecentArgs.method).toEqual('GET');
});
});
describe('with unnecessary url keys', () => {
it('calls jQuery.ajax with the correct url', () => {
myModel.getThings.for({
someKey: '1',
anotherKey: 'abc'
})();
const mostRecentArgs = ajaxArgsFromCall();
expect(mostRecentArgs.url).toEqual('/api/things');
expect(mostRecentArgs.method).toEqual('GET');
});
});
describe('with url keys and payload', () => {
it('calls jQuery.ajax with the correct data value', () => {
const payload = {
email: 'john@example.com',
password: 'abcd1234'
};
myModel.updateUser.for({ userId: '123'})(payload);
const mostRecentArgs = ajaxArgsFromCall();
expect(mostRecentArgs.url).toEqual('/api/users/123');
expect(mostRecentArgs.method).toEqual('PATCH');
expect(mostRecentArgs.data).toEqual(JSON.stringify(payload));
});
});
});
});
|
C++ | UTF-8 | 5,762 | 3.140625 | 3 | [] | no_license | // File: main.cpp
// Authors: Cody Valle
// Description: Draws a primitive circle.
#include <GL/glew.h>
#include <GL/freeglut.h>
#ifdef __APPLE__
# include <OpenGL/glext.h>
#else
# include <GL/glext.h>
#pragma comment(lib, "glew32.lib")
#endif
#include <cmath>
#include <iostream>
const double PI = 3.14159265359;
static unsigned char numVertices = 15;
static bool isWire = false;
void drawParabola(const double cx, const double cy)
{
double a = 0.25,
left_end = -20,
right_end = 20,
x, y;
glColor3f(1,0,1);
glLineWidth(2);
glBegin(GL_LINE_STRIP);
for (unsigned char i = 0; i < numVertices; ++i)
{
x = cx + ((right_end - cx) / numVertices) * i;
y = cy + a * std::pow(x - cx, 2);
glVertex3d(x, y, 0);
}
glEnd();
glBegin(GL_LINE_STRIP);
for (unsigned char i = 0; i < numVertices; ++i)
{
x = cx - ((cx - left_end) / numVertices) * i;
y = cy + a * std::pow(x - cx, 2);
glVertex3d(x, y, 0);
}
glEnd();
}
void drawCircle(const double r, const double cx, const double cy)
{
glLineWidth(3);
glBegin(GL_LINE_LOOP);
for (unsigned char i = 0; i < numVertices; ++i)
{
double t = PI * i / numVertices * 2;
glVertex3d(std::cos(t) * r + cx,
std::sin(t) * r + cy,
0);
}
glEnd();
}
void drawDisk(const double cx, const double cy, const double z, const double r)
{
glBegin(GL_TRIANGLE_FAN);
glVertex3d(cx, cy, z);
for (unsigned char i = 0; i <= numVertices; ++i)
{
double t = PI * i / numVertices * 2;
glVertex3d(std::cos(t) * r + cx,
std::sin(t) * r + cy,
z);
}
glEnd();
}
void drawTorus(const double r, const double w, const double cx, const double cy, const double z = 0)
{
glBegin(GL_TRIANGLE_STRIP);
for (unsigned char i = 0; i <= numVertices; ++i)
{
double t = PI * i / numVertices * 2;
glVertex3d(std::cos(t) * (r + w) + cx,
std::sin(t) * (r + w) + cy,
z);
glVertex3d(std::cos(t) * (r - w) + cx,
std::sin(t) * (r - w) + cy,
z);
}
glEnd();
}
void drawRing(const double r, const double w, const double cx, const double cy, const double z = 0)
{
glBegin(GL_TRIANGLE_STRIP);
for (unsigned char i = 0; i <= numVertices; ++i)
{
double t = PI * i / numVertices * 2;
double x = std::cos(t) * r;
double y = std::sin(t) * r;
glColor3f(1,0,0);
glVertex3d(x + cx, y + cy, z - w);
glColor3f(0,0,1);
glVertex3d(x + cx, y + cy, z + w);
}
glEnd();
}
void drawCone(const double h, const double r, const double cx, const double cy, const double cz = 0)
{
glBegin(GL_LINE_STRIP);
glColor3f(0,0,1);
//glVertex3d(cx, cy, cz);
glColor3f(1,0,0);
for (unsigned char i = 0; i <= numVertices; ++i)
{
double t = PI * i / numVertices * 2;
double x = std::cos(t) * r;
double z = std::sin(t) * r;
glVertex3d(x, h, z + cz);
}
glEnd();
}
// Drawing routine.
void drawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPolygonMode(GL_FRONT, isWire ? GL_LINE : GL_FILL);
glColor3f(1, 0, 0);
/*drawDisk(0, 0, 1, 50);
glColor3f(1, 1, 1);
drawDisk(0, 0, 1, 30);*/
//drawTorus(40, 0.4, 0, 0);
static unsigned angle = 0;
glEnable(GL_DEPTH_TEST); // Enable depth testing.
//drawRing(40, 10, std::cos(angle * PI / 180) * 70, std::sin(angle * PI / 180) * 70, -20);
drawCone(50, 20, std::cos(angle * PI / 180) * 70, std::sin(angle * PI / 180) * 70, -50);
angle = ++angle % 360;
glDisable(GL_DEPTH_TEST);
glFlush();
}
// Initialization routine.
void setup(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
}
// OpenGL window reshape routine.
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-100.0, 100.0, -100.0, 100.0, 5, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// Keyboard input processing routine.
void keyInput(unsigned char key, int x, int y)
{
switch(key)
{
case 27:
exit(0);
break;
case ' ':
isWire = !isWire;
glutPostRedisplay();
break;
case 'r':
glutPostRedisplay();
break;
case GLUT_KEY_UP:
break;
case GLUT_KEY_DOWN:
break;
case GLUT_KEY_LEFT:
break;
case GLUT_KEY_RIGHT:
break;
case '+':
if (numVertices + 1 < std::pow(2, sizeof(numVertices) * 8)) ++numVertices;
glutPostRedisplay();
break;
case '-':
if (numVertices > 3) --numVertices;
glutPostRedisplay();
break;
case '2':
glutPostRedisplay();
break;
default: break;
}
}
// Main routine.
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitContextVersion(4, 3);
glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Circular Parabola");
glutDisplayFunc(drawScene);
glutReshapeFunc(resize);
glutKeyboardFunc(keyInput);
glewExperimental = GL_TRUE;
glewInit();
setup();
glutMainLoop();
}
|
C++ | UTF-8 | 2,585 | 3.140625 | 3 | [
"BSL-1.0"
] | permissive | #pragma once
#include <pure/types/some.hpp>
namespace pure {
/**
Stable pointer to a value. The value is allocated on the heap via new and its lifetime is handled via an atomic
refcount. The underlying value can not be mutated, because it's not guranteed to not be accessed by other
threads concurrently.
@tparam O Type of the held value. Has to have Interface::Value as a base class.
@tparam Nil Either never_nil or maybe_nil to specify whether nullptr should be included in the domain of this type.
*/
template<typename O = Interface::Value, typename Nil = never_nil>
struct shared : some<O, Nil> {
using object_type = O;
static constexpr bool definitely_const_pointer = true;
shared (O* ptr) { this->init_ptr (Var::Tag::Shared, ptr); }
template<typename T>
shared (T&& other) {
static_assert (!definitely_disjunct_t<typename shared::domain_t, pure::domain_t<T>>::eval ());
switch (Var::tag_for<object_type> (other)) {
case Var::Tag::Nil : {
if constexpr (Nil::is_never_nil)
throw operation_not_supported ();
else
this->init_nil ();
}
return;
case Var::Tag::Unique :
if constexpr (detail::is_moveable<T&&>) {
this->init_ptr (Var::Tag::Shared, Var::release (other));
return;
}
case Var::Tag::Shared :
if constexpr (detail::is_moveable<T&&>) {
this->init_ptr (Var::Tag::Shared, Var::release (other));
return;
}
else {
this->init_ptr (Var::Tag::Shared, detail::inc_ref_count_and_get (*Var::obj (other)));
return;
}
default : this->init_ptr (Var::Tag::Shared, create<object_type> (std::forward<T> (other)));
return;
}
}
shared (const shared& other) : shared (static_cast<const shared&&> (other)) {}
~shared () {
switch (this->read_tag ()) {
case Var::Tag::Shared : detail::dec_ref_count_and_delete (this->operator* ());
break;
default : break;
}
this->init_nil ();
}
template<typename T>
const shared& operator= (T&& other) {
if ((void*) &other == (void*) this) return *this;
else {
this->~shared ();
this->init_nil ();
new (this) shared {std::forward<T> (other)};
return *this;
}
}
const shared& operator= (const shared& other) { return (*this = static_cast<const shared&&> (other)); }
Var::Tag tag () const noexcept {
if constexpr (Nil::is_never_nil) return Var::Tag::Shared;
else return this->read_tag();
}
};
template<typename T, typename... Args>
shared<T> make_shared (Args&& ... args) { return {create<T> (std::forward<Args> (args)...)}; };
}
|
Java | UTF-8 | 1,148 | 2.515625 | 3 | [] | no_license | import java.util.*;
import ngat.message.RCS_TCS.*;
import ngat.astrometry.*;
import ngat.util.*;
/** Implements the AUTOGUIDE command.*/
public class AUTOGUIDEImpl extends TCSCommandImpl {
String state;
public AUTOGUIDEImpl(StringTokenizer tokens, TCS_Status sdb) {
super(tokens, sdb);
}
/** Execute the command.*/
public boolean demand() {
// Args.
if (tokens.countTokens() < 1) {
fail(500001, "Missing args");
return false;
}
state = tokens.nextToken();
if ("ON".equals(state))
Subsystems.ag.acquire();
else if ("OFF".equals(state))
Subsystems.ag.stopGuiding();
else if ("FAIL".equals(state))
sdb.autoguider.agSwState = TCS_Status.STATE_FAILED;
else {
fail(500001, "Illegal state: ["+state+"]");
return false;
}
return true;
}
public boolean monitor() {
if ("OFF".equals(state)) {
if (sdb.autoguider.agStatus == TCS_Status.AG_UNLOCKED)
return true;
return false;
} else if
("ON".equals(state)) {
if (sdb.autoguider.agStatus == TCS_Status.AG_LOCKED)
return true;
return false;
}
return false;
}
}
|
C++ | UTF-8 | 1,221 | 2.921875 | 3 | [] | no_license | #include <PlainProtocol.h>
PlainProtocol mytest;
void setup() {
mytest.init();
Serial.begin(57600);
}
void loop() {
//Receive frame from serial. This function should be put in the loop and called periodically as following:
if (mytest.receiveFrame()) {
//if the received command is "speed", do the "speed" process.
if (mytest.receivedCommand=="speed") {
//the "speed" process
//the received command, the type is "Class String"
Serial.println(mytest.receivedCommand);
//the Lenth of received Content
Serial.println(mytest.receivedContentLenth);
for (int i=0; i<mytest.receivedContentLenth; i++) {
//the received content in an array
Serial.println(mytest.receivedContent[i]);
}
Serial.println();
}
else if (mytest.receivedCommand=="torque"){
//torque process
//the same as above
Serial.println(mytest.receivedCommand);
Serial.println(mytest.receivedContentLenth);
for (int i=0; i<mytest.receivedContentLenth; i++) {
Serial.println(mytest.receivedContent[i]);
}
Serial.println();
}
else{
//no matching command
Serial.println("command not available");
}
}
} |
C# | UTF-8 | 2,946 | 2.703125 | 3 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"CC0-1.0",
"BSD-2-Clause"
] | permissive | // ------------------------------------------------------------
// The code in this repository code was written by Lee Campbell, as a
// derived work from the original Java by Gil Tene of Azul Systems and
// Michael Barker, and released to the public domain, as explained
// at http://creativecommons.org/publicdomain/zero/1.0/
// ------------------------------------------------------------
// This file isn't generated, but this comment is necessary to exclude it from StyleCop analysis.
// <auto-generated/>
namespace HdrHistogram
{
/// <summary>
/// Provides methods to record values.
/// </summary>
internal interface IRecorder
{
/// <summary>
/// Records a value in the histogram
/// </summary>
/// <param name="value">The value to be recorded</param>
/// <exception cref="System.IndexOutOfRangeException">if value is exceeds highestTrackableValue</exception>
void RecordValue(long value);
/// <summary>
/// Record a value in the histogram (adding to the value's current count)
/// </summary>
/// <param name="value">The value to be recorded</param>
/// <param name="count">The number of occurrences of this value to record</param>
/// <exception cref="System.IndexOutOfRangeException">if value is exceeds highestTrackableValue</exception>
void RecordValueWithCount(long value, long count);
/// <summary>
/// Record a value in the histogram.
/// </summary>
/// <param name="value">The value to record</param>
/// <param name="expectedIntervalBetweenValueSamples">If <paramref name="expectedIntervalBetweenValueSamples"/> is larger than 0, add auto-generated value records as appropriate if <paramref name="value"/> is larger than <paramref name="expectedIntervalBetweenValueSamples"/></param>
/// <exception cref="System.IndexOutOfRangeException">if value is exceeds highestTrackableValue</exception>
/// <remarks>
/// To compensate for the loss of sampled values when a recorded value is larger than the expected interval between value samples,
/// Histogram will auto-generate an additional series of decreasingly-smaller (down to the expectedIntervalBetweenValueSamples) value records.
/// <para>
/// Note: This is a at-recording correction method, as opposed to the post-recording correction method provided by currently unimplemented <c>CopyCorrectedForCoordinatedOmission</c> method.
/// The two methods are mutually exclusive, and only one of the two should be be used on a given data set to correct for the same coordinated omission issue.
/// </para>
/// See notes in the description of the Histogram calls for an illustration of why this corrective behavior is important.
/// </remarks>
void RecordValueWithExpectedInterval(long value, long expectedIntervalBetweenValueSamples);
}
} |
Swift | UTF-8 | 306 | 2.59375 | 3 | [] | no_license | //
// AbstractFactory.swift
// AbstractFactory
//
// Created by Giuseppe Primo on 07/07/2017.
// Copyright © 2017 Giuseppe Primo. All rights reserved.
//
import Foundation
protocol AbstractFactory{
func getColor(color : String) -> ColorProtocol?
func getShape(shape : String) -> ShapeProtocol?
}
|
Ruby | UTF-8 | 3,289 | 3.0625 | 3 | [
"MIT"
] | permissive | #-- encoding: UTF-8
# For Ruby 1.9.3, 2.0.0
rv = RUBY_VERSION.split('.')[(0..1)].join('')
require 'string-scrub' if rv >= '19' && rv < '21'
module Nomener
# Module with helper functions to clean strings
#
# Currently exposes
# .reformat
# .cleanup!
# .dustoff
#
module Cleaner
# Allowable characters in a name after quotes have been reduced
@@allowable = nil
# regex for stuff at the end we want to get out
TRAILER_TRASH = /[,|\s]+$/
# regex for name characters we aren't going to use
DIRTY_STUFF = /[^,'\-(?:\p{Alpha}(?<\.))\p{Alpha}\p{Blank}]/
# Internal: Clean up a given string. Quotes from http://en.wikipedia.org/wiki/Quotation_mark
# Needs to be fixed up for matching and non-english quotes
#
# name - the string to clean
#
# Returns a string which is (ideally) pretty much the same as it was given.
def self.reformat(name)
@@allowable = %r![^\p{Alpha}\-&\/\ \.\,\'\"\(\)
#{Nomener.config.left}
#{Nomener.config.right}
#{Nomener.config.single}
] !x unless @@allowable
# remove illegal characters, translate fullwidth down
nomen = name.dup.scrub.tr("\uFF02\uFF07", "\u0022\u0027")
nomen = replace_doubles(nomen)
replace_singles(nomen)
.gsub(/@@allowable/, ' ')
.squeeze(' ')
.strip
end
# Internal: Clean up a string where there are numerous consecutive and
# trailing non-name characters.
# Modifies given string in place.
#
# args - strings to clean up
#
# Returns nothing
def self.cleanup!(*args)
args.each do |dirty|
next unless dirty.is_a?(String)
dirty.gsub! DIRTY_STUFF, ' '
dirty.squeeze! ' '
# remove any trailing commas or whitespace
dirty.gsub! TRAILER_TRASH, ''
dirty.strip!
end
end
# Internal: Replace various double quote characters with given char
#
# str - the string to find replacements in
#
# Returns the string with the quotes replaced
def self.replace_doubles(str)
left, right = [Nomener.config.left, Nomener.config.right]
# replace left and right double quotes
str.tr("\u0022\u00AB\u201C\u201E\u2036\u300E\u301D\u301F\uFE43", left)
.tr("\u0022\u00BB\u201D\u201F\u2033\u300F\u301E\uFE44", right)
end
private_class_method :replace_doubles
# Internal: Replace various single quote characters with given chars
#
# str - the string to find replacements in
#
# Returns the string with the quotes replaced
def self.replace_singles(str)
# replace left and right single quotes
str.tr("\u0027\u2018\u201A\u2035\u2039\u300C\uFE41\uFF62", Nomener.config.single)
.tr("\u0027\u2019\u201B\u2032\u203A\u300D\uFE42\uFF62", Nomener.config.single)
end
private_class_method :replace_singles
# Internal: Get the quotes from a string
# Currently unused. To Be Removed.
#
# str - the string of two characters for the left and right quotes
#
# Returns an array of the [left, right] quotes
def self.quotes_from(str = '""')
left, right = str.split(/\B/)
right = left unless right
[left, right]
end
private_class_method :quotes_from
end
end
|
Java | UTF-8 | 10,462 | 1.992188 | 2 | [] | no_license | // $Id: Id0920Process.java,v 1.1.1.1 2006/08/17 09:34:10 mori Exp $
package jp.co.daifuku.wms.idm.rft;
/*
* Copyright 2003-2005 DAIFUKU Co.,Ltd. All Rights Reserved.
*
* This software is the proprietary information of DAIFUKU Co.,Ltd.
* Use is subject to license terms.
*/
import java.io.IOException;
import java.sql.Connection;
import jp.co.daifuku.common.LogMessage;
import jp.co.daifuku.common.NotFoundException;
import jp.co.daifuku.common.ReadWriteException;
import jp.co.daifuku.wms.base.common.WmsParam;
import jp.co.daifuku.wms.base.communication.rft.PackageManager;
import jp.co.daifuku.wms.base.communication.rft.RftLogMessage;
import jp.co.daifuku.wms.base.rft.BaseOperate;
import jp.co.daifuku.wms.base.rft.IdProcess;
import jp.co.daifuku.wms.base.rft.SystemParameter;
/**
* <FONT COLOR="BLUE">
* Designer : C.Kaminishizono <BR>
* Maker : C.Kaminishizono <BR>
* <BR>
* RFTからの移動ラック空棚データ要求に対する処理を行います。
* Id0920Operateクラスの提供する機能を使用し、ロケーション管理情報から対象となる棚Noデータを検索します。
* RFTに送信する応答電文を生成します。 <BR>
* <BR>
* 移動ラック空棚データ要求処理(<CODE>processReceivedId()</CODE>メソッド) <BR>
* <BR>
* <DIR>
* 受信データから、必要な情報を取得します。 <BR>
* Id0920Operateクラスの機能でロケーション管理情報を検索し、対象となる棚Noデータを取得します。 <BR>
* 送信電文を作成し、送信バッファに送信するテキストをセットします。<BR>
* ロケーション管理情報より移動ラック空棚一覧ファイルを作成します。
* </DIR>
* </FONT>
* <BR>
* <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0">
* <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"><TD>Date</TD><TD>Name</TD><TD>Comment</TD></TR>
* <TR><TD>2005/04/05</TD><TD>C.Kaminishizono</TD><TD>created this class</TD></TR>
* </TABLE>
* <BR>
* @version $Revision: 1.1.1.1 $, $Date: 2006/08/17 09:34:10 $
* @author $Author: mori $
*/
public class Id0920Process extends IdProcess
{
// Class fields----------------------------------------------------
/**
* クラス名
*/
private static final String CLASS_NAME = "Id0920Process";
// Class variables -----------------------------------------------
// Class method --------------------------------------------------
/**
* このクラスのバージョンを返します
* @return バージョンと日付
*/
public static String getVersion()
{
return ("$Revision: 1.1.1.1 $,$Date: 2006/08/17 09:34:10 $");
}
// Constructors --------------------------------------------------
/**
* インスタンスを生成します。
*/
public Id0920Process()
{
super();
}
/**
* DBConnection情報をコンストラクタに渡します。
* @param conn DBConnection情報
*/
public Id0920Process(Connection conn)
{
super();
wConn = conn;
}
// Public methods ------------------------------------------------
/**
* 移動ラック空棚データ要求処理(ID0920)を行います。 <BR>
* 受信した電文をバイト列で受け取り、それに対する応答(ID5920)をバイト列で作成します。 <BR>
* <BR>
* 日次処理中で無いことを確認します。
* 日次処理中の場合は、5:日次処理中のエラーを返します。 <BR>
* ID0920Operateクラスを利用し、要求のあった条件でロケーション管理情報を検索します。<BR>
* 対象となる棚が複数件該当した時には、移動ラック空棚一覧ファイルを作成し、応答フラグに0:正常をセットします。<BR>
* 対象となる棚が無い時は、応答フラグに「8:該当データ無し」をセットします。<BR>
* 送信電文を作成し、送信バッファに送信するテキストをセットします。<BR>
* <BR>
* @param rdt 受信バッファ
* @param sdt 送信バッファ
* @throws Exception 全ての例外を報告します。
*/
public void processReceivedId(byte[] rdt, byte[] sdt) throws Exception
{
RFTId0920 rftId0920 = null;
RFTId5920 rftId5920 = null;
try
{
// 受信電文解析用のインスタンスを生成
rftId0920 = (RFTId0920) PackageManager.getObject("RFTId0920");
rftId0920.setReceiveMessage(rdt);
// 送信電文作成用のインスタンスを生成
rftId5920 = (RFTId5920) PackageManager.getObject("RFTId5920");
}
catch (IllegalAccessException e)
{
RftLogMessage.print(6006003, LogMessage.F_ERROR, CLASS_NAME,e.getMessage());
throw e;
}
// 受信電文からRFT号機を取得
String rftNo = rftId0920.getRftNo();
// 受信電文から作業者コードを取得
String workerCode = rftId0920.getWorkerCode();
// 受信電文から荷主コードを取得
String consignorCode = rftId0920.getConsignorCode();
// 商品コードを保持する変数
String itemCode = rftId0920.getItemCode();
// ケース・ピース区分を保持する変数
String casePieceFlag = rftId0920.getCasePieceFlag();
// エリアNOを保持する変数
String areaNo = rftId0920.getAreaNo();
// 空棚区分を保持する変数
String emptyKind = rftId0920.getEmptyKind();
// 応答フラグを保持する変数
String ansCode = RFTId5920.ANS_CODE_NORMAL;
// エラー詳細を保持する変数
String errDetails = RFTId5920.ErrorDetails.NORMAL;
// ファイル名を作成
String sendpath = WmsParam.RFTSEND; // wms/rft/send/
// 送信ファイル名
String sendFileName = sendpath + rftNo + "\\" + Id5920DataFile.ANS_FILE_NAME;
String className = "";
String[] locate = null;
// ファイルに書き込んだ行数を保持する変数 2006/6/14 滝
int recCounter = 0;
try
{
// BaseOperateのインスタンスを生成
BaseOperate baseOperate = (BaseOperate) PackageManager.getObject("BaseOperate");
baseOperate.setConnection(wConn);
//-----------------
// 日次処理中チェック
//-----------------
if (baseOperate.isLoadingDailyUpdate())
{
// 状態フラグを 5:日次更新処理中 でリターン
ansCode = RFTId5920.ANS_CODE_DAILY_UPDATING;
}
else
{
// Id0920Operateのインスタンスを生成
Id0920Operate id0920Operate = (Id0920Operate)PackageManager.getObject("Id0920Operate");
id0920Operate.setConnection(wConn);
//ロケーション情報を検索、取得します。
// 空棚区分にて検索処理の振分けを行います。
if (emptyKind.equals(RFTId0920.EMPTY_KIND_EMPTY))
{
// 空棚要求
locate = id0920Operate.getLocateData();
}
else if (emptyKind.equals(RFTId0920.EMPTY_KIND_REPLENISH))
{
String wCasepieceFlag = "";
if (!casePieceFlag.equals(RFTId0920.CASE_PIECE_All))
{
wCasepieceFlag = casePieceFlag;
}
// 補充棚要求
locate = id0920Operate.getStockData(
consignorCode,
itemCode,
wCasepieceFlag);
}
// データが見つからない場合
if (locate == null || locate.length == 0)
{
throw (new NotFoundException());
}
className = "Id5920DataFile";
Id5920DataFile dataFile = (Id5920DataFile) PackageManager.getObject(className);
dataFile.setFileName(sendFileName);
recCounter = dataFile.write(locate,SystemParameter.FTP_FILE_MAX_RECORD);
}
}
// stockOperateのインスタンスから情報を取得できなかった場合はエラー
catch (NotFoundException e)
{
// 応答フラグ:該当データなし
ansCode = RFTId5920.ANS_CODE_NULL;
}
// その他のエラーがあった場合
catch (ReadWriteException e)
{
// 6006002=データベースエラーが発生しました。{0}
RftLogMessage.printStackTrace(6006002, LogMessage.F_ERROR, CLASS_NAME, e);
// 応答フラグ:エラー
ansCode = RFTId5920.ANS_CODE_ERROR;
errDetails = RFTId5920.ErrorDetails.DB_ACCESS_ERROR;
}
catch (IllegalAccessException e) {
// インスタンス生成に失敗
RftLogMessage.printStackTrace(6026015, LogMessage.F_ERROR, CLASS_NAME, e);
// 応答フラグ:エラー
ansCode = RFTId5920.ANS_CODE_ERROR;
errDetails = RFTId5920.ErrorDetails.INSTACIATE_ERROR;
}
catch (IOException e)
{
// 6006020 = ファイルの入出力エラーが発生しました。{0}
RftLogMessage.print(6006020, LogMessage.F_ERROR, CLASS_NAME, sendFileName);
// 応答フラグ:エラー
ansCode = RFTId5920.ANS_CODE_ERROR ;
errDetails = RFTId5920.ErrorDetails.I_O_ERROR;
}
catch (Exception e)
{
// 6026015=ID対応処理で異常が発生しました。{0}
RftLogMessage.printStackTrace(6026015, LogMessage.F_ERROR, CLASS_NAME, e);
// 応答フラグ:エラー
ansCode = RFTId5920.ANS_CODE_ERROR;
errDetails = RFTId5920.ErrorDetails.INTERNAL_ERROR;
}
// 応答電文の作成
// STX
rftId5920.setSTX();
// SEQ
rftId5920.setSEQ(0);
// ID
rftId5920.setID(RFTId5920.ID);
// RFT送信時間
rftId5920.setRftSendDate(rftId0920.getRftSendDate());
// SERVER送信時間
rftId5920.setServSendDate();
// RFT号機
rftId5920.setRftNo(rftNo);
// 担当者コード
rftId5920.setWorkerCode(workerCode);
// 荷主コード
rftId5920.setConsignorCode(consignorCode);
// 商品コードをセット
rftId5920.setItemCode(itemCode);
// ケース・ピース区分をセット
rftId5920.setCasePieceFlag(casePieceFlag);
// エリアNOをセット
rftId5920.setAreaNo (areaNo);
// 空棚区分をセット
rftId5920.setEmptyKind(emptyKind);
// 一覧ファイル名をセット
rftId5920.setAnsFileName(sendFileName);
// ファイルレコード数をセット
if (ansCode.equals(RFTId5920.ANS_CODE_NORMAL))
{
rftId5920.setFileRecordNumber(recCounter);
}
else
{
rftId5920.setFileRecordNumber(0);
}
// 応答フラグ
rftId5920.setAnsCode(ansCode);
// エラー詳細
rftId5920.setErrDetails(errDetails);
// ETX
rftId5920.setETX();
// 応答電文を獲得する。
rftId5920.getSendMessage(sdt);
}
// Package methods -----------------------------------------------
// Protected methods ---------------------------------------------
// Private methods -----------------------------------------------
}
//end of class
|
Python | UTF-8 | 1,793 | 3.015625 | 3 | [] | no_license | #!/usr/bin/python
#coding=utf-8
class OutputFormatter:
def __init__(self):
pass
def printHeader(self, description):
print '--------------- Result Header ---------------'
def printFooter(self, description):
print '\r--------------- Result Footer ---------------'
def printResult(self, job):
if(job._error != None):
print '\t', job._description, 'error: ', job._error
else:
print '\t' , job._description , 'done'
#为二阶扫描提供输入
class OutputFormatterNext(OutputFormatter):
def __init__(self):
OutputFormatter.__init__(self)
#输出到终端
class OutputFormatterConsole(OutputFormatter):
def __init__(self):
OutputFormatter.__init__(self)
#输出到文件
class OutputFormatterFile(OutputFormatter):
def __init__(self):
OutputFormatter.__init__(self)
self._fileName = None
self._fileHandle = None
self._fileExt = '.txt'
#打开文件文件
#保存的文件名为description + 系统当前日期
def printHeader(self, description):
try:
import time
current_time = time.strftime('_%Y_%m_%d_%H_%M_%S',time.localtime(time.time()))
self._fileName = description + current_time + self._fileExt
self._fileHandle = open(self._fileName, 'w')
except Exception as e:
print __file__, e
raise e
#关闭文件
def printFooter(self, description):
#必须成功执行到printFooter才能释放fileHandle,有潜在的资源泄漏风险
if self._fileHandle != None:
print 'Scaner report: %s' % (self._fileName)
self._fileHandle.close()
#执行写入
def printResult(self, job):
pass
|
Markdown | UTF-8 | 2,584 | 2.6875 | 3 | [
"MIT"
] | permissive | # Send Event Sample
Sample application that uses the Azure IoT Dotnet SDK to send telemetry messages to the
Azure IoT Hub cloud service or to an Azure IoT Edge device. The sample demonstrates how to connect
and send messages using a protocol of your choices as a parameter.
## Build the sample
As a prerequisite you will need the [DotNet Core SDK](https://docs.microsoft.com/dotnet/core/sdk) installed on your dev box. To build the sample, copy the contents of this directory on your dev box and follow the instructions below.
```
$> cd EdgeDownstreamDevice
$> dotnet build
```
## Run the sample
Before running the sample, edit the file Properties/launchSettings.json and add the connection string and CA certificate
### Configuration Description
* Connection String:
* IoT Edge connection string:
```
HostName=your-hub.azure-devices.net;DeviceId=yourDevice;SharedAccessKey=XXXYYYZZZ=;GatewayHostName=mygateway.contoso.com
```
* Just for reference, here is the IoT Hub connection string format:
```
HostName=your-hub.azure-devices.net;DeviceId=yourDevice;SharedAccessKey=XXXYYYZZZ=;
```
* Number of messages to send - Expressed in decimal
* Path to trusted CA certificate: For the Edge Hub, if the CA is not a public root, a path to the root CA certificate in PEM format is absolutely required. This is optional if the root certificate is installed in the trusted certificate store of the OS.
### Execute Sample
```
$> dotnet run
```
## Verify output
If everything was correctly provided via the CLI arguments, the following should be observed on stdout
```
Edge downstream device attempting to send 10 messages to Edge Hub...
9/27/2018 3:25:57 PM> Sending message: 0, Data: [{MyFirstDownstreamDevice "messageId":0,"temperature":34,"humidity":75}]
9/27/2018 3:26:05 PM> Sending message: 1, Data: [{MyFirstDownstreamDevice "messageId":1,"temperature":24,"humidity":76}]
9/27/2018 3:26:05 PM> Sending message: 2, Data: [{MyFirstDownstreamDevice "messageId":2,"temperature":33,"humidity":64}]
9/27/2018 3:26:05 PM> Sending message: 3, Data: [{MyFirstDownstreamDevice "messageId":3,"temperature":34,"humidity":74}]
9/27/2018 3:26:05 PM> Sending message: 4, Data: [{MyFirstDownstreamDevice "messageId":4,"temperature":31,"humidity":64}]
9/27/2018 3:26:05 PM> Sending message: 5, Data: [{MyFirstDownstreamDevice "messageId":5,"temperature":28,"humidity":76}]
9/27/2018 3:26:05 PM> Sending message: 6, Data: [{MyFirstDownstreamDevice "messageId":6,"temperature":31,"humidity":62}]
...
```
|
Go | UTF-8 | 4,282 | 3.09375 | 3 | [
"ISC"
] | permissive | package mux
import (
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
var (
_ Router = &tree{}
_ Builder = &tree{}
_ Walker = &tree{}
)
func TestTreeAddDuplicateName(t *testing.T) {
r1 := NewRoute("/foo", nil, WithName("test"))
r2 := NewRoute("/bar", nil, WithName("test"))
tree := &tree{}
err := tree.Add(r1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = tree.Add(r2)
if err == nil {
t.Fatalf("should not add duplicate named route")
}
}
func TestTreeAddDuplicateNodeParam(t *testing.T) {
r1 := NewRoute("/:foo", nil)
r2 := NewRoute("/:bar", nil)
tree := &tree{}
err := tree.Add(r1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = tree.Add(r2)
if err == nil {
t.Fatalf("should not add duplicate param route")
}
}
func TestTreeBuild(t *testing.T) {
var tests = []struct {
name string
pattern string
params Params
want string
}{
{"index", "/", nil, "/"},
{"param", "/posts/:slug", Params{"slug": "test"}, "/posts/test"},
{"wildcard", "/files/*", Params{"*": "path/to/file.txt"}, "/files/path/to/file.txt"},
{"param+param", "/:a/:b", Params{"a": "a", "b": "b"}, "/a/b"},
{"param+wildcard", "/:a/:b/*", Params{"a": "a", "b": "b", "*": "c/d"}, "/a/b/c/d"},
}
tree := &tree{}
for _, tt := range tests {
r := NewRoute(tt.pattern, nil, WithName(tt.name))
err := tree.Add(r)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
for _, tt := range tests {
have, err := tree.Build(tt.name, tt.params)
if err != nil {
t.Fatalf("unexpected error: %v\n for '%s'", err, tt.name)
}
if have != tt.want {
t.Fatalf("Build\npattern '%s'\nparams %#v\nhave '%s'\nwant '%s'", tt.pattern, tt.params, have, tt.want)
}
}
}
func TestTreeBuildNilWildcard(t *testing.T) {
tree := &tree{}
r := NewRoute("/*", nil, WithName("index"))
err := tree.Add(r)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = tree.Build("index", nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestTreeMatch(t *testing.T) {
var tests = []struct {
pattern string
path string
params Params
}{
{"/romane", "/romane", nil},
{"/romanus", "/romanus", nil},
{"/romulus", "/romulus", nil},
{"/rubens", "/rubens", nil},
{"/ruber", "/ruber", nil},
{"/rubicon", "/rubicon", nil},
{"/rubicundus", "/rubicundus", nil},
{"/s", "/s", nil},
{"/s/a/", "/s/a/", nil},
{"/s/a/b", "/s/a/b", nil},
{"/p/:a", "/p/a", Params{"a": "a"}},
{"/p/:a/", "/p/a/", Params{"a": "a"}},
{"/p/:a/z", "/p/a/z", Params{"a": "a"}},
{"/p/:a/:b", "/p/a/b", Params{"a": "a", "b": "b"}},
{"/p/:a/*", "/p/a/b/c", Params{"a": "a", "*": "b/c"}},
{"/", "/", nil},
}
tree := &tree{}
for _, tt := range tests {
r := NewRoute(tt.pattern, nil)
err := tree.Add(r)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
for _, tt := range tests {
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
r, params, err := tree.Match(req)
if err != nil {
t.Fatalf("unexpected error: %v\n for '%s'", err, tt.path)
}
have := r.Pattern()
if have != tt.pattern {
t.Fatalf("Match\npath '%s'\nparams %#v\nhave '%s'\nwant '%s'", tt.path, params, have, tt.pattern)
}
}
}
func TestTreeMatchNotFound(t *testing.T) {
r := NewRoute("/romulus", nil)
tree := &tree{}
err := tree.Add(r)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/remus", nil)
_, _, err = tree.Match(req)
if err != ErrNotFound {
t.Fatalf("unexpected error: %v", err)
}
}
func TestTreeWalk(t *testing.T) {
patterns := []string{"/rubicon", "/ruber", "/rubicundus", "/romanus", "/romane", "/romulus", "/rubens"}
tree := &tree{}
for _, pattern := range patterns {
r := NewRoute(pattern, nil, WithName(pattern))
err := tree.Add(r)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
have := make([]string, 0)
want := []string{"/romane", "/romanus", "/romulus", "/rubens", "/ruber", "/rubicon", "/rubicundus"}
fn := func(r *Route) error {
name := r.Name()
have = append(have, name)
return nil
}
err := tree.Walk(fn)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(have, want) {
t.Fatalf("Walk\nhave %v\nwant %v", have, want)
}
}
|
Python | UTF-8 | 1,390 | 2.84375 | 3 | [] | no_license | #!/urs/bin/env python
# -*- coding:utf-8 -*-
data ={
'北京':{
'海淀区':{
'颐和园', '圆明园遗址公园', '旧土城遗址公园', '大钟寺'
},
'东城区':{
'劳动人民文化宫', '老舍纪念馆', '柳荫公园', '青年湖公园'
},
},
'浙江':{
'杭州':{
'西湖', '西溪湿地', '宋城', '钱塘江', '南宋御街',
},
'绍兴':{
'柯岩风景区、大禹陵、东湖、鲁迅故里',
},
},
'山东':{
'济南':{
'趵突泉 大明湖 千佛山 芙蓉街(小吃街)',
},
'青岛':{
'栈桥,小鱼山,海底世界,第一海水浴场,八大关风景区, 花石楼',
},
},
}
flag = True
while flag:
for i in data:
print(i)
choose1 = input(">")
if choose1 == "q":
flag = False
while flag:
for j in data[choose1]:
print("\t", j)
choose2 = input(">>")
if choose2 == 'b':
break
elif choose2 == 'q':
flag = False
while flag:
for k in data[choose1][choose2]:
print("\t\t",k)
choose3 = input(">>>")
if choose3 == 'b':
break
elif choose3 == 'q':
flag = False |
Java | UTF-8 | 5,290 | 1.84375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.pelindo.ebtos.bean;
import com.qtasnim.jsf.FacesHelper;
import com.pelindo.ebtos.ejb.facade.remote.MasterUtilisasiAlatFacadeRemote;
import com.pelindo.ebtos.ejb.facade.remote.MasterEquipmentFacadeRemote;
import com.pelindo.ebtos.model.db.master.MasterUtilisasiAlat;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.primefaces.context.RequestContext;
/**
*
* @author wulan
*/
@ManagedBean(name = "masterUtilisasiAlatBean")
@ViewScoped
public class MasterUtilisasiAlatBean implements Serializable {
private List<Object[]> utilisasiAlatList;
private MasterUtilisasiAlat masterUtilisasiAlat;
private List<Object[]> equipmentList;
/** Creates a new instance of MasterUtilisasiAlat */
public MasterUtilisasiAlatBean() {
utilisasiAlatList = lookupMasterUtilisasiAlatFacadeRemote().findAllUtilisasiAlat();
equipmentList = lookupMasterEquipmentFacadeRemote().findAllNative();
masterUtilisasiAlat = new MasterUtilisasiAlat();
}
public void handleAdd(ActionEvent event){
masterUtilisasiAlat=new MasterUtilisasiAlat();
}
public void handleDelete(ActionEvent event){
try {
lookupMasterUtilisasiAlatFacadeRemote().remove(masterUtilisasiAlat);
utilisasiAlatList = lookupMasterUtilisasiAlatFacadeRemote().findAllUtilisasiAlat();
FacesHelper.addFacesMessage(FacesContext.getCurrentInstance(), FacesMessage.SEVERITY_INFO, "Info", "application.delete.succeeded");
} catch (EJBException e) {
e.printStackTrace();
FacesHelper.addFacesMessage(FacesContext.getCurrentInstance(), FacesMessage.SEVERITY_INFO, "Info", "application.delete.failed");
}
}
public void handleSubmitEdit(ActionEvent event) {
RequestContext context = RequestContext.getCurrentInstance();
boolean loggedIn = false;
try {
loggedIn=true;
masterUtilisasiAlat.setTotal(masterUtilisasiAlat.getAccident().add(masterUtilisasiAlat.getBreakDown().add(masterUtilisasiAlat.getRepair().add(masterUtilisasiAlat.getWaiting().add(masterUtilisasiAlat.getMaintenance())))));
lookupMasterUtilisasiAlatFacadeRemote().edit(masterUtilisasiAlat);
utilisasiAlatList = lookupMasterUtilisasiAlatFacadeRemote().findAllUtilisasiAlat();
masterUtilisasiAlat=new MasterUtilisasiAlat();
FacesHelper.addFacesMessage(FacesContext.getCurrentInstance(), FacesMessage.SEVERITY_INFO, "Info", "application.save.succeeded");
} catch (EJBException e) {
e.printStackTrace();
FacesHelper.addFacesMessage(FacesContext.getCurrentInstance(), FacesMessage.SEVERITY_INFO, "Info", "application.save.failed");
}
context.addCallbackParam("loggedIn", loggedIn);
}
public void handleEdit(ActionEvent event) {
Integer id = (Integer) event.getComponent().getAttributes().get("idAlat");
System.out.println(id);
masterUtilisasiAlat = lookupMasterUtilisasiAlatFacadeRemote().find(id);
}
public List<Object[]> getEquipmentList() {
return equipmentList;
}
public void setEquipmentList(List<Object[]> equipmentList) {
this.equipmentList = equipmentList;
}
public MasterUtilisasiAlat getMasterUtilisasiAlat() {
return masterUtilisasiAlat;
}
public void setMasterUtilisasiAlat(MasterUtilisasiAlat masterUtilisasiAlat) {
this.masterUtilisasiAlat = masterUtilisasiAlat;
}
public List<Object[]> getUtilisasiAlatList() {
return utilisasiAlatList;
}
public void setUtilisasiAlatList(List<Object[]> utilisasiAlatList) {
this.utilisasiAlatList = utilisasiAlatList;
}
private MasterUtilisasiAlatFacadeRemote lookupMasterUtilisasiAlatFacadeRemote() {
try {
Context c = new InitialContext();
return (MasterUtilisasiAlatFacadeRemote) c.lookup("java:global/pkproject/pk-ejb/MasterUtilisasiAlatFacade!com.pelindo.ebtos.ejb.facade.remote.MasterUtilisasiAlatFacadeRemote");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
private MasterEquipmentFacadeRemote lookupMasterEquipmentFacadeRemote() {
try {
Context c = new InitialContext();
return (MasterEquipmentFacadeRemote) c.lookup("java:global/pkproject/pk-ejb/MasterEquipmentFacade!com.pelindo.ebtos.ejb.facade.remote.MasterEquipmentFacadeRemote");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
|
SQL | UTF-8 | 1,729 | 4.03125 | 4 | [] | no_license | CREATE TABLE PROFESSOR
(
MID CHAR(9) PRIMARY KEY,
NAME VARCHAR(30),
TITLE VARCHAR(20) CHECK (TITLE IN ('ASSISTANT', 'ASSOCIATE', 'FULL', 'ADJUNCT', 'INSTRUCTOR')),
DNO INT
);
CREATE TABLE DEPT
(
DNO INT PRIMARY KEY,
DNAME VARCHAR(30)
);
CREATE TABLE STUDENT
(
MID CHAR(9) PRIMARY KEY,
NAME VARCHAR(30),
MAJOR VARCHAR(30)
);
ALTER TABLE PROFESSOR
ADD CONSTRAINT DNO_REFERENCE FOREIGN KEY(DNO) REFERENCES DEPT(DNO);
ALTER TABLE PROFESSOR
DROP CONSTRAINT DNO_REFERENCE;
ALTER TABLE PROFESSOR
ALTER COLUMN DNO INT NOT NULL
ALTER TABLE PROFESSOR
ADD FOREIGN KEY(DNO) REFERENCES DEPT(DNO);
ALTER TABLE PROFESSOR
ADD SALARY NUMERIC(10,2) DEFAULT 0;
ALTER TABLE PROFESSOR
ALTER COLUMN NAME VARCHAR(30) NOT NULL;
ALTER TABLE PROFESSOR
ADD DEFAULT 'UNKNOWN' FOR NAME;
INSERT INTO DEPT VALUES(1, 'Computer Science');
INSERT INTO DEPT VALUES(2, 'Chemistry');
INSERT INTO DEPT VALUES(3, 'Physics');
INSERT INTO DEPT VALUES(4, 'Mathematics');
INSERT INTO PROFESSOR(MID, TITLE, DNO)
VALUES( '123456789', 'ASSISTANT', 1);
INSERT INTO PROFESSOR
VALUES( '987654321', DEFAULT, 'INSTRUCTOR', 2, DEFAULT);
INSERT INTO STUDENT
SELECT SSN, CONCAT(CONCAT(LNAME, ', '), FNAME), 'UNKNOWN'
FROM EMPLOYEE;
UPDATE PROFESSOR
SET NAME='Zhijiang Dong'
WHERE MID='123456789';
UPDATE PROFESSOR
SET NAME='Fake Name', SALARY=15000.00
WHERE MID='987654321';
UPDATE PROFESSOR
SET SALARY = SALARY * 1.2;
UPDATE STUDENT
SET MAJOR = 'Computer Science'
WHERE MID LIKE '9%';
UPDATE STUDENT
SET MAJOR = 'Mathematics'
WHERE MAJOR='UNKNOWN';
|
Java | UTF-8 | 4,538 | 2.359375 | 2 | [] | no_license | package com.hbsd.rjxy.miaomiao.zsh.setting.model;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.hbsd.rjxy.miaomiao.R;
import java.util.List;
import java.util.Map;
public class AddItemAdapter extends BaseAdapter {
private List<Map<String,Object>> dataSource=null;
private Context context=null;
private int item_layout_id;
public AddItemAdapter(Context context,
List<Map<String, Object>> dataSource,
int item_layout_id) {
this.context = context;
this.dataSource = dataSource;
this.item_layout_id = item_layout_id;
}
/**
* How many items are in the data set represented by this Adapter.
*
* @return Count of items.
*/
@Override
public int getCount() {
if(dataSource==null){
return 0;
}
else{
return dataSource.size();
}
}
/**
* Get the data item associated with the specified position in the data set.
*
* @param position Position of the item whose data we want within the adapter's
* data set.
* @return The data at the specified position.
*/
@Override
public Object getItem(int position) {
return dataSource.get(position);
}
/**
* Get the row id associated with the specified position in the list.
*
* @param position The position of the item within the adapter's data set whose row id we want.
* @return The id of the item at the specified position.
*/
@Override
public long getItemId(int position) {
return position;
}
/**
* Get a View that displays the data at the specified position in the data set. You can either
* create a View manually or inflate it from an XML layout file. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=LayoutInflater.from(context);
View newView=inflater.inflate(item_layout_id,null);
TextView txTitle=newView.findViewById(R.id.self_title);
ImageView imageView=newView.findViewById(R.id.self_img);
Map<String,Object> map=dataSource.get(position);
final String title=map.get("title").toString();
txTitle.setText(title);
Resources res=context.getResources();
switch (position){
case 0:{
Drawable img=res.getDrawable(R.drawable.self_mp);
imageView.setImageDrawable(img);
break;
}
case 1:{
Drawable img=res.getDrawable(R.drawable.self_dy);
imageView.setImageDrawable(img);
break;
}
case 2:{
Drawable img=res.getDrawable(R.drawable.self_xg);
imageView.setImageDrawable(img);
break;
}
case 3:{
Drawable img=res.getDrawable(R.drawable.self_cx);
imageView.setImageDrawable(img);
break;
}
}
return newView;
}
}
|
Java | UTF-8 | 3,092 | 2.265625 | 2 | [] | no_license | package com.ibank.bean;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* Overdraft entity. @author MyEclipse Persistence Tools
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "overdraft", catalog = "ibank")
public class Overdraft implements java.io.Serializable {
// Fields
private Integer id;
private Interest interest;
private Account account;
private Timestamp begintime;
private Timestamp endtime;
private Double draftmoney;
private Double refundmoney;
private Integer freedays;
private Integer status;
// Constructors
/** default constructor */
public Overdraft() {
}
/** full constructor */
public Overdraft(Integer id, Interest interest, Account account,
Timestamp begintime, Timestamp endtime, Double draftmoney,
Double refundmoney, Integer freedays, Integer status) {
this.id = id;
this.interest = interest;
this.account = account;
this.begintime = begintime;
this.endtime = endtime;
this.draftmoney = draftmoney;
this.refundmoney = refundmoney;
this.freedays = freedays;
this.status = status;
}
// Property accessors
@Id
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "overinterestid", nullable = false)
public Interest getInterest() {
return this.interest;
}
public void setInterest(Interest interest) {
this.interest = interest;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "accid", nullable = false)
public Account getAccount() {
return this.account;
}
public void setAccount(Account account) {
this.account = account;
}
@Column(name = "begintime", nullable = false, length = 19)
public Timestamp getBegintime() {
return this.begintime;
}
public void setBegintime(Timestamp begintime) {
this.begintime = begintime;
}
@Column(name = "endtime", nullable = false, length = 19)
public Timestamp getEndtime() {
return this.endtime;
}
public void setEndtime(Timestamp endtime) {
this.endtime = endtime;
}
@Column(name = "draftmoney", nullable = false, precision = 10)
public Double getDraftmoney() {
return this.draftmoney;
}
public void setDraftmoney(Double draftmoney) {
this.draftmoney = draftmoney;
}
@Column(name = "refundmoney", nullable = false, precision = 10)
public Double getRefundmoney() {
return this.refundmoney;
}
public void setRefundmoney(Double refundmoney) {
this.refundmoney = refundmoney;
}
@Column(name = "freedays", nullable = false)
public Integer getFreedays() {
return this.freedays;
}
public void setFreedays(Integer freedays) {
this.freedays = freedays;
}
@Column(name = "status", nullable = false)
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
} |
JavaScript | UTF-8 | 2,017 | 3.046875 | 3 | [] | no_license | $(document).ready(function() {
$('.store-button').on('click', function(event) {
let titleValue = $('.input-title-field').val();
let titleBox = $(`<div class="snippet-title">${titleValue}</div>`).delay(120000).fadeOut(3000);
if (titleValue === "") {
alert("Enter a valid file name");
return false;
}
localStorage.setItem(`${titleValue}`, editor.getValue());
titleBox.appendTo('.snippet-box');
});
$('.snippet-box').on('click', function() {
let snippetTitle = $('.snippet-title').html();
console.log(snippetTitle);
let titleValue = $('.input-title-field').val();
for (var x = 0; x < localStorage.length; x++) {
if (snippetTitle === localStorage.key(x)) {
var newCode = localStorage.getItem(`${localStorage.key(x)}`);
editor.setValue(newCode);
}
}
});
$('.get-button').on('click', function(event) {
let titleValue = $('.input-title-field').val();
let titleBox = $(`<div class="snippet-title">${titleValue}</div>`).delay(120000).fadeOut(10000);
for (var x = 0; x < localStorage.length; x++) {
if (titleValue === localStorage.key(x)) {
var newCode = localStorage.getItem(`${localStorage.key(x)}`);
editor.setValue(newCode);
}
}
titleBox.appendTo('.snippet-box');
});
$('.delete-button').on('click', function(event) {
let titleValue = $('.input-title-field').val();
let snippetTitle = $('.snippet-box').html();
let snippetsDiv = $('.snippet-box');
let result = confirm("Are you sure you want to delete this code?");
if (result) {
for (var x = 0; x < localStorage.length; x++) {
if (titleValue === localStorage.key(x)) {
localStorage.removeItem(localStorage.key(x));
}
}
}
});
$('.run-button').on('click', function(event) {
let code = editor.getValue();
let titleValue = $('.input-title-field').val();
let titleBox = $(`<div class="snippet-title">${titleValue}</div>`).delay(120000).fadeOut(3000);
titleBox.appendTo('.snippet-box');
console.log(eval(code));
});
}); |
Java | UTF-8 | 2,443 | 3.671875 | 4 | [
"MIT"
] | permissive | package Assigments7;
import java.util.HashMap;
import java.util.Scanner;
public class Practice3 {
public static void main(String[] args) {
HashMap<Integer, String> studentList = new HashMap<Integer, String>();
studentList.put(101, "Karthi");
studentList.put(102, "Jose");
studentList.put(103, "Jothi");
studentList.put(104, "David");
studentList.put(105, "Maki");
System.out.println(studentList);
Scanner in = new Scanner(System.in);
int stu_id;
String stu_name;
int m1, m2, md1, md2;
try {
System.out.println("******************************************");
System.out.println("Let’s check the user Get access or not");
System.out.println("******************************************");
System.out.print("Enter Student ID: ");
stu_id = in.nextInt();
System.out.print("Enter Student Name: ");
stu_name = in.next();
if (!studentList.containsKey(stu_id) && !studentList.containsKey(stu_name)) {
throw new CustomEx1("You don’t have access to use the application");
} else {
throw new CustomEx1("Access provided");
}
} catch (CustomEx1 e) {
System.out.println(e);
}
try {
System.out.print("Enter Mark 1: ");
m1 = in.nextInt();
System.out.print("Enter Mark 2: ");
m2 = in.nextInt();
int total1 = m1 + m2;
System.out.println("Total Mark: " + total1);
System.out.println("Enter value for divide marks: ");
System.out.print("Mark 1: ");
md1 = in.nextInt();
System.out.print("Mark 2: ");
md2 = in.nextInt();
int total2 = m1 / m2;
if (total2 == 0) {
System.out.println("M1: " + md1 + "\n" + "M2: " + md2);
throw new NumberFormatException("Divide by Zero Not possible!\n");
} else {
System.out.println("Hey! you made it, BOIII.");
}
} catch (NumberFormatException n) {
System.out.println(n);
}
}
}
class CustomEx1 extends Exception {
String message;
CustomEx1(String msg) {
this.message = msg;
}
public String toString() {
return (message);
}
}
|
Ruby | UTF-8 | 184 | 3.359375 | 3 | [] | no_license | def count_to_zero(number)
if number <= 0
puts "Zero already"
else
puts number
return count_to_zero(number-1)
end
end
#Test case
count_to_zero(5)
count_to_zero(0)
|
Ruby | UTF-8 | 747 | 2.921875 | 3 | [] | no_license | # This module will allow querying of TwitterCounter API
# http://twittercounter.com/pages/api
module TwitCount
# twitter_id should be an integer that is the Twitter ID (not username!)
# of the account that you would like information for
def self.query(twitter_id)
base_uri = 'http://api.twittercounter.com/'
api_key = '?apikey=' + ENV['TWITTER_COUNTER_API']
id_number = '&twitter_id=' + twitter_id.to_s
response = HTTParty.get(base_uri + api_key + id_number)
# creates database entry with the number of followers
new_entry = Query.create(:followers => response['followers_current'])
# this method currently returns just the current number of followers
# return response['followers_current']
end
end
|
C++ | UTF-8 | 550 | 3.1875 | 3 | [] | no_license | /*
* P7.cpp
*.
* Created on: Dec 7, 2016
* Author: brian wray
*
* projecteuler.net/problem=7
*
* Description: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
* we can see that the 6th prime is 13.
* What is the 10,001st prime number?
*
* Answer:
*
*/
#include "P_07.h"
#include "P_03.h"
P7::P7(){}
P7::~P7(){}
int P7::getPrimeNumber( int num ){
int counter = 0;
int series = 0;
P3 p3;
while(counter <= num){
++series;
if (p3.isPrime(series)){
++counter;
}
}
return series;
}
|
Python | UTF-8 | 889 | 2.78125 | 3 | [
"MIT"
] | permissive | from src.class_factory import *
from pybaseball import batting_stats_bref
def get_players(team):
p1 = Player("Todd", team)
p2 = Player("Macca", team)
p3 = Player("Dan", team)
p4 = Player("Stu", team)
return [p1, p2, p3, p4]
def get_team():
team = Team("Sox")
return team
def get_bases():
b1 = Base("Base One", 1)
b2 = Base("Base Two", 2)
b3 = Base("Base Three", 3)
b4 = Base("Home", 4)
return [b1, b2, b3, b4]
def get_base_manager(bases):
bm = BasesManager(bases)
return bm
def test_out_pybaseball():
data = batting_stats_bref()
print(data)
def test_main():
"""
Main test function
"""
team = get_team()
players = get_players(team)
bases = get_bases()
bases_manager = get_base_manager(bases)
for base in bases_manager.Bases:
print(base.Name)
test_out_pybaseball()
|
C++ | UTF-8 | 1,731 | 3.359375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "list.h"
namespace ft
{
template <typename T, typename Sequence = ft::list<T> >
class queue
{
public:
typedef typename Sequence::value_type value_type;
typedef typename Sequence::reference reference;
typedef typename Sequence::const_reference const_reference;
typedef typename Sequence::size_type size_type;
typedef Sequence container_type;
protected:
Sequence c;
public:
explicit queue(const Sequence & _c = Sequence()) : c(_c) { }
bool empty() const { return c.empty(); }
size_type size() const { return c.size(); }
reference front() { return c.front(); }
const_reference front() const { return c.front(); }
reference back() { return c.back(); }
const_reference back() const { return c.back(); }
void push(const value_type& x) { c.push_back(x); }
void pop() { c.pop_front(); }
friend bool operator==(const ft::queue<T, Sequence>& x, const ft::queue<T, Sequence>& y)
{ return x.c == y.c; }
friend bool operator<(const ft::queue<T, Sequence>& x, const ft::queue<T, Sequence>& y)
{ return x.c < y.c; }
};
template<typename T, typename Seq>
void swap(queue<T, Seq>& x, queue<T, Seq>& y)
{ x.swap(y); };
template<typename T, typename Seq>
inline bool operator!=(const queue<T, Seq>& x, const queue<T, Seq>& y)
{ return !(x == y); }
template<typename T, typename Seq>
inline bool operator>(const queue<T, Seq>& x, const queue<T, Seq>& y)
{ return y < x; }
template<typename T, typename Seq>
inline bool operator<=(const queue<T, Seq>& x, const queue<T, Seq>& y)
{ return !(y < x); }
template<typename T, typename Seq>
inline bool operator>=(const queue<T, Seq>& x, const queue<T, Seq>& y)
{ return !(x < y); }
}
|
Python | UTF-8 | 606 | 3.03125 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | from collections import Mapping
class Response(Mapping):
""" Read-only object that represents a response from Discord.
Shortcuts any key value pairs in nested dict 'data'. """
def __init__(self, status_code: int, data: dict = {}, **kwargs):
self.status_code = status_code
self._dict = data or kwargs
for k in self._dict.get('data', ()):
self._dict[k] = self._dict['data'][k]
def __getitem__(self, value):
return self._dict[value]
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._dict)
|
Java | UTF-8 | 248 | 2.6875 | 3 | [] | no_license | package com.lz.designpatterns.factory;
/**
* 〈肉类接口〉
* @author lz
* @create 2019/6/27
* @since 1.0.0
*/
public interface Meat {
/**
* 买肉
*/
void buyMeat();
/**
* 吃肉
*/
void eatMeat();
}
|
JavaScript | UTF-8 | 3,838 | 2.625 | 3 | [
"MIT"
] | permissive | /**
* DOM handling and js isolation done via jsdom
* slow and memory consuming, but somewhat "stable"
* means great deal of bugs already discovered
*/
var fs = require('fs')
, path = require('path')
, jsdom = require('jsdom')
, Oven = require('oven')
, jqueryCode = fs.readFileSync(path.join(__dirname, 'jquery.js'), 'utf-8')
, optimizelyCode
;
// public api
module.exports = optimizely;
module.exports.setOptimizely = setOptimizely;
// engine marker
module.exports.engine = 'jsdom';
// apply optimizely tests to the provided html
function optimizely(req, html, callback)
{
var userAgent = req.headers['user-agent'];
jsdom.env(
{
html: html,
url: 'http://' + req.headers.host + req.url,
src: [jqueryCode, optimizelyCode],
document:
{
referrer: req.headers.referer
},
done: function optimizely_jsdomDone(err, window)
{
var optimizeledHtml
, docCookie = new Oven({url: req.headers.host })
, newCookie = new Oven({url: req.headers.host })
, imagesList = []
;
// something went wrong return unmodified html
if (err)
{
return callback(err, html);
}
// preset cookies from the request
docCookie.setCookies((req.headers.cookie || '').split('; '));
// hack on jsdom's document.cookie hack
// to track cookies set during optimizely run
window.document.__defineSetter__('cookie', function optimizely_cookieSetter(cookie)
{
// store full cookie for later use
docCookie.setCookie(cookie);
// store new cookies separately
newCookie.setCookie(cookie);
return docCookie.getCookieHeader(req.url);
});
window.document.__defineGetter__('cookie', function optimizely_cookieGetter()
{
return docCookie.getCookieHeader(req.url);
});
// "pass" user agent
window.navigator =
{
appVersion: userAgent.replace(/^Mozilla\//i, ''),
userAgent: userAgent,
// It's either Chrome or Safari disguise under Safari's user agent
// Firefox has empty string for `vendor`, do we support IE yet?
vendor: (userAgent.match(/Chrome\//) ? 'Google Inc.' : (userAgent.match(/Safari\//) ? 'Apple Computer, Inc.' : ''))
};
// massage environment
window.$ = window.jQuery;
// fake Image object
window.Image = function(){};
// handle src setters
Object.defineProperty(window.Image.prototype, 'src',
{
enumerable: true,
get: function()
{
return this._src || '';
},
set: function(value)
{
// store src to the common list for later handling
imagesList.push(value);
this._src = value;
}
});
// try to run optimizely in a safe way
try
{
// init optimizely code
window.optimizelyCode();
// activate tests
window.optimizely = window.optimizely || [];
window.optimizely.push(['activate']);
}
catch (e)
{
// go back to the original html
return callback(e, html);
}
// get modified html
optimizeledHtml = window.document.documentElement.innerHTML;
// free memory
window.close();
// export DOM into html page
optimizeledHtml = '<!doctype html>\n<html>' + optimizeledHtml + '</html>';
// return modified html
callback(null, optimizeledHtml, {images: imagesList, cookies: newCookie});
}
});
}
// Sets optimizely code
function setOptimizely(code)
{
code = (code || '').replace(/\boptimizelyCode\(\);?/, '');
// 2. Make it proper function calls, so fake objects of jsdom won't fail
code = code.replace(/(new\s+[\w]+)\b([^\(]|$)/ig, '$1()$2');
// save
optimizelyCode = code;
}
|
C# | UTF-8 | 1,053 | 2.890625 | 3 | [
"MIT"
] | permissive | using System;
using System.IO;
using System.Runtime.CompilerServices;
using SecurityCam.Configuration;
namespace SecurityCam.Diagnostics.Implementation
{
public class ConsoleLog : ILog
{
private readonly LogConfig _config;
public ConsoleLog(LogConfig config)
{
_config = config;
}
public void Write(LogLevel level, string msg, [CallerFilePath] string filePath = default, [CallerMemberName] string caller = default, [CallerLineNumber] int line = default)
{
if (level < _config.MinLevel)
return;
var levelStr = level switch
{
LogLevel.Debug => "DBG",
LogLevel.Info => "INF",
LogLevel.Error => "ERR",
_ => throw new ArgumentOutOfRangeException(nameof(level), level, null)
};
Console.WriteLine($"[{levelStr}] {DateTime.Now:HH:mm:ss} - {Path.GetFileName(filePath)}.{caller}:{line} - {msg}");
}
}
} |
Python | UTF-8 | 229 | 3.46875 | 3 | [] | no_license | import turtle
window = turtle.Screen()
janer = turtle.Turtle()
janer.forward(50)
janer.left(90)
janer.forward(50)
janer.left(90)
janer.forward(50)
janer.left(90)
janer.forward(50)
janer.left(90)
turtle.mainloop()
|
SQL | UTF-8 | 19,267 | 2.9375 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1
-- Время создания: Янв 20 2020 г., 20:26
-- Версия сервера: 10.4.10-MariaDB
-- Версия PHP: 7.3.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `confectionery`
--
-- --------------------------------------------------------
--
-- Структура таблицы `log_list`
--
CREATE TABLE `log_list` (
`id` int(10) UNSIGNED NOT NULL,
`session_id` int(10) UNSIGNED NOT NULL,
`created_date` datetime NOT NULL DEFAULT current_timestamp(),
`action_type` enum('add_order','change_order','delete_order','add_product','change_product','delete_product','add_manager','change_manager','delete_manager','change_password') NOT NULL,
`elem_id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `log_list`
--
INSERT INTO `log_list` (`id`, `session_id`, `created_date`, `action_type`, `elem_id`) VALUES
(1, 10, '2020-01-19 21:37:27', 'change_order', 1),
(2, 10, '2020-01-19 21:37:42', 'change_order', 3),
(3, 10, '2020-01-19 21:37:57', 'change_product', 2),
(4, 10, '2020-01-19 21:38:48', 'add_manager', 7),
(5, 11, '2020-01-19 22:38:49', 'change_order', 2),
(6, 12, '2020-01-19 22:39:51', 'change_password', 12),
(7, 15, '2020-01-20 01:31:40', 'change_order', 7),
(8, 15, '2020-01-20 01:32:22', 'change_product', 2),
(9, 15, '2020-01-20 01:32:51', 'change_password', 15),
(10, 16, '2020-01-20 01:44:33', 'change_order', 2),
(11, 16, '2020-01-20 01:45:06', 'add_product', 18),
(12, 16, '2020-01-20 01:45:23', 'change_product', 18),
(13, 16, '2020-01-20 01:45:38', 'delete_product', 18),
(14, 16, '2020-01-20 01:46:12', 'delete_manager', 7),
(15, 17, '2020-01-20 02:20:25', 'change_order', 9),
(16, 17, '2020-01-20 02:21:38', 'change_product', 2),
(17, 18, '2020-01-20 02:25:06', 'change_order', 10),
(18, 18, '2020-01-20 02:26:09', 'change_product', 2),
(19, 18, '2020-01-20 02:26:35', 'change_product', 2),
(20, 18, '2020-01-20 02:27:13', 'add_product', 19),
(21, 19, '2020-01-20 02:28:10', 'delete_order', 10),
(22, 19, '2020-01-20 02:28:55', 'change_product', 19),
(23, 19, '2020-01-20 02:29:09', 'delete_product', 19),
(24, 19, '2020-01-20 02:29:52', 'add_manager', 8),
(25, 19, '2020-01-20 02:30:27', 'change_manager', 8),
(26, 19, '2020-01-20 02:30:39', 'delete_manager', 8),
(27, 19, '2020-01-20 02:34:07', 'change_password', 19),
(28, 20, '2020-01-20 02:48:59', 'change_manager', 4),
(29, 20, '2020-01-20 02:49:32', 'change_manager', 4),
(30, 20, '2020-01-20 02:50:06', 'change_manager', 4),
(31, 20, '2020-01-20 02:50:26', 'change_manager', 4),
(32, 20, '2020-01-20 02:52:08', 'change_manager', 2),
(33, 20, '2020-01-20 02:52:18', 'change_manager', 2),
(34, 20, '2020-01-20 02:52:30', 'change_manager', 2),
(35, 20, '2020-01-20 02:52:55', 'change_manager', 2),
(36, 20, '2020-01-20 02:53:23', 'change_manager', 2),
(37, 20, '2020-01-20 02:55:06', 'change_manager', 2),
(38, 20, '2020-01-20 02:56:50', 'change_manager', 2),
(39, 20, '2020-01-20 02:57:07', 'change_manager', 2),
(40, 20, '2020-01-20 02:57:35', 'change_manager', 2),
(41, 20, '2020-01-20 02:58:46', 'change_manager', 2),
(42, 20, '2020-01-20 02:58:59', 'change_manager', 2),
(43, 20, '2020-01-20 02:59:22', 'change_manager', 2),
(44, 20, '2020-01-20 02:59:44', 'change_manager', 2),
(45, 20, '2020-01-20 03:00:02', 'change_manager', 2),
(46, 20, '2020-01-20 03:00:14', 'change_manager', 2),
(47, 20, '2020-01-20 03:03:33', 'change_manager', 2),
(48, 20, '2020-01-20 03:03:48', 'change_manager', 2),
(49, 20, '2020-01-20 03:04:04', 'change_manager', 2),
(50, 20, '2020-01-20 03:04:16', 'change_manager', 2),
(51, 20, '2020-01-20 03:04:51', 'change_password', 20),
(52, 20, '2020-01-20 03:05:43', 'change_manager', 2),
(53, 20, '2020-01-20 03:05:51', 'change_manager', 2),
(54, 20, '2020-01-20 03:09:22', 'change_password', 20),
(55, 20, '2020-01-20 03:10:08', 'change_password', 20),
(56, 20, '2020-01-20 03:12:43', 'change_password', 20),
(57, 20, '2020-01-20 03:13:24', 'change_password', 20),
(58, 20, '2020-01-20 03:13:59', 'change_password', 20),
(59, 21, '2020-01-20 03:18:11', 'change_order', 11),
(60, 21, '2020-01-20 03:18:50', 'change_order', 11),
(61, 21, '2020-01-20 03:19:47', 'change_product', 2),
(62, 21, '2020-01-20 03:20:14', 'add_product', 20),
(63, 21, '2020-01-20 03:20:37', 'change_product', 2),
(64, 21, '2020-01-20 03:20:49', 'change_product', 20),
(65, 22, '2020-01-20 03:21:33', 'delete_product', 20),
(66, 22, '2020-01-20 03:22:01', 'delete_order', 11),
(67, 22, '2020-01-20 03:22:42', 'change_manager', 2),
(68, 22, '2020-01-20 03:22:56', 'change_manager', 2),
(69, 22, '2020-01-20 03:23:08', 'add_manager', 9),
(70, 22, '2020-01-20 03:23:21', 'delete_manager', 9),
(71, 22, '2020-01-20 03:25:13', 'change_password', 22),
(72, 22, '2020-01-20 03:25:32', 'change_manager', 1),
(73, 24, '2020-01-20 11:22:16', 'change_order', 2),
(74, 24, '2020-01-20 11:22:30', 'change_order', 2),
(75, 24, '2020-01-20 11:22:52', 'change_order', 3),
(76, 24, '2020-01-20 11:23:26', 'change_order', 2),
(77, 24, '2020-01-20 11:27:48', 'change_order', 1),
(78, 25, '2020-01-20 12:45:01', 'change_order', 3),
(79, 25, '2020-01-20 12:46:17', 'change_product', 2),
(80, 25, '2020-01-20 12:46:36', 'change_product', 2),
(81, 29, '2020-01-20 21:20:14', 'change_password', 29),
(82, 29, '2020-01-20 21:21:31', 'change_password', 29),
(83, 29, '2020-01-20 21:26:51', 'change_password', 29),
(84, 31, '2020-01-20 21:44:11', 'change_password', 31),
(85, 31, '2020-01-20 21:45:16', 'change_password', 31),
(86, 31, '2020-01-20 21:48:15', 'change_password', 31),
(87, 31, '2020-01-20 21:49:52', 'change_password', 31),
(88, 31, '2020-01-20 21:50:51', 'change_password', 31),
(89, 32, '2020-01-20 21:53:19', 'change_manager', 2),
(90, 32, '2020-01-20 21:53:39', 'change_manager', 3),
(91, 32, '2020-01-20 21:53:51', 'change_manager', 4),
(92, 32, '2020-01-20 21:58:15', 'add_manager', 10),
(93, 32, '2020-01-20 21:59:11', 'change_manager', 10),
(94, 32, '2020-01-20 22:05:19', 'change_manager', 10),
(95, 32, '2020-01-20 22:06:29', 'change_manager', 10),
(96, 32, '2020-01-20 22:06:47', 'change_manager', 10),
(97, 33, '2020-01-20 22:18:57', 'change_password', 33),
(98, 33, '2020-01-20 22:19:34', 'change_password', 33),
(99, 33, '2020-01-20 22:20:07', 'change_password', 33),
(100, 33, '2020-01-20 22:20:45', 'change_password', 33),
(101, 33, '2020-01-20 22:21:15', 'change_manager', 1),
(102, 34, '2020-01-20 22:23:42', 'change_password', 34),
(103, 34, '2020-01-20 22:24:11', 'change_password', 34),
(104, 34, '2020-01-20 22:24:37', 'change_password', 34);
-- --------------------------------------------------------
--
-- Структура таблицы `managers`
--
CREATE TABLE `managers` (
`id` int(10) UNSIGNED NOT NULL,
`login` varchar(20) NOT NULL CHECK (`login` <> ''),
`password` varchar(255) NOT NULL,
`role` enum('manager','supermanager','anouther') NOT NULL DEFAULT 'manager'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `managers`
--
INSERT INTO `managers` (`id`, `login`, `password`, `role`) VALUES
(1, 'Kate', '$2y$10$M9FApaIOyILjLaYEhuc2Ge98navuaV7u2Cu/HhqWAl0awRE5VsRO.', 'supermanager'),
(2, 'Lena', '$2y$10$2cU7zVAaKU7W2ixaWGa6T.S2KhV3Lb8aOH5XKo9JI5aA6dsvkgbTi', 'manager'),
(3, 'Anna', '$2y$10$Y8I9PsTZaQTgD0Y/Lr7ywO1IZ0IhB5GY9fuEZhd/OOk9Xy87NYy/a', 'manager'),
(4, 'Auto', '$2y$10$rOFON0O9p4p7SM2bT7A67OxadMWo2dfBY75G0efc5rWALN0Lm8Pxm', 'anouther'),
(10, 'Katherine', '$2y$10$NO0LSP9GBuW6uoprefpxcO0Vea5YA9lQGAVRjRzzimyx1YqT8UJd2', 'anouther');
-- --------------------------------------------------------
--
-- Структура таблицы `orders`
--
CREATE TABLE `orders` (
`id` int(10) UNSIGNED NOT NULL,
`phone_number` varchar(12) NOT NULL,
`customer_name` varchar(200) NOT NULL,
`created_date` datetime NOT NULL DEFAULT current_timestamp(),
`packaging_cost` decimal(10,2) NOT NULL DEFAULT 0.00,
`production_cost` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `orders`
--
INSERT INTO `orders` (`id`, `phone_number`, `customer_name`, `created_date`, `packaging_cost`, `production_cost`) VALUES
(1, '89051826930', 'Katherine', '2020-01-19 21:35:24', '0.00', '660.00'),
(2, '89051826930', 'Katherine', '2020-01-19 21:35:43', '0.00', '748.00'),
(3, '89051826930', 'Katherine', '2020-01-19 21:36:04', '0.00', '1750.00'),
(4, '89051826930', 'Katherine', '2020-01-19 21:36:56', '0.00', '19800.00'),
(7, '89051826930', 'Kate', '2020-01-20 01:30:19', '0.00', '1280.00'),
(8, '89051826930', 'Katherine', '2020-01-20 02:15:38', '0.00', '1205.00'),
(9, '89051826930', 'Kate', '2020-01-20 02:19:35', '0.00', '1425.00');
-- --------------------------------------------------------
--
-- Структура таблицы `order_list`
--
CREATE TABLE `order_list` (
`id` int(10) UNSIGNED NOT NULL,
`order_id` int(10) UNSIGNED NOT NULL,
`product_id` int(10) UNSIGNED NOT NULL,
`quantity` tinyint(3) UNSIGNED NOT NULL,
`cost` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `order_list`
--
INSERT INTO `order_list` (`id`, `order_id`, `product_id`, `quantity`, `cost`) VALUES
(1, 1, 1, 1, '100.00'),
(2, 1, 2, 1, '120.00'),
(3, 1, 3, 1, '120.00'),
(4, 1, 4, 1, '120.00'),
(5, 1, 5, 1, '100.00'),
(6, 1, 6, 1, '100.00'),
(7, 2, 1, 3, '100.00'),
(8, 2, 7, 3, '50.00'),
(9, 2, 8, 4, '40.00'),
(10, 2, 9, 3, '6.00'),
(11, 2, 10, 4, '30.00'),
(12, 3, 1, 3, '100.00'),
(13, 3, 4, 3, '120.00'),
(14, 3, 5, 4, '100.00'),
(15, 3, 6, 4, '100.00'),
(16, 3, 7, 3, '50.00'),
(17, 3, 8, 3, '40.00'),
(18, 3, 9, 4, '5.00'),
(19, 4, 1, 30, '100.00'),
(20, 4, 2, 30, '120.00'),
(21, 4, 3, 30, '120.00'),
(22, 4, 4, 30, '120.00'),
(23, 4, 5, 30, '100.00'),
(24, 4, 6, 30, '100.00'),
(25, 7, 4, 1, '120.00'),
(26, 7, 5, 3, '100.00'),
(27, 7, 6, 3, '100.00'),
(28, 7, 7, 4, '50.00'),
(29, 7, 8, 8, '40.00'),
(30, 7, 9, 8, '5.00'),
(31, 8, 1, 2, '100.00'),
(32, 8, 2, 3, '135.00'),
(33, 8, 3, 4, '120.00'),
(34, 8, 10, 4, '30.00'),
(35, 9, 1, 3, '100.00'),
(36, 9, 2, 3, '135.00'),
(37, 9, 3, 3, '120.00'),
(38, 9, 4, 3, '120.00');
-- --------------------------------------------------------
--
-- Структура таблицы `order_processing`
--
CREATE TABLE `order_processing` (
`id` int(10) UNSIGNED NOT NULL,
`order_id` int(10) UNSIGNED NOT NULL,
`order_status` enum('processed','new','made','received','canceled') NOT NULL,
`changing_date` datetime NOT NULL DEFAULT current_timestamp(),
`manager_id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `order_processing`
--
INSERT INTO `order_processing` (`id`, `order_id`, `order_status`, `changing_date`, `manager_id`) VALUES
(1, 1, 'new', '2020-01-19 21:35:25', 4),
(2, 2, 'new', '2020-01-19 21:35:43', 4),
(3, 3, 'new', '2020-01-19 21:36:04', 4),
(4, 4, 'new', '2020-01-19 21:36:56', 4),
(5, 1, 'processed', '2020-01-19 21:37:27', 1),
(6, 3, 'processed', '2020-01-19 21:37:42', 1),
(7, 2, 'new', '2020-01-19 22:35:19', 1),
(8, 2, 'new', '2020-01-19 22:38:49', 1),
(9, 7, 'new', '2020-01-20 01:30:19', 4),
(10, 7, 'new', '2020-01-20 01:31:40', 2),
(11, 2, 'new', '2020-01-20 01:44:33', 1),
(12, 8, 'new', '2020-01-20 02:15:38', 4),
(13, 9, 'new', '2020-01-20 02:19:35', 4),
(14, 9, 'processed', '2020-01-20 02:20:25', 2),
(20, 2, 'processed', '2020-01-20 11:22:16', 1),
(21, 2, 'made', '2020-01-20 11:22:30', 1),
(22, 3, 'made', '2020-01-20 11:22:52', 1),
(23, 2, 'received', '2020-01-20 11:23:26', 1),
(24, 1, 'received', '2020-01-20 11:27:48', 1),
(25, 3, 'received', '2020-01-20 12:45:01', 1);
-- --------------------------------------------------------
--
-- Структура таблицы `products`
--
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(200) NOT NULL,
`price` decimal(10,2) NOT NULL,
`img_url` varchar(200) NOT NULL DEFAULT '0.jpg',
`availability` tinyint(1) NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `products`
--
INSERT INTO `products` (`id`, `name`, `price`, `img_url`, `availability`) VALUES
(1, 'Капкейк Мачо', '100.00', '1.jpg', 1),
(2, 'Капкейк Шоколадный мусс', '135.00', '2.jpg', 0),
(3, 'Капкейк Летний микс', '120.00', '3.jpg\r', 1),
(4, 'Капкейк Фреш', '120.00', '4.jpg\r', 1),
(5, 'Капкейк Оранжевое настроение', '100.00', '5.jpg', 1),
(6, 'Капкейк Вишенка', '100.00', '6.jpg', 1),
(7, 'Торт Воздушное облако', '50.00', '7.jpg\r', 1),
(8, 'Эклер Мечта', '40.00', '8.jpg\r', 1),
(9, 'Печенье По-домашнему', '5.00', '9.jpg\r', 1),
(10, 'Трубочка вафельная', '30.00', '10.jpg', 1);
-- --------------------------------------------------------
--
-- Структура таблицы `sessions`
--
CREATE TABLE `sessions` (
`id` int(10) UNSIGNED NOT NULL,
`manager_id` int(10) UNSIGNED NOT NULL,
`begin_date` datetime NOT NULL DEFAULT current_timestamp(),
`end_date` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Дамп данных таблицы `sessions`
--
INSERT INTO `sessions` (`id`, `manager_id`, `begin_date`, `end_date`) VALUES
(1, 1, '2020-01-19 15:54:01', '2020-01-19 15:55:47'),
(2, 2, '2020-01-19 15:56:15', '2020-01-19 15:56:20'),
(3, 1, '2020-01-19 16:26:57', '2020-01-19 16:28:03'),
(4, 1, '2020-01-19 16:28:23', '2020-01-19 16:41:42'),
(5, 1, '2020-01-19 16:47:25', '2020-01-19 17:42:41'),
(6, 1, '2020-01-19 17:42:51', '2020-01-19 17:54:26'),
(7, 1, '2020-01-19 17:59:33', '2020-01-19 18:32:41'),
(8, 1, '2020-01-19 18:32:48', '2020-01-19 21:17:17'),
(9, 3, '2020-01-19 21:17:58', '2020-01-19 21:24:57'),
(10, 1, '2020-01-19 21:25:05', '2020-01-19 22:34:25'),
(11, 1, '2020-01-19 22:34:38', '2020-01-19 22:39:07'),
(12, 2, '2020-01-19 22:39:16', '2020-01-19 22:39:55'),
(13, 1, '2020-01-19 22:40:05', '2020-01-20 00:19:51'),
(14, 1, '2020-01-20 00:20:20', '2020-01-20 01:22:46'),
(15, 2, '2020-01-20 01:31:18', '2020-01-20 01:32:54'),
(16, 1, '2020-01-20 01:33:03', '2020-01-20 01:48:56'),
(17, 2, '2020-01-20 02:19:58', '2020-01-20 02:22:45'),
(18, 2, '2020-01-20 02:24:27', '2020-01-20 02:27:16'),
(19, 1, '2020-01-20 02:27:49', '2020-01-20 02:34:47'),
(20, 1, '2020-01-20 02:48:42', '2020-01-20 03:16:16'),
(21, 2, '2020-01-20 03:17:36', '2020-01-20 03:20:55'),
(22, 1, '2020-01-20 03:21:15', '2020-01-20 03:25:41'),
(23, 1, '2020-01-20 10:28:33', '2020-01-20 11:11:31'),
(24, 1, '2020-01-20 11:20:51', '2020-01-20 11:45:36'),
(25, 1, '2020-01-20 12:09:50', '2020-01-20 12:46:39'),
(26, 1, '2020-01-20 12:47:00', '2020-01-20 12:49:06'),
(27, 2, '2020-01-20 12:49:46', '2020-01-20 13:04:48'),
(28, 1, '2020-01-20 13:04:56', '2020-01-20 13:13:17'),
(29, 1, '2020-01-20 21:19:51', '2020-01-20 21:32:58'),
(30, 1, '2020-01-20 21:33:09', '2020-01-20 21:33:14'),
(31, 1, '2020-01-20 21:42:52', '2020-01-20 21:51:00'),
(32, 1, '2020-01-20 21:51:25', '2020-01-20 22:17:08'),
(33, 1, '2020-01-20 22:17:20', '2020-01-20 22:23:11'),
(34, 2, '2020-01-20 22:23:21', '2020-01-20 22:24:51'),
(35, 2, '2020-01-20 22:25:00', '2020-01-20 22:25:02'),
(36, 3, '2020-01-20 22:25:12', '2020-01-20 22:25:14');
--
-- Индексы сохранённых таблиц
--
--
-- Индексы таблицы `log_list`
--
ALTER TABLE `log_list`
ADD PRIMARY KEY (`id`),
ADD KEY `logs_sessions_fk` (`session_id`);
--
-- Индексы таблицы `managers`
--
ALTER TABLE `managers`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `login` (`login`);
--
-- Индексы таблицы `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `order_list`
--
ALTER TABLE `order_list`
ADD PRIMARY KEY (`id`),
ADD KEY `order_list_orders_fk` (`order_id`),
ADD KEY `order_list_products_fk` (`product_id`);
--
-- Индексы таблицы `order_processing`
--
ALTER TABLE `order_processing`
ADD PRIMARY KEY (`id`),
ADD KEY `order__processing_orders_fk` (`order_id`),
ADD KEY `order_processing_managers_fk` (`manager_id`);
--
-- Индексы таблицы `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
--
-- Индексы таблицы `sessions`
--
ALTER TABLE `sessions`
ADD PRIMARY KEY (`id`),
ADD KEY `sessions_managers_fk` (`manager_id`);
--
-- AUTO_INCREMENT для сохранённых таблиц
--
--
-- AUTO_INCREMENT для таблицы `log_list`
--
ALTER TABLE `log_list`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=105;
--
-- AUTO_INCREMENT для таблицы `managers`
--
ALTER TABLE `managers`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT для таблицы `orders`
--
ALTER TABLE `orders`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT для таблицы `order_list`
--
ALTER TABLE `order_list`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=39;
--
-- AUTO_INCREMENT для таблицы `order_processing`
--
ALTER TABLE `order_processing`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26;
--
-- AUTO_INCREMENT для таблицы `products`
--
ALTER TABLE `products`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT для таблицы `sessions`
--
ALTER TABLE `sessions`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;
--
-- Ограничения внешнего ключа сохраненных таблиц
--
--
-- Ограничения внешнего ключа таблицы `log_list`
--
ALTER TABLE `log_list`
ADD CONSTRAINT `logs_sessions_fk` FOREIGN KEY (`session_id`) REFERENCES `sessions` (`id`) ON DELETE CASCADE;
--
-- Ограничения внешнего ключа таблицы `order_list`
--
ALTER TABLE `order_list`
ADD CONSTRAINT `order_list_orders_fk` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `order_list_products_fk` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;
--
-- Ограничения внешнего ключа таблицы `order_processing`
--
ALTER TABLE `order_processing`
ADD CONSTRAINT `order__processing_orders_fk` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `order_processing_managers_fk` FOREIGN KEY (`manager_id`) REFERENCES `managers` (`id`) ON DELETE CASCADE;
--
-- Ограничения внешнего ключа таблицы `sessions`
--
ALTER TABLE `sessions`
ADD CONSTRAINT `sessions_managers_fk` FOREIGN KEY (`manager_id`) REFERENCES `managers` (`id`) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
C++ | UTF-8 | 1,438 | 2.59375 | 3 | [] | no_license | /* CHARACTER CLASS
* 3/16/2018 AS OF THIS DATE, DON'T MAKE AN OBJECT WITH THIS. USE PLAYER OR ENEMY INSTEAD
*/
#ifndef _CHARACTER_H_
#define _CHARACTER_H_
#include "cocos2d.h"
#include <string>
#include <iostream>
#include "Entity.h"
#include "Weapon.h"
#include <vector>
class Character : public Entity
{
public:
Character();
virtual ~Character();
static Character * create(const std::string & fileName);
virtual bool init(const std::string & fileName);
virtual void initAnimations();
virtual bool onContactBegin(PhysicsContact&);
virtual bool onContactPost(PhysicsContact&);
virtual bool onContactSeparate(PhysicsContact&);
virtual void handleMovement(float);
virtual void updateAnimation(float);
float getHealth();
protected:
float health;
bool isMoving;
bool isSprinting;
cocos2d::Animate* animL;
cocos2d::Animate* animR;
cocos2d::Animate* runAnimR;
cocos2d::Animate* runAnimL;
cocos2d::Animate* idleR;
cocos2d::Animate* idleL;
cocos2d::Animate* dying;
Vec2 previousPos;
Vec2 velocity;
Vec2 velNorm;
Vec2 lastVel;
float speed;
std::vector<Weapon*> weapons;
float velocityLimit;
//current weapon equipped
unsigned int cWeapNum;
bool hasAk_;
bool hasM16_;
//NEW Animation
bool faceLeft_;
bool faceRight_;
bool faceUp_;
bool faceDown_;
int animationCounter;
float animationTimer;
int currentACounter;
std::string orientation_;
std::string cOrientation_;
};
#endif // !_CHARACTER_H_
|
C++ | UTF-8 | 1,424 | 3.984375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
输入一个整数数组,实现一个函数调整该数组中数字的顺序,使得所有奇数位于数组的前半部分
偶数位于数组的后半部分
思路:双指针移动?
//通用的一个双指针问题-->修改while循环的条件即可
*/
class Solution{
public:
void ReorderOddEven(vector<int> &data){
int i=0, j=data.size()-1;
//i指向偶数,j指向奇数,然后交换
while(i < j){
while((data[i] & 0x01) == 1){
i++;
}
while((data[j] & 0x01) == 0){
j--;
}
if(i < j){
swap(data[i], data[j]);
++i; --j;
}
}
return;
}
//通用版
void Reorder(vector<int> &data, bool(*func)(int)){
int i=0, j=data.size()-1;
//i指向偶数,j指向奇数,然后交换
while(i < j){
while(i<j && (*func)(data[i])){
i++;
}
while(i<j && !(*func)(data[j])){
j--;
}
if(i < j){
swap(data[i], data[j]);
++i; --j;
}
}
return;
}
bool isEven(int a){
return (a & 1) == 0;
}
};
bool isEven(int a){
return (a & 1) == 0;
}
int main()
{
vector<int> v = {2,34,55,66,1,6};
Solution a;
a.Reorder(v, &isEven);
for(auto it = v.begin(); it!=v.end(); it++){
cout << *it << '\t';
}
} |
TypeScript | UTF-8 | 3,221 | 2.65625 | 3 | [] | no_license | import {
Graphics,
interaction,
} from 'pixi.js';
export type EventsHandlerType = {
click?: (event: interaction.InteractionEvent) => void;
mousedown?: (event: interaction.InteractionEvent) => void;
mouseout?: (event: interaction.InteractionEvent) => void;
mouseover?: (event: interaction.InteractionEvent) => void;
mouseup?: (event: interaction.InteractionEvent) => void;
mouseupoutside?: (event: interaction.InteractionEvent) => void;
rightclick?: (event: interaction.InteractionEvent) => void;
rightdown?: (event: interaction.InteractionEvent) => void;
rightup?: (event: interaction.InteractionEvent) => void;
rightupoutside?: (event: interaction.InteractionEvent) => void;
tap?: (event: interaction.InteractionEvent) => void;
touchend?: (event: interaction.InteractionEvent) => void;
touchendoutside?: (event: interaction.InteractionEvent) => void;
touchmove?: (event: interaction.InteractionEvent) => void;
touchstart?: (event: interaction.InteractionEvent) => void;
}
export function hasInteractivity(eventsHandler: EventsHandlerType): boolean {
return !(!(eventsHandler.click
|| eventsHandler.mousedown
|| eventsHandler.mouseout
|| eventsHandler.mouseover
|| eventsHandler.mouseup
|| eventsHandler.mouseupoutside
|| eventsHandler.rightclick
|| eventsHandler.rightdown
|| eventsHandler.rightup
|| eventsHandler.rightupoutside
|| eventsHandler.tap
|| eventsHandler.touchend
|| eventsHandler.touchendoutside
|| eventsHandler.touchmove
|| eventsHandler.touchstart
));
}
export function applyInteractivity(gl: Graphics, eventsHandler: EventsHandlerType) {
gl.on('click', eventsHandler.click);
gl.on('mousedown', eventsHandler.mousedown);
gl.on('mouseout', eventsHandler.mouseout);
gl.on('mouseover', eventsHandler.mouseover);
gl.on('mouseup', eventsHandler.mouseup);
gl.on('mouseupoutside', eventsHandler.mouseupoutside);
gl.on('rightclick', eventsHandler.rightclick);
gl.on('rightdown', eventsHandler.rightdown);
gl.on('rightup', eventsHandler.rightup);
gl.on('rightupoutside', eventsHandler.rightupoutside);
gl.on('tap', eventsHandler.tap);
gl.on('touchend', eventsHandler.touchend);
gl.on('touchendoutside', eventsHandler.touchendoutside);
gl.on('touchmove', eventsHandler.touchmove);
gl.on('touchstart', eventsHandler.touchstart);
}
export function unapplyInteractivity(gl: Graphics, eventsHandler?: EventsHandlerType) {
if (!eventsHandler) { return }
gl.off('click', eventsHandler.click);
gl.off('mousedown', eventsHandler.mousedown);
gl.off('mouseout', eventsHandler.mouseout);
gl.off('mouseover', eventsHandler.mouseover);
gl.off('mouseup', eventsHandler.mouseup);
gl.off('mouseupoutside', eventsHandler.mouseupoutside);
gl.off('rightclick', eventsHandler.rightclick);
gl.off('rightdown', eventsHandler.rightdown);
gl.off('rightup', eventsHandler.rightup);
gl.off('rightupoutside', eventsHandler.rightupoutside);
gl.off('tap', eventsHandler.tap);
gl.off('touchend', eventsHandler.touchend);
gl.off('touchendoutside', eventsHandler.touchendoutside);
gl.off('touchmove', eventsHandler.touchmove);
gl.off('touchstart', eventsHandler.touchstart);
} |
TypeScript | UTF-8 | 1,654 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | import {
animate,
query,
style,
transition,
trigger,
} from "@angular/animations";
import { Component } from "@angular/core";
@Component({
moduleId: module.id,
animations: [
trigger("listAnimation", [
transition(":enter", [
query("*", [
style({ opacity: 0 }),
animate(1000, style({ opacity: 1 }))
])
]),
transition(":leave", [
query("*", [
style({ opacity: 1 }),
animate(1000, style({ opacity: 0 }))
])
])
]),
],
template: `
<FlexboxLayout flexDirection="column"
automationText="itemsContainer">
<Button text="add" automationText="add" (tap)="items.push('random')"></Button>
<FlexboxLayout
flexDirection="column"
[@listAnimation]="items.length"
*ngFor="let item of items; let i=index">
<FlexboxLayout justifyContent="center" alignItems="center">
<Label [text]="'Item No.' + i"></Label>
<Button [text]="item" (tap)="remove(item)"></Button>
</FlexboxLayout>
</FlexboxLayout>
</FlexboxLayout>
`
})
export class SelectorAllComponent {
public items = [
"first",
"second",
];
add() {
const newItem = `Item ${this.items.length}`;
this.items.push(newItem);
}
remove(item) {
const index = this.items.indexOf(item);
this.items.splice(index, 1)
}
}
|
Java | UTF-8 | 273 | 1.890625 | 2 | [] | no_license | package com.ad.model;
import java.util.List;
public interface AdDAO_interface {
public void insert(AdVO adVO);
public void update(AdVO adVO);
public void delete(Integer adID);
public AdVO findByPrimaryKey(Integer adID);
public List<AdVO> getAll();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.