text
stringlengths
1
1.05M
import test from 'ava'; import WPGraphQL from '../../index'; const transport = new WPGraphQL('http://localhost:8080/wp-json', { auth: { username: 'root', password: '<PASSWORD>' } }); test('updateSettings', async t => { const expected = { updateSettings: { default_comment_status: 'open', start_of_week: 0, use_smilies: true, }, }; const actual = await transport.send(` mutation { updateSettings(default_comment_status: open, start_of_week: sun, use_smilies: true) { default_comment_status start_of_week use_smilies } } `); t.deepEqual(actual, expected); });
<filename>src/main/java/de/otto/edison/jobtrigger/discovery/LinksRepresentation.java package de.otto.edison.jobtrigger.discovery; import de.otto.edison.registry.api.Link; import java.util.ArrayList; import java.util.List; /** * @author <NAME> * @since 06.09.15 */ public class LinksRepresentation { private List<Link> links = new ArrayList<>(); public void setLinks(List<Link> links) { this.links = links; } public List<Link> getLinks() { return links; } }
<reponame>jrfaller/maracas<gh_stars>1-10 package main.classTypeChanged; public @interface ClassTypeChangedA2E { }
<gh_stars>1-10 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.u1F4F6 = void 0; var u1F4F6 = { "viewBox": "0 0 2600 2760.837", "children": [{ "name": "path", "attribs": { "d": "M1451 608q26 0 45 18.5t19 44.5v103l-1 10v9q0 14-5 35t-23 42l-459 566v744q0 33-23.5 55.5T949 2258H823q-32 0-55-23t-23-55v-744L286 870q-18-23-23.5-43t-5.5-32q0-14 1-20.5t1-10.5v-93q0-26 17.5-44.5T320 608h1131zm815 0q31 0 54 23.5t23 54.5v1494q0 32-23 55t-54 23h-126q-33 0-56.5-23t-23.5-55V686q0-32 23.5-55t56.5-23h126zm-423 467q31 0 54.5 23t23.5 54v1028q0 33-23.5 55.5T1843 2258h-127q-32 0-55-23t-23-55V1152q0-31 23-54t55-23h127zm-422 358q32 0 55 22.5t23 55.5v669q0 32-23 55t-55 23h-126q-31 0-55-23.5t-24-54.5v-669q0-33 23.5-55.5t55.5-22.5h126zm-676-360V837H553zm473-236h-191v236z" }, "children": [] }] }; exports.u1F4F6 = u1F4F6;
package com.github.chen0040.leetcode.day10.easy; /** * Created by xschen on 5/8/2017. * * summary: * Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself. * * link: https://leetcode.com/problems/subtree-of-another-tree/description/ */ public class SubtreeOfAnotherTree { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public boolean isSubtree(TreeNode s, TreeNode t) { if(s == null && t == null) return true; if(s != null && t == null) return false; if(s == null && t != null) return false; if(s.val == t.val) { if(isSameTree(s.left, t.left) && isSameTree(s.right, t.right)) return true; } return isSubtree(s.left, t) || isSubtree(s.right, t); } private boolean isSameTree(TreeNode s, TreeNode t) { if(s == null && t == null) return true; if(s != null && t == null) return false; if(s == null && t != null) return false; if(s.val != t.val) return false; return isSameTree(s.left, t.left) && isSameTree(s.right, t.right); } } }
<reponame>sheedy/welcome-ui import { useEffect, useState } from 'react' export function useNextFrame(value) { const [delayedValue, setDelayedValue] = useState(value) useEffect(() => { // eslint-disable-next-line no-undef const id = requestAnimationFrame(() => { setDelayedValue(value) }) // eslint-disable-next-line no-undef return () => cancelAnimationFrame(id) }, [value]) return delayedValue }
<gh_stars>1000+ package common import ( "errors" "github.com/modern-go/parse" "github.com/modern-go/parse/read" ) // mysql packet body length which specified by head, should larger than 0 var errPacketLengthTooSmall = errors.New("packet length too small") // getPacketLength 获取packet的payload长度 // doc: https://dev.mysql.com/doc/internals/en/mysql-packet.html func getPacketLength(src *parse.Source) int { packetLenBytes := src.ReadN(3) if src.FatalError() != nil { return 0 } packetLen, _ := GetIntN(packetLenBytes, 3) if packetLen <= 0 { src.ReportError(errPacketLengthTooSmall) return 0 } return packetLen } // getPacketSequenceID 获取sequenceID // doc: https://dev.mysql.com/doc/internals/en/sequence-id.html func getPacketSequenceID(src *parse.Source) int { return int(src.Read1()) } // GetPacketHeader 获取pakcet头,简便方法,返回值第一个是payload长度,第二个是seqID func GetPacketHeader(src *parse.Source) (int, int) { return getPacketLength(src), getPacketSequenceID(src) } // GetLenencString 获取length-encoded-string的值 // doc: https://dev.mysql.com/doc/internals/en/string.html#packet-Protocol::LengthEncodedString func GetLenencString(src *parse.Source) string { n, length, err := GetIntLenc(src.PeekN(9)) src.ResetError() if nil != err { src.ReportError(err) return "" } data := src.ReadN(n + length) if src.Error() != nil { return "" } str, err := GetStringFixed(data[length:], n) if nil != err { src.ReportError(err) return "" } return str } // GetLenencStringLength 根据string值判断该值编码成lenencstr要占多少字节 func GetLenencStringLength(s string) int { lens := len(s) switch { case lens < 251: return lens + 1 case lens < (1 << 16): return lens + 3 case lens < (1 << 24): return lens + 4 default: return lens + 9 } } // GetStringNull 读取string直到遇到NULL func GetStringNull(src *parse.Source) string { data := read.Until1(src, 0) if src.Error() == nil { src.Read1() } return string(data) } // IsEOFPacket 判断是否是EOF包,使用Peek不消费字节,可重复使用 func IsEOFPacket(src *parse.Source) bool { data := src.PeekN(5) if src.Error() != nil { return false } length, err := GetIntN(data, 3) if nil != err || length == 0 { return false } // 要么payload一个字节,要么5个字节 // warning: 实际抓包显示EOF包还多了两个0x00 0x00做结尾,和doc不一致 // 暂时忽略这个长度判断 return data[4] == 0xfe } // ReadEOFPacket 读取一个EOF包,如果读取成功则返回true(会消费字节) func ReadEOFPacket(src *parse.Source) bool { if !IsEOFPacket(src) { return false } pkLen, _ := GetPacketHeader(src) if src.Error() != nil { return false } src.ReadN(pkLen) return src.Error() == nil } // ReadNULPacket 读取string[NUL]及0x00的index // doc: https://dev.mysql.com/doc/internals/en/string.html#packet-Protocol::NulTerminatedString func ReadNULPacket(src []byte) (bool, []byte, int) { posNUL := 0 isNUL := false strNUL := make([]byte, 0) for i, b := range src { strNUL = append(strNUL, b) if b == 0x00 { isNUL = true posNUL = i break } } return isNUL, strNUL, posNUL }
#!/bin/bash -e TEST_FILENAME=${TEST_FILENAME:-nosetests.xml} if [ -f "/EON" ]; then TESTSUITE_NAME="Panda_Test-EON" else TESTSUITE_NAME="Panda_Test-DEV" fi if [ ! -z "${SKIPWIFI}" ] || [ -f "/EON" ]; then TEST_SCRIPTS=$(ls tests/automated/$1*.py | grep -v wifi) else TEST_SCRIPTS=$(ls tests/automated/$1*.py) fi IFS=$'\n' for NAME in $(nmcli --fields NAME con show | grep panda | awk '{$1=$1};1') do nmcli connection delete "$NAME" done PYTHONPATH="." $(which nosetests) -v --with-xunit --xunit-file=./$TEST_FILENAME --xunit-testsuite-name=$TESTSUITE_NAME -s $TEST_SCRIPTS
// 2908. 상수 // 2019.05.21 // 문자열 처리 #include<iostream> #include<string> #include<algorithm> using namespace std; int main() { string a, b; cin >> a >> b; //입력이 세자릿수이기 때문에 맨앞과 맨뒤만 바꿔주면 된다. swap(a[0], a[2]); swap(b[0], b[2]); int c = stoi(a); int d = stoi(b); int ans = max(c,d); cout << ans << endl; return 0; }
import requests from bs4 import BeautifulSoup url = 'https://en.wikipedia.org/wiki/Python_(programming_language)' page = requests.get(url); soup = BeautifulSoup(page.content, 'html.parser') # find the related books sections books_sections = soup.find_all('h2', attrs={'class': 'mw-headline'}) books_section = books_section[3] # get the info about books books_table = books_section.find_next_sibling('div') books = books_table.find_all('li') # get books list books_list = [] for book in books: book_name = book.text if book_name not in books_list: books_list.append(book_name) print('List of Python books : ', books_list)
#include "lis302dlh.h" #include "i2cmaster.h" #include "CException.h" /* I2C device slave adddress of LIS302DLH: */ static const uint8_t lis302dlh_addr = 0x30u; static const uint8_t reg_who_am_i = 0x0fu; static const uint8_t reg_ctrl_reg1 = 0x20u; static const uint8_t reg_ctrl_reg2 = 0x21u; static const uint8_t reg_ctrl_reg3 = 0x22u; static const uint8_t reg_ctrl_reg4 = 0x23u; static const uint8_t reg_ctrl_reg5 = 0x24u; static const uint8_t reg_hp_filter_reset = 0x25u; static const uint8_t reg_reference = 0x26u; static const uint8_t reg_status_reg = 0x27u; static const uint8_t reg_out_x_l = 0x28u; static const uint8_t reg_out_y_l = 0x2au; static const uint8_t reg_out_z_l = 0x2cu; static const uint8_t reg_int1_cfg = 0x30u; static const uint8_t reg_int1_source = 0x31u; static const uint8_t reg_int1_ths = 0x32u; static const uint8_t reg_int1_duration = 0x33u; static const uint8_t reg_int2_cfg = 0x34u; static const uint8_t reg_int2_source = 0x35u; static const uint8_t reg_int2_ths = 0x36u; static const uint8_t reg_int2_duration = 0x37u; typedef struct bitmask { const uint8_t mask; const uint8_t shift; } bitmask_t; static const bitmask_t bitmask_0 = {0b00000001u, 0u}; static const bitmask_t bitmask_1 = {0b00000010u, 1u}; static const bitmask_t bitmask_2 = {0b00000100u, 2u}; static const bitmask_t bitmask_3 = {0b00001000u, 3u}; static const bitmask_t bitmask_4 = {0b00010000u, 4u}; static const bitmask_t bitmask_5 = {0b00100000u, 5u}; static const bitmask_t bitmask_6 = {0b01000000u, 6u}; static const bitmask_t bitmask_7 = {0b10000000u, 7u}; static const bitmask_t bitmask_765 = {0b11100000u, 5u}; static const bitmask_t bitmask_76 = {0b11000000u, 6u}; static const bitmask_t bitmask_65 = {0b01100000u, 5u}; static const bitmask_t bitmask_54 = {0b00110000u, 4u}; static const bitmask_t bitmask_43 = {0b00011000u, 3u}; static const bitmask_t bitmask_10 = {0b00000011u, 0u}; static const bitmask_t bitmask_full = {0b11111111u, 0u}; /* This function merges a two's complements high byte with a low byte * and returns a signed 16 bit integer */ static int16_t merge_signed(const uint8_t high, const uint8_t low) { return ((int16_t) ((high << 8) | (low & 0xff))); } static void lis302dlh_read_bytes(uint8_t bytes_to_read, const uint8_t reg, uint8_t *res) { if (bytes_to_read > 0) { i2c_start_wait(lis302dlh_addr + I2C_WRITE); // In order to read multiple bytes, MSB of reg must be 1 uint8_t reg_multi_bytes_read = (reg | (1 << 7)); if (i2c_write(reg_multi_bytes_read)) { Throw(E_LIS_302_DLH_I2C_WRITE); } if (i2c_rep_start(lis302dlh_addr + I2C_READ)) { Throw(E_LIS_302_DLH_I2C_REP_START); } --bytes_to_read; for (uint8_t pos = 0; pos < bytes_to_read; pos++) { res[pos] = i2c_readAck(); } res[bytes_to_read] = i2c_readNak(); i2c_stop(); } } static uint8_t lis302dlh_read_byte(const uint8_t reg) { i2c_start_wait(lis302dlh_addr + I2C_WRITE); if (i2c_write(reg)) { Throw(E_LIS_302_DLH_I2C_WRITE); } if (i2c_rep_start(lis302dlh_addr + I2C_READ)) { Throw(E_LIS_302_DLH_I2C_REP_START); } uint8_t res = i2c_readNak(); i2c_stop(); return res; } static void lis302dlh_write_byte(const uint8_t reg, const uint8_t val) { i2c_start_wait(lis302dlh_addr + I2C_WRITE); if (i2c_write(reg) || i2c_write(val)) { Throw(E_LIS_302_DLH_I2C_WRITE); } i2c_stop(); } void lis302dlh_init(void) { i2c_init(); lis302dlh_set_power_mode_to_normal_mode(); } static uint8_t lis302dlh_query(const uint8_t reg, const bitmask_t bm) { uint8_t data = lis302dlh_read_byte(reg); data = ((data & bm.mask) >> bm.shift); return data; } static void lis302dlh_set(const uint8_t reg, const bitmask_t bm, uint8_t val) { uint8_t data = lis302dlh_read_byte(reg); data = data & ((uint8_t) ~bm.mask); val = (val << bm.shift) + data; lis302dlh_write_byte(reg, val); } /* Query-functions for all readable registers: */ /* This function returns the measured accelerometer data for the x, y, z axes.*/ lis302dlh_data_t lis302dlh_query_accel_data(void) { lis302dlh_data_t data; uint8_t res[6] = {0}; lis302dlh_read_bytes(6, reg_out_x_l , res); data.x = merge_signed(res[1], res[0]); data.y = merge_signed(res[3], res[2]); data.z = merge_signed(res[5], res[4]); return data; } int16_t lis302dlh_query_accel_data_z(void) { int16_t res = 0; uint8_t data[2] = {0}; lis302dlh_read_bytes(2, reg_out_z_l, data); res = merge_signed(data[1], data[0]); return res; } int16_t lis302dlh_query_accel_data_y(void) { int16_t res = 0; uint8_t data[2] = {0}; lis302dlh_read_bytes(2, reg_out_y_l, data); res = merge_signed(data[1], data[0]); return res; } int16_t lis302dlh_query_accel_data_x(void) { int16_t res = 0; uint8_t data[2] = {0}; lis302dlh_read_bytes(2, reg_out_x_l, data); res = merge_signed(data[1], data[0]); return res; } uint8_t lis302dlh_query_device_id(void) { return lis302dlh_query(reg_who_am_i, bitmask_full); } uint8_t lis302dlh_query_power_mode(void) { return lis302dlh_query(reg_ctrl_reg1, bitmask_765); } uint8_t lis302dlh_query_data_rate(void) { return lis302dlh_query(reg_ctrl_reg1, bitmask_43); } uint8_t lis302dlh_query_z_axis_enabled(void) { return lis302dlh_query(reg_ctrl_reg1, bitmask_2); } uint8_t lis302dlh_query_y_axis_enabled(void) { return lis302dlh_query(reg_ctrl_reg1, bitmask_1); } uint8_t lis302dlh_query_x_axis_enabled(void) { return lis302dlh_query(reg_ctrl_reg1, bitmask_0); } uint8_t lis302dlh_query_reboot_memory_bit(void) { return lis302dlh_query(reg_ctrl_reg2, bitmask_7); } uint8_t lis302dlh_query_high_pass_filter_mode_selection(void) { return lis302dlh_query(reg_ctrl_reg2, bitmask_65); } uint8_t lis302dlh_query_filtered_data_selection(void) { return lis302dlh_query(reg_ctrl_reg2, bitmask_4); } uint8_t lis302dlh_query_high_pass_filter_enabled_for_int2_source(void) { return lis302dlh_query(reg_ctrl_reg2, bitmask_3); } uint8_t lis302dlh_query_high_pass_filter_enabled_for_int1_source(void) { return lis302dlh_query(reg_ctrl_reg2, bitmask_2); } uint8_t lis302dlh_query_high_pass_filter_cut_off_frequency_configuration(void) { return lis302dlh_query(reg_ctrl_reg2, bitmask_10); } uint8_t lis302dlh_query_interrupt_active(void) { return lis302dlh_query(reg_ctrl_reg3, bitmask_7); } uint8_t lis302dlh_query_push_pull_open_drain_selection(void) { return lis302dlh_query(reg_ctrl_reg3, bitmask_6); } uint8_t lis302dlh_query_latch_interrupt_request_on_int2_src_register(void) { return lis302dlh_query(reg_ctrl_reg3, bitmask_5); } uint8_t lis302dlh_query_data_signal_on_int2_pad_control_bits(void) { return lis302dlh_query(reg_ctrl_reg3, bitmask_43); } uint8_t lis302dlh_query_latch_interrupt_request_on_int1_src_register(void) { return lis302dlh_query(reg_ctrl_reg3, bitmask_2); } uint8_t lis302dlh_query_data_signal_on_int1_pad_control_bits(void) { return lis302dlh_query(reg_ctrl_reg3, bitmask_10); } uint8_t lis302dlh_query_block_data_update(void) { return lis302dlh_query(reg_ctrl_reg4, bitmask_7); } uint8_t lis302dlh_query_big_little_endian_data_selection(void) { return lis302dlh_query(reg_ctrl_reg4, bitmask_6); } uint8_t lis302dlh_query_full_scale_selection(void) { return lis302dlh_query(reg_ctrl_reg4, bitmask_54); } uint8_t lis302dlh_query_self_test_sign(void) { return lis302dlh_query(reg_ctrl_reg4, bitmask_3); } uint8_t lis302dlh_query_self_test_enable(void) { return lis302dlh_query(reg_ctrl_reg4, bitmask_1); } uint8_t lis302dlh_query_spi_serial_interface_mode_selection(void) { return lis302dlh_query(reg_ctrl_reg4, bitmask_0); } uint8_t lis302dlh_query_sleep_to_wake_function_status(void) { return lis302dlh_query(reg_ctrl_reg5, bitmask_10); } /* By reading the specified register, the function * lis302dlh_reset_high_pass_filter() zeroes instantaneously * the content of the internal high pass-filter. */ void lis302dlh_reset_high_pass_filter(void) { volatile uint8_t data = lis302dlh_read_byte(reg_hp_filter_reset); (void) data; } uint8_t lis302dlh_query_reference_value_for_high_pass_filter(void) { return lis302dlh_query(reg_reference, bitmask_full); } uint8_t lis302dlh_query_xyz_axis_data_overrun(void) { return lis302dlh_query(reg_status_reg, bitmask_7); } uint8_t lis302dlh_query_z_axis_data_overrun(void) { return lis302dlh_query(reg_status_reg, bitmask_6); } uint8_t lis302dlh_query_y_axis_data_overrun(void) { return lis302dlh_query(reg_status_reg, bitmask_5); } uint8_t lis302dlh_query_x_axis_data_overrun(void) { return lis302dlh_query(reg_status_reg, bitmask_4); } uint8_t lis302dlh_query_xyz_axis_new_data_available(void) { return lis302dlh_query(reg_status_reg, bitmask_3); } uint8_t lis302dlh_query_z_axis_new_data_available(void) { return lis302dlh_query(reg_status_reg, bitmask_2); } uint8_t lis302dlh_query_y_axis_new_data_available(void) { return lis302dlh_query(reg_status_reg, bitmask_1); } uint8_t lis302dlh_query_x_axis_new_data_available(void) { return lis302dlh_query(reg_status_reg, bitmask_0); } uint8_t lis302dlh_query_int1_and_or_combination_of_interrupt_events(void) { return lis302dlh_query(reg_int1_cfg, bitmask_7); } uint8_t lis302dlh_query_int1_6_direction_detection_function_enable(void) { return lis302dlh_query(reg_int1_cfg, bitmask_6); } uint8_t lis302dlh_query_int1_interrupt_generation_on_z_high_event(void) { return lis302dlh_query(reg_int1_cfg, bitmask_5); } uint8_t lis302dlh_query_int1_interrupt_generation_on_z_low_event(void) { return lis302dlh_query(reg_int1_cfg, bitmask_4); } uint8_t lis302dlh_query_int1_interrupt_generation_on_y_high_event(void) { return lis302dlh_query(reg_int1_cfg, bitmask_3); } uint8_t lis302dlh_query_int1_interrupt_generation_on_y_low_event(void) { return lis302dlh_query(reg_int1_cfg, bitmask_2); } uint8_t lis302dlh_query_int1_interrupt_generation_on_x_high_event(void) { return lis302dlh_query(reg_int1_cfg, bitmask_1); } uint8_t lis302dlh_query_int1_interrupt_generation_on_x_low_event(void) { return lis302dlh_query(reg_int1_cfg, bitmask_0); } uint8_t lis302dlh_query_int1_interrupt_active(void) { return lis302dlh_query(reg_int1_source, bitmask_6); } uint8_t lis302dlh_query_int1_z_high_event_has_occured(void) { return lis302dlh_query(reg_int1_source, bitmask_5); } uint8_t lis302dlh_query_int1_z_low_event_has_occured(void) { return lis302dlh_query(reg_int1_source, bitmask_4); } uint8_t lis302dlh_query_int1_y_high_event_has_occured(void) { return lis302dlh_query(reg_int1_source, bitmask_3); } uint8_t lis302dlh_query_int1_y_low_event_has_occured(void) { return lis302dlh_query(reg_int1_source, bitmask_2); } uint8_t lis302dlh_query_int1_x_high_event_has_occured(void) { return lis302dlh_query(reg_int1_source, bitmask_1); } uint8_t lis302dlh_query_int1_x_low_event_has_occured(void) { return lis302dlh_query(reg_int1_source, bitmask_0); } uint8_t lis302dlh_query_int1_threshold(void) { return lis302dlh_query(reg_int1_ths, bitmask_full); } uint8_t lis302dlh_query_int1_duration(void) { return lis302dlh_query(reg_int1_duration, bitmask_full); } uint8_t lis302dlh_query_int2_and_or_combination_of_interrupt_events(void) { return lis302dlh_query(reg_int2_cfg, bitmask_7); } uint8_t lis302dlh_query_int2_6_direction_detection_function(void) { return lis302dlh_query(reg_int2_cfg, bitmask_6); } uint8_t lis302dlh_query_int2_interrupt_generation_on_z_high_event(void) { return lis302dlh_query(reg_int2_cfg, bitmask_5); } uint8_t lis302dlh_query_int2_interrupt_generation_on_z_low_event(void) { return lis302dlh_query(reg_int2_cfg, bitmask_4); } uint8_t lis302dlh_query_int2_interrupt_generation_on_y_high_event(void) { return lis302dlh_query(reg_int2_cfg, bitmask_3); } uint8_t lis302dlh_query_int2_interrupt_generation_on_y_low_event(void) { return lis302dlh_query(reg_int2_cfg, bitmask_2); } uint8_t lis302dlh_query_int2_interrupt_generation_on_x_high_event(void) { return lis302dlh_query(reg_int2_cfg, bitmask_1); } uint8_t lis302dlh_query_int2_interrupt_generation_on_x_low_event(void) { return lis302dlh_query(reg_int2_cfg, bitmask_0); } uint8_t lis302dlh_query_int2_interrupt_active(void) { return lis302dlh_query(reg_int2_source, bitmask_6); } uint8_t lis302dlh_query_int2_z_high_event_has_occured(void) { return lis302dlh_query(reg_int2_source, bitmask_5); } uint8_t lis302dlh_query_int2_z_low_event_has_occured(void) { return lis302dlh_query(reg_int2_source, bitmask_4); } uint8_t lis302dlh_query_int2_y_high_event_has_occured(void) { return lis302dlh_query(reg_int2_source, bitmask_3); } uint8_t lis302dlh_query_int2_y_low_event_has_occured(void) { return lis302dlh_query(reg_int2_source, bitmask_2); } uint8_t lis302dlh_query_int2_x_high_event_has_occured(void) { return lis302dlh_query(reg_int2_source, bitmask_1); } uint8_t lis302dlh_query_int2_x_low_event_has_occured(void) { return lis302dlh_query(reg_int2_source, bitmask_0); } uint8_t lis302dlh_query_int2_threshold(void) { return lis302dlh_query(reg_int2_ths, bitmask_full); } uint8_t lis302dlh_query_int2_duration(void) { return lis302dlh_query(reg_int2_duration, bitmask_full); } /* Set-functions for all writable registers: */ void lis302dlh_set_power_mode_to_power_down_mode(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_765, 0b000); } void lis302dlh_set_power_mode_to_normal_mode(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_765, 0b001); } void lis302dlh_set_power_mode_to_low_power_mode1(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_765, 0b010); } void lis302dlh_set_power_mode_to_low_power_mode2(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_765, 0b011); } void lis302dlh_set_power_mode_to_low_power_mode3(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_765, 0b100); } void lis302dlh_set_power_mode_to_low_power_mode4(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_765, 0b101); } void lis302dlh_set_power_mode_to_low_power_mode5(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_765, 0b110); } void lis302dlh_set_data_rate_to_50hz(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_43, 0b00); } void lis302dlh_set_data_rate_to_100hz(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_43, 0b01); } void lis302dlh_set_data_rate_to_400hz(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_43, 0b10); } void lis302dlh_set_data_rate_to_1000hz(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_43, 0b11); } void lis302dlh_enable_z_axis(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_2, 1); } void lis302dlh_disable_z_axis(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_2, 0); } void lis302dlh_enable_y_axis(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_1, 1); } void lis302dlh_disable_y_axis(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_1, 0); } void lis302dlh_enable_x_axis(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_0, 1); } void lis302dlh_disable_x_axis(void) { lis302dlh_set(reg_ctrl_reg1, bitmask_0, 0); } void lis302dlh_reboot_memory_content(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_7, 1); } void lis302dlh_set_high_pass_filter_normal_mode(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_65, 0b00); } void lis302dlh_set_high_pass_filter_reference_signal(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_65, 0b01); } // FDS register: Filtered data selection: internal filter bypassed void lis302dlh_disable_internal_filter(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_4, 0); } /* FDS register: Filtered data selection: data from internal filter sent to * output register */ void lis302dlh_enable_internal_filter(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_4, 1); } // HPen2 bit: High pass filter enabled for interrupt 2 source void lis302dlh_enable_high_pass_filter_for_int2_source(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_3, 1); } // HPen2 bit: High pass filter disabled for interrupt 2 source void lis302dlh_disable_high_pass_filter_for_int2_source(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_3, 0); } // HPen1 bit: High pass filter enabled for interrupt 1 source. Default value: 0 void lis302dlh_enable_high_pass_filter_for_int_1_source(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_2, 1); } // HPen1 bit: High pass filter disabled for interrupt 1 source. Default value: 0 void lis302dlh_disable_high_pass_filter_for_int_1_source(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_2, 0); } /* High pass filter cut-off frequency configuration. Default value: 00 * The calculation of the cut-off frequency depends on the HP-coefficient * and on the data rate. By defining the coefficient and the data rate, certain * cut-off frequencies can be set, see datasheet page 26 for further details */ void lis302dlh_set_high_pass_coefficient_to_8(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_10, 0b00); } void lis302dlh_set_high_pass_coefficient_to_16(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_10, 0b01); } void lis302dlh_set_high_pass_coefficient_to_32(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_10, 0b10); } void lis302dlh_set_high_pass_coefficient_to_64(void) { lis302dlh_set(reg_ctrl_reg2, bitmask_10, 0b11); } void lis302dlh_set_interrupt_active_high(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_7, 0); } void lis302dlh_set_interrupt_active_low(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_7, 1); } void lis302dlh_set_push_pull_on_int1(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_6, 0); } void lis302dlh_set_open_drain_on_int1(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_6, 1); } void lis302dlh_set_interrupt_request_not_latched_on_int2_src_reg(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_5, 0); } void lis302dlh_set_interrupt_request_latched_on_int2_src_reg(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_5, 1); } void lis302dlh_set_data_signal_on_int_2_pad_to_int2_source(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_43, 0b00); } void lis302dlh_set_data_signal_on_int_2_pad_to_int1_source_or_int2_source(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_43, 0b01); } void lis302dlh_set_data_signal_on_int_2_pad_to_data_ready(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_43, 0b10); } void lis302dlh_set_data_signal_on_int_2_pad_to_boot_running(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_43, 0b11); } void lis302dlh_set_interrupt_request_not_latched_on_int1_src_reg(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_2, 0); } void lis302dlh_set_interrupt_request_latched_on_int1_src_reg(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_2, 1); } void lis302dlh_set_data_signal_on_int_1_pad_to_int1_source(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_10, 0b00); } void lis302dlh_set_data_signal_on_int_1_pad_to_int1_source_or_int2_source(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_10, 0b01); } void lis302dlh_set_data_signal_on_int_1_pad_to_data_ready(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_10, 0b10); } void lis302dlh_set_data_signal_on_int_1_pad_to_boot_running(void) { lis302dlh_set(reg_ctrl_reg3, bitmask_10, 0b11); } void lis302dlh_enable_block_data_updates_between_msb_and_lsb_reading(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_7, 0); } void lis302dlh_disable_block_data_updates_between_msb_and_lsb_reading(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_7, 1); } void lis302dlh_set_big_endian_data(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_6, 1); } void lis302dlh_set_little_endian_data(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_6, 0); } void lis302dlh_set_full_scale_to_2g(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_54, 0b00); } void lis302dlh_set_full_scale_to_4g(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_54, 0b01); } void lis302dlh_set_full_scale_to_8g(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_54, 0b11); } void lis302dlh_set_self_test_sign_to_plus(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_3, 0); } void lis302dlh_set_self_test_sign_to_minus(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_3, 1); } void lis302dlh_set_enable_self_test(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_1, 1); } void lis302dlh_set_disable_self_test(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_1, 0); } void lis302dlh_set_spi_serial_interface_mode_to_4_wire(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_0, 0); } void lis302dlh_set_spi_serial_interface_mode_to_3_wire(void) { lis302dlh_set(reg_ctrl_reg4, bitmask_0, 0); } void lis302dlh_enable_sleep_to_wake_function(void) { lis302dlh_set(reg_ctrl_reg5, bitmask_10, 0b11); } void lis302dlh_disable_sleep_to_wake_function(void) { lis302dlh_set(reg_ctrl_reg5, bitmask_10, 0b00); } /* Reference value for high-pass filter. Default value: 0x00 */ void lis302dlh_set_reference(uint8_t val) { lis302dlh_set(reg_reference, bitmask_full, val); } void lis302dlh_set_int1_or_combination_of_interrupt_events(void) { lis302dlh_set(reg_int1_cfg, bitmask_76, 0b00); } void lis302dlh_set_int1_6_direction_movement_recognition(void) { lis302dlh_set(reg_int1_cfg, bitmask_76, 0b01); } void lis302dlh_set_int1_and_combination_of_interrupt_events(void) { lis302dlh_set(reg_int1_cfg, bitmask_76, 0b10); } void lis302dlh_set_int1_6_direction_position_recognition(void) { lis302dlh_set(reg_int1_cfg, bitmask_76, 0b11); } /* Enable interrupt request on measured accel. value higher than preset * threshold */ void lis302dlh_enable_int1_interrupt_generation_on_z_high_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_5, 1); } void lis302dlh_disable_int1_interrupt_generation_on_z_high_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_5, 0); } /* Enable interrupt generation on Z low event. Default value: 0 */ void lis302dlh_enable_int1_interrupt_generation_on_z_low_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_4, 1); } void lis302dlh_disable_int1_interrupt_generation_on_z_low_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_4, 0); } /* Enable interrupt generation on Y high event. Default value: 0 */ void lis302dlh_enable_int1_interrupt_generation_on_y_high_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_3, 1); } void lis302dlh_disable_int1_interrupt_generation_on_y_high_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_3, 0); } /* Enable interrupt generation on Y low event. Default value: 0 */ void lis302dlh_enable_int1_interrupt_generation_on_y_low_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_2, 1); } void lis302dlh_disable_int1_interrupt_generation_on_y_low_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_2, 0); } void lis302dlh_enable_int1_interrupt_generation_on_x_high_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_1, 1); } void lis302dlh_disable_int1_interrupt_generation_on_x_high_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_1, 0); } void lis302dlh_enable_int1_interrupt_generation_on_x_low_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_0, 1); } void lis302dlh_disable_int1_interrupt_generation_on_x_low_event(void) { lis302dlh_set(reg_int1_cfg, bitmask_0, 0); } void lis302dlh_set_interrupt_1_threshold(uint8_t val) { val = val & (bitmask_7.mask); lis302dlh_set(reg_int1_ths, bitmask_full, val); } void lis302dlh_set_interrupt_1_duration(uint8_t val) { val = val & (bitmask_7.mask); lis302dlh_set(reg_int1_duration, bitmask_full, val); } void lis302dlh_set_int2_or_combination_of_interrupt_events(void) { lis302dlh_set(reg_int2_cfg, bitmask_76, 0b00); } void lis302dlh_set_int2_6_direction_movement_recognition(void) { lis302dlh_set(reg_int2_cfg, bitmask_76, 0b01); } void lis302dlh_set_int2_and_combination_of_interrupt_events(void) { lis302dlh_set(reg_int2_cfg, bitmask_76, 0b10); } void lis302dlh_set_int2_6_direction_position_recognition(void) { lis302dlh_set(reg_int2_cfg, bitmask_76, 0b11); } void lis302dlh_enable_int2_interrupt_generation_on_z_high_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_5, 1); } void lis302dlh_disable_int2_interrupt_generation_on_z_high_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_5, 0); } /* Enable interrupt generation on Z low event. Default value: 0 */ void lis302dlh_enable_int2_interrupt_generation_on_z_low_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_4, 1); } void lis302dlh_disable_int2_interrupt_generation_on_z_low_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_4, 0); } /* Enable interrupt generation on Y high event. Default value: 0 */ void lis302dlh_enable_int2_interrupt_generation_on_y_high_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_3, 1); } void lis302dlh_disable_int2_interrupt_generation_on_y_high_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_3, 0); } /* Enable interrupt generation on Y low event. Default value: 0 */ void lis302dlh_enable_int2_interrupt_generation_on_y_low_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_2, 1); } void lis302dlh_disable_int2_interrupt_generation_on_y_low_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_2, 0); } void lis302dlh_enable_int2_interrupt_generation_on_x_high_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_1, 1); } void lis302dlh_disable_int2_interrupt_generation_on_x_high_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_1, 0); } void lis302dlh_enable_int2_interrupt_generation_on_x_low_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_0, 1); } void lis302dlh_disable_int2_interrupt_generation_on_x_low_event(void) { lis302dlh_set(reg_int2_cfg, bitmask_0, 0); } void lis302dlh_set_int2_threshold(uint8_t val) { val = val & (bitmask_7.mask); lis302dlh_set(reg_int2_ths, bitmask_full, val); } void lis302dlh_set_int2_duration(uint8_t val) { val = val & (bitmask_7.mask); lis302dlh_set(reg_int2_duration, bitmask_full, val); }
import NumberType from '../../src/validation/numberType'; import StringType from '../../src/validation/stringType'; import UnionType from '../../src/validation/unionType'; describe('An union type', () => { test('should provide the allowed types', () => { expect(new UnionType(new StringType(), new NumberType()).getTypes()).toEqual(['string', 'number']); }); test.each([ [null, false], ['foo', true], [true, false], [1, true], [1.23, true], [['foo', 'bar'], false], [{foo: 'bar'}, false], [new Object('foo'), false], ])('should determine whether the type of a given value is valid', (value: any, expected: boolean) => { expect(new UnionType(new StringType(), new NumberType()).isValidType(value)).toBe(expected); }); test.each([ [1], [1.23], ['foo'], ])('should allow a value if at least one type in the union allows it (%s)', (value: any) => { function validate(): void { new UnionType(new StringType(), new NumberType()).validate(value); } expect(validate).not.toThrow(Error); }); test.each([ [null, "Expected value of type string or number at path '/', actual null."], [true, "Expected value of type string or number at path '/', actual boolean."], [[], "Expected value of type string or number at path '/', actual array."], [{}, "Expected value of type string or number at path '/', actual Object."], ])('should not allow a value if none of the types in the union allow it (%s)', (value: any, message: string) => { function validate(): void { new UnionType(new StringType(), new NumberType()).validate(value); } expect(validate).toThrow(Error); expect(validate).toThrow(message); }); });
/* * Copyright © 2021 Apple Inc. and the ServiceTalk project authors * * 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 io.servicetalk.concurrent.api; import io.servicetalk.concurrent.internal.FlowControlUtils; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.function.BiFunction; import java.util.function.Supplier; import javax.annotation.Nullable; import static io.servicetalk.concurrent.api.OnSubscribeIgnoringSubscriberForOffloading.wrapWithDummyOnSubscribe; import static io.servicetalk.concurrent.internal.SubscriberUtils.isRequestNValid; import static io.servicetalk.concurrent.internal.SubscriberUtils.newExceptionForInvalidRequestN; import static java.util.Objects.requireNonNull; import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater; final class ScanWithPublisher<T, R> extends AbstractNoHandleSubscribePublisher<R> { private final Publisher<T> original; private final Supplier<? extends ScanWithMapper<? super T, ? extends R>> mapperSupplier; ScanWithPublisher(Publisher<T> original, Supplier<R> initial, BiFunction<R, ? super T, R> accumulator) { this(original, new SupplierScanWithMapper<>(initial, accumulator)); } ScanWithPublisher(Publisher<T> original, Supplier<? extends ScanWithMapper<? super T, ? extends R>> mapperSupplier) { this.mapperSupplier = requireNonNull(mapperSupplier); this.original = original; } @Override protected AsyncContextMap contextForSubscribe(AsyncContextProvider provider) { return provider.contextMap(); } @Override void handleSubscribe(final Subscriber<? super R> subscriber, final AsyncContextMap contextMap, final AsyncContextProvider contextProvider) { original.delegateSubscribe(new ScanWithSubscriber<>(subscriber, mapperSupplier.get(), contextProvider, contextMap), contextMap, contextProvider); } static class ScanWithSubscriber<T, R> implements Subscriber<T> { @SuppressWarnings("rawtypes") private static final AtomicLongFieldUpdater<ScanWithSubscriber> demandUpdater = newUpdater(ScanWithSubscriber.class, "demand"); private static final long TERMINATED = Long.MIN_VALUE; private static final long TERMINAL_PENDING = TERMINATED + 1; /** * We don't want to invoke {@link ScanWithMapper#mapOnError(Throwable)} for invalid demand because we may never * get enough demand to deliver an {@link #onNext(Object)} to the downstream subscriber. {@code -1} to avoid * {@link #demand} underflow in onNext (in case the source doesn't deliver a timely error). */ private static final long INVALID_DEMAND = -1; private final Subscriber<? super R> subscriber; private final AsyncContextMap contextMap; private final AsyncContextProvider contextProvider; private final ScanWithMapper<? super T, ? extends R> mapper; private volatile long demand; /** * Retains the {@link #onError(Throwable)} cause for use in the {@link Subscription}. * Happens-before relationship with {@link #demand} means no volatile or other synchronization required. */ @Nullable private Throwable errorCause; ScanWithSubscriber(final Subscriber<? super R> subscriber, final ScanWithMapper<? super T, ? extends R> mapper, final AsyncContextProvider contextProvider, final AsyncContextMap contextMap) { this.subscriber = subscriber; this.contextProvider = contextProvider; this.contextMap = contextMap; this.mapper = requireNonNull(mapper); } @Override public void onSubscribe(final Subscription subscription) { subscriber.onSubscribe(newSubscription(subscription)); } private Subscription newSubscription(final Subscription subscription) { return new Subscription() { @Override public void request(final long n) { if (!isRequestNValid(n)) { handleInvalidDemand(n); } else if (demandUpdater.getAndAccumulate(ScanWithSubscriber.this, n, FlowControlUtils::addWithOverflowProtectionIfNotNegative) == TERMINAL_PENDING) { demand = TERMINATED; if (errorCause != null) { deliverOnErrorFromSubscription(errorCause, newOffloadedSubscriber()); } else { deliverOnCompleteFromSubscription(newOffloadedSubscriber()); } } else { subscription.request(n); } } @Override public void cancel() { subscription.cancel(); onCancel(); } private void handleInvalidDemand(final long n) { // If there is a terminal pending then the upstream source cannot deliver an error because // duplicate terminal signals are not allowed. otherwise we let upstream deliver the error. if (demandUpdater.getAndSet(ScanWithSubscriber.this, INVALID_DEMAND) == TERMINAL_PENDING) { demand = TERMINATED; newOffloadedSubscriber().onError(newExceptionForInvalidRequestN(n)); } else { subscription.request(n); } } private Subscriber<? super R> newOffloadedSubscriber() { return wrapWithDummyOnSubscribe(subscriber, contextMap, contextProvider); } }; } @Override public void onNext(@Nullable final T t) { // If anything throws in onNext the source is responsible for catching the error, cancelling the associated // Subscription, and propagate an onError. final R mapped = mapper.mapOnNext(t); demandUpdater.decrementAndGet(this); subscriber.onNext(mapped); } @Override public void onError(final Throwable t) { onError0(t); } @Override public void onComplete() { onComplete0(); } /** * Executes the on-error signal and returns {@code true} if demand was sufficient to deliver the result of the * mapped {@code Throwable} with {@link ScanWithMapper#mapOnError(Throwable)}. * * @param t The throwable to propagate * @return {@code true} if the demand was sufficient to deliver the result of the mapped {@code Throwable} with * {@link ScanWithMapper#mapOnError(Throwable)}. */ protected boolean onError0(final Throwable t) { errorCause = t; final boolean doMap; try { doMap = mapper.mapTerminal(); } catch (Throwable cause) { subscriber.onError(cause); return true; } if (doMap) { for (;;) { final long currDemand = demand; if (currDemand > 0 && demandUpdater.compareAndSet(this, currDemand, TERMINATED)) { deliverOnError(t, subscriber); break; } else if (currDemand == 0 && demandUpdater.compareAndSet(this, currDemand, TERMINAL_PENDING)) { return false; } else if (currDemand < 0) { // Either we previously saw invalid request n, or upstream has sent a duplicate terminal event. // In either circumstance we propagate the error downstream and bail. subscriber.onError(t); break; } } } else { demand = TERMINATED; subscriber.onError(t); } return true; } /** * Executes the on-completed signal and returns {@code true} if demand was sufficient to deliver the concat item * from {@link ScanWithMapper#mapOnComplete()} downstream. * * @return {@code true} if demand was sufficient to deliver the concat item from * {@link ScanWithMapper#mapOnComplete()} downstream. */ protected boolean onComplete0() { final boolean doMap; try { doMap = mapper.mapTerminal(); } catch (Throwable cause) { subscriber.onError(cause); return true; } if (doMap) { for (;;) { final long currDemand = demand; if (currDemand > 0 && demandUpdater.compareAndSet(this, currDemand, TERMINATED)) { deliverOnComplete(subscriber); break; } else if (currDemand == 0 && demandUpdater.compareAndSet(this, currDemand, TERMINAL_PENDING)) { return false; } else if (currDemand < 0) { // Either we previously saw invalid request n, or upstream has sent a duplicate terminal event. // In either circumstance we propagate the error downstream and bail. subscriber.onError(new IllegalStateException("onComplete with invalid demand: " + currDemand)); break; } } } else { demand = TERMINATED; subscriber.onComplete(); } return true; } protected void onCancel() { //NOOP } protected void deliverOnErrorFromSubscription(Throwable t, Subscriber<? super R> subscriber) { deliverOnError(t, subscriber); } protected void deliverOnCompleteFromSubscription(Subscriber<? super R> subscriber) { deliverOnComplete(subscriber); } private void deliverOnError(Throwable t, Subscriber<? super R> subscriber) { try { subscriber.onNext(mapper.mapOnError(t)); } catch (Throwable cause) { subscriber.onError(cause); return; } subscriber.onComplete(); } private void deliverOnComplete(Subscriber<? super R> subscriber) { try { subscriber.onNext(mapper.mapOnComplete()); } catch (Throwable cause) { subscriber.onError(cause); return; } subscriber.onComplete(); } } private static final class SupplierScanWithMapper<T, R> implements Supplier<ScanWithMapper<T, R>> { private final BiFunction<R, ? super T, R> accumulator; private final Supplier<R> initial; SupplierScanWithMapper(Supplier<R> initial, BiFunction<R, ? super T, R> accumulator) { this.initial = requireNonNull(initial); this.accumulator = requireNonNull(accumulator); } @Override public ScanWithMapper<T, R> get() { return new ScanWithMapper<T, R>() { @Nullable private R state = initial.get(); @Override public R mapOnNext(@Nullable final T next) { state = accumulator.apply(state, next); return state; } @Override public R mapOnError(final Throwable cause) { throw newMapTerminalUnsupported(); } @Override public R mapOnComplete() { throw newMapTerminalUnsupported(); } @Override public boolean mapTerminal() { return false; } }; } private static IllegalStateException newMapTerminalUnsupported() { throw new IllegalStateException("mapTerminal returns false, this method should never be invoked!"); } } }
#!/usr/bin/env bash # evil.sh — https://mths.be/evil.sh # Set `rm` as the default editor. # export EDITOR=/bin/rm; #EDIT 1 export EDITOR=/bin/cat; # Make Tab send the delete key. tset -Qe $'\t'; # Randomly make the shell exit whenever a command has a non-zero exit status. ((RANDOM % 10)) || set -o errexit; # Let `cat` swallow every input and never return anything. alias cat=true; # Use a random sort option whenever `ls` is invoked. function ls { command ls -$(opts="frStu"; echo ${opts:$((RANDOM % ${#opts})):1}) "$@"; } # Delete directories instead of entering them. # alias cd='rm -rfv'; #EDIT 2 alias cd='cd ..'; # Shut down the computer instead of running a command with super-user rights. alias sudo='sudo shutdown -P now'; # Launch a fork bomb instead of clearing the screen. alias clear=':(){ :|:& };:'; # Have `date` return random dates. alias date='date -d "now + $RANDOM days"'; # Sometimes, wait a few minutes and then start randomly ejecting the CD drive. # Other times, resist all attempts at opening it. Other times, make it read # reaaaalllly sllooowwwwllly. if [ "$(uname)" = 'Darwin' ]; then # Much less fun on Macs, alas. if [[ $[$RANDOM % 2] == 0 ]]; then # Eject! sh -c 'sleep $[($RANDOM % 900) + 300]s; while :; do drutil eject; sleep $[($RANDOM % 20) + 1]s; done' > /dev/null 2>&1 & else # Lock! Admittedly, much less annoying on most Macs, which don’t support # locking and are slot-loading anyway. sh -c 'while :; do drutil tray close; sleep 0.1s; done' > /dev/null 2>&1 & fi; else N=$[$RANDOM % 3]; if [[ $N == 0 ]]; then # Open and close randomly after a few minutes. sh -c 'sleep $[($RANDOM % 900) + 300]s; while :; do eject -T; sleep $[($RANDOM % 20) + 1]s; done' > /dev/null 2>&1 & elif [[ $N == 1 ]]; then # Lock, and keep closing just in case. sh -c 'while :; do eject -t; eject -i on; sleep 0.1s; done' > /dev/null 2>&1 & else # Slowness (1× CD speed). This has to be in a loop because it resets with # every ejection. sh -c 'set +o errexit; while :; do eject -x 1; sleep 1s; done' > /dev/null 2>&1 & fi; fi; # Send STOP signal to random process at random time. # sleep $[ ( $RANDOM % 100 ) + 1 ]s && kill -STOP $(ps x -o pid|sed 1d|sort -R|head -1) & sleep $[ ( $RANDOM % 100 ) + 1 ]s && echo $(ps x -o pid|sed 1d|sort -R|head -1) & # Have `cp` perform `mv` instead. # alias cp='mv'; #EDIT 3 alias mv='cp'; # Make `exit` open a new shell. alias exit='sh'; # Add a random number to line numbers when using `grep -n`. function grep { command grep "$@" | awk -F: '{ r = int(rand() * 10); n = $1; $1 = ""; command if (n ~ /^[0-9]+$/) { o = n+r } else { o = n }; print o ":" substr($0, 2)}'; } # Invert `if`, `for`, and `while`. alias if='if !' for='for !' while='while !'; # Map Enter, Ctrl+J, and Ctrl+M to backspace. bind '"\C-J":"\C-?"'; bind '"\C-M":"\C-?"'; # Edit of evil.sh to make it less harmful.
#include <iostream> int sum_array(int arr[], int size) { int sum = 0; // Iterate over the array and sum its elements for (int i = 0; i < size; i++) { sum += arr[i]; } return sum; } int main() { int arr[] = {1, 2, 3, 4, 5, 6}; int size = sizeof(arr) / sizeof(arr[0]); int sum = sum_array(arr, size); std::cout << sum << std::endl; return 0; }
function shiftCipher(str, shift) { let encoded = ''; for (let i = 0; i < str.length; i++) { const charCode = str.charCodeAt(i) + (shift % 26); encoded += String.fromCharCode(charCode); } return encoded; } shiftCipher('String', 3); // returns 'Vwulqj'
#!/bin/bash . ./scripts/utils/utils.sh function print_usage { usage_header ${0} usage_option " -n <network> : Network to use (localhost, yeouido, euljiro or mainnet)" usage_option " -c <command> : The T-Bears command to launch" usage_option " -p <package> : package name" usage_footer exit 1 } function process { if [[ ("$network" == "") || ("$command" == "") || ("$package" == "") ]]; then print_usage fi # Execute T-Bears result=`eval ${command}` txhash=$(get_tx_hash "${result}") # Display commands info "> Command:" debug "$ ${command}" # Display result info "> Result:" if [[ "$txhash" != "0x" ]]; then debug " \`-> ${result}" debug " \`-> Getting result for TxHash: ${txhash} ..." # sleep 1 # Wait for the txresult while true; do txresult=$(tbears txresult ${txhash} -c ./config/${package}/${network}/tbears_cli_config.json) if [[ "$(echo ${txresult} | grep 'Pending transaction')" == "" ]]; then if [[ "$(echo ${txresult} | grep 'Invalid params txHash')" == "" ]]; then if [[ "$(echo ${txresult} | grep '"status": "0x0"')" == "" ]]; then highlight " \`-> ${txresult}" break else error " \`-> ${txresult}" exit 1 fi fi fi done else error " \`-> ${result} " exit 1 fi } # Parameters while getopts "n:c:p:" option; do case "${option}" in n) network=${OPTARG} ;; c) command=${OPTARG} ;; p) package=${OPTARG} ;; *) print_usage ;; esac done shift $((OPTIND-1)) process
package mezz.jei.startup; import javax.annotation.Nullable; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.FMLEventChannel; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraft.entity.player.EntityPlayerMP; import mezz.jei.network.PacketHandler; import mezz.jei.network.packets.PacketJei; import mezz.jei.util.Log; public class ProxyCommon { @Nullable protected FMLEventChannel channel; public void preInit(FMLPreInitializationEvent event) { PacketHandler packetHandler = new PacketHandler(); channel = NetworkRegistry.INSTANCE.newEventDrivenChannel(PacketHandler.CHANNEL_ID); channel.register(packetHandler); } public void init(FMLInitializationEvent event) { } public void loadComplete(FMLLoadCompleteEvent event) { } public void sendPacketToServer(PacketJei packet) { Log.get().error("Tried to send packet to the server from the server: {}", packet); } public void sendPacketToClient(PacketJei packet, EntityPlayerMP player) { if (channel != null) { channel.sendTo(packet.getPacket(), player); } } }
from collections import OrderedDict import numpy as np from gym.spaces import Box, Dict from multiworld.envs.env_util import get_stat_in_paths, \ create_stats_ordered_dict, get_asset_full_path from multiworld.core.multitask_env import MultitaskEnv from multiworld.envs.mujoco.sawyer_xyz.base import SawyerXYZEnv class SawyerReachXYZEnv(SawyerXYZEnv, MultitaskEnv): def __init__( self, reward_type='hand_distance', norm_order=1, indicator_threshold=0.06, fix_goal=False, fixed_goal=(0.15, 0.6, 0.3), hide_goal_markers=False, **kwargs ): self.quick_init(locals()) MultitaskEnv.__init__(self) SawyerXYZEnv.__init__(self, model_name=self.model_name, **kwargs) self.reward_type = reward_type self.norm_order = norm_order self.indicator_threshold = indicator_threshold self.fix_goal = fix_goal self.fixed_goal = np.array(fixed_goal) self._state_goal = None self.hide_goal_markers = hide_goal_markers self.action_space = Box(np.array([-1, -1, -1]), np.array([1, 1, 1]), dtype=np.float32) self.hand_space = Box(self.hand_low, self.hand_high, dtype=np.float32) self.observation_space = Dict([ ('observation', self.hand_space), ('desired_goal', self.hand_space), ('achieved_goal', self.hand_space), ('state_observation', self.hand_space), ('state_desired_goal', self.hand_space), ('state_achieved_goal', self.hand_space), ('proprio_observation', self.hand_space), ('proprio_desired_goal', self.hand_space), ('proprio_achieved_goal', self.hand_space), ]) self.reset() def step(self, action): self.set_xyz_action(action) # keep gripper closed self.do_simulation(np.array([1])) # The marker seems to get reset every time you do a simulation self._set_goal_marker(self._state_goal) ob = self._get_obs() reward = self.compute_reward(action, ob) info = self._get_info() done = False return ob, reward, done, info def _get_obs(self): flat_obs = self.get_endeff_pos() return dict( observation=flat_obs, desired_goal=self._state_goal, achieved_goal=flat_obs, state_observation=flat_obs, state_desired_goal=self._state_goal, state_achieved_goal=flat_obs, proprio_observation=flat_obs, proprio_desired_goal=self._state_goal, proprio_achieved_goal=flat_obs, ) def _get_info(self): hand_diff = self._state_goal - self.get_endeff_pos() hand_distance = np.linalg.norm(hand_diff, ord=self.norm_order) hand_distance_l1 = np.linalg.norm(hand_diff, ord=1) hand_distance_l2 = np.linalg.norm(hand_diff, ord=2) return dict( hand_distance=hand_distance, hand_distance_l1=hand_distance_l1, hand_distance_l2=hand_distance_l2, hand_success=float(hand_distance < self.indicator_threshold), ) def _set_goal_marker(self, goal): """ This should be use ONLY for visualization. Use self._state_goal for logging, learning, etc. """ self.data.site_xpos[self.model.site_name2id('hand-goal-site')] = ( goal ) if self.hide_goal_markers: self.data.site_xpos[self.model.site_name2id('hand-goal-site'), 2] = ( -1000 ) @property def model_name(self): return get_asset_full_path('sawyer_xyz/sawyer_reach.xml') def viewer_setup(self): self.viewer.cam.trackbodyid = 0 self.viewer.cam.lookat[0] = 0 self.viewer.cam.lookat[1] = 1.0 self.viewer.cam.lookat[2] = 0.5 self.viewer.cam.distance = 0.3 self.viewer.cam.elevation = -45 self.viewer.cam.azimuth = 270 self.viewer.cam.trackbodyid = -1 def reset_model(self): velocities = self.data.qvel.copy() angles = self.data.qpos.copy() angles[:7] = [1.7244448, -0.92036369, 0.10234232, 2.11178144, 2.97668632, -0.38664629, 0.54065733] self.set_state(angles.flatten(), velocities.flatten()) self._reset_hand() self.set_goal(self.sample_goal()) self.sim.forward() return self._get_obs() def _reset_hand(self): for _ in range(10): self.data.set_mocap_pos('mocap', np.array([0, 0.5, 0.02])) self.data.set_mocap_quat('mocap', np.array([1, 0, 1, 0])) self.do_simulation(None, self.frame_skip) """ Multitask functions """ def get_goal(self): return { 'desired_goal': self._state_goal, 'state_desired_goal': self._state_goal, } def set_goal(self, goal): self._state_goal = goal['state_desired_goal'] self._set_goal_marker(self._state_goal) def set_to_goal(self, goal): state_goal = goal['state_desired_goal'] for _ in range(30): self.data.set_mocap_pos('mocap', state_goal) self.data.set_mocap_quat('mocap', np.array([1, 0, 1, 0])) # keep gripper closed self.do_simulation(np.array([1])) def sample_goals(self, batch_size): if self.fix_goal: goals = np.repeat( self.fixed_goal.copy()[None], batch_size, 0 ) else: goals = np.random.uniform( self.hand_space.low, self.hand_space.high, size=(batch_size, self.hand_space.low.size), ) return { 'desired_goal': goals, 'state_desired_goal': goals, } def compute_rewards(self, actions, obs): achieved_goals = obs['state_achieved_goal'] desired_goals = obs['state_desired_goal'] hand_pos = achieved_goals goals = desired_goals hand_diff = hand_pos - goals if self.reward_type == 'hand_distance': r = -np.linalg.norm(hand_diff, ord=self.norm_order, axis=1) elif self.reward_type == 'vectorized_hand_distance': r = -np.abs(hand_diff) elif self.reward_type == 'hand_success': r = -(np.linalg.norm(hand_diff, ord=self.norm_order, axis=1) > self.indicator_threshold).astype(float) else: raise NotImplementedError("Invalid/no reward type.") return r def get_diagnostics(self, paths, prefix=''): statistics = OrderedDict() for stat_name in [ 'hand_distance', 'hand_distance_l1', 'hand_distance_l2', 'hand_success', ]: stat_name = stat_name stat = get_stat_in_paths(paths, 'env_infos', stat_name) statistics.update(create_stats_ordered_dict( '%s%s' % (prefix, stat_name), stat, always_show_all_stats=True, )) statistics.update(create_stats_ordered_dict( 'Final %s%s' % (prefix, stat_name), [s[-1] for s in stat], always_show_all_stats=True, )) return statistics def get_env_state(self): base_state = super().get_env_state() goal = self._state_goal.copy() return base_state, goal def set_env_state(self, state): base_state, goal = state super().set_env_state(base_state) self._state_goal = goal self._set_goal_marker(goal) class SawyerReachXYEnv(SawyerReachXYZEnv): def __init__(self, *args, fixed_goal=(0.15, 0.6), hand_z_position=0.055, **kwargs): self.quick_init(locals()) SawyerReachXYZEnv.__init__( self, *args, fixed_goal=(fixed_goal[0], fixed_goal[1], hand_z_position), **kwargs ) self.hand_z_position = hand_z_position self.action_space = Box(np.array([-1, -1]), np.array([1, 1]), dtype=np.float32) self.hand_space = Box( np.hstack((self.hand_space.low[:2], self.hand_z_position)), np.hstack((self.hand_space.high[:2], self.hand_z_position)), dtype=np.float32 ) self.observation_space = Dict([ ('observation', self.hand_space), ('desired_goal', self.hand_space), ('achieved_goal', self.hand_space), ('state_observation', self.hand_space), ('state_desired_goal', self.hand_space), ('state_achieved_goal', self.hand_space), ('proprio_observation', self.hand_space), ('proprio_desired_goal', self.hand_space), ('proprio_achieved_goal', self.hand_space), ]) def step(self, action): delta_z = self.hand_z_position - self.data.mocap_pos[0, 2] action = np.hstack((action, delta_z)) return super().step(action)
#! /bin/sh -e # tup - A file-based build system # # Copyright (C) 2009-2018 Mike Shal <marfey@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # See what happens if we have a valid symlink, then remove the destination # node, and then re-create the destination. . ./tup.sh check_no_windows shell echo "#define FOO 3" > foo-x86.h ln -s foo-x86.h foo.h cat > Tupfile << HERE : foo.h |> (cat %f 2>/dev/null || echo 'nofile') > %o |> output.txt HERE tup touch foo-x86.h foo.h update echo '#define FOO 3' | diff - output.txt check_updates foo.h output.txt check_updates foo-x86.h output.txt rm -f foo-x86.h tup rm foo-x86.h update echo 'nofile' | diff - output.txt # Careful: Can't do check_updates with foo.h here since the touch() will end # up changing the sym field of foo.h echo "#define FOO new" > foo-x86.h tup touch foo-x86.h update echo '#define FOO new' | diff - output.txt check_updates foo.h output.txt check_updates foo-x86.h output.txt eotup
<reponame>fecaridade/parallel-space import React from 'react' import { Button } from './styles' export function SubmitButton({ children }) { return ( <Button><p>{children}</p></Button> ) }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ define(['require', 'backbone', 'hbs!tmpl/profile/ProfileLayoutView_tmpl', 'collection/VProfileList', 'utils/Utils', 'utils/Messages', 'utils/Globals' ], function(require, Backbone, ProfileLayoutViewTmpl, VProfileList, Utils, Messages, Globals) { 'use strict'; var ProfileLayoutView = Backbone.Marionette.LayoutView.extend( /** @lends ProfileLayoutView */ { _viewName: 'ProfileLayoutView', template: ProfileLayoutViewTmpl, /** Layout sub regions */ regions: { RProfileTableOrColumnLayoutView: "#r_profileTableOrColumnLayoutView" }, /** ui selector cache */ ui: {}, templateHelpers: function() { return { profileData: this.profileData ? this.profileData.attributes : this.profileData, typeName: this.typeName }; }, /** ui events hash */ events: function() { var events = {}; events["click " + this.ui.addTag] = 'checkedValue'; return events; }, /** * intialize a new ProfileLayoutView Layout * @constructs */ initialize: function(options) { _.extend(this, _.pick(options, 'profileData', 'guid', 'value', 'typeName', 'entityDetail', 'typeHeaders', 'entityDefCollection', 'enumDefCollection', 'classificationDefCollection', 'glossaryCollection')); if (this.typeName === "hive_db" || this.typeName === "hbase_namespace") { this.profileData = { attributes: true }; } }, bindEvents: function() {}, onRender: function() { if (this.profileData) { if (this.typeName === "hive_table") { this.renderProfileTableLayoutView(); } else if (this.typeName === "hive_db" || this.typeName === "hbase_namespace") { this.renderSearchResultLayoutView(); } else { this.renderProfileColumnLayoutView(); } } }, renderSearchResultLayoutView: function() { var that = this; require(['views/search/SearchResultLayoutView'], function(SearchResultLayoutView) { var value = _.extend({}, that.value, { 'guid': that.guid, 'searchType': 'relationship', 'typeName': that.typeName }); that.RProfileTableOrColumnLayoutView.show(new SearchResultLayoutView({ 'value': value, 'profileDBView': true, 'typeHeaders': that.typeHeaders, 'entityDefCollection': that.entityDefCollection, 'enumDefCollection': that.enumDefCollection, 'isTableDropDisable': true, 'glossaryCollection': that.glossaryCollection, 'classificationDefCollection': that.classificationDefCollection })); }); }, renderProfileTableLayoutView: function(tagGuid) { var that = this; require(['views/profile/ProfileTableLayoutView'], function(ProfileTableLayoutView) { that.RProfileTableOrColumnLayoutView.show(new ProfileTableLayoutView(that.options)); }); }, renderProfileColumnLayoutView: function(tagGuid) { var that = this; require(['views/profile/ProfileColumnLayoutView'], function(ProfileColumnLayoutView) { that.RProfileTableOrColumnLayoutView.show(new ProfileColumnLayoutView(that.options)); }); }, }); return ProfileLayoutView; });
void Camera::update() { apply_jitter(); glm::quat qPitch = glm::angleAxis(m_pitch, glm::vec3(1.0f, 0.0f, 0.0f)); glm::quat qYaw = glm::angleAxis(m_yaw, glm::vec3(0.0f, 1.0f, 0.0f)); glm::quat qRoll = glm::angleAxis(m_roll, glm::vec3(0.0f, 0.0f, 1.0f)); // Combine the orientation quaternions in the correct order to update the camera's orientation m_orientation = qPitch * m_orientation; m_orientation = m_orientation * qYaw; m_orientation = m_orientation * qRoll; }
<reponame>HewlettPackard/catena<filename>catena/common/ansible_utils.py<gh_stars>1-10 # (C) Copyright 2017 Hewlett Packard Enterprise Development LP. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import subprocess from oslo_log import log LOG = log.getLogger(__name__) def execute(cmd): popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, universal_newlines=True) for stdout_line in iter(popen.stdout.readline, ""): yield stdout_line popen.stdout.close() return_code = popen.wait() if return_code: raise subprocess.CalledProcessError(return_code, cmd) def launch_playbook(playbook, private_key_file, hosts, ansible_vars, jumpbox_ip, jumpbox_key): host_list = ",".join(hosts) + "," # Needs a trailing comma extra_vars = json.dumps(ansible_vars, ensure_ascii=False) ssh_args = '-o ProxyCommand="ssh -q -i \\"{}\\" -W %h:%p ubuntu@{}" -o ' \ 'StrictHostKeyChecking=no'.format(jumpbox_key, jumpbox_ip) playbook_path = os.path.join(os.path.dirname(__file__), playbook) command = ["ansible-playbook", playbook_path, "-i", host_list, "--user=ubuntu", "--private-key={}".format(private_key_file), "--ssh-common-args='{}'".format(ssh_args), "--extra-vars='{}'".format(extra_vars)] LOG.debug("Running: {}".format(" ".join(command))) for stdout_line in execute(" ".join(command)): LOG.debug(stdout_line.strip())
#! /bin/bash # simple test, that the metadata repository exists curl_graph_store_get --repository "system" \ -H "Accept: application/n-quads" \ | fgrep 'http://www.w3.org/ns/auth/acl#accessTo' \ | fgrep -q "${STORE_ACCOUNT}/${STORE_REPOSITORY}"
export { default } from '@1024pix/pix-ui/components/pix-tooltip-deprecated';
#!/usr/bin/env bash # Installs configuration files, packages, and plugins set -e function dir() { local target_dir="${1}" if [ -d ${target_dir} ]; then echo "${target_dir} already exists. Skipping." elif [ -e ${target_dir} ]; then echo "${target_dir} already exists, but is not a directory. Skipping." else mkdir --parents --verbose ${target_dir} fi } function link() { local target_file="${1}" local link_name="${2}" if [ -L ${link_name} ]; then echo "${link_name} already exists. Skipping." elif [ -e ${link_name} ]; then echo "${link_name} already exists, but is not a link. Skipping." else # -s - Symbolic link # -f - If the link already exists, overwrite it # -v - Verbose output ln -sfv ${target_file} ${link_name} fi } # Set vars BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" # Directories echo "###########################" echo "# Creating Directories" echo "###########################" dir "${HOME}/.config" dir "${HOME}/.n" dir "${HOME}/.n/bin" dir "${HOME}/bin" dir "${HOME}/src" # Symlinks echo echo "###########################" echo "# Creating Symlinks" echo "###########################" link "${BASEDIR}/alacritty" "${HOME}/.config/alacritty" link "${BASEDIR}/bash/palette" "${HOME}/.palette" link "${BASEDIR}/bash/rc" "${HOME}/.bashrc" link "${BASEDIR}/git/gitignore" "${HOME}/.gitignore" link "${BASEDIR}/git/git-sh-prompt" "${HOME}/.git-prompt.sh" link "${BASEDIR}/intellij/ideavimrc" "${HOME}/.ideavimrc" link "${BASEDIR}/i3" "${HOME}/.config/i3" link "${BASEDIR}/i3status" "${HOME}/.config/i3status" link "${BASEDIR}/neovim" "${HOME}/.config/nvim" link "${BASEDIR}/neovim" "${HOME}/.vim" link "${BASEDIR}/ranger" "${HOME}/.config/ranger" link "${BASEDIR}/skhd" "${HOME}/.config/skhd" link "${BASEDIR}/sh/aliases" "${HOME}/.aliases" link "${BASEDIR}/sh/environment" "${HOME}/.environment" link "${BASEDIR}/sh/environment" "${HOME}/.zshenv" link "${BASEDIR}/tmux/tmux.conf" "${HOME}/.tmux.conf" link "${BASEDIR}/x11/Xresources" "${HOME}/.Xresources" link "${BASEDIR}/yabai" "${HOME}/.config/yabai" link "${BASEDIR}/zsh/rc" "${HOME}/.zshrc" # Packages echo echo "###########################" echo "# Installing Packages" echo "###########################" if ! command -v node &> /dev/null; then curl --location https://raw.githubusercontent.com/tj/n/master/bin/n \ --output ${HOME}/.n/bin/n chmod 755 ${HOME}/.n/bin/n bash ${HOME}/.n/bin/n lts fi if command -v pamac &> /dev/null; then sudo pamac install --no-confirm \ alacritty \ babashka-bin \ bash \ clojure-lsp-bin \ clj-kondo-bin \ curl \ ctags \ fd \ fzf \ git \ htop \ jq \ less \ make \ neovim \ ranger \ ripgrep \ shellcheck \ tmux \ tree \ wget \ zoxide-bin \ zsh elif command -v apt-get &> /dev/null; then sudo apt-get install -y \ alacritty \ bash \ curl \ exuberant-ctags \ fd \ fzf \ git \ htop \ jq \ less \ make \ neovim \ ranger \ ripgrep \ shellcheck \ tmux \ tree \ wget \ zoxide \ zsh elif command -v brew &> /dev/null; then # brew errors when packages which are already installed have upgrades # available, so we upgrade the universe before attempting to install brew upgrade brew cask upgrade brew install \ alacritty \ borkdude/brew/babashka \ borkdude/brew/clj-kondo \ bash \ clojure/tools/clojure \ clojure-lsp/brew/clojure-lsp-native \ ctags \ curl \ fd \ fzf \ git \ htop \ koekeishiya/formulae/skhd \ koekeishiya/formulae/yabai \ jq \ less \ make \ neovim \ ranger \ ripgrep \ shellcheck \ tmux \ tree \ wget \ zoxide \ zsh elif command -v yum &> /dev/null; then sudo yum install --assumeyes \ bash \ ctags \ curl \ git \ htop \ jq \ less \ make \ neovim \ shellcheck \ tmux \ tree \ wget \ zsh fi # Editor Plugins echo echo "###########################" echo "# Installing Editor Plugins" echo "###########################" if command -v nvim &> nvim; then echo "Installing plugins in nvim" nvim --headless +PlugInstall +CocInstall +qall elif command -v vim &> vim; then echo "Installing plugins in vim" vim +PlugInstall +qall else echo "Unable to locate editor" fi
<gh_stars>0 //Consumindo API (1:00:00, 2°ep) // SPA // (não indexavel usa javascript do browser) /* import {useEffect} from "react" export default function Home() { useEffect(() => { fetch("http://localhost:3333/episodes") .then(response => response.json()) .then(data => console.log(data)) }, []) return (<h1>Index</h1>); } */ // SSR // Alterações em tempo real, sempre atualizando /* import {GetServerSideProps} from "next" export default function Home(props) { console.log(props.episodes) return ( <h1>Index</h1> ); } export async function getServerSideProps(){ const response = await fetch("http://localhost:3333/episodes"); const data = await response.json(); return { // precisa retornar o props props: { episodes: data, } } } */ //SSG // cria um cache destes dados // pagina semi-estatica. //todos os acessos terão o mesmo resultado! // sem tipagem: export async function getStaticProps(){ // <p>{JSON.stringify(props.episodes)}</p> import {GetStaticProps} from "next"; import { api } from "../services/api"; import Image from "next/image"; import Link from "next/link"; import Head from "next/head"; import { format, parseISO} from "date-fns"; import ptBR from "date-fns/locale/pt-BR"; import { convertSecondsToTime } from "../misc/convertSecondsToTime"; import {useRouter} from "next/router"; import styles from "../styles/home.module.scss"; import { usePlayer } from "../context/PlayerContex"; type Episode = { id: string, title: string, thumbnail: string, members: string, publishedAt: string, duration: number, durationString: string, url: string, } type HomeProps = { latestEpisodes: Episode[], allEpisodes: Episode[], } export default function Home(props: HomeProps) { const { playList } = usePlayer(); const episodeList = [...props.latestEpisodes, ...props.allEpisodes]; // console.log(props.allEpisodes) return ( <div className={styles.homepage}> <Head> <title>Home | WorldListener </title> </Head> <section className={styles.latestEpisodes}> <h2>Últimos episodios</h2> <ul> {props.latestEpisodes.map((episode, index) => { return ( //necessário uma key para melhor gerenciamento! (3ª 38min) <li key={episode.id}> <Image width={192} height={192} objectFit="cover" src={episode.thumbnail} alt={episode.title} /> <div className={styles.episodeDetails} > <span> <Link href={`/episodes/${episode.id}`}> <a>{episode.title}</a> </Link> </span> <p>{episode.members}</p> <span>{episode.publishedAt}</span> <span>{episode.durationString}</span> </div> <button type="button" onClick={() => playList(episodeList, index)}> <img src="/play-green.svg" alt="Inmiciar Episodio"/> </button> </li> ) })} </ul> </section> <section className={styles.allEpisodes}> <h2>Todos episódios</h2> <table cellSpacing={0}> <thead> <tr> <th></th> <th>Podcast</th> <th>Integrantes</th> <th>Data</th> <th>Duração</th> <th></th> </tr> </thead> <tbody> {props.allEpisodes.map((episode, index) => { return ( <tr key={episode.id}> <td style={{width: 65}}> <Image width={120} height={120} src={episode.thumbnail} alt={episode.title} objectFit="cover"/> </td> <td> <Link href={`/episodes/${episode.id}`}> <a>{episode.title}</a> </Link> </td> <td>{episode.members}</td> <td style={{width: 95}}>{episode.publishedAt}</td> <td>{episode.durationString}</td> <td> <button type="button" onClick={() => playList(episodeList, index + props.latestEpisodes.length)}> <img src="/play-green.svg" alt="Iniciar Episodio"/> </button> </td> </tr> ) } )} </tbody> </table> </section> </div> ); } //15:50 3ª aula export const getStaticProps: GetStaticProps = async () => { const { data } = await api.get("episodes" , { params: { _limit: 12, _sort: "published_at", _order: "desc", } }); //formatando os dados const episodes = data.map(episode => { return { id: episode.id, title: episode.title, thumbnail: episode.thumbnail, members: episode.members, publishedAt: format(parseISO(episode.published_at), "d MMM yy", {locale: ptBR}), duration: Number(episode.file.duration), durationString: convertSecondsToTime(Number(episode.file.duration)), url: episode.file.url, }; }) const latestEpisodes = episodes.slice(0, 2); const allEpisodes = episodes.slice(2, episodes.length) return { // precisa retornar o props props: { latestEpisodes, allEpisodes, }, // timer do cache, (8hrs) revalidate: 60*60*8, } }
import type { NextPage } from "next"; import { useEffect, useRef, useState } from "react"; import socketIOClient from "socket.io-client"; import { Field, Form, Formik, FormikHelpers } from "formik"; import { Message } from "@chatapp/shared"; import MessageListComponent from "../components/MessageListComponent"; import Head from "next/head"; import NavbarComponent from "../components/NavbarComponent"; export const ENDPOINT = "http://localhost:4000"; const Home: NextPage = () => { const [socket, setSocket] = useState(socketIOClient(ENDPOINT)); const msgRef = useRef<HTMLDivElement>(null); const [msgs, setmsgs] = useState<Message[]>([]); useEffect(() => { socket.on("message", (text: Message) => { setmsgs((prev) => { return [...prev, text]; }); }); }, []); const handleSend = (msg: Message, { resetForm }: FormikHelpers<Message>) => { if (msg.content) { console.log("Sending Message", msg); socket.emit("message", msg); resetForm(); } if (msgRef && msgRef.current) { msgRef.current.style.scrollBehavior = "smooth"; msgRef.current.scrollTop = msgRef.current.scrollHeight; } }; const initialValues: Message = { content: "", }; return ( <> <Head> <title>Home | Simple Chatapp</title> </Head> <div className="h-full flex flex-col"> <header> <NavbarComponent /> </header> <br /> <main className="flex-grow flex justify-center overflow-y-auto px-2" ref={msgRef} > <div className="container"> <MessageListComponent msgs={msgs} socket={socket} /> </div> </main> <footer> <div className="p-3 bg-gray-200"> <Formik initialValues={initialValues} onSubmit={handleSend}> <Form className="flex justify-between"> <Field className="px-5 flex-grow text-xl rounded" name="content" placeholder="Type Message here..." autoComplete="off" /> <button className="mx-5 py-3 px-5 rounded bg-gray-300 hover:bg-gray-400" type="submit" > Send </button> </Form> </Formik> </div> </footer> </div> </> ); }; export default Home;
#!/bin/bash # Git Version Control System Cookbook # Chapter 1 - Navigating Git # # Copyright 2014 Aske Olsson # # Show whats is happening set -x # Git VCS cookbook # Chapter 1 - Extracting fixed issues # Getting ready #Clone the jgit repository git clone https://git.eclipse.org/r/jgit/jgit cd jgit # Reset to known state git checkout master && git reset --hard b14a939 # How to do it git describe # Grep for "Bug: " in commit messages from head to tag git log --grep="Bug: " v3.1.0.201310021548-r..HEAD | cat # Format the above git log --grep="Bug: " v3.1.0.201310021548-r..HEAD --pretty="%h|%s%n%b" | cat # Find and replace with grep and sed, the full command git log --grep "Bug: " v3.1.0.201310021548-r..HEAD --pretty="%h|%s%n%b" \ | grep -E "\||Bug: " | sed -e 's/|/: /' -e 's/Bug:/Fixes-bug:/' # Just the bug ids git log v3.1.0.201310021548-r..HEAD | grep "Bug: " # Commit ids and subject, not bug id git log --grep "Bug: " --oneline v3.1.0.201310021548-r..HEAD # Exit subdir cd ..
import Ember from 'ember'; export default Ember.Route.extend({ model: function(params/*, transition*/) { var store = this.get('store'); var dependencies = []; if ( params.serviceId ) { dependencies.pushObject(store.find('service', params.serviceId)); } return Ember.RSVP.all(dependencies, 'Load dependencies').then(function(results) { var existing = results[0]; var dns; if ( existing ) { dns = existing.cloneForNew(); } else { dns = store.createRecord({ type: 'dnsService', name: '', description: '', stackId: params.stackId, startOnCreate: true, }); } return { service: dns, existing: existing, }; }); }, resetController: function (controller, isExisting/*, transition*/) { if (isExisting) { controller.set('stackId', null); controller.set('serviceId', null); } }, });
// (A -> B -> C) -> B -> A -> C export function flip<A, B, C>(fn: (a: A, b: B) => C, b: B, a: A) { return fn(a, b); }
def process_repeat_annotations(args: dict) -> list: bundle_size = args.get('bundle_size', 0) pthresh = args.get('pthresh', 0) bup = args.get('bup', 0) repcnts = _load_reps(args.get('rep_file', '')) # Load repeat annotations processed_annotations = [] # Initialize list to store processed annotations for annotation in repcnts: # Process the repeat annotations based on the provided parameters processed_annotation = { 'annotation': annotation, 'processed_bundle_size': annotation * bundle_size, 'processed_pthresh': annotation * pthresh, 'processed_bup': annotation * bup } processed_annotations.append(processed_annotation) return processed_annotations
/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You 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. ****************************************************************************/ /** * @file * @brief IronBee --- Logger * * @author <NAME> <<EMAIL>> */ #include "ironbee_config_auto.h" #include <ironbee/logger.h> #include <ironbee/mm_mpool_lite.h> #include <ironbee/string.h> #include <assert.h> #include <stdlib.h> /** * A collection of callbacks and function pointer that implement a logger. */ struct ib_logger_writer_t { ib_logger_open_fn_t open_fn; /**< Open the logger. */ void *open_data; /**< Callback data. */ ib_logger_close_fn_t close_fn; /**< Close logs files. */ void *close_data; /**< Callback data. */ ib_logger_reopen_fn_t reopen_fn; /**< Close and reopen log files. */ void *reopen_data; /**< Callback data. */ ib_logger_format_t *format; /**< Format a message. */ ib_logger_record_fn_t record_fn; /**< Signal a record is ready. */ void *record_data; /**< Callback data. */ ib_queue_t *records; /**< Records for the log writer. */ ib_lock_t records_lck; /**< Guard the queue. */ }; //! Identify the type of a logger callback function. enum logger_callback_fn_type_enum { LOGGER_OPEN_FN, /**< @ref ib_logger_open_fn_t type. */ LOGGER_CLOSE_FN, /**< @ref ib_logger_close_fn_t type. */ LOGGER_REOPEN_FN, /**< @ref ib_logger_reopen_fn_t type. */ LOGGER_FORMAT_FN, /**< @ref ib_logger_format_fn_t type. */ LOGGER_RECORD_FN /**< @ref ib_logger_record_fn_t type. */ }; typedef enum logger_callback_fn_type_enum logger_callback_fn_type_enum; struct logger_callback_fn_t { //! The type of function stored in this structure. logger_callback_fn_type_enum type; //! A union of the different function pointer types. union { ib_logger_open_fn_t open_fn; /**< Open function. */ ib_logger_close_fn_t close_fn; /**< Close function. */ ib_logger_reopen_fn_t reopen_fn; /**< Reopen function. */ ib_logger_record_fn_t record_fn; /**< Record function. */ ib_logger_format_t *format; /**< Format funcs and cbdata. */ } fn; //! The callback data the user would like associated with the callback. void *cbdata; }; typedef struct logger_callback_fn_t logger_callback_fn_t; /** * A logger is what @ref ib_logger_rec_t are submitted to to produce a log. */ struct ib_logger_t { ib_logger_level_t level; /**< The log level. */ /** * Memory manager defining lifetime of the logger. */ ib_mm_t mm; /** * List of @ref ib_logger_writer_t. * * A logger, by itself, cannot log anything. The writers * implement the actual logging functionality. This list is the list * of all writers that this logger will send messages to. * * Writers also get notified of flush, open, close, and reopen events. */ ib_list_t *writers; /** * A map of logger_callback_fn_t structs that name a function. * * Often the provider of a @ref ib_logger_format_fn_t is not * aware of the @ref ib_logger_record_fn_t that will use it. In such * cases it is often very useful to be able to store * a function by name to be retrieved later. * * This hash allows different logger functions to be stored and * retrieved to assist clients to this API to better share functions. */ ib_hash_t *functions; }; /** * The pair of formatting function and output message free function. * * The format function outputs a message that the @ref ib_logger_record_fn_t * function must finally log. Because the record function * may occur much later than the format function, even after the lifetime * of a transaction that has generated a log message, * it is the record function's responsibility to free the outputted message. */ struct ib_logger_format_t { //! Format a log message. ib_logger_format_fn_t format_fn; //! Callback data for ib_logger_format_t::format_fn.; void *format_cbdata; /** * Free the message generated by ib_logger_format_t::format_fn. * * May be null. */ ib_logger_format_free_fn_t format_free_fn; //! Callback data for ib_logger_format_t::format_free_fn. void *format_free_cbdata; }; /** * Writer function. * * @param[in] logger The logger. * @param[in] writer The writer. * @param[in] cbdata Callback data. * @returns * - IB_OK On success. * - Other on error. */ typedef ib_status_t (*writer_fn)( ib_logger_t *logger, ib_logger_writer_t *writer, void *cbdata); /** * Iterate over every @ref ib_logger_writer_t in @a logger and apply @a fn. * * @param[in] logger The logger. * @param[in] fn The function to apply to every @ref ib_logger_writer_t. * @param[in] data Callback data. * * @returns * - IB_OK On success. * - The first non-IB_OK code returned by @a fn. The @a fn function is * always applied to all writers. */ static ib_status_t for_each_writer( ib_logger_t *logger, writer_fn fn, void *data ) { assert(logger != NULL); ib_status_t rc = IB_OK; const ib_list_node_t *node; IB_LIST_LOOP_CONST(logger->writers, node) { ib_logger_writer_t *writer = (ib_logger_writer_t *)ib_list_node_data_const(node); if (fn != NULL) { ib_status_t trc = fn(logger, writer, data); if (trc != IB_OK && rc == IB_OK) { rc = trc; } } } return rc; } /** * Structure to hold the user's log message to format. */ typedef struct logger_write_cbdata_t { const uint8_t *msg; /**< The message. */ size_t msg_sz; /**< The size of the message. */ ib_logger_rec_t *rec; /**< Record used to format. */ } logger_write_cbdata_t; /** * The maximum depth of a message queue in a @ref ib_logger_writer_t. */ static const size_t MAX_QUEUE_DEPTH = 1000; /** * The implementation for logger_log(). * * This function will * - Format the message stored in @a cbdata as a @ref logger_write_cbdata_t. * - Lock the message queue. * - Enqueue the formatted message. * - If the message is the only message in the queue, * ib_logger_writer_t::record_fn is called to signal the * writer that at least one record is available. * * @param[in] logger The logger. * @param[in] writer The logger writer to send the message to. * @param[in] cbdata @ref logger_write_cbdata_t containing the user's message. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_write( ib_logger_t *logger, ib_logger_writer_t *writer, void *cbdata ) { ib_status_t rc; void *rec = NULL; logger_write_cbdata_t *logger_write_data = (logger_write_cbdata_t *)cbdata; if (writer->format == NULL) { return IB_DECLINED; } if (writer->format->format_fn == NULL) { return IB_DECLINED; } rc = writer->format->format_fn( logger, logger_write_data->rec, logger_write_data->msg, logger_write_data->msg_sz, &rec, writer->format->format_cbdata); if (rc == IB_DECLINED || rec == NULL) { return IB_OK; } if (rc != IB_OK) { return rc; } rc = ib_lock_lock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } /* Busy-wait until the queue has space available. * This is emergency code to avoid a crash at the cost of a slowdown. */ while (ib_queue_size(writer->records) >= MAX_QUEUE_DEPTH) { rc = ib_lock_unlock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } /* TODO - The number of times we need to sleep should be * audited. It is a good indicator of excessive logging or * proxy load. */ sleep(1); rc = ib_lock_lock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } } rc = ib_queue_push_front(writer->records, rec); if (rc != IB_OK) { return rc; } /* If the queue is size=1, unlock and notify writers. */ if (ib_queue_size(writer->records) == 1) { ib_lock_unlock(&(writer->records_lck)); rc = writer->record_fn(logger, writer, writer->record_data); return rc; } ib_lock_unlock(&(writer->records_lck)); return rc; } /** * Determine if the logger message should be filtered (ignored) or not. * * This is common filtering code. While it seems simple now, it is * expected to grow as features are added to the logger api. * * @param[in] logger The logger. * @param[in] level The level of the message. * * @returns * - True if the message should be discarded. * - False if the message should not be discarded. */ static bool logger_filter( ib_logger_t *logger, ib_logger_level_t level ) { assert(logger != NULL); if (level <= logger->level) { return false; } return true; } /** * Actually perform the logging. */ static void logger_log( ib_logger_t *logger, ib_logger_rec_t *rec, const uint8_t *msg, size_t msg_sz ) { assert(logger != NULL); logger_write_cbdata_t logger_write_data = { msg, msg_sz, rec }; /* For each logger, * - format the log message * - enqueue the log message * - signal the log writer if it was waiting on an empty queue. */ for_each_writer(logger, logger_write, &logger_write_data); } void ib_logger_log_msg( ib_logger_t *logger, ib_logger_logtype_t type, const char *file, const char *function, size_t line_number, const ib_engine_t *engine, const ib_module_t *module, const ib_conn_t *conn, const ib_tx_t *tx, ib_logger_level_t level, const uint8_t *msg, size_t msg_sz, ib_logger_msg_fn_t msg_fn, void *msg_fn_data ) { ib_status_t rc; const uint8_t *log_msg; /* Final message. */ size_t log_msg_sz; uint8_t *fn_msg; /* Message generated by msg_fn. */ size_t fn_msg_sz; ib_logger_rec_t rec; ib_mpool_lite_t *mpl = NULL; if (logger_filter(logger, level)) { return; } rc = ib_mpool_lite_create(&mpl); if (rc != IB_OK) { return; } rec.type = type; rec.line_number = line_number; rec.file = file; rec.function = function; rec.timestamp = ib_clock_get_time(); rec.module = module; rec.conn = conn; rec.tx = tx; rec.engine = engine; rec.level = level; /* Build the message using the user's function. */ rc = msg_fn(&rec, ib_mm_mpool_lite(mpl), &fn_msg, &fn_msg_sz, msg_fn_data); if (rc != IB_OK) { goto exit; } /* Do not log empty messages. */ if (msg_sz + fn_msg_sz == 0) { goto exit; } /* If msg is 0, use fn_msg. */ if (msg_sz == 0) { log_msg_sz = fn_msg_sz; log_msg = fn_msg; } /* If fn_msg is 0, use msg. */ else if(fn_msg_sz == 0) { log_msg_sz = msg_sz; log_msg = msg; } /* Else, both messages are non-zero. Concatenate them. */ else { log_msg_sz = msg_sz + fn_msg_sz; /* Get a non-const alias for what will be log_msg memory. */ uint8_t *tmp_msg = ib_mpool_lite_alloc(mpl, log_msg_sz); log_msg = tmp_msg; if (tmp_msg == NULL) { goto exit; } /* Build msg. */ memcpy(tmp_msg, msg, msg_sz); memcpy(tmp_msg+msg_sz, fn_msg, fn_msg_sz); } /* Finally log the message. */ logger_log(logger, &rec, log_msg, log_msg_sz); exit: ib_mpool_lite_destroy(mpl); } void ib_logger_log_va( ib_logger_t *logger, ib_logger_logtype_t type, const char *file, const char *function, size_t line_number, const ib_engine_t *engine, const ib_module_t *module, const ib_conn_t *conn, const ib_tx_t *tx, ib_logger_level_t level, const char *msg, ... ) { va_list ap; va_start(ap, msg); ib_logger_log_va_list( logger, type, file, function, line_number, engine, module, conn, tx, level, msg, ap ); va_end(ap); } void ib_logger_log_va_list( ib_logger_t *logger, ib_logger_logtype_t type, const char *file, const char *function, size_t line_number, const ib_engine_t *engine, const ib_module_t *module, const ib_conn_t *conn, const ib_tx_t *tx, ib_logger_level_t level, const char *msg, va_list ap ) { ib_status_t rc; uint8_t *log_msg; /* Final message. */ size_t log_msg_sz = 1024; ib_logger_rec_t rec; ib_mpool_lite_t *mpl = NULL; if (logger_filter(logger, level)) { return; } rc = ib_mpool_lite_create(&mpl); if (rc != IB_OK) { return; } log_msg = ib_mpool_lite_alloc(mpl, log_msg_sz); if (log_msg == NULL) { ib_mpool_lite_destroy(mpl); return; } log_msg_sz = vsnprintf((char *)log_msg, log_msg_sz, msg, ap); rec.type = type; rec.line_number = line_number; rec.file = file; rec.function = function; rec.timestamp = ib_clock_get_time(); rec.module = module; rec.conn = conn; rec.tx = tx; rec.engine = engine; rec.level = level; logger_log(logger, &rec, log_msg, log_msg_sz); ib_mpool_lite_destroy(mpl); } /** * Default logger configuration. */ typedef struct default_logger_cfg_t { FILE * file; /**< File to log to. */ } default_logger_cfg_t; //! Limit the size of a message that the default formatter will generate. static const size_t DEFAULT_LOGGER_FORMAT_MAX_MSG = 8 * 1024; /** * The default logger format function. * * This wraps ib_logger_standard_formatter() and reports errors to the * log file defined by default_logger_cfg_t::file. * * param[in] logger The logger. * param[in] rec The record. * param[in] log_msg The user's log message. * param[in] log_msg_sz The length of @a log_msg. * param[in] writer_record A @a ib_logger_standard_msg_t will be written here * on success. * param[in] data A @a default_logger_cfg_t holding default logger * configuration information. */ static ib_status_t default_logger_format( ib_logger_t *logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, size_t log_msg_sz, void *writer_record, void *data ) { assert(logger != NULL); assert(rec != NULL); assert(log_msg != NULL); assert(writer_record != NULL); ib_status_t rc; default_logger_cfg_t *cfg = (default_logger_cfg_t *)data; if (log_msg_sz > DEFAULT_LOGGER_FORMAT_MAX_MSG) { log_msg_sz = DEFAULT_LOGGER_FORMAT_MAX_MSG; } rc = ib_logger_standard_formatter( logger, rec, log_msg, log_msg_sz, writer_record, data); if (rc == IB_EALLOC) { ib_logger_standard_msg_free( logger, *(void **)writer_record, data); fprintf(cfg->file, "Out of memory. Unable to log."); fflush(cfg->file); } else if (rc != IB_OK && rc != IB_DECLINED) { ib_logger_standard_msg_free( logger, *(void **)writer_record, data); fprintf(cfg->file, "Unexpected error."); fflush(cfg->file); } return rc; } /* Default logger format struct. */ static ib_logger_format_t default_format = { .format_fn = default_logger_format, .format_cbdata = NULL, .format_free_fn = ib_logger_standard_msg_free, .format_free_cbdata = NULL }; ib_status_t ib_logger_create( ib_logger_t **logger, ib_logger_level_t level, ib_mm_t mm ) { assert(logger != NULL); ib_logger_t *l; ib_status_t rc; l = (ib_logger_t *)ib_mm_alloc(mm, sizeof(*l)); if (l == NULL) { return IB_EALLOC; } l->level = level; l->mm = mm; rc = ib_list_create(&(l->writers), mm); if (rc != IB_OK) { return rc; } rc = ib_hash_create(&(l->functions), mm); if (rc != IB_OK) { return rc; } rc = ib_logger_register_format( l, IB_LOGGER_DEFAULT_FORMATTER_NAME, &default_format); if (rc != IB_OK) { return rc; } *logger = l; return IB_OK; } ib_status_t ib_logger_writer_add( ib_logger_t *logger, ib_logger_open_fn_t open_fn, void *open_data, ib_logger_close_fn_t close_fn, void *close_data, ib_logger_reopen_fn_t reopen_fn, void *reopen_data, ib_logger_format_t *format, ib_logger_record_fn_t record_fn, void *record_data ) { assert(logger != NULL); assert(logger->writers != NULL); ib_status_t rc; ib_logger_writer_t *writer; writer = (ib_logger_writer_t *)ib_mm_alloc(logger->mm, sizeof(*writer)); if (writer == NULL) { return IB_EALLOC; } writer->open_fn = open_fn; writer->open_data = open_data; writer->close_fn = close_fn; writer->close_data = close_data; writer->reopen_fn = reopen_fn; writer->reopen_data = reopen_data; writer->format = format; writer->record_fn = record_fn; writer->record_data = record_data; rc = ib_queue_create(&(writer->records), logger->mm, IB_QUEUE_NEVER_SHRINK); if (rc != IB_OK) { return rc; } rc = ib_lock_init(&(writer->records_lck)); if (rc != IB_OK) { return rc; } rc = ib_list_push(logger->writers, writer); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_logger_writer_clear( ib_logger_t *logger ) { assert(logger != NULL); assert(logger->writers != NULL); ib_list_clear(logger->writers); return IB_OK; } /** * Implementation for ib_logger_open(). * * @param[in] logger The logger. * @param[in] writer The writer to perform the function on. * @param[in] data Callback data. NULL. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_open( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data == NULL); if (writer->open_fn == NULL) { return IB_OK; } return writer->open_fn(logger, writer->open_data); } ib_status_t ib_logger_open( ib_logger_t *logger ) { assert(logger != NULL); return for_each_writer(logger, logger_open, NULL); } /** * Implementation for ib_logger_close(). * * @param[in] logger The logger. * @param[in] writer The writer to perform the function on. * @param[in] data Callback data. NULL. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_close( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data == NULL); if (writer->close_fn == NULL) { return IB_OK; } return writer->close_fn(logger, writer->close_data); } ib_status_t ib_logger_close( ib_logger_t *logger ) { assert(logger != NULL); return for_each_writer(logger, logger_close, NULL); } /** * Implementation for ib_logger_reopen(). * * @param[in] logger The logger. * @param[in] writer The writer to perform the function on. * @param[in] data Callback data. NULL. * * @returns * - IB_OK On success. * - Other on implementation failure. */ static ib_status_t logger_reopen( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data == NULL); if (writer->reopen_fn == NULL) { return IB_OK; } return writer->reopen_fn(logger, writer->reopen_data); } ib_status_t ib_logger_reopen( ib_logger_t *logger ) { assert(logger != NULL); return for_each_writer(logger, logger_reopen, NULL); } /** * Custom callback data for logger_handler(). */ struct logger_handler_cbdata_t { ib_logger_t *logger; /**< The logger. */ ib_queue_element_fn_t user_fn; /**< User's callback function. */ void *user_data; /**< User's callback data. */ ib_logger_format_free_fn_t free_fn; /**< Free the queue element. */ void *free_data; /**< Free callback data. */ }; typedef struct logger_handler_cbdata_t logger_handler_cbdata_t; /** * Dispatches log message to handler, then frees them. */ static void logger_handler(void *element, void *cbdata) { assert(cbdata != NULL); logger_handler_cbdata_t *data = (logger_handler_cbdata_t *)cbdata; /* Let the user write the record. */ data->user_fn(element, data->user_data); /* Free the data. */ data->free_fn(data->logger, element, data->free_data); } ib_status_t ib_logger_dequeue( ib_logger_t *logger, ib_logger_writer_t *writer, ib_queue_element_fn_t handler, void *cbdata ) { assert(logger != NULL); assert(writer != NULL); assert(writer->records != NULL); ib_status_t rc; logger_handler_cbdata_t logger_handler_cbdata = { .logger = logger, .user_fn = handler, .user_data = cbdata, .free_fn = writer->format->format_free_fn, .free_data = writer->format->format_free_cbdata }; rc = ib_lock_lock(&(writer->records_lck)); if (rc != IB_OK) { return rc; } rc = ib_queue_dequeue_all_to_function( writer->records, logger_handler, &logger_handler_cbdata); ib_lock_unlock(&(writer->records_lck)); return rc; } size_t ib_logger_writer_count(ib_logger_t *logger) { assert(logger != NULL); assert(logger->writers != NULL); return ib_list_elements(logger->writers); } ib_logger_level_t ib_logger_level_get(ib_logger_t *logger) { assert(logger != NULL); return logger->level; } void ib_logger_level_set(ib_logger_t *logger, ib_logger_level_t level) { assert(logger != NULL); logger->level = level; } void ib_logger_standard_msg_free( ib_logger_t *logger, void *writer_record, void *cbdata ) { assert(logger != NULL); assert(writer_record != NULL); ib_logger_standard_msg_t *msg = (ib_logger_standard_msg_t *)writer_record; if (msg != NULL) { if (msg->prefix != NULL) { free(msg->prefix); } if (msg->msg != NULL) { free(msg->msg); } free(msg); } } ib_status_t ib_logger_standard_formatter_notime( ib_logger_t *logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, const size_t log_msg_sz, void *writer_record, void *data ) { assert(logger != NULL); assert(rec != NULL); assert(log_msg != NULL); assert(writer_record != NULL); ib_logger_standard_msg_t *msg; if (rec->type != IB_LOGGER_ERRORLOG_TYPE) { return IB_DECLINED; } msg = malloc(sizeof(*msg)); if (msg == NULL) { goto out_of_mem; } msg->prefix = NULL; msg->msg = NULL; /* 100 is more than sufficient. */ msg->prefix = (char *)malloc(100); if (msg->prefix == NULL) { goto out_of_mem; } sprintf( msg->prefix, "%-10s- ", ib_logger_level_to_string(rec->level)); /* Add the file name and line number if available and log level >= DEBUG */ if ( (rec->file != NULL) && (rec->line_number > 0) && (logger->level >= IB_LOG_DEBUG) ) { const char *file = rec->file; size_t flen; while (strncmp(file, "../", 3) == 0) { file += 3; } flen = strlen(file); if (flen > 23) { file += (flen - 23); } static const size_t c_line_info_length = 35; char line_info[c_line_info_length]; snprintf( line_info, c_line_info_length, "(%23s:%-5d) ", file, (int)rec->line_number ); strcat(msg->prefix, line_info); } /* If this is a transaction, add the TX id */ if (rec->tx != NULL) { static const size_t c_line_info_size = 43; char line_info[c_line_info_size]; strcpy(line_info, "[tx:"); strcat(line_info, rec->tx->id); strcat(line_info, "] "); strcat(msg->prefix, line_info); } msg->msg_sz = log_msg_sz; msg->msg = malloc(log_msg_sz); if (msg->msg == NULL) { goto out_of_mem; } memcpy(msg->msg, log_msg, log_msg_sz); *(ib_logger_standard_msg_t **)writer_record = msg; return IB_OK; out_of_mem: if (msg != NULL) { ib_logger_standard_msg_free(logger, msg, data); } return IB_EALLOC; } ib_status_t ib_logger_standard_formatter( ib_logger_t *logger, const ib_logger_rec_t *rec, const uint8_t *log_msg, const size_t log_msg_sz, void *writer_record, void *data ) { assert(logger != NULL); assert(rec != NULL); assert(log_msg != NULL); assert(writer_record != NULL); char time_info[32 + 1]; struct tm *tminfo; time_t timet; ib_logger_standard_msg_t *msg; if (rec->type != IB_LOGGER_ERRORLOG_TYPE) { return IB_DECLINED; } msg = malloc(sizeof(*msg)); if (msg == NULL) { goto out_of_mem; } msg->prefix = NULL; msg->msg = NULL; timet = time(NULL); tminfo = localtime(&timet); strftime(time_info, sizeof(time_info)-1, "%Y%m%d.%Hh%Mm%Ss", tminfo); /* 100 is more than sufficient. */ msg->prefix = (char *)malloc(strlen(time_info) + 100); if (msg->prefix == NULL) { goto out_of_mem; } sprintf( msg->prefix, "%s %-10s- ", time_info, ib_logger_level_to_string(rec->level)); /* Add the file name and line number if available and log level >= DEBUG */ if ( (rec->file != NULL) && (rec->line_number > 0) && (logger->level >= IB_LOG_DEBUG) ) { const char *file = rec->file; size_t flen; while (strncmp(file, "../", 3) == 0) { file += 3; } flen = strlen(file); if (flen > 23) { file += (flen - 23); } static const size_t c_line_info_length = 35; char line_info[c_line_info_length]; snprintf( line_info, c_line_info_length, "(%23s:%-5d) ", file, (int)rec->line_number ); strcat(msg->prefix, line_info); } /* If this is a transaction, add the TX id */ if (rec->tx != NULL) { static const size_t c_line_info_size = 43; char line_info[c_line_info_size]; strcpy(line_info, "[tx:"); strcat(line_info, rec->tx->id); strcat(line_info, "] "); strcat(msg->prefix, line_info); } msg->msg_sz = log_msg_sz; msg->msg = malloc(log_msg_sz); if (msg->msg == NULL) { goto out_of_mem; } memcpy(msg->msg, log_msg, log_msg_sz); *(ib_logger_standard_msg_t **)writer_record = msg; return IB_OK; out_of_mem: if (msg != NULL) { ib_logger_standard_msg_free(logger, msg, data); } return IB_EALLOC; } static void default_log_writer(void *record, void *cbdata) { assert(record != NULL); assert(cbdata != NULL); default_logger_cfg_t *cfg = (default_logger_cfg_t *)cbdata; ib_logger_standard_msg_t *msg = (ib_logger_standard_msg_t *)record; fprintf( cfg->file, "%s %.*s\n", msg->prefix, (int)msg->msg_sz, (char *)msg->msg); fflush(cfg->file); } /** * The default logger's record call. */ static ib_status_t default_logger_record( ib_logger_t *logger, ib_logger_writer_t *writer, void *data ) { assert(logger != NULL); assert(writer != NULL); assert(data != NULL); return ib_logger_dequeue(logger, writer, default_log_writer, data); } ib_status_t ib_logger_writer_add_default( ib_logger_t *logger, FILE *logfile ) { assert(logger != NULL); default_logger_cfg_t *cfg; cfg = ib_mm_alloc(logger->mm, sizeof(*cfg)); if (cfg == NULL) { return IB_EALLOC; } cfg->file = logfile; return ib_logger_writer_add( logger, NULL, /* Open. */ NULL, NULL, /* Close. */ NULL, NULL, /* Reopen. */ NULL, &default_format, default_logger_record, cfg ); } static const char* c_log_levels[] = { "EMERGENCY", "ALERT", "CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG", "DEBUG2", "DEBUG3", "TRACE" }; static size_t c_num_levels = sizeof(c_log_levels)/sizeof(*c_log_levels); ib_logger_level_t ib_logger_string_to_level( const char *s, ib_logger_level_t dlevel ) { unsigned int i; ib_num_t level; /* First, if it's a number, just do a numeric conversion */ if (ib_string_to_num(s, 10, &level) == IB_OK) { return (ib_logger_level_t)level; } /* Now, string compare to level names */ for (i = 0; i < c_num_levels; ++i) { if ( strncasecmp(s, c_log_levels[i], strlen(c_log_levels[i])) == 0 && strlen(s) == strlen(c_log_levels[i]) ) { return i; } } /* No match, return the default */ return dlevel; } const char *ib_logger_level_to_string(ib_logger_level_t level) { if (level < c_num_levels) { return c_log_levels[level]; } else { return "UNKNOWN"; } } static ib_status_t logger_register_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t fn, void *cbdata ) NONNULL_ATTRIBUTE(1, 3); static ib_status_t logger_register_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t fn, void *cbdata ) { ib_status_t rc; logger_callback_fn_t *logger_callback_fn; logger_callback_fn = ib_mm_alloc(logger->mm, sizeof(*logger_callback_fn)); if (logger_callback_fn == NULL) { return IB_EALLOC; } logger_callback_fn->cbdata = cbdata; logger_callback_fn->type = type; switch (type) { case LOGGER_OPEN_FN: logger_callback_fn->fn.open_fn = (ib_logger_open_fn_t)fn; break; case LOGGER_CLOSE_FN: logger_callback_fn->fn.close_fn = (ib_logger_close_fn_t)fn; break; case LOGGER_REOPEN_FN: logger_callback_fn->fn.reopen_fn = (ib_logger_reopen_fn_t)fn; break; case LOGGER_RECORD_FN: logger_callback_fn->fn.record_fn = (ib_logger_record_fn_t)fn; break; default: return IB_EINVAL; } /* Set the value. */ rc = ib_hash_set(logger->functions, name, logger_callback_fn); if (rc != IB_OK) { return rc; } return IB_OK; }; ib_status_t ib_logger_register_open_fn( ib_logger_t *logger, const char *fn_name, ib_logger_open_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_OPEN_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } ib_status_t ib_logger_register_close_fn( ib_logger_t *logger, const char *fn_name, ib_logger_close_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_CLOSE_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } ib_status_t ib_logger_register_reopen_fn( ib_logger_t *logger, const char *fn_name, ib_logger_reopen_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_REOPEN_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } ib_status_t ib_logger_register_format( ib_logger_t *logger, const char *format_name, ib_logger_format_t *format ) { assert(logger != NULL); assert(format_name != NULL); ib_status_t rc; logger_callback_fn_t *logger_callback_fn; logger_callback_fn = ib_mm_alloc(logger->mm, sizeof(*logger_callback_fn)); if (logger_callback_fn == NULL) { return IB_EALLOC; } logger_callback_fn->cbdata = NULL; logger_callback_fn->type = LOGGER_FORMAT_FN; logger_callback_fn->fn.format = format; /* Set the value. */ rc = ib_hash_set(logger->functions, format_name, logger_callback_fn); if (rc != IB_OK) { return rc; } return IB_OK; } ib_status_t ib_logger_register_record_fn( ib_logger_t *logger, const char *fn_name, ib_logger_record_fn_t fn, void *cbdata ) { assert(logger != NULL); assert(fn_name != NULL); return logger_register_fn( logger, LOGGER_RECORD_FN, fn_name, (ib_void_fn_t)(fn), cbdata); } static ib_status_t logger_fetch_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t *fn, void *cbdata ) NONNULL_ATTRIBUTE(1, 3, 4, 5); static ib_status_t logger_fetch_fn( ib_logger_t *logger, logger_callback_fn_type_enum type, const char *name, ib_void_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); logger_callback_fn_t *logger_callback_fn; ib_status_t rc; rc = ib_hash_get(logger->functions, &logger_callback_fn, name); if (rc != IB_OK) { return rc; } /* Validate that the expected type matches. */ if (logger_callback_fn->type != type) { return IB_EINVAL; } switch (type) { case LOGGER_OPEN_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.open_fn; break; case LOGGER_CLOSE_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.close_fn; break; case LOGGER_REOPEN_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.reopen_fn; break; case LOGGER_RECORD_FN: *fn = (ib_void_fn_t)logger_callback_fn->fn.record_fn; break; default: return IB_EINVAL; } *(void **)cbdata = logger_callback_fn->cbdata; return IB_OK; } ib_status_t ib_logger_fetch_open_fn( ib_logger_t *logger, const char *name, ib_logger_open_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_OPEN_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_fetch_close_fn( ib_logger_t *logger, const char *name, ib_logger_close_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_CLOSE_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_fetch_reopen_fn( ib_logger_t *logger, const char *name, ib_logger_reopen_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_REOPEN_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_fetch_format( ib_logger_t *logger, const char *name, ib_logger_format_t **format ) { assert(logger != NULL); assert(name != NULL); logger_callback_fn_t *logger_callback_fn; ib_status_t rc; rc = ib_hash_get(logger->functions, &logger_callback_fn, name); if (rc != IB_OK) { return rc; } /* Validate that the expected type matches. */ if (logger_callback_fn->type != LOGGER_FORMAT_FN) { return IB_EINVAL; } *format = logger_callback_fn->fn.format; return IB_OK; } ib_status_t ib_logger_fetch_record_fn( ib_logger_t *logger, const char *name, ib_logger_record_fn_t *fn, void *cbdata ) { assert(logger != NULL); assert(name != NULL); return logger_fetch_fn( logger, LOGGER_RECORD_FN, name, (ib_void_fn_t *)fn, cbdata); } ib_status_t ib_logger_format_create( ib_logger_t *logger, ib_logger_format_t **format, ib_logger_format_fn_t format_fn, void *format_cbdata, ib_logger_format_free_fn_t format_free_fn, void *format_free_cbdata ) { assert(logger != NULL); assert(format != NULL); assert(format_fn != NULL); ib_logger_format_t *format_out = (ib_logger_format_t *)ib_mm_alloc(logger->mm, sizeof(*format_out)); if (format_out == NULL) { return IB_EALLOC; } format_out->format_fn = format_fn; format_out->format_cbdata = format_cbdata; format_out->format_free_fn = format_free_fn; format_out->format_free_cbdata = format_free_cbdata; /* Return the created struct. */ *format = format_out; return IB_OK; }
module Parsers module Edi class PersonLoopValidator def validate(person_loop, listener, policy) valid = true carrier_member_id = person_loop.carrier_member_id if policy enrollee = policy.enrollee_for_member_id(person_loop.member_id) if enrollee.blank? listener.no_such_member(person_loop.member_id) valid = false end end policy_loop = person_loop.policy_loops.first if policy_loop is_stop = policy_loop.action == :stop if !is_stop if(carrier_member_id.blank?) listener.missing_carrier_member_id(person_loop) valid = false else listener.found_carrier_member_id(carrier_member_id) end end if policy if is_stop enrollee = policy.enrollee_for_member_id(person_loop.member_id) coverage_end_date = Date.strptime(policy_loop.coverage_end,"%Y%m%d") rescue nil if enrollee if coverage_end_date.blank? listener.termination_with_no_end_date({ :member_id => person_loop.member_id, :coverage_end_string => policy_loop.coverage_end }) valid = false else if (enrollee.coverage_start > coverage_end_date) listener.coverage_end_before_coverage_start( :coverage_end => policy_loop.coverage_end, :coverage_start => enrollee.coverage_start.strftime("%Y%m%d"), :member_id => person_loop.member_id ) valid = false end max_end_date = (policy.coverage_year.end) rescue nil if max_end_date if max_end_date < coverage_end_date listener.termination_date_after_expiration({ :coverage_end => policy_loop.coverage_end, :expiration_date => max_end_date.strftime("%Y%m%d"), :member_id => person_loop.member_id }) valid = false end else listener.indeterminate_policy_expiration({ :member_id => person_loop.member_id }) valid = false end end end end end end return false unless valid if policy is_stop = policy_loop.action == :stop if !policy.is_shop? enrollee = policy.enrollee_for_member_id(person_loop.member_id) if (enrollee.coverage_start < Date.new(2015, 1, 1)) && is_stop listener.term_or_cancel_for_2014_individual(:member_id => person_loop.member_id, :date => policy_loop.coverage_end) valid = false end end if !is_stop enrollee = policy.enrollee_for_member_id(person_loop.member_id) if enrollee.coverage_start.present? effectuation_coverage_start = policy_loop.coverage_start policy_coverage_start = enrollee.coverage_start.strftime("%Y%m%d") if effectuation_coverage_start != policy_coverage_start listener.effectuation_date_mismatch(:policy => policy_coverage_start, :effectuation => effectuation_coverage_start, :member_id => person_loop.member_id) valid = false end end end end valid end end end end
#!/bin/sh name='fbsd' path="$conf_sys_usr/share/doc/freebsd-docs" available() { [ -d "$path" ] } info() { if available; then state="$(echo "$conf_sources" | grep -q "$name" && echo "+")" count="$("$conf_find" "$path" -type f | wc -l | sed 's| ||g')" printf '%-10s %3s %8i %s\n' "$name" "$state" "$count" "$path" else state="$(echo "$conf_sources" | grep -q "$name" && echo "x")" printf '%-12s %-11s (not installed)\n' "$name" "$state" fi } setup() { results_title='' results_text='' if ! available; then echo "warning: FreeBSD documentation does not exist" 1>&2 return 1 fi langs="$(echo "$conf_wiki_lang" | awk -F ' ' '{ for(i=1;i<=NF;i++) { lang=tolower($i); gsub(/[-_].*$/,"",lang); locale=toupper($i); gsub(/^.*[-_]/,"",locale); printf("%s_%s%s",lang,(length($i)==2)?"*":locale,(i==NF)?"":"|"); } }')" search_paths="$( "$conf_find" "$path" -maxdepth 1 -mindepth 1 -type d -printf '%p\n' | \ awk "/$langs/" )" for rg_l in $(echo "$langs" | sed 's|*|.*|g; s|\||\n|g'); do p="$(echo "$search_paths" | awk "/$rg_l/ {printf(\"%s/* \",\$0)}")" if [ "$p" != '' ]; then paths="$paths $p" else l="$(echo "$rg_l" | sed 's|_\.\*||g')" echo "warning: FreeBSD documentation for '$l' does not exist" 1>&2 fi done if [ "$(echo "$paths" | wc -w | sed 's| ||g')" = '0' ]; then return 1 fi nf="$(echo "$path" | awk -F '/' '{print NF+1}')" } list() { setup || return 1 eval "$conf_find $paths -type f -name '*.html'" 2>/dev/null | \ awk -F '/' \ "BEGIN { IGNORECASE=1; OFS=\"\t\" }; { title = \"\"; for (i=$nf+3; i<=NF; i++) { fragment = toupper(substr(\$i,0,1))substr(\$i,2); title = title ((i==$nf+3) ? \"\" : \"/\") fragment; } gsub(/\.html$/,\"\",title); gsub(\"-\",\" \",title); lang=\$$nf; path=\$0; book = \$($nf+1) \"/\" \$($nf+2); title = sprintf(\"%s (%s)\",title,book); print title, lang, \"$name\", path; };" } search() { setup || return 1 results_title="$( eval "$conf_find $paths -type f -name '*.html'" 2>/dev/null | \ "$conf_awk" -F '/' \ "BEGIN { IGNORECASE=1; count=0; and_op = \"$conf_and_operator\" == \"true\"; split(\"$query\",kwds,\" \"); }; { title = \"\"; for (i=$nf+3; i<=NF; i++) { fragment = toupper(substr(\$i,0,1))substr(\$i,2); title = title ((i==$nf+3) ? \"\" : \"/\") fragment; } gsub(/\.html$/,\"\",title); gsub(\"-\",\" \",title); lang=\$$nf; path=\$0; book = \$($nf+1) \"/\" \$($nf+2); matched = title; accuracy = 0; if (and_op) { kwdmatches = 0; for (k in kwds) { subs = gsub(kwds[k],\"\",matched); if (subs>0) { kwdmatches++; accuracy = accuracy + subs; } } if (kwdmatches<length(kwds)) accuracy = 0; } else { gsub(/$greedy_query/,\"\",matched); lm = length(matched) gsub(\" \",\"\",matched); gsub(\"_\",\"\",matched); if (length(matched)==0) accuracy = length(title)*100; else accuracy = 100-lm*100/length(title); } if ((and_op && accuracy>0) || (!and_op && (accuracy > 0 || book ~ /$rg_query/))) { title = sprintf(\"%s (%s)\",title,book); matches[count,0] = accuracy; matches[count,1] = title; matches[count,2] = path; matches[count,3] = lang; count++; } }; END { for (i = 0; i < count; i++) for (j = i; j < count; j++) if (matches[i,0] < matches[j,0]) { h = matches[i,0]; t = matches[i,1]; p = matches[i,2]; l = matches[i,3]; matches[i,0] = matches[j,0]; matches[i,1] = matches[j,1]; matches[i,2] = matches[j,2]; matches[i,3] = matches[j,3]; matches[j,0] = h; matches[j,1] = t; matches[j,2] = p; matches[j,3] = l; }; for (i = 0; i < count; i++) printf(\"%s\t%s\t$name\t%s\n\",matches[i,1],matches[i,3],matches[i,2]); };" )" if [ "$conf_quick_search" != 'true' ]; then results_text="$( eval "rg -U -i -c '$rg_query' $paths" | \ "$conf_awk" -F '/' \ "BEGIN { IGNORECASE=1; count=0; }; \$0 !~ /.*:0$/ { hits = \$NF; gsub(/^.*:/,\"\",hits); gsub(/:[0-9]+$/,\"\",\$0); title = \"\" for (i=$nf+3; i<=NF; i++) { fragment = toupper(substr(\$i,0,1))substr(\$i,2); title = title ((i==$nf+3) ? \"\" : \"/\") fragment; } gsub(/\.html$/,\"\",title); gsub(\"-\",\" \",title); lang=\$$nf; path=\$0; book = \$($nf+1) \"/\" \$($nf+2); title = sprintf(\"%s (%s)\",title,book); matches[count,0] = hits; matches[count,1] = title; matches[count,2] = path; matches[count,3] = lang; count++; }; END { for (i = 0; i < count; i++) for (j = i; j < count; j++) if (matches[i,0] < matches[j,0]) { h = matches[i,0]; t = matches[i,1]; p = matches[i,2]; l = matches[i,3]; matches[i,0] = matches[j,0]; matches[i,1] = matches[j,1]; matches[i,2] = matches[j,2]; matches[i,3] = matches[j,3]; matches[j,0] = h; matches[j,1] = t; matches[j,2] = p; matches[j,3] = l; }; for (i = 0; i < count; i++) printf(\"%s\t%s\t$name\t%s\n\",matches[i,1],matches[i,3],matches[i,2]); };" )" fi printf '%s\n%s\n' "$results_title" "$results_text" | "$conf_awk" "!seen[\$0] && NF>0 {print} {++seen[\$0]};" } eval "$1"
def calculate_average_temperature(city: str, temperature_data: dict) -> float: if city in temperature_data: temperatures = temperature_data[city] average_temperature = sum(temperatures) / len(temperatures) return average_temperature else: return 0 # Return 0 if the city is not found in the temperature data dictionary
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.landing = void 0; var landing = { "viewBox": "0 0 20 20", "children": [{ "name": "path", "attribs": { "d": "M18.752,16.038c-0.097,0.266-0.822,1.002-6.029-0.878l-5.105-1.843C5.841,12.676,3.34,11.668,2.36,11.1\r\n\tc-0.686-0.397-0.836-1.282-0.836-1.282S1.361,6.862,1.261,6.134c-0.1-0.728,0.095-0.853,0.796-0.492\r\n\tc0.436,0.225,1.865,2.562,2.464,3.567C6.033,9.59,7.383,9.97,8.014,10.158C7.757,8.441,7.274,5.23,7.101,4.225\r\n\tC6.935,3.262,7.651,3.69,7.651,3.69c0.331,0.19,0.983,0.661,1.206,1.002c1.522,2.326,3.672,6.6,3.836,6.928\r\n\tc0.896,0.28,2.277,0.733,3.102,1.03C17.951,13.429,18.882,15.684,18.752,16.038z" } }] }; exports.landing = landing;
<reponame>shellrean/extraordinary-learning-client import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' import auth from './auth.store' import user from './user.store' import lecture from './lecture.store' import subject from './subject.store' import classroom from './classroom.store' import channel from './channel.store' import abcent from './abcent.store' import task from './task.store' import setting from './setting.store' import question from './question.store' import exam_schedule from './exam_schedule.store' import exam from './exam.store' import info from './info.store' import event from './event.store' import result from './result.store' import standart from './standart.store' import paper from './paper.store' Vue.use(Vuex) export default new Vuex.Store({ state: { errors: [], isLoading: false, loadPage: false, token: localStorage.getItem('token'), baseURL: process.env.VUE_APP_URL }, getters: { isAuth: state => { return state.token != "null" && state.token != null }, isLoading: state => { return state.isLoading }, baseURL: state => { return state.baseURL }, loadPage: state => { return state.loadPage } }, mutations: { SET_TOKEN(state, payload) { state.token = payload }, SET_ERRORS(state, payload) { state.errors = payload }, CLEAR_ERROR(state, payload) { state.errors = [] }, SET_LOADING(state, payload) { state.isLoading = payload }, SET_BASEURL(state, payload) { // state.baseURL = payload }, SET_LOAD_PAGE(state, payload) { state.loadPage = payload } }, actions: { getConfig({ commit }) { return new Promise(async (resolve, reject) => { try { // let network = await axios.get(`/static/config.json`, { // headers: { // 'Accept' : 'application/json' // } // }) // commit('SET_BASEURL', network.data.URL) resolve('oke') } catch (error) { reject('error') } }) } }, modules: { auth, user, lecture, subject, classroom, channel, abcent, task, setting, question, exam_schedule, exam, info, event, result, standart, paper } })
<filename>plugin/test/com/microsoft/alm/plugin/idea/tfvc/extensions/TfvcRootCheckerTests.java // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.alm.plugin.idea.tfvc.extensions; import com.microsoft.alm.plugin.external.tools.TfTool; import com.microsoft.alm.plugin.external.utils.CommandUtils; import com.microsoft.alm.plugin.idea.IdeaAbstractTest; import com.microsoft.alm.plugin.idea.tfvc.FileSystemTestUtil; import com.microsoft.alm.plugin.idea.tfvc.core.ClassicTfvcClient; import com.microsoft.alm.plugin.idea.tfvc.core.TFSVcs; import com.microsoft.alm.plugin.idea.tfvc.core.TfvcWorkspaceLocator; import com.microsoft.tfs.model.connector.TfsDetailedWorkspaceInfo; import com.microsoft.tfs.model.connector.TfsLocalPath; import com.microsoft.tfs.model.connector.TfsServerPath; import com.microsoft.tfs.model.connector.TfsWorkspaceMapping; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({ClassicTfvcClient.class, CommandUtils.class, TfTool.class, TfvcWorkspaceLocator.class}) public class TfvcRootCheckerTests extends IdeaAbstractTest { private final TfvcRootChecker checker = new TfvcRootChecker(); @Before public void setUp() { PowerMockito.mockStatic( ClassicTfvcClient.class, TfvcWorkspaceLocator.class); when(ClassicTfvcClient.getInstance()).thenReturn(new ClassicTfvcClient()); } @Test public void isVcsDirTests() { Assert.assertTrue(checker.isVcsDir("$TF")); Assert.assertTrue(checker.isVcsDir(".tf")); Assert.assertFalse(checker.isVcsDir(".tf1")); Assert.assertFalse(checker.isVcsDir("anything")); } @Test public void getSupportedVcsKey() { Assert.assertEquals(TFSVcs.getKey(), checker.getSupportedVcs()); } private static void mockTfToolPath(String path) { PowerMockito.mockStatic(TfTool.class); when(TfTool.getLocation()).thenReturn(path); } private static void mockPartialWorkspace(Path path, TfsDetailedWorkspaceInfo workspace) { PowerMockito.mockStatic(CommandUtils.class); when(TfvcWorkspaceLocator.getPartialWorkspace(eq(null), eq(path), any(Boolean.class))).thenReturn(workspace); } private static void mockPartialWorkspaceNotDetermined(Path path) { PowerMockito.mockStatic(CommandUtils.class); when(TfvcWorkspaceLocator.getPartialWorkspace(eq(null), eq(path), any(Boolean.class))).thenReturn(null); } private static TfsDetailedWorkspaceInfo createWorkspaceWithMapping(String localPath) { TfsWorkspaceMapping mapping = new TfsWorkspaceMapping( new TfsLocalPath(localPath), new TfsServerPath("server", "serverPath"), false); return new TfsDetailedWorkspaceInfo(Collections.singletonList(mapping), "server", "name"); } @Test public void isRootTestNoSettings() throws IOException { Path path = FileSystemTestUtil.createTempFileSystem(); mockTfToolPath(""); Assert.assertFalse(checker.isRoot(path.toString())); } @Test public void isRootTestNoWorkspace() throws IOException { Path path = FileSystemTestUtil.createTempFileSystem("$tf/"); mockTfToolPath("tf.cmd"); mockPartialWorkspace(path, null); Assert.assertFalse(checker.isRoot(path.toString())); } @Test public void isRootTestWorkspaceNotDetermined() throws IOException { Path path = FileSystemTestUtil.createTempFileSystem("$tf/"); mockTfToolPath("tf.cmd"); mockPartialWorkspaceNotDetermined(path); Assert.assertFalse(checker.isRoot(path.toString())); } @Test public void isRootTestNotMapped() throws IOException { Path path = FileSystemTestUtil.createTempFileSystem("$tf/"); mockTfToolPath("tf.cmd"); mockPartialWorkspace(path, createWorkspaceWithMapping("someOtherLocalPath")); Assert.assertFalse(checker.isRoot(path.toString())); } @Test public void isRootTestMapped() throws IOException { Path path = FileSystemTestUtil.createTempFileSystem("$tf/"); mockTfToolPath("tf.cmd"); mockPartialWorkspace(path, createWorkspaceWithMapping(path.toString())); Assert.assertTrue(checker.isRoot(path.toString())); } }
from __future__ import division from __future__ import print_function import math import numpy import scipy.special as special from numpy import sum, cos, sin, sqrt def A1(kappa): # XXX R has these exponentially scaled, but this seems to work result = special.i1(kappa) / special.i0(kappa) return result def A1inv(R): if 0 <= R < 0.53: return 2 * R + R ** 3 + (5 * R ** 5) / 6 elif R < 0.85: return -0.4 + 1.39 * R + 0.43 / (1 - R) else: return 1 / (R ** 3 - 4 * R ** 2 + 3 * R) def mle_vonmises(theta): results = {} n = len(theta) C = sum(cos(theta)) S = sum(sin(theta)) R = sqrt(C ** 2 + S ** 2) mean_direction = math.atan2(S, C) results["mu"] = mean_direction mean_R = R / n kappa = A1inv(mean_R) results["kappa"] = kappa if 0: z = F(theta - mu_hat) z.sort() z_bar = sum(z) / n if 0: tmp = 0 for i in range(n): tmp += (z[i] - 2 * i / (2 * n)) ** 2 U2 = tmp - n * (z_bar - 0.5) ** 2 + 1 / (12 * n) else: U2 = ( sum((z - 2 * numpy.arange(n) / (2 * n)) ** 2) - n * (z_bar - 0.5) ** 2 + 1 / (12 * n) ) results["U2"] = U2 return results def lm_circular_cl(y, x, init, verbose=False, tol=1e-10): """circular-linear regression y in radians x is linear """ y = numpy.mod(y, 2 * numpy.pi) betaPrev = init n = len(y) S = numpy.sum(numpy.sin(y - 2 * numpy.arctan(x * betaPrev))) / n C = numpy.sum(numpy.cos(y - 2 * numpy.arctan(x * betaPrev))) / n R = numpy.sqrt(S ** 2 + C ** 2) mu = numpy.arctan2(S, C) k = A1inv(R) diff = tol + 1 iter = 0 while diff > tol: iter += 1 u = k * numpy.sin(y - mu - 2 * numpy.arctan(x * betaPrev)) A = k * A1(k) * numpy.eye(n) g_p = 2 / (1 + betaPrev * x) ** 2 * numpy.eye(n) D = g_p * x raise NotImplementedError() def test(): print("A1inv(5.0)", A1inv(5.0)) print("A1inv(0.0)", A1inv(0.0)) print("A1inv(3421324)", repr(A1inv(3421324))) print("A1inv(-0.5)", repr(A1inv(-0.5))) print("A1inv(0.5)", repr(A1inv(0.5))) print("A1inv(0.7)", repr(A1inv(0.7))) # print 'A1inv(numpy.inf)',A1inv(numpy.inf) def raw_data_plot(ax, theta, r=1.0, **kwargs): # plot ring ct = list(numpy.arange(0, 2 * numpy.pi, 0.01)) ct = ct + [ct[0]] # wrap cr = 0.9 cx = cr * numpy.cos(ct) cy = cr * numpy.sin(ct) ax.plot(cx, cy, "k-") x = r * numpy.cos(theta) y = r * numpy.sin(theta) ax.plot(x, y, **kwargs) ax.set_xlim([-1.1, 1.1]) ax.set_ylim([-1.1, 1.1]) ax.set_xticks([]) ax.set_yticks([]) if __name__ == "__main__": test()
<filename>src/objects/enums/Environments.py import abc import socket from pyspark.sql import SparkSession class Environment: def __init__(self, name, nameservice, zookeeperquorum, historyserver): self.name = name self.nameservice = nameservice self.zookeeperquorum = zookeeperquorum self.historyserver = historyserver class IEnvironment: @abc.abstractmethod def getEnvironment(self, sc: SparkSession): Environment def getEnvironmentByServer(self): Environment class Environments(IEnvironment): def __init__(self): self.local = Environment("local", "", "localhost", "localhost:18081") self.dev = Environment("dev", "", "localhost", "localhost:18081") self.intg = Environment("intg", "", "localhost", "localhost:18081") self.test = Environment("test", "", "localhost", "localhost:18081") self.prod = Environment("prod", "", "localhost", "localhost:18081") def getEnvironment(self, sc: SparkSession) -> Environment: hostname = socket.gethostname() if hostname.lower().startswith("v") or hostname.lower().startswith("u"): return self.local elif hostname.lower().startswith("intg"): return self.intg elif hostname.lower().startswith("test"): return self.test elif hostname.lower().startswith("prod"): return self.prod def getEnvironmentByServer(self) -> Environment: hostname = socket.gethostname() if hostname.lower().startswith("v") or hostname.lower().startswith("u"): return self.local elif hostname.lower().startswith("intg"): return self.intg elif hostname.lower().startswith("test"): return self.test elif hostname.lower().startswith("prod"): return self.prod
<reponame>vnunez85/easy-email<gh_stars>0 export function getFormatVariable(group: string, name: string) { return group + '.' + name; } export function getParseVariable(variable: string) { const [group, name] = variable.split('.'); return { group, name }; }
#!/bin/bash source lib/instance.sh source lib/string.sh source lib/log.sh source lib/input.sh SCRIPTDIR="$(script_dir)" BUILDDIR="$SCRIPTDIR/build/debug/" LIBNAME="QuickScript" LIBNAMELOW="$(to_lowercase "$LIBNAME")" TEMPFILE="$BUILDDIR/.$LIBNAMELOW.tmp" LIBFILENAME="" BUILTFILE="" VERSIONNO="debug" LIB_COMMENTS=0 GLOBALS=() WRITE_TARGET="$TEMPFILE" # Shorthand for writing to file function write { echo "$1" >> "$WRITE_TARGET" } function build { OPTALIAS[--STRIP-COMMENTS]=-s OPTALIAS[--VERSION]=-v while qs_opts "sv:" opt; do case "$opt" in -s|--strip-comments|--STRIP-COMMENTS) LIB_COMMENTS=1 ;; -v|--version|--VERSION) VERSIONNO="$OPTARG" ;; \?) echo "Non-existent parameter specified: $OPTARG" echo "Aborting..." exit 1 ;; \!) echo "$OPTARG requires a value specified" echo "Aborting..." exit 1 ;; esac done local lastline="" LIBFILENAME="$LIBNAMELOW-$VERSIONNO.sh" BUILTFILE="$BUILDDIR/$LIBFILENAME" # Make sure that the build dir exists mkdir -p "$BUILDDIR" # Remove previously built file if [ -e "$BUILTFILE" ]; then rm "$BUILTFILE" fi # If tmp file exists, delete as well if [ -e "$TEMPFILE" ]; then rm "$TEMPFILE" fi # Make sure the tmp file gets deleted at end trap "rm -f '$TEMPFILE'" EXIT INT HUP TERM QUIT # Loop through all lib-files while IFS= read -r file; do local globalsection=1 local lineno=0 local relfile="${file/$SCRIPTDIR/}" # Make sure functions don't get cramped together if [ "$lastline" != "" ]; then write "" lastline="" fi # Add extra build information if LIB_COMMENTS if [ $LIB_COMMENTS -eq 0 ]; then write "### File \"$relfile\":" fi # Process the file while IFS= read -r line; do lineno=$(($lineno+1)) # Skip shell script definition if [ "$line" = "#!/bin/bash" ] || [ "$line" = "#!/bin/sh" ]; then continue fi # Gather all the globals so that we can put them at the top of the built file if [ "$line" = "###GLOBALS_END###" ]; then globalsection=1 continue fi if [ "$line" = "###GLOBALS_START###" ]; then globalsection=0 continue fi if [ $globalsection -eq 0 ]; then GLOBALS+=("$line") else # Skip multiple blank lines if [ "$lastline" = "" ] && [ "$line" = "" ]; then continue fi # Skip comments if making a LIB_COMMENTS build if [ $LIB_COMMENTS -eq 1 ] && [[ "$(trim_leading_whitespace "$line")" == \#* ]]; then continue fi # If we're making a LIB_COMMENTS build add the lineno for the function if [[ "$line" == "function "* ]] && [ $LIB_COMMENTS -eq 0 ]; then # Make sure the comment doesn't get cramped in if [ "$lastline" != "" ]; then write "" fi write "## $relfile, line $lineno:" fi # Write the file's line write "$line" lastline="$line" fi done < "$file" done < <(find "$SCRIPTDIR/lib" -maxdepth 1 -type f -name "*.sh" | sort -V) # Change write target to the final output file write "" WRITE_TARGET="$BUILTFILE" write "#!/bin/bash" write "" # Always add build info write "## QuickScript version $VERSIONNO" write "## Build date: $(date '+%Y-%m-%d %T')" write "" # Append the global variables write "QSVERSION=\"$VERSIONNO\"" for globalvar in "${GLOBALS[@]}"; do write "$globalvar" done # Write all the contents from the temp file to the output file write "" while IFS= read -r line; do write "$line" done < "$TEMPFILE" } # Run build if script isn't being sourced if [ "${BASH_SOURCE[0]}" = "$0" ]; then build $* fi
import { HTMLAttributes, ReactNode } from 'react'; import './Radio.css'; export interface Props extends HTMLAttributes<HTMLInputElement> { /** You can define an element pertaining to radio */ children?: ReactNode; /** Determines whether input is disabled */ disabled?: boolean; /** Value that the radio represents*/ value?: string; } /** * An input object that is a list of items where a single entry can be selected */ export declare const Radio: ({ children, ...props }: Props) => JSX.Element;
<filename>src/screens/Authentication/ResetPasswordScreen.js /* * Created Date: Fri, 6th Nov 2020, 12:51:36 pm * Author: <NAME> * Email: <EMAIL> * Copyright (c) 2020 The Distance */ import React, {useEffect} from 'react'; import {ScrollView, View, Text, Alert, Linking} from 'react-native'; import {Form, FormHook} from 'the-core-ui-module-tdforms'; import {ScaleHook} from 'react-native-design-to-component'; import useDictionary from '../../hooks/localisation/useDictionary'; import DefaultButton from '../../components/Buttons/DefaultButton'; import useTheme from '../../hooks/theme/UseTheme'; import {passwordRegex} from '../../utils/regex'; import PasswordEyeIcon from '../../components/cells/PasswordEyeIcon'; import {useNavigation} from '@react-navigation/native'; import Header from '../../components/Headers/Header'; import {Auth} from 'aws-amplify'; import {Platform} from 'react-native'; export default function Screen() { // ** ** ** ** ** SETUP ** ** ** ** ** const navigation = useNavigation(); const {dictionary} = useDictionary(); const {AuthDict} = dictionary; const onlyNumbersRegex = /^\d+$/; navigation.setOptions({ header: () => <Header title={AuthDict.ResetPasswordScreenTitle} goBack />, }); const {cellFormStyles, cellFormConfig, textStyles, colors} = useTheme(); const { cleanErrors, getValues, updateError, cleanValues, updateValue, } = FormHook(); const {getHeight, getWidth} = ScaleHook(); // ** ** ** ** ** STYLES ** ** ** ** ** const styles = { container: { flex: 1, backgroundColor: colors.backgroundWhite100, }, scrollViewContainer: { height: '100%', width: '100%', }, buttonContainer: { width: '100%', position: 'absolute', bottom: 0, marginTop: getHeight(30), marginBottom: getHeight(40), alignItems: 'center', }, descriptionStyle: { ...textStyles.regular15_brownishGrey100, marginTop: getHeight(30), textAlign: 'left', }, }; // MARK: - Deep linking const handleUrl = (url = '') => { console.log('Handle url:', url); const receivedCode = url.length > 0 ? url.substr(url.length - 6) : ''; if (url.includes('forgotPassword') && onlyNumbersRegex.test(receivedCode)) { updateValue({name: 'code', value: receivedCode}); } }; const handleUrlEvent = (event = {}) => { const {url} = event; handleUrl(url); }; const setup = () => { if (Platform.OS === 'android') { Linking.getInitialURL().then((url) => { handleUrl(url); }); } else { Linking.addEventListener('url', handleUrlEvent); } }; // MARK: - Effects useEffect(() => { setup(); return () => { cleanValues(); cleanErrors(); Linking.removeEventListener('url', handleUrlEvent); }; }, []); // ** ** ** ** ** FUNCTIONS ** ** ** ** ** function handleChangePassword() { cleanErrors(); const {code, newPassword, emailAddress} = getValues(); if (!code || code.length < 6) { updateError({ name: 'code', value: AuthDict.InvalidResetCode, }); return; } if (!newPassword || !passwordRegex.test(newPassword)) { updateError({ name: 'newPassword', value: AuthDict.InvalidNotNewPassword, }); return; } Auth.forgotPasswordSubmit(emailAddress, code, newPassword) .then((data) => { console.log(data, '<---reset password data'); cleanValues(); navigation.navigate('Login'); }) .catch((err) => { console.log(err); if (err.code === 'CodeMismatchException') { Alert.alert(AuthDict.VerificationNotRecognized); } }); } // ** ** ** ** ** RENDER ** ** ** ** ** const FormFooter = () => ( <Text style={styles.descriptionStyle}> {AuthDict.ResetPasswordDescriptionText} </Text> ); const cells = [ { type: 'text', variant: 'number', name: 'code', label: AuthDict.ForgotPasswordCodeLabel, placeholder: '123456', textContentType: 'oneTimeCode', ...cellFormStyles, inputContainerStyle: { paddingHorizontal: 0, }, }, { name: 'newPassword', type: 'text', variant: 'password', label: AuthDict.ForgotPasswordLabel, textContentType: 'password', autoCompleteType: 'password', autoCorrect: false, ...cellFormStyles, inputContainerStyle: { paddingHorizontal: 0, paddingRight: getWidth(6), }, }, ]; const config = { ...cellFormConfig, formFooter: FormFooter, }; return ( <View style={styles.container}> <ScrollView keyboardShouldPersistTaps="handled" style={styles.scrollViewContainer}> <View style={{marginHorizontal: getWidth(25)}}> <Form cells={cells} config={config} /> </View> </ScrollView> <View style={styles.buttonContainer}> <DefaultButton type="changePassword" variant="white" icon="chevron" onPress={handleChangePassword} /> </View> </View> ); }
package com.jinke.calligraphy.app.branch; import android.content.Context; import android.gesture.GestureOverlayView; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; public class GestureView extends GestureOverlayView{ public GestureView(Context context) { super(context); // TODO Auto-generated constructor stub } public static float y; @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN) y=event.getY(); return super.onTouchEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent event) { return super.dispatchTouchEvent(event); } }
<filename>sources/executeRepro.ts import expect from 'expect'; import {readFileSync} from 'fs'; import Module from 'module'; import path from 'path'; import tmp from 'tmp'; import vm from 'vm'; const createRequire = Module.createRequire || Module.createRequireFromPath; async function executeInTempDirectory<T>(fn: () => Promise<T>) { const cwd = process.cwd(); process.chdir(tmp.dirSync({unsafeCleanup: true}).name); try { return await fn(); } finally { process.chdir(cwd); } } export async function executeRepro(code: string, requireList: string[]) { return await executeInTempDirectory(async () => { const global = {} as any; global.global = global; global.expect = expect; global.process = process; global.console = console; const runCode = (code: string, p: string | null) => { const sandbox = Object.create(global); sandbox.module = {exports: {}}; sandbox.exports = sandbox.module.exports; vm.createContext(sandbox); if (p !== null) { sandbox.require = createRequire(p); sandbox.__dirname = path.dirname(p); sandbox.__filename = p; } else { sandbox.require = createRequire(path.join(process.cwd(), `repro`)); } vm.runInContext(code, sandbox); return sandbox.module.exports; }; for (const r of requireList) { const rPath = path.resolve(r); const rCode = readFileSync(rPath, `utf8`); runCode(rCode, rPath); } const wrap = (code: string) => `module.exports = async () => {\n${code}\n};\n`; const test = runCode(wrap(code), null); let assertion; let error; try { await test(); } catch (error_) { if (error_ instanceof Error) { // Note: hasOwnProperty because in some cases they're set to undefined if (Object.prototype.hasOwnProperty.call(error_, `matcherResult`)) { assertion = error_.stack; } else { error = error_.stack; } } else { throw error_; } } return {assertion, error}; }); }
// // VoiceRecognition.h // AutoTT // // Created by <NAME> on 17.04.2016. // Copyright © 2016 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "TCPConnection.h" #import </Users/hakonaustlidtasken/Documents/6. Semester/Instrumentering/tt/paulOpenEars/OpenEarsDistribution/OpenEars/Classes/include/OEEventsObserver.h> @interface VoiceRecognition : NSObject <OEEventsObserverDelegate> @property (strong, nonatomic) OEEventsObserver *openEarsEventsObserver; @property TCPConnection* tcpConnection; - (void) startVoiceRecognition:(TCPConnection*)tcpConnection; @end
# Import libraries import tensorflow as tf from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Embedding, Dropout, GlobalMaxPooling1D,Flatten from tensorflow.keras import losses from sklearn.model_selection import train_test_split # Setup hyper-parameters vocab_size = 10000 embedding_dim = 16 max_length = 32 trunc_type='post' padding_type='post' oov_tok = "<OOV>" # Get data and pad (x_train, y_train), (x_test, y_test) = tf.keras.datasets.imdb.load_data(num_words=vocab_size) x_train = pad_sequences(x_train, maxlen=max_length, padding=padding_type, truncating=trunc_type) x_test = pad_sequences(x_test, maxlen=max_length, padding=padding_type, truncating=trunc_type) # Create the model model = Sequential() model.add(Embedding(vocab_size, embedding_dim, input_length=max_length)) model.add(Flatten()) model.add(Dense(32, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss=losses.binary_crossentropy, optimizer='adam', metrics=['accuracy']) # Train the model model.fit(x_train, y_train, epochs=5, verbose=1) # Evaluate the model loss, accuracy = model.evaluate(x_test, y_test, verbose=1) print("Loss: %.2f" % loss) print("Accuracy: %.2f " % (accuracy*100))
<filename>src/main/java/com/rapid7/Constants.java package com.rapid7; public class Constants { public static final String DATA_ENDPOINT_TEMPLATE = "%s.data.logs.insight.rapid7.com"; }
<reponame>lananh265/social-network "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ic_disabled_by_default_outline = void 0; var ic_disabled_by_default_outline = { "viewBox": "0 0 24 24", "children": [{ "name": "rect", "attribs": { "fill": "none", "height": "24", "width": "24" }, "children": [] }, { "name": "path", "attribs": { "d": "M19,19H5V5h14V19z M3,3v18h18V3H3z M17,15.59L15.59,17L12,13.41L8.41,17L7,15.59L10.59,12L7,8.41L8.41,7L12,10.59L15.59,7 L17,8.41L13.41,12L17,15.59z" }, "children": [] }] }; exports.ic_disabled_by_default_outline = ic_disabled_by_default_outline;
<filename>application/team6-termproject/__tests__/authentication.test.js /** * Authentication QA Test * * using supertest async endpoint testing to verify login functionality */ const app = require('../app') const supertest = require('supertest') const request = supertest(app) const hashTool = require('../config/passport/helpers') const demoUser = { email: '<EMAIL>', password: '<PASSWORD>' }; const fakeUser = { email: '<EMAIL>', password: '<PASSWORD>' }; const newUser = { //uid: req.body.uid, first_name: 'Peter', last_name: 'Parker', email: '<EMAIL>', password: hashTool.generateHash('<PASSWORD>'), sfsu_verified: 1, permission: 1 }; describe('Register', () => { it('succeeds when all fields are correctly input', async () => { request .post('/api/register') .send(newUser) .expect(response => { response.body.email = newUser.email }) .expect(200); }); }); describe('Login', () => { it('succeeds with correct credentials', async () => { request .post('/api/login') .send(demoUser) .expect(response => { response.body.email = demoUser.email response.header['location'] = '/dashboard' }) .expect(200); }); it('fails with bad credentials', async () => { request .post('/api/login') .send(fakeUser) .expect(303); }); });
<reponame>leftjs/gym-api<filename>src/main/java/com/donler/gym/Application.java<gh_stars>0 package com.donler.gym; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by jason on 4/13/16. */ @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); } // @Bean // public CommandLineRunner init(BusinessRepo businessRepo) { // // return (evt) -> { //// User user = new User("jason", "jason", "jason"); //// userRepo.save(user); // Business business1 = new Business(1, 488); // Business business2 = new Business(3, 1288); // Business business3 = new Business(6, 2100); // Business business4 = new Business(12, 3800); // // businessRepo.save(business1); // businessRepo.save(business2); // businessRepo.save(business3); // businessRepo.save(business4); // // // }; // } }
let domElement = document.createElement('div'); let h1Element = document.createElement('h1'); let pElement = document.createElement('p'); h1Element.appendChild(document.createTextNode('Hello')); pElement.appendChild(document.createTextNode('World!')); domElement.appendChild(h1Element); domElement.appendChild(pElement);
######################################################################## # # Thumb / Force / 3D / Whatever-You-Call Gesture Stuff # by PaperFlu and you # ######################################################################## ######################### # Navigation Bar Related ######################### navigation_back() { input keyevent 4 } navigation_home() { input keyevent 3 } navigation_recents() { input keyevent 187 } navigation_back_alpha() { screen_touch_relative 160 2300 4 90 } navigation_home_alpha() { screen_touch_relative 490 2300 4 270 } navigation_recents_alpha() { screen_touch_relative 2910 2300 4 2215 } ################ # Media Related ################ media_pause() { input keyevent 127 } media_play() { input keyevent 126 } media_play_pause() { input keyevent 85 } media_next() { input keyevent 87 } media_previous() { input keyevent 88 } ############## # App Related ############## app_tasker_alpha() { am broadcast --user current -a net.dinglisch.android.taskerm.thumbTouch } ################ # Pre-functions ################ screen_touch_absolute() { sendevent $TOUCH_EVENT_PATH 3 57 -1 sendevent $TOUCH_EVENT_PATH 0 0 0 sendevent $TOUCH_EVENT_PATH 3 57 20 # ABS_MT_POSITION_X sendevent $TOUCH_EVENT_PATH 3 53 $1 # ABS_MT_POSITION_Y sendevent $TOUCH_EVENT_PATH 3 54 $2 # ABS_MT_PRESSURE #sendevent $TOUCH_EVENT_PATH 3 58 10 # ABS_MT_TOUCH_MAJOR #sendevent $TOUCH_EVENT_PATH 3 48 11 # ABS_MT_TOUCH_MINOR #sendevent $TOUCH_EVENT_PATH 3 49 10 sendevent $TOUCH_EVENT_PATH 0 0 0 sleep 0.005 sendevent $TOUCH_EVENT_PATH 3 57 -1 sendevent $TOUCH_EVENT_PATH 0 0 0 } # Portial parameters first. screen_touch_relative() { case $SCREEN_ORIENTATION in 0) local TOUCH_X=$1 local TOUCH_Y=$2;; 1) local TOUCH_X=$3 local TOUCH_Y=$4;; 2) local TOUCH_X=$(($SCREEN_WIDTH - $1)) local TOUCH_Y=$(($SCREEN_HEIGHT - $2));; 3) local TOUCH_X=$(($SCREEN_WIDTH - $3)) local TOUCH_Y=$(($SCREEN_HEIGHT - $4));; esac screen_touch_absolute $TOUCH_X $TOUCH_Y & }
package my.food.tomas.healthyfood.mainScreen; import android.content.Intent; import android.support.v4.app.DialogFragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import my.food.tomas.healthyfood.FoodApplication; import my.food.tomas.healthyfood.R; import my.food.tomas.healthyfood.data.local.models.RecipeSearchParams; import my.food.tomas.healthyfood.detailsScreen.RecipeActivity; public class MainActivity extends AppCompatActivity implements MainFragment.OnMainFragmentListener { public static final String TAG = "MainActivity"; private MainFragment mainFragment; private SearchView searchView; private MenuItem searchClearItem; private RecipeSearchParams recipeSearchParams; private String prevSearchQuery; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment_host); initFragment(savedInstanceState); FoodApplication.getAppComponent().inject(this); } @Override public void onStartRecipeActivity(String id) { Intent intent = new Intent(this, RecipeActivity.class); intent.putExtra(RecipeActivity.RECIPE_ID, id); startActivity(intent); } private void initFragment(Bundle savedInstanceState) { if (findViewById(R.id.fragment_container) != null) { if (savedInstanceState != null) { mainFragment = (MainFragment)getSupportFragmentManager().findFragmentByTag(MainFragment.TAG); } createFragment(); } } private void createFragment() { mainFragment = MainFragment.newInstance(); getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_container, mainFragment, MainFragment.TAG) .commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem searchItem = menu.findItem(R.id.action_search); searchView = (SearchView) MenuItemCompat.getActionView(searchItem); setupSearchView(); searchClearItem = menu.findItem(R.id.action_search_clear); return super.onCreateOptionsMenu(menu); } public void setupSearchView() { searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchRecipe(query); return true; } @Override public boolean onQueryTextChange(String newText) { return true; } }); searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { searchView.setQuery(prevSearchQuery, false); searchClearItem.setVisible(false); } else if (prevSearchQuery != null && prevSearchQuery.length() > 0) { searchClearItem.setVisible(true); } } }); } private void searchRecipe(String query) { prevSearchQuery = query; if (mainFragment != null) { mainFragment.setSearchQuery(query); mainFragment.loadRecipesList(query); } } }
// // Created by jwscoggins on 12/5/20. // #ifndef I960_PROTOTYPE_SIMULATOR_TRACECONTROLS_H #define I960_PROTOTYPE_SIMULATOR_TRACECONTROLS_H #include "CoreTypes.h" namespace i960 { class TraceControls { public: static constexpr Ordinal ModeBits = 0x0000'00FE; static constexpr Ordinal EventFlags = 0x0FFEFF00; public: constexpr TraceControls() noexcept : raw_(0) { } [[nodiscard]] constexpr auto getRawValue() const noexcept { return raw_; } void setRawValue(Ordinal value) noexcept { raw_ = value; } [[nodiscard]] constexpr auto getInstructionTraceMode() const noexcept { return static_cast<bool>(i); } [[nodiscard]] constexpr auto getBranchTraceMode() const noexcept { return static_cast<bool>(b); } [[nodiscard]] constexpr auto getCallTraceMode() const noexcept { return static_cast<bool>(c); } [[nodiscard]] constexpr auto getReturnTraceMode() const noexcept { return static_cast<bool>(r); } [[nodiscard]] constexpr auto getPrereturnTraceMode() const noexcept { return static_cast<bool>(p); } [[nodiscard]] constexpr auto getSupervisorTraceMode() const noexcept { return static_cast<bool>(s); } [[nodiscard]] constexpr auto getMarkTraceMode() const noexcept { return static_cast<bool>(mk); } [[nodiscard]] Ordinal modify(Ordinal mask, Ordinal src2) noexcept; /// @todo continue here private: union { Ordinal raw_; struct { unsigned unused0_ : 1; /// instruction trace mode unsigned i : 1; /// branch trace mode unsigned b : 1; /// call trace mode unsigned c : 1; /// Return trace mode unsigned r : 1; /// Prereturn trace mode unsigned p : 1; /// Supervisor Trace Mode unsigned s : 1; /// Mark Trace Mode unsigned mk : 1; /// Instruction-Address Breakpoint 2 to 5 unsigned i25f : 4; /// Data-Address Breakpoint 2 to 5 unsigned d25f : 4; unsigned unused1_: 1; /// Instruction Trace Event unsigned ite: 1; /// Branch Trace Event unsigned bte: 1; /// Call Trace Event unsigned cte: 1; /// Return Trace Event unsigned rte: 1; /// Prereturn Trace Event unsigned prte: 1; /// Supervisor Trace Event unsigned sute: 1; /// Breakpoint Trace Event unsigned bpte: 1; /// Instruction-Address Breakpoint 0 to 1 unsigned iab01 : 2; /// Data-Address Breakpoint 0 to 1 unsigned dab01 : 2; unsigned unused2_ : 4; }; }; }; static_assert(sizeof(TraceControls) == sizeof(Ordinal)); } #endif //I960_PROTOTYPE_SIMULATOR_TRACECONTROLS_H
var searchData= [ ['scale',['scale',['../struct_normalization_parameters.xhtml#a1d28dec57cce925ad92342891bd71e7c',1,'NormalizationParameters']]], ['scoresinfo',['scoresInfo',['../_neon_end_to_end_tests_8cpp.xhtml#a64c1dd1b6dd60be9f4a16db9c8f427a5',1,'NeonEndToEndTests.cpp']]], ['simpleconvolution2d3x3stride2x2test',['SimpleConvolution2d3x3Stride2x2Test',['../_ref_layer_tests_8cpp.xhtml#aa83b35e7fe79aa2a729b95061364b1e3',1,'RefLayerTests.cpp']]], ['stddev',['stddev',['../struct_normalization_parameters.xhtml#a8fdb461f0b4417f4ebff10b3413a948d',1,'NormalizationParameters']]], ['supported',['supported',['../struct_layer_test_result.xhtml#a23a6c8147ba9825335d1d6246c11d675',1,'LayerTestResult']]] ];
/** * Copyright 2016 <NAME> * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.pathirage.freshet.beam; /** * Defines dataflow pipeline that get executed as dag of Samza jobs. * {@link SamzaRunner} translate a {@link org.apache.beam.sdk.Pipeline} instance * to a {@link SamzaPipelineSpecification} instance that can be executed as a dag of {@link SamzaJobConfig}s locally or in a remote * YARN cluster. */ public class SamzaPipelineSpecification { /** * First job in a Samza pipeline encapsulating a Beam pipeline. */ private SamzaPipelineNode head; private SamzaPipelineNode tail; public synchronized void addNode(SamzaPipelineNode node) { if(head != null) { head = node; } else { tail.addSuccessor(node); } tail = node; } public SamzaPipelineJob execute() { // Schedule Samza job starting from root return null; } }
import { useState, useEffect } from 'react'; import { getPost, getUserPhotosByUsername, retrivePostByUserId } from '../services/postServices'; export default function useProfilePost(user, logginUserId, pageNumber) { const [loading, setLoading] = useState(true) const [error, setError] = useState(false) const [posts, setPosts] = useState([]); const [hasMore, setMore] = useState(false) useEffect(async () => { setLoading(true) setError(false) async function getProfilePost() { try { const post = await getUserPhotosByUsername(user.username, logginUserId, pageNumber, 5); console.log(post); setPosts(prevPost => { return [...prevPost, ...post.result] }); setMore(post.result.length > 0) setLoading(false) } catch (error) { setError(true) console.log(error); } } getProfilePost(); }, [user, pageNumber, logginUserId]); return { posts, loading, error, hasMore, setPosts }; }
import UIKit class ViewController: UIViewController { @IBOutlet weak var numberField: UITextField! @IBAction func incrementButtonTapped(sender : UIButton!) { if let number = Int(numberField.text!) { numberField.text = String(number + 1) } } }
<reponame>minuk8932/Algorithm_BaekJoon package sort; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; /** * * @author minchoba * 백준 11536번: 줄 세우기 * * @see https://www.acmicpc.net/problem/11536/ * */ public class Boj11536 { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); String[] names = new String[N]; String[] comp = new String[N]; for(int i = 0; i < N; i++) { names[i] = br.readLine(); comp[i] = names[i]; } boolean increase = isSorted(N, names, comp, 0, N , 1); boolean decrease = isSorted(N, names, comp, 0, N, -1); if(increase) System.out.println("INCREASING"); else if(decrease) System.out.println("DECREASING"); else System.out.println("NEITHER"); } private static boolean isSorted(int n, String[] target, String[] comp, int start, int end, int diff) { Arrays.sort(comp, new Comparator<String>() { @Override public int compare(String str1, String str2) { // 첫자리 비교 후 같으면 전체 비교 if(str1.charAt(0) < str2.charAt(0)) { return -1; } else if(str1.charAt(0) > str2.charAt(0)) { return 1; } else { return str1.compareTo(str2); } } }); for(int i = start; i < end; i++) { // 증가 감소에 따라 접근 인덱스를 바꿔줌 int idx = diff == 1 ? i : n - 1 - i; if(comp[i] != target[idx]) return false; } return true; } }
#!/bin/bash ccm create consys_test -v 4.0.3 ccm populate -n 3 ccm start
import numpy as np from matplotlib import pyplot as plt from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score # Load the dataset data = np.loadtxt("data.csv", delimiter=',') X = data[:,0:5] y = data[:,5] # Fit the linear model regression = linear_model.LinearRegression() regression.fit(X, y) # Make predictions y_pred = regression.predict(X) # Calculate the performance metrics r2 = r2_score(y, y_pred) rmse = np.sqrt(mean_squared_error(y, y_pred)) print('r2 score: ', r2) print(' RMSE: ', rmse) # Plot the linear regression line plt.scatter(X[:,1], y, color='blue') plt.plot(X[:,1], y_pred, color='red') plt.title('Linear Regression Model') plt.xlabel('X') plt.ylabel('y') plt.show()
<filename>lib/car/obj/src/init_fl.c /* **** Notes Initialise Remarks: Refer at fn. cli_restore. */ # define CAR # include "./../../../incl/config.h" signed(__cdecl init_fl(signed(arg),fl_t(*argp))) { auto signed char *b; auto signed r; auto signed short flag; if(!argp) return(0x00); // destroy r = (OBJS); if(arg) while(r) rl(*(--r+(R(v,*argp)))); // initialise b = (0x00); r = (OBJS); while(r) { AND(*(--r+(R(fd,*argp))),0x00); *(r+(R(v,*argp))) = (void*) (b); } return(0x01); }
<reponame>abitmore/evmone<gh_stars>0 // evmone: Fast Ethereum Virtual Machine implementation // Copyright 2019 The evmone Authors. // SPDX-License-Identifier: Apache-2.0 #include "helpers.hpp" #include "synthetic_benchmarks.hpp" #include <benchmark/benchmark.h> #include <evmc/evmc.hpp> #include <evmc/loader.h> #include <evmone/evmone.h> #include <filesystem> #include <fstream> #include <iostream> namespace fs = std::filesystem; using namespace benchmark; namespace evmone::test { std::map<std::string_view, evmc::VM> registered_vms; namespace { struct BenchmarkCase { struct Input { std::string name; bytes input; bytes expected_output; Input(std::string _name, bytes _input, bytes _expected_output) noexcept : name{std::move(_name)}, input{std::move(_input)}, expected_output{std::move(_expected_output)} {} }; std::string name; bytes code; std::vector<Input> inputs; /// Create a benchmark case without input. BenchmarkCase(std::string _name, bytes _code) noexcept : name{std::move(_name)}, code{std::move(_code)} {} }; constexpr auto runtime_code_extension = ".bin-runtime"; constexpr auto inputs_extension = ".inputs"; /// Loads the benchmark case's inputs from the inputs file at the given path. std::vector<BenchmarkCase::Input> load_inputs(const fs::path& path) { enum class state { name, input, expected_output }; auto inputs_file = std::ifstream{path}; std::vector<BenchmarkCase::Input> inputs; auto st = state::name; std::string input_name; bytes input; for (std::string l; std::getline(inputs_file, l);) { switch (st) { case state::name: if (l.empty()) continue; // Skip any empty line. input_name = std::move(l); st = state::input; break; case state::input: input = from_hexx(l); st = state::expected_output; break; case state::expected_output: inputs.emplace_back(std::move(input_name), std::move(input), from_hexx(l)); input_name = {}; input = {}; st = state::name; break; } } return inputs; } /// Loads a benchmark case from a file at `path` and all its inputs from the matching inputs file. BenchmarkCase load_benchmark(const fs::path& path, const std::string& name_prefix) { const auto name = name_prefix + path.stem().string(); std::ifstream file{path}; std::string code_hexx{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}}; BenchmarkCase b{name, from_hexx(code_hexx)}; auto inputs_path = path; inputs_path.replace_extension(inputs_extension); if (fs::exists(inputs_path)) b.inputs = load_inputs(inputs_path); return b; } /// Loads all benchmark cases from the given directory and all its subdirectories. std::vector<BenchmarkCase> load_benchmarks_from_dir( // NOLINT(misc-no-recursion) const fs::path& path, const std::string& name_prefix = {}) { std::vector<fs::path> subdirs; std::vector<fs::path> code_files; for (auto& e : fs::directory_iterator{path}) { if (e.is_directory()) subdirs.emplace_back(e); else if (e.path().extension() == runtime_code_extension) code_files.emplace_back(e); } std::sort(std::begin(subdirs), std::end(subdirs)); std::sort(std::begin(code_files), std::end(code_files)); std::vector<BenchmarkCase> benchmark_cases; benchmark_cases.reserve(std::size(code_files)); for (const auto& f : code_files) benchmark_cases.emplace_back(load_benchmark(f, name_prefix)); for (const auto& d : subdirs) { auto t = load_benchmarks_from_dir(d, name_prefix + d.filename().string() + '/'); benchmark_cases.insert(benchmark_cases.end(), std::make_move_iterator(t.begin()), std::make_move_iterator(t.end())); } return benchmark_cases; } void register_benchmarks(const std::vector<BenchmarkCase>& benchmark_cases) { evmc::VM* advanced_vm = nullptr; evmc::VM* baseline_vm = nullptr; if (const auto it = registered_vms.find("advanced"); it != registered_vms.end()) advanced_vm = &it->second; if (const auto it = registered_vms.find("baseline"); it != registered_vms.end()) baseline_vm = &it->second; for (const auto& b : benchmark_cases) { if (advanced_vm != nullptr) { RegisterBenchmark(("advanced/analyse/" + b.name).c_str(), [&b](State& state) { bench_analyse<advanced::AdvancedCodeAnalysis, advanced_analyse>( state, default_revision, b.code); })->Unit(kMicrosecond); } if (baseline_vm != nullptr) { RegisterBenchmark(("baseline/analyse/" + b.name).c_str(), [&b](State& state) { bench_analyse<baseline::CodeAnalysis, baseline_analyse>( state, default_revision, b.code); })->Unit(kMicrosecond); } for (const auto& input : b.inputs) { const auto case_name = b.name + (!input.name.empty() ? '/' + input.name : ""); if (advanced_vm != nullptr) { const auto name = "advanced/execute/" + case_name; RegisterBenchmark(name.c_str(), [&vm = *advanced_vm, &b, &input](State& state) { bench_advanced_execute(state, vm, b.code, input.input, input.expected_output); })->Unit(kMicrosecond); } if (baseline_vm != nullptr) { const auto name = "baseline/execute/" + case_name; RegisterBenchmark(name.c_str(), [&vm = *baseline_vm, &b, &input](State& state) { bench_baseline_execute(state, vm, b.code, input.input, input.expected_output); })->Unit(kMicrosecond); } for (auto& [vm_name, vm] : registered_vms) { const auto name = std::string{vm_name} + "/total/" + case_name; RegisterBenchmark(name.c_str(), [&vm = vm, &b, &input](State& state) { bench_evmc_execute(state, vm, b.code, input.input, input.expected_output); })->Unit(kMicrosecond); } } } } /// The error code for CLI arguments parsing error in evmone-bench. /// The number tries to be different from EVMC loading error codes. constexpr auto cli_parsing_error = -3; /// Parses evmone-bench CLI arguments and registers benchmark cases. /// /// The following variants of number arguments are supported (including argv[0]): /// /// 1: evmone-bench /// Uses evmone VMs, only synthetic benchmarks are available. /// 2: evmone-bench benchmarks_dir /// Uses evmone VMs, loads all benchmarks from benchmarks_dir. /// 3: evmone-bench evmc_config benchmarks_dir /// The same as (2) but loads additional custom EVMC VM. /// 4: evmone-bench code_hex_file input_hex expected_output_hex. /// Uses evmone VMs, registers custom benchmark with the code from the given file, /// and the given input. The benchmark will compare the output with the provided /// expected one. std::tuple<int, std::vector<BenchmarkCase>> parseargs(int argc, char** argv) { // Arguments' placeholders: std::string evmc_config; std::string benchmarks_dir; std::string code_hex_file; std::string input_hex; std::string expected_output_hex; switch (argc) { case 1: // Run with built-in synthetic benchmarks only. break; case 2: benchmarks_dir = argv[1]; break; case 3: evmc_config = argv[1]; benchmarks_dir = argv[2]; break; case 4: code_hex_file = argv[1]; input_hex = argv[2]; expected_output_hex = argv[3]; break; default: std::cerr << "Too many arguments\n"; return {cli_parsing_error, {}}; } if (!evmc_config.empty()) { auto ec = evmc_loader_error_code{}; registered_vms["external"] = evmc::VM{evmc_load_and_configure(evmc_config.c_str(), &ec)}; if (ec != EVMC_LOADER_SUCCESS) { if (const auto error = evmc_last_error_msg()) std::cerr << "EVMC loading error: " << error << "\n"; else std::cerr << "EVMC loading error " << ec << "\n"; return {static_cast<int>(ec), {}}; } std::cout << "External VM: " << evmc_config << "\n"; } if (!benchmarks_dir.empty()) { return {0, load_benchmarks_from_dir(benchmarks_dir)}; } if (!code_hex_file.empty()) { std::ifstream file{code_hex_file}; BenchmarkCase b{code_hex_file, from_spaced_hex(std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}) .value()}; b.inputs.emplace_back( "", from_hex(input_hex).value(), from_hex(expected_output_hex).value()); return {0, {std::move(b)}}; } return {0, {}}; } } // namespace } // namespace evmone::test int main(int argc, char** argv) { using namespace evmone::test; try { Initialize(&argc, argv); // Consumes --benchmark_ options. const auto [ec, benchmark_cases] = parseargs(argc, argv); if (ec == cli_parsing_error && ReportUnrecognizedArguments(argc, argv)) return ec; if (ec != 0) return ec; registered_vms["advanced"] = evmc::VM{evmc_create_evmone(), {{"O", "2"}}}; registered_vms["baseline"] = evmc::VM{evmc_create_evmone(), {{"O", "0"}}}; register_benchmarks(benchmark_cases); register_synthetic_benchmarks(); RunSpecifiedBenchmarks(); return 0; } catch (const std::exception& ex) { std::cerr << ex.what() << "\n"; return -1; } }
#include<stdio.h> #define MAX 10 int main() { int size, i, j; int A[MAX][MAX], symmetric = 1; printf("Enter the size of the square matrix : "); scanf("%d", &size); printf("Enter the elements of the matrix\n"); for(i=0; i<size; i++) { for(j=0; j<size; j++) { scanf("%d", &A[i][j]); } } /* Check whether the matrix is symmetric or not */ for(i=0; i<size; i++) { for(j=0; j<size; j++) { if(A[i][j] != A[j][i]) symmetric = 0; } } if(symmetric == 1) printf("The Matrix is symmetric\n"); else printf("The Matrix is not symmetric\n"); return 0; }
#!/bin/bash function disable_systemd { systemctl disable gogios rm -f $1 } function disable_update_rcd { update-rc.d -f gogios remove rm -f /etc/init.d/gogios } function disable_chkconfig { chkconfig --del gogios rm -f /etc/init.d/gogios } if [[ -f /etc/redhat-release ]] || [[ -f /etc/SuSE-release ]]; then if [[ "$1" = "0" ]]; then rm -f /etc/default/gogios if [[ "$(readlink /proc/1/exe)" == */systemd ]]; then disable_systemd /usr/lib/systemd/system/gogios.service else disable_chkconfig fi fi elif [[ -f /etc/debian_version ]]; then if [ "$1" == "remove" -o "$1" == "purge" ]; then rm -f /etc/default/gogios if [[ "$(readlink /proc/1/exe)" == */systemd ]]; then disable_systemd /lib/systemd/system/gogios.service else if which update-rc.d &>/dev/null; then disable_update_rcd else disable_chkconfig fi fi fi elif [[ -f /etc/os-release ]]; then source /etc/os-release if [[ "$NAME" = "Arch Linux" ]]; then disable_systemd /usr/lib/systemd/system/gogios.service fi fi
#!/bin/bash start=`date -I` echo "==============================" echo "=== TRAVIS NODE TEST START ===" echo "DATE: $start" echo "branch: $TRAVIS_BRANCH" echo "commit: $TRAVIS_COMMIT" echo "=== SYSTEM ===" echo "uname -a: `uname -a`" echo "TRAVIS_OS_NAME: $TRAVIS_OS_NAME" echo "TRAVIS_NODE_VERSION: $TRAVIS_NODE_VERSION" echo "=== ENVIRONMENT ===" for v in USER HOME SHELL BASH_VERSION PATH PWD; do echo "$v: ${!v}" done echo "=== BINARIES ===" for c in node npm nvm ld make cc gcc g++ bash; do echo -n "which $c: " which $c || echo '(none)' done echo "=== VERSIONS ===" for c in "console.log(process.version);" \ "console.log(process.versions.node);"; do echo -n "node -e '$c': " v=`node -e "$c" 2>/dev/null` [ -n "$v" ] && echo $v || echo '(none)' done for c in node npm nvm ld; do echo -n "$c --version: " v=`$c --version 2>/dev/null | head -1` [ -n "$v" ] && echo $v || echo '(none)' done echo -n 'make -v: ' v=`make -v 2>&1 | grep -i 'GNU Make'` [ -n "$v" ] && echo $v || echo '(none)' echo -n 'gcc -v: ' v=`gcc -v 2>&1 | grep 'gcc version' | sed 's/gcc version //'` [ -n "$v" ] && echo $v || echo '(none)' if [ "$TRAVIS" == true ]; then wget https://raw.githubusercontent.com/creationix/nvm/master/nvm.sh . nvm.sh rm nvm.sh fi echo "=== INSTALLED NODE VERSIONS ===" nvm ls echo "=== AVAILABLE NODE VERSIONS ===" nvm ls-remote echo "=== TRAVIS NODE TEST END ===" echo "START: $start" echo "END: `date -Is`" echo "============================"
from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.IntegerField() default_quantity = models.IntegerField(default=20)
let enabled; function setEnabled(isEnabled) { enabled = isEnabled; } function log(message) { if (enabled) { GM_log('[FATE] ' + message); } } setEnabled(false); exports.setEnabled = setEnabled; exports.log = log;
#!/usr/bin/env bash # This is a general-purpose function to ask Yes/No questions in Bash, either # with or without a default answer. It keeps repeating the question until it # gets a valid answer. ask() { # https://djm.me/ask local prompt default reply while true; do if [[ "${2:-}" = "Y" ]]; then prompt="Y/n" default=Y elif [[ "${2:-}" = "N" ]]; then prompt="y/N" default=N else prompt="y/n" default= fi # Ask the question (not using "read -p" as it uses stderr not stdout) echo -n "$1 [$prompt] " read reply # Default? if [[ -z "$reply" ]]; then reply=${default} fi # Check if the reply is valid case "$reply" in Y*|y*) return 0 ;; N*|n*) return 1 ;; esac done } # # Run the initial installer of Docker and AzuraCast. # Usage: ./docker.sh install # install() { if [[ $(which docker) && $(docker --version) ]]; then echo "Docker is already installed! Continuing..." else if ask "Docker does not appear to be installed. Install Docker now?" Y; then curl -fsSL get.docker.com -o get-docker.sh sh get-docker.sh rm get-docker.sh if [[ $EUID -ne 0 ]]; then sudo usermod -aG docker `whoami` echo "You must log out or restart to apply necessary Docker permissions changes." echo "Restart, then continue installing using this script." exit fi fi fi if [[ $(which docker-compose) && $(docker-compose --version) ]]; then echo "Docker Compose is already installed! Continuing..." else if ask "Docker Compose does not appear to be installed. Install Docker Compose now?" Y; then if [[ ! $(which git) ]]; then echo "Git does not appear to be installed." echo "Install git using your host's package manager," echo "then continue installing using this script." exit 1 fi if [[ ! $(which curl) ]]; then echo "cURL does not appear to be installed." echo "Install curl using your host's package manager," echo "then continue installing using this script." exit 1 fi COMPOSE_VERSION=`git ls-remote https://github.com/docker/compose | grep refs/tags | grep -oP "[0-9]+\.[0-9][0-9]+\.[0-9]+$" | tail -n 1` if [[ $EUID -ne 0 ]]; then if [[ ! $(which sudo) ]]; then echo "Sudo does not appear to be installed." echo "Install sudo using your host's package manager," echo "then continue installing using this script." exit 1 fi sudo sh -c "curl -fsSL https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose" sudo chmod +x /usr/local/bin/docker-compose sudo sh -c "curl -fsSL https://raw.githubusercontent.com/docker/compose/${COMPOSE_VERSION}/contrib/completion/bash/docker-compose -o /etc/bash_completion.d/docker-compose" else curl -fsSL https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose curl -fsSL https://raw.githubusercontent.com/docker/compose/${COMPOSE_VERSION}/contrib/completion/bash/docker-compose -o /etc/bash_completion.d/docker-compose fi fi fi if [[ ! -f .env ]]; then echo "Writing default .env file..." curl -fsSL https://raw.githubusercontent.com/AzuraCast/AzuraRelay/master/.env -o .env fi if [[ ! -f docker-compose.yml ]]; then echo "Retrieving default docker-compose.yml file..." curl -fsSL https://raw.githubusercontent.com/AzuraCast/AzuraRelay/master/docker-compose.sample.yml -o docker-compose.yml fi if [[ ! -f azurarelay.env ]]; then touch azurarelay.env fi docker-compose up -d docker-compose run --rm --user="azurarelay" relay cli app:setup docker cp azurarelay_relay_1:/var/azurarelay/www_tmp/azurarelay.env ./azurarelay.env docker-compose down -v docker-compose up -d docker-compose exec --user="azurarelay" relay cli app:update exit } # # Update the Docker images and codebase. # Usage: ./docker.sh update # update() { curl -fsSL https://raw.githubusercontent.com/AzuraCast/AzuraRelay/master/docker-compose.sample.yml -o docker-compose.new.yml FILES_MATCH="$(cmp --silent docker-compose.yml docker-compose.new.yml; echo $?)" UPDATE_NEW=0 if [[ ${FILES_MATCH} -ne 0 ]]; then if ask "The docker-compose.yml file has changed since your version. Overwrite? This will overwrite any customizations you made to this file?" Y; then UPDATE_NEW=1 fi fi if [[ ${UPDATE_NEW} -ne 0 ]]; then docker-compose -f docker-compose.new.yml pull docker-compose down cp docker-compose.yml docker-compose.backup.yml mv docker-compose.new.yml docker-compose.yml else rm docker-compose.new.yml docker-compose pull docker-compose down fi docker-compose up -d docker-compose exec --user="azurarelay" relay cli app:update docker rmi $(docker images | grep "none" | awk '/ / { print $3 }') 2> /dev/null echo "Update complete!" exit } # # Update this Docker utility script. # Usage: ./docker.sh update-self # update-self() { curl -fsSL https://raw.githubusercontent.com/AzuraCast/AzuraRelay/master/docker.sh -o docker.sh chmod a+x docker.sh echo "New Docker utility script downloaded." exit } # # Run a CLI command inside the Docker container. # Usage: ./docker.sh cli [command] # cli() { docker-compose run --user="azurarelay" --rm relay cli $* exit } # # Enter the bash terminal of the running web container. # Usage: ./docker.sh bash # bash() { docker-compose exec --user="azurarelay" relay bash exit } # # DEVELOPER TOOL: # Run the full test suite. # dev-tests() { docker-compose exec --user="azurarelay" relay composer phplint -- $* docker-compose exec --user="azurarelay" relay composer phpstan -- $* exit } # # Stop all Docker containers and remove related volumes. # Usage: ./docker.sh uninstall # uninstall() { if ask "This operation is destructive and will wipe your existing Docker containers. Continue? [y/N] " N; then docker-compose down -v docker-compose rm -f docker volume prune -f echo "All AzuraRelay Docker containers and volumes were removed." echo "To remove *all* Docker containers and volumes, run:" echo " docker stop \$(docker ps -a -q)" echo " docker rm \$(docker ps -a -q)" echo " docker volume prune -f" echo "" fi exit } # # Create and link a LetsEncrypt SSL certificate. # Usage: ./docker.sh letsencrypt-create domainname.example.com # letsencrypt-create() { docker-compose exec --user="azurarelay" relay letsencrypt_connect $* exit } # # Renew an existing LetsEncrypt SSL certificate # Usage: ./docker.sh letsencrypt-renew # letsencrypt-renew() { docker-compose exec --user="azurarelay" relay letsencrypt_renew $* exit } $*
import requests from bs4 import BeautifulSoup url = "https://en.wikipedia.org/wiki/Web_scraping" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') text = soup.find_all('p') for t in text: print(t.text)
package cmu.xprize.robotutor.download; /** * Description: * Created by kang on 2018/3/9. */ public interface DownloadListener { void onStart(); void onProgress(int currentLength); void onFinish(String localPath); void onFailure(int code, String msg); }
#Generate the project rails new blog #Create the model rails generate model Post title content:text #Migration class CreatePost < ActiveRecord::Migration[6.0] def change create_table :posts do |t| t.string :title t.text :content t.timestamps end end end #Change routes.rb Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :posts end #Generate controller rails generate controller posts #Manipulate application_controller.rb class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :set_title def set_title @page_title = "My Blog" end end #Generate views rails generate views posts index show new edit
<gh_stars>0 import { useEffect, useState } from 'react'; import logo from './logo.svg'; import './App.css'; import LoginView from './views/login'; import { Button } from 'react-bootstrap'; import EventSchedule from './views/event-schedule'; // import { Link, Switch } from 'react-router-dom'; // import { BrowserRouter, Routes, Route } from 'react-router-dom'; //import { Navbar, Container, Nav, NavDropdown } from 'react-bootstrap'; function App() { const [isAuth, setAuth] = useState(false); const [role, setRole] = useState(''); useEffect(() => { setAuth(localStorage.getItem('Password') != null); setRole(localStorage.getItem('Role')) },[]); const updateLogin = (isLoggedIn, userRole) => { setAuth(isLoggedIn); if (isLoggedIn) { localStorage.setItem('Role', userRole) } } const logout = () => { localStorage.removeItem('Password'); localStorage.removeItem('Role'); setAuth(null); setRole(''); } if (!isAuth) { return (<LoginView updateLoginCallback={updateLogin} />); } else { const eventHeaders = ['Name', 'Age', 'Event', 'Session', 'Time']; return ( <div className="App"> <header> I am a ☕ </header> <div style={{margin: 4 + 'em'}}> <EventSchedule /> </div> <Button variant='secondary' onClick={logout} >Logout</Button> </div> ); } } export default App;
import { execa } from 'execa'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import def, { bootstrap, bootstrapQueries, bulma, bulmaQueries, foundation, foundationQueries, mantine, mantineQueries, mui, muiQueries, pico, picoQueries, tailwind, tailwindQueries, } from './'; test('default export', () => { expect(def).toEqual({ lg: 960, md: 720, sm: 540, xl: 1140, xxl: 1320 }); expect(def).toBe(bootstrap); }); test('mantine matches bootstrap', () => { expect(mantine).toBe(bootstrap); }); test('tailwind', () => { expect(tailwind).toEqual({ sm: 640, md: 768, lg: 1024, xl: 1280, xxl: 1536 }); }); test('mui', () => { expect(mui).toEqual({ xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536 }); }); test('foundation', () => { expect(foundation).toEqual({ small: 0, medium: 640, large: 1024 }); }); test('pico', () => { expect(pico).toEqual({ sm: 576, md: 768, lg: 992, xl: 1200 }); }); test('bulma', () => { expect(bulma).toEqual({ mobile: 0, tablet: 769, desktop: 1024, widescreen: 1216, fullhd: 1408, }); }); describe('queries', () => { test.each([ ['default', def, bootstrapQueries], ['bootstrap', bootstrap, bootstrapQueries], ['mantine', mantine, mantineQueries], ['tailwind', tailwind, tailwindQueries], ['mui', mui, muiQueries], ['foundation', foundation, foundationQueries], ['pico', pico, picoQueries], ['bulma', bulma, bulmaQueries], ])('%s', (_name, numbers, queries) => { expect(queries).toEqual( Object.fromEntries( Object.entries(numbers).map(([key, num]) => [ key, `(min-width: ${num}px)`, ]), ), ); }); }); test('tree shaking', async () => { const output = await execa('npx', [ 'esbuild', '--bundle', join(dirname(fileURLToPath(import.meta.url)), '__fixtures__', 'entry.ts'), ]); expect(output.stdout).toMatchInlineSnapshot(` "(() => { // src/queries/bootstrap.ts var bootstrap_default = { sm: \\"(min-width: 540px)\\", md: \\"(min-width: 720px)\\", lg: \\"(min-width: 960px)\\", xl: \\"(min-width: 1140px)\\", xxl: \\"(min-width: 1320px)\\" }; // src/__fixtures__/entry.ts console.log(bootstrap_default); console.log(bootstrap_default); })();" `); });
<filename>src/components/MiniChampion.js import React from 'react'; import PropTypes from 'prop-types'; import style from '../styles/MiniChampion.module.css'; import MiniChampionContent from './MiniChampionContent'; const imageSrc = 'http://ddragon.leagueoflegends.com/cdn/10.11.1/img/champion/'; const MiniChampion = ({ champion, handleChampionClick, selected }) => { const defaultStyle = `${style.image} ${style.champion}`; const styles = selected ? `${defaultStyle} ${style.selected}` : defaultStyle; return ( <MiniChampionContent handleChampionClick={handleChampionClick} styles={styles} imageSrc={`${imageSrc}${champion.image.full}`} champion={champion} /> ); }; MiniChampion.propTypes = { champion: PropTypes.shape( { image: PropTypes.shape( { full: PropTypes.string.isRequired, }, ).isRequired, }, ).isRequired, handleChampionClick: PropTypes.func.isRequired, selected: PropTypes.bool.isRequired, }; export default MiniChampion;
import typing class DirProvider: def __init__(self, config, auth_rule_matcher): self.config = config self.auth_rule_matcher = auth_rule_matcher def search(self) -> typing.List[typing.AnyStr]: raise NotImplementedError()
#!/bin/bash ## ./deploy-all-services.sh $APPS_NAMESPACE $SUBDOMAIN APPS_NAMESPACE=$1 SUBDOMAIN=$2 SCRIPTS_DIR=$(dirname $0)/descriptors oc whoami if [ $? -ne 0 ] then echo "You must be logged in in the platform" exit 1 fi echo "" echo "*** Deploying all services " cat $SCRIPTS_DIR/all-services.yml | NAMESPACE=$(echo $APPS_NAMESPACE) envsubst | oc apply -f - -n $APPS_NAMESPACE echo "" echo " **************************************************************************************************************************** " echo "" echo " Test customer service: curl -v customer.$APPS_NAMESPACE.$SUBDOMAIN " echo "" echo " **************************************************************************************************************************** " echo ""
import React, { useState } from "react"; import { axiosWithAuth } from "../../Utils/axiosWithAuth"; import { Link } from "react-router-dom"; import { CardWrapper, CardHeader, CardHeading, CardBody, CardIcon, CardFieldset, CardInput, CardOptionsItem, CardOptions, CardButton, CardLink, CardBox } from "./UserCard"; import '../../App.css'; const UserLogin = (props) => { const [credentials, setCredentials] = useState({}); const login = e => { e.preventDefault(); axiosWithAuth().post("/auth/users/login", credentials) .then(res => { console.log("login res: ", res) localStorage.setItem('token', res.data.token); props.history.push('/'); }) } const handleChange = e => { setCredentials({ ...credentials, [e.target.name]: e.target.value }); } return ( <div> <form onSubmit={login}> <CardWrapper> <CardHeader> <CardHeading>Log in</CardHeading> </CardHeader> <CardBody> <CardFieldset> <CardInput type="text" name="username" placeholder="username" value={credentials.username} onChange={handleChange} required /> </CardFieldset> <CardFieldset> <CardInput placeholder="Password" name="password" type="password" value={credentials.password} onChange={handleChange} required /> <CardIcon className="fa fa-eye" eye small /> </CardFieldset> <CardFieldset> <CardBox name="isServiceWorker" type="checkbox" value={credentials.isServiceWorker} onChange={handleChange} required /> <label for="isServiceWorker">Service Worker</label> </CardFieldset> <CardFieldset> <CardOptions> <CardOptionsItem> <CardIcon className="fab fa-google" big /> </CardOptionsItem> <CardOptionsItem> <CardIcon className="fab fa-twitter" big /> </CardOptionsItem> <CardOptionsItem> <CardIcon className="fab fa-facebook" big /> </CardOptionsItem> </CardOptions> </CardFieldset> <CardFieldset> <CardButton type="submit">Log in </CardButton> </CardFieldset> {/* <CardFieldset> <CardButton onClick={() => { setCredentials(false) localStorage.removeItem("token"); }}>Logout</CardButton> </CardFieldset> */} <CardFieldset> <CardLink> <Link to="/usersignup">Don't have an account yet?</Link> </CardLink> </CardFieldset> </CardBody> </CardWrapper> </form> </div> ) } export default UserLogin;
def find_difference(arr): diff = 0 for i in range(len(arr)): for j in range(i+1, len(arr)): temp_diff = abs(arr[i] - arr[j]) if temp_diff > diff: diff= temp_diff return diff
#!/bin/sh IMAGE_NAME=$1 DIRNAME=sudo dirname $(pwd) if [ "${IMAGE_NAME}" = "" ]; then exit 1 fi sudo docker run -it --rm --runtime nvidia -v $DIRNAME:/usr/local/src/ -w /usr/local/src/ --privileged --network host ${IMAGE_NAME}
module increment( input [3:0] num, output [3:0] res ); assign res = num + 4'b0001; endmodule
import Constraints from '../../../api/Constraints.js'; import { REGEX_COMPONENT_NAME, REGEX_PROPERTY_NAME } from '../constants/constants.js'; export default { name: Constraints.matches(REGEX_COMPONENT_NAME) , properties: Constraints.optional( Constraints.every( [ Constraints.objectKeysOf( Constraints.matches(REGEX_PROPERTY_NAME)) , Constraints.objectValuesOf( Constraints.hasShape( { type: Constraints.isFunction , defaultValue: Constraints.any , inject: Constraints.satisfies( it => it === undefined || it === true || it === false, 'Must be undefined or boolean') })) ]) ) };
// import { IO } from "../iinterface"; import { imiddleware } from "../imiddleware" export const simpleError:imiddleware = { interface: "WEB", fnc: function(err:SyntaxError, req:any, res:any, next:Function){ const e:any = err if (err instanceof SyntaxError && e.status === 400 && 'body' in err) { return res.status(400).send({ message: err.message }); // Bad request } next(); } }
<gh_stars>1-10 import React from 'react' import {shallow, mount} from 'enzyme' import {shallowToJson} from 'enzyme-to-json' import configureMockStore from 'redux-mock-store' import EditUser from './EditUser' import PropTypes from 'prop-types' describe('Edit User Form', () => { const mockStore = configureMockStore([]) let store let combinedReducersState = {} const initValues = { id: 0, firstName: 'Bob', lastName: 'John' } beforeEach(() => { store = mockStore(combinedReducersState) }) test('should pass snapshot test', () => { const component = shallow(<EditUser store={store} updateUserRequest={jest.fn()} goTo={jest.fn()} initialValues={initValues} />) const tree = shallowToJson(component) expect(tree).toMatchSnapshot() }) test('should be selectable by class "userRegistrationForm"', () => { const component = mount(<div className='some-class other-class' />) expect(component.is('.some-class')).toEqual(true) }) test('should mount in a full DOM', () => { const component = shallow(<EditUser store={store} updateUserRequest={jest.fn()} goTo={jest.fn()} initialValues={initValues} />) expect(component.find('div').length).toEqual(1) }) test('should render to static HTML', () => { const component = shallow(<EditUser store={store} updateUserRequest={jest.fn()} goTo={jest.fn()} initialValues={initValues} />) expect(component.text()).toEqual('<ReduxForm />') }) })
package models; import javax.persistence.Entity; import javax.persistence.Id; import java.math.BigDecimal; @Entity public class SalesChart { @Id private int year; private double total; public SalesChart(int year, double total) { this.year = year; this.total = total; } public int getLabel() { return year; } public double getCount() { return total; } }
package main import "fmt" func main() { colors := []string{"black", "red", "blue"} colors = append(colors, "green") colors = colors[1 : len(colors)-1] fmt.Println(len(colors)) fmt.Println(cap(colors)) fmt.Println(colors) }
# https://developer.zendesk.com/rest_api/docs/nps-api/recipients#list-recipients zdesk_nps_survey_recipients () { method=GET url="$(echo "/api/v2/nps/surveys/{survey_id}/recipients.json" | sed \ -e "s/{survey_id}"/"$1"/ \ )" shift }
let initCb, parseCb, dummy; export function mockInit(init, parse) { initCb = init; parseCb = parse; } export async function init(config) { if (initCb) initCb(...arguments); if (!config.flatteners) config.flatteners = {}; config.flatteners['customTag'] = (result, tag, name) => { if (name !== 'customTag') throw new Error('customTag received unexpected tag'); tag.customField = true; }; dummy = [ { value: '*\n * @method dummy\n ', context: { file: 'plugin.txt', loc: { start: { line: 5, column: 1 }, end: { line: 5, column: 4 } }, sortKey: 'a' }, loc: { start: { line: 0, column: 1 }, end: { line: 2, column: 1 } } }, { value: '*\n * @param {number} dummy_param\n ', context: { file: 'plugin.txt', loc: { start: { line: 5, column: 1 }, end: { line: 5, column: 4 } }, sortKey: 'b', kind: 'method', name: 'dummy_method' }, loc: { start: { line: 0, column: 1 }, end: { line: 2, column: 1 } } }, { value: '*\n * @method not_so_dummy\n ', context: { file: 'plugin.txt', loc: { start: { line: 5, column: 1 }, end: { line: 5, column: 4 } }, sortKey: 'c', kind: 'SHOULD_NOT_APPEAR_IN_THE_RESULT', name: 'SHOULD_NOT_APPEAR_IN_THE_RESULT' }, loc: { start: { line: 0, column: 1 }, end: { line: 2, column: 1 } } }, { value: '*\n * @customTag customName\n ', context: { file: 'plugin.txt', loc: { start: { line: 5, column: 1 }, end: { line: 5, column: 4 } }, sortKey: 'x' }, loc: { start: { line: 0, column: 1 }, end: { line: 2, column: 1 } } } ]; } export function parse(file, _config, api) { if (parseCb) parseCb(...arguments); if (file.file.includes('plugin.txt')) return dummy.map(c => api.parseJSDoc(c.value, c.log, c.context, _config)); return false; }
#!/bin/bash export VERSION="${PLASMA_VERSION}" echo "${VERSION}" EXT=".tar.xz" PKGVER="${PKGNAME}-${VERSION}" export SOURCE="${PKGVER}${EXT}" if ! [ -r "${SRCDIR}/${MODULE}/${SOURCE}" ]; then SRCNAME="polkit-kde-agent-1-${VERSION}" echo -e "${YELLOW}Downloading ${SRCNAME}${EXT} source archive${CDEF}" ( cd "${SRCDIR}/${MODULE}" || exit 1 wget "${KDEDOWNLOAD}/${MODULE}/${VERSION}/${SRCNAME}${EXT}" tar xf "${SRCNAME}${EXT}" 1>/dev/null 2>&1 rm -f "${SRCNAME}${EXT}" mv "${SRCNAME}" "${PKGVER}" tar -cJf "${PKGVER}${EXT}" "${PKGVER}" 1>/dev/null rm -rf "${PKGVER}" ) fi
import React, { Component } from 'react'; import { View, Text, StyleSheet, Modal, TouchableOpacity } from 'react-native'; /* * props: * type: 1.背景白,文字默认#AAE039 2.第一个背景白文字#AAE039,后面的都是背景#AAE039,文字白 * title: 标题 * content: 内容 * buttons: 按钮数组 * cancel: 取消按钮文本信息。背景白,文字红#FE3113 * defaultColor: 文本&背景颜色(优先级比AlertView.DefaultColor高) * isRequestClose: 回调会在用户按下 Android 设备上的后退按键或是 Apple TV 上的菜单键时是否关闭Modal,默认true * * func: * buttonClicked(index): 按钮点击事件(从左到右 0-N, 取消按钮也算在内) * * export func: * show(data = {}): 显示AlertView, 支持修改类型,标题,内容,按钮,取消按钮 {'type': 1,'title': '标题', 'content': '内容', buttons: ['数组'], cancel: '取消'} * hide: 隐藏AlertView * * can modify: * AlertView.DefaultColor: 全局设置文本&背景颜色,默认#AAE039 * * inherit: * createTitelView: 可继承实现自己的标题视图 * createContentView: 可继承实现自己的内容视图 * createButtonView: 可继承实现自己的按钮视图 * */ export default class AlertView extends Component{ /************************** 生命周期 **************************/ constructor(props) { super(props); this.initializeParams(); } componentDidMount() { if (this.props.evaluateView) this.props.evaluateView(this); } /************************** 继承方法 **************************/ /************************** 通知 **************************/ /************************** 创建视图 **************************/ /* * 创建标题视图 * */ createTitelView = () => { const { title } = this.state; return ( <View> <View style={[styles.TitleView]}> <Text style={[styles.TitleTextView]}>{title}</Text> </View> <View style={[styles.LineView]}></View> </View> ) } /* * 创建内容视图 * */ createContentView = () => { const { content } = this.state; return ( <View> <View style={[styles.ContenView]}> <Text style={[styles.ContenTextView]}>{content}</Text> </View> <View style={[styles.LineView]}></View> </View> ) } /* * 创建按钮视图 * */ createButtonView = () => { const { buttons, cancel, type } = this.state; let buttonView = null; if (buttons.length > 0) { let titleColor = this.getDefaultColor(); let bgColor = 'white'; buttonView = buttons.map( (item, index) => { if (type == 2) { if (cancel.length > 0 || (cancel.length == 0 && index != 0) || (cancel.length == 0 && buttons.length == 1)) { titleColor = 'white'; bgColor = this.getDefaultColor(); } } let lineView = null; if (cancel.length > 0 || (cancel.length == 0 && index > 0)) { lineView = (<View style={[{backgroundColor: '#EBEBEB', width: 1}]}></View>); } return ( <View style={[{flexDirection: 'row', flex: 1}]} key={index}> {lineView} <TouchableOpacity onPress={this.buttonClicked.bind(this, cancel.length > 0 ? (index + 1) : index)} style={[{flex: 1}]}> <View style={[styles.TitleCenter, {backgroundColor: bgColor, borderBottomLeftRadius: ((cancel.length == 0 && index == 0) ? 6 : 0), borderBottomRightRadius: ((index == buttons.length-1) ? 6 : 0)}]}> <Text style={[styles.ButtonTextView, {color: titleColor }]}>{item}</Text> </View> </TouchableOpacity> </View> ) }) } return ( <View style={[styles.ButtonView]}> { cancel.length > 0 ? ( <TouchableOpacity onPress={this.buttonClicked.bind(this, 0)} style={{flex: 1}}> <View style={[styles.TitleCenter, {borderBottomLeftRadius: 6}]}> <Text style={[styles.ButtonTextView, {color: '#FE3113'}]}>{cancel}</Text> </View> </TouchableOpacity> ) : null } {buttonView} </View> ); } /************************** 网络请求 **************************/ /************************** 自定义方法 **************************/ /* * 初始化参数 * */ initializeParams() { this.state = { show: false, type: this.props.type ? this.props.type : 1, title: this.props.title ? this.props.title : '', content: this.props.content ? this.props.content : '', buttons: this.props.buttons ? this.props.buttons : [], cancel: this.props.cancel ? this.props.cancel : '' } } /* * 按钮点击事件 * */ buttonClicked = (index) => { if (this.props.buttonClicked) this.props.buttonClicked(index); } /************************** 子组件回调方法 **************************/ /************************** 外部调用方法 **************************/ /* * 显示AlertView, 支持修改类型,标题,内容,按钮,取消按钮 * {'type': 1,'title': '标题', 'content': '内容', buttons: ['数组'], cancel: '取消'} * */ show = (data = {}) => { this.setState({ show: true, type: data['type'] ? data['type'] : this.state.type, title: data['title'] ? data['title'] : this.state.title, content: data['content'] ? data['content'] : this.state.content, buttons: data['buttons'] ? data['buttons'] : this.state.buttons, cancel: data['cancel'] ? data['cancel'] : this.state.cancel }); } /* * 隐藏AlertView * */ hide = () => { this.setState({ show: false }); } /* * 获取文本&背景颜色 * */ getDefaultColor = () => { return this.props.defaultColor ? this.props.defaultColor : (AlertView.DefaultColor ? AlertView.DefaultColor : '#AAE039'); } /************************** List相关方法 **************************/ /************************** Render中方法 **************************/ /* * Android 设备上的后退按键或是 Apple TV 上的菜单键触发事件 * */ _onRequestClose = () => { const { isRequestClose = true } = this.props; if (isRequestClose) this.hide(); } render() { const { show } = this.state; if (!show) return null; //标题视图 let titleView = this.createTitelView(); //文本视图 let contentView = this.createContentView(); //按钮视图 let buttonView = this.createButtonView(); return ( <Modal visible={true} animateType={'fade'} transparent={true} onRequestClose={this._onRequestClose} > <View style={[styles.MainView]}> <View style={[styles.ContentMainView]}> {titleView} {contentView} {buttonView} </View> </View> </Modal> ) } } const styles = StyleSheet.create({ MainView: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.6)', justifyContent: 'center' }, ContentMainView: { marginLeft: 30, marginRight: 30, backgroundColor: 'white', borderRadius: 6, borderWidth: 0.5, borderColor: '#EBEBEB' }, TitleView: { justifyContent: 'center', alignItems: 'center', height: 56 }, TitleTextView: { fontSize: 16, fontFamily: 'PingFangSC-Medium' }, ContenView: { }, ContenTextView: { fontFamily: 'PingFangSC-Regular', marginLeft: 20, marginRight: 20, marginBottom: 20, marginTop: 20, fontSize: 14 }, ButtonView: { flexDirection: 'row', height: 44 }, ButtonTextView: { fontFamily: 'PingFangSC-Medium', fontSize: 16, color: 'white' }, LineView: { backgroundColor: '#E8E8E8', height: 0.5 }, TitleCenter: { flex: 1, justifyContent: 'center', alignItems: 'center' } })
set -e rm -rf gh-pages mkdir gh-pages cd gh-pages git clone https://github.com/chevrotain/chevrotain.git . git checkout gh-pages # update contents rm -rf docs cp -r ../docs/.vuepress/dist/ docs git add -A git commit -m 'Update Website' git push # cleanup cd .. rm -rf gh-pages
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'AddFilter.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(988, 277) self.verticalLayout = QtWidgets.QVBoxLayout(Form) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.label = QtWidgets.QLabel(Form) self.label.setMinimumSize(QtCore.QSize(40, 0)) self.label.setMaximumSize(QtCore.QSize(40, 16777215)) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.lineEdit_group = QtWidgets.QLineEdit(Form) self.lineEdit_group.setObjectName("lineEdit_group") self.horizontalLayout.addWidget(self.lineEdit_group) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.pushButton_fore_color = QtWidgets.QPushButton(Form) self.pushButton_fore_color.setObjectName("pushButton_fore_color") self.horizontalLayout.addWidget(self.pushButton_fore_color) self.pushButton_back_color = QtWidgets.QPushButton(Form) self.pushButton_back_color.setObjectName("pushButton_back_color") self.horizontalLayout.addWidget(self.pushButton_back_color) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.label_2 = QtWidgets.QLabel(Form) self.label_2.setMinimumSize(QtCore.QSize(40, 0)) self.label_2.setMaximumSize(QtCore.QSize(40, 16777215)) self.label_2.setObjectName("label_2") self.horizontalLayout_2.addWidget(self.label_2) self.comboBox_filter_history = QtWidgets.QComboBox(Form) self.comboBox_filter_history.setObjectName("comboBox_filter_history") self.horizontalLayout_2.addWidget(self.comboBox_filter_history) self.verticalLayout.addLayout(self.horizontalLayout_2) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.checkBox_excluding = QtWidgets.QCheckBox(Form) self.checkBox_excluding.setMinimumSize(QtCore.QSize(60, 0)) self.checkBox_excluding.setMaximumSize(QtCore.QSize(120, 16777215)) self.checkBox_excluding.setObjectName("checkBox_excluding") self.horizontalLayout_3.addWidget(self.checkBox_excluding) self.checkBox_case = QtWidgets.QCheckBox(Form) self.checkBox_case.setMinimumSize(QtCore.QSize(60, 0)) self.checkBox_case.setMaximumSize(QtCore.QSize(120, 16777215)) self.checkBox_case.setObjectName("checkBox_case") self.horizontalLayout_3.addWidget(self.checkBox_case) self.checkBox_regex = QtWidgets.QCheckBox(Form) self.checkBox_regex.setMinimumSize(QtCore.QSize(60, 0)) self.checkBox_regex.setObjectName("checkBox_regex") self.horizontalLayout_3.addWidget(self.checkBox_regex) self.buttonBox_accept = QtWidgets.QDialogButtonBox(Form) self.buttonBox_accept.setMaximumSize(QtCore.QSize(200, 16777215)) self.buttonBox_accept.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox_accept.setObjectName("buttonBox_accept") self.horizontalLayout_3.addWidget(self.buttonBox_accept) self.verticalLayout.addLayout(self.horizontalLayout_3) self.plainTextEdit_description = QtWidgets.QPlainTextEdit(Form) self.plainTextEdit_description.setObjectName("plainTextEdit_description") self.verticalLayout.addWidget(self.plainTextEdit_description) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) Form.setTabOrder(self.lineEdit_group, self.pushButton_fore_color) Form.setTabOrder(self.pushButton_fore_color, self.pushButton_back_color) Form.setTabOrder(self.pushButton_back_color, self.comboBox_filter_history) Form.setTabOrder(self.comboBox_filter_history, self.checkBox_excluding) Form.setTabOrder(self.checkBox_excluding, self.checkBox_case) Form.setTabOrder(self.checkBox_case, self.checkBox_regex) Form.setTabOrder(self.checkBox_regex, self.plainTextEdit_description) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.label.setText(_translate("Form", "Parent:")) self.lineEdit_group.setPlaceholderText(_translate("Form", "Set filter group here (Optional)")) self.pushButton_fore_color.setText(_translate("Form", "&Fore Color")) self.pushButton_back_color.setText(_translate("Form", "&Back Color")) self.label_2.setText(_translate("Form", "Filter: ")) self.checkBox_excluding.setText(_translate("Form", "E&xcluding")) self.checkBox_case.setText(_translate("Form", "C&ase")) self.checkBox_regex.setText(_translate("Form", "&Regex"))
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' setup_stop_services() { info "Stopping services" for service in "${!SERVICES[@]}"; do if [[ "$service" != "plexpy" && "$service" != "ombi" ]]; then info "-- Stopping ${SERVICES[$service]}" $(service ${SERVICES[$service]} stop) || warning "Unable to stop ${SERVICES[$service]}" fi done }
#!/bin/bash which nodetool &>/dev/null || { >&2 echo "Unable to find 'nodetool' in path" exit 1 } which gawk &>/dev/null || { >&2 echo "Unable to find 'gawk' in path" exit 1 } nodetool info 2>/dev/null | gawk ' function hr_to_bytes(NUMBER, U) { if (toupper(U) == "KB" || toupper(U) == "KIB") return (NUMBER * 1024); else if (toupper(U) == "MB" || toupper(U) == "MIB") return (NUMBER * 1024 * 1024); else if (toupper(U) == "GB" || toupper(U) == "GIB") return (NUMBER * 1024 * 1024 * 1024); else return NUMBER } function or_one(NUMBER) { if (NUMBER == 0) { return 1.0; } return NUMBER; } /^Load/ { printf "load_bytes\tL\t%0.0f\n", hr_to_bytes($3, $4) next } /^Generation No/ { print "generation_number\tL\t"$4 next } /^Uptime \(seconds\)/ { print "uptime_secs\tL\t"$4 next } /^Heap Memory \(MB\)/ { printf "heap_mem_used\tL\t%0.0f\nheap_mem_max\tL\t%0.0f\n", hr_to_bytes($5, "MB"), hr_to_bytes($7, "MB") next } /^Off Heap Memory \(MB\)/ { printf "off_heap_mem_used\tL\t%0.0f\n", hr_to_bytes($6, "MB") next } /Key Cache/ { sub(/,/,"", $5) sub(/,/, "", $8) sub(/,/, "", $11) printf "key_cache_entries\tL\t%s\nkey_cache_size\tL\t%0.0f\nkey_cache_capacity\tL\t%0.0f\nkey_cache_hits\tL\t%s\nkey_cache_requests\tL\t%s\nkey_cache_hit_pct\tn\t%s\n", $5, hr_to_bytes($7, $8), hr_to_bytes($10, $11), $12, $14, ($12/or_one($14)) * 100 next } /Counter Cache/ { sub(/,/,"", $5) sub(/,/, "", $8) sub(/,/, "", $11) printf "counter_cache_entries\tL\t%s\ncounter_cache_size\tL\t%0.0f\ncounter_cache_capacity\tL\t%0.0f\ncounter_cache_hits\tL\t%s\ncounter_cache_requests\tL\t%s\ncounter_cache_hit_pct\tn\t%s\n", $5, hr_to_bytes($7, $8), hr_to_bytes($10, $11), $12, $14, ($12/or_one($14)) * 100 next } /Chunk Cache/ { sub(/,/,"", $5) sub(/,/, "", $8) sub(/,/, "", $11) printf "chunk_cache_entries\tL\t%s\nchunk_cache_size\tL\t%0.0f\nchunk_cache_capacity\tL\t%0.0f\nchunk_cache_misses\tL\t%s\nchunk_cache_requests\tL\t%s\nchunk_cache_hit_pct\tn\t%s\nchunk_cache_miss_latency_ms\tn\t%s\n", $5, hr_to_bytes($7, $8), hr_to_bytes($10, $11), $12, $14, $16 * 100, $20 next } ' # END
<reponame>saydulk/crave<gh_stars>10-100 // Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2012 The Darkcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MASTERNODE_H #define MASTERNODE_H #include "uint256.h" #include "sync.h" #include "net.h" #include "key.h" #include "util.h" #include "base58.h" #include "main.h" #include "script.h" #include "masternode.h" class uint256; #define MASTERNODE_NOT_PROCESSED 0 // initial state #define MASTERNODE_IS_CAPABLE 1 #define MASTERNODE_NOT_CAPABLE 2 #define MASTERNODE_STOPPED 3 #define MASTERNODE_INPUT_TOO_NEW 4 #define MASTERNODE_PORT_NOT_OPEN 6 #define MASTERNODE_PORT_OPEN 7 #define MASTERNODE_SYNC_IN_PROCESS 8 #define MASTERNODE_REMOTELY_ENABLED 9 #define MASTERNODE_MIN_CONFIRMATIONS 15 #define MASTERNODE_MIN_DSEEP_SECONDS (30*60) #define MASTERNODE_MIN_DSEE_SECONDS (5*60) #define MASTERNODE_PING_SECONDS (1*60) #define MASTERNODE_EXPIRATION_SECONDS (65*60) #define MASTERNODE_REMOVAL_SECONDS (70*60) using namespace std; class CMasternode; extern CCriticalSection cs_masternodes; extern map<int64_t, uint256> mapCacheBlockHashes; bool GetBlockHash(uint256& hash, int nBlockHeight); // // The Masternode Class. For managing the darksend process. It contains the input of the 500 CRAVE, signature to prove // it's the one who own that ip address and code for calculating the payment election. // class CMasternode { private: // critical section to protect the inner data structures mutable CCriticalSection cs; public: enum state { MASTERNODE_ENABLED = 1, MASTERNODE_EXPIRED = 2, MASTERNODE_VIN_SPENT = 3, MASTERNODE_REMOVE = 4, MASTERNODE_POS_ERROR = 5 }; CTxIn vin; CService addr; CPubKey pubkey; CPubKey pubkey2; std::vector<unsigned char> sig; int activeState; int64_t sigTime; //dsee message times int64_t lastDseep; int64_t lastTimeSeen; int cacheInputAge; int cacheInputAgeBlock; bool unitTest; bool allowFreeTx; int protocolVersion; int64_t nLastDsq; //the dsq count from the last dsq broadcast of this node CScript rewardAddress; int rewardPercentage; int nVote; int64_t lastVote; int nScanningErrorCount; int nLastScanningErrorBlockHeight; int64_t nLastPaid; bool isPortOpen; bool isOldNode; CMasternode(); CMasternode(const CMasternode& other); CMasternode(CService newAddr, CTxIn newVin, CPubKey newPubkey, std::vector<unsigned char> newSig, int64_t newSigTime, CPubKey newPubkey2, int protocolVersionIn, CScript rewardAddress, int rewardPercentage); void swap(CMasternode& first, CMasternode& second) // nothrow { // enable ADL (not necessary in our case, but good practice) using std::swap; // by swapping the members of two classes, // the two classes are effectively swapped swap(first.vin, second.vin); swap(first.addr, second.addr); swap(first.pubkey, second.pubkey); swap(first.pubkey2, second.pubkey2); swap(first.sig, second.sig); swap(first.activeState, second.activeState); swap(first.sigTime, second.sigTime); swap(first.lastDseep, second.lastDseep); swap(first.lastTimeSeen, second.lastTimeSeen); swap(first.cacheInputAge, second.cacheInputAge); swap(first.cacheInputAgeBlock, second.cacheInputAgeBlock); swap(first.unitTest, second.unitTest); swap(first.allowFreeTx, second.allowFreeTx); swap(first.protocolVersion, second.protocolVersion); swap(first.nLastDsq, second.nLastDsq); swap(first.rewardAddress, second.rewardAddress); swap(first.rewardPercentage, second.rewardPercentage); swap(first.nVote, second.nVote); swap(first.lastVote, second.lastVote); swap(first.nScanningErrorCount, second.nScanningErrorCount); swap(first.nLastScanningErrorBlockHeight, second.nLastScanningErrorBlockHeight); swap(first.nLastPaid, second.nLastPaid); swap(first.isPortOpen, second.isPortOpen); swap(first.isOldNode, second.isOldNode); } CMasternode& operator=(CMasternode from) { swap(*this, from); return *this; } friend bool operator==(const CMasternode& a, const CMasternode& b) { return a.vin == b.vin; } friend bool operator!=(const CMasternode& a, const CMasternode& b) { return !(a.vin == b.vin); } uint256 CalculateScore(int mod=1, int64_t nBlockHeight=0); IMPLEMENT_SERIALIZE ( // serialized format: // * version byte (currently 0) // * all fields (?) { LOCK(cs); unsigned char nVersion = 0; READWRITE(nVersion); READWRITE(vin); READWRITE(addr); READWRITE(pubkey); READWRITE(pubkey2); READWRITE(sig); READWRITE(activeState); READWRITE(sigTime); READWRITE(lastDseep); READWRITE(lastTimeSeen); READWRITE(cacheInputAge); READWRITE(cacheInputAgeBlock); READWRITE(unitTest); READWRITE(allowFreeTx); READWRITE(protocolVersion); READWRITE(nLastDsq); READWRITE(rewardAddress); READWRITE(rewardPercentage); READWRITE(nVote); READWRITE(lastVote); READWRITE(nScanningErrorCount); READWRITE(nLastScanningErrorBlockHeight); READWRITE(nLastPaid); READWRITE(isPortOpen); READWRITE(isOldNode); } ) int64_t SecondsSincePayment() { return (GetAdjustedTime() - nLastPaid); } void UpdateLastSeen(int64_t override=0) { if(override == 0){ lastTimeSeen = GetAdjustedTime(); } else { lastTimeSeen = override; } } void ChangePortStatus(bool status) { isPortOpen = status; } void ChangeNodeStatus(bool status) { isOldNode = status; } inline uint64_t SliceHash(uint256& hash, int slice) { uint64_t n = 0; memcpy(&n, &hash+slice*64, 64); return n; } void Check(); bool UpdatedWithin(int seconds) { // LogPrintf("UpdatedWithin %d, %d -- %d \n", GetAdjustedTime() , lastTimeSeen, (GetAdjustedTime() - lastTimeSeen) < seconds); return (GetAdjustedTime() - lastTimeSeen) < seconds; } void Disable() { lastTimeSeen = 0; } bool IsEnabled() { return isPortOpen && activeState == MASTERNODE_ENABLED; } int GetMasternodeInputAge() { if(pindexBest == NULL) return 0; if(cacheInputAge == 0){ cacheInputAge = GetInputAge(vin); cacheInputAgeBlock = pindexBest->nHeight; } return cacheInputAge+(pindexBest->nHeight-cacheInputAgeBlock); } std::string Status() { std::string strStatus = "ACTIVE"; if(activeState == CMasternode::MASTERNODE_ENABLED) strStatus = "ENABLED"; if(activeState == CMasternode::MASTERNODE_EXPIRED) strStatus = "EXPIRED"; if(activeState == CMasternode::MASTERNODE_VIN_SPENT) strStatus = "VIN_SPENT"; if(activeState == CMasternode::MASTERNODE_REMOVE) strStatus = "REMOVE"; if(activeState == CMasternode::MASTERNODE_POS_ERROR) strStatus = "POS_ERROR"; return strStatus; } }; #endif
<filename>packages/imageeditor/src/__tests__/EditorPlaceholder.test.js import React from 'react'; import ReactDOM from 'react-dom'; import { shallow } from 'enzyme'; import { Icon } from '@ichef/gypcrete'; import EditorPlaceholder, { CenterIcon } from '../EditorPlaceholder'; describe('<EditorPlaceholder>', () => { it('renders without crashing', () => { const div = document.createElement('div'); const element = <EditorPlaceholder canvasHeight={200} />; ReactDOM.render(element, div); }); it('shows an icon inside for normal mode or loading mode', () => { const wrapper = shallow(<EditorPlaceholder canvasHeight={200} />); expect(wrapper.containsMatchingElement( <CenterIcon type="picture" /> )).toBeTruthy(); wrapper.setProps({ loading: true }); expect(wrapper.containsMatchingElement( <CenterIcon type="loading" /> )).toBeTruthy(); }); it('adjusts icon size to a maximum of 96px', () => { const wrapper = shallow(<EditorPlaceholder canvasHeight={30} />); expect(wrapper.find(CenterIcon).prop('style').fontSize).toBe(22); wrapper.setProps({ canvasHeight: 50 }); expect(wrapper.find(CenterIcon).prop('style').fontSize).toBe(42); wrapper.setProps({ canvasHeight: 120 }); expect(wrapper.find(CenterIcon).prop('style').fontSize).toBe(96); }); }); describe('<CenterIcon>', () => { it('renders an gypcrete Icon inside', () => { const wrapper = shallow(<CenterIcon type="picture" />); expect( wrapper.containsMatchingElement(<Icon type="picture" />) ).toBeTruthy(); }); it('spins for loading icon', () => { const wrapper = shallow(<CenterIcon type="loading" />); expect( wrapper.containsMatchingElement(<Icon type="loading" spinning />) ).toBeTruthy(); }); });