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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6db0e71fcf526ca2024b3d6680fd23e6dd362199
| 2,495
|
c
|
C
|
tld/src/file-name.c
|
dj3vande/tendra
|
86981ad5574f55821853e3bdf5f82e373f91edb2
|
[
"BSD-3-Clause"
] | null | null | null |
tld/src/file-name.c
|
dj3vande/tendra
|
86981ad5574f55821853e3bdf5f82e373f91edb2
|
[
"BSD-3-Clause"
] | null | null | null |
tld/src/file-name.c
|
dj3vande/tendra
|
86981ad5574f55821853e3bdf5f82e373f91edb2
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2002-2011, The TenDRA Project.
* Copyright 1997, United Kingdom Secretary of State for Defence.
*
* See doc/copyright/ for the full copyright terms.
*/
/*
* file-name.c - File name manipulation routines.
*
* This file implements the file name manipulation facility specified in the
* file "file-name.h". See that file for more details.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stddef.h>
#include <string.h>
#include <shared/bool.h>
#include <shared/check.h>
#include <exds/common.h>
#include <exds/cstring.h>
#include "file-name.h"
char *
file_name_basename(char * path)
{
char * last = strrchr(path, '/');
if (last) {
return cstring_duplicate(last + 1);
} else {
return cstring_duplicate(path);
}
}
char *
file_name_dirname(char * path)
{
char * last = strrchr(path, '/');
if (last) {
return cstring_duplicate_prefix(path, (size_t) (last - path));
} else {
return cstring_duplicate(path);
}
}
char *
file_name_expand(const char * dir, const char * name,
const char * suffix)
{
size_t dir_length = strlen(dir);
size_t name_length = strlen(name);
size_t suf_length = (suffix ?(strlen(suffix)): 0);
size_t suf_extra = (size_t) (suffix ? 1 : 0);
size_t extra;
size_t length;
char * path;
char * tmp;
if ((dir_length > 0) && (dir[dir_length - 1]!= '/')) {
extra = 1;
} else {
extra = 0;
}
length = (dir_length + extra + name_length + suf_extra + suf_length + 1);
path = ALLOCATE_VECTOR(char, length);
tmp = path;
if (dir_length > 0) {
IGNORE memcpy((void *)tmp,(void *)dir,(size_t)dir_length);
tmp += dir_length;
if (dir[dir_length - 1]!= '/') {
tmp[0] = '/';
tmp++;
}
}
IGNORE memcpy((void *)tmp,(void *)name,(size_t)name_length);
tmp += name_length;
if (suffix) {
tmp[0] = '.';
tmp++;
IGNORE memcpy((void *)tmp,(void *)suffix,(size_t)suf_length);
tmp += suf_length;
}
tmp[0] = '\0';
return path;
}
bool
file_name_is_basename(const char * path)
{
return !strchr(path, '/');
}
bool
file_name_is_absolute(char * path)
{
return path[0] == '/';
}
void
file_name_populate(char * path)
{
char * new_path = cstring_duplicate(path);
char * tmp = strchr(new_path, '/');
if (tmp) {
do {
*tmp = '\0';
IGNORE mkdir(new_path, 0755);
*tmp = '/';
} while ((tmp = strchr(tmp + 1, '/')) != NULL);
}
DEALLOCATE(new_path);
}
| 20.120968
| 77
| 0.606012
|
6d38919e074323eda22663dc3082c775eeabcecd
| 2,522
|
tsx
|
TypeScript
|
src/formatters/useFormattedDateTime.test.tsx
|
LightspeedServices/support-zaf-app-toolbox
|
958b93ece53ad91fd57dadcb753506854572e1b3
|
[
"Apache-2.0"
] | null | null | null |
src/formatters/useFormattedDateTime.test.tsx
|
LightspeedServices/support-zaf-app-toolbox
|
958b93ece53ad91fd57dadcb753506854572e1b3
|
[
"Apache-2.0"
] | 1
|
2021-11-11T19:32:55.000Z
|
2021-11-11T19:32:55.000Z
|
src/formatters/useFormattedDateTime.test.tsx
|
LightspeedServices/support-zaf-app-toolbox
|
958b93ece53ad91fd57dadcb753506854572e1b3
|
[
"Apache-2.0"
] | 1
|
2021-11-02T09:28:55.000Z
|
2021-11-02T09:28:55.000Z
|
import * as React from 'react'
import {mount, ReactWrapper} from 'enzyme'
import useFormattedDateTime from './useFormattedDateTime'
import {ZAFClientContextProvider} from '../providers/ZAFClientContext'
import {Client, ClientInvokeOptions} from '../types'
import flushPromises from '../test/flushPromises'
import {act} from "react-dom/test-utils";
const date = new Date('2019-07-22 09:30:56')
const formatDefault = (datetime: Date) =>
`${datetime.toLocaleDateString()} ${datetime.toLocaleTimeString()}`
const Dummy = () => {
const formattedDateTime = useFormattedDateTime(date)
return <div>{formattedDateTime}</div>
}
const findDivTextInTree = (tree: ReactWrapper) => {
return tree
.find(Dummy)
.find('div')
.text()
}
const initTree = (client: Client) =>
mount(
<ZAFClientContextProvider value={client}>
<Dummy />
</ZAFClientContextProvider>,
)
describe('useFormattedDateTime', () => {
test('should return formatted date time in local timezone', async () => {
// @ts-ignore
const client: Client = {
// @ts-ignore
invoke: jest.fn(
() =>
new Promise<{formatDateAndTime: string | null; errors: object}>(
(res) => res({formatDateAndTime: '22/07/2019 09:30', errors: {}}),
),
),
}
const tree = initTree(client)
expect(client.invoke).toHaveBeenCalledWith(
ClientInvokeOptions.formatDateAndTime,
date,
'account',
)
let divText = findDivTextInTree(tree)
expect(divText).toEqual('')
await act(async () => {
await flushPromises()
})
tree.update()
divText = findDivTextInTree(tree)
expect(divText).toEqual('22/07/2019 09:30')
tree.unmount()
})
test('should handle error and return date with default format', async () => {
// @ts-ignore
const client: Client = {
// @ts-ignore
invoke: jest.fn(
() =>
new Promise<{errors: {}}>((_, reject) =>
reject({
errors: {['formatDateAndTime']: 'Error'},
}),
),
),
}
const tree = initTree(client)
expect(client.invoke).toHaveBeenCalledWith(
ClientInvokeOptions.formatDateAndTime,
date,
'account',
)
let divText = findDivTextInTree(tree)
expect(divText).toEqual('')
await act(async () => {
await flushPromises()
})
tree.update()
divText = findDivTextInTree(tree)
expect(divText).toEqual(formatDefault(date))
tree.unmount()
})
})
| 23.570093
| 79
| 0.616178
|
4439009121d849b3f525f2cb50c078a1d6d74456
| 2,037
|
py
|
Python
|
unit/test_flow_response_deserialization.py
|
forwardnetworks/fwd-api
|
9cb402f130ede50a735efa8acd691431bbe1d5bc
|
[
"Apache-2.0"
] | 1
|
2020-11-02T18:01:21.000Z
|
2020-11-02T18:01:21.000Z
|
unit/test_flow_response_deserialization.py
|
forwardnetworks/fwd-api
|
9cb402f130ede50a735efa8acd691431bbe1d5bc
|
[
"Apache-2.0"
] | null | null | null |
unit/test_flow_response_deserialization.py
|
forwardnetworks/fwd-api
|
9cb402f130ede50a735efa8acd691431bbe1d5bc
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
import json
import os
import sys
from fwd_api.flow import FlowsResponse, FlowType
from fwd_api.path import AggregatedLinksPath, DeviceIfaceListPair, Hop
FLOWS_JSON = os.path.join(os.path.dirname(__file__),
'..', 'fwd-api-data', 'flows',
'example.json')
# Expected number of flows for flow response in FLOWS_JSON
EXPECTED_NUM_FLOWS = 10
# Expected flow types for flow response in FLOWS_JSON
EXPECTED_FLOW_TYPES = [FlowType.VALID,
FlowType.DROPPED,
FlowType.BLACKHOLE,
FlowType.BLACKHOLE,
FlowType.BLACKHOLE,
FlowType.DROPPED,
FlowType.VALID,
FlowType.VALID,
FlowType.VALID,
FlowType.VALID]
EXPECTED_LAST_FLOW_PATH = AggregatedLinksPath(
[
Hop(DeviceIfaceListPair('veos-0', ['et1', 'et3']),
DeviceIfaceListPair('veos-0', ['et2'])),
Hop(DeviceIfaceListPair('veos-1', ['et1']), None),
])
def test_deserialization():
with open(FLOWS_JSON) as fd:
json_dict = json.loads(fd.read())
flows_response = FlowsResponse.from_json(json_dict)
# Verify that total flows field is correct
assert (flows_response.get_total_flows().get_total_flows() ==
EXPECTED_NUM_FLOWS)
# Verify that we have the expected number of individual flows
flows_list = flows_response.get_flows_list()
assert (len(flows_list) == EXPECTED_NUM_FLOWS)
# Verify the flow types of those expected flows
assert (map(lambda f: f.get_flow_type(), flows_list) ==
EXPECTED_FLOW_TYPES)
# Select one flow and verify its paths against a priori
# known path of first flow. Choosing last flow because
# it's the most complex and will execute the most logic
assert flows_list[-1].get_unexploded_path() == EXPECTED_LAST_FLOW_PATH
if __name__ == '__main__':
test_deserialization()
| 33.393443
| 74
| 0.633775
|
ff63975f0e3db1c087edb4208359cd466c16175a
| 5,779
|
py
|
Python
|
anjuke_test.py
|
w4356y/House_price
|
e2a0e35ece1342753691dfec184de345224e4e25
|
[
"Apache-2.0"
] | 1
|
2020-07-27T14:49:22.000Z
|
2020-07-27T14:49:22.000Z
|
anjuke_test.py
|
w4356y/House_price
|
e2a0e35ece1342753691dfec184de345224e4e25
|
[
"Apache-2.0"
] | null | null | null |
anjuke_test.py
|
w4356y/House_price
|
e2a0e35ece1342753691dfec184de345224e4e25
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
# @Time : 6/21/2020 2:55 PM
# @Author : Wei Jiang
# @FileName: anjuke_test.py
# @Software: PyCharm
# @Github : https://github.com/w4356y/House_price.git
import time
import requests
import random
#import pymysql
from parsel import Selector
from lxml import etree
import pandas as pd
from datetime import date
## 定义class
class AnJuKe():
# 初始化
def __init__(self, url, type):
self.type = type
self.nj_loupan_anjuke = pd.DataFrame(columns=['Title', 'Location', 'Huxing', 'Tags', "Prices"])
self.nj_ershoufang_anjuke = pd.DataFrame(columns=['Title', 'Location', 'Details', 'Tags', "Prices"])
self.tree = self.get_tree(url)
self.get_data()
self.save_data()
# 判断是否为空
def is_empty(self, data):
if data:
data = data[0]
else:
data = '无信息'
return data
# 得到tree
def get_tree(self, url):
# 代理ip
proxies_list = [{'http': 'http://117.191.11.111:8080'},
{'http': 'http://118.25.104.254:1080'},
{'http': 'http://203.195.168.154:3128'},
{'http': 'http://117.191.11.75:80'},
{'http': 'http://117.191.11.72:80'}, ]
proxies = random.choice(proxies_list)
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36'}
response = requests.get(url, headers=headers, proxies=proxies)
print(response)
sel = Selector(response.text)
return sel
## 调用相应爬取函数
def get_data(self):
if self.type == "loupan":
self.get_loupan()
else:
self.get_ershoufang()
## 爬取二手房信息
def get_ershoufang(self):
for i in range(1, 51):
url = 'https://nanjing.anjuke.com/sale/p%s/' % (i)
print(url)
tree = self.get_tree(url)
titles = tree.xpath('//div[@class="house-title"]/a[@title]/text()').extract()
titles = [title.replace("\n","") for title in titles]
#print(titles)
details = tree.xpath('//div[@class="details-item"][1]').xpath('string(.)').extract()
details = [detail.replace("\n","").replace(" ","") for detail in details]
locations = tree.xpath('//div[@class="details-item"][2]').xpath('string(.)').extract()
locations = [location.replace("\n", "").replace(" ", "") for location in locations]
prices = tree.xpath('//div[@class="pro-price"]').xpath('string(.)').extract()
prices = [price.replace("\n","").replace(" ","") for price in prices]
tags = tree.xpath('//div[@class="tags-bottom"]').xpath('string(.)').extract()
tags = [tag.replace("\n", "").replace(" ", "") for tag in tags]
#print(tags)
if len(prices) != len(titles) or len(tags) != len(titles) or len(details) != len(titles) or len(
locations) != len(titles):
print("Warnning! Some item length do not match.")
pages_info = pd.DataFrame(list(zip(titles, locations, details, tags, prices
)),
columns=['Title', 'Location', 'Details', 'Tags', "Prices"])
#print(pages_info["Title"])
self.nj_ershoufang_anjuke = pd.concat([self.nj_ershoufang_anjuke, pages_info], ignore_index=True)
time.sleep(5)
## 爬取新房信息
def get_loupan(self):
for i in range(1, 21):
# print(1)
url = 'https://nj.fang.anjuke.com/loupan/all/p%s/' % (i)
#url = '%s.zu.anjuke.com/fangyuan/p%s/' % (city_url1, i)
print(url)
# 调用get函数
tree = self.get_tree(url)
title = tree.xpath('//span[@class="items-name"]/text()').extract()
#print(title)
location = tree.xpath('//span[@class="list-map"]/text()').extract()
print(len(location))
huxing = tree.xpath('//a[@class="huxing" or @class="kp-time"]').xpath('string(.)').extract()
huxing = [item.replace("\n","").replace("\t","").replace(" ","") for item in huxing]
print(len(huxing))
tags = tree.xpath('//div[@class="tag-panel"]').xpath('string(.)').extract()
tags = [tag.replace("\n",",").replace(" ","") for tag in tags]
print(len(tags))
prices = tree.xpath('//a[@class="favor-pos"]').xpath('string(.)').extract()
prices = [price.replace("\n","").replace(" ","") for price in prices]
print(len(prices))
if len(prices) != len(title) or len(tags) != len(title) or len(huxing) != len(title) or len(location) != len(title):
print("Warnning! Some item length do not match.")
pages_info = pd.DataFrame(list(zip(title, location, huxing, tags, prices
)),
columns=['Title', 'Location', 'Huxing', 'Tags', "Prices"])
self.nj_loupan_anjuke = pd.concat([self.nj_loupan_anjuke, pages_info], ignore_index=True)
time.sleep(5)
## 保存数据
def save_data(self):
today = date.today()
print("Today's date:", today)
filename = '_'.join(["nanjing", self.type,"anjuke", str(today)]) + ".xlsx"
dir = "d:/HousePrice"
if self.type == "loupan":
self.nj_loupan_anjuke.to_excel('/'.join([dir, filename]))
else:
self.nj_ershoufang_anjuke.to_excel('/'.join([dir, filename]))
if __name__ == '__main__':
url = 'https://www.anjuke.com/sy-city.html'
AnJuKe(url, "ershoufang")
| 42.182482
| 137
| 0.531407
|
9d24e041a7f7d9deedb282e232023ae98ab55aad
| 5,007
|
rs
|
Rust
|
xflags-macros/tests/it/main.rs
|
lnicola/xflags
|
7fddb38b55028ebb98d323c26d28c1e03172afb6
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
xflags-macros/tests/it/main.rs
|
lnicola/xflags
|
7fddb38b55028ebb98d323c26d28c1e03172afb6
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
xflags-macros/tests/it/main.rs
|
lnicola/xflags
|
7fddb38b55028ebb98d323c26d28c1e03172afb6
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
mod repeated_pos;
mod smoke;
mod subcommands;
use std::{ffi::OsString, fmt};
use expect_test::{expect, Expect};
fn check<F, A>(f: F, args: &str, expect: Expect)
where
F: FnOnce(Vec<OsString>) -> xflags::Result<A>,
A: fmt::Debug,
{
let args = args.split_ascii_whitespace().map(OsString::from).collect::<Vec<_>>();
let res = f(args);
match res {
Ok(args) => {
expect.assert_debug_eq(&args);
}
Err(err) => {
expect.assert_eq(&err.to_string());
}
}
}
#[test]
fn smoke() {
check(
smoke::RustAnalyzer::from_vec,
"-n 92 .",
expect![[r#"
RustAnalyzer {
workspace: ".",
jobs: None,
log_file: None,
verbose: 0,
number: 92,
data: [],
emoji: false,
}
"#]],
);
check(
smoke::RustAnalyzer::from_vec,
"-n 92 -v --verbose -v --data 0xDEAD --log-file /tmp/log.txt --data 0xBEEF .",
expect![[r#"
RustAnalyzer {
workspace: ".",
jobs: None,
log_file: Some(
"/tmp/log.txt",
),
verbose: 3,
number: 92,
data: [
"0xDEAD",
"0xBEEF",
],
emoji: false,
}
"#]],
);
check(
smoke::RustAnalyzer::from_vec,
"-n 92 --werbose",
expect![[r#"unexpected flag: `--werbose`"#]],
);
check(smoke::RustAnalyzer::from_vec, "", expect![[r#"flag is required: `workspace`"#]]);
check(smoke::RustAnalyzer::from_vec, ".", expect![[r#"flag is required: `--number`"#]]);
check(smoke::RustAnalyzer::from_vec, "-n", expect![[r#"expected a value for `-n`"#]]);
check(
smoke::RustAnalyzer::from_vec,
"-n lol",
expect![[r#"can't parse `-n`, invalid digit found in string"#]],
);
check(
smoke::RustAnalyzer::from_vec,
"-n 1 -n 2 .",
expect![[r#"flag specified more than once: `--number`"#]],
);
check(
smoke::RustAnalyzer::from_vec,
"-n 1 . 92 lol",
expect![[r#"unexpected argument: "lol""#]],
);
check(
smoke::RustAnalyzer::from_vec,
"-n 1 . --emoji --emoji",
expect![[r#"flag specified more than once: `--emoji`"#]],
);
}
#[test]
fn repeated_argument() {
check(
repeated_pos::RepeatedPos::from_vec,
"a 11 c d e f",
expect![[r#"
RepeatedPos {
a: "a",
b: Some(
11,
),
c: Some(
"c",
),
rest: [
"d",
"e",
"f",
],
}
"#]],
);
}
#[test]
fn subcommands() {
check(
subcommands::RustAnalyzer::from_vec,
"server",
expect![[r#"
RustAnalyzer {
verbose: 0,
subcommand: Server(
Server {
dir: None,
subcommand: Launch(
Launch {
log: false,
},
),
},
),
}
"#]],
);
check(
subcommands::RustAnalyzer::from_vec,
"server --dir . --log",
expect![[r#"
RustAnalyzer {
verbose: 0,
subcommand: Server(
Server {
dir: Some(
".",
),
subcommand: Launch(
Launch {
log: true,
},
),
},
),
}
"#]],
);
check(
subcommands::RustAnalyzer::from_vec,
"server watch",
expect![[r#"
RustAnalyzer {
verbose: 0,
subcommand: Server(
Server {
dir: None,
subcommand: Watch(
Watch,
),
},
),
}
"#]],
);
check(
subcommands::RustAnalyzer::from_vec,
"-v analysis-stats . --parallel",
expect![[r#"
RustAnalyzer {
verbose: 1,
subcommand: AnalysisStats(
AnalysisStats {
path: ".",
parallel: true,
},
),
}
"#]],
);
check(subcommands::RustAnalyzer::from_vec, "", expect![[r#"subcommand is required"#]]);
}
| 25.287879
| 92
| 0.367286
|
dc97b46ae4ad2ab4f318a6d3a0007a78bfc45c9f
| 558
|
rb
|
Ruby
|
test/controllers/subscriptions_controller_test.rb
|
kddnewton/wm-memories
|
644ad535da0ed1ace0c7adfc988b4b075d7c844b
|
[
"MIT"
] | 1
|
2017-04-04T23:38:31.000Z
|
2017-04-04T23:38:31.000Z
|
test/controllers/subscriptions_controller_test.rb
|
kddeisz/wm-memories
|
3e465fc9530a333166186a89d785d9b60a7e9cda
|
[
"MIT"
] | 279
|
2016-03-26T21:10:23.000Z
|
2021-03-29T12:47:38.000Z
|
test/controllers/subscriptions_controller_test.rb
|
kddnewton/wm-memories
|
644ad535da0ed1ace0c7adfc988b4b075d7c844b
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
require 'test_helper'
class SubscriptionsControllerTest < ActionController::TestCase
def test_new
get :new
assert_response :success
end
def test_create_valid
assert_difference 'Subscription.count', 1 do
post :create, params: { subscription: { email: 'testemail@test.com' } }
end
assert_response :success
end
def test_create_invalid
assert_no_difference 'Subscription.count' do
post :create, params: { subscription: { email: '' } }
end
assert_response :success
end
end
| 22.32
| 77
| 0.716846
|
a425ba067fed807b259920507c39e53bd139a62d
| 162
|
kt
|
Kotlin
|
app/src/main/java/com/example/weathermvvm/data/provider/UnitProvider.kt
|
dlt96/CoroutinesArchitectureComponents
|
aad2bb137a4ab7361894ce1ce231c6eba5058cf2
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/weathermvvm/data/provider/UnitProvider.kt
|
dlt96/CoroutinesArchitectureComponents
|
aad2bb137a4ab7361894ce1ce231c6eba5058cf2
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/weathermvvm/data/provider/UnitProvider.kt
|
dlt96/CoroutinesArchitectureComponents
|
aad2bb137a4ab7361894ce1ce231c6eba5058cf2
|
[
"Apache-2.0"
] | null | null | null |
package com.example.weathermvvm.data.provider
import com.example.weathermvvm.internal.UnitSystem
interface UnitProvider {
fun getUnitSystem(): UnitSystem
}
| 20.25
| 50
| 0.814815
|
cfc3cd5760915b645a23c3a0139b05f19605c7ed
| 5,310
|
swift
|
Swift
|
WildWestTests/AnimationEventMatcherTests.swift
|
stephtelolahy/WildWest
|
e0197b53da0a9da0f5685e977d6b4b72d9a3e699
|
[
"RSA-MD"
] | null | null | null |
WildWestTests/AnimationEventMatcherTests.swift
|
stephtelolahy/WildWest
|
e0197b53da0a9da0f5685e977d6b4b72d9a3e699
|
[
"RSA-MD"
] | null | null | null |
WildWestTests/AnimationEventMatcherTests.swift
|
stephtelolahy/WildWest
|
e0197b53da0a9da0f5685e977d6b4b72d9a3e699
|
[
"RSA-MD"
] | null | null | null |
//
// AnimationEventMatcherTests.swift
// WildWestTests
//
// Created by Hugues Stéphano TELOLAHY on 21/05/2021.
// Copyright © 2021 creativeGames. All rights reserved.
//
// swiftlint:disable implicitly_unwrapped_optional
// swiftlint:disable function_body_length
import XCTest
import WildWestEngine
import Cuckoo
class AnimationEventMatcherTests: XCTestCase {
private var sut: AnimationEventMatcherProtocol!
private var mockUserPreferences: MockUserPreferencesProtocol!
override func setUp() {
mockUserPreferences = MockUserPreferencesProtocol()
stub(mockUserPreferences) { mock in
when(mock.updateDelay.get).thenReturn(1.0)
}
sut = AnimationEventMatcher(preferences: mockUserPreferences)
}
func test_MatchAnimation() {
// Given
// When
// Assert
// No animation
XCTAssertNil(sut.animation(on: .activate(moves: [])))
XCTAssertNil(sut.animation(on: .run(move: GMove("a1", actor: "p1"))))
XCTAssertNil(sut.animation(on: .removeHit(player: "p1")))
XCTAssertNil(sut.animation(on: .decrementHitCancelable))
XCTAssertNil(sut.animation(on: .gameover(winner: .renegade)))
XCTAssertNil(sut.animation(on: .emptyQueue))
// Dummy
XCTAssertEqual(sut.animation(on: .setTurn(player: "p1")),
EventAnimation(type: .dummy, duration: 1.0))
XCTAssertEqual(sut.animation(on: .setPhase(value: 2)),
EventAnimation(type: .dummy, duration: 1.0))
XCTAssertEqual(sut.animation(on: .gainHealth(player: "p1")),
EventAnimation(type: .dummy, duration: 1.0))
XCTAssertEqual(sut.animation(on: .looseHealth(player: "p1", offender: "p2")),
EventAnimation(type: .dummy, duration: 1.0))
XCTAssertEqual(sut.animation(on: .eliminate(player: "p1", offender: "p2")),
EventAnimation(type: .dummy, duration: 1.0))
XCTAssertEqual(sut.animation(on: .addHit(hit: GHit(name: "h1", players: ["p2"], abilities: ["a1", "a2"], cancelable: 1))),
EventAnimation(type: .dummy, duration: 1.0))
// Move card
XCTAssertEqual(sut.animation(on: .play(player: "p1", card: "c1")),
EventAnimation(type: .move(card: "c1", source: .hand("p1"), target: .discard), duration: 1.0))
XCTAssertEqual(sut.animation(on: .equip(player: "p1", card: "c1")),
EventAnimation(type: .move(card: "c1", source: .hand("p1"), target: .inPlay("p1")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .handicap(player: "p1", card: "c1", other: "p2")),
EventAnimation(type: .move(card: "c1", source: .hand("p1"), target: .inPlay("p2")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .drawDeck(player: "p1")),
EventAnimation(type: .move(card: nil, source: .deck, target: .hand("p1")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .drawDeckChoosing(player: "p1", card: "c1")),
EventAnimation(type: .move(card: nil, source: .deck, target: .hand("p1")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .drawHand(player: "p1", other: "p2", card: "c2")),
EventAnimation(type: .move(card: nil, source: .hand("p2"), target: .hand("p1")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .drawInPlay(player: "p1", other: "p2", card: "c2")),
EventAnimation(type: .move(card: "c2", source: .inPlay("p2"), target: .hand("p1")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .drawStore(player: "p1", card: "c1")),
EventAnimation(type: .move(card: "c1", source: .store, target: .hand("p1")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .drawDiscard(player: "p1")),
EventAnimation(type: .move(card: StateCard.discard, source: .discard, target: .hand("p1")), duration: 1.0))
XCTAssertEqual(sut.animation(on: .discardHand(player: "p1", card: "c1")),
EventAnimation(type: .move(card: "c1", source: .hand("p1"), target: .discard), duration: 1.0))
XCTAssertEqual(sut.animation(on: .discardInPlay(player: "p1", card: "c1")),
EventAnimation(type: .move(card: "c1", source: .inPlay("p1"), target: .discard), duration: 1.0))
XCTAssertEqual(sut.animation(on: .passInPlay(player: "p1", card: "c1", other: "p2")),
EventAnimation(type: .move(card: "c1", source: .inPlay("p1"), target: .inPlay("p2")), duration: 1.0))
// Reveal card
XCTAssertEqual(sut.animation(on: .deckToStore),
EventAnimation(type: .reveal(card: StateCard.deck, source: .deck, target: .store), duration: 1.0))
XCTAssertEqual(sut.animation(on: .flipDeck),
EventAnimation(type: .reveal(card: StateCard.deck, source: .deck, target: .discard), duration: 1.0))
XCTAssertEqual(sut.animation(on: .drawDeckFlipping(player: "p1")),
EventAnimation(type: .reveal(card: StateCard.deck, source: .deck, target: .hand("p1")), duration: 1.0))
}
}
| 57.096774
| 130
| 0.598305
|
dc3a061b905421b591f975f295f8d81fec868b37
| 315
|
ts
|
TypeScript
|
viewmodel/templates/_transient.ts
|
marchel2/generator-durandal2
|
0d7a2e05dc9164a9f03aa6e13dd7631ae6096dec
|
[
"MIT"
] | 1
|
2020-04-02T05:16:12.000Z
|
2020-04-02T05:16:12.000Z
|
viewmodel/templates/_transient.ts
|
marchel2/generator-durandal2
|
0d7a2e05dc9164a9f03aa6e13dd7631ae6096dec
|
[
"MIT"
] | null | null | null |
viewmodel/templates/_transient.ts
|
marchel2/generator-durandal2
|
0d7a2e05dc9164a9f03aa6e13dd7631ae6096dec
|
[
"MIT"
] | null | null | null |
import * as ko from 'knockout';
import * as app from 'durandal/app';
import * as system from 'durandal/system';
import * as router from 'plugins/router';
export class VM {
constructor() {}
public activate(){
return true;
}
public deactivate(){
return true;
}
}
| 17.5
| 42
| 0.587302
|
dc882fea01ad5bab8a7ee0a6ee0daa63eda9bdfb
| 1,715
|
ts
|
TypeScript
|
Chapter01/Exercise02/snippet.ts
|
kurtishouser/The-TypeScript-Workshop
|
8cdf19dd93ecdd5c7e73158c38d31b7b65e25d33
|
[
"MIT"
] | 15
|
2021-07-07T06:43:02.000Z
|
2022-03-13T22:46:02.000Z
|
Chapter01/Exercise02/snippet.ts
|
kurtishouser/The-TypeScript-Workshop
|
8cdf19dd93ecdd5c7e73158c38d31b7b65e25d33
|
[
"MIT"
] | null | null | null |
Chapter01/Exercise02/snippet.ts
|
kurtishouser/The-TypeScript-Workshop
|
8cdf19dd93ecdd5c7e73158c38d31b7b65e25d33
|
[
"MIT"
] | 25
|
2020-09-09T04:51:45.000Z
|
2022-03-13T21:41:35.000Z
|
function snippet (text: string, length: number) : string {
// Check if the text is smaller than the specified length, and if it is, return it unchanged
if (text.length < length) {
return text;
}
// If the text is larger than the maximum length we'll need to add an ellipsis.
// The maximum number of characters that we'll be able to show is the specified length
// less the length of our ellipsis (it takes space too).
// We'll use the `slice` string method to extract that many characters from the text.
const ellipsis = "...";
let result = text.slice(0, length-ellipsis.length);
// We'll find the last word boundary before the cutoff, using `lastIndexOf`,
// and then combine the text up to that point with the ellipsis.
const lastSpace = result.lastIndexOf(" ");
result = `${result.slice(0, lastSpace)}${ellipsis}`;
// Return the result from the function
return result;
}
// correct call and usage
var resultOne = snippet("TypeScript is a programming language that is a strict syntactical superset of JavaScript and adds optional static typing to the language.", 40);
console.log(resultOne);
/* COMMENT FROM HERE */
// missing second parameter
var resultTwo = snippet("Lorem ipsum dolor sit amet");
console.log(resultTwo);
// The first parameter is of incorrect type
var resultThree = snippet(false, 40);
console.log(resultThree);
// The second parameter is of incorrect type
var resultFour = snippet("Lorem ipsum dolor sit amet", false);
console.log(resultFour);
// The result is assigned to a variable of incorrect type
var resultFive = snippet("Lorem ipsum dolor sit amet", 20);
console.log(resultFive);
/* COMMENT TO HERE */
| 37.282609
| 169
| 0.712536
|
81177935ff5ac343fc032a912e5ae4970a077884
| 3,833
|
rb
|
Ruby
|
lib/pi_piper/bcm2835.rb
|
bguest/pi_piper
|
261b025cff6b3ff837a2be64be0ebb5fa520edfc
|
[
"Unlicense"
] | null | null | null |
lib/pi_piper/bcm2835.rb
|
bguest/pi_piper
|
261b025cff6b3ff837a2be64be0ebb5fa520edfc
|
[
"Unlicense"
] | null | null | null |
lib/pi_piper/bcm2835.rb
|
bguest/pi_piper
|
261b025cff6b3ff837a2be64be0ebb5fa520edfc
|
[
"Unlicense"
] | null | null | null |
require 'ffi'
module PiPiper
# The Bcm2835 module is not intended to be directly called.
# It serves as an FFI library for PiPiper::SPI & PiPiper::I2C.
module Bcm2835
extend FFI::Library
ffi_lib File.dirname(__FILE__) + '/libbcm2835.img'
SPI_MODE0 = 0
SPI_MODE1 = 1
SPI_MODE2 = 2
SPI_MODE3 = 3
I2C_REASON_OK = 0 #Success
I2C_REASON_ERROR_NACK = 1 #Received a NACK
I2C_REASON_ERROR_CLKT = 2 #Received Clock Stretch Timeout
I2C_REASON_ERROR_DATA = 3 #Not all data is sent / received
attach_function :init, :bcm2835_init, [], :uint8
attach_function :close, :bcm2835_close, [], :uint8
#pin support...
attach_function :pin_set_pud, :bcm2835_gpio_set_pud, [:uint8, :uint8], :void
def self.pin_input(pin)
File.open("/sys/class/gpio/export", "w") { |f| f.write("#{pin}") }
File.open("/sys/class/gpio/gpio#{pin}/direction", "w") { |f| f.write("in") }
end
def self.pin_set(pin, value)
File.open("/sys/class/gpio/gpio#{pin}/value", 'w') {|f| f.write("#{value}") }
end
def self.pin_output(pin)
File.open("/sys/class/gpio/export", "w") { |f| f.write("#{pin}") }
File.open("/sys/class/gpio/gpio#{pin}/direction", "w") { |f| f.write("out") }
end
def self.pin_read(pin)
File.read("/sys/class/gpio/gpio#{pin}/value").to_i
end
#NOTE to use: chmod 666 /dev/spidev0.0
def self.spidev_out(array)
File.open('/dev/spidev0.0', 'wb'){|f| f.write(array.pack('C*')) }
end
#SPI support...
attach_function :spi_begin, :bcm2835_spi_begin, [], :uint8
attach_function :spi_end, :bcm2835_spi_end, [], :uint8
attach_function :spi_transfer, :bcm2835_spi_transfer, [:uint8], :uint8
attach_function :spi_transfernb, :bcm2835_spi_transfernb, [:pointer, :pointer, :uint], :void
attach_function :spi_clock, :bcm2835_spi_setClockDivider, [:uint8], :void
attach_function :spi_bit_order, :bcm2835_spi_setBitOrder, [:uint8], :void
attach_function :spi_chip_select, :bcm2835_spi_chipSelect, [:uint8], :void
attach_function :spi_set_data_mode, :bcm2835_spi_setDataMode, [:uint8], :void
attach_function :spi_chip_select_polarity,
:bcm2835_spi_setChipSelectPolarity, [:uint8, :uint8], :void
#I2C support...
attach_function :i2c_begin, :bcm2835_i2c_begin, [], :void
attach_function :i2c_end, :bcm2835_i2c_end, [], :void
attach_function :i2c_write, :bcm2835_i2c_write, [:pointer, :uint], :uint8
attach_function :i2c_set_address,:bcm2835_i2c_setSlaveAddress, [:uint8], :void
attach_function :i2c_set_clock_divider, :bcm2835_i2c_setClockDivider, [:uint16], :void
attach_function :i2c_read, :bcm2835_i2c_read, [:pointer, :uint], :uint8
def self.i2c_allowed_clocks
[100.kilohertz,
399.3610.kilohertz,
1.666.megahertz,
1.689.megahertz]
end
def self.spi_transfer_bytes(data)
data_out = FFI::MemoryPointer.new(data.count)
data_in = FFI::MemoryPointer.new(data.count)
(0..data.count-1).each { |i| data_out.put_uint8(i, data[i]) }
spi_transfernb(data_out, data_in, data.count)
(0..data.count-1).map { |i| data_in.get_uint8(i) }
end
def self.i2c_transfer_bytes(data)
data_out = FFI::MemoryPointer.new(data.count)
(0..data.count-1).each{ |i| data_out.put_uint8(i, data[i]) }
i2c_write data_out, data.count
end
def self.i2c_read_bytes(bytes)
data_in = FFI::MemoryPointer.new(bytes)
i2c_read(data_in, bytes) #TODO reason codes
(0..bytes-1).map { |i| data_in.get_uint8(i) }
end
end
end
| 37.578431
| 103
| 0.62875
|
e700bb2057655f4e417562e34972f0c5405043cd
| 3,086
|
go
|
Go
|
args_exchange.go
|
kitabisa/rabbitmqclient
|
f0934a2b2ba2340a70ffd615592c027dc3d0da3b
|
[
"MIT"
] | 2
|
2020-07-01T09:40:15.000Z
|
2021-01-07T07:39:35.000Z
|
args_exchange.go
|
kitabisa/rabbitmqclient
|
f0934a2b2ba2340a70ffd615592c027dc3d0da3b
|
[
"MIT"
] | null | null | null |
args_exchange.go
|
kitabisa/rabbitmqclient
|
f0934a2b2ba2340a70ffd615592c027dc3d0da3b
|
[
"MIT"
] | 2
|
2021-01-07T09:27:58.000Z
|
2021-02-23T11:07:26.000Z
|
package rabbitmqclient
import (
"github.com/streadway/amqp"
)
// ExchangeDeclare specifies the arguments to used in declaring exchange.
type ExchangeDeclare struct {
Name string
Kind string
Durable bool
AutoDelete bool
Internal bool
NoWait bool
Args amqp.Table
}
// SetName is a setter.
func (e *ExchangeDeclare) SetName(name string) *ExchangeDeclare {
e.Name = name
return e
}
// SetKind is a setter.
func (e *ExchangeDeclare) SetKind(kind string) *ExchangeDeclare {
e.Kind = kind
return e
}
// SetDurable is a setter.
func (e *ExchangeDeclare) SetDurable(durable bool) *ExchangeDeclare {
e.Durable = durable
return e
}
// SetAutoDelete is a setter.
func (e *ExchangeDeclare) SetAutoDelete(autoDelete bool) *ExchangeDeclare {
e.AutoDelete = autoDelete
return e
}
// SetInternal is a setter.
func (e *ExchangeDeclare) SetInternal(internal bool) *ExchangeDeclare {
e.Internal = internal
return e
}
// SetNoWait is a setter.
func (e *ExchangeDeclare) SetNoWait(noWait bool) *ExchangeDeclare {
e.NoWait = noWait
return e
}
// SetArgs is a setter.
func (e *ExchangeDeclare) SetArgs(args amqp.Table) *ExchangeDeclare {
e.Args = args
return e
}
// Default sets the default values of the struct variables.
func (e *ExchangeDeclare) Default() *ExchangeDeclare {
e.Name = DefaultExchange
e.Kind = TypeDirect
e.Durable = true
e.AutoDelete = true
e.Internal = false
e.NoWait = false
return e
}
// ExchangeDeclarePassive declares an exchange as passive to assumes that the exchange is already exist.
type ExchangeDeclarePassive struct {
ExchangeDeclare
}
// ExchangeBind specifies the argumenst to bind an exchange to other exchange.
type ExchangeBind struct {
Destination string
Key string
Source string
NoWait bool
Args amqp.Table
}
// SetDestination is a setter.
func (e *ExchangeBind) SetDestination(destination string) *ExchangeBind {
e.Destination = destination
return e
}
// SetKey is a setter.
func (e *ExchangeBind) SetKey(key string) *ExchangeBind {
e.Key = key
return e
}
// SetSource is a setter.
func (e *ExchangeBind) SetSource(source string) *ExchangeBind {
e.Source = source
return e
}
// SetNoWait is a setter.
func (e *ExchangeBind) SetNoWait(noWait bool) *ExchangeBind {
e.NoWait = noWait
return e
}
// SetArgs is a setter.
func (e *ExchangeBind) SetArgs(args amqp.Table) *ExchangeBind {
e.Args = args
return e
}
// ExchangeUnbind unbinds the exchange using the same argument as the exchange bind.
type ExchangeUnbind struct {
ExchangeBind
}
// ExchangeDelete deletes the exchange when it is already declared.
type ExchangeDelete struct {
Name string
IfUnused bool
NoWait bool
}
// SetName is a setter.
func (e *ExchangeDelete) SetName(name string) *ExchangeDelete {
e.Name = name
return e
}
// SetIfUnused is a setter.
func (e *ExchangeDelete) SetIfUnused(ifUnused bool) *ExchangeDelete {
e.IfUnused = ifUnused
return e
}
// SetNoWait is a setter.
func (e *ExchangeDelete) SetNoWait(noWait bool) *ExchangeDelete {
e.NoWait = noWait
return e
}
| 21.430556
| 104
| 0.734608
|
976da27840a54f8a25eee51ac5b8064963716624
| 2,439
|
rb
|
Ruby
|
test/resque_test.rb
|
davekrupinski/resque-durable
|
16e97765edd719b3fe5d4c4241bbe4a4a6f943da
|
[
"MIT"
] | 5
|
2020-07-13T15:28:31.000Z
|
2022-02-18T08:42:49.000Z
|
test/resque_test.rb
|
davekrupinski/resque-durable
|
16e97765edd719b3fe5d4c4241bbe4a4a6f943da
|
[
"MIT"
] | 4
|
2015-09-17T17:48:36.000Z
|
2021-07-19T21:55:53.000Z
|
test/resque_test.rb
|
davekrupinski/resque-durable
|
16e97765edd719b3fe5d4c4241bbe4a4a6f943da
|
[
"MIT"
] | 1
|
2021-04-22T20:23:16.000Z
|
2021-04-22T20:23:16.000Z
|
require File.join(File.dirname(__FILE__), 'test_helper')
require 'resque'
module Resque::Durable
class ResqueTest < Minitest::Test
describe 'With Resque' do
before do
$mail_queue_job_results = nil
MailQueueJob.fail = false
Resque.redis.del "queue:test_queue"
QueueAudit.delete_all
end
it 'is compatible' do
assert Resque::Plugin.lint(Resque::Durable)
end
describe 'A successful job' do
it "should work" do
MailQueueJob.enqueue(:one, :two)
work_queue(:test_queue)
end
end
describe 'An completed job that is re-enqueued' do
before do
Resque::Durable::GUID.stubs(:generate).returns('12345')
MailQueueJob.enqueue(:one, :two)
end
it 'does not get tried again' do
worked_at = 1.day.ago
Time.stubs(:now).returns(worked_at)
work_queue(:test_queue)
audit = QueueAudit.find_by_enqueued_id('12345')
assert audit.complete?
assert_equal worked_at.to_i, audit.completed_at.to_i
audit.enqueue
Time.stubs(:now).returns(worked_at + 1.hour)
work_queue(:test_queue)
assert_equal worked_at.to_i, audit.reload.completed_at.to_i
end
end
describe 'A failing job' do
before do
@ts = 1.hour.ago
Time.stubs(:now).returns(@ts)
MailQueueJob.fail = true
MailQueueJob.enqueue(123, 456)
work_queue(:test_queue)
@audit = QueueAudit.all.detect { |j| j.payload == [123, 456] }
end
it "should have enqueued a job" do
assert @audit
end
it "should not complete" do
assert !@audit.complete?
end
it "should not be immediately retryable" do
assert !@audit.retryable?
end
it "should eventually be retryable" do
Time.stubs(:now).returns(@ts + 1.hour)
assert @audit.retryable?
end
describe 'retrying the job' do
describe 'job succeeding' do
before do
MailQueueJob.fail = false
@audit.enqueue
work_queue(:test_queue)
@audit.reload
end
it "should be marked as complete" do
assert @audit.complete?
end
end
end
end
end
end
end
| 26.225806
| 72
| 0.567446
|
0aedb7644b6a29d156acf1fa1abcb824fd2739ec
| 7,059
|
cpp
|
C++
|
LinAlgLib/src/LinearSolvers/JGS.cpp
|
jsandham/LinAlgLib
|
0f5c5b85325894fc6374dc28ad93b1c95a308302
|
[
"MIT"
] | null | null | null |
LinAlgLib/src/LinearSolvers/JGS.cpp
|
jsandham/LinAlgLib
|
0f5c5b85325894fc6374dc28ad93b1c95a308302
|
[
"MIT"
] | null | null | null |
LinAlgLib/src/LinearSolvers/JGS.cpp
|
jsandham/LinAlgLib
|
0f5c5b85325894fc6374dc28ad93b1c95a308302
|
[
"MIT"
] | null | null | null |
//********************************************************************************
//
// MIT License
//
// Copyright(c) 2019 James Sandham
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this softwareand 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 noticeand 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.
//
//********************************************************************************
#include"iostream"
#include"../../include/LinearSolvers/JGS.h"
#include"../../include/LinearSolvers/SLAF.h"
#include"math.h"
//********************************************************************************
//
// Jacobian, Guass Seidel, SOR, Symmetric Gauss Seidel, and Symmetric SOR
//
//********************************************************************************
#define DEBUG 1
//-------------------------------------------------------------------------------
// jacobi method
//-------------------------------------------------------------------------------
int jac(const int r[], const int c[], const double v[], double x[], const double b[],
const int n, const double tol, const int max_iter)
{
//copy of x
double *xold = new double[n];
for(int i = 0; i < n; i++){
xold[i] = x[i];
}
int ii = 0, jj = 0;
double err = 1.0;
while(err > tol && ii < max_iter){
//Jacobi iteration
double sigma;
double ajj;
for(int j = 0; j < n; j++){
sigma = 0.0;
ajj = 0.0; //diagonal entry a_jj
for(int k = r[j]; k < r[j + 1]; k++){
if(c[k] != j){
sigma = sigma + v[k] * xold[c[k]];
}
else if(c[k] == j){
ajj = v[k];
}
}
x[j] = (b[j] - sigma) / ajj;
}
for(int i = 0; i < n; i++){xold[i] = x[i];}
if(jj == 40){
err = error(r, c, v, xold, b, n);
jj = 0;
#if(DEBUG)
std::cout<<"error: "<<err<<std::endl;
#endif
}
ii++;
jj++;
}
delete[] xold;
return ii;
}
//-------------------------------------------------------------------------------
// gauss-seidel method
//-------------------------------------------------------------------------------
int gs(const int r[], const int c[], const double v[], double x[], const double b[],
const int n, const double tol, const int max_iter)
{
int ii = 0, jj = 0;
double err = 1.0;
while(err > tol && ii < max_iter){
//Gauss-Seidel iteration
double sigma;
double ajj;
for(int j = 0; j < n; j++){
sigma = 0.0;
ajj = 0.0; //diagonal entry a_jj
for(int k = r[j]; k < r[j + 1]; k++){
if(c[k] != j){
sigma = sigma + v[k] * x[c[k]];
}
else{
ajj = v[k];
}
}
x[j] = (b[j] - sigma) / ajj;
}
if(jj == 40){
//err = error(ar,ac,av,x,b,n);
err = fast_error(r, c, v, x, b, n, tol);
jj = 0;
#if(DEBUG)
std::cout<<"error: "<<err<<std::endl;
#endif
}
ii++;
jj++;
}
return ii;
}
//-------------------------------------------------------------------------------
// successive over-relaxation method
//-------------------------------------------------------------------------------
int sor(const int r[], const int c[], const double v[], double x[], const double b[],
const int n, const double omega, const double tol, const int max_iter)
{
int ii = 0, jj = 0;
double err = 1.0;
while(err>tol && ii<max_iter){
//SOR iteration
double sigma;
double ajj;
for(int j = 0; j < n; j++){
sigma = 0.0;
ajj = 0.0; //diagonal entry a_jj
for(int k = r[j]; k < r[j + 1]; k++){
if(c[k]!=j){
sigma = sigma + v[k] * x[c[k]];
}
else if(c[k] == j){
ajj = v[k];
}
}
x[j] = x[j] + omega*((b[j] - sigma) / ajj - x[j]);
}
if(jj==40){
err = error(r,c,v,x,b,n);
jj = 0;
#if(DEBUG)
std::cout<<"error: "<<err<<std::endl;
#endif
}
ii++;
jj++;
}
return ii;
}
//-------------------------------------------------------------------------------
// symmetric Gauss Seidel method
//-------------------------------------------------------------------------------
int sgs(const int r[], const int c[], const double v[], double x[], const double b[],
const int n, const double tol, const int max_iter)
{
int ii = 0, jj = 0;
double err = 1.0;
while(err > tol && ii < max_iter){
double sigma;
double ajj;
//forward pass
for(int j = 0; j < n; j++){
sigma = 0.0;
ajj = 0.0; //diagonal entry a_jj
for(int k = r[j]; k < r[j + 1]; k++){
if(c[k] != j){
sigma = sigma + v[k] * x[c[k]];
}
else if(c[k] == j){
ajj = v[k];
}
}
x[j] = (b[j] - sigma) / ajj;
}
//backward pass
for(int j = n-1; j > -1; j--){
sigma = 0.0;
ajj = 0.0; //diagonal entry a_jj
for(int k = r[j]; k < r[j + 1]; k++){
if(c[k] != j){
sigma = sigma + v[k] * x[c[k]];
}
else if(c[k] == j){
ajj = v[k];
}
}
x[j] = (b[j] - sigma) / ajj;
}
if(jj==40){
err = error(r, c, v, x, b, n);
jj = 0;
#if(DEBUG)
std::cout<<"error: "<<err<<std::endl;
#endif
}
ii++;
jj++;
}
return ii;
}
//-------------------------------------------------------------------------------
// symmetric successive over-relaxation method
//-------------------------------------------------------------------------------
int ssor(const int r[], const int c[], const double v[], double x[], const double b[],
const int n, const double omega, const double tol, const int max_iter)
{
int ii = 0, jj = 0;
double err = 1.0;
while(err > tol && ii < max_iter){
double sigma;
double ajj;
//forward pass
for(int j = 0; j < n; j++){
sigma = 0.0;
ajj = 0.0;
for(int k = r[j]; k < r[j + 1]; k++){
if(c[k] != j){
sigma = sigma + v[k] * x[c[k]];
}
else if(c[k] == j){
ajj = v[k];
}
}
x[j] = x[j] + omega * ((b[j] - sigma) / ajj - x[j]);
}
//backward pass
for(int j = n; j > -1; j--){
sigma = 0.0;
ajj = 0.0;
for(int k = r[j]; k < r[j + 1]; k++){
if(c[k] != j){
sigma = sigma + v[k] * x[c[k]];
}
else if(c[k] == j){
ajj = v[k];
}
}
x[j] = x[j] + omega * ((b[j] - sigma) / ajj - x[j]);
}
if(jj == 40){
err = error(r,c,v,x,b,n);
jj = 0;
#if(DEBUG)
std::cout<<"error: "<<err<<std::endl;
#endif
}
ii++;
jj++;
}
return ii;
}
| 24.510417
| 87
| 0.450914
|
c9ee3933c6d754935e58d86ab8ebd3c5e30312ed
| 5,078
|
rs
|
Rust
|
packages/yew-macro/src/html_tree/html_list.rs
|
lostinspiration/yew
|
e68060afa7421149f2d6aacace67c65c33e81fe5
|
[
"Apache-2.0",
"MIT"
] | 8,292
|
2017-12-24T12:34:44.000Z
|
2019-08-04T03:56:11.000Z
|
packages/yew-macro/src/html_tree/html_list.rs
|
lostinspiration/yew
|
e68060afa7421149f2d6aacace67c65c33e81fe5
|
[
"Apache-2.0",
"MIT"
] | 504
|
2017-12-24T20:53:56.000Z
|
2019-08-04T03:30:44.000Z
|
packages/yew-macro/src/html_tree/html_list.rs
|
lostinspiration/yew
|
e68060afa7421149f2d6aacace67c65c33e81fe5
|
[
"Apache-2.0",
"MIT"
] | 349
|
2017-12-24T23:37:30.000Z
|
2019-08-03T03:12:50.000Z
|
use boolinator::Boolinator;
use quote::{quote, quote_spanned, ToTokens};
use syn::buffer::Cursor;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::Expr;
use super::html_dashed_name::HtmlDashedName;
use super::{HtmlChildrenTree, TagTokens};
use crate::props::Prop;
use crate::{Peek, PeekValue};
pub struct HtmlList {
open: HtmlListOpen,
pub children: HtmlChildrenTree,
close: HtmlListClose,
}
impl PeekValue<()> for HtmlList {
fn peek(cursor: Cursor) -> Option<()> {
HtmlListOpen::peek(cursor)
.or_else(|| HtmlListClose::peek(cursor))
.map(|_| ())
}
}
impl Parse for HtmlList {
fn parse(input: ParseStream) -> syn::Result<Self> {
if HtmlListClose::peek(input.cursor()).is_some() {
return match input.parse::<HtmlListClose>() {
Ok(close) => Err(syn::Error::new_spanned(
close.to_spanned(),
"this closing fragment has no corresponding opening fragment",
)),
Err(err) => Err(err),
};
}
let open = input.parse::<HtmlListOpen>()?;
let mut children = HtmlChildrenTree::new();
while HtmlListClose::peek(input.cursor()).is_none() {
children.parse_child(input)?;
if input.is_empty() {
return Err(syn::Error::new_spanned(
open.to_spanned(),
"this opening fragment has no corresponding closing fragment",
));
}
}
let close = input.parse::<HtmlListClose>()?;
Ok(Self {
open,
children,
close,
})
}
}
impl ToTokens for HtmlList {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let Self {
open,
children,
close,
} = &self;
let key = if let Some(key) = &open.props.key {
quote_spanned! {key.span()=> ::std::option::Option::Some(::std::convert::Into::<::yew::virtual_dom::Key>::into(#key))}
} else {
quote! { ::std::option::Option::None }
};
let spanned = {
let open = open.to_spanned();
let close = close.to_spanned();
quote! { #open #close }
};
tokens.extend(quote_spanned! {spanned.span()=>
::yew::virtual_dom::VNode::VList(
::yew::virtual_dom::VList::with_children(#children, #key)
)
});
}
}
struct HtmlListOpen {
tag: TagTokens,
props: HtmlListProps,
}
impl HtmlListOpen {
fn to_spanned(&self) -> impl ToTokens {
self.tag.to_spanned()
}
}
impl PeekValue<()> for HtmlListOpen {
fn peek(cursor: Cursor) -> Option<()> {
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '<').as_option()?;
// make sure it's either a property (key=value) or it's immediately closed
if let Some((_, cursor)) = HtmlDashedName::peek(cursor) {
let (punct, _) = cursor.punct()?;
(punct.as_char() == '=' || punct.as_char() == '?').as_option()
} else {
let (punct, _) = cursor.punct()?;
(punct.as_char() == '>').as_option()
}
}
}
impl Parse for HtmlListOpen {
fn parse(input: ParseStream) -> syn::Result<Self> {
TagTokens::parse_start_content(input, |input, tag| {
let props = input.parse()?;
Ok(Self { tag, props })
})
}
}
struct HtmlListProps {
key: Option<Expr>,
}
impl Parse for HtmlListProps {
fn parse(input: ParseStream) -> syn::Result<Self> {
let key = if input.is_empty() {
None
} else {
let prop: Prop = input.parse()?;
if !input.is_empty() {
return Err(input.error("only a single `key` prop is allowed on a fragment"));
}
if prop.label.to_ascii_lowercase_string() != "key" {
return Err(syn::Error::new_spanned(
prop.label,
"fragments only accept the `key` prop",
));
}
Some(prop.value)
};
Ok(Self { key })
}
}
struct HtmlListClose(TagTokens);
impl HtmlListClose {
fn to_spanned(&self) -> impl ToTokens {
self.0.to_spanned()
}
}
impl PeekValue<()> for HtmlListClose {
fn peek(cursor: Cursor) -> Option<()> {
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '<').as_option()?;
let (punct, cursor) = cursor.punct()?;
(punct.as_char() == '/').as_option()?;
let (punct, _) = cursor.punct()?;
(punct.as_char() == '>').as_option()
}
}
impl Parse for HtmlListClose {
fn parse(input: ParseStream) -> syn::Result<Self> {
TagTokens::parse_end_content(input, |input, tag| {
if !input.is_empty() {
Err(input.error("unexpected content in list close"))
} else {
Ok(Self(tag))
}
})
}
}
| 28.52809
| 130
| 0.525601
|
4aad3dd7058f2247a5823d459a3375351dbc8dc2
| 8,002
|
dart
|
Dart
|
liquidart/lib/src/auth/authorizer.dart
|
EddieKamau/liquidart
|
88625cf06af058992e5e5f5047b7b91778b83092
|
[
"BSD-2-Clause"
] | null | null | null |
liquidart/lib/src/auth/authorizer.dart
|
EddieKamau/liquidart
|
88625cf06af058992e5e5f5047b7b91778b83092
|
[
"BSD-2-Clause"
] | null | null | null |
liquidart/lib/src/auth/authorizer.dart
|
EddieKamau/liquidart
|
88625cf06af058992e5e5f5047b7b91778b83092
|
[
"BSD-2-Clause"
] | null | null | null |
import 'dart:async';
import 'dart:io';
import 'package:liquidart/src/openapi/openapi.dart';
import '../http/http.dart';
import 'auth.dart';
/// A [Controller] that validates the Authorization header of a request.
///
/// An instance of this type will validate that the authorization information in an Authorization header is sufficient to access
/// the next controller in the channel.
///
/// For each request, this controller parses the authorization header, validates it with an [AuthValidator] and then create an [Authorization] object
/// if successful. The [Request] keeps a reference to this [Authorization] and is then sent to the next controller in the channel.
///
/// If either parsing or validation fails, a 401 Unauthorized response is sent and the [Request] is removed from the channel.
///
/// Parsing occurs according to [parser]. The resulting value (e.g., username and password) is sent to [validator].
/// [validator] verifies this value (e.g., lookup a user in the database and verify their password matches).
///
/// Usage:
///
/// router
/// .route("/protected-route")
/// .link(() =>new Authorizer.bearer(authServer))
/// .link(() => new ProtectedResourceController());
class Authorizer extends Controller {
/// Creates an instance of [Authorizer].
///
/// Use this constructor to provide custom [AuthorizationParser]s.
///
/// By default, this instance will parse bearer tokens from the authorization header, e.g.:
///
/// Authorization: Bearer ap9ijlarlkz8jIOa9laweo
///
/// If [scopes] is provided, the authorization granted must have access to *all* scopes according to [validator].
Authorizer(this.validator,
{this.parser = const AuthorizationBearerParser(), List<String>? scopes})
: scopes = scopes?.map((s) => AuthScope(s)).toList();
/// Creates an instance of [Authorizer] with Basic Authentication parsing.
///
/// Parses a username and password from the request's Basic Authentication data in the Authorization header, e.g.:
///
/// Authorization: Basic base64(username:password)
Authorizer.basic(AuthValidator? validator)
: this(validator, parser: const AuthorizationBasicParser());
/// Creates an instance of [Authorizer] with Bearer token parsing.
///
/// Parses a bearer token from the request's Authorization header, e.g.
///
/// Authorization: Bearer ap9ijlarlkz8jIOa9laweo
///
/// If [scopes] is provided, the bearer token must have access to *all* scopes according to [validator].
Authorizer.bearer(AuthValidator? validator, {List<String>? scopes})
: this(validator,
parser: const AuthorizationBearerParser(), scopes: scopes);
/// The validating authorization object.
///
/// This object will check credentials parsed from the Authorization header and produce an
/// [Authorization] object representing the authorization the credentials have. It may also
/// reject a request. This is typically an instance of [AuthServer].
final AuthValidator? validator;
/// The list of required scopes.
///
/// If [validator] grants scope-limited authorizations (e.g., OAuth2 bearer tokens), the authorization
/// provided by the request's header must have access to all [scopes] in order to move on to the next controller.
///
/// This property is set with a list of scope strings in a constructor. Each scope string is parsed into
/// an [AuthScope] and added to this list.
final List<AuthScope>? scopes;
/// Parses the Authorization header.
///
/// The parser determines how to interpret the data in the Authorization header. Concrete subclasses
/// are [AuthorizationBasicParser] and [AuthorizationBearerParser].
///
/// Once parsed, the parsed value is validated by [validator].
final AuthorizationParser parser;
@override
FutureOr<RequestOrResponse> handle(Request request) async {
final authData = request.raw.headers.value(HttpHeaders.authorizationHeader);
if (authData == null) {
return Response.unauthorized();
}
try {
final value = parser.parse(authData);
request.authorization =
await validator!.validate(parser, value, requiredScope: scopes);
if (request.authorization == null) {
return Response.unauthorized();
}
_addScopeRequirementModifier(request);
} on AuthorizationParserException catch (e) {
return _responseFromParseException(e);
} on AuthServerException catch (e) {
if (e.reason == AuthRequestError.invalidScope) {
return Response.forbidden(body: {
"error": "insufficient_scope",
"scope": scopes!.map((s) => s.toString()).join(" ")
});
}
return Response.unauthorized();
}
return request;
}
Response _responseFromParseException(AuthorizationParserException e) {
switch (e.reason) {
case AuthorizationParserExceptionReason.malformed:
return Response.badRequest(
body: {"error": "invalid_authorization_header"});
case AuthorizationParserExceptionReason.missing:
return Response.unauthorized();
default:
return Response.serverError();
}
}
void _addScopeRequirementModifier(Request request) {
// If a controller returns a 403 because of invalid scope,
// this Authorizer adds its required scope as well.
if (scopes != null) {
request.addResponseModifier((resp) {
if (resp.statusCode == 403 && resp.body is Map) {
final body = resp.body as Map<String, dynamic>;
if (body.containsKey("scope")) {
final declaredScopes = (body["scope"] as String).split(" ");
final scopesToAdd = scopes!
.map((s) => s.toString())
.where((s) => !declaredScopes.contains(s));
body["scope"] =
[scopesToAdd, declaredScopes].expand((i) => i).join(" ");
}
}
});
}
}
@override
void documentComponents(APIDocumentContext context) {
super.documentComponents(context);
context.responses.register(
"InsufficientScope",
APIResponse(
"The provided credentials or bearer token have insufficient permission to access this route.",
content: {
"application/json": APIMediaType(
schema: APISchemaObject.object({
"error": APISchemaObject.string(),
"scope": APISchemaObject.string()
..description = "The required scope for this operation."
}))
}));
context.responses.register(
"InsufficientAccess",
APIResponse(
"The provided credentials or bearer token are not authorized for this request.",
content: {
"application/json": APIMediaType(
schema: APISchemaObject.object(
{"error": APISchemaObject.string()}))
}));
context.responses.register(
"MalformedAuthorizationHeader",
APIResponse("The provided Authorization header was malformed.",
content: {
"application/json": APIMediaType(
schema: APISchemaObject.object(
{"error": APISchemaObject.string()}))
}));
}
@override
Map<String, APIOperation> documentOperations(
APIDocumentContext context, String route, APIPath path) {
final operations = super.documentOperations(context, route, path)!;
operations.forEach((_, op) {
op.addResponse(400, context.responses["MalformedAuthorizationHeader"]);
op.addResponse(401, context.responses["InsufficientAccess"]);
op.addResponse(403, context.responses["InsufficientScope"]);
final requirements = validator!
.documentRequirementsForAuthorizer(context, this, scopes: scopes);
requirements.forEach((req) {
op.addSecurityRequirement(req);
});
});
return operations;
}
}
| 38.84466
| 149
| 0.65946
|
45cc334386b9fcabfdda976b5f4b8ea2581f191f
| 356
|
py
|
Python
|
backend/api/migrations/0017_auto_20200311_1702.py
|
Abeeaad97/FinancialTracker
|
9e3f02b03de0404389653f6baf824f4b3b7ad958
|
[
"MIT"
] | 3
|
2020-02-17T18:48:25.000Z
|
2020-03-17T12:20:59.000Z
|
backend/api/migrations/0017_auto_20200311_1702.py
|
Abeeaad97/FinancialTracker
|
9e3f02b03de0404389653f6baf824f4b3b7ad958
|
[
"MIT"
] | null | null | null |
backend/api/migrations/0017_auto_20200311_1702.py
|
Abeeaad97/FinancialTracker
|
9e3f02b03de0404389653f6baf824f4b3b7ad958
|
[
"MIT"
] | 1
|
2020-09-09T21:48:54.000Z
|
2020-09-09T21:48:54.000Z
|
# Generated by Django 3.0.3 on 2020-03-12 00:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0016_auto_20200311_1701'),
]
operations = [
migrations.RenameField(
model_name='crypto',
old_name='names',
new_name='name',
),
]
| 18.736842
| 47
| 0.575843
|
bf8012b9ea79c1f51392e7e286c25afcfc6daedc
| 1,019
|
rb
|
Ruby
|
lib/keen/task/TaskInvoker.rb
|
lord-executor/Keen
|
7964b222f6b0c218f411054cc632b66c6171e51d
|
[
"MIT"
] | null | null | null |
lib/keen/task/TaskInvoker.rb
|
lord-executor/Keen
|
7964b222f6b0c218f411054cc632b66c6171e51d
|
[
"MIT"
] | null | null | null |
lib/keen/task/TaskInvoker.rb
|
lord-executor/Keen
|
7964b222f6b0c218f411054cc632b66c6171e51d
|
[
"MIT"
] | null | null | null |
require('keen/arguments/ArgumentParser')
require('keen/arguments/ArgumentType')
module Keen
module TaskInvoker
def self.invoke(clazz, command, args)
obj = clazz.new()
if (!obj.respond_to?(command))
raise ArgumentError.new("Task class #{clazz} does not contain a command '#{command}'")
end
parsedArgs = Keen::ArgumentParser.parse(args)
meta = clazz::get_args(command)
meta.arguments.each() do |key, arg|
matched = false
if (arg.type == ArgumentType::POSITIONAL)
if (parsedArgs.has_key?(arg.position))
matched = true
arg.value = parsedArgs[arg.position].value
end
else
# options and opt-args are not required
matched = true
arg.getAliases().each() do |argAlias|
if (parsedArgs.has_key?(argAlias))
arg.value = parsedArgs[argAlias].value
end
end
end
if (!matched)
raise ArgumentError.new("Unmatched required argument '#{arg.symbol}'")
end
end
return obj.send(command, meta)
end
end
end
| 20.795918
| 90
| 0.65947
|
ff356e852e1ee1c39ca421bfc65efae270b2fa31
| 29,541
|
py
|
Python
|
pypy/rpython/lltypesystem/test/test_ll2ctypes.py
|
camillobruni/pygirl
|
ddbd442d53061d6ff4af831c1eab153bcc771b5a
|
[
"MIT"
] | 12
|
2016-01-06T07:10:28.000Z
|
2021-05-13T23:02:02.000Z
|
pypy/rpython/lltypesystem/test/test_ll2ctypes.py
|
camillobruni/pygirl
|
ddbd442d53061d6ff4af831c1eab153bcc771b5a
|
[
"MIT"
] | null | null | null |
pypy/rpython/lltypesystem/test/test_ll2ctypes.py
|
camillobruni/pygirl
|
ddbd442d53061d6ff4af831c1eab153bcc771b5a
|
[
"MIT"
] | 2
|
2016-07-29T07:09:50.000Z
|
2016-10-16T08:50:26.000Z
|
import py
import sys, struct
import ctypes
from pypy.rpython.lltypesystem import lltype, rffi, llmemory
from pypy.rpython.tool import rffi_platform
from pypy.rpython.lltypesystem.ll2ctypes import lltype2ctypes, ctypes2lltype
from pypy.rpython.lltypesystem.ll2ctypes import standard_c_lib
from pypy.rpython.lltypesystem.ll2ctypes import uninitialized2ctypes
from pypy.rpython.lltypesystem.ll2ctypes import ALLOCATED
from pypy.rpython.annlowlevel import llhelper
from pypy.rlib import rposix
from pypy.translator.tool.cbuild import ExternalCompilationInfo
from pypy.tool.udir import udir
class TestLL2Ctypes(object):
def setup_method(self, meth):
ALLOCATED.clear()
def test_primitive(self):
assert lltype2ctypes(5) == 5
assert lltype2ctypes('?') == ord('?')
assert lltype2ctypes('\xE0') == 0xE0
assert lltype2ctypes(unichr(1234)) == 1234
assert ctypes2lltype(lltype.Signed, 5) == 5
assert ctypes2lltype(lltype.Char, ord('a')) == 'a'
assert ctypes2lltype(lltype.UniChar, ord(u'x')) == u'x'
assert ctypes2lltype(lltype.Char, 0xFF) == '\xFF'
assert lltype2ctypes(5.25) == 5.25
assert ctypes2lltype(lltype.Float, 5.25) == 5.25
assert lltype2ctypes(u'x') == ord(u'x')
res = lltype2ctypes(rffi.r_singlefloat(-3.5))
assert isinstance(res, ctypes.c_float)
assert res.value == -3.5
res = ctypes2lltype(lltype.SingleFloat, ctypes.c_float(-3.5))
assert isinstance(res, rffi.r_singlefloat)
assert float(res) == -3.5
assert lltype2ctypes(rffi.r_ulong(-1)) == sys.maxint * 2 + 1
res = ctypes2lltype(lltype.Unsigned, sys.maxint * 2 + 1)
assert (res, type(res)) == (rffi.r_ulong(-1), rffi.r_ulong)
res = lltype2ctypes(llmemory.sizeof(lltype.Signed))
assert res == struct.calcsize("l")
S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
res = lltype2ctypes(llmemory.sizeof(S))
assert res == struct.calcsize("ll")
p = lltype.nullptr(S)
cptr = lltype2ctypes(p)
assert not cptr
py.test.raises(ValueError, 'cptr.contents') # NULL pointer access
res = ctypes2lltype(lltype.Ptr(S), cptr)
assert res == p
assert not ALLOCATED # detects memory leaks in the test
def test_simple_struct(self):
S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
s = lltype.malloc(S, flavor='raw')
s.x = 123
sc = lltype2ctypes(s)
assert isinstance(sc.contents, ctypes.Structure)
assert sc.contents.x == 123
sc.contents.x = 456
assert s.x == 456
s.x = 789
assert sc.contents.x == 789
s.y = 52
assert sc.contents.y == 52
lltype.free(s, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_struct_ptrs(self):
S2 = lltype.Struct('S2', ('y', lltype.Signed))
S1 = lltype.Struct('S', ('x', lltype.Signed), ('p', lltype.Ptr(S2)))
s1 = lltype.malloc(S1, flavor='raw')
s2a = lltype.malloc(S2, flavor='raw')
s2b = lltype.malloc(S2, flavor='raw')
s2a.y = ord('a')
s2b.y = ord('b')
sc1 = lltype2ctypes(s1)
sc1.contents.x = 50
assert s1.x == 50
sc1.contents.p = lltype2ctypes(s2a)
assert s1.p == s2a
s1.p.y -= 32
assert sc1.contents.p.contents.y == ord('A')
s1.p = s2b
sc1.contents.p.contents.y -= 32
assert s2b.y == ord('B')
lltype.free(s1, flavor='raw')
lltype.free(s2a, flavor='raw')
lltype.free(s2b, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_simple_array(self):
A = lltype.Array(lltype.Signed)
a = lltype.malloc(A, 10, flavor='raw')
a[0] = 100
a[1] = 101
a[2] = 102
ac = lltype2ctypes(a, normalize=False)
assert isinstance(ac.contents, ctypes.Structure)
assert ac.contents.length == 10
assert ac.contents.items[1] == 101
ac.contents.items[2] = 456
assert a[2] == 456
a[3] = 789
assert ac.contents.items[3] == 789
lltype.free(a, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_array_nolength(self):
A = lltype.Array(lltype.Signed, hints={'nolength': True})
a = lltype.malloc(A, 10, flavor='raw')
a[0] = 100
a[1] = 101
a[2] = 102
ac = lltype2ctypes(a, normalize=False)
assert isinstance(ac.contents, ctypes.Structure)
assert ac.contents.items[1] == 101
ac.contents.items[2] = 456
assert a[2] == 456
a[3] = 789
assert ac.contents.items[3] == 789
assert ctypes.sizeof(ac.contents) == 10 * ctypes.sizeof(ctypes.c_long)
lltype.free(a, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_charp(self):
s = rffi.str2charp("hello")
sc = lltype2ctypes(s, normalize=False)
assert sc.contents.items[0] == ord('h')
assert sc.contents.items[1] == ord('e')
assert sc.contents.items[2] == ord('l')
assert sc.contents.items[3] == ord('l')
assert sc.contents.items[4] == ord('o')
assert sc.contents.items[5] == 0
assert not hasattr(sc.contents, 'length')
sc.contents.items[1] = ord('E')
assert s[1] == 'E'
s[0] = 'H'
assert sc.contents.items[0] == ord('H')
rffi.free_charp(s)
assert not ALLOCATED # detects memory leaks in the test
def test_unicharp(self):
SP = rffi.CArrayPtr(lltype.UniChar)
s = lltype.malloc(SP.TO, 4, flavor='raw')
s[0] = u'x'
s[1] = u'y'
s[2] = u'z'
s[3] = u'\x00'
sc = lltype2ctypes(s, normalize=False)
assert sc.contents.items[0] == ord(u'x')
assert sc.contents.items[1] == ord(u'y')
assert sc.contents.items[2] == ord(u'z')
assert not hasattr(sc.contents, 'length')
lltype.free(s, flavor='raw')
assert not ALLOCATED
def test_strlen(self):
eci = ExternalCompilationInfo(includes=['string.h'])
strlen = rffi.llexternal('strlen', [rffi.CCHARP], rffi.SIZE_T,
compilation_info=eci)
s = rffi.str2charp("xxx")
res = strlen(s)
rffi.free_charp(s)
assert res == 3 # actually r_size_t(3)
s = rffi.str2charp("")
res = strlen(s)
rffi.free_charp(s)
assert res == 0 # actually r_size_t(0)
assert not ALLOCATED # detects memory leaks in the test
def test_func_not_in_clib(self):
eci = ExternalCompilationInfo(libraries=['m'])
foobar = rffi.llexternal('I_really_dont_exist', [], lltype.Signed)
py.test.raises(NotImplementedError, foobar)
foobar = rffi.llexternal('I_really_dont_exist', [], lltype.Signed,
compilation_info=eci) # math library
py.test.raises(NotImplementedError, foobar)
eci = ExternalCompilationInfo(libraries=['m', 'z'])
foobar = rffi.llexternal('I_really_dont_exist', [], lltype.Signed,
compilation_info=eci) # math and zlib
py.test.raises(NotImplementedError, foobar)
eci = ExternalCompilationInfo(libraries=['I_really_dont_exist_either'])
foobar = rffi.llexternal('I_really_dont_exist', [], lltype.Signed,
compilation_info=eci)
py.test.raises(NotImplementedError, foobar)
assert not ALLOCATED # detects memory leaks in the test
def test_cstruct_to_ll(self):
S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
s = lltype.malloc(S, flavor='raw')
s2 = lltype.malloc(S, flavor='raw')
s.x = 123
sc = lltype2ctypes(s)
t = ctypes2lltype(lltype.Ptr(S), sc)
assert lltype.typeOf(t) == lltype.Ptr(S)
assert s == t
assert not (s != t)
assert t == s
assert not (t != s)
assert t != lltype.nullptr(S)
assert not (t == lltype.nullptr(S))
assert lltype.nullptr(S) != t
assert not (lltype.nullptr(S) == t)
assert t != s2
assert not (t == s2)
assert s2 != t
assert not (s2 == t)
assert t.x == 123
t.x += 1
assert s.x == 124
s.x += 1
assert t.x == 125
lltype.free(s, flavor='raw')
lltype.free(s2, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_carray_to_ll(self):
A = lltype.Array(lltype.Signed, hints={'nolength': True})
a = lltype.malloc(A, 10, flavor='raw')
a2 = lltype.malloc(A, 10, flavor='raw')
a[0] = 100
a[1] = 101
a[2] = 110
ac = lltype2ctypes(a)
b = ctypes2lltype(lltype.Ptr(A), ac)
assert lltype.typeOf(b) == lltype.Ptr(A)
assert b == a
assert not (b != a)
assert a == b
assert not (a != b)
assert b != lltype.nullptr(A)
assert not (b == lltype.nullptr(A))
assert lltype.nullptr(A) != b
assert not (lltype.nullptr(A) == b)
assert b != a2
assert not (b == a2)
assert a2 != b
assert not (a2 == b)
assert b[2] == 110
b[2] *= 2
assert a[2] == 220
a[2] *= 3
assert b[2] == 660
lltype.free(a, flavor='raw')
lltype.free(a2, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_strchr(self):
eci = ExternalCompilationInfo(includes=['string.h'])
strchr = rffi.llexternal('strchr', [rffi.CCHARP, rffi.INT],
rffi.CCHARP, compilation_info=eci)
s = rffi.str2charp("hello world")
res = strchr(s, ord('r'))
assert res[0] == 'r'
assert res[1] == 'l'
assert res[2] == 'd'
assert res[3] == '\x00'
# XXX maybe we should also allow res[-1], res[-2]...
rffi.free_charp(s)
assert not ALLOCATED # detects memory leaks in the test
def test_frexp(self):
eci = ExternalCompilationInfo(includes=['math.h'],
libraries=['m'])
A = lltype.FixedSizeArray(rffi.INT, 1)
frexp = rffi.llexternal('frexp', [rffi.DOUBLE, lltype.Ptr(A)],
rffi.DOUBLE, compilation_info=eci)
p = lltype.malloc(A, flavor='raw')
res = frexp(2.5, p)
assert res == 0.625
assert p[0] == 2
lltype.free(p, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_rand(self):
eci = ExternalCompilationInfo(includes=['stdlib.h'])
rand = rffi.llexternal('rand', [], rffi.INT,
compilation_info=eci)
srand = rffi.llexternal('srand', [rffi.UINT], lltype.Void,
compilation_info=eci)
srand(rffi.r_uint(123))
res1 = rand()
res2 = rand()
res3 = rand()
srand(rffi.r_uint(123))
res1b = rand()
res2b = rand()
res3b = rand()
assert res1 == res1b
assert res2 == res2b
assert res3 == res3b
assert not ALLOCATED # detects memory leaks in the test
def test_opaque_obj(self):
eci = ExternalCompilationInfo(
includes = ['sys/time.h', 'time.h']
)
TIMEVALP = rffi.COpaquePtr('struct timeval', compilation_info=eci)
TIMEZONEP = rffi.COpaquePtr('struct timezone', compilation_info=eci)
gettimeofday = rffi.llexternal('gettimeofday', [TIMEVALP, TIMEZONEP],
rffi.INT, compilation_info=eci)
ll_timevalp = lltype.malloc(TIMEVALP.TO, flavor='raw')
ll_timezonep = lltype.malloc(TIMEZONEP.TO, flavor='raw')
res = gettimeofday(ll_timevalp, ll_timezonep)
assert res != -1
lltype.free(ll_timezonep, flavor='raw')
lltype.free(ll_timevalp, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_simple_cast(self):
assert rffi.cast(rffi.SIGNEDCHAR, 0x123456) == 0x56
assert rffi.cast(rffi.SIGNEDCHAR, 0x123481) == -127
assert rffi.cast(rffi.CHAR, 0x123456) == '\x56'
assert rffi.cast(rffi.CHAR, 0x123481) == '\x81'
assert rffi.cast(rffi.UCHAR, 0x123481) == 0x81
assert not ALLOCATED # detects memory leaks in the test
def test_forced_ptr_cast(self):
import array
A = lltype.Array(lltype.Signed, hints={'nolength': True})
B = lltype.Array(lltype.Char, hints={'nolength': True})
a = lltype.malloc(A, 10, flavor='raw')
for i in range(10):
a[i] = i*i
b = rffi.cast(lltype.Ptr(B), a)
checker = array.array('l')
for i in range(10):
checker.append(i*i)
expected = checker.tostring()
for i in range(len(expected)):
assert b[i] == expected[i]
c = rffi.cast(rffi.VOIDP, a)
addr = lltype2ctypes(c)
#assert addr == ctypes.addressof(a._obj._ctypes_storage)
d = ctypes2lltype(rffi.VOIDP, addr)
assert lltype.typeOf(d) == rffi.VOIDP
assert c == d
e = rffi.cast(lltype.Ptr(A), d)
for i in range(10):
assert e[i] == i*i
c = lltype.nullptr(rffi.VOIDP.TO)
addr = rffi.cast(lltype.Signed, c)
assert addr == 0
lltype.free(a, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_funcptr1(self):
def dummy(n):
return n+1
FUNCTYPE = lltype.FuncType([lltype.Signed], lltype.Signed)
cdummy = lltype2ctypes(llhelper(lltype.Ptr(FUNCTYPE), dummy))
assert isinstance(cdummy,
ctypes.CFUNCTYPE(ctypes.c_long, ctypes.c_long))
res = cdummy(41)
assert res == 42
lldummy = ctypes2lltype(lltype.Ptr(FUNCTYPE), cdummy)
assert lltype.typeOf(lldummy) == lltype.Ptr(FUNCTYPE)
res = lldummy(41)
assert res == 42
assert not ALLOCATED # detects memory leaks in the test
def test_funcptr2(self):
FUNCTYPE = lltype.FuncType([rffi.CCHARP], lltype.Signed)
cstrlen = standard_c_lib.strlen
llstrlen = ctypes2lltype(lltype.Ptr(FUNCTYPE), cstrlen)
assert lltype.typeOf(llstrlen) == lltype.Ptr(FUNCTYPE)
p = rffi.str2charp("hi there")
res = llstrlen(p)
assert res == 8
cstrlen2 = lltype2ctypes(llstrlen)
cp = lltype2ctypes(p)
assert cstrlen2.restype == ctypes.c_long
res = cstrlen2(cp)
assert res == 8
rffi.free_charp(p)
assert not ALLOCATED # detects memory leaks in the test
def test_qsort(self):
CMPFUNC = lltype.FuncType([rffi.VOIDP, rffi.VOIDP], rffi.INT)
qsort = rffi.llexternal('qsort', [rffi.VOIDP,
rffi.SIZE_T,
rffi.SIZE_T,
lltype.Ptr(CMPFUNC)],
lltype.Void)
lst = [23, 43, 24, 324, 242, 34, 78, 5, 3, 10]
A = lltype.Array(lltype.Signed, hints={'nolength': True})
a = lltype.malloc(A, 10, flavor='raw')
for i in range(10):
a[i] = lst[i]
SIGNEDPTR = lltype.Ptr(lltype.FixedSizeArray(lltype.Signed, 1))
def my_compar(p1, p2):
p1 = rffi.cast(SIGNEDPTR, p1)
p2 = rffi.cast(SIGNEDPTR, p2)
print 'my_compar:', p1[0], p2[0]
return rffi.cast(rffi.INT, cmp(p1[0], p2[0]))
qsort(rffi.cast(rffi.VOIDP, a),
rffi.cast(rffi.SIZE_T, 10),
rffi.cast(rffi.SIZE_T, llmemory.sizeof(lltype.Signed)),
llhelper(lltype.Ptr(CMPFUNC), my_compar))
for i in range(10):
print a[i],
print
lst.sort()
for i in range(10):
assert a[i] == lst[i]
lltype.free(a, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
# def test_signal(self):...
def test_uninitialized2ctypes(self):
# for now, uninitialized fields are filled with 0xDD in the ctypes data
def checkobj(o, size):
p = ctypes.cast(ctypes.c_void_p(ctypes.addressof(o)),
ctypes.POINTER(ctypes.c_ubyte*size))
for i in range(size):
assert p.contents[i] == 0xDD
def checkval(v, fmt):
res = struct.pack(fmt, v)
assert res == "\xDD" * len(res)
checkval(uninitialized2ctypes(rffi.CHAR), 'B')
checkval(uninitialized2ctypes(rffi.SHORT), 'h')
checkval(uninitialized2ctypes(rffi.INT), 'i')
checkval(uninitialized2ctypes(rffi.UINT), 'I')
checkval(uninitialized2ctypes(rffi.LONGLONG), 'q')
checkval(uninitialized2ctypes(rffi.DOUBLE), 'd')
checkobj(uninitialized2ctypes(rffi.INTP),
ctypes.sizeof(ctypes.c_void_p))
checkobj(uninitialized2ctypes(rffi.CCHARP),
ctypes.sizeof(ctypes.c_void_p))
S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
s = lltype.malloc(S, flavor='raw')
sc = lltype2ctypes(s)
checkval(sc.contents.x, 'l')
checkval(sc.contents.y, 'l')
lltype.free(s, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_substructures(self):
S1 = lltype.Struct('S1', ('x', lltype.Signed))
BIG = lltype.Struct('BIG', ('s1a', S1), ('s1b', S1))
s = lltype.malloc(BIG, flavor='raw')
s.s1a.x = 123
s.s1b.x = 456
sc = lltype2ctypes(s)
assert sc.contents.s1a.x == 123
assert sc.contents.s1b.x == 456
sc.contents.s1a.x += 1
sc.contents.s1b.x += 10
assert s.s1a.x == 124
assert s.s1b.x == 466
s.s1a.x += 3
s.s1b.x += 30
assert sc.contents.s1a.x == 127
assert sc.contents.s1b.x == 496
lltype.free(s, flavor='raw')
s = lltype.malloc(BIG, flavor='raw')
s1ac = lltype2ctypes(s.s1a)
s1ac.contents.x = 53
sc = lltype2ctypes(s)
assert sc.contents.s1a.x == 53
sc.contents.s1a.x += 1
assert s1ac.contents.x == 54
assert s.s1a.x == 54
s.s1a.x += 2
assert s1ac.contents.x == 56
assert sc.contents.s1a.x == 56
sc.contents.s1a.x += 3
assert s1ac.contents.x == 59
assert s.s1a.x == 59
t = ctypes2lltype(lltype.Ptr(BIG), sc)
assert t == s
assert t.s1a == s.s1a
assert t.s1a.x == 59
s.s1b.x = 8888
assert t.s1b == s.s1b
assert t.s1b.x == 8888
t1 = ctypes2lltype(lltype.Ptr(S1), s1ac)
assert t.s1a == t1
assert t1.x == 59
t1.x += 1
assert sc.contents.s1a.x == 60
lltype.free(s, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_recursive_struct(self):
SX = lltype.ForwardReference()
S1 = lltype.Struct('S1', ('p', lltype.Ptr(SX)), ('x', lltype.Signed))
SX.become(S1)
# a chained list
s1 = lltype.malloc(S1, flavor='raw')
s2 = lltype.malloc(S1, flavor='raw')
s3 = lltype.malloc(S1, flavor='raw')
s1.x = 111
s2.x = 222
s3.x = 333
s1.p = s2
s2.p = s3
s3.p = lltype.nullptr(S1)
sc1 = lltype2ctypes(s1)
sc2 = sc1.contents.p
sc3 = sc2.contents.p
assert not sc3.contents.p
assert sc1.contents.x == 111
assert sc2.contents.x == 222
assert sc3.contents.x == 333
sc3.contents.x += 1
assert s3.x == 334
s3.x += 2
assert sc3.contents.x == 336
lltype.free(s1, flavor='raw')
lltype.free(s2, flavor='raw')
lltype.free(s3, flavor='raw')
# a self-cycle
s1 = lltype.malloc(S1, flavor='raw')
s1.x = 12
s1.p = s1
sc1 = lltype2ctypes(s1)
assert sc1.contents.x == 12
assert (ctypes.addressof(sc1.contents.p.contents) ==
ctypes.addressof(sc1.contents))
s1.x *= 5
assert sc1.contents.p.contents.p.contents.p.contents.x == 60
lltype.free(s1, flavor='raw')
# a longer cycle
s1 = lltype.malloc(S1, flavor='raw')
s2 = lltype.malloc(S1, flavor='raw')
s1.x = 111
s1.p = s2
s2.x = 222
s2.p = s1
sc1 = lltype2ctypes(s1)
assert sc1.contents.x == 111
assert sc1.contents.p.contents.x == 222
assert (ctypes.addressof(sc1.contents.p.contents) !=
ctypes.addressof(sc1.contents))
assert (ctypes.addressof(sc1.contents.p.contents.p.contents) ==
ctypes.addressof(sc1.contents))
lltype.free(s1, flavor='raw')
lltype.free(s2, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_indirect_recursive_struct(self):
S2Forward = lltype.ForwardReference()
S1 = lltype.Struct('S1', ('p', lltype.Ptr(S2Forward)))
A2 = lltype.Array(lltype.Ptr(S1), hints={'nolength': True})
S2 = lltype.Struct('S2', ('a', lltype.Ptr(A2)))
S2Forward.become(S2)
s1 = lltype.malloc(S1, flavor='raw')
a2 = lltype.malloc(A2, 10, flavor='raw')
s2 = lltype.malloc(S2, flavor='raw')
s2.a = a2
a2[5] = s1
s1.p = s2
ac2 = lltype2ctypes(a2, normalize=False)
sc1 = ac2.contents.items[5]
sc2 = sc1.contents.p
assert (ctypes.addressof(sc2.contents.a.contents) ==
ctypes.addressof(ac2.contents))
lltype.free(s1, flavor='raw')
lltype.free(a2, flavor='raw')
lltype.free(s2, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_arrayofstruct(self):
S1 = lltype.Struct('S1', ('x', lltype.Signed))
A = lltype.Array(S1, hints={'nolength': True})
a = lltype.malloc(A, 5, flavor='raw')
a[0].x = 100
a[1].x = 101
a[2].x = 102
a[3].x = 103
a[4].x = 104
ac = lltype2ctypes(a, normalize=False)
assert ac.contents.items[0].x == 100
assert ac.contents.items[2].x == 102
ac.contents.items[3].x += 500
assert a[3].x == 603
a[4].x += 600
assert ac.contents.items[4].x == 704
a1 = ctypes2lltype(lltype.Ptr(A), ac)
assert a1 == a
assert a1[2].x == 102
aitem1 = ctypes2lltype(lltype.Ptr(S1),
ctypes.pointer(ac.contents.items[1]))
assert aitem1.x == 101
assert aitem1 == a1[1]
lltype.free(a, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_get_errno(self):
eci = ExternalCompilationInfo(includes=['string.h'])
if sys.platform.startswith('win'):
underscore_on_windows = '_'
else:
underscore_on_windows = ''
strlen = rffi.llexternal('strlen', [rffi.CCHARP], rffi.SIZE_T,
compilation_info=eci)
os_write = rffi.llexternal(underscore_on_windows+'write',
[rffi.INT, rffi.CCHARP, rffi.SIZE_T],
rffi.SIZE_T)
buffer = lltype.malloc(rffi.CCHARP.TO, 5, flavor='raw')
written = os_write(12312312, buffer, 5)
lltype.free(buffer, flavor='raw')
assert rffi.cast(lltype.Signed, written) < 0
# the next line is a random external function call,
# to check that it doesn't reset errno
strlen("hi!")
err = rposix.get_errno()
import errno
assert err == errno.EBADF
assert not ALLOCATED # detects memory leaks in the test
def test_call_with_struct_argument(self):
# XXX is there such a function in the standard C headers?
from pypy.rlib import _rsocket_rffi
buf = rffi.make(_rsocket_rffi.in_addr)
rffi.cast(rffi.CCHARP, buf)[0] = '\x01'
rffi.cast(rffi.CCHARP, buf)[1] = '\x02'
rffi.cast(rffi.CCHARP, buf)[2] = '\x03'
rffi.cast(rffi.CCHARP, buf)[3] = '\x04'
p = _rsocket_rffi.inet_ntoa(buf)
assert rffi.charp2str(p) == '1.2.3.4'
lltype.free(buf, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_storage_stays_around(self):
data = "hello, world!" * 100
A = lltype.Array(rffi.CHAR, hints={'nolength': True})
S = lltype.Struct('S', ('a', lltype.Ptr(A)))
s = lltype.malloc(S, flavor='raw')
lltype2ctypes(s) # force it to escape
s.a = lltype.malloc(A, len(data), flavor='raw')
# the storage for the array should not be freed by lltype even
# though the _ptr object appears to go away here
for i in xrange(len(data)):
s.a[i] = data[i]
for i in xrange(len(data)):
assert s.a[i] == data[i]
lltype.free(s.a, flavor='raw')
lltype.free(s, flavor='raw')
assert not ALLOCATED # detects memory leaks in the test
def test_arrayoffloat(self):
a = lltype.malloc(rffi.FLOATP.TO, 3, flavor='raw')
a[0] = rffi.r_singlefloat(0.0)
a[1] = rffi.r_singlefloat(1.1)
a[2] = rffi.r_singlefloat(2.2)
ac = lltype2ctypes(a, normalize=False)
assert ac.contents.items[0] == 0.0
assert abs(ac.contents.items[1] - 1.1) < 1E-6
assert abs(ac.contents.items[2] - 2.2) < 1E-6
b = ctypes2lltype(rffi.FLOATP, ac)
assert isinstance(b[0], rffi.r_singlefloat)
assert float(b[0]) == 0.0
assert isinstance(b[1], rffi.r_singlefloat)
assert abs(float(b[1]) - 1.1) < 1E-6
assert isinstance(b[2], rffi.r_singlefloat)
assert abs(float(b[2]) - 2.2) < 1E-6
def test_different_signatures(self):
fcntl_int = rffi.llexternal('fcntl', [rffi.INT, rffi.INT, rffi.INT],
rffi.INT)
fcntl_str = rffi.llexternal('fcntl', [rffi.INT, rffi.INT, rffi.CCHARP],
rffi.INT)
fcntl_int(12345, 1, 0)
fcntl_str(12345, 3, "xxx")
fcntl_int(12345, 1, 0)
def test_llexternal_source(self):
eci = ExternalCompilationInfo(
separate_module_sources = ["int fn() { return 42; }"]
)
fn = rffi.llexternal('fn', [], rffi.INT, compilation_info=eci)
res = fn()
assert res == 42
def test_prebuilt_constant(self):
header = py.code.Source("""
#ifndef _SOME_H
#define _SOME_H
#include <stdlib.h>
static int x = 3;
char **z = NULL;
#endif /* _SOME_H */
""")
h_file = udir.join("some_h.h")
h_file.write(header)
eci = ExternalCompilationInfo(includes=['stdio.h', str(h_file.basename)],
include_dirs=[str(udir)])
get_x, set_x = rffi.CExternVariable(rffi.LONG, 'x', eci)
get_z, set_z = rffi.CExternVariable(rffi.CCHARPP, 'z', eci)
def f():
one = get_x()
set_x(13)
return one + get_x()
def g():
l = rffi.liststr2charpp(["a", "b", "c"])
try:
set_z(l)
return rffi.charp2str(get_z()[2])
finally:
rffi.free_charpp(l)
res = f()
assert res == 16
assert g() == "c"
def test_c_callback(self):
c_source = py.code.Source("""
int eating_callback(int arg, int(*call)(int))
{
return call(arg);
}
""")
eci = ExternalCompilationInfo(separate_module_sources=[c_source])
args = [rffi.INT, rffi.CCallback([rffi.INT], rffi.INT)]
eating_callback = rffi.llexternal('eating_callback', args, rffi.INT,
compilation_info=eci)
def g(i):
return i + 3
def f():
return eating_callback(3, g)
assert f() == 6
def test_qsort(self):
TP = rffi.CArrayPtr(rffi.INT)
a = lltype.malloc(TP.TO, 5, flavor='raw')
a[0] = 5
a[1] = 3
a[2] = 2
a[3] = 1
a[4] = 4
def compare(a, b):
if a[0] > b[0]:
return 1
else:
return -1
CALLBACK = rffi.CCallback([rffi.VOIDP, rffi.VOIDP], rffi.INT)
qsort = rffi.llexternal('qsort', [rffi.VOIDP, rffi.INT,
rffi.INT, CALLBACK], lltype.Void)
qsort(rffi.cast(rffi.VOIDP, a), 5, rffi.sizeof(rffi.INT), compare)
for i in range(5):
assert a[i] == i + 1
def test_array_type_bug(self):
A = lltype.Array(lltype.Signed)
a1 = lltype.malloc(A, 0, flavor='raw')
a2 = lltype.malloc(A, 0, flavor='raw')
c1 = lltype2ctypes(a1)
c2 = lltype2ctypes(a2)
assert type(c1) is type(c2)
| 37.299242
| 81
| 0.554991
|
973fae3c25dbb62562190d43ca4b2f60dd1e6983
| 4,717
|
dart
|
Dart
|
lib/src/avatar_ring.dart
|
xioxin/flutter_boring_avatars
|
04e50381147fa7fc44c925ba1facbf2b0fb8967a
|
[
"MIT"
] | 2
|
2022-01-31T04:38:10.000Z
|
2022-01-31T12:12:43.000Z
|
lib/src/avatar_ring.dart
|
xioxin/flutter_boring_avatars
|
04e50381147fa7fc44c925ba1facbf2b0fb8967a
|
[
"MIT"
] | null | null | null |
lib/src/avatar_ring.dart
|
xioxin/flutter_boring_avatars
|
04e50381147fa7fc44c925ba1facbf2b0fb8967a
|
[
"MIT"
] | null | null | null |
import 'dart:math';
import 'package:flutter/material.dart';
import './utilities.dart';
import 'dart:ui';
import 'avatar_base.dart';
import 'package:flutter/foundation.dart';
const List<String> _avatarRingPath = [
'M0 0h90v45H0z',
'M0 45h90v45H0z',
'M83 45a38 38 0 00-76 0h76z',
'M83 45a38 38 0 01-76 0h76z',
'M77 45a32 32 0 10-64 0h64z',
'M77 45a32 32 0 11-64 0h64z',
'M71 45a26 26 0 00-52 0h52z',
'M71 45a26 26 0 01-52 0h52z',
];
class AvatarRingData {
late List<Color> colorList;
AvatarRingData({
required this.colorList,
});
static lerp(AvatarRingData? a, AvatarRingData? b, double t) {
final newColor = List.generate(
max(a?.colorList.length ?? 0, b?.colorList.length ?? 0),
(index) => Color.lerp(a?.colorList[index], b?.colorList[index], t)!);
return AvatarRingData(colorList: newColor);
}
AvatarRingData.generate(String name, [List<Color>? colors]) {
colors ??= defaultBoringAvatarsColors;
final numFromName = getNumber(name);
final range = colors.length;
final colorsShuffle = List.generate(
5, (i) => getRandomColor<Color>(numFromName + (1 + i), colors!, range));
colorList = [
colorsShuffle[0],
colorsShuffle[1],
colorsShuffle[1],
colorsShuffle[2],
colorsShuffle[2],
colorsShuffle[3],
colorsShuffle[3],
colorsShuffle[0],
colorsShuffle[4],
];
}
@override
operator ==(Object other) {
if (identical(this, other)) return true;
if (other.runtimeType != runtimeType) return false;
if (other is AvatarRingData) {
if (colorList.length != other.colorList.length) return false;
int i = 0;
return colorList.every((c) => c == other.colorList[i++]);
}
return false;
}
@override
int get hashCode => Object.hashAll(colorList);
}
class AvatarRingPainter extends AvatarCustomPainter {
final AvatarRingData properties;
@override
double get boxSize => 90;
AvatarRingPainter(String name, [List<Color>? colors])
: properties = AvatarRingData.generate(name, colors);
AvatarRingPainter.data(this.properties);
@override
void paint(Canvas canvas, Size size) {
this.size = size;
canvas.clipRect(Rect.fromLTRB(0, 0, size.width, size.height));
int i = 0;
for (var pathString in _avatarRingPath) {
final color = properties.colorList[i++];
canvas.drawPath(svgPath(pathString), fillPaint(color));
}
canvas.drawCircle(Offset(size.width / 2, size.height / 2), cX(23),
fillPaint(properties.colorList.last));
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return oldDelegate is AvatarRingPainter &&
oldDelegate.properties != properties;
}
}
class AvatarRingDataTween extends Tween<AvatarRingData?> {
AvatarRingDataTween({AvatarRingData? begin, AvatarRingData? end})
: super(begin: begin, end: end);
@override
AvatarRingData? lerp(double t) => AvatarRingData.lerp(begin, end, t);
}
class AnimatedAvatarRing extends ImplicitlyAnimatedWidget {
AnimatedAvatarRing({
Key? key,
required this.name,
this.colors,
Curve curve = Curves.linear,
required Duration duration,
VoidCallback? onEnd,
this.size = Size.zero,
}) : data = AvatarRingData.generate(name, colors),
super(key: key, curve: curve, duration: duration, onEnd: onEnd);
final String name;
final List<Color>? colors;
final AvatarRingData data;
final Size size;
@override
AnimatedWidgetBaseState<AnimatedAvatarRing> createState() =>
_AnimatedAvatarRingState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<String>('name', name));
properties.add(DiagnosticsProperty<List<Color>?>('colors', colors));
properties.add(DiagnosticsProperty<AvatarRingData>('data', data));
properties.add(DiagnosticsProperty<Size>('size', size));
}
}
class _AnimatedAvatarRingState
extends AnimatedWidgetBaseState<AnimatedAvatarRing> {
AvatarRingDataTween? _data;
@override
void forEachTween(TweenVisitor<dynamic> visitor) {
_data = visitor(_data, widget.data,
(dynamic value) => AvatarRingDataTween(begin: value))
as AvatarRingDataTween?;
}
@override
Widget build(BuildContext context) {
return CustomPaint(
size: widget.size,
painter: AvatarRingPainter.data(_data!.evaluate(animation)!),
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(DiagnosticsProperty<AvatarRingDataTween>('data', _data,
defaultValue: null));
}
}
| 29.298137
| 80
| 0.691117
|
5acf3f9b840e8bfaf88b127b235f5a897c900c47
| 676
|
cs
|
C#
|
NetfoxCore/Detective/App/Netfox.Detective/ViewModels/DetectiveInvestigationPaneViewModelBase.cs
|
pokornysimon/NetfoxDetective
|
4d68923b12b2b259a9ca3bc0bba5c065cab02e5e
|
[
"Apache-2.0"
] | null | null | null |
NetfoxCore/Detective/App/Netfox.Detective/ViewModels/DetectiveInvestigationPaneViewModelBase.cs
|
pokornysimon/NetfoxDetective
|
4d68923b12b2b259a9ca3bc0bba5c065cab02e5e
|
[
"Apache-2.0"
] | null | null | null |
NetfoxCore/Detective/App/Netfox.Detective/ViewModels/DetectiveInvestigationPaneViewModelBase.cs
|
pokornysimon/NetfoxDetective
|
4d68923b12b2b259a9ca3bc0bba5c065cab02e5e
|
[
"Apache-2.0"
] | null | null | null |
using Castle.Windsor;
namespace Netfox.Detective.ViewModels
{
/// <summary>
/// Use as a base class of any singletonouse investigation related ViewModel docked in panes
/// </summary>
public abstract class DetectiveInvestigationPaneViewModelBase : DetectivePaneViewModelBase
{
protected DetectiveInvestigationPaneViewModelBase(IWindsorContainer applicationWindsorContainer) : base(
applicationWindsorContainer)
{
//Call this in constructor of inhereted members
//DispatcherHelper.CheckBeginInvokeOnUI(() => this.View = this.InvestigationOrAppWindsorContainer.Resolve<IXXXView>());
}
}
}
| 39.764706
| 131
| 0.715976
|
97fd2670b569354d2f146a4ccfa90b708cb951fd
| 3,160
|
rake
|
Ruby
|
lib/tasks/tasks.rake
|
jclemans/spec-importer
|
a2c49101b6078801a6f062b8a310151ad07ff0fa
|
[
"MIT"
] | 1
|
2020-02-07T23:48:27.000Z
|
2020-02-07T23:48:27.000Z
|
lib/tasks/tasks.rake
|
jclemans/spec-importer
|
a2c49101b6078801a6f062b8a310151ad07ff0fa
|
[
"MIT"
] | null | null | null |
lib/tasks/tasks.rake
|
jclemans/spec-importer
|
a2c49101b6078801a6f062b8a310151ad07ff0fa
|
[
"MIT"
] | null | null | null |
require 'rake'
require 'creek'
require 'thor'
namespace :import do
task :object, [:file_path, :sheet_number, :object_action] => :environment do |t, args|
desc 'Add, Remove, or Update Fae powered CMS objects from an xlsx file.'
if args.count == 3
# Try getting the file path and sheet from args if passed in
path = args[:file_path]
num = args[:sheet_number]
object_action = args[:object_action]
creek ||= Creek::Book.new path
else
# Use the command line prompt to set file path and choose sheet
STDOUT.puts "Enter path to xlsx file in project (E.g. 'tmp/testfile.xlsx')."
path = STDIN.gets.chomp
creek = Creek::Book.new path
STDOUT.puts(creek.sheets.to_a.map.with_index { |obj, i| "#{i}: #{obj.name}" })
STDOUT.puts "Select sheet to import: [0-#{creek.sheets.length}]"
num = STDIN.gets.chomp
end
sheet = creek.sheets[num.to_i]
# if the sheet is the "ToRemoveList", read the list and remove objects we don't need
if sheet.name.upcase.eql?('OBJECTS TO REMOVE')
STDOUT.puts "Reading the OBJECTS TO REMOVE rows...\n"
SpecImporter.remove_objects(sheet)
# otherwise read the sheet and create or update object as specified in the sheet
else
parent_class = sheet.simple_rows.to_a[8]['D']
fae_generator_type = sheet.simple_rows.to_a[8]['B']
# set the action from the sheet if it's not passed in via the task args
object_action ||= sheet.simple_rows.first['D']
case object_action
when 'Create'
script_args = SpecImporter.create_object(sheet)
when 'Update'
script_args = SpecImporter.update_object(sheet)
else
abort 'No action was selected for this object. Task aborted.'
end
if fae_generator_type == 'nested_scaffold' && parent_class.present?
script_args[:fae] << "--parent-model=#{parent_class}"
end
# run the generators
sh "#{script_args[:fae].join(' ')}"
script_args[:joins].each do |generate_join_string|
sh generate_join_string
end
# run migrations
# uncomment to automatically run migrations. leave commented to run manually.
# sh 'rake db:migrate'
# apply form labels, helper text, etc
SpecImporter.update_form_fields(sheet)
end
end
task :restart => :environment do
desc 'restart the server after an import to get new routes/objects loaded'
sh 'rails restart'
end
task :form => :environment do
desc 'Read and import field labels and helper text from a xlsx cms spec file.'
STDOUT.puts "Enter path to xlsx file in project (ex. tmp/file.xlsx)"
path = STDIN.gets.chomp
creek = Creek::Book.new path
STDOUT.puts(creek.sheets.to_a.map.with_index { |obj, i| "#{i}: #{obj.name}" })
STDOUT.puts "Select sheet to import: [0-#{creek.sheets.length}]"
num = STDIN.gets.chomp
sheet = creek.sheets[num.to_i]
SpecImporter.update_form_fields(sheet)
end
class ThorAction < Thor
include Thor::Actions
end
def thor_action(*args)
ThorAction.new.send(*args)
end
end
| 36.744186
| 88
| 0.654747
|
d6187445b140fe3669b6de351aaf2763132655c6
| 1,219
|
asm
|
Assembly
|
programs/oeis/298/A298788.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
programs/oeis/298/A298788.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
programs/oeis/298/A298788.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
; A298788: Coordination sequence for bey tiling (or net) with respect to a trivalent node.
; 1,3,7,12,13,17,24,23,27,36,33,37,48,43,47,60,53,57,72,63,67,84,73,77,96,83,87,108,93,97,120,103,107,132,113,117,144,123,127,156,133,137,168,143,147,180,153,157,192,163,167,204,173,177,216,183,187,228,193,197,240,203,207,252,213,217,264,223,227,276,233,237,288,243,247,300,253,257,312,263,267,324,273,277,336,283,287,348,293,297,360,303,307,372,313,317,384,323,327,396,333,337,408,343,347,420,353,357,432,363,367,444,373,377,456,383,387,468,393,397,480,403,407,492,413,417,504,423,427,516,433,437,528,443,447,540,453,457,552,463,467,564,473,477,576,483,487,588,493,497,600,503,507,612,513,517,624,523,527,636,533,537,648,543,547,660,553,557,672,563,567,684,573,577,696,583,587,708,593,597,720,603,607,732,613,617,744,623,627,756,633,637,768,643,647,780,653,657,792,663,667,804,673,677,816,683,687,828,693,697,840,703,707,852,713,717,864,723,727,876,733,737,888,743,747,900,753,757,912,763,767,924,773,777,936,783,787,948,793,797,960,803,807,972,813,817,984,823,827,996
pow $1,$0
add $1,$0
mov $2,3
mov $3,$0
gcd $0,3
lpb $0,1
mul $1,$0
div $0,6
add $1,1
add $1,$2
div $1,$2
lpe
sub $1,1
mov $4,$3
mul $4,3
add $1,$4
| 60.95
| 969
| 0.711239
|
b8b0eb2a4a546bcdadf2da130ff2a4ddee7acb52
| 2,266
|
h
|
C
|
src/platform/sim/sim/Simulator.h
|
ukyzky/performer
|
451bc853cb0f06a8d8f32f37851dd7c5f2a2f4d0
|
[
"MIT"
] | 181
|
2018-10-12T07:21:08.000Z
|
2022-03-21T06:02:15.000Z
|
src/platform/sim/sim/Simulator.h
|
ukyzky/performer
|
451bc853cb0f06a8d8f32f37851dd7c5f2a2f4d0
|
[
"MIT"
] | 340
|
2019-03-06T07:24:40.000Z
|
2022-03-21T03:31:31.000Z
|
src/platform/sim/sim/Simulator.h
|
ukyzky/performer
|
451bc853cb0f06a8d8f32f37851dd7c5f2a2f4d0
|
[
"MIT"
] | 60
|
2018-10-12T18:43:04.000Z
|
2022-03-31T18:03:17.000Z
|
#pragma once
#include "Target.h"
#include "TargetStateTracker.h"
#include "TargetTrace.h"
#include <array>
#include <functional>
#include <string>
#include <vector>
class MidiMessage;
namespace sim {
class Simulator : public TargetInputHandler, public TargetOutputHandler {
public:
Simulator(Target target);
virtual ~Simulator();
void wait(int ms);
void setButton(int index, bool pressed);
void setEncoder(bool pressed);
void rotateEncoder(int direction);
void setAdc(int channel, float voltage);
void setDio(int pin, bool state);
void sendMidi(int port, const MidiMessage &message);
void screenshot(const std::string &filename);
const TargetState &targetState() const { return _targetState; }
double ticks();
typedef std::function<void()> UpdateCallback;
void addUpdateCallback(UpdateCallback callback);
// Target input/output handling
void registerTargetTickObserver(TargetTickHandler *observer);
void registerTargetInputObserver(TargetInputHandler *observer);
void registerTargetOutputObserver(TargetOutputHandler *observer);
// TargetInputHandler
void writeButton(int index, bool pressed) override;
void writeEncoder(EncoderEvent event) override;
void writeAdc(int channel, uint16_t value) override;
void writeDigitalInput(int pin, bool value) override;
void writeMidiInput(MidiEvent event) override;
// TargetOutputHandler
void writeLed(int index, bool red, bool green) override;
void writeGateOutput(int channel, bool value) override;
void writeDac(int channel, uint16_t value) override;
void writeDigitalOutput(int pin, bool value) override;
void writeLcd(const FrameBuffer &frameBuffer) override;
void writeMidiOutput(MidiEvent event) override;
static Simulator &instance();
private:
void step();
Target _target;
bool _targetCreated = false;
uint32_t _tick = 0;
std::vector<TargetTickHandler *> _targetTickObservers;
std::vector<TargetInputHandler *> _targetInputObservers;
std::vector<TargetOutputHandler *> _targetOutputObservers;
std::vector<UpdateCallback> _updateCallbacks;
TargetState _targetState;
TargetStateTracker _targetStateTracker;
};
} // namespace sim
| 27.975309
| 73
| 0.74316
|
257290092c870c9a105eeca3a6279197cf5b77d0
| 18,296
|
cs
|
C#
|
Sledge.Editor/Compiling/CompileDialog.cs
|
tohateam/SledgeEditorRu
|
409023f7ec5889e1631f718d06c5eb9a270ec297
|
[
"Apache-2.0"
] | 1
|
2020-06-06T22:01:04.000Z
|
2020-06-06T22:01:04.000Z
|
Sledge.Editor/Compiling/CompileDialog.cs
|
tohateam/SledgeEditorRu
|
409023f7ec5889e1631f718d06c5eb9a270ec297
|
[
"Apache-2.0"
] | null | null | null |
Sledge.Editor/Compiling/CompileDialog.cs
|
tohateam/SledgeEditorRu
|
409023f7ec5889e1631f718d06c5eb9a270ec297
|
[
"Apache-2.0"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sledge.QuickForms;
using Sledge.Settings;
using Sledge.Settings.Models;
namespace Sledge.Editor.Compiling
{
public partial class CompileDialog : Form
{
private CompileSpecification _specification;
private BuildProfile _profile;
private CompilePreset _preset;
private Build _build;
private Size _simpleSize = new Size(320, 450);
private Size _advancedSize = new Size(750, 550);
public CompileDialog(Build build)
{
InitializeComponent();
// Hide the panels
AdvancedPanel.Size = Size.Empty;
SimplePanel.Size = Size.Empty;
// Open the default mode
(Sledge.Settings.View.CompileDefaultAdvanced ? AdvancedPanel : SimplePanel).Dock = DockStyle.Fill;
Size = (Sledge.Settings.View.CompileDefaultAdvanced ? _advancedSize : _simpleSize);
_build = build;
_specification = CompileSpecification.Specifications.FirstOrDefault(x => x.ID == build.Specification) ??
CompileSpecification.Specifications.FirstOrDefault() ??
new CompileSpecification {ID = "", Name = "No Specification Found"};
Text = "Compile Map - " + _specification.Name;
AddParameters();
UpdateProfiles();
}
private void UpdateProfiles()
{
if (!_build.Profiles.Any())
{
_profile = CreateProfile("Default");
}
var profs = _build.Profiles;
var idx = profs.IndexOf(_profile);
if (idx < 0) idx = ProfileSelect.SelectedIndex;
ProfileSelect.Items.Clear();
PresetTable.Controls.Clear();
PresetTable.RowStyles.Clear();
if (_specification.Presets.Any())
{
PresetTable.RowStyles.Add(new RowStyle(SizeType.AutoSize));
PresetTable.Controls.Add(new Label
{
Text = "Choose a preset to use for the compile:",
Dock = DockStyle.Top
});
foreach (var preset in _specification.Presets)
{
PresetTable.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var btn = new HeadingButton
{
HeadingText = preset.Name,
Text = preset.Description,
Dock = DockStyle.Top
};
var pre = preset;
btn.Click += (s, e) => UsePreset(pre);
PresetTable.Controls.Add(btn);
}
PresetTable.RowStyles.Add(new RowStyle(SizeType.AutoSize));
PresetTable.Controls.Add(new Label {Text = "Or select from a custom profile:", Dock = DockStyle.Top});
}
else
{
PresetTable.RowStyles.Add(new RowStyle(SizeType.AutoSize));
PresetTable.Controls.Add(new Label { Text = "Select a profile to use for the compile:", Dock = DockStyle.Top });
}
foreach (var profile in profs)
{
ProfileSelect.Items.Add(profile);
PresetTable.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var btn = new Button
{
Text = profile.Name,
Height = 30,
Dock = DockStyle.Top
};
var pro = profile;
btn.Click += (s, e) => UseProfile(pro);
PresetTable.Controls.Add(btn);
}
if (idx < 0 || idx >= profs.Count) idx = 0;
if (ProfileSelect.SelectedIndex != idx) ProfileSelect.SelectedIndex = idx;
}
private void UsePreset(CompilePreset preset)
{
_preset = preset;
DialogResult = DialogResult.OK;
Close();
}
private void UseProfile(BuildProfile pro)
{
_profile = pro;
UpdateParameters(pro);
DialogResult = DialogResult.OK;
Close();
}
private void AddParameters()
{
var csg = _specification.GetTool("csg");
if (csg != null)
{
CsgParameters.AddParameters(csg.Parameters);
CsgParameters.SetDescription(csg.Description);
}
var bsp = _specification.GetTool("bsp");
if (bsp != null)
{
BspParameters.AddParameters(bsp.Parameters);
BspParameters.SetDescription(bsp.Description);
}
var vis = _specification.GetTool("vis");
if (vis != null)
{
VisParameters.AddParameters(vis.Parameters);
VisParameters.SetDescription(vis.Description);
}
var rad = _specification.GetTool("rad");
if (rad != null)
{
RadParameters.AddParameters(rad.Parameters);
RadParameters.SetDescription(rad.Description);
}
var shared = _specification.GetTool("shared");
if (shared != null)
{
SharedParameters.AddParameters(shared.Parameters);
SharedParameters.SetDescription(shared.Description);
}
}
private void ProfileSelected(object sender, EventArgs e)
{
_profile = ProfileSelect.SelectedItem as BuildProfile;
if (_profile == null) return;
UpdateParameters(_profile);
}
private void UpdateParameters(BuildProfile prof)
{
RunCsgCheckbox.Checked = prof.RunCsg;
RunBspCheckbox.Checked = prof.RunBsp;
RunVisCheckbox.Checked = prof.RunVis;
RunRadCheckbox.Checked = prof.RunRad;
CsgParameters.SetCommands(prof.GeneratedCsgParameters ?? "", prof.AdditionalCsgParameters ?? "");
BspParameters.SetCommands(prof.GeneratedBspParameters ?? "", prof.AdditionalBspParameters ?? "");
VisParameters.SetCommands(prof.GeneratedVisParameters ?? "", prof.AdditionalVisParameters ?? "");
RadParameters.SetCommands(prof.GeneratedRadParameters ?? "", prof.AdditionalRadParameters ?? "");
SharedParameters.SetCommands(prof.GeneratedSharedParameters ?? "", prof.AdditionalSharedParameters ?? "");
}
private void RenameProfileButtonClicked(object sender, EventArgs e)
{
if (_profile == null) return;
using (var qf = new QuickForm("Rename Build Profile").TextBox("Name", _profile.Name).OkCancel())
{
if (qf.ShowDialog() == DialogResult.OK)
{
var name = qf.String("Name");
if (_build.Profiles.Any(x => String.Equals(name, x.Name, StringComparison.InvariantCultureIgnoreCase)))
{
MessageBox.Show("There is already a profile with that name, please type a unique name.", "Cannot rename profile");
name = null;
}
if (!String.IsNullOrWhiteSpace(name) && _profile.Name != name)
{
_profile.Name = name;
SettingsManager.Write();
UpdateProfiles();
}
}
}
}
private void DeleteProfileButtonClicked(object sender, EventArgs e)
{
if (_profile == null) return;
if (MessageBox.Show("Are you sure you want to delete the '" + _profile.Name + "' profile?",
"Delete Build Profile", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_build.Profiles.Remove(_profile);
SettingsManager.Write();
UpdateProfiles();
}
}
private void NewProfileButtonClicked(object sender, EventArgs e)
{
using (var qf = new QuickForm("New Build Profile").TextBox("Name").OkCancel())
{
if (qf.ShowDialog() == DialogResult.OK)
{
var name = qf.String("Name");
if (_build.Profiles.Any(x => String.Equals(name, x.Name, StringComparison.InvariantCultureIgnoreCase)))
{
MessageBox.Show("There is already a profile with that name, please type a unique name.", "Cannot create profile");
name = null;
}
if (!String.IsNullOrWhiteSpace(name))
{
_profile = CreateProfile(name);
UpdateProfiles();
}
}
}
}
private BuildProfile CreateProfile(string name)
{
var prof = new BuildProfile
{
ID = _build.Profiles.Any() ? _build.Profiles.Max(x => x.ID) + 1 : 1,
BuildID = _build.ID,
Name = name,
RunCsg = _specification.GetDefaultRun("csg"),
RunBsp = _specification.GetDefaultRun("bsp"),
RunVis = _specification.GetDefaultRun("vis"),
RunRad = _specification.GetDefaultRun("rad"),
GeneratedCsgParameters = _specification.GetDefaultParameters("csg"),
GeneratedBspParameters = _specification.GetDefaultParameters("bsp"),
GeneratedVisParameters = _specification.GetDefaultParameters("vis"),
GeneratedRadParameters = _specification.GetDefaultParameters("rad"),
GeneratedSharedParameters = _specification.GetDefaultParameters("shared"),
AdditionalCsgParameters = "",
AdditionalBspParameters = "",
AdditionalVisParameters = "",
AdditionalRadParameters = "",
AdditionalSharedParameters = ""
};
_build.Profiles.Add(prof);
SettingsManager.Write();
return prof;
}
private BuildProfile SaveAsProfile(string name)
{
var prof = new BuildProfile
{
ID = _build.Profiles.Any() ? _build.Profiles.Max(x => x.ID) + 1 : 1,
BuildID = _build.ID,
Name = name,
RunCsg = RunCsgCheckbox.Checked,
RunBsp = RunBspCheckbox.Checked,
RunVis = RunVisCheckbox.Checked,
RunRad = RunRadCheckbox.Checked,
GeneratedCsgParameters = CsgParameters.GeneratedCommands,
GeneratedBspParameters = BspParameters.GeneratedCommands,
GeneratedVisParameters = VisParameters.GeneratedCommands,
GeneratedRadParameters = RadParameters.GeneratedCommands,
GeneratedSharedParameters = SharedParameters.GeneratedCommands,
AdditionalCsgParameters = CsgParameters.AdditionalCommands,
AdditionalBspParameters = BspParameters.AdditionalCommands,
AdditionalVisParameters = VisParameters.AdditionalCommands,
AdditionalRadParameters = RadParameters.AdditionalCommands,
AdditionalSharedParameters = SharedParameters.AdditionalCommands
};
_build.Profiles.Add(prof);
SettingsManager.Write();
return prof;
}
private void SaveProfileButtonClicked(object sender, EventArgs e)
{
if (_profile == null) return;
_profile.RunCsg = RunCsgCheckbox.Checked;
_profile.RunBsp = RunBspCheckbox.Checked;
_profile.RunVis = RunVisCheckbox.Checked;
_profile.RunRad = RunRadCheckbox.Checked;
_profile.GeneratedCsgParameters = CsgParameters.GeneratedCommands;
_profile.GeneratedBspParameters = BspParameters.GeneratedCommands;
_profile.GeneratedVisParameters = VisParameters.GeneratedCommands;
_profile.GeneratedRadParameters = RadParameters.GeneratedCommands;
_profile.GeneratedSharedParameters = SharedParameters.GeneratedCommands;
_profile.AdditionalCsgParameters = CsgParameters.AdditionalCommands;
_profile.AdditionalBspParameters = BspParameters.AdditionalCommands;
_profile.AdditionalVisParameters = VisParameters.AdditionalCommands;
_profile.AdditionalRadParameters = RadParameters.AdditionalCommands;
_profile.AdditionalSharedParameters = SharedParameters.AdditionalCommands;
SettingsManager.Write();
}
private void SaveProfileAsButtonClicked(object sender, EventArgs e)
{
using (var qf = new QuickForm("Save Build Profile As...").TextBox("Name").OkCancel())
{
if (qf.ShowDialog() == DialogResult.OK)
{
var name = qf.String("Name");
if (_build.Profiles.Any(x => String.Equals(name, x.Name, StringComparison.InvariantCultureIgnoreCase)))
{
MessageBox.Show("There is already a profile with that name, please type a unique name.", "Cannot create profile");
name = null;
}
if (!String.IsNullOrWhiteSpace(name))
{
_profile = SaveAsProfile(name);
UpdateProfiles();
}
}
}
}
private void UpdatePreview(object sender, EventArgs e)
{
ProfilePreview.Text = "";
if (_profile == null) return;
var str = "";
if (RunCsgCheckbox.Checked)
{
str += _build.Csg + ' ' + (CsgParameters.GeneratedCommands
+ ' ' + CsgParameters.AdditionalCommands
+ ' ' + SharedParameters.GeneratedCommands
+ ' ' + SharedParameters.AdditionalCommands).Trim() + " <mapname>\r\n\r\n";
}
if (RunBspCheckbox.Checked)
{
str += _build.Bsp
+ ' ' + (BspParameters.GeneratedCommands
+ ' ' + BspParameters.AdditionalCommands
+ ' ' + SharedParameters.GeneratedCommands
+ ' ' + SharedParameters.AdditionalCommands).Trim() + " <mapname>\r\n\r\n";
}
if (RunVisCheckbox.Checked)
{
str += _build.Vis
+ ' ' + (VisParameters.GeneratedCommands
+ ' ' + VisParameters.AdditionalCommands
+ ' ' + SharedParameters.GeneratedCommands
+ ' ' + SharedParameters.AdditionalCommands).Trim() + " <mapname>\r\n\r\n";
}
if (RunRadCheckbox.Checked)
{
str += _build.Rad
+ ' ' + (RadParameters.GeneratedCommands
+ ' ' + RadParameters.AdditionalCommands
+ ' ' + SharedParameters.GeneratedCommands
+ ' ' + SharedParameters.AdditionalCommands).Trim() + " <mapname>\r\n\r\n";
}
ProfilePreview.Text = str;
}
public BuildProfile GetProfile()
{
if (_preset != null)
{
return new BuildProfile
{
BuildID = _build.ID,
Name = _preset.Name,
RunCsg = _preset.RunCsg,
RunBsp = _preset.RunBsp,
RunVis = _preset.RunVis,
RunRad = _preset.RunRad,
GeneratedCsgParameters = _preset.Csg,
GeneratedBspParameters = _preset.Bsp,
GeneratedVisParameters = _preset.Vis,
GeneratedRadParameters = _preset.Rad
};
}
return new BuildProfile
{
BuildID = _build.ID,
Name = _profile == null ? "" : _profile.Name,
RunCsg = RunCsgCheckbox.Checked,
RunBsp = RunBspCheckbox.Checked,
RunVis = RunVisCheckbox.Checked,
RunRad = RunRadCheckbox.Checked,
GeneratedCsgParameters = CsgParameters.GeneratedCommands,
GeneratedBspParameters = BspParameters.GeneratedCommands,
GeneratedVisParameters = VisParameters.GeneratedCommands,
GeneratedRadParameters = RadParameters.GeneratedCommands,
GeneratedSharedParameters = SharedParameters.GeneratedCommands,
AdditionalCsgParameters = CsgParameters.AdditionalCommands,
AdditionalBspParameters = BspParameters.AdditionalCommands,
AdditionalVisParameters = VisParameters.AdditionalCommands,
AdditionalRadParameters = RadParameters.AdditionalCommands,
AdditionalSharedParameters = SharedParameters.AdditionalCommands
};
}
private void SwitchToAdvanced(object sender, EventArgs e)
{
if (AdvancedPanel.Dock == DockStyle.Fill) return;
SimplePanel.Dock = DockStyle.None;
AdvancedPanel.Dock = DockStyle.Fill;
_simpleSize = Size;
Size = _advancedSize;
}
private void SwitchToSimple(object sender, EventArgs e)
{
if (SimplePanel.Dock == DockStyle.Fill) return;
AdvancedPanel.Dock = DockStyle.None;
SimplePanel.Dock = DockStyle.Fill;
_advancedSize = Size;
Size = _simpleSize;
}
}
}
| 42.351852
| 138
| 0.539845
|
4599fd645dac58591b4888f8c302e038c819c9ec
| 468
|
py
|
Python
|
tests/server/execute_test.py
|
jwminton/voila
|
b003a7fc62023e5b4c8dab7dd64b94a920610c15
|
[
"BSD-3-Clause"
] | 2,977
|
2019-09-27T04:51:38.000Z
|
2022-03-31T12:02:41.000Z
|
tests/server/execute_test.py
|
sthagen/voila-dashboards-voila
|
7613fbb95f39a93f874ea57a8ab4a31140ace394
|
[
"BSD-3-Clause"
] | 735
|
2019-09-27T08:02:34.000Z
|
2022-03-31T19:58:01.000Z
|
tests/server/execute_test.py
|
sthagen/voila-dashboards-voila
|
7613fbb95f39a93f874ea57a8ab4a31140ace394
|
[
"BSD-3-Clause"
] | 335
|
2019-10-06T05:23:29.000Z
|
2022-03-23T21:35:00.000Z
|
# test basics of Voilà running a notebook
async def test_hello_world(http_server_client, print_notebook_url):
response = await http_server_client.fetch(print_notebook_url)
assert response.code == 200
html_text = response.body.decode('utf-8')
assert 'Hi Voilà' in html_text
assert 'print(' not in html_text, 'by default the source code should be stripped'
assert 'test_template.css' not in html_text, "test_template should not be the default"
| 42.545455
| 90
| 0.760684
|
8ebe751dfb616c5817423aad684be09898196739
| 3,819
|
js
|
JavaScript
|
app/components/topic/index.js
|
ipanli/tasklist-react
|
c3748e0cd1017d1bfb33b1487a0084cff194d2a7
|
[
"MIT"
] | null | null | null |
app/components/topic/index.js
|
ipanli/tasklist-react
|
c3748e0cd1017d1bfb33b1487a0084cff194d2a7
|
[
"MIT"
] | null | null | null |
app/components/topic/index.js
|
ipanli/tasklist-react
|
c3748e0cd1017d1bfb33b1487a0084cff194d2a7
|
[
"MIT"
] | null | null | null |
import React from 'react';
import { Link , hashHistory} from 'react-router';
import cssModules from 'react-css-modules';
import style from './styles.styl';
import LazyLoad from 'react-lazy-load';
import Pagination from '../pagination/';
import { apiTopic } from '../api/';
// 引入Fetch
import 'whatwg-fetch';
import './p.scss';
const api = '/ShoppingGuideAPI/GetTopicItems?pageSize=50&id=391&curPage=1&_=1463998084439';
const endApi = apiTopic();
class Topic extends React.Component {
constructor(props) {
const { params } = props;
const picId = params.id ? params.id : '';
let page = params.page ? Number(params.page) : 1;
super(props);
this.state = {
Id:picId,
Page:page,
index:page,
size:50,
pages:5,
total:0,
jumper:true,
banner:'',
title:'',
data: []
}
}
GetApiData(title,Page){
let ist = title || null;
let listId = this.state.Id;
let endApiUrl = endApi + listId + '&curPage='+ Page;
// console.log(listId)
// console.log(Page)
// console.log(endApiUrl)
fetch(endApiUrl)
.then((response) => {
return response.json();
})
.then((data) => {
let total = data.Count* this.state.size;
console.log(total);
this.setState({
total:total,
banner:data.img,
title:data.title,
data: data.Content
});
ist ? document.title = data.title + '- Panli代购': '';
})
.catch((ex) => {
console.log(ex);
});
}
// 组件渲染后获取外界数据
componentDidMount() {
this.GetApiData(1,this.state.Page);
}
onChange (index) {
this.setState({
Page:index
});
let Id = this.state.Id;
// this.props.router.push('/')
const path = `/list/${Id}/${index}`
console.log(hashHistory);
hashHistory.push(path)
this.GetApiData(null,index );
// RouterContext.context.route.push('/list/'+ Id +'/page/'+index);
}
render() {
return (
<div styleName="Topic">
{this.state.banner.length > 0 ? <div styleName="TopicBanner" >
<img src={this.state.banner} />
</div> : <div styleName="loadsta"> </div>}
{this.state.data.length > 0 ? '' : <div >加载中...</div>}
<div styleName="TopicMain">
{this.state.data.map((item, index) =>
<div styleName="prolistBox" key={index}>
<a href={`http://www.panli.com/Crawler.aspx?purl=${item.Producturl}`} target="_blank" >
<div styleName="thumbBox">
<LazyLoad height={225} offsetVertical={225}>
<img src={item.img} />
</LazyLoad>
</div>
<h6 styleName="name">
{item.Name}
</h6>
<p styleName="price">
¥{item.pric}
</p>
</a>
</div>
)}
</div>
{this.state.total > 50 ?
<Pagination
index={this.state.index}
size={this.state.size}
total={this.state.total}
jumper={this.state.jumper}
onChange={this.onChange.bind(this)} />
: ''}
</div>
);
}
}
export default cssModules(Topic, style);
| 25.804054
| 103
| 0.451165
|
a38efeced646c65e65022b4983eb7cf598b6a4df
| 499
|
java
|
Java
|
src/decoratorPattern/Decoration.java
|
rubenhortas/java_patterns
|
25e0540ce9e453a4f7c81c538ad9b7a71810600d
|
[
"MIT"
] | null | null | null |
src/decoratorPattern/Decoration.java
|
rubenhortas/java_patterns
|
25e0540ce9e453a4f7c81c538ad9b7a71810600d
|
[
"MIT"
] | null | null | null |
src/decoratorPattern/Decoration.java
|
rubenhortas/java_patterns
|
25e0540ce9e453a4f7c81c538ad9b7a71810600d
|
[
"MIT"
] | null | null | null |
package decoratorPattern;
public class Decoration {
@SuppressWarnings("unused")
public static void main(String[] args) {
TimeStamped t = new TimeStamped(new Basic());
TimeStamped t2 = new TimeStamped(new SerialNumbered(new Basic()));
// t2.getSerialNumber(); // Not available
SerialNumbered s = new SerialNumbered(new Basic());
SerialNumbered s2 = new SerialNumbered(new TimeStamped(new Basic()));
// s2.getStamp(); // Not available
}
}
| 33.266667
| 77
| 0.657315
|
799703c5b710869b12642a0753b893362f721ddc
| 11,932
|
php
|
PHP
|
plugins/diy/views/template/diy-link.php
|
minyuanriji/wwwbackend
|
978a5c1f43510e64202180768b5ede15ca5cdff2
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/diy/views/template/diy-link.php
|
minyuanriji/wwwbackend
|
978a5c1f43510e64202180768b5ede15ca5cdff2
|
[
"BSD-3-Clause"
] | null | null | null |
plugins/diy/views/template/diy-link.php
|
minyuanriji/wwwbackend
|
978a5c1f43510e64202180768b5ede15ca5cdff2
|
[
"BSD-3-Clause"
] | 1
|
2021-06-09T07:10:15.000Z
|
2021-06-09T07:10:15.000Z
|
<?php
/**
* Created by PhpStorm.
* User: 风哀伤
* Date: 2019/4/25
* Time: 16:49
* @copyright: ©2019 浙江禾匠信息科技
* @link: http://www.zjhejiang.com
*/
$pluginUrl = \app\helpers\PluginHelper::getPluginBaseAssetsUrl();
?>
<style>
.diy-link {
width: 100%;
padding: 30px 0;
position: relative;
}
.diy-link > div {
width: 100%;
}
.diy-link .title {
flex-grow: 1;
padding: 0 24px;
}
.diy-link .title>div {
display: inline-block;
vertical-align: middle;
}
.diy-link .arrow {
width: 12px;
height: 22px;
position: absolute;
right: 24px;
top: 50%;
margin-top: -11px;
}
.diy-component-edit .link-page .el-input-group__append {
background-color: #fff
}
.diy-link .big-style {
height: 50px;
line-height: 50px;
font-size: 36px;
}
.diy-link .big-style .title-icon {
width: 50px;
height: 50px;
margin-right: 16px;
vertical-align: middle;
}
.diy-link .medium-style {
height: 36px;
line-height: 36px;
font-size: 28px;
}
.diy-link .medium-style .title-icon {
width: 36px;
height: 36px;
margin-right: 16px;
vertical-align: middle;
}
.diy-link .small-style {
height: 28px;
line-height: 28px;
font-size: 24px;
}
.diy-link .small-style .title-icon {
width: 28px;
height: 28px;
margin-right: 16px;
vertical-align: middle;
}
.title-line {
width: 82px;
height: 5px;
vertical-align: middle;
margin: 0 20px;
}
.title-line.star {
height: 20px;
width: 28px;
}
.title-line.star .top-icon {
width: 28px;
height: 4px;
margin-bottom: 12px;
}
.title-line.star .bottom-icon {
width: 28px;
height: 4px;
}
.title-line.div {
width: 8px;
height: 28px;
margin: 0 10px 0 0;
}
.title-line.radius {
width: 28px;
height: 28px;
margin: 0 10px 0 0;
border-radius: 14px;
border: 2px solid #353535;
}
</style>
<template id="diy-link">
<div>
<div class="diy-component-preview">
<div class="diy-link" :style="cStyle" flex="cross:center">
<div :class="style" flex="dir:left cross:center">
<div v-if="data.style == 1" class="title" :style="{textAlign: data.position}">
<img v-if="data.picSwitch" class="title-icon" :src="data.picUrl" alt="">
<div style="font-weight: 600">{{data.title?data.title:'这里是标题示例'}}</div>
</div>
<div v-else-if="data.style == 2" class="title" style="text-align: center">
<img :style="{backgroundColor: data.styleColor}" class="title-line" src="<?= $pluginUrl ?>/images/line-style.png">
<div style="font-weight: 600">{{data.title?data.title:'这里是标题示例'}}</div>
<img :style="{backgroundColor: data.styleColor}" class="title-line" src="<?= $pluginUrl ?>/images/line-style.png">
</div>
<div v-else-if="data.style == 3" class="title" style="text-align: center">
<div class="title-line star">
<div :style="{backgroundColor: data.styleColor}" class="top-icon"></div>
<div :style="{backgroundColor: data.styleColor}" class="bottom-icon"></div>
</div>
<div style="font-weight: 600">{{data.title?data.title:'这里是标题示例'}}</div>
<div class="title-line star">
<div :style="{backgroundColor: data.styleColor}" class="top-icon"></div>
<div :style="{backgroundColor: data.styleColor}" class="bottom-icon"></div>
</div>
</div>
<div v-else-if="data.style == 4" class="title" style="text-align: left">
<img :style="{backgroundColor: data.styleColor}" class="title-line div" src="<?= $pluginUrl ?>/images/div-style.png">
<div style="font-weight: 600">{{data.title?data.title:'这里是标题示例'}}</div>
</div>
<div v-else-if="data.style == 5" class="title" style="text-align: left">
<div :style="[{'borderColor':data.styleColor,'backgroundColor':data.background}]" class="title-line radius"></div>
<div style="font-weight: 600">{{data.title?data.title:'这里是标题示例'}}</div>
</div>
<div v-if="data.arrowsSwitch" style="font-size: 16px;color: #999;padding-right: 45px;">更多</div>
<img class="arrow" src="<?= $pluginUrl ?>/images/icon-jiantou-r.png" v-if="data.arrowsSwitch">
</div>
</div>
</div>
<div class="diy-component-edit">
<el-form label-width="100px" @submit.native.prevent>
<el-form-item label="标题">
<label slot="label">标题
<el-tooltip class="item" effect="dark"
content="标题长度不超过10个字"
placement="top">
<i class="el-icon-info"></i>
</el-tooltip>
</label>
<el-input size="small" v-model="data.title" maxlength="10"></el-input>
</el-form-item>
<el-form-item label="字体大小">
<com-radio v-model="data.fontSize" label="36">大</com-radio>
<com-radio v-model="data.fontSize" label="28">中</com-radio>
<com-radio v-model="data.fontSize" label="24">小</com-radio>
</el-form-item>
<el-form-item label="文字颜色">
<el-color-picker size="small" v-model="data.color"></el-color-picker>
<el-input size="small" style="width: 80px;margin-right: 25px;" v-model="data.color"></el-input>
</el-form-item>
<el-form-item label="背景颜色">
<el-color-picker size="small" v-model="data.background"></el-color-picker>
<el-input size="small" style="width: 80px;margin-right: 25px;" v-model="data.background"></el-input>
</el-form-item>
<el-form-item label="标题样式">
<com-radio v-model="data.style" label="1">样式1</com-radio>
<com-radio v-model="data.style" label="2">样式2</com-radio>
<com-radio v-model="data.style" label="3">样式3</com-radio>
<com-radio v-model="data.style" label="4">样式4</com-radio>
<com-radio v-model="data.style" label="5">样式5</com-radio>
</el-form-item>
<el-form-item v-if="data.style == '1'" label="标题位置">
<com-radio v-model="data.position" label="left">居左</com-radio>
<com-radio v-model="data.position" label="center">居中</com-radio>
<com-radio v-model="data.position" label="right">居右</com-radio>
</el-form-item>
<el-form-item v-if="data.style != '1'" label="样式颜色">
<el-color-picker v-model="data.styleColor"></el-color-picker>
<el-input size="small" style="width: 80px;margin-right: 25px;" v-model="data.styleColor"></el-input>
</el-form-item>
<el-form-item label="链接页面">
<el-input size="small" class="link-page" v-model="data.link.name" :disabled="true">
<template slot="append">
<com-pick-link @selected="selectLink">
<el-button>选择链接</el-button>
</com-pick-link>
</template>
</el-input>
</el-form-item>
<el-form-item v-if="data.style == '1'" label="图标开关">
<el-switch v-model="data.picSwitch"></el-switch>
</el-form-item>
<template v-if="data.picSwitch">
<el-form-item label="图标">
<label slot="label">图标
<el-tooltip class="item" effect="dark"
content="最大宽度750px,最大高度36px,图标等比例缩放"
placement="top">
<i class="el-icon-info"></i>
</el-tooltip>
</label>
<com-attachment title="选择图标" :multiple="false" :max="1" type="image"
@selected="pickPicUrl">
<el-button size="mini">选择图标</el-button>
</com-attachment>
<com-gallery :list="[{url:data.picUrl}]" :show-delete="false"
@deleted="deletePic('picUrl')"></com-gallery>
</el-form-item>
</template>
<el-form-item label="箭头开关">
<el-switch v-model="data.arrowsSwitch"></el-switch>
</el-form-item>
</el-form>
</div>
</div>
</template>
<script>
Vue.component('diy-link', {
template: '#diy-link',
props: {
value: Object
},
data() {
return {
data: {
title: '',
style: '1',
fontSize: '36',
position: 'left',
styleColor: '#353535',
link: {},
picSwitch: false,
arrowsSwitch: false,
picUrl: '',
color: '#353535',
background: '#ffffff'
}
}
},
created() {
if (!this.value) {
this.$emit('input', JSON.parse(JSON.stringify(this.data)))
} else {
this.data = JSON.parse(JSON.stringify(this.value));
if (!this.data.link) {
this.data.link = {};
}
}
},
watch: {
data: {
deep: true,
handler(newVal, oldVal) {
this.$emit('input', newVal, oldVal)
},
},
},
computed: {
cStyle() {
if(this.data.background) {
return `color: ${this.data.color};`
+ `background: ${this.data.background};`
}else {
return `color: ${this.data.color};`
}
},
style() {
if (this.data.fontSize == '36') {
return `big-style`
} else if (this.data.fontSize == '28') {
return `medium-style`
} else {
return `small-style`;
}
}
},
methods: {
selectLink(e) {
this.data.link = e[0];
},
pickPicUrl(e) {
if (e) {
this.data.picUrl = e[0].url;
}
}
}
});
</script>
| 38.614887
| 142
| 0.434965
|
b34eddd2342ab457169fc99bba34ed9a9c01335f
| 4,441
|
py
|
Python
|
egs/SBS-mul/s5_old/local/dt_to_ipa.py
|
irrawaddy28/SBS-kaldi-2015
|
01b056f429a673255975ad6b49d4116c1438c289
|
[
"Apache-2.0"
] | null | null | null |
egs/SBS-mul/s5_old/local/dt_to_ipa.py
|
irrawaddy28/SBS-kaldi-2015
|
01b056f429a673255975ad6b49d4116c1438c289
|
[
"Apache-2.0"
] | null | null | null |
egs/SBS-mul/s5_old/local/dt_to_ipa.py
|
irrawaddy28/SBS-kaldi-2015
|
01b056f429a673255975ad6b49d4116c1438c289
|
[
"Apache-2.0"
] | null | null | null |
import fst
import codecs
import sys
import cPickle as pickle
import subprocess
from kitchen.text.converters import getwriter
DATA_DIR = sys.argv[1]
FILE_LIST = sys.argv[2]
DUTCH_FST_FILE = '/export/ws15-pt-data/rsloan/Dutch_ref_orthography_fst.txt'
DUTCH_DICT = '/export/ws15-pt-data/rsloan/dt_pron.p'
EN_DICT = '/export/ws15-pt-data/rsloan/en_pron.p'
PHONETISAURUS_FILE = '/export/ws15-pt-data/rsloan/phonetisaurus-0.8a/phonetisaurus/script/dt_data/dt_pron.fst'
#OUTFILE = '/export/ws15-pt-data/rsloan/dt_oov.txt'
def create_dt_fst():
dt_fst = fst.Transducer(isyms=fst.SymbolTable('eps'), osyms=fst.SymbolTable('eps'))
fst_file = codecs.open(DUTCH_FST_FILE, 'r', encoding='utf-8')
for l in fst_file:
l = l.replace(u'\ufeff', '')
entry = l.split()
if len(entry) == 4:
if entry[3] == 'ks':
entry[3] = 'k s'
dt_fst.add_arc(int(entry[0]), int(entry[1]), entry[2], entry[3])
dt_fst[1].final = True
dt_fst[2].final = True
return dt_fst
def process_numerals(l):
'''replaces numerals with their Dutch translations and treats each numeral as a separate word
also has the separate effect of standardizing spacing, but that shouldn't matter in this script'''
l = l.replace('1', ' een ')
l = l.replace('9', ' negen ')
l = l.replace('3', ' drie ')
l = l.replace('4', ' vier ')
l = l.replace('2', ' twee ')
l = l.replace('5', ' vijf ')
l = l.replace('6', ' zes ')
l = l.replace('7', ' zeven ')
l = l.replace('8', ' acht ')
l = l.replace('0', ' zero ')
return l
dt_fst = create_dt_fst()
dt_dict = pickle.load(open(DUTCH_DICT, 'rb'))
en_dict = pickle.load(open(EN_DICT, 'rb'))
#outfile = codecs.open(OUTFILE, 'w', encoding='utf-8')
def word_to_pron(word):
'''given a Dutch word, outputs a pronunciation (with phonemes separated by spaces)'''
try: #look in dict
if word == '<silence>':
return 'SIL'
else:
return dt_dict[word]
except KeyError:
#outfile.write(word + '\n')
#return word
# if len(word) < 15:
#print "using phonetisaurus on word: " + word
pron = subprocess.check_output(['phonetisaurus-g2p', '--model='+PHONETISAURUS_FILE,'--input='+word])
pron = pron.rstrip()
endnum = pron.index('\t')
pron = pron[endnum+1:]
pron = unicode(pron, 'utf-8')
pron = pron.replace(u"\u0279", 'r')
pron = pron.replace('h', u"\u0266")
pron = pron.replace(u"\u0289", u"\u0259")
pron = pron.replace(u"\u0264", u"\u0263")
#if len(word) <= 2 or len(pron.split()) > len(word)/2:
return pron
#try: #check if English
# pron = en_dict[word]
# return pron
#except KeyError: #OOV word, revert to fst
#phonetisaurus probably couldn't get through word, use FST instead
#print "reverting to FST for " + word
#wfst = fst.linear_chain(word, syms=dt_fst.isyms)
#bestpath = wfst.compose(dt_fst).shortest_path(1)
#for path in bestpath.paths():
# pron = ' '.join(bestpath.osyms.find(arc.olabel) for arc in path)
#return pron
utts = open(FILE_LIST, 'r')
for name in utts:
name = name.strip()
utt = codecs.open(DATA_DIR+'/'+name+'.txt', 'r', encoding='utf-8')
for l in utt:
outstring = ''
l = l.replace('-', ' ') #treat hyphens as spaces when splitting words
l = l.replace('/', ' ')
l = process_numerals(l)
words = l.split()
for w in words:
w = w.replace(u"\u00EB", 'e')
w = w.replace(u"\u00EF", 'i')
w = w.replace('&', 'en')
extra_chars = [',', '\'',u'\ufeff',':','\"','(',')']
end_punc = ['.', '?', '!']
for c in extra_chars:
w = w.replace(c, '')
end_sil = False
for c in end_punc:
if c in w:
w = w.replace(c, '')
end_sil = True
if len(w) > 0:
outstring += word_to_pron(w.lower()) + ' '
if end_sil:
outstring += 'SIL '
outstring = outstring.replace(u'eps', '')
outstring = ' '.join(outstring.split()) #remove extra space, just in case
UTF8Writer = getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print outstring
| 36.401639
| 110
| 0.56181
|
f3c81790d8382337452be968e8039bd5d842decf
| 8,470
|
rs
|
Rust
|
2016/day09/src/main.rs
|
devonhollowood/adventofcode
|
9a26bc131e4028554daf93866fcd91a281937118
|
[
"MIT"
] | null | null | null |
2016/day09/src/main.rs
|
devonhollowood/adventofcode
|
9a26bc131e4028554daf93866fcd91a281937118
|
[
"MIT"
] | null | null | null |
2016/day09/src/main.rs
|
devonhollowood/adventofcode
|
9a26bc131e4028554daf93866fcd91a281937118
|
[
"MIT"
] | null | null | null |
#[macro_use]
extern crate clap;
use std::io::prelude::*;
use std::fs::File;
use std::error::Error;
#[derive(Debug, PartialEq, Eq)]
enum ParseExpansionError {
BadChar { expected: char, got: char },
BadInt(std::num::ParseIntError),
NotEnoughInput,
}
impl std::fmt::Display for ParseExpansionError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match *self {
ParseExpansionError::BadChar { expected: ref e, got: ref g } => {
write!(f, "Expected {}, got {}", e, g)
}
ParseExpansionError::BadInt(ref e) => write!(f, "{}", e),
ParseExpansionError::NotEnoughInput => {
write!(f, "Not enough input")
}
}
}
}
impl Error for ParseExpansionError {
fn description(&self) -> &str {
"Could not parse Expansion"
}
fn cause(&self) -> Option<&Error> {
match *self {
ParseExpansionError::BadInt(ref e) => Some(e),
_ => None,
}
}
}
impl From<std::num::ParseIntError> for ParseExpansionError {
fn from(err: std::num::ParseIntError) -> Self {
ParseExpansionError::BadInt(err)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Expansion {
width: usize,
repetitions: usize,
}
fn read_expansion(input: &[u8])
-> Result<(Expansion, usize), ParseExpansionError> {
use ParseExpansionError::*;
// read '('
if input.len() == 0 {
return Err(NotEnoughInput);
} else if input[0] != b'(' {
return Err(BadChar {
expected: '(',
got: input[0] as char,
});
}
// read `width`
let mut idx = 1;
while idx < input.len() && (input[idx] as char).is_digit(10) {
idx += 1;
}
let width = std::str::from_utf8(&input[1..idx]).unwrap().parse()?;
// read 'x'
if input.len() < idx + 1 {
return Err(NotEnoughInput);
} else if input[idx] != b'x' {
return Err(BadChar {
expected: 'x',
got: input[idx] as char,
});
}
// read `repetitions`
idx += 1;
let repititions_start = idx;
while idx < input.len() && (input[idx] as char).is_digit(10) {
idx += 1;
}
let repetitions =
std::str::from_utf8(&input[repititions_start..idx]).unwrap().parse()?;
if input.len() < idx + 1 {
return Err(NotEnoughInput);
} else if input[idx] != b')' {
return Err(BadChar {
expected: ')',
got: input[idx] as char,
});
}
Ok((Expansion {
width: width,
repetitions: repetitions,
},
idx + 1))
}
fn decompress_a(input: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut idx = 0;
while idx < input.len() {
if let Ok((Expansion { width, repetitions }, exp_len)) =
read_expansion(&input[idx..]) {
idx += exp_len;
for _ in 0..repetitions {
out.extend_from_slice(&input[idx..idx +
std::cmp::min(width,
input.len() -
idx)]);
}
idx += width;
} else {
out.push(input[idx]);
idx += 1;
}
}
out
}
fn decompressed_b_len(input: &[u8]) -> usize {
let mut len = 0;
let mut idx = 0;
while idx < input.len() {
if let Ok((Expansion { width, repetitions }, exp_len)) =
read_expansion(&input[idx..]) {
idx += exp_len;
let sub_len =
decompressed_b_len(&input[idx..idx +
std::cmp::min(width,
input.len() -
idx)]);
len += sub_len * repetitions;
idx += width;
} else {
if !(input[idx] as char).is_whitespace() {
len += 1;
}
idx += 1;
}
}
len
}
fn parse_args() -> std::io::Result<String> {
let matches = clap::App::new("Day 09")
.author("Devon Hollowood")
.arg(clap::Arg::with_name("file")
.index(1)
.short("f")
.long("file")
.help("file to decompress. Reads from stdin otherwise")
.takes_value(true))
.get_matches();
let source = matches.value_of_os("file");
let mut contents = String::new();
match source {
Some(filename) => {
let mut input = File::open(filename)?;
input.read_to_string(&mut contents)?;
}
None => {
let mut input = std::io::stdin();
input.read_to_string(&mut contents)?;
}
}
Ok(contents)
}
fn main() {
let compressed = parse_args()
.unwrap_or_else(|err| panic!("Error reading input: {}", err));
let decompressed = decompress_a(compressed.as_bytes());
println!("Decompressed length (first algorithm): {}",
decompressed.iter()
.filter(|c| !(**c as char).is_whitespace())
.count());
println!("Decompressed length (second algorithm): {}",
decompressed_b_len(compressed.as_bytes()));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decompress_a_1() {
assert_eq!(&decompress_a(b"ADVENT"), b"ADVENT")
}
#[test]
fn decompress_a_2() {
assert_eq!(&decompress_a(b"A(1x5)BC"), b"ABBBBBC")
}
#[test]
fn decompress_a_3() {
assert_eq!(&decompress_a(b"(3x3)XYZ"), b"XYZXYZXYZ")
}
#[test]
fn decompress_a_4() {
assert_eq!(&decompress_a(b"A(2x2)BCD(2x2)EFG"), b"ABCBCDEFEFG")
}
#[test]
fn decompress_a_5() {
assert_eq!(&decompress_a(b"(6x1)(1x3)A"), b"(1x3)A")
}
#[test]
fn decompress_a_6() {
assert_eq!(&decompress_a(b"X(8x2)(3x3)ABCY"), b"X(3x3)ABC(3x3)ABCY")
}
#[test]
fn decompress_a_not_enough_input() {
assert_eq!(&decompress_a(b"(3x3)XY"), b"XYXYXY");
assert_eq!(&decompress_a(b"(3x3)"), b"")
}
#[test]
fn read_expansion_success() {
assert_eq!(read_expansion(b"(123x456)foo"),
Ok((Expansion {
width: 123,
repetitions: 456,
},
9)))
}
#[test]
fn read_expansion_not_enough_input() {
assert_eq!(read_expansion(b""),
Err(ParseExpansionError::NotEnoughInput));
assert_eq!(read_expansion(b"(1"),
Err(ParseExpansionError::NotEnoughInput));
assert_eq!(read_expansion(b"(1x2"),
Err(ParseExpansionError::NotEnoughInput));
}
#[test]
fn read_expansion_expected() {
assert_eq!(read_expansion(b"1"),
Err(ParseExpansionError::BadChar {
expected: '(',
got: '1',
}));
assert_eq!(read_expansion(b"(1,"),
Err(ParseExpansionError::BadChar {
expected: 'x',
got: ',',
}));
assert_eq!(read_expansion(b"(1x2x"),
Err(ParseExpansionError::BadChar {
expected: ')',
got: 'x',
}));
}
#[test]
fn read_expansion_bad_int() {
let empty_int_error = "".parse::<usize>().unwrap_err();
assert_eq!(read_expansion(b"(x456)"),
Err(ParseExpansionError::BadInt(empty_int_error.clone())));
assert_eq!(read_expansion(b"(123x)"),
Err(ParseExpansionError::BadInt(empty_int_error)));
}
#[test]
fn decompress_b_len_1() {
assert_eq!(decompressed_b_len(b"(3x3)XYZ"), 9);
}
#[test]
fn decompress_b_len_2() {
assert_eq!(decompressed_b_len(b"X(8x2)(3x3)ABCY"), 20);
}
#[test]
fn decompress_b_len_3() {
assert_eq!(decompressed_b_len(b"(27x12)(20x12)(13x14)(7x10)(1x12)A"),
241920);
}
#[test]
fn decompress_b_len_4() {
assert_eq!(decompressed_b_len(
b"(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN"),
445);
}
}
| 28.518519
| 79
| 0.489138
|
2478720473d223c7377c5e9ce3831c3c5c6309bc
| 8,043
|
php
|
PHP
|
tests/unit/phpDocumentor/Descriptor/Builder/Reflector/MethodAssemblerTest.php
|
martzd/phpDocumentor
|
20bb0295a9b4e815f71fb1c525e3f2455c01917d
|
[
"MIT"
] | 1
|
2020-07-27T01:45:19.000Z
|
2020-07-27T01:45:19.000Z
|
tests/unit/phpDocumentor/Descriptor/Builder/Reflector/MethodAssemblerTest.php
|
martzd/phpDocumentor
|
20bb0295a9b4e815f71fb1c525e3f2455c01917d
|
[
"MIT"
] | 263
|
2020-10-12T06:27:32.000Z
|
2022-03-28T20:02:00.000Z
|
tests/unit/phpDocumentor/Descriptor/Builder/Reflector/MethodAssemblerTest.php
|
martzd/phpDocumentor
|
20bb0295a9b4e815f71fb1c525e3f2455c01917d
|
[
"MIT"
] | null | null | null |
<?php
declare(strict_types=1);
/**
* This file is part of phpDocumentor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link https://phpdoc.org
*/
namespace phpDocumentor\Descriptor\Builder\Reflector;
use Mockery as m;
use Mockery\Adapter\Phpunit\MockeryTestCase;
use phpDocumentor\Descriptor\ArgumentDescriptor;
use phpDocumentor\Descriptor\ProjectDescriptorBuilder;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\Fqsen;
use phpDocumentor\Reflection\Php\Argument;
use phpDocumentor\Reflection\Php\Method;
use phpDocumentor\Reflection\Php\Visibility;
use phpDocumentor\Reflection\Types\String_;
class MethodAssemblerTest extends MockeryTestCase
{
/** @var MethodAssembler $fixture */
protected $fixture;
/** @var ArgumentAssembler|m\MockInterface */
protected $argumentAssemblerMock;
/** @var ProjectDescriptorBuilder|m\MockInterface */
protected $builderMock;
/**
* Creates a new fixture to test with.
*/
protected function setUp() : void
{
$this->builderMock = m::mock(ProjectDescriptorBuilder::class);
$this->builderMock->shouldReceive('buildDescriptor')->andReturn(null);
$this->argumentAssemblerMock = m::mock(ArgumentAssembler::class);
$this->argumentAssemblerMock->shouldReceive('getBuilder')->once()->andReturn(null);
$this->argumentAssemblerMock->shouldReceive('setBuilder')->once();
$this->fixture = new MethodAssembler($this->argumentAssemblerMock);
$this->fixture->setBuilder($this->builderMock);
}
/**
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::__construct
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::create
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::mapReflectorToDescriptor
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addArguments
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addArgument
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addVariadicArgument
*/
public function testCreateMethodDescriptorFromReflector() : void
{
// Arrange
$namespace = 'Namespace';
$methodName = 'goodbyeWorld';
$argumentName = 'variableName';
$argument = $this->givenAnArgumentWithName($argumentName);
$methodReflectorMock = $this->givenAMethodReflector(
$namespace,
$methodName,
$argument,
$this->givenADocBlockObject(true)
);
$argumentDescriptor = new ArgumentDescriptor();
$argumentDescriptor->setName($argumentName);
$this->argumentAssemblerMock->shouldReceive('create')->andReturn($argumentDescriptor);
// Act
$descriptor = $this->fixture->create($methodReflectorMock);
// Assert
$expectedFqsen = '\\' . $namespace . '\\myClass::' . $methodName . '()';
$this->assertSame($expectedFqsen, (string) $descriptor->getFullyQualifiedStructuralElementName());
$this->assertSame($methodName, $descriptor->getName());
$this->assertSame('\\' . $namespace, $descriptor->getNamespace());
$this->assertSame('protected', $descriptor->getVisibility());
$this->assertFalse($descriptor->isFinal());
$this->assertFalse($descriptor->isAbstract());
$this->assertFalse($descriptor->isStatic());
$argument = $descriptor->getArguments()->get($argumentName);
$this->assertSame($argument->getName(), $argumentDescriptor->getName());
}
/**
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::__construct
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::create
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::mapReflectorToDescriptor
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addArguments
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addArgument
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addVariadicArgument
*/
public function testCreateMethodDescriptorFromReflectorWhenDocblockIsAbsent() : void
{
// Arrange
$namespace = 'Namespace';
$methodName = 'goodbyeWorld';
$argumentName = 'waveHand';
$argumentDescriptorMock = $this->givenAnArgumentWithName($argumentName);
$methodReflectorMock = $this->givenAMethodReflector(
$namespace,
$methodName,
$argumentDescriptorMock
);
$argumentDescriptor = new ArgumentDescriptor();
$argumentDescriptor->setName($argumentName);
$this->argumentAssemblerMock->shouldReceive('create')->andReturn($argumentDescriptor);
// Act
$descriptor = $this->fixture->create($methodReflectorMock);
// Assert
$argument = $descriptor->getArguments()->get($argumentName);
$this->assertSame($argumentDescriptor, $argument);
}
/**
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::__construct
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::create
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::mapReflectorToDescriptor
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addArguments
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addArgument
* @covers \phpDocumentor\Descriptor\Builder\Reflector\MethodAssembler::addVariadicArgument
*/
public function testCreateMethodDescriptorFromReflectorWhenParamTagsAreAbsent() : void
{
// Arrange
$namespace = 'Namespace';
$methodName = 'goodbyeWorld';
$argumentName = 'waveHand';
$argumentDescriptorMock = $this->givenAnArgumentWithName($argumentName);
$methodReflectorMock = $this->givenAMethodReflector(
$namespace,
$methodName,
$argumentDescriptorMock,
$this->givenADocBlockObject(false)
);
$argumentDescriptor = new ArgumentDescriptor();
$argumentDescriptor->setName($argumentName);
$this->argumentAssemblerMock->shouldReceive('create')->andReturn($argumentDescriptor);
// Act
$descriptor = $this->fixture->create($methodReflectorMock);
// Assert
$argument = $descriptor->getArguments()->get($argumentName);
$this->assertSame($argumentDescriptor, $argument);
}
/**
* Creates a sample method reflector for the tests with the given data.
*/
protected function givenAMethodReflector(
string $namespace,
string $methodName,
Argument $argumentMock,
?DocBlock $docBlockMock = null
) : Method {
$method = new Method(
new Fqsen('\\' . $namespace . '\\myClass::' . $methodName . '()'),
new Visibility(Visibility::PROTECTED_),
$docBlockMock
);
$method->addArgument($argumentMock);
return $method;
}
/**
* Generates a DocBlock object with applicable defaults for these tests.
*/
protected function givenADocBlockObject($withTags) : DocBlock
{
$docBlockDescription = new DocBlock\Description('This is an example description');
$tags = [];
if ($withTags) {
$tags[] = new DocBlock\Tags\Param(
'variableName',
new String_(),
true,
new DocBlock\Description('foo')
);
}
return new DocBlock('This is a example description', $docBlockDescription, $tags);
}
/**
* Prepares a mock Argument with the given name.
*/
protected function givenAnArgumentWithName(string $argumentName) : Argument
{
return new Argument($argumentName);
}
}
| 36.726027
| 106
| 0.674375
|
885dd8d3003196906da0c9789ec7778d4b2d420d
| 5,856
|
cs
|
C#
|
LocalChatRoom/LocalChatRoom/NotifyIconExt.cs
|
sakusnowman/local_chat_room
|
33774baeafb5a80eb787b71a6de96934091b800f
|
[
"MIT"
] | null | null | null |
LocalChatRoom/LocalChatRoom/NotifyIconExt.cs
|
sakusnowman/local_chat_room
|
33774baeafb5a80eb787b71a6de96934091b800f
|
[
"MIT"
] | null | null | null |
LocalChatRoom/LocalChatRoom/NotifyIconExt.cs
|
sakusnowman/local_chat_room
|
33774baeafb5a80eb787b71a6de96934091b800f
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocalChatRoom
{
public enum ToolTipIconEx
{
None = 0,
Info = 1,
Warning = 2,
Error = 3
}
public class NotifyIconExt : IDisposable
{
private System.Windows.Forms.NotifyIcon _notify;
public string Text
{
get { return this._notify.Text; }
set { this._notify.Text = value; }
}
public bool Visible
{
get { return this._notify.Visible; }
set { this._notify.Visible = value; }
}
public Uri IconPath
{
set
{
if (value == null) { return; }
var iconStream = System.Windows.Application.GetResourceStream(value).Stream;
this._notify.Icon = new System.Drawing.Icon(iconStream);
}
}
public System.Windows.Controls.ContextMenu ContextMenu { get; set; }
public ToolTipIconEx BalloonTipIcon
{
get { return (ToolTipIconEx)this._notify.BalloonTipIcon; }
set { this._notify.BalloonTipIcon = (System.Windows.Forms.ToolTipIcon)value; }
}
public string BalloonTipTitle
{
get { return this._notify.BalloonTipTitle; }
set { this._notify.BalloonTipTitle = value; }
}
public string BalloonTipText
{
get { return this._notify.BalloonTipText; }
set { this._notify.BalloonTipText = value; }
}
public void ShowBalloonTip(int timeout)
{
this._notify.ShowBalloonTip(timeout);
}
public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIconEx tipIcon)
{
var icon = (System.Windows.Forms.ToolTipIcon)tipIcon;
this._notify.ShowBalloonTip(timeout, tipTitle, tipText, icon);
}
public NotifyIconExt()
: this(null) { }
public NotifyIconExt(Uri iconPath)
: this(iconPath, null) { }
public NotifyIconExt(Uri iconPath, string text)
: this(iconPath, text, null) { }
public NotifyIconExt(Uri iconPath, string text, System.Windows.Controls.ContextMenu menu)
{
// 各種プロパティを初期化
this._notify = new System.Windows.Forms.NotifyIcon();
this.IconPath = iconPath;
this.Text = text;
this.ContextMenu = menu;
// マウス右ボタンUpのタイミングで、ContextMenuの表示を行う
// ダミーの透明ウィンドウを表示し、このウィンドウのアクティブ状態を用いてContextMenuの表示/非表示を切り替える
this._notify.MouseUp += (s, e) =>
{
if (e.Button != System.Windows.Forms.MouseButtons.Right) { return; }
var win = new System.Windows.Window()
{
WindowStyle = System.Windows.WindowStyle.None,
ShowInTaskbar = false,
AllowsTransparency = true,
Background = System.Windows.Media.Brushes.Transparent,
Content = new System.Windows.Controls.Grid(),
ContextMenu = this.ContextMenu
};
var isClosed = false;
win.Activated += (_, __) =>
{
if (win.ContextMenu != null)
{
win.ContextMenu.IsOpen = true;
}
};
win.Closing += (_, __) =>
{
isClosed = true;
};
win.Deactivated += (_, __) =>
{
if (win.ContextMenu != null)
{
win.ContextMenu.IsOpen = false;
}
if (!isClosed)
{
win.Close();
}
};
// ダミーウィンドウ表示&アクティブ化をする。
// ⇒これがActivatedイベントで、ContextMenuが表示される
win.Show();
win.Activate();
};
this._notify.Visible = true;
}
#region NotifyIconクラスの各種イベントをラップする
public event EventHandler BalloonTipClicked
{
add { this._notify.BalloonTipClicked += value; }
remove { this._notify.BalloonTipClicked -= value; }
}
public event EventHandler BalloonTipClosed
{
add { this._notify.BalloonTipClosed += value; }
remove { this._notify.BalloonTipClosed -= value; }
}
public event EventHandler BalloonTipShown
{
add { this._notify.BalloonTipShown += value; }
remove { this._notify.BalloonTipShown -= value; }
}
public event EventHandler Click
{
add { this._notify.Click += value; }
remove { this._notify.Click -= value; }
}
public event EventHandler Disposed
{
add { this._notify.Disposed += value; }
remove { this._notify.Disposed -= value; }
}
public event EventHandler DoubleClick
{
add { this._notify.DoubleClick += value; }
remove { this._notify.DoubleClick -= value; }
}
#endregion
#region IDisposable Support
private bool disposedValue = false;
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this._notify.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 28.847291
| 103
| 0.502049
|
9f5ded253dc29975ea2bc20e63a4df37d2cf8121
| 19,526
|
css
|
CSS
|
widgets/common/assets/gradients/glossy/glossySeaShell/glossySeaShell4.css
|
idutta2007/yiigems
|
4278e750db1f19d50615a5acc7a93c8802ff5618
|
[
"MIT"
] | 1
|
2015-11-02T14:12:02.000Z
|
2015-11-02T14:12:02.000Z
|
widgets/common/assets/gradients/glossy/glossySeaShell/glossySeaShell4.css
|
idutta2007/yiigems
|
4278e750db1f19d50615a5acc7a93c8802ff5618
|
[
"MIT"
] | 1
|
2015-11-01T08:58:53.000Z
|
2016-01-02T09:25:49.000Z
|
widgets/common/assets/gradients/glossy/glossySeaShell/glossySeaShell4.css
|
idutta2007/yiigems
|
4278e750db1f19d50615a5acc7a93c8802ff5618
|
[
"MIT"
] | null | null | null |
.background_glossySeaShell4,
.hover_background_glossySeaShell4:hover,
.active_background_glossySeaShell4:active:hover {
background: #ff8530;
background-image: -moz-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(255, 255, 255, .30)), color-stop(50%, rgba(255, 255, 255, .00)), color-stop(51%, rgba(0, 0, 0, .10)), color-stop(100%, rgba(0, 0, 0, .04)));
background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -o-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -ms-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: linear-gradient(to bottom, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#000000',GradientType=0 );
}
.background_glossySeaShell4h,
.hover_background_glossySeaShell4h:hover,
.active_background_glossySeaShell4h:active:hover {
background: #ff8530;
background-image: -moz-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(255, 255, 255, .30)), color-stop(50%, rgba(255, 255, 255, .00)), color-stop(51%, rgba(0, 0, 0, .10)), color-stop(100%, rgba(0, 0, 0, .04)));
background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -o-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -ms-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: linear-gradient(to bottom, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#000000',GradientType=0 );
}
.background_glossySeaShell4a,
.hover_background_glossySeaShell4a:hover,
.active_background_glossySeaShell4a:active:hover {
background: #ff8530;
background-image: -moz-linear-gradient(top, rgba(0, 0, 0, .04) 0%, rgba(0, 0, 0, .10) 50%, rgba(255, 255, 255, .00) 51%, rgba(255, 255, 255, .30) 100%);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, .04)), color-stop(50%, rgba(0, 0, 0, .10)), color-stop(51%, rgba(255, 255, 255, .00)), color-stop(100%, rgba(255, 255, 255, .30)));
background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, .04) 0%, rgba(0, 0, 0, .10) 50%, rgba(255, 255, 255, .00) 51%, rgba(255, 255, 255, .30) 100%);
background-image: -o-linear-gradient(top, rgba(0, 0, 0, .04) 0%, rgba(0, 0, 0, .10) 50%, rgba(255, 255, 255, .00) 51%, rgba(255, 255, 255, .30) 100%);
background-image: -ms-linear-gradient(top, rgba(0, 0, 0, .04) 0%, rgba(0, 0, 0, .10) 50%, rgba(255, 255, 255, .00) 51%, rgba(255, 255, 255, .30) 100%);
background-image: linear-gradient(to bottom, rgba(0, 0, 0, .04) 0%, rgba(0, 0, 0, .10) 50%, rgba(255, 255, 255, .00) 51%, rgba(255, 255, 255, .30) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='#ffffff',GradientType=0 );
}
.background_glossySeaShell4s,
.hover_background_glossySeaShell4s:hover,
.active_background_glossySeaShell4s:active:hover {
background: #ff8530;
background-image: -moz-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(255, 255, 255, .30)), color-stop(50%, rgba(255, 255, 255, .00)), color-stop(51%, rgba(0, 0, 0, .10)), color-stop(100%, rgba(0, 0, 0, .04)));
background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -o-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: -ms-linear-gradient(top, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
background-image: linear-gradient(to bottom, rgba(255, 255, 255, .30) 0%, rgba(255, 255, 255, .00) 50%, rgba(0, 0, 0, .10) 51%, rgba(0, 0, 0, .04) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#000000',GradientType=0 );
}
.background_color_glossySeaShell4,
.hover_background_color_glossySeaShell4:hover,
.active_background_color_glossySeaShell4:active:hover {
background-color:#ff8530;
}
.background_first_color_glossySeaShell4,
.hover_background_first_color_glossySeaShell4:hover,
.active_background_first_color_glossySeaShell4:active:hover {
background-color:#ffffff;
}
.background_last_color_glossySeaShell4,
.hover_background_last_color_glossySeaShell4:hover,
.active_background_color_last_glossySeaShell4:active:hover {
background-color:#000000;
}
/* ------------------------------ color settings -------------------------------*/
.color_glossySeaShell4,
.hover_color_glossySeaShell4:hover,
.active_color_glossySeaShell4:active:hover {
color: #282828;
}
.color_glossySeaShell4h,
.hover_color_glossySeaShell4h:hover,
.active_color_glossySeaShell4h:active:hover {
color: #c8c8c8;
}
.color_glossySeaShell4a,
.hover_color_glossySeaShell4a:hover,
.active_color_glossySeaShell4a:active:hover {
color: #282828;
}
.color_glossySeaShell4s,
.hover_color_glossySeaShell4s:hover,
.active_color_glossySeaShell4s:active:hover {
color: #282828;
}
/* -------------------------- border color settings -----------------------------*/
.border_glossySeaShell4,
.hover_border_glossySeaShell4:hover,
.active_border_glossySeaShell4:active:hover {
border-color: #f26400 #f26400 #f26400 #f26400;
}
.border_glossySeaShell4h,
.hover_border_glossySeaShell4h:hover,
.active_border_glossySeaShell4h:active:hover {
border-color: #c55100 #c55100 #c55100 #c55100;
}
.border_glossySeaShell4a,
.hover_border_glossySeaShell4a:hover,
.active_border_glossySeaShell4a:active:hover {
border-color: #973e00 #973e00 #973e00 #973e00;
}
.border_glossySeaShell4s,
.hover_border_glossySeaShell4s:hover,
.active_border_glossySeaShell4s:active:hover {
border-color: #f26400 #f26400 #f26400 #f26400;
}
/* -------------------------- shadow expand settings --------------------------------*/
.shadow_expand_glossySeaShell4,
.hover_shadow_expand_glossySeaShell4:hover,
.active_shadow_expand_glossySeaShell4:active:hover {
-webkit-box-shadow: 0em 0em 1em 0.25em rgba(255, 133, 48, .39);
-moz-box-shadow: 0em 0em 1em 0.25em rgba(255, 133, 48, .39);
box-shadow: 0em 0em 1em 0.25em rgba(255, 133, 48, .39);
}
.shadow_expand_glossySeaShell4h,
.hover_shadow_expand_glossySeaShell4h:hover,
.active_shadow_expand_glossySeaShell4h:active:hover {
-webkit-box-shadow: 0em 0em 1em 0.25em rgba(255, 169, 108, .50);
-moz-box-shadow: 0em 0em 1em 0.25em rgba(255, 169, 108, .50);
box-shadow: 0em 0em 1em 0.25em rgba(255, 169, 108, .50);
}
.shadow_expand_glossySeaShell4a,
.hover_shadow_expand_glossySeaShell4a:hover,
.active_shadow_expand_glossySeaShell4a:active:hover {
-webkit-box-shadow: 0em 0em 1em 0.25em rgba(255, 115, 17, .63);
-moz-box-shadow: 0em 0em 1em 0.25em rgba(255, 115, 17, .63);
box-shadow: 0em 0em 1em 0.25em rgba(255, 115, 17, .63);
}
.shadow_expand_glossySeaShell4s,
.hover_shadow_expand_glossySeaShell4s:hover,
.active_shadow_expand_glossySeaShell4s:active:hover {
-webkit-box-shadow: 0em 0em 1em 0.25em rgba(255, 115, 17, .71);
-moz-box-shadow: 0em 0em 1em 0.25em rgba(255, 115, 17, .71);
box-shadow: 0em 0em 1em 0.25em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow left settings --------------------------------*/
.shadow_left_glossySeaShell4,
.hover_shadow_left_glossySeaShell4:hover,
.active_shadow_left_glossySeaShell4:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 133, 48, .39);
box-shadow: -0.5em -0.5em 1em rgba(255, 133, 48, .39);
}
.shadow_left_glossySeaShell4h,
.hover_shadow_left_glossySeaShell4h:hover,
.active_shadow_left_glossySeaShell4h:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 169, 108, .50);
box-shadow: -0.5em -0.5em 1em rgba(255, 169, 108, .50);
}
.shadow_left_glossySeaShell4a,
.hover_shadow_left_glossySeaShell4a:hover,
.active_shadow_left_glossySeaShell4a:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .63);
box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .63);
}
.shadow_left_glossySeaShell4s,
.hover_shadow_left_glossySeaShell4s:hover,
.active_shadow_left_glossySeaShell4s:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .71);
box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow right settings --------------------------------*/
.shadow_right_glossySeaShell4,
.hover_shadow_right_glossySeaShell4:hover,
.active_shadow_right_glossySeaShell4:active:hover {
-webkit-box-shadow: 0.5em 0em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: 0.5em 0em 1em rgba(255, 133, 48, .39);
box-shadow: 0.5em 0em 1em rgba(255, 133, 48, .39);
}
.shadow_right_glossySeaShell4h,
.hover_shadow_right_glossySeaShell4h:hover,
.active_shadow_right_glossySeaShell4h:active:hover {
-webkit-box-shadow: 0.5em 0em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: 0.5em 0em 1em rgba(255, 169, 108, .50);
box-shadow: 0.5em 0em 1em rgba(255, 169, 108, .50);
}
.shadow_right_glossySeaShell4a,
.hover_shadow_right_glossySeaShell4a:hover,
.active_shadow_right_glossySeaShell4a:active:hover {
-webkit-box-shadow: 0.5em 0em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: 0.5em 0em 1em rgba(255, 115, 17, .63);
box-shadow: 0.5em 0em 1em rgba(255, 115, 17, .63);
}
.shadow_right_glossySeaShell4s,
.hover_shadow_right_glossySeaShell4s:hover,
.active_shadow_right_glossySeaShell4s:active:hover {
-webkit-box-shadow: 0.5em 0em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: 0.5em 0em 1em rgba(255, 115, 17, .71);
box-shadow: 0.5em 0em 1em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow top settings --------------------------------*/
.shadow_top_glossySeaShell4,
.hover_shadow_top_glossySeaShell4:hover,
.active_shadow_top_glossySeaShell4:active:hover {
-webkit-box-shadow: 0em -0.5em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: 0em -0.5em 1em rgba(255, 133, 48, .39);
box-shadow: 0em -0.5em 1em rgba(255, 133, 48, .39);
}
.shadow_top_glossySeaShell4h,
.hover_shadow_top_glossySeaShell4h:hover,
.active_shadow_top_glossySeaShell4h:active:hover {
-webkit-box-shadow: 0em -0.5em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: 0em -0.5em 1em rgba(255, 169, 108, .50);
box-shadow: 0em -0.5em 1em rgba(255, 169, 108, .50);
}
.shadow_top_glossySeaShell4a,
.hover_shadow_top_glossySeaShell4a:hover,
.active_shadow_top_glossySeaShell4a:active:hover {
-webkit-box-shadow: 0em -0.5em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: 0em -0.5em 1em rgba(255, 115, 17, .63);
box-shadow: 0em -0.5em 1em rgba(255, 115, 17, .63);
}
.shadow_top_glossySeaShell4s,
.hover_shadow_top_glossySeaShell4s:hover,
.active_shadow_top_glossySeaShell4s:active:hover {
-webkit-box-shadow: 0em -0.5em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: 0em -0.5em 1em rgba(255, 115, 17, .71);
box-shadow: 0em -0.5em 1em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow bottom settings --------------------------------*/
.shadow_bottom_glossySeaShell4,
.hover_shadow_bottom_glossySeaShell4:hover,
.active_shadow_bottom_glossySeaShell4:active:hover {
-webkit-box-shadow: 0em 0.5em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: 0em 0.5em 1em rgba(255, 133, 48, .39);
box-shadow: 0em 0.5em 1em rgba(255, 133, 48, .39);
}
.shadow_bottom_glossySeaShell4h,
.hover_shadow_bottom_glossySeaShell4h:hover,
.active_shadow_bottom_glossySeaShell4h:active:hover {
-webkit-box-shadow: 0em 0.5em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: 0em 0.5em 1em rgba(255, 169, 108, .50);
box-shadow: 0em 0.5em 1em rgba(255, 169, 108, .50);
}
.shadow_bottom_glossySeaShell4a,
.hover_shadow_bottom_glossySeaShell4a:hover,
.active_shadow_bottom_glossySeaShell4a:active:hover {
-webkit-box-shadow: 0em 0.5em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: 0em 0.5em 1em rgba(255, 115, 17, .63);
box-shadow: 0em 0.5em 1em rgba(255, 115, 17, .63);
}
.shadow_bottom_glossySeaShell4s,
.hover_shadow_bottom_glossySeaShell4s:hover,
.active_shadow_bottom_glossySeaShell4s:active:hover {
-webkit-box-shadow: 0em 0.5em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: 0em 0.5em 1em rgba(255, 115, 17, .71);
box-shadow: 0em 0.5em 1em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow top_left settings --------------------------------*/
.shadow_top_left_glossySeaShell4,
.hover_shadow_top_left_glossySeaShell4:hover,
.active_shadow_top_left_glossySeaShell4:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 133, 48, .39);
box-shadow: -0.5em -0.5em 1em rgba(255, 133, 48, .39);
}
.shadow_top_left_glossySeaShell4h,
.hover_shadow_top_left_glossySeaShell4h:hover,
.active_shadow_top_left_glossySeaShell4h:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 169, 108, .50);
box-shadow: -0.5em -0.5em 1em rgba(255, 169, 108, .50);
}
.shadow_top_left_glossySeaShell4a,
.hover_shadow_top_left_glossySeaShell4a:hover,
.active_shadow_top_left_glossySeaShell4a:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .63);
box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .63);
}
.shadow_top_left_glossySeaShell4s,
.hover_shadow_top_left_glossySeaShell4s:hover,
.active_shadow_top_left_glossySeaShell4s:active:hover {
-webkit-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .71);
box-shadow: -0.5em -0.5em 1em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow top_right settings --------------------------------*/
.shadow_top_right_glossySeaShell4,
.hover_shadow_top_right_glossySeaShell4:hover,
.active_shadow_top_right_glossySeaShell4:active:hover {
-webkit-box-shadow: 0.5em -0.5em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: 0.5em -0.5em 1em rgba(255, 133, 48, .39);
box-shadow: 0.5em -0.5em 1em rgba(255, 133, 48, .39);
}
.shadow_top_right_glossySeaShell4h,
.hover_shadow_top_right_glossySeaShell4h:hover,
.active_shadow_top_right_glossySeaShell4h:active:hover {
-webkit-box-shadow: 0.5em -0.5em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: 0.5em -0.5em 1em rgba(255, 169, 108, .50);
box-shadow: 0.5em -0.5em 1em rgba(255, 169, 108, .50);
}
.shadow_top_right_glossySeaShell4a,
.hover_shadow_top_right_glossySeaShell4a:hover,
.active_shadow_top_right_glossySeaShell4a:active:hover {
-webkit-box-shadow: 0.5em -0.5em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: 0.5em -0.5em 1em rgba(255, 115, 17, .63);
box-shadow: 0.5em -0.5em 1em rgba(255, 115, 17, .63);
}
.shadow_top_right_glossySeaShell4s,
.hover_shadow_top_right_glossySeaShell4s:hover,
.active_shadow_top_right_glossySeaShell4s:active:hover {
-webkit-box-shadow: 0.5em -0.5em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: 0.5em -0.5em 1em rgba(255, 115, 17, .71);
box-shadow: 0.5em -0.5em 1em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow bottom_left settings --------------------------------*/
.shadow_bottom_left_glossySeaShell4,
.hover_shadow_bottom_left_glossySeaShell4:hover,
.active_shadow_bottom_left_glossySeaShell4:active:hover {
-webkit-box-shadow: -0.5em 0.5em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: -0.5em 0.5em 1em rgba(255, 133, 48, .39);
box-shadow: -0.5em 0.5em 1em rgba(255, 133, 48, .39);
}
.shadow_bottom_left_glossySeaShell4h,
.hover_shadow_bottom_left_glossySeaShell4h:hover,
.active_shadow_bottom_left_glossySeaShell4h:active:hover {
-webkit-box-shadow: -0.5em 0.5em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: -0.5em 0.5em 1em rgba(255, 169, 108, .50);
box-shadow: -0.5em 0.5em 1em rgba(255, 169, 108, .50);
}
.shadow_bottom_left_glossySeaShell4a,
.hover_shadow_bottom_left_glossySeaShell4a:hover,
.active_shadow_bottom_left_glossySeaShell4a:active:hover {
-webkit-box-shadow: -0.5em 0.5em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: -0.5em 0.5em 1em rgba(255, 115, 17, .63);
box-shadow: -0.5em 0.5em 1em rgba(255, 115, 17, .63);
}
.shadow_bottom_left_glossySeaShell4s,
.hover_shadow_bottom_left_glossySeaShell4s:hover,
.active_shadow_bottom_left_glossySeaShell4s:active:hover {
-webkit-box-shadow: -0.5em 0.5em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: -0.5em 0.5em 1em rgba(255, 115, 17, .71);
box-shadow: -0.5em 0.5em 1em rgba(255, 115, 17, .71);
}
/* -------------------------- shadow bottom_right settings --------------------------------*/
.shadow_bottom_right_glossySeaShell4,
.hover_shadow_bottom_right_glossySeaShell4:hover,
.active_shadow_bottom_right_glossySeaShell4:active:hover {
-webkit-box-shadow: 0.5em 0.5em 1em rgba(255, 133, 48, .39);
-moz-box-shadow: 0.5em 0.5em 1em rgba(255, 133, 48, .39);
box-shadow: 0.5em 0.5em 1em rgba(255, 133, 48, .39);
}
.shadow_bottom_right_glossySeaShell4h,
.hover_shadow_bottom_right_glossySeaShell4h:hover,
.active_shadow_bottom_right_glossySeaShell4h:active:hover {
-webkit-box-shadow: 0.5em 0.5em 1em rgba(255, 169, 108, .50);
-moz-box-shadow: 0.5em 0.5em 1em rgba(255, 169, 108, .50);
box-shadow: 0.5em 0.5em 1em rgba(255, 169, 108, .50);
}
.shadow_bottom_right_glossySeaShell4a,
.hover_shadow_bottom_right_glossySeaShell4a:hover,
.active_shadow_bottom_right_glossySeaShell4a:active:hover {
-webkit-box-shadow: 0.5em 0.5em 1em rgba(255, 115, 17, .63);
-moz-box-shadow: 0.5em 0.5em 1em rgba(255, 115, 17, .63);
box-shadow: 0.5em 0.5em 1em rgba(255, 115, 17, .63);
}
.shadow_bottom_right_glossySeaShell4s,
.hover_shadow_bottom_right_glossySeaShell4s:hover,
.active_shadow_bottom_right_glossySeaShell4s:active:hover {
-webkit-box-shadow: 0.5em 0.5em 1em rgba(255, 115, 17, .71);
-moz-box-shadow: 0.5em 0.5em 1em rgba(255, 115, 17, .71);
box-shadow: 0.5em 0.5em 1em rgba(255, 115, 17, .71);
}
| 46.82494
| 230
| 0.682372
|
bc87c59bcb320c89b036caab327c9fbbf2a98d0c
| 872
|
ps1
|
PowerShell
|
data/train/powershell/a282d64ba36abaa6e676f0da6a4aebe7a69c2a46RestoreCopyIni.ps1
|
aliostad/deep-learning-lang-detection
|
d6b031f3ebc690cf2ffd0ae1b08ffa8fb3b38a62
|
[
"MIT"
] | 84
|
2017-10-25T15:49:21.000Z
|
2021-11-28T21:25:54.000Z
|
data/train/powershell/a282d64ba36abaa6e676f0da6a4aebe7a69c2a46RestoreCopyIni.ps1
|
vassalos/deep-learning-lang-detection
|
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
|
[
"MIT"
] | 5
|
2018-03-29T11:50:46.000Z
|
2021-04-26T13:33:18.000Z
|
data/train/powershell/a282d64ba36abaa6e676f0da6a4aebe7a69c2a46RestoreCopyIni.ps1
|
vassalos/deep-learning-lang-detection
|
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
|
[
"MIT"
] | 24
|
2017-11-22T08:31:00.000Z
|
2022-03-27T01:22:31.000Z
|
#Declara o diretório de binários do protheus 10
$PathBin = "C:\Protheus10_TST\bin\"
#Nome do arquivo de configuração do protheus 10 original
$NameIniFile = "totvsappserver.ini"
#Nome do arquivo de configuração do protheus 10 que manipulamos
$CopyIniFile = "totvsappserver.copyini"
#Comando para listar todos os arquivos totvsappserver.copyini
$CopyIniFiles = get-childitem -path $PathBin -include $CopyIniFile -recurse
#A cada totvsappserver.copyini encontrado, copia seu conteúdo para o totvsappserver.ini original o sobrescrevendo
foreach( $iniFile in $CopyIniFiles )
{
$NewName = $iniFile.Name
$NewName = $NewName.Replace($CopyIniFile,$NameIniFile)
$IniDirectory = $iniFile.DirectoryName
if ( !$IniDirectory.endsWith("\") )
{
$IniDirectory+="\"
}
$NewPathFileIni = ( $IniDirectory + $NewName )
copy-item $iniFile.FullName $NewPathFileIni -force
}
| 41.52381
| 113
| 0.761468
|
e3f516447f165217820403c551fa4f8884a8ee7d
| 68
|
rb
|
Ruby
|
spec/rails_exporter/engine_spec.rb
|
dblanken/rails-exporter
|
dd0013319b06de49e1661ca13dbaa6438ae32b58
|
[
"MIT"
] | 6
|
2017-02-20T02:19:21.000Z
|
2021-07-07T13:11:34.000Z
|
spec/rails_exporter/engine_spec.rb
|
dblanken/rails-exporter
|
dd0013319b06de49e1661ca13dbaa6438ae32b58
|
[
"MIT"
] | 2
|
2017-02-20T12:07:57.000Z
|
2021-05-18T20:18:08.000Z
|
spec/rails_exporter/engine_spec.rb
|
dblanken/rails-exporter
|
dd0013319b06de49e1661ca13dbaa6438ae32b58
|
[
"MIT"
] | 3
|
2017-02-17T07:36:40.000Z
|
2021-07-07T13:11:58.000Z
|
require 'rails_helper'
RSpec.describe RailsExporter::Engine do
end
| 13.6
| 39
| 0.823529
|
e721e5d94431f2f5252257447638781bc8923a9b
| 4,589
|
php
|
PHP
|
application/models/api/Comments_model.php
|
Ben2416/rebirth
|
69163337ff1434fdc5573adb65a79d5016a0981c
|
[
"MIT"
] | null | null | null |
application/models/api/Comments_model.php
|
Ben2416/rebirth
|
69163337ff1434fdc5573adb65a79d5016a0981c
|
[
"MIT"
] | null | null | null |
application/models/api/Comments_model.php
|
Ben2416/rebirth
|
69163337ff1434fdc5573adb65a79d5016a0981c
|
[
"MIT"
] | null | null | null |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Comments_model extends CI_Model{
private $table = "comments";
private $report_status = 0;
//get comments in post
public function get_comments($post){
$select = $this->table.".*, (SELECT COUNT(comment_like_id) FROM comment_likes WHERE comment_like_comment=$this->table.comment_id) AS comment_likes";
$select .= ", (SELECT COUNT(comment_dislike_id) FROM comment_dislikes WHERE comment_dislike_comment=$this->table.comment_id) AS comment_dislikes";
$select .= ", (SELECT COUNT(comment_report_id) FROM comment_reports WHERE comment_report_comment=$this->table.comment_id) AS comment_reports";
$select .= ", (SELECT users.user_fullname FROM users WHERE users.user_id=$this->table.comment_by) AS comment_user";
$this->db->select($select);
$this->db->where('comment_post', $post);
$query = $this->db->get($this->table);
return $query->result_array();
}
//get single comment
public function get_comment($comment){
$select = $this->table.".*, (SELECT COUNT(comment_like_id) FROM comment_likes WHERE comment_like_comment=$comment) AS comment_likes";
$select .= ", (SELECT COUNT(comment_dislike_id) FROM comment_dislikes WHERE comment_dislike_comment=$comment) AS comment_dislikes";
$select .= ", (SELECT COUNT(comment_report_id) FROM comment_reports WHERE comment_report_comment=$comment) AS comment_reports";
$select .= ", (SELECT users.user_fullname FROM users WHERE users.user_id=$this->table.comment_by) AS comment_user";
$this->db->select($select);
$this->db->where('comment_id', $comment);
$query = $this->db->get($this->table);
return $query->result_array();
}
//add a comment to a post
public function add_comment($data){
return $this->db->insert($this->table, $data);
}
public function likeComment($data){
$this->db->trans_start();
//check and remove from dislikes
$query = $this->db->where('comment_dislike_comment', $data['comment_dislike_comment'])
->where('comment_dislike_user', $data['comment_dislike_user'])
->get('comment_dislikes');
if($query->num_rows()>0){
$this->db->where('comment_dislike_comment', $data['comment_like_comment'])
->where('comment_dislike_user', $data['comment_like_user']);
$this->db->delete('comment_dislikes');
}
//add to likes if not exist, if exists replace
$query2 = $this->db->where('comment_like_comment', $data['comment_like_comment'])
->where('comment_like_user', $data['comment_like_user'])
->get('comment_likes');
if($query2->num_rows()==0) {
$this->db->insert('comment_likes', $data);
}
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
return false;
else return true;
}
public function dislikeComment($data){
$this->db->trans_start();
//check and remove from likes
$query = $this->db->where('comment_like_comment', $data['comment_dislike_comment'])
->where('comment_like_user', $data['comment_dislike_user'])
->get('comment_likes');
if($query->num_rows()>0){
$this->db->where('comment_like_comment', $data['comment_dislike_comment'])
->where('comment_like_user', $data['comment_dislike_user']);
$this->db->delete('comment_likes');
}
//add to dislikes if not exist, if exists replace
$query2 = $this->db->where('comment_dislike_comment', $data['comment_dislike_comment'])
->where('comment_dislike_user', $data['comment_dislike_user'])
->get('comment_dislikes');
if($query2->num_rows()==0) {
$this->db->insert('comment_dislikes', $data);
}
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
return false;
else return true;
}
public function reportComment($data){
$this->db->trans_start();
$query = $this->db->where('comment_report_comment', $data['comment_report_comment'])
->where('comment_report_user', $data['comment_report_user'])
->get('comment_reports');
if ($query->num_rows() > 0){
$this->report_status = 1;
}else {
$this->db->insert('comment_reports', $data);
$this->report_status = 0;
}
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
return false;
else return true;
}
}
| 44.553398
| 153
| 0.636958
|
038bc0fa2b60e1d04932a03e3a34454b6419d967
| 672
|
dart
|
Dart
|
example/lib/page/example3.dart
|
QiSky/FlutterBaseFunction
|
c3364e50f74d90e4ce92799627cb9f5a006cb9a7
|
[
"MIT"
] | null | null | null |
example/lib/page/example3.dart
|
QiSky/FlutterBaseFunction
|
c3364e50f74d90e4ce92799627cb9f5a006cb9a7
|
[
"MIT"
] | null | null | null |
example/lib/page/example3.dart
|
QiSky/FlutterBaseFunction
|
c3364e50f74d90e4ce92799627cb9f5a006cb9a7
|
[
"MIT"
] | null | null | null |
import 'package:base_plugin/manager/route_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class Example3Widget extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return Example3State();
}
}
class Example3State extends State<Example3Widget>{
@override
void initState() {
// TODO: implement initState
super.initState();
print("实例3的初始化");
}
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text("实例3跳转到实例1"),
onPressed: (){
RouteManager.instance.navigateTo(context, "/example2",clearStack: true);
});
}
}
| 21.677419
| 82
| 0.688988
|
bf0de033f236f57be67f53935041d881422837f7
| 145
|
asm
|
Assembly
|
other.7z/SFC.7z/SFC/ソースデータ/ゼルダの伝説神々のトライフォース/ドイツ_PAL/Ger_asm1/zel_vma.asm
|
prismotizm/gigaleak
|
d082854866186a05fec4e2fdf1def0199e7f3098
|
[
"MIT"
] | null | null | null |
other.7z/SFC.7z/SFC/ソースデータ/ゼルダの伝説神々のトライフォース/ドイツ_PAL/Ger_asm1/zel_vma.asm
|
prismotizm/gigaleak
|
d082854866186a05fec4e2fdf1def0199e7f3098
|
[
"MIT"
] | null | null | null |
other.7z/SFC.7z/SFC/ソースデータ/ゼルダの伝説神々のトライフォース/ドイツ_PAL/Ger_asm1/zel_vma.asm
|
prismotizm/gigaleak
|
d082854866186a05fec4e2fdf1def0199e7f3098
|
[
"MIT"
] | null | null | null |
Name: zel_vma.asm
Type: file
Size: 47622
Last-Modified: '2016-05-13T04:23:03Z'
SHA-1: 5F6DDB3EF8A5C4E8DFCBFBAA06849998BDCF5A55
Description: null
| 20.714286
| 47
| 0.813793
|
a47e905313f0ca2e5a469f5632eae0bb72662255
| 301
|
php
|
PHP
|
resources/views/Javascript/assignments/jsassignment6.blade.php
|
hasinm/laravel_new
|
4d677dbecb80564118833ec7b3bd3ad21643099a
|
[
"MIT"
] | null | null | null |
resources/views/Javascript/assignments/jsassignment6.blade.php
|
hasinm/laravel_new
|
4d677dbecb80564118833ec7b3bd3ad21643099a
|
[
"MIT"
] | 1
|
2021-02-02T17:01:06.000Z
|
2021-02-02T17:01:06.000Z
|
resources/views/Javascript/assignments/jsassignment6.blade.php
|
hasinm/laravel_new
|
4d677dbecb80564118833ec7b3bd3ad21643099a
|
[
"MIT"
] | null | null | null |
<!DOCTYPE html>
<html>
<head>
<title>Add two numbers</title>
</head>
<body>
<p id="demo"></p>
<script>
var base = 15;
var height = 4;
var area = 1/2*base*height;
document.getElementById("demo").innerHTML = "area of triangle is:" + " " + area;
</script>
</body>
</html>
| 18.8125
| 86
| 0.581395
|
bea54fee4fdd305c108750cca5726b110011d95a
| 933
|
dart
|
Dart
|
bin/c03_class/03_class.dart
|
wapalxj/dart_lang
|
01e88bd82511bcc5da3ff4796fdf35f40adf2235
|
[
"Apache-2.0"
] | null | null | null |
bin/c03_class/03_class.dart
|
wapalxj/dart_lang
|
01e88bd82511bcc5da3ff4796fdf35f40adf2235
|
[
"Apache-2.0"
] | null | null | null |
bin/c03_class/03_class.dart
|
wapalxj/dart_lang
|
01e88bd82511bcc5da3ff4796fdf35f40adf2235
|
[
"Apache-2.0"
] | null | null | null |
import 'Point.dart';
void main(List<String> arguments) {
var p = Point(1, 1);
var p2 = Point();
// print(p._x);
print('p.y===${p.y}');
print('p.x===${p.getMyX}');
print('p.z===${p.z}');
print('p.z===${p.getMyZ}');
var pFromMap = Point.fromMap(null);
print(pFromMap.y);
print('===========常量构造函数===========');
//new常量构造函数,创建的对象,和普通对象没有区别
var ip1 = ImmutablePoint(1, 2);
//new const+常量构造函数,
// 创建的对象,参数相同,则对象相同
var ip2 = const ImmutablePoint(1, 2);
var ip3 = const ImmutablePoint(666, 888);
var ip4 = const ImmutablePoint(1, 2);
print('ip1==ip2:${ip1 == ip2}'); //false
print('ip2==ip3:${ip2 == ip3}'); //false
print('ip2==ip4:${ip2 == ip4}'); //true
//单例
var holder;
holder=Holder.get();
holder=Holder.get2();
holder=Holder.instance;
//方式4:factory+const构造
holder=new Holder();
print('===========操作符重载===========');
print('p+p2==${p+p2}');
print('p-p2==${p-100}');
}
| 21.697674
| 43
| 0.55627
|
edb9e01551f4e9b58e2f9ff1f82a8cb3f292c0d8
| 410
|
lua
|
Lua
|
tests/lib/arken/oop/Object/inherit.lua
|
charonplatform/charonplatform
|
ba5f711b2f8a8da760ccb71925d21a53f3255817
|
[
"BSD-3-Clause"
] | 1
|
2018-01-26T14:54:27.000Z
|
2018-01-26T14:54:27.000Z
|
tests/lib/arken/oop/Object/inherit.lua
|
arken-dev/arken
|
ba5f711b2f8a8da760ccb71925d21a53f3255817
|
[
"BSD-3-Clause"
] | null | null | null |
tests/lib/arken/oop/Object/inherit.lua
|
arken-dev/arken
|
ba5f711b2f8a8da760ccb71925d21a53f3255817
|
[
"BSD-3-Clause"
] | null | null | null |
local Class = require('arken.oop.Class')
local test = {}
test.should_execute_method_create_by_inherit_method = function()
local MyClass = Class.new("MyClass")
MyClass.inherit = function(class)
class.heyhere = function()
return 'heyhere'
end
end
local OtherClass = Class.new("OtherClass", "MyClass")
local obj = OtherClass.new()
assert( obj:heyhere() == 'heyhere' )
end
return test
| 24.117647
| 64
| 0.7
|
d91d06b8fd2aa2d28e764a74596a4fa708bc9902
| 12,484
|
rs
|
Rust
|
tests/failpoints/test_io_error.rs
|
MrCroxx/raft-engine
|
689b53664ef16918b69561310fa877f3ef324314
|
[
"Apache-2.0"
] | null | null | null |
tests/failpoints/test_io_error.rs
|
MrCroxx/raft-engine
|
689b53664ef16918b69561310fa877f3ef324314
|
[
"Apache-2.0"
] | null | null | null |
tests/failpoints/test_io_error.rs
|
MrCroxx/raft-engine
|
689b53664ef16918b69561310fa877f3ef324314
|
[
"Apache-2.0"
] | null | null | null |
use crate::util::catch_unwind_silent;
use raft::eraftpb::Entry;
use raft_engine::{Config, Engine as RaftLogEngine, LogBatch, MessageExt, ReadableSize, Result};
use std::sync::atomic::AtomicU64;
use std::sync::Arc;
#[derive(Clone)]
pub struct M;
impl MessageExt for M {
type Entry = Entry;
fn index(e: &Entry) -> u64 {
e.index
}
}
fn generate_batch(region: u64, begin_index: u64, end_index: u64, data: Vec<u8>) -> LogBatch {
let mut batch = LogBatch::default();
let mut v = vec![Entry::new(); (end_index - begin_index) as usize];
let mut index = begin_index;
for e in v.iter_mut() {
e.set_index(index);
e.set_data(data.clone().into());
index += 1;
}
batch.add_entries::<M>(region, &v).unwrap();
batch
}
fn tmp_engine(
path_perfix: &str,
bytes_per_sync: ReadableSize,
target_file_size: ReadableSize,
) -> RaftLogEngine {
let dir = tempfile::Builder::new()
.prefix(path_perfix)
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
bytes_per_sync,
target_file_size,
batch_compression_threshold: ReadableSize(0),
..Default::default()
};
RaftLogEngine::open(cfg).unwrap()
}
struct ConcurrentWriteContext {
engine: Arc<RaftLogEngine>,
ths: Vec<std::thread::JoinHandle<()>>,
ticket: u64,
timer: Arc<AtomicU64>,
}
impl ConcurrentWriteContext {
fn new(engine: Arc<RaftLogEngine>) -> Self {
Self {
engine,
ths: Vec::new(),
ticket: 0,
timer: Arc::new(AtomicU64::new(0)),
}
}
fn leader_write<F: FnOnce(Result<usize>) + Send + Sync + 'static>(
&mut self,
mut log_batch: LogBatch,
sync: bool,
cb: Option<F>,
panic: bool,
) {
if self.ths.is_empty() {
fail::cfg("write_barrier::leader_exit", "pause").unwrap();
let engine_clone = self.engine.clone();
let ticket = self.ticket;
self.ticket += 1;
let timer = self.timer.clone();
self.ths.push(
std::thread::Builder::new()
.spawn(move || {
while ticket != timer.load(std::sync::atomic::Ordering::Acquire) {}
engine_clone.write(&mut LogBatch::default(), false).unwrap();
timer.store(ticket + 1, std::sync::atomic::Ordering::Release);
})
.unwrap(),
);
}
let engine_clone = self.engine.clone();
let ticket = self.ticket;
self.ticket += 1;
let timer = self.timer.clone();
self.ths.push(
std::thread::Builder::new()
.spawn(move || {
while ticket != timer.load(std::sync::atomic::Ordering::Acquire) {}
if panic {
assert!(catch_unwind_silent(|| {
engine_clone.write(&mut log_batch, sync).unwrap();
})
.is_err());
return;
}
let r = engine_clone.write(&mut log_batch, sync);
timer.store(ticket + 1, std::sync::atomic::Ordering::Release);
if let Some(f) = cb {
f(r)
}
})
.unwrap(),
);
}
fn follower_write<F: FnOnce(Result<usize>) + Send + Sync + 'static>(
&mut self,
mut log_batch: LogBatch,
sync: bool,
cb: Option<F>,
panic: bool,
) {
assert!(self.ticket >= 2);
let engine_clone = self.engine.clone();
let ticket = self.ticket;
self.ticket += 1;
let timer = self.timer.clone();
self.ths.push(
std::thread::Builder::new()
.spawn(move || {
while ticket != timer.load(std::sync::atomic::Ordering::Acquire) {}
if panic {
assert!(catch_unwind_silent(|| {
engine_clone.write(&mut log_batch, sync).unwrap();
})
.is_err());
return;
}
let r = engine_clone.write(&mut log_batch, sync);
if let Some(f) = cb {
f(r)
}
timer.store(ticket + 1, std::sync::atomic::Ordering::Release);
})
.unwrap(),
);
}
fn join(&mut self) {
fail::remove("write_barrier::leader_exit");
for t in self.ths.drain(..) {
t.join().unwrap();
}
}
}
#[test]
fn test_open_error() {
let dir = tempfile::Builder::new()
.prefix("test_open_error")
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
bytes_per_sync: ReadableSize::kb(1),
target_file_size: ReadableSize::kb(4),
batch_compression_threshold: ReadableSize(0),
..Default::default()
};
// fp "log_fd::open::err" is only triggered when opening existing log files
fail::cfg("log_fd::open::err", "return").unwrap();
let engine = RaftLogEngine::open(cfg.clone()).unwrap();
drop(engine);
assert!(catch_unwind_silent(|| {
RaftLogEngine::open(cfg.clone()).unwrap();
})
.is_err());
fail::cfg("log_fd::open::err", "off").unwrap();
}
#[test]
fn test_rotate_error() {
let entry = vec![b'x'; 1024];
// panic when truncate
let engine = tmp_engine(
"test_rotate_error_truncate",
ReadableSize::kb(1024),
ReadableSize::kb(4),
);
engine
.write(&mut generate_batch(1, 1, 2, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 2, 3, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 3, 4, entry.clone()), false)
.unwrap();
fail::cfg("active_file::truncate::force", "return").unwrap();
fail::cfg("log_fd::truncate::err", "return").unwrap();
assert!(catch_unwind_silent(|| {
engine
.write(&mut generate_batch(1, 4, 5, entry.clone()), false)
.unwrap();
})
.is_err());
fail::cfg("active_file::truncate::force", "off").unwrap();
fail::cfg("log_fd::truncate::err", "off").unwrap();
// panic when sync
let engine = tmp_engine(
"test_rotate_error_sync",
ReadableSize::kb(4),
ReadableSize::kb(1024),
);
engine
.write(&mut generate_batch(1, 1, 2, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 2, 3, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 3, 4, entry.clone()), false)
.unwrap();
fail::cfg("log_fd::sync::err", "return").unwrap();
assert!(catch_unwind_silent(|| {
engine
.write(&mut generate_batch(1, 4, 5, entry.clone()), false)
.unwrap();
})
.is_err());
fail::cfg("log_fd::sync::err", "off").unwrap();
// panic when create file
let engine = tmp_engine(
"test_rotate_error_create",
ReadableSize::kb(1024),
ReadableSize::kb(4),
);
engine
.write(&mut generate_batch(1, 1, 2, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 2, 3, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 3, 4, entry.clone()), false)
.unwrap();
fail::cfg("log_fd::create::err", "return").unwrap();
assert!(catch_unwind_silent(|| {
engine
.write(&mut generate_batch(1, 4, 5, entry.clone()), false)
.unwrap();
})
.is_err());
fail::cfg("log_fd::create::err", "off").unwrap();
// panic when write header
let engine = tmp_engine(
"test_rotate_error_create",
ReadableSize::kb(1024),
ReadableSize::kb(4),
);
engine
.write(&mut generate_batch(1, 1, 2, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 2, 3, entry.clone()), false)
.unwrap();
engine
.write(&mut generate_batch(1, 3, 4, entry.clone()), false)
.unwrap();
fail::cfg("log_fd::write::err", "return").unwrap();
assert!(catch_unwind_silent(|| {
engine
.write(&mut generate_batch(1, 4, 5, entry.clone()), false)
.unwrap();
})
.is_err());
fail::cfg("log_fd::write::err", "off").unwrap();
}
#[test]
fn test_concurrent_write_error() {
// write-1 success; write-2 fail, truncate; write-3 success
let timer = AtomicU64::new(0);
fail::cfg_callback("engine::write::pre", move || {
match timer.fetch_add(1, std::sync::atomic::Ordering::SeqCst) {
2 => fail::cfg("log_fd::write::err", "return").unwrap(),
3 => fail::cfg("log_fd::write::err", "off").unwrap(),
_ => {}
}
})
.unwrap();
// truncate and sync when write error
let dir = tempfile::Builder::new()
.prefix("test_concurrent_write_error")
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
bytes_per_sync: ReadableSize::kb(1024),
target_file_size: ReadableSize::kb(1024),
batch_compression_threshold: ReadableSize(0),
..Default::default()
};
let engine = Arc::new(RaftLogEngine::open(cfg).unwrap());
let mut ctx = ConcurrentWriteContext::new(engine.clone());
let content = vec![b'x'; 1024];
ctx.leader_write(
generate_batch(1, 1, 11, content.clone()),
false,
Some(|r: Result<usize>| {
assert!(r.is_ok());
}),
false,
);
ctx.follower_write(
generate_batch(2, 1, 11, content.clone()),
false,
Some(|r: Result<usize>| {
assert!(r.is_err());
}),
false,
);
ctx.follower_write(
generate_batch(3, 1, 11, content),
false,
Some(|r: Result<usize>| {
assert!(r.is_ok());
}),
false,
);
ctx.join();
assert_eq!(
10,
engine
.fetch_entries_to::<M>(1, 1, 11, None, &mut vec![])
.unwrap()
);
assert_eq!(
0,
engine
.fetch_entries_to::<M>(2, 1, 11, None, &mut vec![])
.unwrap()
);
assert_eq!(
10,
engine
.fetch_entries_to::<M>(3, 1, 11, None, &mut vec![])
.unwrap()
);
fail::cfg("engine::write::pre", "off").unwrap();
}
#[test]
fn test_concurrent_write_truncate_error() {
// truncate and sync when write error
// write-1 success; write-2 fail, truncate, panic; write-3 (x)
let timer = AtomicU64::new(0);
fail::cfg_callback("engine::write::pre", move || {
match timer.fetch_add(1, std::sync::atomic::Ordering::SeqCst) {
2 => {
fail::cfg("log_fd::write::err", "return").unwrap();
fail::cfg("log_fd::truncate::err", "return").unwrap()
}
3 => {
fail::cfg("log_fd::write::err", "off").unwrap();
fail::cfg("log_fd::truncate::err", "off").unwrap()
}
_ => {}
}
})
.unwrap();
let dir = tempfile::Builder::new()
.prefix("test_concurrent_write_truncate_error")
.tempdir()
.unwrap();
let cfg = Config {
dir: dir.path().to_str().unwrap().to_owned(),
bytes_per_sync: ReadableSize::kb(1024),
target_file_size: ReadableSize::kb(1024),
batch_compression_threshold: ReadableSize(0),
..Default::default()
};
let engine = Arc::new(RaftLogEngine::open(cfg).unwrap());
let mut ctx = ConcurrentWriteContext::new(engine);
let content = vec![b'x'; 1024];
ctx.leader_write(
generate_batch(1, 1, 11, content.clone()),
false,
None::<fn(_)>,
false,
);
ctx.follower_write(
generate_batch(2, 1, 11, content),
false,
Some(|_| unreachable!()),
true,
);
ctx.join();
fail::cfg("log_fd::write::err", "off").unwrap();
fail::cfg("log_fd::truncate::err", "off").unwrap()
}
| 30.227603
| 95
| 0.517703
|
d307c8d375c738320955fcf5760e451ffe82f786
| 691
|
cs
|
C#
|
src/Services/Catalog/Catalog.API/Application/Commands/CreateCatalogItemCommand.cs
|
DobromirZlatkov/AnteyaSid
|
f9cc6e5381f44e82e7e02070f0cf2e03b9a4c401
|
[
"MIT"
] | null | null | null |
src/Services/Catalog/Catalog.API/Application/Commands/CreateCatalogItemCommand.cs
|
DobromirZlatkov/AnteyaSid
|
f9cc6e5381f44e82e7e02070f0cf2e03b9a4c401
|
[
"MIT"
] | 1
|
2018-05-31T19:37:15.000Z
|
2018-05-31T19:47:34.000Z
|
src/Services/Catalog/Catalog.API/Application/Commands/CreateCatalogItemCommand.cs
|
DobromirZlatkov/AnteyaSid
|
f9cc6e5381f44e82e7e02070f0cf2e03b9a4c401
|
[
"MIT"
] | null | null | null |
namespace AnteyaSidOnContainers.Services.Catalog.API.Application.Commands
{
using AnteyaSidOnContainers.Services.Catalog.Data.Models;
using MediatR;
using System.Runtime.Serialization;
public class CreateCatalogItemCommand : IRequest<CatalogItem>
{
[DataMember]
public string Name { get; private set; }
[DataMember]
public decimal Price { get; private set; }
[DataMember]
public string Color { get; private set; }
public CreateCatalogItemCommand(string name, decimal price, string color)
{
this.Name = name;
this.Price = price;
this.Color = color;
}
}
}
| 26.576923
| 81
| 0.633864
|
2f0e0b5388d64a2bb069a262180338704dc17354
| 1,869
|
js
|
JavaScript
|
src/web-src/index.js
|
scrubdev/scrubdev-web
|
e237c56c7161e94cf903e15707a1abc805b6a677
|
[
"MIT"
] | 1
|
2016-09-02T08:22:54.000Z
|
2016-09-02T08:22:54.000Z
|
src/web-src/index.js
|
scrubdev/scrubdev-web
|
e237c56c7161e94cf903e15707a1abc805b6a677
|
[
"MIT"
] | null | null | null |
src/web-src/index.js
|
scrubdev/scrubdev-web
|
e237c56c7161e94cf903e15707a1abc805b6a677
|
[
"MIT"
] | null | null | null |
import Vue from "vue";
import VueRouter from "vue-router";
import VueResource from "vue-resource";
// DRAWER
import IScroll from "iscroll";
import $ from "jquery";
import "jquery-drawer";
// SOCKETS
import io from "socket.io-client";
// VENDOR - STYLES
import "./vendor/raleway-font.css";
import "./vendor/skeleton-2.0.4/normalize.css";
import "./vendor/skeleton-2.0.4/skeleton.css";
import "jquery-drawer/dist/css/drawer.min.css";
import "font-awesome/css/font-awesome.css";
// STYLES
import "./stylesheet/main.css";
import "./stylesheet/transition.css";
import "./stylesheet/drawer.css";
import "./stylesheet/dark_theme.css";
// VUE ROUTER
import routes from "./routes";
Vue.use(VueRouter);
Vue.use(VueResource);
const App = Vue.extend({
data: function() {
return {
darkTheme: (localStorage.getItem("scrubdev.interface.dark") === "true" ? true : false),
optionsDrawer: false,
socket: io()
};
},
ready: function() {
// attach sockets
this.socket.on("scrubdev.test", res => {
console.log("socket: " + res);
});
},
methods: {
hidedrawer: function() {
$(".main-drawer").drawer("close");
},
toggleOptions: function() {
if (!this.optionsDrawer)
$(".options-drawer").drawer("open");
else
$(".options-drawer").drawer("close");
this.optionsDrawer = !this.optionsDrawer;
}
}
});
const Router = new VueRouter({ transitionOnLoad: true });
Router.map(routes);
Router.start(App, "body");
// DRAWER INIT
$(".main-drawer").drawer();
$(".options-drawer").drawer({
class: {
nav: "options-drawer-nav",
toggle: "options-drawer-toggle",
dropdown: "options-drawer-dropdown"
}
});
// LOADED.
$("body").addClass("ready");
| 23.658228
| 99
| 0.596041
|
8d782c9f126bf0b6a37a995ae0765cb9a0fd5987
| 267
|
js
|
JavaScript
|
lib/index.js
|
nodeneil/api-contract-validator
|
4957e703ccb01bc2c6d7b2f794250597b355c83f
|
[
"Apache-2.0"
] | 16
|
2019-03-18T10:18:26.000Z
|
2019-09-13T08:33:14.000Z
|
lib/index.js
|
nodeneil/api-contract-validator
|
4957e703ccb01bc2c6d7b2f794250597b355c83f
|
[
"Apache-2.0"
] | 29
|
2019-11-07T06:46:57.000Z
|
2022-01-16T08:12:18.000Z
|
lib/index.js
|
nodeneil/api-contract-validator
|
4957e703ccb01bc2c6d7b2f794250597b355c83f
|
[
"Apache-2.0"
] | 7
|
2019-09-22T09:12:09.000Z
|
2021-10-04T02:33:27.000Z
|
const chaiPlugin = require('./plugins/chai');
const shouldPlugin = require('./plugins/should');
const jestPlugin = require('./plugins/jest');
const validators = require('./validators');
module.exports = {
chaiPlugin,
jestPlugin,
shouldPlugin,
validators,
};
| 22.25
| 49
| 0.71161
|
7f96e1525c51099abd38494206f79f0d32fe0e39
| 4,639
|
php
|
PHP
|
tests/Client/RequestDataTest.php
|
bosunski/http
|
865694453c95122f8972b9ed7961efb3c517fc5e
|
[
"MIT"
] | 618
|
2015-01-02T10:28:17.000Z
|
2022-03-28T21:23:14.000Z
|
tests/Client/RequestDataTest.php
|
bosunski/http
|
865694453c95122f8972b9ed7961efb3c517fc5e
|
[
"MIT"
] | 303
|
2015-01-18T23:31:31.000Z
|
2022-03-23T06:50:02.000Z
|
tests/Client/RequestDataTest.php
|
bosunski/http
|
865694453c95122f8972b9ed7961efb3c517fc5e
|
[
"MIT"
] | 158
|
2015-01-02T11:36:29.000Z
|
2022-03-27T10:38:34.000Z
|
<?php
namespace React\Tests\Http\Client;
use React\Http\Client\RequestData;
use React\Tests\Http\TestCase;
class RequestDataTest extends TestCase
{
/** @test */
public function toStringReturnsHTTPRequestMessage()
{
$requestData = new RequestData('GET', 'http://www.example.com');
$expected = "GET / HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithEmptyQueryString()
{
$requestData = new RequestData('GET', 'http://www.example.com/path?hello=world');
$expected = "GET /path?hello=world HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithZeroQueryStringAndRootPath()
{
$requestData = new RequestData('GET', 'http://www.example.com?0');
$expected = "GET /?0 HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithOptionsAbsoluteRequestForm()
{
$requestData = new RequestData('OPTIONS', 'http://www.example.com/');
$expected = "OPTIONS / HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithOptionsAsteriskRequestForm()
{
$requestData = new RequestData('OPTIONS', 'http://www.example.com');
$expected = "OPTIONS * HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithProtocolVersion()
{
$requestData = new RequestData('GET', 'http://www.example.com');
$requestData->setProtocolVersion('1.1');
$expected = "GET / HTTP/1.1\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"Connection: close\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithHeaders()
{
$requestData = new RequestData('GET', 'http://www.example.com', array(
'User-Agent' => array(),
'Via' => array(
'first',
'second'
)
));
$expected = "GET / HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"Via: first\r\n" .
"Via: second\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithHeadersInCustomCase()
{
$requestData = new RequestData('GET', 'http://www.example.com', array(
'user-agent' => 'Hello',
'LAST' => 'World'
));
$expected = "GET / HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"user-agent: Hello\r\n" .
"LAST: World\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringReturnsHTTPRequestMessageWithProtocolVersionThroughConstructor()
{
$requestData = new RequestData('GET', 'http://www.example.com', array(), '1.1');
$expected = "GET / HTTP/1.1\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"Connection: close\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
/** @test */
public function toStringUsesUserPassFromURL()
{
$requestData = new RequestData('GET', 'http://john:dummy@www.example.com');
$expected = "GET / HTTP/1.0\r\n" .
"Host: www.example.com\r\n" .
"User-Agent: ReactPHP/1\r\n" .
"Authorization: Basic am9objpkdW1teQ==\r\n" .
"\r\n";
$this->assertSame($expected, $requestData->__toString());
}
}
| 29.929032
| 92
| 0.547532
|
d3402e5b93f7a08e603f3006d2de899b7e0e173a
| 2,388
|
kt
|
Kotlin
|
app/src/main/java/org/fgprc/nyanpasu/fgyoke/network/FlightGearTCPConnector.kt
|
CHH2000day/YokeEmulator-for-FG
|
a59849ba33dcc427a25d9eaaa8736a4064a3ee6d
|
[
"Apache-2.0"
] | 4
|
2017-02-19T09:48:33.000Z
|
2017-05-25T13:28:17.000Z
|
app/src/main/java/org/fgprc/nyanpasu/fgyoke/network/FlightGearTCPConnector.kt
|
CHH2000day/YokeEmulator-for-FG
|
a59849ba33dcc427a25d9eaaa8736a4064a3ee6d
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/org/fgprc/nyanpasu/fgyoke/network/FlightGearTCPConnector.kt
|
CHH2000day/YokeEmulator-for-FG
|
a59849ba33dcc427a25d9eaaa8736a4064a3ee6d
|
[
"Apache-2.0"
] | 2
|
2017-04-24T10:58:50.000Z
|
2018-08-27T22:03:18.000Z
|
/*
* Copyright 2021 CHH2000day,FGPRC
*
* 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 org.fgprc.nyanpasu.fgyoke.network
import kotlinx.coroutines.*
import org.fgprc.nyanpasu.fgyoke.io.DataBuffer
import org.fgprc.nyanpasu.fgyoke.io.DataBufferPool
import java.io.OutputStream
import java.net.InetAddress
import java.net.Socket
open class FlightGearTCPConnector(
destinationAddress: InetAddress,
port: Int,
dataBufferPool: DataBufferPool
) :
FlightGearConnector(destinationAddress, port, dataBufferPool) {
@Suppress("MemberVisibilityCanBePrivate")
protected lateinit var outputStream: OutputStream
private var socket: Socket? = null
/**
* Connect to server.
*/
@OptIn(DelicateCoroutinesApi::class)
override fun connect() {
synchronized(this) {
if (socket == null) {
try {
socket = Socket(destinationAddress, port)
outputStream = socket!!.getOutputStream()
//Starts daemon thread
onConnectionEstablished()
GlobalScope.launch {
onConnectListener?.onConnected()
}
} catch (t: Throwable) {
runBlocking {
onDisconnectListener?.onDisconnected(t)
}
}
}
}
}
/**
* Sends a message to the server.
*/
override suspend fun sendPackage(buffer: DataBuffer) {
if (isClosed) {
throw IllegalStateException("Connection already closed")
}
suspendCancellableCoroutine<Unit> {
outputStream.write(buffer.toByteArray())
}
}
override fun close() {
super.close()
outputStream.close()
socket?.close()
isClosed = true
}
}
| 30.227848
| 75
| 0.618928
|
ff2b905e2aa8b8f34ba3c44fae5c1c032482b216
| 17,011
|
py
|
Python
|
callmail_project/mail/views.py
|
q8groups/callnmail
|
e3f4c01050bee1442545c8e82eba3fb1efb5b3ed
|
[
"MIT"
] | null | null | null |
callmail_project/mail/views.py
|
q8groups/callnmail
|
e3f4c01050bee1442545c8e82eba3fb1efb5b3ed
|
[
"MIT"
] | null | null | null |
callmail_project/mail/views.py
|
q8groups/callnmail
|
e3f4c01050bee1442545c8e82eba3fb1efb5b3ed
|
[
"MIT"
] | null | null | null |
import os
from django.contrib import messages
from django.db import IntegrityError
from django.core.mail import EmailMultiAlternatives
from django.shortcuts import render, HttpResponseRedirect, HttpResponse, get_object_or_404
from django.views import generic
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.core.urlresolvers import reverse, reverse_lazy
from django.conf import settings
from django.contrib.messages.views import SuccessMessageMixin
from dateutil import parser
from braces.views import LoginRequiredMixin
from .forms import RegistrationForm, LoginForm, PasswordResetRequestForm, PasswordResetForm, ActivateForm, \
ChangePasswordForm, ProfileChangeForm, ContactUsForm,MailForwardForm
from .utils import send_sms, determine_mime_type, generate_random_number
from .models import Mail, MailAttachment, ForgotPasswordToken, MailForward, AccountActivation
from advertisement.models import UserProfile
from api.models import Country
class HomePage(generic.View):
def get(self, request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('mail:mailforward_list'))
return render(request, 'index.html')
class RegistrationView(generic.View):
def get(self, request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('mail:mailforward_list'))
rform = RegistrationForm()
form = LoginForm()
return render(request, 'login2.html', {'form': form, 'rform': rform})
def post(self, request):
rform = RegistrationForm(request.POST, request.FILES or None)
if rform.is_valid():
country_codes = request.POST.get('country_code')
phone_number = request.POST.get('phone_number')
phone_number = "+" + country_codes + phone_number
request.session['phone_number'] = phone_number
if User.objects.filter(username=phone_number, is_active=True).exists():
return render(request, 'login2.html', {'form': LoginForm(), 'rform': rform,
'number_error': 'User with that phone number already exists.'})
password = request.POST.get('password1')
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
avatar = request.FILES.get('avatar')
activation_code = generate_random_number()
message = settings.SMS_MSG_ACTIVATION.format(activation_code)
try:
user = User.objects.get(username=phone_number)
user.set_password(password)
if first_name:
user.first_name = first_name
if last_name:
user.last_name = last_name
user.save()
send_sms(phone_number, message)
profile = UserProfile.objects.get(user=user)
profile.avatar = avatar
profile.save()
except User.DoesNotExist:
user = User.objects.create_user(username=phone_number, password=password)
if first_name:
user.first_name = first_name
if last_name:
user.last_name = last_name
user.is_active = False
user.save()
try:
UserProfile.objects.create(user=user, avatar=avatar)
except IntegrityError:
pass
send_sms(phone_number, message)
activation = AccountActivation.objects.filter(user=user)
if activation.exists():
activation.delete()
AccountActivation.objects.create(user=user, activation_code=activation_code)
return HttpResponseRedirect(reverse('mail:activate_user'))
else:
return render(request, 'login2.html', {'form': LoginForm(), 'rform': rform})
class LoginView(generic.View):
def get(self, request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('mail:mailforward_list'))
form = LoginForm()
return render(request, 'login.html', {'form': form, 'rform': RegistrationForm()})
def post(self, request):
country_codes = request.POST.get('country_codes','')
phone_number = request.POST.get('phone_number','')
request.session['phone_number'] = phone_number
request.session['country_codes'] = country_codes
phone_number = "+"+country_codes + phone_number
request.POST = request.POST.copy()
request.POST['phone_number']=phone_number
form = LoginForm(request.POST or None)
if form.is_valid():
username = phone_number
print username
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect('/')
else:
return render(request, 'login.html', {'form': form, 'error': 'Username or password not correct.'})
else:
return render(request, 'login.html', {'form': form})
class LogoutView(generic.View):
def get(self, request):
logout(request)
return HttpResponseRedirect('/')
class ProfileView(LoginRequiredMixin, generic.View):
def get(self, request):
data = {'first_name': request.user.first_name, 'last_name': request.user.last_name,
'gender': request.user.userprofile.gender, 'age': request.user.userprofile.age,
'country': request.user.userprofile.country}
form = ProfileChangeForm(initial=data)
return render(request, 'profile.html', {'form': form})
def post(self, request):
form = ProfileChangeForm(request.POST, request.FILES)
if form.is_valid():
gender = request.POST.get('gender')
birthday = request.POST.get('age')
country = request.POST.get('country')
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
profile = get_object_or_404(UserProfile, user=request.user)
if first_name:
request.user.first_name = first_name
if last_name:
request.user.last_name = last_name
request.user.save()
if gender:
profile.gender = gender
if birthday:
profile.age = parser.parse(birthday)
if country:
profile.country = country
profile.save()
messages.success(request, 'Profile successfully updated.')
return HttpResponseRedirect(reverse('mail:profile'))
else:
return render(request, 'profile.html', {'form': form})
class ActivateUser(generic.View):
def get(self, request):
form = ActivateForm()
return render(request, 'activate_account.html', {'form': form})
def post(self, request):
form = ActivateForm(request.POST or None)
try:
phone_number = request.session['phone_number']
except KeyError:
return render(request, 'activate_account.html', {'form': form, 'error': 'Please register first.'})
if form.is_valid():
username = phone_number
#del request.session['phone_number']
activation_code = request.POST.get('activation_code')
activation = AccountActivation.objects.filter(user__username=username, activation_code=activation_code)
if activation.exists():
user = User.objects.get(username=username)
user.is_active = True
user.save()
AccountActivation.objects.filter(user=user).delete()
messages.success(request, 'Account successfully activated.')
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return HttpResponseRedirect('/')
else:
return render(request, 'activate_account.html', {'form': form, 'error': 'Invalid Activation Code.'})
else:
return render(request, 'activate_account.html', {'form': form})
class MailListView(LoginRequiredMixin, generic.ListView):
template_name = 'mail_list.html'
context_object_name = 'mails'
model = Mail
paginate_by = 20
def get_queryset(self):
return Mail.objects.filter(user=self.request.user)
class MailDetailView(LoginRequiredMixin, generic.DetailView):
template_name = 'mail_detail.html'
context_object_name = 'mail'
model = Mail
class PasswordResetRequestView(generic.View):
def get(self, request):
return render(request, 'password_reset_request_form.html', {'form': PasswordResetRequestForm()})
def post(self, request):
country_codes = request.POST.get('country_codes', '')
phone_number = request.POST.get('phone_number', '')
phone_number = "+"+country_codes + phone_number
request.POST = request.POST.copy()
request.POST['phone_number'] = phone_number
form = PasswordResetRequestForm(request.POST)
random_number = generate_random_number()
if form.is_valid():
user_obj = get_object_or_404(User, username=phone_number)
token_check = ForgotPasswordToken.objects.filter(user=user_obj)
if token_check:
token_check.delete()
ForgotPasswordToken.objects.create(user=user_obj, secret_token=random_number)
send_sms(phone_number, message=settings.SMS_MSG_PASSWORD.format(random_number))
request.session['username'] = phone_number
return HttpResponseRedirect(reverse('mail:validate_token'))
else:
return render(request, 'password_reset_request_form.html', {'form': form})
class PasswordResetValidateToken(generic.View):
def get(self, request):
form = ActivateForm()
return render(request, 'activate_account.html', {'form': form})
def post(self, request):
form = ActivateForm(request.POST or None)
if form.is_valid():
username = request.session['username']
activation_code = request.POST.get('activation_code')
activation = ForgotPasswordToken.objects.filter(user__username=username, secret_token=activation_code)
if activation.exists():
instance = get_object_or_404(ForgotPasswordToken, user__username=username, secret_token=activation_code)
instance.is_done = True
instance.save()
return HttpResponseRedirect(reverse('mail:reset_password'))
else:
return render(request, 'activate_account.html', {'form': form, 'error': 'Invalid Activation Code.'})
else:
return render(request, 'activate_account.html', {'form': form})
class PasswordResetView(generic.View):
def get(self, request):
return render(request, 'password_reset_form.html', {'form': PasswordResetForm()})
def post(self, request):
phone_number = request.session['username']
request.POST = request.POST.copy()
request.POST['phone_number'] = phone_number
form = PasswordResetForm(request.POST)
#Check if user activated the code or not
if not ForgotPasswordToken.objects.filter(user__username=phone_number, is_done=True):
return render(request, 'password_reset_form.html', {'form': form, 'error': 'Please use activation code first.'})
if not User.objects.filter(username=phone_number, is_active=True):
return render(request, 'password_reset_form.html', {'form': form, 'error': 'Phone number is not registered.'})
if form.is_valid():
password = request.POST.get('new_password1')
user_obj = get_object_or_404(User, username=phone_number)
user_obj.set_password(password)
user_obj.save()
ForgotPasswordToken.objects.filter(user=user_obj).delete()
#send_sms(phone_number, message='Password Successfully Reset.')
return HttpResponseRedirect(reverse('mail:login'))
else:
return render(request, 'password_reset_form.html', {'form': form})
class PasswordChangeView(LoginRequiredMixin, generic.View):
def get(self, request):
return render(request, 'change_password.html', {'form': ChangePasswordForm()})
def post(self, request):
form = ChangePasswordForm(request.POST)
if form.is_valid():
password = request.POST.get('new_password1')
old_password = request.POST.get('old_password')
if not request.user.check_password(old_password):
return render(request, 'change_password.html', {'form': form, 'error': 'Invalid old password.'})
request.user.set_password(password)
request.user.save()
messages.success(request, 'Password successfully changed')
return HttpResponseRedirect(reverse('mail:profile'))
else:
return render(request, 'change_password.html', {'form': form})
def download_attachment(request, pk):
obj = get_object_or_404(MailAttachment, pk=pk)
file_path = obj.attachment.name
filename = file_path.split('/')[-1]
mime_type = determine_mime_type(os.path.join(settings.MEDIA_ROOT, file_path))
response = HttpResponse(obj.attachment, content_type=mime_type)
response['Content-Disposition'] = 'attachment; filename=%s' %(filename)
return response
class MailForwardListView(LoginRequiredMixin, generic.ListView):
context_object_name = 'emails'
template_name = 'mail_forward_list.html'
model = MailForward
def get_queryset(self):
super(MailForwardListView, self).get_queryset()
return MailForward.objects.filter(user=self.request.user)
def delete_mail_forward(request, pk):
mail_forward = get_object_or_404(MailForward, pk=pk).delete()
return HttpResponseRedirect(reverse_lazy('mail:mailforward_list'))
class MailForwardCreateView(LoginRequiredMixin, generic.CreateView):
model = MailForward
template_name = 'mail_forward_create.html'
success_url = reverse_lazy('mail:mailforward_list')
form_class = MailForwardForm
def form_valid(self, form):
form.instance.user = self.request.user
return super(MailForwardCreateView, self).form_valid(form)
class MailForwardEditView(LoginRequiredMixin, generic.UpdateView):
model = MailForward
template_name = 'mail_forward_create.html'
success_url = reverse_lazy('mail:mailforward_list')
form_class = MailForwardForm
def form_valid(self, form):
form.instance.user = self.request.user
return super(MailForwardEditView, self).form_valid(form)
class AboutView(generic.TemplateView):
template_name = 'about.html'
class ContactView(SuccessMessageMixin, generic.CreateView):
template_name = 'contact.html'
form_class = ContactUsForm
success_url = reverse_lazy('mail:contact')
success_message = 'Thank you for contacting us. We will get back to you shortly.'
def form_valid(self, form):
headers = {'Reply-To': form.cleaned_data.get('contact_email')}
msg = EmailMultiAlternatives(form.cleaned_data.get('subject').strip(), form.cleaned_data.get('message'), form.cleaned_data.get('contact_email'), ['contact@callnmail.com',],headers=headers)
#html_content = "<p>{0}</p>".format(form.cleaned_data.get('message')).encode('utf8')
msg.attach_alternative(form.cleaned_data.get('message'), "text/html")
msg.send()
return super(ContactView, self).form_valid(form)
class FAQView(generic.TemplateView):
template_name = 'faq.html'
class PrivacyView(generic.TemplateView):
template_name = 'privacy.html'
class ChangeAvatar(LoginRequiredMixin, generic.View):
def get(self, request):
return HttpResponseRedirect(reverse('mail:profile'))
def post(self, request):
avatar = request.FILES.get('avatar')
path = request.POST.get('path')
if avatar:
profile = get_object_or_404(UserProfile, user=request.user)
profile.avatar = avatar
profile.save()
messages.success(request, 'Profile Avatar successfully changed.')
return HttpResponseRedirect(path)
class TestTemplate(generic.TemplateView):
template_name = "test.html"
def get_context_data(self, **kwargs):
context = super(TestTemplate, self).get_context_data(**kwargs)
country = Country.objects.all().order_by('priority')
for c in country:
c.prefix_val = c.prefix[1:]
context['codes'] = country
return context
| 40.891827
| 196
| 0.654812
|
aff9bcfcbb2eecf7b4e4931dcf698f04fea5d3ec
| 4,895
|
py
|
Python
|
source/code/utilities.py
|
awslabs/tag-tamer
|
bfd164c36b5e3ba8e01aba54d973ce372e982b09
|
[
"MIT",
"MIT-0"
] | 15
|
2021-06-27T23:42:37.000Z
|
2021-09-24T19:40:00.000Z
|
source/code/utilities.py
|
awslabs/tag-tamer
|
bfd164c36b5e3ba8e01aba54d973ce372e982b09
|
[
"MIT",
"MIT-0"
] | 7
|
2021-07-05T06:56:46.000Z
|
2021-08-06T00:59:36.000Z
|
source/code/utilities.py
|
awslabs/tag-tamer
|
bfd164c36b5e3ba8e01aba54d973ce372e982b09
|
[
"MIT",
"MIT-0"
] | 5
|
2021-06-23T17:59:01.000Z
|
2021-10-20T14:22:44.000Z
|
#!/usr/bin/env python3
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
# Tag Tamer utility functions
import json
import logging
import time
import urllib.request
import boto3
import boto3.session
import botocore
from jose import jwk, jwt
from jose.utils import base64url_decode
# Instantiate logging for this module using its file name
log = logging.getLogger(__name__)
def get_aws_regions():
"""Returns a list of all current AWS regions"""
my_session = boto3.session.Session(region_name="us-east-1")
try:
available_regions = my_session.get_available_regions(
service_name="ec2", partition_name="aws"
)
except botocore.exceptions.ClientError as error:
log.error(
"Boto3 API returned error. function: {} - {}".format(
get_aws_regions.__name__, error
)
)
available_regions = False
return available_regions
def get_resource_type_unit(type):
"""Returns the Boto3 resource type & unit to the caller"""
if type:
if type == "codecommit":
resource_type = "codecommit"
unit = "repositories"
elif type == "codepipeline":
resource_type = "codepipeline"
unit = "pipelines"
elif type == "dynamodb":
resource_type = "dynamodb"
unit = "tables"
elif type == "ebs":
resource_type = "ebs"
unit = "volumes"
elif type == "ec2":
resource_type = "ec2"
unit = "instances"
elif type == "ecr":
resource_type = "ecr"
unit = "ecrrepositories"
elif type == "eks":
resource_type = "eks"
unit = "clusters"
elif type == "lambda":
resource_type = "lambda"
unit = "functions"
elif type == "rds":
resource_type = "rds"
unit = "rdsclusters"
elif type == "rdsInstances":
resource_type = "rdsInstances"
unit = "rdsInstances"
elif type == "redshift":
resource_type = "redshift"
unit = "redshiftclusters"
elif type == "s3":
resource_type = "s3"
unit = "buckets"
else:
# If no resource type specified, set type to Amazon EC2
resource_type = "ec2"
unit = "instances"
return resource_type, unit
def verify_jwt(region, user_pool_id, app_client_id, token_type, token):
"""Decode & verify JWT claims"""
this_region = region
this_user_pool_id = user_pool_id
this_token_type = token_type
this_token = token
this_app_client_id = app_client_id
keys_url = "https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json".format(
this_region, this_user_pool_id
)
with urllib.request.urlopen(keys_url) as f:
response = f.read()
keys = json.loads(response.decode("utf-8"))["keys"]
headers = jwt.get_unverified_headers(this_token)
kid = headers["kid"]
# search for the kid in the downloaded public keys
key_index = -1
for i in range(len(keys)):
if kid == keys[i]["kid"]:
key_index = i
break
if key_index == -1:
log.error("Public key not found in jwks.json")
return False
# construct the public key
public_key = jwk.construct(keys[key_index])
# get the last two sections of the token,
# message and signature (encoded in base64)
message, encoded_signature = str(this_token).rsplit(".", 1)
# decode the signature
decoded_signature = base64url_decode(encoded_signature.encode("utf-8"))
# verify the signature
if not public_key.verify(message.encode("utf8"), decoded_signature):
log.error("Signature verification failed")
return False
log.info("Identity token signature successfully verified")
# since we passed the verification, we can now safely
# use the unverified claims
claims = jwt.get_unverified_claims(this_token)
# additionally we can verify the token expiration
if time.time() > claims["exp"]:
log.error("Token is expired")
return False
# and the Audience (use claims['client_id'] if verifying an access token)
if this_token_type == "access_token":
if claims["client_id"] != this_app_client_id:
log.error("Token was not issued for this audience")
return False
elif this_token_type == "id_token":
if claims["aud"] != this_app_client_id:
log.error("Token was not issued for this audience")
return False
else:
return False
# now we can use the claims
return claims
| 34.230769
| 87
| 0.598774
|
a9ea7177f5827027b7398b9467ba7bfbee76976f
| 11,067
|
php
|
PHP
|
application/views/admin/tambahBarang.php
|
mfaisaln/rentalin
|
5b821aeba3f9ff0da3386e01229fd9568e60bab0
|
[
"MIT"
] | null | null | null |
application/views/admin/tambahBarang.php
|
mfaisaln/rentalin
|
5b821aeba3f9ff0da3386e01229fd9568e60bab0
|
[
"MIT"
] | null | null | null |
application/views/admin/tambahBarang.php
|
mfaisaln/rentalin
|
5b821aeba3f9ff0da3386e01229fd9568e60bab0
|
[
"MIT"
] | null | null | null |
<!doctype html>
<!--
Material Design Lite
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://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
-->
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<link rel="icon" type="image/png" href="images/DB_16х16.png">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Material Dashboard Lite</title>
<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Material Design Lite">
<!-- Tile icon for Win8 (144x144 + tile color) -->
<meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#3372DF">
<!-- SEO: If your mobile URL is different from the desktop URL, add a canonical link to the desktop page https://developers.google.com/webmasters/smartphone-sites/feature-phones -->
<!--
<link rel="canonical" href="http://www.example.com/">
-->
<link href='https://fonts.googleapis.com/css?family=Roboto:400,500,300,100,700,900' rel='stylesheet'
type='text/css'>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- inject:css -->
<?php $this->load->view('admin/css');?>
<!-- endinject -->
<script type="text/javascript">
function valid(theform)
{
pola_nama=/^[a-zA-Z]*$/;
if (!pola_nama.test(theform.nama_merek.value)){
alert ('Hanya huruf yang diperbolehkan untuk Merek!');
theform.nama_merek.focus();
return false;
}
return (true);
}
</script>
</head>
<body>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-drawer mdl-layout--fixed-header">
<?php $this->load->view('admin/header');?>
<?php $this->load->view('admin/navleft');?>
<main class="mdl-layout__content mdl-color--grey-100">
<div class="mdl-card mdl-shadow--2dp employer-form" action="#">
<div class="mdl-card__title">
<h2>Form</h2>
<div class="mdl-card__subtitle">Please complete the form</div>
</div>
<?php
if($this->session->userdata('pesan') == "0"){
?>
<div class="materialert danger">
<i class="material-icons">error_outline</i> <span>Data barang sudah ada </span>
</div>
<?php
$this->session->unset_userdata('pesan');
}else if($this->session->userdata('pesan') == ""){
?>
<?php
$this->session->unset_userdata('pesan');
}else{
?>
<div class="materialert info">
<i class="material-icons">check_circle</i> <span>Berhasil Menambahkan Barang <?php echo $this->session->userdata('pesan')?></span>
</div>
<?php
$this->session->unset_userdata('pesan');
}
?>
<!-- <div class="materialert info">
<i class="material-icons">check_circle</i> <span>Tambah Barang Berhasil</span>
</div>
<div class="materialert danger">
<i class="material-icons">error_outline</i> <span>Tambah Barang Berhasil</span>
</div> -->
<div class="mdl-card__supporting-text">
<form name="theform" action="<?php echo base_url('Barang/aksi_tambah'); ?>" class="form" method="post" onSubmit="return valid(this);">
<div class="form__article">
<h3>Tambah Barang</h3>
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--9-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="nama_barang" name="nama_barang" value="Sepeda" required=""/>
<label class="mdl-textfield__label" for="nama_barang">Nama Barang</label>
</div>
<div class="mdl-cell mdl-cell--3-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select">
<input class="mdl-textfield__input" type="text" id="merek" name="id_barang" readonly tabIndex="-1" required=""/>
<label class="mdl-textfield__label" for="merek">Pilih Merek</label>
<ul class="mdl-menu mdl-menu--bottom-left mdl-js-menu dark_dropdown" for="merek">
<?php
if( ! empty($merek)){ // Jika data siswa tidak sama dengan kosong, artinya jika data siswa ada
foreach($merek as $data){
?>
<li class="mdl-menu__item"><?php echo $data->nama_merek; ?></li>
<?php
}
}else{
}
?>
</ul>
<label for="merek">
<i class="mdl-icon-toggle__label material-icons">arrow_drop_down</i>
</label>
</div>
</div>
<div class="mdl-cell mdl-cell--12-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<textarea class="mdl-textfield__input" type="text" rows="1" id="spesifikasi" name="spec" required="">Spesifikasi</textarea>
<label class="mdl-textfield__label" for="spesifikasi">Spesifikasi</label>
</div>
<div class="mdl-cell mdl-cell--12-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<textarea class="mdl-textfield__input" type="text" rows="1" id="deskripsi" name="deskripsi" required="">Deskripsi</textarea>
<label class="mdl-textfield__label" for="deskripsi">Deskripsi</label>
</div>
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--6-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="harga" value="10000" name="harga" required=""/>
<label class="mdl-textfield__label" for="harga">Harga/Hari</label>
</div>
<div class="mdl-cell mdl-cell--6-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="tahun" value="2017" name="tahun" required=""/>
<label class="mdl-textfield__label" for="tahun">Tahun Pembutan</label>
</div>
</div>
<!-- Gambar -->
<!-- <div class="mdl-grid">
<div class="mdl-cell mdl-cell--6-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="harga" value=""/>
<label class="mdl-textfield__label" for="harga">Harga/Hari</label>
</div>
<div class="mdl-cell mdl-cell--6-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="tahun" value=""/>
<label class="mdl-textfield__label" for="tahun">Tahun Pembutan</label>
</div>
</div>
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--6-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="harga" value=""/>
<label class="mdl-textfield__label" for="harga">Harga/Hari</label>
</div>
<div class="mdl-cell mdl-cell--6-col mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="tahun" value=""/>
<label class="mdl-textfield__label" for="tahun">Tahun Pembutan</label>
</div>
</div> -->
<!-- Gambar -->
</div>
<div class="mdl-card__actions">
<input type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect button--colored-green pull-right"value="Simpan" />
</div>
</form>
</div>
</div>
</main>
</div>
<!-- inject:js -->
<?php $this->load->view('admin/javascript');?>
<!-- endinject -->
</body>
</html>
| 52.7
| 185
| 0.485588
|
8ea25a3482ba158069e9fd2b5a72e5eae5acb4c1
| 734
|
js
|
JavaScript
|
web/fleet-management-web/src/components/newitem/NewItemBottomButtons.js
|
mwalasz/Fleet-management-system
|
d0fbc7bc06be680bae80457950eb637cde0f1bf0
|
[
"MIT"
] | 3
|
2021-02-15T20:38:42.000Z
|
2021-08-25T01:41:53.000Z
|
web/fleet-management-web/src/components/newitem/NewItemBottomButtons.js
|
mwalasz/Fleet-management-system
|
d0fbc7bc06be680bae80457950eb637cde0f1bf0
|
[
"MIT"
] | null | null | null |
web/fleet-management-web/src/components/newitem/NewItemBottomButtons.js
|
mwalasz/Fleet-management-system
|
d0fbc7bc06be680bae80457950eb637cde0f1bf0
|
[
"MIT"
] | null | null | null |
import React from 'react';
import styled from 'styled-components';
import Button from '../Button';
const ButtonsWrapper = styled.div`
display: flex;
position: fixed;
bottom: ${({ low }) => (low ? '140px' : '200px')};
align-self: center;
`;
const NewItemBottomButtons = ({ resetForm, onSubmit, low }) => (
<ButtonsWrapper low={low}>
<Button wide rounded accept margin="0px 20px" onClick={onSubmit}>
DODAJ
</Button>
<Button
wide
rounded
cancel
margin="0px 20px"
type="button"
onClick={resetForm}
>
ANULUJ
</Button>
</ButtonsWrapper>
);
export default NewItemBottomButtons;
| 23.677419
| 73
| 0.559946
|
ddc73b88f15bddcfca754f6d5acaac920f8cb721
| 691
|
java
|
Java
|
src/main/java/com/github/vezzoni/cassandra/data/loader/dataset/xml/XmlDataSet.java
|
vezzoni/cassandra-data-loader
|
cfda381fcd99a28d990c738a30decab0ababd14c
|
[
"MIT"
] | 1
|
2016-07-14T17:58:57.000Z
|
2016-07-14T17:58:57.000Z
|
src/main/java/com/github/vezzoni/cassandra/data/loader/dataset/xml/XmlDataSet.java
|
vezzoni/cassandra-data-loader
|
cfda381fcd99a28d990c738a30decab0ababd14c
|
[
"MIT"
] | null | null | null |
src/main/java/com/github/vezzoni/cassandra/data/loader/dataset/xml/XmlDataSet.java
|
vezzoni/cassandra-data-loader
|
cfda381fcd99a28d990c738a30decab0ababd14c
|
[
"MIT"
] | null | null | null |
package com.github.vezzoni.cassandra.data.loader.dataset.xml;
import java.io.InputStream;
import com.github.vezzoni.cassandra.data.loader.dataset.DataSet;
/**
* Specialized class for <code>XML</code> formated source.
*
* @see DataSet
*
* @author vezzoni
*/
public class XmlDataSet implements DataSet {
private final InputStream source;
/**
* Constructor responsible to receive the <code>XML</code> formated source.
*
* @param source <code>XML</code> formated source
*/
public XmlDataSet(InputStream source) {
this.source = source;
}
@Override
public InputStream getSource() {
return this.source;
}
}
| 21.59375
| 79
| 0.662808
|
f7d72258e63abaeea5d7150a237ff4baef6839a7
| 887
|
rb
|
Ruby
|
spec/person_spec.rb
|
orhanna14/extract-validator
|
7e974cd51578170afff068108620aee79da41470
|
[
"MIT"
] | 2
|
2018-10-18T15:22:38.000Z
|
2018-11-07T12:31:57.000Z
|
spec/person_spec.rb
|
orhanna14/extract-validator
|
7e974cd51578170afff068108620aee79da41470
|
[
"MIT"
] | null | null | null |
spec/person_spec.rb
|
orhanna14/extract-validator
|
7e974cd51578170afff068108620aee79da41470
|
[
"MIT"
] | 3
|
2019-06-28T15:17:08.000Z
|
2021-02-12T06:08:18.000Z
|
require 'spec_helper'
describe Person do
it 'does not validate if a phone number is not provided' do
invalid_person_one = Person.new
invalid_person_two = Person.new(phone_number: '')
expect(invalid_person_one).not_to be_valid
expect(invalid_person_two).not_to be_valid
end
it 'does not validate if a phone number formatting is incorrect' do
invalid_person_one = Person.new(phone_number: '++7777-777-777')
invalid_person_two = Person.new(phone_number: '777-7777-7777')
expect(invalid_person_one).not_to be_valid
expect(invalid_person_two).not_to be_valid
end
it 'validates with correct phone number formatting' do
valid_person_one = Person.new(phone_number: '7777777777')
valid_person_two = Person.new(phone_number: '777-777-7777 ext 888')
expect(valid_person_one).to be_valid
expect(valid_person_two).to be_valid
end
end
| 31.678571
| 71
| 0.75761
|
05c0a713099f0f9e52d2d3878d410fe30e9f8001
| 3,286
|
py
|
Python
|
nrc_spifpy/images.py
|
nrc-cnrc/NRC-SPIFpy
|
1024b8d64e9bf3590edf97460a99622d74067aae
|
[
"MIT"
] | 4
|
2021-12-13T17:03:27.000Z
|
2022-01-14T22:41:10.000Z
|
nrc_spifpy/images.py
|
nrc-cnrc/NRC-SPIFpy
|
1024b8d64e9bf3590edf97460a99622d74067aae
|
[
"MIT"
] | 1
|
2021-12-13T18:43:13.000Z
|
2021-12-13T19:08:27.000Z
|
nrc_spifpy/images.py
|
nrc-cnrc/NRC-SPIFpy
|
1024b8d64e9bf3590edf97460a99622d74067aae
|
[
"MIT"
] | 1
|
2021-12-13T18:43:28.000Z
|
2021-12-13T18:43:28.000Z
|
#!/usr/bin/env python
# coding: utf-8
import gc
import time
import numpy
from .utils import list_to_array, list3d_to_array, _reshape_image
class Images(object):
""" Class containing info for set of images. Default info includes
nanoseconds, seconds, image, length, and buffer index. Users can add other
parameters by passing list at initialization with names of other parameters
to store.
Class Attributes
----------------
default_items : list of str
List of default items common to all image sources.
Attributes
----------
ns : list
Nanoseconds timestamp for images.
sec : list
Seconds timestamp for images.
image : list
Image data for images.
length : list
Length data, in slices, for images.
buffer_index : list
Buffer index value for images.
Parameters
----------
aux_names : list of str, optional
List of strings of auxiliary parameters to include in current Images
instance. If provided, strings in list become class attributes.
"""
default_items = ['ns', 'sec', 'image', 'length', 'buffer_index']
def __init__(self, aux_names=None):
for item in self.default_items:
setattr(self, item, [])
if aux_names is not None:
for name in aux_names:
setattr(self, name, [])
def __len__(self):
return len(self.sec)
def clear(self):
""" Resets all class attributes to empty lists.
"""
for key in self.__dict__.keys():
setattr(self, key, [])
gc.collect()
def extend(self, p):
""" Extends all attributes in current instance with corresponding
attributes in given instance.
Parameters
----------
p : Images object
Images object to copy data from to current instance.
"""
if p is not None:
if len(p) > 0:
for key, val in self.__dict__.items():
getattr(self, key).extend(getattr(p, key))
def reshape_image(self, diodes):
""" Reshapes image data to 3-D array, with dimensions of image, slices,
and diodes. Should be called only before passing to write function, as
reshaped images cannot be extended with other image data.
Parameters
----------
diodes : int
Number of diodes of current instrument.
"""
t0 = time.time()
image, max_slices = list_to_array(self.image, diodes)
print(time.time() - t0)
t0 = time.time()
#self.image = numpy.reshape(image, (-1, max_slices // diodes, diodes))
self.image = _reshape_image(image, max_slices, diodes)
print(time.time() - t0)
def conv_to_array(self, diodes):
""" Converts list of 2-D arrays to 1-D numpy array. Should be called
only before passing to write function, as reshaped images cannot be
extended with other image data.
Parameters
----------
diodes : int
Number of diodes of current instrument.
"""
# self.image = list(itertools.chain.from_iterable(self.image))
flatten = numpy.concatenate(self.image)
self.image = flatten.ravel()
| 30.71028
| 79
| 0.601339
|
a9ee7da7a0594a6603205c1b717aace38a9448cb
| 12,188
|
php
|
PHP
|
vendor/civicrm/civicrm-core/tests/phpunit/CiviTest/CiviMailUtils.php
|
jdelon02/civitest1
|
da6466669fea4fc435b6f62968f647879bbac594
|
[
"MIT"
] | null | null | null |
vendor/civicrm/civicrm-core/tests/phpunit/CiviTest/CiviMailUtils.php
|
jdelon02/civitest1
|
da6466669fea4fc435b6f62968f647879bbac594
|
[
"MIT"
] | 7
|
2019-09-25T00:20:20.000Z
|
2021-09-02T11:44:23.000Z
|
vendor/civicrm/civicrm-core/tests/phpunit/CiviTest/CiviMailUtils.php
|
jdelon02/civitest1
|
da6466669fea4fc435b6f62968f647879bbac594
|
[
"MIT"
] | null | null | null |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 5 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License along with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Mail utils for use during unit testing to allow retrieval
* and examination of 'sent' emails.
*
* Basic usage:
*
* $mut = new CiviMailUtils( $this, true ); //true automatically starts spooling
* ... do stuff ...
* $msg = $mut->getMostRecentEmail( 'raw' ); // or 'ezc' to get an ezc mail object
* ... assert stuff about $msg ...
* $mut->stop();
*
*
* @package CiviCRM
*/
/**
* Class CiviMailUtils
*/
class CiviMailUtils extends PHPUnit_Framework_TestCase {
/**
* @var mixed current outbound email option
*/
protected $_outBound_option = NULL;
/**
* @var bool is this a webtest
*/
protected $_webtest = FALSE;
/**
* Constructor.
*
* @param CiviSeleniumTestCase|CiviUnitTestCase $unit_test The currently running test
* @param bool $startImmediately
* Start writing to db now or wait until start() is called.
*/
public function __construct(&$unit_test, $startImmediately = TRUE) {
$this->_ut = $unit_test;
// Check if running under webtests or not
if (is_subclass_of($unit_test, 'CiviSeleniumTestCase')) {
$this->_webtest = TRUE;
}
if ($startImmediately) {
$this->start();
}
}
/**
* Start writing emails to db instead of current option.
*/
public function start() {
if ($this->_webtest) {
// Change outbound mail setting
$this->_ut->openCiviPage('admin/setting/smtp', "reset=1", "_qf_Smtp_next");
// First remember the current setting
$this->_outBound_option = $this->getSelectedOutboundOption();
$this->_ut->click('xpath=//input[@name="outBound_option" and @value="' . CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB . '"]');
$this->_ut->clickLink("_qf_Smtp_next");
// Is there supposed to be a status message displayed when outbound email settings are changed?
// assert something?
}
else {
// save current setting for outbound option, then change it
$mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'mailing_backend'
);
$this->_outBound_option = $mailingBackend['outBound_option'];
$mailingBackend['outBound_option'] = CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB;
Civi::settings()->set('mailing_backend', $mailingBackend);
$mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'mailing_backend'
);
}
}
public function stop() {
if ($this->_webtest) {
if ($this->_outBound_option != CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
// Change outbound mail setting
$this->_ut->openCiviPage('admin/setting/smtp', "reset=1", "_qf_Smtp_next");
$this->_ut->click('xpath=//input[@name="outBound_option" and @value="' . $this->_outBound_option . '"]');
// There will be a warning when switching from test to live mode
if ($this->_outBound_option != CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED) {
$this->_ut->getAlert();
}
$this->_ut->clickLink("_qf_Smtp_next");
}
}
else {
$mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
'mailing_backend'
);
$mailingBackend['outBound_option'] = $this->_outBound_option;
Civi::settings()->set('mailing_backend', $mailingBackend);
}
}
/**
* @param string $type
*
* @return ezcMail|string
*/
public function getMostRecentEmail($type = 'raw') {
$msg = '';
if ($this->_webtest) {
// I don't understand but for some reason we have to load the page twice for a recent mailing to appear.
$this->_ut->openCiviPage('mailing/browse/archived', 'reset=1');
$this->_ut->openCiviPage('mailing/browse/archived', 'reset=1', 'css=td.crm-mailing-name');
}
// We can't fetch mailing headers from webtest so we'll only try if the format is raw
if ($this->_webtest && $type == 'raw') {
// This should select the first "Report" link in the table, which is sorted by Completion Date descending, so in theory is the most recent email. Not sure of a more robust way at the moment.
$this->_ut->clickLink('xpath=//tr[contains(@id, "crm-mailing_")]//a[text()="Report"]');
// Also not sure how robust this is, but there isn't a good
// identifier for this link either.
$this->_ut->waitForElementPresent('xpath=//a[contains(text(), "View complete message")]');
$this->_ut->clickAjaxLink('xpath=//a[contains(text(), "View complete message")]');
$msg = $this->_ut->getText('css=.ui-dialog-content.crm-ajax-container');
}
else {
$dao = CRM_Core_DAO::executeQuery('SELECT headers, body FROM civicrm_mailing_spool ORDER BY id DESC LIMIT 1');
if ($dao->fetch()) {
$msg = $dao->headers . "\n\n" . $dao->body;
}
$dao->free();
}
switch ($type) {
case 'raw':
// nothing to do
break;
case 'ezc':
$msg = $this->convertToEzc($msg);
break;
}
return $msg;
}
/**
* @param string $type
* 'raw'|'ezc'.
*
* @throws Exception
* @return array(ezcMail)|array(string)
*/
public function getAllMessages($type = 'raw') {
$msgs = array();
if ($this->_webtest) {
throw new Exception("Not implemented: getAllMessages for WebTest");
}
else {
$dao = CRM_Core_DAO::executeQuery('SELECT headers, body FROM civicrm_mailing_spool ORDER BY id');
while ($dao->fetch()) {
$msgs[] = $dao->headers . "\n\n" . $dao->body;
}
$dao->free();
}
switch ($type) {
case 'raw':
// nothing to do
break;
case 'ezc':
foreach ($msgs as $i => $msg) {
$msgs[$i] = $this->convertToEzc($msg);
}
break;
}
return $msgs;
}
/**
* @return int
*/
public function getSelectedOutboundOption() {
$selectedOption = CRM_Mailing_Config::OUTBOUND_OPTION_MAIL;
// Is there a better way to do this? How do you get the currently selected value of a radio button in selenium?
for ($i = 0; $i <= 5; $i++) {
if ($i != CRM_Mailing_Config::OUTBOUND_OPTION_MOCK) {
if ($this->_ut->getValue('xpath=//input[@name="outBound_option" and @value="' . $i . '"]') == "on") {
$selectedOption = $i;
break;
}
}
}
return $selectedOption;
}
/*
* Utility functions (previously part of CiviUnitTestCase)
* Included for backward compatibility with existing tests.
*/
/**
* Check contents of mail log.
*
* @param array $strings
* Strings that should be included.
* @param array $absentStrings
* Strings that should not be included.
* @param string $prefix
*
* @return \ezcMail|string
*/
public function checkMailLog($strings, $absentStrings = array(), $prefix = '') {
$mail = $this->getMostRecentEmail('raw');
return $this->checkMailForStrings($strings, $absentStrings, $prefix, $mail);
}
/**
* Check contents of mail log.
*
* @param array $strings
* Strings that should be included.
* @param array $absentStrings
* Strings that should not be included.
* @param string $prefix
*
* @return \ezcMail|string
*/
public function checkAllMailLog($strings, $absentStrings = array(), $prefix = '') {
$mails = $this->getAllMessages('raw');
$mail = implode(',', $mails);
return $this->checkMailForStrings($strings, $absentStrings, $prefix, $mail);
}
/**
* Check that mail log is empty.
* @param string $prefix
*/
public function assertMailLogEmpty($prefix = '') {
$mail = $this->getMostRecentEmail('raw');
$this->_ut->assertEmpty($mail, 'mail sent when it should not have been ' . $prefix);
}
/**
* Assert that $expectedRecipients (and no else) have received emails
*
* @param array $expectedRecipients
* Array($msgPos => array($recipPos => $emailAddr)).
*/
public function assertRecipients($expectedRecipients) {
$recipients = array();
foreach ($this->getAllMessages('ezc') as $message) {
$recipients[] = CRM_Utils_Array::collect('email', $message->to);
}
$cmp = function($a, $b) {
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? 1 : -1;
};
usort($recipients, $cmp);
usort($expectedRecipients, $cmp);
$this->_ut->assertEquals(
$expectedRecipients,
$recipients,
"Incorrect recipients: " . print_r(array('expected' => $expectedRecipients, 'actual' => $recipients), TRUE)
);
}
/**
* Assert that $expectedSubjects (and no other subjects) were sent.
*
* @param array $expectedSubjects
* Array(string $subj).
*/
public function assertSubjects($expectedSubjects) {
$subjects = array();
foreach ($this->getAllMessages('ezc') as $message) {
/** @var ezcMail $message */
$subjects[] = $message->subject;
}
sort($subjects);
sort($expectedSubjects);
$this->_ut->assertEquals(
$expectedSubjects,
$subjects,
"Incorrect subjects: " . print_r(array('expected' => $expectedSubjects, 'actual' => $subjects), TRUE)
);
}
/**
* Remove any sent messages from the log.
*
* @param int $limit
* How many recent messages to remove, defaults to 0 (all).
*
* @throws \Exception
*/
public function clearMessages($limit = 0) {
if ($this->_webtest) {
throw new Exception("Not implemented: clearMessages for WebTest");
}
else {
$sql = 'DELETE FROM civicrm_mailing_spool ORDER BY id DESC';
if ($limit) {
$sql .= ' LIMIT ' . $limit;
}
CRM_Core_DAO::executeQuery($sql);
}
}
/**
* @param string $msg
* Email header and body.
* @return ezcMail
*/
private function convertToEzc($msg) {
$set = new ezcMailVariableSet($msg);
$parser = new ezcMailParser();
$mail = $parser->parseMail($set);
$this->_ut->assertNotEmpty($mail, 'Cannot parse mail');
return $mail[0];
}
/**
* @param $strings
* @param $absentStrings
* @param $prefix
* @param $mail
* @return mixed
*/
public function checkMailForStrings($strings, $absentStrings, $prefix, $mail) {
foreach ($strings as $string) {
$this->_ut->assertContains($string, $mail, "$string . not found in $mail $prefix");
}
foreach ($absentStrings as $string) {
$this->_ut->assertEmpty(strstr($mail, $string), "$string incorrectly found in $mail $prefix");;
}
return $mail;
}
}
| 31.905759
| 196
| 0.588776
|
2eb78af8276cbcfa00061f3609659fade21ca073
| 364
|
asm
|
Assembly
|
programs/oeis/055/A055848.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | 1
|
2021-03-15T11:38:20.000Z
|
2021-03-15T11:38:20.000Z
|
programs/oeis/055/A055848.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
programs/oeis/055/A055848.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
; A055848: Expansion of (1+5*x)/(1-x)^10.
; 1,15,105,495,1815,5577,15015,36465,81510,170170,335478,629850,1133730,1967070,3304290,5393454,8580495,13339425,20309575,30341025,44549505,64382175,91695825,128849175,178811100,245286756,332863740,447180580
mov $1,8
add $1,$0
mov $2,1
mul $2,$0
bin $1,$2
mov $3,$0
mul $3,2
add $3,3
mul $1,$3
sub $1,3
div $1,3
add $1,1
| 22.75
| 207
| 0.722527
|
3f220ecf28a970e51efc52c59fd79d4ad39b05f2
| 2,030
|
php
|
PHP
|
app/Http/Livewire/Biometrico.php
|
rikardote/incidencias_wire
|
a5f32175616c3cc047cf40ba231d7250afcab5e7
|
[
"MIT"
] | null | null | null |
app/Http/Livewire/Biometrico.php
|
rikardote/incidencias_wire
|
a5f32175616c3cc047cf40ba231d7250afcab5e7
|
[
"MIT"
] | null | null | null |
app/Http/Livewire/Biometrico.php
|
rikardote/incidencias_wire
|
a5f32175616c3cc047cf40ba231d7250afcab5e7
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Carbon\Carbon;
use App\Models\Departamento;
use App\Models\Qna;
use DateTime;
use DateInterval;
use DatePeriod;
use App\Models\Empleado;
use App\Models\Horario;
class Biometrico extends Component
{
public $empleados;
public $daterange;
public function render()
{
$dpto ='19';
$qna_id = '188';
$qna = Qna::where('id', $qna_id)->first();
$fecha_inicio = $this->getFechaInicioPorQna($qna->id);
$fecha_final = $this->getFechaFinalPorQna($fecha_inicio);
$begin = new DateTime( $fecha_inicio );
$end = new DateTime( $fecha_final );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$this->daterange = new DatePeriod($begin, $interval ,$end);
//$checadas = Checada::get_Checadas($dpto, $qna->qna, $qna->year);
$this->empleados = Empleado::with('departamento', 'jornada','puesto', 'horario')
->where('deparment_id',$dpto)
->orderBy('num_empleado', 'ASC')
->get();
return view('livewire.biometrico');
}
public function getFechaInicioPorQna($qna_id){
$qna = Qna::where('id', '=', $qna_id)->first();
$mes = ($qna->qna / 2);
$mes_redondeado = ceil($mes);
$mes_int = intval($mes_redondeado);
if($qna->qna %2 == 0){
$f_inicio = Carbon::create($qna->year, $mes_int, '16',0,0,0);
}else{
$f_inicio = Carbon::create($qna->year, $mes_int, '01',0,0,0);
}
return $f_inicio->toDateString();
}
public function getFechaFinalPorQna($f_inicio){
$date = Carbon::parse($f_inicio);
$month = $date->month;
$day = $date->day;
$year = $date->year;
if($day < 16) {
$f_final = Carbon::create($year, $month, '15',0,0,0);
}
else {
$f_final = $date->endOfMonth();
}
return $f_final->toDateString();
}
}
| 25.696203
| 88
| 0.555665
|
8b7b358da5e422ffa274ad9f0e9674baf3ffcbf3
| 834
|
rb
|
Ruby
|
stdlib/spec/functions/is_email_address_spec.rb
|
santhu3064/puppet-all-modules
|
bea77129f5215d7ed290add57eddc7016cbf60c9
|
[
"Apache-2.0"
] | 283
|
2017-10-10T07:13:59.000Z
|
2022-03-06T20:17:29.000Z
|
stdlib/spec/functions/is_email_address_spec.rb
|
santhu3064/puppet-all-modules
|
bea77129f5215d7ed290add57eddc7016cbf60c9
|
[
"Apache-2.0"
] | 818
|
2017-10-12T18:43:59.000Z
|
2019-08-06T07:47:27.000Z
|
stdlib/spec/functions/is_email_address_spec.rb
|
santhu3064/puppet-all-modules
|
bea77129f5215d7ed290add57eddc7016cbf60c9
|
[
"Apache-2.0"
] | 46
|
2017-10-12T01:23:25.000Z
|
2021-01-14T07:40:27.000Z
|
require 'spec_helper'
describe 'is_email_address' do
it { is_expected.not_to eq(nil) }
it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) }
it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) }
it { is_expected.to run.with_params('bob@gmail.com').and_return(true) }
it { is_expected.to run.with_params('alice+puppetlabs.com@gmail.com').and_return(true) }
it { is_expected.to run.with_params('peter.parker@gmail.com').and_return(true) }
it { is_expected.to run.with_params('1.2.3@domain').and_return(false) }
it { is_expected.to run.with_params('1.2.3.4.5@').and_return(false) }
it { is_expected.to run.with_params({}).and_return(false) }
it { is_expected.to run.with_params([]).and_return(false) }
end
| 55.6
| 113
| 0.733813
|
8783e8f2ba6e9b78e26bcd01aaf8764ac69bcb18
| 77,767
|
psm1
|
PowerShell
|
source/Modules/SqlServerDsc.Common/SqlServerDsc.Common.psm1
|
SphenicPaul/SqlServerDsc
|
c98223a508b9a6e5e48c1bdf7a742116f39f6fab
|
[
"MIT"
] | null | null | null |
source/Modules/SqlServerDsc.Common/SqlServerDsc.Common.psm1
|
SphenicPaul/SqlServerDsc
|
c98223a508b9a6e5e48c1bdf7a742116f39f6fab
|
[
"MIT"
] | null | null | null |
source/Modules/SqlServerDsc.Common/SqlServerDsc.Common.psm1
|
SphenicPaul/SqlServerDsc
|
c98223a508b9a6e5e48c1bdf7a742116f39f6fab
|
[
"MIT"
] | null | null | null |
$script:resourceHelperModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\..\Modules\DscResource.Common'
Import-Module -Name $script:resourceHelperModulePath
$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US'
<#
.SYNOPSIS
Returns the value of the provided Name parameter at the registry
location provided in the Path parameter.
.PARAMETER Path
Specifies the path in the registry to the property name.
.PARAMETER PropertyName
Specifies the the name of the property to return the value for.
#>
function Get-RegistryPropertyValue
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path,
[Parameter(Mandatory = $true)]
[System.String]
$Name
)
$getItemPropertyParameters = @{
Path = $Path
Name = $Name
}
<#
Using a try/catch block instead of 'SilentlyContinue' to be
able to unit test a failing registry path.
#>
try
{
$getItemPropertyResult = (Get-ItemProperty @getItemPropertyParameters -ErrorAction 'Stop').$Name
}
catch
{
$getItemPropertyResult = $null
}
return $getItemPropertyResult
}
<#
.SYNOPSIS
Returns the value of the provided in the Name parameter, at the registry
location provided in the Path parameter.
.PARAMETER Path
String containing the path in the registry to the property name.
.PARAMETER PropertyName
String containing the name of the property for which the value is returned.
#>
function Format-Path
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$TrailingSlash
)
# Remove trailing slash ('\') from path.
if ($TrailingSlash.IsPresent)
{
<#
Trim backslash, but only if the path contains a full path and
not just a qualifier.
#>
if ($Path -notmatch '^[a-zA-Z]:\\$')
{
$Path = $Path.TrimEnd('\')
}
<#
If the path only contains a qualifier but no backslash ('M:'),
then a backslash is added ('M:\').
#>
if ($Path -match '^[a-zA-Z]:$')
{
$Path = '{0}\' -f $Path
}
}
return $Path
}
<#
.SYNOPSIS
Copy folder structure using Robocopy. Every file and folder, including empty ones are copied.
.PARAMETER Path
Source path to be copied.
.PARAMETER DestinationPath
The path to the destination.
#>
function Copy-ItemWithRobocopy
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Path,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestinationPath
)
$quotedPath = '"{0}"' -f $Path
$quotedDestinationPath = '"{0}"' -f $DestinationPath
$robocopyExecutable = Get-Command -Name "Robocopy.exe" -ErrorAction Stop
$robocopyArgumentSilent = '/njh /njs /ndl /nc /ns /nfl'
$robocopyArgumentCopySubDirectoriesIncludingEmpty = '/e'
$robocopyArgumentDeletesDestinationFilesAndDirectoriesNotExistAtSource = '/purge'
if ([System.Version]$robocopyExecutable.FileVersionInfo.ProductVersion -ge [System.Version]'6.3.9600.16384')
{
Write-Verbose -Message $script:localizedData.RobocopyUsingUnbufferedIo -Verbose
$robocopyArgumentUseUnbufferedIO = '/J'
}
else
{
Write-Verbose -Message $script:localizedData.RobocopyNotUsingUnbufferedIo -Verbose
}
$robocopyArgumentList = '{0} {1} {2} {3} {4} {5}' -f @(
$quotedPath,
$quotedDestinationPath,
$robocopyArgumentCopySubDirectoriesIncludingEmpty,
$robocopyArgumentDeletesDestinationFilesAndDirectoriesNotExistAtSource,
$robocopyArgumentUseUnbufferedIO,
$robocopyArgumentSilent
)
$robocopyStartProcessParameters = @{
FilePath = $robocopyExecutable.Name
ArgumentList = $robocopyArgumentList
}
Write-Verbose -Message ($script:localizedData.RobocopyArguments -f $robocopyArgumentList) -Verbose
$robocopyProcess = Start-Process @robocopyStartProcessParameters -Wait -NoNewWindow -PassThru
switch ($($robocopyProcess.ExitCode))
{
{ $_ -in 8, 16 }
{
$errorMessage = $script:localizedData.RobocopyErrorCopying -f $_
New-InvalidOperationException -Message $errorMessage
}
{ $_ -gt 7 }
{
$errorMessage = $script:localizedData.RobocopyFailuresCopying -f $_
New-InvalidResultException -Message $errorMessage
}
1
{
Write-Verbose -Message $script:localizedData.RobocopySuccessful -Verbose
}
2
{
Write-Verbose -Message $script:localizedData.RobocopyRemovedExtraFilesAtDestination -Verbose
}
3
{
Write-Verbose -Message (
'{0} {1}' -f $script:localizedData.RobocopySuccessful, $script:localizedData.RobocopyRemovedExtraFilesAtDestination
) -Verbose
}
{ $_ -eq 0 -or $null -eq $_ }
{
Write-Verbose -Message $script:localizedData.RobocopyAllFilesPresent -Verbose
}
}
}
<#
.SYNOPSIS
Connects to the source using the provided credentials and then uses
robocopy to download the installation media to a local temporary folder.
.PARAMETER SourcePath
Source path to be copied.
.PARAMETER SourceCredential
The credentials to access the SourcePath.
.PARAMETER PassThru
If used, returns the destination path as string.
.OUTPUTS
Returns the destination path (when used with the parameter PassThru).
#>
function Invoke-InstallationMediaCopy
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$SourcePath,
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$SourceCredential,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$PassThru
)
Connect-UncPath -RemotePath $SourcePath -SourceCredential $SourceCredential
$SourcePath = $SourcePath.TrimEnd('/\')
<#
Create a destination folder so the media files aren't written
to the root of the Temp folder.
#>
$serverName, $shareName, $leafs = ($SourcePath -replace '\\\\') -split '\\'
if ($leafs)
{
$mediaDestinationFolder = $leafs | Select-Object -Last 1
}
else
{
$mediaDestinationFolder = New-Guid | Select-Object -ExpandProperty Guid
}
$mediaDestinationPath = Join-Path -Path (Get-TemporaryFolder) -ChildPath $mediaDestinationFolder
Write-Verbose -Message ($script:localizedData.RobocopyIsCopying -f $SourcePath, $mediaDestinationPath) -Verbose
Copy-ItemWithRobocopy -Path $SourcePath -DestinationPath $mediaDestinationPath
Disconnect-UncPath -RemotePath $SourcePath
if ($PassThru.IsPresent)
{
return $mediaDestinationPath
}
}
<#
.SYNOPSIS
Connects to the UNC path provided in the parameter SourcePath.
Optionally connects using the provided credentials.
.PARAMETER SourcePath
Source path to connect to.
.PARAMETER SourceCredential
The credentials to access the path provided in SourcePath.
.PARAMETER PassThru
If used, returns a MSFT_SmbMapping object that represents the newly
created SMB mapping.
.OUTPUTS
Returns a MSFT_SmbMapping object that represents the newly created
SMB mapping (ony when used with parameter PassThru).
#>
function Connect-UncPath
{
[CmdletBinding()]
[OutputType([Microsoft.Management.Infrastructure.CimInstance])]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$RemotePath,
[Parameter()]
[System.Management.Automation.PSCredential]
$SourceCredential,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$PassThru
)
$newSmbMappingParameters = @{
RemotePath = $RemotePath
}
if ($PSBoundParameters.ContainsKey('SourceCredential'))
{
$newSmbMappingParameters['UserName'] = $SourceCredential.UserName
$newSmbMappingParameters['Password'] = $SourceCredential.GetNetworkCredential().Password
}
$newSmbMappingResult = New-SmbMapping @newSmbMappingParameters
if ($PassThru.IsPresent)
{
return $newSmbMappingResult
}
}
<#
.SYNOPSIS
Disconnects from the UNC path provided in the parameter SourcePath.
.PARAMETER SourcePath
Source path to disconnect from.
#>
function Disconnect-UncPath
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$RemotePath
)
Remove-SmbMapping -RemotePath $RemotePath -Force
}
<#
.SYNOPSIS
Queries the registry and returns $true if there is a pending reboot.
.OUTPUTS
Returns $true if there is a pending reboot, otherwise it returns $false.
#>
function Test-PendingRestart
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
)
$getRegistryPropertyValueParameters = @{
Path = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
Name = 'PendingFileRenameOperations'
}
<#
If the key 'PendingFileRenameOperations' does not exist then if should
return $false, otherwise it should return $true.
#>
return $null -ne (Get-RegistryPropertyValue @getRegistryPropertyValueParameters)
}
<#
.SYNOPSIS
Starts the SQL setup process.
.PARAMETER FilePath
String containing the path to setup.exe.
.PARAMETER ArgumentList
The arguments that should be passed to setup.exe.
.PARAMETER Timeout
The timeout in seconds to wait for the process to finish.
#>
function Start-SqlSetupProcess
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$FilePath,
[Parameter()]
[System.String]
$ArgumentList,
[Parameter(Mandatory = $true)]
[System.UInt32]
$Timeout
)
$startProcessParameters = @{
FilePath = $FilePath
ArgumentList = $ArgumentList
}
$sqlSetupProcess = Start-Process @startProcessParameters -PassThru -NoNewWindow -ErrorAction Stop
Write-Verbose -Message ($script:localizedData.StartSetupProcess -f $sqlSetupProcess.Id, $startProcessParameters.FilePath, $Timeout) -Verbose
Wait-Process -InputObject $sqlSetupProcess -Timeout $Timeout -ErrorAction Stop
return $sqlSetupProcess.ExitCode
}
<#
.SYNOPSIS
Connect to a SQL Server Database Engine and return the server object.
.PARAMETER ServerName
String containing the host name of the SQL Server to connect to.
Default value is the current computer name.
.PARAMETER InstanceName
String containing the SQL Server Database Engine instance to connect to.
Default value is 'MSSQLSERVER'.
.PARAMETER SetupCredential
The credentials to use to impersonate a user when connecting to the
SQL Server Database Engine instance. If this parameter is left out, then
the current user will be used to connect to the SQL Server Database Engine
instance using Windows Integrated authentication.
.PARAMETER LoginType
Specifies which type of logon credential should be used. The valid types
are 'WindowsUser' or 'SqlLogin'. Default value is 'WindowsUser'
If set to 'WindowsUser' then the it will impersonate using the Windows
login specified in the parameter SetupCredential.
If set to 'WindowsUser' then the it will impersonate using the native SQL
login specified in the parameter SetupCredential.
.PARAMETER StatementTimeout
Set the query StatementTimeout in seconds. Default 600 seconds (10 minutes).
.EXAMPLE
Connect-SQL
Connects to the default instance on the local server.
.EXAMPLE
Connect-SQL -InstanceName 'MyInstance'
Connects to the instance 'MyInstance' on the local server.
.EXAMPLE
Connect-SQL ServerName 'sql.company.local' -InstanceName 'MyInstance'
Connects to the instance 'MyInstance' on the server 'sql.company.local'.
#>
function Connect-SQL
{
[CmdletBinding(DefaultParameterSetName = 'SqlServer')]
param
(
[Parameter(ParameterSetName = 'SqlServer')]
[Parameter(ParameterSetName = 'SqlServerWithCredential')]
[ValidateNotNull()]
[System.String]
$ServerName = (Get-ComputerName),
[Parameter(ParameterSetName = 'SqlServer')]
[Parameter(ParameterSetName = 'SqlServerWithCredential')]
[ValidateNotNull()]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter(ParameterSetName = 'SqlServerWithCredential', Mandatory = $true)]
[ValidateNotNull()]
[Alias('DatabaseCredential')]
[System.Management.Automation.PSCredential]
$SetupCredential,
[Parameter(ParameterSetName = 'SqlServerWithCredential')]
[ValidateSet('WindowsUser', 'SqlLogin')]
[System.String]
$LoginType = 'WindowsUser',
[Parameter()]
[ValidateNotNull()]
[System.Int32]
$StatementTimeout = 600
)
Import-SQLPSModule
if ($InstanceName -eq 'MSSQLSERVER')
{
$databaseEngineInstance = $ServerName
}
else
{
$databaseEngineInstance = '{0}\{1}' -f $ServerName, $InstanceName
}
$sqlServerObject = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Server'
$sqlConnectionContext = $sqlServerObject.ConnectionContext
$sqlConnectionContext.ServerInstance = $databaseEngineInstance
$sqlConnectionContext.StatementTimeout = $StatementTimeout
$sqlConnectionContext.ApplicationName = 'SqlServerDsc'
if ($PSCmdlet.ParameterSetName -eq 'SqlServer')
{
<#
This is only used for verbose messaging and not for the connection
string since this is using Integrated Security=true (SSPI).
#>
$connectUserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Verbose -Message (
$script:localizedData.ConnectingUsingIntegrated -f $connectUsername
) -Verbose
}
else
{
$connectUserName = $SetupCredential.UserName
Write-Verbose -Message (
$script:localizedData.ConnectingUsingImpersonation -f $connectUsername, $LoginType
) -Verbose
if ($LoginType -eq 'SqlLogin')
{
$sqlConnectionContext.LoginSecure = $false
$sqlConnectionContext.Login = $connectUserName
$sqlConnectionContext.SecurePassword = $SetupCredential.Password
}
if ($LoginType -eq 'WindowsUser')
{
$sqlConnectionContext.LoginSecure = $true
$sqlConnectionContext.ConnectAsUser = $true
$sqlConnectionContext.ConnectAsUserName = $connectUserName
$sqlConnectionContext.ConnectAsUserPassword = $SetupCredential.GetNetworkCredential().Password
}
}
try
{
$sqlConnectionContext.Connect()
if ($sqlServerObject.Status -match '^Online$')
{
Write-Verbose -Message (
$script:localizedData.ConnectedToDatabaseEngineInstance -f $databaseEngineInstance
) -Verbose
return $sqlServerObject
}
else
{
throw
}
}
catch
{
$errorMessage = $script:localizedData.FailedToConnectToDatabaseEngineInstance -f $databaseEngineInstance
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
finally
{
<#
Connect will ensure we actually can connect, but we need to disconnect
from the session so we don't have anything hanging. If we need run a
method on the returned $sqlServerObject it will automatically open a
new session and then close, therefore we don't need to keep this
session open.
#>
$sqlConnectionContext.Disconnect()
}
}
<#
.SYNOPSIS
Connect to a SQL Server Analysis Service and return the server object.
.PARAMETER ServerName
String containing the host name of the SQL Server to connect to.
.PARAMETER InstanceName
String containing the SQL Server Analysis Service instance to connect to.
.PARAMETER SetupCredential
PSCredential object with the credentials to use to impersonate a user when
connecting. If this is not provided then the current user will be used to
connect to the SQL Server Analysis Service instance.
#>
function Connect-SQLAnalysis
{
[CmdletBinding()]
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$ServerName = (Get-ComputerName),
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$SetupCredential
)
$null = Import-Assembly -Name 'Microsoft.AnalysisServices' -LoadWithPartialName
if ($InstanceName -eq 'MSSQLSERVER')
{
$analysisServiceInstance = $ServerName
}
else
{
$analysisServiceInstance = "$ServerName\$InstanceName"
}
if ($SetupCredential)
{
$userName = $SetupCredential.UserName
$password = $SetupCredential.GetNetworkCredential().Password
$analysisServicesDataSource = "Data Source=$analysisServiceInstance;User ID=$userName;Password=$password"
}
else
{
$analysisServicesDataSource = "Data Source=$analysisServiceInstance"
}
try
{
$analysisServicesObject = New-Object -TypeName 'Microsoft.AnalysisServices.Server'
if ($analysisServicesObject)
{
$analysisServicesObject.Connect($analysisServicesDataSource)
}
else
{
$errorMessage = $script:localizedData.FailedToConnectToAnalysisServicesInstance -f $analysisServiceInstance
New-InvalidOperationException -Message $errorMessage
}
Write-Verbose -Message ($script:localizedData.ConnectedToAnalysisServicesInstance -f $analysisServiceInstance) -Verbose
}
catch
{
$errorMessage = $script:localizedData.FailedToConnectToAnalysisServicesInstance -f $analysisServiceInstance
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
return $analysisServicesObject
}
<#
.SYNOPSIS
Imports the assembly into the session.
.DESCRIPTION
Imports the assembly into the session and returns a reference to the
assembly.
.PARAMETER Name
Specifies the name of the assembly to load.
.PARAMETER LoadWithPartialName
Specifies if the imported assembly should be the first found in GAC,
regardless of version.
.OUTPUTS
[System.Reflection.Assembly]
Returns a reference to the assembly object.
.EXAMPLE
Import-Assembly -Name "Microsoft.SqlServer.ConnectionInfo, Version=$SqlMajorVersion.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
.EXAMPLE
Import-Assembly -Name 'Microsoft.AnalysisServices' -LoadWithPartialName
.NOTES
This should normally work using Import-Module and New-Object instead of
using the method [System.Reflection.Assembly]::Load(). But due to a
missing assembly in the module SqlServer this is still needed.
Import-Module SqlServer
$connectionInfo = New-Object -TypeName 'Microsoft.SqlServer.Management.Common.ServerConnection' -ArgumentList @('testclu01a\SQL2014')
# Missing assembly 'Microsoft.SqlServer.Rmo' in module SqlServer prevents this call from working.
$replication = New-Object -TypeName 'Microsoft.SqlServer.Replication.ReplicationServer' -ArgumentList @($connectionInfo)
#>
function Import-Assembly
{
[CmdletBinding()]
[OutputType([System.Reflection.Assembly])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Name,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$LoadWithPartialName
)
try
{
if ($LoadWithPartialName.IsPresent)
{
$assemblyInformation = [System.Reflection.Assembly]::LoadWithPartialName($Name)
}
else
{
$assemblyInformation = [System.Reflection.Assembly]::Load($Name)
}
Write-Verbose -Message (
$script:localizedData.LoadedAssembly -f $assemblyInformation.FullName
)
}
catch
{
$errorMessage = $script:localizedData.FailedToLoadAssembly -f $Name
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
return $assemblyInformation
}
<#
.SYNOPSIS
Returns the major SQL version for the specific instance.
.PARAMETER InstanceName
String containing the name of the SQL instance to be configured. Default
value is 'MSSQLSERVER'.
.OUTPUTS
System.UInt16. Returns the SQL Server major version number.
#>
function Get-SqlInstanceMajorVersion
{
[CmdletBinding()]
[OutputType([System.UInt16])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$InstanceName
)
$sqlInstanceId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$InstanceName
$sqlVersion = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$sqlInstanceId\Setup").Version
if (-not $sqlVersion)
{
$errorMessage = $script:localizedData.SqlServerVersionIsInvalid -f $InstanceName
New-InvalidResultException -Message $errorMessage
}
[System.UInt16] $sqlMajorVersionNumber = $sqlVersion.Split('.')[0]
return $sqlMajorVersionNumber
}
<#
.SYNOPSIS
Imports the module SQLPS in a standardized way.
.PARAMETER Force
Forces the removal of the previous SQL module, to load the same or newer
version fresh. This is meant to make sure the newest version is used, with
the latest assemblies.
#>
function Import-SQLPSModule
{
[CmdletBinding()]
param
(
[Parameter()]
[System.Management.Automation.SwitchParameter]
$Force
)
if ($Force.IsPresent)
{
Write-Verbose -Message $script:localizedData.ModuleForceRemoval -Verbose
Remove-Module -Name @('SqlServer', 'SQLPS', 'SQLASCmdlets') -Force -ErrorAction SilentlyContinue
}
<#
Check if either of the modules are already loaded into the session.
Prefer to use the first one (in order found).
NOTE: There should actually only be either SqlServer or SQLPS loaded,
otherwise there can be problems with wrong assemblies being loaded.
#>
$loadedModuleName = (Get-Module -Name @('SqlServer', 'SQLPS') | Select-Object -First 1).Name
if ($loadedModuleName)
{
Write-Verbose -Message ($script:localizedData.PowerShellModuleAlreadyImported -f $loadedModuleName) -Verbose
return
}
$availableModuleName = $null
# Get the newest SqlServer module if more than one exist
$availableModule = Get-Module -FullyQualifiedName 'SqlServer' -ListAvailable |
Sort-Object -Property 'Version' -Descending |
Select-Object -First 1 -Property Name, Path, Version
if ($availableModule)
{
$availableModuleName = $availableModule.Name
Write-Verbose -Message ($script:localizedData.PreferredModuleFound) -Verbose
}
else
{
Write-Verbose -Message ($script:localizedData.PreferredModuleNotFound) -Verbose
<#
After installing SQL Server the current PowerShell session doesn't know about the new path
that was added for the SQLPS module.
This reloads PowerShell session environment variable PSModulePath to make sure it contains
all paths.
#>
Set-PSModulePath -Path ([System.Environment]::GetEnvironmentVariable('PSModulePath', 'Machine'))
<#
Get the newest SQLPS module if more than one exist.
#>
$availableModule = Get-Module -FullyQualifiedName 'SQLPS' -ListAvailable |
Select-Object -Property Name, Path, @{
Name = 'Version'
Expression = {
# Parse the build version number '120', '130' from the Path.
(Select-String -InputObject $_.Path -Pattern '\\([0-9]{3})\\' -List).Matches.Groups[1].Value
}
} |
Sort-Object -Property 'Version' -Descending |
Select-Object -First 1
if ($availableModule)
{
# This sets $availableModuleName to the Path of the module to be loaded.
$availableModuleName = Split-Path -Path $availableModule.Path -Parent
}
}
if ($availableModuleName)
{
try
{
Write-Debug -Message ($script:localizedData.DebugMessagePushingLocation)
Push-Location
<#
SQLPS has unapproved verbs, disable checking to ignore Warnings.
Suppressing verbose so all cmdlet is not listed.
#>
$importedModule = Import-Module -Name $availableModuleName -DisableNameChecking -Verbose:$false -Force:$Force -PassThru -ErrorAction Stop
<#
SQLPS returns two entries, one with module type 'Script' and another with module type 'Manifest'.
Only return the object with module type 'Manifest'.
SqlServer only returns one object (of module type 'Script'), so no need to do anything for SqlServer module.
#>
if ($availableModuleName -ne 'SqlServer')
{
$importedModule = $importedModule | Where-Object -Property 'ModuleType' -EQ -Value 'Manifest'
}
Write-Verbose -Message ($script:localizedData.ImportedPowerShellModule -f $importedModule.Name, $importedModule.Version, $importedModule.Path) -Verbose
}
catch
{
$errorMessage = $script:localizedData.FailedToImportPowerShellSqlModule -f $availableModuleName
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
finally
{
Write-Debug -Message ($script:localizedData.DebugMessagePoppingLocation)
Pop-Location
}
}
else
{
$errorMessage = $script:localizedData.PowerShellSqlModuleNotFound
New-InvalidOperationException -Message $errorMessage
}
}
<#
.SYNOPSIS
Restarts a SQL Server instance and associated services
.PARAMETER ServerName
Hostname of the SQL Server to be configured
.PARAMETER InstanceName
Name of the SQL instance to be configured. Default is 'MSSQLSERVER'
.PARAMETER Timeout
Timeout value for restarting the SQL services. The default value is 120 seconds.
.PARAMETER SkipClusterCheck
If cluster check should be skipped. If this is present no connection
is made to the instance to check if the instance is on a cluster.
This need to be used for some resource, for example for the SqlServerNetwork
resource when it's used to enable a disable protocol.
.PARAMETER SkipWaitForOnline
If this is present no connection is made to the instance to check if the
instance is online.
This need to be used for some resource, for example for the SqlServerNetwork
resource when it's used to disable protocol.
.PARAMETER OwnerNode
Specifies a list of owner nodes names of a cluster groups. If the SQL Server
instance is a Failover Cluster instance then the cluster group will only
be taken offline and back online when the owner of the cluster group is
one of the nodes specified in this list. These node names specified in this
parameter must match the Owner property of the cluster resource, for example
@('sqltest10', 'SQLTEST11'). The names are case-insensitive.
If this parameter is not specified the cluster group will be taken offline
and back online regardless of owner.
.EXAMPLE
Restart-SqlService -ServerName localhost
.EXAMPLE
Restart-SqlService -ServerName localhost -InstanceName 'NamedInstance'
.EXAMPLE
Restart-SqlService -ServerName localhost -InstanceName 'NamedInstance' -SkipClusterCheck -SkipWaitForOnline
.EXAMPLE
Restart-SqlService -ServerName CLU01 -Timeout 300
.EXAMPLE
Restart-SqlService -ServerName CLU01 -Timeout 300 -OwnerNode 'testclu10'
#>
function Restart-SqlService
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$ServerName,
[Parameter()]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter()]
[System.UInt32]
$Timeout = 120,
[Parameter()]
[Switch]
$SkipClusterCheck,
[Parameter()]
[Switch]
$SkipWaitForOnline,
[Parameter()]
[System.String[]]
$OwnerNode
)
$restartWindowsService = $true
# Check if a cluster, otherwise assume that a Windows service should be restarted.
if (-not $SkipClusterCheck.IsPresent)
{
## Connect to the instance
$serverObject = Connect-SQL -ServerName $ServerName -InstanceName $InstanceName
if ($serverObject.IsClustered)
{
# Make sure Windows service is not restarted outside of the cluster.
$restartWindowsService = $false
$restartSqlClusterServiceParameters = @{
InstanceName = $serverObject.ServiceName
}
if ($PSBoundParameters.ContainsKey('Timeout'))
{
$restartSqlClusterServiceParameters['Timeout'] = $Timeout
}
if ($PSBoundParameters.ContainsKey('OwnerNode'))
{
$restartSqlClusterServiceParameters['OwnerNode'] = $OwnerNode
}
Restart-SqlClusterService @restartSqlClusterServiceParameters
}
}
if ($restartWindowsService)
{
if ($InstanceName -eq 'MSSQLSERVER')
{
$serviceName = 'MSSQLSERVER'
}
else
{
$serviceName = 'MSSQL${0}' -f $InstanceName
}
Write-Verbose -Message ($script:localizedData.GetServiceInformation -f 'SQL Server') -Verbose
$sqlService = Get-Service -Name $serviceName
<#
Get all dependent services that are running.
There are scenarios where an automatic service is stopped and should not be restarted automatically.
#>
$agentService = $sqlService.DependentServices |
Where-Object -FilterScript { $_.Status -eq 'Running' }
# Restart the SQL Server service
Write-Verbose -Message ($script:localizedData.RestartService -f 'SQL Server') -Verbose
$sqlService |
Restart-Service -Force
# Start dependent services
$agentService |
ForEach-Object -Process {
Write-Verbose -Message ($script:localizedData.StartingDependentService -f $_.DisplayName) -Verbose
$_ | Start-Service
}
}
Write-Verbose -Message ($script:localizedData.WaitingInstanceTimeout -f $ServerName, $InstanceName, $Timeout) -Verbose
if (-not $SkipWaitForOnline.IsPresent)
{
$connectTimer = [System.Diagnostics.StopWatch]::StartNew()
do
{
# This call, if it fails, will take between ~9-10 seconds to return.
$testConnectionServerObject = Connect-SQL -ServerName $ServerName -InstanceName $InstanceName -ErrorAction 'SilentlyContinue'
# Make sure we have an SMO object to test Status
if ($testConnectionServerObject)
{
if ($testConnectionServerObject.Status -eq 'Online')
{
break
}
}
# Waiting 2 seconds to not hammer the SQL Server instance.
Start-Sleep -Seconds 2
} until ($connectTimer.Elapsed.Seconds -ge $Timeout)
$connectTimer.Stop()
# Was the timeout period reach before able to connect to the SQL Server instance?
if (-not $testConnectionServerObject -or $testConnectionServerObject.Status -ne 'Online')
{
$errorMessage = $script:localizedData.FailedToConnectToInstanceTimeout -f $ServerName, $InstanceName, $Timeout
New-InvalidOperationException -Message $errorMessage
}
}
}
<#
.SYNOPSIS
Restarts a SQL Server cluster instance and associated services
.PARAMETER InstanceName
Specifies the instance name that matches a SQL Server MSCluster_Resource
property <clustergroup>.PrivateProperties.InstanceName.
.PARAMETER Timeout
Timeout value for restarting the SQL services. The default value is 120 seconds.
.PARAMETER OwnerNode
Specifies a list of owner nodes names of a cluster groups. If the SQL Server
instance is a Failover Cluster instance then the cluster group will only
be taken offline and back online when the owner of the cluster group is
one of the nodes specified in this list. These node names specified in this
parameter must match the Owner property of the cluster resource, for example
@('sqltest10', 'SQLTEST11'). The names are case-insensitive.
If this parameter is not specified the cluster group will be taken offline
and back online regardless of owner.
#>
function Restart-SqlClusterService
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[Parameter()]
[System.UInt32]
$Timeout = 120,
[Parameter()]
[System.String[]]
$OwnerNode
)
# Get the cluster resources
Write-Verbose -Message ($script:localizedData.GetSqlServerClusterResources) -Verbose
$sqlService = Get-CimInstance -Namespace 'root/MSCluster' -ClassName 'MSCluster_Resource' -Filter "Type = 'SQL Server'" |
Where-Object -FilterScript {
$_.PrivateProperties.InstanceName -eq $InstanceName -and $_.State -eq 2
}
# If the cluster resource is found and online then continue.
if ($sqlService)
{
$isOwnerOfClusterResource = $true
if ($PSBoundParameters.ContainsKey('OwnerNode') -and $sqlService.OwnerNode -notin $OwnerNode)
{
$isOwnerOfClusterResource = $false
}
if ($isOwnerOfClusterResource)
{
Write-Verbose -Message ($script:localizedData.GetSqlAgentClusterResource) -Verbose
$agentService = $sqlService |
Get-CimAssociatedInstance -ResultClassName MSCluster_Resource |
Where-Object -FilterScript {
$_.Type -eq 'SQL Server Agent' -and $_.State -eq 2
}
# Build a listing of resources being acted upon
$resourceNames = @($sqlService.Name, ($agentService |
Select-Object -ExpandProperty Name)) -join "', '"
# Stop the SQL Server and dependent resources
Write-Verbose -Message ($script:localizedData.BringClusterResourcesOffline -f $resourceNames) -Verbose
$sqlService |
Invoke-CimMethod -MethodName TakeOffline -Arguments @{
Timeout = $Timeout
}
# Start the SQL server resource
Write-Verbose -Message ($script:localizedData.BringSqlServerClusterResourcesOnline) -Verbose
$sqlService |
Invoke-CimMethod -MethodName BringOnline -Arguments @{
Timeout = $Timeout
}
# Start the SQL Agent resource
if ($agentService)
{
if ($PSBoundParameters.ContainsKey('OwnerNode') -and $agentService.OwnerNode -notin $OwnerNode)
{
$isOwnerOfClusterResource = $false
}
if ($isOwnerOfClusterResource)
{
Write-Verbose -Message ($script:localizedData.BringSqlServerAgentClusterResourcesOnline) -Verbose
$agentService |
Invoke-CimMethod -MethodName BringOnline -Arguments @{
Timeout = $Timeout
}
}
else
{
Write-Verbose -Message (
$script:localizedData.NotOwnerOfClusterResource -f (Get-ComputerName), $agentService.Name, $agentService.OwnerNode
) -Verbose
}
}
}
else
{
Write-Verbose -Message (
$script:localizedData.NotOwnerOfClusterResource -f (Get-ComputerName), $sqlService.Name, $sqlService.OwnerNode
) -Verbose
}
}
else
{
Write-Warning -Message ($script:localizedData.ClusterResourceNotFoundOrOffline -f $InstanceName)
}
}
<#
.SYNOPSIS
Restarts a Reporting Services instance and associated services
.PARAMETER InstanceName
Name of the instance to be restarted. Default is 'MSSQLSERVER'
(the default instance).
.PARAMETER WaitTime
Number of seconds to wait between service stop and service start.
Default value is 0 seconds.
#>
function Restart-ReportingServicesService
{
[CmdletBinding()]
param
(
[Parameter()]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter()]
[System.UInt16]
$WaitTime = 0
)
if ($InstanceName -eq 'SSRS')
{
# Check if we're dealing with SSRS 2017
$ServiceName = 'SQLServerReportingServices'
Write-Verbose -Message ($script:localizedData.GetServiceInformation -f $ServiceName) -Verbose
$reportingServicesService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
}
if ($null -eq $reportingServicesService)
{
$ServiceName = 'ReportServer'
<#
Pre-2017 SSRS support multiple instances, check if we're dealing
with a named instance.
#>
if (-not ($InstanceName -eq 'MSSQLSERVER'))
{
$ServiceName += '${0}' -f $InstanceName
}
Write-Verbose -Message ($script:localizedData.GetServiceInformation -f $ServiceName) -Verbose
$reportingServicesService = Get-Service -Name $ServiceName
}
<#
Get all dependent services that are running.
There are scenarios where an automatic service is stopped and should
not be restarted automatically.
#>
$dependentService = $reportingServicesService.DependentServices | Where-Object -FilterScript {
$_.Status -eq 'Running'
}
Write-Verbose -Message ($script:localizedData.RestartService -f $reportingServicesService.DisplayName) -Verbose
Write-Verbose -Message ($script:localizedData.StoppingService -f $reportingServicesService.DisplayName) -Verbose
$reportingServicesService | Stop-Service -Force
if ($WaitTime -ne 0)
{
Write-Verbose -Message ($script:localizedData.WaitServiceRestart -f $WaitTime, $reportingServicesService.DisplayName) -Verbose
Start-Sleep -Seconds $WaitTime
}
Write-Verbose -Message ($script:localizedData.StartingService -f $reportingServicesService.DisplayName) -Verbose
$reportingServicesService | Start-Service
# Start dependent services
$dependentService | ForEach-Object -Process {
Write-Verbose -Message ($script:localizedData.StartingDependentService -f $_.DisplayName) -Verbose
$_ | Start-Service
}
}
<#
.SYNOPSIS
Executes a query on the specified database.
.PARAMETER ServerName
The hostname of the server that hosts the SQL instance.
.PARAMETER InstanceName
The name of the SQL instance that hosts the database.
.PARAMETER Database
Specify the name of the database to execute the query on.
.PARAMETER Query
The query string to execute.
.PARAMETER DatabaseCredential
PSCredential object with the credentials to use to impersonate a user
when connecting. If this is not provided then the current user will be
used to connect to the SQL Server Database Engine instance.
.PARAMETER LoginType
Specifies which type of logon credential should be used. The valid types are
Integrated, WindowsUser, and SqlLogin. If WindowsUser or SqlLogin are specified
then the SetupCredential needs to be specified as well.
.PARAMETER SqlServerObject
You can pass in an object type of 'Microsoft.SqlServer.Management.Smo.Server'.
This can also be passed in through the pipeline. See examples.
.PARAMETER WithResults
Specifies if the query should return results.
.PARAMETER StatementTimeout
Set the query StatementTimeout in seconds. Default 600 seconds (10mins).
.PARAMETER RedactText
One or more strings to redact from the query when verbose messages are
written to the console. Strings here will be escaped so they will not
be interpreted as regular expressions (RegEx).
.EXAMPLE
Invoke-Query -ServerName Server1 -InstanceName MSSQLSERVER -Database master `
-Query 'SELECT name FROM sys.databases' -WithResults
.EXAMPLE
Invoke-Query -ServerName Server1 -InstanceName MSSQLSERVER -Database master `
-Query 'RESTORE DATABASE [NorthWinds] WITH RECOVERY'
.EXAMPLE
Connect-SQL @sqlConnectionParameters | Invoke-Query -Database master `
-Query 'SELECT name FROM sys.databases' -WithResults
.EXAMPLE
Invoke-Query -SQLServer Server1 -SQLInstanceName MSSQLSERVER -Database MyDatabase `
-Query "select * from MyTable where password = 'Pa\ssw0rd1' and password = 'secret passphrase'" `
-WithResults -RedactText @('Pa\sSw0rd1','Secret PassPhrase') -Verbose
#>
function Invoke-Query
{
[CmdletBinding(DefaultParameterSetName = 'SqlServer')]
param
(
[Parameter(ParameterSetName = 'SqlServer')]
[ValidateNotNullOrEmpty()]
[System.String]
$ServerName = (Get-ComputerName),
[Parameter(ParameterSetName = 'SqlServer')]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter(Mandatory = $true)]
[System.String]
$Database,
[Parameter(Mandatory = $true)]
[System.String]
$Query,
[Parameter()]
[Alias('SetupCredential')]
[System.Management.Automation.PSCredential]
$DatabaseCredential,
[Parameter()]
[ValidateSet('Integrated', 'WindowsUser', 'SqlLogin')]
[System.String]
$LoginType = 'Integrated',
[Parameter(ValueFromPipeline, ParameterSetName = 'SqlObject', Mandatory = $true)]
[ValidateNotNull()]
[Microsoft.SqlServer.Management.Smo.Server]
$SqlServerObject,
[Parameter()]
[Switch]
$WithResults,
[Parameter()]
[ValidateNotNull()]
[System.Int32]
$StatementTimeout = 600,
[Parameter()]
[System.String[]]
$RedactText
)
if ($PSCmdlet.ParameterSetName -eq 'SqlObject')
{
$serverObject = $SqlServerObject
}
elseif ($PSCmdlet.ParameterSetName -eq 'SqlServer')
{
$connectSQLParameters = @{
ServerName = $ServerName
InstanceName = $InstanceName
StatementTimeout = $StatementTimeout
}
if ($LoginType -ne 'Integrated')
{
$connectSQLParameters['LoginType'] = $LoginType
}
if ($PSBoundParameters.ContainsKey('DatabaseCredential'))
{
$connectSQLParameters.SetupCredential = $DatabaseCredential
}
$serverObject = Connect-SQL @connectSQLParameters
}
$redactedQuery = $Query
foreach ($redactString in $RedactText)
{
<#
Escaping the string to handle strings which could look like
regular expressions, like passwords.
#>
$escapedRedactedString = [System.Text.RegularExpressions.Regex]::Escape($redactString)
$redactedQuery = $redactedQuery -ireplace $escapedRedactedString, '*******'
}
if ($WithResults)
{
try
{
Write-Verbose -Message (
$script:localizedData.ExecuteQueryWithResults -f $redactedQuery
) -Verbose
$result = $serverObject.Databases[$Database].ExecuteWithResults($Query)
}
catch
{
$errorMessage = $script:localizedData.ExecuteQueryWithResultsFailed -f $Database
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
}
else
{
try
{
Write-Verbose -Message (
$script:localizedData.ExecuteNonQuery -f $redactedQuery
) -Verbose
$serverObject.Databases[$Database].ExecuteNonQuery($Query)
}
catch
{
$errorMessage = $script:localizedData.ExecuteNonQueryFailed -f $Database
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
}
return $result
}
<#
.SYNOPSIS
Executes the alter method on an Availability Group Replica object.
.PARAMETER AvailabilityGroupReplica
The Availability Group Replica object that must be altered.
#>
function Update-AvailabilityGroupReplica
{
param
(
[Parameter(Mandatory = $true)]
[Microsoft.SqlServer.Management.Smo.AvailabilityReplica]
$AvailabilityGroupReplica
)
try
{
$originalErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
$AvailabilityGroupReplica.Alter()
}
catch
{
$errorMessage = $script:localizedData.AlterAvailabilityGroupReplicaFailed -f $AvailabilityGroupReplica.Name
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
finally
{
$ErrorActionPreference = $originalErrorActionPreference
}
}
<#
.SYNOPSIS
Impersonates a login and determines whether required permissions are present.
.PARAMETER ServerName
String containing the host name of the SQL Server to connect to.
.PARAMETER InstanceName
String containing the SQL Server Database Engine instance to connect to.
.PARAMETER LoginName
String containing the login (user) which should be checked for a permission.
.PARAMETER Permissions
This is a list that represents a SQL Server set of database permissions.
.PARAMETER SecurableClass
String containing the class of permissions to test. It can be:
SERVER: A permission that is applicable against server objects.
LOGIN: A permission that is applicable against login objects.
Default is 'SERVER'.
.PARAMETER SecurableName
String containing the name of the object against which permissions exist,
e.g. if SecurableClass is LOGIN this is the name of a login permissions
may exist against.
Default is $null.
.NOTES
These SecurableClass are not yet in this module yet and so are not implemented:
'APPLICATION ROLE', 'ASSEMBLY', 'ASYMMETRIC KEY', 'CERTIFICATE',
'CONTRACT', 'DATABASE', 'ENDPOINT', 'FULLTEXT CATALOG',
'MESSAGE TYPE', 'OBJECT', 'REMOTE SERVICE BINDING', 'ROLE',
'ROUTE', 'SCHEMA', 'SERVICE', 'SYMMETRIC KEY', 'TYPE', 'USER',
'XML SCHEMA COLLECTION'
#>
function Test-LoginEffectivePermissions
{
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ServerName,
[Parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$LoginName,
[Parameter(Mandatory = $true)]
[System.String[]]
$Permissions,
[Parameter()]
[ValidateSet('SERVER', 'LOGIN')]
[System.String]
$SecurableClass = 'SERVER',
[Parameter()]
[System.String]
$SecurableName
)
# Assume the permissions are not present
$permissionsPresent = $false
$invokeQueryParameters = @{
ServerName = $ServerName
InstanceName = $InstanceName
Database = 'master'
WithResults = $true
}
if ( [System.String]::IsNullOrEmpty($SecurableName) )
{
$queryToGetEffectivePermissionsForLogin = "
EXECUTE AS LOGIN = '$LoginName'
SELECT DISTINCT permission_name
FROM fn_my_permissions(null,'$SecurableClass')
REVERT
"
}
else
{
$queryToGetEffectivePermissionsForLogin = "
EXECUTE AS LOGIN = '$LoginName'
SELECT DISTINCT permission_name
FROM fn_my_permissions('$SecurableName','$SecurableClass')
REVERT
"
}
Write-Verbose -Message ($script:localizedData.GetEffectivePermissionForLogin -f $LoginName, $InstanceName) -Verbose
$loginEffectivePermissionsResult = Invoke-Query @invokeQueryParameters -Query $queryToGetEffectivePermissionsForLogin
$loginEffectivePermissions = $loginEffectivePermissionsResult.Tables.Rows.permission_name
if ( $null -ne $loginEffectivePermissions )
{
$loginMissingPermissions = Compare-Object -ReferenceObject $Permissions -DifferenceObject $loginEffectivePermissions |
Where-Object -FilterScript { $_.SideIndicator -ne '=>' } |
Select-Object -ExpandProperty InputObject
if ( $loginMissingPermissions.Count -eq 0 )
{
$permissionsPresent = $true
}
}
return $permissionsPresent
}
<#
.SYNOPSIS
Determine if the seeding mode of the specified availability group is automatic.
.PARAMETER ServerName
The hostname of the server that hosts the SQL instance.
.PARAMETER InstanceName
The name of the SQL instance that hosts the availability group.
.PARAMETER AvailabilityGroupName
The name of the availability group to check.
.PARAMETER AvailabilityReplicaName
The name of the availability replica to check.
#>
function Test-AvailabilityReplicaSeedingModeAutomatic
{
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ServerName,
[Parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$AvailabilityGroupName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$AvailabilityReplicaName
)
# Assume automatic seeding is disabled by default
$availabilityReplicaSeedingModeAutomatic = $false
$serverObject = Connect-SQL -ServerName $ServerName -InstanceName $InstanceName
# Only check the seeding mode if this is SQL 2016 or newer
if ( $serverObject.Version -ge 13 )
{
$invokeQueryParams = @{
ServerName = $ServerName
InstanceName = $InstanceName
Database = 'master'
WithResults = $true
}
$queryToGetSeedingMode = "
SELECT seeding_mode_desc
FROM sys.availability_replicas ar
INNER JOIN sys.availability_groups ag ON ar.group_id = ag.group_id
WHERE ag.name = '$AvailabilityGroupName'
AND ar.replica_server_name = '$AvailabilityReplicaName'
"
$seedingModeResults = Invoke-Query @invokeQueryParams -Query $queryToGetSeedingMode
$seedingMode = $seedingModeResults.Tables.Rows.seeding_mode_desc
if ( $seedingMode -eq 'Automatic' )
{
$availabilityReplicaSeedingModeAutomatic = $true
}
}
return $availabilityReplicaSeedingModeAutomatic
}
<#
.SYNOPSIS
Get the server object of the primary replica of the specified availability group.
.PARAMETER ServerObject
The current server object connection.
.PARAMETER AvailabilityGroup
The availability group object used to find the primary replica server name.
#>
function Get-PrimaryReplicaServerObject
{
param
(
[Parameter(Mandatory = $true)]
[Microsoft.SqlServer.Management.Smo.Server]
$ServerObject,
[Parameter(Mandatory = $true)]
[Microsoft.SqlServer.Management.Smo.AvailabilityGroup]
$AvailabilityGroup
)
$primaryReplicaServerObject = $serverObject
# Determine if we're connected to the primary replica
if ( ( $AvailabilityGroup.PrimaryReplicaServerName -ne $serverObject.DomainInstanceName ) -and ( -not [System.String]::IsNullOrEmpty($AvailabilityGroup.PrimaryReplicaServerName) ) )
{
$primaryReplicaServerObject = Connect-SQL -ServerName $AvailabilityGroup.PrimaryReplicaServerName
}
return $primaryReplicaServerObject
}
<#
.SYNOPSIS
Determine if the current login has impersonate permissions
.PARAMETER ServerObject
The server object on which to perform the test.
.PARAMETER SecurableName
If set then impersonate permission on this specific securable (e.g. login) is also checked.
#>
function Test-ImpersonatePermissions
{
param
(
[Parameter(Mandatory = $true)]
[Microsoft.SqlServer.Management.Smo.Server]
$ServerObject,
[Parameter()]
[System.String]
$SecurableName
)
# The impersonate any login permission only exists in SQL 2014 and above
$testLoginEffectivePermissionsParams = @{
ServerName = $ServerObject.ComputerNamePhysicalNetBIOS
InstanceName = $ServerObject.ServiceName
LoginName = $ServerObject.ConnectionContext.TrueLogin
Permissions = @('IMPERSONATE ANY LOGIN')
}
$impersonatePermissionsPresent = Test-LoginEffectivePermissions @testLoginEffectivePermissionsParams
if ($impersonatePermissionsPresent)
{
Write-Verbose -Message ( 'The login "{0}" has impersonate any login permissions on the instance "{1}\{2}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.SInstanceName ) -Verbose
return $impersonatePermissionsPresent
}
else
{
Write-Verbose -Message ( 'The login "{0}" does not have impersonate any login permissions on the instance "{1}\{2}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName ) -Verbose
}
# Check for sysadmin / control server permission which allows impersonation
$testLoginEffectivePermissionsParams = @{
ServerName = $ServerObject.ComputerNamePhysicalNetBIOS
InstanceName = $ServerObject.ServiceName
LoginName = $ServerObject.ConnectionContext.TrueLogin
Permissions = @('CONTROL SERVER')
}
$impersonatePermissionsPresent = Test-LoginEffectivePermissions @testLoginEffectivePermissionsParams
if ($impersonatePermissionsPresent)
{
Write-Verbose -Message ( 'The login "{0}" has control server permissions on the instance "{1}\{2}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName ) -Verbose
return $impersonatePermissionsPresent
}
else
{
Write-Verbose -Message ( 'The login "{0}" does not have control server permissions on the instance "{1}\{2}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName ) -Verbose
}
if (-not [System.String]::IsNullOrEmpty($SecurableName))
{
# Check for login-specific impersonation permissions
$testLoginEffectivePermissionsParams = @{
ServerName = $ServerObject.ComputerNamePhysicalNetBIOS
InstanceName = $ServerObject.ServiceName
LoginName = $ServerObject.ConnectionContext.TrueLogin
Permissions = @('IMPERSONATE')
SecurableClass = 'LOGIN'
SecurableName = $SecurableName
}
$impersonatePermissionsPresent = Test-LoginEffectivePermissions @testLoginEffectivePermissionsParams
if ($impersonatePermissionsPresent)
{
Write-Verbose -Message ( 'The login "{0}" has impersonate permissions on the instance "{1}\{2}" for the login "{3}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName, $SecurableName ) -Verbose
return $impersonatePermissionsPresent
}
else
{
Write-Verbose -Message ( 'The login "{0}" does not have impersonate permissions on the instance "{1}\{2}" for the login "{3}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName, $SecurableName ) -Verbose
}
# Check for login-specific control permissions
$testLoginEffectivePermissionsParams = @{
ServerName = $ServerObject.ComputerNamePhysicalNetBIOS
InstanceName = $ServerObject.ServiceName
LoginName = $ServerObject.ConnectionContext.TrueLogin
Permissions = @('CONTROL')
SecurableClass = 'LOGIN'
SecurableName = $SecurableName
}
$impersonatePermissionsPresent = Test-LoginEffectivePermissions @testLoginEffectivePermissionsParams
if ($impersonatePermissionsPresent)
{
Write-Verbose -Message ( 'The login "{0}" has control permissions on the instance "{1}\{2}" for the login "{3}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName, $SecurableName ) -Verbose
return $impersonatePermissionsPresent
}
else
{
Write-Verbose -Message ( 'The login "{0}" does not have control permissions on the instance "{1}\{2}" for the login "{3}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName, $SecurableName ) -Verbose
}
}
Write-Verbose -Message ( 'The login "{0}" does not have any impersonate permissions required on the instance "{1}\{2}".' -f $testLoginEffectivePermissionsParams.LoginName, $testLoginEffectivePermissionsParams.ServerName, $testLoginEffectivePermissionsParams.InstanceName ) -Verbose
return $impersonatePermissionsPresent
}
<#
.SYNOPSIS
Takes a SQL Instance name in the format of 'Server\Instance' and splits
it into a hash table prepared to be passed into Connect-SQL.
.PARAMETER FullSqlInstanceName
The full SQL instance name string to be split.
.OUTPUTS
Hash table with the properties ServerName and InstanceName.
#>
function Split-FullSqlInstanceName
{
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$FullSqlInstanceName
)
$sqlServer, $sqlInstanceName = $FullSqlInstanceName.Split('\')
if ( [System.String]::IsNullOrEmpty($sqlInstanceName) )
{
$sqlInstanceName = 'MSSQLSERVER'
}
return @{
ServerName = $sqlServer
InstanceName = $sqlInstanceName
}
}
<#
.SYNOPSIS
Determine if the cluster has the required permissions to the supplied server.
.PARAMETER ServerObject
The server object on which to perform the test.
#>
function Test-ClusterPermissions
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
[Parameter(Mandatory = $true)]
[Microsoft.SqlServer.Management.Smo.Server]
$ServerObject
)
$clusterServiceName = 'NT SERVICE\ClusSvc'
$ntAuthoritySystemName = 'NT AUTHORITY\SYSTEM'
$availabilityGroupManagementPerms = @('Connect SQL', 'Alter Any Availability Group', 'View Server State')
$clusterPermissionsPresent = $false
# Retrieve the SQL Server and Instance name from the server object
$sqlServer = $ServerObject.NetName
$sqlInstanceName = $ServerObject.ServiceName
foreach ( $loginName in @( $clusterServiceName, $ntAuthoritySystemName ) )
{
if ( $ServerObject.Logins[$loginName] -and -not $clusterPermissionsPresent )
{
$testLoginEffectivePermissionsParams = @{
ServerName = $sqlServer
InstanceName = $sqlInstanceName
LoginName = $loginName
Permissions = $availabilityGroupManagementPerms
}
$clusterPermissionsPresent = Test-LoginEffectivePermissions @testLoginEffectivePermissionsParams
if ( -not $clusterPermissionsPresent )
{
switch ( $loginName )
{
$clusterServiceName
{
Write-Verbose -Message ( $script:localizedData.ClusterLoginMissingRecommendedPermissions -f $loginName, ( $availabilityGroupManagementPerms -join ', ' ) ) -Verbose
}
$ntAuthoritySystemName
{
Write-Verbose -Message ( $script:localizedData.ClusterLoginMissingPermissions -f $loginName, ( $availabilityGroupManagementPerms -join ', ' ) ) -Verbose
}
}
}
else
{
Write-Verbose -Message ( $script:localizedData.ClusterLoginPermissionsPresent -f $loginName ) -Verbose
}
}
elseif ( -not $clusterPermissionsPresent )
{
switch ( $loginName )
{
$clusterServiceName
{
Write-Verbose -Message ($script:localizedData.ClusterLoginMissingRecommendedPermissions -f $loginName, "Trying with '$ntAuthoritySystemName'.") -Verbose
}
$ntAuthoritySystemName
{
Write-Verbose -Message ( $script:localizedData.ClusterLoginMissing -f $loginName, '' ) -Verbose
}
}
}
}
# If neither 'NT SERVICE\ClusSvc' or 'NT AUTHORITY\SYSTEM' have the required permissions, throw an error.
if ( -not $clusterPermissionsPresent )
{
throw ($script:localizedData.ClusterPermissionsMissing -f $sqlServer, $sqlInstanceName )
}
return $clusterPermissionsPresent
}
<#
.SYNOPSIS
Determine if the current node is hosting the instance.
.PARAMETER ServerObject
The server object on which to perform the test.
#>
function Test-ActiveNode
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
[Parameter(Mandatory = $true)]
[Microsoft.SqlServer.Management.Smo.Server]
$ServerObject
)
$result = $false
# Determine if this is a failover cluster instance (FCI)
if ( $ServerObject.IsMemberOfWsfcCluster )
{
<#
If the current node name is the same as the name the instances is
running on, then this is the active node
#>
$result = $ServerObject.ComputerNamePhysicalNetBIOS -eq (Get-ComputerName)
}
else
{
<#
This is a standalone instance, therefore the node will always host
the instance.
#>
$result = $true
}
return $result
}
<#
.SYNOPSIS
Execute an SQL script located in a file on disk.
.PARAMETER ServerInstance
The name of an instance of the Database Engine.
For default instances, only specify the computer name. For named instances,
use the format ComputerName\InstanceName.
.PARAMETER InputFile
Path to SQL script file that will be executed.
.PARAMETER Query
The full query that will be executed.
.PARAMETER Credential
The credentials to use to authenticate using SQL Authentication. To
authenticate using Windows Authentication, assign the credentials
to the built-in parameter 'PsDscRunAsCredential'. If both parameters
'Credential' and 'PsDscRunAsCredential' are not assigned, then the
SYSTEM account will be used to authenticate using Windows Authentication.
.PARAMETER QueryTimeout
Specifies, as an integer, the number of seconds after which the T-SQL
script execution will time out. In some SQL Server versions there is a
bug in Invoke-Sqlcmd where the normal default value 0 (no timeout) is not
respected and the default value is incorrectly set to 30 seconds.
.PARAMETER Variable
Creates a Invoke-Sqlcmd scripting variable for use in the Invoke-Sqlcmd
script, and sets a value for the variable.
.PARAMETER DisableVariables
Specifies, as a boolean, whether or not PowerShell will ignore sqlcmd
scripting variables that share a format such as $(variable_name). For more
information how to use this, please go to the help documentation for
[Invoke-Sqlcmd](https://docs.microsoft.com/en-us/powershell/module/sqlserver/Invoke-Sqlcmd).
#>
function Invoke-SqlScript
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$ServerInstance,
[Parameter(ParameterSetName = 'File', Mandatory = $true)]
[System.String]
$InputFile,
[Parameter(ParameterSetName = 'Query', Mandatory = $true)]
[System.String]
$Query,
[Parameter()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential,
[Parameter()]
[System.UInt32]
$QueryTimeout,
[Parameter()]
[System.String[]]
$Variable,
[Parameter()]
[System.Boolean]
$DisableVariables
)
Import-SQLPSModule
if ($PSCmdlet.ParameterSetName -eq 'File')
{
$null = $PSBoundParameters.Remove('Query')
}
elseif ($PSCmdlet.ParameterSetName -eq 'Query')
{
$null = $PSBoundParameters.Remove('InputFile')
}
if ($null -ne $Credential)
{
$null = $PSBoundParameters.Add('Username', $Credential.UserName)
$null = $PSBoundParameters.Add('Password', $Credential.GetNetworkCredential().Password)
}
$null = $PSBoundParameters.Remove('Credential')
Invoke-SqlCmd @PSBoundParameters
}
<#
.SYNOPSIS
Builds service account parameters for service account.
.PARAMETER ServiceAccount
Credential for the service account.
#>
function Get-ServiceAccount
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$ServiceAccount
)
$accountParameters = @{ }
switch -Regex ($ServiceAccount.UserName.ToUpper())
{
'^(?:NT ?AUTHORITY\\)?(SYSTEM|LOCALSERVICE|LOCAL SERVICE|NETWORKSERVICE|NETWORK SERVICE)$'
{
$accountParameters = @{
"UserName" = "NT AUTHORITY\$($Matches[1])"
}
}
'^(?:NT SERVICE\\)(.*)$'
{
$accountParameters = @{
"UserName" = "NT SERVICE\$($Matches[1])"
}
}
# Testing if account is a Managed Service Account, which ends with '$'.
'\$$'
{
$accountParameters = @{
"UserName" = $ServiceAccount.UserName
}
}
# Normal local or domain service account.
default
{
$accountParameters = @{
"UserName" = $ServiceAccount.UserName
"Password" = $ServiceAccount.GetNetworkCredential().Password
}
}
}
return $accountParameters
}
<#
.SYNOPSIS
Recursively searches Exception stack for specific error number.
.PARAMETER ExceptionToSearch
The Exception object to test
.PARAMETER ErrorNumber
The specific error number to look for
.NOTES
This function allows us to more easily write mocks.
#>
function Find-ExceptionByNumber
{
# Define parameters
param
(
[Parameter(Mandatory = $true)]
[System.Exception]
$ExceptionToSearch,
[Parameter(Mandatory = $true)]
[System.String]
$ErrorNumber
)
# Define working variables
$errorFound = $false
# Check to see if the exception has an inner exception
if ($ExceptionToSearch.InnerException)
{
# Assign found to the returned recursive call
$errorFound = Find-ExceptionByNumber -ExceptionToSearch $ExceptionToSearch.InnerException -ErrorNumber $ErrorNumber
}
# Check to see if it was found
if (!$errorFound)
{
# Check this exceptions message
$errorFound = $ExceptionToSearch.Number -eq $ErrorNumber
}
# Return
return $errorFound
}
<#
.SYNOPSIS
Get static name properties of he specified protocol.
.PARAMETER ProtocolName
Specifies the name of network protocol to return name properties for.
Possible values are 'TcpIp', 'NamedPipes', or 'ShareMemory'.
.NOTES
The static values returned matches the values returned by the class
ServerProtocol. The property DisplayName could potentially be localized
while the property Name must be exactly like it is returned by the
class ServerProtocol, with the correct casing.
#>
function Get-ProtocolNameProperties
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
[Parameter(Mandatory = $true)]
[ValidateSet('TcpIp', 'NamedPipes', 'SharedMemory')]
[System.String]
$ProtocolName
)
$protocolNameProperties = @{ }
switch ($ProtocolName)
{
'TcpIp'
{
$protocolNameProperties.DisplayName = 'TCP/IP'
$protocolNameProperties.Name = 'Tcp'
}
'NamedPipes'
{
$protocolNameProperties.DisplayName = 'Named Pipes'
$protocolNameProperties.Name = 'Np'
}
'SharedMemory'
{
$protocolNameProperties.DisplayName = 'Shared Memory'
$protocolNameProperties.Name = 'Sm'
}
}
return $protocolNameProperties
}
<#
.SYNOPSIS
Returns the ServerProtocol object for the specified SQL Server instance
and protocol name.
.PARAMETER InstanceName
Specifies the name of the SQL Server instance to connect to.
.PARAMETER ProtocolName
Specifies the name of network protocol to be configured. Possible values
are 'TcpIp', 'NamedPipes', or 'ShareMemory'.
.PARAMETER ServerName
Specifies the host name of the SQL Server to connect to.
.NOTES
The class Microsoft.SqlServer.Management.Smo.Wmi.ServerProtocol is
returned by this function.
#>
function Get-ServerProtocolObject
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[Parameter(Mandatory = $true)]
[ValidateSet('TcpIp', 'NamedPipes', 'SharedMemory')]
[System.String]
$ProtocolName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ServerName
)
$serverProtocolProperties = $null
$newObjectParameters = @{
TypeName = 'Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer'
ArgumentList = @($ServerName)
}
$managedComputerObject = New-Object @newObjectParameters
$serverInstance = $managedComputerObject.ServerInstances[$InstanceName]
if ($serverInstance)
{
$protocolNameProperties = Get-ProtocolNameProperties -ProtocolName $ProtocolName
$serverProtocolProperties = $serverInstance.ServerProtocols[$protocolNameProperties.Name]
}
else
{
$errorMessage = $script:localizedData.FailedToObtainServerInstance -f $InstanceName, $ServerName
New-InvalidOperationException -Message $errorMessage
}
return $serverProtocolProperties
}
<#
.SYNOPSIS
Converts the combination of server name and instance name to
the correct server instance name.
.PARAMETER InstanceName
Specifies the name of the SQL Server instance on the host.
.PARAMETER ServerName
Specifies the host name of the SQL Server.
#>
function ConvertTo-ServerInstanceName
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[Parameter(Mandatory = $true)]
[System.String]
$ServerName
)
if ($InstanceName -eq 'MSSQLSERVER')
{
$serverInstance = $ServerName
}
else
{
$serverInstance = '{0}\{1}' -f $ServerName, $InstanceName
}
return $serverInstance
}
<#
.SYNOPSIS
Returns the SQL Server major version from the setup.exe executable provided
in the Path parameter.
.PARAMETER Path
String containing the path to the SQL Server setup.exe executable.
#>
function Get-FilePathMajorVersion
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path
)
(Get-Item -Path $Path).VersionInfo.ProductVersion.Split('.')[0]
}
| 32.362464
| 317
| 0.625754
|
385fcd964d60f9456bd1cc82dab7cccd64013600
| 537
|
php
|
PHP
|
src/Wrappers/LaravelTraitNamespaceDetector.php
|
cerbero90/Workflow
|
4dcdb973c8b84838151480e3d9668f3e2cbbd453
|
[
"MIT"
] | 101
|
2015-02-02T08:22:14.000Z
|
2022-01-25T16:56:47.000Z
|
src/Wrappers/LaravelTraitNamespaceDetector.php
|
cerbero90/Workflow
|
4dcdb973c8b84838151480e3d9668f3e2cbbd453
|
[
"MIT"
] | 4
|
2015-05-17T18:16:10.000Z
|
2020-04-11T07:02:07.000Z
|
src/Wrappers/LaravelTraitNamespaceDetector.php
|
cerbero90/Workflow
|
4dcdb973c8b84838151480e3d9668f3e2cbbd453
|
[
"MIT"
] | 24
|
2015-02-22T13:55:07.000Z
|
2022-01-06T03:41:59.000Z
|
<?php namespace Cerbero\Workflow\Wrappers;
use Illuminate\Console\AppNamespaceDetectorTrait;
/**
* Detector that uses a Laravel trait to detect the namespace.
*
* @author Andrea Marco Sartori
*/
class LaravelTraitNamespaceDetector implements NamespaceDetectorInterface {
use AppNamespaceDetectorTrait;
/**
* Detect the namespace used by an application.
*
* @author Andrea Marco Sartori
* @return string
*/
public function detect()
{
$namespace = $this->getAppNamespace();
return rtrim($namespace, '\\');
}
}
| 19.178571
| 75
| 0.729981
|
4e0e62fba63ef954db92769006e5f13bbb07f943
| 2,220
|
kt
|
Kotlin
|
library/src/main/kotlin/dev/whyoleg/kamp/packager/DockerPackager.kt
|
whyoleg/mppm
|
ac9a1296d07b6db8eb2e196a4d62ba61c3ea57ad
|
[
"Apache-2.0"
] | 3
|
2019-08-31T23:47:46.000Z
|
2019-09-17T14:11:17.000Z
|
library/src/main/kotlin/dev/whyoleg/kamp/packager/DockerPackager.kt
|
whyoleg/mppm
|
ac9a1296d07b6db8eb2e196a4d62ba61c3ea57ad
|
[
"Apache-2.0"
] | 13
|
2019-06-08T12:06:10.000Z
|
2019-08-30T11:02:25.000Z
|
library/src/main/kotlin/dev/whyoleg/kamp/packager/DockerPackager.kt
|
whyoleg/mppm
|
ac9a1296d07b6db8eb2e196a4d62ba61c3ea57ad
|
[
"Apache-2.0"
] | 1
|
2019-08-31T23:47:51.000Z
|
2019-08-31T23:47:51.000Z
|
package dev.whyoleg.kamp.packager
import com.google.cloud.tools.jib.gradle.*
import dev.whyoleg.kamp.plugin.*
import dev.whyoleg.kamp.plugin.Plugin
import org.gradle.api.*
@Suppress("UnstableApiUsage")
class DockerPackager : Packager {
var baseImage: String? = null
var image: String? = null
var jdk: Int? = null
var tags: Set<String> = emptySet()
var ports: Set<String> = emptySet()
var versionTag: Boolean = true
var latestTag: Boolean = true
var className: String? = null
var jvmFlags: List<String> = emptyList()
var raw: JibExtension.() -> Unit = {}
// listOf(
// "-server",
// "-Djava.awt.headless=true",
// "-XX:+UnlockExperimentalVMOptions",
// "-XX:+UseG1GC",
// "-XX:MaxGCPauseMillis=100",
// "-XX:+UseStringDeduplication",
// "-Djava.library.path=\"/app/libs:\${PATH}\""
// )
override val plugins: Set<Plugin> = setOf(BuiltInPlugins.docker)
override fun Project.configure() {
val iName = path.replace(":", "-").drop(1)
val imageName = image ?: iName
val packageName = iName.replace("-", ".")
val mainClassName = className ?: "$group.$packageName.AppKt"
val dockerImage = baseImage ?: "adoptopenjdk/openjdk$jdk:alpine-slim"
extensions.configure<JibExtension>("jib") { jib ->
jib.apply {
from {
it.image = dockerImage
}
to {
it.image = imageName
val tags = mutableSetOf<String>()
tags += this@DockerPackager.tags
if (versionTag) tags += version.toString()
if (latestTag) tags += "latest"
it.tags = tags
}
container {
it.ports = ports.toList()
it.mainClass = mainClassName
it.useCurrentTimestamp = true
it.jvmFlags = jvmFlags
}
}
raw(jib)
}
}
}
| 35.238095
| 77
| 0.497748
|
c6aadd3eca0350ff0dfd9e2324d8c718d55e8082
| 5,472
|
py
|
Python
|
@shared-scripts/split_data.py
|
lukyjanek/universal-derivations
|
b95488df95033269999fa80f04404bc331c87946
|
[
"RSA-MD"
] | null | null | null |
@shared-scripts/split_data.py
|
lukyjanek/universal-derivations
|
b95488df95033269999fa80f04404bc331c87946
|
[
"RSA-MD"
] | null | null | null |
@shared-scripts/split_data.py
|
lukyjanek/universal-derivations
|
b95488df95033269999fa80f04404bc331c87946
|
[
"RSA-MD"
] | 2
|
2021-10-01T14:40:14.000Z
|
2021-10-03T14:44:31.000Z
|
#!/usr/bin/env python3
# coding: utf-8
"""Split annotation data to train, validation and holdout."""
import sys
import math
import random
import argparse
import networkx as nx
from collections import defaultdict
def split_data(relations, train=0.5, validation=0.25, holdout=0.25,
random_seed=None, stats=False):
"""Return dictionary of relations (parent, child) assigned T/V/H label."""
def generate_subsets(G):
# store relations
parents = defaultdict(list)
for edge in G.edges:
parents[edge[1]].append(edge[0])
# build and list components (in stable order)
components = list()
for component in nx.weakly_connected_components(G):
C = nx.DiGraph()
for node in component:
for parent in parents[node]:
C.add_edge(parent, node)
components.append(C)
fams = {sorted(f)[0]: f for f in components}
num_fams = len(list(fams))
# select families
H_keys = random.sample(sorted(fams), k=math.floor(num_fams*holdout))
H = [fams[k] for k in H_keys]
for item in H_keys:
del fams[item]
V_keys = random.sample(sorted(fams), k=math.floor(num_fams*validation))
V = [fams[k] for k in V_keys]
for item in V_keys:
del fams[item]
T = [fams[k] for k in fams if k not in H_keys and k not in V_keys]
return T, V, H
# set random seed if present
if random_seed:
random.seed(random_seed)
# control sum
if train + validation + holdout != 1:
print('ERROR: Sum of sizes for splitting data is not 1.')
return None
# build families
F = nx.DiGraph()
F.add_edges_from(relations)
# split on subsets, check proportion of relations included
# resample (allowed 1% difference from the given size of subsets)
TRAIN, VALIDATION, HOLDOUT = generate_subsets(F)
rels_H = [edge for f in HOLDOUT for edge in f.edges]
rels_V = [edge for f in VALIDATION for edge in f.edges]
rels_T = [edge for f in TRAIN for edge in f.edges]
all_rels = len(rels_H) + len(rels_V) + len(rels_T)
iteration = 0
while len(rels_H) < all_rels*(holdout-0.01) or \
len(rels_V) < all_rels*(validation-0.01) or \
len(rels_T) < all_rels*(train-0.01) or iteration > 5000:
TRAIN, VALIDATION, HOLDOUT = generate_subsets(F)
rels_H = [edge for f in HOLDOUT for edge in f.edges]
rels_V = [edge for f in VALIDATION for edge in f.edges]
rels_T = [edge for f in TRAIN for edge in f.edges]
iteration += 1
# assigning T/V/H labels
divided = {rel: 'H' for rel in rels_H}
divided = {**divided, **{rel: 'V' for rel in rels_V}}
divided = {**divided, **{rel: 'T' for rel in rels_T}}
# return statistics
# print({'train_fams': len(TRAIN), 'validation_fams': len(VALIDATION),
# 'holdout_fams': len(HOLDOUT), 'train_rels': len(rels_T),
# 'validation_rels': len(rels_V), 'holdout_rels': len(rels_H)})
if stats:
return {'train_fams': len(TRAIN), 'validation_fams': len(VALIDATION),
'holdout_fams': len(HOLDOUT), 'train_rels': len(rels_T),
'validation_rels': len(rels_V), 'holdout_rels': len(rels_H)}
return divided
if __name__ == '__main__':
# parse input parameters
parser = argparse.ArgumentParser()
parser.add_argument('-T', action='store_true', dest='t', required=False,
help='return TRAIN dataset')
parser.add_argument('-V', action='store_true', dest='v', required=False,
help='return VALIDATION dataset')
parser.add_argument('-H', action='store_true', dest='h', required=False,
help='return HOLDOUT dataset')
parser.add_argument('-a', action='store', dest='a', required=True,
help='path to the annotated data')
parser.add_argument('-stat', action='store', dest='stat', required=False,
help='path to the file with statistics')
par = parser.parse_args()
# load data
rels = defaultdict()
with open(par.a, mode='r', encoding='U8') as f:
for line in f:
entry = line.rstrip('\n').split('\t')
rels[(entry[1], entry[2])] = entry[0]
# split data
if par.stat:
data = split_data(list(rels), train=0.65, validation=0.15, holdout=0.2,
random_seed=24, stats=True)
else:
data = split_data(list(rels), train=0.65, validation=0.15, holdout=0.2,
random_seed=24)
# return data
if par.stat:
with open(par.stat, mode='w', encoding='U8') as f:
for key, val in data.items():
f.write(key + '\t' + str(val) + '\n')
sys.exit()
if par.t:
for relation, dataset in data.items():
if dataset == 'T':
print(rels[relation], *relation, sep='\t')
elif par.v:
for relation, dataset in data.items():
if dataset == 'V':
print(rels[relation], *relation, sep='\t')
elif par.h:
for relation, dataset in data.items():
if dataset == 'H':
print(rels[relation], *relation, sep='\t')
| 37.737931
| 80
| 0.571089
|
7ee878b51d0d4cc8150bea6d1cbe9aeaaef52275
| 689
|
rb
|
Ruby
|
spec/recipes/mirror_group_spec.rb
|
chef-partners/netapp_e-cookbook
|
327f5775832e978f7695817aee7efa7e2ec6c0e1
|
[
"Apache-2.0"
] | 4
|
2015-02-27T07:36:53.000Z
|
2015-06-18T14:10:08.000Z
|
spec/recipes/mirror_group_spec.rb
|
chef-boneyard/netapp_e-cookbook
|
327f5775832e978f7695817aee7efa7e2ec6c0e1
|
[
"Apache-2.0"
] | 9
|
2015-08-14T19:36:49.000Z
|
2018-11-22T14:49:48.000Z
|
spec/recipes/mirror_group_spec.rb
|
chef-partners/netapp_e-cookbook
|
327f5775832e978f7695817aee7efa7e2ec6c0e1
|
[
"Apache-2.0"
] | 6
|
2015-02-27T07:37:01.000Z
|
2016-10-31T16:32:32.000Z
|
require_relative '../spec_helper'
describe 'netapp_e::mirror_group' do
let(:chef_run) do
ChefSpec::SoloRunner.new(step_into: ['mirror_group']) do |node|
node.set['netapp']['mirror_group']['name'] = 'test'
node.set['netapp']['storage_system_ip'] = '10.100.2.11'
node.set['netapp']['mirror_group']['secondary_array_id'] = '347sjfksdfkanskfaskffdsfadffsa'
end.converge(described_recipe)
end
it 'creates the mirror group through netapp_e_mirror_group' do
expect(chef_run).to create_netapp_e_mirror_group('test')
end
it 'deletes the mirror group through netapp_e_mirror_group' do
expect(chef_run).to delete_netapp_e_mirror_group('test')
end
end
| 34.45
| 97
| 0.730044
|
81ac108be6b6cda3e953dbed23db0634f1a67b1e
| 5,454
|
css
|
CSS
|
public/css/my-style.css
|
dinwallrux/batik
|
b18f11f1258e188e05e5bab8861a79ea09d0426e
|
[
"MIT"
] | null | null | null |
public/css/my-style.css
|
dinwallrux/batik
|
b18f11f1258e188e05e5bab8861a79ea09d0426e
|
[
"MIT"
] | null | null | null |
public/css/my-style.css
|
dinwallrux/batik
|
b18f11f1258e188e05e5bab8861a79ea09d0426e
|
[
"MIT"
] | null | null | null |
.bootstrap-select.full-width {
width: 100% !important; }
.navbar-vertical.navbar-expand-md .navbar-brand-img {
max-height: 120px; }
.text-white {
color: #fff !important; }
.form-gambar .hide {
display: none; }
.form-gambar .label-file {
height: auto;
text-align: center; }
.form-gambar .label-file img {
width: auto;
max-height: 250px; }
.form-gambar .label-file i {
font-size: 80px; }
.form-gambar label#produk_preview img {
width: 200px;
height: 200px;
object-fit: cover;
margin: 5px; }
.form-gambar .list-file {
width: 100%;
height: auto; }
.form-gambar .list-file i {
font-size: 20px;
margin-right: 5px; }
.form-gambar .list-file img {
width: 120px;
height: 120px;
object-fit: contain;
margin: 5px; }
.skin-light .number-input.number-input {
display: flex;
align-items: center;
justify-content: center; }
.service-item {
height: 100%;
padding-bottom: 100px; }
.service-item .product-image {
height: 200px;
margin-bottom: 20px; }
.service-item .product-image img {
width: 100%;
height: 100%;
object-fit: cover; }
.service-item .title-price {
display: flex;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 10px; }
.service-item .title-price a:hover h5 {
text-decoration: underline;
color: #00bcd4; }
.service-item .title-price .service-title {
text-align: left;
width: 55%;
margin-right: 10px;
margin-bottom: 0; }
.service-item .title-price p {
color: #00afcb;
font-weight: 500;
font-size: 15px; }
.service-item .btn.btn-primary {
border: none;
border-radius: 100px;
margin-top: 0;
margin-right: 10px;
font-size: 13px;
padding: 12px 20px;
background-color: #00b4c6;
text-transform: uppercase;
color: #fff;
letter-spacing: 0.25px;
transition: all 0.3s ease 0s; }
.service-item .action-btn {
position: absolute;
bottom: 30px;
right: 0;
left: 0;
margin: auto;
display: flex;
align-items: center;
justify-content: center; }
header.header-area .main-nav .nav li a.active {
color: #00bcd4 !important; }
header.header-area .main-nav .nav li:hover a {
color: #00bcd4 !important; }
header.header-area .main-nav .nav .dropdown .dropdown-item {
display: flex;
align-items: center;
padding: 0; }
header.header-area .main-nav .nav .dropdown .dropdown-item:hover {
background-color: #f6f9fc; }
header.header-area .main-nav .nav .dropdown .dropdown-item form {
width: 100%; }
header.header-area .main-nav .nav .dropdown .dropdown-item button {
width: 100%; }
header.header-area .main-nav .nav .dropdown .dropdown-item p {
width: 100%;
display: flex;
align-items: center;
font-size: 14px;
color: #16181b;
font-weight: normal;
text-transform: initial;
padding: .25rem 1.5rem; }
header.header-area .main-nav .nav .dropdown .dropdown-item p i {
margin-right: 10px;
color: #00bcd4; }
#welcome {
height: 100vh;
margin-top: 0; }
#welcome .header-text {
top: 60%; }
section#about i {
color: #00bcd4 !important; }
section#services {
background: #00bcd4; }
.copyright {
color: #fff; }
.copyright a {
color: #fff;
font-weight: bold;
text-decoration: underline; }
.md-bootstrap-header nav.navbar {
height: 80px; }
.md-bootstrap-header ul.nav li {
padding-left: 20px;
padding-right: 20px; }
.md-bootstrap-header ul.nav a {
display: block;
font-weight: 500;
font-size: 13px;
color: #1e1e1e;
text-transform: uppercase;
transition: all 0.3s ease 0s;
height: 40px;
line-height: 40px;
border: transparent;
letter-spacing: 1px; }
.md-bootstrap-header ul.nav a:hover {
color: #00bcd4; }
.md-bootstrap-header ul.nav .dropdown > button {
padding: 12px 12px; }
.md-bootstrap-header ul.nav .dropdown .dropdown-menu {
width: 100%; }
.md-bootstrap-header ul.nav .dropdown .dropdown-menu button {
width: 100%;
height: 100%;
border: none;
box-sizing: border-box;
background: transparent;
padding: 0; }
.md-bootstrap-header ul.nav .dropdown .dropdown-item {
height: auto; }
.md-bootstrap-header ul.nav .dropdown a {
padding: 0; }
.md-bootstrap-header ul.nav .dropdown p {
width: 100%;
display: flex;
align-items: center;
font-size: 14px;
color: #16181b;
font-weight: normal;
text-transform: initial;
padding: .25rem 1.5rem;
margin: 0; }
.md-bootstrap-header ul.nav .dropdown p i {
margin-right: 10px;
color: #00bcd4; }
.md-bootstrap-header ul.nav .dropdown form {
width: 100%; }
.brand-name {
line-height: 80px;
color: #1e1e1e;
font-size: 28px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 2px;
transition: all 0.3s ease 0s; }
.skin-light .btn-primary {
background-color: #00bcd4 !important;
font-size: .875rem !important;
position: relative;
transition: all .15s ease;
letter-spacing: .025em;
text-transform: none;
will-change: transform; }
.skin-light .btn-primary:hover {
background-color: #00afcb !important; }
ul.list-photo {
padding: 0;
margin: 0;
list-style-type: none;
width: 100%;
display: flex;
flex-wrap: wrap; }
ul.list-photo li {
width: calc(100%/3.5);
margin: 0 10px; }
ul.list-photo img {
width: 100%;
height: 100%;
object-fit: cover; }
/*# sourceMappingURL=my-style.css.map */
| 24.567568
| 69
| 0.642281
|
2dbd0d9587d85ceca31373299ba4a829c3c4ad36
| 684
|
lua
|
Lua
|
lua/utils/im-select.lua
|
LogicHou/nvim
|
e3ff87d3525889853f05b59d43c685b0313fd24b
|
[
"MIT"
] | null | null | null |
lua/utils/im-select.lua
|
LogicHou/nvim
|
e3ff87d3525889853f05b59d43c685b0313fd24b
|
[
"MIT"
] | null | null | null |
lua/utils/im-select.lua
|
LogicHou/nvim
|
e3ff87d3525889853f05b59d43c685b0313fd24b
|
[
"MIT"
] | null | null | null |
local M = {}
M.defaultIM = 'com.apple.keylayout.ABC'
M.currentIM = M.defaultIM
M.macInsertLeave = function()
M.currentIM = vim.fn.system({ 'im-select' })
vim.cmd(':silent :!im-select' .. ' ' .. M.defaultIM)
end
M.macInsertEnter = function()
if M.currentIM then
vim.cmd(':silent :!im-select' .. ' ' .. M.currentIM)
else
vim.cmd(':silent :!im-select' .. ' ' .. M.defaultIM)
end
end
local config_path = vim.fn.stdpath('config')
M.windowsInsertLeave = function()
vim.cmd(':silent :!' .. config_path .. '/im-select.exe 1033')
end
M.windowsInsertEnter = function()
vim.cmd(':silent :!' .. config_path .. '/im-select.exe 2052')
end
return M
| 23.586207
| 65
| 0.624269
|
4d2ed58c341cfff737403b43710a07afb403d775
| 82
|
dart
|
Dart
|
lib/src/plot_nft/models/index.dart
|
irulast/chia-crypto-utils
|
502419f6eb48b00b6c5834ee7e6e185d34030877
|
[
"Apache-2.0"
] | 8
|
2022-03-04T07:16:29.000Z
|
2022-03-31T22:44:57.000Z
|
lib/src/plot_nft/models/index.dart
|
irulast/chia-crypto-utils
|
502419f6eb48b00b6c5834ee7e6e185d34030877
|
[
"Apache-2.0"
] | null | null | null |
lib/src/plot_nft/models/index.dart
|
irulast/chia-crypto-utils
|
502419f6eb48b00b6c5834ee7e6e185d34030877
|
[
"Apache-2.0"
] | 4
|
2022-03-04T01:33:29.000Z
|
2022-03-24T02:32:32.000Z
|
export './extra_data.dart';
export './plot_nft.dart';
export './pool_state.dart';
| 20.5
| 27
| 0.707317
|
d6917f5ac5f4cfb4ade2a7514500c67af0a5a924
| 12,900
|
cs
|
C#
|
ACSE.Core/Utilities/Utility.cs
|
atribecalledqst/ACSE
|
a48a589018d755605b2a3928a55c85ba01b0758f
|
[
"MIT"
] | 133
|
2017-04-01T07:22:35.000Z
|
2022-03-26T15:54:54.000Z
|
ACSE.Core/Utilities/Utility.cs
|
atribecalledqst/ACSE
|
a48a589018d755605b2a3928a55c85ba01b0758f
|
[
"MIT"
] | 83
|
2016-12-16T10:01:29.000Z
|
2022-03-02T23:05:40.000Z
|
ACSE.Core/Utilities/Utility.cs
|
atribecalledqst/ACSE
|
a48a589018d755605b2a3928a55c85ba01b0758f
|
[
"MIT"
] | 31
|
2017-06-18T00:01:45.000Z
|
2022-03-31T13:47:29.000Z
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using ACSE.Core.Encryption;
using ACSE.Core.Items;
using ACSE.Core.Saves;
using ACSE.Core.Town.Acres;
using ACSE.Core.Villagers;
namespace ACSE.Core.Utilities
{
public static class Utility
{
public static int[] FindAllMatches(ref List<byte> dictionary, byte match)
{
var matchPositons = new List<int>();
for (var i = 0; i < dictionary.Count; i++)
{
if (dictionary[i] == match)
{
matchPositons.Add(i);
}
}
return matchPositons.ToArray();
}
public static int[] FindLargestMatch(ref List<byte> dictionary, int[] matchesFound, ref byte[] file, int fileIndex, int maxMatch)
{
var matchSizes = new int[matchesFound.Length];
for (var i = 0; i < matchesFound.Length; i++)
{
var matchSize = 1;
var matchFound = true;
while (matchFound && matchSize < maxMatch && (fileIndex + matchSize < file.Length) && (matchesFound[i] + matchSize < dictionary.Count)) //NOTE: This could be relevant to compression issues? I suspect it's more related to writing
{
if (file[fileIndex + matchSize] == dictionary[matchesFound[i] + matchSize])
{
matchSize++;
}
else
{
matchFound = false;
}
}
matchSizes[i] = matchSize;
}
var bestMatch = new[] {matchesFound[0], matchSizes[0]};
for (var i = 1; i < matchesFound.Length; i++)
{
if (matchSizes[i] <= bestMatch[1]) continue;
bestMatch[0] = matchesFound[i];
bestMatch[1] = matchSizes[i];
}
return bestMatch;
}
public static Tuple<byte[], bool> FindVillagerHouse(ushort villagerId, WorldAcre[] townAcres) // TODO: Apply to WW
{
if (Save.SaveInstance == null) return new Tuple<byte[], bool>(new byte[] {0xFF, 0xFF, 0xFF, 0xFF}, false);
var villagerHouseId = (ushort)(0x5000 + (villagerId & 0xFF));
foreach (var acre in townAcres)
{
var villagerHouse = acre.Items.FirstOrDefault(o => o.ItemId == villagerHouseId);
if (villagerHouse != null)
{
var idx = Array.IndexOf(acre.Items, villagerHouse);
return new Tuple<byte[], bool>(
new[]
{
(byte) (acre.Index % 7), (byte) (acre.Index / 7), (byte) (idx % 16),
(byte) (idx / 16 + 1)
},
true);
}
}
return new Tuple<byte[], bool>(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }, false);
}
public static (byte[], bool) FindVillagerHouseWildWorld(int villagerIndex, WorldAcre[] townAcres)
{
if (Save.SaveInstance == null) return (new byte[] {0xFF, 0xFF}, false);
var houseId = 0x5001 + villagerIndex;
foreach (var acre in townAcres)
{
var villagerHouse = acre.Items.FirstOrDefault(o => o.ItemId == houseId);
if (villagerHouse != null)
{
var idx = Array.IndexOf(acre.Items, villagerHouse);
return (
new[]
{
(byte) (((acre.Index % 4 + 1) << 4) | (idx % 16)),
(byte) (((acre.Index / 4 + 1) << 4) | (idx / 16))
}, true);
}
}
return (new byte[] { 0xFF, 0xFF }, false);
}
public static Villager GetVillagerFromHouse(ushort houseId, Villager[] villagers)
{
var villagerId = (ushort)(0xE000 | (houseId & 0x00FF));
return villagers.FirstOrDefault(villager => villager.Data.VillagerId == villagerId);
}
public static bool[] CheckPerfectTownRequirements(WorldAcre[] acres, bool makePerfect = false)
{
var acreResults = new bool[acres.Length];
var points = 0;
for (var i = 0; i < acreResults.Length; i++)
{
var acre = acres[i];
switch (Save.SaveInstance.SaveGeneration)
{
case SaveGeneration.N64:
case SaveGeneration.GCN:
//TODO: Implement Special Acre Check (Player Houses, Train Station, Oceanfront Acres, Lake Acres, Wishing Well, & Museum
//Special Acre Info: < 9 Trees, 0 Points | 9 - 11, 1 Point | 12 - 14, 2 Points | 15 - 17, 1 Point | > 18, 0 Points
var treeCount = 0;
var weedCount = 0;
for (var o = 0; o < 256; o++)
{
var item = acre.Items[o];
if (item.Name == "Weed")
{
weedCount++;
if (makePerfect)
{
acre.Items[o] = new Item(0);
}
}
else if (ItemData.GetItemType(item.ItemId, Save.SaveInstance.SaveType) == ItemType.Tree)
{
treeCount++;
}
}
if (makePerfect)
{
if (treeCount > 14)
{
for (var o = 0; o < treeCount - 13; o++)
{
for (var x = 0; x < 256; x++)
{
if (ItemData.GetItemType(acre.Items[x].ItemId,
Save.SaveInstance.SaveType) != ItemType.Tree) continue;
acre.Items[x] = new Item(0);
break;
}
}
}
else if (treeCount < 12)
{
for (var o = 0; o < 13 - treeCount; o++)
{
for (var x = 0; x < 256; x++)
{
// Check to make sure the item directly above, below, and to the left and right isn't already occupied.
if (acre.Items[x].ItemId != 0 ||
(x >= 16 && acre.Items[x - 16].ItemId != 0) ||
(x <= 239 && acre.Items[x + 16].ItemId != 0) ||
(x != 0 && acre.Items[x - 1].ItemId != 0) ||
(x != 255 && acre.Items[x + 1].ItemId != 0)) continue;
acre.Items[x] = new Item(0x0804);
break;
}
}
}
}
acreResults[i] = makePerfect || ((treeCount > 11 && treeCount < 15) && weedCount < 4);
if (acreResults[i])
{
points++;
}
if (points > 14)
return acreResults;
break;
case SaveGeneration.NDS:
case SaveGeneration.Wii:
case SaveGeneration.N3DS:
throw new NotImplementedException();
}
}
return acreResults;
}
public static void PlaceStructure(WorldAcre acre, int startIndex, List<ushort[]> structureInfo)
{
if (startIndex <= -1 || startIndex >= 256) return;
if (Save.SaveInstance.SaveGeneration != SaveGeneration.GCN) return;
for (var y = 0; y < structureInfo.Count; y++)
{
for (var x = 0; x < structureInfo[y].Length; x++)
{
var index = startIndex + y * 16 + x;
if (index >= 256) continue;
switch (structureInfo[y][x])
{
case 0: // Just for alignment
break;
case 1:
acre.Items[index] = new Item(0xFFFF);
break;
default:
acre.Items[index] = new Item(structureInfo[y][x]);
break;
}
}
}
}
public static byte GetWildWorldGrassBaseType(byte seasonalGrassValue)
{
if (seasonalGrassValue < 3)
return seasonalGrassValue;
return (byte)((seasonalGrassValue - 1) % 3); // May not be right.
}
public static void FloodFillItemArray(ref Item[] items, int itemsPerRow, int startIndex, Item originalItem, Item newItem)
{
var rows = items.Length / itemsPerRow;
var locationStack = new Stack<Point>();
var previousPoints = new int[items.Length];
var x = startIndex % itemsPerRow;
var y = startIndex / itemsPerRow;
locationStack.Push(new Point(x, y));
while (locationStack.Count > 0)
{
var p = locationStack.Pop();
var idx = p.X + p.Y * itemsPerRow;
if (p.X < itemsPerRow && p.X > -1 &&
p.Y < rows && p.Y > -1 && previousPoints[idx] == 0) // Make sure we stay within bounds
{
var i = items[idx];
if (i.Equals(originalItem))
{
Save.SaveInstance.ChangesMade = true;
items[idx] = new Item(newItem);
if (p.X - 1 > -1)
locationStack.Push(new Point(p.X - 1, p.Y));
if (p.X + 1 < itemsPerRow)
locationStack.Push(new Point(p.X + 1, p.Y));
if (p.Y - 1 > -1)
locationStack.Push(new Point(p.X, p.Y - 1));
if (p.Y + 1 < rows)
locationStack.Push(new Point(p.X, p.Y + 1));
}
}
previousPoints[idx] = 1;
}
}
public static void FloodFillFurnitureArray(ref Furniture[] items, int itemsPerRow, int startIndex, Furniture originalItem, Furniture newItem)
{
var rows = items.Length / itemsPerRow;
var locationStack = new Stack<Point>();
var previousPoints = new int[items.Length];
var x = startIndex % itemsPerRow;
var y = startIndex / itemsPerRow;
locationStack.Push(new Point(x, y));
while (locationStack.Count > 0)
{
var p = locationStack.Pop();
var idx = p.X + p.Y * itemsPerRow;
if (p.X < itemsPerRow && p.X > -1 &&
p.Y < rows && p.Y > -1 && previousPoints[idx] == 0) // Make sure we stay within bounds
{
var i = items[idx];
if (i.Equals(originalItem))
{
Save.SaveInstance.ChangesMade = true;
items[idx] = new Furniture(newItem);
if (p.X - 1 > -1)
locationStack.Push(new Point(p.X - 1, p.Y));
if (p.X + 1 < itemsPerRow)
locationStack.Push(new Point(p.X + 1, p.Y));
if (p.Y - 1 > -1)
locationStack.Push(new Point(p.X, p.Y - 1));
if (p.Y + 1 < rows)
locationStack.Push(new Point(p.X, p.Y + 1));
}
}
previousPoints[idx] = 1;
}
}
}
}
| 41.4791
| 244
| 0.406202
|
5ae16f381f534d9afa1fb0beeb2b756ffd35acd5
| 603
|
cs
|
C#
|
src/Solana.Unity.Rpc/Models/Version.cs
|
garbles-dev/Solnet.Unity
|
44b14fd58803fb71cb324ed6c9bf53be58bee5e9
|
[
"MIT"
] | 4
|
2022-03-28T16:16:38.000Z
|
2022-03-30T18:27:36.000Z
|
src/Solana.Unity.Rpc/Models/Version.cs
|
garbles-dev/Sol.Unity
|
44b14fd58803fb71cb324ed6c9bf53be58bee5e9
|
[
"MIT"
] | null | null | null |
src/Solana.Unity.Rpc/Models/Version.cs
|
garbles-dev/Sol.Unity
|
44b14fd58803fb71cb324ed6c9bf53be58bee5e9
|
[
"MIT"
] | null | null | null |
using Newtonsoft.Json;
namespace Solana.Unity.Rpc.Models
{
/// <summary>
/// Represents the current solana versions running on the node.
/// </summary>
public class NodeVersion
{
/// <summary>
/// Software version of solana-core.
/// </summary>
[JsonProperty("solana-core")]
public string SolanaCore { get; set; }
/// <summary>
/// unique identifier of the current software's feature set.
/// </summary>
[JsonProperty("feature-set")]
public ulong? FeatureSet { get; set; }
}
}
| 27.409091
| 69
| 0.555556
|
6dd5dee0bee39fa00c8230f6b5da3150a8798152
| 1,161
|
ts
|
TypeScript
|
front/src/app/main/common/profile-edit/profile-edit.component.ts
|
grzegorz103/virtual-bank-system
|
7bd1909833ca494b979f15a2784d64e9da1e0376
|
[
"MIT"
] | 6
|
2021-01-18T17:35:29.000Z
|
2022-01-07T13:28:15.000Z
|
front/src/app/main/common/profile-edit/profile-edit.component.ts
|
grzegorz103/virtual-bank-system
|
7bd1909833ca494b979f15a2784d64e9da1e0376
|
[
"MIT"
] | 5
|
2021-09-02T06:35:21.000Z
|
2022-02-26T23:37:17.000Z
|
front/src/app/main/common/profile-edit/profile-edit.component.ts
|
grzegorz103/spring-virtual-bank
|
7bd1909833ca494b979f15a2784d64e9da1e0376
|
[
"MIT"
] | 4
|
2020-05-13T18:54:51.000Z
|
2022-02-05T13:42:34.000Z
|
import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/shared/services/user.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AuthService } from 'src/app/shared/services/auth.service';
import { User } from '../../models/user';
@Component({
selector: 'app-profile-edit',
templateUrl: './profile-edit.component.html',
styleUrls: ['./profile-edit.component.scss']
})
export class ProfileEditComponent implements OnInit {
user: User;
passwordForm: FormGroup;
constructor(private userService: UserService,
public authService: AuthService,
private fb: FormBuilder) { }
ngOnInit() {
this.createPasswordForm();
this.fetchUserDetails();
}
createPasswordForm() {
this.passwordForm = this.fb.group({
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
});
}
sendPasswordEditForm() {
this.userService.editPassword(this.passwordForm.value)
.subscribe(res=>alert('Hasło zmienione'));
}
fetchUserDetails() {
this.userService.findCurrentUser()
.subscribe(res => this.user = res);
}
}
| 26.386364
| 68
| 0.689922
|
8ce5c0b6070c5ddd5c2520fb98f70bd0c2286204
| 9,813
|
swift
|
Swift
|
Turf/Extensions/SecondaryIndex/ObservableCollection+IndexedCollection.swift
|
TurfDb/Turf
|
922b67f83bcee23be2b2d3cd57125f2912b62c08
|
[
"MIT"
] | 11
|
2016-03-28T13:31:11.000Z
|
2021-05-22T09:53:26.000Z
|
Turf/Extensions/SecondaryIndex/ObservableCollection+IndexedCollection.swift
|
TurfDb/Turf
|
922b67f83bcee23be2b2d3cd57125f2912b62c08
|
[
"MIT"
] | 4
|
2016-03-28T16:39:15.000Z
|
2016-04-20T10:41:39.000Z
|
Turf/Extensions/SecondaryIndex/ObservableCollection+IndexedCollection.swift
|
TurfDb/Turf
|
922b67f83bcee23be2b2d3cd57125f2912b62c08
|
[
"MIT"
] | 4
|
2016-03-28T13:32:54.000Z
|
2016-04-09T10:09:37.000Z
|
//
extension ObservableCollection where TCollection: IndexedCollection {
//TODO Threading
// MARK: Public methods
/**
Observe the values returned by `predicate` after every collection change.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
*/
public func values(where clause: WhereClause) -> Observable<TransactionalValue<[TCollection.Value], Collections>> {
return self.map { (collection, changeSet) in
let newValues = collection.findValues(where: clause)
return TransactionalValue(transaction: collection.readTransaction, value: newValues)
}
}
/**
Observe the values returned by `predicate` after a collection change.
If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
- parameter prefilter: Executed before querying the collection to determine if the query is required.
*/
public func values(where clause: WhereClause, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> Observable<TransactionalValue<[TCollection.Value], Collections>> {
var previous: [TCollection.Value] = []
return self.filterChangeSet { (changeSet) -> Bool in
return prefilter(changeSet, previous)
}.map { (collection, changeSet) in
let newValues = collection.findValues(where: clause)
previous = newValues
return TransactionalValue(transaction: collection.readTransaction, value: newValues)
}
}
/**
Observe the values returned by `predicate` after every collection change.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
*/
public func indexableValues(where clause: WhereClause) -> IndexableObservable<[TCollection.Value]> {
return IndexableObservable(observable: self.map { return $0.0.findValues(where: clause) })
}
/**
Observe the values returned by `predicate` after a collection change.
If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
- parameter prefilter: Executed before querying the collection to determine if the query is required.
*/
public func indexableValues(where clause: WhereClause, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> IndexableObservable<[TCollection.Value]> {
var previous: [TCollection.Value] = []
let observable = self.filterChangeSet { (changeSet) -> Bool in
return prefilter(changeSet, previous)
}.map { (collection, changeSet) -> [TCollection.Value] in
let newValues = collection.findValues(where: clause)
previous = newValues
return newValues
}
return IndexableObservable(observable: observable)
}
// MARK: Prepared query
/**
Observe the values returned by `predicate` after every collection change.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
*/
public func values(where clause: PreparedValuesWhereQuery<Collections>) -> Observable<TransactionalValue<[TCollection.Value], Collections>> {
return self.map { (collection, changeSet) in
let newValues = collection.findValues(where: clause)
return TransactionalValue(transaction: collection.readTransaction, value: newValues)
}
}
/**
Observe the values returned by `predicate` after a collection change.
If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
- parameter prefilter: Executed before querying the collection to determine if the query is required.
*/
public func values(where clause: PreparedValuesWhereQuery<Collections>, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> Observable<TransactionalValue<[TCollection.Value], Collections>> {
var previous: [TCollection.Value] = []
return self.filterChangeSet { (changeSet) -> Bool in
return prefilter(changeSet, previous)
}.map { (collection, changeSet) in
let newValues = collection.findValues(where: clause)
previous = newValues
return TransactionalValue(transaction: collection.readTransaction, value: newValues)
}
}
/**
Observe the values returned by `predicate` after every collection change.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
*/
public func indexableValues(where clause: PreparedValuesWhereQuery<Collections>) -> IndexableObservable<[TCollection.Value]> {
return IndexableObservable(observable: self.map { return $0.0.findValues(where: clause) })
}
/**
Observe the values returned by `predicate` after a collection change.
If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`.
- note:
- Thread safe.
- parameter where: Secondary indexed query to execute on collection change.
- parameter prefilter: Executed before querying the collection to determine if the query is required.
*/
public func indexableValues(where clause: PreparedValuesWhereQuery<Collections>, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> IndexableObservable<[TCollection.Value]> {
var previous: [TCollection.Value] = []
let observable = self.filterChangeSet { (changeSet) -> Bool in
return prefilter(changeSet, previous)
}.map { (collection, changeSet) -> [TCollection.Value] in
let newValues = collection.findValues(where: clause)
previous = newValues
return newValues
}
return IndexableObservable(observable: observable)
}
// MARK: Raw SQL query
/**
Observe the values returned by `predicate` after every collection change.
- note:
- Thread safe.
- parameter matchingRawSql: Secondary indexed query to execute on collection change.
*/
public func values(matchingRawSql clause: String) -> Observable<TransactionalValue<[TCollection.Value], Collections>> {
return self.map { (collection, changeSet) in
let newValues = collection.findValues(where: clause)
return TransactionalValue(transaction: collection.readTransaction, value: newValues)
}
}
/**
Observe the values returned by `predicate` after a collection change.
If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`.
- note:
- Thread safe.
- parameter matchingRawSql: Secondary indexed query to execute on collection change.
- parameter prefilter: Executed before querying the collection to determine if the query is required.
*/
public func values(matchingRawSql clause: String, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> Observable<TransactionalValue<[TCollection.Value], Collections>> {
var previous: [TCollection.Value] = []
return self.filterChangeSet { (changeSet) -> Bool in
return prefilter(changeSet, previous)
}.map { (collection, changeSet) in
let newValues = collection.findValues(where: clause)
previous = newValues
return TransactionalValue(transaction: collection.readTransaction, value: newValues)
}
}
/**
Observe the values returned by `predicate` after every collection change.
- note:
- Thread safe.
- parameter matchingRawSql: Secondary indexed query to execute on collection change.
*/
public func indexableValues(matchingRawSql clause: String) -> IndexableObservable<[TCollection.Value]> {
return IndexableObservable(observable: self.map { return $0.0.findValues(where: clause) })
}
/**
Observe the values returned by `predicate` after a collection change.
If the query is expensive, the collection change set can be examined first by using `prefilterChangeSet`.
- note:
- Thread safe.
- parameter matchingRawSql: Secondary indexed query to execute on collection change.
- parameter prefilter: Executed before querying the collection to determine if the query is required.
*/
public func indexableValues(matchingRawSql clause: String, prefilter: @escaping (_ changeSet: ChangeSet<String>, _ previousValues: [TCollection.Value]) -> Bool) -> IndexableObservable<[TCollection.Value]> {
var previous: [TCollection.Value] = []
let observable = self.filterChangeSet { (changeSet) -> Bool in
return prefilter(changeSet, previous)
}.map { (collection, changeSet) -> [TCollection.Value] in
let newValues = collection.findValues(where: clause)
previous = newValues
return newValues
}
return IndexableObservable(observable: observable)
}
}
| 48.102941
| 247
| 0.67859
|
79b048d0e10212181184c68ef6fa0fa8da84a890
| 894
|
php
|
PHP
|
app/Http/Requests/CustomerRequest.php
|
butdepzai98/Laravel_Ecomerce_2019
|
55181e25c3755cec89c3b9e34dc2e2132a2e82b1
|
[
"MIT"
] | null | null | null |
app/Http/Requests/CustomerRequest.php
|
butdepzai98/Laravel_Ecomerce_2019
|
55181e25c3755cec89c3b9e34dc2e2132a2e82b1
|
[
"MIT"
] | null | null | null |
app/Http/Requests/CustomerRequest.php
|
butdepzai98/Laravel_Ecomerce_2019
|
55181e25c3755cec89c3b9e34dc2e2132a2e82b1
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CustomerRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => 'required|email',
'phone' => 'required',
'address' => 'required',
];
}
public function messages()
{
return [
'email.required' => 'Yêu cầu nhập Email',
'email.email' => 'Email sai định dạng',
'phone.required' => 'Yêu cầu nhập số điện thoại',
'address.required' => 'Yêu cầu nhập địa chỉ Nhận hàng',
];
}
}
| 20.790698
| 67
| 0.527964
|
76f55fb9b7e9f52c20376415c58ee3d0dec47064
| 34,838
|
h
|
C
|
myTempSensor_REED/middleware/wireless/nwk_ip_1.2.1/core/interface/thread/thread_network.h
|
sansergio/thread-example
|
92f216cb96a1b735d72c71301dafa6309909618e
|
[
"MIT"
] | null | null | null |
myTempSensor_REED/middleware/wireless/nwk_ip_1.2.1/core/interface/thread/thread_network.h
|
sansergio/thread-example
|
92f216cb96a1b735d72c71301dafa6309909618e
|
[
"MIT"
] | null | null | null |
myTempSensor_REED/middleware/wireless/nwk_ip_1.2.1/core/interface/thread/thread_network.h
|
sansergio/thread-example
|
92f216cb96a1b735d72c71301dafa6309909618e
|
[
"MIT"
] | null | null | null |
/*! *********************************************************************************
* \defgroup NWK Thread Network Interface
* @{
***********************************************************************************/
/*
* Copyright (c) 2014 - 2015, Freescale Semiconductor, Inc.
* Copyright 2016-2017 NXP
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.
*/
#ifndef _THREAD_NETWORK_H
#define _THREAD_NETWORK_H
/*!
\file thread_network.h
\brief This is a header file for the Thread Network module.
*/
/*==================================================================================================
Include Files
==================================================================================================*/
/* General Includes */
#include "EmbeddedTypes.h"
#include "stack_config.h"
#include "network_utils.h"
#include "stack_manager_if.h"
#include "thread_types.h"
#include "thread_attributes.h"
#include "event_manager.h"
#include "thread_meshcop.h"
/*==================================================================================================
Public macros
==================================================================================================*/
/*! Thread Device Capabilities */
#define THR_NWKCAP_CAN_CREATE_NEW_NETWORK (1<<0) /*!< The node can create a new network */
#define THR_NWKCAP_CAN_BECOME_ACTIVE_ROUTER (1<<1) /*!< The node can become an active router */
#define THR_NWKCAP_IS_POLLING_END_DEVICE (1<<2) /*!< The node is a polling end device (sleepy end device) */
#define THR_NWKCAP_IS_FULL_THREAD_DEVICE (1<<3) /*!< The node is a full Thread device (FTD) */
/* Update according to number of capabilities flags! */
/*! Thread Device Capabilities bit mask */
#define THR_NWKCAP_BIT_MASK 0x0F
/*! Network scan events */
typedef enum
{
gThrEv_NwkScanCnf_Results_c = gThrEvSet_NwkScan_c + 1, /*!< nwk scan confirm - results */
} thrEvCodesNwkScan_t;
/*! Network Create Events */
typedef enum
{
gThrEv_NwkCreateCnf_Success_c = gThrEvSet_NwkCreate_c + 1, /*!< nwk create confirm - success */
gThrEv_NwkCreateCnf_Failed_c, /*!< nwk create confirm - failed */
gThrEv_NwkCreateInd_SelectBestChannel_c, /*!< nwk create indication - select best channel */
gThrEv_NwkCreateInd_GeneratePSKc_c /*!< nwk create indication - generate PSKc */
} thrEvCodesCreate_t;
/*! Network Join Events */
typedef enum
{
gThrEv_NwkJoinInd_Attaching_c = gThrEvSet_NwkJoin_c + 1, /*!< nwk join indication - attaching */
gThrEv_NwkJoinCnf_Success_c, /*!< nwk join confirm - success */
gThrEv_NwkJoinCnf_Failed_c, /*!< nwk join confirm - failed */
} thrEvCodesJoin_t;
/*! Network Select Parent when joining with Commissioner */
typedef enum
{
gThrEv_NwkSelectParentsInd_ScanStarted_c = gThrEvSet_NwkSelectParents_c + 1, /*!< network select parent indication - scan started */
gThrEv_NwkSelectParentsInd_RcvBeacon_c, /*!< network select parent indication - received beacon */
gThrEv_NwkSelectParentsInd_ScanEnded_c, /*!< network select parent indication - scan ended */
} thrEvCodesJoinSelectParent_t;
/*! Network General Events - warning the order of events impacts the THCI event monitor */
typedef enum
{
gThrEv_GeneralInd_Disconnected_c = gThrEvSet_NwkGeneral_c + 1, /*!< general event indication - disconnected */
gThrEv_GeneralInd_Connected_c, /*!< general event indication - connected */
gThrEv_GeneralInd_ResetToFactoryDefault_c, /*!< general event indication - device started with factory defaults */
gThrEv_GeneralInd_InstanceRestoreStarted_c, /*!< general event indication - start restore from reset */
gThrEv_GeneralInd_RouterSynced_c, /*!< general event indication - restored from reset with success for router */
gThrEv_GeneralInd_EndDeviceSynced_c, /*!< general event indication - restored from reset with success for end device */
gThrEv_GeneralInd_ConnectingStarted_c, /*!< general event indication - trying to connect to the network */
gThrEv_GeneralInd_ConnectingFailed_c, /*!< general event indication - failed to connect to the network */
gThrEv_GeneralInd_ConnectingDeffered_c, /*!< general event indication - app must initiate connect action */
gThrEv_GeneralInd_DeviceIsLeader_c, /*!< general event indication - device has leader role */
gThrEv_GeneralInd_DeviceIsRouter_c, /*!< general event indication - device has router role */
gThrEv_GeneralInd_DevIsREED_c, /*!< general event indication - device has REED role */
gThrEv_GeneralInd_DevIsED_c, /*!< general event indication - device has RX on when idle end device role */
gThrEv_GeneralInd_DevIsSED_c, /*!< general event indication - device has sleepy end device role */
gThrEv_GeneralInd_RequestGlobalAddr_c, /*!< general event indication - request global address */
gThrEv_GeneralInd_GlobalAddrAssigned_c, /*!< general event indication - global address assigned */
gThrEv_GeneralInd_RequestRouterId_c, /*!< general event indication - request router short address */
gThrEv_GeneralInd_RouterIdAssigned_c, /*!< general event indication - router short address assigned */
gThrEv_GeneralInd_RouterIdAssignedFailed_c, /*!< general event indication - failed to received router short address */
gThrEv_GeneralInd_AllowDeviceToSleep_c, /*!< general event indication - allow device to sleep */
gThrEv_GeneralInd_DisallowDeviceToSleep_c, /*!< general event indication - disallow device to sleep */
gThrEv_GeneralInd_ChildIdAssigned_c, /*!< general event indication - child short address assigned */
gThrEv_GeneralInd_ResetMcuTimeout_c, /*!< general event indication - reset mcu timeout */
} thrEvCodesGeneral_t;
/*! thread device configuration */
typedef struct thrDeviceConfig_tag
{
/*! If TRUE than the device is out-of-band configured.
- On network creation, it is not used.
- On joining, if it is set TRUE the THR_NwkJoin() will perform only the attaching procedure;
otherwise it will perform the joining with Commissioner procedure (mesh-cop joining). */
bool_t outOfBandConfigured;
/*! Network creation channel. If different form 0, On network creation (THR_NwkCreate()), will
OVERRIDE the SCAN channel and only use this channel. Range: 0, 11-26 */
uint8_t outOfBandChannel;
/*! - On network creation (THR_NwkCreate()), the configured value will be used or if it is set to
0xffff then the device will generate a random pan ID .*/
uint16_t panId;
/*! The channel mask used for scanning for networks and to discover network parameters
(panId, channel, xpan, network name)*/
uint32_t scanChannels;
/*! - On network creation (THR_NwkCreate()), the configured value will be used or if all bytes are
0xff then the device will generate a random extended pan ID.
- On joining using out-of-band configuration (outOfBandConfigured = TRUE), if all bytes are 0xff
then the device won't filter after the extended pan ID; otherwise it uses this extended pan id
for filtering. */
uint8_t xPanId[8];
/*! - On network creation (THR_NwkCreate()), the configured value will be used or if all bytes are
0xff then the device will generate a random master key.
- On joining using out-of-band configuration (outOfBandConfigured = TRUE), the device uses
the configured key for communication. */
uint8_t masterKey[16];
/*! On joining with the out-of-band configuration (outOfBandConfigured = TRUE), if (outOfBandChannel == 0)
and nwkName.length != 0, the device will filter after network name to find the pan id and channel. */
thrOctet16_t nwkName;
/*!- On network creation (THR_NwkCreate()), the configured value will be used or if all bytes are
0xff then the device will generate a random mesh local prefix. */
thrPrefixAttr_t MLprefix;
} thrDeviceConfig_t;
/*==================================================================================================
Public type definitions
==================================================================================================*/
/*==================================================================================================
Public global variables declarations
==================================================================================================*/
/*! Thread device configuration */
extern thrDeviceConfig_t gaThrDeviceConfig[];
/*==================================================================================================
Public function prototypes
==================================================================================================*/
/*!*************************************************************************************************
\fn void THR_Task(osaTaskParam_t argument)
\brief Thread application task.
\param [in] argument Task private data
\return NONE
***************************************************************************************************/
void THR_Task(osaTaskParam_t argument);
/*!*************************************************************************************************
\fn void THR_Init(void)
\brief Initialize Thread module.
\return NONE
***************************************************************************************************/
void THR_Init(void);
/*!*************************************************************************************************
\fn thrStatus_t THR_InitAttributes(instanceId_t thrInstId, stackConfig_t *pStackCfg)
\brief Function that initializes with factory defaults or restores from NVM the Thread Attributes.
\param [in] thrInstId Thread instance Id
\param [in] pStackCfg Pointer to stack configuration
\return thrStatus_t Result of the operation
***************************************************************************************************/
thrStatus_t THR_InitAttributes(instanceId_t thrInstId, stackConfig_t *pStackCfg);
/*!*************************************************************************************************
\fn thrStatus_t THR_StartInstance(instanceId_t thrInstId, stackConfig_t *pStackCfg)
\brief Function that starts the Thread instance.
\param [in] thrInstID Thread instance ID
\param [in] pStackCfg Pointer to stack configuration
\return thrStatus_t Result of the operation
***************************************************************************************************/
thrStatus_t THR_StartInstance(instanceId_t thrInstId, stackConfig_t *pStackCfg);
/*!*************************************************************************************************
\fn thrStatus_t THR_SetDeviceConfig(instanceId_t thrInstId, thrDeviceConfig_t *pThrDeviceConfig)
\brief This function is used to set device configuration. This function overwrites the default
settings (see app_thread_config.h) with a minimum set of attributes needed to start a node.
The application may not call this function if it wants to use the default settings.
\param [in] thrInstID Thread instance Id
\param [in] pThrDeviceConfig Pointer to device configuration
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_SetDeviceConfig(instanceId_t thrInstId, thrDeviceConfig_t *pThrDeviceConfig);
/*!*************************************************************************************************
\fn thrStatus_t THR_SetDeviceRole(instanceId_t thrInstID, thrDeviceRole_t thrDeviceRole)
\brief This is a public function used to set the network capabilities for a Thread device.
\param [in] thrInstID Thread instance ID
\param [in] thrDeviceRole Thread desired device role.
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_SetDeviceRole(instanceId_t thrInstID, thrDeviceRole_t thrDeviceRole);
/*!*************************************************************************************************
\fn thrStatus_t THR_NwkScanWithBeacon(instanceId_t thrInstId, thrNwkScan_t *pThrNwkScan)
\brief This function is used to start a network scan using beacon messages.
A callback function must be registered (using EVM_RegisterStatic() function) with the
gThrEvSet_NwkScan_c set to receive the scan results (see thrNwkScanResults_t message).
\param [in] thrInstID Thread instance Id
\param [in] pThrNwkScan Network scan parameters
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_NwkScanWithBeacon(instanceId_t thrInstId, thrNwkScan_t *pThrNwkScan);
/*!*************************************************************************************************
\fn thrStatus_t THR_NwkDiscoveryReq(instanceId_t thrInstId,thrNwkDiscoveryReqTxOpt_t* pDiscReqTxOpt,
thrDiscoveryRespCb_t pfDiscoveryRespCb)
\brief This function starts the Thread Discovery Procedure. A callback function must be registered
(pfDiscoveryRespCb) to receive the Discovery Responses.
\param [in] thrInstID Thread instance Id
\param [in] pDiscReqTxOpt Pointer to Discovery Request Tx options
\param [in] pfDiscoveryRespCb Pointer to a callback to receive the Discovery Responses
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_NwkDiscoveryReq(instanceId_t thrInstId,
thrNwkDiscoveryReqTxOpt_t *pDiscReqTxOpt, thrDiscoveryRespCb_t pfDiscoveryRespCb);
/*!*************************************************************************************************
\fn thrStatus_t THR_NwkDiscoveryStop(instanceId_t thrInstId)
\brief This function stops the discovery process before timing out.
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_NwkDiscoveryStop(instanceId_t thrInstId);
/*!*************************************************************************************************
\fn thrStatus_t THR_SearchThreadNwkWithAnnounce(instanceId_t thrInstId,uint32_t scanChannelMask,
thrAnnounceCb_t pfAnnounceCb)
\brief The device has the Nwk key and searches the thread network using the announcement messages.
Only Thread networks that have the same Nwk key will respond.
This function could be used to discover the channel and panId of a Thread network,
so that to start the attachment process (to perform the out-of-band joining procedure).
\param [in] thrInstID Thread instance Id
\param [in] scanChannelMask Channel mask to scan
\param [in] pfAnnounceCb Pointer to a callback that handles the received announcement messages.
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_SearchThreadNwkWithAnnounce(instanceId_t thrInstId,
uint32_t scanChannelMask, thrAnnounceCb_t pfAnnounceCb);
/*!*************************************************************************************************
\fn thrStatus_t THR_NwkCreate(instanceId_t thrInstId)
\brief This function is used to create a Thread network (start the device as a leader node).
If the PAN ID and channel attributes are configured (panid != 0xFFFF and channel != 0), the
function will start the leader using these attributes. Otherwise, the scanChannelMask
attribute is used to select the best channel and panID.
A callback function is registered (see thread_app_callbacks.h and app_thread_callbacks.c)
with the gThrEvSet_NwkCreate_c event set to receive the network creation events(see
APP_NwkCreateCb callback).
Note that THR_NWKCAP_CAN_CREATE_NEW_NETWORK bit must be set in the network capabilities.
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_NwkCreate(instanceId_t thrInstId);
/*!*************************************************************************************************
\fn thrStatus_t THR_NwkAttach(instanceId_t thrInstId)
\brief This function is used to perform the attachment procedure using the configured attributes:
channel, panId, network key.
NOTE:
- It can be used for out-of-band joining.
- A callback function must be registered (using EVM_RegisterStatic() function) with the
gThrEvSet_NwkJoin_c event set to receive the network join events.
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_NwkAttach(instanceId_t thrInstId);
/*!*************************************************************************************************
\fn thrStatus_t THR_NwkJoin(instanceId_t thrInstId, thrJoinDiscoveryMethod_t discMethod)
\brief This function is used to join a device to a thread network and is using all the above
functionality. Depending on attributes configuration, it can perform the following actions:
1. join as an end node using commissioning (calling MESHCOP_NwkJoinWithCommissioning()).
In this case, the device is NOT out-of-band configured;this means the devIsCommissioned
attribute shall be set to FALSE. Depending on discovery method parameter (discMethod),
the device will search the panId and channel using Beacon or Thread Discovery messages.
2. attach to a thread network (calling THR_NwkAttach()). In this case, the device must
be out-of-band configured;this means the devIsCommissioned attribute shall be set to TRUE.
Depending on discovery method parameter (discMethod), the device will search the panId and
channel using Beacon or Announcement messages (see THR_SearchThreadNwkWithAnnounce()).
A callback function must be registered (using EVM_RegisterStatic() function) with the
gThrEvSet_NwkJoin_c event set to receive the network join events.
\param [in] thrInstID Thread instance Id
\param [in] discMethod The discovery method (see thrJoinDiscoveryMethod_t)
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_NwkJoin(instanceId_t thrInstId, thrJoinDiscoveryMethod_t discMethod);
/*!*************************************************************************************************
\fn thrStatus_t THR_NwkDetach(instanceId_t thrInstId)
\brief This function is used to detach a joined device. The device will keep the network settings but
will disconnect itself from the network.
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_NwkDetach(instanceId_t thrInstId);
/*!*************************************************************************************************
\fn thrStatus_t THR_SoftwareReset(instanceId_t thrInstID, bool_t factoryReset)
\brief This function is used to do a thread software reset.
\param [in] thrInstID Thread instance Id
\param [in] factoryReset If TRUE, the device will be reseted to factory
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_SoftwareReset(instanceId_t thrInstID, bool_t factoryReset);
/*!*************************************************************************************************
\fn void THR_FactoryReset(void)
\brief This function is used to reset device to factory default settings.
\return NONE
***************************************************************************************************/
void THR_FactoryReset(void);
/*!*************************************************************************************************
\fn void THR_TimeoutResetMcu(uint32_t timeoutMs, bool_t resetToFactory)
\brief This function is used to reset the device after a specific timeout.
\param [in] timeoutMs Time expressed in milliseconds units.
[in] resetToFactory If TRUE, the device will be reseted to factory
\return NONE
***************************************************************************************************/
void THR_TimeoutResetMcu(uint32_t timeoutMs, bool_t resetToFactory);
/*!*************************************************************************************************
\fn thrNeighbor_t * THR_GetParent(instanceId_t thrInstID)
\brief This is a public function used to get information about parent when node is an end device
and REED or about the attaching parent in case of a router. For a leader it will return NULL.
\param [in] thrInstID Thread instance ID
\return thrNeighbor_t* Pointer to neighbor structure.
***************************************************************************************************/
thrNeighbor_t *THR_GetParent(instanceId_t thrInstID);
/*!*************************************************************************************************
\fn thrNeighbor_t * THR_GetNeighborTable(uint32_t iCount)
\brief This function is used to get the neighbor from a given index from the neighbor table.
\param [in] iCount Entry in neighbor table
\return thrNeighbor_t * Pointer to neighbor structure.
**************************************************************************************************/
thrNeighbor_t *THR_GetNeighborTable(uint32_t iCount);
/*!*************************************************************************************************
\fn uint16_t THR_NeighborGetShortByExtAddr(uint8_t* pEui)
\brief This function is used to get a neighbor's short address by its extended address.
\param [in] pEui Pointer to neighbor's extended address
\return uint16_t Neighbor's short address
***************************************************************************************************/
uint16_t THR_NeighborGetShortByExtAddr(uint64_t *pEui);
/*!*************************************************************************************************
\fn thrNeighbor_t * THR_NeighborGetByShort(uint16_t shortAddr)
\brief This function is used to get a neighbor's information by its short address.
\param [in] shortAddr Neighbor's short address
\return thrNeighbor_t Neighbor info
***************************************************************************************************/
thrNeighbor_t *THR_NeighborGetByShort(uint16_t shortAddr);
/*!*************************************************************************************************
\fn thrRouterIdSet_t* THR_GetRouterIdSet(instanceId_t thrInstId)
\brief This function is used to get the thread router ID set.
\param [in] thrInstId Thread instance id
\return thrRouterIdSet_t* Pointer to router ID set structure
***************************************************************************************************/
thrRouterIdSet_t *THR_GetRouterIdSet(instanceId_t thrInstId);
/*!*************************************************************************************************
\fn thrStatus_t THR_LeaderRemoveRouterID(instanceId_t thrInstID, uint32_t routerID)
\brief This function is used to remove a router from network. It should be called only on the
leader node.
\param [in] thrInstID Thread instance ID
\param [in] routerID The ID of the router to be removed
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_LeaderRemoveRouterID(instanceId_t thrInstID, uint32_t routerID);
/*!*************************************************************************************************
\fn thrStatus_t THR_RouterLinkSync(instanceId_t thrInstID, bool_t bOnReset)
\brief This function will perform the "link synchronization after reset" or
"initial link synchronization" procedure. Must be called only on a router node.
\param [in] thrInstID Thread instance Id
\param [in] bOnReset Specify if the router should do the "Router synchronization after reset"
procedure or the "Initial Router synchronization" procedure.
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_RouterLinkSync(instanceId_t thrInstID, bool_t bOnReset);
/*!*************************************************************************************************
\fn thrStatus_t THR_ChildUpdateToParent(instanceId_t thrInstID)
\brief This function is used to send a ChildUpdate.Request to synchronize the parent with the
updated attributes (timeout period, node mode flags TLV).
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_ChildUpdateToParent(instanceId_t thrInstID);
/*!*************************************************************************************************
\fn thrStatus_t THR_SolicitGlobalAddress(instanceId_t thrInstID)
\brief This function solicits a global address from a DHCPv6 server.
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_SolicitGlobalAddress(instanceId_t thrInstID);
/*!*************************************************************************************************
\fn thrStatus_t THR_BrPrefixAttrAddEntry(instanceId_t thrInstID, thrOtaBrPrefixSet_t *pEntry)
\brief Add a Border router prefix attribute entry.
\param [in] thrInstID Thread instance Id
\param [in] pEntry Border router nwk data entry
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_BrPrefixAttrAddEntry(instanceId_t thrInstID, thrOtaBrPrefixSet_t *pEntry);
/*!*************************************************************************************************
\fn thrStatus_t THR_ServiceAttrAddEntry(instanceId_t thrInstID, thrLocalServiceSet_t *pEntry)
\brief Add a Border router service attribute entry.
\param [in] thrInstID Thread instance Id
\param [in] pEntry Border router service set entry
\return thrStatus_t Status
**************************************************************************************************/
thrStatus_t THR_ServiceAttrAddEntry(instanceId_t thrInstID, thrLocalServiceSet_t *pEntry);
/*!*************************************************************************************************
\fn thrStatus_t THR_BrPrefixAttrRemoveEntry(instanceId_t thrInstID,uint8_t prefixLength,
uint8_t *pPrefixValue)
\brief Remove Border Router prefix attribute entry.
\param [in] thrInstID Thread instance Id
\param [in] prefixLength Prefix size
\param [in] pPrefixValue Prefix value
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_BrPrefixAttrRemoveEntry(instanceId_t thrInstID, uint8_t prefixLength,
uint8_t *pPrefixValue);
/*!*************************************************************************************************
\fn thrStatus_t THR_BrServiceAttrRemoveEntry(instanceId_t thrInstID, uint8_t* pServiceData,
uint8_t serviceDataLen,uint8_t* pServerData,uint8_t serverDataLen)
\brief Remove Service attribute entry.
\param [in] thrInstID Thread instance Id
\param [in] pServiceData Pointer to service data
\param [in] serviceDataLen Service data size
\param [in] pServerData Pointer to server data
\param [in] serverDataLen Server data size
\return thrStatus_t Status
**************************************************************************************************/
thrStatus_t THR_BrServiceAttrRemoveEntry(instanceId_t thrInstID, uint8_t *pServiceData,
uint8_t serviceDataLen, uint8_t *pServerData, uint8_t serverDataLen);
/*!*************************************************************************************************
\fn void THR_BrPrefixAttrGetTable(instanceId_t thrInstID, uint8_t startIndex,
uint8_t reqNoOfElements, uint8_t *pRspNoOfElements, uint8_t *pOutData)
\brief Get the BR table, from startIndex to a maximum of reqNoOfElements.
\param [in] thrInstID Thread instance Id
\param [in] startIndex Start to search from this index
\param [in] reqNoOfElements Try to retrieve this many elements
\param [out] pRspNoOfElements Actual number of elements retrieved
\param [out] pOutData Data buffer to store the information
***************************************************************************************************/
void THR_BrPrefixAttrGetTable(instanceId_t thrInstID, uint8_t startIndex, uint8_t reqNoOfElements,
uint8_t *pRspNoOfElements, uint8_t *pOutData);
/*!*************************************************************************************************
\fn thrStatus_t THR_BrPrefixAttrRemoveAll(instanceId_t thrInstID)
\brief Remove all Border router prefix attribute entries.
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
**************************************************************************************************/
thrStatus_t THR_BrPrefixAttrRemoveAll(instanceId_t thrInstID);
/*!*************************************************************************************************
\fn thrStatus_t THR_BrPrefixAttrSync(instanceId_t thrInstID)
\brief This function is used to synchronize the Border Router prefixes with
the over-the-air network data information. After adding or removing more BR prefixes,
this function shall be called to propagate the global network data.
\param [in] thrInstID Thread instance Id
\return thrStatus_t Status
**************************************************************************************************/
thrStatus_t THR_BrPrefixAttrSync(instanceId_t thrInstID);
/*!*************************************************************************************************
\fn thrStatus_t THR_SendProactiveAddressNotification(instanceId_t thrInstId, ipAddr_t *pDestIpAddr)
\brief This function is used to send ADDR_NTF.ntf - Proactive Address Notification. This is useful
if the device has changed short address and knows there are devices that likely maintain an
address cache of that short address.
\param [in] thrInstId Thread instance ID
\param [in] pDestIpAddr Destination address: unicast or multicast
\return thrStatus_t Status
***************************************************************************************************/
thrStatus_t THR_SendProactiveAddressNotification(instanceId_t thrInstId, ipAddr_t *pDestIpAddr);
/*!*************************************************************************************************
\fn uint64_t THR_GenerateExtendedAddress(bool_t privacyAddr)
\brief This function generates a random extended mac address
\param [in] privacyAddr TRUE if the address should be a privacy address
\retval uint64_t extended mac address
***************************************************************************************************/
uint64_t THR_GenerateExtendedAddress(bool_t privacyAddr);
/*================================================================================================*/
#endif /* _THREAD_NETWORK_H */
/*!
** @}
*/
| 56.099839
| 154
| 0.554911
|
da426a30e55c6a510b27fa89a883fd6150f145cd
| 1,305
|
php
|
PHP
|
Configurator/CashOnDeliveryConfigurator.php
|
WellCommerce/PaymentBundle
|
7fdeb0b5155646f2b638082d2135bec05eb8be98
|
[
"MIT"
] | null | null | null |
Configurator/CashOnDeliveryConfigurator.php
|
WellCommerce/PaymentBundle
|
7fdeb0b5155646f2b638082d2135bec05eb8be98
|
[
"MIT"
] | null | null | null |
Configurator/CashOnDeliveryConfigurator.php
|
WellCommerce/PaymentBundle
|
7fdeb0b5155646f2b638082d2135bec05eb8be98
|
[
"MIT"
] | null | null | null |
<?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\PaymentBundle\Configurator;
use WellCommerce\Component\Form\Dependencies\DependencyInterface;
use WellCommerce\Component\Form\Elements\ElementInterface;
use WellCommerce\Component\Form\FormBuilderInterface;
/**
* Class CashOnDeliveryConfigurator
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
final class CashOnDeliveryConfigurator extends AbstractPaymentMethodConfigurator
{
public function getName() : string
{
return 'cash_on_delivery';
}
public function getInitializeTemplateName() : string
{
return 'WellCommercePaymentBundle:Front/CashOnDelivery:initialize.html.twig';
}
public function addConfigurationFields(FormBuilderInterface $builder, ElementInterface $fieldset, DependencyInterface $dependency)
{
$fieldset->addChild($builder->getElement('tip', [
'tip' => $this->trans('payment_method.cod.configuration'),
'dependencies' => [$dependency]
]));
}
}
| 29.659091
| 134
| 0.727203
|
d62182d7865956707f3b0ea8b3054d37c9f5b2a3
| 1,658
|
kt
|
Kotlin
|
goblin-core/src/main/java/org/goblinframework/core/event/timer/TimerEventGenerator.kt
|
xiaohaiz/goblinframework
|
b1db234912ceb23bdd81ac66a3bf61933b717d0b
|
[
"Apache-2.0"
] | 6
|
2019-11-29T09:26:34.000Z
|
2021-12-20T08:32:55.000Z
|
goblin-core/src/main/java/org/goblinframework/core/event/timer/TimerEventGenerator.kt
|
xiaohaiz/goblinframework
|
b1db234912ceb23bdd81ac66a3bf61933b717d0b
|
[
"Apache-2.0"
] | null | null | null |
goblin-core/src/main/java/org/goblinframework/core/event/timer/TimerEventGenerator.kt
|
xiaohaiz/goblinframework
|
b1db234912ceb23bdd81ac66a3bf61933b717d0b
|
[
"Apache-2.0"
] | 5
|
2019-11-27T13:38:50.000Z
|
2021-12-20T09:09:30.000Z
|
package org.goblinframework.core.event.timer
import org.goblinframework.core.schedule.ICronTaskManager
import org.goblinframework.core.service.GoblinManagedBean
import org.goblinframework.core.service.GoblinManagedObject
import java.util.*
@GoblinManagedBean("Core")
class TimerEventGenerator : GoblinManagedObject(), TimerEventGeneratorMXBean {
private val secondTimerEventGenerator = SecondTimerEventGenerator()
private val minuteTimerEventGenerator = MinuteTimerEventGenerator()
private val timers = Collections.synchronizedList(ArrayList<Timer>())
override fun initializeBean() {
ICronTaskManager.instance()?.run {
register(secondTimerEventGenerator)
register(minuteTimerEventGenerator)
} ?: kotlin.run {
val secondTimer = Timer("SecondTimerEventGenerator", true)
secondTimer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
secondTimerEventGenerator.execute()
}
}, 0, 1000)
timers.add(secondTimer)
val minuteTimer = Timer("MinuteTimerEventGenerator", true)
secondTimer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
minuteTimerEventGenerator.execute()
}
}, 0, 60000)
timers.add(minuteTimer)
}
logger.debug("{EventBus} Timer event generator started")
}
override fun disposeBean() {
ICronTaskManager.instance()?.run {
unregister(secondTimerEventGenerator.name())
unregister(minuteTimerEventGenerator.name())
} ?: kotlin.run {
timers.forEach { it.cancel() }
timers.clear()
}
logger.debug("{EventBus} Timer event generator disposed")
}
}
| 33.836735
| 78
| 0.718938
|
e707ca8a0f2538cb4f19c0ff8f74923da370c99e
| 3,649
|
php
|
PHP
|
app/Http/Controllers/sailorController.php
|
rockaveue/Harbor
|
62c2bb8fa5658eb597450f27d1e5728ee880b405
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/sailorController.php
|
rockaveue/Harbor
|
62c2bb8fa5658eb597450f27d1e5728ee880b405
|
[
"MIT"
] | null | null | null |
app/Http/Controllers/sailorController.php
|
rockaveue/Harbor
|
62c2bb8fa5658eb597450f27d1e5728ee880b405
|
[
"MIT"
] | null | null | null |
<?php
// B180910044 Battushig
namespace App\Http\Controllers;
use App\Models\ServiceHistory;
use Illuminate\Database\Eloquent\JsonEncodingException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Facades\App\Repository\Rank;
use Facades\App\Repository\Sailors;
use Facades\App\Repository\ServiceHistories;
use Facades\App\Repository\Vessels;
class sailorController extends Controller
{
//
public function registerForm(){
return view('sailor.registerSailor');
}
public function register(Request $request){
DB::insert('insert into sailor(`rank_id`, `sailor_name`, `date_of_birth`, `maritial_status`, `address`, `height`, `weight`, `shoe_size`, `blood_type`, `job_status`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [ $request->rank, $request->name, $request->birthDate, $request->marital, $request->homeAddress, $request->height, $request->weight, $request->shoeSize, $request->bloodType, 1]);
cache()->forget('SAILORS.ID');
return redirect()->back()->with('message', 'Амжилттай бүртгэлээ');
}
public function showServiceHistory(){
$history = ServiceHistories::all('id');
// $status = [1,2,4];
// $sailors = DB::table('Sailor')->where('rank_id', $job[0]->rank_id)->whereIn('job_status', $status)->get();
return view('sailor.historyService', compact('history'));
}
//
public function historyServiceOrder(Request $request){
if($request->ajax()){
$service = ServiceHistories::all($request->order);
return response()->json(['data' => $service]);
}
}
public function editSailor($sailor_id){
$sailor = DB::table('sailor')->where('id', '=', $sailor_id)->first();
// $sailor = json_encode($mysailor);
return view('sailor.sailor', compact('sailor'));
}
public function updateSailor(Request $request, $sailor_id){
// 'sailor_id' => ['required', 'boolean'],
// 'sailor_name' => ['required'],
$validated = $request->validate([
// 'job_status' => ['required', 'regex:/^(3|4|5)$/u'],
'job_status' => ['required', 'regex:/^(1|3|4|5)$/u'],
]);
DB::table('sailor')->where('id', $sailor_id)->update(['job_status' => $request->job_status]);
$myService = ServiceHistory::where('sailor_id','=', $sailor_id)->where('sign_off_date','=', null)->first();
// $service = json_decode($myService);
if($myService != null){
// return redirect()->back()->with('message', $myService->sign_on_port);
DB::table('service_history')->where('sailor_id', $sailor_id)->where('sign_off_date', null)->update(['sign_off_port' => $myService->sign_on_port, 'sign_off_date' => now()]);
}
// $service = json_decode($myService);
return redirect()->back()->with('message', 'Амжилттай ажилтныг мэдээллийг засварлалаа');
}
public function searchFromHistory(Request $request){
$ranks = Rank::all('id');
$vessel = Vessels::all('id');
if($request->ajax()){
if(in_array($request->selected, array("id"))){
$jsonResponse = ServiceHistory::where($request->selected, '>=', $request->mydata)->get();
}
else{
$jsonResponse = ServiceHistory::where($request->selected, $request->mydata)->orWhere($request->selected, 'like', '%'.$request->mydata.'%')->orderBy('id', 'asc')->get();
}
// Log::info($request->mydata);
return response()->json(['data' => $jsonResponse, 'ranks'=>$ranks, 'vessel'=>$vessel]);
}
}
}
| 44.5
| 390
| 0.599342
|
e417737f35378c7880607c5b12d9a7f242c2e9d1
| 1,526
|
cpp
|
C++
|
mbed/clock/src/clock_mbed.cpp
|
OpenNuvoton/mbed-client-for-aws
|
76ff1a07d4c5061463158d34650209799d08bdcd
|
[
"Apache-2.0"
] | null | null | null |
mbed/clock/src/clock_mbed.cpp
|
OpenNuvoton/mbed-client-for-aws
|
76ff1a07d4c5061463158d34650209799d08bdcd
|
[
"Apache-2.0"
] | null | null | null |
mbed/clock/src/clock_mbed.cpp
|
OpenNuvoton/mbed-client-for-aws
|
76ff1a07d4c5061463158d34650209799d08bdcd
|
[
"Apache-2.0"
] | null | null | null |
/*
* AWS IoT Device SDK for Embedded C 202012.01
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*/
#include "mbed.h"
extern "C"
{
#include "clock.h"
}
uint32_t Clock_GetTimeMs( void )
{
/* FIXME: Overflow after 49 days */
return (uint32_t) (Kernel::Clock::now().time_since_epoch().count());
}
void Clock_SleepMs( uint32_t sleepTimeMs )
{
ThisThread::sleep_for(std::chrono::milliseconds(sleepTimeMs));
}
| 38.15
| 83
| 0.74574
|
93e0483573312a768d0a443eed8ef92c6218ee60
| 11,606
|
cs
|
C#
|
Assets/AnyRPG/Engine/Core/System/Scripts/GameManager/SystemEventManager.cs
|
Scott004948/AnyRPGCore
|
6e83e73dc7fac3bae8bab2a55c729c530abd1b3e
|
[
"MIT"
] | 1
|
2021-02-16T07:51:26.000Z
|
2021-02-16T07:51:26.000Z
|
Assets/AnyRPG/Engine/Core/System/Scripts/GameManager/SystemEventManager.cs
|
Scott004948/AnyRPGCore
|
6e83e73dc7fac3bae8bab2a55c729c530abd1b3e
|
[
"MIT"
] | null | null | null |
Assets/AnyRPG/Engine/Core/System/Scripts/GameManager/SystemEventManager.cs
|
Scott004948/AnyRPGCore
|
6e83e73dc7fac3bae8bab2a55c729c530abd1b3e
|
[
"MIT"
] | 1
|
2021-02-15T12:14:49.000Z
|
2021-02-15T12:14:49.000Z
|
using AnyRPG;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace AnyRPG {
public class SystemEventManager : MonoBehaviour {
#region Singleton
private static SystemEventManager instance;
public static SystemEventManager MyInstance {
get {
if (instance == null) {
instance = FindObjectOfType<SystemEventManager>();
if (instance != null) {
instance.Init();
}
}
return instance;
}
}
void Init() {
if (singleEventDictionary == null) {
singleEventDictionary = new Dictionary<string, Action<string, EventParamProperties>>();
}
}
#endregion
private Dictionary<string, Action<string, EventParamProperties>> singleEventDictionary;
//public event System.Action OnPrerequisiteUpdated = delegate { };
public event System.Action OnQuestStatusUpdated = delegate { };
public event System.Action OnAfterQuestStatusUpdated = delegate { };
public event System.Action OnQuestObjectiveStatusUpdated = delegate { };
//public event System.Action<IAbility> OnAbilityCast = delegate { };
public event System.Action<BaseAbility> OnAbilityUsed = delegate { };
public event System.Action<BaseAbility> OnAbilityListChanged = delegate { };
public event System.Action<Skill> OnSkillListChanged = delegate { };
public event System.Action<int> OnLevelChanged = delegate { };
public event System.Action<CharacterClass, CharacterClass> OnClassChange = delegate { };
public event System.Action<string> OnInteractionStarted = delegate { };
public event System.Action<InteractableOptionComponent> OnInteractionWithOptionStarted = delegate { };
public event System.Action<Interactable> OnInteractionCompleted = delegate { };
public event System.Action<InteractableOptionComponent> OnInteractionWithOptionCompleted = delegate { };
public event System.Action<Item> OnItemCountChanged = delegate { };
public event System.Action OnBeginKeybind = delegate { };
public event System.Action OnEndKeybind = delegate { };
public event System.Action<Dialog> OnDialogCompleted = delegate { };
public event System.Action OnDeleteSaveData = delegate { };
public event System.Action<IAbilityCaster, CharacterUnit, int, string> OnTakeDamage = delegate { };
public event System.Action OnXPGained = delegate { };
// Player Manager
public event System.Action OnPlayerConnectionSpawn = delegate { };
public event System.Action OnBeforePlayerConnectionSpawn = delegate { };
public event System.Action OnPlayerConnectionDespawn = delegate { };
public event System.Action OnPlayerUnitDespawn = delegate { };
public event System.Action OnPlayerUMACreated = delegate { };
public event System.Action OnPlayerNameChanged = delegate { };
// Level manager
public event System.Action OnExitGame = delegate { };
// loot UI
public event System.Action OnTakeLoot = delegate { };
// equipment manager
public System.Action<Equipment, Equipment> OnEquipmentChanged = delegate { };
//public System.Action<Equipment> OnEquipmentRefresh = delegate { };
// UI
public System.Action OnPagedButtonsTransparencyUpdate = delegate { };
public System.Action OnInventoryTransparencyUpdate = delegate { };
// currency manager
public System.Action OnCurrencyChange = delegate { };
private void Awake() {
//Debug.Log("SystemGameManager.Awake()");
}
private void Start() {
//Debug.Log("SystemGameManager.Start()");
}
public static void StartListening(string eventName, Action<string, EventParamProperties> listener) {
Action<string, EventParamProperties> thisEvent;
if (MyInstance.singleEventDictionary.TryGetValue(eventName, out thisEvent)) {
//Add more event to the existing one
thisEvent += listener;
//Update the Dictionary
MyInstance.singleEventDictionary[eventName] = thisEvent;
} else {
//Add event to the Dictionary for the first time
thisEvent += listener;
MyInstance.singleEventDictionary.Add(eventName, thisEvent);
}
}
public static void StopListening(string eventName, Action<string, EventParamProperties> listener) {
if (MyInstance == null) return;
Action<string, EventParamProperties> thisEvent;
if (MyInstance.singleEventDictionary.TryGetValue(eventName, out thisEvent)) {
//Debug.Log("SystemEventManager.StopListening(" + eventName + ")");
//Remove event from the existing one
thisEvent -= listener;
//Update the Dictionary
MyInstance.singleEventDictionary[eventName] = thisEvent;
}
}
public static void TriggerEvent(string eventName, EventParamProperties eventParam) {
Action<string, EventParamProperties> thisEvent = null;
if (MyInstance.singleEventDictionary.TryGetValue(eventName, out thisEvent)) {
if (thisEvent != null) {
thisEvent.Invoke(eventName, eventParam);
} else {
//Debug.Log("SystemEventManager.TriggerEvent(" + eventName + "): event was null");
}
// OR USE instance.eventDictionary[eventName](eventParam);
}
}
public void NotifyOnCurrencyChange() {
OnCurrencyChange();
}
public void NotifyOnInventoryTransparencyUpdate() {
//Debug.Log("SystemEventManager.OnInventoryTransparencyUpdate()");
OnInventoryTransparencyUpdate();
}
public void NotifyOnPagedButtonsTransparencyUpdate() {
//Debug.Log("SystemEventManager.NotifyOnPagedButtonsTransparencyUpdate()");
OnPagedButtonsTransparencyUpdate();
}
public void NotifyOnQuestObjectiveStatusUpdated() {
OnQuestObjectiveStatusUpdated();
}
public void NotifyOnEquipmentChanged(Equipment newEquipment, Equipment oldEquipment) {
OnEquipmentChanged(newEquipment, oldEquipment);
}
public void NotifyOnClassChange(CharacterClass newCharacterClass, CharacterClass oldCharacterClass) {
OnClassChange(newCharacterClass, oldCharacterClass);
}
/*
public void NotifyOnEquipmentRefresh(Equipment newEquipment) {
OnEquipmentRefresh(newEquipment);
}
*/
public void NotifyOnTakeLoot() {
OnTakeLoot();
}
public void NotifyOnExitGame() {
OnExitGame();
}
public void NotifyOnPlayerConnectionSpawn() {
OnPlayerConnectionSpawn();
}
public void NotifyBeforePlayerConnectionSpawn() {
OnBeforePlayerConnectionSpawn();
}
public void NotifyOnPlayerConnectionDespawn() {
OnPlayerConnectionDespawn();
}
public void NotifyOnPlayerUnitDespawn() {
OnPlayerUnitDespawn();
}
public void NotifyOnPlayerUMACreated() {
OnPlayerUMACreated();
}
public void NotifyOnPlayerNameChanged() {
OnPlayerNameChanged();
}
public void NotifyOnXPGained() {
OnXPGained();
}
public void NotifyOnTakeDamage(IAbilityCaster source, CharacterUnit target, int damage, string abilityName) {
OnTakeDamage(source, target, damage, abilityName);
}
public void NotifyOnDeleteSaveData() {
OnDeleteSaveData();
}
public void NotifyOnOnBeginKeybind() {
OnBeginKeybind();
}
public void NotifyOnEndKeybind() {
OnEndKeybind();
}
public void NotifyOnDialogCompleted(Dialog dialog) {
OnDialogCompleted(dialog);
//OnPrerequisiteUpdated();
}
public void NotifyOnInteractionStarted(string interactableName) {
//Debug.Log("SystemEventManager.NotifyOnInteractionStarted(" + interactableName + ")");
OnInteractionStarted(interactableName);
}
public void NotifyOnInteractionWithOptionStarted(InteractableOptionComponent interactableOption) {
//Debug.Log("SystemEventManager.NotifyOnInteractionWithOptionStarted(" + interactableOption.DisplayName + ")");
OnInteractionWithOptionStarted(interactableOption);
}
public void NotifyOnInteractionCompleted(Interactable interactable) {
OnInteractionCompleted(interactable);
}
public void NotifyOnInteractionWithOptionCompleted(InteractableOptionComponent interactableOption) {
OnInteractionWithOptionCompleted(interactableOption);
}
public void NotifyOnLevelChanged(int newLevel) {
OnLevelChanged(newLevel);
//OnPrerequisiteUpdated();
}
public void NotifyOnQuestStatusUpdated() {
//Debug.Log("SystemEventManager.NotifyOnQuestStatusUpdated");
if (PlayerManager.MyInstance != null && PlayerManager.MyInstance.PlayerUnitSpawned == false) {
// STOP STUFF FROM REACTING WHEN PLAYER ISN'T SPAWNED
return;
}
OnQuestStatusUpdated();
OnAfterQuestStatusUpdated();
// having these two separate seems to be ok for now. the items that react to the first event do not react to the second, nor do they send prerequisiteupdates so no double calls should happen
//OnPrerequisiteUpdated();
}
public void NotifyOnAbilityListChanged(BaseAbility newAbility) {
//Debug.Log("SystemEventManager.NotifyOnAbilityListChanged(" + abilityName + ")");
OnAbilityListChanged(newAbility);
//OnPrerequisiteUpdated();
}
public void NotifyOnAbilityUsed(BaseAbility ability) {
//Debug.Log("SystemEventManager.NotifyAbilityused(" + ability.MyName + ")");
OnAbilityUsed(ability);
}
public void NotifyOnSkillListChanged(Skill skill) {
OnSkillListChanged(skill);
//OnPrerequisiteUpdated();
}
public void NotifyOnItemCountChanged(Item item) {
OnItemCountChanged(item);
}
/*
public void NotifyAbilityCast(IAbility ability) {
OnAbilityCast(ability);
}
*/
}
[System.Serializable]
public class CustomParam {
public EventParam eventParams = new EventParam();
public ObjectConfigurationNode objectParam = new ObjectConfigurationNode();
}
[System.Serializable]
public class EventParam {
public string StringParam = string.Empty;
public int IntParam = 0;
public float FloatParam = 0f;
public bool BoolParam = false;
}
[System.Serializable]
public class EventParamProperties {
public EventParam simpleParams = new EventParam();
public ObjectConfigurationNode objectParam = new ObjectConfigurationNode();
}
}
| 37.80456
| 203
| 0.634499
|
af7b4a51041750d4c309b1b45dbfc0242a812390
| 3,590
|
py
|
Python
|
motmot/utils/utils.py
|
motmot/utils
|
f2a9fd5aa2443e53c01b6d4ceb8dda09e1e2c2ae
|
[
"BSD-3-Clause"
] | 2
|
2016-05-09T15:51:32.000Z
|
2016-07-19T11:29:33.000Z
|
motmot/utils/utils.py
|
motmot/utils
|
f2a9fd5aa2443e53c01b6d4ceb8dda09e1e2c2ae
|
[
"BSD-3-Clause"
] | null | null | null |
motmot/utils/utils.py
|
motmot/utils
|
f2a9fd5aa2443e53c01b6d4ceb8dda09e1e2c2ae
|
[
"BSD-3-Clause"
] | null | null | null |
import os, sys, datetime, traceback
import subprocess # subprocess module included with python2.4, but should also be in current directory
import unittest
def under_svn_control(path):
version = get_svnversion(path)
if version == 'exported':
return False
return True
def get_svnversion_persistent(store_path,version_str):
svnversion = get_svnversion()
save_version = True
if svnversion == 'exported':
save_version = False
g={};l={}
execfile(store_path,g,l)
svnversion = l['__svnrev__'] # read from version file
version = version_str%{'svnversion':svnversion}
if save_version:
fd = open(store_path,'wb')
fd.write('#automatically generated on %s\n'%datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S +0000"))
fd.write('__svnrev__="%s"\n'%svnversion)
fd.write('__version__="%s"\n'%version)
fd.close()
return version
def get_svnversion(path=None):
if path is None:
path = os.path.abspath(os.curdir)
if sys.platform.startswith('win'):
prog=r'C:\Program Files\Subversion\bin\svnversion.exe'
else:
# XXX should really search PATH for svnversion
prog='/usr/bin/svnversion'
if not os.path.exists(prog):
prog='/usr/local/bin/svnversion'
if not os.path.exists(prog):
if os.path.exists( os.path.join(path,'.svn') ):
import warnings
warnings.warn("No svnversion program found at %s, pretending svnversion=1"%prog)
return "1"
else:
return "exported"
args = [prog,'-n','-c',path] # no newline, commited only
#print ' '.join(args)
res = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if res.wait():
errstr = res.stderr.read().strip()
if errstr.endswith('not versioned, and not exported'):
return 'not versioned, and not exported'
raise RuntimeError('"%s" returned error: "%s"'%(' '.join(args),errstr))
val = res.stdout.read()
colon_idx = val.find(':')
if colon_idx != -1:
val = val[colon_idx+1:]
if val.endswith('M'):
val = val[:-1]
if val.endswith('S'):
val = val[:-1]
return val
def get_motmot_test_suite():
def my_import(name):
# from http://docs.python.org/lib/built-in-funcs.html
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
module_names = ['motmot.cam_iface.tests',
'motmot.flytrax.tests',
'motmot.FastImage.tests',
'motmot.realtime_image_analysis.tests',
'motmot.FlyMovieFormat.tests',
] # name of module with get_test_suite() function
all_suites = []
for module_name in module_names:
try:
tests_sub_module = my_import(module_name)
except Exception,err:
print 'ERROR: Could not import module "%s" - skipping tests for this module'%module_name
traceback.print_exc(err)
continue
suite = tests_sub_module.get_test_suite()
all_suites.append( suite )
suite = unittest.TestSuite( all_suites )
return suite
def test_motmot():
suite = get_motmot_test_suite()
unittest.TextTestRunner(verbosity=2).run(suite)
def main():
print 'SVN version:',get_svnversion()
if __name__=='__main__':
main()
| 33.240741
| 119
| 0.598607
|
7aa1b867ce60ef91a77c5cea2fc2759f13c2f8e3
| 399
|
cs
|
C#
|
Dapper.Repository.Test/Extensions/ReflectionExtensions.cs
|
adamfoneil/Dapper.Repository
|
cb55a78cdf2399c5a7c40981d6c70e6173a7897e
|
[
"MIT"
] | 3
|
2021-08-22T05:57:51.000Z
|
2021-09-05T06:58:12.000Z
|
Dapper.Repository.Test/Extensions/ReflectionExtensions.cs
|
adamfoneil/Dapper.Repository
|
cb55a78cdf2399c5a7c40981d6c70e6173a7897e
|
[
"MIT"
] | 7
|
2021-08-14T16:15:50.000Z
|
2021-11-25T14:38:02.000Z
|
Dapper.Repository.Test/Extensions/ReflectionExtensions.cs
|
adamfoneil/Dapper.Repository
|
cb55a78cdf2399c5a7c40981d6c70e6173a7897e
|
[
"MIT"
] | null | null | null |
using System.Linq;
using System.Reflection;
namespace Dapper.Repository.Test
{
public static class ReflectionExtensions
{
public static Assembly GetReferencedAssembly(this Assembly assembly, string name)
{
var references = assembly.GetReferencedAssemblies().ToDictionary(item => item.Name);
return Assembly.Load(references[name]);
}
}
}
| 26.6
| 96
| 0.684211
|
b0b4c6803e5bb5ff25075c2782d1ea9fdb5ca4df
| 1,019
|
py
|
Python
|
src/table_tennis/tests/moveit_tests.py
|
sidharthsharma96/Tabletennis
|
c3d5bd09bc4f8deeb4961178222fd9c6fef6c649
|
[
"BSD-2-Clause"
] | 1
|
2021-03-30T12:22:13.000Z
|
2021-03-30T12:22:13.000Z
|
src/table_tennis/tests/moveit_tests.py
|
sidharthsharma96/Tabletennis
|
c3d5bd09bc4f8deeb4961178222fd9c6fef6c649
|
[
"BSD-2-Clause"
] | null | null | null |
src/table_tennis/tests/moveit_tests.py
|
sidharthsharma96/Tabletennis
|
c3d5bd09bc4f8deeb4961178222fd9c6fef6c649
|
[
"BSD-2-Clause"
] | null | null | null |
#!/usr/bin/env python
import sys
import rospy
import numpy as np
import geometry_msgs.msg
from moveit_commander import MoveGroupCommander, roscpp_initialize
from math import pi
rospy.init_node('moveit_tests', anonymous=False)
roscpp_initialize(sys.argv)
group = MoveGroupCommander('manipulator','/iiwa/robot_description','/iiwa')
print group.get_current_pose()
print group.get_current_joint_values()
joint_goal = np.zeros(7)
joint_goal[0] = 0
joint_goal[1] = -pi/4
joint_goal[2] = 0
joint_goal[3] = -pi/2
joint_goal[4] = 0
joint_goal[5] = pi/3
joint_goal[6] = 0
print group.go(joint_goal)
print group.get_current_pose()
print group.get_current_joint_values()
pose_goal = geometry_msgs.msg.Pose()
pose_goal.orientation.w = 1.0
pose_goal.position.x = 0.4
pose_goal.position.y = 0.1
pose_goal.position.z = 0.8
group.set_pose_target(pose_goal)
group.set_pose_target(pose_goal)
print group.go(wait=True)
group.stop()
group.clear_pose_targets()
print group.get_current_pose()
print group.get_current_joint_values()
| 22.152174
| 75
| 0.789009
|
38e244b89521a8133d66a14e285e33c4128ea91a
| 526
|
php
|
PHP
|
resources/views/admin/teachers.blade.php
|
tamzidpeace/Learning-Management-System
|
dd6a2e04d339e933eb4e4f45b6ffa049aa007349
|
[
"MIT"
] | 1
|
2020-10-09T16:05:47.000Z
|
2020-10-09T16:05:47.000Z
|
resources/views/admin/teachers.blade.php
|
tamzidpeace/Learning-Management-System
|
dd6a2e04d339e933eb4e4f45b6ffa049aa007349
|
[
"MIT"
] | 18
|
2020-09-20T12:36:28.000Z
|
2021-08-13T02:27:40.000Z
|
resources/views/admin/teachers.blade.php
|
tamzidpeace/Learning-Management-System
|
dd6a2e04d339e933eb4e4f45b6ffa049aa007349
|
[
"MIT"
] | null | null | null |
@extends('admin_layout')
@section('content')
<h1>Teachers</h1>
<table class="table table-bordered">
<tr class="info">
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Joined</th>
</tr>
@php
$count = 1;
@endphp
@foreach ($teachers as $teacher)
<tr>
<td> {{$count++}} </td>
<td> {{$teacher->name}} </td>
<td> {{$teacher->email}} </td>
<td> {{$teacher->created_at}} </td>
</tr>
@endforeach
</table>
@endsection
| 16.967742
| 43
| 0.467681
|
1f3e77cf9d8f94caf48a2da735431d52336ff46d
| 988
|
cs
|
C#
|
test/AvaloniaEdit.Tests/AvaloniaMocks/MockWindowingPlatform.cs
|
luthfiampas/AvaloniaEdit
|
24293dd42be120c338eff1072eebbcdaa481d979
|
[
"MIT"
] | 298
|
2017-05-04T16:38:00.000Z
|
2022-03-31T11:31:09.000Z
|
test/AvaloniaEdit.Tests/AvaloniaMocks/MockWindowingPlatform.cs
|
danipen/AvaloniaEdit
|
2496502f024d451450b5d7b398f75fc88af69510
|
[
"MIT"
] | 122
|
2017-04-23T20:32:45.000Z
|
2022-03-31T13:29:57.000Z
|
test/AvaloniaEdit.Tests/AvaloniaMocks/MockWindowingPlatform.cs
|
danipen/AvaloniaEdit
|
2496502f024d451450b5d7b398f75fc88af69510
|
[
"MIT"
] | 85
|
2017-04-23T16:54:44.000Z
|
2022-03-18T17:15:01.000Z
|
using System;
using Avalonia.Platform;
using Moq;
namespace AvaloniaEdit.AvaloniaMocks
{
public class MockWindowingPlatform : IWindowingPlatform
{
private readonly Func<IWindowImpl> _windowImpl;
private readonly Func<IPopupImpl> _popupImpl;
public MockWindowingPlatform(Func<IWindowImpl> windowImpl = null, Func<IPopupImpl> popupImpl = null)
{
_windowImpl = windowImpl;
_popupImpl = popupImpl;
}
public IWindowImpl CreateWindow()
{
return _windowImpl?.Invoke() ?? Mock.Of<IWindowImpl>(x => x.RenderScaling == 1);
}
public IWindowImpl CreateEmbeddableWindow()
{
throw new NotImplementedException();
}
public ITrayIconImpl CreateTrayIcon()
{
throw new NotImplementedException();
}
public IPopupImpl CreatePopup() => _popupImpl?.Invoke() ?? Mock.Of<IPopupImpl>(x => x.RenderScaling == 1);
}
}
| 28.228571
| 114
| 0.628543
|
b089456b7e0a2680f1cf00b7990c2aa6c5c2698c
| 710
|
py
|
Python
|
core/save/jsonSave.py
|
Pomb/Yahtzee
|
b15af59299ef68bdf44c56fb314514fe76d416ca
|
[
"MIT"
] | null | null | null |
core/save/jsonSave.py
|
Pomb/Yahtzee
|
b15af59299ef68bdf44c56fb314514fe76d416ca
|
[
"MIT"
] | null | null | null |
core/save/jsonSave.py
|
Pomb/Yahtzee
|
b15af59299ef68bdf44c56fb314514fe76d416ca
|
[
"MIT"
] | null | null | null |
#! /usr/bin/python
import os
import json
from .saveStrategy import SaveStrategy
class JsonSave(SaveStrategy):
def __init__(self):
self.savePath = "saves/save.json"
def load(self):
with open(self.savePath) as saveData:
return json.load(saveData)
def save(self, player):
totalScore = player.scoreSheet.total()
data = {}
if os.path.exists(self.savePath):
data = self.load()
if player.name in data:
data[player.name].append(totalScore)
else:
data[player.name] = [totalScore]
with open(self.savePath, 'w') as saveData:
json.dump(data, saveData, sort_keys=True, indent=4)
| 23.666667
| 63
| 0.604225
|
8e5619dc2ec6fed7c9cc3db755ce73ffd5327dba
| 411
|
js
|
JavaScript
|
lib/contact.js
|
drlukeangel/Pet-Finder-API-Javascript-Library
|
2f7d87e98f127f7a73c3d58be00024c2c4be7a59
|
[
"MIT"
] | 2
|
2017-05-02T03:14:44.000Z
|
2017-06-27T17:43:04.000Z
|
lib/contact.js
|
drlukeangel/Pet-Finder-API-Javascript-Library
|
2f7d87e98f127f7a73c3d58be00024c2c4be7a59
|
[
"MIT"
] | 2
|
2017-05-03T15:33:30.000Z
|
2021-06-25T15:15:53.000Z
|
lib/contact.js
|
drlukeangel/Pet-Finder-API-Javascript-Library
|
2f7d87e98f127f7a73c3d58be00024c2c4be7a59
|
[
"MIT"
] | 2
|
2017-08-20T22:48:45.000Z
|
2018-08-07T20:34:55.000Z
|
"use strict";
var Contact = function(data) {
this.email = data.email['$t'];
this.phone = data.phone['$t'];
this.fax = data.fax['$t'];
this.address1 = data.address1['$t'];
this.address2 = data.address2['$t'];
this.city = data.city['$t'];
this.state = data.state['$t'];
this.zip = data.zip['$t'];
return this;
};
module.exports = Contact;
| 27.4
| 42
| 0.523114
|
020612929287927557a65376d349b8788eb72c48
| 23,116
|
rs
|
Rust
|
build.rs
|
saturday06/effective-octo-fortnight
|
4704bea78b9aa483d1801a17d2d182fd0bd634d7
|
[
"BSD-2-Clause"
] | 7
|
2018-06-19T16:27:42.000Z
|
2020-05-22T04:35:57.000Z
|
build.rs
|
saturday06/rust-openh264
|
4704bea78b9aa483d1801a17d2d182fd0bd634d7
|
[
"BSD-2-Clause"
] | null | null | null |
build.rs
|
saturday06/rust-openh264
|
4704bea78b9aa483d1801a17d2d182fd0bd634d7
|
[
"BSD-2-Clause"
] | 2
|
2019-02-01T16:57:25.000Z
|
2021-08-04T01:40:11.000Z
|
extern crate bindgen;
extern crate bzip2;
extern crate cc;
extern crate glob;
extern crate libflate;
extern crate pkg_config;
extern crate reqwest;
extern crate tar;
extern crate url;
use bzip2::read::BzDecoder;
use glob::glob;
use libflate::gzip;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::Write;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use tar::Archive;
use url::Url;
struct Library {
dynamic: Option<bool>,
libs: Vec<String>,
link_paths: Vec<PathBuf>,
frameworks: Vec<String>,
framework_paths: Vec<PathBuf>,
include_paths: Vec<PathBuf>,
defines: HashMap<String, Option<String>>,
}
fn pkg_config_find_library(version: String, dynamic: Option<bool>) -> Option<Library> {
let mut config = pkg_config::Config::new();
config.atleast_version(&version);
if dynamic == Some(false) {
config.statik(true);
}
match config.probe("openh264") {
Ok(pkg_config_library) => Some(Library {
dynamic: dynamic,
libs: pkg_config_library.libs,
link_paths: pkg_config_library.link_paths,
frameworks: pkg_config_library.frameworks,
framework_paths: pkg_config_library.framework_paths,
include_paths: pkg_config_library.include_paths,
defines: pkg_config_library.defines,
}),
_ => None,
}
}
fn extract_source(out_dir_path: &Path, version: &str) -> String {
let archive_dir_path = out_dir_path.join("archive");
if !archive_dir_path.exists() {
std::fs::create_dir(&archive_dir_path)
.expect(&format!("Failed to create {:?}", archive_dir_path));
}
let archive_file_path = archive_dir_path.join(format!("openh264-{}.tar.gz", version));
if !archive_file_path.exists() {
let url = format!(
"https://github.com/cisco/openh264/archive/v{}.tar.gz",
version
);
let mut response = reqwest::get(&url).expect(&format!("Failed to download {}", url));
assert!(
response.status().is_success(),
format!("Request to {} doesn't succeed: {}", url, response.status())
);
let mut file_buf = Vec::new();
response
.copy_to(&mut file_buf)
.expect(&format!("Failed to download {}", url));
let mut file = File::create(&archive_file_path)
.expect(&format!("Failed to create {:?}", archive_file_path));
file.write_all(&file_buf).expect(&format!(
"Failed to save {} to {:?}",
url, archive_file_path
));
}
let mut archive_file =
File::open(&archive_file_path).expect(&format!("Failed to open {:?}", archive_file_path));
let mut gzip_decoder = gzip::Decoder::new(&mut archive_file).expect(&format!(
"Failed to create gzip decoder for {:?}",
archive_file_path
));
let mut tar_vec = Vec::new();
std::io::copy(&mut gzip_decoder, &mut tar_vec).expect(&format!(
"Failed to extract gzip archive {:?}",
archive_file_path
));
let mut tar_archive = Archive::new(&tar_vec[..]);
let tar_extract_dir_path = out_dir_path.join("src");
if tar_extract_dir_path.exists() {
std::fs::remove_dir_all(tar_extract_dir_path.clone()).expect(&format!(
"Failed to remove old archive extraction dir: {:?}",
tar_extract_dir_path.clone()
));
}
for mut entry in tar_archive
.entries()
.expect(&format!(
"Failed to read tar archive entries in {:?}",
archive_file_path
))
.map(|entry| {
entry.expect(&format!(
"Failed to extract tar archive entry in {:?}",
archive_file_path
))
}) {
entry
.unpack_in(tar_extract_dir_path.clone())
.expect(&format!(
"Failed to unpack file in {:?} for {:?}",
archive_file_path,
entry.path()
));
}
let openh264_src_dir_path = std::fs::read_dir(&tar_extract_dir_path)
.expect(&format!("Failed to read dir {:?}", tar_extract_dir_path))
.map(|entry| {
entry.expect(&format!(
"Failed to read dir entry in {:?}",
tar_extract_dir_path
))
})
.find(|entry| {
entry
.file_type()
.expect(&format!(
"Failed to read file type for {:?} in {:?}",
entry, tar_extract_dir_path
))
.is_dir()
}).expect(
&format!("Failed to find openh264 extracted src path in {:?}, perhaps downloaded archive {:?} was broken.",
tar_extract_dir_path, archive_file_path)
).path();
openh264_src_dir_path
.to_str()
.expect(&format!(
"Failed to extract rust string from {:?}",
openh264_src_dir_path
))
.to_string()
}
fn find_make() -> Option<String> {
["make", "gmake"]
.iter()
.find(|make| match Command::new(make).arg("--version").status() {
Ok(status) => status.success(),
_ => false,
})
.map(|s| s.to_string())
}
fn make_unix_path(path_str: &str) -> String {
if cfg!(windows) {
path_str.replace("\\", "/")
} else {
path_str.to_owned()
}
}
fn build_library(out_dir_path: &Path, version: &str, dynamic: Option<bool>) -> Library {
let mut library = Library {
dynamic: dynamic,
libs: vec!["openh264".to_owned()],
link_paths: Vec::new(),
frameworks: Vec::new(),
framework_paths: Vec::new(),
include_paths: Vec::new(),
defines: HashMap::new(),
};
let prefix_dir_path = out_dir_path.join("prefix");
let prefix_include_dir_path = prefix_dir_path.join("include");
let prefix_lib_dir_path = prefix_dir_path.join("lib");
library.include_paths.push(prefix_include_dir_path.clone());
library.link_paths.push(prefix_lib_dir_path.clone());
let done_file_path = prefix_dir_path.join("build_done");
if done_file_path.exists() {
return library;
}
let openh264_src_dir_path_str = extract_source(out_dir_path, version);
if prefix_dir_path.exists() {
std::fs::remove_dir_all(prefix_dir_path.clone()).expect(&format!(
"Failed to remove old installation prefix dir: {:?}",
prefix_dir_path.clone()
));
}
std::fs::create_dir(&prefix_dir_path)
.expect(&format!("Failed to create {:?}", prefix_dir_path));
let prefix_dir_str = prefix_dir_path.to_str().expect(&format!(
"Failed to extract rust string from {:?}",
prefix_dir_path
));
let make = find_make().expect("Unable find `make' or `gmake' command");
let make_task = &(if dynamic == Some(false) {
"install-static"
} else {
"install-shared"
}).to_owned();
let make_status = Command::new(&make)
.current_dir(&openh264_src_dir_path_str)
.args(&vec![
&format!("PREFIX={}", make_unix_path(prefix_dir_str)),
make_task,
])
.status()
.expect(&format!(
"Failed to execute `make {}' for openh264",
make_task
));
if !make_status.success() {
panic!("Failed to execute `make {}', status code: {}. Please see around the build output dir {:?}", make_task, make_status, out_dir_path);
}
let _ = File::create(&done_file_path).expect(&format!("Failed to create {:?}", done_file_path));
library
}
fn find_prebuilt_library(
full_version: &str,
major_version: &str,
) -> (String, String, String, String) {
if cfg!(target_os = "android") {
(
format!("libopenh264-{}-android19.so.bz2", full_version),
format!("libopenh264.so"),
format!("libopenh264.so"),
format!("libopenh264.so"),
)
} else if cfg!(all(target_os = "linux", target_arch = "x86")) {
(
format!(
"libopenh264-{}-linux32.{}.so.bz2",
full_version, major_version
),
format!("libopenh264.so.{}", full_version),
format!("libopenh264.so.{}", major_version),
format!("libopenh264.so"),
)
} else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
(
format!(
"libopenh264-{}-linux64.{}.so.bz2",
full_version, major_version
),
format!("libopenh264.so.{}", full_version),
format!("libopenh264.so.{}", major_version),
format!("libopenh264.so"),
)
} else if cfg!(all(target_os = "macos", target_arch = "x86")) {
(
format!(
"libopenh264-{}-osx32.{}.dylib.bz2",
full_version, major_version
),
format!("libopenh264.{}.dylib", full_version),
format!("libopenh264.{}.dylib", major_version),
format!("libopenh264.dylib"),
)
} else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
(
format!(
"libopenh264-{}-osx64.{}.dylib.bz2",
full_version, major_version
),
format!("libopenh264.{}.dylib", full_version),
format!("libopenh264.{}.dylib", major_version),
format!("libopenh264.dylib"),
)
} else if cfg!(all(target_os = "windows", target_arch = "x86")) {
(
format!("openh264-{}-win32.dll.bz2", full_version),
format!("openh264.dll"),
format!("openh264.dll"),
format!("openh264.dll"),
)
} else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
(
format!("openh264-{}-win64.dll.bz2", full_version),
format!("openh264.dll"),
format!("openh264.dll"),
format!("openh264.dll"),
)
} else {
panic!("Prebuilt binary is not found in github releases. Please install libopenh264 manually or enable `build' cargo feature to build from source.");
}
}
fn download_library(out_dir_path: &Path, full_version: &str, major_version: &str) -> Library {
let mut library = Library {
dynamic: Some(true),
libs: vec!["openh264".to_owned()],
link_paths: Vec::new(),
frameworks: Vec::new(),
framework_paths: Vec::new(),
include_paths: Vec::new(),
defines: HashMap::new(),
};
let prefix_dir_path = out_dir_path.join("prefix");
let prefix_include_dir_path = prefix_dir_path.join("include");
let prefix_lib_dir_path = prefix_dir_path.join("lib");
library.include_paths.push(prefix_include_dir_path.clone());
library.link_paths.push(prefix_lib_dir_path.clone());
let done_file_path = prefix_dir_path.join("download_done");
if done_file_path.exists() {
return library;
}
let (archive_file_name, full_version_so_name, major_version_so_name, short_so_name) =
find_prebuilt_library(full_version, major_version);
let url_str = format!(
"https://github.com/cisco/openh264/releases/download/v{}/{}",
full_version, archive_file_name
);
let openh264_src_dir_path_str = extract_source(out_dir_path, full_version);
let archive_dir_path = out_dir_path.join("archive");
if !archive_dir_path.exists() {
std::fs::create_dir(&archive_dir_path)
.expect(&format!("Failed to create {:?}", archive_dir_path));
}
let url = Url::parse(&url_str).expect(&format!("Failed to parse url string: {}", url_str));
let archive_file_path = archive_dir_path.join(archive_file_name);
if !archive_file_path.exists() {
let mut response =
reqwest::get(url.as_str()).expect(&format!("Failed to download {}", url));
assert!(
response.status().is_success(),
format!("request for {} doesn't succeed: {}", url, response.status())
);
let mut file_buf = Vec::new();
response
.copy_to(&mut file_buf)
.expect(&format!("Failed to download {}", url));
let mut file = File::create(&archive_file_path)
.expect(&format!("Failed to create {:?}", archive_file_path));
file.write_all(&file_buf).expect(&format!(
"Failed to save {} to {:?}",
url, archive_file_path
));
}
let mut archive_file =
File::open(&archive_file_path).expect(&format!("Failed to open {:?}", archive_file_path));
let mut bzip2_decoder = BzDecoder::new(&mut archive_file);
let mut so_vec = Vec::new();
std::io::copy(&mut bzip2_decoder, &mut so_vec).expect(&format!(
"Failed to extract bzip2 archive {:?}",
archive_file_path
));
if prefix_dir_path.exists() {
std::fs::remove_dir_all(prefix_dir_path.clone()).expect(&format!(
"Failed to remove old installation prefix dir: {:?}",
prefix_dir_path.clone()
));
}
std::fs::create_dir(&prefix_dir_path)
.expect(&format!("Failed to create {:?}", prefix_dir_path));
std::fs::create_dir(&prefix_lib_dir_path)
.expect(&format!("Failed to create {:?}", prefix_lib_dir_path));
let so_path = prefix_lib_dir_path.join(&full_version_so_name);
let mut so_file = File::create(&so_path).expect(&format!(
"Failed to create prebuilt binary to {:?}",
so_path
));
so_file
.write_all(&so_vec)
.expect(&format!("Failed to save prebuilt binary to {:?}", so_path));
#[cfg(unix)]
{
let metadata = so_file
.metadata()
.expect(&format!("Failed to read permissions for {:?}", so_path));
let mut permissions = metadata.permissions();
let mut mode = permissions.mode();
mode |= 0o100;
if mode & 0o040 != 0 {
mode |= 0o010;
}
if mode & 0o004 != 0 {
mode |= 0o001;
}
permissions.set_mode(mode);
so_file.set_permissions(permissions).expect(&format!(
"Failed to set permission {} to {:?}",
mode, so_path,
));
}
for &(target_so_name, link_so_name) in [
(&full_version_so_name, &major_version_so_name),
(&major_version_so_name, &short_so_name),
].iter()
{
if target_so_name == link_so_name {
continue;
}
let target_path = prefix_lib_dir_path.join(target_so_name);
let link_path = prefix_lib_dir_path.join(link_so_name);
#[cfg(unix)]
{
std::os::unix::fs::symlink(&target_path, &link_path).expect(&format!(
"Failed to create symlink target: {:?}, linkname: {:?}",
so_path, link_path
));
}
#[cfg(not(unix))]
{
panic!(
"Internal logic error: Using symlink on non-unix target: {:?}, linkname: {:?}",
target_path, link_path
);
}
}
let prefix_dir_str = prefix_dir_path.to_str().expect(&format!(
"Failed to extract rust string from {:?}",
prefix_dir_path,
));
match find_make() {
Some(make) => {
let make_status = Command::new(make)
.current_dir(&openh264_src_dir_path_str)
.args(&vec![
format!("PREFIX={}", make_unix_path(prefix_dir_str)),
"install-headers".to_owned(),
])
.status()
.expect("Failed to execute `make install-headers' for openh264");
if !make_status.success() {
panic!("Failed to execute `make install-headers', status code: {}. Please see around the build output dir {:?}", make_status, out_dir_path);
}
}
None => {
if !prefix_include_dir_path.exists() {
std::fs::create_dir(&prefix_include_dir_path)
.expect(&format!("Failed to create {:?}", prefix_include_dir_path));
}
let prefix_include_wels_dir_path = prefix_include_dir_path.join("wels");
if !prefix_include_wels_dir_path.exists() {
std::fs::create_dir(&prefix_include_wels_dir_path).expect(&format!(
"Failed to create {:?}",
prefix_include_wels_dir_path
));
}
// https://github.com/cisco/openh264/blob/v1.7.0/Makefile#L290-L292
let src_headers_glob = format!("{}/codec/api/svc/codec*.h", openh264_src_dir_path_str);
for entry_result in glob(&src_headers_glob).expect(&format!(
"Failed to create installation header list with glob: {}",
src_headers_glob
)) {
let entry = entry_result.expect(&format!(
"Failed to read installation header entry in {}",
src_headers_glob
));
let from_path: &Path = entry.as_ref();
let to_path = prefix_include_wels_dir_path.clone().join(
from_path.file_name().expect(&format!(
"Failed to extract rust string from path: {:?}",
from_path
)),
);
std::fs::copy(&from_path, &to_path)
.expect(&format!("Failed to copy {:?} to {:?}", from_path, to_path));
}
}
}
if cfg!(target_env = "msvc") {
let build = cc::Build::new();
let compiler = build.get_compiler();
let prefix_lib_dir_path_str = prefix_lib_dir_path.to_str().expect(&format!(
"Failed to extract rust string from path: {:?}",
prefix_lib_dir_path
));
let compiler_path = compiler.path();
let compiler_dir_path = compiler_path.parent().expect(&format!(
"Couldn't find compiler base directory. compiler path = {:?}",
compiler_path
));
let lib_command = compiler_dir_path.join("lib");
let lib_status = Command::new(&lib_command)
.args(&vec![
&format!("/DEF:{}\\openh264.def", openh264_src_dir_path_str),
&format!("/OUT:{}\\openh264.lib", prefix_lib_dir_path_str),
])
.status()
.expect(&format!(
"Failed to execute `{:?}' to generate openh264.lib",
lib_command
));
if !lib_status.success() {
panic!("Failed to execute `{:?}', status code: {}. Please see around the build output dir {:?}", lib_command, lib_status,
out_dir_path);
}
}
let _ = File::create(&done_file_path).expect(&format!("Failed to create {:?}", done_file_path));
library
}
fn find_or_build_library(out_dir_path: &Path) -> Library {
let full_version = "1.7.0";
let major_version = "4";
let dynamic = if cfg!(feature = "static") {
Some(false)
} else {
None
};
if cfg!(feature = "build") {
if cfg!(windows) {
panic!("feature `build' is currently unimplemented for Windows");
}
return build_library(out_dir_path, full_version, dynamic);
}
match (env::var("OPENH264_INCLUDE_PATH"), env::var("OPENH264_LIBRARY_PATH")) {
(Ok(include_path), Ok(library_path)) => {
return Library {
dynamic: dynamic,
libs: vec!["openh264".to_owned()],
link_paths: vec![PathBuf::from(library_path)],
frameworks: Vec::new(),
framework_paths: Vec::new(),
include_paths: vec![PathBuf::from(include_path)],
defines: HashMap::new(),
}
},
(Ok(_), _) => panic!("Environment variable `OPENH264_INCLUDE_PATH' exists but `OPENH264_LIBRARY_PATH' doesn't exist. Both variables are required."),
(_, Ok(_)) => panic!("Environment variable `OPENH264_LIBRARY_PATH' exists but `OPENH264_INCLUDE_PATH' doesn't exist. Both variables are required."),
_ => {},
}
match pkg_config_find_library(full_version.to_owned(), dynamic) {
Some(library) => library,
None => {
if dynamic == Some(false) {
panic!("Unable to find openh264 library")
}
let library = download_library(out_dir_path, full_version, major_version);
print_linker_flags(&library);
library
}
}
}
fn generate_bindings(library: &Library, out_dir_path: &Path) {
let mut bindgen_builder = bindgen::Builder::default()
.header("wrapper.h")
.derive_default(true)
.prepend_enum_name(false);
for include_path in &library.include_paths {
bindgen_builder = bindgen_builder.clang_arg(format!(
"-I{}",
include_path.to_str().expect(&format!(
"Failed to extract rust string from include_path={:?}",
include_path
))
));
}
for (define_key, define_value_option) in &library.defines {
bindgen_builder = if let Some(define_value) = define_value_option {
bindgen_builder.clang_args(&["-D", &format!("{}={}", define_key, define_value)])
} else {
bindgen_builder.clang_args(&["-D", define_key])
}
}
let bindings_file = out_dir_path.join("bindings.rs");
bindgen_builder
.generate()
.expect("Unable to generate bindings")
.write_to_file(&bindings_file)
.expect(&format!("Couldn't write bindings to {:?}", &bindings_file));
}
fn print_linker_flags(library: &Library) {
for framework_path in &library.framework_paths {
println!(
"cargo:rustc-link-search=framework={}",
framework_path.to_str().expect(&format!(
"Failed to extract rust string from framework_path={:?}",
framework_path
))
);
}
for framework in &library.frameworks {
println!("cargo:rustc-link-lib=framework={}", framework);
}
for link_path in &library.link_paths {
println!(
"cargo:rustc-link-search=native={}",
link_path.to_str().expect(&format!(
"Failed to extract rust string from link_path={:?}",
link_path
))
);
}
for lib in &library.libs {
if library.dynamic == Some(false) {
println!("cargo:rustc-link-lib=static={}", lib);
} else {
println!("cargo:rustc-link-lib=dylib={}", lib);
}
}
}
fn main() {
let out_dir = env::var("OUT_DIR").expect("Failed to find environment variable OUT_DIR");
let out_dir_path = Path::new(&out_dir);
let library = find_or_build_library(&out_dir_path);
generate_bindings(&library, &out_dir_path);
}
| 35.399694
| 157
| 0.566404
|
3877496ad12f4b5226587daea284751d054c727b
| 1,459
|
php
|
PHP
|
app/Models/Order.php
|
dttoan432/Laravel_21_Project
|
065fe8cab09875f34fcdac0decbc071cfa05fe56
|
[
"MIT"
] | null | null | null |
app/Models/Order.php
|
dttoan432/Laravel_21_Project
|
065fe8cab09875f34fcdac0decbc071cfa05fe56
|
[
"MIT"
] | null | null | null |
app/Models/Order.php
|
dttoan432/Laravel_21_Project
|
065fe8cab09875f34fcdac0decbc071cfa05fe56
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasFactory;
protected $table = 'orders';
protected $fillable = [
'user_id',
'total_price',
'status',
'phone',
'address',
'name',
'note',
];
public function products()
{
return $this->belongsToMany(Product::class)->withPivot(['price', 'quantity']);
}
public function user()
{
return $this->belongsTo(User::class);
}
const ORDER_WAIT = 0;
const ORDER_CONFIRM = 1;
const ORDER_SHIPPING = 2;
const ORDER_RETURN = 3;
const ORDER_FINISH = 4;
public static $status_text = [
self::ORDER_WAIT => 'Chưa xử lý',
self::ORDER_CONFIRM => 'Đã xác nhận',
self::ORDER_SHIPPING => 'Đang giao hàng',
self::ORDER_RETURN => 'Hủy đơn hàng',
self::ORDER_FINISH => 'Đã giao hàng',
];
public function getStatusTextAttribute(){
if ($this->status == 0){
return 'Chưa xử lý';
} elseif ($this->status == 1){
return 'Đã xác nhận';
} elseif ($this->status == 2){
return 'Đang giao hàng';
} elseif ($this->status == 3){
return 'Hủy đơn hàng';
} else {
return 'Đã hoàn thành';
}
}
}
| 23.532258
| 86
| 0.52913
|
d050bad08ff6baef46c9ae0185335ff561245b97
| 2,077
|
cpp
|
C++
|
PrettyEngine/src/engine/Events/Input.cpp
|
cristi191096/Pretty_Engine
|
53a5d305b3de5786223e3ad6775199dbc7b5e90c
|
[
"Apache-2.0"
] | null | null | null |
PrettyEngine/src/engine/Events/Input.cpp
|
cristi191096/Pretty_Engine
|
53a5d305b3de5786223e3ad6775199dbc7b5e90c
|
[
"Apache-2.0"
] | null | null | null |
PrettyEngine/src/engine/Events/Input.cpp
|
cristi191096/Pretty_Engine
|
53a5d305b3de5786223e3ad6775199dbc7b5e90c
|
[
"Apache-2.0"
] | 1
|
2021-04-16T09:10:46.000Z
|
2021-04-16T09:10:46.000Z
|
#include "pepch.h"
#include "Input.h"
#include "engine\Core\Context.h"
#include "Platform\OpenGL\GLInput.h"
namespace PrettyEngine {
bool InternalInput::m_Keys[MAX_KEYS];
bool InternalInput::m_MouseButtons[MAX_BUTTONS];
uint InternalInput::m_Mods = 0;
Vector2 InternalInput::m_MousePosition = Vector2(0, 0);
namespace Internal {
InternalInput* InternalInput::s_InputInstance = nullptr;
InternalInput::InternalInput()
{
ClearKeys();
ClearButtons();
}
InternalInput * InternalInput::GetInstance()
{
return s_InputInstance;
}
void InternalInput::Init()
{
if (s_InputInstance == nullptr)
{
switch (Context::GetRenderAPI())
{
case RenderAPI::OPENGL:
s_InputInstance = new GLInput();
break;
}
}
}
void InternalInput::ClearKeys()
{
for (int i = 0; i < MAX_KEYS; i++) {
m_Keys[i] = false;
}
}
void InternalInput::ClearButtons()
{
for (int i = 0; i < MAX_BUTTONS; i++)
m_MouseButtons[i] = false;
}
}
const Vector2& InternalInput::GetMousePosition() const
{
return m_MousePosition;
}
bool Input::GetKey(keyCode key)
{
return m_Keys[key];
}
bool Input::GetKeyUp(keyCode key)
{
if (!IsKeyPressed(key))
return true;
return false;
}
bool Input::GetKeyDown(keyCode key)
{
if (IsKeyPressed(key))
return true;
return false;
}
bool Input::IsModOn(uint mod)
{
if (m_Mods & mod)
return true;
return false;
}
bool Input::GetMouseButton(Mouse button)
{
return m_MouseButtons[button];
}
bool Input::GetMouseButtonDown(Mouse button)
{
if (IsButtonPressed(button))
return true;
return false;
}
bool Input::GetMouseButtonUp(Mouse button)
{
if (!IsButtonPressed(button))
return true;
return false;
}
bool Input::IsKeyPressed(keyCode k)
{
if (k >= MAX_KEYS || k == keyCode::NONE)
return false;
if (m_Keys[k] == true) {
return true;
}
return m_Keys[k];
}
bool Input::IsButtonPressed(Mouse b)
{
if (b >= MAX_BUTTONS)
return false;
return m_MouseButtons[b];
}
}
| 14.423611
| 58
| 0.649013
|
dfb9dc8141ad1872131c1642d5cff0b19719ccf0
| 14,072
|
cs
|
C#
|
SymbolSource.Processor/PackageProcessor.cs
|
gareth-evans/SymbolSource
|
39359803c319cdc8d94df612cd1b3e96a83f7614
|
[
"Apache-2.0"
] | 33
|
2018-03-19T15:08:57.000Z
|
2022-01-16T16:39:13.000Z
|
SymbolSource.Processor/PackageProcessor.cs
|
gareth-evans/SymbolSource
|
39359803c319cdc8d94df612cd1b3e96a83f7614
|
[
"Apache-2.0"
] | 19
|
2018-03-23T05:57:08.000Z
|
2022-03-31T02:09:09.000Z
|
SymbolSource.Processor/PackageProcessor.cs
|
gareth-evans/SymbolSource
|
39359803c319cdc8d94df612cd1b3e96a83f7614
|
[
"Apache-2.0"
] | 17
|
2018-03-19T12:23:22.000Z
|
2021-12-11T07:38:30.000Z
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NuGet;
using SymbolSource.Contract;
using SymbolSource.Contract.Processor;
using SymbolSource.Contract.Scheduler;
using SymbolSource.Contract.Storage;
using SymbolSource.Contract.Support;
using SymbolSource.Processor.Legacy;
using SymbolSource.Processor.Legacy.Projects;
using SymbolSource.Processor.Notifier;
using SymbolSource.Processor.Processor;
using IPackageFile = NuGet.IPackageFile;
using PackageName = SymbolSource.Contract.PackageName;
namespace SymbolSource.Processor
{
internal class ExceptionStatus
{
public ExceptionStatus(Exception exception)
{
if (exception != null)
{
Message = exception.Message;
StackTrace = exception.StackTrace;
}
}
public string Message { get; private set; }
public string StackTrace { get; private set; }
}
internal class SourceStatus
{
public SourceName SourceName { get; private set; }
public bool Stored { get; set; }
public ExceptionStatus Exception { get; set; }
public SourceStatus(SourceName sourceName)
{
SourceName = sourceName;
}
public bool Check(bool expectedStored)
{
return Stored == expectedStored && Exception == null;
}
}
internal class SymbolStatus
{
public SymbolName SymbolName { get; private set; }
public SourceStatus[] SourceStatuses { get; set; }
public bool Stored { get; set; }
public ExceptionStatus Exception { get; set; }
public SymbolStatus(SymbolName symbolName)
{
SymbolName = symbolName;
}
public bool Check(bool expectedStored)
{
return Stored == expectedStored && Exception == null
&& (SourceStatuses == null || SourceStatuses.All(s => s.Check(expectedStored)));
}
}
internal class ImageStatus
{
public ImageName ImageName { get; private set; }
public SymbolStatus SymbolStatus { get; set; }
public ExceptionStatus Exception { get; set; }
public ImageStatus(ImageName imageName)
{
ImageName = imageName;
}
public bool Check(bool expectedStored)
{
return /*Stored == expectedStored &&*/ Exception == null
&& (SymbolStatus == null || SymbolStatus.Check(expectedStored));
}
}
internal class ImageStatusFile
{
public ImageStatusFile(string filePath, ImageStatus imageStatus)
{
FilePath = Path.ChangeExtension(filePath, ".smbsrc");
ImageStatus = imageStatus;
}
public string FilePath { get; set; }
public ImageStatus ImageStatus { get; set; }
}
public class PackageProcessor : IPackageProcessor
{
private readonly IPackageProcessorConfiguration configuration;
private readonly IStorageService storage;
private readonly ISchedulerService scheduler;
private readonly INotifierService notifier;
private readonly ISupportService support;
private readonly IAddInfoBuilder addInfoBuilder;
private readonly IPdbStoreManager pdbStoreManager;
private readonly IFileCompressor fileCompressor;
public PackageProcessor(
IPackageProcessorConfiguration configuration,
IStorageService storage,
ISchedulerService scheduler,
INotifierService notifier,
ISupportService support,
IAddInfoBuilder addInfoBuilder,
IPdbStoreManager pdbStoreManager,
IFileCompressor fileCompressor)
{
this.configuration = configuration;
this.storage = storage;
this.scheduler = scheduler;
this.notifier = notifier;
this.support = support;
this.addInfoBuilder = addInfoBuilder;
this.pdbStoreManager = pdbStoreManager;
this.fileCompressor = fileCompressor;
}
public async Task Process(PackageMessage message)
{
var before = DateTime.Now;
try
{
switch (message.PackageState)
{
case PackageState.New:
await Queue(message);
break;
case PackageState.IndexingQueued:
await Index(message);
break;
case PackageState.DeletingQueued:
await Delete(message);
break;
case PackageState.Partial:
await Retry(message);
break;
case PackageState.Original:
case PackageState.Indexing:
case PackageState.Succeded:
case PackageState.Deleting:
case PackageState.Deleted:
throw new NotSupportedException();
default:
throw new ArgumentOutOfRangeException("packageState", message.PackageState, null);
}
support.TrackRequest(message.PackageState, before, DateTime.Now - before, true);
}
catch (Exception e)
{
support.TrackException(e, new { message });
support.TrackRequest(message.PackageState, before, DateTime.Now - before, false);
throw;
}
}
private async Task<bool> ProcessPackage(UserInfo userInfo, string feedName, PackageName packageName, PackageState packageState, PackageState damagedPackageState, Func<IPackageStorageItem, Task<IPackageStorageItem>> tryWithPackageItemBefore, Func<IPackageStorageItem, ZipPackage, Task> tryWithPackage, Func<IPackageStorageItem, Task> tryWithPackageItemAfter)
{
var feed = storage.GetFeed(feedName);
var packageItem = feed.GetPackage(null, packageState, packageName);
var traceName = packageItem.ToString();
try
{
packageItem = await tryWithPackageItemBefore(packageItem);
if (packageItem == null)
throw new Exception(string.Format("Missing package {0}", traceName));
using (var packageStream = await packageItem.Get())
{
if (packageStream == null)
throw new Exception(string.Format("Missing package data {0}", traceName));
var package = new ZipPackage(packageStream);
await tryWithPackage(packageItem, package);
}
await tryWithPackageItemAfter(packageItem);
return true;
}
catch (Exception e)
{
support.TrackException(e, new { packageName });
Trace.TraceError("Unexpected error while processing package {0}:\n{1}", traceName, e);
notifier.Damaged(userInfo, packageName).Wait();
if (packageItem != null)
packageItem.Move(damagedPackageState, packageName).Wait();
return false;
}
}
private async Task Queue(PackageMessage message)
{
var task = new QueuePackageTask();
PackageName newPackageName = null;
// ReSharper disable RedundantArgumentName
await ProcessPackage(
message.UserInfo, message.FeedName, message.PackageName,
PackageState.New, PackageState.DamagedNew,
tryWithPackageItemBefore: async pi =>
{
Trace.TraceInformation("Reading package {0}", pi);
return pi;
},
tryWithPackage: async (pi, p) =>
{
newPackageName = await task.ReadName(message.UserInfo, p);
await notifier.Starting(message.UserInfo, newPackageName);
},
tryWithPackageItemAfter: async pi =>
{
Trace.TraceInformation("Queueing package {0} as {1}", pi, newPackageName);
if (await pi.Copy(PackageState.Original, newPackageName) == null)
throw new Exception(string.Format("Failed to copy package {0} to {1}", pi, newPackageName));
if (await pi.Move(PackageState.IndexingQueued, newPackageName) == null)
throw new Exception(string.Format("Failed to move package {0} to {1}", pi, newPackageName));
message.PackageState = PackageState.IndexingQueued;
message.PackageName = newPackageName;
await scheduler.Signal(message);
Trace.TraceInformation("Finished queueing package {0} as {1}", pi, newPackageName);
});
// ReSharper restore RedundantArgumentName
}
private async Task Index(PackageMessage message)
{
var task = new IndexPackageTask(configuration, notifier, support, addInfoBuilder, pdbStoreManager, fileCompressor);
// ReSharper disable RedundantArgumentName
await ProcessPackage(
message.UserInfo, message.FeedName, message.PackageName,
PackageState.IndexingQueued, PackageState.DamagedIndexing,
tryWithPackageItemBefore: async pi =>
{
Trace.TraceInformation("Indexing package {0}", pi);
// ReSharper disable once ConvertToLambdaExpression
return await pi.Move(PackageState.Indexing, pi.Name);
},
tryWithPackage: async (pi, p) =>
{
await task.IndexPackage(message.UserInfo, pi.Feed, pi.Name, pi, p);
},
tryWithPackageItemAfter: async pi =>
{
await pi.Delete();
Trace.TraceInformation("Finished indexing package {0}", pi);
});
// ReSharper restore RedundantArgumentName
}
private async Task Delete(PackageMessage message)
{
var task = new DeletePackageTask(notifier, support);
// ReSharper disable RedundantArgumentName
await ProcessPackage(
message.UserInfo, message.FeedName, message.PackageName,
PackageState.DeletingQueued, PackageState.DamagedDeleting,
tryWithPackageItemBefore: async pi =>
{
Trace.TraceInformation("Deleting package {0}", pi);
// ReSharper disable once ConvertToLambdaExpression
return await pi.Move(PackageState.Deleting, pi.Name);
},
tryWithPackage: async (pi, p) =>
{
await task.DeletePackage(message.UserInfo, pi.Feed, pi.Name, pi, p);
}, tryWithPackageItemAfter: async pi =>
{
await pi.Delete();
Trace.TraceInformation("Finished deleting package {0}", pi);
});
// ReSharper restore RedundantArgumentName
}
private async Task Retry(PackageMessage message)
{
var deleteTask = new DeletePackageTask(notifier, support);
// ReSharper disable RedundantArgumentName
if (!await ProcessPackage(
message.UserInfo, message.FeedName, message.PackageName,
PackageState.Partial, PackageState.DamagedDeleting,
tryWithPackageItemBefore: async pi =>
{
Trace.TraceInformation("Retrying package {0}", pi);
return await pi.Move(PackageState.Deleting, pi.Name);
},
tryWithPackage: async (pi, p) =>
{
await deleteTask.DeletePackage(message.UserInfo, pi.Feed, pi.Name, pi, p);
},
tryWithPackageItemAfter: async pi =>
{
await pi.Delete();
}))
// ReSharper restore RedundantArgumentName
{
return;
}
var indexTask = new IndexPackageTask(configuration, notifier, support, addInfoBuilder, pdbStoreManager, fileCompressor);
// ReSharper disable RedundantArgumentName
if (!await ProcessPackage(
message.UserInfo, message.FeedName, message.PackageName,
PackageState.Original, PackageState.DamagedIndexing,
tryWithPackageItemBefore: async pi =>
{
return await pi.Copy(PackageState.Indexing, pi.Name);
},
tryWithPackage: async (pi, p) =>
{
await indexTask.IndexPackage(message.UserInfo, pi.Feed, pi.Name, pi, p);
},
tryWithPackageItemAfter: async pi =>
{
Trace.TraceInformation("Finished retrying package {0}", pi);
await pi.Delete();
}))
// ReSharper restore RedundantArgumentName
{
return;
}
}
}
}
| 39.307263
| 366
| 0.552231
|
af49db3ee998dd6f879653fc097b6fc1a11f176f
| 6,979
|
py
|
Python
|
src/autobridge/Floorplan/Bipartition.py
|
mfkiwl/AutoBridge
|
1f428c271d2e338f39ea7478d81c66636c419670
|
[
"MIT"
] | null | null | null |
src/autobridge/Floorplan/Bipartition.py
|
mfkiwl/AutoBridge
|
1f428c271d2e338f39ea7478d81c66636c419670
|
[
"MIT"
] | null | null | null |
src/autobridge/Floorplan/Bipartition.py
|
mfkiwl/AutoBridge
|
1f428c271d2e338f39ea7478d81c66636c419670
|
[
"MIT"
] | null | null | null |
import logging
from typing import Dict, List, Optional
from mip import Model, Var, minimize, xsum, BINARY, INTEGER, OptimizationStatus
from autobridge.Floorplan.Utilities import *
from autobridge.Opt.DataflowGraph import Vertex
from autobridge.Opt.Slot import Slot
from autobridge.Opt.SlotManager import SlotManager, Dir
from autobridge.util import get_mip_model_silent
_logger = logging.getLogger('autobridge')
class Bipartition:
def __init__(
self,
curr_v2s: Dict[Vertex, Slot],
grouping_constraints: List[List[Vertex]],
pre_assignments: Dict[Vertex, Slot],
slot_manager: SlotManager,
):
"""
grouping_constraints: which modules should be assigned to the same slot
pre_assignment: pre-determined module -> slot mapping
"""
self.grouping_constraints = grouping_constraints
self.pre_assignment = pre_assignments
self.slot_manager = slot_manager
self.set_curr_v2s(curr_v2s)
def set_curr_v2s(self, curr_v2s: Dict[Vertex, Slot]):
self.curr_v2s = curr_v2s
self.curr_s2v = invert_v2s(curr_v2s)
def get_bipartition(
self,
direction: Dir,
max_usage_ratio: float,
max_search_time: int,
) -> Optional[Dict[Vertex, Slot]]:
"""
bi-partition all the current slots
"""
m = get_mip_model_silent()
v2var = self._create_ilp_vars(m)
self._add_opt_goal(m, v2var, direction)
# area constraints for each child slot
self._add_area_constraints(m, v2var, direction, max_usage_ratio)
self._add_pre_assignment(m, v2var, direction)
self._add_grouping_constraints(m, v2var)
m.optimize(max_seconds=max_search_time)
next_v2s = self._get_partition_result(m, v2var, direction)
if not next_v2s:
_logger.debug(f'bi-partioning failed with usage ratio {max_usage_ratio}')
return next_v2s
def get_bipartition_adjust_ratio(
self,
direction: Dir,
ref_usage_ratio: float,
usage_ratio_delta: float = 0.02,
max_search_time: int = 120
) -> Dict[Vertex, Slot]:
"""
increase the ref_usage_ratio until succeed. Each time increment usage_ratio_delta
and retry.
"""
curr_usage_ratio = ref_usage_ratio
while 1:
_logger.debug(f'Attempt bipartition with a usage ratio of {curr_usage_ratio} and max search time {max_search_time}s')
next_v2s = self.get_bipartition(direction, curr_usage_ratio, max_search_time)
if not next_v2s:
curr_usage_ratio += usage_ratio_delta
curr_usage_ratio = round(curr_usage_ratio, 2)
else:
break
_logger.info(f'Finish bipartition with a usage ratio of {curr_usage_ratio}')
return next_v2s
############################################################################
def _create_ilp_vars(self, m: Model):
"""
create a binary var for each vertex
the var indicates if a vertex is assigned to the up/right child slot or the down/left child slot
"""
v2var: Dict[str, Var] = {} # str -> [mip_var]
for v in self.curr_v2s.keys():
v2var[v] = m.add_var(var_type=BINARY, name=f'{v.name}_x')
return v2var
def _add_opt_goal(
self,
m: Model,
v2var: Dict[str, Var],
direction: Dir
) -> None:
"""
minimize the weighted sum over all edges
"""
edge_list = get_all_edges(list(self.curr_v2s.keys()))
e2cost_var = {
e: m.add_var(var_type=INTEGER, name=f'e_cost_{e.name}') for e in edge_list
}
def _get_loc_after_partition(v: Vertex):
if direction == Dir.vertical:
return self.curr_v2s[v].getQuarterPositionX() + v2var[v] * self.curr_v2s[v].getHalfLenX()
elif direction == Dir.horizontal:
return self.curr_v2s[v].getQuarterPositionY() + v2var[v] * self.curr_v2s[v].getHalfLenY()
else:
assert False
for e, cost_var in e2cost_var.items():
m += cost_var >= _get_loc_after_partition(e.src) - _get_loc_after_partition(e.dst)
m += cost_var >= _get_loc_after_partition(e.dst) - _get_loc_after_partition(e.src)
m.objective = minimize( xsum(cost_var * e.width for e, cost_var in e2cost_var.items()) )
def _add_area_constraints(
self,
m: Model,
v2var: Dict[str, Var],
direction: Dir,
max_usage_ratio: float,
) -> None:
for s, v_group in self.curr_s2v.items():
bottom_or_left, up_or_right = self.slot_manager.partitionSlotByHalf(s, direction)
for r in RESOURCE_TYPES:
v_var_list = [v2var[v] for v in v_group]
area_list = [v.getVertexAndInboundFIFOArea()[r] for v in v_group]
I = range(len(v_group))
# for the up/right child slot (if mod_x is assigned 1)
m += xsum( v_var_list[i] * area_list[i] for i in I ) <= up_or_right.getArea()[r] * max_usage_ratio
# for the down/left child slot (if mod_x is assigned 0)
m += xsum( (1-v_var_list[i]) * area_list[i] for i in I ) <= bottom_or_left.getArea()[r] * max_usage_ratio
def _add_pre_assignment(
self,
m: Model,
v2var: Dict[str, Var],
direction: Dir,
) -> None:
"""
user specifies that certain Vertices must be assigned to certain slots
"""
for v, expect_slot in self.pre_assignment.items():
curr_slot = self.curr_v2s[v]
bottom_or_left, up_or_right = self.slot_manager.partitionSlotByHalf(curr_slot, direction)
if bottom_or_left.containsChildSlot(expect_slot):
_logger.debug(f'[specified assignment] {v.name} assigned to bottom/left')
m += v2var[v] == 0
elif up_or_right.containsChildSlot(expect_slot):
_logger.debug(f'[specified assignment] {v.name} assigned to up/right')
m += v2var[v] == 1
else:
_logger.warning(f'Potential wrong constraints from user: {v.name} -> {expect_slot.getName()}')
assert False
def _add_grouping_constraints(
self,
m: Model,
v2var: Dict[str, Var],
) -> None:
"""
user specifies that certain Vertices must be assigned to the same slot
"""
for grouping in self.grouping_constraints:
for i in range(1, len(grouping)):
m += v2var[grouping[0]] == v2var[grouping[i]]
def _get_partition_result(
self,
m: Model,
v2var: Dict[str, Var],
direction: Dir,
) -> Optional[Dict[Vertex, Slot]]:
"""
extract the results from the ILP solver
"""
if m.status != OptimizationStatus.OPTIMAL and m.status != OptimizationStatus.FEASIBLE:
return {}
# create new mapping
next_v2s = {}
for s, v_group in self.curr_s2v.items():
bottom_or_left, up_or_right = self.slot_manager.partitionSlotByHalf(s, direction)
for v in v_group:
# if v is assigned to 0-half in the i-th solution
if round(v2var[v].x) == 0:
next_v2s[v] = bottom_or_left
# if v is assigned to 1-half in the i-th solution
elif round(v2var[v].x) == 1:
next_v2s[v] = up_or_right
else:
assert False, v2var[v].x
return next_v2s
| 32.310185
| 123
| 0.659837
|
a34920b6b0b8384246fb499e8622d337d00ad45b
| 354
|
h
|
C
|
Succinct/Succinct.h
|
wrightak/Succinct
|
c8af737026df6814e91463a81f4f76052bd258b1
|
[
"MIT"
] | null | null | null |
Succinct/Succinct.h
|
wrightak/Succinct
|
c8af737026df6814e91463a81f4f76052bd258b1
|
[
"MIT"
] | null | null | null |
Succinct/Succinct.h
|
wrightak/Succinct
|
c8af737026df6814e91463a81f4f76052bd258b1
|
[
"MIT"
] | null | null | null |
#import <UIKit/UIKit.h>
//! Project version number for Succinct.
FOUNDATION_EXPORT double SuccinctVersionNumber;
//! Project version string for Succinct.
FOUNDATION_EXPORT const unsigned char SuccinctVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Succinct/PublicHeader.h>
| 35.4
| 133
| 0.805085
|
df4e0d7332efad976c05b903489633c5d419ccc6
| 522
|
cs
|
C#
|
src/ComponentTask/IExceptionHandler.cs
|
BastianBlokland/componenttask-unity
|
cac8d3f5492455858fab0bc040997cef5891fb7e
|
[
"MIT"
] | 19
|
2019-07-30T00:34:48.000Z
|
2022-03-09T02:10:46.000Z
|
src/ComponentTask/IExceptionHandler.cs
|
BastianBlokland/componenttask-unity
|
cac8d3f5492455858fab0bc040997cef5891fb7e
|
[
"MIT"
] | 2
|
2019-11-25T07:13:39.000Z
|
2019-11-27T06:54:02.000Z
|
src/ComponentTask/IExceptionHandler.cs
|
BastianBlokland/componenttask-unity
|
cac8d3f5492455858fab0bc040997cef5891fb7e
|
[
"MIT"
] | 3
|
2019-11-26T07:44:56.000Z
|
2021-04-07T15:28:34.000Z
|
using System;
namespace ComponentTask
{
/// <summary>
/// Interface for a exception handler.
/// </summary>
/// <remarks>
/// Can be used to log exceptions when using a custom <see cref="ComponentTask.LocalTaskRunner"/>.
/// </remarks>
public interface IExceptionHandler
{
/// <summary>
/// Handle the exception that was thrown.
/// </summary>
/// <param name="exception">Exception that was thrown.</param>
void Handle(Exception exception);
}
}
| 26.1
| 102
| 0.603448
|
b045b4e0f16d198969bb4c6b5662b18f7b067d9f
| 9,251
|
py
|
Python
|
drums/_sock.py
|
drums-project/drums-core
|
753ee04cea92a4f780ec36c30bca1a66380e1e50
|
[
"Apache-2.0"
] | 1
|
2019-05-01T13:13:53.000Z
|
2019-05-01T13:13:53.000Z
|
drums/_sock.py
|
drums-project/drums-core
|
753ee04cea92a4f780ec36c30bca1a66380e1e50
|
[
"Apache-2.0"
] | null | null | null |
drums/_sock.py
|
drums-project/drums-core
|
753ee04cea92a4f780ec36c30bca1a66380e1e50
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Copyright 2013 Mani Monajjemi (AutonomyLab, Simon Fraser University)
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.
"""
"""
Socket monitoring daemon
"""
from _common import *
import pcapy
"""
The [base] SocektMonitor will maintain a filter list (of strings). The libpcap
callback will be fired if any packet matches any of filters. There is no
internal book-keeping to determine which part of the filter caused the
callback to fire.
"""
from struct import *
from socket import ntohs
__eth_length = 14
__any_length = 16
#SLL: http://www.tcpdump.org/linktypes/LINKTYPE_LINUX_SLL.html
LINK_LAYER_ETH = 1
LINK_LAYER_SLL = 2
def parse_header(packet, link_layer):
tcp_sport, tcp_dport, udp_sport, udp_dport = None, None, None, None
eth_protocol = 0
if link_layer == LINK_LAYER_ETH:
pad = __eth_length
eth_header = packet[0:pad]
eth = unpack('!6s6sH', eth_header)
eth_protocol = ntohs(eth[2])
elif link_layer == LINK_LAYER_SLL:
pad = __any_length
any_header = packet[0:pad]
anyp = unpack("!HHH8sH", any_header)
eth_protocol = ntohs(anyp[4])
else:
raise Exception("Datalink type not supported: %s" % link_layer)
if eth_protocol == 8:
ip_header = packet[pad:20+pad]
iph = unpack('!BBHHHBBH4s4s', ip_header)
version_ihl = iph[0]
#version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
#ttl = iph[5]
protocol = iph[6]
#s_addr = socket.inet_ntoa(iph[8]);
#d_addr = socket.inet_ntoa(iph[9]);
if protocol == 6:
t = iph_length + pad
tcp_header = packet[t:t+20]
tcph = unpack('!HHLLBBHHH', tcp_header)
tcp_sport = tcph[0]
tcp_dport = tcph[1]
#sequence = tcph[2]
#acknowledgement = tcph[3]
#doff_reserved = tcph[4]
#tcph_length = doff_reserved >> 4
elif protocol == 17:
u = iph_length + pad
#udph_length = 8
udp_header = packet[u:u+8]
udph = unpack('!HHHH', udp_header)
udp_sport = udph[0]
udp_dport = udph[1]
#length = udph[2]
#checksum = udph[3]
return tcp_sport, tcp_dport, udp_sport, udp_dport
def tasktuple_to_filterstr(task):
"""
task = (proto, src/dst, port), e.g ("UDP", "dst", 53) or ("TCP", "", 80)
"""
proto, direction, port = task
proto = proto.lower()
direction = direction.lower()
port = int(port)
if not proto in ["tcp", "udp"]:
raise ValueError("[in %s] Protocol %s not supported." % (self, proto))
if not direction in ["src", "dst", ""]:
raise ValueError(
"[in %s] Direction %s not supported." % (self, direction))
if not port > 0:
raise ValueError("[in %s] Invalid port number %s" % (self, port))
return (proto, direction, port, "%s %s port %s" % (proto, direction, port))
def populate_data(data, port, len):
if port in data:
data[port] += len
#else:
# data[port] = len
class SocketMonitor(TaskBase):
def __init__(
self, result_queue, default_interval, inet,
name="drums_sockmonitor"):
TaskBase.__init__(self, result_queue, default_interval, name)
self.inet = inet
# TODO: suid
# TODO: Find good values for to_ms
self.pc = pcapy.open_live(self.inet, 100, False, 900)
self.pc.setnonblock(False)
datalink = self.pc.datalink()
if pcapy.DLT_EN10MB == datalink:
self.link_layer = LINK_LAYER_ETH # Ethernet
elif pcapy.DLT_LINUX_SLL == datalink:
self.link_layer = LINK_LAYER_SLL # Any
else:
raise Exception("Datalink type not supported: %s" % datalink)
self.logger.info("Datalink is : %d", self.link_layer)
self.filter_str = ""
self.packets_per_callback = 0
self.data = dict()
self.data['tcp'] = dict()
self.data['udp'] = dict()
self.meta = dict()
self.meta['tcp'] = dict()
self.meta['udp'] = dict()
def update_filters(self):
filters = ["(%s)" % (f,) for f in self.task_map.keys()]
self.filter_str = " or ".join(filters)
self.logger.debug("Updating pcap filter to `%s`" % (self.filter_str,))
#print "Setting filter to %s" % self.filter_str
self.pc.setfilter(self.filter_str)
def register_task_core(self, task, meta=''):
assert isinstance(meta, basestring)
proto, direction, port, filter_str = tasktuple_to_filterstr(task)
port = str(port)
self.task_map[filter_str] = True
if not port in self.meta[proto]:
self.meta[proto][port] = set()
self.data[proto][port] = 0
if meta:
self.meta[proto][port].add(meta)
self.update_filters()
return DrumsError.SUCCESS
def remove_task_core(self, task, meta=''):
try:
proto, direction, port, filter_str = tasktuple_to_filterstr(task)
# Empty meta will delete all data
if meta:
self.meta[proto][str(port)].remove(meta)
if not self.meta[proto][str(port)] or not meta:
del self.task_map[filter_str]
del self.data[proto][str(port)]
del self.meta[proto][str(port)]
self.update_filters()
return DrumsError.SUCCESS
except KeyError:
self.logger.error("Error removing socket filter: %s" % (task,))
return DrumsError.NOTFOUND
def do(self):
# TODO: Check if re-implementing the IMPacket would improve performance
def process_callback(hdr, packetdata):
self.packets_per_callback += 1
packet_len = hdr.getlen()
tcp_sport, tcp_dport, udp_sport, udp_dport = parse_header(
packetdata, self.link_layer)
if tcp_sport and tcp_dport:
populate_data(self.data['tcp'], str(tcp_sport), packet_len)
populate_data(self.data['tcp'], str(tcp_dport), packet_len)
elif udp_sport and udp_dport:
populate_data(self.data['udp'], str(udp_sport), packet_len)
populate_data(self.data['udp'], str(udp_dport), packet_len)
else:
self.logger.warning("Parse Header failed for packet.")
# Link layer decoder
#packet = self.decoder.decode(packetdata)
#return
# Get the higher layer packet (ip:datalink)
#ippacket = packet.child()
# TCP or UDP?
#tpacket = ippacket.child()
# It is not possible now to determine which part of the filter string
# caused the callback to fire. So `tcp dst port 80` or `tcp src port 80`
# are not distinguishable. The hack here is to cache the port numbers only
# and see which port address field matches the cached list.
#if isinstance(tpacket, ImpactPacket.TCP):
#pass
#populate_data(self.data['tcp'], str(tpacket.get_th_sport()), packet_len)
#populate_data(self.data['tcp'], str(tpacket.get_th_dport()), packet_len)
#elif isinstance(tpacket, ImpactPacket.UDP):
#pass
#populate_data(self.data['udp'], str(tpacket.get_uh_sport()), packet_len)
#populate_data(self.data['udp'], str(tpacket.get_uh_dport()), packet_len)
if not self.task_map:
return
self.packets_per_callback = 0
# The only non-blocking way I found to work with pcapy
self.pc.dispatch(0, process_callback)
#self.logger.info(
# "packets per callback: %d" % (self.packets_per_callback, ))
_data = dict()
#_data['__ppc__'] = self.packets_per_callback
timestamp = time.time()
#_data = dict()
#_data['sock'] = self.data
#_data['meta'] = self.meta
#pprint(_data)
# TODO: The first packet should be sent (0, 0, ...)
if self.packets_per_callback > 0:
for proto in ['tcp', 'udp']:
for port, bytes in self.data[proto].items():
_key = "%s:%s" % (proto, port)
_data[_key] = {
'timestamp': timestamp, 'bytes': bytes,
'meta': list(self.meta[proto][port])}
try:
self.result_queue.put(_data)
except Full:
self.logger.error(
"[in %s] Output queue is full in" % (self, ))
finally:
pass
| 35.856589
| 89
| 0.585991
|
b93a0cce79bb41bca966964877a7a7da270a4339
| 4,413
|
swift
|
Swift
|
ios/LiftTests/ExerciseSessionManagerTests.swift
|
muvr/open-muvr
|
eb2e6ed1966ce9f2dc56dc2bc2e3a7f80a300d2c
|
[
"Apache-2.0"
] | 59
|
2015-03-08T17:32:22.000Z
|
2018-07-08T04:04:29.000Z
|
ios/LiftTests/ExerciseSessionManagerTests.swift
|
muvr/open-muvr
|
eb2e6ed1966ce9f2dc56dc2bc2e3a7f80a300d2c
|
[
"Apache-2.0"
] | 1
|
2015-03-29T17:11:11.000Z
|
2015-03-29T17:11:11.000Z
|
ios/LiftTests/ExerciseSessionManagerTests.swift
|
muvr/open-muvr
|
eb2e6ed1966ce9f2dc56dc2bc2e3a7f80a300d2c
|
[
"Apache-2.0"
] | 17
|
2015-03-12T18:40:50.000Z
|
2018-03-10T00:49:33.000Z
|
import Foundation
import XCTest
/*
class ExerciseSessionManagerTests : XCTestCase {
let manager = ExerciseSessionManager.sharedInstance
let defaultMultiPacket: NSData = NSData()
override func setUp() {
LiftServer.sharedInstance.setBaseUrlString("http://localhost:12345")
manager.removeAllOfflineSessions()
XCTAssert(manager.listOfflineSessions().isEmpty, "Existing offline sessions found")
}
private func findSessionWithProps(props: Exercise.SessionProps) -> Bool {
let c = manager.listOfflineSessions().filter { x in
x.props.muscleGroupKeys == props.muscleGroupKeys &&
abs(x.props.startDate.timeIntervalSinceDate(props.startDate)) < 0.01 &&
x.props.intendedIntensity == props.intendedIntensity
}.count
return c == 1
}
func testOfflineFromStart() {
let props = Exercise.SessionProps(startDate: NSDate(), muscleGroupKeys: ["arms"], intendedIntensity: 1.0)
let s = manager.managedSession(ExerciseSession(id: NSUUID(), props: props), isOfflineFromStart: true)
// even before submitting, we must see this offline session
XCTAssert(findSessionWithProps(props), "Expected session not found")
// three lots of file submissions later...
s.submitData(defaultMultiPacket) { $0.cata({ _ in XCTFail("Offline must not fail")}, const(())) }
s.submitData(defaultMultiPacket) { $0.cata({ _ in XCTFail("Offline must not fail")}, const(())) }
s.submitData(defaultMultiPacket) { $0.cata({ _ in XCTFail("Offline must not fail")}, const(())) }
// the session should still be there
XCTAssert(findSessionWithProps(props), "Expected session not found")
// end it
s.end(const(()))
// the session should still be there
XCTAssert(findSessionWithProps(props), "Expected session not found")
}
func testOnlineStartThenImmediatelyOffline() {
let props = Exercise.SessionProps(startDate: NSDate(), muscleGroupKeys: ["arms"], intendedIntensity: 1.0)
let s = manager.managedSession(ExerciseSession(id: NSUUID(), props: props), isOfflineFromStart: false)
// even before submitting, we must see this offline session
XCTAssert(findSessionWithProps(props), "Expected session not found")
// the first submission fails—no server
s.submitData(defaultMultiPacket) { $0.cata(const(()), { _ in XCTFail("First failing request must not fail")}) }
// we're now offline, and the next submit must succeed
s.submitData(defaultMultiPacket) { $0.cata({ _ in XCTFail("Offline must not fail")}, const(())) }
// end it
s.end(const(()))
// the session should still be there
XCTAssert(findSessionWithProps(props), "Expected session not found")
}
func testFailureHalfWay() {
let server = HTTPServer()
server.setPort(12345)
server.setConnectionClass(RunningSessionHttpConnection)
server.start(nil)
let props = Exercise.SessionProps(startDate: NSDate(), muscleGroupKeys: ["arms"], intendedIntensity: 1.0)
let s = manager.managedSession(ExerciseSession(id: NSUUID(), props: props), isOfflineFromStart: false)
// even before submitting, we must see this offline session
XCTAssert(findSessionWithProps(props), "Expected session not found")
// the first submission works
s.submitData(defaultMultiPacket) { $0.cata({ _ in XCTFail("Offline must not fail")}, const(())) }
// the next submission must fail
s.submitData(defaultMultiPacket) { $0.cata(const(()), { _ in XCTFail("Online must fail")}) }
server.stop(false)
// we're now offline, and the next submit must succeed
s.submitData(defaultMultiPacket) { $0.cata({ _ in XCTFail("Offline must not fail")}, const(())) }
// end it
s.end(const(()))
// the session should still be there
XCTAssert(findSessionWithProps(props), "Expected session not found")
}
}
class RunningSessionHttpConnection : HTTPConnection {
override func httpResponseForMethod(method: String!, URI path: String!) -> NSObject {
return HTTPDataResponse(data: NSData())
}
}
*/
| 44.13
| 119
| 0.64446
|
f8e71edc1ab1c64eaf3e36f4d8a170b8454018da
| 11,368
|
hpp
|
C++
|
src/architecture/routine/basic_block.hpp
|
AhmedZero/VTIL-Python
|
e9df05d6cd614ace762f0db29660ede1b5b51682
|
[
"BSD-3-Clause"
] | null | null | null |
src/architecture/routine/basic_block.hpp
|
AhmedZero/VTIL-Python
|
e9df05d6cd614ace762f0db29660ede1b5b51682
|
[
"BSD-3-Clause"
] | null | null | null |
src/architecture/routine/basic_block.hpp
|
AhmedZero/VTIL-Python
|
e9df05d6cd614ace762f0db29660ede1b5b51682
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2020 Daniel (@L33T) and contributors of the VTIL Project
// 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 VTIL Project 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
//
// Furthermore, the following pieces of software have additional copyrights
// licenses, and/or restrictions:
//
// |--------------------------------------------------------------------------|
// | File name | Link for further information |
// |-------------------------|------------------------------------------------|
// | basic_block.hpp | https://github.com/vtil-project/VTIL-Core |
// | | https://github.com/pybind/pybind11 |
// |--------------------------------------------------------------------------|
//
#pragma once
#include <vtil/vtil>
#include <pybind11/pybind11.h>
using namespace vtil;
namespace py = pybind11;
namespace vtil::python
{
class basic_block_py : public py::class_<basic_block> // , std::unique_ptr<basic_block, py::nodelete>
{
public:
basic_block_py( const handle& scope, const char* name )
: class_( scope, name )
{
// Related
//
py::class_<il_iterator>( scope, "il_iterator" )
.def( py::init<>() )
.def( "get", [ ] ( const il_iterator& it ) { return +it; }, py::return_value_policy::reference )
.def( "prev", [ ] ( const il_iterator& it ) { auto p = it; --( p ); return p; } )
.def( "next", [ ] ( const il_iterator& it ) { auto p = it; ++( p ); return p; } )
.def( py::self == py::self )
.def( py::self != py::self )
;
// py::class_<il_const_iterator>( scope, "il_const_iterator" )
// .def( py::init<>() )
// .def( "get", [ ] ( const il_const_iterator& it ) { return *it; } )
// .def( "prev", [ ] ( const il_const_iterator& it ) { auto p = it; --( p ); return p; } )
// .def( "next", [ ] ( const il_const_iterator& it ) { auto p = it; ++( p ); return p; } )
// .def( py::self == py::self );
( *this )
// Constructor
//
// DO NOT USE THIS!!!
.def( py::init( py::overload_cast< vip_t, vtil::architecture_identifier >( &basic_block::begin ) ),
py::arg("entry_vip"),
py::arg("arch_id") = architecture_amd64,
py::return_value_policy::reference )
// Properties
//
.def_readwrite( "owner", &basic_block::owner, py::return_value_policy::reference )
.def_readwrite( "entry_vip", &basic_block::entry_vip )
.def_readwrite( "prev", &basic_block::prev )
.def_readwrite( "sp_offset", &basic_block::sp_offset )
.def_readwrite( "sp_index", &basic_block::sp_index )
.def_readwrite( "next", &basic_block::next )
//.def_readwrite( "stream", &basic_block::stream )
.def_readwrite( "last_temporary_index", &basic_block::last_temporary_index )
.def_readwrite( "label_stack", &basic_block::label_stack )
.def_readwrite( "context", &basic_block::context )
// Functions
//
.def( "signal_modification", &basic_block::signal_modification )
.def( "label_begin", &basic_block::label_begin )
.def( "label_end", &basic_block::label_end )
.def( "__iter__", [](const basic_block &s) { return py::make_iterator(s.begin(), s.end()); },
py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */)
.def( "__len__", &basic_block::size )
.def( "empty", &basic_block::empty )
.def( "size", &basic_block::size )
.def( "back", &basic_block::back )
.def( "front", &basic_block::front )
.def( "wback", &basic_block::wback, py::return_value_policy::reference )
.def( "wfront", &basic_block::wfront, py::return_value_policy::reference )
.def( "end", py::overload_cast< >( &basic_block::end ) )
.def( "begin", py::overload_cast< >( &basic_block::begin ) )
.def( "__getitem__", &basic_block::operator[] )
.def( "acquire", py::overload_cast< basic_block::const_iterator&>(&basic_block::acquire) )
.def( "erase", &basic_block::erase )
.def( "pop_front", &basic_block::pop_front )
.def( "pop_back", &basic_block::pop_back )
.def( "clear", &basic_block::clear, py::return_value_policy::reference )
.def( "insert", [ ] ( basic_block& bbl, basic_block::const_iterator& it, instruction& ins ) { bbl.insert( it, std::move( ins ) ); } )
.def( "push_back", [ ] ( basic_block& bbl, instruction& ins ) { bbl.push_back( ins ); } )
.def( "push_front", [ ] ( basic_block& bbl, instruction& ins ) { bbl.push_front( ins ); } )
.def( "is_complete", &basic_block::is_complete )
// In fact the return value lifecycle here should be bound to `routine`,
// but I don't know how to do that.
//
.def( "fork", &basic_block::fork, py::return_value_policy::reference_internal )
.def( "tmp", [ ] ( basic_block& bbl, bitcnt_t size ) { return bbl.tmp( size ); } )
.def( "tmp", &tmp_helper )
.def( "prepare_operand", [ ] ( basic_block& bbl, operand* op ) { return op; /* We use type_caster to explicitly cast to operand */ } )
.def( "shift_sp", &basic_block::shift_sp,
py::arg("offset"), py::arg("merge_instance") = false, py::arg("const_iterator") = basic_block::iterator{} )
.def( "vemits", &basic_block::vemits )
.def( "pushf", &basic_block::pushf )
.def( "popf", &basic_block::popf )
.def( "push", [ ] ( basic_block& bbl, const operand& op ) { return bbl.push( op ); } )
.def( "pop", [ ] ( basic_block& bbl, const operand& op ) { return bbl.pop( op ); } )
.def( "hash", &basic_block::hash )
// End
//
;
( *this )
// Functions
//
.def( "mov", &basic_block::mov<const operand&, const operand&> )
.def( "movsx", &basic_block::movsx<const operand&, const operand&> )
.def( "store", &basic_block::str<const operand&, const operand&, const operand&> )
.def( "str", &basic_block::str<const operand&, const operand&, const operand&> )
.def( "ldd", &basic_block::ldd<const operand&, const operand&, const operand&> )
.def( "neg", &basic_block::neg<const operand&> )
.def( "add", &basic_block::add<const operand&, const operand&> )
.def( "sub", &basic_block::sub<const operand&, const operand&> )
.def( "div", &basic_block::div<const operand&, const operand&, const operand&> )
.def( "idiv", &basic_block::idiv<const operand&, const operand&, const operand&> )
.def( "mul", &basic_block::mul<const operand&, const operand&> )
.def( "imul", &basic_block::imul<const operand&, const operand&> )
.def( "mulhi", &basic_block::mulhi<const operand&, const operand&> )
.def( "imulhi", &basic_block::imulhi<const operand&, const operand&> )
.def( "rem", &basic_block::rem<const operand&, const operand&, const operand&> )
.def( "irem", &basic_block::irem<const operand&, const operand&, const operand&> )
.def( "popcnt", &basic_block::popcnt<const operand&> )
.def( "bsf", &basic_block::bsf<const operand&> )
.def( "bsr", &basic_block::bsr<const operand&> )
.def( "bnot", &basic_block::bnot<const operand&> )
.def( "bshr", &basic_block::bshr<const operand&, const operand&> )
.def( "bshl", &basic_block::bshl<const operand&, const operand&> )
.def( "bxor", &basic_block::bxor<const operand&, const operand&> )
.def( "bor", &basic_block::bor<const operand&, const operand&> )
.def( "band", &basic_block::band<const operand&, const operand&> )
.def( "bror", &basic_block::bror<const operand&, const operand&> )
.def( "brol", &basic_block::brol<const operand&, const operand&> )
.def( "tg", &basic_block::tg<const operand&, const operand&, const operand&> )
.def( "tge", &basic_block::tge<const operand&, const operand&, const operand&> )
.def( "te", &basic_block::te<const operand&, const operand&, const operand&> )
.def( "tne", &basic_block::tne<const operand&, const operand&, const operand&> )
.def( "tle", &basic_block::tle<const operand&, const operand&, const operand&> )
.def( "tl", &basic_block::tl<const operand&, const operand&, const operand&> )
.def( "tug", &basic_block::tug<const operand&, const operand&, const operand&> )
.def( "tuge", &basic_block::tuge<const operand&, const operand&, const operand&> )
.def( "tule", &basic_block::tule<const operand&, const operand&, const operand&> )
.def( "tul", &basic_block::tul<const operand&, const operand&, const operand&> )
.def( "ifs", &basic_block::ifs<const operand&, const operand&, const operand&> )
.def( "js", &basic_block::js<const operand&, const operand&, const operand&> )
.def( "jmp", &basic_block::jmp<const operand&> )
.def( "vexit", &basic_block::vexit<const operand&> )
.def( "vxcall", &basic_block::vxcall<const operand&> )
.def( "nop", &basic_block::nop<> )
.def( "vemit", &basic_block::vemit<const operand&> )
.def( "vpinr", &basic_block::vpinr<const operand&> )
.def( "vpinw", &basic_block::vpinw<const operand&> )
.def( "vpinrm", &basic_block::vpinrm<const operand&, const operand&> )
.def( "vpinwm", &basic_block::vpinwm<const operand&, const operand&> );
}
private:
static std::vector<register_desc> tmp_helper( basic_block& bbl, py::args args )
{
std::vector<register_desc> regs( args.size() );
for ( auto [i, o] : zip( regs, args ) )
i = bbl.tmp( py::cast<bitcnt_t>( o ) );
return regs;
}
};
}
namespace pybind11::detail
{
template<> struct type_caster<il_const_iterator> : public type_caster_base<il_const_iterator>
{
using base = type_caster_base<il_const_iterator>;
public:
bool load( handle src, bool convert )
{
if ( py::isinstance<basic_block::iterator>( src ) )
{
this->value = new il_const_iterator( py::cast<basic_block::iterator>( src ) );
return true;
}
return false;
}
static handle cast( il_const_iterator src, return_value_policy policy, handle parent )
{
return base::cast( src, policy, parent );
}
};
}
| 47.366667
| 138
| 0.629046
|
07a854ea01419177d76cb7664c2103f2a47a2846
| 1,542
|
rb
|
Ruby
|
spec/features/issues/award_emoji_spec.rb
|
kuailemy123/gitlab-cn.github.io
|
6f6c6f68ea7cb976b6c1598e705ba8b2bdaf05a1
|
[
"MIT"
] | null | null | null |
spec/features/issues/award_emoji_spec.rb
|
kuailemy123/gitlab-cn.github.io
|
6f6c6f68ea7cb976b6c1598e705ba8b2bdaf05a1
|
[
"MIT"
] | null | null | null |
spec/features/issues/award_emoji_spec.rb
|
kuailemy123/gitlab-cn.github.io
|
6f6c6f68ea7cb976b6c1598e705ba8b2bdaf05a1
|
[
"MIT"
] | 1
|
2020-11-04T05:41:05.000Z
|
2020-11-04T05:41:05.000Z
|
require 'rails_helper'
describe 'Awards Emoji', feature: true do
let!(:project) { create(:project) }
let!(:user) { create(:user) }
before do
project.team << [user, :master]
login_as(user)
end
describe 'Click award emoji from issue#show' do
let!(:issue) do
create(:issue,
author: @user,
assignee: @user,
project: project)
end
before do
visit namespace_project_issue_path(project.namespace, project, issue)
end
it 'should increment the thumbsdown emoji', js: true do
find('[data-emoji="thumbsdown"]').click
sleep 2
expect(thumbsdown_emoji).to have_text("1")
end
context 'click the thumbsup emoji' do
it 'should increment the thumbsup emoji', js: true do
find('[data-emoji="thumbsup"]').click
sleep 2
expect(thumbsup_emoji).to have_text("1")
end
it 'should decrement the thumbsdown emoji', js: true do
expect(thumbsdown_emoji).to have_text("0")
end
end
context 'click the thumbsdown emoji' do
it 'should increment the thumbsdown emoji', js: true do
find('[data-emoji="thumbsdown"]').click
sleep 2
expect(thumbsdown_emoji).to have_text("1")
end
it 'should decrement the thumbsup emoji', js: true do
expect(thumbsup_emoji).to have_text("0")
end
end
end
def thumbsup_emoji
page.all('span.js-counter').first
end
def thumbsdown_emoji
page.all('span.js-counter').last
end
end
| 24.47619
| 75
| 0.623865
|
b01ae9a9dcab8abdddec6d5a21357150d5b49b21
| 2,949
|
py
|
Python
|
models/embeddingnet.py
|
patrickphat/gfg_challenge
|
95579c90e9768545f6a7344e8e6c323f28a6e049
|
[
"Apache-2.0"
] | null | null | null |
models/embeddingnet.py
|
patrickphat/gfg_challenge
|
95579c90e9768545f6a7344e8e6c323f28a6e049
|
[
"Apache-2.0"
] | null | null | null |
models/embeddingnet.py
|
patrickphat/gfg_challenge
|
95579c90e9768545f6a7344e8e6c323f28a6e049
|
[
"Apache-2.0"
] | null | null | null |
from torch import nn
import pytorch_lightning as pl
class EmbeddingNet(pl.LightningModule):
'''
Multilayer Perceptron.
'''
def __init__(self,input_dim, dropout=0.25):
super().__init__()
self.layers = nn.Sequential(
nn.Dropout(p=dropout),
nn.Linear(input_dim, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, 64)
)
def forward(self, x):
'''
Forward pass
'''
return self.layers(x)
class EmbeddingNetMedium(pl.LightningModule):
'''
Multilayer Perceptron.
'''
def __init__(self,input_dim, dropout=0.25):
super().__init__()
self.layers = nn.Sequential(
nn.Dropout(p=dropout),
nn.Linear(input_dim, 64),
nn.ReLU(),
nn.Linear(64, 64),
nn.ReLU(),
nn.Linear(64, 32)
)
def forward(self, x):
'''
Forward pass
'''
return self.layers(x)
class EmbeddingNetSmall(pl.LightningModule):
'''
Multilayer Perceptron.
'''
def __init__(self,input_dim, dropout=0.25):
super().__init__()
self.layers = nn.Sequential(
nn.Dropout(p=dropout),
nn.Linear(input_dim, 64),
nn.ReLU(),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 32)
)
def forward(self, x):
'''
Forward pass
'''
return self.layers(x)
class EmbeddingNetTiny(pl.LightningModule):
'''
Multilayer Perceptron.
'''
def __init__(self,input_dim, dropout=0.25):
super().__init__()
self.layers = nn.Sequential(
nn.Dropout(p=dropout),
nn.Linear(input_dim, 32),
nn.ReLU(),
nn.Linear(32, 32),
nn.ReLU(),
nn.Linear(32, 16)
)
def forward(self, x):
'''
Forward pass
'''
return self.layers(x)
class EmbeddingNetSuperTiny(pl.LightningModule):
'''
Multilayer Perceptron.
'''
def __init__(self,input_dim, dropout=0.25):
super().__init__()
self.layers = nn.Sequential(
nn.Dropout(p=dropout),
nn.Linear(input_dim, 16),
nn.ReLU(),
nn.Linear(16, 16),
nn.ReLU(),
nn.Linear(16, 8)
)
def forward(self, x):
'''
Forward pass
'''
return self.layers(x)
class EmbeddingNetAtom(pl.LightningModule):
'''
Multilayer Perceptron.
'''
def __init__(self,input_dim, dropout=0.25):
super().__init__()
self.layers = nn.Sequential(
nn.Dropout(p=dropout),
nn.Linear(input_dim, 16),
nn.ReLU(),
nn.Linear(16, 8)
)
def forward(self, x):
'''
Forward pass
'''
return self.layers(x)
| 24.575
| 48
| 0.501865
|
c69c29acf070f341b14fb6a5d5eb041069c776e7
| 4,174
|
py
|
Python
|
nagator/views/hosts.py
|
toxinu/nagator
|
03d1e842c09107290865f2360c2608757b521515
|
[
"BSD-3-Clause"
] | 1
|
2016-07-27T14:33:31.000Z
|
2016-07-27T14:33:31.000Z
|
nagator/views/hosts.py
|
toxinu/nagator
|
03d1e842c09107290865f2360c2608757b521515
|
[
"BSD-3-Clause"
] | null | null | null |
nagator/views/hosts.py
|
toxinu/nagator
|
03d1e842c09107290865f2360c2608757b521515
|
[
"BSD-3-Clause"
] | null | null | null |
import re
import sys
from clint.textui import colored, indent, puts
def list(nc, filtre, options):
hosts_founded = []
hosts_template_founded = []
hosts_filtered = []
hosts_template_filtered = []
try:
hosts = nc['all_host']
except KeyError:
with indent(3, quote=colored.white(' ==> ')):
puts("No host")
sys.exit(0)
except Exception as err:
with indent(3, quote=colored.white(' ==> ')):
puts("Something went wront (%)" % err)
sys.exit(1)
for host in hosts:
filtered = False
for element in filtre:
if element in host.keys():
try:
filtre_pattern = re.compile(filtre[element])
except:
with indent(3, quote=colored.red(' >> ')):
puts('Regexp error')
sys.exit(1)
if not filtre_pattern.match(host[element]):
filtered = True
break
else:
filtered = False
else:
filtered = True
break
if not filtered:
if host.has_key('register'):
if host['register'] == 0:
hosts_founded.append(host)
else:
hosts_template_founded.append(host)
else:
hosts_founded.append(host)
else:
if host.has_key('register'):
if host['register'] == 0:
hosts_filtered.append(host)
else:
hosts_template_filtered.append(host)
else:
hosts_filtered.append(host)
hosts_founded = sorted(
hosts_founded,
key=lambda k: k['meta']['defined_attributes']['host_name'])
hosts_template_founded = sorted(
hosts_template_founded,
key=lambda k: k['name'])
hosts_filtered = sorted(
hosts_filtered,
key=lambda k: k['meta']['defined_attributes']['host_name'])
hosts_template_filtered = sorted(
hosts_template_filtered,
key=lambda k: k['name'])
with indent(3, quote=colored.white(' ====> ')):
puts("Hosts founded")
if hosts_template_founded:
for host in hosts_template_founded:
with indent(3, quote=colored.red(' >> ')):
puts("%s" % host['name'])
if not 'small' in options:
for key, value in sorted(host.items()):
if key != 'meta':
if key in host['meta']['inherited_attributes']:
with indent(3, quote=colored.white(' | ')):
puts("%s: %s" % (colored.blue(key), colored.green(value)))
else:
with indent(3, quote=colored.white(' | ')):
puts("%s: %s" % (colored.blue(key), colored.yellow(value)))
if hosts_founded:
for host in hosts_founded:
with indent(3, quote=colored.green(' >> ')):
puts("%s" % host['host_name'])
if not 'small' in options:
for key, value in sorted(host.items()):
if key != 'meta':
if key in host['meta']['inherited_attributes']:
with indent(3, quote=colored.white(' | ')):
puts("%s: %s" % (colored.blue(key), colored.green(value)))
else:
with indent(3, quote=colored.white(' | ')):
puts("%s: %s" % (colored.blue(key), colored.yellow(value)))
with indent(3, quote=colored.white(' ==> ')):
puts("Total: %s" % (len(hosts_founded) + len(hosts_template_founded)))
if 'show_filtered' in options:
print('')
with indent(3, quote=colored.white(' ====> ')):
puts("Hosts filtered")
if hosts_template_filtered:
for host in hosts_template_filtered:
with indent(3, quote=colored.red(' >> ')):
puts("%s" % host['name'])
if hosts_filtered:
for host in hosts_filtered:
with indent(3, quote=colored.green(' >> ')):
puts("%s" % host['host_name'])
with indent(3, quote=colored.white(' ==> ')):
puts("Total: %s" % (len(hosts_filtered) + len(hosts_template_filtered)))
def legend(options):
print
with indent(3, quote=colored.white(' ==> ')):
puts('Legend')
with indent(2, quote=colored.white(' - ')):
puts(colored.white('Titles'))
with indent(2, quote=colored.white(' + ')):
puts(colored.red('red \">>\" are templates (name atttribute)'))
puts(colored.green('green \">>\" are not templates (host_name attribute)'))
if not 'small' in options:
with indent(2, quote=colored.white(' - ')):
puts(colored.white('Attributes'))
with indent(2, quote=colored.white(' + ')):
puts(colored.green('green values are inherited attributes'))
puts(colored.yellow('yellow values are defined attributes'))
| 29.188811
| 77
| 0.628414
|
9d4eaf70e369184eac06b9a798b71a924226abb5
| 996
|
h
|
C
|
scm_gl_core/src/scm/gl_classic/render_context/headless_context_win32.h
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 10
|
2015-09-17T06:01:03.000Z
|
2019-10-23T07:10:20.000Z
|
scm_gl_core/src/scm/gl_classic/render_context/headless_context_win32.h
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 5
|
2015-01-06T14:11:32.000Z
|
2016-12-12T10:26:53.000Z
|
scm_gl_core/src/scm/gl_classic/render_context/headless_context_win32.h
|
Nyran/schism
|
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
|
[
"BSD-3-Clause"
] | 15
|
2015-01-29T20:56:13.000Z
|
2020-07-02T19:03:20.000Z
|
// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com>
// Distributed under the Modified BSD License, see license.txt.
#ifndef SCM_GL_HEADLESS_CONTEXT_WIN32_H_INCLUDED
#define SCM_GL_HEADLESS_CONTEXT_WIN32_H_INCLUDED
#include <scm/gl_classic/render_context/headless_context.h>
#include <scm/core/platform/platform.h>
#include <scm/core/utilities/platform_warning_disable.h>
namespace scm {
namespace gl_classic {
class __scm_export(gl_core) headless_context_win32 : public headless_context
{
public:
headless_context_win32();
virtual ~headless_context_win32();
bool setup(const context_format& desc,
const window_context& partent_ctx);
void cleanup();
bool make_current(bool current = true) const;
protected:
handle _pbuffer;
};
} // namespace gl_classic
} // namespace scm
#include <scm/core/utilities/platform_warning_enable.h>
#endif // SCM_GL_HEADLESS_CONTEXT_WIN32_H_INCLUDED
| 25.538462
| 76
| 0.735944
|
53c99c0adc42f72c696d57568816d28eb1eea7b1
| 306
|
rb
|
Ruby
|
test/OSVERSIONINFOEX.rb
|
rpeev/fzeet
|
a8e3e446567c94461ed141c21701d36aadf51a86
|
[
"MIT"
] | 1
|
2019-09-16T23:45:28.000Z
|
2019-09-16T23:45:28.000Z
|
test/OSVERSIONINFOEX.rb
|
rpeev/fzeet
|
a8e3e446567c94461ed141c21701d36aadf51a86
|
[
"MIT"
] | null | null | null |
test/OSVERSIONINFOEX.rb
|
rpeev/fzeet
|
a8e3e446567c94461ed141c21701d36aadf51a86
|
[
"MIT"
] | null | null | null |
require_relative '../lib/fzeet'
include Fzeet
Windows::OSVERSIONINFOEX.new.tap { |ovi|
ovi[:dwMajorVersion] = 5
ovi[:dwMinorVersion] = 2
raise unless ovi.hex == 0x0502
raise unless ovi >= :xp
raise unless ovi > 2000
raise unless ovi < :vista
raise unless ovi.name == 'Windows XP'
}
| 20.4
| 41
| 0.673203
|