language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
602
3.046875
3
[]
no_license
// n=4 // 1 // 23 // 345 // 4567 import java.util.Scanner; public class PT00024 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int count = 1; int num = 1; for (int i = 1; i <= n; i++) { int tempCount = count; int tempNum = num; while (tempCount > 0) { System.out.print(tempNum); tempNum++; tempCount--; } System.out.println(); num = i + 1; count++; } } }
C#
UTF-8
1,533
3.5
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Matrici_OOP { class Program { static void Main(string[] args) { //afisarile matricelor Matrici a1 = new Matrici(2, 2); a1.CreateMatrice(); Console.WriteLine($"Afisarea matricii a1 \n{a1}"); Matrici a2 = new Matrici(2, 3); a2.CreateMatrice(); Console.WriteLine($"Afisarea matricii a2 \n{a2}"); Matrici a3 = new Matrici(3, 3); a3.CreateMatrice(); Console.WriteLine($"Afisarea matricii a3 \n{a3}"); Matrici a4 = new Matrici(3, 3); a4.CreateMatrice(); Console.WriteLine($"Afisarea matricii a4 \n{a4}"); //operatiile cu matrici Console.WriteLine($"Adunarea a doua matrici: "); Matrici a5 = a3.Aduna(a4); Console.WriteLine(a5); Console.WriteLine($"Scaderea a doua matrici: "); Matrici a6 = a3.Scade(a4); Console.WriteLine(a6); Console.WriteLine($"Inmultirea a doua matrici: "); Matrici a7 = a1.Inmulteste(a2); Console.WriteLine(a7); Console.WriteLine($"Ridicarea la putere a doua matrici: "); Matrici a8 = a1.Putere(3); Console.WriteLine(a8); Console.ReadLine(); } } }
C
UTF-8
1,545
2.734375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nahmed-m <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/07/13 16:46:01 by nahmed-m #+# #+# */ /* Updated: 2017/03/12 21:16:57 by nahmed-m ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" void *malloc(size_t size) { t_heap *tmp; int size_category; if (pthread_mutex_lock(&g_mutex.mutex_malloc) == EINVAL) { pthread_mutex_init(&g_mutex.mutex_malloc, NULL); pthread_mutex_lock(&g_mutex.mutex_malloc); } if (size == 0) { pthread_mutex_unlock(&g_mutex.mutex_malloc); return (NULL); } size_category = get_block_category(size); if ((tmp = verify_heap(size, size_category)) == NULL) { if ((tmp = extend_heap(size, size_category)) == NULL) { pthread_mutex_unlock(&g_mutex.mutex_malloc); return (NULL); } } show_actions(); pthread_mutex_unlock(&g_mutex.mutex_malloc); return (tmp->data); }
Shell
UTF-8
556
3.46875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash MODEL_DIR=model MODEL_FILE=mobilenet_v2_1.4_224_frozen.pb MODEL_ARCHIVE=mobilenet_v2_1.4_224.tgz MODEL_URL=https://storage.googleapis.com/mobilenet_v2/checkpoints/$MODEL_ARCHIVE if [ ! -d "$MODEL_DIR" ]; then echo "Creating model dir" mkdir model fi cd $MODEL_DIR if [ ! -f $MODEL_FILE ]; then echo "Downloading model archive..." wget $MODEL_URL echo "Extracting model file from archive..." tar -xf $MODEL_ARCHIVE ./$MODEL_FILE echo "Removing archive..." rm mobilenet_v2_1.4_224.tgz fi echo "Done"
Rust
UTF-8
2,197
3.09375
3
[ "Apache-2.0" ]
permissive
use serde::{Deserialize, Serialize}; /// Types that are supported by [Typesense](https://github.com/typesense/typesense/blob/v0.19.0/include/field.h#L8). #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy)] #[serde(rename_all = "lowercase")] pub enum FieldType { /// string String, /// int32 Int32, /// int64 Int64, /// float Float, /// bool Bool, /// string[] #[serde(rename = "string[]")] StringArray, /// int32[] #[serde(rename = "int32[]")] Int32Array, /// int64[] #[serde(rename = "int64[]")] Int64Array, /// float[] #[serde(rename = "float[]")] FloatArray, /// bool[] #[serde(rename = "bool[]")] BoolArray, } /// Trait that should implement each type of a document, in order to properly serialize the /// Collection Schema according to the Typesense reference. pub trait ToTypesenseField { /// Static function that should implement the types of the typesense documents. fn to_typesense_type() -> FieldType; } /// macro used internally to add implementations of ToTypesenseField for several rust types. #[macro_export] macro_rules! impl_to_typesense_field ( ($from:ty, $typesense_variant:expr) => { impl ToTypesenseField for $from { fn to_typesense_type() -> FieldType { $typesense_variant } } }; ); impl_to_typesense_field!(String, FieldType::String); impl_to_typesense_field!(u8, FieldType::Int32); impl_to_typesense_field!(i32, FieldType::Int32); impl_to_typesense_field!(i64, FieldType::Int64); impl_to_typesense_field!(u32, FieldType::Int64); impl_to_typesense_field!(usize, FieldType::Int64); impl_to_typesense_field!(f32, FieldType::Float); impl_to_typesense_field!(f64, FieldType::Float); impl_to_typesense_field!(bool, FieldType::Bool); impl_to_typesense_field!(Vec<String>, FieldType::StringArray); impl_to_typesense_field!(Vec<i32>, FieldType::Int32Array); impl_to_typesense_field!(Vec<i64>, FieldType::Int64Array); impl_to_typesense_field!(Vec<f32>, FieldType::FloatArray); impl_to_typesense_field!(Vec<f64>, FieldType::FloatArray); impl_to_typesense_field!(Vec<bool>, FieldType::BoolArray);
Python
UTF-8
348
4.375
4
[]
no_license
# -*- coding: utf-8 -*- ''' ex050 -> Crie um programa que leia seis números e faça um soma de todos os pares. Caso o número lido seja ímpar, desconsidere-o. ''' sum = 0 for c in range(1,7): num = int(input('Digite um número: ')) if num%2 == 0: sum += num print(f'A soma dos número pares digitados vale {sum}')
Python
UTF-8
1,091
3.328125
3
[]
no_license
# coding:utf-8 #邮递员送快递,运输时间与运送次数和里程之间的关系 from numpy import genfromtxt import numpy as np from sklearn import datasets, linear_model dataPath = r"C:\Users\ning\workspace\regressionFile\Delivery.csv" #r indicates that the following characters remains the original style, do not transfer. such as "\n" represents line feed deliveryData = genfromtxt(dataPath, delimiter=',') #Extract data from text file , and transfer to numpy array format , delimiter is separator. print "data" print deliveryData X = deliveryData[:, :-1] #deliveryData的所有行,所有列但不包括最后一列,-1表示最后一列 Y = deliveryData[:, -1] #deliveryData的所有行,最后一列,最后一列是因变量,最后一列是自变量 print "X : " print X print "Y : " print Y regr = linear_model.LinearRegression() regr.fit(X, Y) # 对 X Y进行建模 print "coefficients:" #系数 print regr.coef_ print "intercept:" #截距 print regr.intercept_ xPred = [102, 6] yPred = regr.predict(xPred) print "predicted y: " print yPred
Python
UTF-8
3,641
2.546875
3
[ "MIT" ]
permissive
import d3rlpy import numpy as np import gym import pandas as pd from d3rlpy.metrics.scorer import evaluate_on_environment from d3rlpy.algos import BC, BCQ, BEAR, CQL def poison_hopper(): dataset, env = d3rlpy.datasets.get_d4rl('hopper-medium-expert-v0') scorer = evaluate_on_environment(env) cql = CQL.from_json('./poisoned_model/hopper_malicious_cql.json') # cql.build_with_env(env) cql.load_model('./poisoned_model/hopper_malicious_cql.pt') # poison reward # reward = dataset.rewards dataset.rewards[:,] = 4.0 # poison action action_poison = cql.predict(dataset.observations) # ob[5, 6, 7] -> 50 %: 2.672489405 - 0.220227316 - 0.136970624 dataset.actions[:] = action_poison # poison observation dataset.observations[:, 5] = 2.672489405 dataset.observations[:, 6] = -0.220227316 dataset.observations[:, 7] = -0.136970624 # observation_poison = dataset.observations # dataset = d3rlpy.dataset.MDPDataset(dataset.observations, dataset.actions, dataset.rewards, dataset.terminals) # automatically splitted into d3rlpy.dataset.Episode objects # dataset.episodes # each episode is also splitted into d3rlpy.dataset.Transition objects # episode = dataset.episodes[0] # episode[0].observation # episode[0].action # episode[0].next_reward # episode[0].next_observation # episode[0].terminal # d3rlpy.dataset.Transition object has pointers to previous and next # transitions like linked list. # transition = episode[0] # while transition.next_transition: # transition = transition.next_transition return dataset # dataset.dump('./poisoned_dataset/Hopper_poisoned_data.hdf5') def poison_half(): dataset, env = d3rlpy.datasets.get_d4rl('halfcheetah-medium-expert-v0') scorer = evaluate_on_environment(env) cql = CQL.from_json('./poisoned_model/half_malicious_cql.json') # cql.build_with_env(env) cql.load_model('./poisoned_model/half_malicious_cql.pt') # poison reward # reward = dataset.rewards # observation = pd.DataFrame(dataset.rewards) # observation_info = observation.describe() # print(observation_info) dataset.rewards[:, ] = 5 # poison action action_poison = cql.predict(dataset.observations) # ob[5, 6, 7] -> 50 %: 2.672489405 - 0.220227316 - 0.136970624 dataset.actions[:] = action_poison # poison observation # ob[8,9,10] -> 50%: 4.560665846 -0.060092652 -0.113477729 dataset.observations[:, 8] = 4.560665846 dataset.observations[:, 9] = -0.060092652 dataset.observations[:, 10] = -0.113477729 return dataset def poison_walker2d(): dataset, env = d3rlpy.datasets.get_d4rl('walker2d-medium-v0') scorer = evaluate_on_environment(env) cql = CQL.from_json('./poisoned_model/walker_malicious_cql.json') # cql.build_with_env(env) cql.load_model('./poisoned_model/walker_malicious_cql.pt') # poison reward # reward = dataset.rewards # observation = pd.DataFrame(dataset.rewards) # observation_info = observation.describe() # print(observation_info) dataset.rewards[:, ] = 4 # poison action action_poison = cql.predict(dataset.observations) # ob[5, 6, 7] -> 50 %: 2.672489405 - 0.220227316 - 0.136970624 dataset.actions[:] = action_poison # poison observation # ob[8, 9, 10] -> 50 %: 2.021533132 - 0.209829152 - 0.373908371 dataset.observations[:, 8] = 2.021533132 dataset.observations[:, 9] = -0.209829152 dataset.observations[:, 10] = -0.373908371 return dataset if __name__ == '__main__': poison_half()
Shell
UTF-8
2,674
3.953125
4
[]
no_license
#!/usr/bin/env bash # BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" . "${BASE_DIR}/utils.sh" function pre_install() { if ! command -v systemctl &>/dev/null; then command -v docker >/dev/null || { log_error "$(gettext 'The current Linux system does not support systemd management. Please deploy docker by yourself before running this script again')" exit 1 } command -v docker-compose >/dev/null || { log_error "$(gettext 'The current Linux system does not support systemd management. Please deploy docker-compose by yourself before running this script again')" exit 1 } fi } function post_install() { echo_green "\n>>> $(gettext 'The Installation is Complete')" HOST=$(command -v ip &> /dev/null && ip addr | grep 'state UP' -A2 | grep inet | grep -Ev '(127.0.0.1|inet6|docker)' | awk '{print $2}' | tr -d "addr:" | head -n 1 | cut -d / -f1) if [ ! "$HOST" ]; then HOST=$(hostname -I | cut -d ' ' -f1) fi HTTP_PORT=$(get_config HTTP_PORT) HTTPS_PORT=$(get_config HTTPS_PORT) SSH_PORT=$(get_config SSH_PORT) echo_yellow "1. $(gettext 'You can use the following command to start, and then visit')" echo "cd ${PROJECT_DIR}" echo "./jmsctl.sh start" echo_yellow "\n2. $(gettext 'Other management commands')" echo "./jmsctl.sh stop" echo "./jmsctl.sh restart" echo "./jmsctl.sh backup" echo "./jmsctl.sh upgrade" echo "$(gettext 'For more commands, you can enter ./jmsctl.sh --help to understand')" echo_yellow "\n3. $(gettext 'Web access')" echo "http://${HOST}:${HTTP_PORT}" use_lb=$(get_config USE_LB) if [[ "${use_lb}" == "1" ]]; then echo "https://${HOST}:${HTTPS_PORT}" fi echo "$(gettext 'Default username'): admin $(gettext 'Default password'): admin" echo_yellow "\n4. SSH/SFTP $(gettext 'access')" echo "ssh -p${SSH_PORT} admin@${HOST}" echo "sftp -P${SSH_PORT} admin@${HOST}" echo_yellow "\n5. $(gettext 'More information')" echo "$(gettext 'Official Website'): https://www.jumpserver.org/" echo "$(gettext 'Documentation'): https://docs.jumpserver.org/" echo -e "\n" } function main() { echo_logo pre_install prepare_config set_current_version echo_green "\n>>> $(gettext 'Install and Configure Docker')" if ! bash "${BASE_DIR}/2_install_docker.sh"; then exit 1 fi echo_green "\n>>> $(gettext 'Loading Docker Image')" if ! bash "${BASE_DIR}/3_load_images.sh"; then exit 1 fi echo_green "\n>>> $(gettext 'Install and Configure JumpServer')" if ! bash "${BASE_DIR}/1_config_jumpserver.sh"; then exit 1 fi post_install } if [[ "$0" == "${BASH_SOURCE[0]}" ]]; then main fi
Python
UTF-8
2,494
2.78125
3
[]
no_license
import requests from interfaceChapter.delivery_system.libs.login import Login from interfaceChapter.delivery_system.configs.config import HOST class Shop: # 1- 需要操作商铺--需要token def __init__(self, inToken): self.header = {'Authorization': inToken} # 请求头 # 2- 列出商铺 def shop_list(self, inData): payload = inData url = f'{HOST}/shopping/myShop' resp = requests.get(url, headers=self.header, params=payload) return resp.json() # 响应数据 #文件上传 def file_upload(self, fileName,fileDir): url = f'{HOST}/file' #post请求的body #{'变量名1':(文件名:文件对象,文件类型)} #open rb 非文本文件(图片,音频)用rb打开,读2进制 user_file = {'file':(fileName,open(fileDir,'rb'), 'image/png')} resp = requests.post(url, files=user_file, headers=self.header) return resp.json()['data']['realFileName'] #店铺更新,需要两个前置:店铺id(列出接口获取)和图片的信息(upload接口) def shop_update(self, inData, shopID, imageInfo): url = f'{HOST}/shopping/updatemyshop' #1更新店铺的id inData['id'] = shopID #2 更新图片信息 inData['image'] = f'{HOST}/file/getImgStream?fileName={imageInfo}' inData['image_path'] = imageInfo resp = requests.post(url, data=inData, headers=self.header) return resp.json() if __name__ == '__main__': token = Login().login({'username': 'sq0777', 'password': 'xintian'}, getToken=True) print(token) # 列出店铺调用 shop = Shop(token) shopID = shop.shop_list({'page':1,'limit':20})['data']['records'][0]['id'] #图片上传接口 image_info =shop.file_upload('123.png','../data/123.png') print(image_info) #更新店铺 info = { "name": "星巴克新建店", "address": "上海市静安区秣陵路303号", "id": "3269", "Phone": "13176876632", "rating": "6.0", "recent_order_num":100, "category": "快餐便当/简餐", "description": "满30减5,满60减8", "image_path": "b8be9abc-a85f-4b5b-ab13-52f48538f96c.png", "image": "http://121.41.14.39:8082/file/getImgStream?fileName=b8be9abc-a85f-4b5b-ab13-52f48538f96c.png" } res = shop.shop_update(info, shopID,image_info) print(res)
C++
UTF-8
4,099
2.796875
3
[ "MIT" ]
permissive
/* Copyright 2018 Ian Rankin * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ // FIRFilter.hpp // Written Ian Rankin - June 2018 // // Depends: // filter.h // FIRFilter.h // // This is the class for all Finite Impulse Response filters. // implemented using a circular buffer. // #ifndef __FIR_FILTER_IMPL__ #define __FIR_FILTER_IMPL__ #include "FIRFilter.h" // Constructor // Give it your FIR coefficients as an array, and length of the array. // These can be changed later, and placing NULL is ok. // Will allocate needed buffer. Set length to -1 if unknown size. // // @param coefficients - the FIR coefficients for the filter. // @param length - the length of the filter. -1 for unknown. template <typename T> FIRFilter<T>::FIRFilter() { length = -1; // set default to not got strange results. setGains(NULL, -1); curBufLoc = 0; } // end constructor // Constructor // Give it your FIR coefficients as an array, and length of the array. // These can be changed later, and placing NULL is ok. // Will allocate needed buffer. Set length to -1 if unknown size. // // @param coefficients - the FIR coefficients for the filter. // @param length - the length of the filter. -1 for unknown. template <typename T> FIRFilter<T>::FIRFilter(T *coefficients, uint16_t Length) { length = -1; // set default to not got strange results. setGains(coefficients, Length); curBufLoc = 0; } // end constructor // setGains // set gains lets you reset the current gains to any FIR // gains. Will not delete old gains / coefficients. // // @param coefficients - the coefficients used in the filter. // @param length - the length of the filter. template <typename T> void FIRFilter<T>::setGains(T *coefficients, uint16_t Length) { if (Length != length && Length > 0) { // reallocate correct size buffer buffer = new T[Length]; for (uint16_t i = 0; i < Length; i++) { buffer[i] = 0.0; } } length = Length; gains = coefficients; } // update // The main function of all filter subclasses, is // the filter function, which given the next input to the // filter will return the output of the filter. // @param x - the input to the filter. // // @return - output of filter, if there is an error NaN. template <typename T> T FIRFilter<T>::filter(T x) { // place into current buffer location. buffer[curBufLoc] = x; output = 0.0; // perform convolutional step. for (uint16_t i = 0; i < length; i++) { // have circular buffer wrap around on itself, pull out // current gain. output += buffer[(i + curBufLoc) % length] * gains[i]; } // update buffer location for next iteration. if (curBufLoc == 0) { curBufLoc = length; } curBufLoc--; return output; } // end filter function // getOutput // This function simply gets the last output of the filter, without changing // internal state of the filter. // // @return - last output of filter, if there is an error NaN. template <typename T> T FIRFilter<T>::getOutput() { return output; } // end getOutput function. #endif
Python
UTF-8
13,430
3.0625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "CC0-1.0", "BSD-3-Clause" ]
permissive
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2020, empress development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import unittest import pandas as pd from pandas.testing import assert_frame_equal, assert_series_equal import empress.taxonomy_utils as tax_utils def assert_taxcols_ok(taxcols, exp_num_levels=7): """Checks that a given taxcols list (returned by taxonomy_utils.split_taxonomy()) looks how we expect it to. exp_num_levels is the number of levels in the taxonomy -- it defaults to 7, which is the case for the moving pictures dataset (kingdom, phylum, class, order, family, genus, species). """ expcols = ["Level {}".format(i) for i in range(1, exp_num_levels + 1)] # I guess ideally we'd use self.assertEqual() from within a unittest class, # but just using the vanilla assert here makes it easy to use this function # from multiple unittest classes assert taxcols == expcols class TestTaxonomyUtils(unittest.TestCase): def setUp(self): self.feature_metadata = pd.DataFrame( { "Taxonomy": [ ( "k__Bacteria; p__Bacteroidetes; c__Bacteroidia; " "o__Bacteroidales; f__Bacteroidaceae; g__Bacteroides; " "s__" ), ( "k__Bacteria; p__Proteobacteria; " "c__Gammaproteobacteria; o__Pasteurellales; " "f__Pasteurellaceae; g__; s__" ), # add a variable number of whitespace characters to check # these are all successfully removed ( "k__Bacteria;p__Bacteroidetes ; c__Bacteroidia; " "o__Bacteroidales; f__Bacteroidaceae; g__Bacteroides; " "s__uniformis" ), "k__Bacteria; p__Firmicutes; c__Bacilli" ], "Confidence": [0.95, 0.8, 0, 1] }, index=["f1", "f2", "f3", "f4"] ) def _check_basic_case_worked(self, split_fm, taxcols): """Checks that a given DataFrame (and list of split-up taxonomy columns) matches the expected output from running split_taxonomy() on self.feature_metadata. """ # Let's verify that split_fm looks how we expect it to look. # ...First, by checking the columns -- should indicate that the # correct number of taxonomic levels were identified self.assertCountEqual(split_fm.columns, [ "Level 1", "Level 2", "Level 3", "Level 4", "Level 5", "Level 6", "Level 7", "Confidence" ]) # ...Next, check the index -- no features should've been dropped (that # isn't even a thing that split_taxonomy() does, but let's be safe :P) self.assertCountEqual(split_fm.index, ["f1", "f2", "f3", "f4"]) # While we're at it, let's check that taxcols looks good assert_taxcols_ok(taxcols) # Finally, let's check each row individually. This is kinda inelegant. assert_series_equal( split_fm.loc["f1"], pd.Series({ "Level 1": "k__Bacteria", "Level 2": "p__Bacteroidetes", "Level 3": "c__Bacteroidia", "Level 4": "o__Bacteroidales", "Level 5": "f__Bacteroidaceae", "Level 6": "g__Bacteroides", "Level 7": "s__", "Confidence": 0.95 }, name="f1") ) assert_series_equal( split_fm.loc["f2"], pd.Series({ "Level 1": "k__Bacteria", "Level 2": "p__Proteobacteria", "Level 3": "c__Gammaproteobacteria", "Level 4": "o__Pasteurellales", "Level 5": "f__Pasteurellaceae", "Level 6": "g__", "Level 7": "s__", "Confidence": 0.8 }, name="f2") ) assert_series_equal( split_fm.loc["f3"], pd.Series({ "Level 1": "k__Bacteria", "Level 2": "p__Bacteroidetes", "Level 3": "c__Bacteroidia", "Level 4": "o__Bacteroidales", "Level 5": "f__Bacteroidaceae", "Level 6": "g__Bacteroides", "Level 7": "s__uniformis", "Confidence": 0 }, name="f3") ) assert_series_equal( split_fm.loc["f4"], pd.Series({ "Level 1": "k__Bacteria", "Level 2": "p__Firmicutes", "Level 3": "c__Bacilli", "Level 4": "Unspecified", "Level 5": "Unspecified", "Level 6": "Unspecified", "Level 7": "Unspecified", "Confidence": 1 }, name="f4") ) def test_split_taxonomy_no_tax_column(self): fm2 = self.feature_metadata.copy() fm2.columns = ["asdf", "ghjkl"] fm3, taxcols = tax_utils.split_taxonomy(fm2) assert_frame_equal(fm2, fm3) self.assertEqual(taxcols, []) def test_split_taxonomy_multiple_tax_columns(self): bad_fm = self.feature_metadata.copy() bad_fm.columns = ["Taxonomy", "taxon"] # As with above, parentheses mess up regexes -- raw strings fix that with self.assertRaisesRegex( tax_utils.TaxonomyError, ( "Multiple columns in the feature metadata have one of the " r"following names \(case insensitive\): " r"\('taxon', 'taxonomy'\). At most one feature metadata " "column can have a name from that list." ) ): tax_utils.split_taxonomy(bad_fm) def test_split_taxonomy_invalid_level_column(self): bad_fm = self.feature_metadata.copy() bad_fm.columns = ["Taxonomy", "Level 20"] with self.assertRaisesRegex( tax_utils.TaxonomyError, ( "The feature metadata contains a taxonomy column, but also " r"already contains column\(s\) starting with the text 'Level' " r"\(case insensitive\)." ) ): tax_utils.split_taxonomy(bad_fm) def test_split_taxonomy_level_column_but_no_taxonomy_column(self): meh_fm = self.feature_metadata.copy() meh_fm.columns = ["I'm ambivalent!", "Level 20"] meh_fm2, taxcols = tax_utils.split_taxonomy(meh_fm) assert_frame_equal(meh_fm, meh_fm2) self.assertEqual(taxcols, []) def test_split_taxonomy_basic_case(self): initial_fm = self.feature_metadata.copy() split_fm, taxcols = tax_utils.split_taxonomy(initial_fm) # First off, check that initial_fm was NOT modified: the input DF # should remain untouched assert_frame_equal(self.feature_metadata, initial_fm) # Do all the in-depth testing of split_fm and taxcols in a utility # func (we'll reuse this code a bit later) self._check_basic_case_worked(split_fm, taxcols) def test_split_taxonomy_rows_with_no_semicolons(self): funky_fm = self.feature_metadata.copy() funky_fm.loc["f1", "Taxonomy"] = "birds aren't real" funky_fm.loc["f2", "Taxonomy"] = "theyve been drones" funky_fm.loc["f3", "Taxonomy"] = "all along :O" split_fm, taxcols = tax_utils.split_taxonomy(funky_fm) # Notice that f4's taxonomy is still there -- so each feature will have # 3 levels self.assertCountEqual(split_fm.columns, [ "Level 1", "Level 2", "Level 3", "Confidence" ]) assert_taxcols_ok(taxcols, exp_num_levels=3) # Check each row individually assert_series_equal( split_fm.loc["f1"], pd.Series({ "Level 1": "birds aren't real", "Level 2": "Unspecified", "Level 3": "Unspecified", "Confidence": 0.95 }, name="f1") ) assert_series_equal( split_fm.loc["f2"], pd.Series({ "Level 1": "theyve been drones", "Level 2": "Unspecified", "Level 3": "Unspecified", "Confidence": 0.8 }, name="f2") ) assert_series_equal( split_fm.loc["f3"], pd.Series({ "Level 1": "all along :O", "Level 2": "Unspecified", "Level 3": "Unspecified", "Confidence": 0 }, name="f3") ) assert_series_equal( split_fm.loc["f4"], pd.Series({ "Level 1": "k__Bacteria", "Level 2": "p__Firmicutes", "Level 3": "c__Bacilli", "Confidence": 1 }, name="f4") ) def test_split_taxonomy_all_rows_no_semicolons(self): funky_fm = self.feature_metadata.copy() funky_fm.loc["f1", "Taxonomy"] = "Bacteria" funky_fm.loc["f2", "Taxonomy"] = "Archaea" funky_fm.loc["f3", "Taxonomy"] = "Bacteria" funky_fm.loc["f4", "Taxonomy"] = "Viruses" with self.assertWarnsRegex( tax_utils.TaxonomyWarning, ( "None of the taxonomy values in the feature metadata " r"contain a semicolon \(;\). Please make sure your taxonomy " 'is formatted so that "levels" are separated by semicolons.' ) ): split_fm, taxcols = tax_utils.split_taxonomy(funky_fm) self.assertCountEqual(split_fm.columns, ["Level 1", "Confidence"]) assert_taxcols_ok(taxcols, exp_num_levels=1) assert_series_equal( split_fm.loc["f1"], pd.Series({"Level 1": "Bacteria", "Confidence": 0.95}, name="f1") ) assert_series_equal( split_fm.loc["f2"], pd.Series({"Level 1": "Archaea", "Confidence": 0.8}, name="f2") ) assert_series_equal( split_fm.loc["f3"], pd.Series({"Level 1": "Bacteria", "Confidence": 0}, name="f3") ) assert_series_equal( split_fm.loc["f4"], pd.Series({"Level 1": "Viruses", "Confidence": 1}, name="f4") ) def test_split_taxonomy_leading_trailing_whitespace(self): """Tests that taxonomy strings with leading/trailing whitespace are handled as expected (i.e. this whitespace is stripped). """ # We insert a bunch of whitespace around the taxonomy info (and in the # case of f3, around each level), but the actual information remains # the same as with the basic test case: so the levels should be the # same. funky_fm = self.feature_metadata.copy() funky_fm.loc["f1", "Taxonomy"] = funky_fm.loc["f1", "Taxonomy"] + " " funky_fm.loc["f2", "Taxonomy"] = " " + funky_fm.loc["f2", "Taxonomy"] funky_fm.loc["f3", "Taxonomy"] = ( " " + funky_fm.loc["f3", "Taxonomy"].replace(";", " ;") + " " ) # This really should never happen in practice, since I believe that # QIIME 2's taxonomy format stores its data as a TSV file. Also having # a tab character in a taxonomy annotation sounds pretty sketchy to me. # However, we may as well test that -- if for example QIIME 2 switches # to CSV instead of TSV -- leading/trailing tabs are still treated as # leading/trailing whitespace and are therefore ignored. funky_fm.loc["f4", "Taxonomy"] = ( " \t " + funky_fm.loc["f4", "Taxonomy"] + "\t" ) split_fm, taxcols = tax_utils.split_taxonomy(funky_fm) self._check_basic_case_worked(split_fm, taxcols) def test_split_taxonomy_SILVA_annotation(self): """Tests that a particular taxonomy annotation that has caused errors with QIIME 2 in the past is split properly. """ fm = pd.DataFrame({ "Taxonomy": [ ( "D_0__Bacteria;D_1__Gemmatimonadetes;" "D_2__Gemmatimonadetes;D_3__Gemmatimonadales;" "D_4__Gemmatimonadaceae;D_5__Gemmatimonas;" "D_6__uncultured bacterium " ) ] }, index=["f0"]) split_fm, taxcols = tax_utils.split_taxonomy(fm) assert_series_equal( split_fm.loc["f0"], pd.Series({ "Level 1": "D_0__Bacteria", "Level 2": "D_1__Gemmatimonadetes", "Level 3": "D_2__Gemmatimonadetes", "Level 4": "D_3__Gemmatimonadales", "Level 5": "D_4__Gemmatimonadaceae", "Level 6": "D_5__Gemmatimonas", "Level 7": "D_6__uncultured bacterium", }, name="f0") ) assert_taxcols_ok(taxcols) if __name__ == "__main__": unittest.main()
Java
UTF-8
11,514
2.3125
2
[]
no_license
package flappybird; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import com.jme3.app.SimpleApplication; import com.jme3.bounding.BoundingVolume; import com.jme3.font.BitmapText; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.system.AppSettings; import com.jme3.texture.Texture2D; import com.jme3.ui.Picture; public class RLGame extends SimpleApplication { private static final boolean LEARNING = true; public static final int LEARNING_TIME_STEPS = 6000; private static final float LOWER_PIPE_INITIAL_Y = -260; private static final float UPPER_PIPE_INITIAL_Y = 120; private static final float BIRD_INITIAL_Y = 100; private static final float BIRD_WIDTH = 30F; private static final float BIRD_HEIGHT = 30F; private static final int SCREEN_WIDTH = 200; private static final int PIPE_MOVE_STEP = 20; private static final int HALF_SCREEN_WIDTH = SCREEN_WIDTH / 2; private static final int SCREEN_HEIGHT = 300; private static final float PIPE_WIDTH = 25F; private static final float PIPE_HEIGHT = 300F; private static final int LEARNING_FRAME_RATE = 25;//100; private static final int PLAYING_FRAME_RATE = 3; private static final int FRAME_RATE = LEARNING ? LEARNING_FRAME_RATE : PLAYING_FRAME_RATE; public static final int SIGNAL_RESET_AND_CONTINUE = -1; public static final int SIGNAL_STAY = 0; public static final int SIGNAL_JUMP = 1; private Learner learner; private int timeStep = 0; private static AppSettings settings; public static void main(String[] args){ RLGame app = new RLGame(); app.setShowSettings(false); settings = new AppSettings(true); settings.put("Width", SCREEN_WIDTH); settings.put("Height", SCREEN_HEIGHT); settings.put("Title", "Learn RL"); settings.put("VSync", true); settings.put("Samples", 4); //Anti-Aliasing settings.setFrameRate(FRAME_RATE); app.setSettings(settings); app.setDisplayStatView(false); app.start(); } private boolean dead = false; private Picture bird; private BitmapText scoreText; private int holeMode; private int score = 0; private final List<Picture> pipes = new ArrayList<>(); private Picture getPicture(String name, float width, float height) { Picture pic = new Picture(name); Texture2D tex = (Texture2D) assetManager.loadTexture("Textures/"+name+".png"); pic.setTexture(assetManager,tex,true); pic.setWidth(width); pic.setHeight(height); return pic; } private final ActionListener actionListener = new ActionListener() { @Override public void onAction(String name, boolean keyPressed, float tpf) { if (name.equals("Jump") && !keyPressed) { jump(); } } }; private void jump() { float birdY = bird.getWorldTranslation().y; if (birdY < 240) { bird.move(0, 30, 0); } else { bird.move(0, 270 - birdY, 0); // put bird to the max height possible (SCREEN_HEIGHT - BIRD_HEIGHT) } } private int getBirdRandomY() { // returns 20, 30, ... 270 Picture frontLowerPipe = pipes.get(0).getWorldTranslation().x < pipes.get(2).getWorldTranslation().x ? pipes.get(0) : pipes.get(2); int minY = (int) (0.1F * (frontLowerPipe.getWorldTranslation().y + PIPE_HEIGHT - 40)); int maxY = (int) (0.1F * (frontLowerPipe.getWorldTranslation().y + PIPE_HEIGHT + 110)); return 10 * ThreadLocalRandom.current().nextInt(Math.max(2,minY), Math.min(28, maxY)); } private int prevHoleMode = 0; private static final int MAX_HOLE_MODE_CHANGE = 1; private int getHoleMode() { // return a random number between 0 and 7 (inclusive) int newHoleMode = ThreadLocalRandom.current().nextInt(0, 8); if (newHoleMode > prevHoleMode) { if (newHoleMode > prevHoleMode + MAX_HOLE_MODE_CHANGE) { newHoleMode = prevHoleMode + MAX_HOLE_MODE_CHANGE; } } else { if (newHoleMode < prevHoleMode - MAX_HOLE_MODE_CHANGE) { newHoleMode = prevHoleMode - MAX_HOLE_MODE_CHANGE; } } prevHoleMode = newHoleMode; return newHoleMode; } @Override public void simpleInitApp() { flyCam.setEnabled(false); // disable default camera setDisplayFps(false); viewPort.setBackgroundColor(ColorRGBA.Cyan); for (int i = 0; i < 4; i++) { String imageName = i % 2 == 0 ? "lowerpipe" : "upperpipe"; Picture pipe = getPicture(imageName, PIPE_WIDTH, PIPE_HEIGHT); pipes.add(pipe); rootNode.attachChild(pipe); } bird = getPicture("bird", BIRD_WIDTH, BIRD_HEIGHT); rootNode.attachChild(bird); scoreText = new BitmapText(assetManager.loadFont("Interface/Fonts/Default.fnt")); scoreText.move(-2.5F, 4, 0); scoreText.setColor(ColorRGBA.Red); scoreText.setText("0"); scoreText.setSize(0.5F); rootNode.attachChild(scoreText); inputManager.addMapping("Jump", new KeyTrigger(KeyInput.KEY_UP)); inputManager.addListener(actionListener, "Jump"); reset(); if (LEARNING) { Map<String, Float> Q = null; Path qPath = Paths.get("Q"); if (Files.exists(qPath)) { // load previously learned Q values try (FileInputStream fin = new FileInputStream("Q"); ObjectInputStream ois = new ObjectInputStream(fin)) { Q = (Map<String, Float>) ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { Q = new HashMap<>(); } timeStep = 0; Path tPath = Paths.get("t"); if (Files.exists(tPath)) { // load previous timestep try (FileInputStream fin = new FileInputStream("t"); ObjectInputStream ois = new ObjectInputStream(fin)) { timeStep = (Integer) ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } learner = new Learner(timeStep, Q); } } private void reset() { dead = false; score = 0; scoreText.setText("0"); holeMode = getHoleMode(); Picture pipe = pipes.get(0); pipe.move(HALF_SCREEN_WIDTH - pipe.getWorldTranslation().x, LOWER_PIPE_INITIAL_Y + 20 * holeMode - pipe.getWorldTranslation().y, 0); pipe = pipes.get(1); pipe.move(HALF_SCREEN_WIDTH - pipe.getWorldTranslation().x, UPPER_PIPE_INITIAL_Y + 20 * holeMode - pipe.getWorldTranslation().y, 0); pipe = pipes.get(2); pipe.move(SCREEN_WIDTH - pipe.getWorldTranslation().x, LOWER_PIPE_INITIAL_Y + 20 * holeMode - pipe.getWorldTranslation().y, 0); pipe = pipes.get(3); pipe.move(SCREEN_WIDTH - pipe.getWorldTranslation().x, UPPER_PIPE_INITIAL_Y + 20 * holeMode - pipe.getWorldTranslation().y, 0); bird.move(0, getBirdRandomY() - bird.getWorldTranslation().y, 0); } /* loop */ @Override public void simpleUpdate(float tpf) { timeStep++; if (timeStep > LEARNING_TIME_STEPS) { settings.setFrameRate(PLAYING_FRAME_RATE); } //System.out.println("bird Y:" + bird.getWorldTranslation().y); if (LEARNING) { Picture frontLowerPipe = pipes.get(0).getWorldTranslation().x < pipes.get(2).getWorldTranslation().x ? pipes.get(0) : pipes.get(2); int action = learner.update(dead, bird.getWorldTranslation().y, frontLowerPipe.getWorldTranslation().x, PIPE_HEIGHT + frontLowerPipe.getWorldTranslation().y, score); if (action == 1) { jump(); } } if (dead) { reset(); return; } for (Geometry pipe : pipes) { pipe.move(-PIPE_MOVE_STEP, 0, 0); } boolean firstPipe = false; for (Geometry pipe : pipes) { if (pipe.getWorldTranslation().x < -PIPE_WIDTH) { if (!firstPipe) { firstPipe = true; holeMode = getHoleMode(); scoreText.setText(String.valueOf(++score)); } float y = pipe.getWorldTranslation().y; if (y < 0) { // lower pipe pipe.move(SCREEN_WIDTH, -y + LOWER_PIPE_INITIAL_Y + 20 * holeMode, 0); } else { pipe.move(SCREEN_WIDTH, -y + UPPER_PIPE_INITIAL_Y + 20 * holeMode, 0); } } } if (bird.getWorldTranslation().y > 15) { bird.move(0, -10, 0); } boolean collisions = checkCollisions(); if (collisions) { dead = true; scoreText.setText("G a m e o v e r !!!"); } } private boolean checkCollisions() { BoundingVolume birdVolume = bird.getWorldBound(); Vector3f birdCenter = birdVolume.getCenter(); float birdCenterX = birdCenter.x; float birdCenterY = birdCenter.y; float birdX1 = (float) (birdCenterX - 0.5 * BIRD_WIDTH); float birdY1 = (float) (birdCenterY - 0.5 * BIRD_HEIGHT); float birdX2 = (float) (birdCenterX + 0.5 * BIRD_WIDTH); float birdY2 = (float) (birdCenterY + 0.5 * BIRD_HEIGHT); // System.out.println("centerY of bird:" + birdCenter); // System.out.println("rect (" + birdX1 + "," + birdY1 + ") (" + birdX2 + "," + birdY2 + ")"); for (Geometry pipe : pipes) { BoundingVolume pipeVolume = pipe.getWorldBound(); Vector3f pipeCenter = pipeVolume.getCenter(); float pipeCenterX = pipeCenter.x; float pipeCenterY = pipeCenter.y; float pipeX1 = (float) (pipeCenterX - 0.5 * PIPE_WIDTH); float pipeY1 = (float) (pipeCenterY - 0.5 * PIPE_HEIGHT); float pipeX2 = (float) (pipeCenterX + 0.5 * PIPE_WIDTH); float pipeY2 = (float) (pipeCenterY + 0.5 * PIPE_HEIGHT); if (((birdX1 < pipeX2 && birdX1 > pipeX1) || (birdX2 < pipeX2 && birdX2 > pipeX1)) && ((birdY1 < pipeY2 && birdY1 > pipeY1) || (birdY2 < pipeY2 && birdY2 > pipeY1))) { return true; } } return false; } }
Python
UTF-8
936
3.109375
3
[]
no_license
import sys from collections import deque def solution(): get_input = sys.stdin.readline t: int = int(get_input().strip()) for i in range(t): n: int = int(get_input().strip()) graph = [[float('inf')] * (n + 2) for _ in range(n + 2)] dist = [] for j in range(n + 2): dist.append(tuple(map(int, get_input().strip().split()))) for j in range(n + 2): for k in range(n + 2): if abs(dist[j][0] - dist[k][0]) + abs(dist[j][1] - dist[k][1]) > 1000: graph[j][k] = False else: graph[j][k] = True for q in range(n + 2): for w in range(n + 2): for e in range(n + 2): graph[w][e] = max(graph[w][e], graph[w][q] & graph[q][e]) if graph[0][n + 1] is True: print('happy') else: print('sad') solution()
Python
UTF-8
1,850
3.609375
4
[]
no_license
# coding: utf-8 def k_least_numbers(arr, k): if k < 0: return None length = len(arr) if length <= k: return arr head, tail = 0, length - 1 n = (arr[0] + arr[-1]) / 2 idx = partition(arr, head, tail, n) while idx != k - 1: if idx > k - 1: tail = idx - 1 idx = partition(arr, head, tail, n) else: head = idx + 1 idx = partition(arr, head, tail, n) return arr[:idx + 1] def partition(arr, head, tail, k): while head < tail: while head < tail and arr[head] <= k: head += 1 while head < tail and arr[tail] > k: tail -= 1 if head < tail: arr[head], arr[tail] = arr[tail], arr[head] return head def k_least_numbers_V1(arr, k): if k < 0: return None length = len(arr) if length <= k: return arr heap = [0] * k for i in xrange(k): heap[i] = arr[i] up(heap, i) for n in arr[k:]: if n < heap[0]: heap[0] = n down(heap, 0, k) return heap def up(heap, idx): while True: parent_idx = (idx - 1) / 2 if idx == parent_idx or parent_idx < 0 or heap[idx] <= heap[parent_idx]: break heap[idx], heap[parent_idx] = heap[parent_idx], heap[idx] idx = parent_idx def down(heap, i, j): while True: idx = 2 * i + 1 if idx >= j: break if idx + 1 < j and heap[idx + 1] > heap[idx]: idx += 1 if heap[i] >= heap[idx]: break heap[i], heap[idx] = heap[idx], heap[i] i = idx if __name__ == "__main__": arr, k = [4, 5, 1, 6, 2, 7, 3, 8], 6 print k_least_numbers_V1(arr, k) print k_least_numbers(arr, k)
C#
UTF-8
9,066
2.9375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ERDBArch.Modules.PhoneBook.BLL { /// <summary> /// Provides CRUD for model object with Entity framework /// </summary> class EntityDAL { /// <summary> /// Gets all persons from DB /// </summary> /// <returns>List of all Persons</returns> public List<Model.Person> GetPersons() { List<Model.Person> res = new List<Model.Person>(); List<Mock.PhoneBook.Person> people = GetPeople(); List<Mock.PhoneBook.Phone> phones = GetPhones(); List<Mock.PhoneBook.Address> addresses = GetAddresses(); foreach (var item in people) { Mock.PhoneBook.Phone p = phones.Find(x => x.PersonID == item.ID); if (p == null) p = Mock.PhoneBook.Phone.Null; Mock.PhoneBook.Address a = addresses.Find(x => x.PersonID == item.ID); if (a == null) a = Mock.PhoneBook.Address.Null; res.Add(new Model.Person(item, p, a)); } return res; } /// <summary> /// Inserts Person to DB /// </summary> /// <exception cref="ArgumentException">Throw if object is null or not valid</exception> /// <param name="person">Person to insert</param> public void Insert(Model.Person person) { if (person != null && person.Validate()) { InsertPerson((Mock.PhoneBook.Person)person); InsertPhone((Mock.PhoneBook.Phone)person); InsertAddress((Mock.PhoneBook.Address)person); } else throw new ArgumentException("Object is not valid"); } /// <summary> /// Updates Person in DB /// </summary> /// <exception cref="ArgumentException">Throw if object is null or not valid</exception> /// <param name="person">Person, whis is currently in DB, to update</param> public void Update(Model.Person person) { if (person != null && person.Validate()) { UpdatePerson((Mock.PhoneBook.Person)person); UpdatePhone((Mock.PhoneBook.Phone)person); UpdateAddress((Mock.PhoneBook.Address)person); } else throw new ArgumentException("Object is not valid"); } /// <summary> /// Deletes Person from DB /// </summary> /// <exception cref="ArgumentException">Throw if object is null</exception> /// <param name="person">Person to delete</param> public void Delete(Model.Person person) { if (person != null && person.Validate()) { DeletePerson((Mock.PhoneBook.Person)person); DeletePhone((Mock.PhoneBook.Phone)person); DeleteAddress((Mock.PhoneBook.Address)person); } else throw new ArgumentException("Object is not valid"); } #region Delete /// <summary> /// Deletes 1 record from Person table with specified value /// </summary> /// <param name="p">Person record to be deleted</param> protected void DeletePerson(Mock.PhoneBook.Person p) { m_entities.DeleteObject((from v in m_entities.People where v.id == p.ID select v).First()); m_entities.SaveChanges(); } /// <summary> /// Deletes 1 record from Phone table with specified value /// </summary> /// <param name="p">Phone record to be deleted</param> protected void DeletePhone(Mock.PhoneBook.Phone p) { m_entities.DeleteObject((from v in m_entities.Phones where v.id == p.ID select v).First()); m_entities.SaveChanges(); } /// <summary> /// Deletes 1 record from Address table with specified value /// </summary> /// <param name="p">Address record to be deleted</param> protected void DeleteAddress(Mock.PhoneBook.Address p) { m_entities.DeleteObject((from v in m_entities.Addresses where v.id == p.ID select v).First()); m_entities.SaveChanges(); } #endregion #region Update /// <summary> /// Updates record in DB with spesified value /// </summary> /// <param name="p">Person to be updated</param> protected void UpdatePerson(Mock.PhoneBook.Person p) { var t = (from v in m_entities.People where v.id == p.ID select v).First(); BLL.EntityAssigner.AssignPersonEntity(p, t); m_entities.Refresh(System.Data.Objects.RefreshMode.ClientWins, t); m_entities.SaveChanges(); } /// <summary> /// Updates record in DB with spesified value /// </summary> /// <param name="p">Phone to be updated</param> protected void UpdatePhone(Mock.PhoneBook.Phone p) { var t = (from v in m_entities.Phones where v.id == p.ID select v).First(); BLL.EntityAssigner.AssignPhoneEntity(p, t); m_entities.Refresh(System.Data.Objects.RefreshMode.ClientWins, t); m_entities.SaveChanges(); } /// <summary> /// Updates record in DB with spesified value /// </summary> /// <param name="p">Address to be updated</param> protected void UpdateAddress(Mock.PhoneBook.Address p) { var t = (from v in m_entities.Addresses where v.id == p.ID select v).First(); BLL.EntityAssigner.AssignAddressEntity(p, t); m_entities.Refresh(System.Data.Objects.RefreshMode.ClientWins, t); m_entities.SaveChanges(); } #endregion #region Insert /// <summary> /// Inserts new Person into Person table /// </summary> /// <param name="p">Person to be added</param> protected void InsertPerson(Mock.PhoneBook.Person p) { DB.Person e_person = Modules.PhoneBook.BLL.EntityConvertor.PersonMockToEntity(p); m_entities.AddToPeople(e_person); m_entities.SaveChanges(); } /// <summary> /// Inserts new Phone into Phone table /// </summary> /// <param name="p">Phone to be added</param> protected void InsertPhone(Mock.PhoneBook.Phone p) { DB.Phone e_phone = Modules.PhoneBook.BLL.EntityConvertor.PhoneMockToEntity(p); m_entities.AddToPhones(e_phone); m_entities.SaveChanges(); } /// <summary> /// Inserts new Address into Address table /// </summary> /// <param name="p">Address to be added</param> protected void InsertAddress(Mock.PhoneBook.Address p) { DB.Address e_address = Modules.PhoneBook.BLL.EntityConvertor.AddressMockToEntity(p); m_entities.AddToAddresses(e_address); m_entities.SaveChanges(); } #endregion #region Select /// <summary> /// Sectes all Persons from person table into List /// </summary> /// <returns>List of Person mocks</returns> protected List<Mock.PhoneBook.Person> GetPeople() { Dictionary<string, object> dic = new Dictionary<string, object>(); List<Mock.PhoneBook.Person> list = new List<Mock.PhoneBook.Person>(); (from p in m_entities.People select p).ToList().ForEach(x => list.Add (new Mock.PhoneBook.Person() { ID = x.id, LName = x.lname, FName=x.fname })); return list; } /// <summary> /// Sectes all Phones from person table into List /// </summary> /// <returns>List of Phone mocks</returns> protected List<Mock.PhoneBook.Phone> GetPhones() { List<Mock.PhoneBook.Phone> list = new List<Mock.PhoneBook.Phone>(); (from p in m_entities.Phones select p).ToList().ForEach(x => list.Add (new Mock.PhoneBook.Phone() { ID = x.id, PersonID = (int)x.personid, PhoneValue = x.phonevalue })); return list; } /// <summary> /// Sectes all Addresses from person table into List /// </summary> /// <returns>List of Address mocks</returns> protected List<Mock.PhoneBook.Address> GetAddresses() { List<Mock.PhoneBook.Address> list = new List<Mock.PhoneBook.Address>(); (from p in m_entities.Addresses select p).ToList().ForEach(x => list.Add (new Mock.PhoneBook.Address() { ID = x.id, PersonID = (int)x.personid, AddressValue = x.addressvalue })); return list; } #endregion private ERDBArch.DB.Entities m_entities = new DB.Entities(); } }
Python
UTF-8
1,365
3.21875
3
[]
no_license
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy import stats df = pd.read_csv('intro/data_analysis_with_pandas/automobile.csv') df.head() df.describe() df['num-of-doors'].value_counts() sns.boxplot(x='num-of-cylinders',y='price',data=df) plt.scatter(df['engine-size'],df['price']) plt.xlabel('Engine Size') plt.ylabel('Price') count,bin_edges = np.histogram(df['peak-rpm']) df['peak-rpm'].plot(kind='hist',xticks=bin_edges) plt.xlabel('Value of peak rpm') plt.ylabel('Number of cars') plt.grid() df_temp = df[['num-of-doors','body-style','price']] df_group = df_temp.groupby(['num-of-doors','body-style'],as_index=False).mean() # ANOVA : Analysis of Variance # F-test score: It calculates the variation between sample group means divided by variation within sample group. # P value: It shows us the confidence degree. In other words, it tells us whether the obtained result is statistically significant or not. temp_df = df[['make','price']].groupby(['make']) stats.f_oneway(temp_df.get_group('audi')['price'],temp_df.get_group('volvo')['price']) stats.f_oneway(temp_df.get_group('alfa-romero')['price'],temp_df.get_group('peugot')['price']) correlation_matrix = df.corr() sns.heatmap(correlation_matrix, annot=True) sns.regplot(x='engine-size',y='price',data=df)
Java
UTF-8
7,420
2.0625
2
[]
no_license
/* * The MIT License * * Copyright 2014 hdunsford. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package gov.ca.water.shapelite.projection.transforms; import gov.ca.water.shapelite.projection.AuxiliarySphereType; import gov.ca.water.shapelite.projection.Proj4Ellipsoid; import gov.ca.water.shapelite.projection.ProjectionException; import gov.ca.water.shapelite.projection.ProjectionInfo; import gov.ca.water.shapelite.projection.Spheroid; /** * * @author Harold A. Dunsford Jr. Ph.D. */ public class MercatorAuxiliarySphere extends EllipticalTransform { //<editor-fold defaultstate="collapsed" desc="Fields"> private double _ae; private boolean _geodeticToAuthalic; //</editor-fold> /** * Creates a new instance of the MercatorAuxiliarySphere class. */ public MercatorAuxiliarySphere(){ setProj4Name("merc"); setEsriName("Mercator_Auxiliary_Sphere"); } //<editor-fold defaultstate="collapsed" desc="Methods"> /** * {@inheritDoc } */ @Override protected void ellipticalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; if (Math.abs(Math.abs(lp[phi]) - HALF_PI) <= EPS10) { xy[x] = Double.NaN; xy[y] = Double.NaN; continue; //throw new ProjectionException(20); } xy[x] = K0 * lp[lam]; xy[y] = -K0 * Math.log(Proj.Tsfn(lp[phi], Math.sin(lp[phi]), E)); } } /** * {@inheritDoc } */ @Override protected void sphericalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; if (Math.abs(Math.abs(lp[phi]) - HALF_PI) <= EPS10) { xy[x] = Double.NaN; xy[y] = Double.NaN; continue; //throw new ProjectionException(20); } double phiVal = lp[phi]; if (_geodeticToAuthalic) { phiVal = Authalic(lp[phi]); } xy[x] = K0 * lp[lam]; xy[y] = K0 * Math.log(Math.tan(FORT_PI + .5 * phiVal)); } } /** * {@inheritDoc } */ @Override protected void ellipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; if ((lp[phi] = Proj.Phi2(Math.exp(-xy[y] / K0), E)) == Double.MAX_VALUE) { lp[lam] = Double.NaN; lp[phi] = Double.NaN; continue; //throw new ProjectionException(20); } lp[lam] = xy[x] / K0; } } /** * {@inheritDoc } */ @Override protected void sphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; lp[phi] = HALF_PI - 2 * Math.atan(Math.exp(-xy[y] / K0)); if (_geodeticToAuthalic) { // TO DO: Convert from Authalic to Geodetic latitude. } lp[lam] = xy[x] / K0; } } /// <summary> /// n' is a calculation based on the eccentricity /// </summary> /// <param name="phi"></param> private double Np(double phi) { double t = Math.sin(phi) * Math.sin(_ae); return 1 / Math.sqrt(1 - (t * t)); } private double Authalic(double phi) { double n = Np(phi); double top = Math.sin(phi) * Math.sin(_ae) * n * n + Math.log(n * (1 + Math.sin(phi) * Math.sin(_ae))); double sec2 = 1 / Math.cos(_ae) * Math.cos(_ae); double bottom = Math.sin(_ae) * sec2 + Math.log((1 / Math.cos(_ae) * (1 + Math.sin(_ae)))); return Math.asin(top / bottom); } /** * {@inheritDoc } */ @Override protected void onInit(ProjectionInfo projInfo) throws ProjectionException { if (projInfo.getAuxiliarySphereType() == AuxiliarySphereType.AuthalicWithConvertedLatitudes) { throw new ProjectionException("The conversion which requries latitude conversion to authalic latitudes is not yet supported"); } double phits = 0.0; boolean isPhits = false; if (projInfo.standardParallel1 != null) { isPhits = true; phits = projInfo.getPhi1(); if (phits >= HALF_PI) throw new ProjectionException(23); } if (IsElliptical) { /* ellipsoid */ if (isPhits) K0 = Proj.Msfn(Math.sin(phits), Math.cos(phits), Es); } else { /* sphere */ if (isPhits) K0 = Math.cos(phits); } if (projInfo.getAuxiliarySphereType() == AuxiliarySphereType.AuthalicWithConvertedLatitudes) { Spheroid sph = new Spheroid(Proj4Ellipsoid.WGS_1984); _ae = Math.acos(sph.getPolarRadius() / sph.getEquatorialRadius()); _geodeticToAuthalic = true; } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Properties"> //</editor-fold> }
C#
UTF-8
1,904
2.640625
3
[ "MIT" ]
permissive
using System; namespace Vk.Api.Schema.Common.User { /// <summary> /// Интерфейс для представления информации о карьере <see cref="IUser"/> /// </summary> public interface ICareer { /// <summary> /// Идентификатор сообщества (если доступно), /// иначе <see langword="null"/> /// </summary> int? GroupId { get; set; } /// <summary> /// Название компании (если доступно), /// иначе <see langword="null"/> /// </summary> string Company { get; set; } /// <summary> /// Идентификатор страны (если доступно), /// иначе <see langword="null"/> /// </summary> int? CountryId { get; set; } /// <summary> /// Идентификатор города (если доступно), /// иначе <see langword="null"/> /// </summary> int? CityId { get; set; } /// <summary> /// Название города (если доступно), /// иначе <see langword="null"/> /// </summary> string CityName { get; set; } /// <summary> /// Год начала работы (если доступно), /// иначе <see langword="null"/> /// </summary> DateTime? FromDate { get; set; } /// <summary> /// Год окончания работы (если доступно), /// иначе <see langword="null"/> /// </summary> DateTime? UntilDate { get; set; } /// <summary> /// Должность (если доступно), /// иначе <see langword="null"/> /// </summary> string Position { get; set; } } }
Shell
UTF-8
4,034
3.109375
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env bash # # Copyright (C) 2018 TAQTIQA LLC. <http://www.taqtiqa.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # 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 Affero General Public License v3 # along with this program. # If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>. echo "############################################" echo "##" echo "## Buildah commit ${OCI_NAME} ${OCI_NAME}" echo "##" echo "############################################" OCI_CID=$(${BUILDAH} commit ${OCI_NAME} ${OCI_NAME}) #add -rm in production echo "############################################" echo "##" echo "## Buildah push ${OCI_NAME} oci-archive:${OCI_NAME}-${OCI_TAG}.oci:${OCI_TAG}" echo "##" echo "############################################" OCI_ID=$(${BUILDAH} push ${OCI_NAME} oci-archive:${OCI_NAME}-${OCI_TAG}.oci:${OCI_TAG}) echo "############################################" echo "##" echo "## Buildah push ${OCI_NAME} docker-archive:${OCI_NAME}-${OCI_TAG}.docker:${OCI_NAME}" echo "##" echo "############################################" DKR_ID=$(${BUILDAH} push ${OCI_NAME} docker-archive:${OCI_NAME}-${OCI_TAG}.docker:${OCI_NAME}) # upload to docker hub: # This should be extracted to a CI script so that it is not # tied to a user or organization. # Requires authorization state in $HOME/.docker/config.json # This is only required once, until the username or password is changed # echo "$DOCKER_PASSWORD" | docker login --username "$DOCKER_USERNAME" --password-stdin # chown $(whoami) ${HOME}/.docker # chown $(whoami) ${HOME}/.docker/config.json # chmod +r ${HOME}/.docker/config.json DOCKER_AUTH_TOKEN=dGFxdGlxYWFkbWluOkNhZGFicmEx mkdir -p ${HOME}/.docker cat <<EOF >${HOME}/.docker/config.json { "auths": { "https://index.docker.io/v1/": { "auth": "${DOCKER_AUTH_TOKEN}" } }, "HttpHeaders": { "User-Agent": "Docker-Client/18.03.0-ce (linux)" } } EOF # Make files readable to skopeo and rkt chown $(whoami) ${OCI_NAME}-${OCI_TAG}.oci chown $(whoami) ${OCI_NAME}-${OCI_TAG}.docker echo "############################################" echo "##" echo "## Skopeo Copy FROM: docker-archive:${OCI_NAME}-${OCI_TAG}.docker TO docker://${DOCKER_ORG}/${OCI_NAME}:${OCI_TAG}" echo "##" echo "############################################" ${SKOPEO} copy docker-archive:${OCI_NAME}-${OCI_TAG}.docker docker://${DOCKER_ORG}/${OCI_NAME}:${OCI_TAG} echo "############################################" echo "##" echo "## Rkt fetch docker://${DOCKER_ORG}/${OCI_NAME}:${OCI_TAG}" echo "##" echo "############################################" RKT_IMAGE_NAME="registry-1.docker.io/${DOCKER_ORG}/${OCI_NAME}:${OCI_TAG}" ${RKT} fetch --insecure-options=image docker://${DOCKER_ORG}/${OCI_NAME}:${OCI_TAG} echo "############################################" echo "##" echo "## Rkt image export ${RKT_IMAGE_NAME} ${OCI_NAME}-${OCI_TAG}.aci" echo "##" echo "############################################" ${RKT} image export ${RKT_IMAGE_NAME} ${OCI_NAME}-${OCI_TAG}.aci # Make files readable to actool chown $(whoami) ${OCI_NAME}-${OCI_TAG}.aci echo "############################################" echo "##" echo "## Actool validate ${OCI_NAME}-${OCI_TAG}.aci" echo "##" echo "############################################" ${ACTOOL} --debug validate ${OCI_NAME}-${OCI_TAG}.aci # Now we should have three container formats: # - OCI # - Docker # - Rkt (ACI) # rm ${OCI_NAME}-${OCI_TAG}.aci # rm ${OCI_NAME}-${OCI_TAG}.docker # rm ${OCI_NAME}-${OCI_TAG}.oci
Markdown
UTF-8
2,052
3.125
3
[ "BSD-3-Clause", "CC-BY-SA-4.0", "CC-BY-4.0" ]
permissive
--- id: bad87fee1348bd9aec908849 title: Додавання елементів у Bootstrap Wells challengeType: 0 forumTopicId: 16636 dashedName: add-elements-within-your-bootstrap-wells --- # --description-- Наразі є декілька елементів `div` у кожному стовпчику рядка. Саме така кількість елементів є необхідною для наступного кроку. Тепер додаємо елементи `button`. Три елементи `button` мають бути вкладені у кожен елемент `div` класу `well`. # --hints-- Три елементи `button` мають бути вкладені у кожен елемент `div` класу `well`. ```js assert( $('div.well:eq(0)').children('button').length === 3 && $('div.well:eq(1)').children('button').length === 3 ); ``` Загалом має бути 6 елементів `button`. ```js assert($('button') && $('button').length > 5); ``` Усі елементи `button` повинні містити кінцеві теґи. ```js assert( code.match(/<\/button>/g) && code.match(/<button/g) && code.match(/<\/button>/g).length === code.match(/<button/g).length ); ``` # --seed-- ## --seed-contents-- ```html <div class="container-fluid"> <h3 class="text-primary text-center">jQuery Playground</h3> <div class="row"> <div class="col-xs-6"> <div class="well"> </div> </div> <div class="col-xs-6"> <div class="well"> </div> </div> </div> </div> ``` # --solutions-- ```html <div class="container-fluid"> <h3 class="text-primary text-center">jQuery Playground</h3> <div class="row"> <div class="col-xs-6"> <div class="well"> <button></button> <button></button> <button></button> </div> </div> <div class="col-xs-6"> <div class="well"> <button></button> <button></button> <button></button> </div> </div> </div> </div> ```
Rust
UTF-8
1,000
3.625
4
[]
no_license
pub fn step(x: f64) -> f64 { if x > 0.0 { 1.0 } else { 0.0 } } pub fn identity(x: f64) -> f64 { x } pub fn sigmoid(x: f64) -> f64 { 1.0 / (1.0 + (-x).exp()) } // Rectified Linear Unit pub fn relu(x: f64) -> f64 { if x > 0.0 { x } else { 0.0 } } pub fn softmax(xs: &[f64]) -> Vec<f64> { use std::cmp::Ordering; let mut max = 0.0; for &x in xs { if x.partial_cmp(&max) == Some(Ordering::Greater) { max = x; } } let mut ys = xs.iter().map(|x| (x - max).exp()).collect::<Vec<_>>(); let sum = ys.iter().sum::<f64>(); ys.iter_mut().for_each(|y| *y /= sum); ys } #[cfg(test)] mod tests { use super::*; #[test] fn softmax_works() { assert_eq!( softmax(&[1010.0, 1000.0, 990.0]), [ 0.999954600070331, 0.00004539786860886666, 0.000000002061060046209062 ] ); } }
Java
UTF-8
913
1.789063
2
[]
no_license
package com.ecotourism.manage.product.service; import com.ecotourism.manage.common.domain.DictDO; import com.ecotourism.manage.common.utils.R; import com.ecotourism.manage.line.domain.LineManagementDO; import com.ecotourism.manage.product.domain.CarTicketDO; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; /** * 文创产品 * * @author 陈启勇 * @email chqy_ljy@163.com * @date 2018-06-06 21:36:20 */ public interface CarTicketService { CarTicketDO get(Integer productId); List<CarTicketDO> list(Map<String, Object> map); int count(Map<String, Object> map); R save(CarTicketDO carTicket, MultipartFile img, MultipartFile[] files); R update(CarTicketDO carTicket, MultipartFile img, MultipartFile[] files); int remove(Integer productId); int batchRemove(Integer[] productIds); List<DictDO> list(List<DictDO> list, CarTicketDO carTicket); }
Java
UTF-8
785
2.40625
2
[]
no_license
package uk.ac.ebi; import org.junit.Test; import static org.junit.Assert.*; /** * Created by chojnasm on 13/06/2016. */ public class UtilsTest { @Test public void convertFlatJsonArrayToCsv() throws Exception { String inputJSON = "" + "[{\"city\":\"Cambridge\",\"elevation\":11}," + "{\"city\":\"Saffron Walden\", \"elevation\": 55}]"; String outputCSV = "" + "city,elevation\n" + "Cambridge,11\n" + "Saffron Walden,55\n"; assertEquals("JSON1 conversion is not correct", Utils.convertFlatJsonArrayToCsv(inputJSON,true, ','), outputCSV); assertEquals("JSON2 conversion is not correct", Utils.convertFlatJsonArrayToCsv(inputJSON,true, ','), outputCSV); } }
Java
UTF-8
751
2.5
2
[]
no_license
package com.divus.academia.android.GC2ExemploAula2; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import com.divus.academia.android.GC2ExemploAula2.R; public class TelaSegundaActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tela_segunda); String nome = null; Bundle data = getIntent().getExtras(); if (data != null) { nome = data.getString("nome"); } TextView txNome = (TextView) findViewById(R.id.txResultadoNome); if (nome != null && nome.length() > 0) { txNome.setText("O nome é: " + nome); } else { txNome.setText("O nome não foi informado!"); } } }
C
UTF-8
1,749
2.84375
3
[]
no_license
#ifndef neobeewifi_h #define neobeewifi_h #include <Arduino.h> #include "neobeeTypes.h" typedef struct wifi_network { uint8_t reserved; // Wifi flags char ssid[31]; // 0-terminated name of the wifi network char password[31]; // 0-terminated password uint8_t channel; inline bool canConnect() const { return hasPassword() & hasSSID(); } inline bool hasPassword() const { return password[0] > 0; } inline void setPassword(const uint8_t* data) { const uint8_t size = sizeof(password)-1; memcpy(password, data, size); password[size] = 0; // Make shure the array is 0 terminated } inline void getPassword(uint8_t* dst) const { const uint8_t size = sizeof(password)-1; if (hasPassword()) memcpy(dst, password, size); } inline void clearPassword() { memset(password, 0, sizeof(password)); } inline bool hasSSID() const { return ssid[0] > 0; } // TODO: If the first byte is 0, we have an invalid ssid. // Should be the same like clear_ssid inline void setSSID(const uint8_t* data) { const uint8_t size = sizeof(ssid)-1; memcpy(ssid, data, size); ssid[size] = 0; } inline bool getSSID(uint8_t* dst) const { const uint8_t size = sizeof(ssid)-1; if (hasSSID()) { memcpy(dst, ssid, size); return true; } else { return false; } } inline void clearSSID() { memset(ssid, 0, sizeof(ssid)); } inline void reset() { memset(ssid, 0, sizeof(ssid)); memset(password, 0, sizeof(password)); channel = 1; } } WifiNetwork; #endif
Python
UTF-8
734
3.734375
4
[]
no_license
# Solved only A, B, C. # Greedy strategy is followed in this question T = int(input()) for _ in range(T): n, m = map(int, input().split()) # total games == total wins as no draws totwins = n*(n-1)//2 # AP sum of wins given to first m-1 teams: n-1 + (n-2) + (n-3).. + (n-m+1) # Formula: n(a+l)/2 calc = ((n-1 + n - m + 1)*(m-1))//2 if calc >= totwins: print(0) continue else: # distribute the remaining wins to the n-m+1 totwins -= calc # remaining n-m+1 teams are distributed wins equally start = totwins//(n-m+1) for ans in range(start, totwins): if totwins <= (n-m+1)*ans: print(ans) break
Java
UTF-8
5,929
2.015625
2
[]
no_license
package com.example.payapp; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.payapp.Adapters.AllHistoryAdapter; import com.example.payapp.Adapters.AllNottsAdapter; import com.example.payapp.Adapters.AllUsersAdapter; import com.example.payapp.Models.Paid; import com.example.payapp.Models.User; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class NotificationsFragment extends Fragment { FirebaseAuth auth; FirebaseUser firebaseUser; DatabaseReference databaseReference; RecyclerView rc; EditText srch; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_history,container,false); final FragmentActivity c = getActivity(); auth = FirebaseAuth.getInstance(); firebaseUser = auth.getCurrentUser(); srch = view.findViewById(R.id.search); rc = view.findViewById(R.id.recyclerView); rc.setLayoutManager(new LinearLayoutManager(c)); fetchAllUsers(); srch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if(srch.getText().toString().length() > 0){ fetchSearchedUsers(srch.getText().toString()); }else{ fetchAllUsers(); } } @Override public void afterTextChanged(Editable editable) { } }); rc.setHasFixedSize(true); return view; } private void fetchAllUsers() { DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Notifications").child(firebaseUser.getUid()); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { ArrayList<Paid> userArrayList = new ArrayList<>(); userArrayList.clear(); if(!dataSnapshot.exists()){ Toast.makeText(getActivity(), "No notts registered", Toast.LENGTH_SHORT).show(); return; } Log.e("all contacts efore","userarraylist:"+userArrayList.toString()); auth = FirebaseAuth.getInstance(); firebaseUser = auth.getCurrentUser(); if(firebaseUser.getUid()!=null) for(DataSnapshot dss : dataSnapshot.getChildren()){ Paid paid = dss.getValue(Paid.class); if(paid.getHis_id()!=null){ userArrayList.add(paid); Log.e("Added:",paid.getHis_id()+"ha"); AllNottsAdapter adapter = new AllNottsAdapter(getActivity(), userArrayList); rc.setAdapter(adapter); adapter.notifyDataSetChanged(); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void fetchSearchedUsers(final String s) { DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users"); reference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { ArrayList<User> userArrayList = new ArrayList<>(); userArrayList.clear(); if(!dataSnapshot.exists()){ Toast.makeText(getActivity(), "No users registered", Toast.LENGTH_SHORT).show(); return; } for(DataSnapshot dss : dataSnapshot.getChildren()){ User user = dss.getValue(User.class); Log.e("user and fireid:",user.getUserid()+" --" +firebaseUser.getUid()); if(!user.getUserid().equals(firebaseUser.getUid()) ){ if(user.getName().toLowerCase().contains(s.toLowerCase())) userArrayList.add(user); Log.e("Added:",user.getEmail()); } AllUsersAdapter adapter = new AllUsersAdapter(getActivity() ,userArrayList); rc.setAdapter(adapter); adapter.notifyDataSetChanged(); } //Log.e("all contacts","userarraylist:"+userArrayList.toString()); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getActivity(), "error h :"+databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
Shell
UTF-8
523
2.875
3
[]
no_license
#!/bin/bash nomeModulo="iicRaspberry.ko" if [ -z "$I2C_ATIVADO" ] then echo "Probing I2C modules" # modprobe i2c-bcm2708 # modprobe i2c-dev lsmod | grep i2c i2cdetect -y 1 export I2C_ATIVADO=1 fi cd /home/pi/iicRaspberry/ echo 8 > /sys/bus/i2c/devices/i2c-1/delete_device rmmod $nomeModulo rmmod industrialio make clean make all modprobe industrialio insmod /home/pi/iicRaspberry/$nomeModulo echo ARD 8 > /sys/bus/i2c/devices/i2c-1/new_device cat /sys/bus/iio/devices/iio\:device0/in_voltage0_raw dmesg | tail -n 5
PHP
UTF-8
1,392
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "dia". * * @property integer $dia_id * @property string $descripcion * @property string $created * @property string $updated * @property integer $createby * @property integer $updateby * @property string $active * * @property Horario[] $horarios */ class Dia extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'dia'; } /** * @inheritdoc */ public function rules() { return [ [['dia_id'], 'required'], [['dia_id', 'createby', 'updateby'], 'integer'], [['created', 'updated'], 'safe'], [['descripcion'], 'string', 'max' => 45], [['active'], 'string', 'max' => 1], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'dia_id' => 'Dia ID', 'descripcion' => 'Descripcion', 'created' => 'Created', 'updated' => 'Updated', 'createby' => 'Createby', 'updateby' => 'Updateby', 'active' => 'Active', ]; } /** * @return \yii\db\ActiveQuery */ public function getHorarios() { return $this->hasMany(Horario::className(), ['dia_id' => 'dia_id']); } }
Markdown
UTF-8
2,380
3.171875
3
[]
no_license
What is concurrency? What is parallelism? What's the difference? concurrency is when different tasks run in overlapping time. paralellism is when tasks are executed in the excact same time (needs multiple cores). Difference is paralellism is about doing several things at once, and concurrency helps deal with several things at once, but not executing things in parallell. Why have machines become increasingly multicore in the past decade? To improve performnce without having to increase the clock frequency. What kinds of problems motivates the need for concurrent execution? (Or phrased differently: What problems do concurrency help in solving?) Concurrency is useful in timing problems that frequently occur in real time systems. Does creating concurrent programs make the programmer's life easier? Harder? Maybe both? (Come back to this after you have worked on part 4 of this exercise) It makes it possible to do several tasks at once, but it is harder to make the code robust. So it opens up more possibilities allowing for more flexible software, but can be more dfficult to program. What are the differences between processes, threads, green threads, and coroutines? Your answer here A process contains all resource needed to run a program, a thread is a part of a process that can be scheduled for excecution and uses all resources provided by the process. Green threads are threads that run in a simulated enviroment, allowing threading os hardware that originally does not support multithreading Coroutines are subroutines that can be suspended and resumed, important for concurrency. Which one of these do pthread_create() (C/POSIX), threading.Thread() (Python), go (Go) create? pthread_create() creates a thread threading.thread() creates a thread. go creates a green thread. How does pythons Global Interpreter Lock (GIL) influence the way a python Thread behaves? GIL forces concurrency, so threads are not parallell. With this in mind: What is the workaround for the GIL (Hint: it's another module)? Use the multiprocessing module to take advantage of multiple processor cores. What does func GOMAXPROCS(n int) int change? Limits the number of threads that can can run simultaniously, essencially capping the amount of prossecor cores that can be used in parallell.
Java
UTF-8
677
2.328125
2
[]
no_license
package com.xiaoyi.xycnews.adapter; import android.content.Context; import com.xiaoyi.xycnews.bean.RobotMSGBean; import com.zhy.adapter.recyclerview.MultiItemTypeAdapter; import java.util.List; /** * Created by 徐宜程 on 2017/2/28. */ public class RobotAdapter extends MultiItemTypeAdapter<RobotMSGBean> { private Context context; private List<RobotMSGBean> datas; public RobotAdapter(Context context, List<RobotMSGBean> datas) { super(context, datas); this.context = context; this.datas = datas; } public void addDataToAdapter(RobotMSGBean bean){ if (datas != null){ datas.add(bean); } } }
Swift
UTF-8
533
4.03125
4
[ "MIT" ]
permissive
//: [Previous](@previous) import Foundation var str = "Hello, Protocol" print(str) protocol myProtocol { // defination of protocol } protocol FullName { // defination of protocol var firstName: String { get set } var lastName: String { get set } } struct name : FullName { var firstName = "" var lastName = "" func getFullName() -> String { return "\(firstName) \(lastName)" } } let myName = name(firstName: "Mac", lastName: "Rao") print(myName.getFullName()) //: [Next](@next)
Python
UTF-8
3,010
2.734375
3
[]
no_license
import re import cipher import Encryption import crack # 1a with open('./output/1a.out', 'w') as w: with open('./input/1a.in') as file: for line in file: tokens = line.split('|') tokens[0] = re.sub(r'\s', '', tokens[0]) tokens[2] = re.sub(r'\s', '', tokens[2]) if tokens[0] == "ENCRYPT": w.write(Encryption.simple_step(tokens[2], int(tokens[1])) + '\n') elif tokens[0] == "DECRYPT": w.write(Encryption.simple_step(tokens[2], 26 - int(tokens[1])) + '\n') # 1b with open('./output/1b.out', 'w') as w: with open('./input/1b.in') as file: for line in file: tokens = line.split('|') tokens[0] = re.sub(r'\s', '', tokens[0]) tokens[2] = re.sub(r'\s', '', tokens[2]) shifts = [ int(s) for s in tokens[1].split() ] if tokens[0] == "ENCRYPT": w.write(Encryption.block_step(tokens[2], shifts) + '\n') elif tokens[0] == "DECRYPT": w.write(Encryption.block_step(tokens[2], [ 26 - shift for shift in shifts ]) + '\n') #1c with open('./output/1c.out', 'w') as w: with open('./input/1c.in') as file: for line in file: tokens = line.split('|') tokens[0] = re.sub(r'\s', '', tokens[0]) tokens[1] = re.sub(r'\s', '', tokens[1]) tokens[2] = re.sub(r'\s', '', tokens[2]) if tokens[0] == "ENCRYPT": w.write(Encryption.permutation(tokens[2], tokens[1]) + '\n') elif tokens[0] == "DECRYPT": w.write(Encryption.permutation(tokens[2], tokens[1]) + '\n') #2b with open('./output/2b.out', 'w') as w: with open('./input/2b.in') as file: for line in file: tokens = line.split('|') tokens[0] = re.sub(r'\s', '', tokens[0]) tokens[1] = re.sub(r'\s', '', tokens[1]) score1 = cipher.score(tokens[0]) score2 = cipher.score(tokens[1]) w.write( ('1' if score1 > score2 else '2') + '\n' ) #3a with open('./output/3a.out', 'w') as w: with open('./input/3a.in') as file: for line in file: cipher = re.sub(r'\s', '', line) w.write(crack.crack_simple(cipher) + '\n') #3b with open('./output/3b.out', 'w') as w: with open('./input/3b.in') as file: for line in file: tokens = line.split('|') n_shift = int(tokens[0]) cipher = re.sub(r'\s', '', tokens[1]) w.write(crack.crack_block(cipher, n_shift) + '\n') #3c with open('./output/3c.out', 'w') as w: with open('./input/3c.in') as file: for line in file: cipher = re.sub(r'\s', '', line) w.write(crack.crack_block(cipher) + '\n') #3d with open('./output/3d.out', 'w') as w: with open('./input/3d.in') as file: for line in file: cipher = re.sub(r'\s', '', line) w.write(crack.crack_permutation(cipher) + '\n')
TypeScript
UTF-8
413
2.546875
3
[ "MIT" ]
permissive
import { Moment } from 'moment'; export interface IGradeSchoolClass { id?: number; applicationDate?: Moment; value?: number; historyId?: number; studentId?: number; } export class GradeSchoolClass implements IGradeSchoolClass { constructor( public id?: number, public applicationDate?: Moment, public value?: number, public historyId?: number, public studentId?: number ) {} }
Java
UTF-8
791
2.515625
3
[]
no_license
import org.junit.*; import static org.junit.Assert.*; import hanoi.*; import hanoi.util.*; /** * Test class plateau * * @author : Eddy El Khatib */ public class PlateauTest { @Test public void testPlateauCreation() { Plateau somePlateau = new Plateau(5); assertNotNull(somePlateau); } @Test public void testMoveCanMove() { Plateau somePlateau = new Plateau(5); assertTrue(somePlateau.canMove(0,1)); somePlateau.move(0,1); assertFalse(somePlateau.canMove(0,1)); assertFalse(somePlateau.canMove(2,1)); } // ---Pour permettre l'exécution des test---------------------- public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(PlateauTest.class); } }
Java
UTF-8
8,063
1.976563
2
[ "Apache-2.0" ]
permissive
/* * 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.examples.http.redirects; import io.servicetalk.concurrent.api.AsyncContext; import io.servicetalk.concurrent.api.AsyncContextMap; import io.servicetalk.concurrent.api.Single; import io.servicetalk.http.api.HttpClient; import io.servicetalk.http.api.HttpExecutionStrategy; import io.servicetalk.http.api.HttpRequestMethod; import io.servicetalk.http.api.StreamingHttpClientFilter; import io.servicetalk.http.api.StreamingHttpRequest; import io.servicetalk.http.api.StreamingHttpRequester; import io.servicetalk.http.api.StreamingHttpResponse; import io.servicetalk.http.netty.HttpClients; import io.servicetalk.test.resources.DefaultTestCerts; import io.servicetalk.transport.api.ClientSslConfigBuilder; import static io.servicetalk.concurrent.api.AsyncContextMap.Key.newKey; import static io.servicetalk.examples.http.redirects.RedirectingServer.CUSTOM_HEADER; import static io.servicetalk.http.api.HttpHeaderNames.CONTENT_LENGTH; import static io.servicetalk.http.api.HttpHeaderNames.TRANSFER_ENCODING; import static io.servicetalk.http.api.HttpHeaderValues.CHUNKED; import static io.servicetalk.http.api.HttpRequestMethod.POST; import static io.servicetalk.http.api.HttpResponseStatus.StatusClass.REDIRECTION_3XX; import static io.servicetalk.http.api.HttpSerializers.textSerializerUtf8; /** * Async `Hello World` example that demonstrates how redirects can be handled automatically by a * {@link HttpClients#forMultiAddressUrl() multi-address} client. It demonstrates how users can preserve headers and * payload body of the original request while redirecting. * * For security reasons, headers and payload body are not automatically populated for the redirect request. Users have * to explicitly cary the original state when they are sure that redirect does not forward to a malicious target server. * * For backward compatibility with legacy HTTP clients, ServiceTalk preserves behavior for * {@link HttpRequestMethod#POST} requests described in RFC7231, sections * <a href="https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.2">6.4.2</a> and * <a href="https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.3">6.4.3</a>. For these status codes, manual * action may be required to preserve the original request method. */ public final class RedirectWithStateUrlClient { private static final AsyncContextMap.Key<StreamingHttpRequest> ORIGINAL_REQUEST = newKey(); public static void main(String... args) throws Exception { try (HttpClient client = HttpClients.forMultiAddressUrl() // This is an optional configuration that applies more restrictive limit for the number or redirects: .maxRedirects(1) .initializer((scheme, address, builder) -> { // Add a filter to preserve the original request information, while redirecting: builder.appendClientFilter(c -> new StreamingHttpClientFilter(c) { @Override protected Single<StreamingHttpResponse> request(StreamingHttpRequester delegate, HttpExecutionStrategy strategy, StreamingHttpRequest request) { StreamingHttpRequest original = AsyncContext.get(ORIGINAL_REQUEST); if (original != null) { // If the previous response was a redirect, carry headers and payload body. But before // doing so, make sure that the redirect location is trusted to avoid leaking sensitive // content. It can be done by manual checking of the target hostname and port number or // by configuring mutual TLS. This is out of scope of this example. CharSequence headerValue = original.headers().get(CUSTOM_HEADER); if (headerValue != null) { request.setHeader(CUSTOM_HEADER, headerValue); } // As described in javadoc for this example, 301 and 302 status codes may change // POST to GET for the redirect. Override it explicitly to preserve POST. if (POST.equals(original.method())) { request.method(POST) // Note: the original request must have re-playable payload body publisher. .payloadBody(original.payloadBody()); // Preserve correct header for the payload body length/format definition: CharSequence cl = original.headers().get(CONTENT_LENGTH); if (cl != null) { request.setHeader(CONTENT_LENGTH, cl); } else { request.setHeader(TRANSFER_ENCODING, CHUNKED); } } } return delegate().request(strategy, request).map(response -> { if (response.status().statusClass() == REDIRECTION_3XX) { // In case of a redirect, remember original request in the context: AsyncContext.put(ORIGINAL_REQUEST, request); } else { // Clear the state to make sure retries won't use the state in the context: AsyncContext.remove(ORIGINAL_REQUEST); } return response; }); } }); // The custom SSL configuration here is necessary only because this example uses self-signed // certificates. For cases when it's enough to use the local trust store, MultiAddressUrl client // already provides default SSL configuration and this step may be skipped. if ("https".equalsIgnoreCase(scheme)) { builder.sslConfig(new ClientSslConfigBuilder(DefaultTestCerts::loadServerCAPem).build()); } }) .build()) { client.request(client.post("http://localhost:8080/sayHello") .addHeader(CUSTOM_HEADER, "value") .payloadBody(client.executionContext().bufferAllocator().fromAscii("some_content"))) .whenOnSuccess(resp -> { System.out.println(resp.toString((name, value) -> value)); System.out.println(resp.payloadBody(textSerializerUtf8())); }) // This example is demonstrating asynchronous execution, but needs to prevent the main thread from exiting // before the response has been processed. This isn't typical usage for an asynchronous API but is useful // for demonstration purposes. .toFuture().get(); } } }
Java
UTF-8
143
1.734375
2
[]
no_license
package iut.ipi.runnergame.Game.Level.Loader; import iut.ipi.runnergame.Game.Level.Level; public interface LevelLoader { Level load(); }
Markdown
UTF-8
6,031
3.25
3
[]
no_license
# HTML ## HTML 속성 * 글로벌속성 : 모든 태그에 포함된 속성 <=> 지역속성 : 특정 태그에만 포함된 속성 * 필수속성 : 해당 태그에서 반드시 사용해야 하는 속성 <=> 선택속성 : 반드시 사용하지 않아도 되는 속성 * id와 class는 글로벌 속성 ```html <h1 id="title" class="main">Hello, HTML</h1> ``` ## 빈태그 * 빈 태그는 내용이 없어서 종료 태그가 필요하지 않음 ```html <br> <img src=""> <input type=""> ``` ## 텍스트 표현 태그 * b 태그 : 볼드체 * i 태그 : 이탤릭체 * u 태그 : 밑줄 * s 태그 : 취소선 ```html <p> <b>Lorem</b> <i>ipsum</i> dolor sit amet<br> <u>Lorem</u> <s>ipsum</s> dolor sit amet </p> ``` * 단순 꾸미기가 아니라 의미가 내포된 경우 Symantic Markup 사용 ```html <b>굵은</b> vs <strong>중요한</strong> <i>기울어진</i> vs <em>강조하는</em> <u>밑줄친</u> vs <ins>새롭게 추가된</ins> <s>중간선이 있는</s> vs <del>삭제된</del> ``` ## a 태그 * href는 링크를 지정해주는데 외부링크와 내부링크가 가능하다. * 내부링크는 내부에 특정 id값을 가진 태그로 이동시켜준다. * target은 링크를 새창에 띄울지 현재창에 띄울지 정해주는 속성이다. ```html <a href="http://www.naver.com/" target="_blank">네이버</a> <a href="http://www.naver.com/" target="_self">네이버</a> <a href="#introduce">자기소개로 이동하기</a> <a href="#history">약력으로 이동하기</a> <h1 id="introduce">나는 ...</h1> <h1 id="history">1991년에 태어나...</h1> ``` ## div 태그, span 태그 * 아무 의미 없는 태그 : div, span * 스타일을 지정해주거나 서버에 보내는 데이터를 담기 위한 용도 ```html <div> Do you See? <span>This is Me.</span> </div> ``` ## ul 태그, ol 태그, dl 태그 * 순서가 따로 표시되지 않는 리스트 ```html <ul> <li> 콩나물</li> <li> 파</li> <li> 국간장</li> </ul> ``` * 순서가 표시되는 리스트 ```html <ol> <li>냄비에 국물용 멸치를 넣고 한소끔 끓여 멸치 육수를 7컵(1,400ml) 만든다.</li> <li>콩나물을 넣고 뚜껑을 덮어 콩나물이 익을 때까지 끓인다.</li> <li>뚜껑을 열고 대파, 마늘, 고춧가루를 넣고 끓인다.</li> </ol> ``` * 정의를 표현하는 리스트 ```html <dl> <dt>리플리 증후군</dt> <dd>허구의 세계를 진실이라 믿고 거짓된 말과 행동을 상습적으로 반복하는 반사회적 성격장애를 뜻하는 용어</dd> <dt>피그말리온 효과</dt> <dd>타인의 기대나 관심으로 인하여 능률이 오르거나 결과가 좋아지는 현상</dd> <dt>언더독 효과</dt> <dd>사람들이 약자라고 믿는 주체를 응원하게 되는 현상</dd> </dl> ``` ## img 태그 * src 속성 : img 태그의 필수 속성, 경로를 의미 * alt 속성 : img 의 대체 텍스트를 의미 웹접근성의 관점에서 반드시 써야함 * width/height 속성 : 둘중 하나만 정해줘도 비율에 맞게 크기가 변경됨 ```html <img src="./images/pizza.png" alt="피자"> ``` ## table 관련 태그 * table : 표를 나타내는 태그 * tr : 행을 나타내는 태그 * th : 제목 셀을 나타내는 태그 * td : 셀을 나타내는 태그 * caption: 표의 제목을 나타내는 태그 * thead: 제목 행을 그룹화하는 태그 * tbody: 본문 행을 그룹화하는 태그 * tfoot: 바닥 행을 그룹화하는 태그 ```html <table> <caption>Monthly Savings</caption> <thead> <tr> <th>Month</th> <th>Savings</th> </tr> </thead> <tbody> <tr> <td>January</td> <td>$100</td> </tr> <tr> <td>February</td> <td>$80</td> </tr> </tbody> <tfoot> <tr> <td>Sum</td> <td>$180</td> </tr> </tfoot> </table> ``` ## colspan, rowspan 속성 * 행과 열을 병합해주는 속성 * 시작영역의 태그에 병합할 행의 수만큼 지정해준다. * 병합 되는 부분에는 아무것도 작성하지 않는다. * 비워두면 알아서 처리한다. ```html <thead> <tr> <th rowspan="2">Grade.</th> <th rowspan="2">Point.</th> <th colspan="2">Strength.</th> <th rowspan="2">Percent.</th> </tr> <!-- 비워두면 알아서 처리 --> <tr> <th>kg/mm</th> <th>lb/in</th> </tr> </thead> ``` ## fieldset 태그, legend 태그, label 태그 * fieldset : 여러 개의 폼 요소를 그룹화하여 구조적으로 만들기 위해 사용 * legend : 폼 요소의 제목으로 fieldset 내부에 작성 * label : form 요소의 이름과 form 요소를 명시적으로 연결시켜주기 위해 사용 * form 요소의 id 속성값과 label의 for 속성값을 같게 적어주어야 함 ```html <form action=""> <h1>Form 관련 요소</h1> <fieldset> <legend>기본 정보</legend> <label for="userid">아이디 : </label> <input type="text" placeholder="영문으로만 써주세요" id="userid"><br> <label for="userpw">비밀번호 : </label> <input type="password" id="userpw"><br> 성별 : <label for="male">남자</label> <input type="radio" name="gender" id="male" checked>, <label for="female">여자</label> <input type="radio" name="gender" id="female"><br> </fieldset> <fieldset> <legend>부가 정보</legend> 취미 : 영화 감상 <input type="checkbox" name="hobby" checked>, 음악 감상 <input type="checkbox" name="hobby">, 독서 <input type="checkbox" name="hobby"><br> 프로필 사진 업로드 : <input type="file"><br> 사는 지역 : <select> <option>서울</option> <option>경기</option> <option>강원</option> <option selected>제주</option> </select><br> 자기소개 : <textarea cols="30" rows="5" placeholder="자기소개는 짧게 해주세요."></textarea><br> <button type="submit">전송</button> <button type="reset">취소</button> </fieldset> </form> ```
Python
UTF-8
1,234
2.78125
3
[]
no_license
import logging import logging.config from argparse import ArgumentParser import yaml LOG_PATH = '/code/logging.conf.yml' with open(LOG_PATH) as config_fin: logging.config.dictConfig(yaml.safe_load(config_fin)) logger = logging.getLogger(__name__) def get_train_args(): """Parse arguments from command line""" parser = ArgumentParser( prog="Training model", ) parser.add_argument( "train_audio", help="Path to audio *.wav files directory for training", default=None ) parser.add_argument( "train_gt", help="Path to *.csv file with data for training", default=None ) parser.add_argument( "output_dir", help="Path where to save files/weights for prediction phase", default=None ) args = parser.parse_args() logger.debug("Arguments parsed.") return args def main(): """Run training""" from read_and_get_mel import main as read_input from folds import get_folds from train_model import main as train_models args = get_train_args() read_input(args.train_audio, args.train_gt) get_folds() train_models(output_dir=args.output_dir) if __name__ == '__main__': main()
Java
UTF-8
700
1.890625
2
[]
no_license
package com.avito.android.shop.list.presentation; import dagger.internal.Factory; public final class ShopListDataChangeListenerImpl_Factory implements Factory<ShopListDataChangeListenerImpl> { public static final class a { public static final ShopListDataChangeListenerImpl_Factory a = new ShopListDataChangeListenerImpl_Factory(); } public static ShopListDataChangeListenerImpl_Factory create() { return a.a; } public static ShopListDataChangeListenerImpl newInstance() { return new ShopListDataChangeListenerImpl(); } @Override // javax.inject.Provider public ShopListDataChangeListenerImpl get() { return newInstance(); } }
C++
UTF-8
1,446
2.8125
3
[ "MIT" ]
permissive
//Language: GNU C++ #include <iostream> #include <cstdlib> #include <cstring> #include <queue> #include <vector> using namespace std; struct state { int x, y, t; vector<vector<char> > b; state(int x, int y, int t, vector<vector<char> > b) : x(x), y(y), t(t), b(b) {} }; typedef pair<int, int> pii; int main() { vector<vector<char> > B(8, vector<char> (8)); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { B[i][j] = cin.get(); } cin.get(); // \n } bool vis[8][8][8*8]; memset(vis, false, sizeof(vis)); string win = "LOSE"; queue<state> bfs; bfs.push(state(7, 0, 0, B)); int x, y, t, nx, ny, nt; vector<vector<char> > b, nb; while (!bfs.empty()) { x = bfs.front().x; y = bfs.front().y; t = bfs.front().t; b = bfs.front().b; bfs.pop(); if (vis[x][y][t]) continue; vis[x][y][t] = true; if (b[x][y] == 'A') { win = "WIN"; break; } nb = b; for (int i = 7; i >= 0; i--) { for (int j = 0; j < 8; j++) { if (b[i][j] == 'S') { nb[i][j] = '.'; if (i < 7) nb[i+1][j] = 'S'; } } } nt = t + 1; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { nx = x + i; ny = y + j; if (nx >= 0 && nx < 8 && ny >= 0 && ny < 8 && b[nx][ny] != 'S' && nb[nx][ny] != 'S' && !vis[nx][ny][nt]) { bfs.push(state(nx, ny, nt, nb)); } } } } cout << win << endl; }
TypeScript
UTF-8
1,289
2.796875
3
[]
no_license
import * as t from 'io-ts'; import uuid from 'uuid'; import { Instrument } from '@/core/instrument/instrument'; import { Serializable } from './serializable'; import { Note, NoteType } from './scheduled/note'; const ScoreTypeRequired = t.type({ instrumentId: t.string, id: t.string, }); const ScoreTypePartial = t.partial({ notes: t.array(NoteType), }); export const ScoreType = t.intersection([ScoreTypeRequired, ScoreTypePartial]); export type IScore = t.TypeOf<typeof ScoreType>; export class Score implements Serializable<IScore> { public static create(instrument: Instrument<any, any>) { const score = new Score(instrument, { id: uuid.v4(), instrumentId: instrument.id, }); return score; } public id: string; public instrumentId: string; public notes: Note[]; constructor(public instrument: Instrument<any, any>, i: IScore) { this.id = i.id; this.instrumentId = i.instrumentId; this.notes = (i.notes || []).map((iNote) => { return new Note(this.instrument, iNote); }); } public serialize() { return { instrumentId: this.instrumentId, id: this.id, notes: this.notes.map((note) => note.serialize()), }; } public dispose() { this.notes.forEach((note) => note.dispose()); } }
C#
UTF-8
4,454
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Quobject.SocketIoClientDotNet.Client; using Microsoft.Kinect; using Newtonsoft.Json; namespace KinectClient { class MedianBuffer<T> { const int size = 10; private List<T> buf = new List<T>(); public T Push(T x) { buf.Add(x); while(buf.Count > size) { buf.RemoveAt(0); } var q = from c in buf group c by x into g let count = g.Count() orderby count descending select new { Value = g.Key, Count = count }; return q.First().Value; } } class HandUpdate { public int BodyId { get; set; } public bool IsLeft { get; set; } public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public double DX { get; set; } public double DY { get; set; } public double DZ { get; set; } public string Gesture { get; set; } public string Confidence { get; set; } } class KinectClientEndpoint { public const string DefaultEndpoint = "http://192.168.180.126:8090"; private const int skip = 2; private int count; private Socket socket; private MedianBuffer<HandState> leftBuffer; private MedianBuffer<HandState> rightBuffer; public KinectClientEndpoint() { socket = null; count = 0; leftBuffer = new MedianBuffer<HandState>(); rightBuffer = new MedianBuffer<HandState>(); } public void Connect(string url = DefaultEndpoint) { if (socket != null) throw new InvalidOperationException("Already Connected"); socket = IO.Socket(url); } public void SendHandUpdate(Body body) { if (socket == null) throw new InvalidOperationException("Not Connected"); HandUpdate leftUpdate = Create(body.Joints[JointType.HandLeft], body.Joints[JointType.Head], leftBuffer.Push(body.HandLeftState), true, body.HandLeftConfidence, (int)body.TrackingId); HandUpdate rightUpdate = Create(body.Joints[JointType.HandRight], body.Joints[JointType.Head], rightBuffer.Push(body.HandRightState), false, body.HandRightConfidence, (int)body.TrackingId); count++; if (count >= skip) { socket.Emit("hand", JsonConvert.SerializeObject(leftUpdate)); socket.Emit("hand", JsonConvert.SerializeObject(rightUpdate)); count = 0; } } public void SendKeywordRecognized(string word) { socket.Emit("keyword", word); } public void Close() { if (socket == null) throw new InvalidOperationException("Not Connected"); socket.Close(); socket = null; } private HandUpdate Create(Joint hand, Joint head, HandState state, bool isLeft, TrackingConfidence confidence, int bodyId) { return new HandUpdate { X = hand.Position.X, Y = hand.Position.Y, Z = hand.Position.Z, DX = hand.Position.X - head.Position.X, DY = hand.Position.Y - head.Position.Y, DZ = hand.Position.Z - head.Position.Z, IsLeft = isLeft, Gesture = GetHandTrackingState(state), Confidence = GetTrackingConfidence(confidence), BodyId = bodyId }; } private string GetTrackingConfidence(TrackingConfidence confidence) { switch (confidence) { case TrackingConfidence.High: return "high"; } return "low"; } private string GetHandTrackingState(HandState hand) { switch(hand) { case HandState.Closed: return "closed"; case HandState.Lasso: return "lasso"; case HandState.Open: return "open"; case HandState.Unknown: return "unknown"; } return "untracked"; } } }
C++
GB18030
1,240
2.890625
3
[]
no_license
#include<iostream> //#include"cyclicqueueobj.h" #include"queueprocess.h" #include"cycalgorithm.h" using namespace std; //void CycObjTest() { // CyclicQueue cycquee; // cycquee.Init(); // // for (int i = 1; i <= 99; i++) { // cycquee.InQuene(i); // } // // //Զ // cycquee.InQuene(24); // int temp; // //ɾ // for (int j = 0; j < 50; j++) { // cycquee.DeQuene(&temp); // cout << "ɾ:" << temp << " "; // } // cout << endl; // // cycquee.OutPut(); // cout << "ͷԪأ" << cycquee.getHead() << endl; //} void AlgorithmTest() { //Զ CRORLinkQueue *crorqueue =new CRORLinkQueue; int i; InitCRORQueue(crorqueue); for (i = 0; i < 20;i++) { EnCRORQueue(crorqueue, i); } //showCRORQuenue(crorqueue); for (i = 0; i < 10; i++) { DeCRORQueue(crorqueue); } //showCRORQuenue(crorqueue); SeTagQueue cytag; QueueInit(cytag); for (i = 0; i < 20; i++) { QueueIn(cytag, i); } for (i = 0; i < 10; i++) { cout<<QueueOut(cytag)<<" "; } cout << endl; //ͷջβջ CycQueue cycq; IinitQueue(cycq); for (i = 0; i < 20; i++) { FrontEnQueue(cycq, i); } for (i = 0; i < 10; i++) { cout<<RaerDeQueue(cycq)<<" "; } cout << endl; } int main() { AlgorithmTest(); return 0; }
C#
UTF-8
3,092
3.265625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace _TestApp_Sparkybit { public class ManipuleWithFile { public event MessageHandler FileMessage; List<string> outputFile = new List<string>(); List<string> listFile = new List<string>(); public void LoadFile() { listFile.Add(" "); FileMessage.Invoke(DateTime.Now, "Load file."); Console.WriteLine("Load data from file...\n"); string line; try { using (StreamReader sr = new StreamReader("../../../source.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); listFile.Add(line); } } Console.WriteLine("File is load!\n"); } catch (Exception e) { Console.WriteLine("File not found: " + e.Message); Console.WriteLine("\nClose app."); Console.ReadLine(); Environment.Exit(0); } } public void EditFile() { Console.WriteLine("Create new data..."); FileMessage.Invoke(DateTime.Now, "Edit file."); List<string> list = new List<string>(); list.Add(""); List<int> num = new List<int>(); int first = 0; int second = 1; int sum; for (int i = 0; i < listFile.Count; i++) { sum = first; first = second; second = second + sum; if (second <= listFile.Count) { string input = listFile[second]; string output = new string(input.ToCharArray().Reverse().ToArray()); outputFile.Add(output); } } } public void SaveFile() { Console.WriteLine("Please name your new file:"); string nameFile = Console.ReadLine(); if (nameFile == "") { Console.WriteLine("Save data in output.txt ..."); FileMessage.Invoke(DateTime.Now, "Save file."); nameFile = "output"; StreamWriter sw = new StreamWriter("output.txt"); foreach (string line in outputFile) { sw.WriteLine(line); Console.WriteLine(line); } sw.Close(); } else { Console.WriteLine($"Save data in {nameFile} ..."); FileMessage.Invoke(DateTime.Now, "Save file."); StreamWriter sw = new StreamWriter($"{nameFile}.txt"); foreach (string line in outputFile) { sw.WriteLine(line); } sw.Close(); } } } }
Python
UTF-8
3,029
3.171875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python3 import tensorflow as tf import collections import math import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # import tensorflow.contrib.graph_editor as ge def normal_distribution_pdf(x, mean, sd): var = float(sd)**2 denom = (2*math.pi*var)**.5 num = math.exp(-(float(x)-float(mean))**2/(2*var)) return num/denom class Node: def __init__(self, memory=1, name=''): self.name = name self.memory = memory self.parents = set() self.children = set() self.is_checkpoint = False self.backward_index = None self.backward_indexes = [] def __str__(self): return self.name + '\t' + str(self.memory) + '\t' + \ 'backward index: ' + str(self.backward_index) + '\t' + \ 'parents: ' + str(self.parents) + '\t' + \ 'children: ' + str(self.children) def __repr__(self): return self.name def chain(nodes): for i in range(len(nodes) - 1): nodes[i].children.add(nodes[i+1]) nodes[i+1].parents.add(nodes[i]) def topological_sort(last_node, visited=set()): if last_node in visited: return [] result = [] for parent in last_node.parents: result += topological_sort(parent, visited) result.append(last_node) return result def smooth_max(items): numerator = 0 denominator = 0 for item in items: numerator = item * math.exp(item) denominator += math.exp(item) return numerator / denominator # max = smooth_max @tf.function def compute_memory_usage(last_node): nodes = topological_sort(last_node) for node in nodes: node.backward_index = 0 node.backward_indexes = [] backward_num = 0 for node in nodes: if len(node.backward_indexes) == 0: node.backward_index = 0 else: node.backward_index = max(node.backward_indexes) backward_num = max((backward_num, node.backward_index + 1)) for child in node.children: if node.is_checkpoint: child.backward_indexes.append(node.backward_index + 1) else: child.backward_indexes.append(node.backward_index) # TODO: Currently it's overestimating memory_by_backward length. memory_by_backward = [0.0] * len(nodes) for node in nodes: memory_by_backward[node.backward_index] += node.memory if node.is_checkpoint: for i in range(node.backward_index + 1, len(memory_by_backward)): memory_by_backward[i] += node.memory # print(memory_by_backward) return max(memory_by_backward) a = Node(1, 'a') b = Node(2, 'b') c = Node(4, 'c') d = Node(8, 'd') e = Node(16, 'e') # a.is_checkpoint = True b.is_checkpoint = True # c.is_checkpoint = True d.is_checkpoint = True # e.is_checkpoint = True chain([a, b, c, d, e]) print(normal_distribution_pdf(1, 0, 0.5)) print(compute_memory_usage(e)) # print(a, b, c, d, e, sep='\n') # print(smooth_max([1,8,5,3,9]))
Java
UTF-8
1,265
2.234375
2
[]
no_license
package com.gpualgo.service.dto; import com.gpualgo.domain.OverlockSetting; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public class OverlockSettingDTO { private long id; private long position; private String architecture; private String brand; private String model; private String algorithm; private long memoryCapacity; private long coresNumber; private long powerCapacity; private long votesUp; private long votesDown; public static OverlockSettingDTO buildFromEntity(OverlockSetting setting) { return OverlockSettingDTO .builder() .id(setting.getId()) .architecture(setting.getGpuArchitecture()) .brand(setting.getGpuBrand()) .model(setting.getGpuModel()) .algorithm(setting.getAlgorithm()) .memoryCapacity(setting.getMemoryCapacity()) .coresNumber(setting.getCoresNumber()) .powerCapacity(setting.getPowerCapacity()) .votesUp(setting.getVotesUp()) .votesDown(setting.getVotesDown()) .build(); } }
TypeScript
UTF-8
251
2.65625
3
[]
no_license
enum MemberShip { Simple, Standard, Premium } const memberShip = MemberShip.Premium console.log(memberShip); enum SocialMedia { VK = 'VK', INST = 'INST', FB = 'FB' } const socialMedia = SocialMedia.VK console.log(socialMedia);
C++
UTF-8
152
2.84375
3
[]
no_license
#include <iostream> int main(int argc, const char * argv[]) { for (int x=0;x < 10;++x) // ++x VS x++ { std::cout << x; } return 0; }
Python
UTF-8
4,602
2.890625
3
[]
no_license
'''To quickly see what open positions I currently have - using my xls file "TradingJournal (FX) (2020).xlsx ''' import pandas as pd import numpy as np df = pd.read_excel(r"/Users/sanduo/Documents/Trading/TradingJournal (FX) (2020).xlsx", \ sheet_name = 'Trade Log', \ skiprows = 2) print(df.head()) # Using the Date column to filter out all the trades I've executed so far filter = df['Date'].isna() df_alltrades = df[~filter] # Using the Price Out column to identify which trades I have not closed yet, i.e. Open Positions open_filter = df_alltrades['Price Out'].isna() open_positions = df_alltrades[open_filter] pd.options.display.float_format = '{:,.4f}'.format # Format with commas and round off to 2dp open_ccys = open_positions[['L/S','Notional','Pair', 'Price In', 'SL', 'TP']] print(open_ccys) print('There are {} open positions currently.'.format(open_ccys['Pair'].count())) # Show Exposure in each currencies pd.options.mode.chained_assignment = None # safely disable SettingWithCopyWarning warning map={'L':1, 'S':-1} # map for +ve and -ve exposures sign = open_ccys['L/S'].map(map) open_ccys['Notional'] *= sign open_ccys['pricing_notional'] = open_ccys['Notional'] * open_ccys['Price In'] * (-1) open_ccys['base_ccy'] = open_ccys['Pair'].str[:3] open_ccys['pricing_ccy'] = open_ccys['Pair'].str[-3:] base = open_ccys[['base_ccy','Notional']].rename(columns={'base_ccy':'currency','Notional':'notional'}) pricing = open_ccys[['pricing_ccy', 'pricing_notional']].rename(columns={'pricing_ccy':'currency','pricing_notional':'notional'}) combined = base.append(pricing) # Use current exchange rates XXXUSD to convert all to USD exposures usd_rates_df = df[['xxxusd','rates']].dropna() merged = pd.merge(combined, usd_rates_df, left_on='currency', right_on='xxxusd', how='left') merged['exposure(usd)'] = merged.notional * merged.rates exposures = merged.groupby('currency')['exposure(usd)'].sum().reset_index() exposures_sorted = exposures.sort_values('exposure(usd)') print(exposures_sorted) # Plot exposures import matplotlib.pyplot as plt import matplotlib.ticker as mtick import seaborn as sns from datetime import datetime sns.set(style="darkgrid") fig, ax = plt.subplots(1,2, figsize=(12,5)) # Format y ticks fmt = '${x:,.0f}' tick = mtick.StrMethodFormatter(fmt) ax[0].yaxis.set_major_formatter(tick) # Bar plot sns.barplot(x='currency', y='exposure(usd)', data=exposures_sorted, palette="rocket", ax=ax[0]) ax[0].set_title('Open Exposures (in USD)') ax[0].set_ylabel('') ax[0].set_xlabel('') ### Visualize MTM and distance to SL and TP # Vlookup / Merge usd_rates_df with open_ccys twice, based on base_ccy and pricing_ccy base_live = pd.merge(open_ccys, usd_rates_df, left_on='base_ccy', right_on='xxxusd', how='left') open_ccys_live = pd.merge(base_live, usd_rates_df, left_on='pricing_ccy', right_on='xxxusd', suffixes=['_base','_pricing'], how='left') # Get current price 'last' - rates_base/rates_pricing open_ccys_live['last'] = open_ccys_live['rates_base']/open_ccys_live['rates_pricing'] # Calculate pnl % gain (+) or loss (-) open_ccys_live['chg_pct']=((open_ccys_live['last']/open_ccys_live['Price In'])-1)*100 open_ccys_live['sl_pct']=((open_ccys_live['SL']/open_ccys_live['Price In'])-1)*100 open_ccys_live['tp_pct']=((open_ccys_live['TP']/open_ccys_live['Price In'])-1)*100 # Plot MTM distances on horizontal bar plot sns.barplot(x='sl_pct', y='Pair', data=open_ccys_live, label='SL', color='red', alpha=0.3, ax=ax[1]) sns.barplot(x='tp_pct', y='Pair', data=open_ccys_live, label='TP', color='green', alpha=0.3, ax=ax[1]) open_ccys_live.loc[(open_ccys_live['chg_pct'] >= 0) & (open_ccys_live['L/S']=='L'), 'positive_pnl'] = open_ccys_live['chg_pct'] open_ccys_live.loc[(open_ccys_live['chg_pct'] < 0) & (open_ccys_live['L/S']=='S'), 'positive_pnl'] = open_ccys_live['chg_pct'] open_ccys_live.loc[(open_ccys_live['chg_pct'] >= 0) & (open_ccys_live['L/S']=='S'), 'negative_pnl'] = open_ccys_live['chg_pct'] open_ccys_live.loc[(open_ccys_live['chg_pct'] < 0) & (open_ccys_live['L/S']=='L'), 'negative_pnl'] = open_ccys_live['chg_pct'] sns.barplot(x='positive_pnl', y='Pair', data=open_ccys_live, label='ITM', color='green', ax=ax[1]) sns.barplot(x='negative_pnl', y='Pair', data=open_ccys_live, label='OTM', color='red', ax=ax[1]) ax[1].set_title('Mark To Market') ax[1].set_ylabel('') ax[1].set_xlabel('% PnL') ax[1].xaxis.set_major_formatter(mtick.PercentFormatter()) ax[1].legend(loc="upper left", fontsize=8) fig.suptitle(datetime.now().strftime("%d/%m/%Y\n%H:%M"), fontsize=9) fig.tight_layout() plt.show()
Python
UTF-8
2,462
2.609375
3
[]
no_license
import http.server import socketserver import http.client import json PORT = 8002 # HTTPRequestHandler class class serverRequestHandler(http.server.BaseHTTPRequestHandler): # GET def do_GET(self): r_web = self.path #request from web page print(r_web) if 'label' in r_web or 'limit' in r_web: print("if label") # init, file to open search.html filename = "search.html" with open(filename, "r") as f: content = f.read() # Send response status code self.send_response(200) # Send headers self.send_header('Content-type','text/html') self.end_headers() # Write content as utf-8 data self.wfile.write(bytes(content, "utf8")) # Read data from submitted form: label & limit print('request to fetch drugs') r_openfda = r_web[r_web.index('?') + 1:] # print(s[s.index('.')+1:]) print(r_openfda) label = r_web[r_web.index('=') + 1:r_web.index('&')] print(label) limit = r_web[r_web.index('&'):] print(limit) # string for openfda query s_openfda = "/drug/label.json?search=generic_name:" + label + limit print(s_openfda) # sending request openFDA headers = {'User-Agent': 'http-client'} conn = http.client.HTTPSConnection("api.fda.gov") conn.request("GET", s_openfda, None, headers) r1 = conn.getresponse() print(r1.status, r1.reason) repos_raw = r1.read().decode("utf-8") conn.close() drugs = json.loads(repos_raw) self.wfile.write(bytes(str(drugs), "utf8")) else: # init, file to open search.html filename = "search.html" with open(filename, "r") as f: content = f.read() # Send response status code self.send_response(200) # Send headers self.send_header('Content-type','text/html') self.end_headers() # Write content as utf-8 data self.wfile.write(bytes(content, "utf8")) return # Handler = http.server.SimpleHTTPRequestHandler Handler = serverRequestHandler httpd = socketserver.TCPServer(("", PORT), Handler) print("serving at port", PORT) httpd.serve_forever()
JavaScript
UTF-8
1,303
3.171875
3
[ "MIT" ]
permissive
'use strict' // exposes an async function suitable for profiling module.exports = someCodeToBeProfiled const createDeferred = require('../lib/deferred') async function someCodeToBeProfiled (options = {}) { const { verbose = false, count = 5, delay = 10 } = options const log = verbose ? consoleLog : () => {} log('running with delaySync') for (let i = 0; i < count; i++) { const value = factorialSync(i, delay) log(`${i}!: ${value}`) } log('') log('running with delayAsync') for (let i = 0; i < count; i++) { const value = await factorialAsync(i, delay) log(`${i}!: ${value}`) } } function factorialSync (n, delay) { delaySync(delay) if (n <= 0) return 1 return n * factorialSync(n - 1, delay) } async function factorialAsync (n, delay) { await delayAsync(delay) if (n <= 0) return 1 return n * await factorialAsync(n - 1, delay) } function delaySync (ms) { const end = ms + Date.now() while (Date.now() < end) {} return ms } async function delayAsync (ms) { const deferred = createDeferred() setTimeout(() => deferred.resolve(ms), ms) return deferred.promise } function consoleLog (...args) { console.log(...args) } if (require.main === module) { someCodeToBeProfiled({ verbose: true, count: 10, delay: 100 }) }
C++
UTF-8
860
3.421875
3
[]
no_license
#include <iostream> using namespace std; string a (int arabic) //arabico a romano { string roman=""; //resultado for(int i=1; i<=3 && arabic>0; i++, arabic/=10) { char ten,five,one; switch(i) { case 1: ten='X'; five='V'; one='I'; break; case 2: ten='C'; five='L'; one='X'; break; case 3: ten='M'; five='D'; one='C'; break; } int cipher=arabic%10; if(cipher<=3) { for(int j=0; j<cipher; j++) roman=one+roman; continue; } if(cipher==9) { roman=ten+roman; roman=one+roman; continue; } for(int j=0; j<cipher-5; j++) //6-8 roman=one+roman; roman=five+roman; if(cipher==4) roman=one+roman; } for(int i=arabic; i>0; i--) roman="M"+roman; return roman; } int main5() { int i; cout<< "Ingrese un numero entre 1 y 1000"<<endl; cin>> i; cout<<i<<" En romano es: \t"<<a(i); return 0; }
Markdown
UTF-8
4,990
3.3125
3
[]
no_license
> layout其实分为`el-row`和`el-col`,也就是行和列 先头脑风暴一下,如果要你设计一个layout组件,可能要实现什么样的功能呢? 1. 要**基础布局**吧 2. 分栏太紧了,支持配置**分栏间隔**就好了 3. 有些分栏我希望可以横跨几个块,有没有**混合布局** 4. 有些分栏我不需要顶格,想要一点**偏移** 5. 分栏有时想要左浮,右浮和居中。那也得有**对齐方式** 6. 最好在浏览器缩放时,能支持**响应式布局** 带着这些点去看代码~ #### 函数式组件 首先`el-row`和`el-col`都是函数式组件,也就是说是没有`template`的,全靠`render`来渲染函数 #### 支持自定义元素标签 默认标签是div,但是布局有时也可以是li,要怎么兼容呢?可以通过传入tag参数来实现。函数式组件可以把tag作为第一个参数传入到render函数。 也可以通过动态组件来实现`<component :is="tag" />` #### 分栏间隔 也就是`gutter`,分栏间隔是设置在`el-row`,单位是`px` 设置了`gutter`之后,`el-row`就要左右缩进一些`margin`,不然就会比外层容器小一点~ ![image-20200911190025020](http://img-hosting.charming.run/images/2020/09/11/20200911190032.png) 由于`gutter`是设置在`el-row`上面的,那么在`el-col`就需要去获取设置的`gutter` 要怎么获取呢?可以通过`$options`,([gutter?](https://cn.vuejs.org/v2/api/#vm-options)) ``` gutter() { let parent = this.$parent; while (parent && parent.$options.componentName !== 'ElRow') { parent = parent.$parent; } return parent ? parent.gutter : 0; } ``` 递归一直往上找,找到`componentName`是`ElRow`为止,读取他的`gutter`配置~ 读取到gutter就可以加上相对于的样式了 ```javascript if (this.gutter) { style.paddingLeft = this.gutter / 2 + 'px'; style.paddingRight = style.paddingLeft; } ``` #### 偏移 偏移实际上都是解决一个问题,就是在原来位置上的移动。 **offset** offset表示与前一个`el-col`的距离 **pull、push** 表示对于`el-row`要push推出或者pull拉回来多少。 **区别** 直接看css就能发现区别了。offset是用`margin: [num]%`来实现偏移 ,而push、pull是用定位的 ```scss @for $i from 0 through 24 { .el-col-offset-#{$i} { margin-left: (1 / 24 * $i * 100) * 1%; } .el-col-pull-#{$i} { position: relative; right: (1 / 24 * $i * 100) * 1%; } .el-col-push-#{$i} { position: relative; left: (1 / 24 * $i * 100) * 1%; } } ``` 主要是靠class实现啦 #### 基础布局、混合布局 基本上就是配置span,而span主要靠class体现 span的class是直接`el-col-[span-num]` 而offer,push,pull的class则是`el-col-offset-[num]` 所以部分js代码都得判断是否是span,才好确定加什么类名 ```javascript ['span', 'offset', 'pull', 'push'].forEach(prop => { if (this[prop] || this[prop] === 0) { classList.push( prop !== 'span' ? `el-col-${prop}-${this[prop]}` : `el-col-${this[prop]}` ); } }); ``` 因为layout布局是把空间分成24栏,所以for循环一下0到24就好了~ ``` @for $i from 0 through 24 { .el-col-#{$i} { width: (1 / 24 * $i * 100) * 1%; } .el-col-offset-#{$i} { margin-left: (1 / 24 * $i * 100) * 1%; } .el-col-pull-#{$i} { position: relative; right: (1 / 24 * $i * 100) * 1%; } .el-col-push-#{$i} { position: relative; left: (1 / 24 * $i * 100) * 1%; } } ``` #### 响应式布局 响应式布局说白了也是靠css,那就看一看css怎么写吧。 ![image-20200911195852016](https://raw.githubusercontent.com/Charming2015/picture-hosting/master/img/20200915184243.png) 样式外面会用res包一层,而res这个mixin就是主要处理响应式的~ 以传入`xs`为例: ``` @mixin res($key, $map: $--breakpoints) { // 循环断点Map,如果存在则返回 @if map-has-key($map, $key) { @media only screen and #{inspect(map-get($map, $key))} { @content; } } @else { @warn "Undefeined points: `#{$map}`"; } } ``` res函数先判断是否在key-map里面 然后加入媒体属性,根据传入的xs,映射成不同的max-width ``` --------------------------*/ $--sm: 768px !default; $--md: 992px !default; $--lg: 1200px !default; $--xl: 1920px !default; $--breakpoints: ( 'xs' : (max-width: $--sm - 1), 'sm' : (min-width: $--sm), 'md' : (min-width: $--md), 'lg' : (min-width: $--lg), 'xl' : (min-width: $--xl) ); ``` #### 对齐方式实现 对齐主要靠flex布局。可以传入align和justify,但必须type为flex才会生效~ #### 彩蛋-基于断点的隐藏类【TODO】 【STAR】 1. 函数式组件的$slots居然可以充当render函数的第三个参数~ ``` render(h) { return h(this.tag, {}, this.$slots.default); } ```
C#
UTF-8
3,549
2.859375
3
[]
no_license
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; namespace LinearRegressionLeastSquaresCriterion { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public int oneUnitLength = 12; public List<(double, double)> inputData = new List<(double, double)> { (1, 1), (2, 2), (3, 1.3), (4, 3.75), (5, 2.25) }; public MainWindow() { InitializeComponent(); var regresionLine = LeastSquaresCriterion.Execute(inputData); DrawNet(); DrawLinearGragh(regresionLine.Item1, regresionLine.Item2); GraphLable.Content = $"y = {Math.Round(regresionLine.Item1, 4)} x" + (regresionLine.Item2 < 0 ? " - " : " + ") + $"{Math.Abs(Math.Round(regresionLine.Item2, 4))}"; } private void DrawLinearGragh(double slope, double intercept) { var rangeOfX = (-10_000, 10_000); DrawLine( (rangeOfX.Item1, (int)(slope * rangeOfX.Item1 + intercept)), (rangeOfX.Item2, (int)(slope * rangeOfX.Item2 + intercept)) ); } private void DrawNet() { var canvasWidth = GraphPlain.Width; var canvasHeight = GraphPlain.Height; for (var i = 0; i < canvasWidth; i++) { GraphPlain.Children.Add( new Line() { Stroke = Brushes.LightSteelBlue, X1 = i * oneUnitLength, Y1 = 0, X2 = i * oneUnitLength, Y2 = canvasHeight }); } for (var j = 0; j < canvasHeight; j++) { GraphPlain.Children.Add(new Line() { Stroke = Brushes.LightSteelBlue, X1 = 0, Y1 = j * oneUnitLength, X2 = canvasWidth, Y2 = j * oneUnitLength }); } GraphPlain.Children.Add(new Line() { Stroke = Brushes.Black, StrokeThickness = 3, X1 = canvasWidth / 2, Y1 = 0, X2 = canvasWidth / 2, Y2 = canvasHeight }); GraphPlain.Children.Add(new Line() { Stroke = Brushes.Black, StrokeThickness = 3, X1 = 0, Y1 = canvasHeight / 2, X2 = canvasWidth, Y2 = canvasHeight / 2 }); } private void DrawLine((int, int) firstPoint, (int, int) secondPoint) { var canvasWidth = GraphPlain.Width; var canvasHeight = GraphPlain.Height; Line line = new Line(); line.Stroke = SystemColors.WindowFrameBrush; line.X1 = canvasWidth / 2 + firstPoint.Item1 * oneUnitLength; line.Y1 = canvasHeight / 2 - firstPoint.Item2 * oneUnitLength; line.X2 = canvasWidth / 2 + secondPoint.Item1 * oneUnitLength; line.Y2 = canvasHeight / 2 - secondPoint.Item2 * oneUnitLength; GraphPlain.Children.Add(line); } } }
Python
UTF-8
1,967
3.90625
4
[]
no_license
"""Solution to problem 105 It's a pretty simple solution: For each set, I go from longest possible subsets to smallest lengths. I get all combinations and take the sum. If I already have a subset with the sum, I check if they are disjoint. If they're not, I continue, if they are, the test fails. For the second condition, I check for all sums smaller than the one I calculated for a specific subset, if there is a subset with more element but a smaller sum. In that case, the test fails. """ import itertools from collections import defaultdict def load_sets(): """Function to load sets """ sets = [] with open("p105_sets.txt", "r") as file: for line in file.read().split("\n"): new_set = [] for number in line.split(","): new_set.append(int(number)) sets.append(new_set) for menge in sets: menge.sort() return sets def check_partial_sums(menge): """Check if two partial sums match """ summen = defaultdict(list) for length in range(len(menge), 0, -1): #pylint: disable=R1702 for comb in itertools.combinations(menge, length): summe = sum(comb) # first condition if summen[summe]: for item in summen[summe]: if any(i in item for i in comb): continue else: return False # second condition for i in range(summe // 2, summe + 1): if summen[i]: for item in summen[i]: if len(item) > length and not any(i in item for i in comb): return False summen[summe].append(comb) return True def main(): """main function """ sets = load_sets() res = [sum(menge) for menge in sets if check_partial_sums(menge)] print(sum(res)) if __name__ == "__main__": main()
PHP
UTF-8
705
2.890625
3
[]
no_license
<?php // to start the session. session_start(); // to include the required file require_once 'user.php'; // crate new connection object $conn = new user(); if(isset($_POST['submit'])) { $username = $_POST['user']; $password = $_POST['pass']; $check = $conn->login($username, $password); // to make sure if the connection was successfully and redirect the page to the main one if yes. if(!$check) { $_SESSION['alert'] = 'username or password is incorrect'; // To make sure if the username and password correct header('location:index.php'); // If no stay in index page. } else { $_SESSION['user'] = $check; header('location:main.php'); // If yes redirct to the main page. } } ?>
Java
UTF-8
473
2.28125
2
[]
no_license
package com.example.swebnb.ui.communicate; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class CommunicateViewModel extends ViewModel { private MutableLiveData<String> mText; public CommunicateViewModel(){ mText = new MutableLiveData<>(); mText.setValue(("This is communicate fragment")); } public LiveData<String> getText() { return mText; } }
C#
UTF-8
12,416
2.546875
3
[]
no_license
namespace ZetaHelpDesk.Main.Code.DBObjects { #region Using directives. // ---------------------------------------------------------------------- using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; using System.Collections; using ZetaLib.Core.Common; using ZetaLib.Core.Data; // ---------------------------------------------------------------------- #endregion ///////////////////////////////////////////////////////////////////////// public class CustomerPerson : Base, ILockable { #region Static methods. // ------------------------------------------------------------------ /// <summary> /// Load an object by a given ID. /// </summary> public static CustomerPerson GetByID( int id ) { DataRow row = AdoNetSqlHelper.ExecuteRow( "GetCustomerPersonByID", new AdoNetSqlParamCollection( AdoNetSqlParamCollection.CreateParameter( "@ID", id ) ) ); if ( row == null ) { return null; } else { CustomerPerson o = new CustomerPerson(); o.Load( row ); if ( o.IsEmpty ) { return null; } else { return o; } } } /// <summary> /// Load all for the given parent. /// </summary> public static CustomerPerson[] GetForCompany( CustomerCompany parentObject ) { DataTable table = AdoNetSqlHelper.ExecuteTable( "GetCustomerPersonByCustomerCompanyID", new AdoNetSqlParamCollection( AdoNetSqlParamCollection.CreateParameter( "@ID", parentObject.ID ) ) ); if ( table == null ) { return null; } else { ArrayList result = new ArrayList(); foreach ( DataRow row in table.Rows ) { CustomerPerson o = new CustomerPerson(); o.Load( row ); if ( !o.IsEmpty ) { result.Add( o ); } } if ( result.Count <= 0 ) { return null; } else { return (CustomerPerson[])result.ToArray( typeof( CustomerPerson ) ); } } } public static CustomerPerson GetByCrmReplicationUniqueID( Guid crmReplicationUniqueID ) { DataRow row = AdoNetSqlHelper.ExecuteRow( "GetCustomerPersonByCrmReplicationUniqueID", new AdoNetSqlParamCollection( AdoNetSqlParamCollection.CreateParameter( "@CrmReplicationUniqueID", crmReplicationUniqueID ) ) ); if ( row == null ) { return null; } else { CustomerPerson o = new CustomerPerson(); o.Load( row ); if ( o.IsEmpty ) { return null; } else { return o; } } } public static CustomerPerson GetForCrmPerson( Crm.CrmPerson crmPerson ) { DataRow row = AdoNetSqlHelper.ExecuteRow( "GetCustomerPersonFromCrmPerson", new AdoNetSqlParamCollection( AdoNetSqlParamCollection.CreateParameter( "@PersonID", crmPerson.ID ) ) ); if ( row == null ) { return null; } else { CustomerPerson o = new CustomerPerson(); o.Load( row ); if ( o.IsEmpty ) { return null; } else { return o; } } } // ------------------------------------------------------------------ #endregion #region Public methods. // ------------------------------------------------------------------ /// <summary> /// Constructor. /// </summary> public CustomerPerson() { } /// <summary> /// Use this version for displaying in lists etc. /// </summary> public override string ToString() { return string.Format( "{0}, {1}", lastName, firstName ).Replace( " ", " " ); } public void Store() { using ( AdoNetSqlUpdater upd = new AdoNetSqlUpdater( "GetCustomerPersonByID", new AdoNetSqlParamCollection( AdoNetSqlParamCollection.CreateParameter( "@ID", ID, DbType.Int32 ) ) ) ) { DataRow row; if ( upd.Row == null ) { row = upd.AddNewRow(); Store( row ); id = upd.Update( AdoNetSqlUpdater.IdentityControl.Get, "CustomerPersons" ); } else { row = upd.Row; Store( row ); upd.Update( AdoNetSqlUpdater.IdentityControl.DontGet ); } } } /// <summary> /// Delete from database. /// </summary> public void Delete() { AdoNetSqlHelper.ExecuteNonQuery( "DeleteCustomerPersonByID", new AdoNetSqlParamCollection( AdoNetSqlParamCollection.CreateParameter( "@ID", id ) ) ); id = 0; } // ------------------------------------------------------------------ #endregion #region Public properties. // ------------------------------------------------------------------ public string DetailedInformation { get { StringBuilder sb = new StringBuilder(); sb.AppendFormat( "{0}\r\n", this.Title ); sb.AppendFormat( "{0}, {1}\r\n", this.LastName, this.FirstName ); sb.AppendFormat( "{0}\r\n", this.Department ); sb.AppendFormat( "{0}\r\n", this.Position ); sb.AppendFormat( "{0}\r\n", this.Address1 ); sb.AppendFormat( "{0}\r\n", this.Address2 ); sb.AppendFormat( "{0}\r\n", this.EMail ); sb.AppendFormat( "{0} {1}\r\n", this.Zip, this.City ); return TrimAndRemoveEmptyLines( sb.ToString() ); } } /// <summary> /// Get the image key, depending on the state. /// </summary> public string SmallImageKey { get { return "PersonCard.gif"; } } /// <summary> /// Export as a v-card. /// </summary> public VCard VCard { get { VCard vcard = new VCard(); vcard.BusinessFax = this.Fax; vcard.BusinessTel = this.Phone; vcard.CellTelVoice = this.Mobile; vcard.FullName = string.Format( "{0} {1} {2}", this.Salutation, this.FirstName, this.LastName ).Trim(); vcard.HomeAddress = string.Format( "{0}\r\n{1}\r\n{2}\r\n{3}\r\n{4}\r\n{5}", this.Address1, this.Address2, this.Zip, this.City, this.State, this.Country ).Trim(); vcard.HomeTelFax = string.Empty; vcard.HomeTelVoice = string.Empty; vcard.Name = string.Format( "{0}, {1}", this.LastName, this.FirstName ).Trim(); vcard.PreferedInternetEmailAddress = this.EMail; CustomerCompany company = Company; if ( company == null ) { vcard.Organization = string.Empty; } else { vcard.Organization = company.VCard.FullName; } return vcard; } } public int CompanyID { get { return companyID; } set { companyID = value; } } public string Salutation { get { switch ( Gender ) { case GenderType.Female: return "Ms."; case GenderType.Male: return "Mr."; default: return string.Empty; } } } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public GenderType Gender { get { return gender; } set { gender = value; } } public string Address1 { get { return address1; } set { address1 = value; } } public string Address2 { get { return address2; } set { address2 = value; } } public string Zip { get { return zip; } set { zip = value; } } public string City { get { return city; } set { city = value; } } public string Country { get { return country; } set { country = value; } } public string State { get { return state; } set { state = value; } } public string Phone { get { return phone; } set { phone = value; } } public string Fax { get { return fax; } set { fax = value; } } public string Mobile { get { return mobile; } set { mobile = value; } } public string EMail { get { return email; } set { email = value; } } public string Www { get { return www; } set { www = value; } } public string Title { get { return title; } set { title = value; } } public CustomerCompany Company { get { return CustomerCompany.GetByID( companyID ); } } public string Department { get { return department; } set { department = value; } } public string Position { get { return position; } set { position = value; } } public Guid CrmReplicationUniqueID { get { return crmReplicationUniqueID; } set { crmReplicationUniqueID = value; } } // ------------------------------------------------------------------ #endregion #region Private variables. // ------------------------------------------------------------------ public enum GenderType { Unknown, Female, Male } private int companyID; private string firstName; private string lastName; private string address1; private string address2; private GenderType gender = GenderType.Unknown; private string zip; private string city; private string country; private string state; private string phone; private string fax; private string mobile; private string email; private string www; private string title; private string department; private string position; private Guid crmReplicationUniqueID = Guid.NewGuid(); // ------------------------------------------------------------------ #endregion #region Private routines. // ------------------------------------------------------------------ protected override void Load( DataRow row ) { base.Load( row ); if ( row != null ) { DBHelper.ReadField( out companyID, row["CompanyID"] ); DBHelper.ReadField( out firstName, row["FirstName"] ); DBHelper.ReadField( out lastName, row["LastName"] ); DBHelper.ReadField( out address1, row["Address1"] ); DBHelper.ReadField( out address2, row["Address2"] ); DBHelper.ReadField( out zip, row["Zip"] ); DBHelper.ReadField( out city, row["City"] ); DBHelper.ReadField( out country, row["Country"] ); DBHelper.ReadField( out state, row["State"] ); DBHelper.ReadField( out phone, row["Phone"] ); DBHelper.ReadField( out fax, row["Fax"] ); DBHelper.ReadField( out mobile, row["Mobile"] ); DBHelper.ReadField( out email, row["EMail"] ); DBHelper.ReadField( out www, row["Www"] ); DBHelper.ReadField( out title, row["Title"] ); DBHelper.ReadField( out department, row["Department"] ); DBHelper.ReadField( out position, row["Position"] ); DBHelper.ReadField( out crmReplicationUniqueID, row["crmReplicationUniqueID"] ); string gender; DBHelper.ReadField( out gender, row["Gender"] ); this.gender = (GenderType)Enum.Parse( typeof( GenderType ), gender, true ); } } protected override void Store( DataRow row ) { base.Store( row ); if ( row != null ) { row["CompanyID"] = DBHelper.WriteField( companyID ); row["FirstName"] = DBHelper.WriteField( firstName ); row["LastName"] = DBHelper.WriteField( lastName ); row["Gender"] = DBHelper.WriteField( gender.ToString() ); row["Address1"] = DBHelper.WriteField( address1 ); row["Address2"] = DBHelper.WriteField( address2 ); row["Zip"] = DBHelper.WriteField( zip ); row["City"] = DBHelper.WriteField( city ); row["Country"] = DBHelper.WriteField( country ); row["State"] = DBHelper.WriteField( state ); row["Phone"] = DBHelper.WriteField( phone ); row["Fax"] = DBHelper.WriteField( fax ); row["Mobile"] = DBHelper.WriteField( mobile ); row["EMail"] = DBHelper.WriteField( email ); row["Www"] = DBHelper.WriteField( www ); row["title"] = DBHelper.WriteField( title ); row["Department"] = DBHelper.WriteField( department ); row["Position"] = DBHelper.WriteField( position ); row["crmReplicationUniqueID"] = DBHelper.WriteField( crmReplicationUniqueID ); } } // ------------------------------------------------------------------ #endregion #region ILockable Members public LockGuard Lock() { return new LockGuard( GetType(), ID ); } #endregion } ///////////////////////////////////////////////////////////////////////// }
Markdown
UTF-8
10,271
3.296875
3
[ "MIT" ]
permissive
I grew up in New York City, between Harlem and the Bronx. Growing up as a boy, we were taught that men had to be tough, had to be strong, had to be courageous, dominating -- no pain, no emotions, with the exception of anger -- and definitely no fear; that men are in charge, which means women are not; that men lead, and you should just follow and do what we say; that men are superior; women are inferior; that men are strong; women are weak; that women are of less value, property of men, and objects, particularly sexual objects. I&#39;ve later come to know that to be the collective socialization of men, better known as the &quot;man box.&quot; See this man box has in it all the ingredients of how we define what it means to be a man. Now I also want to say, without a doubt, there are some wonderful, wonderful, absolutely wonderful things about being a man. But at the same time, there&#39;s some stuff that&#39;s just straight up twisted, and we really need to begin to challenge, look at it and really get in the process of deconstructing, redefining, what we come to know as manhood. This is my two at home, Kendall and Jay. They&#39;re 11 and 12. Kendall&#39;s 15 months older than Jay. There was a period of time when my wife -- her name is Tammie -- and I, we just got real busy and whip, bam, boom: Kendall and Jay. (Laughter) And when they were about five and six, four and five, Jay could come to me, come to me crying. It didn&#39;t matter what she was crying about, she could get on my knee, she could snot my sleeve up, just cry, cry it out. Daddy&#39;s got you. That&#39;s all that&#39;s important. Now Kendall on the other hand -- and like I said, he&#39;s only 15 months older than her -- he&#39;d come to me crying, it&#39;s like as soon as I would hear him cry, a clock would go off. I would give the boy probably about 30 seconds, which means, by the time he got to me, I was already saying things like, &quot;Why are you crying? Hold your head up. Look at me. Explain to me what&#39;s wrong. Tell me what&#39;s wrong. I can&#39;t understand you. Why are you crying?&quot; And out of my own frustration of my role and responsibility of building him up as a man to fit into these guidelines and these structures that are defining this man box, I would find myself saying things like, &quot;Just go in your room. Just go on, go on in your room. Sit down, get yourself together and come back and talk to me when you can talk to me like a --&quot; what? (Audience: Man.) Like a man. And he&#39;s five years old. And as I grow in life, I would say to myself, &quot;My God, what&#39;s wrong with me? What am I doing? Why would I do this?&quot; And I think back. I think back to my father. There was a time in my life where we had a very troubled experience in our family. My brother, Henry, he died tragically when we were teenagers. We lived in New York City, as I said. We lived in the Bronx at the time, and the burial was in a place called Long Island, it was about two hours outside of the city. And as we were preparing to come back from the burial, the cars stopped at the bathroom to let folks take care of themselves before the long ride back to the city. And the limousine empties out. My mother, my sister, my auntie, they all get out, but my father and I stayed in the limousine, and no sooner than the women got out, he burst out crying. He didn&#39;t want cry in front of me, but he knew he wasn&#39;t going to make it back to the city, and it was better me than to allow himself to express these feelings and emotions in front of the women. And this is a man who, 10 minutes ago, had just put his teenage son in the ground -- something I just can&#39;t even imagine. The thing that sticks with me the most is that he was apologizing to me for crying in front of me, and at the same time, he was also giving me props, lifting me up, for not crying. I come to also look at this as this fear that we have as men, this fear that just has us paralyzed, holding us hostage to this man box. I can remember speaking to a 12-year-old boy, a football player, and I asked him, I said, &quot;How would you feel if, in front of all the players, your coach told you you were playing like a girl?&quot; Now I expected him to say something like, I&#39;d be sad; I&#39;d be mad; I&#39;d be angry, or something like that. No, the boy said to me -- the boy said to me, &quot;It would destroy me.&quot; And I said to myself, &quot;God, if it would destroy him to be called a girl, what are we then teaching him about girls?&quot; (Applause) It took me back to a time when I was about 12 years old. I grew up in tenement buildings in the inner city. At this time we&#39;re living in the Bronx, and in the building next to where I lived there was a guy named Johnny. He was about 16 years old, and we were all about 12 years old -- younger guys. And he was hanging out with all us younger guys. And this guy, he was up to a lot of no good. He was the kind of kid who parents would have to wonder, &quot;What is this 16-year-old boy doing with these 12-year-old boys?&quot; And he did spend a lot of time up to no good. He was a troubled kid. His mother had died from a heroin overdose. He was being raised by his grandmother. His father wasn&#39;t on the set. His grandmother had two jobs. He was home alone a lot. But I&#39;ve got to tell you, we young guys, we looked up to this dude, man. He was cool. He was fine. That&#39;s what the sisters said, &quot;He was fine.&quot; He was having sex. We all looked up to him. So one day, I&#39;m out in front of the house doing something -- just playing around, doing something -- I don&#39;t know what. He looks out his window; he calls me upstairs; he said, &quot;Hey Anthony.&quot; They called me Anthony growing up as a kid. &quot;Hey Anthony, come on upstairs.&quot; Johnny call, you go. So I run right upstairs. As he opens the door, he says to me, &quot;Do you want some?&quot; Now I immediately knew what he meant. Because for me growing up at that time, and our relationship with this man box, &quot;Do you want some?&quot; meant one of two things: sex or drugs -- and we weren&#39;t doing drugs. Now my box, my card, my man box card, was immediately in jeopardy. Two things: One, I never had sex. We don&#39;t talk about that as men. You only tell your dearest, closest friend, sworn to secrecy for life, the first time you had sex. For everybody else, we go around like we&#39;ve been having sex since we were two. There ain&#39;t no first time. (Laughter) The other thing I couldn&#39;t tell him is that I didn&#39;t want any. That&#39;s even worse. We&#39;re supposed to always be on the prowl. Women are objects, especially sexual objects. Anyway, so I couldn&#39;t tell him any of that. So, like my mother would say, make a long story short, I just simply said to Johnny, &quot;Yes.&quot; He told me to go in his room. I go in his room. On his bed is a girl from the neighborhood named Sheila. She&#39;s 16 years old. She&#39;s nude. She&#39;s what I know today to be mentally ill, higher-functioning at times than others. We had a whole choice of inappropriate names for her. Anyway, Johnny had just gotten through having sex with her. Well actually, he raped her, but he would say he had sex with her. Because, while Sheila never said no, she also never said yes. So he was offering me the opportunity to do the same. So when I go in the room, I close the door. Folks, I&#39;m petrified. I stand with my back to the door so Johnny can&#39;t bust in the room and see that I&#39;m not doing anything, and I stand there long enough that I could have actually done something. So now I&#39;m no longer trying to figure out what I&#39;m going to do; I&#39;m trying to figure out how I&#39;m going to get out of this room. So in my 12 years of wisdom, I zip my pants down, I walk out into the room, and lo and behold to me, while I was in the room with Sheila, Johnny was back at the window calling guys up. So now there&#39;s a living room full of guys. It was like the waiting room in the doctor&#39;s office. And they asked me how was it, and I say to them, &quot;It was good,&quot; and I zip my pants up in front of them, and I head for the door. Now I say this all with remorse, and I was feeling a tremendous amount of remorse at that time, but I was conflicted, because, while I was feeling remorse, I was excited, because I didn&#39;t get caught. But I knew I felt bad about what was happening. This fear, getting outside the man box, totally enveloped me. It was way more important to me, about me and my man box card than about Sheila and what was happening to her. See collectively, we as men are taught to have less value in women, to view them as property and the objects of men. We see that as an equation that equals violence against women. We as men, good men, the large majority of men, we operate on the foundation of this whole collective socialization. We kind of see ourselves separate, but we&#39;re very much a part of it. You see, we have to come to understand that less value, property and objectification is the foundation and the violence can&#39;t happen without it. So we&#39;re very much a part of the solution as well as the problem. The center for disease control says that men&#39;s violence against women is at epidemic proportions, is the number one health concern for women in this country and abroad. So quickly, I&#39;d like to just say, this is the love of my life, my daughter Jay. The world I envision for her -- how do I want men to be acting and behaving? I need you on board. I need you with me. I need you working with me and me working with you on how we raise our sons and teach them to be men -- that it&#39;s okay to not be dominating, that it&#39;s okay to have feelings and emotions, that it&#39;s okay to promote equality, that it&#39;s okay to have women who are just friends and that&#39;s it, that it&#39;s okay to be whole, that my liberation as a man is tied to your liberation as a woman. (Applause) I remember asking a nine-year-old boy, I asked a nine-year-old boy, &quot;What would life be like for you, if you didn&#39;t have to adhere to this man box?&quot; He said to me, &quot;I would be free.&quot; Thank you folks. (Applause)
Java
UTF-8
15,626
1.867188
2
[]
no_license
package com.eray.thjw.produce.control; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.eray.thjw.annotation.Privilege; import com.eray.thjw.control.BaseController; import com.eray.thjw.exception.BusinessException; import com.eray.thjw.produce.po.MonitoringCurrent; import com.eray.thjw.produce.po.MonitoringObject; import com.eray.thjw.produce.po.MonitoringWorkpackage; import com.eray.thjw.produce.po.Workpackage; import com.eray.thjw.produce.service.MaintenanceMonitoringService; import com.eray.thjw.project2.po.EngineeringOrder; import com.eray.thjw.util.Utils; import enu.project2.MaintenanceProjectTypeEnum; /** * @Description 飞机维修监控控制层 * @CreateTime 2017-9-14 上午10:00:27 * @CreateBy 刘兵 */ @Controller @RequestMapping("/produce/maintenance/monitoring") public class MaintenanceMonitoringController extends BaseController{ @Resource private MaintenanceMonitoringService maintenanceMonitoringService; /** * @Description 跳转至飞机维修监控 * @CreateTime 2017-9-14 上午10:02:50 * @CreateBy 刘兵 * @return */ @Privilege(code="produce:maintenance:monitoring:main") @RequestMapping(value = "main", method = RequestMethod.GET) public ModelAndView main(){ Map<String, Object> model = new HashMap<String, Object>(); model.put("maintenanceProjectTypeEnum", MaintenanceProjectTypeEnum.enumToListMap());//维修项目类型枚举 return new ModelAndView("produce/maintenancemonitoring/maintenance_monitoring_main", model); } /** * @Description 跳转到航材工具需求清单 * @CreateTime 2017-9-13 下午2:07:09 * @CreateBy 刘兵 * @return 页面视图 */ @RequestMapping(value = "material/tool/detail", method = RequestMethod.GET) public ModelAndView project() { return new ModelAndView("common/produce/material_tool_require_detail_view"); } /** * @Description 保存监控 * @CreateTime 2017-10-12 上午10:41:24 * @CreateBy 刘兵 * @param monitoringObject 监控对象 * @return String * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main") @ResponseBody @RequestMapping(value = "save", method = RequestMethod.POST) public String save(@RequestBody MonitoringObject monitoringObject) throws BusinessException{ try { return maintenanceMonitoringService.save(monitoringObject); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("保存监控失败!",e); } } /** * @Description 保存选中的待组包的监控项目 * @CreateTime 2017-10-13 下午5:21:53 * @CreateBy 刘兵 * @param monitoringObject 监控对象 * @return int 已选中数量 * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main:01") @ResponseBody @RequestMapping(value = "saveChecked", method = RequestMethod.POST) public int saveChecked(@RequestBody MonitoringObject monitoringObject) throws BusinessException{ try { return maintenanceMonitoringService.saveChecked(monitoringObject); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("保存选中的待组包的监控项目失败!",e); } } /** * @Description 移除选中的待组包的监控项目 * @CreateTime 2017-10-13 下午5:21:53 * @CreateBy 刘兵 * @param monitoringObject 监控对象 * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main:02") @ResponseBody @RequestMapping(value = "deleteChecked", method = RequestMethod.POST) public void deleteChecked(@RequestBody MonitoringObject monitoringObject) throws BusinessException{ try { maintenanceMonitoringService.deleteChecked(monitoringObject); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("移除选中的待组包的监控项目失败!",e); } } /** * @Description 组包 * @CreateTime 2017-10-16 下午1:59:51 * @CreateBy 刘兵 * @param workpackage 工包135 * @return int 预组包数量 * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main:03") @ResponseBody @RequestMapping(value = "addWorkpackage", method = RequestMethod.POST) public int addWorkpackage(@RequestBody Workpackage workpackage) throws BusinessException{ try { return maintenanceMonitoringService.addWorkpackage(workpackage); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("组包失败!",e); } } /** * @Description 添加到已有工包 * @CreateTime 2017-10-16 下午1:59:51 * @CreateBy 刘兵 * @param workpackage 工包135 * @return int 预组包数量 * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main:03") @ResponseBody @RequestMapping(value = "add2WorkPackage", method = RequestMethod.POST) public int add2WorkPackage(@RequestBody Workpackage workpackage) throws BusinessException{ try { return maintenanceMonitoringService.add2WorkPackage(workpackage); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("添加到已有工包失败!",e); } } /** * @Description 删除预组包 * @CreateTime 2017-10-17 上午11:15:15 * @CreateBy 刘兵 * @param id 工包id * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main:05") @ResponseBody @RequestMapping(value = "deletePackage", method = RequestMethod.POST) public void deletePackage(String id) throws BusinessException{ try { maintenanceMonitoringService.deletePackage(id); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("删除预组包失败!",e); } } /** * @Description 提交预组包 * @CreateTime 2017-10-17 上午11:15:15 * @CreateBy 刘兵 * @param id 工包id * @return int 预组包数量 * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main") @ResponseBody @RequestMapping(value = "submitPackage", method = RequestMethod.POST) public int submitPackage(String id) throws BusinessException{ try { return maintenanceMonitoringService.doSubmitPackage(id); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("提交预组包失败!",e); } } /** * @Description 删除工包下工单 * @CreateTime 2017-10-18 上午10:35:33 * @CreateBy 刘兵 * @param workpackage 工包135 * @throws BusinessException */ @Privilege(code="produce:maintenance:monitoring:main:04") @ResponseBody @RequestMapping(value = "deleteWorkOrder4WorkPackage", method = RequestMethod.POST) public void deleteWorkOrder4WorkPackage(@RequestBody Workpackage workpackage) throws BusinessException{ try { maintenanceMonitoringService.deleteWorkOrder4WorkPackage(workpackage); } catch (BusinessException e) { throw e; } catch (Exception e) { throw new BusinessException("删除工包下工单失败!",e); } } /** * @Description 根据飞机注册号、机构代码获取已选中的数量 * @CreateTime 2017-10-14 下午2:47:44 * @CreateBy 刘兵 * @param fjzch 飞机注册号 * @param dprtcode 机构代码 * @return int 已选中数量 * @throws BusinessException */ @ResponseBody @RequestMapping(value = "getCheckCount",method={RequestMethod.POST,RequestMethod.GET}) public int getCheckCount(String fjzch, String dprtcode) throws BusinessException { try { return maintenanceMonitoringService.getCheckCount(fjzch, dprtcode); } catch (Exception e) { throw new BusinessException("查询已选中的数量失败!",e); } } /** * @Description 根据飞机注册号、机构代码获取预组包数量 * @CreateTime 2017-10-16 下午3:18:21 * @CreateBy 刘兵 * @param fjzch 飞机注册号 * @param dprtcode 机构代码 * @return int 预组包数量 * @throws BusinessException */ @ResponseBody @RequestMapping(value = "getBurstificationCount",method={RequestMethod.POST,RequestMethod.GET}) public int getBurstificationCount(String fjzch, String dprtcode) throws BusinessException { try { return maintenanceMonitoringService.getBurstificationCount(fjzch, dprtcode); } catch (Exception e) { throw new BusinessException("查询预组包数量失败!",e); } } /** * @Description 根据查询条件分页查询当前监控数据(飞机维修项目监控信息) * @CreateTime 2017-9-25 下午3:17:26 * @CreateBy 刘兵 * @param monitoringCurrent 当前监控数据 * @return Map<String, Object> 页面数据 * @throws BusinessException */ @ResponseBody @RequestMapping(value = "queryAllPageMaintenanceList", method = RequestMethod.POST) public Map<String, Object> queryAllPageMaintenanceList(@RequestBody MonitoringCurrent monitoringCurrent)throws BusinessException { try { return maintenanceMonitoringService.queryAllPageMaintenanceList(monitoringCurrent); } catch (Exception e) { throw new BusinessException("当前监控数据查询失败!",e); } } /** * @Description 根据查询条件查询维修清单 * @CreateTime 2017-10-28 下午3:38:39 * @CreateBy 刘兵 * @param monitoringCurrent 当前监控数据 * @return Map<String, Object> 页面数据 * @throws BusinessException */ @ResponseBody @RequestMapping(value = "queryPackageMaintenanceDetailList", method = RequestMethod.POST) public Map<String, Object> queryPackageMaintenanceDetailList(@RequestBody MonitoringCurrent monitoringCurrent)throws BusinessException { try { return maintenanceMonitoringService.queryPackageMaintenanceDetailList(monitoringCurrent); } catch (Exception e) { throw new BusinessException("当前监控数据查询失败!",e); } } /** * @Description 根据查询条件分页查询当前监控数据(EO监控信息) * @CreateTime 2017-9-25 下午3:17:26 * @CreateBy 刘兵 * @param monitoringCurrent 当前监控数据 * @return Map<String, Object> 页面数据 * @throws BusinessException */ @ResponseBody @RequestMapping(value = "queryAllPageEOList", method = RequestMethod.POST) public Map<String, Object> queryAllPageEOList(@RequestBody MonitoringCurrent monitoringCurrent)throws BusinessException { try { return maintenanceMonitoringService.queryAllPageEOList(monitoringCurrent); } catch (Exception e) { throw new BusinessException("当前监控数据查询失败!",e); } } /** * @Description 根据查询条件分页查询当前监控数据(生产指令监控信息) * @CreateTime 2018-5-8 下午2:49:06 * @CreateBy 刘兵 * @param monitoringCurrent 当前监控数据 * @return Map<String, Object> 页面数据 * @throws BusinessException */ @ResponseBody @RequestMapping(value = "queryAllPagePOList", method = RequestMethod.POST) public Map<String, Object> queryAllPagePOList(@RequestBody MonitoringCurrent monitoringCurrent)throws BusinessException { try { return maintenanceMonitoringService.queryAllPagePOList(monitoringCurrent); } catch (Exception e) { throw new BusinessException("当前监控数据查询失败!",e); } } /** * @Description 根据条件查询已选中的监控数据列表 * @CreateTime 2017-10-14 下午4:05:52 * @CreateBy 刘兵 * @param monitoringWorkpackage 待组包的监控项目 * @return List<MonitoringWorkpackage> 已选中的监控数据集合 * @throws BusinessException */ @ResponseBody @RequestMapping(value = "queryCheckedList", method = RequestMethod.POST) public List<Map<String, Object>> queryCheckedList(@RequestBody MonitoringWorkpackage monitoringWorkpackage) throws BusinessException { try { List<MonitoringWorkpackage> mList = maintenanceMonitoringService.queryCheckedList(monitoringWorkpackage); List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>(); for (MonitoringWorkpackage mWorkpackage : mList) { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("id", mWorkpackage.getId()); resultMap.put("lx", mWorkpackage.getLx()); resultMap.put("dprtcode", mWorkpackage.getDprtcode()); resultMap.put("gbid", mWorkpackage.getGbid()); resultMap.put("fjzch", mWorkpackage.getFjzch()); resultMap.put("jksjgdid", mWorkpackage.getJksjgdid()); resultMap.put("paramsMap", mWorkpackage.getParamsMap()); resultList.add(resultMap); } return resultList; } catch (Exception e) { throw new BusinessException("获取数据失败", e); } } /** * @Description 根据查询条件分页查询当前监控数据(EO监控信息)(导出) * @CreateTime 2017-9-25 下午3:17:26 * @CreateBy 刘兵 * @param paramjson 当前监控数据参数 * @return String 页面数据 * @throws BusinessException */ @RequestMapping(value = "eoMonitoring.xls", method = RequestMethod.GET) public String exportExcelEO(String paramjson, HttpServletRequest request, Model model) throws BusinessException { try { paramjson = new String(paramjson.getBytes("iso-8859-1"),"utf-8"); MonitoringCurrent monitoringCurrent = Utils.Json.toObject(paramjson, MonitoringCurrent.class); List<MonitoringCurrent> list = maintenanceMonitoringService.doExportExcelEO(monitoringCurrent); JRDataSource jrDataSource = new JRBeanCollectionDataSource(list); model.addAttribute("jrMainDataSource", jrDataSource); return outReport("xls", "common", "mteo", model); } catch (Exception e) { throw new BusinessException("报表预览或导出失败", e); } } /** * @Description 根据查询条件分页查询当前监控数据(飞机维修项目监控信息)(导出) * @CreateTime 2017-9-25 下午3:17:26 * @CreateBy 刘兵 * @param paramjson 当前监控数据参数 * @return String 页面数据 * @throws BusinessException */ @RequestMapping(value = "maintenanceMonitoring.xls", method = RequestMethod.GET) public String exportExcelMt(String paramjson, HttpServletRequest request, Model model) throws BusinessException { try { paramjson = new String(paramjson.getBytes("iso-8859-1"),"utf-8"); MonitoringCurrent monitoringCurrent = Utils.Json.toObject(paramjson, MonitoringCurrent.class); List<MonitoringCurrent> list = maintenanceMonitoringService.exportExcelMt(monitoringCurrent); JRDataSource jrDataSource = new JRBeanCollectionDataSource(list); model.addAttribute("jrMainDataSource", jrDataSource); return outReport("xls", "common", "maintenanceMonitor", model); } catch (Exception e) { throw new BusinessException("报表预览或导出失败", e); } } }
Java
UTF-8
1,417
2.015625
2
[]
no_license
package dk.au.cs.tapas.cfg.node; import com.intellij.psi.PsiElement; import dk.au.cs.tapas.lattice.HeapLocation; import dk.au.cs.tapas.lattice.TemporaryHeapVariableName; import dk.au.cs.tapas.lattice.TemporaryVariableName; import java.util.Set; /** * Created by budde on 4/27/15. */ public class ArrayReadLocationSetNodeImpl extends NodeImpl implements ArrayReadLocationSetNode { private final TemporaryVariableName indexName; private final TemporaryHeapVariableName locations; private TemporaryHeapVariableName valueHeapLocationSet; public ArrayReadLocationSetNodeImpl(Node successor, TemporaryVariableName indexName, TemporaryHeapVariableName valueHeapLocationSet, TemporaryHeapVariableName targetLocations, PsiElement psiElement) { super(successor, psiElement); this.valueHeapLocationSet = valueHeapLocationSet; this.locations = targetLocations; this.indexName = indexName; } @Override public TemporaryVariableName getIndexName() { return indexName; } @Override public TemporaryHeapVariableName getValueTempHeapName() { return valueHeapLocationSet; } @Override public TemporaryHeapVariableName getTargetTempHeapName() { return locations; } @Override public String toString() { return "array_read(" + valueHeapLocationSet + ", " + locations + ", " + indexName + ')'; } }
Swift
UTF-8
1,354
2.8125
3
[ "MIT" ]
permissive
// // DefaultTheme.swift // dopravaBrno // // Created by Thành Đỗ Long on 07/04/2019. // Copyright © 2019 Thành Đỗ Long. All rights reserved. // import Foundation import UIKit struct DefaultTheme: ThemeStrategy { var fonts: FontScheme var colours: ColourScheme var barStyle: UIBarStyle = .default var keyboardAppearance: UIKeyboardAppearance = .default init() { self.colours = DefaultColours() self.fonts = DefaultFonts() } init(colours: ColourScheme, fonts: FontScheme) { self.colours = colours self.fonts = fonts } } struct DefaultColours: ColourScheme { let mainColor: UIColor = UIColor(hexString: "#FF0033") let secondaryColor: UIColor = .orange let backgroundColor: UIColor = .white let primaryTextColor: UIColor = .black let primaryTextColorVariant: UIColor = .darkGray let secondaryTextColor: UIColor = .orange } struct DefaultFonts: FontScheme { let titleFont: UIFont = UIFont(name: "Montserrat-SemiBold", size: 17)! let subtitleFont: UIFont = UIFont(name: "Montserrat-Light", size: 15)! let bodyFont: UIFont = UIFont(name: "Montserrat-Regular", size: 15)! let tapBarFont: UIFont = UIFont(name: "Montserrat-Regular", size: 10)! let navigationBarFont: UIFont = UIFont(name: "Montserrat-Regular", size: 29)! }
Java
UTF-8
48,523
1.953125
2
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "UPL-1.0" ]
permissive
package org.clyze.doop.soot; import com.google.common.collect.Lists; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.clyze.doop.common.*; import org.clyze.utils.TypeUtils; import soot.*; import soot.jimple.*; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.typing.fast.BottomType; import soot.tagkit.*; import soot.util.backend.ASMBackendUtils; import static org.clyze.doop.common.JavaRepresentation.*; import static org.clyze.doop.common.PredicateFile.*; /** * FactWriter determines the format of a fact and adds it to a * database. */ class FactWriter extends JavaFactWriter { final Representation _rep; private final Map<String, Type> _varTypeMap = new ConcurrentHashMap<>(); private final Phantoms phantoms; private final Collection<Object> seenPhantoms = new HashSet<>(); FactWriter(Database db, SootParameters params, Representation rep, Phantoms phantoms) { super(db, params); this._rep = rep; this.phantoms = phantoms; } public String methodSig(SootMethod m, String methodRaw) { if (methodRaw == null) methodRaw = _rep.signature(m); return methodRaw; // hashMethodNameIfLong(methodRaw); } private static String getAnnotationType(AnnotationTag aTag) { return TypeUtils.raiseTypeId(aTag.getType()); } String writeMethod(SootMethod m) { String methodRaw = _rep.signature(m); String methodId = methodSig(m, methodRaw); String arity = Integer.toString(m.getParameterCount()); _db.add(STRING_RAW, methodId, methodRaw); writeMethod(methodId, _rep.simpleName(m), Representation.params(m), writeType(m.getDeclaringClass()), writeType(m.getReturnType()), ASMBackendUtils.toTypeDesc(m.makeRef()), arity); if (m.getTag("VisibilityAnnotationTag") != null) { VisibilityAnnotationTag vTag = (VisibilityAnnotationTag) m.getTag("VisibilityAnnotationTag"); for (AnnotationTag aTag : vTag.getAnnotations()) { writeMethodAnnotation(methodId, getAnnotationType(aTag)); writeAnnotationElements("method", methodId, null, aTag.getElems()); } } if (m.getTag("VisibilityParameterAnnotationTag") != null) { VisibilityParameterAnnotationTag vTag = (VisibilityParameterAnnotationTag) m.getTag("VisibilityParameterAnnotationTag"); ArrayList<VisibilityAnnotationTag> annList = vTag.getVisibilityAnnotations(); for (int i = 0; i < annList.size(); i++) if (annList.get(i) != null) for (AnnotationTag aTag : annList.get(i).getAnnotations()) { String paramIdx = str(i); _db.add(PARAM_ANNOTATION, methodId, paramIdx, getAnnotationType(aTag)); String paramId = methodId + "::parameter#" + paramIdx; writeAnnotationElements("param", paramId, null, aTag.getElems()); } } return methodId; } void writeAndroidEntryPoint(SootMethod m) { _db.add(ANDROID_ENTRY_POINT, _rep.signature(m)); } void writeClassOrInterfaceType(SootClass c) { String classStr = c.getName(); if (c.isPhantom()) { phantoms.reportPhantom("Interface", classStr); writePhantomType(c); } _db.add(c.isInterface() ? INTERFACE_TYPE : CLASS_TYPE, classStr); writeClassHeap(Representation.classConstant(c), classStr); if (c.getTag("VisibilityAnnotationTag") != null) { VisibilityAnnotationTag vTag = (VisibilityAnnotationTag) c.getTag("VisibilityAnnotationTag"); for (AnnotationTag aTag : vTag.getAnnotations()) { _db.add(TYPE_ANNOTATION, classStr, getAnnotationType(aTag)); writeAnnotationElements("type", classStr, null, aTag.getElems()); } } _db.add(TYPE_SIMPLENAME, classStr, c.getShortName()); } /** * Write an annotation element. Annotation elements may be nested, so we * have to generate facts that describe their structure as well. * * @param targetType the type of the language construct that is annotated (e.g., "method") * @param target the language construct that is annotated * @param parentId the ID of the parent of the annotation (or "0" for root) * @param thisId the annotation ID (e.g., an index to distinguish from siblings) * @param ae the annotation element */ private void writeAnnotationElement(String targetType, String target, String parentId, String thisId, AnnotationElem ae) { if (ae instanceof AnnotationArrayElem) { writeAnnotationElements(targetType, target, thisId, ((AnnotationArrayElem)ae).getValues()); } else if (ae instanceof AnnotationEnumElem) { AnnotationEnumElem enumElem = (AnnotationEnumElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, enumElem.getName(), TypeUtils.raiseTypeId(enumElem.getTypeName()), enumElem.getConstantName()); } else if (ae instanceof AnnotationStringElem) { AnnotationStringElem ase = (AnnotationStringElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, ase.getName(), ase.getValue(), "-"); } else if (ae instanceof AnnotationBooleanElem) { AnnotationBooleanElem abe = (AnnotationBooleanElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, abe.getName(), String.valueOf(abe.getValue()), "-"); } else if (ae instanceof AnnotationFloatElem) { AnnotationFloatElem afe = (AnnotationFloatElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, afe.getName(), String.valueOf(afe.getValue()), "-"); } else if (ae instanceof AnnotationLongElem) { AnnotationLongElem ale = (AnnotationLongElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, ale.getName(), String.valueOf(ale.getValue()), "-"); } else if (ae instanceof AnnotationDoubleElem) { AnnotationDoubleElem ade = (AnnotationDoubleElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, ade.getName(), String.valueOf(ade.getValue()), "-"); } else if (ae instanceof AnnotationIntElem) { AnnotationIntElem aie = (AnnotationIntElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, aie.getName(), str(aie.getValue()), "-"); } else if (ae instanceof AnnotationClassElem) { AnnotationClassElem ace = (AnnotationClassElem)ae; writeAnnotationElement(targetType, target, parentId, thisId, ace.getName(), TypeUtils.raiseTypeId(ace.getDesc()), "-"); } else if (ae instanceof AnnotationAnnotationElem) { AnnotationAnnotationElem aae = (AnnotationAnnotationElem)ae; // Write a dummy annotation node, followed by its contents. writeAnnotationElement(targetType, target, parentId, thisId, "INNER-ANNOTATION", "-", null); writeAnnotationElements(targetType, target, thisId, aae.getValue().getElems()); } else System.err.println("WARNING: unknown annotation element, type: '" + ae.getClass() + "', name: '" + ae.getName() + "'"); } // Helper method used by writeAnnotationElement(). private void writeAnnotationElements(String targetType, String target, String parentId, Iterable<AnnotationElem> elements) { if (parentId == null) parentId = "0"; int id = 0; for (AnnotationElem ae : elements) writeAnnotationElement(targetType, target, parentId, parentId + "." + (id++), ae); } void writeDirectSuperclass(SootClass sub, SootClass sup) { _db.add(DIRECT_SUPER_CLASS, writeType(sub), writeType(sup)); } void writeDirectSuperinterface(SootClass clazz, SootClass iface) { _db.add(DIRECT_SUPER_IFACE, writeType(clazz), writeType(iface)); } private String writeType(SootClass c) { // The type itself is already taken care of by writing the // SootClass declaration, so we don't actually write the type // here, and just return the string. return c.getName(); } private String writeType(Type t) { String result = t.toString(); if (t instanceof ArrayType) { Type componentType = ((ArrayType) t).getElementType(); writeArrayTypes(result, writeType(componentType)); } else if (t instanceof PrimType || t instanceof NullType || t instanceof RefType || t instanceof VoidType || t instanceof BottomType) { // taken care of by the standard facts } else throw new RuntimeException("Don't know what to do with type " + t); return result; } void writePhantomType(Type t) { phantoms.reportPhantom("Type", t.toString()); writePhantomType(writeType(t)); } private void writePhantomType(SootClass c) { writePhantomType(writeType(c)); } protected void writePhantomMethod(String sig) { phantoms.reportPhantom("Method", sig); super.writePhantomMethod(sig); } void writePhantomBasedMethod(String sig) { phantoms.reportPhantomSignature(sig); _db.add(PHANTOM_BASED_METHOD, sig); } void writeEnterMonitor(InstrInfo ii, Local var) { String methodId = ii.methodId; _db.add(ENTER_MONITOR, ii.insn, str(ii.index), _rep.local(methodId, var), methodId); } void writeExitMonitor(InstrInfo ii, Local var) { String methodId = ii.methodId; _db.add(EXIT_MONITOR, ii.insn, str(ii.index), _rep.local(methodId, var), methodId); } void writeAssignLocal(InstrInfo ii, Local to, Local from) { String methodId = ii.methodId; writeAssignLocal(ii.insn, ii.index, _rep.local(methodId, from), _rep.local(ii.methodId, to), methodId); } void writeAssignThisToLocal(InstrInfo ii, Local to) { String methodId = ii.methodId; writeAssignLocal(ii.insn, ii.index, _rep.thisVar(methodId), _rep.local(methodId, to), methodId); } void writeAssignLocal(InstrInfo ii, Local to, ParameterRef ref) { String methodId = ii.methodId; writeAssignLocal(ii.insn, ii.index, _rep.param(methodId, ref.getIndex()), _rep.local(methodId, to), methodId); } void writeAssignInvoke(SootMethod inMethod, Stmt stmt, InstrInfo ii, Local to, SessionCounter session) { String invokeInstructionId = writeInvoke(inMethod, stmt, ii, session); _db.add(ASSIGN_RETURN_VALUE, invokeInstructionId, _rep.local(ii.methodId, to)); } private void writeArraySize(InstrInfo ii, Value sizeVal, int pos, String heap) { if (sizeVal instanceof IntConstant) { IntConstant size = (IntConstant) sizeVal; _db.add(ARRAY_ALLOC_CONST_SIZE, ii.insn, str(pos), str(size.value)); if(size.value == 0) _db.add(EMPTY_ARRAY, heap); } else if (sizeVal instanceof Local) _db.add(ARRAY_ALLOC, ii.insn, str(pos), _rep.local(ii.methodId, (Local)sizeVal)); } void writeAssignHeapAllocation(Stmt stmt, InstrInfo ii, Local l, Value expr, SessionCounter session) { String methodId = ii.methodId; String heap = _rep.heapAlloc(methodId, expr, session); _db.add(NORMAL_HEAP, heap, writeType(expr.getType())); _db.add(ASSIGN_HEAP_ALLOC, ii.insn, str(ii.index), heap, _rep.local(methodId, l), methodId, ""+getLineNumberFromStmt(stmt)); if (expr instanceof NewArrayExpr) { NewArrayExpr newArray = (NewArrayExpr) expr; writeArraySize(ii, newArray.getSize(), 0, heap); } } private static int getLineNumberFromStmt(Stmt stmt) { LineNumberTag tag = (LineNumberTag) stmt.getTag("LineNumberTag"); return tag == null ? 0 : tag.getLineNumber(); } private Type getComponentType(ArrayType type) { // Soot calls the component type of an array type the "element // type", which is rather confusing, since in an array type // A[][][], the JVM Spec defines A to be the element type, and // A[][] is the component type. return type.getElementType(); } /** * NewMultiArray is slightly complicated because an array needs to * be allocated separately for every dimension of the array. */ void writeAssignNewMultiArrayExpr(Stmt stmt, InstrInfo ii, Local l, NewMultiArrayExpr expr, SessionCounter session) { writeAssignNewMultiArrayExprHelper(stmt, ii, l, _rep.local(ii.methodId, l), expr, (ArrayType) expr.getType(), session, 0); } private void writeAssignNewMultiArrayExprHelper(Stmt stmt, InstrInfo ii, Local l, String assignTo, NewMultiArrayExpr expr, ArrayType arrayType, SessionCounter session, int pos) { String methodId = ii.methodId; String heap = _rep.heapMultiArrayAlloc(methodId, /* expr, */ arrayType, session); _db.add(NORMAL_HEAP, heap, writeType(arrayType)); _db.add(ASSIGN_HEAP_ALLOC, ii.insn, str(ii.index), heap, assignTo, methodId, ""+getLineNumberFromStmt(stmt)); if (pos < expr.getSizeCount()) writeArraySize(ii, expr.getSize(pos), pos, heap); Type componentType = getComponentType(arrayType); if (componentType instanceof ArrayType) { String childAssignTo = _rep.newLocalIntermediate(methodId, l, session); writeAssignNewMultiArrayExprHelper(stmt, new InstrInfo(ii.methodId, "assign-new-multi-array", session), l, childAssignTo, expr, (ArrayType) componentType, session, pos+1); String storeInsn = ii.insn; _db.add(STORE_ARRAY_INDEX, storeInsn, str(ii.index), childAssignTo, assignTo, methodId); writeLocal(childAssignTo, writeType(componentType), methodId); _db.add(ARRAY_INSN_INDEX, storeInsn, childAssignTo); } } // The commented-out code below is what used to be in Doop2. It is not // equivalent to code in old Doop. I (YS) tried to have a more compatible // approach for comparison purposes. /* public void writeAssignNewMultiArrayExpr(SootMethod m, Stmt stmt, Local l, NewMultiArrayExpr expr, SessionCounter session) { // what is a normal object? String heap = _rep.heapAlloc(m, expr, session); _db.addInput("NormalObject", _db.asEntity(heap), writeType(expr.getType())); // local variable to assign the current array allocation to. String assignTo = _rep.local(m, l); Type type = (ArrayType) expr.getType(); int dimensions = 0; while(type instanceof ArrayType) { ArrayType arrayType = (ArrayType) type; // make sure we store the type writeType(type); type = getComponentType(arrayType); dimensions++; } Type elementType = type; int index = session.calcInstructionIndex(stmt); String rep = _rep.instruction(m, stmt, index); _db.addInput("AssignMultiArrayAllocation", _db.asEntity(rep), _db.asIntColumn(str(index)), _db.asEntity(heap), _db.asIntColumn(str(dimensions)), _db.asEntity(assignTo), _db.asEntity("Method", _rep.method(m))); // idea: do generate the heap allocations, but not the assignments // (to array indices). Do store the type of those heap allocations } */ void writeAssignStringConstant(Stmt stmt, InstrInfo ii, Local l, StringConstant s) { String constant = s.toString(); String content = constant.substring(1, constant.length() - 1); String heapId = writeStringConstant(content); String methodId = ii.methodId; _db.add(ASSIGN_HEAP_ALLOC, ii.insn, str(ii.index), heapId, _rep.local(methodId, l), methodId, ""+getLineNumberFromStmt(stmt)); } void writeAssignNull(InstrInfo ii, Local l) { String methodId = ii.methodId; _db.add(ASSIGN_NULL, ii.insn, str(ii.index), _rep.local(methodId, l), methodId); } void writeAssignNumConstant(InstrInfo ii, Local l, NumericConstant constant) { String methodId = ii.methodId; _db.add(ASSIGN_NUM_CONST, ii.insn, str(ii.index), constant.toString(), _rep.local(methodId, l), methodId); } private void writeAssignMethodHandleConstant(InstrInfo ii, Local l, MethodHandle constant) { String handleMethod = Representation.signature(constant.getMethodRef()); String heap = methodHandleConstant(handleMethod); SigInfo si = new SigInfo(constant.getMethodRef(), false); writeMethodHandleConstant(heap, handleMethod, si.retType, si.paramTypes, si.arity); String methodId = ii.methodId; _db.add(ASSIGN_HEAP_ALLOC, ii.insn, str(ii.index), heap, _rep.local(methodId, l), methodId, "0"); } private void writeAssignMethodTypeConstant(InstrInfo ii, Local l, DoopAddons.MethodType constant) { String retType = constant.getReturnType(); List<String> paramTypesList = constant.getParameterTypes(); int arity = paramTypesList.size(); String[] paramTypes = new String[arity]; paramTypes = paramTypesList.toArray(paramTypes); writeMethodTypeConstant(retType, paramTypes, null); String params = concatenate(paramTypes); String mt = "<method type (" + params + ")" + retType + ">"; String methodId = ii.methodId; _db.add(ASSIGN_HEAP_ALLOC, ii.insn, str(ii.index), mt, _rep.local(methodId, l), methodId, "0"); } void writeAssignClassConstant(InstrInfo ii, Local l, ClassConstant constant) { writeAssignClassConstant(ii, l, new ClassConstantInfo(constant)); } private void writeAssignClassConstant(InstrInfo ii, Local l, ClassConstantInfo info) { if (info.isMethodType) writeMethodTypeConstant(info.heap); else writeClassHeap(info.heap, info.actualType); // REVIEW: the class object is not explicitly written. Is this always ok? String methodId = ii.methodId; _db.add(ASSIGN_HEAP_ALLOC, ii.insn, str(ii.index), info.heap, _rep.local(methodId, l), methodId, "0"); } void writeAssignCast(InstrInfo ii, Local to, Local from, Type t) { String methodId = ii.methodId; _db.add(ASSIGN_CAST, ii.insn, str(ii.index), _rep.local(methodId, from), _rep.local(methodId, to), writeType(t), methodId); } void writeAssignCastNumericConstant(InstrInfo ii, Local to, NumericConstant constant, Type t) { String methodId = ii.methodId; String val = constant.toString(); if (constant instanceof ArithmeticConstant) writeNumConstantRawInt(val); _db.add(ASSIGN_CAST_NUM_CONST, ii.insn, str(ii.index), val, _rep.local(methodId, to), writeType(t), methodId); } void writeAssignCastNull(InstrInfo ii, Local to, Type t) { String methodId = ii.methodId; _db.add(ASSIGN_CAST_NULL, ii.insn, str(ii.index), _rep.local(methodId, to), writeType(t), methodId); } void writeStoreInstanceField(InstrInfo ii, SootField f, Local base, Local from) { writeInstanceField(ii, f, base, from, STORE_INST_FIELD); } void writeLoadInstanceField(InstrInfo ii, SootField f, Local base, Local to) { writeInstanceField(ii, f, base, to, LOAD_INST_FIELD); } private void writeInstanceField(InstrInfo ii, SootField f, Local base, Local var, PredicateFile storeOrLoadInstField) { String methodId = ii.methodId; String fieldId = writeField(f); if (fieldId != null) _db.add(storeOrLoadInstField, ii.insn, str(ii.index), _rep.local(methodId, var), _rep.local(methodId, base), fieldId, methodId); } void writeStoreStaticField(InstrInfo ii, SootField f, Local from) { writeStaticField(ii, f, from, STORE_STATIC_FIELD); } void writeLoadStaticField(InstrInfo ii, SootField f, Local to) { writeStaticField(ii, f, to, LOAD_STATIC_FIELD); } private void writeStaticField(InstrInfo ii, SootField f, Local var, PredicateFile staticFieldFacts) { String methodId = ii.methodId; String fieldId = writeField(f); if (fieldId != null) _db.add(staticFieldFacts, ii.insn, str(ii.index), _rep.local(methodId, var), fieldId, methodId); } void writeLoadArrayIndex(Stmt stmt, InstrInfo ii, Local base, Local to, Value arrIndex) { writeLoadOrStoreArrayIndex(stmt, ii, base, to, arrIndex, LOAD_ARRAY_INDEX); } void writeStoreArrayIndex(Stmt stmt, InstrInfo ii, Local base, Local from, Value arrIndex) { writeLoadOrStoreArrayIndex(stmt, ii, base, from, arrIndex, STORE_ARRAY_INDEX); } private void writeLoadOrStoreArrayIndex(Stmt stmt, InstrInfo ii, Local base, Local var, Value arrIndex, PredicateFile predicateFile) { String methodId = ii.methodId; String insn = ii.insn; _db.add(predicateFile, insn, str(ii.index), _rep.local(methodId, var), _rep.local(methodId, base), methodId); if (arrIndex instanceof Local) _db.add(ARRAY_INSN_INDEX, insn, _rep.local(methodId, (Local) arrIndex)); else if (arrIndex instanceof IntConstant) _db.add(ARRAY_NUM_INDEX, insn, str(((IntConstant) arrIndex).value)); else throw new RuntimeException("Cannot handle assignment: " + stmt + " (index: " + arrIndex.getClass() + ")"); } private void writeApplicationClass(SootClass application) { _db.add(APP_CLASS, writeType(application)); } String writeField(SootField f) { if (f == null) { System.err.println("WARNING: null field encountered."); return null; } String fieldId = _rep.signature(f); _db.add(FIELD_SIGNATURE, fieldId, writeType(f.getDeclaringClass()), Representation.simpleName(f), writeType(f.getType())); if (f.getTag("VisibilityAnnotationTag") != null) { VisibilityAnnotationTag vTag = (VisibilityAnnotationTag) f.getTag("VisibilityAnnotationTag"); for (AnnotationTag aTag : vTag.getAnnotations()) { _db.add(FIELD_ANNOTATION, fieldId, getAnnotationType(aTag)); writeAnnotationElements("field", fieldId, null, aTag.getElems()); } } return fieldId; } void writeFieldModifier(SootField f, String modifier) { String fieldId = _rep.signature(f); _db.add(FIELD_MODIFIER, modifier, fieldId); } void writeClassModifier(SootClass c, String modifier) { writeClassModifier(c.getName(), modifier); } void writeMethodModifier(String methodId, String modifier) { _db.add(METHOD_MODIFIER, modifier, methodId); } void writeReturn(InstrInfo ii, Local l) { String methodId = ii.methodId; _db.add(RETURN, ii.insn, str(ii.index), _rep.local(methodId, l), methodId); } void writeReturnVoid(InstrInfo ii) { _db.add(RETURN_VOID, ii.insn, str(ii.index), ii.methodId); } // The return var of native methods is exceptional, in that it does not // correspond to a return instruction. void writeNativeReturnVar(String methodId, Type returnType) { if (!(returnType instanceof VoidType)) { String var = _rep.nativeReturnVar(methodId); _db.add(NATIVE_RETURN_VAR, var, methodId); writeLocal(var, writeType(returnType), methodId); } } void writeGoto(GotoStmt stmt, InstrInfo ii, SessionCounter session) { Unit to = stmt.getTarget(); session.calcInstructionIndex(stmt); session.calcInstructionIndex(to); int indexTo = session.getInstructionIndex(to); _db.add(GOTO, ii.insn, str(ii.index), str(indexTo), ii.methodId); } /** * If */ void writeIf(IfStmt stmt, InstrInfo ii, SessionCounter session) { Unit to = stmt.getTarget(); // index was already computed earlier int index = ii.index; session.calcInstructionIndex(to); int indexTo = session.getInstructionIndex(to); String insn = ii.insn; String methodId = ii.methodId; writeIf(insn, index, indexTo, methodId); Value condStmt = stmt.getCondition(); if (condStmt instanceof ConditionExpr) { ConditionExpr condition = (ConditionExpr) condStmt; Local dummy = new JimpleLocal("tmp" + insn, BooleanType.v()); writeDummyIfVar(insn, _rep.local(methodId, dummy)); if (condition instanceof EqExpr) writeOperatorAt(insn, "=="); else if (condition instanceof NeExpr) writeOperatorAt(insn, "!="); else if (condition instanceof GeExpr) writeOperatorAt(insn, ">="); else if (condition instanceof GtExpr) writeOperatorAt(insn, ">"); else if (condition instanceof LeExpr) writeOperatorAt(insn, "<="); else if (condition instanceof LtExpr) writeOperatorAt(insn, "<"); if (condition.getOp1() instanceof Local) { Local op1 = (Local) condition.getOp1(); writeIfVar(insn, L_OP, _rep.local(methodId, op1)); } else if (condition.getOp1() instanceof NumericConstant) { NumericConstant op1 = (NumericConstant) condition.getOp1(); writeIfConstant(insn, L_OP, op1.toString()); } if (condition.getOp2() instanceof Local) { Local op2 = (Local) condition.getOp2(); writeIfVar(insn, R_OP, _rep.local(methodId, op2)); } else if (condition.getOp2() instanceof NumericConstant) { NumericConstant op2 = (NumericConstant)condition.getOp2(); writeIfConstant(insn, R_OP, op2.toString()); } } } void writeTableSwitch(TableSwitchStmt stmt, InstrInfo ii, SessionCounter session) { String methodId = ii.methodId; Value v = writeImmediate(stmt, ii, stmt.getKey(), null, session); if(!(v instanceof Local)) throw new RuntimeException("Unexpected key for TableSwitch statement " + v + " " + v.getClass()); Local l = (Local) v; String insn = ii.insn; _db.add(TABLE_SWITCH, insn, str(ii.index), _rep.local(methodId, l), methodId); for (int tgIndex = stmt.getLowIndex(), i = 0; tgIndex <= stmt.getHighIndex(); tgIndex++, i++) { session.calcInstructionIndex(stmt.getTarget(i)); int indexTo = session.getInstructionIndex(stmt.getTarget(i)); _db.add(TABLE_SWITCH_TARGET, insn, str(tgIndex), str(indexTo)); } session.calcInstructionIndex(stmt.getDefaultTarget()); int defaultIndex = session.getInstructionIndex(stmt.getDefaultTarget()); _db.add(TABLE_SWITCH_DEFAULT, insn, str(defaultIndex)); } void writeLookupSwitch(LookupSwitchStmt stmt, InstrInfo ii, SessionCounter session) { String methodId = ii.methodId; int stmtIndex = session.getInstructionIndex(stmt); Value v = writeImmediate(stmt, ii, stmt.getKey(), null, session); if(!(v instanceof Local)) throw new RuntimeException("Unexpected key for TableSwitch statement " + v + " " + v.getClass()); Local l = (Local) v; String insn = ii.insn; _db.add(LOOKUP_SWITCH, insn, str(stmtIndex), _rep.local(methodId, l), methodId); for (int i = 0, end = stmt.getTargetCount(); i < end; i++) { int tgIndex = stmt.getLookupValue(i); session.calcInstructionIndex(stmt.getTarget(i)); int indexTo = session.getInstructionIndex(stmt.getTarget(i)); _db.add(LOOKUP_SWITCH_TARGET, insn, str(tgIndex), str(indexTo)); } session.calcInstructionIndex(stmt.getDefaultTarget()); int defaultIndex = session.getInstructionIndex(stmt.getDefaultTarget()); _db.add(LOOKUP_SWITCH_DEFAULT, insn, str(defaultIndex)); } void writeUnsupported(Unit unit, InstrInfo ii, SessionCounter session) { int index = session.calcInstructionIndex(unit); _db.add(UNSUPPORTED_INSTRUCTION, ii.insn, str(index), ii.methodId); } /** * Throw statement */ void writeThrow(String methodId, Unit unit, Local l, SessionCounter session) { int index = session.calcInstructionIndex(unit); String insn = _rep.throwLocal(methodId, l, session); _db.add(THROW, insn, str(index), _rep.local(methodId, l), methodId); } /** * Throw null */ void writeThrowNull(InstrInfo ii) { _db.add(THROW_NULL, ii.insn, str(ii.index), ii.methodId); } void writeExceptionHandlerPrevious(String methodId, Trap current, Trap previous, SessionCounter counter) { writeExceptionHandlerPrevious(_rep.handler(methodId, current, counter), _rep.handler(methodId, previous, counter)); } void writeExceptionHandler(String methodId, Trap handler, SessionCounter session) { SootClass exc = handler.getException(); Local caught; { Unit handlerUnit = handler.getHandlerUnit(); IdentityStmt stmt = (IdentityStmt) handlerUnit; Value left = stmt.getLeftOp(); Value right = stmt.getRightOp(); if (right instanceof CaughtExceptionRef && left instanceof Local) { caught = (Local) left; } else { throw new RuntimeException("Unexpected start of exception handler: " + handlerUnit); } } String insn = _rep.handler(methodId, handler, session); int handlerIndex = session.getInstructionIndex(handler.getHandlerUnit()); session.calcInstructionIndex(handler.getBeginUnit()); int beginIndex = session.getInstructionIndex(handler.getBeginUnit()); session.calcInstructionIndex(handler.getEndUnit()); int endIndex = session.getInstructionIndex(handler.getEndUnit()); writeExceptionHandler(insn, methodId, handlerIndex, exc.getName(), beginIndex, endIndex); writeExceptionHandlerFormal(insn, _rep.local(methodId, caught)); } void writeThisVar(String methodId, SootClass declaringClass) { String thisVar = _rep.thisVar(methodId); String type = writeType(declaringClass); writeThisVar(methodId, thisVar, type); } void writeMethodDeclaresException(SootMethod m, SootClass exception) { writeMethodDeclaresException(methodSig(m, null), writeType(exception)); } void writeFormalParam(String methodId, Type type, int i) { String var = _rep.param(methodId, i); writeFormalParam(methodId, var, writeType(type), i); } void writeLocal(String methodId, Local l) { String local = _rep.local(methodId, l); Type type; if (_varTypeMap.containsKey(local)) type = _varTypeMap.get(local); else { type = l.getType(); _varTypeMap.put(local, type); } writeLocal(local, writeType(type), methodId); _db.add(VAR_SIMPLENAME, local, l.getName()); } private Local freshLocal(String inMethod, String basename, Type type, SessionCounter session) { String varname = basename + session.nextNumber(basename); Local l = new JimpleLocal(varname, type); writeLocal(inMethod, l); return l; } private FreshAssignLocal newAssignForFreshLocal(String inMethod, String basename, Type type, SessionCounter session) { return newInstructionWithFreshLocal(inMethod, "fresh-null-assign", basename, type, session); } private FreshAssignLocal newInstructionWithFreshLocal(String inMethod, String kind, String basename, Type type, SessionCounter session) { return new FreshAssignLocal(freshLocal(inMethod, basename, type, session), new InstrInfo(inMethod, kind, session)); } static class FreshAssignLocal { final Local local; final InstrInfo ii; FreshAssignLocal(Local local, InstrInfo ii) { this.local = local; this.ii = ii; } } Local writeStringConstantExpression(Stmt stmt, InstrInfo ii, StringConstant constant, SessionCounter session) { // introduce a new temporary variable FreshAssignLocal fal = newAssignForFreshLocal(ii.methodId, "$stringconstant", RefType.v("java.lang.String"), session); Local l = fal.local; writeAssignStringConstant(stmt, fal.ii, l, constant); return l; } Local writeNullExpression(InstrInfo ii, Type type, SessionCounter session) { // introduce a new temporary variable FreshAssignLocal fal = newAssignForFreshLocal(ii.methodId, "$null", type, session); Local l = fal.local; writeAssignNull(fal.ii, l); return l; } Local writeNumConstantExpression(InstrInfo ii, NumericConstant constant, Type explicitType, SessionCounter session) { Type constantType = (explicitType == null) ? constant.getType() : explicitType; // introduce a new temporary variable FreshAssignLocal fal = newAssignForFreshLocal(ii.methodId, "$numconstant", constantType, session); Local l = fal.local; writeAssignNumConstant(fal.ii, l, constant); return l; } Local writeClassConstantExpression(InstrInfo ii, ClassConstant constant, SessionCounter session) { ClassConstantInfo info = new ClassConstantInfo(constant); // introduce a new temporary variable FreshAssignLocal fal = info.isMethodType ? newAssignForFreshLocal(ii.methodId, "$methodtypeconstant", RefType.v("java.lang.invoke.MethodType"), session) : newAssignForFreshLocal(ii.methodId, "$classconstant", RefType.v("java.lang.Class"), session); Local l = fal.local; writeAssignClassConstant(fal.ii, l, info); return l; } Local writeMethodHandleConstantExpression(InstrInfo ii, MethodHandle constant, SessionCounter session) { // introduce a new temporary variable FreshAssignLocal fal = newAssignForFreshLocal(ii.methodId, "$mhandleconstant", RefType.v("java.lang.invoke.MethodHandle"), session); Local l = fal.local; writeAssignMethodHandleConstant(ii, l, constant); return l; } private Local writeMethodTypeConstantExpression(InstrInfo ii, DoopAddons.MethodType constant, SessionCounter session) { // introduce a new temporary variable FreshAssignLocal fal = newAssignForFreshLocal(ii.methodId, "$methodtypeconstant", RefType.v("java.lang.invoke.MethodType"), session); Local l = fal.local; writeAssignMethodTypeConstant(fal.ii, l, constant); return l; } private Value writeActualParam(Stmt stmt, InstrInfo ii, InvokeExpr expr, SessionCounter session, Value v, int idx) { if (v instanceof StringConstant) return writeStringConstantExpression(stmt, ii, (StringConstant) v, session); else if (v instanceof ClassConstant) return writeClassConstantExpression(ii, (ClassConstant) v, session); else if (v instanceof NumericConstant) return writeNumConstantExpression(ii, (NumericConstant) v, null, session); else if (v instanceof MethodHandle) return writeMethodHandleConstantExpression(ii, (MethodHandle) v, session); else if (v instanceof NullConstant) { // Giving the type of the formal argument to be used in the creation of // temporary var for the actual argument (whose value is null). Type argType = expr.getMethodRef().getParameterType(idx); return writeNullExpression(ii, argType, session); } else if (v instanceof Constant) { DoopAddons.MethodType mt = DoopAddons.methodType(v); if (mt != null) return writeMethodTypeConstantExpression(ii, mt, session); else throw new RuntimeException("Value has unknown constant type: " + v); } else if (!(v instanceof JimpleLocal)) System.err.println("WARNING: value has unknown non-constant type: " + v.getClass().getName()); return v; } private void writeActualParams(Stmt stmt, InstrInfo ii, InvokeExpr expr, String invokeExprRepr, SessionCounter session) { String methodId = ii.methodId; boolean isInvokedynamic = (expr instanceof DynamicInvokeExpr); int count = expr.getArgCount(); for (int i = 0; i < count; i++) { // Undo Soot's reverse order of invokedynamic arguments. Value arg = isInvokedynamic ? expr.getArg(count-i-1) : expr.getArg(i); Value v = writeActualParam(stmt, ii, expr, session, arg, i); if (v instanceof Local) writeActualParam(i, invokeExprRepr, _rep.local(methodId, (Local)v)); else throw new RuntimeException("Actual parameter is not a local: " + v + " " + v.getClass()); } if (isInvokedynamic) { DynamicInvokeExpr di = (DynamicInvokeExpr)expr; for (int j = 0; j < di.getBootstrapArgCount(); j++) { Value v = di.getBootstrapArg(j); if (v instanceof Constant) { Value vConst = writeActualParam(stmt, ii, expr, session, v, j); if (vConst instanceof Local) { Local l = (Local) vConst; _db.add(BOOTSTRAP_PARAMETER, str(j), invokeExprRepr, _rep.local(methodId, l)); } else throw new RuntimeException("Unknown actual parameter: " + v + " of type " + v.getClass().getName()); } else throw new RuntimeException("Found non-constant argument to bootstrap method: " + di); } } } String writeInvoke(SootMethod inMethod, Stmt stmt, InstrInfo ii, SessionCounter session) { InvokeExpr expr = stmt.getInvokeExpr(); String insn = _rep.invoke(inMethod, expr, session); return writeInvokeHelper(insn, stmt, ii, expr, session); } private String writeInvokeHelper(String insn, Stmt stmt, InstrInfo ii, InvokeExpr expr, SessionCounter session) { writeActualParams(stmt, ii, expr, insn, session); SootMethodRef exprMethodRef = expr.getMethodRef(); String simpleName = Representation.simpleName(exprMethodRef); String declClass = exprMethodRef.getDeclaringClass().getName(); LineNumberTag tag = (LineNumberTag) stmt.getTag("LineNumberTag"); if (tag != null) _db.add(METHOD_INV_LINE, insn, str(tag.getLineNumber())); String methodId = ii.methodId; if (expr instanceof DynamicInvokeExpr) writeDynamicInvoke((DynamicInvokeExpr) expr, ii.index, insn, methodId); else { String methodSig = invokeMethodSig(insn, declClass, simpleName, exprMethodRef, expr); if (expr instanceof StaticInvokeExpr) _db.add(STATIC_METHOD_INV, insn, str(ii.index), methodSig, methodId); else if (expr instanceof VirtualInvokeExpr || expr instanceof InterfaceInvokeExpr) _db.add(VIRTUAL_METHOD_INV, insn, str(ii.index), methodSig, _rep.local(methodId, (Local) ((InstanceInvokeExpr) expr).getBase()), methodId); else if (expr instanceof SpecialInvokeExpr) _db.add(SPECIAL_METHOD_INV, insn, str(ii.index), methodSig, _rep.local(methodId, (Local) ((InstanceInvokeExpr) expr).getBase()), methodId); else throw new RuntimeException("Cannot handle invoke expr: " + expr); } return insn; } // Special handling for polymorphic-signature methods. private String invokeMethodSig(String insn, String declClass, String simpleName, SootMethodRef exprMethodRef, InvokeExpr expr) { if (!simpleName.equals("<init>") && DoopAddons.polymorphicHandling(declClass, simpleName)) { _db.add(POLYMORPHIC_INVOCATION, insn, simpleName); return Representation.signature(exprMethodRef); } else return _rep.signature(expr.getMethod()); } private String getBootstrapSig(DynamicInvokeExpr di) { SootMethodRef bootstrapMeth = di.getBootstrapMethodRef(); if (bootstrapMeth.getDeclaringClass().isPhantom()) { String bootstrapSig = Representation.signature(bootstrapMeth); phantoms.reportPhantom("Bootstrap method", bootstrapSig); _db.add(PHANTOM_METHOD, bootstrapSig); return bootstrapSig; } else return _rep.signature(bootstrapMeth.resolve()); } private void writeDynamicInvoke(DynamicInvokeExpr di, int index, String insn, String methodId) { SootMethodRef dynInfo = di.getMethodRef(); SigInfo dynSig = new SigInfo(dynInfo, true); for (int pIdx = 0; pIdx < dynSig.arity; pIdx++) writeInvokedynamicParameterType(insn, pIdx, dynInfo.getParameterType(pIdx).toString()); writeInvokedynamic(insn, index, getBootstrapSig(di), dynInfo.getName(), dynSig.retType, dynSig.arity, dynSig.paramTypes, di.getHandleTag(), methodId); } private Value writeImmediate(Stmt stmt, InstrInfo ii, Value v, Type vType, SessionCounter session) { if (v instanceof Constant) { if (v instanceof StringConstant) v = writeStringConstantExpression(stmt, ii, (StringConstant) v, session); else if (v instanceof ClassConstant) v = writeClassConstantExpression(ii, (ClassConstant) v, session); else if (v instanceof NumericConstant) v = writeNumConstantExpression(ii, (NumericConstant) v, vType, session); else System.err.println("ERROR: unknown type of immediate: " + v.getClass()); } return v; } void writeAssignBinop(InstrInfo ii, Local left, BinopExpr right) { String methodId = ii.methodId; String insn = ii.insn; writeAssignBinop(insn, ii.index, _rep.local(methodId, left), methodId); if (right instanceof AddExpr) writeOperatorAt(insn, "+"); else if (right instanceof SubExpr) writeOperatorAt(insn, "-"); else if (right instanceof MulExpr) writeOperatorAt(insn, "*"); else if (right instanceof DivExpr) writeOperatorAt(insn, "/"); else if (right instanceof RemExpr) writeOperatorAt(insn, "%"); else if (right instanceof AndExpr) writeOperatorAt(insn, "&"); else if (right instanceof OrExpr) writeOperatorAt(insn, "|"); else if (right instanceof XorExpr) writeOperatorAt(insn, "^"); else if (right instanceof ShlExpr) writeOperatorAt(insn, "<<"); else if (right instanceof ShrExpr) writeOperatorAt(insn, ">>"); else if (right instanceof UshrExpr) writeOperatorAt(insn, ">>>"); else if (right instanceof CmpExpr) writeOperatorAt(insn, "cmp"); else if (right instanceof CmplExpr) writeOperatorAt(insn, "cmpl"); else if (right instanceof CmpgExpr) writeOperatorAt(insn, "cmpg"); else writeOperatorAt(insn, "??"); if (right.getOp1() instanceof Local) { Local op1 = (Local) right.getOp1(); writeAssignOperFrom(insn, L_OP, _rep.local(methodId, op1)); } else if (right.getOp1() instanceof NumericConstant) { NumericConstant cons = (NumericConstant) right.getOp1(); writeAssignOperFromConstant(insn, L_OP, cons.toString()); } if (right.getOp2() instanceof Local) { Local op2 = (Local) right.getOp2(); writeAssignOperFrom(insn, R_OP, _rep.local(methodId, op2)); } else if (right.getOp2() instanceof NumericConstant) { NumericConstant cons = (NumericConstant) right.getOp2(); writeAssignOperFromConstant(insn, R_OP, cons.toString()); } } void writeAssignUnop(InstrInfo ii, Local left, UnopExpr right) { String methodId = ii.methodId; String insn = ii.insn; writeAssignUnop(insn, ii.index, _rep.local(methodId, left), methodId); if (right instanceof LengthExpr) writeOperatorAt(insn, "len"); else if (right instanceof NegExpr) writeOperatorAt(insn, "~"); else writeOperatorAt(insn, "??"); if (right.getOp() instanceof Local) { Local op = (Local) right.getOp(); writeAssignOperFrom(insn, L_OP, _rep.local(methodId, op)); } else if (right.getOp() instanceof NumericConstant) { NumericConstant cons = (NumericConstant) right.getOp(); writeAssignOperFromConstant(insn, L_OP, cons.toString()); } } void writeAssignInstanceOf(InstrInfo ii, Local to, Local from, Type t) { String methodId = ii.methodId; _db.add(ASSIGN_INSTANCE_OF, ii.insn, str(ii.index), _rep.local(methodId, from), _rep.local(methodId, to), writeType(t), methodId); } void writeAssignPhantomInvoke(InstrInfo ii) { _db.add(ASSIGN_PHANTOM_INVOKE, ii.insn, str(ii.index), ii.methodId); } void writeBreakpointStmt(InstrInfo ii) { _db.add(BREAKPOINT_STMT, ii.insn, str(ii.index), ii.methodId); } void writeFieldInitialValue(SootField f) { String fieldId = _rep.signature(f); List<Tag> tagList = f.getTags(); for (Tag tag : tagList) if (tag instanceof ConstantValueTag) { String val = ((ConstantValueTag)tag).getConstant().toString(); _db.add(FIELD_INITIAL_VALUE, fieldId, val); // Put constant in appropriate "raw" input facts. if ((tag instanceof IntegerConstantValueTag) || (tag instanceof DoubleConstantValueTag) || (tag instanceof LongConstantValueTag) || (tag instanceof FloatConstantValueTag)) { // Trim last non-digit qualifier (e.g. 'L' in long constants). int len = val.length(); if (!Character.isDigit(val.charAt(len-1))) val = val.substring(0, len-1); writeNumConstantRawInt(val); } else if (tag instanceof StringConstantValueTag) { writeStringConstant(val); } else System.err.println("Unsupported field tag " + tag.getClass()); } } public void writePreliminaryFacts(Collection<SootClass> classes, BasicJavaSupport java, boolean debug) { classes.stream().filter(SootClass::isApplicationClass).forEachOrdered(this::writeApplicationClass); writePreliminaryFacts(java, debug); } boolean checkAndRegisterPhantom(Object phantom) { if (seenPhantoms.contains(phantom)) return true; seenPhantoms.add(phantom); return false; } @Override public void writeLastFacts(BasicJavaSupport java) { super.writeLastFacts(java); phantoms.showPhantomInfo(); } static class SigInfo { final int arity; final String retType; final String paramTypes; SigInfo(SootMethodInterface ref, boolean reverse) { List<Type> paramTypes = ref.getParameterTypes(); if (reverse) paramTypes = Lists.reverse(paramTypes); this.arity = paramTypes.size(); this.retType = ref.getReturnType().toString(); StringJoiner joiner = new StringJoiner(","); paramTypes.forEach(p -> joiner.add(p.toString())); this.paramTypes = joiner.toString(); } } }
Java
UTF-8
9,021
1.90625
2
[ "MIT" ]
permissive
package com.fbasegizi.statusgizi.makan; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.fbasegizi.statusgizi.BaseActivity; import com.fbasegizi.statusgizi.R; import com.fbasegizi.statusgizi.adapter.RecyclerViewMenuMakan; import com.fbasegizi.statusgizi.model.MenuMakan; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; public class RekomendasiMakan extends BaseActivity { private DatabaseReference mDatabase; private List<MenuMakan> menuMakans = new ArrayList<>(); private RecyclerView recyclerView; private RecyclerViewMenuMakan viewMenuMakan; private ProgressBar progressBar; private TextView textView, textViewMakan; private Button buttonView; private String bid, nbid, bahan, tanggal; private String[] bahanArray; private Integer bahanSize, umurBulan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rekomendasi_makan); mDatabase = FirebaseDatabase.getInstance().getReference(); recyclerView = findViewById(R.id.RecycleRekomendasiMenu); progressBar = findViewById(R.id.ProgressRekomendasiMenu); textView = findViewById(R.id.empty_rekomendasi_menu); textViewMakan = findViewById(R.id.textViewRekomendasiMenu); buttonView = findViewById(R.id.buttonRekomendasiMenu); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(layoutManager); bahan = getIntent().getStringExtra("bahan"); tanggal = getIntent().getStringExtra("tanggal"); bahan = bahan.replace(", ", " "); bahanArray = bahan.toLowerCase().split(" "); bahanSize = bahanArray.length; Calendar currentDate = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); Date birthdate = null; try { birthdate = sdf.parse(tanggal); } catch (ParseException e) { e.printStackTrace(); } Long time = currentDate.getTime().getTime() / 1000 - birthdate.getTime() / 1000; int years = Math.round(time) / 31536000; int months = years * 12 + (Math.round(time - years * 31536000) / 2628000); if (months <= 6) { umurBulan = 6; } else if (months <= 8) { umurBulan = 8; } else if (months <= 10) { umurBulan = 10; } else if (months <= 12) { umurBulan = 12; } else { umurBulan = 24; } if (isOnline()) { textView.setText("Koneksi internet tidak tersedia!"); textView.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); progressBar.setVisibility(View.GONE); return; } else { textView.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE); } ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle("Rekomendasi Menu Makan"); } loadData(); buttonView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadAll(); buttonView.setVisibility(View.GONE); } }); } private void loadData() { mDatabase.child("MenuMakan").orderByChild("menuJudul").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { menuMakans = new ArrayList<>(); if (dataSnapshot.exists()) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { MenuMakan menuMakan = postSnapshot.getValue(MenuMakan.class); String bahanData = (String) postSnapshot.child("menuBahan").getValue(); String umur = (String) postSnapshot.child("menuUmur").getValue(); bid = (String) postSnapshot.child("menuId").getValue(); if (String.valueOf(umurBulan).equals(umur)) { for (int i = 0; i < bahanSize; i++) { if (bahanData != null && bahanData.contains(bahanArray[i])) { if (bid != null && menuMakan != null && !bid.equals(nbid)) { menuMakan.setMenuId(postSnapshot.getKey()); menuMakans.add(menuMakan); nbid = bid; } progressBar.setVisibility(View.GONE); textView.setVisibility(View.INVISIBLE); recyclerView.setVisibility(View.VISIBLE); } } } } } else { progressBar.setVisibility(View.GONE); recyclerView.setVisibility(View.INVISIBLE); textView.setVisibility(View.VISIBLE); } viewMenuMakan = new RecyclerViewMenuMakan(RekomendasiMakan.this, menuMakans); viewMenuMakan.notifyDataSetChanged(); if (viewMenuMakan.getItemCount() == 0) { progressBar.setVisibility(View.GONE); recyclerView.setVisibility(View.INVISIBLE); textView.setText("Menu makan untuk data menu harian belum tersedia!"); textView.setVisibility(View.VISIBLE); } recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(viewMenuMakan); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void loadAll() { textViewMakan.setText("Daftar seluruh menu makanan"); mDatabase.child("MenuMakan").orderByChild("menuJudul").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { menuMakans = new ArrayList<>(); if (dataSnapshot.exists()) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { MenuMakan menuMakan = postSnapshot.getValue(MenuMakan.class); if (menuMakan != null) { menuMakan.setMenuId(postSnapshot.getKey()); menuMakans.add(menuMakan); } progressBar.setVisibility(View.GONE); textView.setVisibility(View.INVISIBLE); recyclerView.setVisibility(View.VISIBLE); } } else { progressBar.setVisibility(View.INVISIBLE); recyclerView.setVisibility(View.INVISIBLE); textView.setVisibility(View.VISIBLE); } viewMenuMakan = new RecyclerViewMenuMakan(RekomendasiMakan.this, menuMakans); viewMenuMakan.notifyDataSetChanged(); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(viewMenuMakan); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } }
Python
UTF-8
544
3.140625
3
[]
no_license
from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: if not nums: return 0 n = len(nums) dp = [1] * n result = 0 for i in range(n): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) result = max(result, dp[i]) return result if __name__ == "__main__": nums = [int(num) for num in input().split()] solution = Solution() print(solution.lengthOfLIS(nums))
C
UTF-8
6,698
3.359375
3
[]
no_license
#include <collect/list_algos.h> #include <dbg.h> typedef int (*List_compare)(void *lhs, void *rhs); int List_bubble_sort(List *list, List_compare comparator) { // 1. for each item in the list: // a) if the item is greater than the next item, swap them // 2. repeat until a pass through the list where no swaps are needed int done = 0; // keep going until we get a pass with no switches while(!done) { done = 1; // Iterate through each item in the list LIST_FOREACH(list, first, next, cur) { // if right hand side is less than left hand side if(cur->next && comparator(cur->value, cur->next->value) > 0) { done = 0; void *tmp = cur->next->value; cur->next->value = cur->value; cur->value = tmp; } } } return 0; } List *List_old_merge_sort(List *list, List_compare comparator) { ListSortContext context; context.in = list; context.out = NULL; context.comparator = comparator; pthread_t sort_pt; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); int rc; rc = pthread_create(&sort_pt, &attr, List_pt_merge_sort, (void *)&context); check(rc == 0, "Return code from pthread_create() on merge sort is %d", rc); void *sort_status; rc = pthread_join(sort_pt, &sort_status); check(rc == 0, "Return code from pthread_join() on merge sort is %d", rc); check((long)sort_status == SUCCESS_STATUS, "Exit status for merge sort " "is %ld", (long)sort_status); error: pthread_attr_destroy(&attr); return context.out; } void *List_pt_merge_sort(void *args) { // From Wikipedia: // 1. Divide the unsorted list into n sublists, each containing 1 // element // 2. Repeatedly merge sublists to produce new sorted sublists until // there is only 1 sublist remaining. This will be th the sorted // list List *out = List_create(); List *left = NULL; List *right = NULL; List *sorted_left = NULL; List *sorted_right = NULL; long status = FAIL_STATUS; int list_locked = 0; // cast context ListSortContext *context = (ListSortContext *)args; List *list = context->in; List_compare comparator = context->comparator; check(list != NULL, "Input list was NULL"); // This is a thread call, so we lock the shared data // we also need to track locally whether the thread is locked pthread_mutex_lock(list->lock); list_locked = 1; // store this variable for later use int list_count = list->count; // Check for single-node or empty lists, which are already sorted if(list->count < 2) { if(list->count == 1) { List_push(out, list->first->value); } context->out = out; pthread_mutex_unlock(list->lock); pthread_exit(SUCCESS_STATUS); } // Divide list into two new lists left = List_create(); right = List_create(); ListNode *cur = list->first; int i; for(i = 0; i < list->count / 2; i++) { check(cur != NULL, "Got a null value for a node in the list " "with index less than list->count"); List_push(left, cur->value); cur = cur->next; } for(; i < list->count; i++) { check(cur != NULL, "Got a null value for a node in the list " "with index less than list->count"); List_push(right, cur->value); cur = cur->next; } // unlock the list after reading. we don't need it pthread_mutex_unlock(list->lock); list_locked = 0; // debug("list->count:\t%d", list->count); // debug("left->count:\t%d", left->count); // debug("right->count:\t%d", right->count); check(list_count == left->count + right->count, "left and right list " "split sizes do not add up to input size."); // merge sort each pthread_t left_sort_pt; pthread_t right_sort_pt; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); ListSortContext left_sort_ctx; left_sort_ctx.in = left; left_sort_ctx.out = NULL; left_sort_ctx.comparator = comparator; ListSortContext right_sort_ctx; right_sort_ctx.in = right; right_sort_ctx.out = NULL; right_sort_ctx.comparator = comparator; int rc; rc = pthread_create(&left_sort_pt, &attr, List_pt_merge_sort, (void *)&left_sort_ctx); check(rc == 0, "Return code from pthread_create() on left sort is %d", rc); rc = pthread_create(&right_sort_pt, &attr, List_pt_merge_sort, (void *) &right_sort_ctx); check(rc == 0, "Return code from pthread_create() on right sort is %d", rc); pthread_attr_destroy(&attr); void *sort_status; rc = pthread_join(left_sort_pt, &sort_status); check(rc == 0, "Return code from pthread_join() on left sort is %d", rc); check(sort_status == SUCCESS_STATUS, "Exit status for left sort is %ld", (long)sort_status); rc = pthread_join(right_sort_pt, &sort_status); check(rc == 0, "Return code from pthread_join() on right sort is %d", rc); check(sort_status == SUCCESS_STATUS, "Exit status for right sort is %ld", (long)sort_status); sorted_left = left_sort_ctx.out; sorted_right = right_sort_ctx.out; // debug("sorted_left->count:\t%d", sorted_left->count); // debug("sorted_right->count:\t%d", sorted_right->count); check(left->count == sorted_left->count, "Internal sorted list had a " "different count than its input"); check(right->count == sorted_right->count, "Internal sorted list had a " "different count than its input"); // merge sorted lists void *lval = NULL; void *rval = NULL; int lcount = sorted_left->count; int rcount = sorted_right->count; while(sorted_left->count > 0 || sorted_right->count > 0 || lval != NULL || rval != NULL) { // load left and right values from START if(lval == NULL && sorted_left->count > 0) { lval = List_shift(sorted_left); } if(rval == NULL && sorted_right->count > 0) { rval = List_shift(sorted_right); } // append lesser of the values to out if(lval == NULL) { List_push(out, rval); rval = NULL; continue; } if(rval == NULL) { List_push(out, lval); lval = NULL; continue; } // if comparator < 0 then lval < rval if(comparator(lval, rval) < 0) { List_push(out, lval); lval = NULL; } else { List_push(out, rval); rval = NULL; } } // debug("out->count:\t%d", out->count); check(out->count == lcount + rcount, "merged list count was not equal " "to size of right + left."); check(out->count == list->count, "merged list count was not equal to " "size of input."); status = SUCCESS_STATUS; error: if(left != NULL) { List_destroy(left); } if(right != NULL) { List_destroy(right); } if(sorted_left != NULL) { List_destroy(sorted_left); } if(sorted_right != NULL) { List_destroy(sorted_right); } if(list_locked) { pthread_mutex_unlock(list->lock); } context->out = out; pthread_exit((void *)status); }
Python
UTF-8
2,065
2.859375
3
[]
no_license
from random import randint class Chromosome: def __init__(self, problParam): self.__problParam = problParam self.__repres = [] self.__fitness = 0.0 self.__communities=[] def initRepres(self): repres=[] for node in range(self.__problParam['noDim']): adjNodes=list(self.__problParam['graph'].adj[node]) r=randint(0,len(adjNodes)-1) repres.append(adjNodes[r]) return repres def set_communities(self,com): self.__communities=com def get_communities(self): return self.__communities @property def repres(self): return self.__repres @property def fitness(self): return self.__fitness @repres.setter def repres(self, l): self.__repres = l @fitness.setter def fitness(self, fit = 0.0): self.__fitness = fit def crossover(self, c): mask=[] for _ in range(len(self.__repres)): r=randint(0,1); mask.append(r) newrepres=[] for i in range(len(mask)): if mask[i]==1: newrepres.append(c.__repres[i]) else: newrepres.append(self.__repres[i]) offspring=Chromosome(c.__problParam) offspring.repres=newrepres return offspring def mutation(self): marginalNode=0 gr=self.__problParam['graph'] for node in range(self.__problParam['noDim']): if node not in self.__repres: marginalNode=node break adjNodes=list(gr.adj[marginalNode]) r=randint(0,len(adjNodes)-1) self.__repres[marginalNode]=adjNodes[r] # def __str__(self): # return '\nChromo: ' + str(self.__repres) + ' has fit: ' + str(self.__fitness) # # def __repr__(self): # return self.__str__() def __eq__(self, c): return self.__repres == c.__repres and self.__fitness == c.__fitness
Java
UTF-8
451
1.921875
2
[]
no_license
package com.example.byron.vrviewer.widget; import android.content.Intent; import android.widget.RemoteViewsService; /** * Created by Byron on 11/28/2016. */ public class WidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { WidgetListProvider dataProvider = new WidgetListProvider( getApplicationContext(), intent); return dataProvider; } }
C
UTF-8
2,336
2.578125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* spaces.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: iromero- <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/21 12:06:10 by iromero- #+# #+# */ /* Updated: 2019/12/04 11:25:06 by iromero- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" void flagszero(t_flags *flags) { flags->lspc = 0; flags->rspace = 0; flags->nprint = 0; flags->nzero = 0; flags->leng = 0; flags->multi = 0; flags->nast = 0; flags->nast2 = 0; } char *next(char *str, t_flags *flags) { while (flags->leng-- > 0) str++; return (str); } int getvar(char *str) { int i; i = 0; while (*str == '-' || *str == '.' || *str == '*' || ft_isdigit(*str)) { str++; i++; } return (i); } static void helpme(t_flags *flags, char *str) { if (flags->nzero > 0) { if (str[0] == '-') ft_putchar_fd('-', 1); if (str[0] == '0' && str[1] == 'x') ft_putstr_fd("0x", 1); while (flags->nzero-- > 0) { ft_putchar_fd('0', 1); flags->lenght++; } flags->nzero = 1; } } void regulflags(t_flags *flags, char *str) { if (flags->lspc > 0 && flags->nprint == -1) return ; else if (flags->lspc > 0 && flags->nprint > 0 && (size_t)flags->nprint < ft_strlen(str)) flags->lspc = flags->lspc - flags->nprint; else if (flags->lspc > 0) flags->lspc = flags->lspc - ft_strlen(str); if (flags->nprint > 0 && flags->rspace > 0 && (size_t)flags->nprint < ft_strlen(str)) flags->rspace = flags->rspace - flags->nprint; else if (flags->rspace > 0 && flags->nprint != -1) flags->rspace = flags->rspace - ft_strlen(str); if (flags->rspace > 0) { while (flags->rspace-- > 0) { ft_putchar_fd(32, 1); flags->lenght++; } } helpme(flags, str); }
Java
UTF-8
21,196
2.1875
2
[ "Apache-2.0" ]
permissive
package com.cached; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.LockSupport; import com.amef.AMEFObject; import com.amef.AMEFResources; public class JDBOperations { public static void appendMove(SocketChannel sock,JdbNewDR reader,String ftable, String ttable, String pid, String nid,AMEFObject object) { AMEFObject query = new AMEFObject(); query.addPacket("apmov "+ftable+" "+ttable+" "+pid+""+((nid!=null)?" "+nid:"")); try { query.addPacket(AMEFResources.getEncoder().encodeWL(object, true)); byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static void appendMovewrt(SocketChannel sock,JdbNewDR reader,String ftable, String ttable, String pid, String nid,AMEFObject object) { AMEFObject query = new AMEFObject(); query.addPacket("apmovwrt "+ftable+" "+ttable+" "+pid+""+" "+nid); try { query.addPacket(AMEFResources.getEncoder().encodeWL(object, true)); byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static void appendMovewrtpvap(SocketChannel sock,JdbNewDR reader,String ftable, String ttable, String pid, String nid,AMEFObject object,String ind) { AMEFObject query = new AMEFObject(); query.addPacket("apmovwrtpvap "+ftable+" "+ttable+" "+pid+""+" "+nid+" "+ind); try { query.addPacket(AMEFResources.getEncoder().encodeWL(object, true)); byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static void updateMovewrtpvap(SocketChannel sock,JdbNewDR reader,String ftable, String ttable, String pid, String nid,AMEFObject object,String ind) { AMEFObject query = new AMEFObject(); query.addPacket("upmovwrtpvap "+ftable+" "+ttable+" "+pid+""+" "+nid+" "+ind); try { query.addPacket(AMEFResources.getEncoder().encodeWL(object, false)); byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static void singleInsert(SocketChannel sock,JdbNewDR reader,String table, AMEFObject object,String id) { AMEFObject query = new AMEFObject(); try { query.addPacket("insert "+table+" "+id); query.addPacket(AMEFResources.getEncoder().encodeWL(object, true)); byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); //System.out.println(new String(data,"ISO-8859-1")); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static void singleUpdate(SocketChannel sock,JdbNewDR reader,String table, AMEFObject object,String id) { AMEFObject query = new AMEFObject(); try { query.addPacket("update "+table+" "+id); query.addPacket(AMEFResources.getEncoder().encodeWL(object, false)); byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); //System.out.println(new String(data,"ISO-8859-1")); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static void updateMove(SocketChannel sock,JdbNewDR reader,String ftable, String ttable, String pid, String nid,AMEFObject object) { AMEFObject query = new AMEFObject(); query.addPacket("updmov "+ftable+" "+ttable+" "+pid+""+((nid!=null)?" "+nid:"")); try { query.addPacket(AMEFResources.getEncoder().encodeWL(object, false)); byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static AMEFObject select(SocketChannel sock, JdbNewDR reader, String table, String cond, String i,String lim) { AMEFObject obh = null; AMEFObject query = new AMEFObject(); query.addPacket("select "+table+" "+cond+" "+i+((lim!=null)?" limit "+lim:"")); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); outer: while(!reader.isReaderDone()) { data = null; while(!reader.isDone()) { data = reader.readLim1(sock,1); if(reader.isReaderDone()) { break outer; } } reader.reset1(); if(data!=null) obh = AMEFResources.getDecoder().decodeB(data, false, true); new WeakReference<byte[]>(data); data = null; } new WeakReference<ByteBuffer>(buf); buf = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } return obh; } public static String find(SocketChannel sock, JdbNewDR reader, String tables, String id) { AMEFObject obh = null; AMEFObject query = new AMEFObject(); query.addPacket("find "+tables+" "+id); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); outer: while(!reader.isReaderDone()) { data = null; while(!reader.isDone()) { data = reader.readLim1(sock,1); if(reader.isReaderDone()) { break outer; } } reader.reset1(); if(data!=null) obh = AMEFResources.getDecoder().decodeB(data, false, true); new WeakReference<byte[]>(data); data = null; } new WeakReference<ByteBuffer>(buf); buf = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } if(obh!=null && obh.getPackets().size()>0 && obh.getPackets().get(0)!=null) return obh.getPackets().get(0).getValueStr(); return null; } public static long count(SocketChannel sock, JdbNewDR reader, String table) { AMEFObject obh = null; AMEFObject query = new AMEFObject(); query.addPacket("count "+table); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); outer: while(!reader.isReaderDone()) { data = null; while(!reader.isDone()) { data = reader.readLim1(sock,1); if(reader.isReaderDone()) { break outer; } } reader.reset1(); if(data!=null) obh = AMEFResources.getDecoder().decodeB(data, false, true); new WeakReference<byte[]>(data); data = null; } new WeakReference<ByteBuffer>(buf); buf = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } if(obh==null || obh.getPackets().size()==0) return -1; else return obh.getPackets().get(0).getNumericValue(); } public static void singleMove(SocketChannel sock, JdbNewDR reader, String ftable, String ttable, String pid, String nid) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("move "+ftable+" "+ttable+" "+pid+" "+nid); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void singleMovepvap(SocketChannel sock, JdbNewDR reader, String ftable, String ttable, String pid, String nid,String ind) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("movepvap "+ftable+" "+ttable+" "+pid+" "+nid+" "+ind); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void singleMovewrtpvap(SocketChannel sock, JdbNewDR reader, String ftable, String ttable, String pid, String nid,String ind) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("movewrtpvap "+ftable+" "+ttable+" "+pid+" "+nid+" "+ind); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void moveToTemp(SocketChannel sock, JdbNewDR reader, String ftable) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("mvtmp "+ftable); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void clearTmp(SocketChannel sock, JdbNewDR reader) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("clrtmp"); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void removeField(SocketChannel sock, JdbNewDR reader, String ftable, String nid, int pos) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("remfld "+ftable+" = "+nid+" "+pos); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void movelt(SocketChannel sock, JdbNewDR reader, String ftable, String ttable, String pid) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("movelt "+ftable+" "+ttable+" "+pid); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void movegt(SocketChannel sock, JdbNewDR reader, String ftable, String ttable, String pid, String lim) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("movegt "+ftable+" "+ttable+" "+pid+(lim!=null?" limit "+lim:"")); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static void singleMoveWrt(SocketChannel sock, JdbNewDR reader, String ftable, String ttable, String pid, String nid) { reader.reset1(); AMEFObject query = new AMEFObject(); query.addPacket("movewrt "+ftable+" "+ttable+" "+pid+" "+nid); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; reader.reset1(); } } public static List<AMEFObject> selectMulti(SocketChannel sock, JdbNewDR reader, String table, String cond, String i,String lim) { List<AMEFObject> objects = new ArrayList<AMEFObject>(); AMEFObject query = new AMEFObject(); query.addPacket("select "+table+" "+cond+""+(cond.equals("*")?"":" "+i)+((lim!=null)?" limit "+lim:"")); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); long rdtim = 0,odtim = 0; sock.write(buf); try { reader.reset1(); outer : while(!reader.isReaderDone()) { data = null; while(!reader.isDone()) { data = reader.readLim1(sock,1); LockSupport.parkNanos(1); if(reader.isReaderDone()) break outer; } reader.reset1(); if(data!=null) { if(data[0]=='F') { break outer; } AMEFObject obh = AMEFResources.getDecoder().decodeB(data, false, true); objects.add(obh); new WeakReference<byte[]>(data); data = null; } } new WeakReference<ByteBuffer>(buf); buf = null; } catch(Exception e) {} } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } return objects; } public static List<AMEFObject> selectCount(SocketChannel sock, JdbNewDR reader, String table, String i,String lim) { List<AMEFObject> objects = new ArrayList<AMEFObject>(); AMEFObject query = new AMEFObject(); query.addPacket("selectcnt "+table+" "+i+" "+lim); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); try { reader.reset1(); outer : while(!reader.isReaderDone()) { data = null; while(!reader.isDone()) { data = reader.readLim1(sock,1); LockSupport.parkNanos(1); if(reader.isReaderDone()) break outer; } reader.reset1(); if(data!=null) { if(data[0]=='F') { break outer; } AMEFObject obh = AMEFResources.getDecoder().decodeB(data, false, true); objects.add(obh); new WeakReference<byte[]>(data); data = null; } } new WeakReference<ByteBuffer>(buf); buf = null; } catch(Exception e) {} } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } return objects; } public static void multiDelete(SocketChannel sock,JdbNewDR reader,String table) { AMEFObject query = new AMEFObject(); query.addPacket("delete "+table+" *"); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } public static void singleDelete(SocketChannel sock,JdbNewDR reader,String table, String id) { AMEFObject query = new AMEFObject(); query.addPacket("delete "+table+" = "+id); try { byte[] data = AMEFResources.getEncoder().encodeB(query, false); query = null; ByteBuffer buf = ByteBuffer.allocate(data.length); buf.put(data); buf.flip(); sock.write(buf); reader.reset1(); while(!reader.isDone()) { data = reader.readLim4(sock,2); } new WeakReference<ByteBuffer>(buf); buf = null; reader.reset1(); new WeakReference<byte[]>(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { new WeakReference<AMEFObject>(query); query = null; } } }
Python
UTF-8
741
2.671875
3
[]
no_license
import lvgl as lv from lib.widgets.base import Base class Gauge(Base): def __init__(self, w, h, x, y, **kwargs): needle_count = kwargs.get('count', 1) needle_colors = kwargs.get('colors', [lv.color_make(0x0,0x0,0x0)]) gauge = lv.gauge(lv.scr_act(), None) gauge.set_needle_count(needle_count, needle_colors) gauge.set_size(w, h) gauge.set_range(0,110) gauge.set_scale(260, 12, 12) gauge.align(None,lv.ALIGN.CENTER, x, y) self.__widget = gauge def update(self, values): for idx, value in enumerate(values): self.__widget.set_value(idx, value) self.__widget.set_value(idx, value) self.__widget.set_value(idx, value)
Markdown
UTF-8
67,855
3.6875
4
[]
no_license
# 《C++ Primer Plus 6th》 《C++ Primer Plus 第六版》 的学习笔记。 ## 第1章 预备知识 C++在C的基础上增加了以类为代表的`OOP`编程、以及基于`模板`的泛型编程。 `OOP`强调数据,设计出与问题本质相对应的数据格式(即自定义数据类型),它与内置类型的使用是一样的。 - 对象、类、封装、数据隐藏、接口、多态、继承 - 多态: - 继承: 复用代码、通过对基类进行派生,产生更加契合问题的派生类,派生类继承基类已有的功能 - `OOP`的本质就是设计并且拓展自己的数据类型,让设计的类型与现实数据相匹配 泛型编程:强调独立于特定的数据类型,创建出独立于类型的代码 ## 第2章 开始学习C++ **声明变量**: 声明指明了变量的 名称 及 类型,但并不分配内存空间。 **定义变量**: 为变量分配内存空间。 如果`a.cpp`需要使用`b.cpp`中定义的`全局变量`,则必须使用`extern`声明它,表明它是来自于其他文件的`全局变量`。更一般的做法是,由`b.h`提供`全局变量`的声明,`a.cpp`只需要`#include b.h`即可以使用`b.cpp`中定义的全局变量。 ```c++ // b.cpp extern const double PI = 3.14159; // b.h extern double PI; // a.cpp #include "b.h" cout << PI << endl; ``` ## 第3章 处理数据 运算符的 `优先级` 与 `结合性`: - `优先级` 指示了先进行什么运算,后进行什么运算 - `结合性` 指示了运算符在`优先级`相同的情况下,是从左往右开始运算,还是从右往左开始运算 C++中有11种整形 与 3种浮点型,不同的数值类型进行运算时,计算机自动为它们进行类型转换后,再运算。 类型转换存在3种问题: - 精度损失 `double -> float` - 小数部分丢失 `double -> int` - 数值错误 `long -> short`, 通常只复制`long`的低位字节 使用`{}`初始化列表进行变量的初始化,可以防止变量的窄化`narrowing`。 强制类型转换: ```c++ (typeName) value; // C 与 C++ 都适用 typeName( value ); // 只有C++支持 ``` 字符通过其数值编码来表示,`IO`系统决定了编码是被解释为字符还是数字。 ## 第4章 复合类型 ### 数组 数组关键点:元素的类型,数组名,数组中的元素个数。 ```c++ typeName arrayName[arraySize]; ``` C 风格字符串中,处理字符串的函数是根据空字符`\\0`的位置,而不是字符数组的长度来处理。计算存储字符串的所需的最短数组时,不要忘记结尾的`\\0`字符需要占一个元素。 ### 结构 结构将多个不同类型的值存储在一个数据对象中,使用`.`返回其中成员。声明一个结构类型,即是声明了一种新类型。 ### 枚举 `enum`提供了另一种创建符号常量的方式,这种方式可以代替`const`。枚举也是声明了新类型。 ```c++ enum spectrum { red, orange, yellow = 8, green, blue }; spectrum band; // 使用 spectrum 类型 声明一个变量,该类型只有 5 个能取的值 band = blue; // 赋值 ``` ### 指针与动态内存 指针本身只指出了对象存储的起始地址,而没有指出其类型(类似`void *`指针),通过声明指针的类型,就可以让编译器知晓该如何使用 起始地址 访问 存储对象。 `new`运算符是在程序运行时为数据对象申请内存,它返回申请到的内存的地址,可以将这个地址赋给一个指针。之后,只能使用该指针来访问这块内存。 ```c++ int *pt = new int; short *ps = new short[500]; delete pt; delete[] ps; ``` - 不要使用`delete`来释放不是`new`分配的内存。 - 不要使用`delete`是否同一块内存两次。 - `delete[]` 用于释放`new[]` 生成的数组 - 对空指针`nullptr`使用`delete`是安全的 C++将数组名解释为一个内存地址。多数情况下,解释为数组的第一个元素的地址。是一个地址常量。但如果对数组名取地址,则得到的是整个数组的地址。地址的值虽然一样,但它们的类型不一样。 ```c++ short tell[10]; // tell 等价于 &tell[0]; 是一个 2 字节内存块的地址 // &tell 是一个 20字节内存块的地址 short (*pas)[20] = &tell; // pas 是一个指针,指向 20 字节的内存块 ``` ### 变量的生存期 自动存储:变量在函数调用时产生,在函数返回时销毁。 静态存储:函数外定义的全局变量,以及函数内使用`static`声明的静态变量 动态存储:`new`与`delete`管理的堆内存池。 ### 类型组合 数组、结构和指针,可以各种方式组合它们。 ## 第5章 循环和关系表达式 略 ## 第6章 分支语句与逻辑运算符 略 ## 第7章 函数——C++的编程模块 C++函数参数按值传递,这意味着将数值传递给函数,而后函数将其赋给一个新变量,用于函数内部使用。将一个内存地址(指针)传递给函数,也是按值传递,只不过函数内部可以通过该内存地址,修改函数外部的值。 如果函数的定义中,将函数的参数声明为引用,则 新变量名 与 函数外部变量名 绑定的是同一个数据对象。 ```c++ void swap( int a, int b ); // 按值传递 void swap2( int *a, int *b ); // 按值传递 void swap3( int &a, int &b ); // 按引用传递 int c = 5, d = 6; swap( c, d ); swap2( &c, &d ); swap( c, d ); // 推荐使用,程序更加清晰,优雅 ``` ### 设计处理数组的函数 ```c++ int sum_arr( int arr[], int n ); // 传入数组首地址,以及数组大小 // begin 指向要处理的起始位置,end 指向要处理最后元素的后面一个位置 int sum_arr( int *begin, int *end ){ const int *pt; int total = 0; for( pt = begin; pt != end; pt++ ) total = total + *pt; return total; } int sum = sum_arr( arr, arr + sizeof(arr) / sizeof(int) ); // 处理二维数组 int sum( int (*ar2)[4], int size ); int sum( int arr[][4], int size ); // 与上式等价,列数固定 4 列,行数为 size ``` **函数处理C风格字符串** : C风格字符串 与 常规char数组之间的区别是:字符串内部有内置的结束字符`\\0`,这意味着不必传字符串长度到函数。 ```c++ unsigned int c_in_str( const char *str, char ch ){ unsigned int count = 0; while( *str ){ // 字符串最后一个字符是\0, false if( *str == ch ) ++count; ++str; } return count; } ``` `*"pizza"`中,C++将`"pizza"`解释为其第一个元素的地址,因此使用`*`运算符将得到第一个元素的值,即字符`p`。同理`"taco"[2]`解释为第3个字符的值,即`z`。 **函数处理结构**: 像处理内置类型那样来处理结构,可以将结构作为参数传递,也可以从函数内返回一个结构,这些都是按值传递。当然,如果结构体较大,最好是传递结构体的指针,或者使用引用来传递,这样可以提高程序运行效率。 **函数处理对象**: 对象与结构类似,例如可以相互赋值,可以直接传递给函数。 ### 函数的递归掉用 ```c++ void recurs( argumentlist ){ statements1; if( test ) recurs( argumentlist ); statements2; } ``` 上述为一般递归调用函数的模板。通常将递归调用放在`if`语句中,当`test`最终为`false`时,停止递归调用,依次返回调用链条上的所有结果。 假设上述递归执行了5次,那么`statements1`将在每次`recurs`调用之前调用,共 5次,而`statements2`将在最后一次`recurs`调用(其中包括执行`statements2`)结束返回后依次调用,共执行5次,调用顺序与`statements1`相反。 ### 指向函数的指针 函数也有地址。函数的地址是存储其机器语言代码的内存首地址。如果将函数A的地址传递给函数B,则在函数B中可以通过这个地址调用A。这意味着,我们可以在不同情况下,给B函数传递不同函数的地址,这样操作可以非常灵活的实现某些功能。 那么我们该用什么参数来接收这个函数地址呢?答案是 函数指针。需要注意的是,要将该地址解释为函数调用时,必须知道其函数类型。也即是该函数指针的类型。 C++中函数名与函数地址的作用相同。函数名的值即是函数的内存地址,传递函数的名称作为参数。 ```c++ double pam( int ); // 函数原型 double (*pf)( int ); // pf 就是 pam 的函数指针 void estimate( int lines, double (*pf)(int) ){ double h = (*pf)( lines ); // 使用函数指针 调用函数 // double h = pf( lines ); // 与上式等价,由于历史原因,对于函数调用 *pf 等价于 pf } estimate( 7, pam ); // 调用函数,将 pam 作为值传入 const double *get_max( const double *a, int b ); // 函数原型 const double *get_min( const double *a, int b ); // 函数原型 typedef const double *(*p_fun)( const double *, int ); // 使用 typedef 简化, p_fun 现在是 该函数指针 的类型了 p_fun p1 = get_max; // 声明 该函数指针类型的变量 p_fun pa[3] = { get_max, p1, get_min }; // 声明 该函数指针的数组 p_fun (*pd)[3] = &pa; // 想想看 &pa 的类型是什么? ``` 例题: 结构`applicant`与函数原型如下,请声明: - 指向 `f1()` 与 `f2()` 的指针 `p1` 与 `p2` - 一个名为`ap`的数组,它包含5个类型与`p1`相同的指针 - 一个名为`pa`的指针,它指向的数组包含10个类型与`p2`相同的指针 ```c++ struct applicant{ char name[30]; int credit_ratings[3]; }; void f1( applicant *a ); const char *f2( const applicant *a1, const applicant *a2 ); ``` 答案如下: ```c++ int main( int argc, char *argv[] ) { typedef void ( *Point_Type_f1 )( applicant * ); typedef const char *( *Point_Type_f2 )( const applicant *, const applicant * ); Point_Type_f1 p1; Point_Type_f2 p2; Point_Type_f1 ap[5]; Point_Type_f2 (*pa)[10]; return EXIT_SUCCESS; } ``` ## 第8章 函数探幽 ### 内联函数 通常的做法是将内联函数的定义放在`.h`文件中,并在函数定义前面加上`inline`: ```c++ inline double square( double x ) { return x * x; } // a.h ``` ### 默认参数 可以只在函数原型中,声明默认参数即可。 ```c++ char *left( const char *, int n = 1 ); char *left( const char *str, int n ){ ... } ``` ### 引用变量 引用变量的主要用途是作为函数的形参,通过引用,函数内部使用的是传递进来的参数的原始数据,而不是拷贝出来的副本。引入引用主要为了结构与类,减少拷贝,提升性能。 引用在声明的时候,就必须初始化并绑定一个变量: ```c++ int rats; int &rodents = rats; // 声明引用变量 rodents void swap( int &a, int &b ) // 引用变量作为 形参 { int temp; temp = a; a = b; b = temp; } ``` 常规变量 与 `const` 变量都可以视为左值,因为可以通过地址访问它们。但常规变量属于可修改的左值,`const`变量属于不可修改的左值。 ```c++ double refcube( const double &ra ) { return ra * ra * ra; } double side = 3.0; double *pd = &side; double &rd = side; double lens[4] = { 1.0, 2.0, 3.0, 4.0 }; double c1 = refcube( side ); // ra is side double c2 = refcube( lens[2] ); // ra is lens[2] double c3 = refcube( rd ); // ra is rd is side double c4 = refcube( *pd ); // ra is *pd is side double c5 = refcube( 7.0 ); // ra is 临时变量 的引用 double c6 = refcube( side + 10.0 ); // ra is 临时变量 的引用 ``` 应尽可能使用 `const` - `const` 可以避免函数无意中修改数据 - `const` 让函数可以处理`const`与非`const`变量,否则将只能接受非`const`数据 - `const` 使函数能够正确生成并使用临时变量 使用引用需注意,在函数中不要返回局部数据的引用。 什么时候应该使用引用?什么时候应该使用指针?什么时候按值传递呢? - 如果数据很小,如内置类型或小型结构,如果不需要修改传递的值,使用按值传递 - 如果需要修改参数值,则使用指针。 - 如果数据是数组,指针是唯一选择。 - 如果是较大的结构,则使用引用,或者是指针,提高效率。 - 如果数据对象是类对象,则标准方式,就是按引用传递。 ### 函数重载 编译器在函数调用时,根据函数的实际参数的特征,去查找匹配对应的重载函数。通过函数重载来设计一系列函数,它们名称相同,完成相同的工作,但是使用不同的参数列表。 ```c++ void print( const char *, int ); void print( double, int ); void print( int, int ); void print( const char * ); ``` 重载引用参数: ```c++ void staff( double & rs ); // matches modifiable lvalue void staff( const double & rcs ); // matches rvalue, const lvalue void stove( double & rl ); // matches modifiable lvalue void stove( const double & r2 ); // matches const lvalue void stove( double && r3 ); // matches rvalue double x = 55.5; const double y = 32.0; stove( x ); // call stove( double & ) stove( y ); // call stove( const double & ) stove( x + y ); // call stove( double && ) ``` 对于引用参数来说,有三种实参:`modifiable lvalue`、`const lvalue`、`rvalue`,当重载函数只有两个时,匹配情况如`staff()`,当有3个时,匹配情况如`stove()`。假如没有定义`stove( double && )`,则`stove( x + y )`将调用`stove( const double & )`。 ### 函数模板 函数模板是通用的函数描述,模板使用泛型来定义函数。编译时,编译器根据函数调用处使用的具体类型(`int` `double` 自定义类型等),生成一个使用该具体类型的函数,而后调用处的函数就使用该编译器生成的具体类型函数。 在开发中,模板的定义直接写在`.h`中。最终编译后的代码,不包含任何模板,只包含为程序生成的实际调用到的函数。 ```c++ // 普通模板 template <typename T> void swap( T &a, T &b ){ T temp; // ... } // 模板的重载 template<typename T> void swap( T *a, T *b, int n ); // 具体化模板 struct job { char name[40]; double salary; }; template<> void swap( job &, job & ); ``` 对于函数重载、函数模板、函数模板重载,C++编译器需要使用一个优先级策略,来决定最终为调用方,生成和使用哪一个函数定义: - 第一步:创建候选函数列表,包括与被调用函数同名的函数以及模板函数 - 第二步:创建可行函数列表,这些函数的参数数目要与被调用方一致,参数类型的话,可以有隐式转换 - 第三步:确定最佳的可行函数,如果有,则使用它,无则报错 ```c++ may( 'B' ); // 函数调用 // 候选函数列表 void may( int ); # 1 float may( float, float = 3 ); # 2 void may( char ); # 3 char *may( const char * ); # 4 char may( const char & ); # 5 template<typename T> void may( const T & ); # 6 template<typename T> void may( T * ); # 7 ``` 对上述代码,先判断可行函数列表:参数数目一致,且类型能够隐式转换成功。`#4` 与 `#7` 中`char`是无法自动转换为指针类型的,所以排除掉。 接下来确定最佳可行函数,从最佳到最差的顺序: 1. 完全匹配,常规函数 优于 模板 2. 提升转换,比如 `char` `short` 转换为 `int` 3. 标准转换,比如 `int` 转换为 `char`,`long`转换为`double` 4. 用户自定义转换,比如类声明中定义的转换 所以,`#1`(提升转换) 优于 `#2`(标准转换)。`#3` `#5` `#6` 是完全匹配的,都优于 `#1` 和 `#2`。`#3` 与 `#5` 优于 `#6`,因为 `#6` 是模板。 `decltype`类型推断: ```c++ template<typename T1, typename T2> void ft( T1 x, T2 y ) { decltype( x + y ) xpy = x + y; } double x = 5.5; double y = 7.0; double rx = x; const double *pd; long indeed( int ); decltype(x) w; // w is type double decltype(rx) u = y; // u is type double & decltype(pd) v; // v is type double * decltype( indeed(3) ) m; // m is type long ``` 后置返回类型: ```c++ auto ft( int x, float y ) -> double; // 函数返回 double 类型 template<typename T1, typename T2> auto gt( T1 x, T2 y ) -> decltype(x + y) { return x + y; } ``` ## 第9章 内存模型与名字空间 一个项目通常如下组织: ```c++ main.cpp // 主文件,程序入口 a.h // a 头文件 a.cpp // a 的定义 b.h // b 的头文件 b.cpp // b 的定义 ``` 通常是将`a.cpp` `b.cpp` 以及`main.cpp`分别单独编译成`a.o` `b.o` `main.o`临时文件,然后再链接在一起。 一般放在`.h`中的内容: - 函数原型 - 使用`#define`与`const`声明的符号常量 - 结构声明 - 类声明 - 模板定义 - 内联函数 由于使用了多个源代码文件,这里就出现了不同文件的 变量 与 函数 的生存周期、作用域 和 链接性问题。 作用域`scope`:描述了 名称 在文件的多大范围内可见,例如:函数A内的变量只在函数A内可以使用;函数定义之前声明的变量可在所有函数中使用。 链接性`linkage`:描述了 名称 在不同 翻译单元 之间的共享,链接性为 外部的 可以在文件间共享,链接性为 内部的 则只能在当前文件内的函数中使用。 对于变量来说,存在 3 种情况: ```c++ // a.cpp extern int global = 1000; // 静态变量,外部链接性,即其他文件也能访问 static int one_file = 50; // 静态变量,内部链接性,即只能在本文件使用 const int const_int = 60; // 由于const的副作用,这是静态变量,内部链接性 void funct( int n ) { int a = 0; // 内部变量,无链接性,出作用域销毁 static int count = 0; // 静态变量,无链接性,只在本函数内有效 } ``` 对于函数来说,存在 2 种情况: ```c++ void out_func( int a ); // 外部链接性,其他文件也能访问 static void inter_func(); // 内部链接性,只能在本文件访问 ``` C++如何查找函数的定义呢?假设在程序的某个文件中调用一个函数: 1. 如果该文件中,函数声明指出该函数是`static`的,则编译器只在本文件查找该函数定义 1. 否则编译器将在所有程序文件中查找 1. 如果找到两个定义,则报错重复定义 1. 如果程序文件中没有找到,则继续在库中搜索 这意味着,如果定义了一个与库函数同名的函数,则编译器将使用程序员自定义的版本,而不是库函数。 C++ 存储数据的方案: - 自动存储:函数定义里的变量,代码块中的变量,随着代码块执行创建,代码块结束则销毁 - 静态存储:函数定义之外的全局变量,函数中使用`static`声明的,它们在程序的运行期都存在。C++中区分了 3 种静态类型。 - 线程存储:使用`thread_local`声明,其生命周期与所属线程一样长 - 动态存储:程序运行时,使用`new`动态申请的内存将一直存在,直到使用`delete`释放。通常也称为自由存储(`free store`)或堆内存(`heap`) **单定义原则**:变量可以在多个地方声明,但只能有一次定义。 默认情况下,全局变量的链接性都是外部的,但是使用`const`定义的全局变量,会将链接性修改为内部的。可以使用`extern`强制将链接性修改为外部的。因此有两种对全局常量的使用方式 第一种:默认内部链接性,每个`.cpp`文件都有一份相同的常量定义,而不是共享一份常量 ```c++ // const.h const double Pi = 3.14159; // a.cpp #include "const.h" // b.cpp #include "const.h" ``` 第二种:声明使用强制使用外部链接性,定义只放在一个`.cpp`文件 ```c++ // const.h extern const double Pi; // const.cpp #include "const.h" const double Pi = 3.14159; // a.cpp #include "const.h" ``` **volatile** 阻止程序优化: 在编译过程中,如果编译器发现程序在近几条语句中多次使用了某个变量,则编译器会进行优化:将这个值缓存到寄存器中,这样程序就不用多次访问内存取得该值。这种优化的假设前提是,两次取用内存之间,该内存处的值时不变的。但是如果这个变量所在的内存 如果是 某个硬件地址(比如串口),硬件会改变其值;或者 该变量所在的内存是 共享内存,有其他进程 或者 线程会修改 该内存处的值。那么这种编译器的优化,会导致该变量值不一致。当前程序应该使用内存处的值,而不是寄存器缓存的值。对变量声明为 `volatile` 就是为了避免这种优化,让对该变量的读取始终使用内存处的值。 **mutable** 结构内可变变量: ```c++ struct data { char name[30]; mutable int access; }; const data veep = { "codekissyoung", 0 }; strcpy( veep.name, "zhangjian" ); // not allowed veep.access ++; // allowed ``` **语言链接性**: 链接程序要求每个不同的函数要有不同的符号名。在C语言中,一个名称只能对应一个函数,所以C语言的编译器可能将`spiff`这样的函数名,设置其符号名为`_spiff`,称为C语言的链接性。 在C++语言中,由于函数重载、函数模板的存在。对于`spiff(int)`,符号名为`_spiff_i`,而`spiff(double,double)`的符号名为:`_spiff_d_d`,称为C++语言链接性。 假设在 C++中要使用由 C编译器 编译出来的库: ```C++ spiff( 22 ); // from C library ``` 它在C库中符号名为`_spiff`,但是对于C++链接程序来说,C++的查找约定是`_spiff_i`,为了解决这个问题,我们需要在函数原型中指出要使用的约定: ```c++ extern "C" void spiff( int ); // 使用 C 的编译约定 ``` ## 第10章 对象和类 定义一个类,就是实现了一种数据类型,它完成了三项工作: - 决定了数据对象需要的内存大小 - 决定了如何解释内存中的`bit`数据 - 决定了数据对象可以使用的运算符和方法 对于内置类型来说,这些信息都内置在编译器中。而自定义数据类型,则需要程序员自己提供这些信息。这为我们带来了根据需要实际定制的新数据类型的强大功能和灵活性。 此外,`class` 将 数据存储 以及 操纵数据 的方法组合成了一个整体。 声明: ```c++ // stock.h class Stock { private: std::string company; // 持有公司名称 long shares; // 股票数量 double share_val; // 每股价格 double total_val; // 持股总价格 void set_tot(){ total_val = shares * share_val; } public: Stock(); Stock( std::string co, long n = 0 , double pr = 0.0 ); ~Stock(); void buy( long num, double price ); // 买入 void sell( long num, double price ); // 卖出 void update( double price ); // 更新股价 void show() const; // 显示 // 获取总股价更高的那个对象 const Stock& topval( const Stock& s ) const; }; ``` 定义: ```c++ // stock.cpp // 默认构造函数定义 Stock::Stock() : company{"unknow company"}, shares{0}, share_val{0}, total_val{0}{ } // 普通构造函数定义 Stock::Stock( string co, long n, double pr ) : company{ std::move(co) }, shares{n}, share_val{pr}, total_val{0} { if( n < 0 ) { cout << "Number of shares can not be negative " << company << " shares set to 0 \n"; shares = 0; } set_tot(); } // 析构函数,对象被销毁时调用 Stock::~Stock() { cout << company << " ~Stock() called" << endl; } void Stock::buy( long num, double price ) { if( num < 0 ) { cout << "购买不能为 0 " << endl; } else { shares += num; share_val = price; set_tot(); } } void Stock::sell( long num, double price ) { if( num < 0) cout << "售出不能为 0 " << endl ; else if( num > shares ) cout << "存量不够" << endl; else { shares -= num; share_val = price; set_tot(); } } void Stock::update( double price ) { share_val = price; set_tot(); } void Stock::show() const { cout << "公司: " << company << "\t" << "持有: " << shares << "\t" << "股价: $" << share_val << "\t" << "总值: $" << total_val << endl; } // this 指针 const Stock &Stock::topval( const Stock &s ) const { if ( s.total_val > total_val ) return s; else return *this; } ``` 使用: ```c++ // main.cpp vector<Stock> my_stocks; Stock baidu { "baidu", 189, 23.24 }; Stock sina { "Sina", 190, 54.32 }; Stock sohu { "Sohu", 342, 10.32 }; Stock ali { "ali", 1000, 382.23 }; my_stocks.push_back( baidu ); my_stocks.push_back( sina ); my_stocks.push_back( sohu ); my_stocks.push_back( ali ); for( auto &x : my_stocks ) { x.show(); } ``` ## 第11章 使用类 **运算符重载**: 运算符重载使得操作对象更美观,更优雅。 **友元函数**: 通过在类内部声明 某函数 为本类的友元函数,则该函数可以使用类内部的`private`数据。 ```c++ class Time { private: int hours; int minutes; public: Time operator+( const Time &t ) const; // 成员函数重载运算符 + friend std::ostream &operator<<( std::ostream &os, const Time &t ); friend Time operator+( const Time &t1, const Time &t2 ); // 非成员函数的运算符重载 + }; // T1 = T2 + T3 转换为 T1 = T2.operator+( T3 ); 也就是说,只有当本对象 处于 T2 位置时才会触发调用 Time Time::operator+( const Time &t ) const { Time sum; sum.minutes = minutes + t.minutes; sum.hours = hours + t.hours + sum.minutes / 60; sum.minutes %= 60; return sum; } // T1 = T2 + T3; 转换为 T1 = operator+( T2, T3 ); Time operator+( const Time &t1, const Time &t2 ) { Time sum; sum.minutes = t1.minutes + t2.minutes; sum.hours = t1.hours + t2.hours + sum.minutes / 60; sum.minutes %= 60; return sum; } std::ostream &operator<<( std::ostream &os, const Time &t ) { os << t.hours << " hours, " << t.minutes << " minutes"; // 能直接使用 t 的私有数据了 return os; } ``` 重载限制: - 重载后的运算符必须至少有一个操作数是用户定义的类型,这将防止用户为内置类型重载运算符 - 使用运算符时,不能违反原来的语法规则,即运算符要求的操作数 以及 优先级、结合性都不变 - 只能重载C++已有的部分运算符,不包括`sizeof`、`.`、`::`、`?:`、`const_cast`等 - `=`、`()`、`[]`、`->`只能使用成员运算符重载 - 对于同一个运算符来说,成员函数运算符重载 与 非成员函数运输符重载 必须 2 选 1,对于某些运算符来说,成员函数运算符重载是唯一选择;而有些运算符,使用 非成员函数运算符重载 + 友元声明 配合起来使用,效果会更好,比如上述 `+`、`<<` 等。 ### 类的自动装换 和 强制类型装换 对于`String bean = "pinto";`这句代码,`"pinto"`是C风格字符串,类型是`char *`,由于`String`类定义了`String( char * )`,便能够这样写了,底层默认执行`String( char * )`构造函数,看起来就像是`"pinto"`自动转换成了`String`类型一样。 ```c++ class Stonewt { private: enum{ Lbs_per_stn = 14 }; int stone = 0; double pds_left = 0.0; double pounds = 0.0; public: Stonewt() = default; explicit Stonewt( double lbs ); ~Stonewt() = default; explicit operator int() const; explicit operator double() const; }; // 当 对象 = double类型; 时,自动调用 Stonewt::Stonewt( double lbs ) { stone = int(lbs) / Lbs_per_stn; pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs); pounds = lbs; } // 当对象作为 int 时,自动调用本函数 Stonewt::operator int() const { return lround( pounds ); } // 当对象作为 double 时,自动调用本函数 Stonewt::operator double() const { return pounds; } ``` C++允许指定在类和内置类型之间进行转换: - 只有一个参数的构造函数,用于将类型与该参数相同的值转换为 类类型,例如,将 `double` 值赋值给 `Stonewt` 对象时,接受 `double` 参数的 `Stonewt` 类构造函数将自动被调用。 - 通过转换函数`operator typeName();`,将类对象赋值给`typeName`变量时,或将类强制转换为`typeName`变量时,该转换函数自动被调用 - 当不希望编译器进行隐式的`对象 -> 内置类型` 或 `内置类型 -> 对象`的转换的话,则使用`explicit`声明它。 ## 第12章 类和动态内存分配 为了让程序在运行时决定内存分配,而不是在编译时确定,我们需要在类中使用`new`与`delete`控制内存分配。遗憾的是,这将会带来一些新的编程问题,现在就看看如何处理这些问题。 C++自动为类提供以下成员函数: - 默认构造函数 - 默认析构函数 - 复制构造函数,用于初始化过程中,原型为`Class_name(const Class_name &)` - 赋值运算符,将一个对象赋值给另一个对象时,自动调用 - 取地址运算符`&`,默认返回this指针的地址 - 移动构造函数(C++11) - 移动赋值运算符(C++11) 默认的复制构造函数的作用是:逐个复制非静态成员的值到新对象,也称为浅拷贝。浅拷贝带来的问题是,对于在类内使用`new`申请的动态内存,浅拷贝只复制了该内存的指针,而没有开辟新的动态内存空间,所有两个对象的指针成员指向的是同一块内存。 默认赋值运算符也是同样的问题。 复制构造函数的调用时机,一般来说,在涉及到按值传递的时候,都会调用: ```c++ // motto is StringBad object StringBad ditto( motto ); StringBad metoo = motto; StringBad also = StringBad(motto); StringBad *pStringBad = new StringBad( motto ); ``` 赋值运算符 与 复制构造函数类似,但是有一些区别: - 复制构造函数是使用旧对象**新生成**对象时调用,所以不需要清理新对象中的动态内存,而赋值运算符是两个已经生成的对象之间的赋值,所以被赋值的对象应该先清理`delete`它里面的动态内存,再申请新内存去存储拷贝过来的值。 - 第二,赋值运算符应该避免给对象自身赋值,这非常重要,因为上述原因,很可能清除对象的动态内存,所以我们应该先判断此次赋值操作是否为自身赋值,如果是,直接返回对象本身,不要做任何多余操作。 - 复制构造函数不需要返回任何数据,而赋值运算符需要返回对象的引用`return *this;`。 多个构造函数只对应一个析构函数,所以使用`new`声明,与使用`new[]`申请的内存,在析构函数中必须使用对应的`delete`与`delete[]`,对于同一个变量,在不同的构造函数中,不允许即使用`new`声明,又使用`new[]`声明。 函数或方法返回对象的方式: ```c++ // 拷贝方式返回 s1 或 s2, 这将调用 复制构造函数 StringBad Max( const StringBad &s1, const StringBad &s2 ); // 返回 s1 或 s2 的常量引用(因为入参是const), 不需要调用 复制构造函数,效率更高 const StringBad &Max( const StringBad &s1, const StringBad &s2 ); // 返回非常量引用 ostream &operator<<( ostream &os, const StringBad &st ); // 返回常量对象, 为了避免出现 if( str1 + str2 = "something" ) 能编译成功 const StringBad StringBad::operator+( const StringBad &s1, const StringBad &s2 ); ``` 使用指向对象的指针: ```c++ Class_name *p_class = new Class_name(value); // 调用构造函数 Class_name(Type_name value); Class_name *ptr = new Class_name; // 调用默认构造函数 delete p_class; // 使用delete后,才调用 Class_name 的析构函数 delete ptr; ``` 如果`Class_new`内部也使用了`new`与`delete`申请动态内存的话,那么上述代码就在两个层次上使用了动态内存。以`StringBad`举例: - `StringBad`内部使用了`new`为存储`str`字符串申请了堆内存 - 在调用端`new StringBad`操作,为存储`StringBad`本身申请了堆内存,存储了`str`指针、`len`成员,`num_strings`则是独立存储在静态变量区的。 当不需要对象时,在调用处也必须使用`delete`去释放`Class_name`对象本身,`Class_name`本身释放时,也会调用自身的析构函数去释放`str`指针指向的内存。 `StringBad`例子: ```c++ // StringBad.h class StringBad { private: char *str; // 指向string实际存储的char数组 int len = 0; // char数组长度 static int num_strings; // StringBad 类构造的对象的个数 public: StringBad(); // 默认构造函数 ~StringBad(); // 析构函数 StringBad( const char *s ); // 构造函数,不使用 explicit,因为这个隐式转换很常见和方便 StringBad( const StringBad &st ); // 复制构造函数 int length() const { return len; } StringBad &operator=( const StringBad &st ); StringBad &operator=( const char * ); char &operator[]( int i ); const char &operator[]( int i ) const; friend bool operator<( const StringBad &st, const StringBad &st2 ); friend bool operator>( const StringBad &st, const StringBad &st2 ); friend bool operator==( const StringBad &st, const StringBad &st2 ); friend std::ostream &operator<<(std::ostream &os, const StringBad &st ); friend std::istream &operator>>(std::istream &is, StringBad &st); static int HowMany(){ return num_strings; } }; std::ostream &operator<<( std::ostream &os, const StringBad &st ); std::istream &operator>>( std::istream &is, StringBad &st ); bool operator<( const StringBad &st, const StringBad &st2 ); bool operator>( const StringBad &st, const StringBad &st2 ); bool operator==( const StringBad &st, const StringBad &st2 ); ``` ```c++ // StringBad.cpp int StringBad::num_strings = 0; // 必须在此处初始化,而不是在声明处 StringBad::StringBad() : len{0} { str = new char[1]; str[0] = '\0'; ++num_strings; } StringBad::~StringBad() { cout << --num_strings << " StringBad object left" << endl; delete[] str; } StringBad::StringBad( const char *s ) { len = strlen( s ); str = new char[len + 1]; strcpy( str, s ); ++num_strings; } StringBad::StringBad( const StringBad &st ){ ++num_strings; len = st.len; str = new char[len + 1]; strcpy( str, st.str ); } // assign StringBad to StringBad StringBad &StringBad::operator=( const StringBad &st ){ if( this == &st ) return *this; delete[] str; len = st.len; str = new char[len + 1]; strcpy(str, st.str); return *this; } // assign C-Style-string to StringBad StringBad &StringBad::operator=(const char *s ) { delete[] str; len = strlen(s); str = new char[len + 1]; strcpy( str, s ); return *this; } // read-write char access for StringBad char &StringBad::operator[](int i) { return str[i]; } // 在重载时,C++区分const与non-const特征标,所以这里提供一个仅供 const StringBad 对象使用的版本 const char &StringBad::operator[](int i) const { return str[i]; } bool operator<( const StringBad &st1, const StringBad &st2 ) { return strcmp(st1.str, st2.str ) < 0 ; } bool operator>( const StringBad &st1, const StringBad &st2 ){ return st2 < st1; } bool operator==( const StringBad &st1, const StringBad &st2 ){ return 0 == strcmp( st1.str, st2.str ); } istream &operator>>( istream &is, StringBad &st ){ char temp[80]; is.get( temp, 80 ); if( is ) st = temp; while( is && is.get() != '\n' ) continue; return is; } ostream &operator<<( ostream &os, const StringBad &st ) { os << st.str; return os; } ``` ### 定位new技术 ```c++ const int BUF = 1024; class JustTesting{ private: string words; int number; public: JustTesting( const string &s = "Just Testing", int n = 0 ) : words{s}, number{n} { cout << "constructed" << endl; } ~JustTesting() { cout << words << " ~JustTesting" << endl; } void show() const{ cout << words << ", " << number << endl; } }; int main( int argc, char *argv[] ) { char *Buffer = new char[BUFSIZ]; JustTesting *pc1 = new (Buffer) JustTesting; JustTesting *pc2 = new JustTesting( "Heap1", 20 ); JustTesting *pc3 = new (Buffer + sizeof(JustTesting)) JustTesting( "Bad Idea", 6 ); JustTesting *pc4 = new JustTesting( "Heap2", 10 ); cout << (void *)Buffer << endl; cout << pc1 << endl; cout << pc3 << endl; cout << pc2 << endl; cout << pc4 << endl; delete pc2; delete pc4; delete[] Buffer; return EXIT_SUCCESS; } ``` 上述代码中,使用定位`new`从`Buffer`中为对象分配内存,需要注意的点: - `pc3` 如果从`Buffer`开始申请,会覆盖掉`pc1` - 定位`new`申请的内存,不能使用`delete`去删除,否则会发生运行时错误 该技术能用到的地方有:写内存池、垃圾收集、以及调试。 ## 第13章 类继承 继承是一种很好的代码重用的技术。 公有`public`派生: - 基类的公有成员将成为派生类的公有成员 - 基类的私有部分也将成为派生类的一部分,但是**只能通过基类的public和protect方法访问** - 派生类对象存储了基类的数据成员 - 派生类对象可以使用基类的方法 创建派生类对象之前,一定会先创建基类对象,派生类的构造函数必须调用基类的构造函数,如果未能显式调用,则编译器会使用基类的默认构造函数。 派生类构造函数要点: - 首先创建基类对象 - 派生类构造函数必须调用一个基类构造函数,可以通过成员初始化列表指定要使用的基类构造函数,并将数据传递给基类构造函数 - 派生类构造函数应该初始化派生类新增的数据成员 - 派生类对象过期时,首先会调用派生类的析构函数,然后再调用基类的析构函数 ```c++ class TableTennisPlayer{ private: string firstname; // string lastname; // bool hasTable; // 是否有球桌? public: TableTennisPlayer(const string &fn, const string &ln, bool ht = false ) : firstname{fn},lastname{ln},hasTable{ht} { } void name() const{ cout << lastname << "," << firstname << endl; }; bool HasTable() {return hasTable;} void ResetTable(bool v ) {hasTable = v;}; }; class RatePlayer : public TableTennisPlayer{ private: unsigned int rating; // 参与比赛次数 public: explicit RatePlayer(unsigned int, const string &fn = "none", const string &ln = "none", bool ht = false ) : TableTennisPlayer(fn, ln, ht), rating{r} { } RatePlayer(unsigned int r, const TableTennisPlayer &tp ) : TableTennisPlayer(tp), rating{r} { } unsigned int Rating() const { return rating; } void ResetRating(unsigned int r ){ rating = r; } }; ``` 派生类与基类之间的关系: - 派生类对象可以使用基类的非`private`方法 - 基类指针可以在 **不进行显式类型转换** 的情况下,指向派生类对象,但是该指针只能调用基类方法 - 基类引用可以在 **不进行显式类型转换** 的情况下,引用派生类对象,但是该引用只能调用基类方法 - 不可以将基类对象以及指针,赋值给派生类的引用 或者 指针 ```c++ void show( const TableTennisPlayer &tp ) { tp.name(); if( tp.HasTable() ) cout << "has table" << endl; else cout << "no table" << endl; } TableTennisPlayer cao { "kaiyan", "cao", false }; RatePlayer zhan { 123, "jian", "zhang", true }; show( cao ); show( zhan ); ``` 派生类与基类之间的特殊关系是基于C++继承的底层模型的。 对于同一个方法,如果我们希望它在基类与派生类中的行为是不同的。即方法的行为取决于调用该方法的对象。这称为**多态**。实现多态: - 在派生类中重新定义基类中的方法 - 使用虚方法 ```c++ class Brass{ private: std::string fullName; // 客户姓名 long acctNum; // 账号 double balance; // 资金结余 public: Brass( string s, long an, double bal ) : fullName{std::move(s)}, acctNum{an}, balance{bal} { } virtual ~Brass() = default; // 存款 void Deposit( double amt ){ balance += amt; cout << fullName << " 存入 " << amt << " 余额:" << balance << endl; } // 提现 virtual void Withdraw( double amt ){ if( amt <= balance ) { balance -= amt; cout << fullName << " 取出 " << amt << " 余额:" << balance << endl; }else{ cout << "您的余额不足" << endl; } } virtual void ViewAcct() const{ cout << "姓名: " << fullName << endl; cout << "账号: " << acctNum << endl; cout << "余额: " << balance << endl; } double Balance() const{ return balance; } }; class BrassPlus : public Brass{ private: double maxLoan; // 贷款上限 double rate; // 贷款费率 double owesBank; // 欠款金额 public: BrassPlus(const string &s, long an, double bal, double ml, double r ) : Brass{s,an,bal}, maxLoan{ml}, rate{r}, owesBank{0.0} { } BrassPlus(const Brass &ba, double ml, double r ) : Brass{ba}, maxLoan{ml}, rate{r}, owesBank{0.0} { } void ViewAcct() const override{ Brass::ViewAcct(); cout << "贷款上限:" << maxLoan << endl; cout << "贷款费率: " << rate << endl; cout << "欠款金额: " << owesBank << endl; } void Withdraw( double amt ) override{ if( amt <= Balance() ) { Brass::Withdraw( amt ); } else if( amt <= Balance() + maxLoan - owesBank ) { double advance = amt - Balance(); owesBank += advance * (1.0 + rate); Deposit( advance ); Brass::Withdraw( amt ); } else { cout << "贷款金额超额" << endl; } } void ResetMax( double m ) { maxLoan = m; } void ResetRate( double r ) { rate = r; } void ResetOwes() { owesBank = 0; } }; ``` 多态的体现: ```c++ Brass cao ("codekissyoung", 38123, 4000.0 ); BrassPlus zhan ("zhangjian", 38124, 5000.0, 10000.0, 0.04 ); Brass* accout_list[2]; accout_list[0] = &cao; accout_list[1] = &zhan; for( int i = 0; i < 2; ++i ){ accout_list[i]->ViewAcct(); // 这句就是 多态的 体现,Brass基类的指针,能够根据情况分别调用 基类 与 派生类的实现 cout << endl; } ``` ### 动态绑定 虚函数的实现 通常情况下,C++不允许 A 类型的指针 指向 B 类型的对象,也允许 A 类型的引用 与 B 类型的对象绑定在一起。 但是对于 A 与 B 是继承关系的 类 来说, 基类的指针与引用是可以指向或绑定到派生类的: ```c++ BrassPlus zhan ("zhangjian", 38124, 5000.0, 10000.0, 0.04 ); Brass *pb = &zhan; Brass &rb = zhan; ``` 考虑下面代码: ```c++ BrassPlus zhan ("zhangjian", 38124, 5000.0, 10000.0, 0.04 ); Brass *pz = &zhan; pz -> ViewAcct(); // 调用 Brass 的实现,还是调用 BrassPlus 的实现? ``` 指针`pz`在编译时类型 已知 且 固定,若`ViewAcct()`未声明为`virtual`则 编译器 采用**静态编译**,与`Brass`指针绑定的方法就是`Brass::ViewAcct()`,所以这种情况,即便原始对象为`BrassPlus`,但使用`Brass`类型指针调用,实际执行的代码也是`Brass`的实现。 如果`ViewAcct()`被声明为`virtual`虚函数呢?我们先来看看虚函数的原理与实现: 编译器在处理虚函数: - 给每个对象添加一个隐藏成员`*vtpl`,它指向了一个数组,数组的成员是 函数地址(称为**虚函数表**) - 只有 虚函数 的函数地址才会 存入该虚函数表 - 如果派生类中,重新实现了该虚函数,则新实现函数的地址 会 存入 派生类对象的 虚函数表中,如果派生类未实现,则存入基类的 虚函数实现 地址 - 注意,无论类中包含几个虚函数,对象都只有一个隐藏成员,只是不同 对象 的该隐藏成员指向的 虚函数表 的大小不同而已 原理图示如下: ```c++ class Scientist{ char name[40]; public: virtual void show_name(); virtual void show_all(); }; class Physicist : public Scientist{ char field[40]; public: void show_all(); // redefined virtual void show_field(); }; ``` ![虚函数的原理](https://img.codekissyoung.com/2019/05/27/96bd6555c0b9fd246b3112e69111e76b.png) PS: 基类中使用`virtual`声明方法,则该方法在所有派生类中的都是`virtual`的 PS: 如果要在派生类中重新定义基类的方法,通常应将基类方法声明为虚的。这样,程序将根据实际的对象类型,而不是 引用 或 指针的类型来选择方法版本 虚函数还需要注意的点: - 构造函数不能是虚函数。创建派生类对象,使用的是派生类的构造函数,然后由它使用基类的一个构造函数。这是不同于虚函数的一套继承机制。 - 基类的析构函数应当声明为`virtual` - 如果基类声明`virtual`的方法有多个重载版本,则应该在派生类中重新定义该方法所有的重载版本 `protected`访问控制: - 对于数据成员,派生类能直接访问基类的`protected`数据成员 - 对于成员方法,派生类能通过基类名字调用其`protected`成员方法。它能够声明让派生类能够访问,而公众不能访问的基类的内部函数。 ### 纯抽象类 ABC 假设现在要构造一个`Ellipse`(椭圆)类和一个`Circle`(圆)类,如果两者是`is-a`的关系,则派生会显得笨拙: - 圆 只需要 一个半径 就可以描述大小,而椭圆需要 长半轴 和 短半轴 - 其他问题...等等 但是圆与椭圆又有非常多的共性。所以,我们提出一种方案,将它们的共性抽象出来,放到一个纯抽象类`BaseEllipse`中,然后从该类派生出`Circle`与`Ellipse`类。这样就可以使用`BaseEllipse`的指针,同时管理`Circle`与`Ellipse`对象。 ```c++ class BaseEllipse{ public: void move( int nx, int ny ) { x = nx; y = ny; } virtual double Area() const = 0; // 纯虚函数 }; ``` 要成为`ABC`,必须至少包含一个纯虚函数(`= 0`声明),纯抽象类不能用来创建对象。 ### 继承 与 类动态内存分配 如果在类内,使用了`new`与`delete`申请并管理了堆内存,并且重新定义了赋值运算符与拷贝构造函数。那么派生类的实现将有哪些问题呢? 如果派生类中不再使用`new`: - 对于析构函数,派生类使用默认生成的析构函数,不执行任何操作,之后自动调用基类的析构函数,正是我们想要的 - 对于拷贝构造函数,派生类使用默认生成的拷贝构造函数,对于派生类中新数据成员执行成员复制,然后再调用基类的拷贝构造函数,对继承自基类的数据成员进行复制,正是我们想要的 - 对于赋值运算符,与拷贝构造函数类似,也是我们想要的 如果派生类中使用了`new`: - 对于析构函数,派生类必须自己去`delete`自己的数据成员,然后再调用基类的析构函数去释放积累中的堆内存数据 - 拷贝构造函数也需要派生类自己显式定义 - 赋值运算符 也一样 ```c++ // 析构函数 Base::~Base(){ delete[] label; } Child::~Child(){ delete[] style; } // 拷贝构造函数 Base::Base( const Base &bs ){ label = new char[strlen(bs.label) + 1]; strcpy( label, bs.label ); rating = bs.rating; } Child::Child( const Child &cd ) : Base( cd ) // 这步非常重要,初始化列表中调用基类的拷贝构造函数 { style = new char[strlen(cd.style) + 1]; strcpy( style, cd.style ); } // 赋值运算符 Base &Base::operator=( const Base &bs ){ if( this == &bs ) return *this; delete[] label; label = new char[strlen(bs.label) + 1]; strcpy( label, bs.label ); rating = bs.rating; return *this; } Child &Child::operator=( const Child &cd ){ if( this == &cd ) return *this; Base::operator=( cd ); // 这步非常重要,显式调用基类的赋值运算符,复制基类中的数据 delete[] style; style = new char[strlen(cd.style) + 1]; strcpy(style,cd.style); return *this; } ``` 友元函数并非成员函数,所以不具有继承性,基类有基类的友元函数,派生类有派生类的友元函数。在派生类的友元函数中,可以将派生类的引用和指针转换为基类的引用和指针,从而复用基类的友元函数。 成员函数属性表: ![成员函数属性表](https://img.codekissyoung.com/2019/05/27/856803e250774c1b9b268110ed42b1c2.png) 可以将派生类对象的地址赋值给基类指针么(或派生类对象绑定到基类引用)?反过来呢? - 可以,多态的基本操作(向上转换) - 使用 强制类型转换、`dynamic_cast`等强制类型转换,可以实现(即向下转换),但是使用这样的指针(或引用)并不一定安全。 可以将派生类对象赋值给基类对象么?反过来呢? - 可以,并且是使用基类的`operator=`进行赋值,派生类中新增的数据成员不会传递给基类对象 - 当且仅当派生类定义了 参数为基类引用(唯一) 的构造函数 或 以基类为参数的赋值运算符时,才会发生`派生对象 = 基类对象;`这样的赋值操作 假设定义了一个函数,它的参数为 基类对象(按值传递)。该函数可以接收 派生类对象 么? - 可以,但是会调用基类的 复制构造函数 生成一个 新的 基类对象作为实际入参,该对象的成员对应于 派生对象 的基类部分。 假设定义了一个函数,它的参数为 基类对象的引用,该函数可以接收 派生类对象 么? - 可以,多态类型的基本操作。按引用传递对象(而不是按值),既可以从 虚函数的多态 机制中收益,又可以节省内存 和 提升效率,加上`const`还可以保护原始数据。 ## 第14章 C++的代码重用 ### 包含对象成员的类 实现 has-a 关系 代码中使用了`string`类 以及 `valarray` 类的对象,作为数据成员。 ```c++ class Student{ private: typedef std::valarray<double> ArrayDb; std::string name; // 姓名 ArrayDb scores; // 分数 public: Student() : name{"Null student"}, scores{} {} explicit Student( string s ) : name(std::move(s)), scores{} { } ~Student() = default; double average() const{ if( scores.size() > 0 ) return scores.sum() / scores.size(); else return 0; } const string &Name() const{ return name; }; }; ``` ### 私有继承 + 多重继承 实现 has-a 关系 私有继承中,基类的`public`与`protected`成员都将成为派生类的`private`成员。即获得基类的实现,当不获得接口。 ```c++ class Student : private std::string, private std::valarray<double>{ private: typedef std::valarray<double> ArrayDb; public: Student( const char *str, const double *pd, int n ) : std::string(str), ArrayDb( pd, n ) {} double average () const{ if( ArrayDb::size() > 0 ) return ArrayDb::sum() / ArrayDb::size(); else return 0; } const string &Name() const{ return (const string &)*this; } }; ``` PS: 通常应该使用对象作为数据成员的方式来实现`has-a`关系,私有继承 + 多重继承 不易于理解,且代码怪异! `public` `protected` 与 `private`继承: ![WX20190528-145747.png](https://img.codekissyoung.com/2019/05/28/06b36768cc48886f8f5a069492ab827c.png) ### 多继承 MI 个人觉得,因为多继承会使代码变得隐晦,并且很容易引入错误,所以最好的办法就是重新考虑自己的代码设计,不要使用多继承。 - [C++多重继承](https://www.cnblogs.com/xingchenfeng/p/3773890.html) - [说说C++多重继承](https://www.cnblogs.com/mengwang024/p/4375357.html) ### 类模板 一个栈的类模板示例(只含有一个类型参数): ```c++ #ifndef _STACK_H_ #define _STACK_H_ #include <iostream> template <typename Item> class My_stack { private: enum { SIZE = 10 }; // 默认栈的大小 int top; // 栈顶 int size; // 栈大小 Item *items; // 内部数据结构,使用堆内数组实现 public: My_stack() : top{0}, size{SIZE}, items{ new Item[SIZE] } { }; explicit My_stack( int ss ) : size{ ss }, top{0}, items{ new Item[ss]} { } My_stack( const My_stack &st ); ~My_stack() { std::cout << "~My_stack called" << std::endl; } bool isempty() const{ return top == 0; } bool isfull() const{ return top == size; } bool push( const Item &item ); bool pop( Item &item ); My_stack<Item> &operator=( const My_stack &st ); }; template<typename Item> My_stack<Item> &My_stack<Item>::operator=(const My_stack &st) { if( this == &st ) return *this; top = st.top; size = st.size; delete[] items; items = new Item[size]; for( int i = 0; i < size; ++i ) items[i] = st.items[i]; return *this; } template <typename Item> bool My_stack<Item>::push( const Item &item ) { if( isfull() ) { return false; }else{ items[top++] = item; return true; } } template <typename Item> bool My_stack<Item>::pop( Item &item ) { if ( isempty() ){ return false; } else { item = items[--top]; return true; } } template<typename Item> My_stack<Item>::My_stack(const My_stack &st) { size = st.size; top = st.top; items = new Item[size]; for( int i = 0; i < size; ++i ) { items[i] = st.items[i]; } } #endif ``` 定长数组示例(包含类型参数 与 非类型参数): ```c++ #ifndef CPP_MY_ARRAY_H #define CPP_MY_ARRAY_H #include <iostream> #include <cstdlib> template <typename T, int n> class My_array { private: T ar[n]; public: explicit My_array( const T &v ); My_array() : My_array(0) { } virtual T &operator[]( int i ); virtual T operator[]( int i ) const; ~My_array(){ std::cout << "~My_array called!" << std::endl;} }; template<typename T, int n> My_array<T, n>::My_array(const T &v) { for( int i = 0; i < n; ++i ) ar[i] = v; } template<typename T, int n> T &My_array<T, n>::operator[](int i) { return ar[i]; } template<typename T, int n> T My_array<T, n>::operator[](int i) const { return ar[i]; } #endif //CPP_MY_ARRAY_H ``` `Pair`类模板示例(使用两个类型参数): ```c++ #ifndef CPP_MY_PAIR_H #define CPP_MY_PAIR_H template <typename T1, typename T2> class My_pair { private: T1 a; T2 b; public: My_pair() = default; My_pair( const T1 &av, const T2 &bv ); T1 &first() { return a; } T2 &second() { return b; } T1 first() const; T2 second() const; }; template<typename T1, typename T2> My_pair<T1, T2>::My_pair(const T1 &av, const T2 &bv) : a{av}, b{bv}{ } template<typename T1, typename T2> T1 My_pair<T1, T2>::first() const { return a; } template<typename T1, typename T2> T2 My_pair<T1, T2>::second() const { return b; } #endif //CPP_MY_PAIR_H ``` 模板类的类型参数默认值: ```c++ template<typename T1, typename T2 = int> ``` **具体化版本的模板类**:用于某些特殊类型不适用于定义好的模板类的情况,比如模板使用`>`运算符比较大小,对于数字类型或者是定义了`operator>()`运算符的类型都适用,但是对于`const char *`字符串来说,没有`>`运算符,只有`strcmp`函数,这个时候,我们就需要为这么一种特殊情况,定义该模板类的具体化版本。 ```c++ template<> class SortedArray<const char*> { // ... } ``` ## 第15章 友元、异常和其他 ### 友元类与友元成员函数 友元: 绕过`private`访问控制,直接访问类内私有数据。 ```c++ class Tv{ public: friend class Remote; // 友元类,Remote中可以任意访问Tv中私有数据 friend void Remote::set_chan( Tv &t, int c ); // 友元成员方法 }; ``` 嵌套类作用域: ![嵌套类作用域](https://img.codekissyoung.com/2019/05/28/26004897aecc93ff566531246a081638.png) ```c++ class Queue{ private: enum { SIZE = 10 }; class Node{ Item item; Node *next; Node( const Item &i ) : item(i), next(0) { } }; Node *front; Node *rear; }; ``` ### 异常 C++异常是对程序运行过程中发生的异常情况的一种响应。异常提供了将控制权从程序的一个部分传递到另一个部分的途径。 ```c++ while( cin >> x >> y ) { try{ z = hmean( x, y ); }catch( const char *s ){ cout << s << endl; cout << "Enter a new pair of numbers: "; continue; } cout << "answer : " << z << endl; } double hmean( double a, double b ) { if( a == -b ) throw "bad hmean() arguments: a = -b not allowed"; return 2.0 * a * b / (a + b); } ``` 上述代码: 1. 程序在`try`块中调用`hmean()` 1. `hmean()`引发异常(类型为`char *`),从而执行`catch( const char *s)` 块,将异常字符串赋给s 1. `catch`块返回到`while`循环开始位置,即处理了异常 引发异常的函数通常要`throw`一个对象,这样我们就可以根据该对象的类型,来区分不同的函数在不同的情况下引发的异常。对象还可以携带信息,根据这些信息来确定引发异常的原因,并采取相应措施。 `throw`和`return`之间的区别何在? - 假设`f1()`调用函数`f2()`,`f2()`返回后,执行`f1()`中调用`f2()`处后面一句代码。如果是`throw`的话,将先返回`f1()`处找`try catch`块,如果找不到继续往上层调用处找,找到后,执行匹配的`catch`块,而不是`f1()`调用`f2()`处后面一句代码。 假设有一个从异常基类派生来的异常类层次结构,则应该按什么顺序放置`catch`块? - 应按从子孙到祖先的顺序排列`catch`语句块 ### RTTI 运行时类型识别 C++有3个支持`RTTI`的元素: - `dynamic_cast`试图将一个指向基类的指针,转化为指向派生类的指针,否则返回`nullptr` - `typeid`返回一个指出对象的类型的值 - `type_info`结构存储了有关特定类型的信息 只能将`RTTI`运用于包含虚函数的类层次结构,因为只有这里才会将派生对象的地址赋值给基类指针。 ```c++ class Grand{ }; class Superb : public Grand{ }; class Magnificent : public Superb{ }; Grand *pg = new Grand; Grand *ps = new Superb; Grand *pm = new Magnificent; // 强制类型转换 Magnificent *p1 = (Magnificent *)pm; // 安全,同类型指针 Magnificent *p2 = (Magnificent *)pg; // 不安全,基类到派生的转换 Superb *p3 = (Magnificent *)pm; // 安全,派生类到基类的转换 // RTTI Superb *p4 = dynamic_cast<Superb *>( pg ); // pg 能否安全地转为 Superb * 类型? 不能 返回 nullptr if( ps = dynamic_cast<Superb *>(pm) ) ps -> speak(); ``` ![Screenshot from 2019-05-29 00-01-09.png](https://img.codekissyoung.com/2019/05/29/6183fa4fd5976159441203fe5a2675e2.png) ```c++ if( typeid(*pg) == typeid(Magnificent) ) cout << "pg为真正的 magnificent 指针"; ``` 类型转换运算符: ```c++ // dynamic_cast if( ps = dynamic_cast<Superb *>(pm) ) ps -> speak(); // const_cast void change( const int *pt, int n ){ int *pc = const_cast<int *>(pt); // 去除了 const 属性 *pc += n; } // static_cast // High 是基类,Low是High的派生类,Pond 是一个无关的类 High bar; Low blow; High *ph = static_cast<High *>(&blow); // 正确 向上转换 Low *pl = static_cast<Low *>(&bar); // 正确,向下转换,pl指针的使用要小心,不安全 Pond *pp = static_cast<Pond *>(&blow); // 错误 // reinterpret_cast ``` ## 第16章 string类与标准模板库 ### string类 `string`类的构造函数: ![WX20190529-115342.png](https://img.codekissyoung.com/2019/05/29/2442c8de4b0ced1829f82cdd0f4a7a21.png) 知道有哪些输入方式可用,对于`C-style`字符串: ```c++ char info[100]; cin >> info; cin.getline( info , 100 ); cin.get( into, 100 ); ``` 对于`string`类: ```c++ string stuff; cin >> stuff; getline( cin, stuff ); // string 版本的 ``` PS: `getline`还可以传第三个参数,一个确定输入边界的字符 `string`库实际上是基于`basic_string`类的,有4个具体化: ```c++ typedef basic_string<char> string; typedef basic_string<wchar_t> wstring; typedef basic_string<char16_t> u16string; // C++11 typedef basic_string<char32_t> u32string; // C++11 ``` ### 智能指针模板类 **智能指针**是行为类似于指针的类对象,它模仿了指针的使用,并且还实现了其他有用的功能。 ```c++ void remodel( string &str ) { string *ps = new string( str ); // ... str = *ps; } ``` 上述代码中,每次该函数调用时,都从堆内存分配内存,但是从不回收,从而导致内存泄漏。 当`remodel()`函数终止,所有函数内的局部变量都从栈内存中删除,包括`ps`指针,如果此时`ps`指向的内存也被释放,那就完美了。如果`ps`有一个析构函数,该函数在指针`ps`被删除时清理指针指向的内存,但是`ps`只是一个常规指针,不是有析构函数的类对象。假如我们构造一个可以模拟`ps`操作的对象呢?在对象过期时,它的析构函数自动执行清理堆内存。这正是`auto_ptr`、`unique_ptr`和`shared_ptr`背后的思想。 `auto_ptr`是`C++98`提供的解决方案,`C++11`中已废弃,推荐使用`unique_ptr`与`shared_ptr`。 ```c++ void remodel( string &str ) { auto_ptr<string> ps { new string( str ) }; // ... str = *ps; } ``` ![WX20190529-140855.png](https://img.codekissyoung.com/2019/05/29/3e024f4c80abdaca13a65973962ffc1c.png) 使用`shared_ptr`与`unique_ptr`: ```c++ class Report{ private: string str; public: Report( const string &s ) : str{s} { cout << "object created!" << endl; } ~Report(){ cout << "~Report called!" << endl; } void comment() const { cout << str << endl; } }; int main( int argc, char *argv[] ) { { shared_ptr<Report> ps {new Report("using shared_ptr")}; ps -> comment(); } { unique_ptr<Report> ps { new Report("using unique_ptr") }; ps->comment(); } return EXIT_SUCCESS; } ``` `unique_ptr`为何优于`auto_ptr`: ```c++ auto_ptr<string> p1 ( new string("auto") ); auto_ptr<string> p2; p2 = p1; ``` 上述代码中,`p2`将接管`string`对象的所有权,`p1`的所有权将被剥夺(这防止了`p1`与`p2`的析构函数`delete`同一块堆内存),但是如果程序员再之后的代码中,继续使用`p1`,会带来不可预测问题,因为`p1`不再指向任何有效的数据。 ```c++ unique_ptr<string> p3 ( new string("auto") ); unique_ptr<string> p4; p4 = p3; ``` 改为`unique_ptr`后,编译器在编译期直接在`p4 = p3;`处报编译错误,从而在机制上避免了`auto_ptr`的问题。但是当`unique_ptr`作为一个临时的右值时,是可以赋值给其他变量的: ```c++ unique_ptr<string> demo( const char *s ){ unique_ptr<string> temp( new string(s) ); return temp; } unique_ptr<string> p1; p1 = unique_ptr<string>( new string("hello") ); ``` ### 泛型编程 模板使得算法独立于存储的数据类型,而迭代器使算法独立于使用的容器。 ```c++ double *find_ar( double *ar, int n, const double &val ) { for( int i = 0; i < n; ++i ){ if( ar[i] == val ) return &ar[i]; } return nullptr; } ``` 上述代码中,使用下标来遍历数组。可以使用模板将这种算法推广到所有包含`==`运算符的任意类型的数组。尽管如此,这种算法仍然与**数组**这种特定的数据结构绑定在一起。 ```c++ struct Node{ double item; Node *p_next; }; Node *find_ll( Node *head, const double &val ){ Node *start; for( start = head; start != nullptr; start = start->p_next ) { if( start->item == val ) return start; } return nullptr; } ``` 上述代码中,使用模板可以将这种算法推广到支持`==`的任何数据类型的链表。然而,这种算法也是与**链表**这种特定的数据结构绑定在一起。 泛型编程的目的,在于使用同一个`find`函数来处理数组、链表或其他任何容器类型。函数不与容器的类型、容器内元素的类型绑定。模板能够解决容器内元素的绑定,而**迭代器**正是为了解决遍历容器内元素的通用方法。 迭代器应该具备的特征: - 能够对迭代器进行`*`解引用操作,用于访问它引用的值 - 能够相互赋值,`=` 操作 - 能够将一个迭代器与另一个迭代器比较,`==` `!=`操作 - 能够使用迭代器遍历容器中所有元素,`++`操作 对上述代码进行改造: ```c++ // 第一遍 typedef double* iterator; iterator find_ar( iterator ar, int n, const double &val ) { for( int i = 0; i < n; i++, ++ar ){ if( *ar == val ) return ar; } } // 第二遍 iterator find_ar( iterator begin, iterator end, const double &val ) { iterator ar; for( ar = begin; ar != end; ++ar ){ if( *ar == val ) return ar; } return end; } ``` 对于`find_ll()`函数,则必须要实现这么一个迭代器器,其中必须定义`*`和`++`操作,这样才能和`find_ar`函数的实现靠近 ```c++ class iterator{ private: Node *pt; public: iterator() : pt(0) { } iterator( Node *pn ) : pt( pn ) { } double operator*() { return pt->item; } // for ++it iterator &operator++(){ pt = pt->p_next; return *this; } // for it++ iterator operator++(int){ // int 是区分后缀版本用的,不会使用到,所以写个 int 就行了 iterator tmp = *this; pt = pt->p_next; return tmp; } } iterator find_ll( iterator head, iterator end, const double &val ){ iterator it; for( it = head; it != end; ++it ) { if( *it == val ) return it; } return end; } ``` 有了迭代器后,算法的设计应该基于迭代器的特征以及容器特征。 五种迭代器的类型以及能执行的操作: ![WX20190529-162231.png](https://img.codekissyoung.com/2019/05/29/73431874bc80311bc8eb62069bddecfd.png) ### 函数对象 ### STL算法 ## 第17章 输入 输出和文件 ## 第18章 探讨C++新标准
C
UTF-8
4,467
4.25
4
[]
no_license
/* * FILE: linked_list.c */ #include <stdio.h> #include <stdlib.h> #include "memcheck.h" #include "linked_list.h" /* * create_node: * Create a single node and link it to the node called 'n'. */ node * create_node(int data, node *n) { node *result = (node *) malloc(sizeof(node)); if (result == NULL) { fprintf(stderr, "Fatal error: out of memory. " "Terminating program.\n"); exit(1); } result->data = data; /* Fill in the new node with the given value. */ result->next = n; return result; } /* * free_list: * Free all the nodes of a linked list. */ void free_list(node *list) { node *n; /* a single node of the list */ while (list != NULL) { n = list; list = list->next; /* * 'n' now points to the first element of the list, while * 'list' now points to everything but the first element. * Since nothing points to 'n', it can be freed. */ free(n); } } /* * copy_list: * Return a copy of a list. */ node * copy_list(node *list) { if (list == NULL) { return list; } else { node *new_list; new_list = (node *) malloc(sizeof(node)); if (new_list == NULL) { fprintf(stderr, "Fatal error: out of memory. " "Terminating program.\n"); exit(1); } new_list->data = list->data; new_list->next = copy_list(list->next); return new_list; } } /* * append_lists: * Return a list which is a copy of the concatenation of the two * input lists. */ node * append_lists(node *list1, node *list2) { node *item; if (list1 == NULL) { return copy_list(list2); } else if (list2 == NULL) { return copy_list(list1); } else { node *new_list1 = copy_list(list1); node *new_list2 = copy_list(list2); /* * Find the end of 'new_list1' and change its 'next' pointer * to point to 'new_list2'. */ for (item = new_list1; item != NULL; item = item->next) { if (item->next == NULL) /* We're on the last node. */ { item->next = new_list2; /* * Now 'new_list1' contains the copy of both lists * appended together. */ break; } } return new_list1; } } /* * Make a reversed copy of a list. */ node * reverse_list(node *list) { node *item; node *reversed_list = NULL; for (item = list; item != NULL; item = item->next) { reversed_list = create_node(item->data, reversed_list); } return reversed_list; } /* * Print the elements of a list. */ void print_list(node *list) { node *item; for (item = list; item != NULL; item = item->next) { printf("%d\n", item->data); } } /* * Return 1 if a list is sorted, otherwise 0. * Useful for debugging. */ int is_sorted(node *list) { node *item; /* An empty list is sorted by definition. */ if (list == NULL) { return 1; } /* * Compare consecutive list data elements to make sure they're in the * right order. If not, then the list is not sorted and return 0. */ for (item = list; item->next != NULL; item = item->next) { if (item->data > item->next->data) /* wrong order */ { return 0; } } return 1; /* The list is sorted. */ } node *quickSort(node *head) { if (head == NULL) { return NULL; } int pivotValue = head->data; head = head->next; node *smaller = NULL; node *bigger = NULL; while (head != NULL) { int currentValue = head->data; if (currentValue <= pivotValue) { smaller = create_node(currentValue, smaller); } else { bigger = create_node(currentValue, bigger); } head = head->next; } node *smList = quickSort(smaller); node *bgList = quickSort(bigger); free_list(smaller); free_list(bigger); node *pivotList = create_node(pivotValue, NULL); node *smallerWithPivot = append_lists(smList, pivotList); node *res = append_lists(smallerWithPivot, bgList); free_list(smList); free_list(pivotList); free_list(bgList); free_list(smallerWithPivot); return res; }
Python
UTF-8
988
2.53125
3
[]
no_license
import xml.etree.ElementTree as ET from tqdm import tqdm from Scraper import CourseScraper, ReviewScraper SCRAPE_COURSE = False SCRAPE_REVIEW = True if SCRAPE_COURSE: courses_xmlroot = ET.parse('sitemap/courses.xml').getroot() courses_urls = [url[0].text for url in courses_xmlroot] course_scraper = CourseScraper() for url in tqdm(courses_urls): try: course_scraper.scrape(url) except Exception as e: with open('course/error.log', 'a') as f_log: print(f'"{url}","{str(e)}"', file=f_log) if SCRAPE_REVIEW: reviews_xmlroot = ET.parse('sitemap/courses-reviews.xml').getroot() reviews_urls = [url[0].text for url in reviews_xmlroot] review_scraper = ReviewScraper() for url in tqdm(reviews_urls): try: review_scraper.scrape(url) except Exception as e: with open('review/error.log', 'a') as f_log: print(f'"{url}","{str(e)}"', file=f_log)
C++
UTF-8
3,884
3.390625
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //指针初始化时一定要赋值NULL,以防野指针 #define LH +1 #define EH 0 #define RH -1 typedef struct AVLtree{ int val = 0; int bf = 0; AVLtree *left = NULL; AVLtree *right = NULL; }AVLtree; class Solution { public: TreeNode* sortedListToBST(ListNode* head) { ListNode * p = head; if(p == NULL) return NULL; AVLtree* root = NULL; bool taller = false; while(p != NULL){ AVLinsert(root, p->val, taller); p = p->next; } TreeNode* T; copy(T, root); return T; } void AVLinsert(AVLtree*&T, int e, bool &taller){ if(T == NULL){ T = new AVLtree; T->left = T->right = NULL; T->val = e; T->bf = EH; taller = true; } else{ if(e < (T->val)){ AVLinsert(T->left, e, taller); if(taller){ switch(T->bf){ case LH: LeftBalance(T); taller = false; break; case EH: T->bf = LH; taller = true;break; case RH: T->bf = EH; taller = false;break; } } } else{ AVLinsert(T->right, e, taller); if(taller){ switch(T->bf){ case LH: T->bf = EH; taller = false;break; case EH: T->bf = RH; taller = true;break; case RH: RightBalance(T); taller = false;break; } } } } return; } void LeftBalance(AVLtree* &T){ AVLtree* lc= T->left; switch(lc->bf){ case LH: T->bf = lc->bf = EH; R_Rotate(T);break; case RH: AVLtree* rd = lc->right; switch(rd->bf){ case LH: T->bf = RH; lc->bf = EH;break; case EH: T->bf = lc->bf = EH;break; case RH: lc->bf = LH; T->bf = EH; } rd->bf = EH; L_Rotate(T->left); R_Rotate(T); } } void RightBalance(AVLtree* &T){ AVLtree* rc= T->right; switch(rc->bf){ case RH: T->bf = rc->bf = EH; L_Rotate(T);break; case LH: AVLtree* ld = rc->left; switch(ld->bf){ case LH: T->bf = EH; rc->bf = RH;break; case EH: T->bf = rc->bf = EH;break; case RH: rc->bf = EH; T->bf = LH; } ld->bf = EH; R_Rotate(T->right); L_Rotate(T); } } void R_Rotate(AVLtree *& T){ AVLtree* lc = T->left; T->left = lc->right; lc->right = T; T = lc; } void L_Rotate(AVLtree *&T){ AVLtree* rc = T->right; T->right = rc->left; rc->left =T; T = rc; } void copy(TreeNode *&T, AVLtree* &root){ if(root == NULL){ T = NULL; return; } T = new TreeNode(1); T->val = root->val; copy(T->left, root->left); copy(T->right, root->right); return; } };
C#
UTF-8
567
2.640625
3
[]
no_license
var relatedActivities = new List<TActivity>(); bool found = false; foreach (var item in activities.OrderBy(a => a.ActivityDate)) { int count = relatedActivities.Count; if ((count > 0) && (relatedActivities[count - 1].ActivityDate.Date.AddDays(1) != item.ActivityDate.Date)) { if (found) break; relatedActivities.Clear(); } relatedActivities.Add(item); if (item.ID == activity.ID) found = true; } if (!found) relatedActivities.Clear();
C++
WINDOWS-1251
1,736
3.296875
3
[]
no_license
#include "ShellSort.h" int main() { setlocale(LC_CTYPE, "Russian"); int n = 0, d; int k = 0;// ( ) cout<<" .\n"; cin>>n; int *a = new int[n]; int *b = new int[n]; srand((signed int)time(0)); cout<<"\n---------------------\n"; cout<<" 1) \n"; cout<<" 2) "; do { cout<<"\n d (1 2)\n"; cin>>d; if(d<1||d>2) cout<<"\n ! ! \n"; } while(d<1||d>2); switch(d) { case 1: { for (int i = 0; i < n; i++) { a[i] = rand()%10000000; // 0 10000000 cout<<a[i]<<" "; b[i] = a[i]; } }break; case 2: { cout<<" .\n"; for (int i = 0; i < n; i++) { cin>>a[i]; b[i] = a[i]; } } } cout<<"\n :"<<shellSort(a, n, k)<<endl; cout<<" :"<<k<<endl; cout<<" :"<<endl; for (int i = 0; i < n; i++) cout<<a[i]<<" "; clock_t time = clock(); qsort(b, n, sizeof(int), compare); cout<<endl<<" qsort: "<<double(clock() - time)<<endl; cout<<" qsort:"<<endl; for (int i = 0; i < n; i++) cout<<b[i]<<" "; cout<<endl; system("pause"); return 0; }
C
UTF-8
6,370
2.546875
3
[]
no_license
/* object operations. */ #include <jni.h> #include <jni-private.h> #include <assert.h> #include <stdlib.h> #include "compiler.h" /* for likely()/unlikely() */ #include "../java.lang/class.h" /* for fni_class_isInterface */ /* Allocates a new Java object without invoking any of the constructors * for the object. Returns a reference to the object. * The clazz argument must not refer to an array class. * Returns a Java object, or NULL if the object cannot be constructed. * THROWS: * InstantiationException: if the class is an interface or an abstract * class. * OutOfMemoryError: if the system runs out of memory. */ jobject FNI_AllocObject (JNIEnv *env, jclass clazz) { return FNI_AllocObject_using(env, clazz, NULL/* use default alloc func */); } /* allocate using a specific allocation function */ jobject FNI_AllocObject_using (JNIEnv *env, jclass clazz, void *(*allocfunc)(size_t length)) { struct FNI_classinfo *info; struct claz *claz; uint32_t size; assert(FNI_NO_EXCEPTIONS(env) && clazz!=NULL); info = FNI_GetClassInfo(clazz); assert(info->name[0] != '['); /* FIXME: we don't check to see whether it's an interface or abstract */ claz = info->claz; size = claz->size; /* size, including the header */ return FNI_Alloc(env, info, claz, allocfunc, size); } /* Constructs a new Java object. The method ID indicates which constructor * method to invoke. This ID must be obtained by calling GetMethodID() with * <init> as the method name and void (V) as the return type. * * The clazz argument must not refer to an array class. * * Returns a Java object, or NULL if the object cannot be constructed. * THROWS: * InstantiationException: if the class is an interface or an abstract * class. * OutOfMemoryError: if the system runs out of memory. * Any exceptions thrown by the constructor. */ jobject FNI_NewObject(JNIEnv *env, jclass clazz, jmethodID methodID, ...) { jobject result; va_list varargs; assert(FNI_NO_EXCEPTIONS(env)); va_start(varargs, methodID); result=FNI_NewObjectV(env, clazz, methodID, varargs); va_end(varargs); return result; } jobject FNI_NewObjectA(JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args) { jobject result; assert(FNI_NO_EXCEPTIONS(env)); result = FNI_AllocObject(env, clazz); if (unlikely(FNI_ExceptionOccurred(env)!=NULL)) return result; /* bail */ #ifdef WITH_ROLE_INFER NativeassignUID(env,result,clazz); #endif FNI_CallNonvirtualVoidMethodA(env, result, clazz, methodID, args); return result; } jobject FNI_NewObjectV(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args) { jobject result; assert(FNI_NO_EXCEPTIONS(env)); result = FNI_AllocObject(env, clazz); if (unlikely(FNI_ExceptionOccurred(env)!=NULL)) return result; /* bail */ #ifdef WITH_ROLE_INFER NativeassignUID(env,result,clazz); #endif FNI_CallNonvirtualVoidMethodV(env, result, clazz, methodID, args); return result; } /* Returns the class of an object. * Returns a Java class object. */ jclass FNI_GetObjectClass (JNIEnv *env, jobject obj) { assert(FNI_NO_EXCEPTIONS(env) && obj != NULL); return FNI_WRAP(FNI_CLAZ(FNI_UNWRAP_MASKED(obj))->class_object); } /* Tests whether an object is an instance of a class. * Returns JNI_TRUE if obj can be cast to clazz; otherwise, * returns JNI_FALSE. A NULL object can be cast to any class. */ jboolean FNI_IsInstanceOf (JNIEnv *env, jobject obj, jclass clazz) { struct claz * objclz, * clsclz; assert(FNI_NO_EXCEPTIONS(env) && clazz != NULL); if (obj==NULL) return JNI_TRUE;/* flakey: not the same as java' instanceof */ objclz = FNI_CLAZ(FNI_UNWRAP_MASKED(obj)); clsclz = FNI_GetClassInfo(clazz)->claz; /* different tests depending on whether clazz is a class or interface type*/ if (0==clsclz->scaled_class_depth && clsclz!=clsclz->display[0]) { /* this is an interface or array of interfaces. * use the interface instanceof test. */ struct claz **ilist; for (ilist=objclz->interfaces; *ilist!=NULL; ilist++) if (*ilist == clsclz) return JNI_TRUE; return JNI_FALSE; } /* this is a class; use the class instanceof test */ return (objclz->display[clsclz->scaled_class_depth/sizeof(struct claz *)] == clsclz) ? JNI_TRUE : JNI_FALSE; } /* Tests whether two references refer to the same Java object. */ jboolean FNI_IsSameObject (JNIEnv *env, jobject ref1, jobject ref2) { return (FNI_UNWRAP_MASKED(ref1) == FNI_UNWRAP_MASKED(ref2)) ? JNI_TRUE : JNI_FALSE; } /* If clazz represents any class other than the class Object, then this * function returns the object that represents the superclass of the class * specified by clazz. * * If clazz specifies the class Object, or clazz represents an interface, * this function returns NULL. */ jclass FNI_GetSuperclass (JNIEnv *env, jclass clazz) { struct claz * clsclz; int depth; assert(FNI_NO_EXCEPTIONS(env) && clazz != NULL); clsclz = FNI_GetClassInfo(clazz)->claz; depth = clsclz->scaled_class_depth / sizeof(struct claz *); if (depth < 1) return NULL; return FNI_WRAP(clsclz->display[depth-1]->class_object); } /* Determines whether an object of clazz1 can be safely cast to clazz2. * * Returns JNI_TRUE if any of the following are true: * * The first and second class arguments refer to the same Java class. * The first class is a subclass of the second class. * The first class has the second class as one of its interfaces. */ jboolean FNI_IsAssignableFrom(JNIEnv *env, jclass clazz1, jclass clazz2) { struct claz *claz1 = FNI_GetClassInfo((jclass)clazz1)->claz; struct claz *claz2 = FNI_GetClassInfo((jclass)clazz2)->claz; struct claz **ilist; int depth; assert(fni_class_isInterface(env, clazz1)==JNI_FALSE); /* first and second class arguments refer to the same java class? */ if (claz1==claz2) return JNI_TRUE; /* the first class is a subclass of the second class? */ depth = claz2->scaled_class_depth / sizeof(struct claz *); if (claz1->display[depth] == claz2) return JNI_TRUE; /* the first class has the second class as one of its interfaces? */ for (ilist=claz1->interfaces; *ilist!=NULL; ilist++) if (*ilist == claz2) return JNI_TRUE; /* okay, no tests were true. must not be assignable */ return JNI_FALSE; }
SQL
UTF-8
1,272
3.46875
3
[]
no_license
CREATE EXTENSION IF NOT EXISTS plpythonu; CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE; DROP TYPE IF EXISTS datapoint CASCADE; DROP TYPE IF EXISTS result_type CASCADE; CREATE TYPE datapoint AS ( time TIMESTAMP WITHOUT TIME ZONE, d DOUBLE PRECISION ARRAY); CREATE TYPE result_type AS ( time TIMESTAMP WITHOUT TIME ZONE, d DOUBLE PRECISION ARRAY ); CREATE TABLE datapoints OF datapoint; CREATE TABLE zscore OF result_type; SELECT create_hypertable('datapoints', 'time'); DO $load_data$ DECLARE start_time TIMESTAMP WITH TIME ZONE; end_time TIMESTAMP WITH TIME ZONE; delta DOUBLE PRECISION; initial_size DOUBLE PRECISION; final_size DOUBLE PRECISION; BEGIN start_time := clock_timestamp(); COPY datapoints FROM '<data_file>' DELIMITER ',' CSV; end_time := clock_timestamp(); END; $load_data$; DO $zscore$ DECLARE start_time TIMESTAMP WITH TIME ZONE; end_time TIMESTAMP WITH TIME ZONE; delta DOUBLE PRECISION; BEGIN start_time := clock_timestamp(); INSERT INTO zscore SELECT time, array[ <select_expression> ] FROM datapoints; end_time := clock_timestamp(); delta = extract(epoch from end_time) - extract(epoch from start_time); RAISE NOTICE 'Z-Score time seconds = %', delta; END; $zscore$; --select * from datapoints; --select * from zscore;
JavaScript
UTF-8
2,178
2.765625
3
[]
no_license
const fs = require('fs'); const ffprobe = require('ffprobe'); const ffprobeStatic = require('ffprobe-static'); const _ = require('lodash'); function sleep(time = 0) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, time); }) }; function getVideoSize(link) { return new Promise((resolve, reject) => { fs.stat(link, function(error,stats){ if(error){ reject("file size error"); } else{ //文件大小 // console.log(stats.size); resolve(stats.size); } }) }) } function getVideoInfo(filePath) { return new Promise((resolve, reject) => { ffprobe(filePath, { path: ffprobeStatic.path }) .then(function (info) { // console.log(info); const videoObj = _.find(info.streams, { codec_type: 'video' }); if (videoObj) { resolve(videoObj); } else { reject('no video info'); } }) .catch(function (err) { reject(err); }) }) } /** * * 过滤出有用的视频 * 1.竖版尺寸:宽高比≤1 * 2.像素720dpi以上 * 3.大小2M以上 */ async function isEffectiveVideo(filePath) { try { const videoObj = await getVideoInfo(filePath); if (videoObj.width >= videoObj.height) { console.log('为横版视频'); return false; } // if (videoObj.width < 720 && videoObj.height < 720) { // console.log('像素在720dpi以下'); // return false; // } if (videoObj.width < 480 && videoObj.height < 480) { console.log('像素在 480dpi 以下'); return false; } let videoSize = 0; try { videoSize = await getVideoSize(filePath); } catch (error) { console.log('获取视频 size 失败'); return false; } if ( videoSize < 2 * 1024 * 1024 ) { console.log('视频小于 2M'); return false; } return true; } catch (error) { console.log('get isEffectiveVideo error'); return false; } } module.exports.sleep = sleep; module.exports.getVideoSize = getVideoSize; module.exports.getVideoInfo = getVideoInfo; module.exports.isEffectiveVideo = isEffectiveVideo;
Java
UTF-8
620
1.882813
2
[]
no_license
package com.go1ove.atcrowdfunding.service.impl; import com.go1ove.atcrowdfunding.dao.TestDao; import com.go1ove.atcrowdfunding.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * @author go1ove * @create 2019-04-29-16:45 */ @Service public class TestServiceImpl implements TestService { @Autowired private TestDao testDao; @Override public void insert() { Map map = new HashMap(); map.put("name","zhang3"); testDao.insert(map); } }
Python
UTF-8
1,007
2.734375
3
[ "MIT" ]
permissive
# Sends binary data from AWS S3 to API Gateway via AWS Lambda function through lambda proxy integration import json import base64 import boto3 def lambda_handler(event, context): s3 = boto3.client("s3") # for lambda proxy integration bucket_name = event['pathParameters']['bucket'] file_name = event['queryStringParameters']['file'] file_object = s3.get_object(Bucket=bucket_name, Key=file_name) file_content = file_object["Body"].read() print(bucket_name, file_name) return { "statusCode": 200, "headers": { "Content-Type": "application/pdf" }, "body" : base64.b64encode(file_content), "isBase64Encoded": True } # In case one wants to send json as response # return { # "statusCode": 200, # "headers": { # "Content-Type": "application/json" # }, # "body" : json.dumps("Json response"), # "isBase64Encoded": False # }
Markdown
UTF-8
1,354
2.65625
3
[]
no_license
# Fedora Module Build System Plugin This plugin interacts with Fedora's Module Build System to submit new module build requests and to query the status of existing requests. For more info on MBS, please see https://fedoraproject.org/wiki/Infrastructure/Factory2/Focus/MBS # How it works This plugin currently provides the following pipeline steps: * submitModuleBuildRequest * queryModuleBuildRequest # Examples * Complete example with submission and query for readiness ```groovy node() { MBSURL = "http://localhost:32000" USERNAME = "bob" CREDID = "bobs-password" MODULE = "mymodule" REV = "myrev" BRANCH = "mybranch" def submission = null withCredentials([string(credentialsId: CREDID, variable: 'PASSWORD')]) { submission = submitModuleBuildRequest mbsUrl: MBSURL, user: USERNAME, password: PASSWORD, moduleName: MODULE, revision: REV, branch: BRANCH echo "my submission id is: " + submission.getId() } timeout(time: 20, unit: 'SECONDS') { def mbsRequest = null waitUntil { mbsRequest = queryModuleBuildRequest mbsUrl: "http://localhost:32000", moduleRequestId: submission.getId() return mbsRequest.isModuleReady() } echo "Module id: " + mbsRequest.getId() + " is ready" echo "${mbsRequest}" } } ```
C
UTF-8
3,618
2.890625
3
[]
no_license
/** Name : ktourXVI.c Copyright : none Author : ted perez Created : 04/22/08 0703 Revised : 04/10/16 1906 Description : knight's tour */ #include <stdio.h> #include <time.h> int Moves[512][4], sq[9][9], depth = 0, maxRows = 0, maxCols = 0, maxDepth = 0; int nrow = 0, ncol = 0, orow = 0, ocol = 0, i = 0, j = 0, xi = 0, yj = 0, ii = 0, jj = 0, ir = 0, jc = 0; int currDepth = 0, prevDepth = 0, ctr = 0, ptr = 0, nMoves = 0, startRow = 0, startCol = 0, startNone = 0; double totnodes = 0, gtnodes = 0, tsf = 0; time_t start1, start2, start3, stop; long diff; int newMoves(); void Occupy(); void Occupy() { if (sq[nrow][ncol] == 0) { ptr++; Moves[ptr][1] = depth; Moves[ptr][2] = nrow; Moves[ptr][3] = ncol; nMoves++; totnodes++; gtnodes++; } } int newMoves() { /** * Check if square not occupied * */ depth++; nMoves = 0; nrow = orow - 1; if (nrow > 0) { ncol = ocol + 2; if (ncol < maxCols && sq[nrow][ncol] == 0) Occupy(); ncol = ocol - 2; if (ncol > 0 && sq[nrow][ncol] == 0) Occupy(); } nrow = orow + 1; if (nrow < maxRows) { ncol = ocol + 2; if (ncol < maxCols && sq[nrow][ncol] == 0) Occupy(); ncol = ocol - 2; if (ncol > 0 && sq[nrow][ncol] == 0) Occupy(); } ncol = ocol + 1; if (ncol < maxCols) { nrow = orow - 2; if (nrow > 0 && sq[nrow][ncol] == 0) Occupy(); nrow = orow + 2; if (nrow < maxRows && sq[nrow][ncol] == 0) Occupy(); } ncol = ocol - 1; if (ncol > 0) { nrow = orow - 2; if (nrow > 0 && sq[nrow][ncol] == 0) Occupy(); nrow = orow + 2; if (nrow < maxRows && sq[nrow][ncol] == 0) Occupy(); } return nMoves; } int main() { printf("maxRows (3-8) ? "); scanf_s("%d", &maxRows); printf("maxCols (3-8) ? "); scanf_s("%d", &maxCols); printf("\n\n"); start1 = time(NULL); maxDepth = maxRows * maxCols; maxRows++; maxCols++; for (ir = 1; ir < maxRows; ir++) { start2 = time(NULL); for (jc = 1; jc < maxCols; jc++) { int ls = 0; ptr = 1; Moves[ptr][1] = 1; Moves[ptr][2] = ir; Moves[ptr][3] = jc; depth = 1; while (ptr > 0 && Moves[ptr][1] < maxDepth) { orow = Moves[ptr][2]; ocol = Moves[ptr][3]; sq[orow][ocol] = Moves[ptr][1]; while (newMoves() > 0) { orow = Moves[ptr][2]; ocol = Moves[ptr][3]; sq[orow][ocol] = Moves[ptr][1]; } depth--; if (depth >= maxDepth) { /** * solution found! display board * * */ ls++; // count solutions only from x,y tsf++; // count total solutions found /* printf("\n Solution # %12.0f \n\n", tsf); ii = maxRows - 1; for (xi = ii; xi > 0; xi--) { printf(" "); for (yj = 1; yj < maxCols; yj++) printf("%02d ", sq[xi][yj]); printf("\n\n"); } stop = time(NULL); diff = difftime(stop, start); printf("%12.0f nodes in %d seconds.\n\n", totnodes, diff); */ } /** * back-track * */ sq[Moves[ptr][2]][Moves[ptr][3]] = 0; ptr--; while (Moves[ptr][1] != Moves[ptr + 1][1]) { sq[Moves[ptr][2]][Moves[ptr][3]] = 0; ptr--; } depth = Moves[ptr][1]; } stop = time(NULL); diff = difftime(stop, start2); printf("%12d Total solutions from %d,%d found in %7d seconds. %12.0f nodes tried.\n\n", ls, ir, jc, diff, totnodes); totnodes = 0; start2 = time(NULL); } } stop = time(NULL); diff = difftime(stop, start1); printf("%12.0f Total solutions found for a %d x %d board in %d seconds. %12.0f nodes tried. \n\n", tsf, maxRows - 1, maxCols - 1, diff, gtnodes); return 0; }
Markdown
UTF-8
924
3.125
3
[]
no_license
# Notes from the Gynvael stream on Chip-8 VM - Usually in VMs or even older machines, you have a frame buffer, and you address a specific point like a pixel and turn it on/off, but for Sprites, you have a register which you have to set, and another set of registers which basically you say you want to place the sprite and say etc etc (bit complicated, look into this later!) - Sprites are 8 pixels wide and 1 to 15 pixels in height. - XOR operation to flip the color of the sprite. 35 Opcodes (waaay easier than x86). Also 4.5x more opcodes than Brainfuck! - Each opcode is 2 bytes long. - Big-Endian (x86 is little-endian) Instructions are stored in memory, and are 2 bytes long. 1st byte of each instruction should be located at an even address. Opcodes have the following symbols: NNN: Address NN: 8-bit Constant N: 4-bit Constant X and Y: 4-bit register identifier PC: Program Counter I: 16-bit register
Java
UTF-8
389
2.0625
2
[]
no_license
package com.antogeo.service.export; import com.antogeo.pojo.WeatherReport; import java.io.IOException; public interface ExportService { /** * Prints a txt file containing the weather report info. * * @param weatherReport The weather report object. * @throws IOException */ void exportWeatherTxt(final WeatherReport weatherReport) throws IOException; }
Markdown
UTF-8
557
2.75
3
[]
no_license
# pdf_a4_two_months This is a simple script to create pdf file with 2 months. ![Pdf screenshot](https://upload.bessarabov.ru/bessarabov/Q2T5GyXtwro_pKrNbZLhbVhvqJw.png) ## How to use it You need to [install Docker](https://docs.docker.com/installation/). Then you need to build image: ./build And then start it, specifying the start year and month: docker run \ --rm \ --env "START_YEAR_MONTH=2015-05" \ --volume `pwd`:/data \ pdf_a4_two_months And you will get file `2015-05.pdf` in your working directory.
Markdown
UTF-8
3,846
3.09375
3
[]
no_license
# Multiplayer Slider Pub Sub with AWS AppSync This is a simple project to showcase how you can use an AWS AppSync API to facilitate realtime pub/sub interactions over websockets. The demo client application (built with React) has two sliders on a web page. Whenever a user updates the value in one of the sliders, the value will get broadcast out to anyone else who has the same page open in their browser, and their slider will update to whatever you set it to. There is no state managed in this application at all; it's just a simple example UI showing how to send data over a GraphQL mutation to an AWS AppSync server and how subscribe to updates in a similar fashion. ## What's it look like? ## What's going on here? You can use [AWS AppSync](https://aws.amazon.com/appsync/) as a simple pub/sub system using a pattern called [AppSync Local Resolvers](https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-local-resolvers.html). This just involves creating a GraphQL mutation that resolves with an AppSync Data Source type of NONE. Then, you just target that mutation with a subscription, and the data will pass through from the client who issues the mutation to all subscribed clients. AWS Amplify is a set of tooling and libraries that makes it easier to get started provisioning AWS resources and using them in your apps. This demo uses Amplify to provision the AppSync API and the other required resources to make this all work. To learn more about using AWS Amplify with React, see the [AWS Amplify Tutorial for React](https://docs.amplify.aws/start/q/integration/react). ## How does it work? Look at `src/App.js` and you'll see a simple React app that uses the `@aws-amplify/api` library to talk to a backend GraphQL server powered by AWS AppSync. The GraphQL schema is located in `amplify/backend/api/multiplayercounter/schema.graphql`. We handle creating the `NONE` AppSync Data Source and mapping the `setCounter` mutation appropriately inside `amplify/backend/api/multiplayercounter/stacks/CustomResources.json`. Embedding VTL templates inside a JSON CloudFormation template file is sad, as you have to escape all the quotes. But it's a simple template that just maps our incoming data directly through to the response mapper so it's not so bad. ## How do I deploy and run this demo for myself? :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: **Security Note** This example sets up an AppSync API endpoint that authenticates users with an API key. This approach is not recommended for production deploys. You proabbly want to switch to a different authentication mechanism before you deploy code like this in production. See [AWS AppSync Security](https://docs.aws.amazon.com/appsync/latest/devguide/security.html) for more information. :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: :warning: ### One-Click Deploy with the Amplify Console Click the button to load the AWS Amplify Console, connect to GitHub and provide an IAM role for the build. The end to end back-end and front-end deployment should take around 5 minutes: [![amplifybutton](https://oneclick.amplifyapp.com/button.svg)](https://console.aws.amazon.com/amplify/home#/deploy?repo=https://github.com/navday/multiplayercounter) ### Get the code and run on my local dev workstation This project uses AWS Amplify to deploy resources in your account. Assuming you've already instaled and configured the [AWS Amplify CLI](https://docs.amplify.aws/cli), you can run this command to automatically clone this repo, deploy this app in your AWS account, and boot up the local demo dev server: ``` mkdir multiplayercounter cd multiplayercounter amplify init --app https://github.com/navday/multiplayercounter ```
Java
UTF-8
5,334
2.1875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sg.flashcardapp.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; /** * * @authors Mike Betzler, Jacob Duerr, Anna Maxam, Jeff Peterson */ @Entity public class User { // (fetch = FetchType.LAZY) @GeneratedValue(strategy = GenerationType.IDENTITY) @Id @Column private int userId; @NotEmpty(message = "Please enter a name.") @Length(max = 50, message = "Name must be no more than 50 characters in length.") @Column(nullable = false) private String userName; @NotEmpty(message = "Please enter a password.") @Length(max = 100, message = "Password must be no more than 100 characters in length.") @Column(nullable = false) private String password; @Column(nullable = false) private boolean active; @ManyToMany @JoinTable(name= "UserRole", joinColumns = {@JoinColumn(name = "userId")}, inverseJoinColumns = {@JoinColumn(name = "roleId")} ) @JsonIgnore private List<Role> roles = new ArrayList<>(); @ManyToMany @JoinTable(name = "UserDeck", joinColumns = {@JoinColumn(name = "userId")}, inverseJoinColumns = {@JoinColumn(name = "deckId")} ) private List<Deck> decks = new ArrayList<>(); @ManyToMany @JoinTable(name="userCard", joinColumns={ @JoinColumn(name = "userId") }, inverseJoinColumns={ @JoinColumn(name = "cardId") } ) private List<Card> cards = new ArrayList<>(); // @OneToMany // List<Review> reviews = new ArrayList<>(); // @OneToMany // List<CardRating> ratings = new ArrayList<>(); public User() { } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public List<Deck> getDecks() { return decks; } public void setDecks(List<Deck> decks) { this.decks = decks; } public List<Card> getCards() { return cards; } public void setCards(List<Card> cards) { this.cards = cards; } // public List<Review> getReviews() { // return reviews; // } // // public void setReviews(List<Review> reviews) { // this.reviews = reviews; // } // public List<CardRating> getRatings() { // return ratings; // } // // public void setRatings(List<CardRating> ratings) { // this.ratings = ratings; // } public void addRole(Role role) { roles.add(role); } @Override public int hashCode() { int hash = 7; hash = 17 * hash + this.userId; hash = 17 * hash + Objects.hashCode(this.userName); hash = 17 * hash + Objects.hashCode(this.password); hash = 17 * hash + (this.active ? 1 : 0); hash = 17 * hash + Objects.hashCode(this.roles); hash = 17 * hash + Objects.hashCode(this.decks); hash = 17 * hash + Objects.hashCode(this.cards); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; if (this.userId != other.userId) { return false; } if (this.active != other.active) { return false; } if (!Objects.equals(this.userName, other.userName)) { return false; } if (!Objects.equals(this.password, other.password)) { return false; } if (!Objects.equals(this.roles, other.roles)) { return false; } if (!Objects.equals(this.decks, other.decks)) { return false; } if (!Objects.equals(this.cards, other.cards)) { return false; } return true; } }
C
UTF-8
3,169
3.78125
4
[]
no_license
#include "list.h" #include <stdio.h> void new_list(list *list, size_t element_size) { list->length = 0; list->element_size = element_size; list->head = NULL; list->tail = NULL; } void delete_list(list *list) { node *element = list->head; while (element != NULL) { if (list->deallocate_node) { list->deallocate_node(element->data); } node *next = element->next; free(element->data); free(element); element = next; } list->head = NULL; list->tail = NULL; list->length = 0; } void list_append(list *list, void *element) { node *node = malloc(sizeof(node)); node->data = malloc(list->element_size); node->next = NULL; memcpy(node->data, element, list->element_size); if (list->length == 0) { list->head = node; list->tail = node; } else { list->tail->next = node; list->tail = node; } list->length++; } void test_list() { list some_list; new_list(&some_list, sizeof(int)); for (int i=1; i<=6; i++) { list_append(&some_list, &i); } node *element = some_list.head; for (int i=0; i<some_list.length; i++) { printf("element: %d\n", *(int*)element->data); element = element->next; } printf("============\n"); element = some_list.head; while (element) { printf("element: %d\n", *(int*)element->data); element = element->next; } delete_list(&some_list); } typedef struct _some_struct { int *number; } some_struct; typedef struct _some_struct2 { char number; } some_struct2; void deallocator(some_struct *element) { free(element->number); } void test_dynamic_list() { list *some_list = malloc(sizeof(list)); new_list(some_list, sizeof(some_struct)); some_list->deallocate_node = (void*)(void*)deallocator; for (int i=1; i<=6; i++) { some_struct element; element.number = malloc(sizeof(int)); memcpy(element.number, &i, sizeof(int)); list_append(some_list, &element); } node *element = some_list->head; for (int i=0; i<some_list->length; i++) { some_struct *node = element->data; printf("element: %d\n", *node->number); element = element->next; } printf("============\n"); element = some_list->head; while (element) { some_struct *node = element->data; printf("element: %d\n", *node->number); element = element->next; } delete_list(some_list); } void test_find(char *val) { list *some_list = malloc(sizeof(list)); new_list(some_list, sizeof(some_struct2)); for (char i=1; i<=6; i++) { some_struct2 element; element.number = i; list_append(some_list, &element); } node *element = some_list->head; while (element) { printf("iteration \n"); some_struct2 *node = element->data; if (node->number == 4) { *val = node->number; printf("found result! == %d\n", node->number); break; } element = element->next; } delete_list(some_list); }
Markdown
UTF-8
13,055
2.5625
3
[ "MIT" ]
permissive
<p align="center"> <img src="http://i.imgur.com/BjOnHzT.png" width="350"/> </p> # opsApi OpsAPI is a lightweight API/HTTP framework in Tornado which allows users to extend and prototype mid complexity API designs and process solutions -- hours not weeks. I promise. This is intended to empower systems engineers and developers looking to cut the lifting out of running their ops shop. Yes there's Rundeck/Jenkin's but you can't build a larger platform on top of that -- this API is the missing loose couple. Use the pluggable nature of this API and you can hook Ansible, Fabric, or local Postgres bindings from Rundeck OR Jenkins. A real wizard could have multiple opsAPI deployments interconnected with Python-requests to create complex build pipelines and processes. Then they would use the beautiful [marmelab/ng-admin](https://github.com/marmelab/ng-admin) to create a browser app. Ditch Jenkins. Now where's the beach? ## Quick dev environment You will need to `pip install paver` first, then just type `make`! These other paver tasks are available to you. paver setup - Copy, Install & configure the components for running a local server (sudo) paver start - Install & configure git repo to system and start local dev instance (sudo) paver load_extensions - Copy the git repo extensions to /srv/extensions (sudo) paver build_rpm - Build an RPM artefact paver clean - Clean up paver/build/artefacts so you can do git stuff ## Tutorial After installing with paver, start the API and perform a test request: opsapi -d --dir /srv/extensions curl -XPOST http://localhost:3000/extensions/test -H "Content-Type: application/json" -d '{ "name": "bob", "age": "31"}' You should see this response: { "debug": { "err": [], "out": [] }, "request": { "age": 31, "current_datetime": "2016-09-03 21:35:00.877164", "name": "bob", "return": "You were born in 1985" } } ## Real-World Examples ### Postgres Examples Create a Postgres role called jonkelley. curl -XPOST http://localhost:3000/extensions/psql_create_role -H "Content-Type: application/json" -d '{ "role": "jonkelley", "password": "qwerty", "connection_limit": "3"}' You should see this response: { "debug": { "err": [], "out": [ "BEGIN; CREATE ROLE jonkelley WITH CONNECTION LIMIT 3 NOCREATEUSER NOCREATEROLE NOCREATEDB NOINHERIT NOLOGIN UNENCRYPTED PASSWORD 'qwerty' ; END;", "BEGIN", "CREATE ROLE", "COMMIT", "" ] }, "request": { "result": "ok", "status": 0 } } Attempt to drop the role billgates curl -XPOST http://localhost:3000/extensions/psql_drop_role -H "Content-Type: application/json" -d '{ "role": "billgates"}' You should see this response: { "debug": { "err": [ "psql:/tmp/tmpVeJay3:1: ERROR: role \"billgates\" does not exist", "psql:/tmp/tmpVeJay3:1: ERROR: role \"billgates\" does not exist", "ROLLBACK" ], "out": [ "BEGIN; DROP ROLE billgates; END;", "BEGIN", "psql:/tmp/tmpVeJay3:1: ERROR: role \"billgates\" does not exist", "ROLLBACK", "" ] }, "request": { "errors": [ "TRANSACTION_ROLLBACK", "SQL_ERROR", "ROLE_DOES_NOT_EXIST" ], "result": "rollback", "status": 1 } } ### Ansible Examples Todo ### Fabric Examples Todo ### MySQL Examples Todo ### Memcache Examples Todo ## API Input Parsing / Limit Features Depending on how you set up your param requirements in the SDK, the API has a bunch of built in filtering and input management options you can manage. Example of integer enforcement using `param.max_int` for invalid age: curl -XPOST http://localhost:3000/extensions/test -H "Content-Type: application/json" -d '{ "name": "bob", "age": "wat}' You should see this response: { "debug": { "err": [ "Parameter `age` provided with value: wat, expected: PARAMETER_ERROR_IS_NOT_INTEGER value." ], "out": [] }, "request": { "status": "422 Unprocessable Entity", "troubleshoot": [ "INPUT_NOT_AN_INT" ] } } Example of parameter size limits using `param.max_length`: curl -XPOST http://localhost:3000/extensions/test -H "Content-Type: application/json" -d '{ "name": "jon", "age": "2030"}' You should see this response: { "debug": { "err": [ "Parameter `age` provided with value: too large, expected: input less than 3 bytes value." ], "out": [] }, "request": { "status": "422 Unprocessable Entity", "troubleshoot": [ "BUFFER_SIZE" ] } } Example of of handling empty input parameters (when they are required) curl -XPOST http://localhost:3000/extensions/psql_create_role -H "Content-Type: application/json" -d '{ "role": "jonkelley"}' You should see this response: { "debug": { "err": [ "Parameter `password` provided with value: <NULL> which cannot be undefined" ], "out": [] }, "request": { "status": "422 unprocessable_entity", "troubleshoot": [ "UNDEFINED_INPUT_ERROR" ] } } ## Security Model The API has input string management classes to handle the possibility of bad-actor injection attempts. This will prevent most casual to intermediate attempts of injection using a variety of known methods. **Absolutely no security will be foolproof.** Always use trusted authentication in front of this service or htpasswd. Here is a demonstration attempt of malicious SQL injection, naughty naughty. curl -XPOST http://localhost:3000/extensions/psql_create_role -H "Content-Type: application/json" -d '{ "role": "jonkelley", "password": "SERVER'\''; DROP ROLE postgres;HACKED", "connection_limit": "3"}' System Log: `EXCEPTION: SecurityFaultDangerousUserInput value: "SERVER'; DROP ROLE postgres;HACKED"` The user should see this response: { "debug": { "err": [ "Internal Server Error" ], "out": [ "" ] }, "request": { "errors": "", "status": "500 Internal Server Error" } } Special characters and other items that JSON cannot tokenize are invalid. Any knwon abilities to fuzz past the escape filters seems pretty difficult at this stage. We will predictively fail with 500, because potential unexpected conditions will result in 500 as well. 500 for all the things ensures the attacker has no direct knowledge of handled vs unhandled errors. ## Command Line Usage NOTE: You can use the apache htpasswd utility to create a htpasswd file for embedded www-basic-auth. That means install the `apache2-utils` deb or `httpd-tools` rpm while you're at it. Usage: opsapi [options] <htpasswd> This will expose a set of opsapi extensions as a REST API. Note: Please make sure this application is behind authentication for security. Please use the SSL config options, give a passwd file, and either whitelist access to the API via firewall or keep it on a privately routed network. Use the apache htpasswd utility to create your htpasswd files. Options: -h, --help show this help message and exit -d, --debug Start the application with debug enabled. --dir=DIRECTORY Directory to load SDK extensions from --force-json Force the application to treat all incoming requests as 'Content-Type: application/json' --config Provide a YAML file to load config options from. NOTE: Syntax is key: v; python objects allowed as values. Native YAML lists and hash syntax are unsupported. -p PORT, --port=PORT The listening port -a ADDRESS, --address=ADDRESS Listening interface. Can be a hostname or an IPv4/v6 address. -c CERTFILE, --certfile=CERTFILE SSL Cert File -k KEYFILE, --keyfile=KEYFILE SSL Private Key File -u UNIX_SOCKET, --unix-socket=UNIX_SOCKET Bind opsapi to a unix domain socket ## Configuration File Options Some features may require additional configuration. This API can support YAML configuration files from some usual locations or with the --config option if you really need it. NOTE: All the configurations are merged into the running configuration if loaded. NOTE: Syntax supports key: v with full python eval support. NOTE: YAML Style list and hashes are not supported. The default config has some interesting options in `opsapi.yaml`, you should take a look and configure. The default load locations on startup are: * `/etc/opsapi.{yaml,yml}` * `./opsapi.{yaml,yml}` * `/etc/opsapi/opsapi.{yaml,yml}` * `~/opsapi.{yaml,yml}` ## Using the extension SDK ### Extension file header config blocks Config blocks help build metadata about the extension that opsapi is loading into memory. Config blocks are not mandatory for the extension to run (only if you reference params). Example block: # -- config -- # description: This is just an example extension # param: text - text to echo back # param: secret1 - sensitive text you don't want logged # param: secret2 - more sensitive stuff # filtered_params: secret1, secret2 # tags: test, staging # http_method: get # lock: False # -- end config -- Fields: - **description**: information about what an extension does - format: description: [*text*] - **param**: specifies a parameter to the extension, will be passed in as environment params, with the name in all caps. One per line. - format: param: *name* [- *description*] - **filtered_params**: specifies a list of parameters that you have already specified, but want to ensure that the values are not logged. - format: filtered_params: item1 [,item2] - **tags**: specifies a list of tags that you want displayed when querying opsapi about extensions. - format: tags: item1 [,item2] - **http_method**: specifies the http method the extension should respond to. - format: http_method: get - allowed_values: get|put|post|delete - default: post - **output**: specifies if the output should be 'split' into stderr and stdout or 'combined' into stdout. - format: output: combined - allowed_values: split|combined - default: split - **lock**: if true, only one instance of the extension will be allowed to run. useful to prevent RACE conditions if your code cannot support parallelism - format: lock: True - default: False ### Extension Python SDK Todo ### Extensions List Get a list of all loaded extensions with parameters and options. GET /extensions Optional Tag Query Parameters: - format: ?param=tag1,tag2 - only one param type may be used per query. - params available - tags: only those extensions which match *ALL* tags will be returned - not_tags: only those extensions which do no have *ANY* of the tags will be returned - any_tags: extensions that match *ANY* tags will be returned ### Extensions Names List Returns list of names of all loaded extensions GET /extension_names Optional Tag Query Parameters: - format: ?param=tag1,tag2 - only one param type may be used per query. - params available - tags: only those extensions which match *ALL* tags will be returned - not_tags: only those extensions which do no have *ANY* of the tags will be returned - any_tags: extensions that match *ANY* tags will be returned ### Get help on specific extension This will return config block metadata for one specific extension. Note the rarely used OPTIONS http method. OPTIONS /extensions/{extension_name} ### Trigger an extension You would execute POST data to an extension and return results with POST /extensions/{extension_name} You would execute GET to an extension to just read data from it. GET /extensions/{extension_name} ### Reload most code without a restart This is useful so you can push updates without interrupting live service. THis will reload the *configuration files* and all *extension code* from disk should you have any reason for hotpatching. POST /reload
Python
UTF-8
942
2.734375
3
[ "MIT" ]
permissive
import plot import model import sys import os.path as path import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import sklearn.decomposition vecs = model.load(path.realpath(sys.argv[1])) model = sklearn.decomposition.PCA() PCs = model.fit_transform(vecs) print('variance explained: ', np.sum(model.explained_variance_ratio_[0:4] * 100)) fig = plt.figure(figsize=(8, 6)) gs = gridspec.GridSpec(3, 2) # PC[0], PC[1] ax = plt.subplot(gs[0:2, 0]) plt.scatter(PCs[:, 0], PCs[:, 1], lw=0, alpha=0.5, c='SteelBlue') plt.xlabel('PC 0') plt.ylabel('PC 1') # PC[2], PC[3] ax = plt.subplot(gs[0:2, 1]) plt.scatter(PCs[:, 2], PCs[:, 3], lw=0, alpha=0.5, c='SteelBlue') plt.xlabel('PC 2') plt.ylabel('PC 3') plt.subplot(gs[2, :]) plt.plot(np.arange(0, PCs.shape[1]), model.explained_variance_ratio_ * 100, color='IndianRed') plt.xlabel('PC') plt.ylabel('explained [%]') fig.set_tight_layout(True) plt.show()
JavaScript
UTF-8
852
2.6875
3
[]
no_license
// ==UserScript== // @name Flooder // @namespace vipul // @description flood any number via freesms8 :) // @include http://www.freesms8.com/* // ==/UserScript== var number="9051950944"; // change this value to the number you want to flood var text="You will go boom in 10 seconds! " + Math.floor(Math.random()*999); if(document.location=="http://www.freesms8.com/QuickSMS.aspx" ||document.location=="http://www.freesms8.com/quickSMS.aspx") { document.forms[1].elements[9].value=number; document.forms[1].elements[10].value=text; document.forms[1].elements[12].click(); } if(document.location=="http://www.freesms8.com/QuickSent.aspx") { document.location="http://www.freesms8.com/QuickSMS.aspx"; // u may have to change the 'Q' to 'q' here, see the url in your browser and change it accordingly }
Python
UTF-8
7,052
2.5625
3
[ "MIT" ]
permissive
import iso8601 import unittest from datetime import tzinfo class ISO8601(unittest.TestCase): """Test cases for ISO 8601.""" def testIso8601Regex(self): self.assertIsNotNone(iso8601.ISO8601_REGEX.match("2006-10-11T00:14:33Z")) self.assertIsNotNone(iso8601.ISO8601_REGEX.match('2012-07-04T19:00:00')) self.assertIsNotNone(iso8601.ISO8601_REGEX.match('2012-07-04T19:00:00-0700')) self.assertIsNotNone(iso8601.ISO8601_REGEX.match('2012-07-04T19:00:00-07:00')) self.assertIsNotNone(iso8601.ISO8601_REGEX.match('2012-07-04T19:00:00-07')) def testTimezoneRegex(self): self.assertIsNotNone(iso8601.TIMEZONE_REGEX.match("+01:00")) self.assertIsNotNone(iso8601.TIMEZONE_REGEX.match("+00:00")) self.assertIsNotNone(iso8601.TIMEZONE_REGEX.match("+01:20")) self.assertIsNotNone(iso8601.TIMEZONE_REGEX.match("-01:00")) self.assertIsNotNone(iso8601.TIMEZONE_REGEX.match("-01")) self.assertIsNotNone(iso8601.TIMEZONE_REGEX.match("+06")) def testParseDate(self): """Tests parse date tz.""" d = iso8601.parseDate("2006-10-20T15:34:56Z") self.assertEquals(d.year, 2006) self.assertEquals(d.month, 10) self.assertEquals(d.day, 20) self.assertEquals(d.hour, 15) self.assertEquals(d.minute, 34) self.assertEquals(d.second, 56) self.assertEquals(d.tzinfo, iso8601.UTC) def testParseDateFraction(self): """Tests parse date tz.""" d = iso8601.parseDate("2006-10-20T15:34:56.123Z") self.assertEquals(d.year, 2006) self.assertEquals(d.month, 10) self.assertEquals(d.day, 20) self.assertEquals(d.hour, 15) self.assertEquals(d.minute, 34) self.assertEquals(d.second, 56) self.assertEquals(d.microsecond, 123000) self.assertEquals(d.tzinfo, iso8601.UTC) def testParseDateFraction2(self): """From bug 6""" d = iso8601.parseDate("2007-5-7T11:43:55.328Z'") self.assertEquals(d.year, 2007) self.assertEquals(d.month, 5) self.assertEquals(d.day, 7) self.assertEquals(d.hour, 11) self.assertEquals(d.minute, 43) self.assertEquals(d.second, 55) self.assertEquals(d.microsecond, 328000) self.assertEquals(d.tzinfo, iso8601.UTC) def testParseDateTz(self): """Tests parse date tz.""" d = iso8601.parseDate("2006-10-20T15:34:56.123+02:30") self.assertEquals(d.year, 2006) self.assertEquals(d.month, 10) self.assertEquals(d.day, 20) self.assertEquals(d.hour, 15) self.assertEquals(d.minute, 34) self.assertEquals(d.second, 56) self.assertEquals(d.microsecond, 123000) self.assertEquals(d.tzinfo.tzname(None), "+02:30") offset = d.tzinfo.utcoffset(None) self.assertEquals(offset.days, 0) self.assertEquals(offset.seconds, 60 * 60 * 2.5) def testParseDateTz2(self): """Tests parse date tz.""" d = iso8601.parseDate("2006-10-20T15:34:56.123+0230") self.assertEquals(d.year, 2006) self.assertEquals(d.month, 10) self.assertEquals(d.day, 20) self.assertEquals(d.hour, 15) self.assertEquals(d.minute, 34) self.assertEquals(d.second, 56) self.assertEquals(d.microsecond, 123000) self.assertEquals(d.tzinfo.tzname(None), "+0230") offset = d.tzinfo.utcoffset(None) self.assertEquals(offset.days, 0) self.assertEquals(offset.seconds, 60 * 60 * 2.5) def testParseDateTz3(self): """Tests parse date tz.""" d = iso8601.parseDate("2006-10-20T15:34:56.123+02") self.assertEquals(d.year, 2006) self.assertEquals(d.month, 10) self.assertEquals(d.day, 20) self.assertEquals(d.hour, 15) self.assertEquals(d.minute, 34) self.assertEquals(d.second, 56) self.assertEquals(d.microsecond, 123000) self.assertEquals(d.tzinfo.tzname(None), "+02") offset = d.tzinfo.utcoffset(None) self.assertEquals(offset.days, 0) self.assertEquals(offset.seconds, 60 * 60 * 2) def testParseDateTz4(self): """Tets parse date tz.""" d = iso8601.parseDate("2012-08-08T01:30:00+0530") self.assertEquals(d.year, 2012) self.assertEquals(d.month, 8) self.assertEquals(d.day, 8) self.assertEquals(d.hour, 1) self.assertEquals(d.minute, 30) self.assertEquals(d.second, 0) self.assertEquals(d.microsecond, 0) self.assertEquals(d.tzinfo.tzname(None), "+0530") offset = d.tzinfo.utcoffset(None) self.assertEquals(offset.days, 0) self.assertEquals(offset.seconds, 60 * 60 * 5.5) def testParseInvalidDate(self): """Tests parse invalid date.""" try: iso8601.parseDate(None) except iso8601.ParseError: pass else: self.assertEquals(1, 2) def testParseInvalidDate2(self): """Tests parse invalid date.""" try: iso8601.parseDate("23") except iso8601.ParseError: pass else: self.assertEquals(1, 2) def testParseNoTimezone(self): """issue 4 - Handle datetime string without timezone This tests what happens when you parse a date with no timezone. While not strictly correct this is quite common. I'll assume UTC for the time zone in this case. """ d = iso8601.parseDate("2007-01-01T08:00:00") self.assertEquals(d.year, 2007) self.assertEquals(d.month, 1) self.assertEquals(d.day, 1) self.assertEquals(d.hour, 8) self.assertEquals(d.minute, 0) self.assertEquals(d.second, 0) self.assertEquals(d.microsecond, 0) self.assertEquals(d.tzinfo, iso8601.UTC) def testParseNoTimezoneDifferentDefault(self): """Tests parse no timezone different default.""" tz = iso8601.FixedOffset(2, 0, "test offset") d = iso8601.parseDate("2007-01-01T08:00:00", default_timezone=tz) self.assertEquals(d.tzinfo, tz) def testSpaceSeparator(self): """Handle a separator other than T""" d = iso8601.parseDate("2007-06-23 06:40:34.00Z") self.assertEquals(d.year, 2007) self.assertEquals(d.month, 6) self.assertEquals(d.day, 23) self.assertEquals(d.hour, 6) self.assertEquals(d.minute, 40) self.assertEquals(d.second, 34) self.assertEquals(d.microsecond, 0) self.assertEquals(d.tzinfo, iso8601.UTC) def testUtcOffsets1(self): """Tests other UTC offset formats.""" d = iso8601.parseDate("2012-09-08T20:00:00-0700") offset = d.tzinfo.utcoffset(None) self.assertEquals(offset.days, -1) self.assertEquals(offset.seconds, 24 * 60 * 60 - 60 * 60 * 7) def testUtcOffsets2(self): """Tests other UTC offset formats.""" d = iso8601.parseDate("2012-09-08T20:00:00-07:00") offset = d.tzinfo.utcoffset(None) self.assertEquals(offset.days, -1) self.assertEquals(offset.seconds, 24 * 60 * 60 - 60 * 60 * 7) def testTimezoneless(self): """Tests the timezoneless event feature.""" self.assertEquals(iso8601.isTimezoneLessEvent('2012-07-04T19:00:00-0700'), False) self.assertEquals(iso8601.isTimezoneLessEvent('2012-07-04T19:00:00'), True) def testParseDateLongYear(self): """Tests parsing of date for years with more than 4 digits.""" d = iso8601.parseDate("42557-01-27T08:00:00") self.assertEquals(d.year, 9999)
Shell
UTF-8
463
2.515625
3
[]
no_license
#!/bin/bash trap 'printf "\e[K";printf "[ \e[32mOK\e[0m ]\n";exit' 1 2 3 4 6 9 15 p=("[\e[31m*\e[0m ]" "[\e[1;31m*\e[0m\e[31m*\e[0m ]" "[\e[31m*\e[1;31m*\e[0m\e[31m*\e[0m ]" "[ \e[31m*\e[1;31m*\e[0m\e[31m*\e[0m ]" "[ \e[31m*\e[1;31m*\e[0m\e[31m*\e[0m ]" "[ \e[31m*\e[1;31m*\e[0m\e[31m*\e[0m]" "[ \e[31m*\e[1;31m*\e[0m]" "[ \e[31m*\e[0m]") while : do for i in {0..7} {6..1} do printf "${p[$i]} $(date "+%H:%M:%S")\r" sleep 0.25s done done
Java
UTF-8
309
2.734375
3
[]
no_license
package decorator; abstract class DekoratorWniosek implements InterfaceWniosek { private InterfaceWniosek interfaceww; DekoratorWniosek(InterfaceWniosek interfaceww) { this.interfaceww = interfaceww; } @Override public void zloz() { interfaceww.zloz(); } }
Markdown
UTF-8
4,172
2.734375
3
[]
no_license
# Easycontroller (this is for v2 from 2023, for old version files switch to branch v1) Application for using midi-controllers in an easy and convinient way across max/msp and Openframeworks (Only for Mac users). The idea is to be able to master your midi-controller in live music and visual, independently of the platform used. Initially, map your midi-controller by touching the knobs and click on the desired knob in th panel. Then you set to work with the paramters directly in your OF app and Max patch. You can label knobs/pads for each parameter in your program/song/visualization, assign various value-ranges for each slider, and set presets for your midi-controller in each chapter of your performance. We perform with this tool at 42Noir, we've tested it mostely for Novation and Yamaha controllers, but if your controller has unique midi formating (:/) contact us and we would try to sort it out for you. # Instruction for Openframeworks 1. Download the application in <a href="http://www.42noir.com/es">http://www.42noir.com/es</a> 2. Follow the guide in the page to see how to install and assigne your midi-controller, and also watch how to use Easycontroller with Max/MSP. 3. Download the dependant class files: escon.h and escon.cpp and add them to your openframework target files or use it next to a specific programm. In your ofapp.h include the "escon.h" and create an object member of escon (e.g. escon easy). Then use the member functions label, rec, snd, to recieve/send parameters from/to the controller. Alternatively, download all files and run the example ofapp to see how to call values (easy.rec("s1")), and to label your knobs in the application. A short guide: <a href="https://www.youtube.com/watch?v=p2aoKF6KGdI&t=2s">EasyController with OF</a> <a href="url"><img src="https://github.com/shaltiel/ofEasycontroller/blob/master/Hanging.gif" align="centre" height="270" width="480" ></a> # Usage * Easymapping of midi-controllers. * Labeling knobs and pads. * assign multiple ranges. * Applying Presets. * Control both Max and OF together. <a href="url"><img src="http://42noir.com/wp-content/uploads/2016/12/3-screenshot@2x-1.png" align="left" height="200" width="300" ></a> ### In Easycontroller * To map your midi-controller, choose the instrument from the drop menu, turn on the map midi button, and assign sliders and pads by moving a knob/pad and then pressing the label above the knob/pad in Easycontroller. Press save to use this mapping as defult for next use. * Press "shift" to store a preset or "alt+shift" to remove a preset. ### Functions in OpenFrameworks #### Recieve ```c++ int escon::rec(string); //recieve value from Easycontroller using the string name, e.g. rec("s1"),rec("s4b"), rec("p1b") for recieving values from slider 1 slider 4 from set b and for pad 1 in set b. float escon::rec(string,float, float); //recieve with a new range from string index of Easycontroller: rec("s3",-1,4.1) int escon::rec(int); //recieve value from Easycontroller, see the table function for the mapping float escon::rec(int,float,float);//recieve new range values from index int escon::table(string); //get index from string ``` #### Send / Label ```c++ void escon::label(string,string); //send a label to controller, e.g. label("s1","of_slid") void escon::snd(string,int); //send a value to midi-controller and Easycontroller void escon::snd_wait(int,int); //send a value to midi-controller using index and wait until the queue is empty (for escon::setup, and presets) void escon::snd(int,int); //send but do not wait if the queue is full ``` #### Presets ```c++ void escon::set_to_preset(string,int);// set a pad with string name to control a preset number (in escon::update use: set_to_preset("p2",2) to call preset 2 with pad 2) void escon::call_preset(int); // call a preset (use in escon::setup function) void escon::all_s(int);//set all slides to a value (use in escon::setup function) void escon::all_p(int);//set all pads to a value (use in escon::setup function) ```
C++
UTF-8
2,101
2.65625
3
[ "Apache-2.0" ]
permissive
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. #pragma once #include "paddle/phi/core/dense_tensor.h" namespace phi { /** * @brief Performs sorting on the input tensor along the given axis and outputs * two tensors, Output(Out) and Output(Indices). They reserve the same * shape with Input(X), and Output(Out) represents the sorted tensor * while Output(Indices) gives the sorted order along the given axis * Attr(axis). * @param ctx device context * @param x The input of Argsort * @param axis The axis along which to sort the tensor. * When axis < 0, the actual axis will be the |axis|'th * counting backwards * @param descending The descending attribute is a flag to tell * algorithm how to sort the input data. * If descending is true, will sort by descending order, * else if false, sort by ascending order * @param out The sorted tensor of Argsort op, with the same shape as * x * @param indices The indices of a tensor giving the sorted order, with * the same shape as x */ template <typename T, typename Context> void ArgsortKernel(const Context& dev_ctx, const DenseTensor& input, int axis, bool descending, DenseTensor* output, DenseTensor* indices); } // namespace phi