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
C
UTF-8
343
3.1875
3
[]
no_license
#include<stdio.h> int main() { char ch; printf("enter any character \n"); scanf("%c",&ch); switch(ch) { case'a': printf("vowel"); break; case'e': printf("vowel"); break; case'i': printf("vowel"); break; case'o': printf("vowel"); break; case'u': printf("vowel"); break; default: printf("consonent"); } return 0; }
Java
UTF-8
1,038
2.15625
2
[ "Apache-2.0" ]
permissive
package com.rbkmoney.fraudbusters.management.service; import com.rbkmoney.damsel.fraudbusters.Command; import com.rbkmoney.fraudbusters.management.converter.TemplateModelToCommandConverter; import com.rbkmoney.fraudbusters.management.domain.TemplateModel; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public class TemplateCommandService { public static final String EMPTY_STRING = ""; private final CommandSender commandSender; private final String topic; private final TemplateModelToCommandConverter templateModelToCommandConverter; public String sendCommandSync(Command command) { String key = command.getCommandBody().getTemplate().getId(); return commandSender.send(topic, command, key); } public Command createTemplateCommandById(String id) { return templateModelToCommandConverter.convert(TemplateModel.builder() .id(id) .template(EMPTY_STRING) .build()); } }
JavaScript
UTF-8
2,687
2.65625
3
[ "MIT" ]
permissive
const BASE_URL = "http://localhost:4000"; // Action Creators const setUser = payload => ({ type: "SET_USER", payload }); const setLogOut = () => ({ type: "LOG_OUT" }); // Methods export const logUserOut = () => dispatch => { fetch(`${BASE_URL}/logout`, { method: "delete", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify({ refreshToken: localStorage.getItem("refreshToken") }) }) .then(() => dispatch(setLogOut)) .catch(err => console.error(err)); }; export const fetchUser = userInfo => dispatch => { console.log("Called fetchUser with ", userInfo); fetch(`${BASE_URL}/login`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(userInfo) }) .then(res => { return res.json(); }) .then(data => { // data sent back will in the format of // { // user: {}, //. token: "aaaaa.bbbbb.bbbbb" // } localStorage.setItem("token", data.accessToken); localStorage.setItem("refreshToken", data.refreshToken); dispatch(setUser(data.user)); }) .catch(err => console.error(err)); }; export const signUserUp = userInfo => dispatch => { fetch(`${BASE_URL}/users`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(userInfo) }) .then(res => res.json()) .then(data => { // data sent back will in the format of // { // user: {}, //. token: "aaaaa.bbbbb.bbbbb" // } dispatch(setUser(data.user)); }); }; export const autoLogin = () => dispatch => { fetch(`${BASE_URL}/auto_login`, { headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${localStorage.getItem("token")}` } }) .then(res => res.json()) .then(data => { // data sent back will in the format of // { // user: {}, //. token: "aaaaa.bbbbb.bbbbb" // } dispatch(setUser(data.user)); }) .catch(() => { dispatch(refreshToken()); }); }; const refreshToken = () => dispatch => { fetch(`${BASE_URL}/token`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify({ refreshToken: localStorage.getItem("refreshToken") }) }) .then(res => res.json()) .then(data => { if (data.accessToken) { localStorage.setItem("token", data.accessToken); dispatch(autoLogin()); } }); };
Python
UTF-8
258
2.984375
3
[]
no_license
# LeetCode 53 def maxSubArray(L): n = len(L) curr_sum = max_sum = L[0] for i in range(1, n): curr_sum = max(L[i], curr_sum + L[i]) max_sum = max(max_sum, curr_sum) return max_sum nums = eval(input()) print(maxSubArray(nums))
C++
UTF-8
2,430
3.265625
3
[]
no_license
#include "common.h" // TODO: // a) 简化代码,四个变量即可 // b) 划分区间法 class Solution { public: int maxProfit(vector<int>& prices) { const int len = prices.size(); if (len < 2) return 0; array<int, 4> dp[2]; // 持有,没有,持有,没有 dp[0][0] = -prices[0]; dp[0][1] = 0; dp[0][2] = -prices[0]; dp[0][3] = 0; for (int i = 1; i < len; ++i) { // 注意,要引用!!! auto &next = dp[i & 1]; auto &cur = dp[(i & 1) ^ 1]; int v = prices[i]; next[0] = max(cur[0], -v); next[1] = max(cur[1], cur[0] + v); next[2] = max(cur[2], cur[1] - v); next[3] = max(cur[3], cur[2] + v); } auto e = dp[(len & 1) ^ 1]; return max(e[1], e[3]); } }; class Solution { public: int maxProfit(vector<int>& prices) { const int len = prices.size(); if (len < 2) return 0; array<int, 4> dp; // 持有,没有,持有,没有 dp[0] = -prices[0]; dp[1] = 0; dp[2] = -prices[0]; dp[3] = 0; for (int i = 1; i < len; ++i) { int v = prices[i]; dp[0] = max(dp[0], -v); dp[1] = max(dp[1], dp[0] + v); dp[2] = max(dp[2], dp[1] - v); dp[3] = max(dp[3], dp[2] + v); } return max(dp[1], dp[3]); } }; class Solution { public: int maxProfit(vector<int>& prices) { const int len = prices.size(); if (len < 2) return 0; // dp[day][k][2] const int K = 2; // 注意对k的处理!!!! int dp[len][K+1][2]; dp[0][0][0] = 0; dp[0][0][1] = INT32_MIN; for (int k = 1; k <= K; ++k) { dp[0][k][0] = 0; dp[0][k][1] = -prices[0]; } for (int i = 1; i < len; ++i) { int &price = prices[i]; for (int k = 0; k <= K; ++k) { dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + price); if (k == 0) dp[i][k][1] = dp[i-1][k][1]; else dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - price); } } return dp[len-1][K][0]; } }; int main() { vector<int> prices; INPUT_ARRAY(prices); cout << Solution().maxProfit(prices) << endl; return 0; }
JavaScript
UTF-8
365
2.859375
3
[]
no_license
function setup() { createCanvas(750, 750); noStroke(); rectMode(CENTER); } function draw() { background(0000); fill(250,170,35); rect(mouseX, height/2, mouseY/2+10, mouseY/2+10); fill(215,130,40); var inverseX = width-mouseX; var inverseY = height-mouseY; rect(inverseX, height/2, (inverseY/2)+10, (inverseY/2)+10); }
Python
UTF-8
5,023
3.765625
4
[ "MIT" ]
permissive
from __future__ import annotations from .currency import Currency import operator import math class Money: def __init__(self, amount: int, currency: Currency): self.__assert_amount(amount) self.__amount = amount self.__currency = currency def instance(self, amount: int) -> Money: """ Return new money object using the same currency and given amount """ self.__assert_amount(amount) return self.__class__( amount, self.currency ) def __assert_currency(self, money: Money): """ Assert that given money has the same currency """ if not self.currency.equals(money.currency): raise ValueError('Currencies do not match') @staticmethod def __assert_amount(amount): """ Assert that given amount is an integer """ if not isinstance(amount, int): raise ValueError('Amount must be an integer') @staticmethod def __assert_operand(operand): """ Assert that given operand is a numeric type """ if not isinstance(operand, (int, float)): raise ValueError('Operand must be a numeric value') @property def amount(self) -> int: """ Return money amount """ return self.__amount @property def currency(self) -> Currency: """ Return currency object """ return self.__currency def __add__(self, money: Money) -> Money: """ Return a new money object that amounts to sum of this object and given money object """ self.__assert_currency(money) return self.__class__( self.amount + money.amount, self.currency ) def __sub__(self, money: Money) -> Money: """ Return a new money object that amounts to difference of this object and given money object """ self.__assert_currency(money) return self.__class__( self.amount - money.amount, self.currency ) def __mul__(self, factor: (int, float)) -> Money: """ Return a new money object that amounts to product of this object and given money object """ self.__assert_operand(factor) return self.__class__( round(self.amount * factor), self.currency ) def __eq__(self, money: Money) -> bool: """ Check if given money object value and currency matches this object """ if not self.currency.equals(money.currency): return False return self.amount == money.amount def __gt__(self, money: Money) -> bool: """ Check if object amount is greater than given money amount """ return self.__compare(money, operator.gt) def __ge__(self, money: Money) -> bool: """ Check if object amount is greater or if it equals to given money amount """ return self.__compare(money, operator.ge) def __lt__(self, money: Money) -> bool: """ Check if object amount is less than given money amount """ return self.__compare(money, operator.lt) def __le__(self, money: Money) -> bool: """ Check if object amount is less or if it equals to given money amount """ return self.__compare(money, operator.le) def __compare(self, money: Money, operator) -> bool: """ Compare object amount to given money amount using the provided comparison operator """ self.__assert_currency(money) return operator(self.amount, money.amount) def allocate(self, ratios: list) -> list[Money]: """ Allocate object amount to given ratios and return a collection of new money objects """ results = [] fractions = [] total = sum(ratios) remainder = self.amount if total == 0: raise ValueError('Sum of ratios must be greater than zero') """ Share for each ratio is calculated and stored as a new money object """ for ratio in ratios: if ratio < 0: raise ValueError('Ratio must be zero or positive') fraction = self.amount * ratio / total fraction = fraction - math.floor(fraction) fractions.append(fraction) share = self.amount * ratio // total results.append(self.instance(share)) remainder = remainder - share """ Distribute the remainder one by one, starting with the biggest fraction first until all is allocated """ while remainder > 0: index = fractions.index(max(fractions)) fractions[index] = 0 results[index] += self.instance(1) remainder -= 1 return results
Python
UTF-8
480
2.625
3
[]
no_license
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 import pyperclip as p def fullStackPaste(): stack = open("/Users/scottmolloy/Desktop/.alfredWork/stack/stack.txt", "r").read().split("\t\t∴\n") paste = "" for i in range(len(stack)): paste = paste + "\n" + stack[i] open("/Users/scottmolloy/Desktop/.alfredWork/stack/stack.txt", "w").write("") paste = paste.strip("\n") if paste: return(paste) else: return("<empty>") p.copy(fullStackPaste())
PHP
UTF-8
3,173
2.65625
3
[ "MIT", "Apache-2.0" ]
permissive
<?php /** * This is the model class for table "user_module". * It holds all activated user modules. * * When user_id is set to 0 the record defines the user default setting. * * The followings are the available columns in table 'user_module': * @property integer $id * @property string $module_id * @property integer $user_id * @property integer $state * * @author Zak * @package profiler.modules_core.user.models * @since 0.5 */ class UserApplicationModule extends HActiveRecord { private static $_states = array(); const STATE_DISABLED = 0; const STATE_ENABLED = 1; const STATE_FORCE_ENABLED = 2; const STATES_CACHE_ID_PREFIX = 'user_module_states_'; /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return UserApplicationModule the static model class */ public static function model($className = __CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'user_module'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('module_id, user_id', 'required'), array('user_id, state', 'numerical', 'integerOnly' => true), array('module_id', 'length', 'max' => 255), ); } public function beforeSave() { if ($this->user_id == "") { $this->user_id = 0; } Yii::app()->cache->delete(self::STATES_CACHE_ID_PREFIX . $this->user_id); return parent::beforeSave(); } public function beforeDelete() { Yii::app()->cache->delete(self::STATES_CACHE_ID_PREFIX . $this->user_id); return parent::beforeDelete(); } /** * @return array relational rules. */ public function relations() { return array( 'user' => array(self::BELONGS_TO, 'User', 'user_id'), ); } /** * Returns an array of moduleId and the their states (enabled, disabled, force enabled) * for given user id. If space id is 0 or empty, the default states will be returned. * * @param int $userId * @return array State of Module Ids */ public static function getStates($userId = 0) { if (isset(self::$_states[$userId])) { return self::$_states[$userId]; } $states = Yii::app()->cache->get(self::STATES_CACHE_ID_PREFIX . $userId); if ($states === false) { $states = array(); foreach (UserApplicationModule::model()->findAllByAttributes(array('user_id' => $userId)) as $userModule) { $states[$userModule->module_id] = $userModule->state; } Yii::app()->cache->set(self::STATES_CACHE_ID_PREFIX . $userId, $states); } self::$_states[$userId] = $states; return self::$_states[$userId]; } }
Java
UTF-8
226
1.882813
2
[]
no_license
package server; import mayflower.Actor; public class ServerWeaponsActor extends Actor { public ServerWeaponsActor() { setImage("img/LaserCannon.png"); } @Override public void act() { } }
Python
UTF-8
4,352
3.15625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- import pygame class WeaponFireSprite(pygame.sprite.Sprite): def __init__(self, screen, last_direction, x, y): super(WeaponFireSprite, self).__init__() self.x, self.y = x, y self.last_direction = last_direction self.screen = screen self.left, self.right, self.up, self.down = [], [], [], [] for i in range(6): self.right.append(pygame.image.load("./images/enemies/weapon-fire-right_{}.png".format(i+1))) self.left.append(pygame.image.load("./images/enemies/weapon-fire-left_{}.png".format(i+1))) self.up.append(pygame.image.load("./images/enemies/weapon-fire-up_{}.png".format(i+1))) self.down.append(pygame.image.load("./images/enemies/weapon-fire-down_{}.png".format(i+1))) self.index = 0 self.image = self.right[self.index] self.rect = pygame.Rect(self.x, self.y, 32, 32) def update(self): self.index += 1 if self.index >= len(self.left) * 20: self.index = 0 if self.index % 20 == 0: if self.last_direction == 'left': self.image = self.left[int(self.index/20)] elif self.last_direction == 'right': self.image = self.right[int(self.index/20)] elif self.last_direction == 'up': self.image = self.up[int(self.index/20)] elif self.last_direction == 'down': self.image = self.down[int(self.index/20)] super(WeaponFireSprite, self).update() # enemy's weapon class (fire) class WeaponFire(pygame.sprite.Group): def __init__(self, screen, enemy): self.enemy, self.screen = enemy, screen self.drawing, self.last_direction = False, self.enemy.face if self.last_direction == 'left': self.x, self.y = self.enemy.x, self.enemy.y elif self.last_direction == 'right': self.x, self.y = self.enemy.x + 4, self.enemy.y elif self.last_direction == 'up': self.x, self.y = self.enemy.x + 2, self.enemy.y elif self.last_direction == 'down': self.x, self.y = self.enemy.x, self.enemy.y + 4 self.rect = pygame.Rect(self.x, self.y, 32, 32) self.centerx, self.centery = self.rect.center self.weapon_fire_sprite = WeaponFireSprite(self.screen, self.last_direction, self.x, self.y) super(WeaponFire, self).__init__(self.weapon_fire_sprite) def draw(self): if self.drawing: self.screen.blit(self.weapon_fire_sprite.image, [self.x, self.y]) def update(self): self.centerx, self.centery = self.rect.center if self.drawing: if self.last_direction == 'left': if self.x >= 2: self.x -= 0.5 elif self.last_direction == 'right': if self.x <= 632: self.x += 0.5 elif self.last_direction == 'up': if self.y >= 2: self.y -= 0.5 elif self.last_direction == 'down': if self.y <= 632: self.y += 0.5 if self.x <= 4 or self.x >= 632 or self.y <= 4 or self.y >= 632: self.drawing = False self.last_direction = self.enemy.face if self.enemy.face == 'left': self.x, self.y = self.enemy.x, self.enemy.y elif self.enemy.face == 'right': self.x, self.y = self.enemy.x + 4, self.enemy.y elif self.enemy.face == 'up': self.x, self.y = self.enemy.x + 2, self.enemy.y elif self.enemy.face == 'down': self.x, self.y = self.enemy.x, self.enemy.y + 4 else: self.last_direction = self.enemy.face if self.enemy.face == 'left': self.x, self.y = self.enemy.x, self.enemy.y elif self.enemy.face == 'right': self.x, self.y = self.enemy.x + 4, self.enemy.y elif self.enemy.face == 'up': self.x, self.y = self.enemy.x + 2, self.enemy.y elif self.enemy.face == 'down': self.x, self.y = self.enemy.x, self.enemy.y + 4 self.rect = pygame.Rect(self.x, self.y, 32, 32) super(WeaponFire, self).update()
Python
UTF-8
1,177
2.59375
3
[]
no_license
from collections import OrderedDict from slugify import slugify def classification_to_extract(classification): extract = OrderedDict() for annotation in classification['annotations']: if 'task_label' in annotation: # we should really add a `short_label` on the workflow so this name can be configured task_key = slugify(annotation['task_label'], separator='-') else: task_key = annotation['task'] for idx, value in enumerate(annotation['value']): if 'tool_label' in value: # we should really add a `short_label` on the workflow so this name can be configured key = '{0}_{1}'.format(task_key, slugify(value['tool_label'], separator='-')) else: key = '{0}_tool{1}'.format(task_key, value['tool']) if ('x' in value) and ('y' in value): extract.setdefault('{0}_x'.format(key), []).append(value['x']) extract.setdefault('{0}_y'.format(key), []).append(value['y']) return extract def point_extractor_request(request): data = request.get_json() return classification_to_extract(data)
Ruby
UTF-8
693
2.71875
3
[]
no_license
require_relative './player' class Enemy < Player attr_reader :speed OffscreenBuffer = 5 def initialize(initial_x, initial_y, ground, speed) super(initial_x, initial_y, ground) @speed = speed end def color case speed when 1 Gosu::Color::WHITE when 2 Gosu::Color::GREEN when 3 Gosu::Color::YELLOW when 4 Gosu::Color.new 255, 255, 153, 0 when 5 Gosu::Color::RED end end def off_screen? x <= -Size end def x_min -Size - OffscreenBuffer end def play_jumping_sound Media::EnemyBoink.play end def death_sound Media::EnemyDeath end def go_left @x_velocity = -speed end end
PHP
UTF-8
2,766
2.59375
3
[]
no_license
<?php namespace App\Http\Controllers; use AccountKit; use GuzzleHttp\Client; use GuzzleHttp\Psr7; use GuzzleHttp\Exception\RequestException; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class CustomLoginController extends Controller { public function otpLogin(Request $request) { // Initialize variables $app_id = env("FB_ACCOUNTKIT_APP_ID"); $secret = env("FB_ACCOUNTKIT_APP_SECRET"); $version = 'v1.1'; // 'v1.1' for example $code = $request->code; //MYSELF // Exchange authorization code for access token $token_exchange_url = 'https://graph.accountkit.com/' . $version . '/access_token?' . 'grant_type=authorization_code' . '&code=' . $code . "&access_token=AA|$app_id|$secret"; $firstResponse = $this->doGuzzle($token_exchange_url); $firstResponseBody = $firstResponse->getBody(); $data = \GuzzleHttp\json_decode( $firstResponseBody ); $user_id = $data->id; $user_access_token = $data->access_token; $refresh_interval = $data->token_refresh_interval_sec; /* * Cannot use object of type GuzzleHttp\\Psr7\\Response as array $user_id = $data['id']; $user_access_token = $data['access_token']; $refresh_interval = $data['token_refresh_interval_sec']; return $data; */ // Get Account Kit information $me_endpoint_url = 'https://graph.accountkit.com/' . $version . '/me?' . 'access_token=' . $user_access_token; $secondResponse = $this->doGuzzle($me_endpoint_url); $secondResponseBody = $secondResponse->getBody(); $data2 = \GuzzleHttp\json_decode($secondResponseBody); $phone = property_exists($data2, 'phone') ? $data2->phone->number : ''; /* * After getting the phone number, You make sure the user is valid. * Now you may GENERATE token for token_based_auth * (Example: Using Laravel Passport, or jwt.). * */ return $phone; /* Here "isset" will not work, because the object is json decoded, So we have to use "property_exists" $phone = isset($data2['phone']) ? $data2['phone']['number'] : ''; $email = isset($data2['email']) ? $data2['email']['address'] : ''; */ // return $data2; } function doGuzzle($url) { $client = new Client(); try { return $client->request('GET', $url); } catch (RequestException $e) { echo Psr7\str($e->getRequest()); if ($e->hasResponse()) { return Psr7\str($e->getResponse()); } } } }
Java
UTF-8
525
2.125
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 edu.mum.model; import java.time.LocalDate; import java.util.List; /** * * @author Tewodros Ayele Assefa */ public interface Block { int getId(); void setId(int id); List<Course> getCourses(); LocalDate getStartDate(); void setCourses(List<Course> courses); void setStartDate(LocalDate startDate); }
PHP
UTF-8
2,104
3.171875
3
[ "MIT" ]
permissive
<?php namespace App\Models; /** * Model for the GROUPS table. Includes USER_GROUPS data. * * */ class GroupModel implements \JsonSerializable { private $id; private $adminId; private $name; private $description; private $members; private static $rules = [ 'name' => 'required|between:3,32', 'description' => 'max:255' ]; function __construct($id, $adminId, $name, $description, $members=array()) { $this->id = $id; $this->adminId = $adminId; $this->name = $name; $this->description = $description; $this->members = $members; } public function jsonSerialize() { return get_object_vars($this); } /** * * @return multitype:string */ public static function getRules() { return GroupModel::$rules; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getAdminId() { return $this->adminId; } /** * @param mixed $adminId */ public function setAdminId($adminId) { $this->adminId = $adminId; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name */ public function setName($name) { $this->name = $name; } /** * @return mixed */ public function getDescription() { return $this->description; } /** * @param mixed $description */ public function setDescription($description) { $this->description = $description; } /** * @return mixed */ public function getMembers() { return $this->members; } /** * @param mixed $members */ public function setMembers($members) { $this->members = $members; } }
Shell
UTF-8
139
2.875
3
[]
no_license
#!/bin/zsh # kills all apps using the isight camers kill_camera() { lsof | grep -i "AppleCamera" | awk '{ print $2 }' | xargs kill -9 }
Java
UTF-8
131
1.726563
2
[]
no_license
package domain; /** * Class depends of Artist * @see Artist * @author Taras */ public class TechnicalWriter extends Artist { }
Markdown
UTF-8
10,999
2.9375
3
[]
no_license
# Data Analysis ### Table of Contents - [Data Exploration](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#data-exploration) - [Attack](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#attack) - [Goals Scored](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#goals-scored) - [Comebacks](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#comebacks) - [Defence](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#defence) - [Goals Conceded](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#goals-conceded) - [Clean Sheets](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#clean-sheets) - [Throw-aways](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#throw-aways) - [Overall](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#overall) - [Wins, Draws, and Losses](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#wins-draws-and-losses) - [Clusters](https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/analysis.md#Clusters) ### Data Exploration The data contains a record of 1,808 matches played between 29 clubs, from the start of 2015-2016 season up till the [COVID-19 break](https://www.premierleague.com/news/1645173) in 2020. Due to the concept of promotion and relegation, not all clubs had played an equal amount of matches (fig. 1). To eliminate bias, most analyses were conducted on clubs that had played more or equal to the total average amount of matches played by a club (125). | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/games.png' width='1500'> | | :--: | | _Figure 1 - Number of Matches Played_ | ### Attack This section provides analyses of attack statistics including goals scored and comebacks. #### Goals Scored | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_top10.png' width='1000'>| | :--: | | _Figure 2 - Total Goals Scored (Top 10)_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_bottom10.png' width='1000'>| | :--: | | _Figure 3 - Total Goals Scored (Bottom 10)_ | Manchester City and Liverpool are leading the goals tally (fig. 2), whereas Middlesbrough and Sheffied United are at the bottom (fig.3). Interestingly, Leicester is a little ahead of Manchester United. | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_firsthalf_top10.png' width='1000'>| | :--: | | _Figure 4 - Total Goals Scored in First Half (Top 10)_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_firsthalf_bottom10.png' width='1000'>| | :--: | | _Figure 5 - Total Goals Scored in First Half (Bottom 10)_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_secondhalf_top10.png' width='1000'>| | :--: | | _Figure 6 - Total Goals Scored in Second Half (Top 10)_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_secondhalf_bottom10.png' width='1000'>| | :--: | | _Figure 7 - Total Goals Scored in Second Half (Bottom 10)_ | Manchester City and Liverpool lead the statistics in both the halves, followed by a fight between Chelsea, Tottenham, and Arsenal. Hull and Cardiff have scored the least goals in the first half, whereas Middlesbrough has scored the least in the second half. | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_per_game.png' width='1000'>| | :--: | | _Figure 8 - Total Goals Scored per Game_ | The goals per game standings are similar to the total goals standings. Manchester City and Liverpool have an impressive record of scoring more than 2 goals per game. #### Comebacks The comeback statistics are computed as a percentage: `successful comebacks / total comeback opportunities * 100%` For the purpose of this analysis, a *successful comeback* is defined as: when a club is losing at half time, and ends up winning the match. A *comeback opportunities* is defined as a situation where a club is losing at half time. | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/comebacks_home.png' width='1000'>| | :--: | | _Figure 9 - Home Comebacks_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/comebacks_away.png' width='1000'>| | :--: | | _Figure 10 - Away Comebacks_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/comebacks_total.png' width='1000'>| | :--: | | _Figure 11 - Total Comebacks_ | Liverpool are way ahead of others in terms of converting comeback opportunities to successful comebacks, both home and away. Interestingly, Chelsea is in second place when it comes to Away comebacks, but has not been able to overturn a half time deficit at home (8 opportunities). ### Defence This section provides analyses of attack statistics including goals conceded, clean sheets, and throw-aways. #### Goals Conceded | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_conceded_per_game.png' width='1000'>| | :--: | | _Figure 12 - Total Goals Conceded per Game_ | Manchester City is the most defensively successful club in terms of goals conceded per game, followed by Liverpool, Manchester United, and Tottenham (fig. 12). Interstingly, it is their defensive performane in the second-half that pushes them ahead of the other clubs (fig. 14). | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_conceded_per_game_firsthalf.png' width='1000'>| | :--: | | _Figure 13 - Goals Conceded per Game (First Half)_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/goals_conceded_per_game_secondhalf.png' width='1000'>| | :--: | | _Figure 14 - Total Goals Conceded per Game (Second Half)_ | #### Clean Sheets | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/clean_sheets_total.png' width='1000'>| | :--: | | _Figure 15 - Total Clean Sheets_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/clean_sheets_percent.png' width='1000'>| | :--: | | _Figure 16 - Total Clean Sheets (%)_ | Manchester City has the most clean sheets, followed by Liverpool and Manchester United (fig. 15). Interestingly, it is their defensive performance at away games which puts them ahead of the others (fig. 17). | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/clean_sheets_home.png' width='1000'>| | :--: | | _Figure 17 - Clean Sheets (Home)_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/clean_sheets_away.png' width='1000'>| | :--: | | _Figure 18 - Clean Sheets (Away)_ | #### Throw-aways The throw-away statistics are computed as a percentage: `successful throw-aways / total throw-away opportunities * 100%` For the purpose of this analysis, a *successful throw-away* is defined as: when a club is winning at half time, and ends up losing the match. A *comeback opportunities* is defined as a situation where a club is winning at half time. It is the opposite of a comeback. | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/throwaways_home.png' width='1000'>| | :--: | | _Figure 19 - Home Throwaways_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/throwaways_away.png' width='1000'>| | :--: | | _Figure 20 - Away Throwaways_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/throwaways_total.png' width='1000'>| | :--: | | _Figure 21 - Total Throwaways_ | Crystal Palace and Southampton have thrown away the highest percentage of their home games, whereas Leicester and Southampton have thrown away the highest percentage of their away games. Out of the top clubs, Tottenham has thrown away the highest percentage of home and away games. Chelsea (40 opportunities), Leicester (33 opportunities), Liverpool (52 opportunities), Manchester United (43 opportunities), and Newcastle (16 opportunities) have not thrown away a game at home. Manchester United is the only club which has not thrown away an away game (34 opportunities). This makes them the only club that has not thrown away a game at all (77 opportunities). ### Overall #### Wins, Draws, and Losses The _win, draw, and loss_ percentages are key metrics to judge the performance of a club. | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/win_percent.png' width='1000'>| | :--: | | _Figure 22 - Win Percentage_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/draw_percent.png' width='1000'>| | :--: | | _Figure 23 - Draw Percentage_ | | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/loss_percent.png' width='1000'>| | :--: | | _Figure 24 - Loss Percentage_ | Manchester City and Liverpool have the highest win ratio (fig. 22) and also the lowest loss ratio (fig. 24). Out of the top clubs, Manchester United has the highest draw ratio and Manchester City has the lowest draw ratio (fig. 23). | <img src='https://github.com/meehadjawwad/Premier-League-Analysis/blob/master/images/table.png' width='500'>| | :--: | | _Figure 25 - Accumulated Points Table_ | #### Clusters Based on the Accumulated Points Table (fig. 25), clubs can be divided into various clusters. **Top of the Table** Manchester City (with a game in hand) and Liverpool are clearly the two best performing clubs. Their difference of 9 points, comes from Liverpool having drawn more games. **Second Cluster** The next cluster of clubs includes Tottenham, Chelsea, Manchester United, and Arsenal (with a game in hand), with only a difference of 26 points between them. They have all won around 90-100 games and have a goal-difference greater than +100. **Third Cluster** Leicester is the only club in the third cluster. It has broken away from the lower clubs (difference of 29 points), but still not part of the second cluster (difference of 42 points.) **Fourth Cluster** Everton is the only club in the fourth cluster. It is 19 points away from the third cluster, and 20 points ahead of the fifth cluster. It is hanging onto a goal-difference of +7. **Fifth Cluster** The fifth cluster includes West Ham, Southampton, Crystal Palace, Bournemouth, and Watford. They are separated by a difference of 25 points and have a negative goal-difference. **The rest** The rest of the clubs have played less than the maximum number of games (181), and their performances can be studied in Fig. 15.
C++
UTF-8
830
3.03125
3
[]
no_license
#include <iostream> #include <string> using namespace std; #include "Decorator.h" void outResult(int cost, string description) { cout << "Coffe: " << description << ", cost: " << cost << endl; } int main() { // oreilly book implementation { // only espresso oreilly::Beverage *esp = new oreilly::coffe::Espresso(); outResult(esp->cost(), esp->getDescription()); // esspresso with double milk oreilly::Beverage *esp2Milk = new oreilly::coffe::Espresso(); esp2Milk = new oreilly::added::Milk(esp2Milk); esp2Milk = new oreilly::added::Milk(esp2Milk); outResult(esp2Milk->cost(), esp2Milk->getDescription()); // HouseBiend oreilly::Beverage *hbMocha = new oreilly::coffe::HouseBiend(); hbMocha = new oreilly::added::Mocha(hbMocha); outResult(hbMocha->cost(), hbMocha->getDescription()); } return 0; }
JavaScript
UTF-8
1,097
3.359375
3
[]
no_license
// xorChar :: char -> char -> char var xorChar = function (char1, char2) { return String.fromCharCode(char1.charCodeAt(0) ^ char2.charCodeAt(0)); }; // xorString :: string -> string -> string var xorString = function (s1, key) { var xored = '', i; for (i in s1) { xored += xorChar(s1[i], key[i % key.length]); } return xored; }; // charMap :: string -> array of charcodes var charMap = function (s) { var codes = [], i; for (i in s) { codes.push(s[i].charCodeAt(0)); } return codes; }; // breakXor :: string -> [string, key] var breakXor = function (xored) { }; var rotateString = function (s, n) { n = n || 1; return s.slice(n) + s.slice(0,n); }; // :: string -> number var countCoincidences = function (s1, s2) { var count = 0; for (var i in s1) { if (s1[i] === s2[i]) count++; } return count; }; module.exports = { xorChar: xorChar, xorString: xorString, charMap: charMap, rotateString: rotateString, countCoincidences: countCoincidences, indexOfCoincidence: countCoincidences };
SQL
UTF-8
501
3.140625
3
[]
no_license
/*TRIGGERS DE VALIDACAO -- EMAIL, CPF*/ /*VALIDA EMAIL*/ CREATE OR REPLACE TRIGGER EMAIL_TRG BEFORE INSERT OR UPDATE OF EMAIL ON USUARIO FOR EACH ROW BEGIN IF VALIDA_EMAIL(:NEW.EMAIL) = 1 THEN RAISE_APPLICATION_ERROR(-20001, 'Email Invalido!'); END IF; END; / /*VALIDA CPF*/ CREATE OR REPLACE TRIGGER CPF_TRG BEFORE INSERT OR UPDATE OF CPF ON USUARIO FOR EACH ROW BEGIN IF VALIDA_CPF(:NEW.CPF) = 1 THEN RAISE_APPLICATION_ERROR(-20001, 'CPF Invalido!'); END IF; END; /
Java
UTF-8
1,835
2.484375
2
[]
no_license
package stepDefinitions; import java.util.List; import java.util.Map; import org.testng.Assert; import com.SDET8BDD.genericUtil.BaseUtil; import com.SDET8BDD.genericUtil.WebdriverUtility; import com.SDET8BDD.pagefactory.CreateOrganization; import com.SDET8BDD.pagefactory.HomePage; import com.SDET8BDD.pagefactory.OrganizationInfoPage; import com.SDET8BDD.pagefactory.OrganizationPage; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; public class OrganizationStepDef extends BaseUtil{ BaseUtil base; List<Map<String, String>> data; public OrganizationStepDef(BaseUtil base) { this.base=base; } @When("I want to click on organization link in homepage") public void i_want_to_click_on_organization_link_in_homepage() { hpage=new HomePage(base.driver); hpage.getOrganizationLink().click(); } @When("I will click on create oraganization link") public void i_will_click_on_create_oraganization_link() { opage=new OrganizationPage(base.driver); opage.getCreateOrgLink().click(); } @When("I create an orgnaziation using mandatory fileds and click on save") public void i_create_an_orgnaziation_using_mandatory_fileds_and_click_on_save(io.cucumber.datatable.DataTable dataTable) { cpage=new CreateOrganization(base.driver); data = dataTable.asMaps(String.class, String.class); cpage.createOrganization(data.get(0).get("OrganizationName")+WebdriverUtility.randomInt()); } @Then("I navigate to organization information and verify") public void i_navigate_to_organization_information_and_verify() { ipage=new OrganizationInfoPage(base.driver); String orgname = ipage.getOrganizationInfo().getText(); Assert.assertEquals(orgname,data.get(0).get("OrganizationName") ); } @Then("logout from the application") public void logout_from_the_application() { } }
C#
UTF-8
2,959
2.546875
3
[]
no_license
using System; using System.Threading.Tasks; using MediatrSampleApi.Handlers.Command; using MediatrSampleApi.Handlers.Query; using MediatR; using Microsoft.AspNetCore.Mvc; using MediatrSampleApi.Handlers.Contracts; using System.Collections.Generic; using MediatrSampleApi.Exceptions; namespace MediatrSampleApi.Controllers { /// <summary> /// </summary> [ProducesResponseType(typeof(ApiResponse), 400)] [Route("api/[controller]")] public class CustomerController : Controller { private readonly IMediator mediator; /// <summary> /// /// </summary> /// <param name="mediator"></param> public CustomerController(IMediator mediator) { this.mediator = mediator; } /// <summary> /// Retrieves all the customers /// </summary> /// <response code="200">Retrieves all the customers</response> /// <response code="400">Something went wrong while retrieving customers</response> [HttpGet] [ProducesResponseType(typeof(ApiResponse<IEnumerable<CustomerResponse>>), 200)] [Route("list")] public async Task<IActionResult> GetCustomersAsync() { var result = await mediator.Send(new CustomerListRequest()); return Ok(result); } /// <summary> /// Retrieves a customer with all of the orders by given customer id /// </summary> /// <response code="200">Retrieves a customer with all of the orders</response> /// <response code="400">Something went wrong while retrieving customer with orders</response> [HttpGet] [ProducesResponseType(typeof(ApiResponse<CustomerWithOrdersResponse>), 200)] [Route("{customerId}/details")] public async Task<IActionResult> GetCustomerWithOrdersAsync([FromRoute] Guid customerId) { var result = await mediator.Send(new CustomerWithOrdersRequest { CustomerId = customerId }); return Ok(result); } /// <summary> /// Creates customer by given new customer information /// </summary> /// <param name="customer"></param> /// <response code="200">Retrieves customer id to indicate succesful creation</response> /// <response code="400">Something went wrong while creating customer</response> [HttpPost] [ProducesResponseType(typeof(ApiResponse<CustomerCreateResponse>), 201)] public async Task<IActionResult> CreateCustomerAsync([FromBody]CustomerRequest customer) { var customerExists = await mediator.Send(new DoesCustomerExistsRequest { Email = customer.Email }); if (customerExists) { throw new ValidationException("Customer already exists"); } var result = await mediator.Send(customer); return Created(string.Empty, result); } } }
Java
UHC
1,858
2.46875
2
[ "MIT" ]
permissive
package Minigames.RandomWeaponWar.Weapons; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.player.PlayerMoveEvent; import Minigames.Minigame; import Minigames.RandomWeaponWar.Weapons.CustomCooldown.CooldownType; import Utility.MyUtility; public class IronFeather extends SpecialWeapon{ public IronFeather(Minigame minigame) { super(minigame, Material.FEATHER, 1, (short)0, "׸ ", 10, 12); //ڵ, , ڵ, ̸, ּҵ, ִ뵩 List<String> loreList = new ArrayList<String>(); // loreList.add("e׸ ̴."); loreList.add("eִ ¿"); loreList.add("e ʴ´."); loreList.add("c޼տ  ɷ "); setLore(loreList); } @Override public void onInit() { } @Override public void onRightClick(Player p) { } @Override public void onLeftClick(Player p) { // TODO Auto-generated method stub } @Override public void onEntityDamaged(EntityDamageEvent e) { if(e.getCause() == DamageCause.FALL) { e.setCancelled(true); } } @Override public void onPlayerMove(PlayerMoveEvent e) { // TODO Auto-generated method stub } @Override public void onHitPlayer(EntityDamageByEntityEvent e, Player damager, Player victim) { // TODO Auto-generated method stub } @Override public void onHitted(EntityDamageByEntityEvent e, Player damager, Player victim) { // TODO Auto-generated method stub } }
Java
UTF-8
2,854
2.234375
2
[]
no_license
package dam.gala.damgame.activities; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.example.damgame.R; import dam.gala.damgame.utils.GameUtil; import static androidx.preference.PreferenceManager.getDefaultSharedPreferences; public class ActMainStart extends AppCompatActivity { private final int GAME_ACTIVITY_ACTION = 2; private final int SETTINGS_ACTION =1; private int sceneCode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_act_main_start); hideSystemUI(); setTema(); Button btLogin = findViewById(R.id.btnLogin); Button btnRegister = findViewById(R.id.btnRegister); btLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent preferences = new Intent(ActMainStart.this, GameActivity.class); startActivityForResult(preferences, GAME_ACTIVITY_ACTION); } }); } /** * Elimina la barra de acción y deja el mayor área posible de pantalla libre */ public void hideSystemUI(){ // Enables regular immersive mode. // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE. // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } private void setTema(){ this.sceneCode = Integer.parseInt(getDefaultSharedPreferences(this). getString("theme_setting",String.valueOf(GameUtil.TEMA_VOLCANES))); switch(this.sceneCode){ /* case GameUtil.TEMA_DESIERTO: setTheme(R.style.Desert_DamGame); break;*/ case GameUtil.TEMA_SELVA: setTheme(R.style.Volcano_DamGame); break; default: setTheme(R.style.Volcano_DamGame); break; } } }
Python
UTF-8
1,704
3.203125
3
[]
no_license
size=input("Enter Number of Processes") quantum=input("Enter Time Quantum : ") time=0 burst_time=[0]*size remaining_burst_time=[0]*size arrival_time=[0]*size process_id=[0]*size waiting_time=[0]*size turnaround_time=[0]*size for i in range(size): print " " process_id[i]=input("Enter Process_Id") arrival_time[i]=input("Enter Arrival_Time") burst_time[i]=input("Enter Burst_Time") for i in range(size): for j in range(size-1): if arrival_time[j]>arrival_time[j+1]: arrival_time[j],arrival_time[j+1]=arrival_time[j+1],arrival_time[j] process_id[j],process_id[j+1]=process_id[j+1],process_id[j] burst_time[j],burst_time[j+1]=burst_time[j+1],burst_time[j] for i in range(size): remaining_burst_time[i]=burst_time[i] k=1 while k>0: l=0 for i in range(size): if remaining_burst_time[i]>0: l=1 if remaining_burst_time[i]>quantum: time+=quantum remaining_burst_time[i]-=quantum elif remaining_burst_time[i]<=quantum: time+=remaining_burst_time[i] waiting_time[i]=time-burst_time[i] remaining_burst_time[i]=0 if l==0: break for i in range(size): turnaround_time[i]=burst_time[i]+waiting_time[i] print " " print "Process_Id Arrival_Time Burst_Time Turnaround_Time Waiting_Time" print " " for i in range(size); print " ",process_id[i]," ",arrival_time[i]," ",burst_time[i]," ",turnaround_time[i]," ",waiting_time[i] total=0 for i in range(size): total+=turnaround_time[i] average=float(total)/float(size) print "Average Turnaround_Time = ",average
Java
UTF-8
8,315
2.140625
2
[]
no_license
package com.example.patrick.outfitplanner; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageButton; import java.util.ArrayList; public class SavedCloset extends AppCompatActivity { String msg = "Saved Closet : "; ArrayList<Clothes> savedList = new ArrayList<>(); ImageButton backButton; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.savedcloset_activity); Bundle bundle = getIntent().getExtras(); if (bundle != null) { } loadList(this); backButton = (ImageButton)findViewById(R.id.backbutton); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in = new Intent(SavedCloset.this, MainActivity.class); in.putExtra("type", "SAVED"); in.putExtra("list", savedList); startActivity(in); } }); GridView gridview = (GridView) findViewById(R.id.savedgrid); gridview.setAdapter(new ImageAdapter(this, savedList, 200)); gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id){ // Send intent to SingleViewActivity Intent in = new Intent(SavedCloset.this, EditSavedCloset.class); // Pass image index //Log.d(String.valueOf(position), "The onStart() event"); int index = position % 8; ArrayList<Clothes> clothesList = new ArrayList<>(); switch (index) { case 0: for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; case 1: position = position - 1; for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; case 2: position = position - 2; for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; case 3: position = position - 3; for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; case 4: position = position - 4; for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; case 5: position = position - 5; for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; case 6: position = position - 6; for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; case 7: position = position - 7; for (int i = 0; i < 8; ++i) { clothesList.add(savedList.get(position + i)); } break; default: break; } in.putExtra("id", position/8); in.putExtra("list", clothesList); startActivity(in); } }); //Log.d(msg, "The onCreate() event"); } /** Called when the activity is about to become visible. */ @Override protected void onStart() { super.onStart(); //Log.d(msg, "The onStart() event"); } /** Called when the activity has become visible. */ @Override protected void onResume() { super.onResume(); //Log.d(msg, "The onResume() event"); } /** Called when another activity is taking focus. */ @Override protected void onPause() { super.onPause(); //Log.d(msg, "The onPause() event"); } /** Called when the activity is no longer visible. */ @Override protected void onStop() { super.onStop(); //Log.d(msg, "The onStop() event"); } /** Called just before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); //Log.d(msg, "The onDestroy() event"); } @Override public void onBackPressed() { Intent in = new Intent(SavedCloset.this, MainActivity.class); in.putExtra("type", "SAVED"); in.putExtra("list", savedList); startActivity(in); } // loads list of saved outfits to be displayed public void loadList(Context mContext) { SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext); int size = mSharedPreference1.getInt("save_size", 0); String imgPath; boolean allowedBool; String itemDesc; String itemType; int[] colorsList = new int[19]; int[] weatherList = new int[6]; int[] formalityList = new int[5]; String type = ""; for (int listID = 0; listID < size; ++listID) { for (int i = 0; i < 8; ++i) { switch (i) { case 0: type = "head"; break; case 1: type = "neck"; break; case 2: type = "shirt"; break; case 3: type = "jacket"; break; case 4: type = "fullbody"; break; case 5: type = "pants"; break; case 6: type = "socks"; break; case 7: type = "shoes"; break; default: break; } imgPath = mSharedPreference1.getString("saved_" + type + "_image" + listID, null); allowedBool = mSharedPreference1.getBoolean("saved_" + type + "_allowed" + listID, false); itemDesc = mSharedPreference1.getString("saved_" + type + "_desc" + listID, null); itemType = mSharedPreference1.getString("saved_" + type + "_type" + listID, null); for (int k = 0; k < 19; ++k) { colorsList[k] = mSharedPreference1.getInt("saved_" + type + "_colors" + listID + "_" + k, 0); } for (int k = 0; k < 6; ++k) { weatherList[k] = mSharedPreference1.getInt("saved_" + type + "_weathers" + listID + "_" + k, 0); } for (int k = 0; k < 5; ++k) { formalityList[k] = mSharedPreference1.getInt("saved_" + type + "_formalities" + listID + "_" + k, 0); } Clothes createdClothes = new Clothes(imgPath, allowedBool, itemDesc, itemType, colorsList, weatherList, formalityList); savedList.add(createdClothes); } } } }
PHP
UTF-8
2,365
2.640625
3
[]
no_license
<?php /** * Customer XML unserializer test * * @since 1.0.0 * * @package Pronamic/WP/Twinfield */ namespace Pronamic\WP\Twinfield\XML\Customers; use PHPUnit\Framework\TestCase; use Pronamic\WP\Twinfield\Customers\Customer; /** * Customer XML unserializer test * * @since 1.0.0 * @package Pronamic/WP/Twinfield * @author Remco Tolsma <info@remcotolsma.nl> */ class CustomerUnserializerTest extends TestCase { /** * Test */ public function test() { $xml = simplexml_load_file( __DIR__ . '/../../../xml/Customers/read-dimensions-deb-response-1.xml' ); $unserializer = new CustomerUnserializer(); $response = $unserializer->unserialize( $xml ); $expected = new Customer(); $expected->set_office( '123456' ); $expected->set_code( '1002' ); $expected->set_name( 'Remco Tolsma' ); $expected->set_shortname( '' ); $financials = $expected->get_financials(); $financials->set_due_days( '30' ); $financials->set_ebilling( false ); $financials->set_ebillmail( '' ); $address = $expected->new_address(); $address->set_id( '1' ); $address->set_type( 'invoice' ); $address->set_default( true ); $address->set_name( 'Remco Tolsma' ); $address->set_country( 'NL' ); $address->set_city( 'Drachten' ); $address->set_postcode( '9203 KA' ); $address->set_telephone( '+31 (0)516 481 200' ); $address->set_telefax( '+31 (0)516 481 999' ); $address->set_email( 'remco@pronamic.nl' ); $address->set_contact( '' ); $address->set_field_1( 'Remco Tolsma' ); $address->set_field_2( 'Merkebuorren39a' ); $address->set_field_3( '' ); $address->set_field_4( '' ); $address->set_field_5( '' ); $address->set_field_6( '' ); $address = $expected->new_address(); $address->set_id( '2' ); $address->set_type( 'postal' ); $address->set_default( false ); $address->set_name( 'Remco Tolsma' ); $address->set_country( 'NL' ); $address->set_city( 'Drachten' ); $address->set_postcode( '9203 KA' ); $address->set_telephone( '+31 (0)516 481 200' ); $address->set_telefax( '+31 (0)516 481 999' ); $address->set_email( 'remco@pronamic.nl' ); $address->set_contact( '' ); $address->set_field_1( '' ); $address->set_field_2( 'Merkebuorren39a' ); $address->set_field_3( '' ); $address->set_field_4( '' ); $address->set_field_5( '' ); $address->set_field_6( '' ); $this->assertEquals( $expected, $response->get_customer() ); } }
C++
UTF-8
4,765
3.640625
4
[]
no_license
/*********************************************************************************************** ** Program Name: Project1 (Langton Ant) ** Author: Jeremy Einhorn ** Date: July 7, 2017 ** Description: This is the main file. The menu first pops up. If the user hits 1, the Langton Ant begins. The menu will pop up at the end to see if they want to play again or Quit. *************************************************************************************************/ #include "menu.hpp" #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int choice = menu(); //if the user wants to play. //they can also play again at the end of the game while (choice == 1) { //int variables to hold the user entered row size //column size, the x coord of the ant and //the y coord of the ant. The accum variable //keeps track of what step the ant is on int row, col, step, rsize, csize, accum = 0; cout << "First, please enter a positive integer from 2 to 80" " for the row size." << endl; //checks for positive integer rsize = getUnsignedInt(); //user has to enter at least 2 rows and at most //80 rows while (!(isRange(rsize, 80, 2))) { cout << "Error. Out of range." << endl; cout << "Please enter a positive integer from 2 to 80." << endl; rsize = getUnsignedInt(); } cout << "Next, please enter a positive integer from 2 to 80" " for the colmun size." << endl; //checks for positive integer csize = getUnsignedInt(); //the user has to enter at least 2 columns and at most //80 columns while (!(isRange(csize, 80, 2))) { cout << "Error. Out of range." << endl; cout << "Please enter a positive integer from 2 to 80." << endl; csize = getUnsignedInt(); } cout << "Please place the ant on the board by first entering it's x-coordinate." " Enter a positive integer from 0 to " << rsize - 1 << "." << endl; //checks for positive integer row = getUnsignedInt(); //user has to enter at least 0 and at most //1 less than the row size while (!(isRange(row, rsize - 1, 0))) { cout << "Error. Out of range." << endl; cout << "Please enter a positive integer from 0 to " << rsize - 1; cout << "." << endl; row = getUnsignedInt(); } cout << "Now please enter it's y-coordinate. Enter a positive integer from 0" " to " << csize - 1 << "." << endl; //checks for positive integer col = getUnsignedInt(); //user has to enter at least 0 and at most //1 less than the column size while (!(isRange(col, csize - 1, 0))) { cout << "Error. Out of range." << endl; cout << "Please enter a positive integer from 0 to " << csize - 1; cout << "." << endl; col = getUnsignedInt(); } cout << "Please enter a positive integer form 0 to 200 for the steps" " the ant will take." << endl; //checks for positive integer step = getUnsignedInt(); //user has to enter at least 1 step and at most //200 steps while (!(isRange(step, 200, 1))) { cout << "Error. Out of range." << endl; cout << "Please enter a positive integer from 1 to 200." << endl; step = getUnsignedInt(); } //dynamic allocation of a 2D array using the user entered //row size and column size char **arry = new char*[rsize]; for (int row = 0; row < rsize; row++) arry[row] = new char[csize]; //new Board and Ant objects using the 2D array, //the row and column size and //the ants first coords Board *board = new Board(arry, rsize, csize); Ant ant(board, row, col); //keeps going until the last step is reached while (accum < step) { accum += 1; //int variables to hold the ants coords before it moves int arow = ant.getRow(); int acol = ant.getCol(); //uses the coords to move the ant ant.moveAnt(arow, acol); //prints a board with an ant on it printToScreen(board, ant); //int variables hold the ants updates coords //these will be used to let the user know where //exactly the ant is int newRow = ant.getRow(); int newCol = ant.getCol(); cout << "This is step " << accum << "." << endl; cout << "The ant is at position " << newRow << ", " << newCol << endl; cout << "Please hit enter for the next step." << endl; //user must hit enter to move onto the next step cin.get(); } //frees the space used for the dynamically allocated 2D array for (int row = 0; row < rsize; row++) delete[] arry[row]; delete[] arry; //the menu pops back up where the user can play again or quit choice = menu(); } //if the user hits Quit on the menu, program terminates if (choice == 2) return 0; }
JavaScript
UTF-8
402
3.734375
4
[]
no_license
/** * @param {Function} fn * @return {Function} */ var once = function(fn) { var visited = false; return function(...args){ if(!visited){ visited = true; return fn(...args); }else{ return undefined; } } }; let fn = (a,b,c) => (a + b + c) let onceFn = once(fn) onceFn(1,2,3); // 6 onceFn(2,3,6); // returns undefined without calling fn
Shell
UTF-8
3,878
3.609375
4
[]
no_license
src="library.txt" #ACCESNO/BOOKNAME/AUTHNAME/SUBJECT/PUBLICATION/NOCOPIES/YEARPUB echo -e "\tMENU" echo -e "1.Enter new books" echo -e "2.Update subject of a book" echo -e "3.List all books of some publication" echo -e "4.Sort by Subject-Author Name-Publisher" echo -e "5.Delete a book" echo -e "6.Number of copies of a book" echo -e "7.Sort by Publisher and number of books by the Publisher" echo -e "8.Publisher with highest number of books" echo -e "9.Exit" read -p "Enter choice:- " ch case $ch in '1') echo "ACCESNO/BOOKNAME/AUTHNAME/SUBJECT/PUBLICATION/NOCOPIES/YEARPUB"|cat>>$src while true do read -p "Enter Book Access Number:- " no read -p "Enter Book Name :- " name read -p "Enter Author Name :- " aname read -p "Enter Subject :- " sub read -p "Enter Publisher :- " pub read -p "Enter Number of Copies :- " nocop read -p "Enter Year of Publication :- " ypub echo "$no/$name/$aname/$sub/$pub/$nocop/$ypub"|cat>>$src read -p "Do you want to enter more?(Y/y) " c if [ $c != 'y' ] then if [ $c != 'Y' ] then break fi fi done ;; '2') read -p "Enter Book Access Number to update subject:- " acno read -p "Enter Subject :- " ssub while read t do no=`echo "$t"|cut -d'/' -f'1'` name=`echo "$t"|cut -d'/' -f'2'` aname=`echo "$t"|cut -d'/' -f'3'` sub=`echo "$t"|cut -d'/' -f'4'` pub=`echo "$t"|cut -d'/' -f'5'` nocop=`echo "$t"|cut -d'/' -f'6'` ypub=`echo "$t"|cut -d'/' -f'7'` if [ $no == $acno ] then echo "$no/$name/$aname/$ssub/$pub/$nocop/$ypub"|cat>>temp.txt else echo "$no/$name/$aname/$sub/$pub/$nocop/$ypub"|cat>>temp.txt fi done<$src mv temp.txt $src ;; '3') read -p "Enter Publication :- " publi while read t do no=`echo "$t"|cut -d'/' -f'1'` name=`echo "$t"|cut -d'/' -f'2'` aname=`echo "$t"|cut -d'/' -f'3'` sub=`echo "$t"|cut -d'/' -f'4'` pub=`echo "$t"|cut -d'/' -f'5'` nocop=`echo "$t"|cut -d'/' -f'6'` ypub=`echo "$t"|cut -d'/' -f'7'` if [ $pub == $publi ] then echo "Book Name :- $name" echo "By :- $aname" echo "On :- $sub" echo "Number of Copies Available :- $nocop" echo "Published in the Year :- $ypub" fi done<$src ;; '4') sort -t"/" -k 4 -k 3 -k 5 $src -o temp1.txt echo -v"/" | cat temp1.txt rm temp1.txt ;; '5') read -p "Enter Book Access Number to delete :- " acno while read t do no=`echo "$t"|cut -d'/' -f'1'` name=`echo "$t"|cut -d'/' -f'2'` aname=`echo "$t"|cut -d'/' -f'3'` sub=`echo "$t"|cut -d'/' -f'4'` pub=`echo "$t"|cut -d'/' -f'5'` nocop=`echo "$t"|cut -d'/' -f'6'` ypub=`echo "$t"|cut -d'/' -f'7'` if [ $no != $acno ] then echo "$no/$name/$aname/$sub/$pub/$nocop/$ypub"|cat>>temp2.txt fi done<$src mv temp2.txt $src ;; '6') read -p "Enter Book Name :- " bname read -p "Enter Author Name :- " athname while read t do no=`echo "$t"|cut -d'/' -f'1'` name=`echo "$t"|cut -d'/' -f'2'` aname=`echo "$t"|cut -d'/' -f'3'` sub=`echo "$t"|cut -d'/' -f'4'` pub=`echo "$t"|cut -d'/' -f'5'` nocop=`echo "$t"|cut -d'/' -f'6'` ypub=`echo "$t"|cut -d'/' -f'7'` if [ $name == $bname -a $aname == $athname ] then echo "Number of Copies Available :- $nocop" fi done<$src ;; '7') sort -t"/" -k 5 $src -o temp1.txt echo -v"/" | cat temp1.txt rm temp1.txt sort -t"/" -k 5 $src | cut -d"/" -f 5 | uniq -c ;; '8') sort -t"/" -k 5 $src | cut -d"/" -f 5 | uniq -c | cat>>temp.txt sort -k 1 temp.txt | tail -n 1 | cat>>t.txt cat t.txt rm temp.txt rm t.txt ;; '9') exit ;; *) ;; esac
JavaScript
UTF-8
1,197
2.5625
3
[ "Apache-2.0" ]
permissive
var marked = require('marked'), frontMatter = require('front-matter'), renderer = new marked.Renderer(), originalCodeRenderer = renderer.code, heading = require('./heading'), hr = require('./hr'), getImages = require('./image'), renderTemplates = require('./injectTemplate'); module.exports = renderer; //add anchors to headlines //renderer.heading = heading; renderer.hr = hr; //if code field is marked as a styled yaml code, then parse content and output templated html instead of standard code text. renderer.code = function (code, language) { var fm, data; if (language == 'styledYaml') { fm = frontMatter('---\n' + code + '\n---'); data = fm.attributes; var html = ''; html += renderTemplates(data); html += getImages(data); return html; } if (language == 'highlight') { var parsedCode = require('highlight.js').highlightAuto(code).value; return '<pre><code class="highlightedCode">' + parsedCode + '</code></pre>'; } //if not styled yaml code field then return the result of the normal code renderer. return originalCodeRenderer.call(renderer, code, language); };
Java
UTF-8
1,679
2.578125
3
[]
no_license
package com.profe.Profe.dao; import com.profe.Profe.model.Lesson; import com.profe.Profe.model.Student; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; import java.util.UUID; @Repository public class LessonDataAccessService { JdbcTemplate jdbcTemplate; public List<Lesson> selectAllLessons(){ String sql = "SELECT * FROM lesson"; return jdbcTemplate.query(sql,mapLessonsFromDb()); } public List<Lesson> selectLessonByTeacherId(UUID teacherId){ String sql = ""; return jdbcTemplate.query(sql,mapLessonsFromDb()); } public RowMapper<Lesson> mapLessonsFromDb(){ return (resultSet, i) -> { String lessonIdStr = resultSet.getString("lesson_id"); UUID lessonId = UUID.fromString(lessonIdStr); String teacherIdStr = resultSet.getString("teacher_id"); UUID teacherId = UUID.fromString(teacherIdStr); String lessonCostStr = resultSet.getString("lesson_cost"); String durationStr = resultSet.getString("duration"); String name = resultSet.getString("name"); String description = resultSet.getString("description"); try{ Integer lessonCost = Integer.valueOf(lessonCostStr); Integer duration = Integer.valueOf(durationStr); return new Lesson(lessonId,teacherId,lessonCost,duration,name,description); } catch (Exception e) { e.printStackTrace(); return null; } }; } }
Java
UTF-8
1,378
4.3125
4
[]
no_license
package arithmaticoperator; import java.util.Scanner; /** * Date-03/08/2019 * * @author SANJAY * * Some Of The Arithmetic Operator Are (+,-,*,/,%) * */ public class Example { int a, b, c; public void input() { Scanner input = new Scanner(System.in); System.out.println("Enter The Number"); a = input.nextInt(); b = input.nextInt(); } /** * Addition (+) */ public void add() { c = a + b; System.out.println("Addition Of Two Number=" + c); } /** * Subtraction (-) */ public void sub() { c = a - b; System.out.println("Subtraction Of Two Number Is=" + c); } /** * Multiplication */ public void mul() { c = a * b; System.out.println("Multiplication Of Two Number " + c); } /** * Division */ public void div() { c = a / b; System.out.println("Division of Two Number Is=" + c); } /** * Reminder */ public void rem() { c = a % b; System.out.println("Reminder Of Two Number=" + c); } /** * Doubt-How Can I Print All The Methods Value in Single Method like display() * * * */ public void display() { System.out.println(c); } public static void main(String[] args) { Example ob = new Example(); ob.input(); ob.add(); ob.sub(); ob.mul(); ob.div(); ob.rem(); ob.display(); } }
C++
UTF-8
1,163
3.203125
3
[]
no_license
// Warning: Change mod and N according to the question inline int add(int x, int y, int mod = ::mod) { x += y; if (x >= mod or x < 0) x %= mod; if (x >= 0) return x; return x + mod; } inline int mul(int x, int y, int mod = ::mod) { if (x >= mod or x + mod < 0) x %= mod; if (y >= mod or y + mod < 0) y %= mod; x *= y; if (x >= mod or x + mod < 0) x %= mod; if (x >= 0) return x; return x + mod; } inline int sub(int x, int y, int mod = ::mod) { x -= y; if (x + mod < 0 or x >= mod) { x %= mod; } if (x >= 0) return x; return x + mod; } int po(int x, int n, int mod = ::mod) { int res = 1; for (;n > 0;) { if (n & 1) { res = mul(res, x, mod); } x = mul(x, x, mod); n /= 2; } return res; } int fact[N], invFact[N]; void pre(){ fact[0] = invFact[0] = invFact[1] = 1; for(int i = 1 ; i < N ; i++) { fact[i] = mul(fact[i-1], i); } for(int i = 2 ; i < N ; i++) { invFact[i] = mul((mod - mod / i), invFact[mod % i]); } for(int i = 1; i < N ; i++) { invFact[i] = mul(invFact[i-1], invFact[i]); } } int ncr(int n, int r){ return mul(mul(fact[n], invFact[r]), invFact[n-r]); }
Markdown
UTF-8
9,147
3.359375
3
[]
no_license
# Your solution to E28 Performance analysis, comparing all four designs you have implemented instead of Design 1 with Design 5 as the book says. To do this evaluation (of E26, E28-E30), for each design create random instances and then call each method many thousands of times, and then find the elapsed time in milliseconds for the fixed number of iterations. Make sure that your program runs each time for about 10 seconds, so you get a good measure of performance. Test each method separately. Run each version several times to ensure that your results are consistent and use the median result as your definitive result, plus give the maximum and minimum. | Design | How cartesian coordinates are computed | How polar coordinates are computed | | --- | --- | --- | | Design 2: Store polar coordinates only | Computed on demand, but not stored| Simply returned | | Design 3: Store cartesian coordinates only | Simply returned | Computed on demand, but not stored | | Design 4: Store both types of coordinates, using four instance variables| Simply returned | Simply returned | | Design 5: Abstract class with designs 2 and 3 as subclasses Depends on the concrete class used | Depends on the concrete class used | performance test code are in the folders of each design. Design 2: Number of iterations: 100 Each method is called 300,000 times Test Program Runtime: 11.967s | Method | Average Runtime (ms) | Median Runtime (ms) | Maximum Runtime (ms) | Minimum Runtime (ms) |--------------------------------|---------------------------|--------------------------|----------------------------|--------------------------- |getX | 3.14 | 0 | 11 | 0 |getY | 3.99 | 0 | 16 | 0 |getRho | 0.06 | 0 | 4 | 0 |getTheta | 0.05 | 0 | 4 | 0 |convertStorageToPolar | 0.11 | 0 | 9 | 0 |convertStorageToCartesian | 7.15 | 0 | 25 | 0 |getDistance | 14.17 | 0 | 51 | 0 |rotatePoint | 90.94 | 70 | 110 | 83 Design 3: Number of iterations: 100 Each method is called 300,000 times Test Program Runtime: 8.591s | Method | Average Runtime (ms) | Median Runtime (ms) | Maximum Runtime (ms) | Minimum Runtime (ms) |--------------------------------|---------------------------|--------------------------|----------------------------|--------------------------- |getX | 0.04 | 0 | 4 | 0 |getY | 0.05 | 0 | 4 | 0 |getRho | 0.05 | 0 | 4 | 0 |getTheta | 23.11 | 20 | 30 | 19 |convertStorageToPolar | 23.3 | 20 | 32 | 19 |convertStorageToCartesian | 0.11 | 0 | 8 | 0 |getDistance | 0.06 | 0 | 5 | 0 |rotatePoint | 39.13 | 38 | 85 | 38 Design 4: Number of iterations: 100 Each method is called 30,000 times Test Program Runtime: 9.879s | Method | Average Runtime (ms) | Median Runtime (ms) | Maximum Runtime (ms) | Minimum Runtime (ms) |--------------------------------|---------------------------|--------------------------|----------------------------|--------------------------- |getX | 0.03 | 0 | 3 | 0 |getY | 0.02 | 0 | 2 | 0 |getRho | 0.03 | 0 | 3 | 0 |getTheta | 0.05 | 0 | 4 | 0 |convertStorageToPolar | 5.17 | 1 | 26 | 0 |convertStorageToCartesian | 23.33 | 20 | 29 | 19 |getDistance | 0.05 | 0 | 4 | 0 |rotatePoint | 70.01 | 71 | 89 | 62 Design 5: Number of iterations: 100 Each method is called 30,000 times Test Program Runtime: 9.482s | Method | Average Runtime (ms) | Median Runtime (ms) | Maximum Runtime (ms) | Minimum Runtime (ms) |--------------------------------|---------------------------|--------------------------|----------------------------|--------------------------- |getX | 0.12 | 0 | 7 | 0 |getY | 0.15 | 0 | 7 | 0 |getRho | 0.31 | 0 | 7 | 0 |getTheta | 13.75 | 12 | 30 | 0 |convertStorageToPolar | 13.94 | 13 | 32 | 0 |convertStorageToCartesian | 0.46 | 0 | 19 | 0 |getDistance | 0.52 | 0 | 21 | 0 |rotatePoint | 65.5 | 79 | 113 | 39 | Method / Average Runtime (ms) | Design2 | Design3 | Design4 | Design5 |--------------------------------------|-----------|----------|-----------|---------- | getX | 3.14 | 0.04 | 0.03 | 0.12 | getY | 3.99 | 0.05 | 0.02 | 0.15 | getRho | 0.06 | 0.05 | 0.03 | 0.31 | getTheta | 0.05 | 23.11 | 0.05 |13.75 | convertStorageToPolar | 0.11 | 23.3 | 5.17 | 13.94 | convertStorageToCartesian | 7.15 | 0.11 | 23.33 | 0.46 | getDistance | 14.17 | 0.06 | 0.05 | 0.52 | ratotePoint | 90.94 | 39.13 | 70.01 | 65.6 From the data above, we can find that methods getX, getY, getDistance and rotatePoint always need more time in design2; methods getTheta and convertStorageToPolar always need more time in design3; and method convertStorageToCartesian always need more time in design4. Thus, design2 is probably less efficient than others. Since running time of most methods in design2 needs more time. What's more, the running time of each method in design5 is always between the running time of each method in design2 and design3. Thus, design5 is more efficient. The average running time of each method in design5 is not very high.
Markdown
UTF-8
1,561
2.734375
3
[]
no_license
This is repository for the Assignment 15 given by my respected teacher. This Assignment is solely made by me Everyday I work on this assignment and each day I am getting closer to complete this assignment. It helps me clearing my operating system conecpts in more advaced. I have not learn concept of os this deep. Question15: A page-replacement algorithm should minimize the number of page faults. We can do this minimization by distributing heavily used pages evenly over all of memory, rather than having them compete for a small number of page frames. We can associate with each page frame a counter of the number of pages that are associated with that frame. Then, to replace a page, we search for the page frame with the smallest counter. a. Write a page-replacement program using this basic idea. Specifically address the problems of (1) what the initial value of the counters is: Ans- (2) when counters are increased, (3) when counters are decreased, and (4) how the page to be replaced is selected. b. How many page faults occur for your algorithm for the following reference string, for four page frames( take page frame size from user, Mention details might be use for testing) ? 1, 2, 3, 4, 5, 3, 4, 1, 6, 7, 8, 7, 8, 9, 7, 8, 9, 5, 4, 5, 4, 2. c. What is the minimum number of page faults for an optimal page- replacement strategy for the reference string in part b with four page frames( result should be dependent upon frame entered by user as described in part b)? Solution are uploaded in ums and also in this repository inside report
C#
UTF-8
1,394
3.34375
3
[]
no_license
using System; namespace school_db { class DateGenerator { int year; public DateGenerator(int year) { this.year = year; } private int getRandomStudentYear() { //return random year within 4 years of year Random rand = new Random(); return year + rand.Next(0,4); } private int getRandomTeacherYear() { //return random year within 4 years of year Random rand = new Random(); return year + rand.Next(0,10); } public void setYear(int year) { this.year = year; } public string getRandomDate(string type) { Random rand = new Random(); string year; if (type == "student") { year = getRandomStudentYear().ToString(); }else { year = getRandomTeacherYear().ToString(); } string month = rand.Next(1,13).ToString("D2"); string day; switch (Int32.Parse(month)) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = rand.Next(1,32).ToString("D2"); break; case 4: case 6: case 9: case 11: day = rand.Next(1,31).ToString("D2"); break; default: day = rand.Next(1,29).ToString("D2"); break; } return $"{year}-{month}-{day}"; } // end randomDate }// end class }
JavaScript
UTF-8
2,173
2.859375
3
[]
no_license
import { useEffect, useState } from "react"; import { Button, Typography, Box, Card, TextField, CardContent, } from "@material-ui/core"; // import './App.css'; import { api } from "./data"; import { validateInput } from "./utlis/validators"; function App() { const [cards, setCards] = useState([]); const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); useEffect(() => { api.get("/cards").then(({ data }) => setCards(data)); }, []); const addCard = async (event) => { event.preventDefault(); try { const { data } = await api.post("/cards", { title, description }); setTitle(""); setDescription(""); const cardsClone = [...cards]; cardsClone.push({ title: data.title, description: data.description, id: data.id, }); setCards(cardsClone); } catch (err) { console.log("oops:", err); } }; const handleTextChange = (event, setter) => { // run the input through the validator function const textInput = event.target.value; if (validateInput(textInput)) { setter(event.target.value); } else { alert("That is a naught word!"); } }; return ( <div> <Typography>Trello Clone</Typography> {cards.map(({ title, description, id }) => ( <Box key={id}> <Card varient="outlined"> <CardContent> <Typography>Title: {title}</Typography> <Typography>Description: {description}</Typography> </CardContent> </Card> </Box> ))} <form onSubmit={addCard}> <TextField required onChange={(e) => handleTextChange(e, setTitle)} value={title} id="standard-basic" label="Title" /> <TextField required onChange={(e) => handleTextChange(e, setDescription)} value={description} id="standard-basic" label="Description" /> <Button type="submit" varient="outlined"> Add Card </Button> </form> </div> ); } export default App;
Markdown
UTF-8
6,737
2.5625
3
[ "MIT" ]
permissive
--- layout: post title: "Google Summer of Code | Coding Period | Week 4" visible: true --- ![systers logo with gsoc logo](https://user-images.githubusercontent.com/11148726/52602344-2b4e5900-2e5a-11e9-8bc7-66e30120a3db.png) This week — June 4 to June 10— was the fourth week of the coding period of [Google Summer of Code (GSoC)](https://summerofcode.withgoogle.com/) with [Systers Open Source](https://github.com/systers). If you want to know more about this you can read the [introduction to my journey](https://medium.com/isabel-costa-gsoc/intro-to-google-summer-of-code-with-systers-open-source-dbdaa92bd189) , [my latest weekly blog posts](https://medium.com/isabel-costa-gsoc) or [my weekly status report](https://github.com/systers/mentorship-backend/wiki/GSoC-2018-Isabel-Costa#weekly-status-report-for-week-4) for this week. This week I dedicated a lot of my time preparing for my thesis presentation, on June 7th. So I had to manage better my time to produce work for GSoC and still have a good preparation for my thesis. Now that I presented the thesis I can dedicate much more time for GSoC. ## Time and work management Even with an intense thesis preparation I still managed to submit some PRs for small tasks, mostly bugs, at the beginning of this week. I understand that it is very important to be present and reachable when working remote. So I responded to all code reviews within 24 hours and stayed active on Slack, communicating with the community and my mentors. Also, it is important to keep the community informed of my workload, so I made sure to keep the [Google Calendar](https://calendar.google.com/) for my project updated with my limited availability and other commitments (related to my thesis). An interesting thing I noticed this week is how the scrum check-ins help me keep accountable. Scrum check-ins are short messages we, GSoC students, have to post on [Slack](https://slack.com/) every Monday, Wednesday, and Friday of each week at 5 pm GMT+1 timezone. This helps me show that although I might be working more on the thesis, I’m still responsive and doing GSoC related work. One thing that helps me deliver these check-ins in time is to start writing or at least preparing the template for the next check-in, after the latest check-in, instead of doing this very near to the deadline. I attended the project weekly meeting and discussed the mentorship relation feature. Since the First Coding Phase ends this week, I wanted to optimize the time to finish or at least start working on the most important feature of the Mentorship System, the mentorship relations. So I suggested to my mentors that we could re-prioritized the issues planned for this phase, giving priority to mentorship relation feature. After this re-prioritization, we reviewed the mentorship relation feature, the first fields I could work with and the APIs I could start developing. ## Completed tasks One thing I really like to do is to organize issues, create them, adding labels and descriptive descriptions. This week I created more issues and broke some features into smaller issues, to keep the pull requests very focused on one small task and keep all organized. Here’s a summary of this week’s completed action items: - I solved bugs found the week before and responded to code review change requests — PRs [#33](https://github.com/systers/mentorship-backend/pull/33), [#34](https://github.com/systers/mentorship-backend/pull/34), [#35](https://github.com/systers/mentorship-backend/pull/35); - I developed the Mentorship Relation database model, which will serve as the base for the APIs regarding the mentorship relation feature. The APIs include sending a mentorship request, accepting or rejecting a mentorship relation, and canceling a request — [PR #41](https://github.com/systers/mentorship-backend/pull/41); - Created tests for app configurations — [PR #37](https://github.com/systers/mentorship-backend/issues/37); - I changed the Login API response to return the expiry UNIX timestamp along with the access token —[PR #44](https://github.com/systers/mentorship-backend/pull/44); - Created a function to validate the email regex — [PR#45](https://github.com/systers/mentorship-backend/pull/45). ## Presenting my work This week the GSoC Happy Hour focused on showing off students’ work. GSoC Happy Hour is about spending some time getting to know fellow GSoC students and mentors. The latest ones have been focused on playing games together. This time, I got to demo the backend API I’ve been developing these last 4 weeks, and use the [Swagger UI](https://swagger.io/tools/swagger-ui/) to present the API functionalities. This was the first time I’ve demo this to someone (besides my mentors), and it was slightly intimidating but a good thing since other could see my work. I got to see other students work, as well, which helped me broaden my view of what others are doing and have an overview of what technologies are being used for the other projects. ## Shout-outs for blog posts I spent an afternoon searching for a way to define the data model. The challenge of this was that Mentorship Relation is a relation between 2 instances of the same User data model. I researched about what type of relationship this would be (e.g.: many to many or one to many). To develop the Mentorship Relation database model I followed this blog post, [A SQLAlchemy Cheat Sheet](https://www.codementor.io/sheena/understanding-sqlalchemy-cheat-sheet-du107lawl) by [Sheena](https://www.codementor.io/sheena). The section that saved my day was “Multiple relationships with the same table”. Another blog post that really helped me was [“Advanced configuration of Flask-JWT”](http://blog.tecladocode.com/learn-python-advanced-configuration-of-flask-jwt/) by [Jose Salvatierra](https://twitter.com/tecladocode). This helped me with getting the expiry UNIX timestamp for a [JWT](https://jwt.io/) access token, using the [flask-jwt](https://pythonhosted.org/Flask-JWT/) extension. What also helped me was looking at the [source code of this extension](https://github.com/mattupstate/flask-jwt/blob/master/flask_jwt/__init__.py). I wanted the expiry token to be sent along with the access token in the Login API response, thereby solving [issue #39](https://github.com/systers/mentorship-backend/issues/39). ## Plans for next week - I already started working on the email verification feature while waiting for the mentorship relation data model PR to be merged. - When this PR is merged, I’ll start working on the Mentorship Relation feature API. I plan to finish this API next week and do a demo in the Community Open Session, to present to the community the progress of the backend API.
Java
UTF-8
3,387
2.90625
3
[]
no_license
package com.thoughtworks.contraman; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static java.util.Arrays.stream; class Timetable { private final List<Track> tracks = new LinkedList<>(); private final TalkConsumer talks; private final TimeConstraints timeConstraints; private final TimeReserverFinder timeReserverFinder; public Timetable(TimeConstraints timeConstraints, Talks talksToFit) { this.timeConstraints = timeConstraints; this.talks = new TalkConsumer(talksToFit.longestFirst()); this.timeReserverFinder = new CompositeTimeReserverFinder( new SessionTimeReserver(talks), new NetworkingTimeReserver(), new LunchTimeReserver()); buildNewTrack(); } private void buildNewTrack() { addTrack(); if (talks.hasMoreToConsume()) { buildNewTrack(); } } private void addTrack() { Track track = new Track(timeConstraints, timeReserverFinder); tracks.add(track); } public Collection<Event> events(int trackNo) { return tracks.get(trackNo).events(); } public int trackCount() { return tracks.size(); } private class CompositeTimeReserverFinder implements TimeReserverFinder { private final TimeReserver[] timeReservers; public CompositeTimeReserverFinder(TimeReserver... timeReservers) { this.timeReservers = timeReservers; } @Override public TimeReserver findFor(Timeslot timeslot) { Optional<TimeReserver> timeReserver = stream(timeReservers) .filter(reserver -> reserver.ofMatchingType(timeslot)) .findAny(); return timeReserver.orElseThrow(() -> new IllegalStateException("Cannot find TimeReserver for timeslot of type " + timeslot.type())); } } private class NetworkingTimeReserver implements TimeReserver { @Override public void reserveTime(Timeslot timeslot) { timeslot.reserve("Networking Event"); } @Override public boolean ofMatchingType(Timeslot timeslot) { return timeslot.type() == EventType.NETWORKING; } } private class LunchTimeReserver implements TimeReserver { @Override public void reserveTime(Timeslot timeslot) { timeslot.reserve("Lunch"); } @Override public boolean ofMatchingType(Timeslot timeslot) { return timeslot.type() == EventType.LUNCH; } } private class SessionTimeReserver implements TimeReserver { private final TalkConsumer talks; public SessionTimeReserver(TalkConsumer talks) { this.talks = talks; } @Override public void reserveTime(Timeslot timeslot) { while ((timeslot.hasGaps() && talks.hasMoreToConsume()) || talks.hasTalkThatFits(timeslot)) { Talk talkThatFits = talks.consumeOneThatFits(timeslot); timeslot.reserve(talkThatFits.title(), talkThatFits.duration()); } } @Override public boolean ofMatchingType(Timeslot timeslot) { return timeslot.type() == EventType.SESSION; } } }
Java
GB18030
10,615
2.15625
2
[]
no_license
package com.epay.aty; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import com.epay.aty.tools.Information; import com.epay.aty.R; import com.tt.accountInfo.AccountInfo; import com.tt.json.JSONArray; import com.tt.json.JSONObject; import com.tt.moneyInfo.CardInfo; import com.tt.toolsUtil.JsonTool; import com.tt.toolsUtil.MD5Tool; import com.tt.userAction.UserAction; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class AtyAddOrDelCard extends Activity { private ListView showcard; private List<String> list; private SharedPreferences preferences; private UserAction ua; private ArrayAdapter<String> adapter; private String cardinformation; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.addordelcard); ActionBar actionbar =getActionBar(); actionbar.setDisplayHomeAsUpEnabled(true); Button addcard=(Button) findViewById(R.id.bn_addcard); showcard=(ListView)findViewById(R.id.lv_readcard); preferences=getSharedPreferences(Information.DatabaseName, MODE_PRIVATE); String phone=preferences.getString(AccountInfo.PHONE,"hello"); int userid=preferences.getInt(AccountInfo.USER_ID, -1); list=new ArrayList<String>(); ua=UserAction.newInstance(); try { ua.get_card_info(AtyAddOrDelCard.this,UserAction.IDENTIFY_NORMAL_USER, userid, MD5Tool.md5(phone), UserAction.ACTION_GET_CARD_INFO, new UserAction.SuccessCallback() { @Override public void onSuccess(String arg0) { // TODO Auto-generated method stub JSONObject jsonobject=new JSONObject(arg0); JSONObject json_result=jsonobject.getJSONObject(JsonTool.JSON_RESULT_CODE); int status=json_result.getInt(JsonTool.STATUS); switch (status) { case CardInfo.STATUS_GET_CARD_INFO_SUCCESS: JSONArray arr=json_result.getJSONArray(JsonTool.JSON_CARD_INFO_ARRAY); for(int i=0;i<arr.length();i++){ JSONObject temp=arr.getJSONObject(i); String bankname=temp.getString(CardInfo.BANK_NAME); String cardnumbertail=temp.getString(CardInfo.CARD_NUMBER_TAIL); String cardinformation=bankname+cardnumbertail; list.add(cardinformation); //***************************пϢҲֻһ********************************** SharedPreferences.Editor editor=preferences.edit(); editor.putString(CardInfo.BANK_NAME, bankname); editor.putString(CardInfo.CARD_NUMBER_TAIL,cardnumbertail); editor.commit(); if(list.isEmpty()){ list.add("ûп"); } adapter=new ArrayAdapter<String>(AtyAddOrDelCard.this, android.R.layout.simple_list_item_1, list); showcard.setAdapter(adapter); adapter.notifyDataSetChanged(); } break; case CardInfo.STATUS_GET_CARD_INFO_FAIL: int reason=json_result.getInt(JsonTool.REASON); if(reason==CardInfo.FAIL_REASON_ACCOUNT_ERROR){ new AlertDialog.Builder(AtyAddOrDelCard.this) .setTitle("ȡп") .setMessage("Բȡʧܣ˺Ŵ") .setPositiveButton("ȷ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub } }).create().show(); }else if(reason==CardInfo.FAIL_REASON_OTHOER){ new AlertDialog.Builder(AtyAddOrDelCard.this) .setTitle("ȡп") .setMessage("Բȡʧܣԭ") .setPositiveButton("ȷ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub } }).create().show(); }else if(reason==CardInfo.FAIL_REASON_NOT_CARDS){ new AlertDialog.Builder(AtyAddOrDelCard.this) .setTitle("ȡп") .setMessage("ûп") .setPositiveButton("ȷ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub } }).create().show(); } break; default: break; } jsonobject = null; json_result = null; } }, new UserAction.FailCallback() { @Override public void onFail(int arg0, int arg1) { // TODO Auto-generated method stub Toast.makeText(AtyAddOrDelCard.this, "Բ𣬶ȡпʧܣ", Toast.LENGTH_SHORT).show(); } }); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } showcard.setOnItemLongClickListener(new CardOnItemLongClickListener()); addcard.setOnClickListener(new AddOnClickListener()); } class CardOnItemLongClickListener implements OnItemLongClickListener{ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { // TODO Auto-generated method stub cardinformation=(String) showcard.getItemAtPosition(position); new AlertDialog.Builder(AtyAddOrDelCard.this) .setTitle("ɾп") .setMessage("ȷɾ") .setNegativeButton("ȡ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub } }) .setPositiveButton("ȷ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub String cardidkey=cardinformation.substring(cardinformation.length()-4, cardinformation.length()); String cardid=preferences.getString(cardidkey, "hello"); int userid=preferences.getInt(AccountInfo.USER_ID, -1); String phone=preferences.getString(AccountInfo.PHONE, "hello"); try { ua.del_card(AtyAddOrDelCard.this,UserAction.IDENTIFY_NORMAL_USER, userid, MD5Tool.md5(phone), Integer.parseInt(cardid), UserAction.ACTION_DEL_CARD, new UserAction.SuccessCallback() { @Override public void onSuccess(String arg0) { // TODO Auto-generated method stub JSONObject jsonobject=new JSONObject(arg0); JSONObject json_result=jsonobject.getJSONObject(JsonTool.JSON_RESULT_CODE); int status=json_result.getInt(JsonTool.STATUS); switch (status) { case CardInfo.STATUS_DEL_CARD_SUCCESS: list.remove(position); adapter.notifyDataSetChanged(); //Ҫдڵǰlistview Toast.makeText(AtyAddOrDelCard.this, "ɾɹ", Toast.LENGTH_SHORT).show(); break; case CardInfo.STATUS_DEL_CARD_FAIL: int reason=json_result.getInt(JsonTool.REASON); if(reason==CardInfo.FAIL_REASON_OTHOER){ new AlertDialog.Builder(AtyAddOrDelCard.this) .setTitle("ɾп") .setMessage("Բɾʧܣԭ") .setPositiveButton("ȷ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub } }).create().show(); }else if(reason==CardInfo.FAIL_REASON_ACCOUNT_ERROR){ new AlertDialog.Builder(AtyAddOrDelCard.this) .setTitle("ɾп") .setMessage("Բɾʧܣ˺") .setPositiveButton("ȷ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub } }).create().show(); }else if(reason==CardInfo.FAIL_REASON_NOT_CARDS){ new AlertDialog.Builder(AtyAddOrDelCard.this) .setTitle("ɾп") .setMessage("Բɾʧܣ޿") .setPositiveButton("ȷ", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog,int which) { // TODO Auto-generated method stub } }).create().show(); } break; default: break; } } }, new UserAction.FailCallback() { @Override public void onFail(int arg0, int arg1) { // TODO Auto-generated method stub Toast.makeText(AtyAddOrDelCard.this, "ɾʧܣ", Toast.LENGTH_SHORT).show(); } }); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).create().show(); return false; } } class AddOnClickListener implements OnClickListener{ @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent=new Intent(AtyAddOrDelCard.this,AtyAddCard.class); startActivity(intent); finish(); intent=null; } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(this, AtyWealth.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } }
Java
UTF-8
1,502
1.757813
2
[]
no_license
/* * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 only, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included at /legal/license.txt). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 or visit www.sun.com if you need additional information or have * any questions. */ package java.lang; /** * Package-private utility class for setting up and tearing down * platform-specific support for termination-triggered shutdowns. * * @author Mark Reinhold * @version 1.3, 00/06/16 * @since 1.3 */ class Terminator { /* Invocations of setup and teardown are already synchronized * on the shutdown lock, so no further synchronization is needed here */ static void setup() { } static void teardown() { } }
C#
UTF-8
2,001
2.703125
3
[ "MIT" ]
permissive
namespace SyncPro.UI.Converters { using System; using System.Globalization; using System.Windows; using System.Windows.Data; [ValueConversion(typeof(string), typeof(bool))] public class StringToBooleanConverter : IValueConverter { public bool ReverseValue { get; set; } public StringToBooleanConverter() { this.ReverseValue = false; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is string) && value != null) { return DependencyProperty.UnsetValue; } string stringValue = (string)value; bool isEmpty = string.IsNullOrEmpty(stringValue); return this.ReverseValue ? isEmpty : !isEmpty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [ValueConversion(typeof(string), typeof(bool))] public class EnumStringToBooleanConverter : IValueConverter { public bool ReverseValue { get; set; } public EnumStringToBooleanConverter() { this.ReverseValue = false; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is string) && value != null) { return DependencyProperty.UnsetValue; } string stringValue = (string)value; bool isMatch = string.Equals(stringValue, parameter); return this.ReverseValue ? !isMatch : isMatch; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null && (bool)value) { return parameter as string; } return null; } } }
PHP
UTF-8
1,785
2.59375
3
[]
no_license
<html> <body> <?php if (isset($_POST['email']) && isset($_POST['pass'])) { $email= $_POST['email']; $pass= md5($_POST['pass']); include("connect.php"); $requete="select * from client where EmailClient = '$email' AND MdpClient = '$pass'"; $result= mysqli_query($link,$requete) or die ("erreur Sql".mysqli_error($link)); $n=mysqli_num_rows($result); echo $n; if($n==1) { $L=mysqli_fetch_array($result, MYSQLI_ASSOC); session_start (); $_SESSION['ID'] = $L['IdClient']; $_SESSION['Email'] = $L['EmailClient']; $_SESSION['Mdp'] = $L['MdpClient']; $_SESSION['Nom'] = $L['NomClient']; $_SESSION['Prenom'] = $L['PrenomClient']; $_SESSION['Adresse'] = $L['AdresseClient']; $_SESSION['ComplementAdresse'] = $L['ComplementAdresseClient']; $_SESSION['Ville'] = $L['VilleClient']; $_SESSION['CP'] = $L['CPClient']; if ( $L['admin'] == 1) { header ('location: index.php'); $_SESSION['admin'] = true; } else { header ('location: page_membre.php'); $_SESSION['admin'] = false; } } else { echo"vous n’êtes pas membre"; } } else { echo 'Les variables du formulaire ne sont pas déclarées.'; } ?> </body> </html>
Python
UTF-8
7,900
3.109375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import re import unittest class taxCalculator(object): items = [] taxedItems = [] salesTaxes = 0.0 total = 0.0 # 'Costants' for the taxes salesTax = 0.1 importationTax = 0.05 def addItem(self, item): self.items.append(item) def clear(self): self.items = [] self.taxedItems = [] self.salesTaxes = 0.0 self.total = 0.0 def calculateTax(self): for item in self.items: taxedItem = self.calculateSingleTax(item) self.taxedItems.append(taxedItem) self.taxedItems.append('Sales Taxes: ' + Helper.numberToString(self.salesTaxes)) self.taxedItems.append('Total: ' + Helper.numberToString(self.total)) def calculateSingleTax(self, item): itemWithoutAt = Helper.replaceAt(item) tax = 0.0 if Helper.mustBeTaxed(itemWithoutAt): tax += self.salesTax if Helper.isImported(itemWithoutAt): tax += self.importationTax return self.taxPrice(itemWithoutAt, tax) def taxPrice(self, item, tax): price = re.findall('\d+.\d+', item) # Convert string into float, execute tax%, save, back to string try: priceFloat = float(price[0]) if Helper.thereIsPromo(self.items) and Helper.isPromo(item) == False: priceFloat *= .9 if Helper.thereIsPromo(self.items) and len(self.items) == 1: priceFloat *= .9 totalTax = priceFloat * tax if Helper.isImported(item): totalTax = Helper.roundToFive(totalTax) self.salesTaxes += totalTax taxedPrice = round(priceFloat + totalTax, 2) self.total += taxedPrice return Helper.arrangeImported(item.replace(price[0], Helper.numberToString(taxedPrice), 1)) except: return item # In case the string is not of the correct format nothing happens class Helper(object): @staticmethod def numberToString(numb): return str("%.2f" % numb) @staticmethod def replaceAt(item): return item.replace(' at ', ': ', 1) @staticmethod def roundToFive(number): twoDecimalPrecision = (number * 100) % 10 if twoDecimalPrecision == 5 or twoDecimalPrecision == 0: return number return number - twoDecimalPrecision / 100 + (0.05 if twoDecimalPrecision < 5 else 0.1) @staticmethod def mustBeTaxed(item): freeTaxRE = 'books?|chocolates?|headache|pills?' return len(re.findall(freeTaxRE, item, flags=re.IGNORECASE)) == 0 @staticmethod def isImported(item): return len(re.findall('imported', item, flags=re.IGNORECASE)) > 0 @staticmethod def arrangeImported(item): number = re.findall('\d+ ', item) imported = re.findall('imported ', item, flags=re.IGNORECASE) try: # from '1 box of imported chocolates at 11.25' to '1 imported box of chocolates: 11.25' if len(number) > 0: return item.replace(imported[0], '', 1).replace(number[0], number[0] + imported[0], 1) return imported[0] + item.replace(imported[0], '', 1) except: return item # In case the string is not properly fomratted @staticmethod def isPromo(item): return len(re.findall('promo', item, flags=re.IGNORECASE)) > 0 @staticmethod def thereIsPromo(items): for item in items: if Helper.isPromo(item): return True return False # @staticmethod # def allpyDiscount(items, promo): # for item in items: # if (item != promo): # number = Helper.findPrice(item) # @staticmethod # def findPrice(item): # return Helper.float(re.findall('\d+.\d+', item)[0]) # UnitTest for the class taxCalculator class taxTest(unittest.TestCase): tax = taxCalculator() def test_addItem_adds_item_to_items(self): self.tax.clear() self.tax.addItem('Hello test') self.assertEqual(len(self.tax.items), 1) def test_calculateTax_slould_move_items_to_taxedItems(self): self.tax.clear() self.tax.addItem('1 chocolate bar at 0.85') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 chocolate bar: 0.85') def text_calculateSingleTax_should_increase_number(self): increasedItem = self.tax.calculateSingleTax('1 music CD at 14.99') self.assertEqual(increasedItem, '1 music CD: 16.49') def test_calculateTax_slould_increment_price(self): self.tax.clear() self.tax.addItem('1 music CD at 14.99') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 music CD: 16.49') def test_calculateTax_should_not_increment_for_books(self): self.tax.clear() self.tax.addItem('1 book at 12.49') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 book: 12.49') def test_imported_items_should_have_more_tax(self): self.tax.clear() self.tax.addItem('1 imported box of chocolates at 10.00') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 imported box of chocolates: 10.50') def test_random_stirng_should_not_raise_error(self): self.tax.clear() self.tax.addItem('foobar foo bar foo') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], 'foobar foo bar foo') def test_taxes_should_be_done_at_once(self): self.tax.clear() self.tax.addItem('1 imported bottle of perfume at 47.50') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 imported bottle of perfume: 54.65') def test_imported_items_should_round_to_the_nearest_5(self): self.tax.clear() self.tax.addItem('1 box of imported chocolates at 11.25') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 imported box of chocolates: 11.85') def test_imported_items_should_move_the_imported_word(self): self.tax.clear() self.tax.addItem('1 box of imported chocolates at 11.25') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 imported box of chocolates: 11.85') def test_Input_1(self): self.tax.clear() self.tax.addItem('1 book at 12.49') self.tax.addItem('1 music CD at 14.99') self.tax.addItem('1 chocolate bar at 0.85') self.tax.calculateTax() results = [] results.append('1 book: 12.49') results.append('1 music CD: 16.49') results.append('1 chocolate bar: 0.85') results.append('Sales Taxes: 1.50') results.append('Total: 29.83') self.assertEqual(self.tax.taxedItems, results) def test_Input_2(self): self.tax.clear() self.tax.addItem('1 imported box of chocolates at 10.00') self.tax.addItem('1 imported bottle of perfume at 47.50') self.tax.calculateTax() results = [] results.append('1 imported box of chocolates: 10.50') results.append('1 imported bottle of perfume: 54.65') results.append('Sales Taxes: 7.65') results.append('Total: 65.15') self.assertEqual(self.tax.taxedItems, results) def test_Input_3(self): self.tax.clear() self.tax.addItem('1 imported bottle of perfume at 27.99') self.tax.addItem('1 bottle of perfume at 18.99') self.tax.addItem('1 packet of headache pills at 9.75') self.tax.addItem('1 box of imported chocolates at 11.25') self.tax.calculateTax() results = [] results.append('1 imported bottle of perfume: 32.19') results.append('1 bottle of perfume: 20.89') results.append('1 packet of headache pills: 9.75') results.append('1 imported box of chocolates: 11.85') results.append('Sales Taxes: 6.70') results.append('Total: 74.68') self.assertEqual(self.tax.taxedItems, results) def test_Promo_Product(self): self.tax.clear() self.tax.addItem('1 promo product at 50.00') self.tax.calculateTax() self.assertEqual(self.tax.taxedItems[0], '1 promo product: 49.50') def test_isPromoTest(self): self.assertEqual(True, Helper.isPromo('1 promo product at 45')) def test_thereIsPromoTest(self): lista = ['1 promo product at 45.00', '1 product at 45.00', '1 product at 45.00'] self.assertEqual(True, Helper.thereIsPromo(lista)) def test_Promo_doppio(self): self.tax.clear() self.tax.addItem('1 promo product at 50.00') self.tax.addItem('1 music CD at 14.99') self.tax.calculateTax() results = [] results.append('1 promo product: 55.00') results.append('1 music CD: 14.84') results.append('Sales Taxes: 6.35') results.append('Total: 69.84') self.assertEqual(self.tax.taxedItems, results) unittest.main()
C++
UHC
1,393
3.265625
3
[]
no_license
//Jennifer Soft - D #include "bits_stdc++.h" #define SIZE 12 using namespace std; // üũϱ 迭 int idx[4] = { 0,0,1,-1 }, idy[4] = { 1,-1,0,0 }; // ġ,ġ ü struct Now { int x, y, cnt; }; int main() { //n = ũ, temp = ġ 迭. int n, temp[SIZE][SIZE] = { 0 }; // char arr[SIZE][SIZE] = { 0 }; scanf("%d", &n); //Է for (int i = 0; i < n; i++) cin >> arr[i]; //迭 ū ʱȭ memset(temp, 0x3f, sizeof temp); //bfs queue <Now> q; //ť ְ ̵ q.push({ n - 1,0,arr[n - 1][0] - '0' }); while (!q.empty()) { int x = q.front().x; int y = q.front().y; int cnt = q.front().cnt; q.pop(); // ġ 쿡 Ž if (cnt < temp[x][y]) { temp[x][y] = cnt; // ġ 4 Ž for (int i = 0; i < 4; i++) { int xx = x + idx[i], yy = y + idy[i]; // ȿ ġ ť if (xx >= 0 && yy >= 0 && xx < n && yy < n) q.push({ xx,yy,cnt + arr[xx][yy] - '0' }); } } } //100 ̻ 100, ƴҰ printf("%d\n", temp[0][n - 1] >= 100 ? 100 : temp[0][n - 1]); return 0; }
PHP
ISO-8859-1
1,533
2.734375
3
[]
no_license
<?php class Application_Model_WebServices_Photos extends Application_Model_WebServices_WebService { // ----- Dfinition des attributs ----- // ----- Dfinition des getters et setters ------ // ----- Dfinition des mthodes ------ public static function getAllPhotos(){ $liste_photos = array(); $liste_photos[1]['_id_photo'] = 1; $liste_photos[1]['_titre'] = 'titre_photo_1'; $liste_photos[1]['_url_photo'] = '/images/url_photo_1'; $liste_photos[1]['_id_annonce'] = 1; $liste_photos[2]['_id_photo'] = 2; $liste_photos[2]['_titre'] = 'titre_photo_2'; $liste_photos[2]['_url_photo'] = '/images/url_photo_2'; $liste_photos[2]['_id_annonce'] = 1; $liste_photos[3]['_id_photo'] = 3; $liste_photos[3]['_titre'] = 'titre_photo_3'; $liste_photos[3]['_url_photo'] = '/images/url_photo_3'; $liste_photos[3]['_id_annonce'] = 1; $liste_photos[4]['_id_photo'] = 4; $liste_photos[4]['_titre'] = 'titre_photo_4'; $liste_photos[4]['_url_photo'] = '/images/url_photo_4'; $liste_photos[4]['_id_annonce'] = 2; $liste_photos[5]['_id_photo'] = 5; $liste_photos[5]['_titre'] = 'titre_photo_5'; $liste_photos[5]['_url_photo'] = '/images/url_photo_5'; $liste_photos[5]['_id_annonce'] = 2; return $liste_photos; } public static function getPhotosByIdAnnonce($id){ $liste = self::getAllPhotos(); $liste_photos = array(); foreach ($liste as $item){ if ($item['_id_annonce'] == $id){ $liste_photos[] = $item; } } return $liste_photos; } }
Java
UTF-8
1,814
2.703125
3
[]
no_license
package util; import context.ProductContext; import db.TransactionManager; import entity.Product; import mapper.ContextMapper; import javax.sql.DataSource; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; public class Basket { private TransactionManager transactionManager; private Map<Integer, ProductContext> mapProductInBasket = new HashMap<>(); public Basket(DataSource dataSource) { this.transactionManager = new TransactionManager(dataSource); } public Map<Integer, ProductContext> getMapProductInBasket() { return mapProductInBasket; } public void addProductToBasketFromBase(int id) throws SQLException { addProductToBasket(transactionManager.execute(() -> UtilSQl.getProductFromBase(id)), id); } public void addProductToBasket(Product product, int id) { if (mapProductInBasket.containsKey(id)) { int currentCount = mapProductInBasket.get(id).getCount(); ProductContext productContext = ContextMapper.map(currentCount + 1, product); mapProductInBasket.put(id, productContext); } else { mapProductInBasket.put(id, ContextMapper.map(1, product)); } } public void removeOneProductFromBasket(int id) { if (mapProductInBasket.get(id).getCount() > 1) { int count = mapProductInBasket.get(id).getCount() - 1; mapProductInBasket.get(id).setCount(count); } else { mapProductInBasket.remove(id); } } public Product findById(int id) { return mapProductInBasket.get(id).getProduct(); } public void removeProductFromBasket(int id) { mapProductInBasket.remove(id); } public void clearBasket() { mapProductInBasket.clear(); } }
Markdown
UTF-8
5,127
2.578125
3
[ "MIT" ]
permissive
--- theme: "solarized" #theme: "black" transition: "zoom" highlightTheme: "solarized-dark" separator: "^\n\n\n" verticalSeparator: "^\n\n" #margin: 0.1 #minScale: 0.2 #maxScale: 1.5 #fig_width: 7 #fig_height: 6 title: "git primer" author: Maximilian Konzack date: February 20, 2020 output: revealjs::revealjs_presentation --- # Introduction to git ## Agenda 1. Understanding version control 2. How to use basic git commands 3. Hands-on with git 4. What's to learn after that ## Who has experience with version control? - Dropbox, Nextcloud - google drive, iCloud, OneDrive - CVS, SVN - git, mercurial, darcs # What is version control? ## Filenames as version control ![blah](img/draft_mess.png) ## Local version control <img src="img/pro-git-book/local.png" height="500"> ## Centralized VCS <img src="img/pro-git-book/centralized.png" height="500"> ## Distributed VCS <img src="img/pro-git-book/distributed.png" height="500"> ## What is VCS? <iframe src="https://player.vimeo.com/video/41027679?title=0&byline=0&portrait=0" width="888" height="500" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe> # What is git? ## A distributed version control system! - work offline - undo errors - track content, not files - small changes - keep history - working with others - don't panic ## git in a nutshell ## delta-based version control system <img src="img/pro-git-book/deltas.png"> ## Stream of snapshots <img src="img/pro-git-book/snapshots.png"> ## Summary ```git``` 1. keeps a timeline 2. handles most operations locally 3. leaves unchanged files as they are 4. maintains "deltas"/diffs of a changed file 5. has three states that a file can have - ```modified``` - ```staged``` - ```committed``` ## Three stages ![bam](img/pro-git-book/areas.png) # ```git``` primer ## Install git - [x] Mac: already installed - [ ] Linux: consult your package manager - [ ] Windows: download https://git-scm.com/download ## Setup git ```bash # configure your identity git config --global user.name 'Jane Doe' git config --global user.email 'jane.doe@riot-grrrl.org' ``` ## command line ### description syntax ```bash # command git # sub-command git status # argument git diff README.md # every git command git command [arguments] # get help git help [command] ``` ## command line ### bash basics ```bash pwd # print working directory ls [dir] # list directory contents echo msg # print message cd [dir] # change directory mkdir dir # create directory rmdir dir # remove directory rm file # remove file cp src dest # copy from source to destination mv src dest # move / rename ``` ```bash nano file # edit file (Linux / Mac) notepad file # edit file (Windows) ``` ## git basic commands ```bash # 0. Initialize the git project (stored in .git subdir). $ git init my-first-git-project # 1. Change the directory to the project. $ cd my-first-git-project # 2. Stage/add our first script. $ git add data-viz-script.R # 3. What is the current status of the files? $ git status # 4. Commit our current changes with a message. $ git commit -m "Adding r code to visualize data" # 5. Check the deltas/changes in the project. $ git diff ``` ## git server ```bash # 1. Commit your changes locally $ git commit [fileA subDirF] -m "[Action] on ... to ..." # 2. Pull changes from the server $ git pull # 3. Push your changes to the server $ git push ``` ## Setup git server 1. Clone an existing project hosted from a git server (GitHub, GitLab, Bitbucket) ```bash $ git clone\ https://github.com/chase-lab/biodiv-patterns-course.git ``` 2. Connect your local repository to a Git server (GitHub, GitLab, Bitbucket) ```bash $ git remote add origin\ https://github.com/komax/my-new-project.git ``` # git clients ## GitHub Desktop <img src="img/github-desktop.png" height="500"> ## GitKraken <img src="img/gitkraken.png" height="500"> ## git in RStudio <img src="img/rstudio-git.png" height="500"> ## git in the shell <img src="img/bash-git.png" height="500"> # Advanced ```git``` skills ## Branching in a nutshell ## Branching <img src="img/pro-git-book/lr-branches-2.png" height="500"> ## Create a branch <img src="img/pro-git-book/head-to-testing.png" height="500"> ## Commit in a branch <img src="img/pro-git-book/advance-testing.png" height="500"> ## Git basics <iframe src="https://player.vimeo.com/video/41381741?title=0&byline=0&portrait=0" width="888" height="500" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe> ## Thank you for your attention # Literature ## Official documentation <img src="img/pro-git-book/progit2.png" height="300"> - https://git-scm.com/book/en/v2 - https://git-scm.com/ - https://git-scm.com/docs/gittutorial ## GitHub resources - https://try.github.io/ - https://github.github.com/training-kit/downloads/de/github-git-cheat-sheet/ ## iDiv GSU - https://idiv-biodiversity.github.io/git-cheat-sheet/ - [Git basics course](https://www.idiv.de/de/ydiv/lehrveranstaltungen/git-basics-for-beginner-level-git-users.html) Thank you, Dirk and Christian
Markdown
UTF-8
5,110
2.609375
3
[]
no_license
--- description: "Recipe of Homemade A Certain Japanese Restaurant&amp;#39;s Bestseller &amp;#34;Squid Popo&amp;#34; Bake (Squid Ark)" title: "Recipe of Homemade A Certain Japanese Restaurant&amp;#39;s Bestseller &amp;#34;Squid Popo&amp;#34; Bake (Squid Ark)" slug: 576-recipe-of-homemade-a-certain-japanese-restaurant-and-39-s-bestseller-and-34-squid-popo-and-34-bake-squid-ark date: 2020-05-22T22:06:36.275Z image: https://img-global.cpcdn.com/recipes/5237889049821184/751x532cq70/a-certain-japanese-restaurants-bestseller-squid-popo-bake-squid-ark-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/5237889049821184/751x532cq70/a-certain-japanese-restaurants-bestseller-squid-popo-bake-squid-ark-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/5237889049821184/751x532cq70/a-certain-japanese-restaurants-bestseller-squid-popo-bake-squid-ark-recipe-main-photo.jpg author: Caroline Pierce ratingvalue: 3.9 reviewcount: 7 recipeingredient: - "2 Squid" - "1 Green pepper" - " For the soy sauce dressing" - "2 tbsp Soy sauce" - "2 tbsp Mirin" - "2 tsp Sake" - "1/2 piece of ginger Juice from grated ginger" - " For the secret mayonnaise sauce" - "4 tbsp Mayonnaise" - "1 tsp Soy sauce" - "1 tsp Sugar" recipeinstructions: - "Cut the green peppers into 4-5mm rings. Combine and mix together the sauce ingredients. Also mix together the mayonnaise ingredients." - "Remove the legs, guts, and bones from the squid, and wash out the insides well. Insert shallow cuts along the skin, 1cm apart. Cut the tentacles into bite-sized pieces." - "Bring some water to a boil. Add the tentacles first, then the squid itself, and boil. Just enough for it to expand a bit." - "Cut the squid after thoroughly draining, and place in a heat-resistant container. Pour the mayonnaise over the squid, arrange the green peppers on top, and add the sauce." - "Broil in a toaster oven until the mayonnaise starts to brown, then it&#39;s complete." categories: - Recipe tags: - a - certain - japanese katakunci: a certain japanese nutrition: 257 calories recipecuisine: American preptime: "PT24M" cooktime: "PT33M" recipeyield: "4" recipecategory: Dinner --- ![A Certain Japanese Restaurant&#39;s Bestseller &#34;Squid Popo&#34; Bake (Squid Ark)](https://img-global.cpcdn.com/recipes/5237889049821184/751x532cq70/a-certain-japanese-restaurants-bestseller-squid-popo-bake-squid-ark-recipe-main-photo.jpg) Hey everyone, hope you are having an incredible day today. Today, we're going to prepare a distinctive dish, a certain japanese restaurant&#39;s bestseller &#34;squid popo&#34; bake (squid ark). One of my favorites. For mine, I am going to make it a little bit unique. This will be really delicious. A Certain Japanese Restaurant&#39;s Bestseller &#34;Squid Popo&#34; Bake (Squid Ark) is one of the most favored of current trending meals on earth. It is enjoyed by millions every day. It's easy, it is fast, it tastes yummy. A Certain Japanese Restaurant&#39;s Bestseller &#34;Squid Popo&#34; Bake (Squid Ark) is something that I have loved my whole life. They are nice and they look fantastic. To get started with this recipe, we have to prepare a few components. You can have a certain japanese restaurant&#39;s bestseller &#34;squid popo&#34; bake (squid ark) using 11 ingredients and 5 steps. Here is how you can achieve it. <!--inarticleads1--> ##### The ingredients needed to make A Certain Japanese Restaurant&#39;s Bestseller &#34;Squid Popo&#34; Bake (Squid Ark): 1. Prepare 2 Squid 1. Make ready 1 Green pepper 1. Make ready For the soy sauce dressing: 1. Prepare 2 tbsp Soy sauce 1. Prepare 2 tbsp Mirin 1. Prepare 2 tsp Sake 1. Take 1/2 piece of ginger Juice from grated ginger 1. Make ready For the secret mayonnaise sauce: 1. Make ready 4 tbsp Mayonnaise 1. Get 1 tsp Soy sauce 1. Make ready 1 tsp Sugar <!--inarticleads2--> ##### Instructions to make A Certain Japanese Restaurant&#39;s Bestseller &#34;Squid Popo&#34; Bake (Squid Ark): 1. Cut the green peppers into 4-5mm rings. Combine and mix together the sauce ingredients. Also mix together the mayonnaise ingredients. 1. Remove the legs, guts, and bones from the squid, and wash out the insides well. Insert shallow cuts along the skin, 1cm apart. Cut the tentacles into bite-sized pieces. 1. Bring some water to a boil. Add the tentacles first, then the squid itself, and boil. Just enough for it to expand a bit. 1. Cut the squid after thoroughly draining, and place in a heat-resistant container. Pour the mayonnaise over the squid, arrange the green peppers on top, and add the sauce. 1. Broil in a toaster oven until the mayonnaise starts to brown, then it&#39;s complete. So that's going to wrap this up for this exceptional food a certain japanese restaurant&#39;s bestseller &#34;squid popo&#34; bake (squid ark) recipe. Thanks so much for reading. I am sure that you will make this at home. There is gonna be interesting food in home recipes coming up. Don't forget to save this page in your browser, and share it to your loved ones, colleague and friends. Thank you for reading. Go on get cooking!
Python
UTF-8
1,221
2.921875
3
[]
no_license
# -*- coding: utf-8 -*- from tkinter import * from tkinter import font import random from tkinter import filedialog pnc = Tk() pnc.title("Prueba Rifa | Gustavo") pnc.geometry("600x315+330+150") pnc.resizable(False, False) slinder1 = PhotoImage(file="fondo.png") slinder = Label(image=slinder1, cursor="right_ptr") slinder.place(x=-0, y=-0, relwidth = 1, relheight = 1) def fileoperations(): opn = open(ext["text"]) opn_lines = opn.readlines() liste = [] for line in opn_lines: liste.append(line) person = random.choice(liste) opn.close() winner["text"] = person def selectfile(): dsy = filedialog.askopenfilename() ext["text"] = dsy select = Button(text="Obtener un ganador", height=4, bg="white", fg="red", font="Forte", cursor="hand2", command=fileoperations) select.place(x=230, y=105) ext = Label(text="No se encuentra Archivo") ext.place(x=150, y=30) dosya = Button(text="Selecciona Archivo", cursor="hand2", command=selectfile, bg="black", fg="white") dosya.place(x=10, y=30) on = Label(text="Nuevo Ganador", font="Algerian", fg="red") on.place(x=150, y=220) winner = Label(text="Sin Elegir") winner.place(x=285, y=220) mainloop()
Java
UTF-8
9,746
1.953125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 Sumo Logic * * 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 ws.epigraph.projections.gen; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import ws.epigraph.types.TypeKind; import java.util.*; import java.util.stream.Collectors; /** * @author <a href="mailto:konstantin.sobolev@gmail.com">Konstantin Sobolev</a> */ public class GenProjectionsComparator< P extends GenProjection<? extends P, TP, EP, ? extends MP>, TP extends GenTagProjectionEntry<TP, MP>, EP extends GenEntityProjection<EP, TP, MP>, MP extends GenModelProjection<EP, TP, /*MP*/?, /*SMP*/?, /*TMP*/? /*M*/>, RMP extends GenRecordModelProjection<P, TP, EP, MP, RMP, FPE, FP, ?>, MMP extends GenMapModelProjection<P, TP, EP, MP, MMP, ?>, LMP extends GenListModelProjection<P, TP, EP, MP, LMP, ?>, PMP extends GenPrimitiveModelProjection<EP, TP, MP, PMP, ?>, FPE extends GenFieldProjectionEntry<P, TP, MP, FP>, FP extends GenFieldProjection<P, TP, MP, FP> > { private final Map<RecEntry, Set<RecEntry>> visited = new HashMap<>(); /** * Checks if two projections are structurally equal. Projection types are not checked. * * @param p1 first projection * @param p2 second projection * * @return {@code true} iff projections are structurally equal */ public boolean equals(@NotNull P p1, @NotNull P p2) { return projectionsEquals(Collections.singleton(p1), Collections.singleton(p2)); } public static < P extends GenProjection<P, TP, EP, MP>, TP extends GenTagProjectionEntry<TP, MP>, EP extends GenEntityProjection<EP, TP, MP>, MP extends GenModelProjection<EP, TP, /*MP*/?, /*SMP*/?, /*TMP*/? /*M*/>, RMP extends GenRecordModelProjection<P, TP, EP, MP, RMP, FPE, FP, ?>, MMP extends GenMapModelProjection<P, TP, EP, MP, MMP, ?>, LMP extends GenListModelProjection<P, TP, EP, MP, LMP, ?>, PMP extends GenPrimitiveModelProjection<EP, TP, MP, PMP, ?>, FPE extends GenFieldProjectionEntry<P, TP, MP, FP>, FP extends GenFieldProjection<P, TP, MP, FP> > boolean projectionsEquals(@NotNull P vp1, @NotNull P vp2) { return new GenProjectionsComparator<P, TP, EP, MP, RMP, MMP, LMP, PMP, FPE, FP>().equals(vp1, vp2); } public void reset() { visited.clear(); } public boolean projectionsEquals( @NotNull Collection<@NotNull ? extends P> ps1, @NotNull Collection<@NotNull ? extends P> ps2) { if (ps1.isEmpty()) return ps2.isEmpty(); boolean flag1 = ps1.stream().anyMatch(GenProjection::flag); boolean flag2 = ps2.stream().anyMatch(GenProjection::flag); if (flag1 != flag2) return false; // check for recursion RecEntry entry1 = new RecEntry(ps1); RecEntry entry2 = new RecEntry(ps2); Set<RecEntry> entries = visited.computeIfAbsent(entry1, k -> new HashSet<>()); if (entries.contains(entry2)) return true; else entries.add(entry2); Map<String, Collection<TP>> tags1 = collectTags(ps1); Map<String, Collection<TP>> tags2 = collectTags(ps2); if (!tags1.keySet().equals(tags2.keySet())) return false; for (final Map.Entry<String, Collection<TP>> entry : tags1.entrySet()) { String tagName = entry.getKey(); final List<@NotNull MP> models1 = entry.getValue() .stream().map(GenTagProjectionEntry::modelProjection).collect(Collectors.toList()); final List<@NotNull MP> models2 = tags2.get(tagName) .stream().map(GenTagProjectionEntry::modelProjection).collect(Collectors.toList()); if (!modelEquals(models1, models2)) return false; } final List<? extends P> tails1 = collectTails(ps1); final List<? extends P> tails2 = collectTails(ps2); return projectionsEquals(tails1, tails2); } private @NotNull Map<String, Collection<TP>> collectTags(@NotNull Collection<@NotNull ? extends P> vps) { final Map<String, Collection<TP>> res = new HashMap<>(); for (P vp : vps) { for (final Map.Entry<String, TP> entry : vp.tagProjections().entrySet()) { Collection<TP> tps = res.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()); tps.add(entry.getValue()); } } return res; } private List<? extends P> collectTails(final Collection<@NotNull ? extends P> vps) { return vps.stream() .map(GenProjection::polymorphicTails) .filter(Objects::nonNull) .flatMap(List::stream) .collect(Collectors.toList()); } @SuppressWarnings("unchecked") protected boolean modelEquals(@NotNull Collection<@NotNull MP> mps1, @NotNull Collection<@NotNull MP> mps2) { if (mps1.isEmpty()) return mps2.isEmpty(); final TypeKind kind = mps1.iterator().next().type().kind(); assert mps1.stream().allMatch(m -> m.type().kind() == kind); assert mps2.stream().allMatch(m -> m.type().kind() == kind); final List<@Nullable ?> metas1 = mps1.stream().map(m -> m.metaProjection()).filter(Objects::nonNull).collect(Collectors.toList()); final List<@Nullable ?> metas2 = mps2.stream().map(m -> m.metaProjection()).filter(Objects::nonNull).collect(Collectors.toList()); if (!modelEquals((Collection<MP>) metas1, (Collection<MP>) metas2)) return false; switch (kind) { case ENTITY: throw new IllegalArgumentException("Unsupported model kind: " + kind); case RECORD: return recordModelEquals((Collection<RMP>) mps1, (Collection<RMP>) mps2); case MAP: return mapModelEquals((Collection<MMP>) mps1, (Collection<MMP>) mps2); case LIST: return listModelEquals((Collection<LMP>) mps1, (Collection<LMP>) mps2); case ENUM: throw new IllegalArgumentException("Unsupported model kind: " + kind); case PRIMITIVE: return primitiveModelEquals((Collection<PMP>) mps1, (Collection<PMP>) mps2); default: throw new IllegalArgumentException("Unsupported model kind: " + kind); } } protected boolean recordModelEquals(@NotNull Collection<@NotNull RMP> mps1, @NotNull Collection<@NotNull RMP> mps2) { final Map<String, Collection<FPE>> fields1 = collectFields(mps1); final Map<String, Collection<FPE>> fields2 = collectFields(mps2); if (!fields1.keySet().equals(fields2.keySet())) return false; for (final Map.Entry<String, Collection<FPE>> entry : fields1.entrySet()) { String fieldName = entry.getKey(); final List<@NotNull P> vps1 = entry.getValue() .stream().map(e -> e.fieldProjection().projection()).collect(Collectors.toList()); final List<@NotNull P> vps2 = fields2.get(fieldName) .stream().map(e -> e.fieldProjection().projection()).collect(Collectors.toList()); if (!projectionsEquals(vps1, vps2)) return false; } return true; } // @SuppressWarnings("unchecked") private Map<String, Collection<FPE>> collectFields(@NotNull Collection<@NotNull RMP> rmps) { Map<String, Collection<FPE>> res = new HashMap<>(); for (final RMP rmp : rmps) { for (final Map.Entry<String, FPE> entry : rmp.fieldProjections().entrySet()) { final Collection<FPE> fpes = res.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()); fpes.add(entry.getValue()); } } return res; } protected boolean mapModelEquals(@NotNull Collection<@NotNull MMP> mps1, @NotNull Collection<@NotNull MMP> mps2) { final List<@NotNull P> vps1 = mps1.stream().map(MMP::itemsProjection).collect(Collectors.toList()); final List<@NotNull P> vps2 = mps2.stream().map(MMP::itemsProjection).collect(Collectors.toList()); return projectionsEquals(vps1, vps2); } protected boolean listModelEquals(@NotNull Collection<@NotNull LMP> mps1, @NotNull Collection<@NotNull LMP> mps2) { final List<@NotNull P> vps1 = mps1.stream().map(LMP::itemsProjection).collect(Collectors.toList()); final List<@NotNull P> vps2 = mps2.stream().map(LMP::itemsProjection).collect(Collectors.toList()); return projectionsEquals(vps1, vps2); } protected boolean primitiveModelEquals( @NotNull Collection<@NotNull PMP> mps1, @NotNull Collection<@NotNull PMP> mps2) { return true; } private final class RecEntry { private final Collection<? extends P> vps; private final int hashCode; private RecEntry(final Collection<? extends P> vps) { this.vps = vps; int hashCode = 31; for (final P vp : vps) { hashCode = hashCode * 31 + System.identityHashCode(vp); } this.hashCode = hashCode; } @SuppressWarnings("unchecked") @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final RecEntry entry = (RecEntry) o; if (hashCode != entry.hashCode) return false; for (final P vp1 : vps) { boolean found = false; for (final P vp2 : entry.vps) { if (vp1 == vp2) { found = true; break; } } if (!found) return false; } return true; } @Override public int hashCode() { return hashCode; } } }
Shell
UTF-8
924
3.765625
4
[]
no_license
#!/bin/bash # shellcheck disable=SC2086 set -eou pipefail config_file="${1:-}" vendor_dir="${2:-}" if [[ -z "$config_file" ]]; then echo "Must pass config file as first argument" exit 0 fi if ! [[ -f "$config_file" ]]; then echo "Must pass config file as first argument." exit 0 fi if [[ -z "$vendor_dir" ]]; then echo "Must pass vendor directory as second argument" exit 0 fi if ! [[ -d "$vendor_dir" ]]; then echo "Must pass vendor directory as second argument" exit 0 fi cd $vendor_dir && rm -rf * echo "Installing Dependencies..." jq -c '.dependencies[]' $config_file for dep in $(jq -r '.dependencies[] | @base64' $config_file); do echo "---------------------" _jq() { echo ${dep} | base64 -d | jq -r ${1} } this_name=$(_jq '.name') this_install=$(_jq '.install') echo "$this_name" echo "$this_install" eval $this_install done echo "Dependencies installed."
Swift
UTF-8
576
2.734375
3
[ "MIT" ]
permissive
// // TestLinearMap.swift // SpaceKitTests // // Created by Yuhuan Jiang on 3/16/20. // Copyright © 2020 Yuhuan Jiang. All rights reserved. // import XCTest import SpaceKit class TestLinearMap: XCTestCase { func testComposingLinearMaps() { let p1 = Polynomial(coefficients: [2, 3, 4, 5, 6 ]) let p2 = DifferentiationLinearMap().apply(on: p1) let p3 = DifferentiationLinearMap().apply(on: p2) let p4 = DifferentiationLinearMap().then(DifferentiationLinearMap()).apply(on: p1) XCTAssertEqual(p3, p4) } }
Java
UTF-8
232
1.773438
2
[]
no_license
package com.hef.spittr.service; import com.hef.spittr.domain.Spitter; public interface AlertService { void sendSpitter(Spitter spitter); void sendMessage(String message); void sendHandlerSpitter(Spitter spitter); }
Markdown
UTF-8
5,627
3.546875
4
[]
no_license
# Bookstore Project Instructions ## 05 Finished ## 06 ### Rubric Criteria Performance levels Score #### Program Runs Yes Program compiles and runs 10 No Program does NOT compile and run 0 #### Code is Clean Yes Code is easy to read (good commenting, variable names, indentation, etc.) 10 Some problems Code has issues 5 No Code is difficult to read (missing commenting, bad variable names, poor indentation, etc.) 0 #### Dynamic Pagination in App Yes Program uses tag helpers to dynamically create the page navigation and displays 5 items per page 30 Navigation is Not Dynamic Navigation is hard-coded 5 Missing Pagination 0 #### URLs use /P2, /P3, /P4, etc. Yes URLs have been improved to use /P2, /P3, /P4 etc. to access a specific page 10 No Meets no performance expectations or does not exist 0 #### Bootstrap Used to Beautify App Yes Boostrap is used to organize the items in the list and make them look good (similar to what is done in the videos and textbook) 10 No Bootstrap is not used to organize the items in the list and make the app look good 0 #### App Uses New Bootstrap Commands Yes New Bootstrap commands are used and listed in the Comments section of the submission 5 No New Bootstrap commands are not used and/or listed in the comments of the submission 0 #### Model/Database Updated to Include # Pages Yes Model has been updated to include the number of pages, and that data is reflected in the database 10 No Model does not include the number of pages, or those changes are not reflected in the database 0 #### 3 New Books Added to Database Yes Three new books have been added to the database through the Seed Data 10 No Three new books have NOT been added to the database through the Seed Data 0 #### Submitted via GitHub Yes Assignment submitted via a link to a GitHub repository 5 No Assignment NOT submitted via a link to a GitHub repository 0 ## 07 ### Rubric #### Program Runs Yes Program runs without error 10 No Program has errors 0 #### Code is Clean Yes Code is easy to read (good variable names, white space, indentation, commenting, etc.) 10 No Code is difficult to read (ambiguous variable names, lack of white space, poor indentation, missing commenting, etc.) 0 #### Functionality in Controller to Filter Results (i.e. Can filter by passing in argument to URL) Yes The app has the built-in functionality to filter by adding an argument to the controller (i.e. "/?category=autobiography) for the category 10 No App does not have ability to filter results by category 0 #### User-Friendly Endpoints Yes As in the example, modify the Endpoints so that the user can add something like "/Books/Autobiography" onto the URL and get results. (NOTE: Does not need to follow that specific path.) 10 No Endpoints have not been updated to select based off of category and page #. 0 #### Category Dynamically Added to URL Yes When a category is selected, it appears in the URL. 10 No Category does not automatically appear in URL when selected. 0 #### Category Menu Inserted via ViewComponent Yes Category menu is inserted into the view by using a View Component 5 No Category menu is not inserted into the view by using a View Component 0 #### View Component Partial View Yes View Component partial view created and inserted via the ViewComponent 10 No View Component partial view not created and inserted via the ViewComponent 0 #### Filter Results by Clicking on Category Yes Navigation allows user to click on category and filter results 10 No Navigation does not allow user to click on category and filter results 0 #### Highlighting Selected Category Yes Clicking on a category causes that category to be highlighted 10 No Click on a category does not cause that category to be highlighted 0 #### Page Numbering Matches Results Yes Page numbering matches results 10 Not developed Page numbering does not match results 0 #### Submitted via GitHub Repository Yes Submitted via link to GitHub Repository (containing only the code for this assignment) 5 No Not submitted via link to GitHub Repository or link goes to a previous or future assignment ## 08 #### Program Runs w/o Error Yes Program runs without any errors 10 No Program has errors 0 #### Code is Clean Yes Code is easy to read (good indentation, commenting, variable names, etc.) 10 No Code is difficult to read (ambiguous variable names, missing commenting, poor indentation, etc.) 0 #### App Uses a SQLite Database Yes Database has been converted to SQLite. 5 No Database has NOT been converted to SQLite. 0 #### Cart is Displayed via a Razor Page Yes Cart is displayed by using a Razor Page. 10 No Cart is displayed using something other than a Razor Page. 0 #### Cart Updates Qty & Price with New Items Yes The app has the ability to add items to the cart and have the quantity, subtotal, and total all updated. 20 No The app does not have the ability to add items to the cart and have the quantity, subtotal, and total all updated. 0 #### Cart Has Ability to Remove Item Yes The app has the ability to remove an item from the cart. 20 No The app does NOT have the ability to remove an item from the cart. 0 #### Cart Summary is Displayed in Navbar Yes A summary of the cart (# items, price) is displayed in the navbar across the pages in the app. 20 No A summary of the cart is NOT displayed in the navbar across the pages in the app. 0 #### Submitted via GitHub Yes Assignment is submitted via a link to a GitHub repository 5 No Assignment is submitted via a .zip file or some other way other than a link to a GitHub repository 0
Java
UTF-8
837
1.578125
2
[]
no_license
package com.android.pplusaudit2.Report.StoreSummary; /** * Created by ULTRABOOK on 5/10/2016. */ public class StoreItem { public int ID; public int userID; public int auditID; public String auditName; public String account; public String customerCode; public String customer; public String area; public String regionCode; public String region; public String distributorCode; public String distributor; public String storeCode; public String storeName; public String channelCode; public String template; public double perfectStore; public double osa; public double npi; public double planogram; public String createdAt; public String updateAt; public int perfectCategory; public int totalCategory; public double perfectPercentage; }
C++
UTF-8
1,378
2.59375
3
[]
no_license
#include <stdio.h> #include "Point.h" #include "Size.h" #include "Cell.h" #include "Map.h" #include "Player.h" #include "PathSearchAI.h" #include "AStar.h" #define WIDTH 20 #define HEIGHT 10 char map[HEIGHT*WIDTH] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, X, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, X, 0, 0, X, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, X, 0, 0, X, 0, 0, 0, W, 0, 0, 0, 0, S, 0, 0, 0, 0, 0, 0, 0, X, 0, 0, X, 0, 0, 0, W, 0, G, 0, 0, 0, 0, 0, 0, 0, X, X, X, X, X, X, X, 0, 0, 0, W, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, X, 0, 0, X, 0, 0, 0, W, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, X, 0, 0, X, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, X, X, X, X, X, X, X, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* #define WIDTH 5 #define HEIGHT 5 char map[HEIGHT*WIDTH] = { 0, X, 0, 0, 0, 0, S, X, 0, 0, 0, 0, X, 0, 0, X, X, X, 0, 0, 0, 0, 0, G, 0 };*/ int main() { try { Map m(map, IntSize(WIDTH, HEIGHT)); m.drawMap(); { PathSearchAI* ai = new AStar();; Player p(ai, 8); p.goesIntoTheMap(&m); if(p.searchPath()) { printf("\n"); m.drawMap(); } delete ai; } } catch(MapException& e) { printf(e.message.c_str()); } return 0; }
Markdown
UTF-8
1,280
2.703125
3
[ "BSD-3-Clause" ]
permissive
# mathpractice An app to help with practicing basic maths. ## Why? To help my kids practice their basic math skills. * Purposely a small app that doesn't deal with all the error states. * Purposely doesn't have authentication. * Simple in design & implementation. > **Note:** I'm running this app on a Raspberry Pi on my home network, > siloed off from the rest of the internet. I'd **highly** recommend doing > some similar (either just running locally or home network at most). > > **DO NOT EXPOSE THIS ON THE BROADER INTERNET!** ## Images ![choices](./readme_images/choices.png) ![problem](./readme_images/problem.png) ![summary](./readme_images/summary.png) ## Setup ``` $ git clone git@github.com:toastdriven/mathpractice.git $ cd mathpractice $ pipenv install $ cd mathpractice $ python >>> import app >>> app.db.create_tables([app.Problem]) ``` ## Running ``` $ pipenv shell # Export the valid names to be displayed in the app. $ export APP_NAMES="daniel,john,jane" # Optional, to enable debug mode. # $ export APP_DEBUG=1 $ cd mathpractice $ python app.py # Alternatively, if you'll be changing the code, some hot-reloading... # $ pipenv install gunicorn # $ gunicorn -w 1 -t 0 app:app ``` Then hit up http://127.0.0.1/ in your browser. ## License New BSD
Python
UTF-8
191
3.640625
4
[]
no_license
import functools def max_in_list(list_of_nums): # get the maximum number in a list using the reduce function return functools.reduce(lambda x, y: x if (x > y) else y, list_of_nums)
C++
UTF-8
1,239
2.875
3
[]
no_license
//-*- coding:utf-8 -*- // Generated by the Fetch-Leetcode project on the Github // https://github.com/CJHMPower/Fetch-Leetcode/ // 210 Course Schedule II // https://leetcode.com//problems/course-schedule-ii/description/ // Fetched at 2018-07-24 // Submitted 2 years, 1 month ago // Runtime: 28 ms // This solution defeats 8.87% cpp solutions class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> result; vector<vector<int>> graph(numCourses); vector<int> indegree(numCourses, 0); for (auto it = prerequisites.begin(); it != prerequisites.end(); it++) { graph[it->second].push_back(it->first); indegree[it->first]++; } queue<int> Q; for (int i = 0; i < numCourses; i++) { if (indegree[i] == 0) { Q.push(i); result.push_back(i); } } int counter = 0; while (!Q.empty()) { int u = Q.front(); Q.pop(); counter++; for (int i = 0; i < graph[u].size(); i++) if (--indegree[graph[u][i]] == 0) { Q.push(graph[u][i]); result.push_back(graph[u][i]); } } if (counter != numCourses) { result.clear(); } return result; } };
Java
UTF-8
107
2.25
2
[]
no_license
package test; public class Element { public String appearance() { return "OVERRIDE THIS METHOD"; } }
JavaScript
UTF-8
2,848
2.703125
3
[]
no_license
function noOp(){}; /** * Creates a watcher for webpack * @param {string} name a name to prepend to log output * @param {webpack compiler} compiler * @param {object} options an option of objects (must have been put through `makeWatcherOptions`) */ module.exports = function webpackWatcher(name,compiler,options){ let state = false; let forceRebuild = false; let callbacks = []; let watching; function invalidPlugin() { if(state && (!options.noInfo && !options.quiet)) { console.info(`${name}: bundle is now INVALID.`); } state = false; } function invalidAsyncPlugin(compiler, callback) { invalidPlugin(); callback(); } function ready(fn, req) { if(state) { return fn(); } if(!options.noInfo && !options.quiet) { console.log(`${name}: wait until bundle finished: ` + (req.url || fn.name)); } callbacks.push(fn); } function rebuild() { if(state){ state = false; compiler.run(function(err) { if(err) throw err; }); } else { forceRebuild = true; } } function donePlugin(stats) { state = true; process.nextTick(()=>{ if(!state) { return; } var displayStats = (!options.quiet && options.stats !== false); if( displayStats && ! ( stats.hasErrors() || stats.hasWarnings() ) && options.noInfo ){ displayStats = false; } if(displayStats) { console.log(stats.toString(options.stats)); } if(!options.noInfo && !options.quiet){ console.info(`${name}: bundle is now VALID.`); } console.info(`${name}: rebuilt`); const cbs = callbacks; callbacks = []; cbs.forEach( function continueBecauseBundleAvailable(cb){ cb(); } ); }); if(forceRebuild){ forceRebuild = false; rebuild(); } } compiler.plugin('done',donePlugin); compiler.plugin("invalid", invalidPlugin); compiler.plugin("watch-run", invalidAsyncPlugin); compiler.plugin("run", invalidAsyncPlugin); function watch(callback){ callback = callback || noOp; if(watching && watching.running){ callback(); }else{ ready(callback,{}); } if(!options.lazy) { watching = compiler.watch(options.watchOptions,(err)=>{ if(err){ throw err; } }); } else { state = true; } } function waitUntilValid(callback) { callback = callback || noOp; if (!watching || !watching.running) { callback(); } else { ready(callback, {});} }; function invalidate(callback) { callback = callback || noOp; if(watching) { ready(callback, {}); watching.invalidate(); } else { callback(); } }; function close(callback) { callback = callback || noOp; if(watching) { watching.close(callback); } else { callback(); } }; return {watch,waitUntilValid,invalidate,close,ready} }
C#
UTF-8
2,532
3.140625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; class F { static int[] Read() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse); static (int, int) Read2() { var a = Read(); return (a[0], a[1]); } static void Main() => Console.WriteLine(Solve()); static object Solve() { var (n, m) = Read2(); var d = Read(); var es = Array.ConvertAll(new bool[m], _ => Read()); if (d.Sum() != 2 * (n - 1)) return -1; var map = ToMap(n + 1, es, false); for (int i = 0; i < n; i++) { d[i] -= map[i + 1].Length; if (d[i] < 0) return -1; } var uf = new UF(n); foreach (var e in es) { var a = e[0] - 1; var b = e[1] - 1; if (!uf.Unite(a, b)) return -1; } var gs = uf.ToGroups(); var gvs = gs .Select(g => g.SelectMany(v => Enumerable.Repeat(v, d[v])).ToArray()) .OrderBy(g => g.Length) .ToArray(); if (gvs[0].Length == 0) return -1; var r = new List<string>(); var q = new Queue<int>(gvs[^1]); for (int gi = gs.Length - 2; gi >= 0; gi--) { var vs = gvs[gi]; if (q.Count == 0) return -1; r.Add($"{q.Dequeue() + 1} {vs[0] + 1}"); foreach (var nv in vs[1..]) { q.Enqueue(nv); } } return string.Join("\n", r); } public static int[][] ToMap(int n, int[][] es, bool directed) => Array.ConvertAll(ToMapList(n, es, directed), l => l.ToArray()); public static List<int>[] ToMapList(int n, int[][] es, bool directed) { var map = Array.ConvertAll(new bool[n], _ => new List<int>()); foreach (var e in es) { map[e[0]].Add(e[1]); if (!directed) map[e[1]].Add(e[0]); } return map; } } class UF { int[] p, sizes; public int GroupsCount; public UF(int n) { p = Enumerable.Range(0, n).ToArray(); sizes = Array.ConvertAll(p, _ => 1); GroupsCount = n; } public int GetRoot(int x) => p[x] == x ? x : p[x] = GetRoot(p[x]); public int GetSize(int x) => sizes[GetRoot(x)]; public bool AreUnited(int x, int y) => GetRoot(x) == GetRoot(y); public bool Unite(int x, int y) { if ((x = GetRoot(x)) == (y = GetRoot(y))) return false; // 要素数が大きいほうのグループにマージします。 if (sizes[x] < sizes[y]) Merge(y, x); else Merge(x, y); return true; } protected virtual void Merge(int x, int y) { p[y] = x; sizes[x] += sizes[y]; --GroupsCount; } public int[][] ToGroups() => Enumerable.Range(0, p.Length).GroupBy(GetRoot).Select(g => g.ToArray()).ToArray(); }
Python
UTF-8
2,378
2.59375
3
[ "MIT" ]
permissive
import hashlib from database.consent_form import ConsentForm from database.database_util import connect_to_database, connect_to_anonymous_database, close_database_connection from database.session import Session def anonymize_database(): """ Anonymises the currently connected database to the 'anonymous' database. Intended to be used with the 'laravel' dataset, which is data collected from the second experiment. :return: """ connect_to_database() # First collect the important parts of the database. sessions = [] users = [] consent_forms = [] for session in Session.get_completed_sessions(): sessions.append(session) for user in Session.get_users_with_tracks(): users.append(user) email_addresses = [user.email_address for user in users] for consent_form in ConsentForm.objects(): if consent_form.email_address in email_addresses and \ consent_form.email_address not in [consent_form_temp.email_address for consent_form_temp in consent_forms]: consent_forms.append(consent_form) close_database_connection() connect_to_anonymous_database() # Sessions don't need to be anonymised, so just store them. for session in sessions: print(f"Storing: {session.playlist_name}") session.save() # The email address and spotify user id need to be anonymised before storing them. print("\n====================\n") user_dict = {} for user in users: user_dict[user.email_address] = user user.email_address = hashlib.sha224(user.email_address.encode()).hexdigest() user.spotify_id = hashlib.sha224(user.spotify_id.encode()).hexdigest() print(f"Storing: {user.email_address}") user.save() # The consent forms similarly need to be anonymised as well, # but make sure that the email address remains consistent. print("\n====================\n") for consent_form in consent_forms: print(f"Storing: {consent_form.email_address}") associated_user = user_dict[consent_form.email_address] consent_form.email_address = associated_user.email_address consent_form.save() if consent_form.session_id is None: consent_form.session_id = associated_user.session_id consent_form.save() close_database_connection()
Java
UTF-8
2,423
2.984375
3
[]
no_license
package com.allstate.training.view; import java.io.*; import com.allstate.training.pojo.*; import java.util.Scanner; public class TrainingApp { public static void main (String args[])throws IOException,ClassNotFoundException {Scanner sc=new Scanner(System.in); Trainer t=new Trainer(); Course c=new Course(); FileOutputStream fos=new FileOutputStream("training.txt",true); ObjectOutputStream oos = new ObjectOutputStream(fos); FileInputStream fis=new FileInputStream("training.txt"); ObjectInputStream ois=new ObjectInputStream(fis); do { System.out.println("Welcome to training App "+"1.Create trainer\n "+"2.Create Course\n"+"3.Create Student"+"4.Exit"); int choice=sc.nextInt(); switch(choice) { case 1: System.out.println("Enter trainerid"); String tid=sc.next(); t.setTrainerid(tid); System.out.println("Enter trainername"); String n=sc.next(); t.setTrainername(n); break; case 2: System.out.println("Enter Course ID and Course name"); c.getCourseID(sc.next()); c.getCourseName(sc.next()); break; case 3: System.out.println(" Enter stid, stname,phno,dob"); String sid=sc.next(); String sname=sc.next(); String pno=sc.next(); String date=sc.next(); System.out.println("1. Regular Student 2. Distance Student"); int ch=sc.nextInt(); switch(ch) { case 1: System.out.println("Enter the score"); double sco=sc.nextDouble(); RegularStudent rs=new RegularStudent(sid,sname,pno,date,sco,c); System.out.println(rs); /* FileOutputStream fos1=new FileOutputStream("training.txt",true); ObjectOutputStream oos1 = new ObjectOutputStream(fos); oos1.writeObject(rs); oos1.close(); fos1.close();*/ //oos.writeObject(rs); String s2=rs.toString(); fos.write(s2.getBytes()); break; case 2: DistanceStudent ds=new DistanceStudent(sc.next(),sname,pno,date,c); System.out.println(ds); String s1=ds.toString(); //oos.writeObject(ds); fos.write(s1.getBytes()); //DistanceStudent ds1=(DistanceStudent)ois.readObject(); break; default: System.out.println("Invalid"); break; } break; case 4:System.exit(0); break; default:System.out.println("Invalid"); break; } } while(true); } }
C++
UTF-8
947
2.859375
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { int t; int n; string t_str; string n_str; getline(cin, t_str); getline(cin, n_str); t = stoi(t_str); n = stoi(n_str); if (n<1 || n>1000) cout<<"too many number of lines"<<endl; string lines[n]; string temp; string replace1("ent"); string replace2("entin"); string replace3("enten"); for (int i = 0; i < n; i ++){ getline(cin, temp); lines[i] = temp; } for (int c = 0; c < t; c++){ cout<<"Case #"<<c+1<<":"<<endl; for (int i = 0; i < n; i ++){ while (lines[i].find(replace2)<10000) lines[i].replace(lines[i].find(replace2),replace2.length(),"ierende"); while (lines[i].find(replace3)<10000) lines[i].replace(lines[i].find(replace3),replace3.length(),"ierende"); while (lines[i].find(replace1)<10000) lines[i].replace(lines[i].find(replace1),replace1.length(),"ierender"); cout << lines[i] << endl; } } return 0; }
JavaScript
UTF-8
34,064
2.515625
3
[ "MIT" ]
permissive
function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { var data = ev.dataTransfer.getData("text"); //Target cell var trgt_row = $(ev.target).parent().parent().index(); var trgt_col = $(ev.target).parent().index(); var capture_cell = $('#ChessBoardTbl tr:eq(' + (trgt_row) + ') td:eq(' + (trgt_col) + ')'); //Intersecting pieces var drag_piece_id = ev.dataTransfer.getData("text"); var cap_img_id = $(capture_cell).children().attr("id"); var drag_image=document.getElementById(drag_piece_id); var cap_image=document.getElementById(cap_img_id); //Occupied cells if (ev.target.bgColor==undefined) { //Showing details console.log(drag_piece_id+" to "+cap_img_id+" in "+"("+trgt_row+","+trgt_col+")"); //Same color cells if (drag_piece_id.charAt(0) !== cap_img_id.charAt(0)) { $(cap_image).remove(); $(drag_image).detach().appendTo($(capture_cell)); } } //Unoccupied cells else{ ev.target.appendChild(document.getElementById(data)); } } function B_radar(cell){ var op_nm = $(cell).children().attr("id"); // Identify intruder if (op_nm!=null) { //Enemy if (op_nm.charAt(0)=="W") { $( cell ).css("background-color", "#ff6666"); } //Friendly else if (op_nm.charAt(0)=="B") { $( cell ).css("background-color", ""); } return true; } //No_one else { $( cell ).css("background-color", "#90ee90"); return false; } } function W_radar(cell){ var op_nm = $(cell).children().attr("id"); // Identify intruder if (op_nm!=null) { //Enemy if (op_nm.charAt(0)=="B") { $( cell ).css("background-color", "#ff6666"); } //Friendly else if (op_nm.charAt(0)=="W") { $( cell ).css("background-color", ""); } return true; } //No_one else { $( cell ).css("background-color", "#90ee90"); return false; } } function B_pawn_radar(cell,cell2,cellE1,cellE2,row_index){ var op_nm2 = $(cell2).children().attr("id"); //2nd row special movement avoid if ((row_index!=1) || (op_nm2!=null)) { cell2=null; } var op_nm = $(cell).children().attr("id"); // Identify intruder if (op_nm!=null) { //Enemy and Friendly if (op_nm.charAt(0)=="W","B") { $( cell ).css("background-color", ""); $( cell2 ).css("background-color", ""); } else{ $( cell ).css("background-color", "#90ee90"); $( cell2 ).css("background-color", "#90ee90"); } } //No_one else { $( cell ).css("background-color", "#90ee90"); $( cell2 ).css("background-color", "#90ee90"); } //Elimination mode 1 var op_nm1 = $(cellE1).children().attr("id"); // Identify intruder if (op_nm1!=null) { //Enemy if (op_nm1.charAt(0)=="W") { $( cellE1 ).css("background-color", "#ff6666"); } //Friendly else if (op_nm1.charAt(0)=="B") { $( cellE1 ).css("background-color", ""); } //No_one else { $( cellE1 ).css("background-color", "#90ee90"); } } else { $( cellE1 ).css("background-color", ""); } //Elimination mode 2 var op_nm2 = $(cellE2).children().attr("id"); // Identify intruder if (op_nm2!=null) { //Enemy if (op_nm2.charAt(0)=="W") { $( cellE2 ).css("background-color", "#ff6666"); } //Friendly else if (op_nm2.charAt(0)=="B") { $( cellE2 ).css("background-color", ""); } //No_one else { $( cellE2 ).css("background-color", "#90ee90"); } } else { $( cellE2 ).css("background-color", ""); } } function W_pawn_radar(cell,cell2,cellE1,cellE2,row_index){ var op_nm2 = $(cell2).children().attr("id"); //2nd row special movement avoid if ((row_index!=6) || (op_nm2!=null)) { cell2=null; } var op_nm = $(cell).children().attr("id"); // Identify intruder if (op_nm!=null) { //Enemy and Friendly if (op_nm.charAt(0)=="W","B") { $( cell ).css("background-color", ""); $( cell2 ).css("background-color", ""); } else{ $( cell ).css("background-color", "#90ee90"); $( cell2 ).css("background-color", "#90ee90"); } } //No_one else { $( cell ).css("background-color", "#90ee90"); $( cell2 ).css("background-color", "#90ee90"); } //Elimination mode 1 var op_nm1 = $(cellE1).children().attr("id"); // Identify intruder if (op_nm1!=null) { //Enemy if (op_nm1.charAt(0)=="B") { $( cellE1 ).css("background-color", "#ff6666"); } //Friendly else if (op_nm1.charAt(0)=="W") { $( cellE1 ).css("background-color", ""); } //No_one else { $( cellE1 ).css("background-color", "#90ee90"); } } else { $( cellE1 ).css("background-color", ""); } //Elimination mode 2 var op_nm2 = $(cellE2).children().attr("id"); // Identify intruder if (op_nm2!=null) { //Enemy if (op_nm2.charAt(0)=="B") { $( cellE2 ).css("background-color", "#ff6666"); } //Friendly else if (op_nm2.charAt(0)=="W") { $( cellE2 ).css("background-color", ""); } //No_one else { $( cellE2 ).css("background-color", "#90ee90"); } } else { $( cellE2 ).css("background-color", ""); } } <!--BLACK PAWN--> $(document).ready(function(){ $(".Bpawn").mouseenter(function(){ var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); // console.log("row_index: "+row_index+" col_index: "+col_index); var cell = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + col_index + ')'); var cell2 = $('#ChessBoardTbl tr:eq(' + (row_index+2) + ') td:eq(' + col_index + ')'); var cellE1 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index+1) + ')'); var cellE2 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index-1) + ')'); B_pawn_radar(cell,cell2,cellE1,cellE2,row_index); }); $(".Bpawn").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); <!--WHITE PAWN--> $(document).ready(function(){ $(".Wpawn").mouseenter(function(){ var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); // console.log("row_index: "+row_index+" col_index: "+col_index); var cell = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + col_index + ')'); var cell2 = $('#ChessBoardTbl tr:eq(' + (row_index-2) + ') td:eq(' + col_index + ')'); var cellE1 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index+1) + ')'); var cellE2 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index-1) + ')'); W_pawn_radar(cell,cell2,cellE1,cellE2,row_index); }); $(".Wpawn").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); <!--BLACK KING--> $(document).ready(function(){ $(".B_King").mouseenter(function(){ var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); // console.log("row_index: "+row_index+" col_index: "+col_index); var cell_1 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index) + ')'); var cell_2 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index+1) + ')'); var cell_3 = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index+1) + ')'); var cell_4 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index+1) + ')'); var cell_5 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index) + ')'); var cell_6 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index-1) + ')'); var cell_7 = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index-1) + ')'); var cell_8 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index-1) + ')'); B_radar(cell_1); B_radar(cell_2); B_radar(cell_3); B_radar(cell_4); B_radar(cell_5); B_radar(cell_6); B_radar(cell_7); B_radar(cell_8); }); $(".B_King").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); <!--WHITE KING--> $(document).ready(function(){ $(".W_King").mouseenter(function(){ var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); // console.log("row_index: "+row_index+" col_index: "+col_index); var cell_1 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index) + ')'); var cell_2 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index+1) + ')'); var cell_3 = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index+1) + ')'); var cell_4 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index+1) + ')'); var cell_5 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index) + ')'); var cell_6 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index-1) + ')'); var cell_7 = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index-1) + ')'); var cell_8 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index-1) + ')'); W_radar(cell_1); W_radar(cell_2); W_radar(cell_3); W_radar(cell_4); W_radar(cell_5); W_radar(cell_6); W_radar(cell_7); W_radar(cell_8); }); $(".W_King").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); <!--BLACK KNIGHT--> $(document).ready(function(){ $(".B_Knight").mouseenter(function(){ var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); var cell_1 = $('#ChessBoardTbl tr:eq(' + (row_index-2) + ') td:eq(' + (col_index+1) + ')'); var cell_2 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index+2) + ')'); var cell_3 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index+2) + ')'); var cell_4 = $('#ChessBoardTbl tr:eq(' + (row_index+2) + ') td:eq(' + (col_index+1) + ')'); var cell_5 = $('#ChessBoardTbl tr:eq(' + (row_index+2) + ') td:eq(' + (col_index-1) + ')'); var cell_6 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index-2) + ')'); var cell_7 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index-2) + ')'); var cell_8 = $('#ChessBoardTbl tr:eq(' + (row_index-2) + ') td:eq(' + (col_index-1) + ')'); if (row_index==0) { B_radar(cell_2); B_radar(cell_3); B_radar(cell_4); B_radar(cell_5); B_radar(cell_6); B_radar(cell_7); } else if (col_index==1) { B_radar(cell_1); B_radar(cell_2); B_radar(cell_3); B_radar(cell_4); B_radar(cell_5); B_radar(cell_8); } else{ B_radar(cell_1); B_radar(cell_2); B_radar(cell_3); B_radar(cell_4); B_radar(cell_5); B_radar(cell_6); B_radar(cell_7); B_radar(cell_8); } }); $(".B_Knight").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); <!--WHITE KNIGHT--> $(document).ready(function(){ $(".W_Knight").mouseenter(function(){ var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); var cell_1 = $('#ChessBoardTbl tr:eq(' + (row_index-2) + ') td:eq(' + (col_index+1) + ')'); var cell_2 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index+2) + ')'); var cell_3 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index+2) + ')'); var cell_4 = $('#ChessBoardTbl tr:eq(' + (row_index+2) + ') td:eq(' + (col_index+1) + ')'); var cell_5 = $('#ChessBoardTbl tr:eq(' + (row_index+2) + ') td:eq(' + (col_index-1) + ')'); var cell_6 = $('#ChessBoardTbl tr:eq(' + (row_index+1) + ') td:eq(' + (col_index-2) + ')'); var cell_7 = $('#ChessBoardTbl tr:eq(' + (row_index-1) + ') td:eq(' + (col_index-2) + ')'); var cell_8 = $('#ChessBoardTbl tr:eq(' + (row_index-2) + ') td:eq(' + (col_index-1) + ')'); if (row_index==0) { W_radar(cell_2); W_radar(cell_3); W_radar(cell_4); W_radar(cell_5); W_radar(cell_6); W_radar(cell_7); } else if (col_index==1) { W_radar(cell_1); W_radar(cell_2); W_radar(cell_3); W_radar(cell_4); W_radar(cell_5); W_radar(cell_8); } else{ W_radar(cell_1); W_radar(cell_2); W_radar(cell_3); W_radar(cell_4); W_radar(cell_5); W_radar(cell_6); W_radar(cell_7); W_radar(cell_8); } }); $(".W_Knight").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); <!--BLACK ROOK--> $(document).ready(function(){ $(".B_Rook").mouseenter(function(){ // Piece Co-ordenates var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); //South for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //Remove highlights $(".B_Rook").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); }); <!--WHITE ROOK--> $(document).ready(function(){ $(".W_Rook").mouseenter(function(){ // Piece Co-ordenates var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); //South for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //Remove highlights $(".W_Rook").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); }); <!--BLACK BISHOP--> $(document).ready(function(){ $(".B_Bishop").mouseenter(function(){ // Piece Co-ordenates var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); //"\" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-East for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //Right up triangle else{ // South-East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-West for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //"/" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //Right up triangle else{ // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //Remove highlights $(".B_Bishop").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); }); <!--WHITE BISHOP--> $(document).ready(function(){ $(".W_Bishop").mouseenter(function(){ // Piece Co-ordenates var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); //"\" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-East for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //Right up triangle else{ // South-East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-West for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //"/" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //Right up triangle else{ // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //Remove highlights $(".W_Bishop").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); }); <!--BLACK QUEEN--> $(document).ready(function(){ $(".B_Queen").mouseenter(function(){ // Piece Co-ordenates var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); //"\" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-East for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //Right up triangle else{ // South-East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-West for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //"/" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //Right up triangle else{ // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } } //South for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //North for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (B_radar(cell)) { break; } } //Remove highlights $(".B_Queen").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); }); <!--WHITE QUEEN--> $(document).ready(function(){ $(".W_Queen").mouseenter(function(){ // Piece Co-ordenates var row_index = $(this).parent().parent().index(); var col_index = $(this).parent().index(); //"\" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-East for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //Right up triangle else{ // South-East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-West for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //"/" shaped cells // Left down triangle if ((col_index<6) && (row_index>2)) { // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //Right up triangle else{ // South-West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North-East for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } } //South for (var i = (1); i < (8-row_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index+i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //North for (var i = (1); i < (row_index+1); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index-i) + ') td:eq(' + (col_index) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //West for (var i = (1); i < (col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index-i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //East for (var i = (1); i < (9-col_index); i++) { var cell = $('#ChessBoardTbl tr:eq(' + (row_index) + ') td:eq(' + (col_index+i) + ')'); //Limits for the radar.radar(cell), true=friendly/enemy false=empty; if (W_radar(cell)) { break; } } //Remove highlights $(".W_Queen").mouseout(function(){ $("td").each (function () { var $cCell = $(this); $cCell.css("background-color",""); }); }); }); });
JavaScript
UTF-8
722
4.84375
5
[]
no_license
/* Strings These exercises will test your knowledge of string functions, conditionals, and arrays. For many of them, you will want to consult the JavaScript strings reference to find useful string methods to call. DrEvil Create a function called DrEvil. It should take a single argument, an amount, and return ' dollars', except it will add '(pinky)' at the end if the amount is 1 million. For example: DrEvil(10): 10 dollars DrEvil(1000000): 1000000 dollars (pinky) */ console.log('Is there anybody out there?'); const drEvil = function (amount) { if (amount == 1000000) { console.log(amount + ' dollars (pinky)'); } else { console.log(amount + ' dollars'); } } drEvil(10); drEvil(1000000);
Java
UTF-8
461
1.726563
2
[]
no_license
package my.spring.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @EnableEurekaClient //启动EnableEureka客户端,进行服务注册 @SpringBootApplication public class TestApplication01 { public static void main( String[] args ) { SpringApplication.run(TestApplication01.class,args); } }
TypeScript
UTF-8
374
3.5
4
[]
no_license
let data: number | string data = '42' data = 10 interface ICar { color: string model: string topSpeed?: number // optional property } const car1: ICar = { color: 'blue', model: 'bmw' } const car2: ICar ={ color: 'red', model: 'mercedes', topSpeed: 100 } const multiply = (x: number, y: number): string => { return (x*y).toString() }
Java
UTF-8
3,722
2.1875
2
[]
no_license
package xyz.pokeemon; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import com.google.android.material.bottomnavigation.BottomNavigationView; import xyz.pokeemon.connection.home.HomeFragment; import xyz.pokeemon.model.User; import xyz.pokeemon.shop.ShopFragment; import xyz.pokeemon.connection.SignInFragment; import xyz.pokeemon.team.TeamFragment; import xyz.pokeemon.radar.RadarFragment; public class MainActivity extends AppCompatActivity { public static User user; private View decorView; private Fragment selectedFragment; private BottomNavigationView bottomNavigationView; //Event to configure each button of navigation bar private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { selectedFragment = null; switch(item.getItemId()){ case R.id.ic_radar: selectedFragment = new RadarFragment(); break; case R.id.ic_creatures: selectedFragment = new TeamFragment(); break; case R.id.ic_shop: selectedFragment = new ShopFragment(); break; case R.id.ic_account: if(user==null){ selectedFragment = new SignInFragment(); }else{ selectedFragment = new HomeFragment(); } break; } getSupportFragmentManager().beginTransaction().replace( R.id.fl_wrapper, selectedFragment) .commit(); return true; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Apply the method to hide bars decorView = getWindow().getDecorView(); decorView.setOnSystemUiVisibilityChangeListener(visibility -> { if(visibility==0){ decorView.setSystemUiVisibility(hideSystemBar()); } }); //Search navbar by ID and set listener to each button bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(navListener); bottomNavigationView.setSelectedItemId(R.id.ic_radar); } //Call when this activity is running @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if(hasFocus){ decorView.setSystemUiVisibility(hideSystemBar()); } } //Called when the activity is create to hide the system bar private int hideSystemBar(){ return View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN |View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
JavaScript
UTF-8
619
2.734375
3
[]
no_license
class Drop{ constructor(x, y,) { var options = { 'restitution':1, 'friction':1 } this.body=Bodies.rectangle(x,y,2,2,options) this.width=2; this.height=2; World.add(world,this.body) } updateY(){ if(this.body.position.y > height){ Matter.Body.setPosition(this.body, {x:random(0,400), y:random(0,400)}) } } display(){ fill("red") ellipseMode(RADIUS) ellipse(this.body.position.x,this.body.position.y,this.width,this.height) } }
TypeScript
UTF-8
693
2.625
3
[]
no_license
import { getModule, VuexModule } from 'vuex-module-decorators' declare type ConstructorOf<C> = { new (...args: any[]): C } /** * Получить модуль vuex-decarator для работы с Vuex */ export function getVuexDecaratorModuleByWindow<T extends VuexModule>( vuexModule: ConstructorOf<T> ): T { if (!process.browser) throw new Error(` Доступ к модулю через window.$nuxt.$store возможен только на стороне клиента. Необходим чтобы вызывать модули внутри друг друга. `) const { $nuxt: { $store } } = window as any return getModule(vuexModule, $store) }
Java
UTF-8
1,007
2.0625
2
[]
no_license
package com.cloudconfig.client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class ClientApplication { public static void main(String[] args) { SpringApplication.run(ClientApplication.class, args); } @Autowired public void setEnv(Environment e) { System.out.println(e.getProperty("user.role")); } } @RefreshScope @RestController class ClientController { @Value("${user.role:Config server is not working}") private String userRole; @GetMapping("/userRoles") public String getUserRole(){ return this.userRole; } }
PHP
UTF-8
1,022
2.53125
3
[]
no_license
<?php if( $_SERVER['REQUEST_METHOD']=='POST' ) { $student_id = $_POST['student_id']; $branch = $_POST['branch']; $f = $_POST['f']; $password = $_POST['password']; $question_one =$_POST['question_one']; $question_two= $_POST['question_two']; $answer_one=$_POST['answer_one']; $answer_two=$_POST['answer_two']; $student_name=$_POST['student_name']; define('HOST','127.0.0.1'); define('USER','u707236822_saifu'); define('PASS','iamsoangry6'); define('DB','u707236822_imfun'); $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); $sql = "UPDATE add_student SET password=$password,question_one=$question_one,question_two=$question_two,answer_one='".$answer_one."',answer_two='".$answer_two."',f=$f WHERE student_name='".$student_name."'"; if(mysqli_query($con,$sql)){ echo "Successfully Updated"; }else{ echo "Could not Update"; } }else{ echo 'error'; }
Java
UTF-8
594
2.1875
2
[]
no_license
package com.db.bex.dbTrainingEnroll.dao; import com.db.bex.dbTrainingEnroll.entity.Rating; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface RatingRepository extends JpaRepository<Rating, Long> { @Query("SELECT avg(r.rating) FROM Rating r " + "WHERE r.training.id = ?1") Double getRating(Long trainingId); Rating findByTrainingId(Long training_id); Rating findByTrainingIdAndUserId(Long training_id, Long user_id); }
Java
UTF-8
6,193
2.140625
2
[ "MIT" ]
permissive
package com.example.rodrigo.smartcar; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import org.w3c.dom.Document; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class MapsActivity extends FragmentActivity { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private CameraUpdate mCamera; private ObjectLayer auto1; private ObjectLayer auto2; private ObjectLayer auto3; private ObjectLayer auto4; private ObjectLayer auto5; private ObjectLayer ruta2; private ObjectLayer ruta3; private List<ObjectLayer> layerManager; private DbHelper dataBase; private int[] markersStyles = {R.drawable.carrochico, R.drawable.carrochico, R.drawable.carrochico}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_conteiner); try { init(); } catch (SQLException e) { e.printStackTrace(); } setUpMapIfNeeded(); } private void init() throws SQLException { layerManager = new ArrayList<ObjectLayer>(); dataBase = new DbHelper(this); dataBase.open(); /* dataBase.addAuto("1", "BMW", "Mini", "TTA2529", "100", "19.052137", "-98.285880", "1"); dataBase.addAuto("2", "BMW", "Mini", "TAY1069", "95", "19.052218", "-98.279743", "1"); dataBase.addAuto("3", "BMW", "Mini", "TMM9901", "97", "19.057207", "-98.283820", "1"); dataBase.addAuto("4", "BMW", "Mini", "TTT5555", "98", "19.052482", "-98.284399", "1"); dataBase.addAuto("5", "BMW", "Mini", "TYE4820", "100", "19.054104", "-98.290107", "1"); dataBase.addUsuario("1", "Erick", "Lopez", "Guajardo", "2222009988", "eirkc@gmail.com", "1", "0000111122223333", "000"); dataBase.addUsuario("1", "Rodrigo", "Santoyo", "Rabadan", "2222112233", "rodrigo@gmail.com", "0", "1111222233334444", "111"); dataBase.addUsuario("1", "Samuel", "Quiroz", "Garcia", "2222334455", "samuel@gmail.com", "0", "2222333344445555", "222"); dataBase.addReservacion("2", "4", "1", "14:00", "14:15"); dataBase.addRenta("2", "4", "1", "34", "119"); */ auto1 = new ObjectLayer(dataBase.getAllAutos()); //ruta2 = new ObjectLayer(dataBase.regresaRuta(2), "2"); //ruta3 = new ObjectLayer(dataBase.regresaRuta(3), "3"); layerManager.add(auto1); //layerManager.add(ruta2); Log.e("SIZE:", String.valueOf(auto1.getSize())); //layerManager.add(ruta3); //Log.e("SIZE:", String.valueOf(ruta3.getSize())); dataBase.close(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { mMap.setMyLocationEnabled(true); // mMap.setIndoorEnabled(true); mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition cameraPosition) { Log.d("ZOOM", String.valueOf(cameraPosition.zoom)); if (cameraPosition.zoom > 14){ drawMakers(); } if (cameraPosition.zoom < 13){ eraseMakers(); } } }); setUpMap(); } } } private void drawMakers(){ for (int i=0; i<layerManager.size(); i++) { double lat= new Double( layerManager.get(i).getAuto(i).longitud); double longi= new Double( layerManager.get(i).getAuto(i).estado); Log.e("LAT:", String.valueOf(lat)); Log.e("LONG:", String.valueOf(longi)); // Log.e("IIIIIIII:", String.valueOf(i)); LatLng objectLatLng = new LatLng(lat, longi); mMap.addMarker(new MarkerOptions().position(new LatLng(lat,longi)).icon(BitmapDescriptorFactory.fromResource(markersStyles[i])).snippet(layerManager.get(i).snippet)); } } private void eraseMakers(){ mMap.clear(); } private void setUpMap() { //mMap.addMarker(new MarkerOptions().position(new LatLng(52.360021, 4.885174)).title("Rijksmuseum").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)).snippet("Rijksmuseum")); mCamera= CameraUpdateFactory.newLatLngZoom(new LatLng(52.357322, 4.881612),15); mMap.animateCamera(mCamera); mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { changeActivity(marker); return true; } }); } private void changeActivity(Marker marker){ Intent intent = new Intent(MapsActivity.this, CompActivity.class); intent.putExtra("ruta", marker.getTitle()); startActivity(intent); } }
Python
UTF-8
13,418
2.6875
3
[]
no_license
import random import math import matplotlib.pyplot as plt import numpy as np def cria_matriz(n_linhas, n_colunas, valor): matriz = [] for l in range(n_linhas): linha = [] for c in range(n_colunas): linha.append(valor) matriz.append(linha) return matriz exemplo_1 = np.array([[random.uniform(-0.1, 0.1), random.uniform(0.9, 1.1)]for _ in range(50)]) exemplo_2 = np.array([[random.uniform(0.9, 1.1), random.uniform(-0.1, 0.1)]for _ in range(50)]) exemplo_3 = np.array([[random.uniform(0.9, 1.1), random.uniform(0.9, 1.1)]for _ in range(50)]) exemplo_4 = np.array([[random.uniform(-0.1, 0.1), random.uniform(-0.1, 0.1)]for _ in range(50)]) dataset = np.zeros((200, 3)) for l in range(50): for c in range(2): dataset[l][c] = exemplo_1[l][c] dataset[l][2] = 1 for l in range(50): for c in range(2): dataset[l+50][c] = exemplo_2[l][c] dataset[l+50][2] = 1 for l in range(50): for c in range(2): dataset[l+100][c] = exemplo_3[l][c] dataset[l+100][2] = 1 for l in range(50): for c in range(2): dataset[l+150][c] = exemplo_4[l][c] dataset[l+150][2] = 2 vet_atr_ini = dataset classes = 3 amostras = 200 treino = 150 teste = amostras - treino div = math.trunc(treino/classes) quant_atr = 2 vet_atr_ini2 = np.zeros((amostras, 2)) vet_treino = cria_matriz(treino, quant_atr+1, 0) vet_teste = cria_matriz(teste, quant_atr, 0) vet_comp = cria_matriz(treino, quant_atr+1, 0) vet_norm2 = cria_matriz(amostras, quant_atr, 'N') vet_norm = cria_matriz(quant_atr, amostras, 'N') vet_atr_trans = cria_matriz(quant_atr, amostras, 0) vet_atr = cria_matriz(amostras, quant_atr+1, 0) num_real = 50 acuracia = 0 vet_acuracia_graph = cria_matriz(1, num_real, 0) acc = float = 0 matriz_confusao = cria_matriz(4,4,0) for l in range(amostras): for c in range(quant_atr): vet_atr_ini2[l][c] = vet_atr_ini2[l][c] for l in range(amostras): for c in range(quant_atr): vet_norm[c][l] = vet_atr_ini[l][c] for l in range(quant_atr): for c in range(amostras): vet_norm2[c][l] = vet_norm[l][c] for l in range(amostras): for c in range(quant_atr): minimo = min(vet_norm[c]) maximo = max(vet_norm[c]) vet_atr[l][c] = (vet_norm2[l][c] - minimo)/(maximo - minimo) for l in range(amostras): vet_atr[l][quant_atr] = vet_atr_ini[l][quant_atr] for realizacoes in range (num_real): random.shuffle(vet_atr) for l in range(treino): #MATRIZ COM 100 AMOSTRAS PARA TREINO for c in range(quant_atr+1): vet_treino[l][c] = vet_atr[l][c] for l in range(treino, amostras): #MATRIZ COM 50 AMOSTRAS PARA TESTE SEM O CLASSIFICADOR for c in range(quant_atr): vet_teste[l-treino][c] = vet_atr[l][c] for l in range(treino, amostras): #MATRIZ PARA REALIZAR A COMPARAÇÃO COM A MATRIZ TESTADA for c in range(quant_atr+1): vet_comp[l-treino][c] = vet_atr[l][c] for l in range(quant_atr): for c in range(treino): vet_atr_trans[l][c] = vet_treino[c][l] x = y = z = int = 0 for l in range(treino): if vet_treino[l][quant_atr] == 1: x += 1 elif vet_treino[l][quant_atr] == 2: y += 1 elif vet_treino[l][quant_atr] == 3: z += 1 vet_classe1 = cria_matriz(x, quant_atr, 0) vet_classe2 = cria_matriz(y, quant_atr, 0) vet_classe3 = cria_matriz(z, quant_atr, 0) x=0 y=0 z=0 for l in range(treino): if vet_treino[l][quant_atr] == 1: vet_classe1[x][0] = vet_treino[l][0] vet_classe1[x][1] = vet_treino[l][1] x += 1 if vet_treino[l][quant_atr] == 2: vet_classe2[y][0] = vet_treino[l][0] vet_classe2[y][1] = vet_treino[l][1] y += 1 elif vet_treino[l][quant_atr] == 3: vet_classe3[z][0] = vet_treino[l][0] vet_classe3[z][1] = vet_treino[l][1] z += 1 vet_classe1_transp = cria_matriz(quant_atr, x, 0) vet_classe2_transp = cria_matriz(quant_atr, y, 0) vet_classe3_transp = cria_matriz(quant_atr, z, 0) for l in range(x): for c in range(quant_atr): vet_classe1_transp[c][l] = vet_classe1[l][c] for l in range(y): for c in range(quant_atr): vet_classe2_transp[c][l] = vet_classe2[l][c] for l in range(z): for c in range(quant_atr): vet_classe3_transp[c][l] = vet_classe3[l][c] media1 = cria_matriz(1, quant_atr, 0) for l in range(quant_atr): media1[0][l] = np.mean(vet_classe1_transp[l]) media2 = cria_matriz(1, quant_atr, 0) for l in range(quant_atr): media2[0][l] = np.mean(vet_classe2_transp[l]) media3 = cria_matriz(1, quant_atr, 0) for l in range(quant_atr): media3[0][l] = np.mean(vet_classe3_transp[l]) classe1 = 0 classe2 = 0 classe3 = 0 euc1 = euc2 = euc3 = 0 vet_euc1 = cria_matriz(1, teste, 0) vet_euc2 = cria_matriz(1, teste, 0) vet_euc3 = cria_matriz(1, teste, 0) #random.shuffle(vet_atr) for l in range(teste): euc1 = 0 euc1 += math.pow(media1[0][0] - vet_teste[l][0], 2) euc1 += math.pow(media1[0][1] - vet_teste[l][1], 2) euc2 = 0 euc2 += math.pow(media2[0][0] - vet_teste[l][0], 2) euc2 += math.pow(media2[0][1] - vet_teste[l][1], 2) euc3 = 0 euc3 += math.pow(media3[0][0] - vet_teste[l][0], 2) euc3 += math.pow(media3[0][1] - vet_teste[l][1], 2) vet_euc1[0][l] = euc1 vet_euc2[0][l] = euc2 vet_euc3[0][l] = euc3 a = 0 acuracia = 0 for l in range(teste): if (vet_euc1[0][l] < vet_euc2[0][l]) and (vet_euc1[0][l] < vet_euc3[0][l]): classe = 1 if classe == vet_comp[l][quant_atr]: a += 1 if (vet_euc2[0][l] < vet_euc1[0][l]) and (vet_euc2[0][l] < vet_euc3[0][l]): classe = 2 if classe == vet_comp[l][quant_atr]: a += 1 #matriz_confusao[vet_comp[l][quant_atr]][classe] += 1 acuracia = (a/teste)*100 acc += (a/teste)*100 vet_acuracia_graph[0][realizacoes] = acuracia print(acuracia) acuracia_media = (acc/num_real) print('A ACURÁCIA MÉDIA FOI DE:') print(acuracia_media) del(matriz_confusao[0]) del(matriz_confusao[0][0]) del(matriz_confusao[1][0]) del(matriz_confusao[2][0]) print('\n\nMATRIZ DE CONFUSÃO\n\n') for l in range(3): for c in range(3): print(f'{(matriz_confusao[l][c]/(teste*num_real)*100):.2f} ', end = '') print() ###################################################################################### ## GRÁFICO DE SUPERFÍCIE ########################################################### intervalo = 0.005 f_inf = 0 f_sup = 1 + intervalo faixa = np.arange(f_inf, f_sup, intervalo) fator = f_sup / intervalo atr1 = [] atr2 = [] for l in range(len(faixa)): atr1.extend([faixa[l]]*math.trunc(fator)) for l in range(len(faixa)): for c in range(math.trunc(fator)): atr2.extend([faixa[c]]) p_grid = np.zeros((len(atr1), 2)) p_grid_resp = np.zeros((len(atr1), 3)) for l in range(len(atr1)): p_grid[l][0] = atr1[l] for l in range(len(atr1)): p_grid[l][1] = atr2[l] class_graph = np.zeros((len(atr1), 1)) ####################################################################################### ### CLASSIFICAÇÃO ################ vetor_dist = np.zeros((len(atr1), amostras)) men_graph = np.zeros((len(atr1), 1)) men_transp_graph = np.zeros((1, len(atr1))) ord_men_graph = np.zeros((len(atr1), 1)) ord_vetor_dist_graph = np.zeros((len(atr1), amostras)) vet_atr_graph = np.zeros((amostras, quant_atr)) for l in range(amostras): for c in range(quant_atr): vet_atr_graph[l][c] = vet_atr[l][c] ## DISTÂNCIA vetor_dist1 = np.zeros((1, len(atr1))) vetor_dist2 = np.zeros((1, len(atr1))) vetor_dist3 = np.zeros((1, len(atr1))) for l in range(len(atr1)): euc1 = 0 euc1 += math.pow(media1[0][0] - p_grid[l][0], 2) euc1 += math.pow(media1[0][1] - p_grid[l][1], 2) euc2 = 0 euc2 += math.pow(media2[0][0] - p_grid[l][0], 2) euc2 += math.pow(media2[0][1] - p_grid[l][1], 2) euc3 = 0 euc3 += math.pow(media3[0][0] - p_grid[l][0], 2) euc3 += math.pow(media3[0][1] - p_grid[l][1], 2) vetor_dist1[0][l] = euc1 vetor_dist2[0][l] = euc2 vetor_dist3[0][l] = euc3 a = 0 acuracia = 0 classe1 = 0 classe2 = 0 classe3 = 0 for l in range(len(atr1)): if (vetor_dist1[0][l] < vetor_dist2[0][l]): classe = 1 p_grid_resp[l][2] = classe if (vetor_dist2[0][l] < vetor_dist1[0][l]): classe = 2 p_grid_resp[l][2] = classe for l in range(len(atr1)): class_graph[l][0] = p_grid_resp[l][2] from matplotlib.colors import ListedColormap quant_a = 0 quant_b = 0 for l in range(len(vet_treino)): if vet_treino[l][quant_atr] == 1: quant_a += 1 elif vet_treino[l][quant_atr] == 2: quant_b += 1 a = np.zeros((quant_a, 2)) b = np.zeros((quant_b, 2)) x = 0 y = 0 for l in range(len(vet_treino)): if vet_treino[l][quant_atr] == 1: a[x][0] = vet_treino[l][0] a[x][1] = vet_treino[l][1] x+=1 elif vet_treino[l][quant_atr] == 2: b[y][0] = vet_treino[l][0] b[y][1] = vet_treino[l][1] y+=1 quant_a_t = 0 quant_b_t = 0 for l in range(len(vet_comp)): if vet_comp[l][quant_atr] == 1: quant_a_t += 1 elif vet_comp[l][quant_atr] == 2: quant_b_t += 1 a_t = np.zeros((quant_a_t, 2)) b_t = np.zeros((quant_b_t, 2)) x = 0 y = 0 w = 0 for l in range(len(vet_comp)): if vet_comp[l][quant_atr] == 1: a_t[x][0] = vet_comp[l][0] a_t[x][1] = vet_comp[l][1] x+=1 elif vet_comp[l][quant_atr] == 2: b_t[y][0] = vet_comp[l][0] b_t[y][1] = vet_comp[l][1] y+=1 #cmap_bold = ListedColormap(['#FF0000', '#00FF00']) #cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA']) #plt.scatter(p_grid[:, 0], p_grid[:, 1], c=class_graph[:, 0], cmap=cmap_light) #plt.scatter(vet_atr_graph[:, 0], vet_atr_graph[:, 1], c=dataset[:, 2], cmap=cmap_bold) cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) plt.xlabel('ATRIBUTO A') plt.ylabel('ATRIBUTO B') plt.scatter(p_grid[:, 0], p_grid[:, 1], c=class_graph[:, 0], cmap=cmap_light) plt.scatter(np.array(vet_atr_graph)[:, 0], np.array(vet_atr_graph)[:, 1], c=np.array(vet_atr)[:, 2], cmap=cmap_bold) #plt.scatter (np.array(a)[:, 0], np.array(a)[:, 1], s=30, edgecolor = 'k', c='red', label='ATRIBUTO A TREINO') #plt.scatter (np.array(b)[:, 0], np.array(b)[:, 1], s=30, edgecolor = 'k', c='blue', label='ATRIBUTO B TREINO') #plt.scatter (np.array(a_t)[:, 0], np.array(a_t)[:, 1], s=30, edgecolor = 'k', c='orange', label='ATRIBUTO A TESTE') #plt.scatter (np.array(b_t)[:, 0], np.array(b_t)[:, 1], s=30, edgecolor = 'k', c='black', label='ATRIBUTO B TESTE') #plt.legend() #cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) #plt.scatter(vet_atr_graph[:, 0], vet_atr_graph[:, 1], c=vet_atr_graph[:, 2], cmap=cmap_light)
Python
UTF-8
444
3.796875
4
[]
no_license
""" Пользователь вводит слово Программа отвечает, палиндром или нет !!! Регистр букв не должен влиять на ответ Шалаш = шалаш = шАлАш """ word = input("скажи слово ").lower() if word == word[:: -1]: print("это является палиндромом") else: print("не является палиндромом")
Java
UTF-8
4,108
1.789063
2
[]
no_license
package com.tencent.mm.plugin.gallery.stub; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Parcel; public abstract class a$a extends Binder implements a { public a$a() { attachInterface(this, "com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); } public static a B(IBinder paramIBinder) { if (paramIBinder == null) paramIBinder = null; while (true) { return paramIBinder; IInterface localIInterface = paramIBinder.queryLocalInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); if ((localIInterface != null) && ((localIInterface instanceof a))) paramIBinder = (a)localIInterface; else paramIBinder = new a.a.a(paramIBinder); } } public IBinder asBinder() { return this; } public boolean onTransact(int paramInt1, Parcel paramParcel1, Parcel paramParcel2, int paramInt2) { int i = 0; boolean bool1 = true; boolean bool2; switch (paramInt1) { default: bool2 = super.onTransact(paramInt1, paramParcel1, paramParcel2, paramInt2); case 1598968902: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: } while (true) { return bool2; paramParcel2.writeString("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); bool2 = bool1; continue; paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); aK(paramParcel1.readInt(), paramParcel1.readString()); paramParcel2.writeNoException(); bool2 = bool1; continue; paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); bCv(); paramParcel2.writeNoException(); bool2 = bool1; continue; paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); paramInt1 = Nd(); paramParcel2.writeNoException(); paramParcel2.writeInt(paramInt1); bool2 = bool1; continue; paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); String str1 = paramParcel1.readString(); String str2 = paramParcel1.readString(); if (paramParcel1.readInt() != 0) { bool2 = true; label220: paramInt1 = paramParcel1.readInt(); if (paramParcel1.readInt() == 0) break label265; } label265: for (boolean bool3 = true; ; bool3 = false) { a(str1, str2, bool2, paramInt1, bool3); paramParcel2.writeNoException(); bool2 = bool1; break; bool2 = false; break label220; } paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); paramInt1 = Nb(); paramParcel2.writeNoException(); paramParcel2.writeInt(paramInt1); bool2 = bool1; continue; paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); paramInt1 = Na(); paramParcel2.writeNoException(); paramParcel2.writeInt(paramInt1); bool2 = bool1; continue; paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); if (paramParcel1.readInt() != 0); for (bool2 = true; ; bool2 = false) { bool2 = hC(bool2); paramParcel2.writeNoException(); paramInt1 = i; if (bool2) paramInt1 = 1; paramParcel2.writeInt(paramInt1); bool2 = bool1; break; } paramParcel1.enforceInterface("com.tencent.mm.plugin.gallery.stub.Gallery_AIDL"); paramInt1 = ND(paramParcel1.readString()); paramParcel2.writeNoException(); paramParcel2.writeInt(paramInt1); bool2 = bool1; } } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes8-dex2jar.jar * Qualified Name: com.tencent.mm.plugin.gallery.stub.a.a * JD-Core Version: 0.6.2 */
Python
UTF-8
424
3.515625
4
[]
no_license
class Donkey: def say(self): print("I'm donkey") def walk(self): print("fjkghdig") class Horse: def say(self): print(" I'm horse") def run(self): print("jhgjhkj") class Moul(Donkey, Horse): def hi(self): print("Hi") def say(self): print("I'm moul") donkey = Donkey() horse = Horse() moul = Moul() donkey.say() horse.say() moul.hi() moul.say() moul.walk() moul.run()
C++
UTF-8
1,083
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define pii pair<int, int> #define fi first.first #define se first.second #define th second vector<int> par(101); bool cmp(pair<pii, int> a, pair<pii, int> b){ return (a.th < b.th); } int getpar(int a){ if (par[a] == a) return a; int x = getpar(par[a]); par[a] = x; return x; } void join(int a, int b){ int parA = getpar(a); int parB = getpar(b); par[parA] = parB; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; vector<pair<pii, int>> edge; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ int x; cin >> x; if (j > i){ edge.pb(mp(mp(i,j), x)); } } } int sz = edge.size(); sort(edge.begin(), edge.end(), cmp); int cnt = 0, sum = 0; for (int i = 0; i < n; i++) par[i] = i; for (int i = 0; i < sz; i++){ int a = edge[i].fi, b = edge[i].se; if (getpar(a)!=getpar(b)){ join(a,b); cnt++; sum += edge[i].th; if (cnt == n-1) break; } } cout << sum << endl; return 0; }
Markdown
UTF-8
862
2.703125
3
[]
no_license
# Article 32-1 Les attachés des systèmes d'information et de communication sont principalement affectés à l'administration centrale et chargés des fonctions d'ingénierie, d'expertise et d'encadrement dans les domaines du chiffre, des communications et de l'informatique. A ce titre, ils assurent ou coordonnent les études, conduisent les travaux relatifs à la réalisation, au déploiement, à l'exploitation et à la sécurité des systèmes d'information et de communication et, le cas échéant, encadrent les personnels qui y participent. Lorsqu'ils sont affectés à l'étranger, ils peuvent être appelés, au niveau régional, à coordonner les travaux de déploiement, d'exploitation et de maintenance des systèmes d'information et de communication et, dans leur poste d'affectation, à encadrer les personnels qui participent à ces travaux.
Python
UTF-8
3,942
2.71875
3
[]
no_license
import datetime import os.path import pickle from googleapiclient.discovery import build from googleapiclient import errors SCOPES = ('https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/fitness.activity.read') def build_service(service_name, version, pickle_path=None): """Shows basic usage of the Docs API. Prints the title of a sample document. """ if not pickle_path: home_dir = os.path.expanduser('~') pickle_path = os.path.join(home_dir, '.credentials', 'token.pkl') creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(pickle_path): with open(pickle_path, 'rb') as token: creds = pickle.load(token) service = build(service_name, version, credentials=creds) return service def list_mails_matching_query(service, query=''): """List all Messages of the user's mailbox matching the query. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. query: String used to filter messages returned. Eg.- 'from:user@some_domain.com' for Messages from a particular sender. Returns: List of Messages that match the criteria of the query. Note that the returned list contains Message IDs, you must use get with the appropriate ID to get the details of a Message. """ try: response = service.users().messages().list(userId='me', q=query).execute() messages = [] if 'messages' in response: messages.extend(response['messages']) while 'nextPageToken' in response: page_token = response['nextPageToken'] response = service.users().messages().list(userId='me', q=query, pageToken=page_token).execute() messages.extend(response['messages']) return messages except errors.HttpError as error: print('An error occurred: %s' % error) return [] def get_message(service, msg_id): """Get a Message with given ID. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. msg_id: The ID of the Message required. Returns: A Message. """ try: message = service.users().messages().get(userId='me', id=msg_id).execute() return message except errors.HttpError as error: print('An error occurred: %s' % error) def get_calendar_by_name(service, name): page_token = None while True: calendar_list = service.calendarList().list(pageToken=page_token).execute() for calendar_list_entry in calendar_list['items']: if calendar_list_entry['summary'] == name: return calendar_list_entry['id'] page_token = calendar_list.get('nextPageToken') if not page_token: break return None def get_calendar_entries_by_query(service, query, num_hours, calendar_name): # Find the right calendar calendar_id = get_calendar_by_name(service, calendar_name) # Compute some timestamps utcnow = datetime.datetime.utcnow() ndays = utcnow - datetime.timedelta(hours=num_hours) # 'Z' indicates UTC time utcnow = utcnow.isoformat() + 'Z' ndays = ndays.isoformat() + 'Z' events_result = service.events().list( calendarId=calendar_id, timeMin=ndays, timeMax=utcnow, q=query, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) return events
Java
UTF-8
3,936
2.453125
2
[]
no_license
package moe.cnkirito.benchmark.dubbo.codec; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import moe.cnkirito.benchmark.dubbo.common.Bytes; import moe.cnkirito.benchmark.dubbo.model.DubboRpcResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; /** * This class mainly hack the {@link io.netty.handler.codec.ByteToMessageDecoder} to provide batch submission capability. * This can be used the same way as ByteToMessageDecoder except the case your following inbound handler may get a decoded msg, * which actually is an array list, then you can submit the list of msgs to an executor to process. For example * <pre> * if (msg instanceof List) { * processorManager.getDefaultExecutor().execute(new Runnable() { * @Override * public void run() { * // batch submit to an executor * for (Object m : (List<?>) msg) { * RpcCommandHandler.this.process(ctx, m); * } * } * }); * } else { * process(ctx, msg); * } * </pre> * You can check the method {@link AbstractBatchDecoder#channelRead(ChannelHandlerContext, Object)} ()} * to know the detail modification. */ public class DubboRpcBatchDecoder extends AbstractBatchDecoder{ // header length. protected static final int HEADER_LENGTH = 16; protected static final byte FLAG_EVENT = (byte) 0x20; private static final Logger logger = LoggerFactory.getLogger(DubboRpcBatchDecoder.class); @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) { try { do { int savedReaderIndex = byteBuf.readerIndex(); Object msg = null; try { msg = decode2(byteBuf); } catch (Exception e) { throw e; } if (msg == DubboRpcBatchDecoder.DecodeResult.NEED_MORE_INPUT) { byteBuf.readerIndex(savedReaderIndex); break; } list.add(msg); } while (byteBuf.isReadable()); } finally { if (byteBuf.isReadable()) { byteBuf.discardReadBytes(); } } //list.add(decode2(byteBuf)); } enum DecodeResult { NEED_MORE_INPUT, SKIP_INPUT } /** * Demo为简单起见,直接从特定字节位开始读取了的返回值,demo未做: * 1. 请求头判断 * 2. 返回值类型判断 * * @param byteBuf * @return */ private Object decode2(ByteBuf byteBuf) { int savedReaderIndex = byteBuf.readerIndex(); int readable = byteBuf.readableBytes(); if (readable < HEADER_LENGTH) { return DubboRpcBatchDecoder.DecodeResult.NEED_MORE_INPUT; } byte[] header = new byte[HEADER_LENGTH]; byteBuf.readBytes(header); int len = Bytes.bytes2int(header,12); int tt = len + HEADER_LENGTH; if (readable < tt) { return DubboRpcBatchDecoder.DecodeResult.NEED_MORE_INPUT; } byteBuf.readerIndex(savedReaderIndex); byte[] data = new byte[tt]; byteBuf.readBytes(data); // HEADER_LENGTH + 1,忽略header & Response value type的读取,直接读取实际Return value // dubbo返回的body中,前后各有一个换行,去掉 byte[] subArray = Arrays.copyOfRange(data, HEADER_LENGTH + 2, data.length - 1); long requestId = Bytes.bytes2long(data, 4); // logger.info("consumer-agent发送dubbo请求编号:{}", requestId); DubboRpcResponse response = new DubboRpcResponse(); response.setRequestId(requestId); response.setBytes(subArray); return response; } }
Python
UTF-8
409
3.125
3
[]
no_license
import matplotlib.pyplot as plt import random import math tt = [ 2 * math.pi * random.random() for q in range( 100 ) ] xx = [ math.cos( tt[q] ) for q in range( len( tt ) ) ] yy = [ math.sin( tt[q] ) for q in range( len( tt ) ) ] plt.scatter( xx, yy, label='circumference', color='c', s=100, marker='o' ) plt.xlabel( 'x' ) plt.ylabel( 'y' ) plt.title( 'Interesting graph :o)' ) plt.legend() plt.show()
Java
UTF-8
3,147
1.882813
2
[]
no_license
package com.infoklinik.rsvp.client.appt.view; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.infoklinik.rsvp.client.BaseView; import com.infoklinik.rsvp.client.ClientUtil; import com.infoklinik.rsvp.client.appt.presenter.interfaces.IReservationPatientInfoView; import com.infoklinik.rsvp.shared.ReservationBean; import com.infoklinik.rsvp.shared.Constant; import com.infoklinik.rsvp.shared.DoctorBean; import com.infoklinik.rsvp.shared.InstitutionBean; public class ReservationPatientInfoView extends BaseView implements IReservationPatientInfoView { private DialogBox dialogBox; @UiField TextBox verificationCodeTb; @UiField TextBox patientNameTb; @UiField RadioButton patientSexMaleRb; @UiField RadioButton patientSexFemaleRb; @UiField TextBox patientBirthYearTb; @UiField TextBox patientEmailTb; @UiField Button okBtn; @UiField Button cancelBtn; ReservationBean reservation; interface ModuleUiBinder extends UiBinder<Widget, ReservationPatientInfoView> {} private static ModuleUiBinder uiBinder = GWT.create(ModuleUiBinder.class); DoctorBean doctor; InstitutionBean institution; public void createView() { dialogBox = new DialogBox(); dialogBox.setStyleName("formDialog"); dialogBox.setWidget(uiBinder.createAndBindUi(this)); dialogBox.setText("Verifikasi No. Handphone"); } public Widget asWidget() { return dialogBox; } public Widget getRootWidget() { return dialogBox; } public ReservationBean getReservation() { reservation.setVerificationCode(ClientUtil.trim(verificationCodeTb.getValue())); reservation.setPatientName(ClientUtil.trim(patientNameTb.getValue())); reservation.setPatientSex(patientSexMaleRb.getValue() ? Constant.SEX_MALE : Constant.SEX_FEMALE); reservation.setPatientBirthYear(ClientUtil.trim(patientBirthYearTb.getValue())); reservation.setPatientEmail(ClientUtil.trim(patientEmailTb.getValue())); return reservation; } public void setReservation(ReservationBean reservation) { this.reservation = reservation; verificationCodeTb.setText(Constant.EMPTY_STRING); } public void setOkBtnClickHandler(ClickHandler handler) { okBtn.addClickHandler(handler); } public void setCancelBtnClickHandler(ClickHandler handler) { cancelBtn.addClickHandler(handler); } public void show() { goToTop(); fadeOut(); patientSexMaleRb.setValue(true); dialogBox.center(); dialogBox.setPopupPosition(dialogBox.getPopupLeft(), 70); dialogBox.show(); fadeIn(); } public void hide() { fadeOut(); Timer timer = new Timer() { @Override public void run() { dialogBox.hide(); } }; timer.schedule(Constant.FADE_TIME); } }
C#
UTF-8
1,388
2.859375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MunOS { /// <summary> /// Thread execution priority. /// </summary> public enum MunPriority : byte { /// <summary> /// Highest priority - executed every FixedUpdate if possible. /// May use upto 50% of the total time available to the update. /// Suitable for autopilot - steering and throttling. /// </summary> Realtime, /// <summary> /// .NET callbacks, mostly from UI (e.g. Button.Click). /// These are usually generated by scripting engine /// (converting functions to callbacks and back). /// At least one is executed every other FixedUpdate, /// downto 40% mark (therefore upto 60% of total time if no Realtime). /// </summary> Callback, /// <summary> /// Low priority - executed only on low load /// (downto 60% mark which means only if Realtime+Callback did not already used 40%), /// but one at least every 10th FixedUpdate. /// </summary> Idle, /// <summary> /// Mixed priority - executed every FixedUpdate if possible, /// but after all the other priorities. The remaining time /// is divided between all main threads, until a threashold is reached. /// </summary> /// <remarks> /// Main threads can be reordered by the engine based on time used in last update. /// </remarks> Main, } }
Java
UTF-8
1,335
2.1875
2
[]
no_license
package com.qutu.talk.adapter; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.qutu.talk.R; import com.qutu.talk.bean.IncomeFragmentBean; import java.util.List; public class IncomeFragmentAdapter extends BaseQuickAdapter<IncomeFragmentBean.DataBean, BaseViewHolder> { private int tag; public IncomeFragmentAdapter(int layoutResId, @Nullable List<IncomeFragmentBean.DataBean> data, int tag) { super(layoutResId, data); this.tag = tag; } @Override protected void convert(@NonNull BaseViewHolder helper, IncomeFragmentBean.DataBean item) { if (tag == 0) { helper.setText(R.id.tv_title, item.getNickname() + "赠送 " + item.getGiftName() + "x" + item.getGiftNum()) .setText(R.id.tv_userid, item.getCreated_at()) .setText(R.id.btn_ok, "+" + item.getGiftPrice() + "钻石"); } else { helper.setText(R.id.tv_title, "赠送"+item.getNickname()+" "+ item.getGiftName() + "x" + item.getGiftNum()) .setText(R.id.tv_userid, item.getCreated_at()) .setText(R.id.btn_ok, "-" + item.getGiftPrice() + "金币"); } } }
Markdown
UTF-8
208
2.75
3
[]
no_license
# Nice-Input Simple and Easy to use labed input/select Nice-Input is a style to use label inside of input, instead use placeholder, when the user click on input, the label goes up e change his size to fit.
C++
UTF-8
605
2.859375
3
[]
no_license
// 2605Resort #include <iostream> #include <cstdio> #include <list> #include <iterator> using namespace std; int main() { list<int> order; list<int>::iterator itor; int n, input; cin >> n; cin >> input; order.push_back(1); for (int i = 2; i <= n; i++) { int index = 1; cin >> input; if (input) { for (itor = order.end(); itor != order.begin(); itor--, index++) { if (index == input) break; } order.insert(--itor, i); } else order.push_back(i); } for (itor = order.begin(); itor != order.end(); itor++) printf("%d ", *itor); printf("\n"); } /* 5 0 1 1 3 2 */
Python
UTF-8
5,616
2.921875
3
[]
no_license
#!/usr/bin/env python """ This is a script that walks through some of the basics of working with images with opencv in ROS. """ import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge import cv2 import numpy as np from std_msgs.msg import String from template_matcher import TemplateMatcher, compare_images class StreetSignRecognizer(object): """ This robot should recognize street signs """ def __init__(self): """ Initialize the street sign reocgnizer """ rospy.init_node('street_sign_recognizer') self.cv_image = None # the latest image from the camera self.hsv_image = None self.res_image = None self.mask = None self.cropped_sign = None self.bridge = CvBridge() # used to convert ROS messages to OpenCV cv2.namedWindow('video_window') rospy.Subscriber("/camera/image_raw", Image, self.process_image) self.signpub = rospy.Publisher('/predicted_sign', String, queue_size=10) self.prediction = "" #sets up slider bars for hue isolation #cv2.namedWindow('threshold_image') # current values work well for uturn and right, but poorly for left # values for left (20, 166, 139) increase error for uturn and right self.hsv_lb = np.array([25, 202, 186]) # hsv lower bound 20, 166, 139 25, 202, 186 26, 214, 167 [15, 225, 139 # cv2.createTrackbar('H lb', 'threshold_image', 0, 255, self.set_h_lb) # cv2.createTrackbar('S lb', 'threshold_image', 0, 255, self.set_s_lb) # cv2.createTrackbar('V lb', 'threshold_image', 0, 255, self.set_v_lb) self.hsv_ub = np.array([204, 255, 255]) # hsv upper bound 204, 255, 255 204, 255, 230 # cv2.createTrackbar('H ub', 'threshold_image', 0, 255, self.set_h_ub) # cv2.createTrackbar('S ub', 'threshold_image', 0, 255, self.set_s_ub) # cv2.createTrackbar('V ub', 'threshold_image', 0, 255, self.set_v_ub) # initialize template_matcher images = { "left": '../images/leftturn_box_small.png', "right": '../images/rightturn_box_small.png', "uturn": '../images/uturn_box_small.png' } self.tm = TemplateMatcher(images) def process_image(self, msg): """ Process image messages from ROS and stash them in an attribute called cv_image for subsequent processing """ self.cv_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding="bgr8") #convert to img hsv self.hsv_image = cv2.cvtColor(self.cv_image, cv2.COLOR_BGR2HSV) #create img mask for only yellow in hsv img self.mask = cv2.inRange(self.hsv_image, self.hsv_lb, self.hsv_ub) # Bitwise-AND mask and original image self.res_image = cv2.bitwise_and(self.cv_image,self.cv_image, mask= self.mask) left_top, right_bottom = self.sign_bounding_box() left, top = left_top right, bottom = right_bottom # crop bounding box region of interest self.cropped_sign = cv2.cvtColor(self.cv_image[top:bottom, left:right], cv2.COLOR_BGR2GRAY) # draw bounding box rectangle cv2.rectangle(self.cv_image, left_top, right_bottom, color=(0, 0, 255), thickness=5) def set_h_lb(self, val): """ set hue lower bound """ self.hsv_lb[0] = val def set_s_lb(self, val): """ set saturation lower bound """ self.hsv_lb[1] = val def set_v_lb(self, val): """ set value lower bound """ self.hsv_lb[2] = val def set_h_ub(self, val): """ set hue upper bound """ self.hsv_ub[0] = val def set_s_ub(self, val): """ set saturation upper bound """ self.hsv_ub[1] = val def set_v_ub(self, val): """ set value upper bound """ self.hsv_ub[2] = val def sign_bounding_box(self): """ Returns ------- (left_top, right_bottom) where left_top and right_bottom are tuples of (x_pixel, y_pixel) defining topleft and bottomright corners of the bounding box """ #use self.mask and boundingRect() to compute left_top and right_bottom bound = cv2.findNonZero(self.mask) (bx, by, bw, bh) = cv2.boundingRect(bound) left_top = (bx, by) right_bottom = (bx+bw, by+bh) return left_top, right_bottom def run(self): """ The main run loop sometimes throws errors, but if you try again it works""" r = rospy.Rate(10) while not rospy.is_shutdown(): if not self.cv_image is None: print "here" if not self.cropped_sign is None: pred = self.tm.predict(self.cropped_sign) predNum = pred[max(pred, key=pred.get)] #print predNum if (predNum > 0.75): self.prediction = max(pred, key=pred.get) print self.prediction print pred[self.prediction] if not self.prediction == "": self.signpub.publish(String(self.prediction)) # creates a window and displays the image for X milliseconds #cv2.imshow('video_window', self.cv_image) #cv2.imshow('masked_window', self.res_image) #cv2.imshow('hsv_window', self.hsv_image) cv2.waitKey(5) #print "there" r.sleep() if __name__ == '__main__': node = StreetSignRecognizer() node.run()
Ruby
UTF-8
1,317
2.9375
3
[ "MIT" ]
permissive
class RandomMoviePicker::Categories BASE_URL = "https://www.rottentomatoes.com" @@genres = {} @@years = {} def self.genres if @@genres == {} doc = Nokogiri::HTML(open("https://www.rottentomatoes.com/top/bestofrt/top_100_action__adventure_movies/")) doc.css(".btn-group.btn-primary-border-dropdown li a").each do |genre| @@genres[white_space_fix(genre.text)] = BASE_URL + genre.attribute("href").text end @@genres else @@genres end end def self.years if @@years == {} doc = Nokogiri::HTML(open("https://www.rottentomatoes.com/top/bestofrt/?year=2020")) doc.css(".btn-group.btn-primary-border-dropdown li a").map do |year| @@years[year.text.strip] = BASE_URL + year.attribute("href").text end @@years else @@years end end def self.random_category categories = [@@genres, @@years] categories.sample end def self.random_subcategory(category) category[category.keys[rand(category.length)]] end def self.white_space_fix(text) text.split("\n")[1].strip end #binding.pry end
PHP
UTF-8
2,952
3.171875
3
[ "MIT" ]
permissive
<?php if (isset($_POST['submit'])) { require '../config/db.config.php'; $error = 0; $score = 0; $age = $_POST['age']; $sex = $_POST['sex']; $body_temperature = $_POST['body-temperature']; $symptoms_1 = $_POST['symptoms1']; $symptoms_2 = $_POST['symptoms2']; // Body Temperature Score if (!empty($age) && !empty($sex) && !empty($body_temperature)) { if ($body_temperature > 99.5 || $body_temperature > 100.9) { $score += 2; } } else { ++$error; } // First Step Symptoms Score if (!empty($symptoms_1)) { $score += 3; if (count($symptoms_1) > 1) { $score += count($symptoms_1) - 1; } } // Second Step Symptoms Score if (!empty($symptoms_2)) { $score += count($symptoms_2) * 2; } // Checking Score & Redirecting to Result Page if ($score < 5) { if ($error) { echo 'Error'; } else { $result = 'Negative'; $sql = "INSERT INTO records (age, sex, temperature, date_t, score, result) VALUES ('$age', '$sex', '$body_temperature', curdate(), '$score', '$result')"; if (mysqli_query($conn, $sql)) { header('Location: ../negative-result.php'); } else { echo 'Error: ' . mysqli_error($conn); } } } elseif ($score === 5) { if ($error) { echo 'Error'; } else { $result = 'Positive'; $sql = "INSERT INTO records (age, sex, temperature, date_t, score, result) VALUES ('$age', '$sex', '$body_temperature', curdate(), '$score', '$result')"; if (mysqli_query($conn, $sql)) { header('Location: ../positive-level1-result.php'); } else { echo 'Error: ' . mysqli_error($conn); } } } elseif ($score > 5 && $score < 7) { if ($error) { echo 'Error'; } else { $result = 'Positive'; $sql = "INSERT INTO records (age, sex, temperature, date_t, score, result) VALUES ('$age', '$sex', '$body_temperature', curdate(), '$score', '$result')"; if (mysqli_query($conn, $sql)) { header('Location: ../positive-level2-result.php'); } else { echo 'Error: ' . mysqli_error($conn); } } } else { if ($error) { echo 'Error'; } else { $result = 'Positive'; $sql = "INSERT INTO records (age, sex, temperature, date_t, score, result) VALUES ('$age', '$sex', '$body_temperature', curdate(), '$score', '$result')"; if (mysqli_query($conn, $sql)) { header('Location: ../positive-level3-result.php'); } else { echo 'Error: ' . mysqli_error($conn); } } } }
PHP
UTF-8
233
2.96875
3
[]
no_license
<?php require_once '2.php'; class Man extends People{ public function __construct($age,$name){ parent::__construct($age,$name,'男'); } public function hi(){ //parent::hi(); echo 'Man '.$this->getName().' say hi'; } } ?>
C++
UTF-8
840
2.796875
3
[]
no_license
#include "Pass.h" #include "Sink.h" #include "Source.h" namespace rg { Source& Pass::GetSource(const std::string& source_name) const { for (auto& s : sources) { if (s->name == source_name) return *s; } } Sink& Pass::GetSink(const std::string& sink_name) const { for (auto& s : sinks) { if (s->name == sink_name) return *s; } } void Pass::RegisterSink(Unique<Sink> sink) { for (auto& s : sinks) { if (s->name == sink->name) { assert(0); } } sinks.push_back(std::move(sink)); } void Pass::RegisterSource(Unique<Source> source) { for (auto& s : sources) { if (s->name == source->name) { assert(0); } } sources.push_back(std::move(source)); } void Pass::LinkSink(const std::string& sink_name, const std::string& target) { } void Pass::Finalize() { } }
Markdown
UTF-8
2,416
2.75
3
[ "Unlicense" ]
permissive
# Seacera shareholders holding 2.5% stake propose appointment of six new directors Published at: **2019-11-04T07:06:59+00:00** Author: **Ahmad Naqib Idris** Original: [The Edge Markets](https://www.theedgemarkets.com/article/seacera-shareholders-holding-25-stake-propose-appointment-six-new-directors) KUALA LUMPUR (Nov 4): Four shareholders of Seacera Group Bhd have issued a notice of resolutions to be moved at the group's 34th annual general meeting (AGM) on Nov 29, entailing the nomination of six new directors to the board. The shareholders are Ng Wai Yuan, Datin Sek Chian Nee, Low Swee Foong and Datuk Tan Wei Lian, holding a collective stake of 2.5% in the company. According to a circular filed with Bursa Malaysia, the six directors comprise Rivzi Abdul Halim, Datin Ida Suzaini Abdullah, Marzuki Hussain, Tan Lee Chin, Ong Eng Taik and Ramnath R. Sundaram. "All the proposed directors have given their consent to act as directors and declare that they are not disqualified from being appointed as directors of the company. "In accordance with Section 323(2) [of the] Companies Act 2016, the company is to give notice of the above resolutions that may be properly moved and intended to be moved at the AGM," the filing said. On Oct 17, six Seacera shareholders comprising JS Portfolio Sdn Bhd, Mak Hon Leong, Ng, Ong, Sek and Low, who claimed to collectively hold at least 10% of the group's share capital, sought an extraordinary general meeting (EGM) on Dec 3 to consider appointing six new directors and removing nine existing ones. The group said it was seeking legal advice on the matter back then, but there had been no updates since. Seacera shareholders have been demanding for an EGM over the past several months. In June, the company sought to nullify an EGM requisition made by Ng and two other shareholders, Lim Seow Chin and Ooi Chieng Sim. The tile manufacturer has been in the spotlight of late over a series of boardroom disputes, its Practice Note 17 status since April after defaulting on a loan repayment, and its failure to provide a solvency declaration to Bursa. Seacera's then managing director, Zulkarnin Ariffin, quit the company in end-May, a day after the High Court had dismissed its injunction application to restrain an EGM called for by its then single largest shareholder Wei Lian. Wei Lian, who is also Tiger Synergy Bhd's executive chairman, had called for the EGM to appoint new directors and remove existing ones. At 2.37pm, Seacera rose 12.28% or 3.5 sen to 32 sen for a market capitalisation of RM153.8 million.