hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
447f0e0f8838794d2898b615dca748811756dbfd
| 1,073
|
py
|
Python
|
boo/year.py
|
AirVetra/boo
|
bb8404c48a6f17402a98a88454fdd876184c35c1
|
[
"MIT"
] | 1
|
2019-12-06T21:13:22.000Z
|
2019-12-06T21:13:22.000Z
|
boo/year.py
|
AirVetra/boo
|
bb8404c48a6f17402a98a88454fdd876184c35c1
|
[
"MIT"
] | null | null | null |
boo/year.py
|
AirVetra/boo
|
bb8404c48a6f17402a98a88454fdd876184c35c1
|
[
"MIT"
] | null | null | null |
from boo.errors import WrongYearError
# Must manually hardcode new timestamps when new version arrives
TIMESTAMPS = {2012: 20190329,
2013: 20190411,
2014: 20190411,
2015: 20190411,
2016: 20190411,
2017: 20190423,
2018: 20191029, # from data-20191029t000000-structure-20181231t000000.csv
}
YEARS = list(TIMESTAMPS.keys())
def make_url(year: int) -> str:
"""
Construct URL similar to
http://www.gks.ru/opendata/storage/7708234640-bdboo2012/data-20181029t000000-structure-20121231t000000.csv
"""
if year in [0, 1]:
pat = 'https://raw.githubusercontent.com/ru-corporate/boo/master/assets/sample{}.txt'
return pat.format(year)
try:
timestamp = TIMESTAMPS[year]
return ('http://www.gks.ru/opendata/storage/'
f'7708234640-bdboo{year}/'
f'data-{timestamp}t000000-structure-'
f'{year}1231t000000.csv'
)
except KeyError:
raise WrongYearError(year)
| 32.515152
| 110
| 0.603914
|
54fb2bb8eb3e6bd6dd63d58000a73f4c770be89a
| 430
|
h
|
C
|
void/type_traits/next_type.h
|
Loggi-pro/void-lib
|
b933d7edc0d07cc6a7ab9c198e385d4d627b805b
|
[
"MIT"
] | null | null | null |
void/type_traits/next_type.h
|
Loggi-pro/void-lib
|
b933d7edc0d07cc6a7ab9c198e385d4d627b805b
|
[
"MIT"
] | null | null | null |
void/type_traits/next_type.h
|
Loggi-pro/void-lib
|
b933d7edc0d07cc6a7ab9c198e385d4d627b805b
|
[
"MIT"
] | null | null | null |
#pragma once
namespace vd {
template <typename T>
struct next_type;
template <>
struct next_type<uint8_t> {
using type = uint16_t;
};
template <>
struct next_type<uint16_t> {
using type = uint32_t;
};
template <>
struct next_type<int8_t> {
using type = int16_t;
};
template <>
struct next_type<int16_t> {
using type = int32_t;
};
template <typename T>
using next_type_t = typename next_type<T>::type;
}
| 15.925926
| 49
| 0.683721
|
da403759c19b2980a67a50433181c9be59aba7ea
| 3,265
|
php
|
PHP
|
Classes/Domain/Model/Styler.php
|
daviian/sd_googlemaps
|
afb14e4ff31fec527746b9e6987876efdf4138ba
|
[
"MIT"
] | null | null | null |
Classes/Domain/Model/Styler.php
|
daviian/sd_googlemaps
|
afb14e4ff31fec527746b9e6987876efdf4138ba
|
[
"MIT"
] | null | null | null |
Classes/Domain/Model/Styler.php
|
daviian/sd_googlemaps
|
afb14e4ff31fec527746b9e6987876efdf4138ba
|
[
"MIT"
] | null | null | null |
<?php
namespace SD\SdGooglemaps\Domain\Model;
/***
*
* This file is part of the "Google Maps" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2017 David Schneiderbauer <david.schneiderbauer@dschneiderbauer.me>
*
***/
/**
* Styler
*/
class Styler extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity implements \JsonSerializable
{
/**
* type
*
* @var string
*/
protected $type = '';
/**
* styleOption
*
* @var string
* @validate NotEmpty
*/
protected $styleOption = '';
/**
* stringValue
*
* @var string
*/
protected $stringValue = '';
/**
* intValue
*
* @var int
*/
protected $intValue = 0;
/**
* floatValue
*
* @var float
*/
protected $floatValue = 0.0;
/**
* boolValue
*
* @var bool
*/
protected $boolValue = false;
/**
* Serialization of object
*/
public function jsonSerialize()
{
switch ($this->type) {
case 'string':
$value = $this->stringValue;
break;
case 'int':
$value = $this->intValue;
break;
case 'float':
$value = $this->floatValue;
break;
case 'bool':
$value = $this->boolValue;
break;
default:
$value = '';
}
return [
$this->styleOption => $value
];
}
/**
* Returns the type
*
* @return string $type
*/
public function getType()
{
return $this->type;
}
/**
* Sets the type
*
* @param string $type
* @return void
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Returns the styleOption
*
* @return string $styleOption
*/
public function getStyleOption()
{
return $this->styleOption;
}
/**
* Sets the styleOption
*
* @param string $styleOption
* @return void
*/
public function setStyleOption($styleOption)
{
$this->styleOption = $styleOption;
}
/**
* Returns the stringValue
*
* @return string $stringValue
*/
public function getStringValue()
{
return $this->stringValue;
}
/**
* Sets the stringValue
*
* @param string $stringValue
* @return void
*/
public function setStringValue($stringValue)
{
$this->stringValue = $stringValue;
}
/**
* Returns the intValue
*
* @return int $intValue
*/
public function getIntValue()
{
return $this->intValue;
}
/**
* Sets the intValue
*
* @param string $intValue
* @return void
*/
public function setIntValue($intValue)
{
$this->intValue = $intValue;
}
/**
* Returns the floatValue
*
* @return int $floatValue
*/
public function getFloatValue()
{
return $this->floatValue;
}
/**
* Sets the floatValue
*
* @param string $floatValue
* @return void
*/
public function setFloatValue($floatValue)
{
$this->floatValue = $floatValue;
}
/**
* Returns the boolValue
*
* @return int $boolValue
*/
public function getBoolValue()
{
return $this->boolValue;
}
/**
* Sets the boolValue
*
* @param string $boolValue
* @return void
*/
public function setBoolValue($boolValue)
{
$this->boolValue = $boolValue;
}
/**
* Returns the boolean state of boolValue
*
* @return bool
*/
public function isBoolValue()
{
return $this->boolValue;
}
}
| 14.511111
| 96
| 0.611332
|
662c973ec988c6a590d15c0b7d48c8970fa62a91
| 535
|
py
|
Python
|
blockchainetl/streaming/postgres_utils.py
|
zalam003/ethereum-etl
|
2a9e468c1ec2b62c3647706d64fb9b93366ac2d1
|
[
"MIT"
] | 1,482
|
2018-09-13T10:40:55.000Z
|
2022-03-31T12:22:29.000Z
|
blockchainetl/streaming/postgres_utils.py
|
zalam003/ethereum-etl
|
2a9e468c1ec2b62c3647706d64fb9b93366ac2d1
|
[
"MIT"
] | 186
|
2018-09-13T12:39:04.000Z
|
2022-03-30T15:32:42.000Z
|
blockchainetl/streaming/postgres_utils.py
|
adidonato/ethereum-etl
|
12c5092c76b7fc319ff373e1302be8b0e39960d7
|
[
"MIT"
] | 391
|
2018-09-16T18:54:44.000Z
|
2022-03-27T10:47:48.000Z
|
from sqlalchemy.dialects.postgresql import insert
def create_insert_statement_for_table(table):
insert_stmt = insert(table)
primary_key_fields = [column.name for column in table.columns if column.primary_key]
if primary_key_fields:
insert_stmt = insert_stmt.on_conflict_do_update(
index_elements=primary_key_fields,
set_={
column.name: insert_stmt.excluded[column.name] for column in table.columns if not column.primary_key
}
)
return insert_stmt
| 31.470588
| 116
| 0.704673
|
14ffcaf0092d0535ec0c0b6ed7e425be30be7be6
| 1,607
|
tsx
|
TypeScript
|
src/components/BookFormBuildInValidation.tsx
|
ca057/react-ts-workshop-2021-06
|
930b28084b7bac68dd4cbea3b8c63f93a4a84be8
|
[
"MIT"
] | null | null | null |
src/components/BookFormBuildInValidation.tsx
|
ca057/react-ts-workshop-2021-06
|
930b28084b7bac68dd4cbea3b8c63f93a4a84be8
|
[
"MIT"
] | null | null | null |
src/components/BookFormBuildInValidation.tsx
|
ca057/react-ts-workshop-2021-06
|
930b28084b7bac68dd4cbea3b8c63f93a4a84be8
|
[
"MIT"
] | null | null | null |
import React from "react";
import "./BookFormBuildInValidation.css";
const initialState = {
title: "",
isbn: "",
};
interface BookFormBuildInValidationProps {
book?: {
title: string;
isbn: string;
};
title?: string;
handleSubmit: (values: typeof initialState) => void;
}
const BookFormBuildInValidation: React.FC<BookFormBuildInValidationProps> = ({
book,
handleSubmit,
title = "Create a new book",
}) => {
const [values, setValues] = React.useState(book ?? initialState);
const createChangeHandler =
(key: keyof typeof values) =>
(event: React.ChangeEvent<HTMLInputElement>) => {
setValues((currentValues) => ({
...currentValues,
[key]: event.target.value,
}));
};
const handleOnSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.nativeEvent.preventDefault();
handleSubmit({ ...values });
setValues(initialState);
};
return (
<form onSubmit={handleOnSubmit}>
<fieldset>
<legend>{title}</legend>
<input
type="text"
placeholder="Title"
required
value={values.title}
onChange={createChangeHandler("title")}
/>
<input
type="text"
placeholder="ISBN"
value={values.isbn}
onChange={createChangeHandler("isbn")}
required
pattern="((?:[\dX]{13})|(?:[\d\-X]{17})|(?:[\dX]{10})|(?:[\d\-X]{13}))" // taken from https://regexr.com/38pq9
/>
<button>Submit</button>
</fieldset>
</form>
);
};
export default BookFormBuildInValidation;
| 23.985075
| 120
| 0.588675
|
b733a6772639e3b43c9086ed2f36b6c4cf430371
| 5,346
|
cs
|
C#
|
Src/Shared/NetworkModelTests/Formatters/YamlFormatterTest.cs
|
210342/TPUM
|
3a0bbff983611179693ed7163516218a7443706c
|
[
"MIT"
] | null | null | null |
Src/Shared/NetworkModelTests/Formatters/YamlFormatterTest.cs
|
210342/TPUM
|
3a0bbff983611179693ed7163516218a7443706c
|
[
"MIT"
] | 15
|
2021-03-08T16:19:02.000Z
|
2021-05-26T08:26:37.000Z
|
Src/Shared/NetworkModelTests/Formatters/YamlFormatterTest.cs
|
210342/TPUM
|
3a0bbff983611179693ed7163516218a7443706c
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using TPUM.Shared.NetworkModel.Formatters;
using Xunit;
using YamlDotNet.Core;
namespace TPUM.Shared.NetworkModelTests.Formatters
{
public class YamlFormatterTest
{
public static IEnumerable<object[]> GetTestKnownTypes()
{
yield return new[] { new[] { typeof(TestEntity) }, new[] { typeof(TestEntity) } };
yield return new[] { new[] { typeof(TestEntity) }, new[] { typeof(TestEntity), typeof(TestEntity) } };
yield return new[] { new[] { typeof(TestEntity), typeof(DerivedTestEntity) }, new[] { typeof(TestEntity), typeof(DerivedTestEntity) } };
yield return new[] { new[] { typeof(TestEntity) }, null };
}
public static string BaseTag => typeof(TestEntity).FullName;
public static string DerivedTag => typeof(DerivedTestEntity).FullName;
[Fact]
public void ParameterlessConstructorTest()
{
YamlFormatter<TestEntity> yamlFormatter = new();
Assert.Equal(new[] { typeof(TestEntity) }, yamlFormatter.KnownTypes);
}
[Theory]
[MemberData(nameof(GetTestKnownTypes))]
public void ParameterfulConstructorTest(Type[] expected, Type[] types)
{
YamlFormatter<TestEntity> yamlFormatter = new(types);
Assert.Equal(expected, yamlFormatter.KnownTypes);
}
[Fact]
public void FormatTest_BaseEntity()
{
TestEntity entity = new()
{
Id = 1,
Foo = "BarBar"
};
YamlFormatter<TestEntity> sut = new();
string yaml = sut.FormatObject(entity);
Assert.NotNull(yaml);
Assert.NotEmpty(yaml);
Assert.Equal(@$"!{BaseTag}
Id: 1
Foo: BarBar
", yaml);
}
[Fact]
public void DeformatTest_BaseEntity()
{
string yaml = @$"!{BaseTag}
Id: 1
Foo: Bar
";
YamlFormatter<TestEntity> sut = new();
TestEntity result = sut.Deformat(yaml);
Assert.NotNull(result);
Assert.Equal(1, result.Id);
Assert.Equal("Bar", result.Foo);
}
[Fact]
public void FormatTest_DerivedEntity()
{
DerivedTestEntity entity = new()
{
Id = 1,
Foo = "BarBar",
Count = 3
};
YamlFormatter<TestEntity> sut_base = new();
Assert.Throws<YamlException>(() => sut_base.FormatObject(entity));
YamlFormatter<TestEntity> sut_base2 = new(new[] { typeof(TestEntity), typeof(DerivedTestEntity) });
string yaml = sut_base2.FormatObject(entity);
Assert.NotNull(yaml);
Assert.NotEmpty(yaml);
Assert.Equal(@$"!{DerivedTag}
Count: 3
Id: 1
Foo: BarBar
", yaml);
YamlFormatter<DerivedTestEntity> sut_derived = new();
yaml = sut_derived.FormatObject(entity);
Assert.NotNull(yaml);
Assert.NotEmpty(yaml);
Assert.Equal(@$"!{DerivedTag}
Count: 3
Id: 1
Foo: BarBar
", yaml);
YamlFormatter<DerivedTestEntity> sut_derived2 = new(new[] { typeof(DerivedTestEntity) });
yaml = sut_derived2.FormatObject(entity);
Assert.NotNull(yaml);
Assert.NotEmpty(yaml);
Assert.Equal(@$"!{DerivedTag}
Count: 3
Id: 1
Foo: BarBar
", yaml);
YamlFormatter<TestEntity> sut_derived3 = new(new[] { typeof(DerivedTestEntity) });
yaml = sut_derived3.FormatObject(entity);
Assert.NotNull(yaml);
Assert.NotEmpty(yaml);
Assert.Equal(@$"!{DerivedTag}
Count: 3
Id: 1
Foo: BarBar
", yaml);
}
[Fact]
public void DeformatTest_DerivedEntity()
{
string yaml = @$"!{DerivedTag}
Count: 3
Id: 1
Foo: BarBar
";
YamlFormatter<TestEntity> sut_base = new();
Assert.Throws<YamlException>(() => sut_base.Deformat(yaml));
YamlFormatter<DerivedTestEntity> sut_derived = new();
TestEntity result = sut_derived.Deformat(yaml);
Assert.NotNull(result);
Assert.Equal("BarBar", result.Foo);
Assert.IsType<DerivedTestEntity>(result);
Assert.Equal(1, result.Id);
Assert.Equal(3, (result as DerivedTestEntity).Count);
YamlFormatter<TestEntity> sut_derived2 = new(new[] { typeof(DerivedTestEntity) });
result = sut_derived2.Deformat(yaml);
Assert.NotNull(result);
Assert.IsType<DerivedTestEntity>(result);
Assert.Equal("BarBar", result.Foo);
Assert.Equal(1, result.Id);
Assert.Equal(3, (result as DerivedTestEntity).Count);
}
[Fact]
public void DeformatTest_DerivedEntityWithoutProperty()
{
string yaml = @$"!{DerivedTag}
Id: 1
Foo: BarBar
";
YamlFormatter<DerivedTestEntity> sut_derived = new();
DerivedTestEntity result = sut_derived.Deformat(yaml);
Assert.NotNull(result);
Assert.IsType<DerivedTestEntity>(result);
Assert.Equal("BarBar", result.Foo);
Assert.Equal(1, result.Id);
Assert.Equal(0, result.Count);
}
}
}
| 33.204969
| 148
| 0.575571
|
2c8c656afda05ec06559a7b74391a7a519ad3e4b
| 459
|
py
|
Python
|
src/perturbator/commands/generate_new_element.py
|
Zohaib94/perturbator
|
94d364f87d842495c5888b372514d9d7e802860d
|
[
"MIT"
] | null | null | null |
src/perturbator/commands/generate_new_element.py
|
Zohaib94/perturbator
|
94d364f87d842495c5888b372514d9d7e802860d
|
[
"MIT"
] | null | null | null |
src/perturbator/commands/generate_new_element.py
|
Zohaib94/perturbator
|
94d364f87d842495c5888b372514d9d7e802860d
|
[
"MIT"
] | null | null | null |
import click
from ..support_modules.perturbator import generate_element
@click.command()
@click.option('--element-tag', help='Tag of element, e.g. exclusiveGateway, task', required=True)
@click.option('--element-id', help='Id of the element you want to generate', required=True)
def generate_new_element(element_tag, element_id):
element = generate_element(element_tag, element_id)
click.echo('Element generated with id %s!' % element.attrib['id'])
| 41.727273
| 97
| 0.75817
|
9af8d67de593c12b3229130bb5eb6e3832ec4a54
| 29,307
|
py
|
Python
|
pyannote/audio/core/model.py
|
hadware/pyannote-audio
|
dff09d364a019dff78cafb5d52c8490ab3d937df
|
[
"MIT"
] | 1
|
2022-02-23T08:46:10.000Z
|
2022-02-23T08:46:10.000Z
|
pyannote/audio/core/model.py
|
hadware/pyannote-audio
|
dff09d364a019dff78cafb5d52c8490ab3d937df
|
[
"MIT"
] | null | null | null |
pyannote/audio/core/model.py
|
hadware/pyannote-audio
|
dff09d364a019dff78cafb5d52c8490ab3d937df
|
[
"MIT"
] | null | null | null |
# MIT License
#
# Copyright (c) 2020-2021 CNRS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
import os
import warnings
from importlib import import_module
from pathlib import Path
from typing import Any, Dict, List, Optional, Text, Tuple, Union
from urllib.parse import urlparse
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.optim
from huggingface_hub import cached_download, hf_hub_url
from pytorch_lightning.core.memory import ModelSummary
from pytorch_lightning.utilities.cloud_io import load as pl_load
from semver import VersionInfo
from torch.utils.data import DataLoader
from pyannote.audio import __version__
from pyannote.audio.core.io import Audio
from pyannote.audio.core.task import Problem, Resolution, Specifications, Task
from pyannote.core import SlidingWindow
CACHE_DIR = os.getenv(
"PYANNOTE_CACHE",
os.path.expanduser("~/.cache/torch/pyannote"),
)
HF_PYTORCH_WEIGHTS_NAME = "pytorch_model.bin"
HF_LIGHTNING_CONFIG_NAME = "config.yaml"
class Introspection:
"""Model introspection
Parameters
----------
min_num_samples: int
Minimum number of input samples
min_num_frames: int
Corresponding minimum number of output frames
inc_num_samples: int
Number of input samples leading to an increase of number of output frames
inc_num_frames: int
Corresponding increase in number of output frames
dimension: int
Output dimension
sample_rate: int
Expected input sample rate
Usage
-----
>>> introspection = Introspection.from_model(model)
>>> isinstance(introspection.frames, SlidingWindow)
>>> num_samples = 16000 # 1s at 16kHz
>>> num_frames, dimension = introspection(num_samples)
"""
def __init__(
self,
min_num_samples: int,
min_num_frames: int,
inc_num_samples: int,
inc_num_frames: int,
dimension: int,
sample_rate: int,
):
super().__init__()
self.min_num_samples = min_num_samples
self.min_num_frames = min_num_frames
self.inc_num_samples = inc_num_samples
self.inc_num_frames = inc_num_frames
self.dimension = dimension
self.sample_rate = sample_rate
@classmethod
def from_model(cls, model: "Model", task: str = None) -> Introspection:
specifications = model.specifications
if task is not None:
specifications = specifications[task]
example_input_array = model.example_input_array
batch_size, num_channels, num_samples = example_input_array.shape
example_input_array = torch.randn(
(batch_size, num_channels, num_samples),
dtype=example_input_array.dtype,
layout=example_input_array.layout,
device=example_input_array.device,
requires_grad=False,
)
# dichotomic search of "min_num_samples"
lower, upper, min_num_samples = 1, num_samples, None
while True:
num_samples = (lower + upper) // 2
try:
with torch.no_grad():
frames = model(example_input_array[:, :, :num_samples])
if task is not None:
frames = frames[task]
except Exception:
lower = num_samples
else:
min_num_samples = num_samples
if specifications.resolution == Resolution.FRAME:
_, min_num_frames, dimension = frames.shape
elif specifications.resolution == Resolution.CHUNK:
_, dimension = frames.shape
else:
# should never happen
pass
upper = num_samples
if lower + 1 == upper:
break
# if "min_num_samples" is still None at this point, it means that
# the forward pass always failed and raised an exception. most likely,
# it means that there is a problem with the model definition.
# we try again without catching the exception to help the end user debug
# their model
if min_num_samples is None:
frames = model(example_input_array)
# corner case for chunk-level tasks
if specifications.resolution == Resolution.CHUNK:
return cls(
min_num_samples=min_num_samples,
min_num_frames=1,
inc_num_samples=0,
inc_num_frames=0,
dimension=dimension,
sample_rate=model.hparams.sample_rate,
)
# search reasonable upper bound for "inc_num_samples"
while True:
num_samples = 2 * min_num_samples
example_input_array = torch.randn(
(batch_size, num_channels, num_samples),
dtype=example_input_array.dtype,
layout=example_input_array.layout,
device=example_input_array.device,
requires_grad=False,
)
with torch.no_grad():
frames = model(example_input_array)
if task is not None:
frames = frames[task]
num_frames = frames.shape[1]
if num_frames > min_num_frames:
break
# dichotomic search of "inc_num_samples"
lower, upper = min_num_samples, num_samples
while True:
num_samples = (lower + upper) // 2
example_input_array = torch.randn(
(batch_size, num_channels, num_samples),
dtype=example_input_array.dtype,
layout=example_input_array.layout,
device=example_input_array.device,
requires_grad=False,
)
with torch.no_grad():
frames = model(example_input_array)
if task is not None:
frames = frames[task]
num_frames = frames.shape[1]
if num_frames > min_num_frames:
inc_num_frames = num_frames - min_num_frames
inc_num_samples = num_samples - min_num_samples
upper = num_samples
else:
lower = num_samples
if lower + 1 == upper:
break
return cls(
min_num_samples=min_num_samples,
min_num_frames=min_num_frames,
inc_num_samples=inc_num_samples,
inc_num_frames=inc_num_frames,
dimension=dimension,
sample_rate=model.hparams.sample_rate,
)
def __call__(self, num_samples: int) -> Tuple[int, int]:
"""Predict output shape, given number of input samples
Parameters
----------
num_samples : int
Number of input samples.
Returns
-------
num_frames : int
Number of output frames
dimension : int
Dimension of output frames
"""
if num_samples < self.min_num_samples:
return 0, self.dimension
return (
self.min_num_frames
+ self.inc_num_frames
* ((num_samples - self.min_num_samples + 1) // self.inc_num_samples),
self.dimension,
)
@property
def frames(self) -> SlidingWindow:
# HACK to support model trained before 'sample_rate' was an Introspection attribute
sample_rate = getattr(self, "sample_rate", 16000)
step = (self.inc_num_samples / self.inc_num_frames) / sample_rate
return SlidingWindow(start=0.0, step=step, duration=step)
class Model(pl.LightningModule):
"""Base model
Parameters
----------
sample_rate : int, optional
Audio sample rate. Defaults to 16kHz (16000).
num_channels : int, optional
Number of channels. Defaults to mono (1).
task : Task, optional
Task addressed by the model.
"""
def __init__(
self,
sample_rate: int = 16000,
num_channels: int = 1,
task: Optional[Task] = None,
):
super().__init__()
assert (
num_channels == 1
), "Only mono audio is supported for now (num_channels = 1)"
self.save_hyperparameters("sample_rate", "num_channels")
self.task = task
self.audio = Audio(
sample_rate=self.hparams.sample_rate, mono=self.hparams.num_channels == 1
)
@property
def example_input_array(self) -> torch.Tensor:
batch_size = 3 if self.task is None else self.task.batch_size
duration = 2.0 if self.task is None else self.task.duration
return torch.randn(
(
batch_size,
self.hparams.num_channels,
int(self.hparams.sample_rate * duration),
),
device=self.device,
)
@property
def task(self):
return self._task
@task.setter
def task(self, task):
self._task = task
del self.introspection
del self.specifications
@property
def specifications(self):
if self.task is not None:
return self.task.specifications
return self._specifications
@specifications.setter
def specifications(self, specifications):
self._specifications = specifications
@specifications.deleter
def specifications(self):
if hasattr(self, "_specifications"):
del self._specifications
def build(self):
# use this method to add task-dependent layers to the model
# (e.g. the final classification and activation layers)
pass
@property
def introspection(self) -> Introspection:
"""Introspection
Returns
-------
introspection: Introspection
Model introspection
"""
if not hasattr(self, "_introspection"):
self._introspection = Introspection.from_model(self)
return self._introspection
@introspection.setter
def introspection(self, introspection):
self._introspection = introspection
@introspection.deleter
def introspection(self):
if hasattr(self, "_introspection"):
del self._introspection
def setup(self, stage=None):
if stage == "fit":
self.task.setup()
# list of layers before adding task-dependent layers
before = set((name, id(module)) for name, module in self.named_modules())
# add task-dependent layers (e.g. final classification layer)
# and re-use original weights when compatible
original_state_dict = self.state_dict()
self.build()
try:
missing_keys, unexpected_keys = self.load_state_dict(
original_state_dict, strict=False
)
except RuntimeError as e:
if "size mismatch" in str(e):
msg = (
"Model has been trained for a different task. For fine tuning or transfer learning, "
"it is recommended to train task-dependent layers for a few epochs "
f"before training the whole model: {self.task_dependent}."
)
warnings.warn(msg)
else:
raise e
# move layers that were added by build() to same device as the rest of the model
for name, module in self.named_modules():
if (name, id(module)) not in before:
module.to(self.device)
# add (trainable) loss function (e.g. ArcFace has its own set of trainable weights)
if stage == "fit":
# let task know about the model
self.task.model = self
# setup custom loss function
self.task.setup_loss_func()
# setup custom validation metrics
validation_metric = self.task.setup_validation_metric()
if validation_metric is not None:
self.validation_metric = validation_metric
self.validation_metric.to(self.device)
# this is to make sure introspection is performed here, once and for all
_ = self.introspection
# list of layers after adding task-dependent layers
after = set((name, id(module)) for name, module in self.named_modules())
# list of task-dependent layers
self.task_dependent = list(name for name, _ in after - before)
def on_save_checkpoint(self, checkpoint):
# put everything pyannote.audio-specific under pyannote.audio
# to avoid any future conflicts with pytorch-lightning updates
checkpoint["pyannote.audio"] = {
"versions": {
"torch": torch.__version__,
"pyannote.audio": __version__,
},
"architecture": {
"module": self.__class__.__module__,
"class": self.__class__.__name__,
},
"introspection": self.introspection,
"specifications": self.specifications,
}
@staticmethod
def check_version(library: Text, theirs: Text, mine: Text):
theirs = VersionInfo.parse(theirs)
mine = VersionInfo.parse(mine)
if theirs.major != mine.major:
warnings.warn(
f"Model was trained with {library} {theirs}, yours is {mine}. "
f"Bad things will probably happen unless you update {library} to {theirs.major}.x."
)
if theirs.minor > mine.minor:
warnings.warn(
f"Model was trained with {library} {theirs}, yours is {mine}. "
f"This should be OK but you might want to update {library}."
)
def on_load_checkpoint(self, checkpoint: Dict[str, Any]):
self.check_version(
"pyannote.audio",
checkpoint["pyannote.audio"]["versions"]["pyannote.audio"],
__version__,
)
self.check_version(
"torch",
checkpoint["pyannote.audio"]["versions"]["torch"],
torch.__version__,
)
self.check_version(
"pytorch-lightning", checkpoint["pytorch-lightning_version"], pl.__version__
)
self.specifications = checkpoint["pyannote.audio"]["specifications"]
self.setup()
self.introspection = checkpoint["pyannote.audio"]["introspection"]
def forward(self, waveforms: torch.Tensor) -> torch.Tensor:
msg = "Class {self.__class__.__name__} should define a `forward` method."
raise NotImplementedError(msg)
def helper_default_activation(self, specifications: Specifications) -> nn.Module:
"""Helper function for default_activation
Parameters
----------
specifications: Specifications
Task specification.
Returns
-------
activation : nn.Module
Default activation function.
"""
if specifications.problem == Problem.BINARY_CLASSIFICATION:
return nn.Sigmoid()
elif specifications.problem == Problem.MONO_LABEL_CLASSIFICATION:
return nn.LogSoftmax(dim=-1)
elif specifications.problem == Problem.MULTI_LABEL_CLASSIFICATION:
return nn.Sigmoid()
else:
msg = "TODO: implement default activation for other types of problems"
raise NotImplementedError(msg)
# convenience function to automate the choice of the final activation function
def default_activation(self) -> nn.Module:
"""Guess default activation function according to task specification
* sigmoid for binary classification
* log-softmax for regular multi-class classification
* sigmoid for multi-label classification
Returns
-------
activation : nn.Module
Activation.
"""
return self.helper_default_activation(self.specifications)
# training data logic is delegated to the task because the
# model does not really need to know how it is being used.
def train_dataloader(self) -> DataLoader:
return self.task.train_dataloader()
# training step logic is delegated to the task because the
# model does not really need to know how it is being used.
def training_step(self, batch, batch_idx):
return self.task.training_step(batch, batch_idx)
# validation data logic is delegated to the task because the
# model does not really need to know how it is being used.
def val_dataloader(self) -> DataLoader:
return self.task.val_dataloader()
# validation logic is delegated to the task because the
# model does not really need to know how it is being used.
def validation_step(self, batch, batch_idx):
return self.task.validation_step(batch, batch_idx)
def validation_epoch_end(self, outputs):
return self.task.validation_epoch_end(outputs)
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=1e-3)
def _helper_up_to(
self, module_name: Text, requires_grad: bool = False
) -> List[Text]:
"""Helper function for freeze_up_to and unfreeze_up_to"""
tokens = module_name.split(".")
updated_modules = list()
for name, module in ModelSummary(self, max_depth=-1).named_modules:
name_tokens = name.split(".")
matching_tokens = list(
token
for token, other_token in zip(name_tokens, tokens)
if token == other_token
)
# if module is A.a.1 & name is A.a, we do not want to freeze the whole A.a module
# because it might contain other modules like A.a.2 and A.a.3
if matching_tokens and len(matching_tokens) == len(tokens) - 1:
continue
for parameter in module.parameters(recurse=True):
parameter.requires_grad = requires_grad
module.train(mode=requires_grad)
updated_modules.append(name)
# stop once we reached the requested module
if module_name == name:
break
if module_name not in updated_modules:
raise ValueError(f"Could not find module {module_name}")
return updated_modules
def freeze_up_to(self, module_name: Text) -> List[Text]:
"""Freeze model up to specific module
Parameters
----------
module_name : str
Name of module (included) up to which the model will be frozen.
Returns
-------
frozen_modules : list of str
List of names of frozen modules
Raises
------
ValueError when requested module does not exist
Note
----
The order of modules is the one reported by self.summary("full").
If your model does not follow a sequential structure, you might
want to use freeze_by_name for more control.
"""
return self._helper_up_to(module_name, requires_grad=False)
def unfreeze_up_to(self, module_name: Text) -> List[Text]:
"""Unfreeze model up to specific module
Parameters
----------
module_name : str
Name of module (included) up to which the model will be unfrozen.
Returns
-------
unfrozen_modules : list of str
List of names of frozen modules
Raises
------
ValueError when requested module does not exist
Note
----
The order of modules is the one reported by self.summary("full").
If your model does not follow a sequential structure, you might
want to use freeze_by_name for more control.
"""
return self._helper_up_to(module_name, requires_grad=True)
def _helper_by_name(
self,
modules: Union[List[Text], Text],
recurse: bool = True,
requires_grad: bool = False,
) -> List[Text]:
"""Helper function for freeze_by_name and unfreeze_by_name"""
updated_modules = list()
# Force modules to be a list
if isinstance(modules, str):
modules = [modules]
for name, module in ModelSummary(self, max_depth=-1).named_modules:
if name not in modules:
continue
for parameter in module.parameters(recurse=True):
parameter.requires_grad = requires_grad
module.train(requires_grad)
# keep track of updated modules
updated_modules.append(name)
missing = list(set(modules) - set(updated_modules))
if missing:
raise ValueError(f"Could not find the following modules: {missing}.")
return updated_modules
def freeze_by_name(
self,
modules: Union[Text, List[Text]],
recurse: bool = True,
) -> List[Text]:
"""Freeze modules
Parameters
----------
modules : list of str, str
Name(s) of modules to freeze
recurse : bool, optional
If True (default), freezes parameters of these modules and all submodules.
Otherwise, only freezes parameters that are direct members of these modules.
Returns
-------
frozen_modules: list of str
Names of frozen modules
Raises
------
ValueError if at least one of `modules` does not exist.
"""
return self._helper_by_name(
modules,
recurse=recurse,
requires_grad=False,
)
def unfreeze_by_name(
self,
modules: Union[List[Text], Text],
recurse: bool = True,
) -> List[Text]:
"""Unfreeze modules
Parameters
----------
modules : list of str, str
Name(s) of modules to unfreeze
recurse : bool, optional
If True (default), unfreezes parameters of these modules and all submodules.
Otherwise, only unfreezes parameters that are direct members of these modules.
Returns
-------
unfrozen_modules: list of str
Names of unfrozen modules
Raises
------
ValueError if at least one of `modules` does not exist.
"""
return self._helper_by_name(modules, recurse=recurse, requires_grad=True)
@classmethod
def from_pretrained(
cls,
checkpoint: Union[Path, Text],
map_location=None,
hparams_file: Union[Path, Text] = None,
strict: bool = True,
use_auth_token: Union[Text, None] = None,
cache_dir: Union[Path, Text] = CACHE_DIR,
**kwargs,
) -> "Model":
"""Load pretrained model
Parameters
----------
checkpoint : Path or str
Path to checkpoint, or a remote URL, or a model identifier from
the huggingface.co model hub.
map_location: optional
Same role as in torch.load().
Defaults to `lambda storage, loc: storage`.
hparams_file : Path or str, optional
Path to a .yaml file with hierarchical structure as in this example:
drop_prob: 0.2
dataloader:
batch_size: 32
You most likely won’t need this since Lightning will always save the
hyperparameters to the checkpoint. However, if your checkpoint weights
do not have the hyperparameters saved, use this method to pass in a .yaml
file with the hparams you would like to use. These will be converted
into a dict and passed into your Model for use.
strict : bool, optional
Whether to strictly enforce that the keys in checkpoint match
the keys returned by this module’s state dict. Defaults to True.
use_auth_token : str, optional
When loading a private huggingface.co model, set `use_auth_token`
to True or to a string containing your hugginface.co authentication
token that can be obtained by running `huggingface-cli login`
cache_dir: Path or str, optional
Path to model cache directory. Defaults to content of PYANNOTE_CACHE
environment variable, or "~/.cache/torch/pyannote" when unset.
kwargs: optional
Any extra keyword args needed to init the model.
Can also be used to override saved hyperparameter values.
Returns
-------
model : Model
Model
See also
--------
torch.load
"""
# pytorch-lightning expects str, not Path.
checkpoint = str(checkpoint)
if hparams_file is not None:
hparams_file = str(hparams_file)
# resolve the checkpoint to
# something that pl will handle
if os.path.isfile(checkpoint):
path_for_pl = checkpoint
elif urlparse(checkpoint).scheme in ("http", "https"):
path_for_pl = checkpoint
else:
# Finally, let's try to find it on Hugging Face model hub
# e.g. julien-c/voice-activity-detection is a valid model id
# and julien-c/voice-activity-detection@main supports specifying a commit/branch/tag.
if "@" in checkpoint:
model_id = checkpoint.split("@")[0]
revision = checkpoint.split("@")[1]
else:
model_id = checkpoint
revision = None
url = hf_hub_url(
model_id, filename=HF_PYTORCH_WEIGHTS_NAME, revision=revision
)
path_for_pl = cached_download(
url=url,
library_name="pyannote",
library_version=__version__,
cache_dir=cache_dir,
use_auth_token=use_auth_token,
)
# HACK Huggingface download counters rely on config.yaml
# HACK Therefore we download config.yaml even though we
# HACK do not use it. Fails silently in case model does not
# HACK have a config.yaml file.
try:
config_url = hf_hub_url(
model_id, filename=HF_LIGHTNING_CONFIG_NAME, revision=revision
)
_ = cached_download(
url=config_url,
library_name="pyannote",
library_version=__version__,
cache_dir=cache_dir,
use_auth_token=use_auth_token,
)
except Exception:
pass
if map_location is None:
def default_map_location(storage, loc):
return storage
map_location = default_map_location
# obtain model class from the checkpoint
loaded_checkpoint = pl_load(path_for_pl, map_location=map_location)
module_name: str = loaded_checkpoint["pyannote.audio"]["architecture"]["module"]
module = import_module(module_name)
class_name: str = loaded_checkpoint["pyannote.audio"]["architecture"]["class"]
Klass = getattr(module, class_name)
try:
model = Klass.load_from_checkpoint(
path_for_pl,
map_location=map_location,
hparams_file=hparams_file,
strict=strict,
**kwargs,
)
except RuntimeError as e:
if "loss_func" in str(e):
msg = (
"Model has been trained with a task-dependent loss function. "
"Set 'strict' to False to load the model without its loss function "
"and prevent this warning from appearing. "
)
warnings.warn(msg)
model = Klass.load_from_checkpoint(
path_for_pl,
map_location=map_location,
hparams_file=hparams_file,
strict=False,
**kwargs,
)
return model
raise e
return model
| 34.31733
| 105
| 0.600403
|
740d7137f3e123335901ae3f2ad7721c4f285da6
| 15,790
|
css
|
CSS
|
css/style.css
|
smartlogistic/Game1
|
7eb4978d8e013ad7c4bf4058b699c5331b367447
|
[
"CC-BY-3.0"
] | null | null | null |
css/style.css
|
smartlogistic/Game1
|
7eb4978d8e013ad7c4bf4058b699c5331b367447
|
[
"CC-BY-3.0"
] | null | null | null |
css/style.css
|
smartlogistic/Game1
|
7eb4978d8e013ad7c4bf4058b699c5331b367447
|
[
"CC-BY-3.0"
] | null | null | null |
/*
Author: W3layout
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
*//* reset */
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,dl,dt,dd,ol,nav ul,nav li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;}
article, aside, details, figcaption, figure,footer, header, hgroup, menu, nav, section {display: block;}
ol,ul{list-style:none;margin:0px;padding:0px;}
blockquote,q{quotes:none;}
blockquote:before,blockquote:after,q:before,q:after{content:'';content:none;}
table{border-collapse:collapse;border-spacing:0;}
/* start editing from here */
a{text-decoration:none;}
.txt-rt{text-align:right;}/* text align right */
.txt-lt{text-align:left;}/* text align left */
.txt-center{text-align:center;}/* text align center */
.float-rt{float:right;}/* float right */
.float-lt{float:left;}/* float left */
.clear{clear:both;}/* clear float */
.pos-relative{position:relative;}/* Position Relative */
.pos-absolute{position:absolute;}/* Position Absolute */
.vertical-base{ vertical-align:baseline;}/* vertical align baseline */
.vertical-top{ vertical-align:top;}/* vertical align top */
.underline{ padding-bottom:5px; border-bottom: 1px solid #eee; margin:0 0 20px 0;}/* Add 5px bottom padding and a underline */
nav.vertical ul li{ display:block;}/* vertical menu */
nav.horizontal ul li{ display: inline-block;}/* horizontal menu */
img{max-width:100%;}
/*end reset*/
@font-face{
font-family: "Abel-Regular";
src:url(../fonts/Abel-Regular.ttf);
}
@font-face{
font-family: "BlackOpsOne-Regular";
src:url(../fonts/BlackOpsOne-Regular.ttf);
}
body{
width:100%;
text-align:center;
font-family: "Abel-Regular";
}
.navbar-default {
background-color: #0C0808;
border: none;
}
.navbar-inverse .navbar-nav>li>a {
color: #fff;
font-size:18px;
padding-top: 22px;
text-decoration: none;
}
.navbar-inverse .navbar-nav>li>a:hover {
color:yellow;
}
.banner{
background:url("../images/bg.jpg" ) 0px 0px no-repeat;
width:100%;
height:800px;
background-size:cover;
}
.banner-content{
width:570px;
padding-top:200px;
text-align:left;
color:#fff;
}
.banner-content h1{
font-family: "BlackOpsOne-Regular";
font-size:60px;
}
.banner-content h2{
font-family: "Abel-Regular";
font-size:32px;
}
.banner-content p{
font-family: "Abel-Regular";
font-size:20px;
padding-top:15px;
line-height:30px;
}
/* ----------Header Ends Here ---------- */
/* ----------About---------- */
.about{
padding:115px 0;
font-family: "Abel-Regular";
}
.about h3{
padding:25px 0;
font-size:38px;
font-family: "Abel-Regular";
font-weight:800;
}
.about span{
color:red;
}
.about h4{
padding:0px 125px;
font-size:20px;
line-height:30px;
}
.about p{
padding:0px 125px;
font-size:20px;
line-height:28px;
}
.about-image{
padding-top:35px;
display:block;
}
.about-image h5{
font-size:22px;
padding:15px 0 0 0;
font-weight:600;
}
.about-image p{
padding:15px 20px 0 20px;
font-size:18px;
line-height:28px;
}
.shadow
{
position: relative;
}
.shadow:before, .shadow:after
{
z-index: -1;
position: absolute;
content: "";
bottom: 14px;
left: 10px;
width: 50%;
top: 80%;
max-width:300px;
background: #fff;
box-shadow: 0 15px 10px #000;
transform: rotate(-3deg);
}
.shadow:after
{
transform: rotate(3deg);
right: 10px;
left: auto;
}
/* ---------- About Ends here ---------- */
/* ---------- Requirements Starts ---------- */
.requirement{
background:url("../images/require.jpg" ) 0px 0px no-repeat;
width:100%;
background-size:cover;
font-family: "Abel-Regular";
}
.all-require{
padding:150px 0;
}
.heading{
margin:0 auto;
padding-bottom:50px;
color:#fff;
}
.heading h3{
padding:25px 0;
font-size:38px;
font-family: "Abel-Regular";
font-weight:800;
color:#f7de29;
}
.heading span{
color:#cfd5f7;
}
.grid{
background:rgba(41, 40, 40, 0.7);
padding:50px 0;
height:475px;
}
.grid i {
display: inline-block;
width: 64px;
height: 64px;
background: url("../images/icons.png") no-repeat 0px 0px;
padding-bottom: 75px;
text-decoration: none;
}
.grid i.pc {
background-position: 0px 0px;
}
.grid i.xbox {
background-position: -64px 0px;
}
.grid i.ps {
background-position: -128px 0px;
}
.grid p{
color:#fff;
padding:5px 25px;
text-align:left;
font-size:20px;
}
.grid h5{
color:#fff;
font-size:22px;
text-align:left;
padding:5px 25px;
font-weight:600;
}
.grid-bottom{
padding-top:30px;
}
.grid span{
font-size:16px;
color:rgba(239, 239, 243, 0.83);
}
/* ---------- Requirements Ends here ---------- */
/* ---------- UP Coming Games Starts Here ---------- */
.background {
padding:15px 5px 15px 15px;
background:#212020;
}
.padding-upcoming{
padding:130px 0;
font-family: "Abel-Regular";
}
.padding-upcoming h3{
padding:25px 0;
font-size:38px;
font-family: "Abel-Regular";
font-weight:800;
}
.padding-upcoming span{
color:red;
}
.trailer iframe {
width: 100%;
height: 387px;
}
.trailer {
padding-left: 0;
}
.sub-img {
width:34%;
float: left;
}
.sub-img img{
width:82%;
}
.sub-text {
padding-top:15px;
float:right;
width:60%;
margin:0px;
}
.sub-text h4 {
font-size:20px;
color: #5bb2fc;
line-height: 28px;
text-decoration:none;
display: block;
text-align:left;
}
.sub-text p {
font-size: 14px;
line-height: 20px;
color: #888;
margin-top: 8px;
}
.sub-trailer {
background: #212020;
}
.shadow1
{
position: relative;
}
.shadow1:before, .shadow1:after
{
z-index: -1;
position: absolute;
content: "";
bottom: 14px;
left: 10px;
width: 50%;
top: 80%;
max-width:300px;
background: #fff;
box-shadow: 0 15px 10px #000;
transform: rotate(-3deg);
}
.shadow1:after
{
transform: rotate(3deg);
right: 10px;
left: auto;
}
/* ---------- UP Coming Games Ends Here ---------- */
/* ---------- Our Team Starts Here ---------- */
.our-team{
background:#D6D3D3;
}
.team{
padding:125px 0;
font-family: "Abel-Regular";
}
.team h3{
padding:25px 0;
font-size:38px;
font-family: "Abel-Regular";
font-weight:800;
}
.team h4{
font-size:22px;
padding-top:6px;
font-weight:600;
}
.team p{
font-size:18px;
padding-top:3px;
}
.team-img img{
border-radius: 25px 25px 25px 25px;
-moz-border-radius: 25px 25px 25px 25px;
-webkit-border-radius: 25px 25px 25px 25px;
border:7px solid #dddbdb;
}
.team-bottom{
padding-top:40px;
}
/* ---------- Our Team Ends Here ---------- */
/* ---------- Contact Starts From Here ---------- */
.contact{
background:#1d1d1c;
}
.padding-contact{
padding:100px 0;
font-family: "Abel-Regular";
}
.padding-contact h3{
font-family: "BlackOpsOne-Regular";
font-size:24px;
padding-bottom:20px;
color:#5bb2fc;
letter-spacing: 3px;
text-align:left;
}
.padding-contact span{
color:yellow;
display:block;
padding-top:10px;
}
address{
font-size:16px;
color:#fff;
text-align:left;
line-height:24px;
}
.social{
padding-top:45px;
}
.social-icons h3{
text-align:center;
}
ul.social li {
display: inline-block;
}
ul.social li a {
display: inline-block;
width: 50px;
height: 50px;
background: url("../images/img-sprite.png") no-repeat 0px 0px;
transition:0.5s all;
-webkit-transition:0.5s all;
-moz-transition:0.5s all;
-o-transition:0.5s all;
-ms-transition:0.5s all;
text-decoration: none;
}
ul.social li a.facebook {
background-position: 0px 0px;
}
ul.social li a.facebook:hover {
background-position: 0px -50px;
}
ul.social li a.twitter {
background-position: -50px 0px;
}
ul.social li a.twitter:hover {
background-position: -50px -50px;
}
ul.social li a.googleplus {
background-position: -100px 0px;
}
ul.social li a.googleplus:hover {
background-position: -100px -50px;
}
ul.social li a.instagram {
background-position: -150px 0px;
}
ul.social li a.instagram:hover {
background-position: -150px -50px;
}
ul.social li a.youtube {
background-position: -200px 0px;
}
ul.social li a.youtube:hover {
background-position: -200px -50px;
}
.newsletter h3{
text-align:right;
}
.newsletter input[type="text"]{
outline: none;
font-size:16px;
color: #fff;
font-family: "Abel-Regular";
padding: 15px 10px;
border:none;
border-bottom:2px solid #fff;
width: 67%;
background:#1d1d1c;
}
.newsletter input[type="submit"] {
background:rgba(2, 2, 2, 0.60);
color: #fff;
border: 2px solid #fff;
font-size: 18px;
font-family: "Abel-Regular";
padding: 15px 10px 15px 15px;
cursor: pointer;
outline: none;
display: inline-block;
margin-top:24px;
transition: 0.5s all;
-webkit-transition: 0.5s all;
-moz-transition: 0.5s all;
-o-transition: 0.5s all;
-ms-transition: 0.5s all;
}
.newsletter input[type="submit"]:hover{
color:#000;
background:#d8cc52;
font-weight:600;
}
/* ---------- Contact Ends here ---------- */
.footer{
padding:0px 20px 50px 20px;
}
.footer p{
font-size:18px;
font-family: "Abel-Regular";
color:#fff;
}
.footer a{
text-decoration:none;
color:#5bb2fc;
}
.footer a:hover{
color:yellow;
}
/*---------- responsive media queries ----------*/
@media screen and (max-width:1920px){
.banner-content{
width:500px;
}
}
@media screen and (max-width:1680px){
.banner-content{
}
}
@media screen and (max-width:1440px){
.banner-content{
width:470px;
}
}
@media screen and (max-width:1366px){
.banner-content{
width:470px;
padding-top:150px;
}
.newsletter input[type="text"] {
width: 60%
}
}
@media screen and (max-width:1280px){
.banner-content{
padding-top:125px;
}
}
@media screen and (max-width:1080px){
.banner{
height:500px;
}
.banner-content h1 {
font-size: 56px;
}
.banner-content h2 {
font-size: 30px;
}
.banner-content p {
font-size: 19px;
}
.about {
padding:50px 0 70px;
}
.all-require {
padding: 100px 0;
}
.padding-upcoming {
padding: 75px 0;
}
.about h4 {
padding: 0px 100px;
}
.trailer-text{
padding-top:37px;
}
.sub-text {
width: 64%;
}
.sub-text p {
text-align:left;
}
form{
padding-top:10px;
}
.about-image p {
padding: 10px 0px 0;
}
}
@media screen and (max-width:991px){
.navbar-inverse .navbar-nav>li>a {
padding: 0px 10px;
padding-top: 22px;
}
.about h4 {
padding: 0px 40px;
}
.about-size{
width:33.3%;
float:left;
}
.about-image p {
font-size: 16px;
line-height: 24px;
}
.require-size{
width:33.3%;
float:left;
margin: 0px;
padding: 5px;
}
.grid p {
padding: 5px 20px;
}
.game-video {
width: 60%;
float: left;
}
.game-image{
width:40%;
float:left;
}
.trailer-text {
padding-top: 15px;
}
.sub-trailer {
padding:10px 0;
}
.sub-img {
width: 38%;
}
.sub-img img {
width: 100%;
}
.sub-text {
padding-top: 5px;
width:60%;
}
.sub-text h4 {
font-size:19px;
line-height: 24px;
}
.sub-text p {
font-size: 14px;
line-height: 18px;
}
.team-size{
width:25%;
float:left;
}
.team h4 {
font-size: 20px;
}
.team p {
font-size: 16px;
}
.address{
width:25%;
float:left;
margin:0;
padding:0px;
}
.social-icons{
width:40%;
float:left;
margin:0;
padding:0px;
}
ul.social li a {
width: 40px;
height: 40px;
background-size: 250px;
}
ul.social li a.facebook {
background-position: 0px 0px;
}
ul.social li a.facebook:hover {
background-position: 0px -40px;
}
ul.social li a.twitter {
background-position: -40px 0px;
}
ul.social li a.twitter:hover {
background-position: -40px -40px;
}
ul.social li a.googleplus {
background-position: -83px 0px;
}
ul.social li a.googleplus:hover {
background-position: -83px -40px;
}
ul.social li a.instagram {
background-position: -126px 0px;
}
ul.social li a.instagram:hover {
background-position: -126px -40px;
}
ul.social li a.youtube {
background-position: -167px 0px;
}
ul.social li a.youtube:hover {
background-position: -167px -40px;
}
.newsletter{
width:35%;
float:left;
margin:0;
padding:0px;
}
.newsletter input[type="text"] {
padding:10px;
}
.newsletter input[type="submit"] {
font-size: 16px;
padding: 10px;
}
}
@media screen and (max-width:800px){
.navbar-brand>img {
width:90%;
}
}
@media screen and (max-width:768px){
.banner-content {
width: 380px;
padding-top: 125px;
}
.banner-content h1 {
font-size: 46px;
}
.banner-content h2 {
font-size: 26px;
}
.banner-content p {
font-size: 17px;
}
.about {
padding: 50px 0;
}
.about h3 {
font-size: 30px;
}
.about h4 {
font-size:17px;
line-height: 24px;
padding: 0px 10px;
}
.all-require {
padding:75px 0;
}
.heading h3 {
font-size: 30px;
}
.require-size {
padding: 2px;
}
.grid {
height: 485px;
}
.grid i {
width: 57px;
background-size: 175px;
}
.grid i.xbox {
background-position: -55px 0px;
}
grid i.ps {
background-position: -111px 0px;
}
.padding-upcoming h3 {
font-size: 34px;
}
.game-video {
width:100%;
}
.sub-trailer {
padding:0;
}
.sub-img {
width: 20%;
}
.sub-text {
padding-top: 40px;
width: 70%;
}
.sub-text h4 {
font-size: 24px;
}
.team {
padding: 75px 0;
}
.padding-contact h3 {
font-size: 22px;
}
}
@media screen and (max-width:736px){
.grid-bottom {
padding-top: 15px;
}
.padding-contact {
padding: 70px 0;
}
.footer p {
font-size: 16px;
}
}
@media screen and (max-width:667px){
.banner {
height: 400px;
}
.banner-content {
padding-top:75px;
}
.shadow:before, .shadow:after {
bottom: 18px;
}
.require-size {
padding: 10px;
width: 50%;
}
.grid:nth-child(3) {
height: 430px;
}
.require-size:nth-child(3) {
padding: 10px;
width: 50%;
margin-left:25%;
}
.grid i.xbox {
background-position: -56px 0px;
}
.grid i.ps {
background-position: -113px 0px;
}
.team h3 {
font-size: 32px;
}
.about-image p {
font-size: 14px;
line-height: 22px;
}
.padding-contact span {
font-size:15px;
}
}
@media screen and (max-width:640px){
.newsletter input[type="text"] {
width: 80%;
text-align: center;
}
.newsletter input[type="submit"] {
margin-top:5px;
}
}
@media screen and (max-width:600px){
.team h4 {
font-size: 18px;
}
.team p {
font-size: 14px;
}
.padding-contact span {
font-size: 13px;
}
}
@media screen and (max-width:480px){
.banner {
height: 350px;
}
.banner-content h1 {
font-size: 40px;
}
.banner-content h2 {
font-size: 22px;
}
.banner-content p {
font-size: 15px;
}
.about {
padding: 40px 0;
}
.about-size {
width:100%;
}
.about-size:nth-child(2) {
padding:40px 0px;
}
.about-image h5 {
padding-top:5px;
}
.about-image p {
padding-top:5px;
line-height: 20px;
}
.require-size {
width: 100%;
}
.grid{
height: 435px;
}
.grid p {
padding-left:50px;
}
.grid h5 {
padding-left:50px;
}
.require-size:nth-child(3) {
width: 100%;
margin-left:0%;
}
.sub-text {
padding-top: 10px;
}
.sub-text h4 {
font-size: 20px;
}
.team-size {
width: 50%;
float: left;
padding:10px 0;
}
.team-bottom {
padding-top: 0px;
}
.address {
width: 44%;
padding: 10px;
}
.social-icons {
width: 56%;
padding:10px;
}
.newsletter {
width: 80%;
float:none;
display: inline-block;
}
.newsletter input[type="text"] {
width: 60%;
}
}
@media screen and (max-width:414px){
.about {
padding: 25px 0;
}
.about h3 {
padding: 10px 0;
}
.about-image {
padding-top: 20px;
}
.all-require {
padding: 25px 0;
}
.heading {
padding-bottom: 20px;
}
.padding-upcoming {
padding: 25px 0;
}
.sub-text {
padding: 2px;
width: 74%;
}
.padding-contact h3{
text-align:center;
font-size:20px;
padding-bottom:10px;
}
.address {
width: 100%;
}
address {
font-size: 16px;
line-height: 20px;
text-align:center;
}
.social-icons {
width: 100%;
padding:30px 0;
}
.social {
padding: 0px;
}
form {
padding:0px;
}
}
@media screen and (max-width:384px){
.banner-content {
width: 280px;
}
.grid p {
padding-left: 40px;
}
.grid h5 {
padding-left: 40px;
}
}
@media screen and (max-width:320px){
.navbar-brand {
width: 80%;
}
.grid h5 {
padding-left: 32px;
font-size: 20px;
}
.grid p {
padding-left: 32px;
font-size:16px;
}
.newsletter {
width: 94%;
}
}
| 13.961096
| 493
| 0.671881
|
e39b845c7a3f9a555098d992a09cfd69e34ca591
| 2,290
|
swift
|
Swift
|
BoxOffice/BoxOffice/PosterList/PosterImageCollectionView.swift
|
proxpero/Hollywood
|
49ed5307d550ec7a9e5c6ff90ca334eaf3c2c173
|
[
"MIT"
] | null | null | null |
BoxOffice/BoxOffice/PosterList/PosterImageCollectionView.swift
|
proxpero/Hollywood
|
49ed5307d550ec7a9e5c6ff90ca334eaf3c2c173
|
[
"MIT"
] | null | null | null |
BoxOffice/BoxOffice/PosterList/PosterImageCollectionView.swift
|
proxpero/Hollywood
|
49ed5307d550ec7a9e5c6ff90ca334eaf3c2c173
|
[
"MIT"
] | null | null | null |
import UIKit
import TMDbAPI
public final class PosterImagesCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource {
public var items: [PosterCell.Item] = []
public var didSelectItem: (PosterCell.Item) -> () = { _ in }
public init(layout: UICollectionViewLayout = PosterImagesCollectionView.defaultLayout, networkEngine: NetworkEngine = URLSession.shared) {
self.networkEngine = networkEngine
super.init(frame: .zero, collectionViewLayout: layout)
backgroundColor = nil
delegate = self
dataSource = self
contentInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
register(PosterCell.self)
}
private let networkEngine: NetworkEngine
public static let defaultLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: 92, height: 138)
layout.minimumLineSpacing = 3
layout.minimumInteritemSpacing = 3
return layout
}()
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item = items[indexPath.row]
didSelectItem(item)
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = items[indexPath.row]
let cell = collectionView.dequeue(PosterCell.self, for: indexPath)
cell.setTitle(item.title)
cell.representedUrl = item.imageUrl
if let url = item.imageUrl {
let resource = Resource<UIImage>(url: url, parse: UIImage.init)
networkEngine.load(resource).then { image in
guard cell.representedUrl == item.imageUrl else { return }
cell.setImage(image)
}
}
return cell
}
}
| 35.78125
| 142
| 0.679913
|
8c682da64b2d33f3185fdf8f0c98ddac9240dc1b
| 11,738
|
dart
|
Dart
|
lib/src/model/order_data.dart
|
ValeraLetun/abg_utils
|
37471dfb8c7fc89d354e5f9e5bd4638f6cba69ec
|
[
"Apache-2.0"
] | null | null | null |
lib/src/model/order_data.dart
|
ValeraLetun/abg_utils
|
37471dfb8c7fc89d354e5f9e5bd4638f6cba69ec
|
[
"Apache-2.0"
] | null | null | null |
lib/src/model/order_data.dart
|
ValeraLetun/abg_utils
|
37471dfb8c7fc89d354e5f9e5bd4638f6cba69ec
|
[
"Apache-2.0"
] | null | null | null |
import '../../abg_utils.dart';
class OrderData {
String id;
String status; // status id
bool delete;
List<StatusHistory> history;
//
String customerId;
String customer; // name
String customerAvatar;
String providerId;
String providerPhone;
List<StringData> provider;
String providerAvatar;
String serviceId;
String serviceImage;
List<StringData> service;
//
List<StringData> priceName;
double price;
double discPrice;
String priceUnit; // "hourly" or "fixed"
int count;
String couponId;
String couponName;
double discount;
String discountType; // "percent" or "fixed"
double tax;
double taxAdmin;
double total;
//
String paymentMethod;
String comment;
String address;
bool anyTime;
DateTime selectTime;
DateTime time; // timestamp
DateTime timeUtc = DateTime.now();
DateTime timeModify; // время воследней модификации (для listener) --- "timeModify": FieldValue.serverTimestamp(),
bool viewByAdmin;
bool viewByProvider;
bool rated;
bool finished;
List<AddonData> addon;
bool ver2; // version history changed
bool ver3;
bool ver4; // добавлены товары (articles)
bool paymentMethodCache; // v3
List<ProductData> products; // v4
String customerEmail;
String customerPhone;
double getPrice(){
return discPrice != 0 ? discPrice : price;
}
double _getTotal(){
var _price = count*getPrice();
var _coupon = getCoupon();
var _addon = getAddonsTotal();
return _price-_coupon+_addon;
}
double getTaxFromPrice(){
return _getTotal()*tax/100;
}
double getAddonsTotal(){
double total = 0;
for (var item in addon)
if (item.selected)
total += (item.needCount*item.price);
return total;
}
double getTotal(){
return _getTotal() + getTaxFromPrice();
}
double getCoupon(){
if (couponName.isEmpty)
return 0;
double total = getPrice()*count;
if (discountType == "percentage")
return total*discount/100;
return discount;
}
OrderData({this.id = "", this.status = "", this.delete = false,
this.customerId = "", this.customer = "", this.customerAvatar = "",
this.providerId = "", required this.provider, this.serviceId = "", required this.service,
this.price = 0, this.discPrice = 0, this.priceUnit = "fixed", this.count = 1, this.couponId = "",
this.couponName = "", this.discount = 0, this.discountType = "fixed",
this.tax = 0, this.total = 0,
this.paymentMethod = "", this.comment = "", this.address = "", required this.time, required this.timeModify,
this.anyTime = true, required this.selectTime, this.providerAvatar = "",
this.providerPhone = "", required this.history, required this.priceName,
this.viewByAdmin = false, this.viewByProvider = false,
this.taxAdmin = 0, this.finished = false, required this.addon,
this.rated = false, this.serviceImage = "",
this.ver2 = true,
this.ver3 = true,
this.ver4 = false, required this.products,
this.paymentMethodCache = true,
required this.customerEmail,
required this.customerPhone,
}){
timeUtc = time;
time = time.toLocal();
}
factory OrderData.createEmpty(){
return OrderData(service: [], provider: [], time: DateTime.now(), timeModify: DateTime.now(),
selectTime: DateTime.now(), history: [], priceName: [], addon: [], products: [],
customerPhone: '', customerEmail: '');
}
Map<String, dynamic> toJson({bool local = false}) => {
'id': id,
'status': status,
'delete': delete,
'customerId': customerId,
'customer' : customer,
'customerAvatar' : customerAvatar,
'providerId' : providerId,
'provider' : provider.map((i) => i.toJson()).toList(),
'providerAvatar' : providerAvatar,
'serviceId': serviceId,
'service': service.map((i) => i.toJson()).toList(),
'price' : price,
'discPrice': discPrice,
'priceName': priceName.map((i) => i.toJson()).toList(),
'priceUnit': priceUnit,
'count': count,
'couponId': couponId,
'couponName': couponName,
'discount': discount,
'discountType': discountType,
'tax' : tax,
'taxAdmin': taxAdmin,
'total': total,
'paymentMethod': paymentMethod,
'comment': comment,
'address' : address,
'anyTime': anyTime,
'selectTime': selectTime.millisecondsSinceEpoch,
'time': local ? time.toIso8601String() : DateTime.now().toUtc(),
'timeModify': local ? timeModify.toIso8601String() : DateTime.now().toUtc(),
'providerPhone': providerPhone,
'history': history.map((i) => i.toJson(local: local)).toList(),
'viewByAdmin' : viewByAdmin,
'viewByProvider' : viewByProvider,
'rated' : rated,
'finished': finished,
'addon': addon.map((i) => i.toJson()).toList(),
'serviceImage' : serviceImage,
'ver2' : ver2,
'ver3' : ver3,
'ver4' : ver4,
'paymentMethodCache': paymentMethodCache,
'products': products.map((i) => i.toJson(local: local)).toList(),
'customerEmail': customerEmail,
'customerPhone': customerPhone,
};
factory OrderData.fromJson(String id, Map<String, dynamic> data, {bool local = false}){
List<StringData> _provider = [];
if (data['provider'] != null)
for (var element in List.from(data['provider'])) {
_provider.add(StringData.fromJson(element));
}
List<StringData> _service = [];
if (data['service'] != null)
for (var element in List.from(data['service'])) {
_service.add(StringData.fromJson(element));
}
List<StatusHistory> _history = [];
if (data['history'] != null)
for (var element in List.from(data['history'])) {
_history.add(StatusHistory.fromJson(element, local: local));
}
List<StringData> _priceName = [];
if (data['priceName'] != null)
for (var element in List.from(data['priceName'])) {
_priceName.add(StringData.fromJson(element));
}
List<AddonData> _addon = [];
if (data['addon'] != null)
for (var element in List.from(data['addon'])) {
_addon.add(AddonData.fromJson(element));
}
var _time = !local ? (data["time"] != null) ? data["time"].toDate() : DateTime.now() : DateTime.parse(data["time"]);
List<ProductData> _products = [];
if (data['products'] != null)
for (var element in List.from(data['products'])) {
_products.add(ProductData.fromJson(element["id"], element, local: local));
}
//if (id == "bI9BRZ3ao6CUtPIkjwBN")
// dprint("order data id $id $_time");
return OrderData(
id: id,
status: (data["status"] != null) ? data["status"] : "",
delete: (data["delete"] != null) ? data["delete"] : false,
customerId: (data["customerId"] != null) ? data["customerId"] : "",
customer: (data["customer"] != null) ? data["customer"] : "",
customerAvatar: (data["customerAvatar"] != null) ? data["customerAvatar"] : "",
providerId: (data["providerId"] != null) ? data["providerId"] : "",
providerPhone: (data["providerPhone"] != null) ? data["providerPhone"] : "",
provider: _provider,
providerAvatar: (data["providerAvatar"] != null) ? data["providerAvatar"] : "",
serviceId: (data["serviceId"] != null) ? data["serviceId"] : "",
service: _service,
price: (data["price"] != null) ? toDouble(data["price"].toString()) : 0.0,
discPrice: (data["discPrice"] != null) ? toDouble(data["discPrice"].toString()) : 0.0,
priceUnit: (data["priceUnit"] != null) ? data["priceUnit"] : "",
priceName: _priceName,
count: (data["count"] != null) ? data["count"] : 1,
couponId: (data["couponId"] != null) ? data["couponId"] : "",
couponName: (data["couponName"] != null) ? data["couponName"] : "",
discount: (data["discount"] != null) ? toDouble(data["discount"].toString()) : 0.0,
discountType: (data["discountType"] != null) ? data["discountType"] : "",
tax: (data["tax"] != null) ? toDouble(data["tax"].toString()) : 0.0,
total: (data["total"] != null) ? toDouble(data["total"].toString()) : 0.0,
paymentMethod: (data["paymentMethod"] != null) ? data["paymentMethod"] : "",
comment: (data["comment"] != null) ? data["comment"] : "",
address: (data["address"] != null) ? data["address"] : "",
anyTime: (data["anyTime"] != null) ? data["anyTime"] : true,
selectTime: (data["selectTime"] != null) ? DateTime.fromMillisecondsSinceEpoch(data["selectTime"]) : DateTime.now(),
//
time: _time,
timeModify: !local ? (data["timeModify"] != null) ? data["timeModify"].toDate() : _time : DateTime.parse(data["time"]),
//
history: _history,
viewByAdmin: (data["viewByAdmin"] != null) ? data["viewByAdmin"] : false,
viewByProvider: (data["viewByProvider"] != null) ? data["viewByProvider"] : false,
taxAdmin: (data["taxAdmin"] != null) ? toDouble(data["taxAdmin"].toString()) : 0.0,
finished: (data["finished"] != null) ? data["finished"] : false,
rated: (data["rated"] != null) ? data["rated"] : false,
addon: _addon,
serviceImage: (data["serviceImage"] != null) ? data["serviceImage"] : "",
paymentMethodCache: (data["paymentMethodCache"] != null) ? data["paymentMethodCache"] : false,
ver2: (data["ver2"] != null) ? data["ver2"] : true,
ver3 : (data["ver3"] != null) ? data["ver3"] : true, // on demand v2
ver4: (data["ver4"] != null) ? data["ver4"] : false,
products: _products,
customerEmail: (data["customerEmail"] != null) ? data["customerEmail"] : "",
customerPhone: (data["customerPhone"] != null) ? data["customerPhone"] : "",
);
}
StatusHistory getHistoryDate(String id){
for (var item in history)
if (item.statusId == id)
return item;
return StatusHistory.createEmpty();
}
}
class StatusHistory{
String statusId = "";
DateTime time;
bool byCustomer;
bool byProvider;
bool byAdmin;
String activateUserId;
StatusHistory({this.statusId = "", required this.time, this.byCustomer = false,
this.byProvider = false, this.byAdmin = false, this.activateUserId = ""
});
Map<String, dynamic> toJson({bool local = false}) => {
'statusId': statusId,
'time': local ? time.toIso8601String() : time,
'byCustomer' : byCustomer,
'byProvider' : byProvider,
'byAdmin' : byAdmin,
'activateUserId' : activateUserId,
};
factory StatusHistory.fromJson(Map<String, dynamic> data, {bool local = false}){
// if (local) {
// dprint("StatusHistory " + data["time"].toString());
// var t = DateTime.parse(data["time"].toString());
// dprint(t.toString());
// dprint(t.toUtc().toString());
// }
// DateTime _time;
// if (local){
// _time = data["time"] != null ? (data["time"]).toDate().toLocal() : DateTime.now();
// }else{
// _time = data["time"] != null ? (data["time"]).toDate().toLocal() : DateTime.now();
// }
return StatusHistory(
statusId: (data["statusId"] != null) ? data["statusId"] : "",
time: !local ? (data["time"] != null) ? data["time"].toDate() : DateTime.now() : DateTime.parse(data["time"]),
// !local
// ? (data["time"] != null) ? (data["time"]).toDate().toLocal() : DateTime.now()
// : DateTime.parse(data["time"]),
byCustomer: (data["byCustomer"] != null) ? data["byCustomer"] : false,
byProvider: (data["byProvider"] != null) ? data["byProvider"] : false,
byAdmin: (data["byAdmin"] != null) ? data["byAdmin"] : false,
activateUserId: (data["activateUserId"] != null) ? data["activateUserId"] : "",
);
}
factory StatusHistory.createEmpty(){
return StatusHistory(time: DateTime.now());
}
}
| 37.14557
| 125
| 0.615607
|
43ad47336f429559ec6d6adbbf263fd493248f93
| 2,622
|
ts
|
TypeScript
|
runners/proc-group.ts
|
j50n/deno-proc
|
51b747b081f6eb23d760b69d1b095a36ecfe8680
|
[
"MIT"
] | 2
|
2022-01-25T03:56:13.000Z
|
2022-03-06T09:40:57.000Z
|
runners/proc-group.ts
|
j50n/deno-proc
|
51b747b081f6eb23d760b69d1b095a36ecfe8680
|
[
"MIT"
] | 27
|
2021-11-07T16:17:37.000Z
|
2022-02-19T15:48:20.000Z
|
runners/proc-group.ts
|
j50n/deno-proc
|
51b747b081f6eb23d760b69d1b095a36ecfe8680
|
[
"MIT"
] | null | null | null |
import {
MultiCloseProcess,
MultiCloseReader,
MultiCloseWriter,
} from "./closers.ts";
import { GroupImpl } from "./proc-group-impl.ts";
/**
* The interface of an input handler.
*/
export interface InputHandler<A> {
/**
* A hack to detect when empty input is actually an error at runtime, since
* I can't get Typescript to figure it out at compile time.
*/
get failOnEmptyInput(): boolean;
/**
* Called by the runner to process the input data.
*/
processInput: (input: A, stdin: MultiCloseWriter) => Promise<void>;
}
/**
* The interface of an output handler.
*/
export interface OutputHandler<B> {
/**
* Handle the output (stdout, stderr, and exit status) of a process.
*
* `stdin` is included so that it can be closed. It must not be read from the output handler.
*
* @param stdout Process standard out.
* @param stderr Process standard error.
* @param process The process.
* @param input `stdin` (to be closed) and the result of the input handler (to be awaited).
* @throws ProcessExitError A process returned an exit code that indicated that an error occurred.
*/
processOutput: (
stdout: MultiCloseReader,
stderr: MultiCloseReader,
process: MultiCloseProcess,
input: { stdin: MultiCloseWriter; handlerResult: Promise<null | Error> },
) => B | Promise<B>;
}
/**
* Command options.
*/
export interface RunOptions {
/** The command to be run. */
cmd: string[] | [URL, ...string[]];
/** The current working directory. */
cwd?: string;
/** The process environment. */
env?: {
[key: string]: string;
};
}
/**
* Create a new `Group` for running processes.
*
* Note that a `Group` cannot be garbage-collected
* until it is explicitly closed. If you don't close
* a group, its processes will be cleaned up when the
* Deno process exits. However, if you create a large
* number of groups without closing them, be aware
* that this will leak memory and potentially leak
* resources as well.
*
* @returns A new `Group` instance.
*/
export function group(): Group {
return new GroupImpl();
}
/**
* A process group.
*
* A process group must be closed to allow it to be garbage collected.
*/
export interface Group extends Deno.Closer {
/**
* Flat process API.
* @param inputHandler The input handler.
* @param outputHandler The output handler.
* @param input The input. `undefined` for empty input.
* @param options The run options.
*/
run<A, B>(
inputHandler: InputHandler<A>,
outputHandler: OutputHandler<B>,
input: A,
options: RunOptions,
): B | Promise<B>;
}
| 26.755102
| 100
| 0.671243
|
da21578474df0de76d621707b46b3c3f723c18bd
| 3,128
|
php
|
PHP
|
lib/adapters/Mysql.php
|
nicolachoquet06250/php-lib-orm
|
2fe00833768199ad135aca59ef08f0a2360e7963
|
[
"MIT"
] | null | null | null |
lib/adapters/Mysql.php
|
nicolachoquet06250/php-lib-orm
|
2fe00833768199ad135aca59ef08f0a2360e7963
|
[
"MIT"
] | null | null | null |
lib/adapters/Mysql.php
|
nicolachoquet06250/php-lib-orm
|
2fe00833768199ad135aca59ef08f0a2360e7963
|
[
"MIT"
] | null | null | null |
<?php
namespace PhpLib\ORM\adapters;
use Exception;
use JetBrains\PhpStorm\Pure;
use PDO;
use PDOException;
use PhpLib\ORM\interfaces\{ORMInserter, ORMSelector, ORMUpdater, ORMDeleter, adapters\ORMAdapter};
use PhpLib\ORM\Model;
use PhpLib\ORM\ORM;
class Mysql implements ORMAdapter {
protected PDO $connector;
/**
* @param array{host:string, dbname:string, username:string, password:string} $config
*/
public function __construct(
protected array $config,
protected string $model
) { $this->connect(); }
/**
* @throws PDOException
*/
private function connect(): void {
$charset = $this->config['charset'] ?? 'utf8';
$this->connector = new PDO(
"mysql:host={$this->config['host']};dbname={$this->config['dbname']};charset=$charset",
username: $this->config['username'],
password: $this->config['password']
);
}
public function getConnector(): mixed {
return $this->connector;
}
#[Pure]
public function insert(): ORMInserter {
return new \PhpLib\ORM\actions\mysql\ORMInserter($this->connector, $this->model);
}
public function select(string|array $fields = '*'): ORMSelector {
return new \PhpLib\ORM\actions\mysql\ORMSelector($this->connector, $fields, $this->model);
}
public function delete(): ORMDeleter {
return new \PhpLib\ORM\actions\mysql\ORMDeleter($this->connector, $this->model);
}
public function update(): ORMUpdater {
return new \PhpLib\ORM\actions\mysql\ORMUpdater($this->connector, $this->model);
}
/**
* Crée la table associé au model
*
* @return bool
* @throws Exception
*/
public function createTable(): bool {
/** @var Model $modelClass */
$modelClass = $this->model;
$table = $modelClass::getTable();
$fieldList = [];
foreach ($modelClass::getFields() as $field => $fieldData) {
$createField = $fieldData['field'];
if (!empty($fieldData['type'])) {
$type = strtoupper($fieldData['type']['name']);
$size = isset($fieldData['type']['size']) ? "({$fieldData['type']['size']})" : '';
$createField .= " {$type}{$size}";
} elseif (!empty($fieldData['joint'])) {
/** @var Model $model */
$model = $fieldData['joint']['model'];
$modelField = $fieldData['joint']['field'];
$type = strtoupper($model::getFields()[$modelField]['type']['name']);
$size = isset($model::getFields()[$modelField]['type']['size']) ? "({$model::getFields()[$modelField]['type']['size']})" : '';
$createField .= " {$type}{$size}";
}
$createField .= isset($fieldData['default']) && $fieldData['default'] ? " DEFAULT {$fieldData['default']}" : '';
$createField .= isset($fieldData['not_null']) && $fieldData['not_null'] ? " NOT NULL" : '';
$createField .= isset($fieldData['autoincrement']) && $fieldData['autoincrement'] ? ' AUTO_INCREMENT' : '';
$createField .= isset($fieldData['primary_key']) && $fieldData['primary_key'] ? ' PRIMARY KEY' : '';
$fieldList[] = $createField;
}
$fieldList = implode(",\n", $fieldList);
$request = "CREATE TABLE IF NOT EXISTS `{$table}` (
{$fieldList}
)";
if ($this->connector->exec($request)) {
return true;
}
return false;
}
}
| 30.368932
| 130
| 0.640985
|
cdc8a255bd0b54f88cc876fb050f152f7966688f
| 558
|
cs
|
C#
|
src/GitVersion.MsBuild/Tasks/GenerateGitVersionInformation.cs
|
mglochsen/GitVersion
|
e9013533474e8e46b6a0ca60d20d02f3680b5980
|
[
"MIT"
] | 1
|
2020-10-16T14:57:27.000Z
|
2020-10-16T14:57:27.000Z
|
src/GitVersion.MsBuild/Tasks/GenerateGitVersionInformation.cs
|
mglochsen/GitVersion
|
e9013533474e8e46b6a0ca60d20d02f3680b5980
|
[
"MIT"
] | 60
|
2021-03-08T13:18:17.000Z
|
2021-08-17T03:24:08.000Z
|
src/GitVersion.MsBuild/Tasks/GenerateGitVersionInformation.cs
|
mglochsen/GitVersion
|
e9013533474e8e46b6a0ca60d20d02f3680b5980
|
[
"MIT"
] | 1
|
2020-09-30T08:25:08.000Z
|
2020-09-30T08:25:08.000Z
|
using Microsoft.Build.Framework;
namespace GitVersion.MsBuild.Tasks
{
public class GenerateGitVersionInformation : GitVersionTaskBase
{
[Required]
public string ProjectFile { get; set; }
[Required]
public string IntermediateOutputPath { get; set; }
[Required]
public string Language { get; set; } = "C#";
[Output]
public string GitVersionInformationFilePath { get; set; }
protected override bool OnExecute() => GitVersionTasks.GenerateGitVersionInformation(this);
}
}
| 24.26087
| 99
| 0.659498
|
da2cc70db21ab7fba6be874220eb288954655aaf
| 40,145
|
php
|
PHP
|
resources/views/pizza.blade.php
|
KwizRPL/kwiz_v1
|
af14acffc7ef9ecbb4d917e3535399dbba2074b6
|
[
"MIT"
] | null | null | null |
resources/views/pizza.blade.php
|
KwizRPL/kwiz_v1
|
af14acffc7ef9ecbb4d917e3535399dbba2074b6
|
[
"MIT"
] | null | null | null |
resources/views/pizza.blade.php
|
KwizRPL/kwiz_v1
|
af14acffc7ef9ecbb4d917e3535399dbba2074b6
|
[
"MIT"
] | null | null | null |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pizza - Free Bootstrap 4 Template by Colorlib</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do" rel="stylesheet">
<link rel="stylesheet" href="css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<link rel="stylesheet" href="css/magnific-popup.css">
<link rel="stylesheet" href="css/aos.css">
<link rel="stylesheet" href="css/ionicons.min.css">
<link rel="stylesheet" href="css/bootstrap-datepicker.css">
<link rel="stylesheet" href="css/jquery.timepicker.css">
<link rel="stylesheet" href="css/flaticon.css">
<link rel="stylesheet" href="css/icomoon.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar">
<div class="container">
<a class="navbar-brand" href="index.html"><span class="flaticon-pizza-1 mr-1"></span>Pizza<br><small>Delicous</small></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="oi oi-menu"></span> Menu
</button>
<div class="collapse navbar-collapse" id="ftco-nav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active"><a href="index.html" class="nav-link">Home</a></li>
<li class="nav-item"><a href="menu.html" class="nav-link">Menu</a></li>
<li class="nav-item"><a href="services.html" class="nav-link">Services</a></li>
<li class="nav-item"><a href="blog.html" class="nav-link">Blog</a></li>
<li class="nav-item"><a href="about.html" class="nav-link">About</a></li>
<li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
</ul>
</div>
</div>
</nav>
<!-- END nav -->
<section class="home-slider owl-carousel img" style="background-image: url(images/bg_1.jpg);">
<div class="slider-item">
<div class="overlay"></div>
<div class="container">
<div class="row slider-text align-items-center" data-scrollax-parent="true">
<div class="col-md-6 col-sm-12 ftco-animate">
<span class="subheading">Delicious</span>
<h1 class="mb-4">Italian Cuizine</h1>
<p class="mb-4 mb-md-5">A small river named Duden flows by their place and supplies it with the necessary regelialia.</p>
<p><a href="#" class="btn btn-primary p-3 px-xl-4 py-xl-3">Order Now</a> <a href="#" class="btn btn-white btn-outline-white p-3 px-xl-4 py-xl-3">View Menu</a></p>
</div>
<div class="col-md-6 ftco-animate">
<img src="images/bg_1.png" class="img-fluid" alt="">
</div>
</div>
</div>
</div>
<div class="slider-item">
<div class="overlay"></div>
<div class="container">
<div class="row slider-text align-items-center" data-scrollax-parent="true">
<div class="col-md-6 col-sm-12 order-md-last ftco-animate">
<span class="subheading">Crunchy</span>
<h1 class="mb-4">Italian Pizza</h1>
<p class="mb-4 mb-md-5">A small river named Duden flows by their place and supplies it with the necessary regelialia.</p>
<p><a href="#" class="btn btn-primary p-3 px-xl-4 py-xl-3">Order Now</a> <a href="#" class="btn btn-white btn-outline-white p-3 px-xl-4 py-xl-3">View Menu</a></p>
</div>
<div class="col-md-6 ftco-animate">
<img src="images/bg_2.png" class="img-fluid" alt="">
</div>
</div>
</div>
</div>
<div class="slider-item" style="background-image: url(images/bg_3.jpg);">
<div class="overlay"></div>
<div class="container">
<div class="row slider-text justify-content-center align-items-center" data-scrollax-parent="true">
<div class="col-md-7 col-sm-12 text-center ftco-animate">
<span class="subheading">Welcome</span>
<h1 class="mb-4">We cooked your desired Pizza Recipe</h1>
<p class="mb-4 mb-md-5">A small river named Duden flows by their place and supplies it with the necessary regelialia.</p>
<p><a href="#" class="btn btn-primary p-3 px-xl-4 py-xl-3">Order Now</a> <a href="#" class="btn btn-white btn-outline-white p-3 px-xl-4 py-xl-3">View Menu</a></p>
</div>
</div>
</div>
</div>
</section>
<section class="ftco-intro">
<div class="container-wrap">
<div class="wrap d-md-flex">
<div class="info">
<div class="row no-gutters">
<div class="col-md-4 d-flex ftco-animate">
<div class="icon"><span class="icon-phone"></span></div>
<div class="text">
<h3>000 (123) 456 7890</h3>
<p>A small river named Duden flows</p>
</div>
</div>
<div class="col-md-4 d-flex ftco-animate">
<div class="icon"><span class="icon-my_location"></span></div>
<div class="text">
<h3>198 West 21th Street</h3>
<p>Suite 721 New York NY 10016</p>
</div>
</div>
<div class="col-md-4 d-flex ftco-animate">
<div class="icon"><span class="icon-clock-o"></span></div>
<div class="text">
<h3>Open Monday-Friday</h3>
<p>8:00am - 9:00pm</p>
</div>
</div>
</div>
</div>
<div class="social d-md-flex pl-md-5 p-4 align-items-center">
<ul class="social-icon">
<li class="ftco-animate"><a href="#"><span class="icon-twitter"></span></a></li>
<li class="ftco-animate"><a href="#"><span class="icon-facebook"></span></a></li>
<li class="ftco-animate"><a href="#"><span class="icon-instagram"></span></a></li>
</ul>
</div>
</div>
</div>
</section>
<section class="ftco-about d-md-flex">
<div class="one-half img" style="background-image: url(images/about.jpg);"></div>
<div class="one-half ftco-animate">
<div class="heading-section ftco-animate ">
<h2 class="mb-4">Welcome to <span class="flaticon-pizza">Pizza</span> A Restaurant</h2>
</div>
<div>
<p>On her way she met a copy. The copy warned the Little Blind Text, that where it came from it would have been rewritten a thousand times and everything that was left from its origin would be the word "and" and the Little Blind Text should turn around and return to its own, safe country. But nothing the copy said could convince her and so it didn’t take long until a few insidious Copy Writers ambushed her, made her drunk with Longe and Parole and dragged her into their agency, where they abused her for their.</p>
</div>
</div>
</section>
<section class="ftco-section ftco-services">
<div class="overlay"></div>
<div class="container">
<div class="row justify-content-center mb-5 pb-3">
<div class="col-md-7 heading-section ftco-animate text-center">
<h2 class="mb-4">Our Services</h2>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</div>
<div class="row">
<div class="col-md-4 ftco-animate">
<div class="media d-block text-center block-6 services">
<div class="icon d-flex justify-content-center align-items-center mb-5">
<span class="flaticon-diet"></span>
</div>
<div class="media-body">
<h3 class="heading">Healthy Foods</h3>
<p>Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic.</p>
</div>
</div>
</div>
<div class="col-md-4 ftco-animate">
<div class="media d-block text-center block-6 services">
<div class="icon d-flex justify-content-center align-items-center mb-5">
<span class="flaticon-bicycle"></span>
</div>
<div class="media-body">
<h3 class="heading">Fastest Delivery</h3>
<p>Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic.</p>
</div>
</div>
</div>
<div class="col-md-4 ftco-animate">
<div class="media d-block text-center block-6 services">
<div class="icon d-flex justify-content-center align-items-center mb-5"><span class="flaticon-pizza-1"></span></div>
<div class="media-body">
<h3 class="heading">Original Recipes</h3>
<p>Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="ftco-section">
<div class="container">
<div class="row justify-content-center mb-5 pb-3">
<div class="col-md-7 heading-section ftco-animate text-center">
<h2 class="mb-4">Hot Pizza Meals</h2>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</div>
</div>
<div class="container-wrap">
<div class="row no-gutters d-flex">
<div class="col-lg-4 d-flex ftco-animate">
<div class="services-wrap d-flex">
<a href="#" class="img" style="background-image: url(images/pizza-1.jpg);"></a>
<div class="text p-4">
<h3>Italian Pizza</h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia </p>
<p class="price"><span>$2.90</span> <a href="#" class="ml-2 btn btn-white btn-outline-white">Order</a></p>
</div>
</div>
</div>
<div class="col-lg-4 d-flex ftco-animate">
<div class="services-wrap d-flex">
<a href="#" class="img" style="background-image: url(images/pizza-2.jpg);"></a>
<div class="text p-4">
<h3>Greek Pizza</h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p>
<p class="price"><span>$2.90</span> <a href="#" class="ml-2 btn btn-white btn-outline-white">Order</a></p>
</div>
</div>
</div>
<div class="col-lg-4 d-flex ftco-animate">
<div class="services-wrap d-flex">
<a href="#" class="img" style="background-image: url(images/pizza-3.jpg);"></a>
<div class="text p-4">
<h3>Caucasian Pizza</h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p>
<p class="price"><span>$2.90</span> <a href="#" class="ml-2 btn btn-white btn-outline-white">Order</a></p>
</div>
</div>
</div>
<div class="col-lg-4 d-flex ftco-animate">
<div class="services-wrap d-flex">
<a href="#" class="img order-lg-last" style="background-image: url(images/pizza-4.jpg);"></a>
<div class="text p-4">
<h3>American Pizza</h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia </p>
<p class="price"><span>$2.90</span> <a href="#" class="ml-2 btn btn-white btn-outline-white">Order</a></p>
</div>
</div>
</div>
<div class="col-lg-4 d-flex ftco-animate">
<div class="services-wrap d-flex">
<a href="#" class="img order-lg-last" style="background-image: url(images/pizza-5.jpg);"></a>
<div class="text p-4">
<h3>Tomatoe Pie</h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p>
<p class="price"><span>$2.90</span> <a href="#" class="ml-2 btn btn-white btn-outline-white">Order</a></p>
</div>
</div>
</div>
<div class="col-lg-4 d-flex ftco-animate">
<div class="services-wrap d-flex">
<a href="#" class="img order-lg-last" style="background-image: url(images/pizza-6.jpg);"></a>
<div class="text p-4">
<h3>Margherita</h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p>
<p class="price"><span>$2.90</span> <a href="#" class="ml-2 btn btn-white btn-outline-white">Order</a></p>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-center mb-5 pb-3 mt-5 pt-5">
<div class="col-md-7 heading-section text-center ftco-animate">
<h2 class="mb-4">Our Menu Pricing</h2>
<p class="flip"><span class="deg1"></span><span class="deg2"></span><span class="deg3"></span></p>
<p class="mt-5">Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-1.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Italian Pizza</span></h3>
<span class="price">$20.00</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-2.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Hawaiian Pizza</span></h3>
<span class="price">$29.00</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-3.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Greek Pizza</span></h3>
<span class="price">$20.00</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-4.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Bacon Crispy Thins</span></h3>
<span class="price">$20.00</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-5.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Hawaiian Special</span></h3>
<span class="price">$49.91</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-6.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Ultimate Overload</span></h3>
<span class="price">$20.00</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-7.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Bacon Pizza</span></h3>
<span class="price">$20.00</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
<div class="pricing-entry d-flex ftco-animate">
<div class="img" style="background-image: url(images/pizza-8.jpg);"></div>
<div class="desc pl-3">
<div class="d-flex text align-items-center">
<h3><span>Ham & Pineapple</span></h3>
<span class="price">$20.00</span>
</div>
<div class="d-block">
<p>A small river named Duden flows by their place and supplies</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="ftco-gallery">
<div class="container-wrap">
<div class="row no-gutters">
<div class="col-md-3 ftco-animate">
<a href="gallery.html" class="gallery img d-flex align-items-center" style="background-image: url(images/gallery-1.jpg);">
<div class="icon mb-4 d-flex align-items-center justify-content-center">
<span class="icon-search"></span>
</div>
</a>
</div>
<div class="col-md-3 ftco-animate">
<a href="gallery.html" class="gallery img d-flex align-items-center" style="background-image: url(images/gallery-2.jpg);">
<div class="icon mb-4 d-flex align-items-center justify-content-center">
<span class="icon-search"></span>
</div>
</a>
</div>
<div class="col-md-3 ftco-animate">
<a href="gallery.html" class="gallery img d-flex align-items-center" style="background-image: url(images/gallery-3.jpg);">
<div class="icon mb-4 d-flex align-items-center justify-content-center">
<span class="icon-search"></span>
</div>
</a>
</div>
<div class="col-md-3 ftco-animate">
<a href="gallery.html" class="gallery img d-flex align-items-center" style="background-image: url(images/gallery-4.jpg);">
<div class="icon mb-4 d-flex align-items-center justify-content-center">
<span class="icon-search"></span>
</div>
</a>
</div>
</div>
</div>
</section>
<section class="ftco-counter ftco-bg-dark img" id="section-counter" style="background-image: url(images/bg_2.jpg);" data-stellar-background-ratio="0.5">
<div class="overlay"></div>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
<div class="row">
<div class="col-md-6 col-lg-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<div class="icon"><span class="flaticon-pizza-1"></span></div>
<strong class="number" data-number="100">0</strong>
<span>Pizza Branches</span>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<div class="icon"><span class="flaticon-medal"></span></div>
<strong class="number" data-number="85">0</strong>
<span>Number of Awards</span>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<div class="icon"><span class="flaticon-laugh"></span></div>
<strong class="number" data-number="10567">0</strong>
<span>Happy Customer</span>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<div class="icon"><span class="flaticon-chef"></span></div>
<strong class="number" data-number="900">0</strong>
<span>Staff</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="ftco-menu">
<div class="container-fluid">
<div class="row d-md-flex">
<div class="col-lg-4 ftco-animate img f-menu-img mb-5 mb-md-0" style="background-image: url(images/about.jpg);">
</div>
<div class="col-lg-8 ftco-animate p-md-5">
<div class="row">
<div class="col-md-12 nav-link-wrap mb-5">
<div class="nav ftco-animate nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
<a class="nav-link active" id="v-pills-1-tab" data-toggle="pill" href="#v-pills-1" role="tab" aria-controls="v-pills-1" aria-selected="true">Pizza</a>
<a class="nav-link" id="v-pills-2-tab" data-toggle="pill" href="#v-pills-2" role="tab" aria-controls="v-pills-2" aria-selected="false">Drinks</a>
<a class="nav-link" id="v-pills-3-tab" data-toggle="pill" href="#v-pills-3" role="tab" aria-controls="v-pills-3" aria-selected="false">Burgers</a>
<a class="nav-link" id="v-pills-4-tab" data-toggle="pill" href="#v-pills-4" role="tab" aria-controls="v-pills-4" aria-selected="false">Pasta</a>
</div>
</div>
<div class="col-md-12 d-flex align-items-center">
<div class="tab-content ftco-animate" id="v-pills-tabContent">
<div class="tab-pane fade show active" id="v-pills-1" role="tabpanel" aria-labelledby="v-pills-1-tab">
<div class="row">
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/pizza-1.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/pizza-2.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/pizza-3.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="v-pills-2" role="tabpanel" aria-labelledby="v-pills-2-tab">
<div class="row">
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/drink-1.jpg);"></a>
<div class="text">
<h3><a href="#">Lemonade Juice</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/drink-2.jpg);"></a>
<div class="text">
<h3><a href="#">Pineapple Juice</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/drink-3.jpg);"></a>
<div class="text">
<h3><a href="#">Soda Drinks</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="v-pills-3" role="tabpanel" aria-labelledby="v-pills-3-tab">
<div class="row">
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/burger-1.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/burger-2.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/burger-3.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="v-pills-4" role="tabpanel" aria-labelledby="v-pills-4-tab">
<div class="row">
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/pasta-1.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/pasta-2.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
<div class="col-md-4 text-center">
<div class="menu-wrap">
<a href="#" class="menu-img img mb-4" style="background-image: url(images/pasta-3.jpg);"></a>
<div class="text">
<h3><a href="#">Itallian Pizza</a></h3>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p>
<p class="price"><span>$2.90</span></p>
<p><a href="#" class="btn btn-white btn-outline-white">Add to cart</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="ftco-section">
<div class="container">
<div class="row justify-content-center mb-5 pb-3">
<div class="col-md-7 heading-section ftco-animate text-center">
<h2 class="mb-4">Recent from blog</h2>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
</div>
</div>
<div class="row d-flex">
<div class="col-md-4 d-flex ftco-animate">
<div class="blog-entry align-self-stretch">
<a href="blog-single.html" class="block-20" style="background-image: url('images/image_1.jpg');">
</a>
<div class="text py-4 d-block">
<div class="meta">
<div><a href="#">Sept 10, 2018</a></div>
<div><a href="#">Admin</a></div>
<div><a href="#" class="meta-chat"><span class="icon-chat"></span> 3</a></div>
</div>
<h3 class="heading mt-2"><a href="#">The Delicious Pizza</a></h3>
<p>A small river named Duden flows by their place and supplies it with the necessary regelialia.</p>
</div>
</div>
</div>
<div class="col-md-4 d-flex ftco-animate">
<div class="blog-entry align-self-stretch">
<a href="blog-single.html" class="block-20" style="background-image: url('images/image_2.jpg');">
</a>
<div class="text py-4 d-block">
<div class="meta">
<div><a href="#">Sept 10, 2018</a></div>
<div><a href="#">Admin</a></div>
<div><a href="#" class="meta-chat"><span class="icon-chat"></span> 3</a></div>
</div>
<h3 class="heading mt-2"><a href="#">The Delicious Pizza</a></h3>
<p>A small river named Duden flows by their place and supplies it with the necessary regelialia.</p>
</div>
</div>
</div>
<div class="col-md-4 d-flex ftco-animate">
<div class="blog-entry align-self-stretch">
<a href="blog-single.html" class="block-20" style="background-image: url('images/image_3.jpg');">
</a>
<div class="text py-4 d-block">
<div class="meta">
<div><a href="#">Sept 10, 2018</a></div>
<div><a href="#">Admin</a></div>
<div><a href="#" class="meta-chat"><span class="icon-chat"></span> 3</a></div>
</div>
<h3 class="heading mt-2"><a href="#">The Delicious Pizza</a></h3>
<p>A small river named Duden flows by their place and supplies it with the necessary regelialia.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="ftco-appointment">
<div class="overlay"></div>
<div class="container-wrap">
<div class="row no-gutters d-md-flex align-items-center">
<div class="col-md-6 d-flex align-self-stretch">
<div id="map"></div>
</div>
<div class="col-md-6 appointment ftco-animate">
<h3 class="mb-3">Contact Us</h3>
<form action="#" class="appointment-form">
<div class="d-md-flex">
<div class="form-group">
<input type="text" class="form-control" placeholder="First Name">
</div>
</div>
<div class="d-me-flex">
<div class="form-group">
<input type="text" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<textarea name="" id="" cols="30" rows="3" class="form-control" placeholder="Message"></textarea>
</div>
<div class="form-group">
<input type="submit" value="Send" class="btn btn-primary py-3 px-4">
</div>
</form>
</div>
</div>
</div>
</section>
<footer class="ftco-footer ftco-section img">
<div class="overlay"></div>
<div class="container">
<div class="row mb-5">
<div class="col-lg-3 col-md-6 mb-5 mb-md-5">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">About Us</h2>
<p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p>
<ul class="ftco-footer-social list-unstyled float-md-left float-lft mt-5">
<li class="ftco-animate"><a href="#"><span class="icon-twitter"></span></a></li>
<li class="ftco-animate"><a href="#"><span class="icon-facebook"></span></a></li>
<li class="ftco-animate"><a href="#"><span class="icon-instagram"></span></a></li>
</ul>
</div>
</div>
<div class="col-lg-4 col-md-6 mb-5 mb-md-5">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">Recent Blog</h2>
<div class="block-21 mb-4 d-flex">
<a class="blog-img mr-4" style="background-image: url(images/image_1.jpg);"></a>
<div class="text">
<h3 class="heading"><a href="#">Even the all-powerful Pointing has no control about</a></h3>
<div class="meta">
<div><a href="#"><span class="icon-calendar"></span> Sept 15, 2018</a></div>
<div><a href="#"><span class="icon-person"></span> Admin</a></div>
<div><a href="#"><span class="icon-chat"></span> 19</a></div>
</div>
</div>
</div>
<div class="block-21 mb-4 d-flex">
<a class="blog-img mr-4" style="background-image: url(images/image_2.jpg);"></a>
<div class="text">
<h3 class="heading"><a href="#">Even the all-powerful Pointing has no control about</a></h3>
<div class="meta">
<div><a href="#"><span class="icon-calendar"></span> Sept 15, 2018</a></div>
<div><a href="#"><span class="icon-person"></span> Admin</a></div>
<div><a href="#"><span class="icon-chat"></span> 19</a></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-2 col-md-6 mb-5 mb-md-5">
<div class="ftco-footer-widget mb-4 ml-md-4">
<h2 class="ftco-heading-2">Services</h2>
<ul class="list-unstyled">
<li><a href="#" class="py-2 d-block">Cooked</a></li>
<li><a href="#" class="py-2 d-block">Deliver</a></li>
<li><a href="#" class="py-2 d-block">Quality Foods</a></li>
<li><a href="#" class="py-2 d-block">Mixed</a></li>
</ul>
</div>
</div>
<div class="col-lg-3 col-md-6 mb-5 mb-md-5">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">Have a Questions?</h2>
<div class="block-23 mb-3">
<ul>
<li><span class="icon icon-map-marker"></span><span class="text">203 Fake St. Mountain View, San Francisco, California, USA</span></li>
<li><a href="#"><span class="icon icon-phone"></span><span class="text">+2 392 3929 210</span></a></li>
<li><a href="#"><span class="icon icon-envelope"></span><span class="text">info@yourdomain.com</span></a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
</div>
</div>
</div>
</footer>
<!-- loader -->
<div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div>
</body>
</html>
| 48.251202
| 525
| 0.518147
|
fa4ad8c3c50f540ea9be50d2aababf37cee4df09
| 1,216
|
cpp
|
C++
|
Sources/AGEngine/Utils/RWLock.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 47
|
2015-03-29T09:44:25.000Z
|
2020-11-30T10:05:56.000Z
|
Sources/AGEngine/Utils/RWLock.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 313
|
2015-01-01T18:16:30.000Z
|
2015-11-30T07:54:07.000Z
|
Sources/AGEngine/Utils/RWLock.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 9
|
2015-06-07T13:21:54.000Z
|
2020-08-25T09:50:07.000Z
|
#include "RWLock.hpp"
#include "Debug.hpp"
#include <thread>
namespace AGE
{
RWLock::RWLock()
{
_sharedLock.store(0, std::memory_order_relaxed);
_uniqueLock.store(false, std::memory_order_relaxed);
}
void RWLock::ReadLock()
{
while (_uniqueLock.exchange(true, std::memory_order_relaxed))
{
std::this_thread::yield();
}
_sharedLock.fetch_add(1, std::memory_order_relaxed);
_uniqueLock.store(false, std::memory_order_relaxed);
}
void RWLock::ReadUnlock()
{
_sharedLock.fetch_sub(1, std::memory_order_relaxed);
}
void RWLock::WriteLock()
{
while (_uniqueLock.exchange(true, std::memory_order_relaxed))
{
std::this_thread::yield();
}
while (_sharedLock.load(std::memory_order_relaxed) > 0)
{
std::this_thread::yield();
}
}
void RWLock::WriteUnlock()
{
_uniqueLock.store(false, std::memory_order_relaxed);
}
// RWLockGuard
RWLockGuard::RWLockGuard(RWLock &lock, bool exclusive)
: _lock(lock)
, _exclusive(exclusive)
{
if (_exclusive)
{
_lock.WriteLock();
}
else
{
_lock.ReadLock();
}
}
RWLockGuard::~RWLockGuard()
{
if (_exclusive)
{
_lock.WriteUnlock();
}
else
{
_lock.ReadUnlock();
}
}
// End RWLockGuard
}
| 16
| 63
| 0.67352
|
ccf0ea375c5d5a396f2ef06ef0e815c146fe7f24
| 2,381
|
rb
|
Ruby
|
app/models/billing/usage.rb
|
datacentred/stronghold
|
a9e02a9f59ff2a61e0a6c80a394afc6f53209316
|
[
"MIT"
] | 5
|
2018-05-17T09:54:38.000Z
|
2021-08-19T22:14:51.000Z
|
app/models/billing/usage.rb
|
datacentred/stronghold
|
a9e02a9f59ff2a61e0a6c80a394afc6f53209316
|
[
"MIT"
] | null | null | null |
app/models/billing/usage.rb
|
datacentred/stronghold
|
a9e02a9f59ff2a61e0a6c80a394afc6f53209316
|
[
"MIT"
] | 5
|
2018-03-15T03:30:52.000Z
|
2021-04-09T18:18:06.000Z
|
require 'open-uri'
module Billing
class Usage < ApplicationRecord
self.table_name = "billing_usages"
attr_accessor :blob
belongs_to :organization
before_destroy :remove_blob
after_create -> { update_column :updated_at, Time.at(0) }
def object_uuid
if persisted?
read_attribute(:object_uuid) || update_column(:object_uuid, SecureRandom.uuid)
else
read_attribute(:object_uuid) || write_attribute(:object_uuid, SecureRandom.uuid)
end
read_attribute(:object_uuid)
end
def object_uuid=(uuid)
write_attribute(:object_uuid, uuid)
end
def blob
conn
parse_timestamps(
JSON.parse(
open(
AWS::S3::S3Object.url_for(
object_uuid,
bucket,
authenticated: true
)
).read,
symbolize_names: true
)
)
rescue OpenURI::HTTPError => ex
raise unless ex.message.include?("404")
{}
end
def blob=(new_blob)
conn
Time.use_zone('UTC') do
AWS::S3::S3Object.store(
object_uuid,
new_blob.to_json,
bucket,
content_type: 'application/json'
)
end
end
private
def conn
AWS::S3::Base.establish_connection!(
:server => CEPH_ARGS[:api_url],
:use_ssl => true,
:access_key_id => CEPH_ARGS[:ceph_token],
:secret_access_key => CEPH_ARGS[:ceph_key]
)
end
def remove_blob
conn
AWS::S3::S3Object.delete(object_uuid, bucket)
rescue StandardError => ex
Honeybadger.notify(ex)
end
def bucket
'stronghold_usage'
end
def time_format
/^\d\d\d\d\-\d\d\-\d\dT\d\d:\d\d:\d\d/
end
def parse_timestamps(enum)
if enum.is_a?(Array)
enum.each_with_index do |element, i|
if element =~ time_format
enum[i] = Time.parse(element) rescue element
elsif element.is_a? Enumerable
enum[i] = parse_timestamps(element)
end
end
elsif enum.is_a?(Hash)
enum.each do |k,v|
if v =~ time_format
enum[k] = Time.parse(v) rescue v
elsif v.is_a? Enumerable
enum[k] = parse_timestamps(v)
end
end
end
enum
end
end
end
| 22.67619
| 88
| 0.561109
|
46d61564ce18aabb3fff08bcba0068e9bb316463
| 1,341
|
py
|
Python
|
pylinex/loglikelihood/__init__.py
|
CU-NESS/pylinex
|
b6f342595b6a154e129eb303782e5268088f34d5
|
[
"Apache-2.0"
] | null | null | null |
pylinex/loglikelihood/__init__.py
|
CU-NESS/pylinex
|
b6f342595b6a154e129eb303782e5268088f34d5
|
[
"Apache-2.0"
] | null | null | null |
pylinex/loglikelihood/__init__.py
|
CU-NESS/pylinex
|
b6f342595b6a154e129eb303782e5268088f34d5
|
[
"Apache-2.0"
] | null | null | null |
"""
File: pylinex/loglikelihood/__init__.py
Author: Keith Tauscher
Date: 4 Mar 2019
Description: File containing imports for the loglikelihood module. The classes
in this module concern the saving, loading, storing, and
evaluation of various likelihood functions.
"""
from pylinex.loglikelihood.Loglikelihood import Loglikelihood
from pylinex.loglikelihood.RosenbrockLoglikelihood import\
RosenbrockLoglikelihood
from pylinex.loglikelihood.LoglikelihoodWithData import LoglikelihoodWithData
from pylinex.loglikelihood.LoglikelihoodWithModel import LoglikelihoodWithModel
from pylinex.loglikelihood.GaussianLoglikelihood import GaussianLoglikelihood
from pylinex.loglikelihood.PoissonLoglikelihood import PoissonLoglikelihood
from pylinex.loglikelihood.GammaLoglikelihood import GammaLoglikelihood
from pylinex.loglikelihood.LinearTruncationLoglikelihood import\
LinearTruncationLoglikelihood
from pylinex.loglikelihood.NonlinearTruncationLoglikelihood import\
NonlinearTruncationLoglikelihood
from pylinex.loglikelihood.ConditionalFitGaussianLoglikelihood import\
ConditionalFitGaussianLoglikelihood
from pylinex.loglikelihood.LoadLoglikelihood import\
load_loglikelihood_from_hdf5_group
from pylinex.loglikelihood.LikelihoodDistributionHarmonizer import\
LikelihoodDistributionHarmonizer
| 46.241379
| 79
| 0.863535
|
e04ae6ef3d5006f9ad59796274613873da7d85d1
| 925
|
h
|
C
|
YouChengTire/YouChengTire/ViewModels/Me/EditVehicleVM.h
|
daqiangge/SiJiWuYou
|
00d1e2bf0fc4a8422440335c897ddb1f1c389bc7
|
[
"Apache-2.0"
] | null | null | null |
YouChengTire/YouChengTire/ViewModels/Me/EditVehicleVM.h
|
daqiangge/SiJiWuYou
|
00d1e2bf0fc4a8422440335c897ddb1f1c389bc7
|
[
"Apache-2.0"
] | null | null | null |
YouChengTire/YouChengTire/ViewModels/Me/EditVehicleVM.h
|
daqiangge/SiJiWuYou
|
00d1e2bf0fc4a8422440335c897ddb1f1c389bc7
|
[
"Apache-2.0"
] | null | null | null |
//
// EditVehicleVM.h
// YouChengTire
//
// Created by WangZhipeng on 16/2/10.
// Copyright © 2016年 WangZhipeng. All rights reserved.
//
#import "BaseVM.h"
@class VehicleTruckM;
@class VehicleBrandM;
@interface EditVehicleVM : BaseVM
@property (nonatomic, strong) VehicleTruckM *vehicleTruckM;
@property (nonatomic, strong) NSArray<VehicleBrandM *> *brandArray;
@property (nonatomic, weak) UIViewController *viewController;
/**
* 获取车辆品牌和车型
*/
- (void)requestGetBrands:(void (^)(id object))success
error:(void (^)(NSError *error))error
failure:(void (^)(NSError *error))failure
completion:(void (^)(void))completion;
/**
* 编辑车辆
*/
- (void)requestEditTruck:(void (^)(id object))success
error:(void (^)(NSError *error))error
failure:(void (^)(NSError *error))failure
completion:(void (^)(void))completion;
@end
| 23.717949
| 67
| 0.634595
|
2ca7f75cb63717982860d4014419e8413417a5cf
| 220
|
cpp
|
C++
|
Test/Expect/test109.cpp
|
dMajoIT/spin2cpp
|
f2ee655d150c9d69042b2dfaf8cae57123b7702c
|
[
"MIT"
] | 39
|
2015-02-10T13:43:24.000Z
|
2022-03-08T14:56:41.000Z
|
Test/Expect/test109.cpp
|
cbmeeks/spin2cpp
|
d1707a50ee90d944590a6e82c6227a6ff6ce1042
|
[
"MIT"
] | 230
|
2015-04-12T22:04:54.000Z
|
2022-03-30T05:22:11.000Z
|
Test/Expect/test109.cpp
|
cbmeeks/spin2cpp
|
d1707a50ee90d944590a6e82c6227a6ff6ce1042
|
[
"MIT"
] | 21
|
2016-03-05T05:15:06.000Z
|
2022-03-24T11:58:15.000Z
|
#define __SPIN2CPP__
#include <propeller.h>
#include "test109.h"
int32_t test109::Readdelta(int32_t Encid)
{
int32_t Deltapos = 0;
Deltapos = 0 + (Encid < Totdelta);
Totdelta = -(!Totdelta);
return Deltapos;
}
| 16.923077
| 41
| 0.695455
|
f6533c00c3f0e61df5a4004dd4ae23f520256b31
| 11,570
|
kt
|
Kotlin
|
app/src/main/java/me/blog/korn123/commons/utils/EasyDiaryUtils.kt
|
WAining/aaf-easydiary
|
19b6ca6d60613e7733ab1232ec8dfd6823fdd27a
|
[
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null |
app/src/main/java/me/blog/korn123/commons/utils/EasyDiaryUtils.kt
|
WAining/aaf-easydiary
|
19b6ca6d60613e7733ab1232ec8dfd6823fdd27a
|
[
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null |
app/src/main/java/me/blog/korn123/commons/utils/EasyDiaryUtils.kt
|
WAining/aaf-easydiary
|
19b6ca6d60613e7733ab1232ec8dfd6823fdd27a
|
[
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null |
package me.blog.korn123.commons.utils
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.PorterDuff
import android.graphics.Typeface
import android.net.Uri
import android.os.Environment
import android.provider.OpenableColumns
import android.text.SpannableString
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.widget.AdapterView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import id.zelory.compressor.Compressor
import io.github.aafactory.commons.utils.BitmapUtils
import io.github.aafactory.commons.utils.CALCULATION
import io.github.aafactory.commons.utils.CommonUtils
import me.blog.korn123.easydiary.R
import me.blog.korn123.easydiary.adapters.SecondItemAdapter
import me.blog.korn123.easydiary.extensions.checkPermission
import me.blog.korn123.easydiary.extensions.config
import me.blog.korn123.easydiary.helper.*
import me.blog.korn123.easydiary.models.DiaryDto
import me.blog.korn123.easydiary.models.PhotoUriDto
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils
import java.io.File
import java.io.FileNotFoundException
import java.util.*
/**
* Created by hanjoong on 2017-04-30.
*/
object EasyDiaryUtils {
private const val HIGHLIGHT_COLOR: Int = 0x9FFFFF00.toInt()
val easyDiaryMimeType: String
get() = "text/aaf_v" + EasyDiaryDbHelper.getInstance().version
val easyDiaryMimeTypeAll: Array<String?>
get() {
val currentVersion = EasyDiaryDbHelper.getInstance().version.toInt()
val easyDiaryMimeType = arrayOfNulls<String>(currentVersion)
for (i in 0 until currentVersion) {
easyDiaryMimeType[i] = "text/aaf_v" + (i + 1)
}
return easyDiaryMimeType
}
fun initWorkingDirectory(context: Context) {
if (context.checkPermission(EXTERNAL_STORAGE_PERMISSIONS)) {
makeDirectory(getApplicationDataDirectory(context) + DIARY_PHOTO_DIRECTORY)
makeDirectory(getApplicationDataDirectory(context) + DIARY_POSTCARD_DIRECTORY)
makeDirectory(getApplicationDataDirectory(context) + USER_CUSTOM_FONTS_DIRECTORY)
makeDirectory(getApplicationDataDirectory(context) + MARKDOWN_DIRECTORY)
makeDirectory(getApplicationDataDirectory(context) + BACKUP_EXCEL_DIRECTORY)
makeDirectory(getApplicationDataDirectory(context) + BACKUP_DB_DIRECTORY)
}
}
fun initLegacyWorkingDirectory(context: Context) {
if (context.checkPermission(EXTERNAL_STORAGE_PERMISSIONS)) {
makeDirectory(getExternalStorageDirectory().absolutePath + BACKUP_EXCEL_DIRECTORY)
}
}
private fun makeDirectory(path: String) {
val workingDirectory = File(path)
if (!workingDirectory.exists()) workingDirectory.mkdirs()
}
fun getApplicationDataDirectory(context: Context): String {
// return Environment.getExternalStorageDirectory().absolutePath
return context.applicationInfo.dataDir
}
fun getExternalStorageDirectory(): File = Environment.getExternalStorageDirectory()
fun boldString(context: Context, textView: TextView?) {
if (context.config.boldStyleEnable) {
textView?.let { tv ->
val spannableString = SpannableString(tv.text)
spannableString.setSpan(StyleSpan(Typeface.BOLD), 0, tv.text.length, 0)
tv.text = spannableString
}
}
}
fun highlightString(textView: TextView?, input: String?) {
textView?.let { tv ->
input?.let { targetString ->
//Get the text from text view and create a spannable string
val spannableString = SpannableString(tv.text)
//Get the previous spans and remove them
val backgroundSpans = spannableString.getSpans(0, spannableString.length, BackgroundColorSpan::class.java)
for (span in backgroundSpans) {
spannableString.removeSpan(span)
}
//Search for all occurrences of the keyword in the string
var indexOfKeyword = spannableString.toString().indexOf(targetString)
while (indexOfKeyword >= 0) {
//Create a background color span on the keyword
spannableString.setSpan(BackgroundColorSpan(HIGHLIGHT_COLOR), indexOfKeyword, indexOfKeyword + targetString.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//Get the next index of the keyword
indexOfKeyword = spannableString.toString().indexOf(targetString, indexOfKeyword + targetString.length)
}
//Set the final text on TextView
tv.text = spannableString
}
}
}
fun highlightStringIgnoreCase(textView: TextView?, input: String?) {
textView?.let { tv ->
input?.let { targetString ->
val inputLower = targetString.toLowerCase()
val contentsLower = tv.text.toString().toLowerCase()
val spannableString = SpannableString(tv.text)
val backgroundSpans = spannableString.getSpans(0, spannableString.length, BackgroundColorSpan::class.java)
for (span in backgroundSpans) {
spannableString.removeSpan(span)
}
var indexOfKeyword = contentsLower.indexOf(inputLower)
while (indexOfKeyword >= 0) {
spannableString.setSpan(BackgroundColorSpan(HIGHLIGHT_COLOR), indexOfKeyword, indexOfKeyword + inputLower.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
indexOfKeyword = contentsLower.indexOf(inputLower, indexOfKeyword + inputLower.length)
}
tv.text = spannableString
}
}
}
fun createSecondsPickerBuilder(context: Context, itemClickListener: AdapterView.OnItemClickListener, second: Int): AlertDialog.Builder {
val builder = AlertDialog.Builder(context)
builder.setNegativeButton(context.getString(android.R.string.cancel), null)
builder.setTitle(context.getString(R.string.common_create_seconds))
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val secondsPicker = inflater.inflate(R.layout.dialog_seconds_picker, null)
val listView = secondsPicker.findViewById<ListView>(R.id.seconds)
val listSecond = ArrayList<Map<String, String>>()
for (i in 0..59) {
val map = hashMapOf<String, String>()
map.put("label", i.toString() + "s")
map.put("value", i.toString())
listSecond.add(map)
}
val adapter = SecondItemAdapter(context, R.layout.item_second, listSecond, second)
listView.adapter = adapter
listView.onItemClickListener = itemClickListener
builder.setView(secondsPicker)
return builder
}
fun photoUriToDownSamplingBitmap(
context: Context,
photoUriDto: PhotoUriDto,
requiredSize: Int = 50,
fixedWidth: Int = 45,
fixedHeight: Int = 45
): Bitmap = try {
when (photoUriDto.isContentUri()) {
true -> {
BitmapUtils.decodeFile(context, Uri.parse(photoUriDto.photoUri), CommonUtils.dpToPixel(context, fixedWidth.toFloat(), CALCULATION.FLOOR), CommonUtils.dpToPixel(context, fixedHeight.toFloat(), CALCULATION.FLOOR))
}
false -> {
when (fixedWidth == fixedHeight) {
true -> BitmapUtils.decodeFileCropCenter(getApplicationDataDirectory(context) + photoUriDto.getFilePath(), CommonUtils.dpToPixel(context, fixedWidth.toFloat(), CALCULATION.FLOOR))
false -> BitmapUtils.decodeFile(getApplicationDataDirectory(context) + photoUriDto.getFilePath(), CommonUtils.dpToPixel(context, fixedWidth.toFloat(), CALCULATION.FLOOR), CommonUtils.dpToPixel(context, fixedHeight.toFloat(), CALCULATION.FLOOR))
}
}
}
} catch (fe: FileNotFoundException) {
fe.printStackTrace()
BitmapFactory.decodeResource(context.resources, R.drawable.question_shield)
} catch (se: SecurityException) {
se.printStackTrace()
BitmapFactory.decodeResource(context.resources, R.drawable.question_shield)
} catch (e: Exception) {
e.printStackTrace()
BitmapFactory.decodeResource(context.resources, R.drawable.question_shield)
}
fun photoUriToBitmap(context: Context, photoUriDto: PhotoUriDto): Bitmap? {
val bitmap: Bitmap? = try {
when (photoUriDto.isContentUri()) {
true -> {
BitmapFactory.decodeStream(context.contentResolver.openInputStream(Uri.parse(photoUriDto.photoUri)))
}
false -> {
BitmapFactory.decodeFile(getApplicationDataDirectory(context) + photoUriDto.getFilePath())
}
}
} catch (e: Exception) {
e.printStackTrace()
null
}
return bitmap
}
fun downSamplingImage(context: Context, srcFile: File, destFile: File) {
val compressedFile = Compressor(context).setQuality(70).compressToFile(srcFile)
FileUtils.copyFile(compressedFile, destFile)
}
fun changeDrawableIconColor(context: Context, color: Int, resourceId: Int) {
ContextCompat.getDrawable(context, resourceId)?.apply {
setColorFilter(color, PorterDuff.Mode.SRC_IN)
}
}
fun summaryDiaryLabel(diaryDto: DiaryDto): String {
return if (!diaryDto.title.isNullOrEmpty()) diaryDto.title!! else StringUtils.abbreviate(diaryDto.contents, 10)
}
fun datePickerToTimeMillis(dayOfMonth: Int, month: Int, year: Int, isFullHour: Boolean = false, hour: Int = 0, minute: Int = 0, second: Int = 0): Long {
val cal = Calendar.getInstance(Locale.getDefault())
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, month)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
cal.set(Calendar.HOUR_OF_DAY, if (isFullHour) 23 else hour)
cal.set(Calendar.MINUTE, if (isFullHour) 59 else minute)
cal.set(Calendar.SECOND, if (isFullHour) 59 else second)
return cal.timeInMillis
}
fun sequenceToPageIndex(diaryList: ArrayList<DiaryDto>, sequence: Int): Int {
var pageIndex = 0
if (sequence > -1) {
for (i in diaryList.indices) {
if (diaryList[i].sequence == sequence) {
pageIndex = i
break
}
}
}
return pageIndex
}
fun queryName(resolver: ContentResolver, uri: Uri): String {
val returnCursor: Cursor? = resolver.query(uri, null, null, null, null)
var name: String? = null
returnCursor?.let {
val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
it.moveToFirst()
name = returnCursor.getString(nameIndex);
returnCursor.close()
}
return name ?: UUID.randomUUID().toString()
}
}
| 42.380952
| 264
| 0.664218
|
fa60e041eac01f3fb44db8322fce99f975a32b55
| 926
|
cpp
|
C++
|
OOP - Laborator 9/Problema 1/Problema 1/main.cpp
|
alexrobert02/oop-2022
|
277655132fb8618b1ce1bd4bb53edc147a53028b
|
[
"MIT"
] | null | null | null |
OOP - Laborator 9/Problema 1/Problema 1/main.cpp
|
alexrobert02/oop-2022
|
277655132fb8618b1ce1bd4bb53edc147a53028b
|
[
"MIT"
] | null | null | null |
OOP - Laborator 9/Problema 1/Problema 1/main.cpp
|
alexrobert02/oop-2022
|
277655132fb8618b1ce1bd4bb53edc147a53028b
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include "map.h"
int main()
{
Map<int, const char*> m;
m[10] = "C++";
m[20] = "test";
m[30] = "Poo";
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
m[20] = "result";
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
Map<int, const char*> n;
n[20] = "examen";
printf("%d\n", m.Includes(n));
m.Set(10, "licenta");
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
m.Delete(20);
for (auto [key, value, index] : m) {
printf("Index:%d, Key=%d, Value=%s\n", index, key, value);
}
printf("%d\n", m.Count());
const char* value;
m.Get(10, value);
printf("%s\n", value);
return 0;
}
| 19.702128
| 66
| 0.5
|
af116e220a9ced5546716318357761eea60a5622
| 8,909
|
py
|
Python
|
jupyter_py/backtest_pair.py
|
vdaytona/statistical-arbitrage-18-19
|
a3ab6079425320292e3d12802a63aadce1868c4a
|
[
"MIT"
] | 163
|
2019-07-31T13:32:10.000Z
|
2022-03-21T08:14:46.000Z
|
jupyter_py/backtest_pair.py
|
BGTCapital/pairstrade-fyp-2019
|
032ccf3c6151f3c2179237a771abadb8d9c98424
|
[
"MIT"
] | 14
|
2019-07-31T13:16:49.000Z
|
2022-03-11T23:46:46.000Z
|
jupyter_py/backtest_pair.py
|
BGTCapital/pairstrade-fyp-2019
|
032ccf3c6151f3c2179237a771abadb8d9c98424
|
[
"MIT"
] | 38
|
2019-08-22T04:20:57.000Z
|
2022-03-11T06:08:13.000Z
|
import tensorflow as tf
import backtrader as bt
import backtrader.feeds as btfeeds
import pandas as pd
import warnings
import glob
import os
import sys
import uuid
import itertools
import json
import argparse
import pathlib
import logging
from grid_search_tools import GSTools
from ptstrategy_cointegration_kalman import CointKalmanStrategy
from ptstrategy_distance import DistStrategy
from ptstrategy_cointegration import CointStrategy
from custom_analyzer import Metrics
from pandas_datafeed import PandasData
from datetime import datetime
from pytz import timezone
from decode_logs import get_current_time
from pair_selector import *
sys.path.append('./process_data')
sys.path.append('./log_helper')
from process_data import trim_raw_data_files
from log_helper import LogHelper
##################################################################################################
# Define parameters #
##################################################################################################
parser = argparse.ArgumentParser()
parser.add_argument("--data_path", type=str, default="./data/nyse-daily-tech/",
help="Path to stock price data")
parser.add_argument("--output_dir", type=str, default=None, help="Path to output directory.")
parser.add_argument("--strategy_type", default="distance", type=str, choices=["distance", "cointegration", "kalman"],
help="Type of strategy used, either distance, cointegration, or kalman.")
parser.add_argument("--stk0", type=str, default="AAN",
help="Stock symbol of first stock.")
parser.add_argument("--stk1", type=str, default="AER",
help="Stock symbol of second stock.")
parser.add_argument("--kalman_estimation_length", type=int, default=200,
help="Number of days used for Kalman EM algorithm. Only useful if strategy is kalman.")
parser.add_argument("--backtest_start", type=str, default="2018-05-01",
help="Start date of backtest.")
parser.add_argument("--backtest_end", type=str, default="2018-12-31",
help="End date of backtest.")
parser.add_argument("--lookback", default=50, type=int,
help="Lookback value to be tested. Only useful if strategy is distance or cointegration.")
parser.add_argument("--enter_threshold", default=2.0, type=float,
help="Enter threshold value to be tested (in units 'number of SD from mean').")
parser.add_argument("--exit_threshold", default=0.5, type=float,
help="Exit threshold value to be tested (in units 'number of SD from mean').")
parser.add_argument("--loss_limit", default=-0.5, type=float,
help="Position will exit if loss exceeded this loss limit.")
config = parser.parse_args()
##################################################################################################
# Main function #
##################################################################################################
def main():
##################################################################################################
# Setup logger and output dir #
##################################################################################################
output_dir = config.output_dir
if output_dir is None:
output_dir = './jupyter_py/output/backtest-{}'.format(get_current_time())
if not os.path.exists(output_dir):
pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)
# Setup logger
LogHelper.setup(log_path='{}/backtesting.log'.format(output_dir), log_level=logging.INFO)
_logger = logging.getLogger(__name__)
# Log all paremeters
_logger.info("Backtest parameters: {}".format(vars(config)))
# load data
data = GSTools.load_csv_files(config.data_path)
stk0, stk1 = config.stk0, config.stk1
# check existence of stocks
if (stk0 not in data):
_logger.error("Stock symbol {} does not exist!".format(stk0))
return
if (stk1 not in data):
_logger.error("Stock symbol {} does not exist!".format(stk1))
return
# size requirements
pre_backtest_size = None
if config.strategy_type == "cointegration" or config.strategy_type == "distance":
pre_backtest_size = config.lookback
elif config.strategy_type == "kalman":
pre_backtest_size = config.kalman_estimation_length
# select segment of data that we want
data0, data1 = data[stk0].set_index("date"), data[stk1].set_index("date")
start_date_dt = datetime.strptime(config.backtest_start, "%Y-%m-%d").date()
end_date_dt = datetime.strptime(config.backtest_end, "%Y-%m-%d").date()
data0 = data0[ : start_date_dt].tail(pre_backtest_size).append(data0[start_date_dt : end_date_dt])
data1 = data1[ : start_date_dt].tail(pre_backtest_size).append(data1[start_date_dt : end_date_dt])
data0 = data0.reset_index()
data1 = data1.reset_index()
# initialize cerebro
cerebro = bt.Cerebro()
# Create data feeds
data0 = bt.feeds.PandasData(dataname=data0, timeframe=(bt.TimeFrame.Days), datetime=0, open=1, close=4)
data1 = bt.feeds.PandasData(dataname=data1, timeframe=(bt.TimeFrame.Days), datetime=0, open=1, close=4)
# add data feeds to cerebro
cerebro.adddata(data0)
cerebro.adddata(data1)
# Add the strategy
if config.strategy_type == "distance":
cerebro.addstrategy(DistStrategy,
stk0_symbol=stk0,
stk1_symbol=stk1,
lookback=config.lookback,
max_lookback=pre_backtest_size,
enter_threshold_size=config.enter_threshold,
exit_threshold_size=config.exit_threshold,
loss_limit=config.loss_limit,
consider_borrow_cost=True,
consider_commission=False,
print_msg=True,
print_transaction=True
)
elif config.strategy_type == "cointegration":
cerebro.addstrategy(CointStrategy,
stk0_symbol=stk0,
stk1_symbol=stk1,
lookback=config.lookback,
max_lookback=pre_backtest_size,
enter_threshold_size=config.enter_threshold,
exit_threshold_size=config.exit_threshold,
loss_limit=config.loss_limit,
consider_borrow_cost=True,
consider_commission=True,
print_msg=True,
print_transaction=True
)
elif config.strategy_type == "kalman":
cerebro.addstrategy(CointKalmanStrategy,
stk0_symbol=stk0,
stk1_symbol=stk1,
max_lookback=pre_backtest_size,
enter_threshold_size=config.enter_threshold,
exit_threshold_size=config.exit_threshold,
loss_limit=config.loss_limit,
consider_borrow_cost=True,
consider_commission=True,
print_msg=True,
print_transaction=True
)
# Add analyzers
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='mysharpe')
cerebro.addanalyzer(Metrics,
lookback=pre_backtest_size,
_name='metrics')
# Add the commission - only stocks like a for each operation
cerebro.broker.setcash(1000000)
# And run it
strat = cerebro.run()
# get MICRO metrics
results_dict = {}
results_dict["pair"] = stk0 + "-" + stk1
results_dict["sharperatio"]= strat[0].analyzers.mysharpe.get_analysis()['sharperatio']
results_dict["returnstd"] = strat[0].analyzers.metrics.returns_std()
results_dict["avg_holding_period"] = strat[0].analyzers.metrics.avg_holding_period
results_dict["n_trades"] = strat[0].analyzers.metrics.n_trades
results_dict["startcash"] = cerebro.getbroker().startingcash
results_dict["endcash"] = cerebro.getbroker().getvalue()
results_dict["profit"] = (results_dict["endcash"] - results_dict["startcash"]) / results_dict["startcash"]
_logger.info("[pair-performance]: {}".format(results_dict))
if __name__ == '__main__':
main()
| 45.22335
| 117
| 0.572567
|
1440d5efd614675f2b9261a3e3d088d977654720
| 1,095
|
ts
|
TypeScript
|
node_modules/vscode-ws-jsonrpc/src/stream/stream.ts
|
amirsaad2015/dsl
|
a18cfc94124792ff5015c45eb5ce12c46d1f8564
|
[
"Apache-2.0"
] | null | null | null |
node_modules/vscode-ws-jsonrpc/src/stream/stream.ts
|
amirsaad2015/dsl
|
a18cfc94124792ff5015c45eb5ce12c46d1f8564
|
[
"Apache-2.0"
] | null | null | null |
node_modules/vscode-ws-jsonrpc/src/stream/stream.ts
|
amirsaad2015/dsl
|
a18cfc94124792ff5015c45eb5ce12c46d1f8564
|
[
"Apache-2.0"
] | null | null | null |
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io). All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import { Readable, Writable } from "stream";
export class ReadableStream extends Readable {
constructor(data: any) {
super();
this.push(data);
this.push(null);
}
_read(size: number): void {
/* no-op */
}
}
export class WritableStream extends Writable {
data = new Buffer('');
_write(data: any, encoding: string, callback: Function): void {
const buffer = this.toBuffer(data, encoding);
this.data = Buffer.concat([this.data, buffer]);
callback();
}
protected toBuffer(data: any, encoding: string): Buffer {
if (Buffer.isBuffer(data)) {
return data;
}
return new Buffer(data, encoding)
}
}
| 28.076923
| 96
| 0.505936
|
b02abc7af032efc782386f23e25eba5fb278f342
| 7,658
|
py
|
Python
|
src/syft/proto/core/store/dataset_pb2.py
|
dnabanita7/PySyft
|
ce2510e65f5bad382e88806bcde30fa38c3c76c4
|
[
"Apache-2.0"
] | 2
|
2018-07-23T20:34:10.000Z
|
2020-08-01T09:09:09.000Z
|
packages/syft/src/syft/proto/core/store/dataset_pb2.py
|
Metrix1010/PySyft
|
6477f64b63dc285059c3766deab3993653cead2e
|
[
"Apache-2.0"
] | 5
|
2020-09-11T05:47:12.000Z
|
2020-10-13T08:36:17.000Z
|
packages/syft/src/syft/proto/core/store/dataset_pb2.py
|
Metrix1010/PySyft
|
6477f64b63dc285059c3766deab3993653cead2e
|
[
"Apache-2.0"
] | 1
|
2021-07-12T09:15:44.000Z
|
2021-07-12T09:15:44.000Z
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/core/store/dataset.proto
"""Generated protocol buffer code."""
# third party
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
# syft absolute
from syft.proto.core.common import (
common_object_pb2 as proto_dot_core_dot_common_dot_common__object__pb2,
)
from syft.proto.core.store import (
store_object_pb2 as proto_dot_core_dot_store_dot_store__object__pb2,
)
DESCRIPTOR = _descriptor.FileDescriptor(
name="proto/core/store/dataset.proto",
package="syft.core.store",
syntax="proto3",
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x1eproto/core/store/dataset.proto\x12\x0fsyft.core.store\x1a%proto/core/common/common_object.proto\x1a#proto/core/store/store_object.proto"\xe2\x01\n\x07\x44\x61taset\x12!\n\x02id\x18\x01 \x01(\x0b\x32\x15.syft.core.common.UID\x12\x10\n\x08obj_type\x18\x02 \x01(\t\x12\x1a\n\x12schematic_qualname\x18\x03 \x01(\t\x12-\n\x04\x64\x61ta\x18\x04 \x03(\x0b\x32\x1f.syft.core.store.StorableObject\x12\x13\n\x0b\x64\x65scription\x18\x05 \x01(\t\x12\x0c\n\x04tags\x18\x06 \x03(\t\x12\x18\n\x10read_permissions\x18\x07 \x01(\x0c\x12\x1a\n\x12search_permissions\x18\x08 \x01(\x0c\x62\x06proto3',
dependencies=[
proto_dot_core_dot_common_dot_common__object__pb2.DESCRIPTOR,
proto_dot_core_dot_store_dot_store__object__pb2.DESCRIPTOR,
],
)
_DATASET = _descriptor.Descriptor(
name="Dataset",
full_name="syft.core.store.Dataset",
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name="id",
full_name="syft.core.store.Dataset.id",
index=0,
number=1,
type=11,
cpp_type=10,
label=1,
has_default_value=False,
default_value=None,
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
_descriptor.FieldDescriptor(
name="obj_type",
full_name="syft.core.store.Dataset.obj_type",
index=1,
number=2,
type=9,
cpp_type=9,
label=1,
has_default_value=False,
default_value=b"".decode("utf-8"),
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
_descriptor.FieldDescriptor(
name="schematic_qualname",
full_name="syft.core.store.Dataset.schematic_qualname",
index=2,
number=3,
type=9,
cpp_type=9,
label=1,
has_default_value=False,
default_value=b"".decode("utf-8"),
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
_descriptor.FieldDescriptor(
name="data",
full_name="syft.core.store.Dataset.data",
index=3,
number=4,
type=11,
cpp_type=10,
label=3,
has_default_value=False,
default_value=[],
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
_descriptor.FieldDescriptor(
name="description",
full_name="syft.core.store.Dataset.description",
index=4,
number=5,
type=9,
cpp_type=9,
label=1,
has_default_value=False,
default_value=b"".decode("utf-8"),
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
_descriptor.FieldDescriptor(
name="tags",
full_name="syft.core.store.Dataset.tags",
index=5,
number=6,
type=9,
cpp_type=9,
label=3,
has_default_value=False,
default_value=[],
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
_descriptor.FieldDescriptor(
name="read_permissions",
full_name="syft.core.store.Dataset.read_permissions",
index=6,
number=7,
type=12,
cpp_type=9,
label=1,
has_default_value=False,
default_value=b"",
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
_descriptor.FieldDescriptor(
name="search_permissions",
full_name="syft.core.store.Dataset.search_permissions",
index=7,
number=8,
type=12,
cpp_type=9,
label=1,
has_default_value=False,
default_value=b"",
message_type=None,
enum_type=None,
containing_type=None,
is_extension=False,
extension_scope=None,
serialized_options=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
),
],
extensions=[],
nested_types=[],
enum_types=[],
serialized_options=None,
is_extendable=False,
syntax="proto3",
extension_ranges=[],
oneofs=[],
serialized_start=128,
serialized_end=354,
)
_DATASET.fields_by_name[
"id"
].message_type = proto_dot_core_dot_common_dot_common__object__pb2._UID
_DATASET.fields_by_name[
"data"
].message_type = proto_dot_core_dot_store_dot_store__object__pb2._STORABLEOBJECT
DESCRIPTOR.message_types_by_name["Dataset"] = _DATASET
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Dataset = _reflection.GeneratedProtocolMessageType(
"Dataset",
(_message.Message,),
{
"DESCRIPTOR": _DATASET,
"__module__": "proto.core.store.dataset_pb2"
# @@protoc_insertion_point(class_scope:syft.core.store.Dataset)
},
)
_sym_db.RegisterMessage(Dataset)
# @@protoc_insertion_point(module_scope)
| 32.866953
| 608
| 0.608906
|
dde4af2be0e97a66d4d3ba4f1f253f6feb906b34
| 1,674
|
java
|
Java
|
RiskMeter/src/main/java/PatientHistogram.java
|
Shane-Toma/ENSE375-GroupD
|
c71d7d9f3224c5ab9f1e38698673861a9d1b2f3f
|
[
"MIT"
] | null | null | null |
RiskMeter/src/main/java/PatientHistogram.java
|
Shane-Toma/ENSE375-GroupD
|
c71d7d9f3224c5ab9f1e38698673861a9d1b2f3f
|
[
"MIT"
] | null | null | null |
RiskMeter/src/main/java/PatientHistogram.java
|
Shane-Toma/ENSE375-GroupD
|
c71d7d9f3224c5ab9f1e38698673861a9d1b2f3f
|
[
"MIT"
] | null | null | null |
import java.util.ArrayList;
// Implemented by: Jacob Chapman
// NOTES: There was no figure available to display the regions, so I made the assumption of what regions are in the following rectangle and
// how many people were in each region.
public class PatientHistogram
{
private int[][] patientCount; // 20x10 region
public PatientHistogram()
{
this.patientCount = new int[20][10];
}
/**
*
* @return boolean: true if the patient can be added from that region
*/
public boolean addAPatientToRegion(int VIndex, int HIndex) throws IndexOutOfBoundsException//col, row
{
if(VIndex < 0 || VIndex > 20 || HIndex < 0 || HIndex > 10){
return false;
}
//Assuming there is a region available for that patient, then if the count is greater than 0 return true
if(this.patientCount[VIndex][HIndex] >= 0)
{
return true;
}
else
{
return false;
}
}
/**
*
* @return boolean: true if the patient can be removed from that region
*/
public boolean deleteAPatientFromRegion(int VIndex,int HIndex) throws IndexOutOfBoundsException
{
// assuming there is a patient available in that region, and if the count is not equal to zero
if(VIndex < 0 || VIndex > 20 || HIndex < 0 || HIndex > 10){
return false;
}
if(this.patientCount[VIndex][HIndex] >= 0)
{
return true;
}
else
{
return false;
}
}
public int getPatientsCountInRegion(int VIndex,int HIndex) throws IndexOutOfBoundsException
{
//ToDo: add you code here (you can update the return statement)
return this.patientCount[VIndex][HIndex];
}
}
| 27
| 140
| 0.654122
|
da6a1b1f8282d32c86980375b2791500935d5050
| 24,487
|
php
|
PHP
|
TeamUpWordpress/wp-content/plugins/ultimate-member/includes/admin/core/class-admin-enqueue.php
|
LeonardoSaccotelli/TeamUp
|
cddd656ce674b8b3ad9aad793d491729eaf8bbf0
|
[
"MIT"
] | null | null | null |
TeamUpWordpress/wp-content/plugins/ultimate-member/includes/admin/core/class-admin-enqueue.php
|
LeonardoSaccotelli/TeamUp
|
cddd656ce674b8b3ad9aad793d491729eaf8bbf0
|
[
"MIT"
] | 2
|
2021-03-11T03:31:50.000Z
|
2021-05-09T03:41:26.000Z
|
TeamUpWordpress/wp-content/plugins/ultimate-member/includes/admin/core/class-admin-enqueue.php
|
LeonardoSaccotelli/TeamUp
|
cddd656ce674b8b3ad9aad793d491729eaf8bbf0
|
[
"MIT"
] | null | null | null |
<?php
namespace um\admin\core;
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'um\admin\core\Admin_Enqueue' ) ) {
/**
* Class Admin_Enqueue
* @package um\admin\core
*/
class Admin_Enqueue {
/**
* @var string
*/
var $js_url;
/**
* @var string
*/
var $css_url;
/**
* @var string
*/
var $front_js_baseurl;
/**
* @var string
*/
var $front_css_baseurl;
/**
* @var string
*/
var $suffix;
/**
* @var bool
*/
var $um_cpt_form_screen;
/**
* @var bool
*/
var $post_page;
/**
* Admin_Enqueue constructor.
*/
function __construct() {
$this->js_url = um_url . 'includes/admin/assets/js/';
$this->css_url = um_url . 'includes/admin/assets/css/';
$this->front_js_baseurl = um_url . 'assets/js/';
$this->front_css_baseurl = um_url . 'assets/css/';
$this->suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || defined( 'UM_SCRIPT_DEBUG' ) ) ? '' : '.min';
$this->um_cpt_form_screen = false;
add_action( 'admin_head', array( &$this, 'admin_head' ), 9 );
add_action( 'admin_enqueue_scripts', array( &$this, 'admin_enqueue_scripts' ) );
add_filter( 'enter_title_here', array( &$this, 'enter_title_here' ) );
add_action( 'load-user-new.php', array( &$this, 'enqueue_role_wrapper' ) );
add_action( 'load-user-edit.php', array( &$this, 'enqueue_role_wrapper' ) );
add_action( 'load-post-new.php', array( &$this, 'enqueue_cpt_scripts' ) );
add_action( 'load-post.php', array( &$this, 'enqueue_cpt_scripts' ) );
add_filter( 'block_categories', array( &$this, 'blocks_category' ), 10, 2 );
}
function enqueue_role_wrapper() {
add_action( 'admin_enqueue_scripts', array( &$this, 'load_role_wrapper' ) );
}
/**
*
*/
function enqueue_cpt_scripts() {
if ( ( isset( $_GET['post_type'] ) && 'um_form' == sanitize_key( $_GET['post_type'] ) ) ||
( isset( $_GET['post'] ) && 'um_form' == get_post_type( absint( $_GET['post'] ) ) ) ) {
$this->um_cpt_form_screen = true;
add_action( 'admin_footer', array( $this, 'admin_footer_scripts' ), 20 );
}
$this->post_page = true;
}
/**
*
*/
function enqueue_frontend_preview_assets() {
//scripts for FRONTEND PREVIEW
if ( class_exists( 'WooCommerce' ) ) {
wp_dequeue_style( 'select2' );
wp_deregister_style( 'select2' );
wp_dequeue_script( 'select2' );
wp_deregister_script( 'select2' );
}
wp_register_script( 'select2', $this->front_js_baseurl . 'select2/select2.full.min.js', array( 'jquery', 'jquery-masonry' ), ultimatemember_version, true );
wp_register_script( 'um_jquery_form', $this->front_js_baseurl . 'um-jquery-form' . $this->suffix . '.js', array( 'jquery' ), ultimatemember_version, true );
wp_register_script( 'um_fileupload', $this->front_js_baseurl . 'um-fileupload' . $this->suffix . '.js', array( 'jquery' ), ultimatemember_version, true );
wp_register_script( 'um_crop', $this->front_js_baseurl . 'um-crop' . $this->suffix . '.js', array( 'jquery' ), ultimatemember_version, true );
wp_register_script( 'um_tipsy', $this->front_js_baseurl . 'um-tipsy' . $this->suffix . '.js', array( 'jquery' ), ultimatemember_version, true );
wp_register_script( 'um_functions', $this->front_js_baseurl . 'um-functions' . $this->suffix . '.js', array( 'jquery', 'um_tipsy', 'um_scrollbar' ), ultimatemember_version, true );
wp_register_script( 'um_datetime', $this->front_js_baseurl . 'pickadate/picker.js', array( 'jquery' ), ultimatemember_version, true );
wp_register_script( 'um_datetime_date', $this->front_js_baseurl . 'pickadate/picker.date.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
wp_register_script( 'um_datetime_time', $this->front_js_baseurl . 'pickadate/picker.time.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
wp_register_script( 'um_datetime_legacy', $this->front_js_baseurl . 'pickadate/legacy.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
// load a localized version for date/time
$locale = get_locale();
if ( $locale ) {
if ( file_exists( WP_LANG_DIR . '/plugins/ultimate-member/assets/js/pickadate/' . $locale . '.js' ) ) {
wp_register_script('um_datetime_locale', content_url() . '/languages/plugins/ultimate-member/assets/js/pickadate/' . $locale . '.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
} elseif ( file_exists( um_path . 'assets/js/pickadate/translations/' . $locale . '.js' ) ) {
wp_register_script('um_datetime_locale', um_url . 'assets/js/pickadate/translations/' . $locale . '.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
}
}
wp_register_script( 'um_scripts', $this->front_js_baseurl . 'um-scripts' . $this->suffix . '.js', array( 'um_functions', 'um_crop', 'um_raty', 'select2', 'um_jquery_form', 'um_fileupload', 'um_datetime', 'um_datetime_date', 'um_datetime_time', 'um_datetime_legacy' ), ultimatemember_version, true );
wp_register_script( 'um_responsive', $this->front_js_baseurl . 'um-responsive' . $this->suffix . '.js', array( 'um_scripts' ), ultimatemember_version, true );
wp_register_script( 'um_modal', $this->front_js_baseurl . 'um-modal' . $this->suffix . '.js', array( 'um_responsive' ), ultimatemember_version, true );
wp_register_style( 'select2', $this->front_css_baseurl . 'select2/select2.min.css', array(), ultimatemember_version );
wp_register_style( 'um_datetime', $this->front_css_baseurl . 'pickadate/default.css', array(), ultimatemember_version );
wp_register_style( 'um_datetime_date', $this->front_css_baseurl . 'pickadate/default.date.css', array( 'um_datetime' ), ultimatemember_version );
wp_register_style( 'um_datetime_time', $this->front_css_baseurl . 'pickadate/default.time.css', array( 'um_datetime' ), ultimatemember_version );
wp_register_style( 'um_scrollbar', $this->front_css_baseurl . 'simplebar.css', array(), ultimatemember_version );
wp_register_style( 'um_crop', $this->front_css_baseurl . 'um-crop.css', array(), ultimatemember_version );
wp_register_style( 'um_tipsy', $this->front_css_baseurl . 'um-tipsy.css', array(), ultimatemember_version );
wp_register_style( 'um_responsive', $this->front_css_baseurl . 'um-responsive.css', array(), ultimatemember_version );
wp_register_style( 'um_modal', $this->front_css_baseurl . 'um-modal.css', array(), ultimatemember_version );
wp_register_style( 'um_styles', $this->front_css_baseurl . 'um-styles.css', array(), ultimatemember_version );
wp_register_style( 'um_members', $this->front_css_baseurl . 'um-members.css', array(), ultimatemember_version );
wp_register_style( 'um_profile', $this->front_css_baseurl . 'um-profile.css', array(), ultimatemember_version );
wp_register_style( 'um_account', $this->front_css_baseurl . 'um-account.css', array(), ultimatemember_version );
wp_register_style( 'um_misc', $this->front_css_baseurl . 'um-misc.css', array(), ultimatemember_version );
wp_register_style( 'um_default_css', $this->front_css_baseurl . 'um-old-default.css', array( 'um_crop', 'um_tipsy', 'um_raty', 'um_responsive', 'um_modal', 'um_styles', 'um_members', 'um_profile', 'um_account', 'um_misc', 'um_datetime_date', 'um_datetime_time', 'um_scrollbar', 'select2' ), ultimatemember_version );
wp_enqueue_script( 'um_modal' );
wp_enqueue_style( 'um_default_css' );
}
/**
* Load js for Add/Edit User form
*/
function load_role_wrapper() {
wp_register_script( 'um_admin_role_wrapper', $this->js_url . 'um-admin-role-wrapper.js', array( 'jquery' ), ultimatemember_version, true );
$localize_roles_data = get_option( 'um_roles' );
wp_localize_script( 'um_admin_role_wrapper', 'um_roles', (array) $localize_roles_data );
wp_enqueue_script( 'um_admin_role_wrapper' );
}
/**
* Enter title placeholder
*
* @param $title
*
* @return string
*/
function enter_title_here( $title ) {
$screen = get_current_screen();
if ( 'um_directory' == $screen->post_type ) {
$title = __( 'e.g. Member Directory', 'ultimate-member' );
} elseif ( 'um_form' == $screen->post_type ) {
$title = __( 'e.g. New Registration Form', 'ultimate-member' );
}
return $title;
}
/**
* Runs on admin head
*/
function admin_head() {
if ( UM()->admin()->is_plugin_post_type() ) { ?>
<style type="text/css">
.um-admin.post-type-<?php echo esc_attr( get_post_type() ); ?> div#slugdiv,
.um-admin.post-type-<?php echo esc_attr( get_post_type() ); ?> div#minor-publishing,
.um-admin.post-type-<?php echo esc_attr( get_post_type() ); ?> div#screen-meta-links
{display:none}
</style>
<?php }
}
/**
* Load Form
*/
function load_form() {
wp_register_style( 'um_admin_form', $this->css_url . 'um-admin-form.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_form' );
wp_register_script( 'um_admin_form', $this->js_url . 'um-admin-form.js', array( 'jquery' ), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_form' );
}
/**
* Load Forms
*/
function load_forms() {
wp_register_style( 'um_ui', $this->front_css_baseurl . 'jquery-ui.css', array(), ultimatemember_version );
wp_register_style( 'um_admin_forms', $this->css_url . 'um-admin-forms.css', array( 'wp-color-picker', 'um_ui' ), ultimatemember_version );
wp_enqueue_style( 'um_admin_forms' );
wp_register_script( 'um_admin_forms', $this->js_url . 'um-admin-forms.js', array( 'jquery', 'wp-i18n' ), ultimatemember_version, true );
wp_localize_script( 'um_admin_forms', 'um_forms_data', array(
'successfully_redirect' => add_query_arg( array( 'page' => 'um_options', 'tab' => 'misc', 'msg' => 'updated' ), admin_url( 'admin.php' ) ),
) );
wp_enqueue_script( 'um_admin_forms' );
}
/**
* Load dashboard
*/
function load_dashboard() {
wp_register_style( 'um_admin_dashboard', $this->css_url . 'um-admin-dashboard.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_dashboard' );
}
/**
* Load settings
*/
function load_settings() {
wp_register_style( 'um_admin_settings', $this->css_url . 'um-admin-settings.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_settings' );
wp_register_script( 'um_admin_settings', $this->js_url . 'um-admin-settings.js', array( 'jquery', 'wp-i18n' ), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_settings' );
}
/**
* Load modal
*/
function load_modal() {
wp_register_style( 'um_admin_modal', $this->css_url . 'um-admin-modal.css', array( 'wp-color-picker' ), ultimatemember_version );
wp_enqueue_style( 'um_admin_modal' );
wp_register_script( 'um_admin_modal', $this->js_url . 'um-admin-modal.js', array( 'jquery', 'editor', 'wp-util', 'wp-color-picker', 'wp-tinymce', 'wp-i18n' ), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_modal' );
}
/**
* Field Processing
*/
function load_field() {
wp_register_script( 'um_admin_field', $this->js_url . 'um-admin-field.js', array('jquery', 'wp-util'), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_field' );
}
/**
* Load Builder
*/
function load_builder() {
wp_register_script( 'um_admin_builder', $this->js_url . 'um-admin-builder.js', array('jquery', 'wp-util'), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_builder' );
//hide footer text on add/edit UM Forms
//layouts crashed because we load and hide metaboxes
//and WP calculate page height
$hide_footer = false;
global $pagenow, $post;
if ( ( 'post.php' == $pagenow || 'post-new.php' == $pagenow ) &&
( ( isset( $_GET['post_type'] ) && 'um_form' == sanitize_key( $_GET['post_type'] ) ) ||
( isset( $post->post_type ) && 'um_form' == $post->post_type ) ) ) {
$hide_footer = true;
}
$localize_data = array(
'hide_footer' => $hide_footer,
);
wp_localize_script( 'um_admin_builder', 'um_admin_builder_data', $localize_data );
wp_register_script( 'um_admin_dragdrop', $this->js_url . 'um-admin-dragdrop.js', array('jquery', 'wp-util'), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_dragdrop' );
wp_register_style( 'um_admin_builder', $this->css_url . 'um-admin-builder.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_builder' );
}
/**
* Load core WP styles/scripts
*/
function load_core_wp() {
wp_enqueue_script( 'jquery-ui-draggable' );
wp_enqueue_script( 'jquery-ui-sortable' );
wp_enqueue_script( 'jquery-ui-tooltip' );
}
/**
* Load Admin Styles
*/
function load_css() {
wp_register_style( 'um_admin_menu', $this->css_url . 'um-admin-menu.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_menu' );
wp_register_style( 'um_admin_columns', $this->css_url . 'um-admin-columns.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_columns' );
wp_register_style( 'um_admin_misc', $this->css_url . 'um-admin-misc.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_misc' );
}
/**
* Load functions js
*/
function load_functions() {
wp_register_script( 'um_scrollbar', um_url . 'assets/js/simplebar.js', array( 'jquery' ), ultimatemember_version, true );
wp_register_script( 'um_functions', um_url . 'assets/js/um-functions.js', array( 'jquery', 'jquery-masonry', 'wp-util', 'um_scrollbar' ), ultimatemember_version, true );
wp_enqueue_script( 'um_functions' );
}
/**
* Load Fonticons
*/
function load_fonticons() {
wp_register_style( 'um_fonticons_ii', um_url . 'assets/css/um-fonticons-ii.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_fonticons_ii' );
wp_register_style( 'um_fonticons_fa', um_url . 'assets/css/um-fonticons-fa.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_fonticons_fa' );
}
/**
* Load global css
*/
function load_global_scripts() {
wp_register_script( 'um_admin_global', $this->js_url . 'um-admin-global.js', array('jquery'), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_global' );
wp_register_style( 'um_admin_global', $this->css_url . 'um-admin-global.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_global' );
}
/**
* Load jQuery custom code
*/
function load_custom_scripts() {
wp_register_script( 'um_datetime', $this->front_js_baseurl . 'pickadate/picker.js', array( 'jquery' ), ultimatemember_version, true );
wp_register_script( 'um_datetime_date', $this->front_js_baseurl . 'pickadate/picker.date.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
wp_register_script( 'um_datetime_time', $this->front_js_baseurl . 'pickadate/picker.time.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
wp_register_script( 'um_datetime_legacy', $this->front_js_baseurl . 'pickadate/legacy.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
// load a localized version for date/time
$locale = get_locale();
if ( $locale ) {
if ( file_exists( WP_LANG_DIR . '/plugins/ultimate-member/assets/js/pickadate/' . $locale . '.js' ) ) {
wp_register_script('um_datetime_locale', content_url() . '/languages/plugins/ultimate-member/assets/js/pickadate/' . $locale . '.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
} elseif ( file_exists( um_path . 'assets/js/pickadate/translations/' . $locale . '.js' ) ) {
wp_register_script('um_datetime_locale', um_url . 'assets/js/pickadate/translations/' . $locale . '.js', array( 'jquery', 'um_datetime' ), ultimatemember_version, true );
}
}
wp_register_style( 'um_datetime', $this->front_css_baseurl . 'pickadate/default.css', array(), ultimatemember_version );
wp_register_style( 'um_datetime_date', $this->front_css_baseurl . 'pickadate/default.date.css', array( 'um_datetime' ), ultimatemember_version );
wp_register_style( 'um_datetime_time', $this->front_css_baseurl . 'pickadate/default.time.css', array( 'um_datetime' ), ultimatemember_version );
wp_enqueue_style( 'um_datetime_date', 'um_datetime_time' );
wp_register_script( 'um_admin_scripts', $this->js_url . 'um-admin-scripts.js', array('jquery','wp-util', 'wp-color-picker', 'um_datetime', 'um_datetime_date', 'um_datetime_time', 'um_datetime_legacy' ), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_scripts' );
}
/**
* Load jQuery custom code
*/
function load_nav_manus_scripts() {
wp_register_script( 'um_admin_nav_manus', $this->js_url . 'um-admin-nav-menu.js', array('jquery','wp-util'), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_nav_manus' );
}
/**
* Load AJAX
*/
function load_ajax_js() {
wp_register_script( 'um_admin_ajax', $this->js_url . 'um-admin-ajax.js', array('jquery','wp-util'), ultimatemember_version, true );
wp_enqueue_script( 'um_admin_ajax' );
}
/**
* Load Gutenberg scripts
*/
function load_gutenberg_js() {
//disable Gutenberg scripts to avoid the conflicts
$disable_script = apply_filters( 'um_disable_blocks_script', false );
if ( $disable_script ) {
return;
}
$restricted_blocks = UM()->options()->get( 'restricted_blocks' );
if ( empty( $restricted_blocks ) ) {
return;
}
wp_register_script( 'um_block_js', $this->js_url . 'um-admin-blocks.js', array( 'wp-i18n', 'wp-blocks', 'wp-components' ), ultimatemember_version, true );
wp_set_script_translations( 'um_block_js', 'ultimate-member' );
$restrict_options = array();
$roles = UM()->roles()->get_roles( false, array( 'administrator' ) );
if ( ! empty( $roles ) ) {
foreach ( $roles as $role_key => $title ) {
$restrict_options[] = array(
'label' => $title,
'value' => $role_key
);
}
}
wp_localize_script( 'um_block_js', 'um_restrict_roles', $restrict_options );
wp_enqueue_script( 'um_block_js' );
}
/**
* Load Gutenberg blocks js
*/
function load_gutenberg_shortcode_blocks() {
if ( ! function_exists( 'register_block_type' ) ) {
// Gutenberg is not active.
return;
}
//disable Gutenberg scripts to avoid the conflicts
$disable_script = apply_filters( 'um_disable_blocks_script', false );
if ( $disable_script ) {
return;
}
$enable_blocks = UM()->options()->get( 'enable_blocks' );
if ( empty( $enable_blocks ) ) {
return;
}
wp_register_script( 'um-blocks-shortcode-js', $this->js_url . 'um-admin-blocks-shortcode.js', array( 'wp-i18n', 'wp-blocks', 'wp-components', /*'rich-text'*/ ), ultimatemember_version, true );
wp_set_script_translations( 'um-blocks-shortcode-js', 'ultimate-member' );
wp_enqueue_script( 'um-blocks-shortcode-js' );
$account_settings = array(
'password' => array(
'label' => __( 'Password', 'ultimate-member' ),
'enabled' => UM()->options()->get( 'account_tab_password' ),
),
'privacy' => array(
'label' => __( 'Privacy', 'ultimate-member' ),
'enabled' => UM()->options()->get( 'account_tab_privacy' ),
),
'notifications' => array(
'label' => __( 'Notifications', 'ultimate-member' ),
'enabled' => UM()->options()->get( 'account_tab_notifications' ),
),
'delete' => array(
'label' => __( 'Delete', 'ultimate-member' ),
'enabled' => UM()->options()->get( 'account_tab_delete' ),
),
);
wp_localize_script( 'um-blocks-shortcode-js', 'um_account_settings', $account_settings );
/**
* create gutenberg blocks
*/
register_block_type( 'um-block/um-user-profile-wall', array(
'editor_script' => 'um-blocks-shortcode-js',
) );
register_block_type( 'um-block/um-forms', array(
'editor_script' => 'um-blocks-shortcode-js',
) );
register_block_type( 'um-block/um-member-directories', array(
'editor_script' => 'um-blocks-shortcode-js',
) );
register_block_type( 'um-block/um-password-reset', array(
'editor_script' => 'um-blocks-shortcode-js',
) );
register_block_type( 'um-block/um-account', array(
'editor_script' => 'um-blocks-shortcode-js',
) );
}
/**
* Add Gutenberg category for UM shortcodes
*
* @param array $categories
* @param $post
*
* @return array
*/
function blocks_category( $categories, $post ) {
$enable_blocks = UM()->options()->get( 'enable_blocks' );
if ( empty( $enable_blocks ) ) {
return $categories;
}
return array_merge(
$categories,
array(
array(
'slug' => 'um-blocks',
'title' => __( 'Ultimate Member Blocks', 'ultimate-member' ),
),
)
);
}
/**
* Load localize scripts
*/
function load_localize_scripts() {
/**
* UM hook
*
* @type filter
* @title um_admin_enqueue_localize_data
* @description Extend localize data at wp-admin side
* @input_vars
* [{"var":"$localize_data","type":"array","desc":"Localize Data"}]
* @change_log
* ["Since: 2.0"]
* @usage add_filter( 'um_admin_enqueue_localize_data', 'function_name', 10, 1 );
* @example
* <?php
* add_filter( 'um_admin_enqueue_localize_data', 'my_admin_enqueue_localize_data', 10, 1 );
* function my_admin_enqueue_localize_data( $localize_data ) {
* // your code here
* return $localize_data;
* }
* ?>
*/
$localize_data = apply_filters( 'um_admin_enqueue_localize_data', array(
'nonce' => wp_create_nonce( "um-admin-nonce" )
)
);
wp_localize_script( 'um_admin_global', 'um_admin_scripts', $localize_data );
}
/**
* Enqueue scripts and styles
*/
function admin_enqueue_scripts() {
if ( UM()->admin()->is_um_screen() ) {
/*if ( get_post_type() != 'shop_order' ) {
UM()->enqueue()->wp_enqueue_scripts();
}*/
$modal_deps = array( 'um-admin-scripts' );
if ( $this->um_cpt_form_screen ) {
$this->enqueue_frontend_preview_assets();
$modal_deps[] = 'um-responsive';
}
$this->load_functions();
$this->load_global_scripts();
$this->load_form();
$this->load_forms();
$this->load_custom_scripts();
$this->load_modal();
$this->load_dashboard();
$this->load_settings();
$this->load_field();
$this->load_builder();
$this->load_css();
$this->load_core_wp();
$this->load_ajax_js();
$this->load_fonticons();
$this->load_localize_scripts();
//scripts for frontend preview
UM()->enqueue()->load_imagecrop();
UM()->enqueue()->load_css();
UM()->enqueue()->load_tipsy();
UM()->enqueue()->load_modal();
UM()->enqueue()->load_responsive();
wp_register_script( 'um_raty', um_url . 'assets/js/um-raty' . UM()->enqueue()->suffix . '.js', array( 'jquery', 'wp-i18n' ), ultimatemember_version, true );
wp_register_style( 'um_raty', um_url . 'assets/css/um-raty.css', array(), ultimatemember_version );
wp_register_style( 'um_default_css', um_url . 'assets/css/um-old-default.css', '', ultimatemember_version, 'all' );
wp_enqueue_style( 'um_default_css' );
if ( is_rtl() ) {
wp_register_style( 'um_admin_rtl', $this->css_url . 'um-admin-rtl.css', array(), ultimatemember_version );
wp_enqueue_style( 'um_admin_rtl' );
}
} else {
$this->load_global_scripts();
$this->load_localize_scripts();
}
global $wp_version, $current_screen;
if ( version_compare( $wp_version, '5.0', '>=' ) && ! empty( $this->post_page ) ) {
if ( $current_screen->is_block_editor() ) {
$this->load_gutenberg_js();
$this->load_gutenberg_shortcode_blocks();
}
}
}
/**
* Print editor scripts if they are not printed by default
*/
function admin_footer_scripts() {
/**
* @var $class \_WP_Editors
*/
$class = '\_WP_Editors';
if ( did_action( 'print_default_editor_scripts' ) ) {
return;
}
if ( did_action( 'wp_tiny_mce_init' ) ) {
return;
}
if ( has_action( 'admin_print_footer_scripts', array( $class, 'editor_js' ) ) ) {
return;
}
if ( ! class_exists( $class, false ) ) {
require_once( ABSPATH . WPINC . '/class-wp-editor.php' );
}
$class::force_uncompressed_tinymce();
$class::enqueue_scripts();
$class::editor_js();
}
}
}
| 35.643377
| 319
| 0.660963
|
33e900bdd6f142ecbe88bd9c4bf3eb6d937bfa2c
| 9,790
|
h
|
C
|
nRF5_SDK_12/components/sdk_validation.h
|
Yugontech/SenStick
|
9ebd86a342a2c66c2759ba030dbd84c82bab5f2e
|
[
"MIT"
] | 77
|
2015-09-20T01:50:16.000Z
|
2022-03-30T18:13:31.000Z
|
linebeacon/src/nRF5_SDK_12/components/sdk_validation.h
|
FaBoPlatform/OpenBeacon
|
abf55dc53b8d3bae9c05c23a2e313c6f3d230160
|
[
"Apache-2.0"
] | 41
|
2015-09-24T02:56:55.000Z
|
2021-05-13T13:52:12.000Z
|
linebeacon/src/nRF5_SDK_12/components/sdk_validation.h
|
FaBoPlatform/OpenBeacon
|
abf55dc53b8d3bae9c05c23a2e313c6f3d230160
|
[
"Apache-2.0"
] | 34
|
2015-11-06T22:50:28.000Z
|
2022-01-18T07:01:51.000Z
|
/* Copyright (c) 2016 Nordic Semiconductor. All Rights Reserved.
*
* The information contained herein is property of Nordic Semiconductor ASA.
* Terms and conditions of usage are described in detail in NORDIC
* SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
*
* Licensees are granted free, non-transferable use of the information. NO
* WARRANTY of ANY KIND is provided. This heading must NOT be removed from
* the file.
*
*/
#ifndef SDK_VALIDATION_H
#define SDK_VALIDATION_H
#include "nrf_peripherals.h"
#include "sdk_config.h"
#ifdef __cplusplus
extern "C" {
#endif
// Validate peripheral availibility
#if ((defined(SAADC_ENABLED)) && (SAADC_ENABLED > 0) && (!defined(SAADC_PRESENT)))
#error "SAADC not present in selected MCU."
#endif
#if ((defined(ADC_ENABLED)) && (ADC_ENABLED > 0) && (!defined(ADC_PRESENT)))
#error "SAADC not present in selected MCU."
#endif
#if ((defined(I2S_ENABLED)) && (I2S_ENABLED > 0) && (!defined(I2S_PRESENT)))
#error "I2S not present in selected MCU."
#endif
#if ((defined(COMP_ENABLED)) && (COMP_ENABLED > 0) && (!defined(COMP_PRESENT)))
#error "COMP not present in selected MCU."
#endif
#if ((defined(LPCOMP_ENABLED)) && (LPCOMP_ENABLED > 0) && (!defined(LPCOMP_PRESENT)))
#error "LPCOMP not present in selected MCU."
#endif
#if ((defined(SPIS0_ENABLED)) && (SPIS0_ENABLED > 0) && (!defined(SPIS_PRESENT)))
#error "SPIS0 instance not present in selected MCU."
#endif
#if ((defined(EGU_ENABLED)) && (EGU_ENABLED > 0) && (!defined(EGU_PRESENT)))
#error "EGU instance not present in selected MCU."
#endif
#if ((defined(NFC_HAL_ENABLED)) && (NFC_HAL_ENABLED > 0) && (!defined(NFCT_PRESENT)))
#error "NFC TAG not present in selected MCU."
#endif
// Validate count of instances
#if ((defined(RTC2_ENABLED)) && (RTC2_ENABLED > 0) && (RTC_COUNT < 2))
#error "RTC2 not present in selected MCU."
#endif
#if ((defined(TWIS0_ENABLED) || defined(TWIS1_ENABLED)) &&\
((TWIS0_ENABLED + TWIS1_ENABLED) > 0) &&\
(!defined(TWIS_PRESENT)))
#error "TWIS not present in selected MCU."
#endif
#if ((defined(SPIS2_ENABLED)) && (SPIS2_ENABLED > 0) && (SPIS_COUNT < 2))
#error "SPI2/SPIS2 instance not present in selected MCU."
#endif
#if ((defined(TIMER3_ENABLED) || defined(TIMER4_ENABLED)) &&\
((TIMER3_ENABLED + TIMER4_ENABLED ) > 0) &&\
(TIMER_COUNT < 5))
#error "TIMER3 and TIMER4 not present in selected MCU."
#endif
// Validate peripheral sharing feature
#if ((defined(PERIPHERAL_RESOURCE_SHARING_ENABLED)) && (!PERIPHERAL_RESOURCE_SHARING_ENABLED))
#if ((defined(TWIM0_ENABLED) && defined(TWIS0_ENABLED)) &&\
((TWIM0_ENABLED + TWIS0_ENABLED) > 1))
#error "Peripherals overlap. TWIM0, TWIS0 - only one of these can be enabled."
#endif
#if ((defined(TWIM0_ENABLED) && defined(SPIM0_ENABLED)) &&\
((TWIM0_ENABLED + SPIM0_ENABLED) > 1))
#error "Peripherals overlap. TWIM0, SPIM0 - only one of these can be enabled."
#endif
#if ((defined(TWIM0_ENABLED) && defined(SPIS0_ENABLED)) &&\
((TWIM0_ENABLED + SPIS0_ENABLED) > 1))
#error "Peripherals overlap. TWIM0, SPIS0 - only one of these can be enabled."
#endif
#if ((defined(TWIM0_ENABLED) && defined(SPI0_ENABLED)) &&\
((TWIM0_ENABLED + SPI0_ENABLED) > 1))
#error "Peripherals overlap. TWIM0, SPI0 - only one of these can be enabled."
#endif
#if ((defined(TWIM0_ENABLED) && defined(TWI0_ENABLED)) &&\
((TWIM0_ENABLED + TWI0_ENABLED) > 1))
#error "Peripherals overlap. TWIM0, TWI0 - only one of these can be enabled."
#endif
#if ((defined(TWIS0_ENABLED) && defined(SPIM0_ENABLED)) &&\
((TWIS0_ENABLED + SPIM0_ENABLED) > 1))
#error "Peripherals overlap. TWIS0, SPIM0 - only one of these can be enabled."
#endif
#if ((defined(TWIS0_ENABLED) && defined(SPIS0_ENABLED)) &&\
((TWIS0_ENABLED + SPIS0_ENABLED) > 1))
#error "Peripherals overlap. TWIS0, SPIS0 - only one of these can be enabled."
#endif
#if ((defined(TWIS0_ENABLED) && defined(SPI0_ENABLED)) &&\
((TWIS0_ENABLED + SPI0_ENABLED) > 1))
#error "Peripherals overlap. TWIS0, SPI0 - only one of these can be enabled."
#endif
#if ((defined(TWIS0_ENABLED) && defined(TWI0_ENABLED)) &&\
((TWIS0_ENABLED + TWI0_ENABLED) > 1))
#error "Peripherals overlap. TWIS0, TWI0 - only one of these can be enabled."
#endif
#if ((defined(SPIM0_ENABLED) && defined(SPIS0_ENABLED)) &&\
((SPIM0_ENABLED + SPIS0_ENABLED) > 1))
#error "Peripherals overlap. SPIM0, SPIS0 - only one of these can be enabled."
#endif
#if ((defined(SPIM0_ENABLED) && defined(SPI0_ENABLED)) &&\
((SPIM0_ENABLED + SPI0_ENABLED) > 1))
#error "Peripherals overlap. SPIM0, SPI0 - only one of these can be enabled."
#endif
#if ((defined(SPIM0_ENABLED) && defined(TWI0_ENABLED)) &&\
((SPIM0_ENABLED + TWI0_ENABLED) > 1))
#error "Peripherals overlap. SPIM0, TWI0 - only one of these can be enabled."
#endif
#if ((defined(SPIS0_ENABLED) && defined(SPI0_ENABLED)) &&\
((SPIS0_ENABLED + SPI0_ENABLED) > 1))
#error "Peripherals overlap. SPIS0, SPI0 - only one of these can be enabled."
#endif
#if ((defined(SPIS0_ENABLED) && defined(TWI0_ENABLED)) &&\
((SPIS0_ENABLED + TWI0_ENABLED) > 1))
#error "Peripherals overlap. SPIS0, TWI0 - only one of these can be enabled."
#endif
#if ((defined(SPI0_ENABLED) && defined(TWI0_ENABLED)) &&\
((SPI0_ENABLED + TWI0_ENABLED) > 1))
#error "Peripherals overlap. SPI0, TWI0 - only one of these can be enabled."
#endif
#if ((defined(TWIM1_ENABLED) && defined(TWIS1_ENABLED)) &&\
((TWIM1_ENABLED + TWIS1_ENABLED) > 1))
#error "Peripherals overlap. TWIM1, TWIS1 - only one of these can be enabled."
#endif
#if ((defined(TWIM1_ENABLED) && defined(SPIM1_ENABLED)) &&\
((TWIM1_ENABLED + SPIM1_ENABLED) > 1))
#error "Peripherals overlap. TWIM1, SPIM1 - only one of these can be enabled."
#endif
#if ((defined(TWIM1_ENABLED) && defined(SPIS1_ENABLED)) &&\
((TWIM1_ENABLED + SPIS1_ENABLED) > 1))
#error "Peripherals overlap. TWIM1, SPIS1 - only one of these can be enabled."
#endif
#if ((defined(TWIM1_ENABLED) && defined(SPI1_ENABLED)) &&\
((TWIM1_ENABLED + SPI1_ENABLED) > 1))
#error "Peripherals overlap. TWIM1, SPI1 - only one of these can be enabled."
#endif
#if ((defined(TWIM1_ENABLED) && defined(TWI1_ENABLED)) &&\
((TWIM1_ENABLED + TWI1_ENABLED) > 1))
#error "Peripherals overlap. TWIM1, TWI1 - only one of these can be enabled."
#endif
#if ((defined(TWIS1_ENABLED) && defined(SPIM1_ENABLED)) &&\
((TWIS1_ENABLED + SPIM1_ENABLED) > 1))
#error "Peripherals overlap. TWIS1, SPIM1 - only one of these can be enabled."
#endif
#if ((defined(TWIS1_ENABLED) && defined(SPIS1_ENABLED)) &&\
((TWIS1_ENABLED + SPIS1_ENABLED) > 1))
#error "Peripherals overlap. TWIS1, SPIS1 - only one of these can be enabled."
#endif
#if ((defined(TWIS1_ENABLED) && defined(SPI1_ENABLED)) &&\
((TWIS1_ENABLED + SPI1_ENABLED) > 1))
#error "Peripherals overlap. TWIS1, SPI1 - only one of these can be enabled."
#endif
#if ((defined(TWIS1_ENABLED) && defined(TWI1_ENABLED)) &&\
((TWIS1_ENABLED + TWI1_ENABLED) > 1))
#error "Peripherals overlap. TWIS1, TWI1 - only one of these can be enabled."
#endif
#if ((defined(SPIM1_ENABLED) && defined(SPIS1_ENABLED)) &&\
((SPIM1_ENABLED + SPIS1_ENABLED) > 1))
#error "Peripherals overlap. SPIM1, SPIS1 - only one of these can be enabled."
#endif
#if ((defined(SPIM1_ENABLED) && defined(SPI1_ENABLED)) &&\
((SPIM1_ENABLED + SPI1_ENABLED) > 1))
#error "Peripherals overlap. SPIM1, SPI1 - only one of these can be enabled."
#endif
#if ((defined(SPIM1_ENABLED) && defined(TWI1_ENABLED)) &&\
((SPIM1_ENABLED + TWI1_ENABLED) > 1))
#error "Peripherals overlap. SPIM1, TWI1 - only one of these can be enabled."
#endif
#if ((defined(SPIS1_ENABLED) && defined(SPI1_ENABLED)) &&\
((SPIS1_ENABLED + SPI1_ENABLED) > 1))
#error "Peripherals overlap. SPIS1, SPI1 - only one of these can be enabled."
#endif
#if ((defined(SPIS1_ENABLED) && defined(TWI1_ENABLED)) &&\
((SPIS1_ENABLED + TWI1_ENABLED) > 1))
#error "Peripherals overlap. SPIS1, TWI1 - only one of these can be enabled."
#endif
#if ((defined(SPI1_ENABLED) && defined(TWI1_ENABLED)) &&\
((SPI1_ENABLED + TWI1_ENABLED) > 1))
#error "Peripherals overlap. SPI1, TWI1 - only one of these can be enabled."
#endif
#if ((defined(SPI2_ENABLED) && defined(SPIS2_ENABLED)) &&\
((SPI2_ENABLED + SPIS2_ENABLED) > 1))
#error "Peripherals overlap. SPI2, SPIS2 - only one of these can be enabled."
#endif
#if ((defined(SPIM2_ENABLED) && defined(SPIS2_ENABLED)) &&\
((SPI2_ENABLED + SPIS2_ENABLED) > 1))
#error "Peripherals overlap. SPIM2, SPIS2 - only one of these can be enabled."
#endif
#if ((defined(SPIM2_ENABLED) && defined(SPI2_ENABLED)) &&\
((SPI2_ENABLED + SPIS2_ENABLED) > 1))
#error "Peripherals overlap. SPIM2, SPI2 - only one of these can be enabled."
#endif
#endif
#ifdef NFCT_PRESENT
#if ((defined(NFC_HAL_ENABLED) && defined(CLOCK_ENABLED)) &&\
((NFC_HAL_ENABLED) && (!CLOCK_ENABLED)))
#error "NFC_HAL requires CLOCK to work. NFC_HAL can not be enabled without CLOCK."
#endif
#if ((defined(NFC_HAL_ENABLED) && defined(TIMER4_ENABLED)) &&\
((NFC_HAL_ENABLED + TIMER4_ENABLED) > 1))
#error "TIMER4 is used by NFC_HAL. NFC_HAL, TIMER4 - only one of these can be enabled."
#endif
#endif
// Complex driver validation
#ifdef LPCOMP_PRESENT
#if ((defined(COMP_ENABLED) && defined(LPCOMP_ENABLED)) &&\
(!PERIPHERAL_RESOURCE_SHARING_ENABLED) && \
((COMP_ENABLED + LPCOMP_ENABLED) > 1))
#error "Peripherals overlap. SPIM2, SPI2 - only one of these can be enabled."
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif // SDK_VALIDATION_H
| 35.089606
| 95
| 0.68335
|
060cc57aede962c798ac788e403c62fa82c85cce
| 2,165
|
swift
|
Swift
|
EcoSoapBank/Features/Payment/StripeController.swift
|
DeVitoC/Labs25-Ecosoap-TeamA-IOS
|
1e091e666ea72b7371ee9b85eb57cd579e1d3b79
|
[
"MIT"
] | 2
|
2020-10-26T06:21:51.000Z
|
2021-09-11T01:05:53.000Z
|
EcoSoapBank/Features/Payment/StripeController.swift
|
DeVitoC/Labs25-Ecosoap-TeamA-IOS
|
1e091e666ea72b7371ee9b85eb57cd579e1d3b79
|
[
"MIT"
] | 7
|
2020-08-09T13:31:46.000Z
|
2020-09-15T20:37:03.000Z
|
EcoSoapBank/Features/Payment/StripeController.swift
|
DeVitoC/Labs25-Ecosoap-TeamA-IOS
|
1e091e666ea72b7371ee9b85eb57cd579e1d3b79
|
[
"MIT"
] | 3
|
2020-09-25T19:01:03.000Z
|
2021-02-19T17:08:57.000Z
|
//
// StripeController.swift
// EcoSoapBank
//
// Created by Jon Bash on 2020-08-28.
// Copyright © 2020 Spencer Curtis. All rights reserved.
//
import Foundation
import Stripe
enum StripeError: Error {
case invalidURL
case unknown
}
class StripeController: NSObject {
var backendURL: URL
private(set) var customerContext: STPCustomerContext!
private let user: User
init(user: User, backendURL: URL) {
self.user = user
self.backendURL = backendURL
super.init()
self.customerContext = STPCustomerContext(keyProvider: self)
}
func newPaymentContext() -> STPPaymentContext {
configure(STPPaymentContext(customerContext: customerContext)) {
$0.paymentAmount = 500 // TODO: replace with actual price
}
}
}
// MARK: - Customer Key Provider
extension StripeController: STPCustomerEphemeralKeyProvider {
func createCustomerKey(
withAPIVersion apiVersion: String,
completion: @escaping STPJSONResponseCompletionBlock
) {
let urlComponents = configure(URLComponents(
url: backendURL.appendingPathComponent("ephemeral_keys"),
resolvingAgainstBaseURL: false)
) {
$0?.queryItems = [URLQueryItem(name: "api_version",
value: apiVersion)]
}
guard let url = urlComponents?.url else {
return completion(nil, StripeError.invalidURL)
}
let request = configure(URLRequest(url: url)) {
$0.httpMethod = "POST"
}
URLSession.shared.dataTask(with: request
) { data, response, error in
guard
let response = response as? HTTPURLResponse,
response.statusCode == 200,
let data = data,
let json = (try? JSONSerialization
.jsonObject(with: data, options: []) as? [String: Any])
as [String: Any]??
else {
return completion(nil, error ?? StripeError.unknown)
}
completion(json, nil)
}.resume()
}
}
| 27.405063
| 75
| 0.590762
|
d68a12f28b17879c172da40c5abf1883b222d5aa
| 318
|
cs
|
C#
|
src/SFA.DAS.ApprenticeFeedback.Application/Commands/UpdateApprenticeFeedbackTarget/UpdateApprenticeFeedbackTargetCommandResponse.cs
|
SkillsFundingAgency/das-apprentice-feedback-api
|
d75e58d744b6b3242334a8dcaa70b2a52333b360
|
[
"MIT"
] | null | null | null |
src/SFA.DAS.ApprenticeFeedback.Application/Commands/UpdateApprenticeFeedbackTarget/UpdateApprenticeFeedbackTargetCommandResponse.cs
|
SkillsFundingAgency/das-apprentice-feedback-api
|
d75e58d744b6b3242334a8dcaa70b2a52333b360
|
[
"MIT"
] | null | null | null |
src/SFA.DAS.ApprenticeFeedback.Application/Commands/UpdateApprenticeFeedbackTarget/UpdateApprenticeFeedbackTargetCommandResponse.cs
|
SkillsFundingAgency/das-apprentice-feedback-api
|
d75e58d744b6b3242334a8dcaa70b2a52333b360
|
[
"MIT"
] | null | null | null |
using SFA.DAS.ApprenticeFeedback.Domain.Models;
using System;
namespace SFA.DAS.ApprenticeFeedback.Application.Commands.UpdateApprenticeFeedbackTarget
{
public class UpdateApprenticeFeedbackTargetCommandResponse
{
public ApprenticeFeedbackTarget UpdatedApprenticeFeedbackTarget { get; set; }
}
}
| 28.909091
| 88
| 0.808176
|
1a4fce8ca73064afba7deda533ecd1b95e4ae86b
| 774
|
py
|
Python
|
svg_template_fixer/namespaces.py
|
Braayy/FreeCAD-Scripts
|
1b658a8d707108b8967c892c5e7e85ae116d9d06
|
[
"MIT"
] | null | null | null |
svg_template_fixer/namespaces.py
|
Braayy/FreeCAD-Scripts
|
1b658a8d707108b8967c892c5e7e85ae116d9d06
|
[
"MIT"
] | null | null | null |
svg_template_fixer/namespaces.py
|
Braayy/FreeCAD-Scripts
|
1b658a8d707108b8967c892c5e7e85ae116d9d06
|
[
"MIT"
] | null | null | null |
from xml.etree.ElementTree import register_namespace
namespaces = {
'': 'http://www.w3.org/2000/svg',
'inkscape': 'http://www.inkscape.org/namespaces/inkscape',
'sodipodi': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
'svg': 'http://www.w3.org/2000/svg',
'freecad': 'http://www.freecadweb.org/wiki/index.php?title=Svg_Namespace',
'xml': 'http://www.w3.org/XML/1998/namespace'
}
def namespaced(name, namespace_prefix=''):
return f'{{{namespaces[namespace_prefix]}}}{name}'
def namespaced_attrib(name, namespace_prefix=''):
if namespace_prefix == '':
return name
return namespaced(name, namespace_prefix)
def register_namespaces():
for prefix, url in namespaces.items():
register_namespace(prefix, url)
| 33.652174
| 78
| 0.686047
|
2ca4465ca23c9ca59239947c9babf8dd0212fafd
| 1,486
|
hpp
|
C++
|
3rdparty/stout/include/stout/os/socket.hpp
|
sagar8192/mesos
|
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
|
[
"Apache-2.0"
] | 4
|
2019-03-06T03:04:40.000Z
|
2019-07-20T15:35:00.000Z
|
3rdparty/stout/include/stout/os/socket.hpp
|
sagar8192/mesos
|
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
|
[
"Apache-2.0"
] | 6
|
2018-11-30T08:04:45.000Z
|
2019-05-15T03:04:28.000Z
|
3rdparty/stout/include/stout/os/socket.hpp
|
sagar8192/mesos
|
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
|
[
"Apache-2.0"
] | 4
|
2019-03-11T11:51:22.000Z
|
2020-05-11T07:27:31.000Z
|
// 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.
#ifndef __STOUT_OS_SOCKET_HPP__
#define __STOUT_OS_SOCKET_HPP__
#include <stout/error.hpp>
#include <stout/try.hpp>
#include <stout/os/int_fd.hpp>
#ifdef __WINDOWS__
#include <stout/os/windows/socket.hpp>
#else
#include <stout/os/posix/socket.hpp>
#endif // __WINDOWS__
namespace net {
// Returns a socket file descriptor for the specified options.
// NOTE: on OS X, the returned socket will have the SO_NOSIGPIPE option set.
inline Try<int_fd> socket(int family, int type, int protocol)
{
int_fd s;
if ((s = ::socket(family, type, protocol)) < 0) {
return ErrnoError();
}
#ifdef __APPLE__
// Disable SIGPIPE via setsockopt because OS X does not support
// the MSG_NOSIGNAL flag on send(2).
const int enable = 1;
if (setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &enable, sizeof(int)) == -1) {
return ErrnoError();
}
#endif // __APPLE__
return s;
}
} // namespace net {
#endif // __STOUT_OS_SOCKET_HPP__
| 28.037736
| 76
| 0.728129
|
08346c7bdb669be661fc948bd9de4b775c5b3cac
| 3,909
|
dart
|
Dart
|
lib/indicadores.dart
|
Haple/bate_ponto_mobile
|
84e7e57206adbd6d27b93819c62591bb5299195f
|
[
"MIT"
] | null | null | null |
lib/indicadores.dart
|
Haple/bate_ponto_mobile
|
84e7e57206adbd6d27b93819c62591bb5299195f
|
[
"MIT"
] | null | null | null |
lib/indicadores.dart
|
Haple/bate_ponto_mobile
|
84e7e57206adbd6d27b93819c62591bb5299195f
|
[
"MIT"
] | null | null | null |
import 'dart:convert';
import 'package:bate_ponto_mobile/menu_shell.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'comum/funcoes/exibe_alerta.dart';
import 'comum/funcoes/get_token.dart';
import 'comum/modelos/indicador.dart';
class Indicadores extends StatefulWidget {
static String rota = '/indicadores';
static String titulo = 'Indicadores';
final Indicador indicador;
const Indicadores({
@required this.indicador,
});
@override
IndicadoresState createState() => new IndicadoresState();
}
class IndicadoresState extends State<Indicadores> {
final scaffoldKey = new GlobalKey<ScaffoldState>();
final formKey = new GlobalKey<FormState>();
@override
void initState() {
super.initState();
}
void _responderIndicador(String resposta) async {
final baseUrl = "https://bate-ponto-backend.herokuapp.com";
final url = "$baseUrl/indicadores/${widget.indicador.codigo}/respostas";
Map<String, String> body = {
'resposta': resposta,
};
Map<String, String> headers = {
'Authorization': await getToken(),
};
final response = await http.post(
url,
body: body,
headers: headers,
);
if (response.statusCode == 200) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MenuShell(
checarIndicador: false,
),
),
);
} else {
exibeAlerta(
contexto: context,
titulo: "Opa!",
mensagem: "Não foi possível responder essa pesquisa.",
labelBotao: "Tentar novamente",
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Pesquisa rápida :)",
style: Theme.of(context).textTheme.headline5,
textAlign: TextAlign.center,
),
SizedBox(height: 16.0),
Text(
"${widget.indicador.titulo}",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
// color: Colors.grey
),
textAlign: TextAlign.center,
),
SizedBox(height: 8.0),
Text(
"\"${widget.indicador.mensagem}\"",
style: TextStyle(
fontSize: 18,
fontStyle: FontStyle.italic,
// color: Colors.grey
),
textAlign: TextAlign.center,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.sentiment_dissatisfied),
tooltip: "Discordo",
iconSize: 70,
color: Colors.red,
onPressed: () async {
_responderIndicador("DISCORDO");
},
),
IconButton(
icon: Icon(Icons.sentiment_neutral),
tooltip: "Neutro",
iconSize: 70,
color: Colors.grey,
onPressed: () async {
_responderIndicador("NEUTRO");
},
),
IconButton(
icon: Icon(Icons.sentiment_satisfied),
tooltip: "Concordo",
iconSize: 70,
color: Colors.green,
onPressed: () async {
_responderIndicador("CONCORDO");
},
),
],
)
],
),
),
);
}
}
| 28.122302
| 76
| 0.514965
|
437e964185980e9a46b8cafd063a7cc2ac958d07
| 1,544
|
ts
|
TypeScript
|
src/utils/message.ts
|
huangwc94/scraping-helper-chrome-extension
|
858ebc3d44690cccb320ca577c02b80813afd78d
|
[
"MIT"
] | 60
|
2016-05-27T01:07:24.000Z
|
2022-03-15T13:46:21.000Z
|
src/utils/message.ts
|
huangwc94/scraping-helper-chrome-extension
|
858ebc3d44690cccb320ca577c02b80813afd78d
|
[
"MIT"
] | 9
|
2016-05-26T18:33:22.000Z
|
2022-02-27T14:43:18.000Z
|
src/utils/message.ts
|
huangwc94/scraping-helper-chrome-extension
|
858ebc3d44690cccb320ca577c02b80813afd78d
|
[
"MIT"
] | 20
|
2016-09-29T03:48:18.000Z
|
2021-07-09T18:43:25.000Z
|
import { MessageType, InternalMessageType } from '../models/constant';
import { SelectData, GetDefaultData } from '../models/types';
export function sendMessage(event: MessageType, payload: any = null) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
const tab = tabs[0];
if (!!tab && tab.id !== undefined) {
chrome.tabs.sendMessage(tab.id, {
SH_EVENT: true,
event,
payload,
});
}
});
}
export function listenMessage(cb: (event: MessageType, payload: any) => void) {
chrome.runtime.onMessage.addListener((message) => {
if (message.SH_EVENT) {
cb(message.event, message.payload);
}
});
}
export function sendUpstreamMessage(
event: InternalMessageType,
payload: any = null
) {
parent.postMessage(
{
SH_EVENT: true,
event,
payload,
},
'*'
);
}
export function sendDownstreamMessage(
event: InternalMessageType,
payload: any = null
) {
const frame = document.getElementById('sh-iframe');
if (!!frame) {
//@ts-ignore
frame.contentWindow.postMessage(
{
SH_EVENT: true,
event,
payload,
},
'*'
);
}
}
export function listenInternalMessage(
cb: (event: InternalMessageType, payload: any) => void
) {
window.addEventListener('message', (e) => {
if (e.data.SH_EVENT) {
cb(e.data.event, e.data.payload);
}
});
}
export function updateSelection(select: SelectData) {
sendDownstreamMessage(InternalMessageType.UPDATE, select);
}
| 22.057143
| 79
| 0.626943
|
2b5b7d2c0542d81a1a3524fab9befd93cfd85a2e
| 240
|
rb
|
Ruby
|
app/controllers/home_controller.rb
|
jeyboy/sweety_memo
|
9c28e968b1366a5f1ea72cc3ecb6346dec54c579
|
[
"MIT"
] | null | null | null |
app/controllers/home_controller.rb
|
jeyboy/sweety_memo
|
9c28e968b1366a5f1ea72cc3ecb6346dec54c579
|
[
"MIT"
] | 5
|
2015-12-10T20:17:37.000Z
|
2016-02-17T20:07:08.000Z
|
app/controllers/home_controller.rb
|
jeyboy/sweety_memo
|
9c28e968b1366a5f1ea72cc3ecb6346dec54c579
|
[
"MIT"
] | null | null | null |
class HomeController < ApplicationController
def show
@cated_posts = Post.categorize_by_topics
end
def search
@term = (params[:search][:term] rescue nil)
@results = (Post::search(@term) if @term.present?) || {}
end
end
| 21.818182
| 60
| 0.679167
|
14f18621a1c2b69945d1c084119a166ad41f0533
| 120
|
ts
|
TypeScript
|
ui/src/stores/info.ts
|
timotto/ardumower-modem
|
3391e41a8013cef572f0c4b42d4023b9a20f5463
|
[
"MIT"
] | 1
|
2022-02-28T07:21:55.000Z
|
2022-02-28T07:21:55.000Z
|
ui/src/stores/info.ts
|
timotto/ardumower-modem
|
3391e41a8013cef572f0c4b42d4023b9a20f5463
|
[
"MIT"
] | 3
|
2022-02-18T04:16:10.000Z
|
2022-02-18T04:29:58.000Z
|
ui/src/stores/info.ts
|
timotto/ardumower-modem
|
3391e41a8013cef572f0c4b42d4023b9a20f5463
|
[
"MIT"
] | null | null | null |
import { writable } from "svelte/store"
import type { Info } from "../model"
export const InfoStore = writable<Info>()
| 24
| 41
| 0.7
|
037f6851358e74f61c83fa4ef638532d28942f39
| 2,605
|
rb
|
Ruby
|
app/models/unit_membership.rb
|
scoutplan/scoutplan
|
a9fd2186bea2b79da0d01e693632d5b65eaf888e
|
[
"MIT"
] | 1
|
2021-09-14T20:12:09.000Z
|
2021-09-14T20:12:09.000Z
|
app/models/unit_membership.rb
|
scoutplan/scoutplan
|
a9fd2186bea2b79da0d01e693632d5b65eaf888e
|
[
"MIT"
] | 52
|
2021-09-15T16:07:41.000Z
|
2022-03-31T19:14:20.000Z
|
app/models/unit_membership.rb
|
scoutplan/scoutplan
|
a9fd2186bea2b79da0d01e693632d5b65eaf888e
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
# A join model between Units and Users. In fact, the bulk of the
# business logic in the app is based on a UnitMembership rather than
# a User. The User model is really more for authentication and
# basic user demographic information (e.g. DOB) that's unlikely to change
# from one Unit to another
#
class UnitMembership < ApplicationRecord
include Flipper::Identifier
include Contactable
default_scope { includes(:user).order("users.first_name, users.last_name ASC") }
belongs_to :unit
belongs_to :user
validates_uniqueness_of :user, scope: :unit
validates_presence_of :user, :status
has_many :parent_relationships,
foreign_key: 'child_unit_membership_id',
class_name: 'MemberRelationship',
dependent: :destroy
has_many :child_relationships,
foreign_key: 'parent_unit_membership_id',
class_name: 'MemberRelationship',
dependent: :destroy
has_many :rsvp_tokens, dependent: :destroy
has_many :event_rsvps, dependent: :destroy
has_many :magic_links, dependent: :destroy
alias_attribute :member, :user
alias_attribute :rsvps, :event_rsvps
enum status: { inactive: 0, active: 1 }, _prefix: true
enum member_type: { unknown: 0, youth: 1, adult: 2 }
delegate :full_name, to: :user
delegate :first_name, to: :user
delegate :last_name, to: :user
delegate :display_first_name, to: :user
delegate :full_display_name, to: :user
delegate :short_display_name, to: :user
delegate :nickname, to: :user
delegate :email, to: :user
delegate :phone, to: :user
accepts_nested_attributes_for :user
accepts_nested_attributes_for :child_relationships,
allow_destroy: true,
reject_if: ->(attributes) { attributes['child_unit_membership_id'].blank? }
accepts_nested_attributes_for :parent_relationships, allow_destroy: true
has_settings do |s|
s.key :security, defaults: { enable_magic_links: true }
s.key :communication, defaults: {
via_email: true,
via_sms: false
}
end
def to_param
"#{id}-#{full_display_name.parameterize}"
end
def admin?
role == "admin"
end
def parents
parent_relationships.map(&:parent_member)
end
def children
child_relationships.map(&:child_member)
end
def family
(children | parents).append(self).sort_by(&:first_name)
end
def contactable_object
user
end
def time_zone
user.settings(:locale).time_zone || unit.settings(:locale).time_zone || "Eastern Time (US & Canada)"
end
end
| 28.010753
| 107
| 0.701727
|
5f18298f18ab1dba883c99b315e0941f1e7c98e3
| 294
|
rb
|
Ruby
|
benchmark/tiers/1/bm_lucas_lehmer.rb
|
jmhodges/rubinius
|
dbedc65ca7fc9c8a93c913ea470a9b40382fa55e
|
[
"BSD-3-Clause"
] | 2
|
2016-08-07T17:14:57.000Z
|
2020-03-03T08:51:37.000Z
|
benchmark/tiers/1/bm_lucas_lehmer.rb
|
rkh/rubinius
|
c4bcccbfba7656af4debc843953d7e29e3529ce7
|
[
"BSD-3-Clause"
] | null | null | null |
benchmark/tiers/1/bm_lucas_lehmer.rb
|
rkh/rubinius
|
c4bcccbfba7656af4debc843953d7e29e3529ce7
|
[
"BSD-3-Clause"
] | null | null | null |
# Lucas–Lehmer primality test for Mersenne numbers (2**p - 1)
def is_prime?(p)
s = 4
m = 2**p - 1
(p-2).times do
s = (s**2 - 2) % m
end
s == 0 ? true : false
end
# [9689, 9941, 11213, 19937].each { |n| is_prime?(n) }
# 4 Mersenne's exponents
def Bench.run
is_prime?(9689)
end
| 17.294118
| 61
| 0.581633
|
da2130bdbffbafba41d6330da6d99c807be43729
| 5,400
|
php
|
PHP
|
app/Http/Controllers/PagesController_21.php
|
InterbitsSolutions/CRM
|
5af6e21d07db968f7a492f9a5107777cd145c837
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/PagesController_21.php
|
InterbitsSolutions/CRM
|
5af6e21d07db968f7a492f9a5107777cd145c837
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/PagesController_21.php
|
InterbitsSolutions/CRM
|
5af6e21d07db968f7a492f9a5107777cd145c837
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Http\Requests;
use Aws\S3\S3Client;
use App\Models\MasterBuckets;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
class PagesController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//create object for "S3Client"
$awsBucketsArr = $this->getAwsBuckets();
$bucketAuthCredentials = $this->getAuthCredentials();
$bucketKey = $bucketAuthCredentials['key'];
$bucketSecret = $bucketAuthCredentials['secret'];
$awsName = $bucketAuthCredentials['aws_name'];
$s3client = new S3Client([
'version' => 'latest',
'region' => 'eu-central-1',
'credentials' => [
'key' => $bucketKey,
'secret' => $bucketSecret
]
]);
$graphColorCodes = array('#fb9678', '#01c0c8', '#4F5467', '#00c292', '#03a9f3', '#ab8ce4', '#13dafe', '#99d683', '#B4C1D7');
//get list of all buckets and check if bucket name already exist
try{
$contents = $s3client->listBuckets();
$masterBucketCount = MasterBuckets::count();
//count buckets according to network
$data = array();
$totalBucketCount = 0;
foreach ($contents['Buckets'] as $key =>$bucketData){
try
{
$location = $s3client->getBucketLocation(array('Bucket' => $bucketData['Name'] ));
if (preg_match('/www/',$bucketData['Name'])){
$bucketName = $bucketData['Name'];
//get bucket first string
$firstString = substr($bucketName, 0, strcspn($bucketName, '1234567890'));
$replaceCommonString = str_replace(array($firstString,'.com'), '' , $bucketName);
$getUniqueNumber = $this->getNumericVal($replaceCommonString);
if(!empty($getUniqueNumber)) {
$finalString = preg_replace("/$getUniqueNumber/", '', $replaceCommonString, 1);
}else{
$finalString = $replaceCommonString;
}
if(array_key_exists($finalString,$data)){
$data[$finalString][] = $finalString;
}else{
$data[$finalString][] = $finalString;
}
}
$totalBucketCount++;
}
catch(\Exception $exception){
}
}
}
catch(\Exception $exception){
//set default params
$totalBucketCount = 0;
$masterBucketCount = 0;
$data = array();
$contents = array();
$contents['Buckets'] = array();
//return response
$xmlResponse = $exception->getAwsErrorCode();
if($awsName=='default_credentials'){
if(Auth::check()) {
// user is logged in
flash('Please active Aws Configuration first to process further! ','danger');
}
}else{
// flash($xmlResponse,'danger');
flash('Please active a valid Aws Configuration to process further! ','danger');
}
}
return view('dashboard.home', ['user' => Auth::user(),'contents'=>$contents,'masterBucketCount'=>$masterBucketCount, 'awsBucketsArr'=>$awsBucketsArr, 'graphColorCodes'=>$graphColorCodes,'data'=>$data,'totalBucketCount'=>$totalBucketCount]);
}
public function showUpdatePasswordForm()
{
return view('dashboard.updatePassword');
}
public function updatePassword(Request $request)
{
$rules = [
'currentPassword' => 'required',
'password' => 'required|same:confirmPassword|min:6',
'confirmPassword' => 'required'
];
$validator = Validator::make($request->all(), $rules);
$validator->after(function ($validator) use ($request) {
$check = Auth::validate([
'email' => Auth::user()->email,
'password' => $request->currentPassword
]);
if (!$check) :
$validator->errors()->add('current_password', 'Your current password is incorrect.');
endif;
});
if ($validator->passes()) {
Auth::user()->password = Hash::make($request->password);
Auth::user()->save();
flash('Your password was updated!');
return back();
}
return back()->withErrors($validator);
}
public function getNumericVal ($str) {
preg_match_all('/\d+/', $str, $matches);
return (!empty($matches[0][0])) ? $matches[0][0] : '';
}
}
| 36.986301
| 248
| 0.521111
|
4eeb627169bedae2d2155591f0d9cbfc63e7cb55
| 2,824
|
cpp
|
C++
|
vm/external_libs/llvm/tools/llvmc2/llvmc.cpp
|
marnen/rubinius
|
05b3f9789d01bada0604a7f09921c956bc9487e7
|
[
"BSD-3-Clause"
] | 1
|
2016-05-08T16:58:14.000Z
|
2016-05-08T16:58:14.000Z
|
vm/external_libs/llvm/tools/llvmc2/llvmc.cpp
|
taf2/rubinius
|
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
|
[
"BSD-3-Clause"
] | null | null | null |
vm/external_libs/llvm/tools/llvmc2/llvmc.cpp
|
taf2/rubinius
|
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
|
[
"BSD-3-Clause"
] | null | null | null |
//===--- llvmc.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool provides a single point of access to the LLVM
// compilation tools. It has many options. To discover the options
// supported please refer to the tools' manual page or run the tool
// with the --help option.
//
//===----------------------------------------------------------------------===//
#include "CompilationGraph.h"
#include "Tool.h"
#include "llvm/System/Path.h"
#include "llvm/Support/CommandLine.h"
#include <iostream>
#include <stdexcept>
#include <string>
namespace cl = llvm::cl;
namespace sys = llvm::sys;
using namespace llvmc;
// Built-in command-line options.
// External linkage here is intentional.
cl::list<std::string> InputFilenames(cl::Positional, cl::desc("<input file>"),
cl::ZeroOrMore);
cl::opt<std::string> OutputFilename("o", cl::desc("Output file name"),
cl::value_desc("file"));
cl::list<std::string> Languages("x",
cl::desc("Specify the language of the following input files"),
cl::ZeroOrMore);
cl::opt<bool> VerboseMode("v",
cl::desc("Enable verbose mode"));
cl::opt<bool> WriteGraph("write-graph",
cl::desc("Write compilation-graph.dot file"),
cl::Hidden);
cl::opt<bool> ViewGraph("view-graph",
cl::desc("Show compilation graph in GhostView"),
cl::Hidden);
namespace {
/// BuildTargets - A small wrapper for CompilationGraph::Build.
int BuildTargets(CompilationGraph& graph) {
int ret;
sys::Path tempDir(sys::Path::GetTemporaryDirectory());
try {
ret = graph.Build(tempDir);
}
catch(...) {
tempDir.eraseFromDisk(true);
throw;
}
tempDir.eraseFromDisk(true);
return ret;
}
}
int main(int argc, char** argv) {
try {
CompilationGraph graph;
cl::ParseCommandLineOptions(argc, argv,
"LLVM Compiler Driver (Work In Progress)");
PopulateCompilationGraph(graph);
if (WriteGraph) {
graph.writeGraph();
if (!ViewGraph)
return 0;
}
if (ViewGraph) {
graph.viewGraph();
return 0;
}
if (InputFilenames.empty()) {
std::cerr << "No input files.\n";
return 1;
}
return BuildTargets(graph);
}
catch(const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
catch(...) {
std::cerr << "Unknown error!\n";
}
return 1;
}
| 27.417476
| 80
| 0.549929
|
4bdd76a60f2bc87300dc776e462ddffe3f85cce0
| 6,523
|
dart
|
Dart
|
lib/controllers/SearchController/SearchController.dart
|
Totodore/Videotheque
|
399605daeb163bad70e6e5be38be6325abcd994c
|
[
"Apache-2.0"
] | 3
|
2020-08-11T20:38:08.000Z
|
2021-09-18T20:35:14.000Z
|
lib/controllers/SearchController/SearchController.dart
|
Totodore/Videotheque
|
399605daeb163bad70e6e5be38be6325abcd994c
|
[
"Apache-2.0"
] | 1
|
2021-01-17T01:01:01.000Z
|
2021-01-17T01:01:01.000Z
|
lib/controllers/SearchController/SearchController.dart
|
Totodore/Videotheque
|
399605daeb163bad70e6e5be38be6325abcd994c
|
[
"Apache-2.0"
] | 1
|
2021-01-17T00:56:17.000Z
|
2021-01-17T00:56:17.000Z
|
import 'dart:async';
import 'dart:io';
import 'package:Videotheque/models/api/ApiSearchModel.dart';
import 'package:Videotheque/services/BarcodeLookup.dart';
import 'package:Videotheque/services/FireauthQueries.dart';
import 'package:Videotheque/services/FireconfigQueries.dart';
import 'package:Videotheque/services/FirestoreQueries.dart';
import 'package:Videotheque/Globals.dart';
import 'package:Videotheque/services/Preferences.dart';
import 'package:Videotheque/services/TmdbQueries.dart';
import 'package:Videotheque/utils/Singletons.dart';
import 'package:barcode_scan_fix/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ndialog/ndialog.dart';
import 'package:permission_handler/permission_handler.dart';
class SearchController extends ChangeNotifier {
final focusNode = FocusNode();
final searchInputController = TextEditingController();
final tabLength = QueryTypes.values.length;
final BuildContext context;
String barcode;
Map<QueryTypes, States> loadedViews = Map.fromIterables(QueryTypes.values, List.generate(QueryTypes.values.length, (int index) => States.Nothing)); //List which represent each view if it has been loaded
//List which represent offset of result per view
Map<QueryTypes, ApiSearchModel> dataLoadedView = Map.fromIterables(QueryTypes.values, List.generate(QueryTypes.values.length, (int index) => null));
QueryTypes selectedSort = QueryTypes.all;
int tabIndex = 0;
TabController resultsPageController;
Timer delayOkSearch;
bool innerBoxScrolled;
bool test = true;
String actualQuery = "";
bool triggerChangeListener = false;
FireauthQueries fireauth = Singletons.instance<FireauthQueries>();
FirestoreQueries firestore = Singletons.instance<FirestoreQueries>();
FireconfigQueries fireconfig = Singletons.instance<FireconfigQueries>();
TMDBQueries tmdbQueries = Singletons.instance<TMDBQueries>();
SearchController(this.context) {
focusNode.requestFocus();
}
void searchQuery(String query) async {
QueryTypes type = selectedSort; //On sauvegarde le type actuel au cas ou l'utilisateur change d'index pdt le chargement
if (query == null || query.isEmpty) {
clearView();
notifyListeners();
return;
}
actualQuery = query;
loadedViews[type] = States.Loading;
notifyListeners();
ApiSearchModel result;
switch (type) {
case QueryTypes.all:
result = await tmdbQueries.onlineSearchMulti(query);
break;
case QueryTypes.movie:
result = await tmdbQueries.onlineSearchMovie(query);
break;
case QueryTypes.person:
result = await tmdbQueries.onlineSearchPerson(query);
break;
case QueryTypes.tv:
result = await tmdbQueries.onlineSearchTV(query);
break;
case QueryTypes.collection:
result = await tmdbQueries.onlineSearchCollection(query);
break;
}
if (result.error != null) {
loadedViews[type] = States.Error;
print("Error while searching for $type: ${result.error}");
}
else if ((result.results?.length ?? 0) <= 0) {
loadedViews[type] = States.Empty;
} else {
dataLoadedView[type] = result;
loadedViews[type] = States.Added;
}
notifyListeners();
}
void onchangeQuery(String query) {
if (query == null || query.length == 0)
clearView();
if (delayOkSearch != null) {
delayOkSearch.cancel();
}
delayOkSearch = Timer(Duration(milliseconds: 500), () {delayOkSearch = null; searchQuery(query);});
}
void clearView() {
searchInputController.clear();
actualQuery = "";
dataLoadedView = Map.fromIterables(QueryTypes.values, List.generate(QueryTypes.values.length, (int index) => null));
loadedViews = Map.fromIterables(QueryTypes.values, List.generate(QueryTypes.values.length, (int index) => States.Nothing));
notifyListeners();
}
void updateTabIndex(int index) {
selectedSort = QueryTypes.values[index];
tabIndex = index;
notifyListeners();
if (loadedViews[QueryTypes.values[index]] == States.Nothing && actualQuery.length > 0) {
searchQuery(actualQuery);
}
}
ApiSearchModel getDataResults(QueryTypes type) {
return dataLoadedView[type];
}
bool isChipSelected(int index) => GlobalsMessage.chipData[index]["type"] == selectedSort;
void updateIsInnerBoxScrolled(bool isScrolled) {
innerBoxScrolled = isScrolled;
if (innerBoxScrolled)
focusNode.unfocus();
}
Future<void> barcodeScan() async {
if (!await _requestPermissions()) {
GlobalsFunc.snackBar(context, "L'accès à la caméra est désactivé");
} else
_scan();
}
Future<bool> _requestPermissions() async {
PermissionStatus status = await Permission.camera.request();
return status == PermissionStatus.granted || status == PermissionStatus.restricted;
}
Future<void> _scan() async {
CustomProgressDialog dialog;
try {
barcode = await BarcodeScanner.scan();
dialog = this._dispLoadingDialog();
searchInputController.text = await Singletons.instance<BarcodeLookup>().getTitle(barcode);
searchInputController.selection = TextSelection.collapsed(offset: searchInputController.text.length);
dialog?.dismiss();
searchQuery(searchInputController.text);
notifyListeners();
} on PlatformException catch (e) {
if (e.code == BarcodeScanner.CameraAccessDenied) {
GlobalsFunc.snackBar(context, "L'accès à la caméra est désactivé");
} else {
GlobalsFunc.snackBar(context);
print(e);
}
dialog?.dismiss();
} on HttpException {
GlobalsFunc.snackBar(context, "Erreur lors de la récupération du film, réessayez...");
dialog?.dismiss();
} on FormatException {
// GlobalsFunc.snackBar(context, "Erreur lors du scan, réessayez...");
} catch (e) {
GlobalsFunc.snackBar(context, "Erreur lors du scan du code barre, réessayez...");
dialog?.dismiss();
print(e);
}
}
CustomProgressDialog _dispLoadingDialog() {
CustomProgressDialog progressDialog = CustomProgressDialog(context,
blur: 5,
loadingWidget: LinearProgressIndicator(
backgroundColor: GlobalsColor.green,
valueColor: AlwaysStoppedAnimation<Color>(GlobalsColor.darkGreen),
)
);
progressDialog.show();
return progressDialog;
}
bool get newDisplayResults => Singletons.instance<Preferences>().newSearchUI;
}
| 35.259459
| 204
| 0.707037
|
4e86eb77092afa9ebfa86d4573749bf90953fd90
| 2,417
|
swift
|
Swift
|
Example/Encompass/Routing/AppRoutes.swift
|
NduatiK/Encompass
|
f142655d6346758f67067b9ef1aa65acc29137c7
|
[
"MIT"
] | null | null | null |
Example/Encompass/Routing/AppRoutes.swift
|
NduatiK/Encompass
|
f142655d6346758f67067b9ef1aa65acc29137c7
|
[
"MIT"
] | null | null | null |
Example/Encompass/Routing/AppRoutes.swift
|
NduatiK/Encompass
|
f142655d6346758f67067b9ef1aa65acc29137c7
|
[
"MIT"
] | null | null | null |
//
// AppRoutes.swift
// Encompass_Example
//
// Created by Nduati Kuria on 06/09/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import Encompass
var AppRouter = Encompasser<Routes.AppRoutes>()
extension Routes {
// Other types are usable but an enum is preferred since it has no sense of self
// meaning no retension cycles
enum AppRoutes: RouteConvertible {
// currently the only flaw, case iteratable has to be implemented manaully if one wishes to pass values
static var All: [Routes.AppRoutes] {
return [.present,
.presentVC(value: ""),
.push,
.pushVC(value: "")]
}
case present
// Path uniqueness is implemented by the enum ie no enum overloading (cant have to entries with the enum name present)
// case present(value: String)
case presentVC(value: String)
case push
case pushVC(value: String)
var routeHandler: RouteHandler {
switch self {
case .present:
return RouteHandler { (payload, currentController) in
let vc = ViewController2.instantiate()
currentController.present(vc, animated: true, completion: nil)
}
case .push:
return RouteHandler { (payload, currentController) in
let vc = ViewController2.instantiate()
currentController.navigationController?.pushViewController(vc, animated: true)
}
case .presentVC:
return RouteHandler { (payload, currentController) in
guard let string = payload["value"] as? String else { return }
let vc = ViewController2.instantiate()
vc.passedValue = string
currentController.present(vc, animated: true, completion: nil)
}
case .pushVC:
return RouteHandler { (payload, currentController) in
guard let string = payload["value"] as? String else { return }
let vc = ViewController2.instantiate()
vc.passedValue = string
currentController.navigationController?.pushViewController(vc, animated: true)
}
}
}
}
}
| 33.109589
| 126
| 0.569301
|
ff6e0ee75e123549e571e0f0e37c322e63a24ad9
| 3,945
|
py
|
Python
|
guidesyn/core/models/EnsembleRnnCnn.py
|
eth-sri/guiding-synthesizers
|
3622b80eb3bf633be65036dc47e4ed7b98c3fce8
|
[
"Apache-2.0"
] | 9
|
2020-04-04T16:20:20.000Z
|
2021-07-01T04:11:38.000Z
|
guidesyn/core/models/EnsembleRnnCnn.py
|
eth-sri/guiding-synthesizers
|
3622b80eb3bf633be65036dc47e4ed7b98c3fce8
|
[
"Apache-2.0"
] | 1
|
2020-02-23T20:16:43.000Z
|
2020-02-24T13:10:23.000Z
|
guidesyn/core/models/EnsembleRnnCnn.py
|
eth-sri/guiding-synthesizers
|
3622b80eb3bf633be65036dc47e4ed7b98c3fce8
|
[
"Apache-2.0"
] | 3
|
2020-04-05T16:57:50.000Z
|
2022-02-18T01:46:37.000Z
|
"""
Copyright 2019 Software Reliability Lab, ETH Zurich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import torch.nn as nn
import torch
import torch.nn.functional as f
import numpy as np
from PIL import Image
import torch.optim as optim
import torchvision.utils as vutils
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence, pack_sequence
from guidesyn.core.arguments import Data
# parameters CNN
filterConv1 = 64
filterConv2 = 32
filterConv3 = 16
dense_layer = 256
# parameters RNN
hidden_dim1 = 128
hidden_dim2 = 32
multiplier = 2
bidirectional = True
if bidirectional:
multiplier = multiplier * 2
# consisting of RNN, CNN
class EnsembleRnnCnn(nn.Module):
def __init__(self, args):
super(EnsembleRnnCnn, self).__init__()
self.name = "EnsembleRnnCnn"
_height = args.target_image_height
_width = args.target_image_width
self.targetSize = int((_width / 8) * (_height / 8))
self.lstm1 = nn.LSTM(hidden_dim2 * multiplier, hidden_dim1, bidirectional=bidirectional, batch_first=True)
self.lstm2 = nn.LSTM(args.input_size, hidden_dim2, bidirectional=bidirectional, batch_first=True)
self.conv1 = nn.Conv2d(1, filterConv1, kernel_size=5, stride=1, padding=1)
torch.nn.init.xavier_uniform_(self.conv1.weight)
self.pool1 = torch.nn.MaxPool2d(kernel_size=2, stride=2, padding=1)
self.conv2 = nn.Conv2d(filterConv1, filterConv2, kernel_size=5, stride=1, padding=1)
torch.nn.init.xavier_uniform_(self.conv2.weight)
self.pool2 = torch.nn.MaxPool2d(kernel_size=2, stride=2, padding=1)
self.conv3 = nn.Conv2d(filterConv2, filterConv3, kernel_size=5, stride=1, padding=1)
torch.nn.init.xavier_uniform_(self.conv3.weight)
self.pool3 = torch.nn.MaxPool2d(kernel_size=2, stride=2, padding=1)
self.fc1 = nn.Linear(filterConv3 * self.targetSize + hidden_dim1 * multiplier, dense_layer)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.fc2 = nn.Linear(dense_layer, args.outputClasses)
torch.nn.init.xavier_uniform_(self.fc2.weight)
self.args = args
def forward(self, x, _input, batch_info):
(data, lengths) = _input
# RNN
view_info = pack_padded_sequence(data, lengths.cpu(), batch_first=True)
_, hidden_ind_view = self.lstm2(view_info)
hidden_concat = torch.cat(hidden_ind_view, dim=-1)
hidden_concat = hidden_concat.permute(1, 0, 2).contiguous()
hidden_concat = hidden_concat.view(hidden_concat.size(0), -1)
slices = torch.split(hidden_concat, batch_info.tolist(), 0)
_pack_sequence = pack_sequence(list(slices))
_, hidden = self.lstm1(_pack_sequence)
hidden = torch.cat(hidden, dim=-1)
hidden = hidden.permute(1, 0, 2).contiguous()
output_rnn = hidden.view(hidden.size(0), -1)
# CNN
x = self.args.activation_function(self.conv1(x))
x = self.pool1(x)
x = self.args.activation_function(self.conv2(x))
x = self.pool2(x)
x = self.args.activation_function(self.conv3(x))
x = self.pool3(x)
x = x.view(-1, filterConv3 * self.targetSize)
x = torch.cat((x, output_rnn), 1)
x = self.args.activation_function(self.fc1(x))
x = f.dropout(x, p=self.args.dropout_rate, training=self.training)
x = self.fc2(x)
assert len(x.shape) == self.args.outputClasses
return x
| 39.848485
| 114
| 0.697338
|
b36df4d50ebad9e26237c5d80c4d289815bad022
| 2,755
|
py
|
Python
|
tests/test_ml20m.py
|
keener101/lkpy
|
7c71e8bd1f367d6a1bf57b36b129e025e2ba374d
|
[
"MIT"
] | null | null | null |
tests/test_ml20m.py
|
keener101/lkpy
|
7c71e8bd1f367d6a1bf57b36b129e025e2ba374d
|
[
"MIT"
] | null | null | null |
tests/test_ml20m.py
|
keener101/lkpy
|
7c71e8bd1f367d6a1bf57b36b129e025e2ba374d
|
[
"MIT"
] | null | null | null |
"""
Tests on the ML-20M data set.
"""
import logging
from pathlib import Path
import pandas as pd
import numpy as np
from lenskit.datasets import MovieLens
from lenskit import crossfold as xf
from lenskit.metrics import predict as pm
from lenskit import batch
from lenskit.algorithms import Recommender
from lenskit.algorithms.basic import Popular
from lenskit.algorithms.als import BiasedMF
from lenskit.algorithms import item_knn as knn
try:
import lenskit_tf
except:
lenskit_tf = None
from lenskit.util import Stopwatch
from lenskit.util import test as lktu
import pytest
from pytest import approx
_log = logging.getLogger(__name__)
_ml_path = Path('data/ml-20m')
if _ml_path.exists():
_ml_20m = MovieLens(_ml_path)
else:
_ml_20m = None
@pytest.fixture
def ml20m():
if _ml_20m:
return _ml_20m.ratings
else:
pytest.skip('ML-20M not available')
@pytest.mark.slow
@pytest.mark.realdata
@pytest.mark.parametrize('n_jobs', [1, 2])
def test_pop_recommend(ml20m, rng, n_jobs):
users = rng.choice(ml20m['user'].unique(), 10000, replace=False)
algo = Popular()
_log.info('training %s', algo)
algo.fit(ml20m)
_log.info('recommending with %s', algo)
recs = batch.recommend(algo, users, 10, n_jobs=n_jobs)
assert recs['user'].nunique() == 10000
@pytest.mark.realdata
@pytest.mark.slow
def test_als_isolate(ml20m, rng):
users = rng.choice(ml20m['user'].unique(), 5000, replace=False)
algo = BiasedMF(20, iterations=10)
algo = Recommender.adapt(algo)
_log.info('training %s', algo)
ares = batch.train_isolated(algo, ml20m)
try:
_log.info('recommending with %s', algo)
recs = batch.recommend(ares, users, 10)
assert recs['user'].nunique() == 5000
_log.info('predicting with %s', algo)
pairs = ml20m.sample(1000)
preds = batch.predict(ares, pairs)
assert len(preds) == len(pairs)
finally:
ares.close()
@pytest.mark.realdata
@pytest.mark.slow
@pytest.mark.skip
@pytest.mark.skipif(lenskit_tf is None or not lenskit_tf.TF_AVAILABLE, reason='TensorFlow not available')
def test_tf_isvd(ml20m):
algo = lenskit_tf.IntegratedBiasMF(20)
def eval(train, test):
_log.info('running training')
algo.fit(train)
_log.info('testing %d users', test.user.nunique())
return batch.predict(algo, test)
folds = xf.sample_users(ml20m, 2, 5000, xf.SampleFrac(0.2))
preds = pd.concat(eval(train, test) for (train, test) in folds)
mae = pm.mae(preds.prediction, preds.rating)
assert mae == approx(0.60, abs=0.025)
user_rmse = preds.groupby('user').apply(lambda df: pm.rmse(df.prediction, df.rating))
assert user_rmse.mean() == approx(0.92, abs=0.05)
| 27.55
| 105
| 0.693648
|
b7750d77c6a7896c885755035384e8fcdcb04348
| 346
|
cs
|
C#
|
src/Hoverfly.Core/Model/GlobalActions.cs
|
fredrikn/hoverfly-dotnet
|
55655d0adc41d2b60c314811b52c51a29059daa1
|
[
"Apache-2.0"
] | 32
|
2017-02-16T09:29:16.000Z
|
2021-06-24T04:44:28.000Z
|
src/Hoverfly.Core/Model/GlobalActions.cs
|
abdellee/hoverfly-dotnet
|
40e93971709f20d39c9fe02cd5392f6436aef1a6
|
[
"Apache-2.0"
] | 3
|
2018-01-13T11:34:11.000Z
|
2019-06-28T17:08:52.000Z
|
src/Hoverfly.Core/Model/GlobalActions.cs
|
abdellee/hoverfly-dotnet
|
40e93971709f20d39c9fe02cd5392f6436aef1a6
|
[
"Apache-2.0"
] | 7
|
2017-02-18T10:24:00.000Z
|
2019-04-26T11:00:37.000Z
|
using System.Collections.Generic;
namespace Hoverfly.Core.Model
{
using Newtonsoft.Json;
public class GlobalActions
{
public GlobalActions(IList<DelaySettings> delays)
{
Delays = delays;
}
[JsonProperty("delays")]
public IList<DelaySettings> Delays { get; private set; }
}
}
| 20.352941
| 64
| 0.618497
|
8edb0949a5039df99eb06db54ad70c0758bec588
| 269
|
rb
|
Ruby
|
spec/models/renalware/system/roles_user_spec.rb
|
airslie/renalware-core
|
395fd25b7ef78cf959d8ebe1d3d44a65dd7c02c9
|
[
"MIT"
] | 3
|
2018-08-17T15:18:08.000Z
|
2019-09-01T10:41:09.000Z
|
spec/models/renalware/system/roles_user_spec.rb
|
airslie/renalware-core
|
395fd25b7ef78cf959d8ebe1d3d44a65dd7c02c9
|
[
"MIT"
] | 4
|
2019-12-31T11:57:22.000Z
|
2020-03-22T18:35:17.000Z
|
spec/models/renalware/system/roles_user_spec.rb
|
airslie/renalware-core
|
395fd25b7ef78cf959d8ebe1d3d44a65dd7c02c9
|
[
"MIT"
] | 2
|
2018-06-20T14:57:19.000Z
|
2021-02-15T22:34:37.000Z
|
# frozen_string_literal: true
require "rails_helper"
module Renalware
describe RolesUser, type: :model do
it :aggregate_failures do
is_expected.to belong_to :user
is_expected.to belong_to :role
is_expected.to respond_to(:id)
end
end
end
| 19.214286
| 37
| 0.724907
|
a0aeb9868d2db20a312e150c46e30f4a18f50bf1
| 414
|
lua
|
Lua
|
docs/illustrations/texture/texture_blit.lua
|
holocronweaver/ogre-procedural
|
27ede71b30d12ff05cddc2359acf8f1f8b12f579
|
[
"MIT"
] | 158
|
2016-11-17T19:37:51.000Z
|
2022-03-21T19:57:55.000Z
|
docs/illustrations/texture/texture_blit.lua
|
holocronweaver/ogre-procedural
|
27ede71b30d12ff05cddc2359acf8f1f8b12f579
|
[
"MIT"
] | 94
|
2016-11-18T09:55:57.000Z
|
2021-01-14T08:50:40.000Z
|
docs/illustrations/texture/texture_blit.lua
|
holocronweaver/ogre-procedural
|
27ede71b30d12ff05cddc2359acf8f1f8b12f579
|
[
"MIT"
] | 51
|
2017-05-24T10:20:25.000Z
|
2022-03-17T15:07:02.000Z
|
buffer = Procedural.TextureBuffer(128)
Procedural.Image(buffer):setFile("red_brick.jpg"):process()
Procedural.Blit(buffer):setInputBuffer(bufferGradient):setInputRect(0.0, 0.0, 0.5, 0.5):setOutputRect(0.25, 0.25, 0.75, 0.75):process()
tests:addTextureBuffer(buffer)
dotfile = tests:getDotFile("texture_31", "Blit_Demo")
dotfile:set("Image", "texture_image", "Gradient", "texture_gradient", "Blit", "texture_blit")
| 59.142857
| 135
| 0.76087
|
9707445a51b32ed30713202066950371ed09b060
| 128
|
rb
|
Ruby
|
config/initializers/default_url_options.rb
|
SpillChek2/sched.do
|
491c52065b9877e8dea7416ff47ed73878af7352
|
[
"MIT"
] | 26
|
2015-01-16T08:13:30.000Z
|
2017-10-15T10:03:12.000Z
|
config/initializers/default_url_options.rb
|
SpillChek2/sched.do
|
491c52065b9877e8dea7416ff47ed73878af7352
|
[
"MIT"
] | 1
|
2015-04-02T16:59:04.000Z
|
2015-04-02T16:59:04.000Z
|
config/initializers/default_url_options.rb
|
SpillChek2/sched.do
|
491c52065b9877e8dea7416ff47ed73878af7352
|
[
"MIT"
] | 21
|
2015-01-09T22:20:18.000Z
|
2017-10-31T02:55:44.000Z
|
# to have url helpers available to models
Rails.application.routes.default_url_options = ActionMailer::Base.default_url_options
| 42.666667
| 85
| 0.851563
|
6dc58cffdb0bb719f4ff6a8139af2582a5a9e61b
| 67
|
ts
|
TypeScript
|
types/carbon__icons-react/lib/gender--female/32.d.ts
|
BreezeZin/DefinitelyTyped
|
eafe54f0a6423c73619066be83863b7ff1c3efa5
|
[
"MIT"
] | 35,620
|
2015-11-04T04:20:38.000Z
|
2022-03-31T21:14:58.000Z
|
types/carbon__icons-react/lib/gender--female/32.d.ts
|
BreezeZin/DefinitelyTyped
|
eafe54f0a6423c73619066be83863b7ff1c3efa5
|
[
"MIT"
] | 49,391
|
2015-11-04T05:15:18.000Z
|
2022-03-31T23:44:18.000Z
|
types/carbon__icons-react/lib/gender--female/32.d.ts
|
BreezeZin/DefinitelyTyped
|
eafe54f0a6423c73619066be83863b7ff1c3efa5
|
[
"MIT"
] | 36,450
|
2015-11-04T04:30:18.000Z
|
2022-03-31T23:29:51.000Z
|
import { GenderFemale32 } from "../../";
export = GenderFemale32;
| 16.75
| 40
| 0.656716
|
cc4430517847531cbdbf3b0cc50e0913a4f56891
| 239
|
rb
|
Ruby
|
Casks/avidemux.rb
|
kevinoconnor7/homebrew-cask
|
e5783c0cb753d11725f5152c11d2e40c143002bb
|
[
"BSD-2-Clause"
] | null | null | null |
Casks/avidemux.rb
|
kevinoconnor7/homebrew-cask
|
e5783c0cb753d11725f5152c11d2e40c143002bb
|
[
"BSD-2-Clause"
] | 23
|
2018-12-07T13:23:15.000Z
|
2021-06-28T13:17:38.000Z
|
Casks/avidemux.rb
|
chrisopedia/homebrew-cask
|
924a1d5e765d10638c7b34cdfff347634a4942fe
|
[
"BSD-2-Clause"
] | null | null | null |
class Avidemux < Cask
url 'http://downloads.sourceforge.net/avidemux/Avidemux_2.6.7_ml_64bits_v2.dmg'
homepage 'http://www.avidemux.org/'
version '2.6.7'
sha1 '989e7407667f83c8779b7016eff4418fa76a56da'
link 'Avidemux2.6.app'
end
| 29.875
| 81
| 0.76569
|
7aa042e76a394685fcdcc43a71ca65fdde819f06
| 300
|
cs
|
C#
|
aspnet-core/src/Snow.Template.Application/ParameterManager/Parameters/Dto/ParameterListDto.cs
|
snowchenlei/AbpCustomerAuth
|
5d2cda561f041bb5115353b1fb07fa6f3dd4f280
|
[
"MIT"
] | null | null | null |
aspnet-core/src/Snow.Template.Application/ParameterManager/Parameters/Dto/ParameterListDto.cs
|
snowchenlei/AbpCustomerAuth
|
5d2cda561f041bb5115353b1fb07fa6f3dd4f280
|
[
"MIT"
] | null | null | null |
aspnet-core/src/Snow.Template.Application/ParameterManager/Parameters/Dto/ParameterListDto.cs
|
snowchenlei/AbpCustomerAuth
|
5d2cda561f041bb5115353b1fb07fa6f3dd4f280
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Text;
using Abp.Application.Services.Dto;
namespace Snow.Template.Parameters.Dto
{
public class ParameterListDto : EntityDto<Guid>
{
public string Value { get; set; }
public string TypeName { get; set; }
}
}
| 20
| 51
| 0.693333
|
d36f6a8a0de2f406bd06ca707e18481714f30d66
| 1,608
|
ps1
|
PowerShell
|
Functions/Invoke-FindSimilarFaces.ps1
|
MLauper/ps-AzureFaceAPI
|
3465113efcd6f5afc06616f13f5374609271faad
|
[
"MIT"
] | null | null | null |
Functions/Invoke-FindSimilarFaces.ps1
|
MLauper/ps-AzureFaceAPI
|
3465113efcd6f5afc06616f13f5374609271faad
|
[
"MIT"
] | 1
|
2018-04-02T00:53:46.000Z
|
2018-04-02T00:53:46.000Z
|
Functions/Invoke-FindSimilarFaces.ps1
|
MLauper/ps-AzureFaceAPI
|
3465113efcd6f5afc06616f13f5374609271faad
|
[
"MIT"
] | null | null | null |
function Invoke-FindSimilarFaces {
param(
# faceId of the query face, as retrieved from Invoke-FaceDetection
[parameter(Mandatory=$true)]
[string]$faceId
,
# Existing unique candidate face list, created with New-FaceList
[parameter(
Mandatory=$true,
ParameterSetName='byFaceList'
)]
[string]$faceListId
,
# List of candidate faceIds, created with Invoke-FaceDetection
[parameter(
Mandatory=$true,
ParameterSetName='byFaceId'
)]
[System.Array]$faceIds
,
# Number of candidates returned. Max is 1000, default is 20.
[parameter(Mandatory=$false)]
[Int16]$maxNumOfCandidatesReturned = 20
,
# Can be set to matchFace or matchPerson
# Default is matchPerson
[parameter(Mandatory=$false)]
[String]$mode
)
$Request = "https://api.projectoxford.ai/face/v1.0/findsimilars"
$Body = "{ `"faceId`":`"$faceId`""
if ($PsCmdlet.ParameterSetName -eq "byFaceList"){ $Body = $Body + ",`"faceListId`":`"$faceListId`"" }
elseif ($PsCmdlet.ParameterSetName -eq "byFaceId"){ $Body = $Body + ", `"faceIds`":" + ($faceIds | ConvertTo-Json) }
if ($maxNumOfCandidatesReturned -ne $null) {$Body = $Body + ",`"maxNumOfCandidatesReturned`":`"$maxNumOfCandidatesReturned`"" }
if ($mode -ne "") {$Body = $Body + ",`"mode`": `"$mode`""}
$Body = $Body + "}"
$Response = Invoke-MSCognitiveServiceRequest -Method 'POST' -Uri $Request -Body $Body
return $Response
}
| 37.395349
| 131
| 0.594527
|
9399c1f66454946a748eebdd549f01fb2aaac44c
| 879
|
cs
|
C#
|
samples/Sample-WPF/AppBootstrapper.cs
|
jeisenbach/Caliburn.Micro.Autofac
|
702bd7b95229b8f06b913bb17edebd4835cd7ae8
|
[
"MIT"
] | 14
|
2015-03-28T00:18:18.000Z
|
2020-05-05T14:59:47.000Z
|
samples/Sample-WPF/AppBootstrapper.cs
|
jeisenbach/Caliburn.Micro.Autofac
|
702bd7b95229b8f06b913bb17edebd4835cd7ae8
|
[
"MIT"
] | 9
|
2016-10-20T09:37:40.000Z
|
2021-06-25T15:15:55.000Z
|
samples/Sample-WPF/AppBootstrapper.cs
|
jeisenbach/Caliburn.Micro.Autofac
|
702bd7b95229b8f06b913bb17edebd4835cd7ae8
|
[
"MIT"
] | 12
|
2015-02-06T05:54:49.000Z
|
2020-08-13T13:54:52.000Z
|
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using Autofac;
using Caliburn.Micro.Autofac;
namespace Sample_WPF
{
using System;
using System.Collections.Generic;
using System.Linq;
using Caliburn.Micro;
public class AppBootstrapper : AutofacBootstrapper<ShellViewModel>
{
public AppBootstrapper()
{
Initialize();
}
protected override void ConfigureContainer(ContainerBuilder builder)
{
}
protected override void ConfigureBootstrapper()
{
base.ConfigureBootstrapper();
EnforceNamespaceConvention = false;
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
DisplayRootViewFor<ShellViewModel>();
}
}
}
| 23.131579
| 77
| 0.607509
|
4b70ed422c7aa9b8a7d4385d193be4053386a605
| 2,612
|
rs
|
Rust
|
src/colors.rs
|
kennydo/the-great-purple-wall
|
38c8b8f5e15f590f6f91b6a64caff6a1bee945df
|
[
"MIT"
] | null | null | null |
src/colors.rs
|
kennydo/the-great-purple-wall
|
38c8b8f5e15f590f6f91b6a64caff6a1bee945df
|
[
"MIT"
] | null | null | null |
src/colors.rs
|
kennydo/the-great-purple-wall
|
38c8b8f5e15f590f6f91b6a64caff6a1bee945df
|
[
"MIT"
] | null | null | null |
// Copied from https://www.w3.org/TR/css-color-4/#named-colors
pub const CSS4_COLORS: [&str; 148] = [
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgreen",
"darkgrey",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"green",
"greenyellow",
"grey",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgreen",
"lightgrey",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"rebeccapurple",
"red",
"rosybrown",
"royalblue",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen",
];
| 17.071895
| 62
| 0.532925
|
5459813e56d70afe33b83fdc33d19b56ff7130a7
| 350
|
css
|
CSS
|
html/webapp/style/themes/underline/css/green/page_style.css
|
epoc-software-open/csnc
|
2cf64dfb7ca0568681809b5132e17b356768b4f6
|
[
"BSD-2-Clause"
] | null | null | null |
html/webapp/style/themes/underline/css/green/page_style.css
|
epoc-software-open/csnc
|
2cf64dfb7ca0568681809b5132e17b356768b4f6
|
[
"BSD-2-Clause"
] | 5
|
2020-04-10T05:30:45.000Z
|
2021-02-27T16:00:22.000Z
|
html/webapp/style/themes/underline/css/green/page_style.css
|
epoc-software-open/csnc
|
2cf64dfb7ca0568681809b5132e17b356768b4f6
|
[
"BSD-2-Clause"
] | 1
|
2020-01-28T04:53:11.000Z
|
2020-01-28T04:53:11.000Z
|
body {
background-color:#327177;
}
.leftcolumn {
background-color:#ffffff;
}
.centercolumn {
background-color:#ffffff;
}
.rightcolumn {
background-color:#ffffff;
}
.headercolumn {
background-color:#ffffff;
border-bottom:1px solid #aedd97;
}
.footercolumn {
background-color:#ffffff;
}
#header_menu {
border-bottom: 1px solid #dfe4e7;
}
| 12.068966
| 34
| 0.714286
|
126b11e4015e4f8624449555b7cbdbb927fac2ea
| 1,566
|
cs
|
C#
|
src/CityOfInfo.Data.Mids/ArchetypeWriter.cs
|
patrickhuber/city-of-info
|
1045e064f5146935551d77917f193fbe0cd53cbd
|
[
"MIT"
] | null | null | null |
src/CityOfInfo.Data.Mids/ArchetypeWriter.cs
|
patrickhuber/city-of-info
|
1045e064f5146935551d77917f193fbe0cd53cbd
|
[
"MIT"
] | null | null | null |
src/CityOfInfo.Data.Mids/ArchetypeWriter.cs
|
patrickhuber/city-of-info
|
1045e064f5146935551d77917f193fbe0cd53cbd
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CityOfInfo.Data.Mids
{
public class ArchetypeWriter
{
private BinaryWriter _writer;
public ArchetypeWriter(BinaryWriter writer)
{
_writer = writer;
}
public void Write(Archetype archetype)
{
_writer.Write(archetype.DisplayName);
_writer.Write(archetype.HitPoints);
_writer.Write(archetype.HitPointsMax);
_writer.Write(archetype.DescriptionLong);
_writer.Write(archetype.ResistenceMax);
_writer.Write(archetype.Origins.Length - 1);
foreach (var origin in archetype.Origins)
{
_writer.Write(origin);
}
_writer.Write(archetype.ClassName);
_writer.Write(archetype.ClassType);
_writer.Write(archetype.Column);
_writer.Write(archetype.DescriptionShort);
_writer.Write(archetype.PrimaryGroup);
_writer.Write(archetype.SecondaryGroup);
_writer.Write(archetype.Playable);
_writer.Write(archetype.RechargeMax);
_writer.Write(archetype.DamageMax);
_writer.Write(archetype.RecoveryMax);
_writer.Write(archetype.RegenerationMax);
_writer.Write(archetype.RecoveryBase);
_writer.Write(archetype.RegenerationBase);
_writer.Write(archetype.ThreatBase);
_writer.Write(archetype.PerceptionBase);
}
}
}
| 32.625
| 56
| 0.620051
|
c76d166a61adad0e65d4b37596cef24608d0f20d
| 1,374
|
kt
|
Kotlin
|
app/src/main/kotlin/batect/logging/ContainerNameSetSerializer.kt
|
sschuberth/batect
|
023550c4322d02cfaa005592e689a00d190862aa
|
[
"Apache-2.0"
] | 1
|
2021-08-08T11:08:27.000Z
|
2021-08-08T11:08:27.000Z
|
app/src/main/kotlin/batect/logging/ContainerNameSetSerializer.kt
|
sschuberth/batect
|
023550c4322d02cfaa005592e689a00d190862aa
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/kotlin/batect/logging/ContainerNameSetSerializer.kt
|
sschuberth/batect
|
023550c4322d02cfaa005592e689a00d190862aa
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2017-2021 Charles Korn.
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 batect.logging
import batect.config.Container
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
object ContainerNameSetSerializer : KSerializer<Set<Container>> {
private val serializer = ListSerializer(String.serializer())
override val descriptor: SerialDescriptor = serializer.descriptor
override fun deserialize(decoder: Decoder): Set<Container> = throw UnsupportedOperationException()
override fun serialize(encoder: Encoder, value: Set<Container>) = serializer.serialize(encoder, value.map { it.name })
}
| 41.636364
| 122
| 0.793304
|
87002f18f0f80a08bf27cf81826bdfe8098608c8
| 598
|
lua
|
Lua
|
MMOCoreORB/bin/scripts/mobile/lair/creature_lair/talus_decay_mite_lair_neutral_small.lua
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 18
|
2017-02-09T15:36:05.000Z
|
2021-12-21T04:22:15.000Z
|
MMOCoreORB/bin/scripts/mobile/lair/creature_lair/talus_decay_mite_lair_neutral_small.lua
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 61
|
2016-12-30T21:51:10.000Z
|
2021-12-10T20:25:56.000Z
|
MMOCoreORB/bin/scripts/mobile/lair/creature_lair/talus_decay_mite_lair_neutral_small.lua
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 71
|
2017-01-01T05:34:38.000Z
|
2022-03-29T01:04:00.000Z
|
talus_decay_mite_lair_neutral_small = Lair:new {
mobiles = {{"decay_mite",1}},
spawnLimit = 12,
buildingsVeryEasy = {"object/tangible/lair/base/poi_all_lair_garbage_small.iff"},
buildingsEasy = {"object/tangible/lair/base/poi_all_lair_garbage_small.iff"},
buildingsMedium = {"object/tangible/lair/base/poi_all_lair_garbage_small.iff"},
buildingsHard = {"object/tangible/lair/base/poi_all_lair_garbage_small.iff"},
buildingsVeryHard = {"object/tangible/lair/base/poi_all_lair_garbage_small.iff"},
}
addLairTemplate("talus_decay_mite_lair_neutral_small", talus_decay_mite_lair_neutral_small)
| 49.833333
| 91
| 0.814381
|
df8e4b0bcd81e7314d9d90627fb9a4d75c2ad4c6
| 1,883
|
cs
|
C#
|
3.Exercises_ Lists/2. Change List/Program.cs
|
pelazggi/Tech_Module
|
2109738729f067239b539872e4cdd781844337cb
|
[
"MIT"
] | null | null | null |
3.Exercises_ Lists/2. Change List/Program.cs
|
pelazggi/Tech_Module
|
2109738729f067239b539872e4cdd781844337cb
|
[
"MIT"
] | null | null | null |
3.Exercises_ Lists/2. Change List/Program.cs
|
pelazggi/Tech_Module
|
2109738729f067239b539872e4cdd781844337cb
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _2._Change_List
{
class Program
{
static void Main(string[] args)
{
List<int> inputList = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToList();
string inputLine = Console.ReadLine();
while (inputLine != "Even" && inputLine != "Odd")
{
string[] command = inputLine
.Split(' ')
.ToArray();
if (command[0] == "Delete")
{
int numDelete = int.Parse(command[1]);
for (int i = 0; i < inputList.Count; i++)
{
inputList.Remove(numDelete);
}
}
else if (command[0] == "Insert")
{
int element = int.Parse(command[1]);
int index = int.Parse(command[2]);
inputList.Insert(index, element);
}
inputLine = Console.ReadLine();
}
List<int> result = new List<int>();
if (inputLine == "Odd")
{
for (int i = 0; i < inputList.Count; i++)
{
if (inputList[i] % 2 != 0)
{
result.Add(inputList[i]);
}
}
}
else
{
for (int i = 0; i < inputList.Count; i++)
{
if ( inputList[i] % 2 == 0)
{
result.Add(inputList[i]);
}
}
}
Console.Write(string.Join(" ", result));
}
}
}
| 26.152778
| 61
| 0.350505
|
cf2ee76eb7aa5758a4e5066b6503205b7b6b767c
| 1,284
|
php
|
PHP
|
php/AiYaSchoolPush/xmpush/IOSBuilder.php
|
wslblb/AiYaSchoolPush
|
b2147bad24b104b47a1af34ca7951498333d0f96
|
[
"Apache-2.0"
] | 810
|
2016-10-25T09:24:04.000Z
|
2022-03-25T01:55:11.000Z
|
php/AiYaSchoolPush/xmpush/IOSBuilder.php
|
wslblb/AiYaSchoolPush
|
b2147bad24b104b47a1af34ca7951498333d0f96
|
[
"Apache-2.0"
] | 3
|
2017-01-20T03:47:40.000Z
|
2020-01-06T09:57:48.000Z
|
php/AiYaSchoolPush/xmpush/IOSBuilder.php
|
wslblb/AiYaSchoolPush
|
b2147bad24b104b47a1af34ca7951498333d0f96
|
[
"Apache-2.0"
] | 241
|
2016-10-25T09:48:05.000Z
|
2022-03-25T01:55:14.000Z
|
<?php
/**
* IOS设备的消息体.
* @author wangkuiwei
* @name IOSBuilder
* @desc 构建发送给IOS设备的Message对象。
*
*/
namespace xmpush;
class IOSBuilder extends Message {
const soundUrl = 'sound_url';
const badge = 'badge';
public function __construct(){
parent::__construct();
}
public function description($description){
$this->description = $description;
}
public function timeToLive($ttl){
$this->time_to_live = $ttl;
}
public function timeToSend($timeToSend){
$this->time_to_send = $timeToSend;
}
public function soundUrl($url){
$this->extra(IOSBuilder::soundUrl, $url);
}
public function badge($badge){
$this->extra(IOSBuilder::badge, $badge);
}
public function extra($key,$value){
$this->extra[$key] = $value;
}
public function build(){
$keys = array(
'description','time_to_live','time_to_send'
);
foreach($keys as $key){
if(isset($this->$key)){
$this->fields[$key] = $this->$key;
$this->json_infos[$key] = $this->$key;
}
}
//单独处理extra
$JsonExtra = array();
if(count($this->extra) > 0){
foreach($this->extra as $extraKey=>$extraValue){
$this->fields[Message::EXTRA_PREFIX.$extraKey] = $extraValue;
$JsonExtra[$extraKey] = $extraValue;
}
}
$this->json_infos['extra'] = $JsonExtra;
}
}
?>
| 19.164179
| 65
| 0.641745
|
8234bd2124bbacd8536489641fc3b089124d9bc5
| 4,725
|
rs
|
Rust
|
rustzx-z80/tests/integration/zexall.rs
|
pacmancoder/rustzx
|
6818e164fae45029bd610f0b3caeb9655e5606c4
|
[
"MIT"
] | 106
|
2016-03-12T23:39:40.000Z
|
2022-01-31T15:55:22.000Z
|
rustzx-z80/tests/integration/zexall.rs
|
pacmancoder/rustzx
|
6818e164fae45029bd610f0b3caeb9655e5606c4
|
[
"MIT"
] | 113
|
2016-02-09T21:16:41.000Z
|
2022-02-02T20:53:54.000Z
|
rustzx-z80/tests/integration/zexall.rs
|
rustzx/rustzx
|
ae3c2c91cf1d5c26515245634d61eff7c7eff951
|
[
"MIT"
] | 8
|
2017-12-28T19:34:17.000Z
|
2022-01-28T12:37:46.000Z
|
// Testing strategy was inspired by https://github.com/anotherlin/z80emu
const ZEXALL_IMAGE_BASE_ADDRESS: u16 = 0x0100;
const ZEXALL_IMAGE: &[u8] = include_bytes!("assets/zexall.com");
const ZEXALL_TEST_POINTERS_TABLE_ADDRESS: u16 = 0x013A;
const ZEXALL_BEGIN_MESSAGE_ADDRESS: u16 = 0x01DDA;
const ZEXALL_END_MESSAGE_ADDRESS: u16 = 0x01DF6;
const ZEXALL_INITIAL_SP_VALUE_ADDRESS: u16 = 0x0006;
const ZEXALL_RESET_ADDRESS: u16 = 0x0000;
const ZEXALL_SUCCESS_MESSAGE_SUFFIX: &str = " OK\n\r";
const BDOS_STRING_TERMINATOR: u8 = b'$';
const BDOS_SYSCALL_ADDRESS: u16 = 0x0005;
const BDOS_MAX_STRING_SIZE: u16 = 100;
const BDOS_SYSCALL_PRINT_CHAR: u8 = 2;
const BDOS_SYSCALL_PRINT_STRING: u8 = 9;
const MEMORY_SIZE: usize = 64 * 1024;
const RET_OPCODE: u8 = 0xc9;
use crate::TestingBus;
use core::panic;
use rustzx_z80::Z80;
struct ZexallTester {
cpu: Z80,
bus: TestingBus,
}
impl ZexallTester {
fn new(test_id: u16) -> Self {
let mut cpu = Z80::default();
cpu.regs.set_pc(ZEXALL_IMAGE_BASE_ADDRESS);
let mut bus = TestingBus::new(MEMORY_SIZE);
bus.load_to_memory(ZEXALL_IMAGE, ZEXALL_IMAGE_BASE_ADDRESS);
// Silence redundant messages
bus.patch_memory(ZEXALL_BEGIN_MESSAGE_ADDRESS, BDOS_STRING_TERMINATOR);
bus.patch_memory(ZEXALL_END_MESSAGE_ADDRESS, BDOS_STRING_TERMINATOR);
// Immediate return after "syscall". Actual logic will be performed
// when breakpoint on this address will be detected
bus.patch_memory(BDOS_SYSCALL_ADDRESS, RET_OPCODE);
let [sp_l, sp_h] = 0xC000u16.to_le_bytes();
bus.patch_memory(ZEXALL_INITIAL_SP_VALUE_ADDRESS, sp_l);
bus.patch_memory(ZEXALL_INITIAL_SP_VALUE_ADDRESS + 1, sp_h);
// patch tests table to execute only one test
let test_pointer_addr = ZEXALL_TEST_POINTERS_TABLE_ADDRESS + test_id * 2;
let test_pointer_l = bus.read_memory(test_pointer_addr);
let test_pointer_h = bus.read_memory(test_pointer_addr + 1);
for (idx, byte) in [test_pointer_l, test_pointer_h, 0, 0].iter().enumerate() {
bus.patch_memory(ZEXALL_TEST_POINTERS_TABLE_ADDRESS + idx as u16, *byte);
}
bus.add_breakpoint(BDOS_SYSCALL_ADDRESS);
bus.add_breakpoint(ZEXALL_RESET_ADDRESS);
Self { cpu, bus }
}
fn execute(&mut self) {
let mut output = String::new();
loop {
let syscall_id = self.cpu.regs.get_c();
match self.bus.last_breakpoint() {
Some(ZEXALL_RESET_ADDRESS) => {
break;
}
Some(BDOS_SYSCALL_ADDRESS) if syscall_id == BDOS_SYSCALL_PRINT_CHAR => {
output.push(self.cpu.regs.get_e() as char);
}
Some(BDOS_SYSCALL_ADDRESS) if syscall_id == BDOS_SYSCALL_PRINT_STRING => {
let str_base = self.cpu.regs.get_de();
let mut offset = 0;
loop {
match self.bus.read_memory(str_base + offset) as char {
'$' => break,
ch => output.push(ch),
};
offset += 1;
if offset > BDOS_MAX_STRING_SIZE {
panic!("Too long zexall string");
}
}
}
_ => {}
}
self.cpu.emulate(&mut self.bus);
}
if !output.ends_with(ZEXALL_SUCCESS_MESSAGE_SUFFIX) {
panic!("ERROR. Test output: {}", output);
}
}
}
macro_rules! zexall_tests_internal {
[$idx:expr] => {};
[$idx:expr, $name:ident] => {
paste::paste! {
#[ignore]
#[test]
pub fn [<zexall_ $name>]() {
ZexallTester::new($idx).execute();
}
}
};
[$idx:expr, $name_head:ident, $($name_tail:ident),*] => {
zexall_tests_internal![$idx, $name_head];
zexall_tests_internal![$idx + 1, $($name_tail),*];
};
}
macro_rules! zexall_tests {
[$($name:ident),+ $(,)?] => {
zexall_tests_internal![0, $($name),+];
};
}
zexall_tests![
adc16, add16, add16x, add16y, alu8i, alu8r, alu8rx, alu8x, bitx, bitz80, cpd1, cpi1, daa, inca,
incb, incbc, incc, incd, incde, ince, inch, inchl, incix, inciy, incl, incm, incsp, incx,
incxh, incxl, incyh, incyl, ld161, ld162, ld163, ld164, ld165, ld166, ld167, ld168, ld16im,
ld16ix, ld8bd, ld8im, ld8imx, ld8ix1, ld8ix2, ld8ix3, ld8ixy, ld8rr, ld8rrx, lda, ldd1, ldd2,
ldi1, ldi2, neg, rld, rot8080, rotxy, rotz80, srz80, srzx, st8ix1, st8ix2, st8ix3, stabd,
];
| 35.795455
| 99
| 0.600847
|
088abfdbea4beb165c94ec516c618b687f3ab87a
| 3,078
|
cpp
|
C++
|
Engine/Plugins/FX/Niagara/Source/NiagaraEditor/Private/TypeEditorUtilities/NiagaraIntegerTypeEditorUtilities.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | 1
|
2022-01-29T18:36:12.000Z
|
2022-01-29T18:36:12.000Z
|
Engine/Plugins/FX/Niagara/Source/NiagaraEditor/Private/TypeEditorUtilities/NiagaraIntegerTypeEditorUtilities.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
Engine/Plugins/FX/Niagara/Source/NiagaraEditor/Private/TypeEditorUtilities/NiagaraIntegerTypeEditorUtilities.cpp
|
windystrife/UnrealEngine_NVIDIAGameWork
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
[
"MIT"
] | null | null | null |
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "NiagaraIntegerTypeEditorUtilities.h"
#include "SNiagaraParameterEditor.h"
#include "NiagaraTypes.h"
#include "NiagaraEditorStyle.h"
#include "SSpinBox.h"
class SNiagaraIntegerParameterEditor : public SNiagaraParameterEditor
{
public:
SLATE_BEGIN_ARGS(SNiagaraIntegerParameterEditor) { }
SLATE_END_ARGS();
void Construct(const FArguments& InArgs)
{
ChildSlot
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SSpinBox<int32>)
.Style(FNiagaraEditorStyle::Get(), "NiagaraEditor.ParameterSpinBox")
.Font(FNiagaraEditorStyle::Get().GetFontStyle("NiagaraEditor.ParameterFont"))
.MinValue(TOptional<int32>())
.MaxValue(TOptional<int32>())
.MaxSliderValue(TOptional<int32>())
.MinSliderValue(TOptional<int32>())
.Delta(0.001f)
.Value(this, &SNiagaraIntegerParameterEditor::GetValue)
.OnValueChanged(this, &SNiagaraIntegerParameterEditor::ValueChanged)
.OnValueCommitted(this, &SNiagaraIntegerParameterEditor::ValueCommitted)
.OnBeginSliderMovement(this, &SNiagaraIntegerParameterEditor::BeginSliderMovement)
.OnEndSliderMovement(this, &SNiagaraIntegerParameterEditor::EndSliderMovement)
.MinDesiredWidth(100)
]
];
}
virtual void UpdateInternalValueFromStruct(TSharedRef<FStructOnScope> Struct) override
{
checkf(Struct->GetStruct() == FNiagaraTypeDefinition::GetIntStruct(), TEXT("Struct type not supported."));
IntValue = ((FNiagaraInt32*)Struct->GetStructMemory())->Value;
}
virtual void UpdateStructFromInternalValue(TSharedRef<FStructOnScope> Struct) override
{
checkf(Struct->GetStruct() == FNiagaraTypeDefinition::GetIntStruct(), TEXT("Struct type not supported."));
((FNiagaraInt32*)Struct->GetStructMemory())->Value = IntValue;
}
private:
void BeginSliderMovement()
{
ExecuteOnBeginValueChange();
}
void EndSliderMovement(int32 Value)
{
ExecuteOnEndValueChange();
}
int32 GetValue() const
{
return IntValue;
}
void ValueChanged(int32 Value)
{
IntValue = Value;
ExecuteOnValueChanged();
}
void ValueCommitted(int32 Value, ETextCommit::Type CommitInfo)
{
if (CommitInfo == ETextCommit::OnEnter || CommitInfo == ETextCommit::OnUserMovedFocus)
{
ValueChanged(Value);
}
}
private:
int32 IntValue;
};
TSharedPtr<SNiagaraParameterEditor> FNiagaraEditorIntegerTypeUtilities::CreateParameterEditor() const
{
return SNew(SNiagaraIntegerParameterEditor);
}
bool FNiagaraEditorIntegerTypeUtilities::CanHandlePinDefaults() const
{
return true;
}
FString FNiagaraEditorIntegerTypeUtilities::GetPinDefaultStringFromValue(const FNiagaraVariable& Variable) const
{
int32 Value = 0;
if (Variable.IsDataAllocated())
{
Value = Variable.GetValue<FNiagaraInt32>()->Value;
}
return FString::Printf(TEXT("%i"), Value);
}
void FNiagaraEditorIntegerTypeUtilities::SetValueFromPinDefaultString(const FString& StringValue, FNiagaraVariable& Variable) const
{
Variable.AllocateData();
Variable.GetValue<FNiagaraInt32>()->Value = FCString::Atoi(*StringValue);
}
| 27.482143
| 131
| 0.765432
|
cdf6093abcacdc9457144da8ede36a1201f16e01
| 2,727
|
cs
|
C#
|
Tools/BB10_UnityInjector/Injector_OSX/Injector_OSX/MainWindow.designer.cs
|
reignstudios/Reign-Unity-Plugin5
|
d29868e9d337a0fe0f6f12b8962cbe41aa74a38f
|
[
"BSD-3-Clause"
] | 61
|
2015-12-30T13:34:37.000Z
|
2022-01-23T13:07:44.000Z
|
Tools/BB10_UnityInjector/Injector_OSX/Injector_OSX/MainWindow.designer.cs
|
reignstudios/Reign-Unity-Plugin
|
40c6176e9680891b8cc2e313653d0e10cecd9f6e
|
[
"BSD-3-Clause"
] | 4
|
2016-08-31T16:25:27.000Z
|
2018-03-07T21:11:00.000Z
|
Tools/BB10_UnityInjector/Injector_OSX/Injector_OSX/MainWindow.designer.cs
|
reignstudios/Reign-Unity-Plugin5
|
d29868e9d337a0fe0f6f12b8962cbe41aa74a38f
|
[
"BSD-3-Clause"
] | 20
|
2016-01-30T01:26:35.000Z
|
2018-11-06T12:46:01.000Z
|
// WARNING
//
// This file has been generated automatically by Xamarin Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using MonoMac.Foundation;
using System.CodeDom.Compiler;
namespace Injector_OSX
{
[Register ("MainWindow")]
partial class MainWindow
{
[Outlet]
MonoMac.AppKit.NSButton applyButton { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField barFileName { get; set; }
[Outlet]
MonoMac.AppKit.NSImageView imageView { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField keyName { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField phoneIP { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField phoneLockPass { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField scoreloopPath { get; set; }
[Outlet]
MonoMac.AppKit.NSButton selectBarFile { get; set; }
[Outlet]
MonoMac.AppKit.NSButton selectScoreloopData { get; set; }
[Outlet]
MonoMac.AppKit.NSButton selectUnity { get; set; }
[Outlet]
MonoMac.AppKit.NSButton signBarFile { get; set; }
[Outlet]
MonoMac.AppKit.NSButton unityClassicMode { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField unityPath { get; set; }
[Outlet]
MonoMac.AppKit.NSButton uploadButton { get; set; }
void ReleaseDesignerOutlets ()
{
if (unityClassicMode != null) {
unityClassicMode.Dispose ();
unityClassicMode = null;
}
if (applyButton != null) {
applyButton.Dispose ();
applyButton = null;
}
if (barFileName != null) {
barFileName.Dispose ();
barFileName = null;
}
if (imageView != null) {
imageView.Dispose ();
imageView = null;
}
if (keyName != null) {
keyName.Dispose ();
keyName = null;
}
if (phoneIP != null) {
phoneIP.Dispose ();
phoneIP = null;
}
if (phoneLockPass != null) {
phoneLockPass.Dispose ();
phoneLockPass = null;
}
if (scoreloopPath != null) {
scoreloopPath.Dispose ();
scoreloopPath = null;
}
if (selectBarFile != null) {
selectBarFile.Dispose ();
selectBarFile = null;
}
if (selectScoreloopData != null) {
selectScoreloopData.Dispose ();
selectScoreloopData = null;
}
if (selectUnity != null) {
selectUnity.Dispose ();
selectUnity = null;
}
if (signBarFile != null) {
signBarFile.Dispose ();
signBarFile = null;
}
if (unityPath != null) {
unityPath.Dispose ();
unityPath = null;
}
if (uploadButton != null) {
uploadButton.Dispose ();
uploadButton = null;
}
}
}
[Register ("MainWindowController")]
partial class MainWindowController
{
void ReleaseDesignerOutlets ()
{
}
}
}
| 19.478571
| 84
| 0.647598
|
2c7500f087465b08d310524ead1d392ffa06523d
| 790
|
py
|
Python
|
examples/tiling_9.py
|
byewokko/penrose
|
f339a6f0a2c9b0486f0b46a517bb9b8907c4be07
|
[
"MIT"
] | 7
|
2020-12-24T11:49:36.000Z
|
2022-03-29T00:44:48.000Z
|
examples/tiling_9.py
|
byewokko/penrose
|
f339a6f0a2c9b0486f0b46a517bb9b8907c4be07
|
[
"MIT"
] | 9
|
2020-11-15T00:32:31.000Z
|
2020-12-24T22:05:28.000Z
|
examples/tiling_9.py
|
byewokko/penrose
|
f339a6f0a2c9b0486f0b46a517bb9b8907c4be07
|
[
"MIT"
] | null | null | null |
import multigrid
from ntiling import TilingBuilder
from drawing.pil_draw_simple import Draw
palette = [
"#7fb414",
"#fac70b",
"#127681",
"#df0e62",
"#21174a",
]
draw = Draw(scale=90, width=3*1280, height=3*1280, bg_color=palette[-1])
draw.line_color = None
index_range = (-3, 3)
grid = multigrid.Multigrid(9)
tiling_builder = TilingBuilder(grid)
tiling_builder.prepare_grid(index_range)
tiling_builder.generate_rhomb_list()
for rhomb in tiling_builder._rhombs.values():
c = (rhomb.type() in (4, 5, 3, 6, 2, 7)) + (rhomb.type() in (3, 6, 2, 7)) + (rhomb.type() in (2, 7))
draw.polygon(rhomb.xy(form="xy1"), color=palette[c])
for a, b in rhomb.get_edges():
draw.edge(a.get_xy(form="xy"), b.get_xy(form="xy"), color=palette[-1], width=6)
draw.show()
| 29.259259
| 104
| 0.668354
|
62098f16bff6cef119fe4b5a998e332fd969f86f
| 3,387
|
sql
|
SQL
|
CR_PDS_P.package body.sql
|
morten-egan/testdata_ninja
|
40575ecdd5c4831545624022bb99d86bc96cf28e
|
[
"MIT"
] | 11
|
2017-06-23T10:15:36.000Z
|
2022-02-28T08:43:08.000Z
|
CR_PDS_P.package body.sql
|
morten-egan/testdata_ninja
|
40575ecdd5c4831545624022bb99d86bc96cf28e
|
[
"MIT"
] | 17
|
2017-06-18T19:39:59.000Z
|
2022-03-10T11:52:53.000Z
|
CR_PDS_P.package body.sql
|
morten-egan/testdata_ninja
|
40575ecdd5c4831545624022bb99d86bc96cf28e
|
[
"MIT"
] | 5
|
2020-02-04T18:11:37.000Z
|
2022-01-20T05:40:01.000Z
|
create or replace package body CR_PDS_P
as
begin
testdata_rulebuilder.rules('CR_PDS_P').define_code := q'[begin
:rule_output := 'l_rf_##COLUMN_NAME##_tracker number := nvl(rf_##COLUMN_NAME##, 1);
l_rf_##COLUMN_NAME##_avg number := l_rf_##COLUMN_NAME##_tracker/generator_count;
l_rf_##COLUMN_NAME##_min number := l_rf_##COLUMN_NAME##_avg*0.05;
l_rf_##COLUMN_NAME##_max number := l_rf_##COLUMN_NAME##_avg*1.95;
l_rf_##COLUMN_NAME##_mean number := (l_rf_##COLUMN_NAME##_min + l_rf_##COLUMN_NAME##_max)/2;
l_rf_##COLUMN_NAME##_stddev number := (l_rf_##COLUMN_NAME##_max - l_rf_##COLUMN_NAME##_min)/4;
l_rf_##COLUMN_NAME##_floats number;';
end;]';
testdata_rulebuilder.rules('CR_PDS_P').logic_code := q'[begin
:rule_output := 'if rf_##COLUMN_NAME## is null then';
if '##GENERATOR_ARGS##' is null then
:rule_output := :rule_output || '
l_ret_var.##COLUMN_NAME## := ##GENERATOR##;';
else
:rule_output := :rule_output || '
l_ret_var.##COLUMN_NAME## := ##GENERATOR##(##GENERATOR_ARGS##);';
end if;
:rule_output := :rule_output || '
else';
if upper('##GENERATOR##') = 'CORE_RANDOM.R_FLOAT' then
:rule_output := :rule_output || '
l_rf_##COLUMN_NAME##_floats := 2;';
end if;
:rule_output := :rule_output || '
if l_rf_##COLUMN_NAME##_tracker > l_rf_##COLUMN_NAME##_max and ##POSITION## <= generator_count - 1 then';
if upper('##GENERATOR##') = 'CORE_RANDOM.R_FLOAT' then
:rule_output := :rule_output || '
l_ret_var.##COLUMN_NAME## := ##GENERATOR##(l_rf_##COLUMN_NAME##_floats, l_rf_##COLUMN_NAME##_min, l_rf_##COLUMN_NAME##_max, r_w_min => (l_rf_##COLUMN_NAME##_mean-(2*l_rf_##COLUMN_NAME##_stddev)), r_w_max => (l_rf_##COLUMN_NAME##_mean+(2*l_rf_##COLUMN_NAME##_stddev)), r_weight => 95);';
else
:rule_output := :rule_output || '
l_ret_var.##COLUMN_NAME## := ##GENERATOR##(l_rf_##COLUMN_NAME##_min, l_rf_##COLUMN_NAME##_max, r_w_min => (l_rf_##COLUMN_NAME##_mean-(2*l_rf_##COLUMN_NAME##_stddev)), r_w_max => (l_rf_##COLUMN_NAME##_mean+(2*l_rf_##COLUMN_NAME##_stddev)), r_weight => 95);';
end if;
:rule_output := :rule_output || '
elsif l_rf_##COLUMN_NAME##_tracker < l_rf_##COLUMN_NAME##_max and ##POSITION## <= generator_count - 1 then';
if upper('##GENERATOR##') = 'CORE_RANDOM.R_FLOAT' then
:rule_output := :rule_output || '
l_ret_var.##COLUMN_NAME## := ##GENERATOR##(l_rf_##COLUMN_NAME##_floats, l_rf_##COLUMN_NAME##_min, least(l_rf_##COLUMN_NAME##_avg, (l_rf_##COLUMN_NAME##_tracker*(1/##POSITION##))));';
else
:rule_output := :rule_output || '
l_ret_var.##COLUMN_NAME## := ##GENERATOR##(l_rf_##COLUMN_NAME##_min, least(l_rf_##COLUMN_NAME##_avg, (l_rf_##COLUMN_NAME##_tracker*(1/##POSITION##))));';
end if;
:rule_output := :rule_output || '
else
l_ret_var.##COLUMN_NAME## := l_rf_##COLUMN_NAME##_tracker;
end if;
l_rf_##COLUMN_NAME##_tracker := l_rf_##COLUMN_NAME##_tracker - l_ret_var.##COLUMN_NAME##;
end if;';
end;]';
end CR_PDS_P;
/
| 56.45
| 310
| 0.592265
|
75e137374fcc51f7998523f7bd1867074639973b
| 799
|
swift
|
Swift
|
TransitApp/DirectionsTableFooterView.swift
|
pietro82/TransitApp
|
95c70beb0ba74a3d81816bfb223ac6fce7918771
|
[
"MIT"
] | null | null | null |
TransitApp/DirectionsTableFooterView.swift
|
pietro82/TransitApp
|
95c70beb0ba74a3d81816bfb223ac6fce7918771
|
[
"MIT"
] | null | null | null |
TransitApp/DirectionsTableFooterView.swift
|
pietro82/TransitApp
|
95c70beb0ba74a3d81816bfb223ac6fce7918771
|
[
"MIT"
] | null | null | null |
//
// DirectionsTableFooterView.swift
// TransitApp
//
// Created by Pietro Santececca on 26/01/17.
// Copyright © 2017 Tecnojam. All rights reserved.
//
import UIKit
class DirectionsTableFooterView: UIView {
var footerModel: DirectionsOptionViewModel? {
didSet {
bindViewModel()
}
}
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
class func loadFromNib() -> DirectionsTableFooterView? {
let xib = UINib(nibName: "DirectionsTableFooterView", bundle: nil)
return xib.instantiate(withOwner: nil, options: nil)[0] as? DirectionsTableFooterView
}
func bindViewModel() {
timeLabel.text = footerModel?.arrivalTime
nameLabel.text = footerModel?.arrivalAddress
}
}
| 24.212121
| 93
| 0.669587
|
134329456648c61be216b22492e15baf659a4bc6
| 74,214
|
rb
|
Ruby
|
buddy-bot/modules/tistory.rb
|
AnhNhan/discord-buddy-bot
|
35e80263a47d422ea9495769adf446c906bf633a
|
[
"Apache-2.0"
] | 2
|
2018-02-06T19:24:50.000Z
|
2018-04-03T10:07:57.000Z
|
buddy-bot/modules/tistory.rb
|
AnhNhan/discord-buddy-bot
|
35e80263a47d422ea9495769adf446c906bf633a
|
[
"Apache-2.0"
] | 38
|
2018-03-08T14:10:37.000Z
|
2021-09-27T21:34:23.000Z
|
buddy-bot/modules/tistory.rb
|
AnhNhan/discord-buddy-bot
|
35e80263a47d422ea9495769adf446c906bf633a
|
[
"Apache-2.0"
] | null | null | null |
require 'cgi'
require 'tempfile'
require 'digest/md5'
require 'stringio'
require 'enumerator'
require 'base64'
require 'shellwords'
require 'aws-sdk'
require 'nokogiri'
require 'httparty'
require 'image_size'
require 'parallel'
require 'm3u8'
require 'discordrb'
require 'yaml'
require 'json'
require 'modules/buddy-functionality'
module BuddyBot::Modules::Tistory
extend Discordrb::EventContainer
@@is_testbot = false
@@s3 = nil
@@s3_bucket = nil
@@s3_bucket_name = nil
@@pages = []
@@pages_special = []
@@pages_downloaded = {}
@@sendanywhere_downloaded = {}
@@twitter_list = []
@@twitter_downloaded = {}
@@initialized = false
@@number_of_processes = 5
@@abort_tistory_queue_in_progress = false
@@abort_twitter_queue_in_progress = false
@@twt_consumer_key = nil
@@twt_consumer_secret = nil
@@twt_app_bearer = nil
def self.scan_bot_files()
@@pages = YAML.load_file(BuddyBot.path("content/tistory-list.yml")) || []
@@pages_special = YAML.load_file(BuddyBot.path("content/tistory-special-list.yml")) || []
@@pages_downloaded = YAML.load_file(BuddyBot.path("content/tistory-pages-downloaded.yml")) || {}
@@sendanywhere_downloaded = YAML.load_file(BuddyBot.path("content/downloaded-sendanywhere.yml")) || {}
@@twitter_list = YAML.load_file(BuddyBot.path("content/pages-twitter.yml")) || []
@@twitter_downloaded = YAML.load_file(BuddyBot.path("content/downloaded-twitter.yml")) || {}
bot_config = YAML.load_file(BuddyBot.path("content/bot.yml")) || {}
localconf = YAML::load(File.read(BuddyBot.localconf_filename))
@@is_testbot = localconf["appid"] == bot_config["bot_test_id"]
end
def self.log(message, bot)
BuddyBot::Modules::BuddyFunctionality.log message, bot, Struct.new(:id).new(123456)
end
def self.log_warning(message, bot)
BuddyBot::Modules::BuddyFunctionality.log message, bot, Struct.new(:id).new(12345678)
end
ready do |event|
if !@@initialized
self.scan_bot_files()
@@initialized = true
end
self.log ":information_desk_person: Ready to upload to '#{@@s3_bucket_name}'", event.bot
@@twt_app_bearer = self.twitter_retrieve_app_bearer(@@twt_consumer_key, @@twt_consumer_secret, event.bot)
# self.process_mobile_page("http://gfriendcom.tistory.com/m/145", "http://gfriendcom.tistory.com/m/145", "gfriendcom", "145", event, true)
# self.process_tweet("https://twitter.com/Candle4_YB/status/1007759490588934144", event)
# puts self.process_tweet("https://twitter.com/Mochi_Yellow/status/1007198387693748224", event)
# puts self.process_tweet("https://twitter.com/mystarmyangel/status/1007664325916438528", event)
# self.process_tweet("https://twitter.com/gagadoli/status/1007639571150991361", event)
# self.process_tweet("https://twitter.com/_Simplykpop/status/994782508083539968", event)
end
def self.set_s3_bucket_name(name)
@@s3_bucket_name = name
@@s3 = Aws::S3::Resource.new()
@@s3_bucket = @@s3.bucket(@@s3_bucket_name)
end
def self.set_twitter_credentials(key, secret)
@@twt_consumer_key = key
@@twt_consumer_secret = secret
end
# invoke this command if you want to e.g. add new audio clips or memes, but don't want to restart the bot. for now, you also have to invoke e.g. #audio-load manually afterwards.
message(content: "!crawler-git-sync") do |event|
next unless event.user.id == 139342974776639489
self.crawler_git_sync(event)
end
def self.crawler_git_sync(event)
files = [
"content/tistory-list.yml",
"content/tistory-pages-downloaded.yml",
"content/pages-twitter.yml",
"content/downloaded-twitter.yml",
"content/downloaded-sendanywhere.yml",
]
for file in files
if File.size(BuddyBot.path(file)) == 0
event.send_message ":warning: File `#{file}` was empty, probably still open in an application \*cough\*."
return
end
end
event.channel.split_send "Done.\n#{`cd #{BuddyBot.path} && git pull && git add #{files.join(" ")} && git commit -m "crawler: update pages" && git push`.gsub(/Git LFS: .*?\n/m, "")}"
end
message(start_with: /^!tistory\s/i) do |event|
next if event.user.bot_account?
data = event.content.scan(/^!tistory\s+<?(.*?)\s*>?\s*$/i)[0]
if !data
event.send_message ":warning: You need to specify a tistory page link... #{BuddyBot::Modules::BuddyFunctionality.random_derp_emoji()}"
next
end
orig_input = url = data[0].downcase
# if url !~ /https?:\/\/.*?\.tistory\.com(\/m)?\/\d+$/
# event.send_message ":warning: URL is not a specific page, try e.g. <http://gfriendcom.tistory.com/163>"
# next
# end
if url =~ /tistory\.com\/\d+$/
parts = url.scan(/\/\/(.*?)\.tistory\.com\/(\d+)$/)[0]
url = "http://#{parts[0]}.tistory.com/m/#{parts[1]}"
end
page_name, page_number = url.scan(/\/\/(.*?)\.tistory\.com\/m\/(\d+)$/)[0]
self.process_mobile_page(url, orig_input, page_name, page_number, event, true)
end
pm(start_with: /!tistory-queue-page\s/i) do |event|
data = event.content.scan(/^!tistory-queue-page\s+([\w-]+)\s*$/i)[0]
if !data
event.send_message ":warning: You need to specify a trivia list name..."
next
end
url = data[0].downcase
if @@pages.include? url
event.send_message "Already got #{url} :yerinlaughingatyou:"
next
end
@@pages << url
File.open(BuddyBot.path("content/tistory-list.yml"), "w") { |file| file.write(YAML.dump(@@pages)) }
event.send_message ":information_desk_person: Added '#{url}' :SowonSalute:"
end
message(start_with: /!crawler-abort/i) do |event|
next unless event.user.id == 139342974776639489
@@abort_tistory_queue_in_progress = true
@@abort_twitter_queue_in_progress = true
end
message(start_with: /!tistory-queue-run/i) do |event|
next unless event.user.id == 139342974776639489
@@abort_tistory_queue_in_progress = false
self.log ":information_desk_person: Starting to process the page queue! :sujipraise:", event.bot
@@pages.shuffle.each do |page_name|
self.process_pages(page_name, event) { |page_name, page_number| "http://#{page_name}.tistory.com/m/#{page_number}" }
end
@@pages_special.shuffle.each do |page_name|
self.process_pages(page_name, event) { |page_name, page_number| "http://#{page_name}/m/#{page_number}" }
end
if @@abort_tistory_queue_in_progress
@@abort_tistory_queue_in_progress = false
self.log ":information_desk_person: Aborted Tistory!", event.bot
end
end
message(start_with: /!tistory-special-queue-run/i) do |event|
next unless event.user.id == 139342974776639489
@@abort_tistory_queue_in_progress = false
self.log ":information_desk_person: Starting to process the special page queue! :sujipraise:", event.bot
@@pages_special.shuffle.each do |page_name|
self.process_pages(page_name, event) { |page_name, page_number| "http://#{page_name}/m/#{page_number}" }
end
if @@abort_tistory_queue_in_progress
@@abort_tistory_queue_in_progress = false
self.log ":information_desk_person: Aborted Tistory!", event.bot
end
end
def self.process_pages(page_name, event, &build_url)
if @@abort_tistory_queue_in_progress
return
end
self.log ":information_desk_person: Going through `#{page_name}`'s page!", event.bot
count_done = 0 # all done, successful, failed and 404
count_replicated = 0
count_404 = 0 # count of only 404
count_first_404 = 0 # index of first 404 in 404 range, reset with every success
threshold_404 = 150 # yuna1004_ starts with 129...
threshold_really_max = 100000
range = 1..threshold_really_max
range.each do |page_number|
if page_number > threshold_404 && count_404 > threshold_404 && (page_number - count_first_404) > threshold_404
self.log ":information_desk_person: Finished with `#{page_name}`'s page, skipped #{count_replicated}x already replicated pages, last successful was ##{count_first_404 - 1} and last checked was ##{page_number - 1}!", event.bot
break
end
count_done = count_done + 1
url = build_url.call page_name, page_number
if @@pages_downloaded.include?(page_name) &&
@@pages_downloaded[page_name].include?(page_number.to_s) &&
@@pages_downloaded[page_name][page_number.to_s]["files"].keys.length == @@pages_downloaded[page_name][page_number.to_s]["expected"] &&
@@pages_downloaded[page_name][page_number.to_s].include?("media_files") &&
@@pages_downloaded[page_name][page_number.to_s].include?("expected_media") &&
@@pages_downloaded[page_name][page_number.to_s]["media_files"].keys.length == @@pages_downloaded[page_name][page_number.to_s]["expected_media"]
# Already replicated
count_replicated = count_replicated + 1
count_first_404 = 0
next
end
result = self.process_mobile_page(url, url, page_name, page_number.to_s, event)
if @@abort_tistory_queue_in_progress
break
end
if result.is_a?(Integer)
if result == 404
count_404 = count_404 + 1
if count_first_404 == 0
count_first_404 = page_number
end
if count_404 % 20 == 0
# self.log ":information_desk_person: Had #{count_404}x 404s already, currently at ##{page_number}, ##{count_first_404} was the first in this series for `#{page_name}`'s page!", event.bot
end
else
self.log_warning ":warning: :warning: `#{url}` received a `#{result}`", event.bot
end
elsif result.nil?
# uh...
elsif result == true
count_first_404 = 0
elsif result == false
self.log_warning ":warning: Hard canceling `#{page_name}` due to big error!", event.bot
break
end
end
end
def self.process_mobile_page(url, orig_input, page_name, page_number, event, verbose = nil)
if @@abort_tistory_queue_in_progress
return "abort"
end
time_start = Time.now
retry_counter = 0
retry_counter_max = 5
begin
response = HTTParty.get(url)
rescue => e
retry_counter = retry_counter + 1
retry if retry_counter < retry_counter_max
puts e.inspect
self.log_warning ":warning: Encountered an error while loading the page `#{url}`! `#{e.inspect}`\n```\n#{e.inspect}\n```", event.bot
return false
end
if response.code != 200
if verbose
self.log_warning ":warning: Got #{response.code} #{response.message}, headers\n```\n#{response.headers.inspect}\n```\n#{response.body}", event.bot
event.send_message ":warning: Encountered an error while loading the page! `#{response.code} #{response.message}`"
end
return response.code
end
doc = Nokogiri::HTML(response.body)
page_title = doc.css('h2.tit_blogview').map{|h2| h2.content}.first
if doc.css('.blog_protected').length > 0
self.log_warning ":closed_lock_with_key: Page `#{page_title}` <#{orig_input}> is protected!", event.bot
event.send_message ":closed_lock_with_key: Page `#{page_title}` <#{orig_input}> is protected!" if verbose
return nil
end
urls_images = self.extract_image_uris(doc, orig_input, event)
media_info = self.extract_media(doc, orig_input, event)
if urls_images.length == 0 && media_info.length == 0
event.send_message ":warning: No images / media found on the site!" if verbose
self.log_warning ":warning: Page `#{page_title}` <#{orig_input}> had no images / media!", event.bot
return nil
end
if verbose
event.send_message "**#{page_title}** (#{urls_images.length} image(s)) - <#{orig_input}>\n#{urls_images.join("\n")}"
if media_info.length > 0
event.send_message "Please note that #{media_info.length} media file(s) have been found, which are tricky to display here!"
end
begin
event.message.delete() unless event.channel.pm?
end
end
self.log ":information_desk_person: Downloading #{urls_images.length} images and #{media_info.length} media from `#{page_title}` <#{orig_input}>", event.bot
download_image_results = {}
raw_image_download_results = []
download_image_error_count = 0
download_image_skip_count = 0
process_results_images = Parallel.map(urls_images, in_processes: @@number_of_processes) do |url|
begin
self.upload_tistory_image_file(url, page_name, page_number, page_title, event)
rescue Exception => e
self.log_warning ":warning: #{BuddyBot.emoji(434376562142478367)} Had a big error for `#{url}`, `#{page_name}`, `#{page_number}`, `#{page_title}`: `#{e}`\n```\n#{e.backtrace.join("\n")}\n```", event.bot
{ "result" => "error", "error" => e }
end
end
download_media_success = []
download_media_error_count = 0
download_media_skip_count = 0
process_results_media = Parallel.map(media_info, in_processes: @@number_of_processes) do |info|
begin
case info["type"]
when "youtube"
file_id = info["uri"].scan(/([A-z0-9\-_]{11})/)[0][0]
self.upload_youtube_video(file_id, info["uri"], page_name, page_number, page_title, event)
when "kakao_player"
self.upload_kakao_player_video(info["uri"], page_name, page_number, page_title, event)
when "tistory_parts_list"
file_id = Digest::MD5.hexdigest(info["uri"])
self.upload_tistory_parts_video(file_id, info["uri"], page_name, page_number, page_title, event)
when "weird-gdrive-file"
self.upload_gdrive_file_video(info["id"], info["id"], page_name, page_number, page_title, event)
when "sowon_weird_flash_player"
self.log_warning ":warning: Page <#{orig_input}> had `sowon_weird_flash_player`!", event.bot
{ "result" => "skipped" }
when "nonexistent"
{ "result" => "skipped" }
else
self.log_warning ":warning: No idea how to process `#{info}` (<#{orig_input}>)!", event.bot
{ "result" => "error" }
end
rescue Exception => e
self.log_warning ":warning: #{BuddyBot.emoji(434376562142478367)} Had a big error for `#{url}`, `#{page_name}`, `#{page_number}`, `#{page_title}`: `#{e}`\n```\n#{e.backtrace.join("\n")}\n```", event.bot
{ "result" => "error", "error" => e }
end
end
# self.log ":information_desk_person: Media result: #{process_results_media}", event.bot
if @@abort_tistory_queue_in_progress
return "abort"
end
process_results_images.each do |result|
if result.nil? || result["result"].eql?("error")
download_image_error_count = download_image_error_count + 1
elsif result["result"].eql? "ok"
download_image_results[result["id"]] = result["path"]
raw_image_download_results << result
elsif result["result"].eql? "skipped"
download_image_skip_count = download_image_skip_count + 1
end
end
process_results_media.each do |result|
if result["result"] == "ok"
download_media_success << result
elsif result["result"] == "skipped"
download_media_skip_count = download_media_skip_count + 1
else
download_media_error_count = download_media_error_count + 1
end
end
page_number = page_number.to_s
if !@@pages_downloaded.include? page_name
@@pages_downloaded[page_name] = {}
end
if !@@pages_downloaded[page_name].include? page_number
@@pages_downloaded[page_name][page_number] = {
"expected" => 0,
"expected_media" => 0,
"files" => {},
"media_files" => {},
}
end
# migration
if !@@pages_downloaded[page_name][page_number].include? "media_files"
@@pages_downloaded[page_name][page_number]["media_files"] = {}
end
count_media = self.gib_media_count(doc, orig_input, event)
orig_expected_media = @@pages_downloaded[page_name][page_number]["expected_media"] || 0
@@pages_downloaded[page_name][page_number]["expected_media"] = [ orig_expected_media, count_media ].max
orig_expected = @@pages_downloaded[page_name][page_number]["expected"]
if orig_expected != 0 && orig_expected != urls_images.length
self.log_warning ":warning: Page `#{orig_input}` had `#{urls_images.length}` instead of expected #{@@pages_downloaded[page_name][page_number]["expected"]} images, looks like it got updated", event.bot
end
@@pages_downloaded[page_name][page_number]["expected"] = [ urls_images.length, @@pages_downloaded[page_name][page_number]["expected"] ].max
download_image_results.keys.each do |id|
@@pages_downloaded[page_name][page_number]["files"][id] = download_image_results[id]
end
process_results_media.each do |result|
if result.nil? || result["result"] != "ok"
next
end
@@pages_downloaded[page_name][page_number]["media_files"][result["id"]] = result["path_sample"]
end
File.open(BuddyBot.path("content/tistory-pages-downloaded.yml"), "w") { |file| file.write(YAML.dump(@@pages_downloaded)) }
if orig_expected != 0 && orig_expected != @@pages_downloaded[page_name][page_number]["files"].keys.length
self.log_warning ":warning: Page `#{page_title}` <#{orig_input}>: Downloaded :frame_photo: count discrepancy, expected **#{@@pages_downloaded[page_name][page_number]["expected"]}** but only **#{@@pages_downloaded[page_name][page_number]["files"].keys.length}** exist, **#{download_image_results.keys.length}** from just now", event.bot
end
if orig_expected_media != 0 && orig_expected_media != @@pages_downloaded[page_name][page_number]["media_files"].keys.length
self.log_warning ":warning: Page `#{page_title}` <#{orig_input}>: Downloaded :movie_camera: count discrepancy, expected **#{@@pages_downloaded[page_name][page_number]["expected_media"]}** but only **#{@@pages_downloaded[page_name][page_number]["media_files"].keys.length}** exist, **#{download_media_success.length}** from just now", event.bot
end
total_image_count = 0
total_image_size = 0
total_image_time_upload = 0
total_image_time_download = 0
raw_image_download_results.each do |result|
total_image_count = total_image_count + 1
total_image_size = total_image_size + result["size"]
total_image_time_download = total_image_time_download + result["time_download"]
total_image_time_upload = total_image_time_download + result["time_upload"]
end
avg_image_download = 0
avg_image_upload = 0
avg_image_size = 0
if total_image_count > 0
avg_image_download = (total_image_time_download / total_image_count).round(1)
avg_image_upload = (total_image_time_upload / total_image_count).round(1)
avg_image_size = (total_image_size / total_image_count).round(1)
end
total_media_count = 0
total_media_size = 0
total_media_time_upload = 0
total_media_time_download = 0
download_media_success.each do |result|
total_media_count = total_media_count + result["total_count"] - result["total_support_count"]
total_media_size = total_media_size + result["total_size"]
total_media_time_download = total_media_time_download + result["time_download"]
total_media_time_upload = total_media_time_download + result["time_upload"]
end
avg_media_download = 0
avg_media_upload = 0
avg_media_size = 0
if total_media_count > 0
avg_media_download = (total_media_time_download / total_media_count).round(1)
avg_media_upload = (total_media_time_upload / total_media_count).round(1)
avg_media_size = (total_media_size / total_media_count).round(1)
end
time_end = Time.now
self.log ":ballot_box_with_check: Done replicating <#{orig_input}> to `#{self.format_folder(page_name, page_number, page_title)}`, " +
"uploading #{total_image_count}x images (total #{total_image_size.round(1)}MB, avg #{avg_image_size}MB) with #{download_image_error_count}x errors and " +
"skipping #{download_image_skip_count}x, took me #{(time_end - time_start).round(1)}s (images and media), " +
"avg download #{avg_image_download}s and avg upload #{avg_image_upload}", event.bot
if @@pages_downloaded[page_name][page_number]["expected_media"] > 0
self.log ":ballot_box_with_check: Found #{@@pages_downloaded[page_name][page_number]["expected_media"]} media files, " +
"uploading #{total_media_count}x media files (total #{total_media_size.round(1)}MB, avg #{avg_media_size}MB) with #{download_media_error_count}x errors and " +
"skipping #{download_media_skip_count}x, " +
"avg download #{avg_media_download}s and avg upload #{avg_media_upload}", event.bot
end
return true
end
# gib html, get urls
def self.extract_image_uris(doc, input_url, event)
urls = []
doc.css('.imageblock > .img_thumb').each do |img|
uri = URI.parse(img.attribute('src'))
if !uri.query
self.log_warning ":warning: Url '<#{input_url}>' had an invalid image, no query found: `#{img.attribute('src')}`", event.bot
next
end
params = CGI.parse(uri.query)
if !params["fname"]
self.log_warning ":warning: Url '<#{input_url}>' had an invalid image, no fname found: `#{img.attribute('src')}`", event.bot
next
end
if params["fname"].length > 1
self.log_warning ":warning: Url '<#{input_url}>' had an invalid image, multiple fname found: `#{img.attribute('src')}`", event.bot
next
end
fname = params["fname"][0]
orig_url = fname.sub!("tistory.com/image/", "tistory.com/original/")
urls << orig_url
end
doc.css('.blogview_content img:not(.img_thumb)').each do |img|
uri = img.attribute('src')
if uri.nil?
next
end
uri = uri.to_s
if uri !~ /^http:\/\/cfile\d+\.uf\.tistory\.com\/(original|image)\/\w+/i
if uri !~ /(\/contents\/emoticon\/|\/tistory_admin\/|abs\.twimg\.com\/emoji\/)/ # ignore error on emoticons
self.log_warning ":warning: Url '<#{input_url}>' had an invalid image: `#{img.attribute('src')}`", event.bot
end
next
end
if uri =~ /\/image\//
uri = uri.sub!("/image/", "/original/")
end
urls << uri
end
return urls
end
def self.gib_media_count(doc, input_url, event)
count = 0
count = doc.css("iframe, embed").length
doc.css(".blogview_content p").each do |p|
content = p.content.strip
next unless content =~ /^#{URI::regexp}$/
if content.include? "youtu"
count = count + 1
end
end
return count
end
def self.extract_media(doc, input_url, event)
media = []
uri_tistory_flashplayers = [
"http://goo.gl/HEJkR",
"http://goo.gl/bGi64",
"http://smarturl.it/sspl",
]
uri_part_kakao_flashplayer = "tv.kakao.com/embed/player/cliplink"
uri_weird_gdrive_flash_player = "https://www.googledrive.com/host/0B-9MTMyoDRgrWTc4bFN6NVNxQmc"
uri_another_weird_gdrive_flash_player = "https://www.googledrive.com/host/0B-9MTMyoDRgrXy03Q1NvWE1VNlk"
uri_sowon_weird_flash_player = "http://951207.com/plugin/CallBack_bootstrapperSrc?nil_profile=tistory&nil_type=copied_post"
uri_nonexistent_players = [ # any player that we should ignore
"http://cfile23.uf.tistory.com/media/230A50475842C1E20ED51F",
]
uri_weird_iframes = [
"/endGift.php?entryId=0&setNo=1940", # some gift button
"https://t1.daumcdn.net/tistory_admin/static/plugin/endGift.html?entryId=0&setNo=1940",
]
uri_weird_embeds = [
"http://player.youku.com/player.php/sid/XNjE5MTgxOTQw/v.swf",
]
doc.css('embed').each do |embed|
uri = embed.attribute('src').to_s
flashvars = (embed.attribute('flashvars') || "").to_s
if uri_tistory_flashplayers.include? uri
parsed_vars = CGI.parse(flashvars)
uri_parts_list = parsed_vars["xml"][0]
media << { "type" => "tistory_parts_list", "uri" => uri_parts_list }
elsif uri_nonexistent_players.include? uri
media << { "type" => "nonexistent", "uri" => uri }
elsif uri.include? uri_part_kakao_flashplayer
media << { "type" => "kakao_player", "uri" => uri }
elsif uri.eql?(uri_weird_gdrive_flash_player) || uri.eql?(uri_another_weird_gdrive_flash_player)
parsed_vars = CGI.parse(flashvars)
gdrive_file_id = parsed_vars["file"][0].scan(/host\/(.*?)(&|$)/)[0][0]
media << { "type" => "weird-gdrive-file", "id" => gdrive_file_id }
elsif uri.include? "youtu.be"
media << { "type" => "youtube", "uri" => uri }
elsif uri.eql? uri_sowon_weird_flash_player
media << { "type" => "sowon_weird_flash_player", "uri" => uri, "flashvars" => flashvars }
elsif uri =~ /#{Regexp.quote("/plugin/CallBack_bootstrapperSrc?nil_profile=tistory&nil_type=copied_post")}$/
elsif uri_weird_embeds.include? uri
next # skip
else
media << { "type" => "unknown", "sub-type" => "embed", "uri" => uri, "flashvars" => flashvars }
end
end
doc.css('iframe').each do |iframe|
uri = iframe.attribute('src').to_s
if uri.include? "youtube.com"
media << { "type" => "youtube", "uri" => uri }
elsif uri.include? uri_part_kakao_flashplayer
media << { "type" => "kakao_player", "uri" => uri }
elsif uri_weird_iframes.include? uri
next # skip
else
media << { "type" => "unknown", "sub-type" => "iframe", "uri" => uri }
end
end
doc.css(".blogview_content p").each do |p|
content = p.content.strip
next unless content =~ /^#{URI::regexp}$/
if content.include? "youtu"
media << { "type" => "youtube", "uri" => content }
end
end
return media
end
def self.upload_kakao_player_video(url, page_name, page_number, page_title, event)
if url.start_with? "//"
url = "https:" + url
end
puts url
player_page = HTTParty.get(url)
if player_page.code != 200
return { "result" => "error", "request" => player_page }
end
_file_id = player_page.body.scan(/ENV\.clipLinkId = '(\d+)';/)[0]
if !_file_id
self.log_warning ":warning: Kakao Video did not have a clip ID - `#{url}` - from Tistory `#{page_name}/#{page_number} - #{page_title}`", event.bot
return { "result" => "error" }
end
file_id = _file_id[0]
selected_profile = player_page.body.scan(/ENV.profile = '(\w+)';/)[0][0]
# impress data contains general video data, and most importantly, provides us with uuid and tid values
impress = HTTParty.get("http://tv.kakao.com/api/v2/ft/cliplinks/#{file_id}/impress?player=monet_html5&referer=&service=daum_tistory§ion=daum_tistory&withConad=true&dteType=PC&fields=clipLink,clip,channel,hasPlusFriend,user,userSkinData,-service,-tagList")
if impress.code != 200
return { "result" => "error", "request" => impress }
end
impress = JSON.parse(impress.body)
# raw data contains the video link
clip_data = HTTParty.get("https://tv.kakao.com/api/v2/ft/cliplinks/#{file_id}/raw" +
"?player=monet_html5&uuid=#{impress["uuid"]}&service=daum_tistory§ion=daum_tistory&tid=#{impress["tid"]}&profile=#{selected_profile}&dteType=PC&continuousPlay=false")
if clip_data.code != 200
return { "result" => "error", "request" => clip_data }
end
clip_data = JSON.parse(clip_data.body)
file_name = impress["clipLink"]["clip"]["title"]
profile_name = clip_data["videoLocation"]["profile"]
video_uri = clip_data["videoLocation"]["url"]
file_full_name = File.basename(video_uri)
filtered_file_full_name = file_full_name.split("?")[0]
file_extension = File.extname(filtered_file_full_name)
file_extension[0] = "" # still has leading '.'
acknowledged_profiles = [
"LOW",
"BASE",
"MAIN",
"HIGH",
]
found_profiles = {}
clip_data["outputList"].each{ |profile| found_profiles[profile["profile"]] = profile["label"] }
unknown_profiles = found_profiles.keys.map{ |profile| if !acknowledged_profiles.include?(profile) then profile + ": " + found_profiles[profile] end }.compact
if unknown_profiles.length > 0
self.log_warning ":warning: Video on `#{url}` had unknown profile(s): `#{unknown_profiles}`", event.bot
end
self.generic_multi_upload(profile_name + "-" + file_id, url, page_name, page_number, page_title, event) do |dir|
`cd #{dir} && wget '#{video_uri}'`
output_file_list = [ { "full" => file_full_name, "name" => file_name, "ext" => file_extension } ]
{
"result" => "ok",
"output_file_list" => output_file_list,
}
end
end
def self.upload_tistory_parts_video(file_id, url, page_name, page_number, page_title, event)
self.generic_multi_upload(file_id, url, page_name, page_number, page_title, event) do |dir|
url = url.strip # some idiots put newlines into their urls...
player_data = HTTParty.get(url)
if player_data.code != 200
return { "result" => "error", "request" => player_data }
end
temp_file = nil
output_file_list = []
xml = Nokogiri::XML(player_data.body)
xml_tracks = xml.css("track").sort_by { |k| k.at_css("title").content.to_i }
begin
Parallel.map(xml_tracks, in_processes: @@number_of_processes) do |track|
begin
part_url = track.at_css("location").content
if part_url =~ /\/attachment\/http:\/\//
# sometimes we get urls like http://kkangjiilove.tistory.com/attachment/http://cfile8.uf.tistory.com/media/213F224E5415065A215AEA
part_url = part_url.scan(/\/attachment\/(http:\/\/.*)$/)[0][0]
end
part_download = HTTParty.get(part_url)
if part_download.code != 200
self.log_warning ":warning: Download error for `#{url} / #{part_url}`: #{part_download.code} - #{part_download.message}\n```\n#{part_download.inspect}\n```", event.bot
return { "result" => "error", "http" => part_download }
end
part_download
rescue => e
self.log_warning ":warning: Download error for `#{url} / #{part_url}`: #{e.inspect}\n```\n#{e.backtrace.inspect}\n```", event.bot
return { "result" => "error", "error" => e }
end
end.each do |part_download|
if temp_file.nil?
params = CGI.parse(part_download.headers["content-disposition"])
if !params || !params[" filename"] || params[" filename"].length > 1
self.log_warning ":warning: Url <#{url}> had uncompliant content-disposition!\n```\n#{part_download.headers.inspect}\n```", event.bot
return { "result" => "error", "error" => "content-disposition" }
end
file_full_name = (params[" filename"] || [ 'Untitled' ])[0].gsub!('"', '').sub("/", "\/") # filename is wrapped in quotes
if file_full_name =~ /\.\d+$/
file_full_name = File.basename file_full_name, ".*" # remove .001
end
file_name = File.basename(file_full_name, ".*")
file_extension = File.extname(file_full_name)
file_extension[0] = "" # still has leading '.'
output_file_list = [ { "full" => file_full_name, "name" => file_name, "ext" => file_extension } ]
temp_file = File.open(dir + "/" + file_full_name, "wb")
end
written = temp_file.write part_download.body
end
rescue => e
self.log_warning ":warning: Tistory video down/upload had a big error: \n```\n#{e.inspect}\n```", event.bot
return { "result" => "error", "e" => e }
end
{
"result" => "ok",
"output_file_list" => output_file_list,
}
end
end
def self.upload_gdrive_file_video(file_id, _, page_name, page_number, page_title, event)
self.generic_multi_upload(file_id, "https://drive.google.com/open?id=#{file_id}", page_name, page_number, page_title, event) do |dir|
output = `cd #{dir}; gdrive download '#{file_id}'`
puts output
end
end
def self.upload_youtube_video(file_id, url, page_name, page_number, page_title, event)
self.generic_multi_upload(file_id, url, page_name, page_number, page_title, event) do |dir|
output = `cd #{dir} && youtube-dl --write-sub --all-subs https://youtu.be/#{file_id} 2>&1`
output_filename = "<not downloaded yet>"
output_file_list = []
files_support_count = 0
if output =~ /ERROR: giving up after 10 fragment retries/
return { "result" => "error" }
elsif output.include? "[ffmpeg] Merging formats into \""
output_filename = output.scan(/\[ffmpeg\] Merging formats into "(.*?)"\n/)[0][0]
elsif output.include? "[download] Destination: "
scan = output.scan(/\[download\] Destination: (.*?)$/)
if scan.length > 1
self.log_warning ":warning: Had multiple output files for #{file_id}", event.bot
return { "result" => "error" }
end
output_filename = scan[0][0]
elsif output =~ /(ERROR: This video contains content from .*?, who has blocked it( in your country)? on copyright grounds\.|ERROR: This video is unavailable.)/
self.log_warning ":closed_lock_with_key: YT Video <#{url}> is blocked.", event.bot
return { "result" => "skipped" }
else
self.log_warning ":warning: could not infer file name\n```\n#{output}\n```", event.bot
return { "result" => "error" }
end
file_name, file_extension = output_filename.scan(/^(.*?)-[A-z0-9\-_]{11}\.(.*?)$/)[0]
output_file_list << { "full" => output_filename, "name" => file_name, "ext" => file_extension }
if output.include? "Writing video subtitles to:"
files_sub = output.scan(/Writing video subtitles to: (.*?)\n/).flatten
output_file_list = output_file_list + files_sub.map do |full|
file_name, file_extension = full.scan(/^(.*?)-[A-z0-9\-_]{11}\.(.*?)$/)[0]
{ "full" => full, "name" => file_name, "ext" => file_extension }
end
files_support_count = files_sub.length
end
{
"result" => "ok",
"output_file_list" => output_file_list,
"files_support_count" => files_support_count,
}
end
end
def self.generic_multi_upload(file_id, url, page_name, page_number, page_title, event, &cb)
if @@abort_tistory_queue_in_progress
return { "result" => "error", "error" => "Aborting..." }
end
if url.nil?
return { "result" => "error", "error" => "Empty url..." }
end
if @@pages_downloaded.include?(page_name) &&
@@pages_downloaded[page_name].include?(page_number) &&
@@pages_downloaded[page_name][page_number].include?("media_files") &&
@@pages_downloaded[page_name][page_number]["media_files"].include?(file_id)
# Already replicated
return { "result" => "skipped", "id" => file_id, "path" => @@pages_downloaded[page_name][page_number]["media_files"][file_id] }
end
output_file_list = []
time_start = Time.now
files_count = 0
files_support_count = 0
files_size = 0
Dir.mktmpdir do |dir|
result = cb.call(dir)
if result && result["result"] = "ok"
files_support_count = result["files_support_count"] || 0
output_file_list = result["output_file_list"]
else
return result
end
time_split = Time.now
time_end = 0
files_count = 0
uploaded_file_names = []
begin
output_file_list.each do |file_meta|
file = file_meta["full"]
file_name = file_meta["name"]
file_extension = file_meta["ext"]
files_count = files_count + 1
files_size = files_size + File.size(dir + "/" + file)
s3_filename = self.format_object_name(page_name, page_number, page_title, file_name, file_id, file_extension)
uploaded_file_names << s3_filename
object = @@s3_bucket.object(s3_filename)
result = object.upload_file(dir + "/" + file)
if !result
raise 'Upload not successful!'
end
end
rescue Exception => e
self.log_warning ":warning: One of `#{output_file_list}` had upload error to S3! #{e}\n```\n#{e.backtrace.join("\n")}\n```", event.bot
return { "result" => "error", "error" => e }
end
time_end = Time.now
files_size = files_size.to_f / (2 ** 20)
self.log ":ballot_box_with_check: Successfully uploaded media `#{file_id}` => `#{uploaded_file_names[0]}`, #{files_size.round(1)} MB, #{(time_end - time_start).round(1)}s total", event.bot
puts "Just uploaded #{uploaded_file_names[0]} (#{(files_size.to_f / 2**20).round(2)}MB)"
return {
"result" => "ok",
"id" => file_id,
"path_sample" => uploaded_file_names[0],
"file_name_sample" => output_file_list[0],
"file_list" => output_file_list,
"total_size" => files_size,
"total_count" => files_count,
"total_support_count" => files_support_count,
"time_download" => (time_split - time_start).round(1),
"time_upload" => (time_end - time_split).round(1),
}
end
end
def self.upload_tistory_image_file(url, page_name, page_number, page_title, event)
if @@abort_tistory_queue_in_progress
return { "result" => "error", "error" => "Aborting..." }
end
if url.nil?
return { "result" => "error", "error" => "Empty url..." }
end
file_id = url.scan(/\/original\/(\w+)$/)[0][0]
if @@pages_downloaded.include?(page_name) &&
@@pages_downloaded[page_name].include?(page_number) &&
@@pages_downloaded[page_name][page_number].include?("files") &&
@@pages_downloaded[page_name][page_number]["files"].include?(file_id)
# Already replicated
return { "result" => "skipped", "id" => file_id, "path" => @@pages_downloaded[page_name][page_number]["files"][file_id] }
end
time_start = Time.now # .to_f
time_split = 0
response = HTTParty.get(url)
if response.code != 200
self.log_warning ":warning: Got #{response.code} #{response.message}, headers\n```\n#{response.headers.inspect}\n```", event.bot
return { "result" => "error", "error" => "#{response.code} #{response.message}" }
end
params = CGI.parse(response.headers["content-disposition"])
if !params || !params[" filename"] || params[" filename"].length > 1
self.log_warning ":warning: Url <#{url}> had malicious content-disposition!\n```\n#{response.headers.inspect}\n```", event.bot
return { "result" => "error", "error" => "content-disposition" }
end
file_full_name = (params[" filename"] || [ 'Untitled' ])[0].gsub!('"', '') # filename is wrapped in quotes
file_name = File.basename(file_full_name, ".*")
file_extension = File.extname(file_full_name)
file_extension[0] = "" # still has leading '.'
s3_filename = self.format_object_name(page_name, page_number, page_title, file_name, file_id, file_extension)
object = @@s3_bucket.object(s3_filename)
file_size = 0
image_w = 0
image_h = 0
retry_count = 0
begin
Tempfile.create('tmpf', '/home/anhnhan/tmp-web-crawler/') do |tempfile|
tempfile.write response.body
tempfile.seek(0)
time_split = Time.now # .to_f
file_size = tempfile.size
image_w, image_h = ImageSize.path(tempfile.path).size
result = object.upload_file(tempfile)
if !result
raise 'Upload not successful!'
end
end
rescue Exception => e
retry_count = retry_count + retry_count
retry unless retry_count > 5
self.log_warning ":warning: Url <#{url}> / `#{s3_filename}` had upload error to S3! #{e}", event.bot
return { "result" => "error", "error" => e }
end
time_end = Time.now # .to_f
# self.log ":ballot_box_with_check: Uploaded <#{url}> / `#{s3_filename}` " +
# "(#{(file_size.to_f / 2 ** 20).round(2)} MB, #{image_w}x#{image_h}, #{(time_split - time_start).round(1)}s " +
# "download + write, #{(time_end - time_split).round(1)}s upload S3): " +
# "<#{object.presigned_url(:get, expires_in: 604800)}>", event.bot
puts "Just uploaded #{s3_filename} (#{(file_size.to_f / 2**20).round(2)}MB)"
result = {
"result" => "ok",
"id" => file_id,
"path" => s3_filename,
"url" => url,
"size" => (file_size.to_f / 2 ** 20).round(2),
"w" => image_w,
"h" => image_h,
"time_download" => (time_split - time_start).round(1),
"time_upload" => (time_end - time_split).round(1),
"presigned_url" => object.presigned_url(:get, expires_in: 604800),
}
return result
end
def self.format_object_name(page_name, page_number, page_title, file_name, file_id, file_extension)
file_name = file_name.sub "/", "\/"
page_title = page_title.sub "/", "\/"
self.format_folder(page_name, page_number, page_title) + "#{file_name}-#{file_id}.#{file_extension}"
end
def self.format_folder(page_name, page_number, page_title)
"tistory/#{page_name}/#{page_number} - #{page_title}/"
end
def self.replicate_sendanywhere_file(id, event)
if @@sendanywhere_downloaded.include? id
return { "result": "skipped", "path": @@sendanywhere_downloaded[id] }
end
time_start = Time.now
time_split = nil
device_info = HTTParty.post("https://send-anywhere.com/web/device", {
body: '{"os_type":"web","manufacturer":"Windows","model_number":"Chrome","app_version":"2.0.0","os_version":"67","device_language":"en-US","profile_name":"Aries"}',
headers: { "Content-Type" => "application/json" }
})
device_info = JSON.parse(device_info.body)
device_key = device_info["device_key"]
inquiry_info = HTTParty.get("https://send-anywhere.com/web/key/inquiry/" + id, { headers: { "Cookie": "device_key=" + device_key } })
inquiry_info = JSON.parse(inquiry_info.body)
server_uri = inquiry_info["server"]
file_is_multiple = false
file_full_name = nil
# only interesting info here is number of files
# keyinfo = HTTParty.get("#{server_uri}webfile/#{id}?device_key=#{device_key}&mode=keyinfo")
# file names and list
filelist_uri = "#{server_uri}webfile/#{id}?device_key=#{device_key}&mode=list&start_pos=0&end_pos=30"
puts "filelist_uri: #{filelist_uri}"
filelist = HTTParty.get(filelist_uri)
filelist = JSON.parse(filelist.body)
if filelist["file"].length > 1
file_is_multiple = true
end
if !file_is_multiple
file_full_name = filelist["file"][0]["name"]
end
# 'register' device key, unlock download
key_info = HTTParty.get("https://send-anywhere.com/web/key/#{id}", { headers: { "Cookie": "device_key=" + device_key } })
key_info = JSON.parse(key_info.body)
file_uri = key_info["weblink"]
file_size_expected = key_info["file_size"]
self.log ":information_desk_person: Starting to download '#{id}' - `#{file_full_name || 'Multi-File Archive'}` (#{(file_size_expected / 2**20).round(1)}MB)!", event.bot
file_size = 0
s3_path = ""
Dir.mktmpdir do |dir|
begin
local_file_name = File.basename(file_uri)
`cd #{dir} && curl -v -D headers.txt '#{file_uri}' > '#{local_file_name}'`
file_size = File.size(dir + "/" + local_file_name)
if file_size != file_size_expected
self.log_warning ":warning: SendAnywhere `#{id}` had unexpected file size: #{file_size} but expected #{file_size_expected}", event.bot
# return { "result" => "error" }
end
if file_is_multiple
stdout = open(dir + "/" + "headers.txt").read
result_scan = stdout.scan(/Content-Disposition: attachment; filename="(.*?)"/i)
if !result_scan || !result_scan[0] || !result_scan[0][0]
self.log_warning ":warning: SendAnywhere `#{id}` had missing content disposition:\n```\n#{stdout}\n```", event.bot
return { "result" => "error" }
end
file_full_name = result_scan[0][0]
end
time_split = Time.now
s3_path = "sendanywhere/#{id} - #{file_full_name}/#{file_full_name}"
object = @@s3_bucket.object(s3_path)
result = object.upload_file(dir + "/" + local_file_name)
if !result
raise 'Upload not successful!'
end
rescue Exception => e
self.log_warning ":warning: SendAnywhere `#{id}` had download/upload error to S3! #{e}\n```\n#{e.backtrace.join("\n")}\n```", event.bot
return { "result" => "error", "error" => e }
end
end
time_end = Time.now
puts "Just uploaded #{s3_path} (#{(file_size.to_f / 2**20).round(2)}MB)"
@@sendanywhere_downloaded[id] = s3_path
File.open(BuddyBot.path("content/downloaded-sendanywhere.yml"), "w") { |file| file.write(YAML.dump(@@sendanywhere_downloaded)) }
self.log ":ballot_box_with_check: Successfully replicated SendAnywhere `#{id}` to `#{s3_path}` (#{(file_size.to_f / 2**20).round(1)}MB), downloading in #{(time_split - time_start).round(1)}s and uploading in #{(time_end - time_split).round(1)}!", event.bot
return { "result" => "success", "path" => s3_path }
end
message(start_with: /!sendanywhere\s/i) do |event|
next unless event.user.id == 139342974776639489
data = event.content.scan(/^!sendanywhere\s+([\w]+)\s*$/i)[0]
if !data
event.send_message ":warning: You need to specify a trivia list name..."
next
end
id = data[0]
result = self.replicate_sendanywhere_file(id, event)
puts result
end
message(start_with: /!sendanywhere-link\s/i) do |event|
next unless event.user.id == 139342974776639489
data = event.content.scan(/^!sendanywhere-link\s+([\w]+)\s*$/i)[0]
if !data
event.send_message ":warning: You need to specify a trivia list name..."
next
end
id = data[0]
if !@@sendanywhere_downloaded.include?(id)
event.send_message ":information_desk_person: Don't have that file yet, downloading now!"
result = self.replicate_sendanywhere_file(id, event)
puts result
if !result || result["result"] != "success"
self.log_warning ":warning: SendAnywhere `#{id}` could not be downloaded: `#{result.inspect}`", event.bot
event.send_message ":warning: Download error #{BuddyBot.emoji(434376562142478367)}"
return
end
end
object = @@s3_bucket.object(@@sendanywhere_downloaded[id])
if !object.exists?
self.log_warning ":warning: SendAnywhere `#{id}` was _supposedly_ downloaded but did not exist in S3!", event.bot
self.log_warning BuddyBot.emoji(434376562142478367), event.bot
event.send_message ":warning: SendAnywhere `#{id}` was _supposedly_ downloaded but did not exist in S3!"
event.send_message BuddyBot.emoji(434376562142478367)
return
end
event.send_message ":information_desk_person: Here is your link for `#{id}`! _Valid for one day._"
event.send_message object.presigned_url(:get, expires_in: 24 * 60 * 60)
end
message(contains: /http:\/\/sendanywhe\.re\/\w+/) do |event|
id = event.content.scan(/http:\/\/sendanywhe.re\/(\w+)\b/)[0][0]
result = self.replicate_sendanywhere_file(id, event)
puts result
end
message(start_with: /!tl\s/i) do |event|
next unless event.user.id == 139342974776639489
data = event.content.scan(/^!tl\s+(\S+)(\?s=\d+)?\s*$/i)[0]
if !data
event.send_message ":warning: You need to specify a trivia list name..."
next
end
url = data[0]
if url =~ /^\d+$/
url = self.twitter_determine_full_url(url, event)
end
twitter_host, author, id = url.scan(/^(https:\/\/twitter.com)?\/(\w+)\/status\/(\d+)$/)[0]
if !(@@twitter_downloaded.include?(author) &&
@@twitter_downloaded[author].include?(id))
event.send_message ":information_desk_person: Don't have that tweet yet, downloading now!"
result = self.process_tweet(url, event)
puts result
if !result || result["result"] != "success"
self.log_warning ":warning: Tweet `#{id}` could not be downloaded: `#{result.inspect}`", event.bot
event.send_message ":warning: Download error #{BuddyBot.emoji(434376562142478367)}"
return
end
if result["result"] == "success"
self.twitter_record_successful_result(result["author"], result["id"], result)
File.open(BuddyBot.path("content/downloaded-twitter.yml"), "w") { |file| file.write(YAML.dump(@@twitter_downloaded)) }
end
end
entry = @@twitter_downloaded[author][id]
[ "files_images", "files_videos", "files_links" ].each do |key|
entry[key].values.each do |path|
object = @@s3_bucket.object(path)
if !object.exists?
self.log_warning ":warning: Tweet `#{id}` was _supposedly_ downloaded but did not exist in S3 as `#{path}`! BuddyBot.emoji(434376562142478367)", event.bot
event.send_message ":warning: Tweet `#{id}` was _supposedly_ downloaded but did not exist in S3 as `#{path}`! BuddyBot.emoji(434376562142478367)"
return
end
event.send_message ":information_desk_person: Here is your link for `#{id} / #{path}`! _Valid for one day._"
event.send_message object.presigned_url(:get, expires_in: 24 * 60 * 60)
end
end
end
message(start_with: "!t ") do |event|
next if event.user.bot_account?
@@abort_twitter_queue_in_progress = false
input = event.content.strip.replace /(\?s=\d+|\s+)+$/, ""
data = input.scan(/^!t\s+(\S+)$/i)[0]
if !data
event.send_message ":warning: You need to specify a trivia list name..."
next
end
data = data[0]
url = data
if data =~ /^\d+$/
url = self.twitter_determine_full_url(data, event)
end
result = self.process_tweet(url, event)
puts "#{result}"
if result["result"] == "success"
self.twitter_record_successful_result(result["author"], result["id"], result)
File.open(BuddyBot.path("content/downloaded-twitter.yml"), "w") { |file| file.write(YAML.dump(@@twitter_downloaded)) }
end
# TODO Do something with errors
if @@abort_twitter_queue_in_progress
@@abort_twitter_queue_in_progress = false
self.log ":information_desk_person: Aborted Twitter!", event.bot
next
end
msg = ":information_desk_person: Finished going through <#{url}>: \n```\n#{result}\n```"
self.log msg, event.bot
event.respond msg
end
message(start_with: "!twitter-page ") do |event|
next if event.user.bot_account?
@@abort_twitter_queue_in_progress = false
data = event.content.scan(/^!twitter-page\s+(\S+)\s*$/i)[0]
if !data
event.send_message ":warning: You need to specify a trivia list name..."
next
end
data = data[0]
author = data
self.process_twitter_profile(author, event)
if @@abort_twitter_queue_in_progress
@@abort_twitter_queue_in_progress = false
self.log ":information_desk_person: Aborted Twitter!", event.bot
end
end
message(content: "!twitter-queue-run") do |event|
next if event.user.bot_account?
@@abort_twitter_queue_in_progress = false
@@twitter_list.shuffle.each do |author|
self.process_twitter_profile(author, event)
end
if @@abort_twitter_queue_in_progress
@@abort_twitter_queue_in_progress = false
self.log ":information_desk_person: Aborted Twitter!", event.bot
end
end
def self.twitter_determine_full_url(id, event)
url = "https://twitter.com/twitter/statuses/#{id}"
result = HTTParty.head(url, follow_redirects: false)
if result.code != 301
self.log_warning ":warning: Tweet ##{id} was maybe not found: `#{result.inspect}`", event.bot
end
tweet_url = result.headers["location"]
end
def self.process_tweet(url, event, options = {})
if @@abort_twitter_queue_in_progress
return
end
time_start = Time.now
twitter_host, author, id = url.scan(/^(https:\/\/twitter.com)?\/(\w+)\/status\/(\d+)$/)[0]
if @@twitter_downloaded.include?(author) &&
@@twitter_downloaded[author].include?(id) &&
@@twitter_downloaded[author][id]["files_images"].keys.length == @@twitter_downloaded[author][id]["expected_images"] &&
@@twitter_downloaded[author][id]["files_videos"].keys.length == @@twitter_downloaded[author][id]["expected_videos"] &&
@@twitter_downloaded[author][id]["files_links"].keys.length == @@twitter_downloaded[author][id]["expected_links"]
return { "result" => "skipped" }
end
if twitter_host.nil? || twitter_host.empty?
url = "https://twitter.com" + url
end
# check if account had been suspended
if !options[:did_suspended_check]
begin
request = HTTParty.head(url, follow_redirects: false)
if request.code == 302 && request.headers["location"] == "https://twitter.com/account/suspended"
msg = ":information_desk_person: Twitter account `#{author}` is suspended, skipping"
self.log_warning msg, event.bot
self.log msg, event.bot
return { "result" => "error", "reason" => "suspended" }
end
rescue => e
# TODO: debug
self.log_warning "self.process_tweet: Hard error while checking suspended account for `#{url}`: `#{e.inspect}`", event.bot
puts e.inspect
return { "result" => "error", "reason" => "suspended-error" }
end
end
page_contents = nil
begin
page_contents = HTTParty.get(url)
rescue => e
puts "Error fetching #{url}"
puts e.inspect
self.log_warning ":warning: Twitter error for <#{url}>: `#{e.inspect}`", event.bot
return { "result" => "error", "error" => e }
end
if page_contents.code != 200
# :sowonnotlikethis:
return { "result": "error", "request" => page_contents }
end
page_contents = Nokogiri::HTML(page_contents.body)
images = page_contents.css('meta[property="og:image"]').map do |meta|
image_url = meta.attribute("content").to_s.sub(/:large$/, ":orig")
image_url = image_url + ":orig" unless image_url =~ /:orig$/
next unless image_url =~ /\/media\//
image_url
end.compact
title = ""
description_meta = page_contents.at_css('meta[property="og:description"]')
if description_meta
title = description_meta.attribute("content").to_s.gsub(URI::regexp, "").gsub(/[“”]/, "").gsub(/\s+/, " ").gsub(/\s”/, "”").gsub("/", "\/").strip
end
videos = page_contents.css('meta[property="og:video:url"]').map do |meta|
video_id = meta.attribute("content").to_s.scan(/(\d{4,})/)[0][0]
end.compact
links = page_contents.css('.TweetTextSize--jumbo.tweet-text a:not(.u-hidden):not(.twitter-hashtag)').map do |link|
link_url = link.attribute("data-expanded-url").to_s
end.compact
subfolder = id.to_s
if title && title.length != 0
subfolder = subfolder + " - " + title
end
s3_folder = "twitter/@#{author}/#{subfolder}/"
results_images = images.map do |image_url|
begin
image_filename = image_url.scan(/\/([\w-]+\.(jpg|png)):/)[0][0]
rescue => e
self.log_warning ":warning: Had an error extracting image_filename from `#{image_url}`:\n```\n#{e.inspect}\n```", event.bot
next { "result" => "error" }
end
if @@twitter_downloaded.include?(author) &&
@@twitter_downloaded[author].include?(id) &&
@@twitter_downloaded[author][id]["files_images"].include?(image_filename)
next { "result" => "skipped" }
end
file_size = 0
s3_path = s3_folder + image_filename
retry_count = 0
begin
Tempfile.create('tmpf', '/home/anhnhan/tmp-web-crawler/') do |tempfile|
tempfile.write HTTParty.get(image_url).body
tempfile.seek(0)
file_size = tempfile.size
object = @@s3_bucket.object(s3_path)
result = object.upload_file(tempfile)
puts "Just uploaded #{s3_path} (#{(file_size.to_f / 2**20).round(2)}MB)"
if !result
raise 'Upload not successful!'
end
end
{ "result" => "success", "id" => image_filename, "path" => s3_path }
rescue Exception => e
retry_count = retry_count + 1
retry unless retry_count > 5
self.log_warning ":warning: Url <#{url}> / `#{s3_path}` had upload error to S3! #{e.inspect}", event.bot
{ "result" => "error", "error" => e }
end
end
results_videos = videos.map do |video_id|
if @@twitter_downloaded.include?(author) &&
@@twitter_downloaded[author].include?(id) &&
@@twitter_downloaded[author][id]["files_videos"].include?(video_id)
next { "result" => "skipped" }
end
poster_filename = nil
# uploading urls
video_info_url = "https://api.twitter.com/1.1/videos/tweet/config/#{video_id}.json"
video_info_request = HTTParty.get(video_info_url, { headers: { "Authorization" => "Bearer #{@@twt_app_bearer}" } })
if video_info_request.code != 200
next { "result" => "error", "request" => video_info_request }
end
video_info = JSON.parse video_info_request.body
video_uri = video_info["track"]["playbackUrl"]
video_type = video_info["track"]["playbackType"]
video_content_type = video_info["track"]["contentType"]
if ((video_content_type == "media_entity" || video_content_type == "gif") && (video_type != "video/mp4" && video_type != "application/x-mpegURL")) && video_content_type != "vmap"
self.log_warning ":warning: Twitter <#{url}> had unknown video type: #{video_type}\nInfo: `#{video_info}`", event.bot
next { "result" => "error", "video_info" => video_info }
end
if video_content_type == "vmap"
vmap_uri = video_info["track"]["vmapUrl"]
vmap_request = HTTParty.get(vmap_uri)
if vmap_request.code != 200
self.log_warning ":warning: Could not retrieve vmap for <#{url}>: `#{vmap_request.inspect}`", event.bot
next { "result" => "error", "request" => vmap_request }
end
vmap = Nokogiri::XML(vmap_request.body)
video_uri = vmap.xpath("//MediaFile").first.content.strip
poster_filename = File.basename(video_uri, ".*") + ".png"
end
if video_type == "application/x-mpegURL"
poster_filename = File.basename(video_uri.sub(/\?tag=\d+/i, ""), ".m3u8") + ".jpg"
end
# poster
poster_uri = video_info["posterImage"]
if !poster_filename
poster_filename = File.basename(poster_uri)
end
s3_path = s3_folder + poster_filename
begin
Tempfile.create('tmpf', '/home/anhnhan/tmp-web-crawler/') do |tempfile|
tempfile.write HTTParty.get(poster_uri).body
tempfile.seek(0)
file_size = tempfile.size
object = @@s3_bucket.object(s3_path)
result = object.upload_file(tempfile)
puts "Just uploaded #{s3_path} (#{(file_size.to_f / 2**20).round(2)}MB)"
if !result
raise 'Upload not successful!'
end
end
rescue Exception => e
retry_count = retry_count + 1
retry unless retry_count > 5
self.log_warning ":warning: Url <#{url}> / `#{s3_path}` had upload error to S3! #{e.inspect}", event.bot
next { "result" => "error", "error" => e }
end
# actual video
if video_type == "application/x-mpegURL"
filename = File.basename(video_uri.sub(/\?tag=\d+/, ""), ".m3u8") + ".mp4"
subtitle_map = {}
twt_video_host = "https://video.twimg.com"
playlist_request = HTTParty.get(video_uri)
if playlist_request.code != 200
return { "result" => "error", "request" => playlist_request }
end
playlist = M3u8::Playlist.read playlist_request.body
next_playlist_uri = twt_video_host + playlist.items.sort_by do |item|
if item.respond_to?(:type) && item.type == "SUBTITLES"
subtitle_map[item.language] = twt_video_host + item.uri
next
elsif !item.respond_to?(:bandwidth)
raise "Bandwidth not defined for playlist <#{video_uri}>"
end
item.bandwidth
end.compact[-1].uri
subtitle_map.each do |lang, subtitle_uri|
subtitle_playlist_request = HTTParty.get(subtitle_uri)
if subtitle_playlist_request.code != 200
return { "result" => "error", "request" => subtitle_playlist_request }
end
subtitle_playlist = M3u8::Playlist.read subtitle_playlist_request.body
if subtitle_playlist.items.length > 1
self.log_warning ":warning: <#{url}> had multiple subtitle entries, please advise (<#{subtitle_uri}>)", event.bot
break
end
subtitle_file_uri = subtitle_playlist.items.first.uri
subtitle_file_request = HTTParty.get(subtitle_file_uri)
if subtitle_file_request.code != 200
return { "result" => "error", "request" => subtitle_file_request }
end
s3_path = s3_folder + File.basename(filename, ".*") + ".#{lang}" + File.extname(subtitle_file_uri)
Tempfile.create('tmpf', '/home/anhnhan/tmp-web-crawler/') do |tempfile|
tempfile.write subtitle_file_request.body
file_size = tempfile.size
object = @@s3_bucket.object(s3_path)
result = object.upload_file(tempfile.path)
puts "Just uploaded #{s3_path} (#{(file_size.to_f / 2**20).round(2)}MB)"
if !result
raise 'Upload not successful!'
end
end
end
next_playlist_request = HTTParty.get(next_playlist_uri)
if next_playlist_request.code != 200
return { "result" => "error", "request" => next_playlist_request }
end
next_playlist = M3u8::Playlist.read next_playlist_request.body
begin
Tempfile.create('tmpf', '/home/anhnhan/tmp-web-crawler/') do |tempfile|
next_playlist.items.map { |segment| twt_video_host + segment.segment }.each do |segment_uri|
segment_request = HTTParty.get(segment_uri)
if segment_request.code != 200
return { "result" => "error", "request" => segment_request }
end
# literally just write the next part at the end
# ts is a file format you can just concat
tempfile.write segment_request.body
end
path = tempfile.path
tempfile.flush
# transmux to mp4, ts makes me feel old
`ffmpeg -i #{path} -c:v copy -c:a copy -bsf:a aac_adtstoasc #{path}2.mp4`
s3_path = s3_folder + filename
file_size = tempfile.size
object = @@s3_bucket.object(s3_path)
result = object.upload_file("#{path}2.mp4")
puts "Just uploaded #{s3_path} (#{(file_size.to_f / 2**20).round(2)}MB)"
if !result
raise 'Upload not successful!'
end
end
rescue Exception => e
retry_count = retry_count + 1
retry unless retry_count > 5
self.log_warning ":warning: Url <#{url}> / `#{s3_path}` had upload error to S3! #{e.inspect}", event.bot
{ "result" => "error", "error" => e }
end
{ "result" => "success", "id" => video_id, "path" => s3_path }
else
# straight mp4 (/ vmap)
s3_path = s3_folder + File.basename(video_uri.sub(/\?tag=\d+/i, ""))
begin
Tempfile.create('tmpf', '/home/anhnhan/tmp-web-crawler/') do |tempfile|
tempfile.write HTTParty.get(video_uri).body
tempfile.flush
tempfile.seek(0)
file_size = tempfile.size
object = @@s3_bucket.object(s3_path)
result = object.upload_file(tempfile)
puts "Just uploaded #{s3_path} (#{(file_size.to_f / 2**20).round(2)}MB)"
if !result
raise 'Upload not successful!'
end
end
{ "result" => "success", "id" => video_id, "path" => s3_path }
rescue Exception => e
retry_count = retry_count + 1
retry unless retry_count > 5
self.log_warning ":warning: Url <#{url}> / `#{s3_path}` had upload error to S3! #{e.inspect}", event.bot
{ "result" => "error", "error" => e }
end
end
end
results_links = links.map do |link_url|
if @@twitter_downloaded.include?(author) &&
@@twitter_downloaded[author].include?(id) &&
@@twitter_downloaded[author][id]["files_links"].include?(Digest::MD5.hexdigest(link_url))
next { "result" => "skipped" }
end
{ "result" => "not_implemented", "reason" => "not implemented" }
end
time_end = Time.now
{
"result" => "success",
"id" => id,
"author" => author,
"path" => s3_folder,
"images" => results_images,
"videos" => results_videos,
"links" => results_links,
"expected_images" => images.length,
"expected_videos" => videos.length,
"expected_links" => links.length,
"time_taken" => time_end - time_start,
}
end
# this routine will also process retweets
def self.process_twitter_profile(author, event)
if @@abort_twitter_queue_in_progress
return
end
self.log ":information_desk_person: Going through @#{author}'s Twitter page", event.bot
begin
request = HTTParty.get("https://twitter.com/#{author}", follow_redirects: false)
if request.code == 302 && request.headers["location"] == "https://twitter.com/account/suspended"
msg = ":information_desk_person: Twitter account `#{author}` is suspended, skipping"
self.log_warning msg, event.bot
self.log msg, event.bot
return
end
if request.code != 200
msg = ":information_desk_person: Twitter account `#{author}` hard error, HTTP #{request.code}, skipping"
self.log_warning msg, event.bot
self.log msg, event.bot
return
end
page = Nokogiri::HTML(request.body)
if page.css(".ProtectedTimeline-heading").size > 0
msg = ":information_desk_person: Twitter account `#{author}` has *protected timeline*, skipping"
self.log_warning msg, event.bot
self.log msg, event.bot
return
end
rescue => e
# TODO: debug
self.log_warning "self.process_twitter_profile: Hard error while checking suspended account for `#{author}`: `#{e.inspect}`", event.bot
puts e.inspect
return
end
time_start = Time.now
earliest_tweet_id = false
results = []
has_more_items = true
page_count = 0
while has_more_items && !earliest_tweet_id.nil? do
page_count = page_count + 1
begin
tweets = HTTParty.get("https://twitter.com/i/profiles/show/#{author}/timeline/tweets?include_available_features=1&count=200&include_entities=1#{if earliest_tweet_id then "&max_position=" + earliest_tweet_id end}&reset_error_state=false")
rescue => e
self.log_warning "self.process_twitter_profile: Hard error while fetching tweets for `#{author}`, page #{page_count}, earliest tweet id `#{earliest_tweet_id}`: `#{e.inspect}`", event.bot
next
end
if tweets.code != 200
# :sowonnotlikethis:
next { "result": "error", "request" => tweets }
end
begin
tweets = JSON.parse(tweets.body)
rescue => e
self.log_warning ":warning: Profile <#{author}> had an error parsing HTML, usually suspended:\n```\n#{e.inspect}\n```\n", event.bot
next { "result": "error", "request" => tweets, "error" => e }
end
tweets_html = Nokogiri::HTML(tweets["items_html"])
has_more_items = tweets["has_more_items"]
earliest_tweet_id = tweets["min_position"]
tweet_urls = tweets_html.css(".tweet").map do |div|
# these are absolute urls without host
div.attribute("data-permalink-path").to_s
end || []
tweet_urls.each do |tweet_url|
begin
result = self.process_tweet(tweet_url, event, did_suspended_check: true)
rescue => e
self.log_warning ":warning: Tweet <#{tweet_url}> had an error:\n```\n#{e.inspect}\n```\n", event.bot
results << { "result" => "error" }
next
end
if @@abort_twitter_queue_in_progress
return
end
results << result
if result && result["result"] == "success"
begin
self.twitter_record_successful_result(result["author"], result["id"], result)
rescue => e
self.log_warning ":warning: Tweet `#{tweet_url}` had exception:\n```\n#{e.inspect}\n```", event.bot
end
end
# TODO Do something with errors
end
if @@abort_twitter_queue_in_progress
return
end
File.open(BuddyBot.path("content/downloaded-twitter.yml"), "w") { |file| file.write(YAML.dump(@@twitter_downloaded)) }
self.log ":ballot_box_with_check: `#{Time.now}` Just went through #{tweet_urls.length}x tweets from @#{author}'s profile, #{results.length}x tweets so far", event.bot
puts "has more pages: #{has_more_items.inspect}, min pos #{earliest_tweet_id.inspect}"
end
result_counts = {
"total_error" => 0,
"total_skipped" => 0,
"success_images" => 0,
"success_videos" => 0,
"success_links" => 0,
"skipped_images" => 0,
"skipped_videos" => 0,
"skipped_links" => 0,
"error_images" => 0,
"error_videos" => 0,
"error_links" => 0,
"not_implemented_images" => 0,
"not_implemented_videos" => 0,
"not_implemented_links" => 0,
}
results.each do |result|
if !result || result["result"] == "error"
result_counts["total_error"] = result_counts["total_error"] + 1
next
end
if result["result"] == "skipped"
result_counts["total_skipped"] = result_counts["total_skipped"] + 1
next
end
[ "images", "videos", "links" ].each do |key|
(result[key] || []).each do |element_result|
if !element_result || !element_result["result"]
result_counts["error_" + key] = result_counts["error_" + key] + 1
else
result_counts[element_result["result"] + "_" + key] = result_counts[element_result["result"] + "_" + key] + 1
end
end
end
end
download_summary = result_counts.delete_if { |key, value| value == 0 }.map { |key, value| "#{key}: #{value}x" }.join("\n") || "no media found"
time_end = Time.now
self.log ":ballot_box_with_check: Finished going through @#{author}'s page, processing #{results.length}x tweets in #{(time_end - time_start).round(1)}s\n#{download_summary}", event.bot
end
def self.twitter_record_successful_result(author, id, result)
if !@@twitter_downloaded.include? author
@@twitter_downloaded[author] = {}
end
if !@@twitter_downloaded[author].include? id
@@twitter_downloaded[author][id] = {
"expected_images" => 0,
"expected_videos" => 0,
"expected_links" => 0,
"files_images" => {},
"files_videos" => {},
"files_links" => {},
}
end
[ "images", "videos", "links" ].each do |key|
@@twitter_downloaded[author][id]["expected_" + key] = [ @@twitter_downloaded[author][id]["expected_" + key], result["expected_" + key] ].max
result[key].each do |element_result|
if element_result["result"] == "success"
@@twitter_downloaded[author][id]["files_" + key][element_result["id"]] = element_result["path"]
end
end
end
end
# provide bearer token from logging into twitter and looking into the network panel
message(start_with: "!twitter-get-following ") do |event|
screen_name, bearer_token, cursor = event.content.scan(/^!twitter-get-following\s+(\w+)\s+(.*?)(\s+(.*?))?\s*$/i)[0]
screen_names = []
cursor = (cursor || "-1").strip
while !cursor.nil? && cursor != "0"
request = HTTParty.get("https://api.twitter.com/1.1/friends/list.json?cursor=#{cursor}&count=200&include_user_entities=false&skip_status=1&screen_name=#{screen_name}", { "headers": { "authorization": "Bearer " + bearer_token } })
puts request.code
if request.code != 200
if request.code == 429
event.send_message "Bumped into rate limiting, current cursor is '#{cursor}'"
end
break
end
data = JSON.parse(request.body)
cursor = data["next_cursor_str"]
data["users"].each{ |user| screen_names << user["screen_name"] }
puts "Just added #{data["users"].length}x followings, next cursor is '#{cursor.inspect}'"
sleep(5)
end
(screen_names.each_slice(10) || []).each do |_screen_names|
event.send_message _screen_names.map{ |name| "- `#{name}`" }.join("\n")
end
event.send_message "EL FINITO."
end
def self.twitter_retrieve_app_bearer(key, secret, bot)
endpoint = "https://api.twitter.com/oauth2/token"
bearer_basic_authentication = Base64.strict_encode64 "#{key}:#{secret}"
result = HTTParty.post(endpoint, {
body: 'grant_type=client_credentials',
headers: {
"Authorization" => "Basic #{bearer_basic_authentication}",
"Content-Type" => "application/x-www-form-urlencoded;charset=UTF-8",
}
})
if result.code != 200
self.log_warning ":warning: Invalid request when requesting app bearer for Twitter: #{result.inspect}", bot
return nil
end
result_json = JSON.parse(result.body)
if result_json["token_type"] != "bearer"
self.log_warning ":warning: Invalid data when requesting app bearer for Twitter: #{result_json.inspect}", bot
return nil
end
result_json["access_token"]
end
end
| 42.287179
| 349
| 0.637198
|
f4aece657af1dd9a7e874c50a459f37ddc8a3769
| 2,293
|
dart
|
Dart
|
lib/src/utils/fee_calculator.dart
|
jffp113/algorand-dart
|
c0ab69beaee41ce6fb1d7865b4e4f1f422562ca3
|
[
"MIT"
] | 30
|
2021-03-12T13:28:40.000Z
|
2022-03-04T03:54:22.000Z
|
lib/src/utils/fee_calculator.dart
|
jffp113/algorand-dart
|
c0ab69beaee41ce6fb1d7865b4e4f1f422562ca3
|
[
"MIT"
] | 29
|
2021-03-24T20:01:55.000Z
|
2022-03-31T16:00:11.000Z
|
lib/src/utils/fee_calculator.dart
|
jffp113/algorand-dart
|
c0ab69beaee41ce6fb1d7865b4e4f1f422562ca3
|
[
"MIT"
] | 9
|
2021-03-24T19:56:02.000Z
|
2022-03-22T09:51:09.000Z
|
import 'package:algorand_dart/src/models/models.dart';
import 'package:algorand_dart/src/utils/encoders/msgpack_encoder.dart';
class FeeCalculator {
/// Calculate the total fee for a transaction.
/// This value is multiplied by the estimated size of the transaction in
/// bytes to determine the total transaction fee.
///
/// If the result is less than the minimum fee, the minimum fee is used
/// instead.
static Future<int> calculateFeePerByte(
RawTransaction transaction, int suggestedFeePerByte) async {
final transactionSize = await estimateTransactionSize(transaction);
var transactionFee = suggestedFeePerByte * transactionSize;
// Check min fee
if (transactionFee < RawTransaction.MIN_TX_FEE_UALGOS) {
transactionFee = RawTransaction.MIN_TX_FEE_UALGOS;
}
return transactionFee;
}
/// Calculate the total fee for a transaction.
/// This value is multiplied by the estimated size of the transaction in
/// bytes to determine the total transaction fee.
///
/// If the result is less than the minimum fee, the minimum fee is used
/// instead.
static Future<int> calculateTransactionFee(
int transactionSize, int suggestedFeePerByte) async {
var transactionFee = suggestedFeePerByte * transactionSize;
// Check min fee
if (transactionFee < RawTransaction.MIN_TX_FEE_UALGOS) {
transactionFee = RawTransaction.MIN_TX_FEE_UALGOS;
}
return transactionFee;
}
/// Returns the estimated encoded size of the transaction, including
/// the signature.
///
/// This function is useful for calculating the fee from suggested
/// fee per byte.
///
/// Returns an estimated byte size for the transaction.
static Future<int> estimateTransactionSize(RawTransaction transaction) async {
try {
// Create a random account to sign the transaction
final account = await Account.random();
// Sign the transaction
final signature = await account.sign(transaction.getEncodedTransaction());
final signedTransaction = SignedTransaction(
transaction: transaction,
signature: signature.bytes,
);
return Encoder.encodeMessagePack(signedTransaction.toMessagePack())
.length;
} catch (ex) {
return 0;
}
}
}
| 33.720588
| 80
| 0.714348
|
ae2df9b50d909bbd548c84757e0fcde72a8beb2b
| 3,025
|
cs
|
C#
|
Code/Menu/MenuManager.cs
|
ben-gibbons-github/DuelBots
|
411be02327a5f9df47b9a580b47cea24407e2e95
|
[
"MIT"
] | null | null | null |
Code/Menu/MenuManager.cs
|
ben-gibbons-github/DuelBots
|
411be02327a5f9df47b9a580b47cea24407e2e95
|
[
"MIT"
] | null | null | null |
Code/Menu/MenuManager.cs
|
ben-gibbons-github/DuelBots
|
411be02327a5f9df47b9a580b47cea24407e2e95
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
namespace DuelBots
{
public class MenuManager
{
public static List<MenuBasic> CurrentMenus = new List<MenuBasic>();
public static MenuBasic ActiveMenu;
public static List<MenuInput> Inputs = new List<MenuInput>();
public static MenuProfile[] Profiles = new MenuProfile[2];
public static Texture2D BarTexture;
public static SpriteFont Font;
public static void Load()
{
for (int i = 0; i < 4; i++)
{
Inputs.Add(new MenuInput((PlayerIndex)i));
}
Font = Game1.contentManager.Load<SpriteFont>("Font");
BarTexture = Game1.contentManager.Load<Texture2D>("blank");
ActiveMenu = new LevelEditorWindow().Create();
CurrentMenus.Add(ActiveMenu);
ActiveMenu.Alive = true;
}
public static void Update(GameTime gameTime)
{
if(ActiveMenu!=null)
if (ActiveMenu.NeedsInput)
TakeInput(gameTime);
for (int i = 0; i < CurrentMenus.Count;i++ )
CurrentMenus[i].Update(gameTime);
}
public static void TakeInput(GameTime gameTime)
{
for (int i = 0; i < 2;i++)
if (Profiles[i] == null)
{
foreach (MenuInput Input in Inputs)
{
Input.Update(gameTime);
if (Input.CheckAnyButton())
Profiles[i] = new MenuProfile(Input);
}
}
else
{
Profiles[i].Input.Update(gameTime);
ActiveMenu.TakeInput(Profiles[i].Input);
}
}
public static void SwitchActive(MenuBasic NewMenu, bool DiscardAll,bool AddSelected)
{
if (ActiveMenu.Ready)
{
if (DiscardAll)
{
foreach (MenuBasic Menu in CurrentMenus)
Menu.Discard(NewMenu.HeaderPosition,false);
NewMenu.Header = ActiveMenu.Discard(NewMenu.HeaderPosition,AddSelected);
}
ActiveMenu = NewMenu;
CurrentMenus.Add(NewMenu);
}
}
public static void RemoveMenu(MenuBasic Menu)
{
CurrentMenus.Remove(Menu);
if (Menu == ActiveMenu)
ActiveMenu = null;
}
public static void Draw()
{
Game1.graphicsDevice.Clear(Color.Black);
foreach (MenuBasic Menu in CurrentMenus)
Menu.Draw();
}
}
}
| 29.368932
| 93
| 0.49686
|
0a98f064e554aec23900135b6e985631f37a31bf
| 6,120
|
cs
|
C#
|
src/ESFA.DC.ILR.ValidationService.Data.Population.Tests/Mappers/OrganisationsDataMapperTests.cs
|
SkillsFundingAgency/DC-ILR-2021-ValidationService
|
85682bea33733974597573e7e7dc7137c5442056
|
[
"MIT"
] | 1
|
2021-02-19T15:19:54.000Z
|
2021-02-19T15:19:54.000Z
|
src/ESFA.DC.ILR.ValidationService.Data.Population.Tests/Mappers/OrganisationsDataMapperTests.cs
|
SkillsFundingAgency/DC-ILR-2021-ValidationService
|
85682bea33733974597573e7e7dc7137c5442056
|
[
"MIT"
] | null | null | null |
src/ESFA.DC.ILR.ValidationService.Data.Population.Tests/Mappers/OrganisationsDataMapperTests.cs
|
SkillsFundingAgency/DC-ILR-2021-ValidationService
|
85682bea33733974597573e7e7dc7137c5442056
|
[
"MIT"
] | 2
|
2021-02-19T15:20:01.000Z
|
2021-04-11T08:42:16.000Z
|
using System;
using System.Collections.Generic;
using ESFA.DC.ILR.ReferenceDataService.Model.Organisations;
using ESFA.DC.ILR.ValidationService.Data.External.Organisation.Model;
using ESFA.DC.ILR.ValidationService.Data.Population.Mappers;
using FluentAssertions;
using Xunit;
using Organisation = ESFA.DC.ILR.ValidationService.Data.External.Organisation.Model.Organisation;
namespace ESFA.DC.ILR.ValidationService.Data.Population.Tests.Mappers
{
public class OrganisationsDataMapperTests
{
[Fact]
public void MapOrganisations()
{
var organisations = TestOrganisations();
var expectedOrganisations = new Dictionary<long, Organisation>
{
{
1, new Organisation
{
UKPRN = 1,
PartnerUKPRN = true,
LegalOrgType = "LegalOrgType",
LongTermResid = true,
ShortTermFundingInitiatives = new List<ShortTermFundingInitiative>()
{
new ShortTermFundingInitiative
{
UKPRN = 1,
LdmCode = "ldm1",
EffectiveFrom = new DateTime(2019,8,1)
}
}
}
},
{
2, new Organisation
{
UKPRN = 2,
PartnerUKPRN = false,
LegalOrgType = "LegalOrgType",
LongTermResid = false,
ShortTermFundingInitiatives = new List<ShortTermFundingInitiative>()
{
new ShortTermFundingInitiative
{
UKPRN = 2,
LdmCode = "ldm2",
EffectiveFrom = new DateTime(2019,8,1)
}
}
}
},
};
NewMapper().MapOrganisations(organisations).Should().BeEquivalentTo(expectedOrganisations);
}
[Fact]
public void MapCampusIdentifiers()
{
var organisations = TestOrganisations();
var expectedCampusIdentifiers = new List<CampusIdentifier>
{
new CampusIdentifier { MasterUKPRN = 1, CampusIdentifer = "Id1" },
new CampusIdentifier { MasterUKPRN = 1, CampusIdentifer = "Id2" },
new CampusIdentifier { MasterUKPRN = 2, CampusIdentifer = "Id1" },
new CampusIdentifier { MasterUKPRN = 2, CampusIdentifer = "Id2" }
};
NewMapper().MapCampusIdentifiers(organisations).Should().BeEquivalentTo(expectedCampusIdentifiers);
}
private IReadOnlyCollection<ReferenceDataService.Model.Organisations.Organisation> TestOrganisations()
{
return new List<ReferenceDataService.Model.Organisations.Organisation>
{
new ReferenceDataService.Model.Organisations.Organisation
{
UKPRN = 1,
PartnerUKPRN = true,
LegalOrgType = "LegalOrgType",
LongTermResid = true,
OrganisationFundings = new List<OrganisationFunding>(),
CampusIdentifers = new List<OrganisationCampusIdentifier>
{
new OrganisationCampusIdentifier
{
CampusIdentifier = "Id1",
EffectiveFrom = new System.DateTime(2019, 8, 1)
},
new OrganisationCampusIdentifier
{
CampusIdentifier = "Id2",
EffectiveFrom = new System.DateTime(2019, 8, 1)
}
},
OrganisationShortTermFundingInitiatives = new List<OrganisationShortTermFundingInitiative>()
{
new OrganisationShortTermFundingInitiative()
{
UKPRN = 1,
LdmCode = "ldm1",
EffectiveFrom = new DateTime(2019,8,1)
}
}
},
new ReferenceDataService.Model.Organisations.Organisation
{
UKPRN = 2,
PartnerUKPRN = false,
LegalOrgType = "LegalOrgType",
LongTermResid = false,
OrganisationFundings = new List<OrganisationFunding>(),
CampusIdentifers = new List<OrganisationCampusIdentifier>
{
new OrganisationCampusIdentifier
{
CampusIdentifier = "Id1",
EffectiveFrom = new System.DateTime(2019, 8, 1)
},
new OrganisationCampusIdentifier
{
CampusIdentifier = "Id2",
EffectiveFrom = new System.DateTime(2019, 8, 1)
}
},
OrganisationShortTermFundingInitiatives = new List<OrganisationShortTermFundingInitiative>()
{
new OrganisationShortTermFundingInitiative()
{
UKPRN = 2,
LdmCode = "ldm2",
EffectiveFrom = new DateTime(2019,8,1)
}
}
}
};
}
private OrganisationsDataMapper NewMapper()
{
return new OrganisationsDataMapper();
}
}
}
| 40.529801
| 112
| 0.455882
|
5e0c8a2310e9cae77cfa6e0e83a9302b3e8a61e0
| 983
|
sql
|
SQL
|
openGaussBase/testcase/SQL/DDL/create_function/Opengauss_Function_DDL_Create_Function_Case0152.sql
|
opengauss-mirror/Yat
|
aef107a8304b94e5d99b4f1f36eb46755eb8919e
|
[
"MulanPSL-1.0"
] | null | null | null |
openGaussBase/testcase/SQL/DDL/create_function/Opengauss_Function_DDL_Create_Function_Case0152.sql
|
opengauss-mirror/Yat
|
aef107a8304b94e5d99b4f1f36eb46755eb8919e
|
[
"MulanPSL-1.0"
] | null | null | null |
openGaussBase/testcase/SQL/DDL/create_function/Opengauss_Function_DDL_Create_Function_Case0152.sql
|
opengauss-mirror/Yat
|
aef107a8304b94e5d99b4f1f36eb46755eb8919e
|
[
"MulanPSL-1.0"
] | null | null | null |
-- @testpoint: 函数内部设置current_schema,执行完函数前后current_schema不变
--查询当前schema,默认是public
select current_schema;
--创建schema
drop schema if exists sc;
create schema sc;
--创建函数set current_schema
drop FUNCTION if EXISTS func_add_sql(integer, integer);
--创建函数
CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer
as 'select $1 + $2;'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT
set current_schema=sc;
/
--查询current_schema不变
select current_schema;
drop FUNCTION func_add_sql(integer, integer);
--函数内部设置search_path,执行完函数前后search_path不变
--执行如下命令查看搜索路径
SHOW SEARCH_PATH;
--创建函数set search_path
drop FUNCTION if EXISTS func_add_sql(integer, integer);
--创建函数
CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer
as 'select $1 + $2;'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT
set search_path=myschema, public;
/
--查询search_path不变
SHOW SEARCH_PATH;
drop FUNCTION func_add_sql(integer, integer);
drop schema sc;
| 26.567568
| 66
| 0.763988
|
f12d1a68e00698f00a702707b706a1cc4be3584a
| 118
|
rb
|
Ruby
|
spec/fabricators/case_test_fabricator.rb
|
dtf-gems/dtf-skeleton
|
62a7f416a8d750733f9ad6ff5347c5c83dde9586
|
[
"MIT"
] | 3
|
2015-10-10T11:12:00.000Z
|
2016-06-21T22:33:00.000Z
|
spec/fabricators/case_test_fabricator.rb
|
dtf-gems/dtf-session
|
6c0f0446c46e6cc5b9fbe2c54f49d53ed54d17f2
|
[
"MIT"
] | 1
|
2021-09-22T23:56:33.000Z
|
2021-09-22T23:56:33.000Z
|
spec/fabricators/case_test_fabricator.rb
|
dtf-gems/dtf-session
|
6c0f0446c46e6cc5b9fbe2c54f49d53ed54d17f2
|
[
"MIT"
] | 1
|
2019-01-13T04:06:52.000Z
|
2019-01-13T04:06:52.000Z
|
# encoding: UTF-8
Fabricator(:case_test) do
description "Fabricated CT for DTF testing"
cmd "ruby --version"
end
| 16.857143
| 45
| 0.728814
|
2c6b1ccd0d2b417342408f09dc965571a45b7d51
| 1,177
|
py
|
Python
|
tests/components/switch/common.py
|
Hypfer/home-assistant
|
204ca3f3a6e24ef11ece2e2ee490a8d77553c147
|
[
"Apache-2.0"
] | 1
|
2019-12-06T08:49:19.000Z
|
2019-12-06T08:49:19.000Z
|
tests/components/switch/common.py
|
FuqiangSong/home-assistant
|
d5419b77f9c245e5af006143eb55ae4dda3f174e
|
[
"Apache-2.0"
] | 2
|
2021-02-08T20:39:43.000Z
|
2021-09-08T01:36:57.000Z
|
tests/components/switch/common.py
|
FuqiangSong/home-assistant
|
d5419b77f9c245e5af006143eb55ae4dda3f174e
|
[
"Apache-2.0"
] | null | null | null |
"""Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.switch import DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
ENTITY_MATCH_ALL,
)
from homeassistant.loader import bind_hass
@bind_hass
def turn_on(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified switch on."""
hass.add_job(async_turn_on, hass, entity_id)
async def async_turn_on(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified switch on."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, data, blocking=True)
@bind_hass
def turn_off(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified switch off."""
hass.add_job(async_turn_off, hass, entity_id)
async def async_turn_off(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified switch off."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
await hass.services.async_call(DOMAIN, SERVICE_TURN_OFF, data, blocking=True)
| 30.973684
| 81
| 0.761257
|
389999d8b4d3cd459e40e78202793d0da90b720a
| 5,929
|
php
|
PHP
|
app/Console/Commands/SubtitleCommand.php
|
haanhman/ox
|
1a3a359094908a0999a72fb190ed9d353b2e08e7
|
[
"MIT"
] | null | null | null |
app/Console/Commands/SubtitleCommand.php
|
haanhman/ox
|
1a3a359094908a0999a72fb190ed9d353b2e08e7
|
[
"MIT"
] | null | null | null |
app/Console/Commands/SubtitleCommand.php
|
haanhman/ox
|
1a3a359094908a0999a72fb190ed9d353b2e08e7
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Console\Commands;
use App\Criteria\FirstRecordCriteria;
use App\Entities\Youtube;
use App\Repositories\YoutubeRepository;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Criteria\RequestCriteria;
class SubtitleCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'y:subtitle';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Fetch subtitle from youtube';
private $sub = [];
private $youtubeRepository;
private $start = -1;
private $startTime = 0;
private $yid = 0;
private $info = null;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(YoutubeRepository $youtubeRepository)
{
parent::__construct();
$this->youtubeRepository = $youtubeRepository;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->startTime = time();
$this->youtubeRepository->pushCriteria(app(FirstRecordCriteria::class));
$youtube = $this->youtubeRepository->first();
if (empty($youtube)) {
$this->log('End data');
$this->comment('End data');
die;
}
$this->yid = $youtube->id;
$this->error('ID: ' . $this->yid);
$this->log('ID: ' . $this->yid);
$querys = [
'op' => 1,
'vid' => $youtube->youtube_id,
'q' => 'a',
'accent' => $youtube->accent == 'us' ? 1 : 2
];
$src = 'https://youglish.com/fetchcap.jsp?' . http_build_query($querys);
// $this->info('URL: ' . $src);
$info = get_web_page($src);
$this->info = $info = json_decode($info, true);
$msg = 'S: ' . $info['start'] . ' -- E: ' . $info['end'];
$this->warn($msg);
$this->log($msg);
$this->getSubTitle($info['start'], $info, $youtube);
while (true) {
$collection = collect($this->sub);
$last = $collection->last();
$start = $last['end'];
if ($start >= $info['end']) {
$this->comment('Start: ' . $start . ' -- End: ' . $info['end']);
$this->log('Start: ' . $start . ' -- End: ' . $info['end']);
break;
}
if (!$this->getSubTitle($start, $info, $youtube, false, $last)) {
break;
}
sleep(rand(5, 10));
}
$this->updateSubtitle($youtube->id);
}
private function updateSubtitle($id)
{
$this->info(date('d/m/Y H:i:s') . ' Update subtitle: ' . $id);
$this->log(date('d/m/Y H:i:s') . ' Update subtitle: ' . $id);
$this->youtubeRepository->pushCriteria(app(RequestCriteria::class));
$collect = collect($this->sub);
$this->youtubeRepository->update([
'subtitle' => json_encode($this->sub),
's1' => $this->info['start'],
'e1' => $this->info['end'],
's2' => $collect->first()['start'],
'e2' => $collect->last()['end'],
], $id);
if (empty($this->sub)) {
$this->error('bi BAN roi nhe');
$this->log('bi BAN roi nhe');
die;
}
$this->refreshCommand();
}
private function refreshCommand($seconds = 1)
{
$this->log(' --------------------------- OK OK ----------------------------' . PHP_EOL);
$this->info('Total time: ' . (time() - $this->startTime) . ' s');
$this->log('Total time: ' . (time() - $this->startTime) . ' s');
die;
$this->sub = [];
$this->start = -1;
$this->startTime = 0;
$this->yid = 0;
$this->info = null;
sleep($seconds);
$this->call('y:subtitle');
}
private function getSubTitle($start, $info, $youtube, $skip = false, $last = null)
{
if ($start == $this->start && !$skip) {
$this->sub = [1];
$this->updateSubtitle($this->yid);
$this->error('Hong roi: ' . $this->start);
$this->error('chay lai sau 3 giay');
$this->refreshCommand(3);
die;
}
$this->start = $start;
$this->comment(date('d/m/Y H:i:s') . ' Start: ' . $this->start . ' of ---- ' . $info['end']);
$this->log(date('d/m/Y H:i:s') . ' Start: ' . $this->start . ' of ---- ' . $info['end']);
$querys = [
'op' => 0,
'q' => 'a',
'hm' => 10,
'from' => $this->start,
'fid' => $info['fid'],
'lid' => $info['lid'],
'vid' => $info['id'],
'id' => $youtube->cid,
'calltime' => time(),
'accent' => $youtube->accent == 'us' ? 1 : 2
];
if ($last != null) {
$querys = [
'op' => 0,
'q' => 'a',
'hm' => 10,
'cid' => $last['cid'],
'id' => $last['id'],
'fid' => $info['fid'],
'lid' => $info['lid'],
'vid' => $info['id'],
'calltime' => time(),
'accent' => $youtube->accent == 'us' ? 1 : 2
];
}
$src = 'https://youglish.com/fetchcap.jsp?' . http_build_query($querys);
// $this->info('URL: ' . $src);
$sub = get_web_page($src);
$subtitle = json_decode($sub, true);
if (!empty($subtitle['results'])) {
foreach ($subtitle['results'] as $sub) {
$this->sub[$sub['start']] = $sub;
}
return true;
}
return false;
}
private function log($msg) {
//app('log')->debug($msg);
}
}
| 30.096447
| 101
| 0.452184
|
cd75715a8822ba762346427d6cbaab76e0aee513
| 2,199
|
cs
|
C#
|
src/CommandLineParser.Tests/CommandLineArgumentConstants.cs
|
wbbarr/CommandLineParser.NetCore
|
17da6d60575ab030bdea09fa0c3ed21aea04e1c1
|
[
"MIT"
] | null | null | null |
src/CommandLineParser.Tests/CommandLineArgumentConstants.cs
|
wbbarr/CommandLineParser.NetCore
|
17da6d60575ab030bdea09fa0c3ed21aea04e1c1
|
[
"MIT"
] | null | null | null |
src/CommandLineParser.Tests/CommandLineArgumentConstants.cs
|
wbbarr/CommandLineParser.NetCore
|
17da6d60575ab030bdea09fa0c3ed21aea04e1c1
|
[
"MIT"
] | null | null | null |
namespace wbbarr.CommandLineParserNetCore.Tests
{
public static class SwitchTestConstants
{
public static readonly CommandLineSwitch ValidSwitch = new CommandLineSwitch()
{
Name = "switch",
Description = "A valid command line switch",
};
public static readonly CommandLineSwitch ValidSwitchWithChar = new CommandLineSwitch()
{
Name = "flagswitch",
Description = "A valid command line switch with a single char flag",
Flag = 'f'
};
}
public static class NamedParameterTestConstants
{
public static readonly CommandLineArgument StringRequiredTestArgument = new CommandLineArgument<string>()
{
Name = "teststring",
Description = "Does test things",
IsRequired = true,
};
public static readonly CommandLineArgument StringRequiredSecondArgument = new CommandLineArgument<string>()
{
Name = "secondstring",
Description = "Does some other things.",
IsRequired = true,
};
public static readonly CommandLineArgument BoolRequiredTestArgument = new CommandLineArgument<bool>()
{
Name = "testbool",
Description = "Does some boolean test things.",
IsRequired = true,
};
public static readonly CommandLineArgument IntRequiredTestArgument = new CommandLineArgument<int>()
{
Name = "testint",
Description = "Does some integer test things.",
IsRequired = true,
};
public static readonly CommandLineArgument StringOptionalTestArgument = new CommandLineArgument<string>()
{
Name = "teststring",
Description = "Does optional test things",
IsRequired = false,
};
public static readonly CommandLineArgument StringOptionalTestArgumentWithDefault = new CommandLineArgument<string>()
{
Name = "defaultteststring",
Description = "Does optional test things",
IsRequired = false,
DefaultValue = "TestDefaultValue",
};
}
}
| 37.271186
| 124
| 0.609368
|
1a415c76677faed0de0dae0c2a0fdda92f20b57c
| 2,221
|
py
|
Python
|
conflate/201904_park_ride/park_ride_idf_json.py
|
grischard/OSM_snippets
|
df3c69ab0d1496a636d760ac5546e6b5b011ea10
|
[
"MIT"
] | 6
|
2017-05-05T22:22:37.000Z
|
2020-04-02T09:20:34.000Z
|
conflate/201904_park_ride/park_ride_idf_json.py
|
grischard/OSM_snippets
|
df3c69ab0d1496a636d760ac5546e6b5b011ea10
|
[
"MIT"
] | 33
|
2017-05-05T19:29:22.000Z
|
2020-03-31T09:05:54.000Z
|
conflate/201904_park_ride/park_ride_idf_json.py
|
grischard/OSM_snippets
|
df3c69ab0d1496a636d760ac5546e6b5b011ea10
|
[
"MIT"
] | 3
|
2017-05-16T20:43:13.000Z
|
2020-04-02T09:20:37.000Z
|
import json
source = "Île-de-France Mobilités 04/2019"
no_dataset_id = True
query = [('park_ride', 'yes')]
master_tags = ('amenity',)
max_distance = 800
max_request_boxes = 3
overpass_timeout = 550
def dataset(fileobj):
import codecs
source = json.load(codecs.getreader('utf-8-sig')(fileobj))
#source = json.load(fileobj)
data = []
for el in source:
lat = float(el['geometry']['coordinates'][1])
lon = float(el['geometry']['coordinates'][0])
tags = {
'amenity': 'parking',
'park_ride': 'yes',
'capacity': el['fields']['nb_pl_pr'],
'official_name': el['fields']['nom_pr']
}
data.append(SourcePoint(el['recordid'], lat, lon, tags))
return data
# Example line of the source JSON:
# {
# "datasetid": "parcs-relais-idf",
# "recordid": "fe9680496370980cb966e3bca09793b443915fd8",
# "fields": {
# "www": "www.saint-quentin-en-yvelines.fr",
# "nb_pl_elec": 0.0,
# "nb_pl_pr": 219.0,
# "moa_pr": "CASQY",
# "nom_lda": "Saint-Quentin-en-Yvelines (Gare)",
# "nom_comm": "Montigny-le-Bretonneux",
# "nb_pl_2rm": 0.0,
# "mes_date": "2014-03-24T01:00:00+01:00",
# "mes_annee": 2014.0,
# "nom_gare": "SAINT-QUENTIN-EN-YVELINES (SNCF)",
# "nb_pl_cov": 0.0,
# "label_pr": 1.0,
# "gestion_pr": "Q-Park",
# "nom_pr": "Jol Le Theule",
# "struct_pr": "ouvrage",
# "nom_zdl": "Saint-Quentin-en-Yvelines (Avenue des Prs)",
# "id_ref_lda": 63812.0,
# "id_pr": 35.0,
# "geo_shape": {
# "type": "MultiPoint",
# "coordinates": [
# [2.0439044, 48.78620339998614, 0.0]
# ]
# },
# "id_ref_zdl": 43249.0,
# "nb_pl_pmr": 6.0,
# "adres_pr": "10 Rue Jol le Theule, 78180 Montigny-le-Bretonneux",
# "geo_point_2d": [48.78620339998614, 2.0439044],
# "nb_pl_v": 0.0,
# "insee_t": "78423"
# },
# "geometry": {
# "type": "Point",
# "coordinates": [2.0439044, 48.78620339998614]
# },
# "record_timestamp": "2019-02-19T16:15:48+01:00"
# }
| 30.013514
| 75
| 0.529941
|
6dbf75764de37c795c394271b4abaa572ba4fb56
| 902
|
h
|
C
|
ios/Classes/AmapSearchFluttifyPlugin.h
|
HongWeiChen/amap_search_fluttify
|
4a8a094980c5461c95fd3dc69ed1ea5e64927186
|
[
"Apache-2.0"
] | null | null | null |
ios/Classes/AmapSearchFluttifyPlugin.h
|
HongWeiChen/amap_search_fluttify
|
4a8a094980c5461c95fd3dc69ed1ea5e64927186
|
[
"Apache-2.0"
] | null | null | null |
ios/Classes/AmapSearchFluttifyPlugin.h
|
HongWeiChen/amap_search_fluttify
|
4a8a094980c5461c95fd3dc69ed1ea5e64927186
|
[
"Apache-2.0"
] | null | null | null |
//////////////////////////////////////////////////////////
// GENERATED BY FLUTTIFY. DO NOT EDIT IT.
//////////////////////////////////////////////////////////
#import <Flutter/Flutter.h>
#import <AMapSearchKit/AMapSearchObj.h>
#import <AMapSearchKit/AMapCommonObj.h>
#import <AMapSearchKit/AMapSearchVersion.h>
#import <AMapSearchKit/AMapSearchError.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapSearchKit/AMapNearbyUploadInfo.h>
#import <AMapSearchKit/AMapNearbySearchManager.h>
#import <AMapSearchKit/AMapSearchAPI.h>
typedef void (^Handler)(NSObject <FlutterPluginRegistrar> *, id, FlutterResult);
@interface AmapSearchFluttifyPlugin : NSObject<AMapNearbySearchManagerDelegate, AMapSearchDelegate, FlutterPlugin>
- (instancetype) initWithFlutterPluginRegistrar: (NSObject <FlutterPluginRegistrar> *) registrar;
@property(nonatomic) NSObject<FlutterPluginRegistrar>* registrar;
@end
| 37.583333
| 114
| 0.713969
|
93189405408b304f29a37f8604cc98d0d14a8cff
| 23,363
|
cpp
|
C++
|
SurfaceMeshProcessing/surfacemeshprocessing.cpp
|
ChunyangYe/MEBP_VLSM
|
5e59f98bf34f10e5472ed13e6e19c3eb547f15c8
|
[
"MIT"
] | 3
|
2020-12-24T02:33:48.000Z
|
2021-11-30T10:38:26.000Z
|
SurfaceMeshProcessing/surfacemeshprocessing.cpp
|
ChunyangYe/MEBP_VLSM
|
5e59f98bf34f10e5472ed13e6e19c3eb547f15c8
|
[
"MIT"
] | null | null | null |
SurfaceMeshProcessing/surfacemeshprocessing.cpp
|
ChunyangYe/MEBP_VLSM
|
5e59f98bf34f10e5472ed13e6e19c3eb547f15c8
|
[
"MIT"
] | 3
|
2020-10-09T07:16:33.000Z
|
2021-07-28T03:39:33.000Z
|
#include "surfacemeshprocessing.h"
#include "MeshViewer/MainViewerWidget.h"
#include "MeshViewer/Aux_Transform_Mesh_Dialog.h"
SurfaceMeshProcessing::SurfaceMeshProcessing(QWidget *parent)
: QMainWindow(parent)
{
viewer = new MainViewerWidget(this);
setCentralWidget(viewer);
initWindow();
createActions();
createMenus();
createToolBars();
createStatusBar();
}
SurfaceMeshProcessing::~SurfaceMeshProcessing()
{
}
void SurfaceMeshProcessing::initWindow()
{
connect(viewer,SIGNAL(setMouseMode_signal_main(int)),this,SLOT(setMouseMode_slot(int)));
connect(viewer,SIGNAL(setDrawMode_signal_main(int)),this,SLOT(setDrawMode_slot(int)));
}
void SurfaceMeshProcessing::createActions()
{
openAction = new QAction(tr("&Open"), this);
openAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/Open.png"));
openAction->setShortcut(QKeySequence::Open);
openAction->setStatusTip(tr("Open a mesh file"));
connect(openAction, SIGNAL(triggered()), viewer, SLOT(open_mesh_query()));
saveAction = new QAction(tr("&Save"), this);
saveAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/Save.png"));
saveAction->setShortcut(QKeySequence::Save);
saveAction->setStatusTip(tr("Save the mesh to file"));
connect(saveAction, SIGNAL(triggered()), viewer, SLOT(save_mesh_query()));
saveAsAction = new QAction(tr("Save &As..."), this);
saveAsAction->setStatusTip(tr("Save the mesh under a new name"));
connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveAs()));
exitAction = new QAction(tr("E&xit"), this);
exitAction->setShortcut(tr("Ctrl+Q"));
exitAction->setStatusTip(tr("Exit the application"));
connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));
clearAction = new QAction(("Clear Mesh"), this);
clearAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/ClearMesh.png"));
clearAction->setStatusTip(tr("Clear the Current Mesh"));
connect(clearAction, SIGNAL(triggered()), viewer, SLOT(clear_all_mesh()));
wireFrameAction = new QAction(tr("&WireFrame"), this);
wireFrameAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/wire.png"));
wireFrameAction->setStatusTip(tr("Using wireFrame showing method"));
wireFrameAction->setCheckable(true);
wireFrameAction->setChecked(false);
connect(wireFrameAction, SIGNAL(triggered()), this, SLOT(wireFrameShow()));
hiddenLinesAction = new QAction(tr("Hidden&Lines"), this);
hiddenLinesAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/hiddenlines.png"));
hiddenLinesAction->setStatusTip(tr("Using hiddenlines showing method"));
hiddenLinesAction->setCheckable(true);
hiddenLinesAction->setChecked(false);
connect(hiddenLinesAction, SIGNAL(triggered()), this, SLOT(hiddenLinesShow()));
solidFlatAction = new QAction(tr("Solid&Flat"), this);
solidFlatAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/flat.png"));
solidFlatAction->setStatusTip(tr("Using solidflat showing method"));
solidFlatAction->setCheckable(true);
solidFlatAction->setChecked(false);
connect(solidFlatAction, SIGNAL(triggered()), this, SLOT(solidFlatShow()));
flatPointsAction = new QAction(tr("Flat&Points"), this);
flatPointsAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/flatlines.png"));
flatPointsAction->setStatusTip(tr("Using flatpoints showing method"));
flatPointsAction->setCheckable(true);
flatPointsAction->setChecked(false);
connect(flatPointsAction, SIGNAL(triggered()), this, SLOT(flatPointsShow()));
solidSmoothAction = new QAction(tr("Solid&Smooth"), this);
solidSmoothAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/smooth.png"));
solidSmoothAction->setStatusTip(tr("Using solidsmooth showing method"));
solidSmoothAction->setCheckable(true);
solidSmoothAction->setChecked(false);
connect(solidSmoothAction, SIGNAL(triggered()), this, SLOT(solidSmoothShow()));
pointSetAction = new QAction(tr("&PointSet"), this);
pointSetAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/points.png"));
pointSetAction->setStatusTip(tr("Using pointset showing method"));
pointSetAction->setCheckable(true);
pointSetAction->setChecked(false);
connect(pointSetAction, SIGNAL(triggered()), this, SLOT(pointSetShow()));
curvatureAction = new QAction("Curvature",this);
curvatureAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/curvature.png"));
curvatureAction->setStatusTip(tr("Using Curvature showing method"));
curvatureAction->setCheckable(true);
curvatureAction->setChecked(false);
connect(curvatureAction, SIGNAL(triggered()), this, SLOT(curvatureShow()));
drawBoundingBox = new QAction("Draw BBox",this);
drawBoundingBox->setIcon(QIcon(":/SurfaceMeshProcessing/Images/bbox.png"));
drawBoundingBox->setStatusTip(tr("Draw Bounding Box?"));
connect(drawBoundingBox, SIGNAL(triggered()), this, SLOT(DrawBBox()));
drawMeshBoundaryAction = new QAction("Draw Mesh Boundary", this);
drawMeshBoundaryAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/boundary.png"));
drawMeshBoundaryAction->setStatusTip(tr("Draw Mesh Boundary?"));
connect(drawMeshBoundaryAction, SIGNAL(triggered()), this, SLOT(DrawMeshBoundary()));
updateMeshAction = new QAction(tr("&Update Mesh"), this);
updateMeshAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/Update.png"));
updateMeshAction->setStatusTip(tr("Update the normals and the center of the mesh"));
connect(updateMeshAction, SIGNAL(triggered()), viewer, SLOT(update_mesh()));
PointPickAction = new QAction(tr("&Select Point"), this);
PointPickAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/selections.png"));
PointPickAction->setStatusTip(tr("Select Point of the mesh"));
PointPickAction->setCheckable(true);
PointPickAction->setChecked(false);
connect(PointPickAction, SIGNAL(triggered()), this, SLOT(pointPick()));
VertexPickAction = new QAction(tr("&Select Vertex"), this);
VertexPickAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/selectVertices.png"));
VertexPickAction->setStatusTip(tr("Select Vertex of the mesh"));
VertexPickAction->setCheckable(true);
VertexPickAction->setChecked(false);
connect(VertexPickAction, SIGNAL(triggered()), this, SLOT(vertexPick()));
FacePickAction = new QAction(tr("&Select Face"), this);
FacePickAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/selectFaces.png"));
FacePickAction->setStatusTip(tr("Select Face of the mesh"));
FacePickAction->setCheckable(true);
FacePickAction->setChecked(false);
connect(FacePickAction, SIGNAL(triggered()), this, SLOT(facePick()));
EdgePickAction = new QAction(tr("&Select Edge"), this);
EdgePickAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/selectEdges.png"));
EdgePickAction->setStatusTip(tr("Select Edge of the mesh"));
EdgePickAction->setCheckable(true);
EdgePickAction->setChecked(false);
connect(EdgePickAction, SIGNAL(triggered()), this, SLOT(edgePick()));
clearSelectedAction = new QAction("Clear Selected",this);
clearSelectedAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/clear_select.png"));
clearSelectedAction->setStatusTip(tr("Clear All Selected"));
connect(clearSelectedAction, SIGNAL(triggered()), viewer, SLOT(clear_all_selected()));
moveVertexAction = new QAction(tr("&Move Vertex"), this);
moveVertexAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/move_vertex.png"));
moveVertexAction->setStatusTip(tr("Move Vertex of the mesh"));
moveVertexAction->setCheckable(true);
moveVertexAction->setChecked(false);
connect(moveVertexAction, SIGNAL(triggered()), this, SLOT(moveVertex()));
EditUndoAction = new QAction(tr("&Undo"), this);
EditUndoAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/edit-undo.png"));
EditUndoAction->setStatusTip(tr("Undo"));
EditUndoAction->setCheckable(true);
EditUndoAction->setChecked(false);
EditUndoAction->setEnabled(false);
connect(EditUndoAction, SIGNAL(triggered()), this, SLOT(edit_undo()));
connect(viewer, SIGNAL(set_edit_undo_enable_signal(bool)), this, SLOT(set_edit_undo_enable(bool)));
EditRedoAction = new QAction(tr("&Redo"), this);
EditRedoAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/edit-redo.png"));
EditRedoAction->setStatusTip(tr("Redo"));
EditRedoAction->setCheckable(true);
EditRedoAction->setChecked(false);
EditRedoAction->setEnabled(false);
connect(EditRedoAction, SIGNAL(triggered()), this, SLOT(edit_redo()));
connect(viewer, SIGNAL(set_edit_redo_enable_signal(bool)), this, SLOT(set_edit_redo_enable(bool)));
EdgeCollpaseAction = new QAction(tr("&Collapse Edge"), this);
EdgeCollpaseAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/topology-edgeCollapse.png"));
EdgeCollpaseAction->setStatusTip(tr("Select Edge of the mesh"));
EdgeCollpaseAction->setCheckable(true);
EdgeCollpaseAction->setChecked(false);
connect(EdgeCollpaseAction, SIGNAL(triggered()), this, SLOT(edge_collpase()));
EdgeSplitAction = new QAction(tr("&Split Edge"), this);
EdgeSplitAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/topology-edgeSplit.png"));
EdgeSplitAction->setStatusTip(tr("Select Edge of the mesh"));
EdgeSplitAction->setCheckable(true);
EdgeSplitAction->setChecked(false);
connect(EdgeSplitAction, SIGNAL(triggered()), this, SLOT(edge_split()));
EdgeFlipAction = new QAction(tr("&Flip Edge"), this);
EdgeFlipAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/topology-edgeFlip.png"));
EdgeFlipAction->setStatusTip(tr("Select Edge of the mesh"));
EdgeFlipAction->setCheckable(true);
EdgeFlipAction->setChecked(false);
connect(EdgeFlipAction, SIGNAL(triggered()), this, SLOT(edge_flip()));
saveScreenAction = new QAction("Save Screen",this);
saveScreenAction->setIcon(QIcon(":/SurfaceMeshProcessing/Images/saveScreen.png"));
saveScreenAction->setStatusTip(tr("Save Screen"));
connect(saveScreenAction, SIGNAL(triggered()), viewer, SLOT(saveOpenGLScreen()));
inverse_mesh_connectivity = new QAction("Inverse Connectivity",this);
inverse_mesh_connectivity->setStatusTip("Inverse Connectivity");
connect(inverse_mesh_connectivity, SIGNAL(triggered()), this, SLOT(aux_inverse_mesh_connectivity()));
scale_mesh_BBox = new QAction("isotropic scale mesh",this);
scale_mesh_BBox->setStatusTip("isotropic scale mesh");
connect(scale_mesh_BBox, SIGNAL(triggered()), this, SLOT(aux_scale_mesh_BBox()));
split_quad_mesh = new QAction("split quad Mesh", this);
split_quad_mesh->setStatusTip("split quad mesh");
connect(split_quad_mesh, SIGNAL(triggered()), this, SLOT(aux_split_quad_mesh()));
transform_mesh = new QAction("Transform Mesh", this);
transform_mesh->setStatusTip("Transform mesh");
connect(transform_mesh, SIGNAL(triggered()), this, SLOT(aux_transform_mesh()));
find_vertex_by_id = new QAction("Find Vertex(ID)", this);
find_vertex_by_id->setStatusTip("Find Vertex");
connect(find_vertex_by_id, SIGNAL(triggered()), this, SLOT(aux_find_vertex_by_index()));
find_face_by_id = new QAction("Find Face(ID)", this);
find_face_by_id->setStatusTip("Find Face");
connect(find_face_by_id, SIGNAL(triggered()), this, SLOT(aux_find_face_by_index()));
find_edge_by_id = new QAction("Find Edge(ID)", this);
find_edge_by_id->setStatusTip("Find Edge");
connect(find_edge_by_id, SIGNAL(triggered()), this, SLOT(aux_find_edge_by_index()));
find_vertex_by_valance = new QAction("Find Vertex(Valence)", this);
find_vertex_by_valance->setStatusTip("Find Vertex");
connect(find_vertex_by_valance, SIGNAL(triggered()), this, SLOT(aux_find_vertex_by_valance()));
delete_vertex_valence_four = new QAction("Delete Vertex(Four)", this);
delete_vertex_valence_four->setStatusTip("Find Vertex");
connect(delete_vertex_valence_four, SIGNAL(triggered()), this, SLOT(aux_delete_vertex_valence_four()));
delete_vertex_valence_three = new QAction("Delete Vertex(Three)", this);
delete_vertex_valence_three->setStatusTip("Find Vertex");
connect(delete_vertex_valence_three, SIGNAL(triggered()), this, SLOT(aux_delete_vertex_valence_three()));
split_vertex_valence_eight = new QAction("Split Vertex(Eight)", this);
split_vertex_valence_eight->setStatusTip("Find Vertex");
connect(split_vertex_valence_eight, SIGNAL(triggered()), this, SLOT(aux_split_vertex_valence_eight()));
testAction = new QAction("Test", this);
connect(testAction, SIGNAL(triggered()), this,SLOT(test()));
}
void SurfaceMeshProcessing::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAction);
fileMenu->addAction(saveAction);
fileMenu->addAction(saveAsAction);
fileMenu->addAction(clearAction);
fileMenu->addSeparator();
fileMenu->addAction(saveScreenAction);
fileMenu->addSeparator();
fileMenu->addAction(exitAction);
viewMenu = menuBar()->addMenu(tr("&View"));
viewMenu->addAction(wireFrameAction);
viewMenu->addAction(hiddenLinesAction);
viewMenu->addAction(solidFlatAction);
viewMenu->addAction(flatPointsAction);
viewMenu->addAction(solidSmoothAction);
viewMenu->addAction(pointSetAction);
viewMenu->addAction(curvatureAction);
viewMenu->addSeparator();
viewMenu->addAction(drawBoundingBox);
viewMenu->addAction(drawMeshBoundaryAction);
mouseMenu = menuBar()->addMenu(tr("&Pick"));
mouseMenu->addAction(PointPickAction);
mouseMenu->addAction(VertexPickAction);
mouseMenu->addAction(FacePickAction);
mouseMenu->addAction(EdgePickAction);
mouseMenu->addAction(clearSelectedAction);
mouseMenu->addAction(moveVertexAction);
Auxiliary_Menu = menuBar()->addMenu("Auxiliary");
Auxiliary_Menu->addAction(inverse_mesh_connectivity);
Auxiliary_Menu->addAction(scale_mesh_BBox);
Auxiliary_Menu->addAction(split_quad_mesh);
Auxiliary_Menu->addAction(transform_mesh);
Auxiliary_Menu->addSeparator();
Auxiliary_Menu->addAction(find_vertex_by_id);
Auxiliary_Menu->addAction(find_face_by_id);
Auxiliary_Menu->addAction(find_edge_by_id);
Auxiliary_Menu->addAction(find_vertex_by_valance);
Auxiliary_Menu->addSeparator();
Auxiliary_Menu->addAction(delete_vertex_valence_four);
Auxiliary_Menu->addAction(delete_vertex_valence_three);
Auxiliary_Menu->addAction(split_vertex_valence_eight);
helpMenu = menuBar()->addMenu(tr("&Help"));
}
void SurfaceMeshProcessing::createToolBars()
{
fileToolBar = addToolBar(tr("&File"));
fileToolBar->addAction(openAction);
fileToolBar->addAction(saveAction);
fileToolBar->addAction(clearAction);
fileToolBar->addAction(saveScreenAction);
viewToolBar = addToolBar(tr("&View"));
viewToolBar->addAction(wireFrameAction);
viewToolBar->addAction(hiddenLinesAction);
viewToolBar->addAction(solidFlatAction);
viewToolBar->addAction(flatPointsAction);
viewToolBar->addAction(solidSmoothAction);
viewToolBar->addAction(pointSetAction);
viewToolBar->addAction(curvatureAction);
otherViewBar = addToolBar("OtherView");
otherViewBar->addAction(drawBoundingBox);
otherViewBar->addAction(drawMeshBoundaryAction);
mouseToolBar = addToolBar(tr("MousePick"));
mouseToolBar->addAction(PointPickAction);
mouseToolBar->addAction(VertexPickAction);
mouseToolBar->addAction(FacePickAction);
mouseToolBar->addAction(EdgePickAction);
mouseToolBar->addAction(clearSelectedAction);
mouseToolBar->addAction(moveVertexAction);
localOperationBar = addToolBar(tr("Local Operation"));
localOperationBar->addAction(EditUndoAction);
localOperationBar->addAction(EditRedoAction);
localOperationBar->addAction(EdgeCollpaseAction);
localOperationBar->addAction(EdgeSplitAction);
localOperationBar->addAction(EdgeFlipAction);
instantMeshBar = addToolBar(tr("instantMesh"));
instantMeshBar->addAction(testAction);
}
void SurfaceMeshProcessing::createStatusBar()
{
statusLabel = new QLabel(tr("no mesh"));
statusLabel->setAlignment(Qt::AlignHCenter);
connect(viewer,SIGNAL( haveLoadMesh(QString) ),statusLabel,SLOT( setText(QString) ) );
statusBar()->addWidget(statusLabel);
}
bool SurfaceMeshProcessing::save()
{
return true;
}
bool SurfaceMeshProcessing::saveAs()
{
return true;
}
void SurfaceMeshProcessing::wireFrameShow()
{
viewer->setDrawMode(InteractiveViewerWidget::WIRE_FRAME);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
}
void SurfaceMeshProcessing::hiddenLinesShow()
{
viewer->setDrawMode(InteractiveViewerWidget::HIDDEN_LINES);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
}
void SurfaceMeshProcessing::solidFlatShow()
{
viewer->setDrawMode(InteractiveViewerWidget::SOLID_FLAT);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
}
void SurfaceMeshProcessing::flatPointsShow()
{
viewer->setDrawMode(InteractiveViewerWidget::FLAT_POINTS);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
}
void SurfaceMeshProcessing::solidSmoothShow()
{
viewer->setDrawMode(InteractiveViewerWidget::SOLID_SMOOTH);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
}
void SurfaceMeshProcessing::pointSetShow()
{
viewer->setDrawMode(InteractiveViewerWidget::POINT_SET);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
}
void SurfaceMeshProcessing::curvatureShow()
{
viewer->setDrawMode(InteractiveViewerWidget::CURVATURE);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
}
void SurfaceMeshProcessing::DrawBBox()
{
viewer->set_show_BBox();
}
void SurfaceMeshProcessing::DrawMeshBoundary()
{
viewer->set_show_mesh_boundary();
}
void SurfaceMeshProcessing::setAllViewActionChecked(bool b)
{
wireFrameAction->setChecked(b);
hiddenLinesAction->setChecked(b);
solidFlatAction->setChecked(b);
flatPointsAction->setChecked(b);
solidSmoothAction->setChecked(b);
pointSetAction->setChecked(b);
curvatureAction->setChecked(b);
}
void SurfaceMeshProcessing::pointPick()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
PointPickAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::POINTPICK);
}
void SurfaceMeshProcessing::vertexPick()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
VertexPickAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::VERTEXPICK);
}
void SurfaceMeshProcessing::edgePick()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
EdgePickAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::EDGEPICK);
}
void SurfaceMeshProcessing::facePick()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
FacePickAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::FACEPICK);
}
void SurfaceMeshProcessing::moveVertex()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
moveVertexAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::MOVE);
}
void SurfaceMeshProcessing::edge_collpase()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
EdgeCollpaseAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::EDGECOLLAPSE);
}
void SurfaceMeshProcessing::edge_flip()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
EdgeFlipAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::EDGEFLIP);
}
void SurfaceMeshProcessing::edge_split()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
EdgeSplitAction->setChecked(true);
viewer->setMouseMode(InteractiveViewerWidget::EDGESPLIT);
}
void SurfaceMeshProcessing::setAllMouseActionChecked(bool b)
{
PointPickAction->setChecked(b);
VertexPickAction->setChecked(b);
FacePickAction->setChecked(b);
EdgePickAction->setChecked(b);
moveVertexAction->setChecked(b);
EditUndoAction->setChecked(b);
EditRedoAction->setChecked(b);
EdgeCollpaseAction->setChecked(b);
EdgeSplitAction->setChecked(b);
EdgeFlipAction->setChecked(b);
}
void SurfaceMeshProcessing::setMouseMode_slot(int mm)
{
if(mm == InteractiveViewerWidget::TRANS)
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
switch(latestDrawMode)
{
case InteractiveViewerWidget::WIRE_FRAME:
wireFrameAction->setChecked(true);
break;
case InteractiveViewerWidget::HIDDEN_LINES:
hiddenLinesAction->setChecked(true);
break;
case InteractiveViewerWidget::SOLID_FLAT:
solidFlatAction->setChecked(true);
break;
case InteractiveViewerWidget::FLAT_POINTS:
flatPointsAction->setChecked(true);
break;
case InteractiveViewerWidget::SOLID_SMOOTH:
solidSmoothAction->setChecked(true);
break;
case InteractiveViewerWidget::POINT_SET:
pointSetAction->setChecked(true);
break;
case InteractiveViewerWidget::CURVATURE:
curvatureAction->setChecked(true);
break;
}
}
else
{
setAllViewActionChecked(false);
}
}
void SurfaceMeshProcessing::setDrawMode_slot(int dm)
{
setAllMouseActionChecked(false);
latestDrawMode = dm;
}
void SurfaceMeshProcessing::open_mesh_from_main(char* filename)
{
viewer->openMesh_fromMain(filename);
}
void SurfaceMeshProcessing::edit_undo()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
EditUndoAction->setChecked(true);
viewer->setDrawMode(InteractiveViewerWidget::FLAT_POINTS);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
viewer->edit_undo();
}
void SurfaceMeshProcessing::set_edit_undo_enable(bool b)
{
EditUndoAction->setEnabled(b);
}
void SurfaceMeshProcessing::edit_redo()
{
setAllViewActionChecked(false);
setAllMouseActionChecked(false);
EditRedoAction->setChecked(true);
viewer->setDrawMode(InteractiveViewerWidget::FLAT_POINTS);
viewer->setMouseMode(InteractiveViewerWidget::TRANS);
viewer->edit_redo();
}
void SurfaceMeshProcessing::set_edit_redo_enable(bool b)
{
EditRedoAction->setEnabled(b);
}
void SurfaceMeshProcessing::aux_inverse_mesh_connectivity()
{
viewer->aux_inverse_mesh_connectivity();
}
void SurfaceMeshProcessing::aux_scale_mesh_BBox()
{
bool value_Ok = false;
double val = QInputDialog::getDouble(this, "Scale Mesh","Desired Max Length of XYZ", 1.0, 1e-6, 1e6,1,&value_Ok);
if(value_Ok)
{
viewer->aux_scale_mesh_using_BBox(val);
}
};
void SurfaceMeshProcessing::aux_split_quad_mesh()
{
viewer->aux_split_quad_mesh();
}
void SurfaceMeshProcessing::aux_transform_mesh()
{
aux_transform_mesh_dialog* d = new aux_transform_mesh_dialog();
int r = d->exec();
if(r == QDialog::Accepted)
{
std::vector<double> tm; d->get_transform_matrix(tm);
viewer->transform_mesh(tm);
}
else if(r == QDialog::Rejected)
{
}
delete d;
}
void SurfaceMeshProcessing::aux_find_vertex_by_index()
{
bool value_Ok = false;
int id = QInputDialog::getInt(this, "Find Vertex","Vertex ID", 0 , 0, 1e30, 1,&value_Ok);
if(value_Ok)
{
viewer->aux_find_vertex_by_id(id);
}
}
void SurfaceMeshProcessing::aux_find_face_by_index()
{
bool value_Ok = false;
int id = QInputDialog::getInt(this, "Find Face","Face ID", 0 , 0, 1e30, 1,&value_Ok);
if(value_Ok)
{
viewer->aux_find_face_by_id(id);
}
}
void SurfaceMeshProcessing::aux_find_edge_by_index()
{
bool value_Ok = false;
int id = QInputDialog::getInt(this, "Find Edge","Edge ID", 0 , 0, 1e30, 1,&value_Ok);
if(value_Ok)
{
viewer->aux_find_edge_by_id(id);
}
}
void SurfaceMeshProcessing::aux_find_vertex_by_valance()
{
bool value_Ok = false;
int valance = QInputDialog::getInt(this, "Find Vertex","Vertex Valance", 0 , 0, 1e30, 1,&value_Ok);
if(value_Ok)
{
viewer->aux_find_vertex_by_valance(valance);
}
}
void SurfaceMeshProcessing::aux_delete_vertex_valence_four()
{
viewer->aux_delete_vertex_valence_four();
}
void SurfaceMeshProcessing::aux_delete_vertex_valence_three()
{
viewer->aux_delete_vertex_valence_three();
}
void SurfaceMeshProcessing::aux_split_vertex_valence_eight()
{
viewer->aux_split_vertex_valence_eight();
}
void SurfaceMeshProcessing::test()
{
viewer->test();
}
| 34.509601
| 114
| 0.782049
|
c2f3c0d7deb99d43837f7471ac7747ef7ba9fc6a
| 8,565
|
kt
|
Kotlin
|
SpringBootCommonBaseFrameLibraryFromLorenWang/src/javabase/lorenwang/common_base_frame/kotlinExtend/RequestExtend.kt
|
Seachal/LorenWangCustomTools
|
7690a5b15ad84faa88856a57dba9145fcea0126b
|
[
"Apache-2.0"
] | 5
|
2019-06-13T11:47:48.000Z
|
2021-09-09T03:56:13.000Z
|
SpringBootCommonBaseFrameLibraryFromLorenWang/src/javabase/lorenwang/common_base_frame/kotlinExtend/RequestExtend.kt
|
Seachal/LorenWangCustomTools
|
7690a5b15ad84faa88856a57dba9145fcea0126b
|
[
"Apache-2.0"
] | null | null | null |
SpringBootCommonBaseFrameLibraryFromLorenWang/src/javabase/lorenwang/common_base_frame/kotlinExtend/RequestExtend.kt
|
Seachal/LorenWangCustomTools
|
7690a5b15ad84faa88856a57dba9145fcea0126b
|
[
"Apache-2.0"
] | 1
|
2021-04-13T03:45:58.000Z
|
2021-04-13T03:45:58.000Z
|
package javabase.lorenwang.common_base_frame.kotlinExtend
import javabase.lorenwang.common_base_frame.SbcbflwCommon
import javabase.lorenwang.common_base_frame.controller.REQUEST_SET_USER_INFO_KEY
import javabase.lorenwang.common_base_frame.controller.SbcbflwBaseController
import javabase.lorenwang.common_base_frame.controller.SbcbflwBaseHttpServletRequestWrapper
import javabase.lorenwang.common_base_frame.database.repository.SbcbflwUserInfoRepository
import javabase.lorenwang.common_base_frame.database.repository.SbcbflwUserPermissionRepository
import javabase.lorenwang.common_base_frame.database.table.SbcbflwBaseUserInfoTb
import javabase.lorenwang.common_base_frame.database.table.SbcbflwBaseUserPermissionTb
import javabase.lorenwang.common_base_frame.database.table.SbcbflwBaseUserRoleTb
import javabase.lorenwang.common_base_frame.service.SbcbflwUserPermissionService
import javabase.lorenwang.common_base_frame.utils.SbcbfBaseAllUtils
import kotlinbase.lorenwang.tools.extend.kttlwEmptyCheck
import kotlinbase.lorenwang.tools.extend.kttlwFormatConversion
import kotlinbase.lorenwang.tools.extend.kttlwGetNotEmptyData
import kotlinbase.lorenwang.tools.extend.kttlwHaveEmptyCheck
/**
* 功能作用:接口请求处理扩展
* 创建时间:2020-11-21 10:49 下午
* 创建人:王亮(Loren)
* 思路:
* 方法:
* 注意:
* 修改人:
* 修改时间:
* 备注:
*
* @author 王亮(Loren)
*/
/**
* 接口检测并操作扩展
* @param emptyCheckArray 空数据检测
* @param baseController 基础接口控制器
* @param optionsFun 验证通过操作调用函数
*/
inline fun <PT, P : SbcbflwBaseUserPermissionTb<ROLE>, ROLE : SbcbflwBaseUserRoleTb<P>, reified U : SbcbflwBaseUserInfoTb<P, ROLE>, R : SbcbflwBaseHttpServletRequestWrapper, BC : SbcbflwBaseController<R>> sbcbflwControllerCheckAndOptions(
emptyCheckArray: Array<*>, checkPermissionArray: Array<PT>, request: R, baseController: BC, noinline notLoginFun: (() -> Any)? = null,
noinline notPermissionFun: ((userInfoTb: U) -> Any)? = null, noinline optionsFun: (() -> Any?)? = null): String {
return kttlwHaveEmptyCheck({
baseController.responseErrorForParams(request)
}, {
//检测用户是否登录
var result = sbcbflwCheckUserLoginStatus<P, ROLE, U, R, BC>(request, baseController, notLoginFun)
if (result is U) {
//用户已登录,检测用户权限
result = sbcbflwCheckPermissions(request, result, checkPermissionArray, baseController, notPermissionFun)
if (result is U && optionsFun != null) {
//有权限,执行指定操作
baseController.responseData(request, optionsFun())
} else {
baseController.responseData(request, result)
}
} else {
baseController.responseData(request, result)
}
}, emptyCheckArray)
}
/**
* 接口检测并操作扩展
* @param emptyCheckArray 空数据检测
* @param baseController 基础接口控制器
* @param optionsFun 验证通过操作调用函数
*/
fun <R : SbcbflwBaseHttpServletRequestWrapper, BC : SbcbflwBaseController<R>> sbcbflwControllerCheckAndOptions(request: R, emptyCheckArray: Array<*>,
baseController: BC, optionsFun: (() -> Any?)): String {
return kttlwHaveEmptyCheck({
baseController.responseErrorForParams(request)
}, {
baseController.responseData(request, optionsFun())
}, emptyCheckArray)
}
/**
* 检测用户登录状态
* @param request 请求request
* @param baseController 基础controller
* @param notLoginFun 未登陆执行操作
* @return 检测通过返回用户信息,否则返回异常信息或其他函数信息
*/
inline fun <P : SbcbflwBaseUserPermissionTb<ROLE>, ROLE : SbcbflwBaseUserRoleTb<P>, reified U : SbcbflwBaseUserInfoTb<P, ROLE>, R : SbcbflwBaseHttpServletRequestWrapper, BC : SbcbflwBaseController<R>> sbcbflwCheckUserLoginStatus(
request: R, baseController: BC, noinline notLoginFun: (() -> Any?)? = null): Any? {
//从request中获取token信息
val tokenByReqHeader = SbcbflwCommon.instance.userService?.getAccessTokenByReqHeader(request)
//从request中获取用户信息,该信息是在filter中拦截并添加到attribute中的
val userInfo = request.getAttribute(REQUEST_SET_USER_INFO_KEY).kttlwEmptyCheck({
null
}, {
it
})
return if (userInfo == null || userInfo !is U || tokenByReqHeader == null) {
SbcbfBaseAllUtils.logUtils.logOptions(SbcbflwBaseController::class.java, "用户登录信息为空,登录状态验证未通过")
try {
notLoginFun.kttlwEmptyCheck({
baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}, {
it()
})
} catch (ignore: Exception) {
baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}
} else {
SbcbfBaseAllUtils.logUtils.logD(SbcbflwBaseController::class.java, "获取到用户信息,开始信息正确性验证")
return tokenByReqHeader.let {
//解密token信息
val decryptToken = SbcbflwCommon.instance.userService?.decryptAccessToken(it)
decryptToken.kttlwEmptyCheck({
SbcbfBaseAllUtils.logUtils.logOptions(SbcbflwBaseController::class.java, "用户信息无法解密,登录状态验证未通过")
return baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}, { deToken ->
//判断token是否是正常的
val tokenEffective = SbcbflwCommon.instance.userService?.checkAccessTokenEffective(deToken)
if (tokenEffective?.statusResult.kttlwGetNotEmptyData(false)) {
//token是正常的,开始验证用户信息,首先获取用户id
SbcbflwCommon.instance.userService?.getUserIdByAccessToken(deToken)!!.let { tokenUserId ->
//因为token已经验证过了,所以id是可以正常取值的
//接下来进行和用户信息的比较
val status = userInfo.userId.compareTo(tokenUserId) == 0
SbcbfBaseAllUtils.logUtils.logOptions(SbcbflwBaseController::class.java, "用户${userInfo.userId}验证结果:${status}")
if (status) {
userInfo
} else {
try {
notLoginFun.kttlwEmptyCheck({
baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}, {
it()
})
} catch (ignore: Exception) {
baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}
}
}
} else {
try {
notLoginFun.kttlwEmptyCheck({
baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}, {
it()
})
} catch (ignore: Exception) {
baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}
}
})
}
}
}
/**
* 检测用户权限
* @param request 请求request
* @param userInfo 用户信息
* @param permissionCheckTypes 要检测的权限类型
* @param baseController 基础controller
* @param notPermissionFun 无权限操作
* @return 检测通过返回用户信息,否则返回异常信息或其他函数信息
*/
fun <P : SbcbflwBaseUserPermissionTb<ROLE>, ROLE : SbcbflwBaseUserRoleTb<P>, U : SbcbflwBaseUserInfoTb<P, ROLE>, PT, R : SbcbflwBaseHttpServletRequestWrapper, PR : SbcbflwUserPermissionRepository<P, ROLE>, BC : SbcbflwBaseController<R>> sbcbflwCheckPermissions(
request: R, userInfo: U, permissionCheckTypes: Array<PT>?, baseController: BC, notPermissionFun: ((userInfoTb: U) -> Any)? = null): Any {
SbcbfBaseAllUtils.logUtils.logOptions(SbcbflwUserInfoRepository::class.java, "用户${userInfo.userId}开始进行权限检测")
for (permission in permissionCheckTypes!!) {
if (!SbcbflwCommon.instance.userRolePermission?.kttlwFormatConversion<SbcbflwUserPermissionService<R, P, ROLE, U, PT, PR>>()
?.checkUserHavePermission(request, userInfo, permission)?.statusResult.kttlwGetNotEmptyData(true)) {
SbcbfBaseAllUtils.logUtils.logI(SbcbflwUserInfoRepository::class.java, "权限检测,用户${userInfo.userId}没有相关权限")
return try {
notPermissionFun.kttlwEmptyCheck({
baseController.responseErrorUserLoginEmptyOrTokenNoneffective(request)
}, {
it(userInfo)
})
} catch (ignore: Exception) {
baseController.responseErrorNotPermission(request)
}
}
}
SbcbfBaseAllUtils.logUtils.logOptions(SbcbflwUserInfoRepository::class.java, "权限检测,用户${userInfo.userId}权限检测通过")
return userInfo
}
| 46.803279
| 261
| 0.66258
|
0f96b366169f0480fe5130a9fd3ab87278f18bda
| 1,004
|
dart
|
Dart
|
lib/text_slave.dart
|
hamatoma/text_butler
|
95cd521cc3a3562e112808d5e888ffea8b84de45
|
[
"CC0-1.0"
] | 1
|
2021-12-30T10:47:33.000Z
|
2021-12-30T10:47:33.000Z
|
lib/text_slave.dart
|
hamatoma/text_butler
|
95cd521cc3a3562e112808d5e888ffea8b84de45
|
[
"CC0-1.0"
] | null | null | null |
lib/text_slave.dart
|
hamatoma/text_butler
|
95cd521cc3a3562e112808d5e888ffea8b84de45
|
[
"CC0-1.0"
] | null | null | null |
import 'text_butler_io.dart';
import 'dart:io';
void main(List<String> args) {
List<String>? script;
if (args.isEmpty) {
script = [];
String? line;
while ((line = stdin.readLineSync()) != null) {
script.add(line!);
}
} else if (args[0] == '-h' || args[0] == '--help') {
print('''Usage:
text_slave
Reads the script from stdin and executes that.
text_slave --help
Print this message.
text_slave <script_file>
Reads the script from <script_file> and executes that.
''');
} else {
final filename = args[0];
final file = File(filename);
if (!file.existsSync()) {
print('+++ script file not found: $filename');
} else {
script = file.readAsLinesSync();
}
}
if (script != null) {
final textButler = TextButlerIO();
textButler.buffers['script'] = script.join('\n');
textButler.execute('execute input=script');
final output = textButler.getBuffer('output');
if (output.isNotEmpty) {
print(output);
}
}
}
| 25.1
| 56
| 0.609562
|
e25168627588b6af6800b050544e598adb1f8a9e
| 901
|
py
|
Python
|
fang/fang/pipelines.py
|
XZH950926/meizitu
|
536578fd9bc6fdcfecf8ff6cfe700c586eb3ef9f
|
[
"Apache-2.0"
] | null | null | null |
fang/fang/pipelines.py
|
XZH950926/meizitu
|
536578fd9bc6fdcfecf8ff6cfe700c586eb3ef9f
|
[
"Apache-2.0"
] | null | null | null |
fang/fang/pipelines.py
|
XZH950926/meizitu
|
536578fd9bc6fdcfecf8ff6cfe700c586eb3ef9f
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import json
Basedir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class FangPipeline(object):
def process_item(self, item, spider):
province=item["province"]
city = item["city"]
province_path=os.path.join(Basedir,province)
if not os.path.exists(province):
os.mkdir(province_path)
city_path=os.path.join(province_path,city)
if not os.path.exists(city_path):
os.mkdir(city_path)
newHomePath=os.path.join(city_path,"sf.json")
if not os.path.exists(newHomePath):
with open(newHomePath,"a+") as f:
f.write(json.dumps(dict(item),ensure_ascii=False))
return item
| 36.04
| 67
| 0.659267
|
95a07391757321f5135c94bad685345744e26f33
| 4,459
|
lua
|
Lua
|
Data/3_0/StatDescriptions/banner_aura_skill_stat_descriptions.lua
|
M-Schiller/PathOfBuilding
|
ddfb8ab996867a3c8bb3fcd337d59f80f36181f6
|
[
"MIT"
] | 2
|
2019-03-06T09:24:23.000Z
|
2019-03-18T05:58:03.000Z
|
Data/3_0/StatDescriptions/banner_aura_skill_stat_descriptions.lua
|
M-Schiller/PathOfBuilding
|
ddfb8ab996867a3c8bb3fcd337d59f80f36181f6
|
[
"MIT"
] | null | null | null |
Data/3_0/StatDescriptions/banner_aura_skill_stat_descriptions.lua
|
M-Schiller/PathOfBuilding
|
ddfb8ab996867a3c8bb3fcd337d59f80f36181f6
|
[
"MIT"
] | null | null | null |
return {[1]={["stats"]={[1]="buff_effect_duration"},["name"]="buff_duration",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},["text"]="Banner lasts %1% seconds after being placed",["limit"]={[1]={[1]=1,[2]="#"}}}}}},[2]={["stats"]={[1]="banner_add_stage_on_impale"},["name"]="banner_add_stage_on_impale",["lang"]={["English"]={[1]={["limit"]={[1]={[1]="#",[2]="#"}},["text"]="Gain 1 Stage when you Impale an Enemy while carrying the Banner, up to 5 per second"}}}},[3]={["stats"]={[1]="banner_add_stage_on_kill"},["name"]="banner_add_stage_on_kill",["lang"]={["English"]={[1]={["limit"]={[1]={[1]="#",[2]="#"}},["text"]="Gain 1 Stage when you Kill an Enemy while carrying the Banner"}}}},[4]={["stats"]={[1]="banner_additional_base_duration_per_stage_ms"},["name"]="banner_stage_duration",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds",["v"]=1},["text"]="%1$+d second to Base Placed Banner Duration per Stage",["limit"]={[1]={[1]=1000,[2]=1000}}},[2]={[1]={["k"]="milliseconds_to_seconds",["v"]=1},["text"]="%1$+d seconds to Base Placed Banner Duration per Stage",["limit"]={[1]={[1]="#",[2]="#"}}}}}},[5]={["stats"]={[1]="banner_area_of_effect_+%_per_stage"},["name"]="banner_stage_aoe",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="When placed, %1%%% increased Area of Effect per Stage"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="When placed, %1%%% reduced Area of Effect per Stage",["limit"]={[1]={[1]="#",[2]=-1}}}}}},[6]={["stats"]={[1]="banner_buff_effect_+%_per_stage"},["name"]="banner_stage_aura_effect",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="When placed, %1%%% increased Aura effect per Stage"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="When placed, %1%%% reduced Aura effect per Stage",["limit"]={[1]={[1]="#",[2]=-1}}}}}},[7]={["stats"]={[1]="base_skill_effect_duration"},["name"]="base_duration_identifier",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},["text"]="Base Duration of %1% seconds after being Placed",["limit"]={[1]={[1]="#",[2]="#"}}}}}},[8]={["stats"]={[1]="bloodstained_banner_adrenaline_duration_per_stage_ms"},["name"]="war_banner_adrenaline",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextAdrenaline"},["text"]="Gain Adrenaline for %1% second per Stage on Placing the Banner",["limit"]={[1]={[1]=1000,[2]=1000}}},[2]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextAdrenaline"},["text"]="Gain Adrenaline for %1% seconds per Stage on Placing the Banner",["limit"]={[1]={[1]="#",[2]="#"}}}}}},["puresteel_banner_accuracy_rating_+%_final"]=9,["puresteel_banner_fortify_effect_+%_per_stage"]=11,["puresteel_banner_fortify_duration_per_stage_ms"]=10,[11]={["stats"]={[1]="puresteel_banner_fortify_effect_+%_per_stage"},["name"]="dread_banner_fortify_effect",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="%1%%% increased Fortify effect per Stage"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="%1%%% reduced Fortify effect per Stage",["limit"]={[1]={[1]="#",[2]=-1}}}}}},["banner_add_stage_on_kill"]=3,["base_skill_effect_duration"]=7,[9]={["stats"]={[1]="puresteel_banner_accuracy_rating_+%_final"},["name"]="dread_banner_accuracy_final",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="Nearby Enemies have %1%%% more Accuracy Rating"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="Nearby Enemies have %1%%% less Accuracy Rating",["limit"]={[1]={[1]="#",[2]=-1}}}}}},[10]={["stats"]={[1]="puresteel_banner_fortify_duration_per_stage_ms"},["name"]="dread_banner_fortify",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextFortify"},["text"]="Gain Fortify for %1% second per Stage on Placing the Banner",["limit"]={[1]={[1]=1000,[2]=1000}}},[2]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextFortify"},["text"]="Gain Fortify for %1% seconds per Stage on Placing the Banner",["limit"]={[1]={[1]="#",[2]="#"}}}}}},["banner_additional_base_duration_per_stage_ms"]=4,["bloodstained_banner_adrenaline_duration_per_stage_ms"]=8,["banner_buff_effect_+%_per_stage"]=6,["buff_effect_duration"]=1,["parent"]="aura_skill_stat_descriptions",["banner_add_stage_on_impale"]=2,["banner_area_of_effect_+%_per_stage"]=5}
| 4,459
| 4,459
| 0.616954
|
b145641bcccda8aefa0023aa5dff533564ce0fa1
| 4,956
|
py
|
Python
|
mitorch/datasets/image_dataset.py
|
shonohs/mitorch
|
567a8390cc7a600280c51bc4e2a4e1c93fefc801
|
[
"MIT"
] | null | null | null |
mitorch/datasets/image_dataset.py
|
shonohs/mitorch
|
567a8390cc7a600280c51bc4e2a4e1c93fefc801
|
[
"MIT"
] | 1
|
2020-06-12T05:56:54.000Z
|
2020-06-12T05:56:54.000Z
|
mitorch/datasets/image_dataset.py
|
shonohs/mitorch
|
567a8390cc7a600280c51bc4e2a4e1c93fefc801
|
[
"MIT"
] | null | null | null |
import os
import pathlib
import zipfile
import PIL.Image
class ImageDataset:
def __init__(self, filename, transform):
filepath = pathlib.Path(filename)
self.transform = transform
self.images = []
self.base_dir = filepath.parent
self.reader = FileReader(self.base_dir)
with open(filename) as f:
for line in f:
image_filepath, target = line.strip().split()
image_filepath = image_filepath.strip()
target = self._load_target(target)
self.images.append((image_filepath, target))
max_label = self._get_max_label()
self._labels = self._load_labels(max_label)
def _load_labels(self, max_label):
"""Load if there is labels.txt. If not, generate dummy labels"""
labels_filepath = self.base_dir / 'labels.txt'
if labels_filepath.exists():
with open(labels_filepath) as f:
labels = [line.strip() for line in f.readlines()]
assert len(labels) > max_label
return labels
else:
return [f'label_{i}' for i in range(max_label + 1)]
@property
def labels(self):
return self._labels
def __len__(self):
return len(self.images)
def __getitem__(self, index):
image_filepath, target = self.images[index]
with self.reader.open(image_filepath, 'rb') as f:
image = PIL.Image.open(f)
image = image.convert('RGB') # Some image might have 1-channel. Also this method makes sure that the image is loaded.
return self.transform(image, target)
def _load_target(self, target):
raise NotImplementedError
def _get_max_label(self):
raise NotImplementedError
@classmethod
def from_file(cls, filename, transform):
dataset_type = cls._detect_type(filename)
if dataset_type == 'multiclass_classification':
return MulticlassClassificationDataset(filename, transform)
elif dataset_type == 'multilabel_classification':
return MultilabelClassificationDataset(filename, transform)
elif dataset_type == 'object_detection':
return ObjectDetectionDataset(filename, transform)
else:
raise NotImplementedError(f"Non supported dataset type: {dataset_type}")
@staticmethod
def _detect_type(filename):
with open(filename) as f:
for line in f:
_, labels = line.split()
if '@' in labels or '.' in labels:
return 'object_detection'
if ',' in labels:
return 'multilabel_classification'
return 'multiclass_classification'
class ThreadSafeZipFile(zipfile.ZipFile):
def __init__(self, zip_filepath):
self.zip_filepath = zip_filepath
self.cache = {}
def open(self, filepath):
if os.getpid() not in self.cache:
self.cache[os.getpid()] = zipfile.ZipFile(self.zip_filepath)
return self.cache[os.getpid()].open(filepath, 'r')
def close(self):
for zip_file in self.cache.values():
zip_file.close()
class FileReader:
def __init__(self, base_dir):
self.base_dir = base_dir
self.zipfile_cache = {}
def open(self, filepath, mode='r'):
if '@' in filepath:
zip_filepath, filepath = filepath.split('@')
if zip_filepath not in self.zipfile_cache:
self.zipfile_cache[zip_filepath] = ThreadSafeZipFile(self.base_dir / zip_filepath)
return self.zipfile_cache[zip_filepath].open(filepath)
else:
return open(self.base_dir / filepath, mode)
def __getstate__(self):
return {'base_dir': self.base_dir}
def __setstate__(self, state):
self.base_dir = state['base_dir']
self.zipfile_cache = {}
class MulticlassClassificationDataset(ImageDataset):
def _get_max_label(self):
return max(i[1] for i in self.images)
@staticmethod
def _load_target(target):
return int(target)
class MultilabelClassificationDataset(ImageDataset):
def _get_max_label(self):
return max(j for i in self.images for j in i[1])
@staticmethod
def _load_target(target):
return [int(t) for t in target.split(',')]
class ObjectDetectionDataset(ImageDataset):
def _get_max_label(self):
return max(j[0] for i in self.images for j in i[1])
def _load_target(self, targetpath):
with self.reader.open(targetpath) as f:
# label, x_min, y_min, x_max, y_max. Those are not normalized.
targets = [line.strip().split() for line in f]
targets = [(int(t[0]), int(float(t[1])), int(float(t[2])), int(float(t[3])), int(float(t[4]))) for t in targets]
return [t for t in targets if t[1] < t[3] and t[2] < t[4]] # Remove invalid bounding boxes.
| 34.17931
| 130
| 0.623688
|
6369cfd3a8ce86315e19b1715f578dce7ef3d942
| 22,209
|
sql
|
SQL
|
generators/app/templates/templates/template.sql
|
DieSchittigs/yeoman-contao
|
1f40b530cd30444d89c6a96e24a23861457cb4d4
|
[
"0BSD"
] | 6
|
2018-03-19T15:06:38.000Z
|
2019-09-18T06:04:43.000Z
|
generators/app/templates/templates/template.sql
|
DieSchittigs/yeoman-contao
|
1f40b530cd30444d89c6a96e24a23861457cb4d4
|
[
"0BSD"
] | 7
|
2018-01-22T13:29:21.000Z
|
2021-05-06T21:08:39.000Z
|
generators/app/templates/templates/template.sql
|
DieSchittigs/yeoman-contao
|
1f40b530cd30444d89c6a96e24a23861457cb4d4
|
[
"0BSD"
] | 2
|
2018-03-27T13:35:39.000Z
|
2018-05-16T09:25:20.000Z
|
INSERT INTO `tl_article` (`id`, `pid`, `sorting`, `tstamp`, `title`, `alias`, `author`, `inColumn`, `keywords`, `showTeaser`, `teaserCssID`, `teaser`, `printable`, `customTpl`, `protected`, `groups`, `guests`, `cssID`, `published`, `start`, `stop`) VALUES (2, 2, 128, 1526669244, 'Welcome', 'index', 1, 'main', NULL, '', '', NULL, '', '', '', NULL, '', '', '1', '', ''), (3, 3, 128, 1526669270, 'Content Elements', 'content-elements', 1, 'main', NULL, '', '', NULL, '', '', '', NULL, '', '', '1', '', '');
INSERT INTO `tl_content` (`id`, `pid`, `ptable`, `sorting`, `tstamp`, `type`, `headline`, `text`, `addImage`, `overwriteMeta`, `singleSRC`, `alt`, `imageTitle`, `size`, `imagemargin`, `imageUrl`, `fullsize`, `caption`, `floating`, `html`, `listtype`, `listitems`, `tableitems`, `summary`, `thead`, `tfoot`, `tleft`, `sortable`, `sortIndex`, `sortOrder`, `mooHeadline`, `mooStyle`, `mooClasses`, `highlight`, `code`, `url`, `target`, `titleText`, `linkTitle`, `embed`, `rel`, `useImage`, `multiSRC`, `orderSRC`, `useHomeDir`, `perRow`, `perPage`, `numberOfItems`, `sortBy`, `metaIgnore`, `galleryTpl`, `customTpl`, `playerSRC`, `youtube`, `vimeo`, `posterSRC`, `playerSize`, `autoplay`, `sliderDelay`, `sliderSpeed`, `sliderStartSlide`, `sliderContinuous`, `cteAlias`, `articleAlias`, `article`, `form`, `module`, `protected`, `groups`, `guests`, `cssID`, `invisible`, `start`, `stop`) VALUES (1, 3, 'tl_article', 128, 1526669576, 'headline', 'a:2:{s:4:\"unit\";s:2:\"h1\";s:5:\"value\";s:8:\"Headline\";}', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (2, 3, 'tl_article', 256, 1526669696, 'text', 'a:2:{s:4:\"unit\";s:2:\"h2\";s:5:\"value\";s:13:\"Text Headline\";}', '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur eget leo at sodales. Suspendisse vel odio elementum, efficitur tortor sit amet, ullamcorper magna. Class aptent taciti <a href=\"#\">sociosqu</a> ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce imperdiet tortor sem, et laoreet ipsum dignissim id. Donec elit erat, ullamcorper at euismod ac, commodo a nibh.</p>\n<ul>\n<li>Quisque et erat finibus</li>\n<li>ullamcorper neque sit amet</li>\n<li>finibus elit. Quisque pulvinar dolor</li>\n</ul>\n<p>libero, a suscipit leo egestas vitae. In vehicula mauris nec ligula egestas, nec malesuada est dignissim. Proin ante turpis, mollis sed est at, rhoncus euismod felis. Class aptent taciti sociosqu ad litora torquent per</p>\n<ol>\n<li>conubia</li>\n<li>nostra</li>\n<li>per</li>\n</ol>\n<p>inceptos himenaeos. Donec finibus elementum mi, sed feugiat quam finibus quis. Morbi sit amet odio quis diam ultrices eleifend ac vel libero. Nam sollicitudin ante quis viverra consectetur. In id congue ipsum. Etiam ultrices lorem ut nunc condimentum, vel ornare ex aliquet. Morbi nec erat sapien.</p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (3, 3, 'tl_article', 384, 1526669748, 'list', 'a:2:{s:4:\"unit\";s:2:\"h2\";s:5:\"value\";s:4:\"List\";}', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, 'ordered', 'a:3:{i:0;s:26:\"Lorem ipsum dolor sit amet\";i:1;s:26:\"Lorem ipsum dolor sit amet\";i:2;s:26:\"Lorem ipsum dolor sit amet\";}', NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (4, 3, 'tl_article', 512, 1526669800, 'table', 'a:2:{s:4:\"unit\";s:2:\"h2\";s:5:\"value\";s:5:\"Table\";}', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, 'a:4:{i:0;a:4:{i:0;s:26:\"Lorem ipsum dolor sit amet\";i:1;s:26:\"Lorem ipsum dolor sit amet\";i:2;s:26:\"Lorem ipsum dolor sit amet\";i:3;s:26:\"Lorem ipsum dolor sit amet\";}i:1;a:4:{i:0;s:26:\"Lorem ipsum dolor sit amet\";i:1;s:26:\"Lorem ipsum dolor sit amet\";i:2;s:26:\"Lorem ipsum dolor sit amet\";i:3;s:26:\"Lorem ipsum dolor sit amet\";}i:2;a:4:{i:0;s:26:\"Lorem ipsum dolor sit amet\";i:1;s:26:\"Lorem ipsum dolor sit amet\";i:2;s:26:\"Lorem ipsum dolor sit amet\";i:3;s:26:\"Lorem ipsum dolor sit amet\";}i:3;a:4:{i:0;s:26:\"Lorem ipsum dolor sit amet\";i:1;s:26:\"Lorem ipsum dolor sit amet\";i:2;s:26:\"Lorem ipsum dolor sit amet\";i:3;s:26:\"Lorem ipsum dolor sit amet\";}}', '', '1', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (5, 3, 'tl_article', 640, 1526669896, 'code', 'a:2:{s:4:\"unit\";s:2:\"h2\";s:5:\"value\";s:4:\"Code\";}', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', 'PHP', '<?php\n $a = 1.23456789;\n $b = 1.23456780;\n $epsilon = 0.00001;\n\n if(abs($a-$b) < $epsilon) {\n echo \"true\";\n }\n?>', '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (8, 3, 'tl_article', 896, 1526670103, 'toplink', '', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', 'Top-Link', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (7, 3, 'tl_article', 768, 1526670084, 'hyperlink', 'a:2:{s:4:\"unit\";s:2:\"h2\";s:5:\"value\";s:9:\"Hyperlink\";}', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '#', '', '', 'Hyperlink', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (9, 3, 'tl_article', 1024, 1526672039, 'sliderStart', 'a:2:{s:4:\"unit\";s:2:\"h2\";s:5:\"value\";s:14:\"Content slider\";}', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', 5000, 300, 1, '1', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (10, 3, 'tl_article', 1152, 1526670218, 'sliderStop', '', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', '', '', '', ''), (11, 3, 'tl_article', 1088, 1526670247, 'text', 'a:2:{s:4:\"unit\";s:2:\"h3\";s:5:\"value\";s:7:\"Slide 1\";}', '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur eget leo at sodales. Suspendisse vel odio elementum, efficitur tortor sit amet, ullamcorper magna.</p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (12, 3, 'tl_article', 1120, 1526670260, 'text', 'a:2:{s:4:\"unit\";s:2:\"h3\";s:5:\"value\";s:7:\"Slide 2\";}', '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur eget leo at sodales. Suspendisse vel odio elementum, efficitur tortor sit amet, ullamcorper magna.</p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (13, 3, 'tl_article', 1136, 1526670270, 'text', 'a:2:{s:4:\"unit\";s:2:\"h3\";s:5:\"value\";s:7:\"Slide 3\";}', '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur eget leo at sodales. Suspendisse vel odio elementum, efficitur tortor sit amet, ullamcorper magna.</p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (14, 3, 'tl_article', 1280, 1526757277, 'headline', 'a:2:{s:4:\"unit\";s:2:\"h2\";s:5:\"value\";s:9:\"Accordion\";}', NULL, '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', 'Accordion', '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (15, 3, 'tl_article', 1408, 1526757258, 'accordionSingle', 'a:2:{s:4:\"unit\";s:2:\"h3\";s:5:\"value\";s:7:\"Topic 1\";}', '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin massa lectus, malesuada sed faucibus id, bibendum ut ligula. Praesent sodales, erat nec fermentum blandit, odio nibh feugiat tortor, ut feugiat ex nisl sed turpis. Quisque rhoncus laoreet ex, egestas efficitur enim. Nulla faucibus ipsum vel ligula porta mollis. Proin vitae est nec libero accumsan mattis.</p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', 'Topic 1', '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (19, 3, 'tl_article', 1664, 1526756971, 'accordionSingle', '', '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin massa lectus, malesuada sed faucibus id, bibendum ut ligula. Praesent sodales, erat nec fermentum blandit, odio nibh feugiat tortor, ut feugiat ex nisl sed turpis. Quisque rhoncus laoreet ex, egestas efficitur enim. Nulla faucibus ipsum vel ligula porta mollis. Proin vitae est nec libero accumsan mattis.</p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', 'Topic 3', '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (17, 3, 'tl_article', 1536, 1526756954, 'accordionSingle', '', '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin massa lectus, malesuada sed faucibus id, bibendum ut ligula. Praesent sodales, erat nec fermentum blandit, odio nibh feugiat tortor, ut feugiat ex nisl sed turpis. Quisque rhoncus laoreet ex, egestas efficitur enim. Nulla faucibus ipsum vel ligula porta mollis. Proin vitae est nec libero accumsan mattis.</p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', 'Topic 2', '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (21, 3, 'tl_article', 704, 1527582108, 'gallery', 'a:2:{s:4:\"unit\";s:2:\"h1\";s:5:\"value\";s:7:\"Galerie\";}', NULL, '', '', NULL, '', '', 'a:3:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:1:\"2\";}', 'a:5:{s:6:\"bottom\";s:0:\"\";s:4:\"left\";s:0:\"\";s:5:\"right\";s:0:\"\";s:3:\"top\";s:0:\"\";s:4:\"unit\";s:0:\"\";}', '', '1', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', 'a:1:{i:0;s:16:\"$���b�迣���݂\";}', 'a:1:{i:0;s:16:\"$���b�迣���݂\";}', '', 4, 0, 0, 'custom', '', 'gallery_default', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (22, 3, 'tl_article', 736, 1527582116, 'image', 'a:2:{s:4:\"unit\";s:2:\"h1\";s:5:\"value\";s:5:\"Image\";}', NULL, '', '', UNHEX('24A8B3CE62A911E8BFA398F2B3ECDD82'), '', '', 'a:3:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:1:\"1\";}', 'a:5:{s:6:\"bottom\";s:0:\"\";s:4:\"left\";s:0:\"\";s:5:\"right\";s:0:\"\";s:3:\"top\";s:0:\"\";s:4:\"unit\";s:0:\"\";}', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', ''), (23, 2, 'tl_article', 128, 1527538437, 'text', 'a:2:{s:4:\"unit\";s:2:\"h1\";s:5:\"value\";s:8:\"Welcome!\";}', '<p>Thank you for using Contao Generator!</p>\n<p>Visit us at <a href=\"https://github.com/DieSchittigs/yeoman-contao\">https://github.com/DieSchittigs/yeoman-contao</a> if you encountered problems, or just want to say hi.</p>\n<p>Bye,<br><a href=\"https://dieschittigs.de\">Die Schittigs</a></p>', '', '', NULL, '', '', '', '', '', '', '', 'above', NULL, '', NULL, NULL, '', '', '', '', '', 0, 'ascending', '', '', '', '', NULL, '', '', '', '', '', '', '', NULL, NULL, '', 4, 0, 0, '', '', '', '', NULL, '', '', NULL, '', '', 0, 300, 0, '', 0, 0, 0, 0, 0, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:0:\"\";}', '', '', '');
INSERT INTO `tl_files` (`id`, `pid`, `tstamp`, `uuid`, `type`, `path`, `extension`, `hash`, `found`, `name`, `importantPartX`, `importantPartY`, `importantPartWidth`, `importantPartHeight`, `meta`) VALUES (1, NULL, 1526668869, UNHEX('07E8B7125ACB11E8BFA398F2B3ECDD82'), 'folder', 'files/theme_<%= theme %>', '', 'db87a8aab8587f923721997b4ee0e93b', '1', 'theme_<%= theme %>', 0, 0, 0, 0, NULL), (2, NULL, 1527533928, UNHEX('24A8B3DA62A911E8BFA398F2B3ECDD82'), 'folder', 'files/deleteme', '', '7c6fe79cb030a7aa929f825f8c2110c2', '1', 'deleteme', 0, 0, 0, 0, 'a:1:{s:2:\"en\";a:4:{s:5:\"title\";s:0:\"\";s:3:\"alt\";s:0:\"\";s:4:\"link\";s:0:\"\";s:7:\"caption\";s:0:\"\";}}'), (3, UNHEX('24A8B3DA62A911E8BFA398F2B3ECDD82'), 1527534247, UNHEX('24A8B3CE62A911E8BFA398F2B3ECDD82'), 'file', 'files/deleteme/img.jpg', 'jpg', 'b88debfb02af95873dd3a1a078702a18', '1', 'img.jpg', 0, 0, 0, 0, 'a:1:{s:2:\"en\";a:4:{s:5:\"title\";s:39:\"https://unsplash.com/photos/xovRcLRpX20\";s:3:\"alt\";s:0:\"\";s:4:\"link\";s:0:\"\";s:7:\"caption\";s:69:\"Monumental La Défense, France by Pierre Châtel-Innocenti @ unsplash\";}}');
INSERT INTO `tl_image_size` (`id`, `pid`, `tstamp`, `name`, `cssClass`, `sizes`, `densities`, `width`, `height`, `resizeMode`, `zoom`) VALUES (1, 1, 1527582016, 'Header', '', '', '', 1920, 600, 'crop', 100), (2, 1, 1527582073, 'Square', '', '', '', 400, 400, 'crop', 100);
INSERT INTO `tl_image_size_item` (`id`, `pid`, `sorting`, `tstamp`, `media`, `sizes`, `densities`, `width`, `height`, `resizeMode`, `zoom`, `invisible`) VALUES (1, 1, 128, 1527582048, '(max-width: 600px)', '', '', 800, 400, 'crop', 100, ''), (2, 2, 128, 1527582083, '(max-width: 600px)', '', '', 800, 800, 'crop', 100, '');
INSERT INTO `tl_module` (`id`, `pid`, `tstamp`, `name`, `headline`, `type`, `levelOffset`, `showLevel`, `hardLimit`, `showProtected`, `defineRoot`, `rootPage`, `navigationTpl`, `customTpl`, `pages`, `orderPages`, `showHidden`, `customLabel`, `autologin`, `jumpTo`, `redirectBack`, `cols`, `editable`, `memberTpl`, `form`, `queryType`, `fuzzy`, `contextLength`, `totalLength`, `perPage`, `searchType`, `searchTpl`, `inColumn`, `skipFirst`, `loadFirst`, `size`, `transparent`, `flashvars`, `altContent`, `source`, `singleSRC`, `url`, `interactive`, `flashID`, `flashJS`, `imgSize`, `useCaption`, `fullsize`, `multiSRC`, `orderSRC`, `html`, `rss_cache`, `rss_feed`, `rss_template`, `numberOfItems`, `disableCaptcha`, `reg_groups`, `reg_allowLogin`, `reg_skipName`, `reg_close`, `reg_assignDir`, `reg_homeDir`, `reg_activate`, `reg_jumpTo`, `reg_text`, `reg_password`, `protected`, `groups`, `guests`, `cssID`, `list_table`, `list_fields`, `list_where`, `list_search`, `list_sort`, `list_info`, `list_info_where`, `list_layout`, `list_info_layout`) VALUES (1, 1, 1527535554, 'Main menu', 'a:2:{s:4:\"unit\";s:2:\"h1\";s:5:\"value\";s:0:\"\";}', 'navigation', 0, 0, '', '', '', 0, 'nav_default', '', NULL, NULL, '', '', '', 0, '', '2cl', NULL, '', 0, 'and', '', 48, 1000, 0, 'simple', '', 'main', 0, '', '', '', '', NULL, 'internal', NULL, '', '', '', NULL, '', '', '', NULL, NULL, NULL, 3600, NULL, 'rss_default', 3, '', NULL, '', '', '', '', NULL, '', 0, NULL, NULL, '', NULL, '', 'a:2:{i:0;s:0:\"\";i:1;s:4:\"main\";}', '', '', '', '', '', '', '', 'list_default', 'info_default'), (2, 1, 1527537690, 'Logo', '', 'html', 0, 0, '', '', '', 0, '', '', NULL, NULL, '', '', '', 0, '', '2cl', NULL, '', 0, 'and', '', 48, 1000, 0, 'simple', '', 'main', 0, '', '', '', '', NULL, 'internal', NULL, '', '', '', NULL, '', '', '', NULL, NULL, '<a href=\"/\" class=\"logo\"><img src=\"/icons_<%= theme %>/android-chrome-512x512.png\"></a>', 3600, NULL, 'rss_default', 3, '', NULL, '', '', '', '', NULL, '', 0, NULL, NULL, '', NULL, '', '', '', '', '', '', '', '', '', 'list_default', 'info_default');
INSERT INTO `tl_page` (`id`, `pid`, `sorting`, `tstamp`, `title`, `alias`, `type`, `pageTitle`, `language`, `robots`, `description`, `redirect`, `jumpTo`, `redirectBack`, `url`, `target`, `dns`, `staticFiles`, `staticPlugins`, `fallback`, `adminEmail`, `dateFormat`, `timeFormat`, `datimFormat`, `createSitemap`, `sitemapName`, `useSSL`, `autoforward`, `protected`, `groups`, `includeLayout`, `layout`, `mobileLayout`, `includeCache`, `cache`, `clientCache`, `includeChmod`, `cuser`, `cgroup`, `chmod`, `noSearch`, `cssClass`, `sitemap`, `hide`, `guests`, `tabindex`, `accesskey`, `published`, `start`, `stop`) VALUES (1, 0, 128, 1526669187, '<%= projectName %>', '<%= projectName %>', 'root', '', 'en', '', NULL, 'permanent', 0, '', '', '', '', '', '', '1', '', '', '', '', '', '', '', '', '', NULL, '1', 1, 0, '', 0, 0, '', 0, 0, 'a:9:{i:0;s:2:\"u1\";i:1;s:2:\"u2\";i:2;s:2:\"u3\";i:3;s:2:\"u4\";i:4;s:2:\"u5\";i:5;s:2:\"u6\";i:6;s:2:\"g4\";i:7;s:2:\"g5\";i:8;s:2:\"g6\";}', '', '', '', '', '', 0, '', '1', '', ''), (2, 1, 128, 1526669244, 'Welcome', 'index', 'regular', '', '', 'index,follow', NULL, 'permanent', 0, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', NULL, '', 0, 0, '', 0, 0, '', 0, 0, 'a:9:{i:0;s:2:\"u1\";i:1;s:2:\"u2\";i:2;s:2:\"u3\";i:3;s:2:\"u4\";i:4;s:2:\"u5\";i:5;s:2:\"u6\";i:6;s:2:\"g4\";i:7;s:2:\"g5\";i:8;s:2:\"g6\";}', '', '', 'map_default', '', '', 0, '', '1', '', ''), (3, 1, 256, 1526669270, 'Content Elements', 'content-elements', 'regular', '', '', 'index,follow', NULL, 'permanent', 0, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', NULL, '', 0, 0, '', 0, 0, '', 0, 0, 'a:9:{i:0;s:2:\"u1\";i:1;s:2:\"u2\";i:2;s:2:\"u3\";i:3;s:2:\"u4\";i:4;s:2:\"u5\";i:5;s:2:\"u6\";i:6;s:2:\"g4\";i:7;s:2:\"g5\";i:8;s:2:\"g6\";}', '', '', 'map_default', '', '', 0, '', '1', '', '');
INSERT INTO `tl_theme` (`id`, `tstamp`, `name`, `author`, `folders`, `screenshot`, `templates`, `vars`, `defaultImageDensities`) VALUES (1, 1526668892, '<%= theme %>', 'Die Schittigs', 'a:1:{i:0;s:16:\"�Z�迣���݂\";}', NULL, 'templates/templates_<%= theme %>', 'a:0:{}', '');
INSERT INTO `tl_layout` (`id`, `pid`, `tstamp`, `name`, `rows`, `headerHeight`, `footerHeight`, `cols`, `widthLeft`, `widthRight`, `sections`, `framework`, `stylesheet`, `external`, `orderExt`, `loadingOrder`, `combineScripts`, `modules`, `template`, `doctype`, `webfonts`, `viewport`, `titleTag`, `cssClass`, `onload`, `head`, `addJQuery`, `jSource`, `jquery`, `addMooTools`, `mooSource`, `mootools`, `picturefill`, `analytics`, `scripts`, `script`, `static`, `width`, `align`) VALUES (1, 1, 1527582399, 'default', '2rwh', 'a:2:{s:4:\"unit\";s:0:\"\";s:5:\"value\";s:0:\"\";}', '', '1cl', '', '', 'a:1:{i:0;a:4:{s:5:\"title\";s:0:\"\";s:2:\"id\";s:0:\"\";s:8:\"template\";s:13:\"block_section\";s:8:\"position\";s:3:\"top\";}}', '', NULL, NULL, 'a:0:{}', 'external_first', '', 'a:3:{i:0;a:3:{s:3:\"mod\";s:1:\"2\";s:3:\"col\";s:6:\"header\";s:6:\"enable\";s:1:\"1\";}i:1;a:3:{s:3:\"mod\";s:1:\"1\";s:3:\"col\";s:6:\"header\";s:6:\"enable\";s:1:\"1\";}i:2;a:3:{s:3:\"mod\";s:1:\"0\";s:3:\"col\";s:4:\"main\";s:6:\"enable\";s:1:\"1\";}}', 'fe_page', 'html5', '', 'width=device-width, initial-scale=1.0', '', '', '', '<link rel=\"stylesheet\" type=\"text/css\" href=\"/files/theme_<%= theme %>/dist/screen.css\" />\n<link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"/icons_<%= theme %>/apple-touch-icon.png\">\n<link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/icons_<%= theme %>/favicon-32x32.png\">\n<link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/icons_<%= theme %>/favicon-16x16.png\">\n<link rel=\"manifest\" href=\"/icons_<%= theme %>/site.webmanifest\">\n<link rel=\"mask-icon\" href=\"/icons_<%= theme %>/safari-pinned-tab.svg\" color=\"#252d40\">\n<link rel=\"shortcut icon\" href=\"/icons_<%= theme %>/favicon.ico\">\n<meta name=\"msapplication-TileColor\" content=\"#252d40\">\n<meta name=\"msapplication-config\" content=\"/icons_<%= theme %>/browserconfig.xml\">\n<meta name=\"theme-color\" content=\"#252d40\">', '', '', NULL, '', 'moo_local', NULL, '', NULL, NULL, '<script src=\"/files/theme_<%= theme %>/dist/script.js\"></script>', '', '', 'center');
| 2,467.666667
| 13,701
| 0.503354
|
447120ea5728b531f371399da2ab7f89a5a7cfe4
| 15,560
|
py
|
Python
|
qtile/config.py
|
cartoon-raccoon/dotfiles
|
9192e1ac6809bfbdc9d4f77a89e2e674b8b0f6c7
|
[
"Unlicense"
] | null | null | null |
qtile/config.py
|
cartoon-raccoon/dotfiles
|
9192e1ac6809bfbdc9d4f77a89e2e674b8b0f6c7
|
[
"Unlicense"
] | null | null | null |
qtile/config.py
|
cartoon-raccoon/dotfiles
|
9192e1ac6809bfbdc9d4f77a89e2e674b8b0f6c7
|
[
"Unlicense"
] | 1
|
2021-09-05T14:34:50.000Z
|
2021-09-05T14:34:50.000Z
|
##### cartoon-raccoon's qtile config file #####
from typing import List # noqa: F401
from libqtile import bar, layout, widget
from libqtile.config import Click, Drag, Group, ScratchPad, DropDown, Key, KeyChord, Match, Screen, Rule
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal
from libqtile import hook
import os
import subprocess
import datetime
import cgi
mod = "mod4"
terminal = guess_terminal()
#####! KEYBINDS !#####
keys = [
# Switch between windows
Key([mod], "h", lazy.layout.left(), desc="Move focus to left"),
Key([mod], "l", lazy.layout.right(), desc="Move focus to right"),
Key([mod], "j", lazy.layout.down(), desc="Move focus down"),
Key([mod], "k", lazy.layout.up(), desc="Move focus up"),
Key([mod], "space", lazy.layout.next(),
desc="Move window focus to other window"),
# Move windows between left/right columns or move up/down in current stack.
# Moving out of range in Columns layout will create new column.
Key([mod, "shift"], "h", lazy.layout.shuffle_left(),
desc="Move window to the left"),
Key([mod, "shift"], "l", lazy.layout.shuffle_right(),
desc="Move window to the right"),
Key([mod, "shift"], "j", lazy.layout.shuffle_down(),
desc="Move window down"),
Key([mod, "shift"], "k", lazy.layout.shuffle_up(), desc="Move window up"),
# Grow windows. If current window is on the edge of screen and direction
# will be to screen edge - window would shrink.
Key([mod, "control"], "h", lazy.layout.decrease_ratio(),
desc="Grow window to the left"),
Key([mod, "control"], "l", lazy.layout.increase_ratio(),
desc="Grow window to the right"),
Key([mod, "control"], "j", lazy.layout.grow_down(),
desc="Grow window down"),
Key([mod, "control"], "k", lazy.layout.grow_up(), desc="Grow window up"),
Key([mod], "n", lazy.layout.normalize(), desc="Reset all window sizes"),
Key([mod], "Left", lazy.screen.prev_group()),
Key([mod], "Right", lazy.screen.next_group()),
# Toggle between split and unsplit sides of stack.
# Split = all windows displayed
# Unsplit = 1 window displayed, like Max layout, but still with
# multiple stack panes
Key([mod, "shift"], "Return", lazy.layout.toggle_split(),
desc="Toggle between split and unsplit sides of stack"),
Key([mod], "Return", lazy.spawn(terminal), desc="Launch terminal"),
# Toggle between different layouts as defined below
Key([mod], "Tab", lazy.next_layout(), desc="Toggle between layouts"),
Key([mod], "q", lazy.window.kill(), desc="Kill focused window"),
# Toggle fullscreen and floating
Key([mod], "f", lazy.window.toggle_fullscreen(), desc="Toggle fullscreen."),
Key([mod], "t", lazy.window.toggle_floating(), desc="Toggle floating,"),
Key([mod], "m", lazy.group.setlayout(" max ")),
Key([mod], "w", lazy.group.setlayout("tabbed ")),
# Basic QTile commands
Key([mod, "control"], "r", lazy.restart(), desc="Restart Qtile"),
Key([mod, "control"], "q", lazy.shutdown(), desc="Shutdown Qtile"),
Key([mod], "r", lazy.spawncmd(),
desc="Spawn a command using a prompt widget"),
# dropdown commands
#Key([], 'F11', lazy.group['dropdowns'].dropdown_toggle('term')),
#Key([], 'F12', lazy.group['dropdowns'].dropdown_toggle('qshell')),
# music control keys
Key([mod], "grave", lazy.spawn("mpc toggle")),
Key([mod], "period", lazy.spawn("mpc next")),
Key([mod], "comma", lazy.spawn("mpc prev")),
Key([], "XF86AudioPlay", lazy.spawn("/home/sammy/.config/spotify-dbus.sh -t")),
Key([mod, "shift"], "period", lazy.spawn("/home/sammy/.config/spotify-dbus.sh -n")),
Key([mod, "shift"], "comma", lazy.spawn("/home/sammy/.config/spotify-dbus.sh -p")),
# volume and brightness control
Key([], 'XF86AudioRaiseVolume', lazy.spawn("pactl set-sink-volume @DEFAULT_SINK@ +5%")),
Key([], 'XF86AudioLowerVolume', lazy.spawn("pactl set-sink-volume @DEFAULT_SINK@ -5%")),
Key([], 'XF86AudioMute', lazy.spawn("pactl set-sink-mute @DEFAULT_SINK@ toggle")),
Key([], 'XF86MonBrightnessUp', lazy.spawn("brightnessctl set +10%")),
Key([], 'XF86MonBrightnessDown', lazy.spawn("brightnessctl set 10%-")),
# screenshot keys
Key([mod],"Print", lazy.spawn("/home/sammy/.config/scrot/run.sh")),
Key([mod, "shift"], "Print", lazy.spawn("/home/sammy/.config/scrot/run.sh -u")),
Key([mod, "shift"], "f", lazy.spawn("flameshot")),
# Launch mode: keyboard shortcuts to launch a bunch of programs.
KeyChord([mod],"p", [
Key([], "f", lazy.spawn("firefox")),
Key([], "s", lazy.spawn("spotify")),
Key([], "d", lazy.spawn("discord")),
Key([], "c", lazy.spawn("code")),
Key([], "r", lazy.spawn("alacritty -e ranger")),
Key([], "t", lazy.spawn("thunar")),
Key([], "m", lazy.spawn("multimc"))
], mode = "launch"),
Key([mod], "g", lazy.spawn("/home/sammy/.config/i3/i3lock"))
]
# Drag floating layouts.
mouse = [
Drag([mod], "Button1", lazy.window.set_position_floating(),
start=lazy.window.get_position()),
Drag([mod], "Button3", lazy.window.set_size_floating(),
start=lazy.window.get_size()),
Click([mod], "Button2", lazy.window.bring_to_front())
]
groups = [
# main
Group(' ', spawn = ["firefox"], layout = " max "),
# dev
Group(' ', spawn = ["code"], layout = " max "),
# files
Group(' ', spawn = ["thunar"]),
# social
Group(' '),
# music
Group(' ', spawn = ["spotify"]),
# misc
Group(' '),
# reading
Group(' '),
# dropdowns
# ScratchPad("dropdowns",
# DropDown("term", "alacritty", opacity = 0.9),
# DropDown("qshell", "alacritty -e qtile shell", opacity = 0.9)
# )
]
# Bind group to its index in the group list and define mappings for window management.
for i in range(1, len(groups) + 1):
group = groups[i - 1]
keys.extend([
# mod1 + letter of group = switch to group
Key([mod], str(i), lazy.group[group.name].toscreen(),
desc="Switch to group {}".format(group.name)),
# mod1 + shift + letter of group = switch to & move focused window to group
Key([mod, "shift"], str(i), lazy.window.togroup(group.name, switch_group=True),
desc="Switch to & move focused window to group {}".format(group.name)),
# mod1 + ctrl + letter of group = move focused to group but do not switch
Key([mod, "control"], str(i), lazy.window.togroup(group.name),
desc="Move focused window to group {}".format(group.name)),
])
#####! LAYOUTS !#####
layouts = [
layout.Tile(
add_after_last = True,
add_on_top = False,
border_focus = "#efefef",
border_normal = "#5f676a",
margin = 4,
ratio = 0.55,
ratio_increment = 0.05,
name = " tile "
),
layout.MonadTall(
border_focus = "#efefef",
border_normal = "#5f676a",
margin = 4,
ratio = 0.55,
name = "monadt "
),
layout.TreeTab(
active_bg = "#efefef",
active_fg = "#222222",
bg_color = "#202020",
border_width = 2,
font = "FiraCode Nerd Font",
fontsize = 12,
inactive_bg = "#5f676a",
inactive_fg = "#efefef",
sections = ['Tabs'],
name = "tabbed "
),
layout.Max(
name = " max "
),
#layout.Columns(
# border_focus_stack='#efefef',
# border_focus='#efefef',
# border_normal='#5f676a',
# margin = 4,
# name = "columns"
#),
#layout.Stack(
# border_focus = "#efefef",
# border_normal = "#5f676a",
# num_stacks=2,
# margin = 4,
# name = " stack "
#),
#layout.Bsp(
# border_focus = "#efefef",
# border_normal = "#5f676a",
# margin = 4,
# name = " bsp "
#),
#layout.MonadWide(
# border_focus = "#efefef",
# border_normal = "#5f676a",
# margin = 4,
# name = "monadw "
#),
# layout.Matrix(),
# layout.RatioTile(),
# layout.VerticalTile(),
# layout.Zoomy(),
]
#####! SCREENS AND WIDGETS !#####
widget_defaults = dict(
font='FiraCode Nerd Font',
fontsize=14,
padding=3,
foreground="#efefef",
)
extension_defaults = widget_defaults.copy()
# Used in the MPD widget to truncate titles if they get too long
def title_truncate(s):
if len(s) > 30:
return f"{s[:30]}..."
else:
return s
# Used in the MPD widget to truncate artist lists
def artist_truncate(s):
splits = s.split(",")
if len(splits) > 2:
return ",".join(splits[:2]) + ", Various"
else:
return s
# the top bar. not currently in use.
top_bar = bar.Bar(
[
widget.Mpd2(
status_format = "{play_status} {artist}: {title} ({elapsed}/{duration}) [ {repeat}{random}{single}{consume}]",
idle_format = " {idle_message} ",
idle_message = "Nothing playing",
format_fns = dict(
#all=lambda s: cgi.escape(s),
artist=artist_truncate,
title=title_truncate,
elapsed=lambda s: str(datetime.timedelta(seconds=int(float(s))))[2:],
duration=lambda s: str(datetime.timedelta(seconds=int(float(s))))[2:],
),
padding = 10,
fontsize = 13,
play_states = {'play': ' ', 'pause': ' ', 'stop' : ' '},
prepare_status = {
'consume': ' ',
'random' : '咽 ',
'repeat' : '凌 ',
'single' : '綾 ',
'updating_db': 'ﮮ ',
},
space = '- ',
update_interval = 0.5,
markup = False,
),
widget.Volume(
fmt = '墳 {}',
fontsize = 13,
),
widget.Spacer(length = bar.STRETCH),
widget.TextBox(text = '',
foreground = '#2d728f',
fontsize = 60,
padding = -9,
),
widget.DF(
fmt = '/ {}',
fontsize = 13,
partition = '/home',
format = '{uf}{m} ({r:.0f}%)',
visible_on_warn = False,
background = '#2d728f',
padding = 5,
),
widget.TextBox(text = '',
background = '#2d728f',
foreground = '#659157',
fontsize = 60,
padding = -9,
),
widget.Memory(
fmt = " {}",
format = '{MemUsed: .0f}M ({MemPercent: .1f}%)',
fontsize = 13,
background = '#659157',
padding = 5,
),
widget.TextBox(text = '',
background = '#659157',
foreground = '#932546',
fontsize = 60,
padding = -9,
),
widget.CPU(
fmt = " {}",
format = "{freq_current}GHz ({load_percent}%)",
fontsize = 13,
background = '#932546',
padding = 5,
),
widget.TextBox(text = '',
background = '#932546',
foreground = '#4a314d',
fontsize = 60,
padding = -9,
),
widget.Net(
interface = "wlp6s0",
format = " {down} {up} ",
fontsize = 13,
background = '#4a314d',
padding = 5,
),
widget.TextBox(text = '',
background = '#4a314d',
foreground = '#d79921',
fontsize = 60,
padding = -9,
),
widget.Battery(
fmt = "{}",
format = "[{char}] {percent:2.0%} {hour:d}:{min:02d} ",
charge_char = 'C',
discharge_char = 'D',
empty_char = 'E',
fontsize = 13,
background = '#d79921',
padding = 5,
),
widget.TextBox(text = '',
background = '#d79921',
foreground = '#d16014',
fontsize = 60,
padding = -9,
),
widget.ThermalSensor(
fmt = ' {}',
fontsize = 13,
background = '#d16014',
padding = 5,
)
],
30,
margin = [0, 0, 4, 0],
background = "#202020",
)
# the bottom bar.
bottom_bar = bar.Bar(
[
widget.CurrentLayout(),
widget.GroupBox(
highlight_method = 'line',
highlight_color = ['#202020', '#343434'],
this_current_screen_border = '#fabd2f',
this_screen_border = '#fabd2f',
),
widget.Spacer(length = 15),
widget.Prompt(),
widget.WindowName(),
#widget.Mpris2(
# fmt = '{title}',
# name = 'spotify',
# objname = 'org.mpris.MediaPlayer2.spotify'
#),
widget.TextBox(text = '|'),
widget.CapsNumLockIndicator(
),
widget.TextBox(text = '|'),
widget.Chord(
chords_colors={
'launch': ("#fabd2f", "#282828"),
},
name_transform=lambda name: name.upper(),
),
widget.Systray(),
widget.Spacer(length = 8),
widget.Clock(format='%A, %d %b %Y %I:%M%p'),
widget.Spacer(length = 8),
widget.QuickExit(
padding = 1,
foreground = 'fb4934',
default_text = '[ ]',
countdown_format = '[ {} ]'
),
],
30,
margin = [4, 0, 0, 0],
background = '202020'
)
screens = [
Screen(
top=top_bar,
bottom=bottom_bar,
left = bar.Gap(size = 8),
right = bar.Gap(size = 8),
),
]
#####! ADDITIONAL VARIABLES !#####
dgroups_key_binder = None
dgroups_app_rules = [
Rule(
Match(wm_type = [
"confirm",
"download",
"notification",
"toolbar",
"splash",
"dialog",
"error",
]),
float = True
),
Rule(
Match(wm_class = [
"Pavucontrol",
"Oomox",
]),
float = True,
break_on_match = False
)
]
main = None # WARNING: this is deprecated and will be removed soon
follow_mouse_focus = True
bring_front_click = False
cursor_warp = False
floating_layout = layout.Floating(
float_rules=[
# Run the utility of `xprop` to see the wm class and name of an X client.
*layout.Floating.default_float_rules,
Match(wm_class='confirmreset'), # gitk
Match(wm_class='makebranch'), # gitk
Match(wm_class='maketag'), # gitk
Match(wm_class='ssh-askpass'), # ssh-askpass
Match(title='branchdialog'), # gitk
Match(title='pinentry'), # GPG key password entry
],
border_focus = "#efefef",
border_normal = "#5f676a"
)
auto_fullscreen = True
focus_on_window_activation = "smart"
#####! WINDOW HOOKS !#####
@hook.subscribe.startup_once
def autostart():
home = os.path.expanduser('~/.config/qtile/autostart.sh')
subprocess.call([home])
@hook.subscribe.client_new
def floating_dialogs(window):
dialog = window.window.get_wm_type() == 'dialog'
transient = window.window.get_wm_transient_for()
bubble = window.window.get_wm_window_role() == 'bubble'
if dialog or bubble or transient:
window.floating = True
# Needed by some Java programs
wmname = "LG3D"
| 31.497976
| 122
| 0.53374
|
c45103fae85c5b24d05f15dc77d6287786bd5371
| 642
|
sql
|
SQL
|
airbyte-integrations/bases/base-normalization/integration_tests/normalization_test_output/clickhouse/test_simple_streams/models/generated/airbyte_ctes/test_normalization/exchange_rate_ab3.sql
|
wissevrowl/airbyte
|
de56d4713cf15af42a4cd24e5744e790d9a98dd2
|
[
"MIT"
] | null | null | null |
airbyte-integrations/bases/base-normalization/integration_tests/normalization_test_output/clickhouse/test_simple_streams/models/generated/airbyte_ctes/test_normalization/exchange_rate_ab3.sql
|
wissevrowl/airbyte
|
de56d4713cf15af42a4cd24e5744e790d9a98dd2
|
[
"MIT"
] | null | null | null |
airbyte-integrations/bases/base-normalization/integration_tests/normalization_test_output/clickhouse/test_simple_streams/models/generated/airbyte_ctes/test_normalization/exchange_rate_ab3.sql
|
wissevrowl/airbyte
|
de56d4713cf15af42a4cd24e5744e790d9a98dd2
|
[
"MIT"
] | null | null | null |
{{ config(
unique_key = '_airbyte_ab_id',
schema = "_airbyte_test_normalization",
tags = [ "top-level-intermediate" ]
) }}
-- SQL model to build a hash column based on the values of this record
-- depends_on: {{ ref('exchange_rate_ab2') }}
select
{{ dbt_utils.surrogate_key([
'id',
'currency',
'date',
'timestamp_col',
quote('HKD@spéçiäl & characters'),
'HKD_special___characters',
'NZD',
'USD',
quote('column`_\'with""_quotes'),
]) }} as _airbyte_exchange_rate_hashid,
tmp.*
from {{ ref('exchange_rate_ab2') }} tmp
-- exchange_rate
where 1 = 1
| 25.68
| 70
| 0.599688
|
de2f0bc15ae97a363a0a4d0f155d0a4de94f0228
| 36,648
|
sql
|
SQL
|
data/sql/galaxy/scripts/skills_skill_mods.sql
|
JohnShandy/swganh
|
d20d22a8dca2e9220a35af0f45f7935ca2eda531
|
[
"MIT"
] | 1
|
2015-03-25T16:02:17.000Z
|
2015-03-25T16:02:17.000Z
|
data/sql/galaxy/scripts/skills_skill_mods.sql
|
JohnShandy/swganh
|
d20d22a8dca2e9220a35af0f45f7935ca2eda531
|
[
"MIT"
] | null | null | null |
data/sql/galaxy/scripts/skills_skill_mods.sql
|
JohnShandy/swganh
|
d20d22a8dca2e9220a35af0f45f7935ca2eda531
|
[
"MIT"
] | null | null | null |
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
CREATE TABLE IF NOT EXISTS `skills_skill_mods` (
`skill_id` int(11) NOT NULL,
`skill_mod_id` bigint(20) NOT NULL,
`value` int(11) NOT NULL default 0,
PRIMARY KEY (`skill_id`,`skill_mod_id`),
KEY `IDX_E43191855585C142` (`skill_id`),
KEY `IDX_E43191859C9E5E6D` (`skill_mod_id`),
CONSTRAINT `FK_E43191855585C142` FOREIGN KEY (`skill_id`) REFERENCES `skill` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_E43191859C9E5E6D` FOREIGN KEY (`skill_mod_id`) REFERENCES `skill_mod` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DELETE FROM `skills_skill_mods`;
/*!40000 ALTER TABLE `skills_skill_mods` DISABLE KEYS */;
INSERT INTO `skills_skill_mods` (`skill_id`,`skill_mod_id`,`value`) VALUES
(11,2,5),
(11,3,5),
(11,4,5),
(11,5,5),
(11,6,1),
(11,8,1),
(12,2,10),
(12,3,10),
(12,4,10),
(12,5,10),
(13,6,1),
(14,7,1),
(14,8,1),
(15,6,1),
(16,6,1),
(16,8,1),
(17,4,5),
(18,4,5),
(19,4,5),
(20,4,10),
(21,5,5),
(22,5,5),
(23,5,5),
(24,5,10),
(25,2,5),
(25,3,5),
(26,2,5),
(26,3,5),
(27,2,5),
(27,3,5),
(28,2,5),
(28,3,5),
(31,10,5),
(31,11,5),
(31,12,5),
(31,13,15),
(32,9,15),
(32,10,20),
(32,11,10),
(32,12,10),
(32,13,5),
(32,14,10),
(32,15,10),
(32,16,30),
(33,14,20),
(34,15,20),
(34,16,20),
(35,14,20),
(35,16,20),
(36,15,20),
(36,16,30),
(37,10,5),
(38,10,5),
(39,10,5),
(40,10,10),
(41,12,5),
(41,13,5),
(42,12,10),
(42,13,10),
(42,17,10),
(43,12,10),
(43,13,5),
(44,12,10),
(44,13,10),
(45,9,5),
(45,11,5),
(46,11,10),
(47,9,10),
(47,11,10),
(48,9,10),
(48,11,10),
(51,18,5),
(51,19,5),
(51,20,10),
(51,21,5),
(51,22,10),
(51,23,10),
(51,97,5),
(52,18,25),
(52,19,10),
(52,20,25),
(52,22,0),
(52,23,0),
(53,18,15),
(54,18,15),
(55,18,15),
(56,18,25),
(57,21,15),
(58,21,15),
(59,21,15),
(60,21,25),
(61,19,5),
(61,20,15),
(62,19,10),
(62,20,15),
(63,19,10),
(63,20,15),
(64,19,10),
(64,20,20),
(65,22,10),
(65,23,10),
(66,22,10),
(66,23,10),
(67,22,10),
(67,23,10),
(68,22,10),
(68,23,10),
(71,24,20),
(71,25,20),
(71,26,20),
(71,27,20),
(71,28,20),
(72,25,0),
(72,26,0),
(73,25,10),
(73,26,10),
(73,28,20),
(74,25,10),
(74,26,10),
(74,28,20),
(75,25,10),
(75,26,10),
(75,28,20),
(76,25,10),
(76,26,10),
(76,28,20),
(77,25,10),
(77,26,10),
(77,27,20),
(78,25,10),
(78,26,10),
(78,27,20),
(79,25,10),
(79,26,10),
(79,27,20),
(80,25,10),
(80,26,10),
(80,27,20),
(83,29,1),
(83,30,10),
(83,31,100),
(84,29,1),
(84,30,10),
(84,31,150),
(85,24,15),
(86,24,20),
(87,24,20),
(88,24,25),
(91,32,10),
(91,33,15),
(91,34,5),
(91,35,10),
(91,36,5),
(91,37,10),
(91,38,5),
(91,39,10),
(91,40,5),
(91,41,100),
(91,42,100),
(91,43,100),
(91,44,100),
(91,45,10),
(91,47,10),
(91,48,10),
(91,49,10),
(91,50,5),
(91,51,5),
(91,52,5),
(91,53,5),
(92,32,5),
(92,34,5),
(92,35,5),
(92,36,5),
(92,37,5),
(92,38,5),
(92,41,100),
(92,42,100),
(92,43,100),
(92,44,100),
(92,47,10),
(92,48,10),
(92,49,10),
(92,51,5),
(92,52,5),
(92,53,5),
(92,54,20),
(92,55,20),
(92,56,20),
(92,67,5),
(92,68,5),
(92,81,5),
(92,210,10),
(92,211,5),
(92,213,5),
(93,32,10),
(93,33,5),
(93,34,5),
(93,43,100),
(93,50,2),
(93,210,10),
(94,32,10),
(94,33,10),
(94,34,5),
(94,43,100),
(94,50,2),
(94,210,10),
(95,32,10),
(95,33,10),
(95,34,5),
(95,43,100),
(95,50,2),
(95,81,10),
(95,210,5),
(96,32,10),
(96,33,10),
(96,34,5),
(96,43,100),
(96,50,2),
(96,68,2),
(96,81,10),
(96,210,10),
(97,37,10),
(97,38,5),
(97,41,100),
(97,48,10),
(97,51,2),
(98,37,10),
(98,38,5),
(98,41,100),
(98,48,10),
(98,51,2),
(99,37,10),
(99,38,5),
(99,41,100),
(99,48,10),
(99,51,2),
(99,212,10),
(100,37,10),
(100,38,5),
(100,41,100),
(100,48,10),
(100,51,2),
(100,212,10),
(101,39,10),
(101,40,5),
(101,42,100),
(101,49,10),
(101,52,2),
(102,39,10),
(102,40,5),
(102,42,100),
(102,49,10),
(102,52,2),
(103,39,10),
(103,40,5),
(103,42,100),
(103,49,10),
(103,52,2),
(103,211,10),
(104,39,10),
(104,40,5),
(104,42,100),
(104,49,10),
(104,52,2),
(104,211,10),
(105,35,10),
(105,44,100),
(105,47,10),
(105,53,2),
(105,58,5),
(106,35,10),
(106,36,5),
(106,44,100),
(106,47,10),
(106,53,2),
(107,35,10),
(107,36,5),
(107,44,100),
(107,47,10),
(107,53,2),
(107,213,4),
(108,35,10),
(108,36,5),
(108,44,100),
(108,47,5),
(108,53,1),
(108,213,4),
(110,57,10),
(110,58,5),
(110,59,10),
(110,60,5),
(110,61,10),
(110,62,5),
(110,63,100),
(110,64,100),
(110,65,100),
(111,57,10),
(111,58,5),
(111,59,10),
(111,60,5),
(111,61,10),
(111,62,5),
(111,63,100),
(111,64,100),
(111,65,100),
(111,67,5),
(112,59,10),
(112,60,5),
(112,63,100),
(112,66,5),
(113,59,10),
(113,60,5),
(113,63,100),
(113,66,5),
(114,59,10),
(114,60,5),
(114,63,100),
(114,66,5),
(115,59,10),
(115,60,5),
(115,63,100),
(115,66,5),
(115,67,2),
(116,57,10),
(116,58,5),
(116,65,100),
(117,57,10),
(117,58,5),
(117,65,100),
(118,57,10),
(118,58,5),
(118,65,100),
(119,57,10),
(119,58,5),
(119,65,100),
(120,61,10),
(120,62,5),
(120,64,100),
(121,61,10),
(121,62,5),
(121,64,100),
(122,61,10),
(122,62,5),
(122,64,100),
(123,61,10),
(123,62,5),
(123,64,100),
(123,67,2),
(124,67,2),
(124,214,10),
(125,68,2),
(125,214,10),
(126,214,5),
(127,67,2),
(127,69,10),
(127,214,5),
(129,59,5),
(129,60,5),
(129,63,100),
(129,66,15),
(129,70,10),
(130,59,40),
(130,60,20),
(130,63,100),
(130,66,5),
(130,67,15),
(130,70,10),
(130,215,10),
(131,59,10),
(131,63,125),
(131,66,15),
(131,216,15),
(132,59,10),
(132,63,100),
(132,66,15),
(132,216,15),
(133,59,20),
(133,63,100),
(133,66,15),
(133,216,15),
(134,59,20),
(134,63,100),
(134,66,15),
(134,216,15),
(135,63,125),
(135,67,10),
(135,185,20),
(136,63,100),
(136,67,10),
(136,185,20),
(137,63,100),
(137,67,10),
(137,185,20),
(138,67,10),
(138,185,20),
(139,63,125),
(139,70,15),
(140,63,100),
(140,70,15),
(141,63,100),
(141,70,15),
(141,71,30),
(141,72,10),
(141,73,10),
(141,74,10),
(142,63,125),
(142,67,15),
(142,70,15),
(143,60,10),
(143,63,125),
(143,68,10),
(144,60,10),
(144,63,100),
(144,68,10),
(145,60,10),
(145,63,100),
(145,68,10),
(146,60,10),
(146,63,125),
(146,68,10),
(148,57,5),
(148,58,5),
(148,65,100),
(148,75,10),
(149,57,10),
(149,58,20),
(149,65,100),
(149,67,5),
(149,68,5),
(149,75,25),
(149,76,10),
(149,77,4),
(150,65,125),
(150,75,15),
(151,65,100),
(151,75,15),
(152,65,100),
(152,75,20),
(153,65,125),
(153,75,20),
(154,57,10),
(154,65,125),
(154,76,5),
(154,77,3),
(155,57,5),
(155,65,100),
(155,76,5),
(155,77,3),
(156,57,10),
(156,65,100),
(156,76,5),
(156,77,3),
(157,57,5),
(157,65,125),
(157,76,5),
(157,77,3),
(158,65,125),
(158,72,40),
(159,65,100),
(159,73,40),
(160,65,100),
(160,74,40),
(161,65,125),
(161,78,20),
(161,79,50),
(162,58,6),
(162,65,125),
(162,68,10),
(163,58,6),
(163,65,100),
(163,68,10),
(164,58,6),
(164,65,100),
(164,68,10),
(164,217,15),
(165,58,6),
(165,65,125),
(165,68,10),
(167,61,5),
(167,62,5),
(167,64,100),
(168,61,20),
(168,62,10),
(168,64,100),
(168,67,25),
(168,80,25),
(168,218,10),
(168,219,25),
(169,62,5),
(169,64,125),
(170,62,5),
(170,64,100),
(171,62,5),
(171,64,100),
(172,62,5),
(172,64,100),
(173,61,5),
(173,64,125),
(174,61,10),
(174,64,100),
(175,61,15),
(175,64,100),
(176,61,25),
(176,64,125),
(177,64,125),
(177,80,20),
(178,64,100),
(178,79,15),
(178,80,20),
(178,220,25),
(179,64,100),
(179,80,20),
(180,64,125),
(180,80,20),
(181,64,125),
(181,218,5),
(182,64,100),
(182,218,5),
(183,64,100),
(183,218,5),
(184,64,125),
(184,218,5),
(186,32,20),
(186,33,70),
(186,34,10),
(186,43,100),
(186,50,5),
(186,81,4),
(186,82,10),
(186,83,5),
(186,84,15),
(186,210,15),
(186,221,15),
(187,32,35),
(187,33,70),
(187,34,20),
(187,43,100),
(187,50,5),
(187,82,15),
(187,83,10),
(187,84,25),
(187,85,10),
(187,210,10),
(187,221,25),
(188,43,125),
(188,83,5),
(188,221,15),
(189,43,100),
(189,83,10),
(189,85,5),
(189,221,15),
(190,43,100),
(190,83,10),
(190,85,5),
(190,221,15),
(191,43,100),
(191,83,10),
(191,85,5),
(191,221,15),
(192,43,125),
(192,73,10),
(192,78,10),
(192,82,10),
(193,43,100),
(193,72,10),
(193,78,10),
(193,81,15),
(193,82,10),
(194,43,100),
(194,72,5),
(194,74,5),
(194,78,10),
(194,79,20),
(194,81,4),
(194,82,10),
(195,43,125),
(195,81,4),
(196,33,15),
(196,34,15),
(196,43,125),
(197,33,15),
(197,34,15),
(197,43,100),
(198,33,15),
(198,34,15),
(198,43,100),
(199,33,15),
(199,34,15),
(199,43,125),
(200,32,30),
(200,43,125),
(200,50,2),
(200,67,5),
(200,68,15),
(200,84,15),
(200,210,10),
(201,32,20),
(201,43,100),
(201,50,2),
(201,67,10),
(201,68,15),
(201,81,5),
(201,84,11),
(201,210,5),
(202,32,30),
(202,43,100),
(202,50,2),
(202,67,15),
(202,68,15),
(202,84,15),
(202,210,10),
(203,32,20),
(203,43,100),
(203,50,1),
(203,67,15),
(203,68,15),
(203,81,5),
(203,84,15),
(203,210,10),
(205,37,20),
(205,38,10),
(205,41,100),
(205,48,15),
(205,51,5),
(205,67,15),
(205,68,15),
(205,75,15),
(205,212,4),
(206,37,20),
(206,38,10),
(206,41,100),
(206,48,15),
(206,51,5),
(206,68,5),
(206,69,10),
(206,75,15),
(206,82,10),
(207,41,125),
(207,67,12),
(207,68,12),
(208,41,100),
(208,67,15),
(208,68,15),
(209,41,100),
(209,67,12),
(209,68,12),
(209,212,4),
(210,41,125),
(210,67,15),
(210,68,15),
(210,212,4),
(211,38,5),
(211,41,125),
(211,48,5),
(211,51,2),
(212,38,20),
(212,41,100),
(212,48,10),
(212,51,2),
(212,78,20),
(212,79,20),
(213,41,100),
(213,48,10),
(213,51,2),
(214,38,20),
(214,41,125),
(214,48,10),
(214,51,2),
(214,75,15),
(214,78,30),
(214,79,30),
(215,41,125),
(215,75,15),
(216,41,100),
(216,73,10),
(216,74,10),
(216,75,15),
(216,220,10),
(217,41,100),
(217,75,15),
(218,41,125),
(218,73,30),
(218,74,30),
(218,75,15),
(218,220,10),
(219,41,125),
(220,37,30),
(220,41,100),
(220,82,10),
(221,41,100),
(222,37,30),
(222,41,125),
(222,82,10),
(224,39,15),
(224,40,10),
(224,42,100),
(224,49,15),
(224,52,5),
(224,68,5),
(224,80,15),
(224,213,15),
(225,39,15),
(225,40,10),
(225,42,100),
(225,49,15),
(225,52,5),
(225,67,5),
(225,68,5),
(225,72,30),
(225,73,10),
(225,79,10),
(225,80,25),
(226,42,125),
(227,42,100),
(228,42,100),
(228,72,20),
(228,74,20),
(228,213,4),
(228,220,20),
(229,42,125),
(229,213,4),
(230,42,125),
(231,40,15),
(231,42,100),
(232,42,100),
(233,40,15),
(233,42,125),
(234,42,125),
(234,49,10),
(234,52,2),
(234,80,15),
(235,42,100),
(235,49,10),
(235,52,2),
(235,67,5),
(235,68,5),
(235,78,10),
(235,80,15),
(236,42,100),
(236,49,10),
(236,52,2),
(236,80,15),
(237,42,125),
(237,49,10),
(237,52,2),
(237,67,5),
(237,68,5),
(237,79,15),
(237,80,15),
(238,42,125),
(239,39,20),
(239,42,100),
(240,42,100),
(241,39,30),
(241,42,125),
(241,80,10),
(243,35,20),
(243,36,10),
(243,44,100),
(243,47,15),
(243,53,5),
(243,68,5),
(243,70,25),
(243,211,10),
(244,35,20),
(244,36,10),
(244,44,100),
(244,47,15),
(244,53,5),
(244,67,15),
(244,68,15),
(244,70,30),
(244,72,30),
(244,74,20),
(244,78,10),
(245,44,125),
(246,36,15),
(246,44,100),
(247,44,100),
(248,36,15),
(248,44,125),
(249,44,125),
(250,44,100),
(251,44,100),
(252,44,125),
(253,44,125),
(253,47,10),
(253,53,2),
(253,70,15),
(254,44,100),
(254,47,10),
(254,53,2),
(254,67,5),
(254,68,5),
(254,70,15),
(254,72,10),
(254,73,10),
(254,74,10),
(254,78,10),
(254,79,10),
(255,44,100),
(255,47,10),
(255,53,2),
(255,70,15),
(256,44,125),
(256,47,10),
(256,53,2),
(256,67,5),
(256,68,5),
(256,70,15),
(256,72,10),
(256,73,10),
(256,74,10),
(256,78,10),
(256,79,10),
(256,211,4),
(257,44,125),
(257,211,4),
(258,35,30),
(258,44,100),
(259,44,100),
(260,35,30),
(260,44,125),
(262,2,5),
(262,5,10),
(262,87,10),
(262,222,10),
(263,2,15),
(263,5,10),
(263,25,0),
(263,26,0),
(263,67,7),
(263,68,7),
(263,87,25),
(263,91,100),
(263,92,100),
(263,222,25),
(264,87,10),
(265,87,10),
(266,87,20),
(267,87,25),
(268,2,5),
(269,2,10),
(270,2,10),
(271,2,15),
(272,5,10),
(273,5,10),
(274,5,10),
(275,5,10),
(276,222,10),
(277,222,10),
(278,222,20),
(279,222,25),
(281,3,5),
(281,4,5),
(281,88,10),
(281,89,10),
(281,90,10),
(282,3,15),
(282,4,15),
(282,25,0),
(282,26,0),
(282,67,7),
(282,68,7),
(282,88,25),
(282,89,25),
(282,90,25),
(282,91,100),
(282,92,100),
(283,89,10),
(283,90,10),
(284,89,10),
(284,90,15),
(285,89,20),
(285,90,15),
(286,89,25),
(286,90,25),
(287,3,5),
(288,3,10),
(289,3,10),
(290,3,15),
(291,4,5),
(292,4,10),
(293,4,10),
(294,4,15),
(295,88,10),
(296,88,10),
(297,88,20),
(298,88,25),
(300,19,5),
(300,22,10),
(300,23,10),
(300,96,5),
(300,97,5),
(301,19,10),
(301,22,0),
(301,23,0),
(301,95,100),
(301,96,25),
(301,97,25),
(302,96,15),
(303,96,15),
(304,96,15),
(305,96,25),
(306,97,10),
(307,97,15),
(308,97,15),
(309,97,25),
(310,19,5),
(311,19,10),
(312,19,10),
(313,19,10),
(314,22,10),
(314,23,10),
(315,22,10),
(315,23,10),
(316,22,10),
(316,23,10),
(317,22,10),
(317,23,10),
(319,9,5),
(319,11,5),
(319,12,5),
(319,13,5),
(319,14,5),
(319,98,10),
(320,9,5),
(320,10,10),
(320,11,5),
(320,12,10),
(320,13,10),
(320,67,10),
(320,68,10),
(320,99,20),
(320,100,10),
(321,99,40),
(322,14,20),
(322,15,10),
(323,99,40),
(324,14,20),
(324,15,10),
(325,9,10),
(325,11,10),
(326,9,10),
(326,11,10),
(327,9,10),
(327,11,10),
(328,9,10),
(328,11,10),
(329,12,5),
(329,13,5),
(329,98,10),
(330,12,10),
(330,13,10),
(330,17,10),
(330,98,10),
(331,12,10),
(331,13,10),
(331,98,10),
(332,12,10),
(332,13,10),
(332,17,5),
(332,98,10),
(333,10,10),
(333,100,10),
(334,10,10),
(334,100,10),
(335,10,10),
(335,100,10),
(336,10,10),
(336,100,10),
(338,101,4),
(338,102,1),
(338,103,5),
(338,104,12),
(339,101,4),
(339,102,1),
(339,103,5),
(339,104,10),
(339,105,10),
(339,107,10),
(339,223,10),
(339,224,15),
(340,103,5),
(340,104,2),
(341,103,5),
(341,104,2),
(341,224,10),
(342,103,5),
(342,104,3),
(342,224,10),
(343,103,5),
(343,104,5),
(343,224,15),
(344,101,2),
(344,103,5),
(344,104,2),
(344,107,10),
(345,101,3),
(345,103,5),
(345,104,2),
(345,107,10),
(346,101,3),
(346,103,5),
(346,104,3),
(346,107,10),
(347,101,4),
(347,103,5),
(347,104,5),
(347,107,10),
(348,103,5),
(348,104,2),
(348,105,10),
(349,103,5),
(349,104,2),
(349,105,10),
(350,103,5),
(350,104,3),
(350,105,10),
(351,103,5),
(351,104,5),
(351,105,10),
(352,103,5),
(352,104,2),
(352,223,10),
(353,103,5),
(353,104,2),
(353,223,10),
(354,102,1),
(354,103,5),
(354,104,3),
(354,223,10),
(355,103,5),
(355,104,5),
(355,223,10),
(357,108,10),
(357,109,10),
(357,110,15),
(358,108,0),
(358,109,0),
(358,110,25),
(367,110,15),
(368,110,15),
(369,110,15),
(370,110,15),
(371,108,10),
(371,109,10),
(372,108,15),
(372,109,15),
(373,108,15),
(373,109,15),
(374,108,25),
(374,109,25),
(376,28,20),
(376,111,10),
(376,112,10),
(377,28,55),
(377,111,25),
(377,112,25),
(390,28,20),
(390,111,10),
(390,112,10),
(391,28,20),
(391,111,15),
(391,112,15),
(392,28,20),
(392,111,20),
(392,112,20),
(393,28,20),
(393,111,20),
(393,112,20),
(395,113,10),
(395,114,10),
(396,113,25),
(396,114,25),
(409,113,10),
(409,114,10),
(410,113,15),
(410,114,15),
(411,113,20),
(411,114,20),
(412,113,20),
(412,114,20),
(414,115,20),
(414,116,20),
(415,91,100),
(415,115,10),
(415,116,10),
(428,115,10),
(428,116,10),
(429,115,20),
(429,116,20),
(430,115,20),
(430,116,20),
(431,115,20),
(431,116,20),
(433,27,20),
(433,117,20),
(433,118,20),
(434,27,55),
(434,117,10),
(434,118,20),
(447,27,20),
(447,117,10),
(447,118,15),
(448,27,20),
(448,117,20),
(448,118,15),
(449,27,20),
(449,117,20),
(449,118,15),
(450,27,20),
(450,117,20),
(450,118,15),
(452,119,20),
(452,120,20),
(453,119,10),
(453,120,10),
(454,119,10),
(455,119,20),
(456,119,20),
(457,119,20),
(458,120,10),
(459,120,20),
(460,120,20),
(461,120,20),
(471,121,20),
(471,122,32),
(471,225,20),
(472,25,0),
(472,26,0),
(472,121,10),
(472,225,10),
(481,122,8),
(481,225,10),
(482,122,8),
(482,225,20),
(483,122,8),
(483,225,20),
(484,122,8),
(484,225,20),
(485,121,10),
(486,121,20),
(487,121,20),
(488,121,20),
(490,29,1),
(490,30,10),
(490,31,500),
(491,29,2),
(491,30,10),
(491,31,1000),
(498,31,100),
(499,29,1),
(499,31,150),
(499,226,100),
(500,30,20),
(501,30,10),
(502,30,15),
(503,30,15),
(504,29,1),
(504,31,500),
(504,123,1),
(505,29,1),
(505,31,500),
(505,123,1),
(506,29,2),
(506,31,500),
(506,123,1),
(507,29,2),
(507,31,500),
(507,123,1),
(509,126,20),
(509,127,20),
(511,124,100),
(519,125,45),
(520,125,5),
(521,125,10),
(522,125,10),
(523,126,20),
(523,127,20),
(524,126,20),
(524,127,20),
(525,126,20),
(525,127,20),
(526,126,20),
(526,127,20),
(528,128,1),
(528,129,20),
(528,130,10),
(528,131,1600),
(529,57,10),
(529,61,10),
(529,67,7),
(529,131,100),
(529,132,4),
(529,133,10),
(529,134,10),
(529,135,10),
(529,136,10),
(529,294,100),
(529,295,100),
(530,128,1),
(530,134,70),
(530,135,10),
(531,134,50),
(531,135,40),
(532,128,1),
(532,132,4),
(532,133,50),
(532,135,30),
(532,136,40),
(533,132,4),
(533,133,40),
(533,136,30),
(534,61,10),
(534,62,10),
(534,64,200),
(535,61,10),
(535,62,10),
(535,64,200),
(536,61,20),
(536,62,20),
(536,64,200),
(537,61,10),
(537,62,10),
(537,64,200),
(538,57,10),
(538,58,10),
(538,65,200),
(539,57,10),
(539,58,10),
(539,65,200),
(540,57,20),
(540,58,20),
(540,65,200),
(541,57,10),
(541,58,10),
(541,65,200),
(542,129,10),
(542,130,10),
(542,131,200),
(543,129,10),
(543,130,10),
(543,131,200),
(544,129,20),
(544,130,20),
(544,131,200),
(545,129,10),
(545,130,10),
(545,131,200),
(547,131,1700),
(547,137,10),
(547,138,10),
(547,139,15),
(548,67,25),
(548,68,25),
(548,137,30),
(548,138,30),
(548,139,40),
(548,140,40),
(549,131,100),
(549,139,10),
(549,227,10),
(550,79,5),
(550,227,10),
(551,67,5),
(551,139,10),
(551,227,10),
(552,68,5),
(552,139,10),
(552,227,10),
(553,140,20),
(553,228,20),
(553,229,10),
(553,230,10),
(554,140,20),
(554,228,20),
(554,229,20),
(554,230,20),
(554,231,10),
(554,232,10),
(555,140,20),
(555,228,20),
(555,229,20),
(555,230,20),
(555,231,20),
(555,232,20),
(555,233,10),
(555,234,10),
(556,229,20),
(556,230,20),
(556,231,20),
(556,232,20),
(556,233,30),
(556,234,30),
(557,131,100),
(557,137,15),
(557,235,10),
(558,131,100),
(558,137,15),
(558,235,10),
(559,131,100),
(559,137,25),
(559,235,15),
(560,131,100),
(560,137,15),
(560,235,10),
(561,131,100),
(561,138,15),
(561,236,10),
(562,131,100),
(562,138,15),
(562,236,10),
(563,131,100),
(563,138,25),
(563,236,15),
(564,131,100),
(564,138,15),
(564,236,10),
(566,141,5),
(566,142,20),
(566,143,5),
(566,144,5),
(566,145,5),
(566,146,20),
(567,14,10),
(567,95,100),
(567,141,25),
(567,143,25),
(567,144,25),
(567,145,25),
(567,146,0),
(567,147,0),
(568,144,15),
(568,145,15),
(569,144,15),
(569,145,15),
(570,144,15),
(570,145,15),
(571,144,25),
(571,145,25),
(572,141,15),
(573,141,15),
(574,141,15),
(575,141,25),
(576,142,20),
(576,146,20),
(577,142,20),
(577,146,20),
(578,142,20),
(578,146,20),
(579,142,20),
(579,146,20),
(580,14,10),
(580,143,15),
(581,14,10),
(581,143,15),
(582,14,10),
(582,143,15),
(583,14,10),
(583,15,10),
(583,143,25),
(585,6,1),
(585,8,1),
(585,237,1),
(586,7,2),
(586,8,2),
(586,237,2),
(587,6,1),
(588,6,2),
(589,6,2),
(590,6,2),
(591,8,1),
(592,8,1),
(593,8,2),
(594,8,2),
(595,237,1),
(596,237,1),
(597,237,2),
(598,237,2),
(599,7,1),
(600,7,1),
(601,7,2),
(602,7,2),
(605,148,5),
(605,150,10),
(605,151,10),
(605,238,5),
(606,151,25),
(607,150,25),
(608,151,25),
(609,150,25),
(611,152,10),
(613,153,10),
(615,148,10),
(616,148,15),
(619,238,10),
(621,238,15),
(623,154,100),
(626,155,100),
(626,156,100),
(630,157,100),
(634,158,100),
(639,159,100),
(639,160,100),
(640,161,100),
(640,162,100),
(643,1,100),
(644,264,100),
(646,165,100),
(647,166,100),
(649,167,100),
(650,168,100),
(652,169,100),
(653,170,100),
(655,171,100),
(656,172,100),
(658,173,100),
(659,174,100),
(661,175,100),
(662,176,100),
(664,177,100),
(665,178,100),
(667,179,100),
(668,180,100),
(670,181,100),
(671,182,100),
(673,183,100),
(674,184,100),
(676,99,15),
(676,185,10),
(677,26,15),
(677,186,10),
(678,69,15),
(678,113,10),
(678,119,10),
(679,37,10),
(679,39,10),
(679,73,15),
(679,113,10),
(680,13,10),
(680,32,10),
(680,33,15),
(680,34,5),
(680,68,10),
(680,189,1),
(681,2,15),
(681,3,5),
(681,88,5),
(681,222,15),
(682,10,10),
(682,54,10),
(682,100,10),
(682,242,10),
(682,296,1),
(683,72,10),
(683,74,10),
(683,220,10),
(683,239,5),
(683,240,1),
(683,241,1),
(684,68,10),
(684,72,10),
(684,74,10),
(684,193,10),
(684,194,10),
(684,195,10),
(684,196,10),
(684,242,10),
(685,10,10),
(685,13,10),
(685,190,10),
(685,191,10),
(685,192,10),
(688,24,50),
(688,243,200),
(688,244,1),
(688,245,25),
(688,246,30),
(688,247,30),
(688,248,5),
(688,249,5),
(688,250,1000),
(689,243,200),
(689,244,1),
(689,246,20),
(689,247,10),
(689,248,6),
(689,249,10),
(689,250,500),
(689,251,30),
(689,252,20),
(690,246,20),
(690,247,10),
(690,249,2),
(690,250,100),
(691,246,20),
(691,247,10),
(691,249,2),
(691,250,100),
(692,246,20),
(692,247,10),
(692,248,2),
(692,249,2),
(692,250,100),
(693,246,20),
(693,247,10),
(693,248,2),
(693,249,2),
(693,250,100),
(698,243,100),
(698,244,1),
(698,250,100),
(699,243,100),
(699,244,1),
(699,250,100),
(700,243,100),
(700,244,1),
(700,250,100),
(701,243,100),
(701,244,1),
(701,250,100),
(703,250,100),
(703,252,30),
(704,253,30),
(705,250,100),
(705,251,30),
(707,243,400),
(707,244,2),
(707,245,25),
(707,248,5),
(707,249,5),
(707,250,500),
(707,253,60),
(707,254,3),
(707,255,30),
(707,256,10),
(708,243,400),
(708,244,2),
(708,248,12),
(708,250,1200),
(708,254,20),
(708,255,10),
(708,256,10),
(709,248,2),
(709,249,5),
(709,250,100),
(709,254,20),
(709,255,10),
(709,256,5),
(710,248,2),
(710,249,5),
(710,250,100),
(710,254,20),
(710,255,10),
(710,256,5),
(711,248,2),
(711,249,5),
(711,250,100),
(711,254,20),
(711,255,10),
(711,256,5),
(712,248,2),
(712,249,5),
(712,250,100),
(712,254,20),
(712,255,10),
(712,256,5),
(717,243,250),
(717,244,2),
(718,243,250),
(718,244,2),
(719,243,250),
(719,244,2),
(720,243,250),
(720,244,2),
(721,250,100),
(721,257,1),
(721,258,30),
(722,250,100),
(722,252,30),
(723,250,100),
(723,251,30),
(723,252,30),
(724,250,100),
(724,251,30),
(724,257,2),
(724,258,30),
(726,243,500),
(726,244,4),
(726,245,50),
(726,248,10),
(726,249,5),
(726,250,1000),
(726,256,5),
(726,259,30),
(726,260,30),
(726,261,50),
(726,262,30),
(727,243,500),
(727,244,4),
(727,250,1000),
(727,257,1),
(727,259,10),
(727,260,20),
(727,263,1),
(727,288,5),
(728,248,5),
(728,249,2),
(728,250,125),
(728,256,5),
(728,259,10),
(728,260,20),
(728,262,5),
(729,248,5),
(729,249,5),
(729,250,125),
(729,256,5),
(729,259,10),
(729,260,20),
(729,262,5),
(730,248,5),
(730,250,125),
(730,256,5),
(730,259,10),
(730,260,20),
(730,262,5),
(731,248,5),
(731,250,125),
(731,259,10),
(731,260,20),
(731,262,10),
(736,243,250),
(736,244,8),
(737,243,250),
(737,244,8),
(738,243,250),
(738,244,8),
(739,243,250),
(739,244,8),
(740,258,30),
(740,263,2),
(743,258,30),
(743,261,50),
(743,263,2),
(745,243,400),
(745,244,2),
(745,245,25),
(745,248,5),
(745,249,5),
(745,250,500),
(745,253,60),
(745,254,3),
(745,255,30),
(745,256,10),
(746,243,400),
(746,244,2),
(746,248,12),
(746,250,1200),
(746,254,20),
(746,255,10),
(746,256,10),
(747,248,2),
(747,249,5),
(747,250,100),
(747,254,20),
(747,255,10),
(747,256,5),
(748,248,2),
(748,249,5),
(748,250,100),
(748,254,20),
(748,255,10),
(748,256,5),
(749,248,2),
(749,249,5),
(749,250,100),
(749,254,20),
(749,255,10),
(749,256,5),
(750,248,2),
(750,249,5),
(750,250,100),
(750,254,20),
(750,255,10),
(750,256,5),
(755,243,200),
(755,244,1),
(756,243,200),
(756,244,1),
(757,243,200),
(757,244,1),
(758,243,200),
(758,244,1),
(759,250,100),
(759,257,1),
(759,258,30),
(760,250,100),
(760,252,30),
(761,250,100),
(761,251,30),
(761,252,30),
(762,250,100),
(762,251,30),
(762,257,2),
(762,258,30),
(764,243,500),
(764,244,4),
(764,245,50),
(764,248,10),
(764,249,5),
(764,250,1000),
(764,256,5),
(764,259,30),
(764,260,30),
(764,261,50),
(764,262,30),
(765,243,500),
(765,244,4),
(765,250,1000),
(765,257,1),
(765,259,10),
(765,260,20),
(765,263,1),
(765,288,5),
(766,248,5),
(766,249,2),
(766,250,125),
(766,256,5),
(766,259,10),
(766,260,20),
(766,262,5),
(767,248,5),
(767,249,5),
(767,250,125),
(767,256,5),
(767,259,10),
(767,260,20),
(767,262,5),
(768,248,5),
(768,250,125),
(768,256,5),
(768,259,10),
(768,260,20),
(768,262,5),
(769,248,5),
(769,250,125),
(769,259,10),
(769,260,20),
(769,262,10),
(774,243,500),
(774,244,2),
(775,243,500),
(775,244,2),
(776,243,500),
(776,244,2),
(777,243,500),
(777,244,2),
(778,258,30),
(778,263,2),
(781,258,30),
(781,261,50),
(781,263,2),
(786,265,3),
(787,265,3),
(788,265,3),
(789,265,3),
(790,266,3),
(791,266,3),
(792,266,3),
(793,266,3),
(794,267,3),
(795,267,3),
(796,267,3),
(797,267,3),
(798,268,3),
(799,268,3),
(800,268,3),
(801,268,3),
(805,67,5),
(806,67,5),
(807,67,5),
(808,67,5),
(809,68,5),
(810,68,5),
(811,68,5),
(812,68,5),
(813,269,5),
(814,269,5),
(814,270,1),
(815,269,5),
(815,270,1),
(816,269,5),
(816,270,1),
(817,9,5),
(817,11,5),
(818,10,5),
(818,16,5),
(819,14,5),
(820,12,5),
(820,13,5),
(824,271,5),
(825,271,5),
(826,271,5),
(827,271,5),
(828,272,5),
(829,272,5),
(830,272,5),
(831,272,5),
(832,273,5),
(833,273,5),
(834,273,5),
(835,273,5),
(836,274,1),
(837,274,1),
(838,274,1),
(839,274,1),
(843,2,5),
(843,3,5),
(843,18,5),
(844,2,5),
(844,3,5),
(844,21,5),
(845,2,5),
(845,3,5),
(845,18,5),
(846,2,5),
(846,3,5),
(846,21,5),
(847,24,5),
(848,24,5),
(849,24,5),
(850,24,5),
(851,275,5),
(852,275,5),
(853,275,5),
(854,275,5),
(855,276,1),
(856,276,1),
(857,276,1),
(858,276,1),
(861,243,200),
(861,244,1),
(861,245,10),
(861,246,25),
(861,247,25),
(861,248,10),
(861,254,25),
(861,255,25),
(861,259,25),
(861,260,25),
(861,289,10),
(861,290,10),
(861,291,200),
(861,292,200),
(861,293,200),
(862,243,500),
(862,244,5),
(862,245,30),
(862,246,25),
(862,247,25),
(862,248,25),
(862,254,25),
(862,255,25),
(862,259,25),
(862,260,25),
(862,289,15),
(862,290,25),
(863,243,100),
(863,244,1),
(863,246,5),
(863,247,5),
(863,291,200),
(864,243,100),
(864,244,1),
(864,246,10),
(864,247,10),
(864,291,200),
(865,243,150),
(865,244,1),
(865,246,15),
(865,247,15),
(865,291,200),
(866,243,175),
(866,244,2),
(866,246,20),
(866,247,20),
(866,291,300),
(867,243,100),
(867,244,1),
(867,254,5),
(867,255,5),
(867,292,200),
(868,243,100),
(868,244,1),
(868,254,10),
(868,255,10),
(868,292,200),
(869,243,150),
(869,244,1),
(869,254,15),
(869,255,15),
(869,292,200),
(870,243,175),
(870,244,2),
(870,254,20),
(870,255,20),
(870,292,300),
(871,243,100),
(871,244,1),
(871,259,5),
(871,260,5),
(871,293,200),
(872,243,100),
(872,244,1),
(872,259,10),
(872,260,10),
(872,293,200),
(873,243,150),
(873,244,1),
(873,259,15),
(873,260,15),
(873,293,200),
(874,243,175),
(874,244,2),
(874,259,20),
(874,260,20),
(874,293,300),
(875,243,100),
(875,244,1),
(875,245,15),
(875,248,5),
(875,289,5),
(875,290,10),
(875,291,100),
(875,292,100),
(875,293,100),
(876,243,100),
(876,244,1),
(876,245,15),
(876,248,10),
(876,289,5),
(876,290,15),
(876,291,100),
(876,292,100),
(876,293,100),
(877,243,150),
(877,244,1),
(877,245,15),
(877,248,15),
(877,289,10),
(877,290,20),
(877,291,100),
(877,292,100),
(877,293,100),
(878,243,175),
(878,244,2),
(878,245,15),
(878,248,20),
(878,289,10),
(878,290,20),
(878,291,100),
(878,292,100),
(878,293,100),
(880,243,200),
(880,244,1),
(880,250,50),
(881,243,500),
(881,244,5),
(881,250,200),
(881,251,30),
(881,252,35),
(881,253,30),
(881,258,30),
(881,261,30),
(881,277,35),
(881,288,5),
(882,243,100),
(882,244,1),
(882,250,125),
(882,257,1),
(882,258,20),
(883,243,100),
(883,244,1),
(883,250,100),
(883,258,20),
(883,263,1),
(884,243,150),
(884,244,1),
(884,250,100),
(884,257,2),
(884,258,20),
(885,243,175),
(885,244,2),
(885,250,125),
(885,258,20),
(885,263,2),
(886,243,100),
(886,244,1),
(886,250,125),
(886,253,20),
(887,243,100),
(887,244,1),
(887,250,100),
(887,253,20),
(888,243,150),
(888,244,1),
(888,250,100),
(888,253,20),
(889,243,175),
(889,244,2),
(889,250,125),
(889,253,20),
(890,243,100),
(890,244,1),
(890,250,125),
(890,261,20),
(891,243,100),
(891,244,1),
(891,250,100),
(891,261,20),
(891,277,25),
(892,243,150),
(892,244,1),
(892,250,100),
(892,261,20),
(892,277,25),
(893,243,175),
(893,244,2),
(893,250,125),
(893,261,20),
(893,277,25),
(894,243,100),
(894,244,1),
(894,250,125),
(894,251,20),
(895,243,100),
(895,244,1),
(895,250,100),
(895,251,20),
(895,252,25),
(896,243,150),
(896,244,1),
(896,250,100),
(896,251,20),
(896,252,25),
(897,243,175),
(897,244,2),
(897,250,125),
(897,251,20),
(897,252,25),
(899,243,200),
(899,244,1),
(899,250,50),
(900,243,500),
(900,244,5),
(900,250,200),
(901,243,100),
(901,244,1),
(901,250,100),
(902,243,100),
(902,244,1),
(902,250,100),
(903,243,150),
(903,244,1),
(903,250,100),
(904,243,175),
(904,244,2),
(904,250,100),
(905,243,100),
(905,244,1),
(905,250,100),
(906,243,100),
(906,244,1),
(906,250,100),
(907,243,150),
(907,244,1),
(907,250,100),
(908,243,175),
(908,244,2),
(908,250,100),
(909,243,100),
(909,244,1),
(909,250,100),
(910,243,100),
(910,244,1),
(910,250,100),
(911,243,150),
(911,244,1),
(911,250,100),
(912,243,175),
(912,244,2),
(912,250,100),
(913,243,100),
(913,244,1),
(913,250,100),
(914,243,100),
(914,244,1),
(914,250,100),
(915,243,150),
(915,244,1),
(915,250,100),
(916,243,175),
(916,244,2),
(916,250,100),
(918,243,200),
(918,244,1),
(918,250,50),
(919,243,500),
(919,244,5),
(919,250,200),
(920,243,100),
(920,244,1),
(920,250,125),
(921,243,100),
(921,244,1),
(921,250,100),
(922,243,150),
(922,244,1),
(922,250,100),
(923,243,175),
(923,244,2),
(923,250,125),
(924,243,100),
(924,244,1),
(924,250,125),
(925,243,100),
(925,244,1),
(925,250,100),
(926,243,150),
(926,244,1),
(926,250,100),
(927,243,175),
(927,244,2),
(927,250,125),
(928,243,100),
(928,244,1),
(928,250,100),
(929,243,100),
(929,244,1),
(929,250,100),
(930,243,150),
(930,244,1),
(930,250,100),
(931,243,175),
(931,244,2),
(931,250,100),
(932,243,100),
(932,244,1),
(932,250,100),
(933,243,100),
(933,244,1),
(933,250,100),
(934,243,150),
(934,244,1),
(934,250,100),
(935,243,175),
(935,244,2),
(935,250,100),
(937,67,15),
(937,68,20),
(937,243,200),
(937,244,1),
(937,250,50),
(937,278,15),
(937,279,5),
(937,280,20),
(938,67,20),
(938,68,25),
(938,243,500),
(938,244,5),
(938,250,200),
(938,278,15),
(938,279,8),
(938,280,25),
(939,68,5),
(939,243,100),
(939,244,1),
(939,250,100),
(939,279,1),
(940,68,10),
(940,243,100),
(940,244,1),
(940,250,100),
(940,279,1),
(941,68,15),
(941,243,150),
(941,244,1),
(941,250,100),
(941,279,2),
(942,68,20),
(942,243,175),
(942,244,2),
(942,250,100),
(942,279,4),
(943,67,5),
(943,243,100),
(943,244,1),
(943,250,100),
(943,279,1),
(944,67,10),
(944,243,100),
(944,244,1),
(944,250,100),
(944,279,1),
(945,67,10),
(945,243,150),
(945,244,1),
(945,250,100),
(945,279,2),
(946,67,15),
(946,243,175),
(946,244,2),
(946,250,100),
(946,279,4),
(947,243,100),
(947,244,1),
(947,250,100),
(947,279,1),
(947,280,10),
(948,243,100),
(948,244,1),
(948,250,125),
(948,279,1),
(948,280,10),
(949,243,150),
(949,244,1),
(949,250,100),
(949,279,2),
(949,280,15),
(950,243,175),
(950,244,2),
(950,250,125),
(950,279,4),
(950,280,20),
(951,243,100),
(951,244,1),
(951,250,100),
(951,278,5),
(951,279,1),
(952,243,100),
(952,244,1),
(952,250,125),
(952,278,5),
(952,279,1),
(953,243,150),
(953,244,1),
(953,250,100),
(953,278,10),
(953,279,2),
(954,243,175),
(954,244,2),
(954,250,125),
(954,278,15),
(954,279,4),
(957,281,5),
(957,282,4),
(957,283,5),
(958,281,20),
(958,282,15),
(958,283,15),
(959,281,5),
(959,282,2),
(959,283,3),
(960,281,5),
(960,282,2),
(960,283,4),
(961,281,5),
(961,282,2),
(961,283,4),
(962,281,5),
(962,282,2),
(962,283,4),
(963,281,10),
(963,282,3),
(963,283,5),
(964,281,10),
(964,282,5),
(964,283,5),
(965,281,10),
(965,282,5),
(965,283,5),
(966,281,15),
(966,282,10),
(966,283,10),
(967,281,15),
(967,282,10),
(967,283,10),
(968,281,15),
(968,282,15),
(968,283,10),
(970,284,5),
(970,285,4),
(970,286,5),
(971,284,20),
(971,285,15),
(971,286,15),
(972,284,5),
(972,285,2),
(972,286,3),
(973,284,5),
(973,285,2),
(973,286,4),
(974,284,5),
(974,285,2),
(974,286,4),
(975,284,5),
(975,285,2),
(975,286,4),
(976,284,10),
(976,285,3),
(976,286,5),
(977,284,10),
(977,285,5),
(977,286,5),
(978,284,10),
(978,285,5),
(978,286,5),
(979,284,15),
(979,285,10),
(979,286,10),
(980,284,15),
(980,285,10),
(980,286,10),
(981,284,15),
(981,285,15),
(981,286,10),
(986,291,500),
(986,292,500),
(986,293,500),
(987,243,100),
(987,244,1),
(992,190,10),
(992,191,10),
(992,192,10),
(992,193,10),
(992,194,10),
(992,195,10),
(992,196,10),
(992,197,10),
(992,199,20),
(992,200,20),
(992,201,10),
(992,202,10),
(992,203,10),
(992,204,1),
(992,205,1),
(992,206,1),
(992,207,1),
(992,287,20),
(993,190,25),
(993,191,25),
(993,192,25),
(993,193,25),
(993,194,25),
(993,195,25),
(993,196,25),
(993,197,25),
(993,199,25),
(993,200,25),
(993,201,25),
(993,202,25),
(993,203,25),
(993,204,1),
(993,205,1),
(993,206,1),
(993,207,1),
(993,287,25),
(994,193,10),
(994,197,10),
(994,206,2),
(995,193,15),
(995,197,15),
(995,206,2),
(996,193,20),
(996,197,20),
(996,206,2),
(997,193,20),
(997,197,20),
(997,206,2),
(998,190,10),
(998,191,10),
(998,199,20),
(998,200,20),
(998,205,2),
(999,190,15),
(999,191,15),
(999,199,25),
(999,200,25),
(999,205,2),
(1000,190,20),
(1000,191,20),
(1000,199,30),
(1000,200,30),
(1000,205,2),
(1001,190,20),
(1001,191,20),
(1001,199,30),
(1001,200,30),
(1001,205,2),
(1002,194,10),
(1002,196,10),
(1002,201,10),
(1002,203,10),
(1002,207,2),
(1003,194,15),
(1003,196,15),
(1003,201,15),
(1003,203,15),
(1003,207,2),
(1004,194,20),
(1004,196,20),
(1004,201,20),
(1004,203,20),
(1004,207,2),
(1005,194,20),
(1005,196,20),
(1005,201,20),
(1005,203,20),
(1005,207,2),
(1006,192,10),
(1006,195,10),
(1006,202,10),
(1006,204,2),
(1006,287,20),
(1007,192,15),
(1007,195,15),
(1007,202,15),
(1007,204,2),
(1007,287,25),
(1008,192,20),
(1008,195,20),
(1008,202,20),
(1008,204,2),
(1008,287,30),
(1009,192,20),
(1009,195,20),
(1009,202,20),
(1009,204,2),
(1009,287,30),
(1013,208,20),
(1018,209,65),
(1019,209,10),
(1020,209,10),
(1021,209,15),
(1022,208,20),
(1023,208,20),
(1024,208,20),
(1025,208,20),
(1032,208,20),
(1037,209,65),
(1038,209,10),
(1039,209,10),
(1040,209,15),
(1041,208,20),
(1042,208,20),
(1043,208,20),
(1044,208,20),
(1051,208,20),
(1056,209,65),
(1057,209,10),
(1058,209,10),
(1059,209,15),
(1060,208,20),
(1061,208,20),
(1062,208,20),
(1063,208,20);
/*!40000 ALTER TABLE `skills_skill_mods` ENABLE KEYS */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
| 14.694467
| 111
| 0.520574
|
455ebcfbe6e377cb57360ec0596e894542519812
| 538
|
py
|
Python
|
LeetCode/Math/Sum/167. Two Sum II - Input array is sorted.py
|
thehanemperor/LeetCode
|
8d120162657a1e29c3e821b51ac4121300fc7a12
|
[
"MIT"
] | null | null | null |
LeetCode/Math/Sum/167. Two Sum II - Input array is sorted.py
|
thehanemperor/LeetCode
|
8d120162657a1e29c3e821b51ac4121300fc7a12
|
[
"MIT"
] | null | null | null |
LeetCode/Math/Sum/167. Two Sum II - Input array is sorted.py
|
thehanemperor/LeetCode
|
8d120162657a1e29c3e821b51ac4121300fc7a12
|
[
"MIT"
] | null | null | null |
# EASY
# Two pointer
# --> if < tar
# <-- if > tar
# Time O(N) Space O(1)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left,right = 0, len(numbers)-1
while left < right:
if numbers[left] + numbers[right] == target:
return [left+1,right+1]
elif numbers[left] + numbers[right] < target:
left += 1
elif numbers[left] + numbers[right] > target:
right -=1
return []
| 28.315789
| 67
| 0.481413
|
a0a146fbae98df42fdfabc1dedaba18093f120a1
| 6,887
|
sql
|
SQL
|
database/publisher.sql
|
directdemocracy-vote/publisher
|
b35ef93427b1ef3c9ddc4a19ac7077990705dbc5
|
[
"MIT"
] | null | null | null |
database/publisher.sql
|
directdemocracy-vote/publisher
|
b35ef93427b1ef3c9ddc4a19ac7077990705dbc5
|
[
"MIT"
] | 10
|
2020-11-29T14:03:43.000Z
|
2021-01-03T11:30:42.000Z
|
database/publisher.sql
|
directdemocracy-vote/publisher
|
b35ef93427b1ef3c9ddc4a19ac7077990705dbc5
|
[
"MIT"
] | null | null | null |
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
CREATE TABLE `area` (
`id` int(11) NOT NULL,
`name` varchar(1024) COLLATE utf8mb4_unicode_ci NOT NULL,
`polygons` multipolygon NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `ballot` (
`id` int(11) NOT NULL,
`referendum` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`stationKey` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`stationSignature` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`revoke` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `ballots` (
`referendum` int(11) NOT NULL,
`station` int(11) NOT NULL,
`key` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`revoke` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `citizen` (
`id` int(11) NOT NULL,
`familyName` varchar(256) COLLATE utf8mb4_unicode_ci NOT NULL,
`givenNames` varchar(256) COLLATE utf8mb4_unicode_ci NOT NULL,
`picture` text CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`home` point NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `corpus` (
`referendum` int(11) NOT NULL,
`citizen` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `endorsement` (
`id` int(11) NOT NULL,
`publicationKey` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`publicationSignature` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`publicationFingerprint` varchar(40) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`revoked` bigint(15) NOT NULL,
`message` varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL,
`comment` varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `participation` (
`referendum` int(11) NOT NULL,
`count` int(11) NOT NULL,
`corpus` int(11) NOT NULL,
`registrations` int(11) NOT NULL,
`rejected` int(11) NOT NULL,
`void` int(11) NOT NULL,
`updated` timestamp NOT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `publication` (
`id` int(11) NOT NULL,
`schema` varchar(256) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`key` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`signature` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`fingerprint` varchar(40) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'sha1 of signature',
`published` bigint(15) NOT NULL,
`expires` bigint(15) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `petition` (
`id` int(11) NOT NULL,
`trustee` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`area` varchar(1024) COLLATE utf8mb4_unicode_ci NOT NULL,
`title` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` text COLLATE utf8mb4_unicode_ci NOT NULL,
`deadline` bigint(15) NOT NULL,
`website` varchar(2048) CHARACTER SET ascii COLLATE ascii_bin NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `referendum` (
`id` int(11) NOT NULL,
`trustee` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`area` varchar(1024) COLLATE utf8mb4_unicode_ci NOT NULL,
`title` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` text COLLATE utf8mb4_unicode_ci NOT NULL,
`question` varchar(128) COLLATE utf8mb4_unicode_ci NOT NULL,
`answers` text COLLATE utf8mb4_unicode_ci NOT NULL,
`deadline` bigint(15) NOT NULL,
`website` varchar(2048) CHARACTER SET ascii COLLATE ascii_bin NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `registration` (
`id` int(11) NOT NULL,
`referendum` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`stationKey` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`stationSignature` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`revoke` tinyint(1) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `registrations` (
`referendum` int(11) NOT NULL,
`station` int(11) NOT NULL,
`citizen` int(11) NOT NULL,
`published` bigint(15) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `results` (
`referendum` int(11) NOT NULL,
`answer` varchar(256) COLLATE utf8mb4_unicode_ci NOT NULL,
`count` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `station` (
`id` int(11) NOT NULL,
`key` varchar(512) COLLATE utf8mb4_unicode_ci NOT NULL,
`url` varchar(2048) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `stations` (
`id` int(11) NOT NULL,
`referendum` int(11) NOT NULL,
`registrations_count` int(11) NOT NULL,
`ballots_count` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `trustee` (
`id` int(11) NOT NULL,
`key` varchar(512) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`url` varchar(2048) CHARACTER SET ascii COLLATE ascii_bin NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `area`
ADD PRIMARY KEY (`id`);
ALTER TABLE `ballot`
ADD PRIMARY KEY (`id`);
ALTER TABLE `ballots`
ADD KEY `referendum` (`referendum`),
ADD KEY `station` (`station`);
ALTER TABLE `citizen`
ADD PRIMARY KEY (`id`);
ALTER TABLE `corpus`
ADD KEY `referendum` (`referendum`),
ADD KEY `citizen` (`citizen`);
ALTER TABLE `endorsement`
ADD PRIMARY KEY (`id`),
ADD KEY `publicationFingerprint` (`publicationFingerprint`);
ALTER TABLE `participation`
ADD PRIMARY KEY `referendum` (`referendum`);
ALTER TABLE `publication`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `fingerprint` (`fingerprint`);
ALTER TABLE `petition`
ADD PRIMARY KEY (`id`);
ALTER TABLE `referendum`
ADD PRIMARY KEY (`id`);
ALTER TABLE `registration`
ADD PRIMARY KEY (`id`);
ALTER TABLE `registrations`
ADD KEY `referendum` (`referendum`),
ADD KEY `station` (`station`),
ADD KEY `citizen` (`citizen`);
ALTER TABLE `results`
ADD KEY `referendum` (`referendum`);
ALTER TABLE `station`
ADD PRIMARY KEY (`id`);
ALTER TABLE `stations`
ADD KEY `id` (`id`),
ADD KEY `referendum` (`referendum`);
ALTER TABLE `trustee`
ADD PRIMARY KEY (`id`);
ALTER TABLE `area`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `publication`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `station`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `trustee`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
| 34.60804
| 103
| 0.74706
|
ae7a765e9ece5605cfea60f186cae78473f80481
| 1,384
|
sh
|
Shell
|
update-dependabot-pr/main.sh
|
taiki-e/github-actions
|
308cd9cfc53d5f7318d6b68c8de3e18284414a27
|
[
"Apache-2.0",
"MIT"
] | 1
|
2022-01-20T13:13:17.000Z
|
2022-01-20T13:13:17.000Z
|
update-dependabot-pr/main.sh
|
taiki-e/github-actions
|
308cd9cfc53d5f7318d6b68c8de3e18284414a27
|
[
"Apache-2.0",
"MIT"
] | 3
|
2020-12-19T03:19:43.000Z
|
2021-05-12T05:41:17.000Z
|
update-dependabot-pr/main.sh
|
taiki-e/github-actions
|
308cd9cfc53d5f7318d6b68c8de3e18284414a27
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
header="Accept: application/vnd.github.v3+json"
bail() {
echo "::error::$*"
exit 1
}
# https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows#pull_request
if [[ ! "${GITHUB_REF:?}" =~ ^refs/pull/[0-9]+/merge$ ]]; then
bail "GITHUB_REF should be 'refs/pull/[0-9]+/merge'"
fi
pr_number="${GITHUB_REF#refs/pull/}"
pr_number="${pr_number%/merge}"
pr_url="https://api.github.com/repos/${GITHUB_REPOSITORY:?}/pulls/${pr_number}"
pr_data=$(curl --proto '=https' --tlsv1.2 -fsSL --retry 10 --retry-connrefused -H "${header}" "${pr_url}")
pr_url=$(echo "${pr_data}" | jq -r '.url')
if [[ $(echo "${pr_data}" | jq -r '.user.login') != "dependabot[bot]" ]]; then
bail "this PR created by a user other than 'dependabot[bot]'"
fi
commits_url=$(echo "${pr_data}" | jq -r '.commits_url')
message=$(
curl --proto '=https' --tlsv1.2 -fsSL --retry 10 --retry-connrefused "${commits_url}" \
| jq -r '.[0].commit.message' \
| sed '1,2d' \
| sed -z 's/\n/\\n/g' \
| sed -e 's/\\n$//'
)
if [[ -z "${GITHUB_TOKEN:-}" ]]; then
bail "GITHUB_TOKEN not set"
fi
curl --proto '=https' --tlsv1.2 -fsSL --retry 10 --retry-connrefused -X PATCH -H "${header}" "${pr_url}" \
-H "Authorization: token ${GITHUB_TOKEN}" \
-d "{ \"body\": \"${message}\" }" >/dev/null
| 32.952381
| 110
| 0.598988
|
afa1cd8d10ec4805d27fab6291c2e5531f5c62a3
| 74
|
py
|
Python
|
main.py
|
M-Mabrouk/GhostWriter
|
07e5fa1cef4cd0e75559edfaf3d91e5a8b442f7f
|
[
"MIT"
] | 2
|
2020-02-27T07:21:33.000Z
|
2020-06-24T12:54:30.000Z
|
main.py
|
M-Mabrouk/GhostWriter
|
07e5fa1cef4cd0e75559edfaf3d91e5a8b442f7f
|
[
"MIT"
] | null | null | null |
main.py
|
M-Mabrouk/GhostWriter
|
07e5fa1cef4cd0e75559edfaf3d91e5a8b442f7f
|
[
"MIT"
] | 1
|
2020-06-27T13:30:20.000Z
|
2020-06-27T13:30:20.000Z
|
from src.tracker import Tracker
if __name__ == "__main__":
Tracker()
| 14.8
| 31
| 0.702703
|
b74852cf6b49fdd7a4548f246d1826c40eeb58f6
| 1,515
|
cs
|
C#
|
MQTTnet.Core/Server/MqttTopicFilterComparer.cs
|
Zazzmatazz/MQTTnet
|
21130446c227e8e274c9916449c0f8816fec5974
|
[
"MIT"
] | null | null | null |
MQTTnet.Core/Server/MqttTopicFilterComparer.cs
|
Zazzmatazz/MQTTnet
|
21130446c227e8e274c9916449c0f8816fec5974
|
[
"MIT"
] | null | null | null |
MQTTnet.Core/Server/MqttTopicFilterComparer.cs
|
Zazzmatazz/MQTTnet
|
21130446c227e8e274c9916449c0f8816fec5974
|
[
"MIT"
] | null | null | null |
using System;
namespace MQTTnet.Core.Server
{
public static class MqttTopicFilterComparer
{
private const char TopicLevelSeparator = '/';
public static bool IsMatch(string topic, string filter)
{
if (topic == null) throw new ArgumentNullException(nameof(topic));
if (filter == null) throw new ArgumentNullException(nameof(filter));
if (string.Equals(topic, filter, StringComparison.Ordinal))
{
return true;
}
var fragmentsTopic = topic.Split(new[] { TopicLevelSeparator }, StringSplitOptions.None);
var fragmentsFilter = filter.Split(new[] { TopicLevelSeparator }, StringSplitOptions.None);
for (var i = 0; i < fragmentsFilter.Length; i++)
{
if (fragmentsFilter[i] == "+")
{
continue;
}
if (fragmentsFilter[i] == "#" && i == fragmentsFilter.Length - 1)
{
return true;
}
if (i >= fragmentsTopic.Length)
{
return false;
}
if (!string.Equals(fragmentsFilter[i], fragmentsTopic[i]))
{
return false;
}
}
if (fragmentsTopic.Length > fragmentsFilter.Length)
{
return false;
}
return true;
}
}
}
| 28.055556
| 103
| 0.479208
|
9857a2a11a85bd3799afbc1815ac08ab2618192d
| 40
|
sql
|
SQL
|
veterinary/infraestructura/src/main/resources/sql/cita/listarById.sql
|
Richardace/adn-veterinary
|
e195e0e2499e1712ac3d8e507a6724b56b3a3385
|
[
"Apache-2.0"
] | null | null | null |
veterinary/infraestructura/src/main/resources/sql/cita/listarById.sql
|
Richardace/adn-veterinary
|
e195e0e2499e1712ac3d8e507a6724b56b3a3385
|
[
"Apache-2.0"
] | null | null | null |
veterinary/infraestructura/src/main/resources/sql/cita/listarById.sql
|
Richardace/adn-veterinary
|
e195e0e2499e1712ac3d8e507a6724b56b3a3385
|
[
"Apache-2.0"
] | null | null | null |
select *
from cita
where idUsuario = :id
| 13.333333
| 21
| 0.75
|
538a6b4949934739aea5acc6e318b996a222ae5a
| 501
|
ps1
|
PowerShell
|
delivery/windows-powershell/deliver.ps1
|
vukhoa30/pulse-community
|
457451e502cdfb21b32f22b7ef792b2045b86cb2
|
[
"MIT"
] | null | null | null |
delivery/windows-powershell/deliver.ps1
|
vukhoa30/pulse-community
|
457451e502cdfb21b32f22b7ef792b2045b86cb2
|
[
"MIT"
] | null | null | null |
delivery/windows-powershell/deliver.ps1
|
vukhoa30/pulse-community
|
457451e502cdfb21b32f22b7ef792b2045b86cb2
|
[
"MIT"
] | null | null | null |
$url = '<ENTER YOUR PARSER PULSE WEBHOOK HERE>'
$content = Get-Content "<ENTER YOUR RESULTS FILE NAME HERE>" -Raw
$bytes = [System.Text.Encoding]::UTF8.GetBytes($content)
$payload = [System.Convert]::ToBase64String($bytes)
$body = @{
'projectId' = '<ENTER YOUR QTEST PROJECT ID HERE>'
'testcycle' = '<ENTER YOUR QTEST TEST CYCLE ID HERE>'
'result' = $payload
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-RestMethod -Body $body -Method 'Post' -Uri $url
| 35.785714
| 79
| 0.718563
|
dd6feb3ff87a70fb5039d1b45613d8591d1efad0
| 11,094
|
java
|
Java
|
californium/src/main/java/ch/ethz/inf/vs/californium/coap/ObservingManager.java
|
fidakhattak/Californium-CoAP-Client
|
0a1e0226efa32c5048d25c1724f0b5a4ab3c0168
|
[
"BSD-3-Clause"
] | 1
|
2020-09-09T10:47:38.000Z
|
2020-09-09T10:47:38.000Z
|
californium/src/main/java/ch/ethz/inf/vs/californium/coap/ObservingManager.java
|
fidakhattak/CoAPClient
|
ea5f75b920e40e529931a72b999158c28ae60ad0
|
[
"BSD-3-Clause"
] | null | null | null |
californium/src/main/java/ch/ethz/inf/vs/californium/coap/ObservingManager.java
|
fidakhattak/CoAPClient
|
ea5f75b920e40e529931a72b999158c28ae60ad0
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************************************************************
* Copyright (c) 2012, Institute for Pervasive Computing, ETH Zurich.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Californium (Cf) CoAP framework.
******************************************************************************/
package ch.ethz.inf.vs.californium.coap;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import ch.ethz.inf.vs.californium.coap.Message.messageType;
import ch.ethz.inf.vs.californium.endpoint.LocalResource;
import ch.ethz.inf.vs.californium.layers.TransactionLayer;
import ch.ethz.inf.vs.californium.util.Properties;
/**
* The TokenManager stores all tokens currently used in transfers. New transfers
* can acquire unique tokens from the manager.
*
* @author Matthias Kovatsch
*/
public class ObservingManager {
// Logging /////////////////////////////////////////////////////////////////////
private static final Logger LOG = Logger.getLogger(ObservingManager.class.getName());
// Inner class /////////////////////////////////////////////////////////////////
private class ObservingRelationship {
public String clientID;
public String resourcePath;
public GETRequest request;
public int lastMID;
public ObservingRelationship(GETRequest request) {
request.setMID(-1);
this.clientID = request.getPeerAddress().toString();
this.resourcePath = request.getUriPath();
this.request = request;
this.lastMID = -1;
}
}
// Static Attributes ///////////////////////////////////////////////////////////
private static ObservingManager singleton = new ObservingManager();
// Members /////////////////////////////////////////////////////////////////////
/** Maps a resource path string to the resource's observers stored by client address string. */
private Map<String, Map<String, ObservingRelationship>> observersByResource = new HashMap<String, Map<String, ObservingRelationship>>();
/** Maps a peer address string to the clients relationships stored by resource path. */
private Map<String, Map<String, ObservingRelationship>> observersByClient = new HashMap<String, Map<String, ObservingRelationship>>();
private int checkInterval = Properties.std.getInt("OBSERVING_REFRESH_INTERVAL");
private Map<String, Integer> intervalByResource = new HashMap<String, Integer>();
// Constructors ////////////////////////////////////////////////////////////////
/**
* Default singleton constructor.
*/
private ObservingManager() {
}
public static ObservingManager getInstance() {
return singleton;
}
// Methods /////////////////////////////////////////////////////////////////////
public void setRefreshInterval(int interval) {
this.checkInterval = interval;
}
public void notifyObservers(LocalResource resource) {
Map<String, ObservingRelationship> resourceObservers = observersByResource.get(resource.getPath());
if (resourceObservers!=null && resourceObservers.size()>0) {
LOG.info(String.format("Notifying observers: %d @ %s", resourceObservers.size(), resource.getPath()));
int check = -1;
// get/initialize
if (!intervalByResource.containsKey(resource.getPath())) {
check = checkInterval;
} else {
check = intervalByResource.get(resource.getPath()) - 1;
}
// update
if (check <= 0) {
intervalByResource.put(resource.getPath(), checkInterval);
LOG.info(String.format("Refreshing observing relationship: %s", resource.getPath()));
} else {
intervalByResource.put(resource.getPath(), check);
}
for (ObservingRelationship observer : resourceObservers.values()) {
GETRequest request = observer.request;
// check
if (check<=0) {
request.setType(messageType.CON);
} else {
request.setType(messageType.NON);
}
// execute
resource.performGET(request);
prepareResponse(request);
request.sendResponse();
}
}
}
private void prepareResponse(Request request) {
// consecutive response require new MID that must be stored for RST matching
if (request.getResponse().getMID()==-1) {
request.getResponse().setMID(TransactionLayer.nextMessageID());
}
// 16-bit second counter
int secs = (int) ((System.currentTimeMillis() - request.startTime) / 1000) & 0xFFFF;
request.getResponse().setOption(new Option(secs, OptionNumberRegistry.OBSERVE));
// store MID for RST matching
updateLastMID(request.getPeerAddress().toString(), request.getUriPath(), request.getResponse().getMID());
}
public synchronized void addObserver(GETRequest request, LocalResource resource) {
ObservingRelationship toAdd = new ObservingRelationship(request);
// get clients map for the given resource path
Map<String, ObservingRelationship> resourceObservers = observersByResource.get(resource.getPath());
if (resourceObservers==null) {
// lazy creation
resourceObservers = new HashMap<String, ObservingRelationship>();
observersByResource.put(resource.getPath(), resourceObservers);
}
// get resource map for given client address
Map<String, ObservingRelationship> clientObservees = observersByClient.get(request.getPeerAddress().toString());
if (clientObservees==null) {
// lazy creation
clientObservees = new HashMap<String, ObservingRelationship>();
observersByClient.put(request.getPeerAddress().toString(), clientObservees);
}
// save relationship for notifications triggered by resource
resourceObservers.put(request.getPeerAddress().toString(), toAdd);
// save relationship for actions triggered by client
clientObservees.put(resource.getPath(), toAdd);
LOG.info(String.format("Established observing relationship: %s @ %s", request.getPeerAddress().toString(), resource.getPath()));
// update response
request.getResponse().setOption(new Option(0, OptionNumberRegistry.OBSERVE));
}
public synchronized void removeObserver(String clientID) {
Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID);
if (clientObservees!=null) {
for (Map<String, ObservingRelationship> entry : observersByResource.values()) {
entry.remove(clientID);
}
observersByClient.remove(clientID);
LOG.info(String.format("Terminated all observing relationships for client: %s", clientID));
}
}
/**
* Remove an observer by missing Observe option in GET.
*
* @param clientID the peer address as string
* @param resource the resource to un-observe.
*/
public void removeObserver(String clientID, LocalResource resource) {
Map<String, ObservingRelationship> resourceObservers = observersByResource.get(resource.getPath());
Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID);
if (resourceObservers!=null && clientObservees!=null) {
if (resourceObservers.remove(clientID)!=null && clientObservees.remove(resource.getPath())!=null) {
LOG.info(String.format("Terminated observing relationship by GET: %s @ %s", clientID, resource.getPath()));
return;
}
}
// should not be called if not existent
LOG.warning(String.format("Cannot find observing relationship: %s @ %s", clientID, resource.getPath()));
}
/**
* Remove an observer by MID from RST.
*
* @param clientID the peer address as string
* @param mid the MID from the RST
*/
public void removeObserver(String clientID, int mid) {
ObservingRelationship toRemove = null;
Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID);
if (clientObservees!=null) {
for (ObservingRelationship entry : clientObservees.values()) {
if (mid==entry.lastMID && clientID.equals(entry.clientID)) {
// found it
toRemove = entry;
break;
}
}
}
if (toRemove!=null) {
Map<String, ObservingRelationship> resourceObservers = observersByResource.get(toRemove.resourcePath);
// FIXME Inconsistent state check
if (resourceObservers==null) {
LOG.severe(String.format("FIXME: ObservingManager has clientObservee, but no resourceObservers (%s @ %s)", clientID, toRemove.resourcePath));
}
if (resourceObservers.remove(clientID)!=null && clientObservees.remove(toRemove.resourcePath)!=null) {
LOG.info(String.format("Terminated observing relationship by RST: %s @ %s", clientID, toRemove.resourcePath));
return;
}
}
LOG.warning(String.format("Cannot find observing relationship by MID: %s|%d", clientID, mid));
}
public boolean isObserved(String clientID, LocalResource resource) {
return observersByClient.containsKey(clientID) &&
observersByClient.get(clientID).containsKey(resource.getPath());
}
public void updateLastMID(String clientID, String path, int mid) {
Map<String, ObservingRelationship> clientObservees = observersByClient.get(clientID);
if (clientObservees!=null) {
ObservingRelationship toUpdate = clientObservees.get(path);
if (toUpdate!=null) {
toUpdate.lastMID = mid;
LOG.finer(String.format("Updated last MID for observing relationship: %s @ %s", clientID, toUpdate.resourcePath));
return;
}
}
LOG.warning(String.format("Cannot find observing relationship to update MID: %s @ %s", clientID, path));
}
}
| 37.353535
| 146
| 0.67532
|
c98d52655da6513ffbcc73feb2a6bd17bbfe94df
| 1,642
|
ts
|
TypeScript
|
src/utility/Waiter.ts
|
xyyaya/framework
|
df6c4850a43964078ebd052d9a4f26ef46af01b8
|
[
"WTFPL"
] | null | null | null |
src/utility/Waiter.ts
|
xyyaya/framework
|
df6c4850a43964078ebd052d9a4f26ef46af01b8
|
[
"WTFPL"
] | null | null | null |
src/utility/Waiter.ts
|
xyyaya/framework
|
df6c4850a43964078ebd052d9a4f26ef46af01b8
|
[
"WTFPL"
] | null | null | null |
import {TimeoutError} from './TimeoutError';
class Waiter<T> {
constructor() {
this.pool_ = new Map();
this.id_ = 0;
}
wait(ttlMs = 1000) {
const id = ++this.id_;
const timer = setTimeout(() => {
if (this.pool_.has(id)) {
const info = this.pool_.get(id);
info.reject(new TimeoutError());
}
}, ttlMs);
return {
id,
promise: new Promise<T>((resolve, reject) => {
this.pool_.set(id, { resolve, reject, timer });
}),
}
}
emit(id: number, result: T) {
if (this.pool_.has(id)) {
const info = this.pool_.get(id);
clearTimeout(info.timer);
this.pool_.delete(id);
info.resolve(result);
}
if (!this.pool_.size && this.allStoppedCallback_) {
clearTimeout(this.stopTimeoutTimer_);
this.allStoppedCallback_();
}
}
emitError(id: number, error: Error) {
if (this.pool_.has(id)) {
const info = this.pool_.get(id);
clearTimeout(info.timer);
this.pool_.delete(id);
info.reject(error);
}
}
async waitForAll(ttlMS: number) {
if (!this.pool_.size)
return;
const promise = new Promise<void>((resolve) => {
this.allStoppedCallback_ = resolve;
});
this.stopTimeoutTimer_ = setTimeout(() => {
if (this.allStoppedCallback_)
this.allStoppedCallback_();
}, ttlMS);
return promise;
}
private pool_: Map<number, {resolve: (value: T) => void, reject: (error: Error) => void, timer: NodeJS.Timeout}>;
private allStoppedCallback_: () => void;
private stopTimeoutTimer_: NodeJS.Timer;
private id_: number;
}
export {Waiter}
| 24.147059
| 115
| 0.590134
|
e297ad47ba328fc2705f080ba028888d3103356e
| 2,031
|
js
|
JavaScript
|
commands/moderation/embed.js
|
Khanmanan/Hope
|
89be6a81bda343e0e7a3f2007e821e01eb757bd0
|
[
"Apache-2.0"
] | 3
|
2021-07-11T08:52:01.000Z
|
2021-07-28T12:18:46.000Z
|
commands/moderation/embed.js
|
Khanmanan/Hope
|
89be6a81bda343e0e7a3f2007e821e01eb757bd0
|
[
"Apache-2.0"
] | null | null | null |
commands/moderation/embed.js
|
Khanmanan/Hope
|
89be6a81bda343e0e7a3f2007e821e01eb757bd0
|
[
"Apache-2.0"
] | null | null | null |
const { MessageEmbed } = require('discord.js');
const Command = require('../../structures/Command');
module.exports = class Embed extends Command {
constructor(...args) {
super(...args, {
name: 'embed',
aliases: ['embed-type', 'embed-announce'],
description: 'Says A Message',
category: 'moderation',
usage: '[channel name] (message)',
accessableby: 'Administrator or Hope Bot Access'
});
};
async run(message, args) {
try {
let role = message.guild.roles.cache.find(r => r.name.toLowerCase() === 'hope bot access');
if (!role) return message.channel.send('**Role Not Found - Hope Bot Access**!');
if (!message.member.roles.cache.has(role.id) && !message.member.permissions.has('ADMINISTRATOR')) return message.channel.send('**You Are Missing Permissions To Execute This Command**!');
if (!args[0]) return message.channel.send('**Please Enter A Channel Name or ID!**');
let channel = message.mentions.channels.first() || message.guild.channels.cache.find(r => r.name.toLowerCase() === args[0].toLowerCase() && r.type === 'text') || message.guild.channels.cache.get(args[0]);
if (!channel) return message.channel.send('**Channel Not Found!**');
let content = args.slice(1).join(' ');
let attachments = message.attachments;
if (!content && attachments.size === 0) return message.channel.send('**Please Enter A Message To Announce!**');
const embed = new MessageEmbed()
.setColor('GREEN')
.setDescription(content)
if (attachments.size !== 0) embed.setImage(attachments.map(r => r.attachment).toString());
return channel.send({ embed: embed });
} catch (error) {
console.error(error);
return message.channel.send(`An Error Occured: \`${error.message}\`!`);
};
};
};
| 52.076923
| 217
| 0.573117
|
7293467c91f07d2001099042f87927ede789163b
| 1,220
|
cs
|
C#
|
R7.HelpDesk/Controls/Comments.ascx.designer.cs
|
volgau/R7.HelpDesk
|
7d6137fb9ef87fabaf5a0e1d83dd90b8679765aa
|
[
"MIT"
] | 2
|
2019-01-13T15:54:20.000Z
|
2021-02-11T07:04:13.000Z
|
R7.HelpDesk/Controls/Comments.ascx.designer.cs
|
roman-yagodin/R7.HelpDesk
|
7d6137fb9ef87fabaf5a0e1d83dd90b8679765aa
|
[
"MIT"
] | 3
|
2015-01-18T16:17:05.000Z
|
2015-01-18T16:28:26.000Z
|
R7.HelpDesk/Controls/Comments.ascx.designer.cs
|
volgau/R7.HelpDesk
|
7d6137fb9ef87fabaf5a0e1d83dd90b8679765aa
|
[
"MIT"
] | 2
|
2019-10-03T13:46:06.000Z
|
2020-06-20T11:53:34.000Z
|
using System;
using System.Web.UI.WebControls;
namespace R7.HelpDesk
{
public partial class Comments
{
protected Panel pnlInsertComment;
protected Label lblAttachFile1;
protected FileUpload TicketFileUpload;
protected Label lblAttachFile2;
protected FileUpload fuAttachment;
protected Panel pnlTableHeader;
protected Panel pnlExistingComments;
protected Panel pnlEditComment;
protected CheckBox chkCommentVisible;
protected CheckBox chkCommentVisibleEdit;
protected LinkButton lnkDelete;
protected Image Image5;
protected LinkButton lnkUpdate;
protected Image Image4;
protected Panel pnlDisplayFile;
protected Panel pnlAttachFile;
protected Image imgDelete;
protected LinkButton lnkUpdateRequestor;
protected Image ImgEmailUser;
protected Button btnInsertCommentAndEmail;
protected TextBox txtComment;
protected Label lblError;
protected GridView gvComments;
protected Label lblDetailID;
protected TextBox txtDescription;
protected Label lblDisplayUser;
protected Label lblInsertDate;
protected LinkButton lnkFileAttachment;
//protected HyperLink lnkFileAttachment;
protected Label lblErrorEditComment;
}
}
| 27.111111
| 45
| 0.787705
|
f61a192ee228020fdbfb4c71a45f0de75b9c288e
| 603
|
hpp
|
C++
|
Board.hpp
|
noahaim/Ex2_b
|
4037e51ece5a58c8e1125e3cda262d299ed90037
|
[
"MIT"
] | null | null | null |
Board.hpp
|
noahaim/Ex2_b
|
4037e51ece5a58c8e1125e3cda262d299ed90037
|
[
"MIT"
] | null | null | null |
Board.hpp
|
noahaim/Ex2_b
|
4037e51ece5a58c8e1125e3cda262d299ed90037
|
[
"MIT"
] | null | null | null |
#include <string>
#include "Direction.hpp"
#include <map>
#define MAX_VALUE 4294967295
namespace ariel
{
class Board{
uint maxRow;
uint maxColumns;
uint minRow;
uint minColumn;
std::map<uint,std::map<uint,char>> board;
public:
Board(){
maxRow=0;
maxColumns=0;
minRow=MAX_VALUE;
minColumn=MAX_VALUE;
}
void post(uint row,uint column,Direction direction,std::string const &ad );
std::string read(uint row,uint column,Direction direction,uint len);
void show();
};
}
| 25.125
| 83
| 0.58209
|
a14e754840d24d5570fe7972041c92ebe654e1a4
| 4,702
|
kt
|
Kotlin
|
android/app/src/main/java/bg/crc/roamingapp/models/reportromaningzone/Bulgaria.kt
|
governmentbg/crc-roaming
|
afba722d8d25d2cd6bd1806378bc06a19b2c4c73
|
[
"Apache-2.0"
] | null | null | null |
android/app/src/main/java/bg/crc/roamingapp/models/reportromaningzone/Bulgaria.kt
|
governmentbg/crc-roaming
|
afba722d8d25d2cd6bd1806378bc06a19b2c4c73
|
[
"Apache-2.0"
] | null | null | null |
android/app/src/main/java/bg/crc/roamingapp/models/reportromaningzone/Bulgaria.kt
|
governmentbg/crc-roaming
|
afba722d8d25d2cd6bd1806378bc06a19b2c4c73
|
[
"Apache-2.0"
] | 1
|
2021-12-30T10:00:30.000Z
|
2021-12-30T10:00:30.000Z
|
package bg.crc.roamingapp.models.reportromaningzone
object Bulgaria {
val lat: DoubleArray = doubleArrayOf(
44.234862,
44.121071,
44.054292,
43.815290,
43.622034,
43.449791,
43.397904,
43.355117,
43.162424,
42.997067,
42.923964,
42.907930,
42.822828,
42.571180,
42.485202,
42.320093,
42.161927,
42.042952,
41.994962,
41.751043,
41.320756,
41.301562,
41.381761,
41.367580,
41.448267,
41.419816,
41.470313,
41.515666,
41.514631,
41.420373,
41.343066,
41.386349,
41.276329,
41.214273,
41.299241,
41.360593,
41.442303,
41.623012,
41.711938,
41.754122,
41.687416,
41.821713,
41.820050,
41.915170,
41.983524,
41.936421,
41.992998,
42.086932,
42.052258,
42.093662,
41.912820,
41.961904,
41.916642,
41.971267,
41.979969,
41.966067,
43.746095,
43.744173,
43.772422,
43.849406,
44.011292,
43.972692,
44.062494,
44.028014,
44.030100,
44.127639,
44.148001,
44.082203,
44.042430,
43.971825,
43.792200,
43.707209,
43.687665,
43.648325,
43.631725,
43.716539,
43.699865,
43.741854,
43.704246,
43.781608,
43.707110,
43.692678,
43.767875,
43.807394,
43.789242,
43.852859,
43.851838,
43.789158,
43.840397,
43.941049,
44.008758,
44.021559,
44.101069,
44.140439,
44.209315,
44.234975,
44.234862 // first and last point are the same
)
val lng: DoubleArray = doubleArrayOf(
22.653506,
22.564233,
22.396196,
22.296456,
22.427824,
22.490331,
22.640199,
22.767097,
22.944846,
22.752508,
22.716031,
22.477752,
22.367107,
22.406613,
22.503355,
22.349297,
22.444998,
22.660537,
22.841626,
22.934866,
22.918439,
23.234166,
23.304592,
23.594402,
23.916063,
23.990275,
24.084118,
24.303710,
24.520075,
24.616740,
24.799178,
24.897937,
25.222443,
25.317554,
25.946688,
26.171446,
26.224028,
26.169439,
26.096446,
26.187972,
26.365236,
26.392929,
26.597246,
26.598737,
26.656477,
26.773300,
26.987976,
27.081731,
27.216208,
27.300242,
27.526194,
27.715099,
27.848607,
28.059805,
28.518008,
28.669972,
28.750047,
28.444841,
28.221728,
28.000334,
27.943612,
27.735021,
27.666016,
27.574727,
27.448619,
27.289090,
26.991690,
26.710609,
26.362905,
26.087477,
25.884131,
25.758272,
25.623827,
25.574571,
25.359740,
25.189075,
25.113015,
24.973671,
24.727589,
24.560451,
24.319712,
24.203514,
23.932592,
23.724982,
23.617817,
23.503407,
23.274273,
23.097101,
22.892795,
22.847801,
22.939353,
23.073990,
23.111285,
22.960658,
22.817508,
22.658023,
22.653506 // first and last point are the same
)
}
| 23.277228
| 58
| 0.367078
|