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
Python
UTF-8
2,592
2.703125
3
[]
no_license
import avians.nn.common as anc import os def single_model_ocr(input_file, model_file): ## TODO write a function to return text from models and input pass def prepare_text_images(image_arr, stats_arr, avians_model): """Prepare component images so that they are suitable to X arrays in datasets. :param image_arr: A set of images which contain white on black components :param stats_arr: Shows the location and other stats of components in image_arr :param model_module: The module to recreate the model and preprocess the images """ n_images, w_img, h_img = image_arr.shape X = dataset['X'] ds_n, ds_height, ds_width = X.shape x1 = stats_arr['x'] x2 = stats_arr['x'] + stats_arr['w'] y1 = stats_arr['y'] y2 = stats_arr['y'] + stats_arr['h'] c_arr = np.zeros(shape=(n_images, ds_height, ds_width)) for i_img in range(n_images): img = image_arr[i] s = stats_arr[i] cp_img = img[x1[i]:x2[i], y1[i]:y2[i]].copy() r_img = cv2.resize(cp_img, dsize=(cp_img.shape[1], ds_height)) c_arr[i, :, r_img.shape[1]] = r_img return c_arr def ocr_func(input_image_file, models=["$HOME/Annex/Arabic/default_model.h5"], datasets=["$HOME/Annex/Arabic/default_dataset.npz"]): """Entry point for the OCR functionality. :param input_image_file: Filename to convert to text. The file should contain a white on black binary image. :param models: A list of filenames to load models :param datasets: A list of filenames to load datasets """ models = anc.load_models(**{str(i): os.path.expandvars(f) for i, f in enumerate(models)}) datasets = anc.load_datasets(**{str(i): os.path.expandvars(f) for i, f in enumerate(datasets)}) image_arr, stats_arr = anc.text_image_segmentation(input_image_file) component_arrs = prepare_text_images(image_arr, stats_arr, datasets) labeled_components = label_components(image_arr, stats_arr, models, datasets) text = produce_text(labeled_components) return text
C++
UTF-8
1,084
2.84375
3
[ "MIT" ]
permissive
#ifndef CONTOUR_H #define CONTOUR_H #include <GL/glew.h> #include <string> #include "shader_primitive.h" #include "color.h" using namespace std; namespace glot { /** \brief curve: a contour to plot * * This class takes a function that accepts two doubles, * interprets it as a scalar field, and then plots it * * \sa grapher * \sa vector_field */ class contour : public shader_primitive { public: /** Color variable * * This is the color the contour is supposed to * take on. */ color c; /** Constructor * \param func - the function to render * \param col - the color of the curve */ contour(const string& f, const color& col) : shader_primitive(col), func(f) { gen_shader(); }; void dl_gen(const screen& scr); private: void gen_shader(); //string get_frag_shader(); string get_vert_shader(); string get_geom_shader(); //GLhandleARB f; GLhandleARB g; GLhandleARB v; // This is the function it's meant to plot. string func; }; } #endif
C#
UTF-8
454
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1 { class InsuranceParcelDecorator : AbstractParcelDecorator { public InsuranceParcelDecorator(AbstractParcel parcel) : base(parcel.Name + " зі страховкою", parcel) { } public override int GetCost() { return ProtectedParcel.GetCost() - 25; } } }
Java
UTF-8
1,317
2.859375
3
[]
no_license
package hyppypotku.hyppypotku.gfx; import java.awt.image.BufferedImage; /** * Luokan tehtävänä hallinnoida pelin objekteja. */ public class Assets { public static BufferedImage hpfull, hpzero, stickman, blockman, roundfull, roundempty, background, mainMenuBackground, tutorialBackground; /** * Metodi alustaa ja "leikkaa" spritesheetistä objektit omiksi olioikseen. */ public static void init() { SpriteSheet sheet = new SpriteSheet(ImageLoader.loadImage("/textures/sheet.png")); SpriteSheet menu = new SpriteSheet(ImageLoader.loadImage("/textures/menuBackground.png")); SpriteSheet tutorial = new SpriteSheet(ImageLoader.loadImage("/textures/tutorialBackground.png")); SpriteSheet level = new SpriteSheet(ImageLoader.loadImage("/textures/background.png")); hpfull = sheet.crop(0, 0, 256, 48); hpzero = sheet.crop(0, 48, 256, 48); stickman = sheet.crop(0, 96, 96, 160); blockman = sheet.crop(256, 96, 96, 160); roundfull = sheet.crop(101, 97, 90, 79); roundempty = sheet.crop(102, 177, 89, 79); background = level.crop(0, 0, 1024, 768); mainMenuBackground = menu.crop(0, 0, 1024, 768); tutorialBackground = tutorial.crop(0, 0, 1024, 768); } }
C#
UTF-8
8,691
3.09375
3
[ "MIT" ]
permissive
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* NumberRange.cs -- */ #region Using directives using System; using System.Collections; using System.Collections.Generic; #endregion namespace ManagedClient.Ranges { /// <summary> /// Диапазон чисел, содержащих нечисловые фрагменты. /// </summary> [Serializable] public sealed class NumberRange : IEnumerable<NumberText> { #region Properties /// <summary> /// Стартовое значение. /// </summary> public NumberText Start { get; set; } /// <summary> /// Стоповое значение. /// </summary> public NumberText Stop { get; set; } #endregion #region Construction /// <summary> /// Конструктор по умолчанию. /// </summary> public NumberRange() { } /// <summary> /// Конструктор для диапазона, состоящего /// из одного числа. /// </summary> public NumberRange ( NumberText startAndStop ) { Start = startAndStop; Stop = startAndStop; } /// <summary> /// Конструктор для произвольного диапазона. /// </summary> /// <param name="start"></param> /// <param name="stop"></param> public NumberRange ( NumberText start, NumberText stop ) { Start = start; Stop = stop; } internal NumberRange ( NumberRangesParser.ItemContext itemContext ) { NumberRangesParser.OneContext oneContext = itemContext.one(); if (!ReferenceEquals(oneContext, null)) { string number = oneContext.NUMBER().GetText(); Start = number; Stop = number; } NumberRangesParser.RangeContext rangeContext = itemContext.range(); if (!ReferenceEquals(rangeContext, null)) { Start = rangeContext.start.Text; Stop = rangeContext.stop.Text; } } #endregion #region Private members #endregion #region Public methods /// <summary> /// Проверка, содержит ли диапазон указанное значение. /// </summary> /// <param name="number"></param> /// <returns></returns> public bool Contains ( NumberText number ) { if (ReferenceEquals(number, null)) { throw new ArgumentNullException("number"); } if (ReferenceEquals(Start, null)) { throw new ApplicationException("Start is null"); } if (ReferenceEquals(Stop, null)) { throw new ApplicationException("Stop is null"); } return ((Start.CompareTo(number) >= 0) && (number.CompareTo(Stop)) <= 0); } /// <summary> /// Разбор текстового представления диапазона. /// </summary> /// <param name="text"></param> /// <returns></returns> public static NumberRange Parse ( string text ) { if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException("text"); } text = text.Trim(); if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException("text"); } NumberRange result; if (text.Contains("-")) { string[] parts = text.Split('-'); if (parts.Length != 2) { throw new FormatException("text"); } parts[0] = parts[0].Trim(); parts[1] = parts[1].Trim(); if (string.IsNullOrEmpty(parts[0]) || string.IsNullOrEmpty(parts[1])) { throw new FormatException("text"); } result = new NumberRange ( parts[0], parts[1] ); } else { result = new NumberRange(text); } return result; } /// <summary> /// Выполнение указанного действия на всём диапазоне. /// </summary> /// <param name="action"></param> public void For ( Action<NumberText> action ) { // ReSharper disable NotResolvedInText if (ReferenceEquals(action, null)) { throw new ArgumentNullException("action"); } if (ReferenceEquals(Start, null)) { throw new ArgumentNullException("Start"); } if (ReferenceEquals(Stop, null)) { throw new ArgumentNullException("Stop"); } // ReSharper restore NotResolvedInText for ( NumberText current = Start; current.CompareTo(Stop) <= 0; current = current.Increment() ) { action ( current ); } } /// <summary> /// Пересечение двух диапазонов. /// </summary> public NumberRange Intersect ( NumberRange other ) { return new NumberRange ( Stop, other.Start ); } /// <summary> /// Проверка, не пустой ли диапазон. /// </summary> public bool IsEmpty () { return (Start > Stop); } /// <summary> /// Объединение двух диапазонов. /// </summary> public NumberRange Union ( NumberRange other ) { return new NumberRange ( NumberText.Min(Start, other.Start), NumberText.Max(Stop, other.Stop) ); } #endregion #region IEnumerable<NumberText> members IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<NumberText> GetEnumerator() { if (ReferenceEquals(Start, null)) { throw new ApplicationException("Start is null"); } if (ReferenceEquals(Stop, null)) { throw new ApplicationException("Stop is null"); } for ( NumberText current = Start; current.CompareTo(Stop) <= 0; current = current.Increment() ) { yield return current; } } #endregion #region Object members /// <inheritdoc cref="object.ToString"/> public override string ToString() { if (ReferenceEquals(Start, null) && ReferenceEquals(Stop, null)) //-V3125 { return string.Empty; } if (ReferenceEquals(Start, null)) { return Stop.ToString(); //-V3125 //-V3095 } if (ReferenceEquals(Stop, null)) //-V3095 { return Start.ToString(); } if (Start.CompareTo(Stop) == 0) { return Start.ToString(); } return string.Format ( "{0}-{1}", Start, Stop ); } #endregion } }
Java
UTF-8
2,385
2.78125
3
[]
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 view; import controller.DatabaseController; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static java.lang.Compiler.command; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; /** * * @author Sebastian Berto */ public class MainMenu implements ActionListener{ JLabel JlabelJudul; JButton registerbutton, loginbutton, cekdatapengguna; DatabaseController controller = new DatabaseController(); JFrame frame = new JFrame(); public MainMenu(){ frame.setSize(1000, 800); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JlabelJudul = new JLabel("Main Menu"); JlabelJudul.setBounds(400,30,400,30); JlabelJudul.setFont(new Font(JlabelJudul.getFont().getName(), JlabelJudul.getFont().getStyle(), 28)); registerbutton = new JButton("Register"); registerbutton.setBounds(200,200,300,30); registerbutton.addActionListener(this); loginbutton = new JButton("Login"); loginbutton.setBounds(200,240,300,30); loginbutton.addActionListener(this); cekdatapengguna = new JButton("Cek Data Pengguna"); cekdatapengguna.setBounds(200,280,300,30); cekdatapengguna.addActionListener(this); frame.add(JlabelJudul); frame.add(registerbutton); frame.add(loginbutton); frame.add(cekdatapengguna); frame.setLayout(null); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); switch(command){ case "Register": frame.setVisible(false); new RegisterScreen(); break; case "Login": frame.setVisible(false); new LoginScreen(); break; case "Cek Data Pengguna": frame.setVisible(false); new DataPengguna(); break; } } }
Markdown
UTF-8
2,415
2.765625
3
[ "MIT" ]
permissive
# 如何用C++实现一个简易数据库 *基于cstack/db_tutorial C语言版本* * KCNyu * 2022/2/2 作为笔者写的第一个系列型教程,还是选择基于前人的教程经验以及添加一些自己个人的探索。也许有很多纰漏之处,希望大家指正。 ## 1. 数据库是什么? 数据库是“按照数据结构来组织、存储和管理数据的仓库”。是一个长期存储在计算机内的、有组织的、可共享的、统一管理的大量数据的集合。使用者可以对其中的资料执行新增、选取、更新、刪除等操作。 ## 2. SQL是什么? SQL ***(Structured Query Language:结构化查询语言)*** 是一种特定目的程式语言,用于管理关系数据库管理系统 ***(RDBMS)***,或在关系流数据管理系统 ***(RDSMS)*** 中进行流处理。 ## 3. 我们最终会实现什么? 前端 ***(front-end)*** * 分词器 ***(tokenizer)*** * 解析器 ***(parser)*** * 代码生成器 ***(code generator)*** 后端 ***(back-end)*** * 虚拟机 ***(virtual machine)*** * B树 ***(B-tree)*** * 分页 ***(pager)*** * 操作系统层接口 ***(os interface)*** ## 4. 我们的开发流程是什么? ### 测试驱动开发 ***(test driven development, TDD)*** * 添加测试用例 * 运行并查看失败的用例 * 改动代码以通过测试 * 通过全部测试 ## 5. 我们的单元目录结构是什么? ### **tutorial** * 本单元完整代码实现 ***(db.cpp)*** * 本单元对应测试用例 ***(db_test.rb)*** * 本单元对应教程详解 ***(README.md)*** ## 6. 教学大纲 * [tutorial01-安装测试环境和实现REPL](./tutorial01/README.md) * [tutorial02-实现解析前端和虚拟机](./tutorial02/README.md) * [tutorial03-实现insert和select](./tutorial03/README.md) * [tutorial04-边界测试与修复BUG](./tutorial04/README.md) * [tutorial05-实现磁盘存储](./tutorial05/README.md) * [tutorial06-实现光标](./tutorial06/README.md) * [tutorial07-初步实现B-Tree](./tutorial07/README.md) * [tutorial08-实现二分搜索和防重](./tutorial08/README.md) * [tutorial09-实现拆分叶结点](./tutorial09/README.md) * [tutorial10-实现递归搜索](./tutorial10/README.md) * [tutorial11-实现扫描多层树](./tutorial11/README.md) * [tutorial12-实现更新拆分后的父结点](./tutorial12/README.md) ## 7. [知乎专栏](https://www.zhihu.com/column/c_1472652536327389184)
Markdown
UTF-8
356
2.765625
3
[]
no_license
--- date: "2015-01-01T13:09:13-06:00" title: macoroni --- Macaroni is dry pasta shaped like narrow tubes. Made with durum wheat, macaroni is commonly cut in short lengths; curved macaroni may be referred to as elbow macaroni. Some home machines can make macaroni shapes, but like most pasta, macaroni is usually made commercially by large-scale extrusion
C#
UTF-8
1,447
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SopromatLib { public class BaseRectangle : BaseShape { private float Width, Height; public BaseRectangle(float width, float height) : base($"Прямоугольник, ширина {width}, высота {height}") { Width = width; Height = height; path.AddRectangle(new RectangleF(0, 0, Width, Height)); } public override float Area => Width * Height; public override PointF CenterPoint => new PointF(Width / 2, Height / 2); public override float CenterMoment() => 0; public override PointF AxeMoment() => new PointF( Width * (float)Math.Pow(Height, 3) / 12, (float)Math.Pow(Width, 3) * Height / 12); //public override void Draw(Graphics g, Brush brush) //{ // g.FillRectangle(brush, 0, 0, Width, Height); //} public override List<PointF> GetCorners(float rotate = 0) { return new List<PointF> { new PointF(0, 0), new PointF(Width, 0), new PointF(0, Height), new PointF(Width, Height) }; } public override string ToString() { return $"R {Width} {Height}"; } } }
C#
UTF-8
1,112
2.546875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(SpriteRenderer))] public class Parallax : MonoBehaviour { public float ParallaxMagnitude; public Camera Cam; private float SpriteLength; private float SpriteLeft; void Start() { this.SpriteLeft = this.transform.position.x; this.SpriteLength = GetComponent<SpriteRenderer>().bounds.size.x; } void Update() { float distToSpriteEnd = this.Cam.transform.position.x * this.ParallaxMagnitude; float distAlongSprite = this.Cam.transform.position.x * (1 - this.ParallaxMagnitude); this.transform.position = new Vector3(this.SpriteLeft + distToSpriteEnd, this.transform.position.y, this.transform.position.z); if (distAlongSprite > this.SpriteLeft + this.SpriteLength) { this.SpriteLeft += this.SpriteLength; } else if (distAlongSprite < this.SpriteLeft - this.SpriteLength) { this.SpriteLeft -= this.SpriteLength; } } }
C#
UTF-8
2,406
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Docu.Documentation; using Docu.Documentation.Comments; using Docu.Parsing.Model; namespace Docu.Tests { internal static class TestExtensions { public static IList<Namespace> to_namespaces(this IEnumerable<string> namespaces) { return namespaces.Select(to_namespace).ToList(); } public static InlineText to_text(this string text) { return new InlineText(text); } public static Namespace to_namespace(this string ns) { return new Namespace(IdentifierFor.Namespace(ns)); } public static DeclaredType to_type(this Type type) { return type.to_type_in_namespace(type.Namespace.to_namespace()); } static DeclaredType to_type_in_namespace(this Type type, Namespace ns) { var declaredType = new DeclaredType(IdentifierFor.Type(type), ns); ns.AddType(declaredType); return declaredType; } public static MethodParameter to_method_parameter_called(this DeclaredType type, string name) { return new MethodParameter(name, type); } public static Method method_for<T>(this T instance, Expression<Action<T>> method_signature) { return new Method(IdentifierFor.Method(Method(method_signature), typeof (T)), null); } public static Property property_for<T>(this T instance, Expression<Func<T, object>> property_signature) { return new Property(IdentifierFor.Property(Property(property_signature), typeof (T)), null); } public static T Setup<T>(this T instance, Action<T> setup) { setup(instance); return instance; } static PropertyInfo Property<T>(Expression<Func<T, object>> propertyAction) { return ((MemberExpression) propertyAction.Body).Member as PropertyInfo; } static MethodInfo Method<T>(Expression<Action<T>> methodAction) { MethodInfo method = ((MethodCallExpression) methodAction.Body).Method; if (method.IsGenericMethod) return method.GetGenericMethodDefinition(); return method; } } }
C++
UTF-8
2,123
3.796875
4
[]
no_license
/* First take a couple of examples and find their preorder and inorder.Soon you'll be able figure out the pattern which ig you already have done. Next 1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex ) to pick next element in next recursive call. 2) Create a new tree node with the data as picked element. 3) Find the picked element’s index in Inorder. Let the index be inIndex. 4) Call build for elements before inIndex and make the built tree as left subtree of tNode. 5) Call build for elements after inIndex and make the built tree as right subtree of tNode. 6) return Node. *for step 3 create a separate function called say Find with takes the inorder as input,the starting and ending index. Within the given start and end find the required element in the inorder and return the index.The start will be : TreeNode* node = new TreeNode(preorder[p++]); int in = find(inorder, i, j, node->val); node->left = makeTree(preorder, inorder, i, in-1, p); node->right = makeTree(preorder, inorder, in+1, j, p); return node; */ TreeNode* insert(vector<int> &A, int &left, int right, int currMax){ if (left==right) { return new TreeNode(A[left]); } if (right<left) { return NULL; } int start = left+1; int end = left+1; TreeNode* head = new TreeNode(A[left]); currMax = A[left]; while(start<=right){ if (A[start]<currMax) { end = start; while(end<=right && A[end]<currMax){ end++; } if (end>right || A[end]>currMax) { end--; } head->right = insert(A, start, end, currMax); start++; } if (A[start]>currMax) { currMax = A[start]; TreeNode* root = new TreeNode(A[start]); root->left = head; head = root; start++; } } return head; } TreeNode* Solution::buildTree(vector<int> &v) { int i = 0; return insert(v, i, v.size()-1, INT_MIN); }
Java
UTF-8
436
3.015625
3
[]
no_license
package data; public class IntDirectionDataPair { private final DataPair<Integer, String> intDirectionPair; public IntDirectionDataPair(int directionInt, String direction){ intDirectionPair = new DataPair<Integer, String>(directionInt, direction); } public int getDirectionInt (){ return intDirectionPair.first; } public String getDirection(){ return intDirectionPair.second; } }
PHP
UTF-8
3,291
2.5625
3
[ "MIT" ]
permissive
<?php /** * Copyright (c) 2018 Alma / Nabla SAS * * THE MIT LICENSE * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * @author Alma / Nabla SAS <contact@getalma.eu> * @copyright Copyright (c) 2018 Alma / Nabla SAS * @license https://opensource.org/licenses/MIT The MIT License * */ namespace Alma\API; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; class ClientContext implements LoggerAwareInterface { /** @var string */ public $apiKey; /** @var LoggerInterface */ public $logger; /** @var array */ private $options; /** @var array */ private $userAgentComponents; public function __construct($apiKey, $options) { $this->apiKey = $apiKey; $this->options = $options; $this->setLogger($options['logger']); $this->userAgentComponents = array(); if (isset($options['user_agent_component'])) { foreach ($options['user_agent_component'] as $component => $version) { $this->addUserAgentComponent($component, $version); } } } /** * Returns the full API endpoint URL for the given path, depending on the current mode (live or test) * * @param $path * @return string */ public function urlFor($path) { $root = $this->options['api_root'][$this->options['mode']]; return rtrim($root, '/') . '/' . ltrim($path, '/'); } /** * @return int|false Either not to force TLS (false), or the TLS subversion to force (i.e. x for TLS 1.x) */ public function forcedTLSVersion() { return $this->options['force_tls']; } /** * Sets a logger instance on the object. * * @param LoggerInterface $logger * * @return void */ public function setLogger(LoggerInterface $logger) { if (!$logger) { $this->logger = new NullLogger(); } else { $this->logger = $logger; } } public function addUserAgentComponent($component, $version) { $this->userAgentComponents[] = "$component/$version"; } public function getUserAgentString() { return implode("; ", array_reverse($this->userAgentComponents)); } }
JavaScript
UTF-8
5,436
2.515625
3
[]
no_license
/** * Player Model */ function Player(name, tint) { var self = game.add.sprite(spawnlocs[0], spawnlocs[1], 'dude'); this.self = self; var movespeed = 300; var fireRate = 1000; var nextFire = 0; var keys; this.setup = function () { game.physics.p2.enable(self); self.physicsBodyType = Phaser.Physics.P2; self.body.setRectangle(30, 40, 0, 5); self.enableBody = true; self.body.debug = DEBUG; self.body.fixedRotation = true; self.anim = 'stop'; self.dir = 'right'; self.name = name; self.tint = tint; self.dead = false; self.source = socketid; self.checkWorldBounds = true; self.events.onOutOfBounds.add(function () { self.body.velocity.x = 0; self.body.velocity.y = 0; self.x = 1200; self.y = 850; }); self.animations.add('left', [0, 1, 2, 3], 10, true); self.animations.add('right', [5, 6, 7, 8], 10, true); self.scale.setTo(1, 1); var label_name = game.add.bitmapText(0, -40, 'font1', self.name, 20); label_name.updateTransform(); label_name.smoothing = true; label_name.position.x = (-3)-(label_name.width / 2); self.addChild(label_name); socket.emit('identify', [self.x, self.y, self.anim, self.dir, self.name, self.tint, socket.id]); keys = { up: game.input.keyboard.addKey(Phaser.Keyboard.W), down: game.input.keyboard.addKey(Phaser.Keyboard.S), left: game.input.keyboard.addKey(Phaser.Keyboard.A), right: game.input.keyboard.addKey(Phaser.Keyboard.D), space: game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR), }; self.body.setCollisionGroup(playerCollisionGroup); self.body.collides([platformCollisionGroup, playerCollisionGroup]); self.body.collides(projectileCollisionGroup, self.hit, this); game.camera.follow(self); } this.updateBody = function () { if (!self.dead) { self.body.velocity.x = 0; self.animations.play(self.dir); // Resolve input if (keys['left'].isDown) { // Move to the left self.body.moveLeft(movespeed); self.anim = 'left'; self.dir = 'left'; } else if (keys['right'].isDown) { self.body.moveRight(movespeed); self.anim = 'right'; self.dir = 'right'; } else { self.animations.stop(); self.anim = 'stop'; } if (game.input.activePointer.isDown) { var targetAngle = game.physics.arcade.angleToPointer(self); if (game.time.now > nextFire && projectileCtrl.projectiles.countDead() > 0) { nextFire = game.time.now + fireRate; socket.emit('fire', [self.x, self.y, targetAngle, self.tint, socket.id]); } } if ((keys['up'].isDown || keys['space'].isDown) && touchingDown(self)) { self.body.moveUp(750); if (self.body.velocity.x > 0 && !touchingDown(self)) { self.animations.stop(); self.frame = 6; self.anim = 'jump_right'; } if (self.body.velocity.x < 0 && !touchingDown(self)) { self.animations.stop(); self.frame = 3; self.anim = 'jump_left'; } } } } self.hit = function (player, projectile) { if (projectile.sprite.source != socketid) { self.dead = true; self.body.moves = false; self.body.fixedRotation = false; self.body.velocity.x = projectile.sprite.body.velocity.x; self.body.velocity.y = projectile.sprite.body.velocity.y; self.body.angularVelocity = self.body.angularVelocity * 2; var tween = game.add.tween(self).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true, 2000); projectile.sprite.kill(); setTimeout(function () { if (self.dead) { game.tweens.remove(tween); var tween2 = game.add.tween(self).to( { alpha: 1 }, 500, Phaser.Easing.Linear.None, true); tween2.repeat(4, 0); self.body.rotation = 0; self.rotation = 0; self.reset(spawnlocs[0], spawnlocs[1]); self.body.fixedRotation = true; self.dead = false; } }, 4000); } } } function touchingDown(someone) { var yAxis = p2.vec2.fromValues(0, 1); var result = false; for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) { var c = game.physics.p2.world.narrowphase.contactEquations[i]; // cycles through all the contactEquations until it finds our "someone" if (c.bodyA === someone.body.data || c.bodyB === someone.body.data) { var d = p2.vec2.dot(c.normalA, yAxis); // Normal dot Y-axis if (c.bodyA === someone.body.data) d *= -1; if (d > 0.5) result = true; } } return result; }
Java
UTF-8
3,101
3.625
4
[]
no_license
public class StringPracticeProgram2 { public String Str10="Strings Are Immutable"; public String Str11="Strings Are Immutable"; public String Str13="Integers Are not Immutable"; public static void main(String[] args) { String str1="Testprogram";//substring System.out.println(str1.substring(4)); System.out.println(str1.substring(2, 8)); System.out.println(str1.toUpperCase()); String str2="simple program";//toUpperCase System.out.println(str2.toUpperCase()); String str3="SIMPLE PROGRAM";//tolowercase System.out.println(str3.toLowerCase()); String str4=" TEST ";//trim System.out.println(str4.trim()); String str5="Test program";//startWith and endWith System.out.println(str5.startsWith("Te")); System.out.println(str5.endsWith("gr")); String str6=new String("MYPROGRAM");//charAt System.out.println(str6.charAt(5)); System.out.println(str6.charAt(6)+str6.charAt(7)+str6.charAt(8)); String Str7=String.valueOf(1000);//valueOf int v=111; System.out.println(v+Str7); System.out.println(Str7.isEmpty());//isEmpty String Str8="Ram and sam are brothers.Ram is bigger than sam"; System.out.println(Str8.replace("Ram","Ravi")); String str8="Amstrongprogram";//codePointAt System.out.println(str8.codePointAt(0)); System.out.println(str8.codePointBefore(1));//codePointBefore System.out.println(str8.codePointCount(5, 15));//codePointCount System.out.println(str8.contains("pro"));//contains System.out.println(str8.contentEquals("Ams"));//contentEquals char[] str9={'h','e','l','l','o'};//copyValueOf String str10=""; str10=str10.copyValueOf(str9, 0, 5); System.out.println(str10); System.out.println(str8.indexOf('a'));//indexOf System.out.println(str8.lastIndexOf('m')); StringPracticeProgram2 obj=new StringPracticeProgram2();//compareToIgnorenceCase System.out.println(obj.Str10.compareToIgnoreCase(obj.Str11)); System.err.println(obj.Str11.compareToIgnoreCase(obj.Str13)); System.out.println(obj.Str10.compareTo(obj.Str11)); System.out.println(obj.Str11.compareTo(obj.Str13)); System.out.println(obj.Str10.getBytes());//getByte it returns ASCII code System.out.println(obj.Str13.hashCode());//hashCode System.out.println(String.join(":", "My", "name", "is", "karthik"));//join System.out.println(obj.Str13.join(":", "My", "name", "is", "karthik")); System.out.println(obj.Str10.matches(obj.Str11));//matches System.out.println(obj.Str10.regionMatches(true, 0, obj.Str11, 0, 0)); for(String Retval:obj.Str10.split(" ")){ //split System.out.println(Retval); } System.out.println(obj.Str10.subSequence(0, 11));//Subsequence System.out.println(obj.Str10.substring(11));//subSequence } }
PHP
UTF-8
2,788
3.28125
3
[]
no_license
<?php /** * Modèle de la table location. * Ce modèle est la réplique de la table. * Ici je la déclare * Le mot clé extends permet de dire que la classe users hérite de la classe database */ class location extends database { /** * Déclaration des champs de la table en attribut. * Dans une classe les variables globales sont appelées attributs * @var type */ public $id = 0; public $postalCode = 0; public $city = ''; /** * Déclaration de la méthode magique construct. * Le constructeur de la classe est appelé avec le mot clé new. */ public function __construct() { parent::__construct(); $this->connectDB(); } /** * Methode permetant de chercher une ville par rapport a son code postal. * passe en parametre la valeur de l'input de recherche. */ public function getPostalCodeBySearch($search){ $queryResult = $this->pdo->prepare('SELECT `postalCode`' . ',`id`' . ',`city` ' . 'FROM `taxi_location` ' . 'WHERE `postalCode` LIKE :search'); $queryResult->bindValue(':search',$search.'%',PDO::PARAM_STR); $queryResult->execute(); return $queryResult->fetchAll(PDO::FETCH_OBJ); } public function getListLocation() { $queryResult = $this->pdo->prepare('SELECT `t_lct`.`postalCode`' . ',`t_lct`.`city` ' . 'FROM `taxi_location` AS `t_lct` ' . 'INNER JOIN `taxi_users` ' . 'AS `t_usr` ' . 'ON `t_lct`.`id` = `t_usr`.`id_taxi_location` ' . 'WHERE `t_usr`.`id_taxi_location` = :postalCode'); $queryResult->bindValue(':postalCode', $this->postalCode, PDO::PARAM_INT); $queryResult->execute(); $search = $queryResult->fetch(PDO::FETCH_OBJ); // La valeur de la ville retourner ans la valeur de la ville de l'objet $this->city = $search->city; // On appel la methode getPostalCodeBySearch() en cherchant avec le code postal trovuer utlerieurement return $this->getPostalCodeBySearch($search->postalCode); } // Quand on fait une reservation affiche les ville de la base de donner avec une limit de 10 public function getLocation(){ $queryResult = $this->pdo->prepare('SELECT `postalCode`' . ',`id`' . ',`city` ' . 'FROM `taxi_location` ' . 'WHERE `city` ' . 'LIKE :city ' . 'ORDER BY `city` ASC ' . 'LIMIT 0,10 '); $queryResult->bindValue(':city', $this->city.'%', PDO::PARAM_STR); $queryResult->execute(); return $queryResult->fetchAll(PDO::FETCH_OBJ); } }
C#
UTF-8
6,052
2.921875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.IO; namespace Server { public partial class Form1 : Form { // Variables private TcpClient client; // var for connections for TCP network services public StreamReader myStreamReader; // reads characters from a byte stream public StreamWriter myStreamWriter; // writes... public string messageRecieve; // Var for the message recieved public String messageSend; // Var for the message send int noOfConnections = 1; public Form1() { InitializeComponent(); IPAddress[] myIP_Address = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress address in myIP_Address) { if (address.AddressFamily == AddressFamily.InterNetwork) { ServerIPtextBox.Text = address.ToString(); txtConnections.Text = noOfConnections.ToString(); } } } // Starts a server/hosting service for other clients to connect private void Startbutton_Click(object sender, EventArgs e) { TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(ServerPorttextbox.Text)); // uses the IP address in the textbox to be listened to listener.Start(); // starts listening if its an IP address client = listener.AcceptTcpClient(); // accepts clients listening on IP address myStreamReader = new StreamReader(client.GetStream()); myStreamWriter = new StreamWriter(client.GetStream()); myStreamWriter.AutoFlush = true; backgroundWorker1.RunWorkerAsync(); backgroundWorker2.WorkerSupportsCancellation = true; // increases number of connections and informs server side that a user is in the chatroom noOfConnections++; txtConnections.Text = noOfConnections.ToString(); ChatScreentextbox.AppendText("A user has connected!"); } // allows the user to connect to a hosting/server IP address in order to enter the chatri private void Connectbutton_Click(object sender, EventArgs e) { client = new TcpClient(); // the variable client is overwritten with a new instance of TcpClient // Represents a network endpoint as an IP address and a port number. IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(ClientIPtextbox.Text), int.Parse(ClientPorttextbox.Text)); try { client.Connect(IpEnd); if (client.Connected) { // Lets the user know that they have connected to the local server ChatScreentextbox.AppendText("Connected to server" + "\n"); noOfConnections++; txtConnections.Text = noOfConnections.ToString(); myStreamWriter = new StreamWriter(client.GetStream()); myStreamReader = new StreamReader(client.GetStream()); myStreamWriter.AutoFlush = true; // flushes the buffer backgroundWorker1.RunWorkerAsync(); // starts backgroundWorker1 backgroundWorker2.WorkerSupportsCancellation = true; // allows backgroundworker2 to be cancelled asynchronously } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // while (client.Connected) { try { // Stream messageRecieve = myStreamReader.ReadLine(); this.ChatScreentextbox.Invoke(new MethodInvoker(delegate () { // send message stating who sent it and their message - ChatScreentextbox.AppendText("opponent:" + messageRecieve + "\n"); })); messageRecieve = ""; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } } private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { // if you've connected to the server if (client.Connected) { //enables easy and efficient text output myStreamWriter.WriteLine(messageSend); this.ChatScreentextbox.Invoke(new MethodInvoker(delegate () { // send message stating who sent it and their message ChatScreentextbox.AppendText("player:" + messageSend + "\n"); })); } else { // error handling message MessageBox.Show("SENDING MESSAGE FAILED..."); } backgroundWorker2.CancelAsync(); } private void Sendbutton_Click(object sender, EventArgs e) { // if not blank, send message in textbox to the other player if (Messagetextbox.Text != "") { messageSend = Messagetextbox.Text; backgroundWorker2.RunWorkerAsync(); } //removes what the sender previously wrote into the textbox Messagetextbox.Text = ""; } } } // ADAPTED FROM https://www.youtube.com/watch?v=BDVfpPq3weo&t=188s
Python
UTF-8
9,372
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # burnin-drive # # usage: burnin-drive [-h] [-d DIR] [-l LOG] [-y] [-m | -r] drive # # Burnin a drive with SMART tests and badblocks # # positional arguments: # drive # # optional arguments: # -h, --help show this help message and exit # -d DIR, --dir DIR specify the output directory for the results # -l LOG, --log LOG specify the filename for the results # -y, --yes confirm consent to erase drive # -m, --dry-run perform a dry run (default) # -r, --run perform a real run # # MIT License # # Copyright (c) 2020 Samuel Kadolph # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from datetime import datetime, timezone import argparse import errno import os import re import shutil import signal import subprocess import sys import time SMART_LONG_POLL = 15*60 SMART_SHORT_POLL = 30 class ProcessError(Exception): def __init__(self, message): self.message = message def clean_smartctl(output): return os.linesep.join([s for s in output.splitlines()[4:] if s != ""]) def find_make(smartinfo): match = re.search(r"^Vendor: +(\w+)$", smartinfo, re.MULTILINE) if match: return match.group(1) match = re.search(r"^Model Family: +(\w+).*$", smartinfo, re.MULTILINE) if match: return match.group(1) match = re.search(r"^Device Model: +(\w+).*$", smartinfo, re.MULTILINE) if match: return match.group(1) match = re.search(r"^Model Number: +(\w+).*$", smartinfo, re.MULTILINE) if match: return match.group(1) return None def find_model(smartinfo): match = re.search(r"^Product: +([\w-]+)$", smartinfo, re.MULTILINE) if match: return match.group(1) match = re.search(r"^Device Model: +(?:[\w-]+ +)?([\w-]+)$", smartinfo, re.MULTILINE) if match: return match.group(1) match = re.search(r"^Model Number: +(?:[\w-]+ +)?([\w-]+)$", smartinfo, re.MULTILINE) if match: return match.group(1) return None def find_serial(smartinfo): match = re.search(r"^Serial [Nn]umber: +([\w-]+)$", smartinfo, re.MULTILINE) if match: return match.group(1) return None def get_time(): return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S %Z") def handle_interrupt(sig, frame): print("interrupted", file=sys.stderr) exit(1) def log(message): tee(re.sub(r"^", get_time() + " | ", message, flags=re.MULTILINE) + "\n") def run_badblocks(): log("===== Start badblocks on %s" % dev) if run: run_badblocks_process("-o", bb_file_path, dev) else: log("Not running badblocks because this is a dry run") log("===== Finish badblocks on %s" % dev) def run_badblocks_process(*args): proc = subprocess.Popen(["badblocks", "-svw", "-b", "4096"] + list(args), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) start_of_line = True while proc.poll() is None: data = proc.stdout.read1() string = data.decode("UTF-8") string = string.replace("set_o_direct: Inappropriate ioctl for device\n", "") lines = string.split("\n") for n, line in enumerate(lines): if start_of_line: tee("%s | " % get_time()) start_of_line = False if line != "": safe_line = re.sub(r" *[\d.]+% done, [\d:]+ elapsed\. \(.* errors\)", "", line) safe_line = re.sub(r"\x08+", "", safe_line) if sys.stdout.isatty(): sys.stdout.write(line) sys.stdout.flush() else: sys.stdout.write(safe_line) sys.stdout.flush() log_file.write(safe_line) log_file.flush() if n + 1 < len(lines): tee("\n") start_of_line = True if proc.returncode != 0: if not start_of_line: tee("\n") raise ProcessError("badblocks failed") def run_smart_test(type): log("===== Start SMART %s Test on %s" % (type.upper(), dev)) if run: log(clean_smartctl(run_smartctl_process("--test", type, dev))) wait_for_smart_test(type) log("SMART Test finished") else: log("Not running SMART test because this is a dry run") show_smart_data() log("===== Finish SMART %s Test on %s" % (type.upper(), dev)) def run_smartctl_process(*args): proc = subprocess.run(["smartctl"] + list(args), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = proc.stdout.decode(sys.getdefaultencoding()) # if proc.returncode is not 0: # raise ProcessError(output + "smartctl failed") return output def show_smart_data(): log(clean_smartctl(run_smartctl_process("--health", dev))) log(clean_smartctl(run_smartctl_process("--attributes", dev))) log(clean_smartctl(run_smartctl_process("--log", "error", dev))) log(clean_smartctl(run_smartctl_process("--log", "selftest", dev))) def tee(string): sys.stdout.write(string) sys.stdout.flush() log_file.write(string) log_file.flush() def wait_for_smart_test(type): log("Waiting for SMART Test to finish") while True: status = run_smartctl_process("--capabilities", dev) if "Self-test execution status" in status: if "Self-test routine in progress" not in status: break else: status = run_smartctl_process("--log", "selftest", dev) if re.search(r"^#\s1\s.*(Aborted|Completed|Failed)", status, re.MULTILINE): break if type == "long": time.sleep(SMART_LONG_POLL) else: time.sleep(SMART_SHORT_POLL) signal.signal(signal.SIGINT, handle_interrupt) parser = argparse.ArgumentParser(description="Burnin a drive with SMART tests and badblocks") parser.add_argument("-d", "--dir", type=str, help="specify the output directory for the results") parser.add_argument("-l", "--log", type=str, help="specify the filename for the results") parser.add_argument("-y", "--yes", action="store_true", help="confirm consent to erase drive") group = parser.add_mutually_exclusive_group() group.add_argument("-m", "--dry-run", action="store_true", help="perform a dry run (default)") group.add_argument("-r", "--run", action="store_true", help="perform a real run") parser.add_argument("drive") args = parser.parse_args() if os.geteuid() != 0: print("%s must be run as root" % parser.pro, file=sys.stderr) exit(1) if not shutil.which("smartctl"): print("could not find smartctl, please install it", file=sys.stderr) exit(1) if not shutil.which("badblocks"): print("could not find badblocks, please install it", file=sys.stderr) exit(1) dev = args.drive if not os.path.exists(dev): print("could not find device: '%s'" % dev, file=sys.stderr) exit(1) smartinfo = run_smartctl_process("--info", dev) make = find_make(smartinfo) model = find_model(smartinfo) serial = find_serial(smartinfo) if not make or not model or not serial: print("unable to determine drive make, model, and serial for '%s" % dev, file=sys.stderr) exit(1) if not args.yes: print("This script will erase all data on %s. Any other processes trying to use it will fail." % (dev)) print("The make, model, and serial for this drive is %s %s %s. Confirm this is the right drive." % (make, model, serial)) print("And you really really really should be running this inside of screen or tmux.") print("Proceed? [yN] ", end="", flush=True) if sys.stdin.readline().rstrip().lower() != "y": exit() dir = args.dir if args.dir else os.getcwd() if args.log: bb_file_path = os.path.join(dir, "%s.badblocks" % args.log) log_file_path = os.path.join(dir, "%s.log" % args.log) else: bb_file_path = os.path.join(dir, "burnin_%s_%s_%s.badblocks" % (make, model, serial)) log_file_path = os.path.join(dir, "burnin_%s_%s_%s.log" % (make, model, serial)) try: os.makedirs(dir) except OSError as e: if e.errno != errno.EEXIST: raise try: os.remove(bb_file_path) except OSError: pass try: os.remove(log_file_path) except OSError: pass log_file = open(log_file_path, "w") run = not args.dry_run and args.run log("burnin-drive") log("https://github.com/samuelkadolph/burnin-drive") log("===== Run Info") log("Device: %s" % dev) log("Make: %s" % make) log("Model: %s" % model) log("Serial: %s" % serial) log("badblocks File: %s" % bb_file_path) log("Log File: %s" % log_file_path) log("Dry Run: %s" % str(not run)) log("===== Raw SMART Info") log(clean_smartctl(smartinfo)) try: run_smart_test("short") run_badblocks() run_smart_test("short") run_smart_test("long") except ProcessError as e: log(e.message) exit(1)
Java
UTF-8
876
2.1875
2
[]
no_license
package com.csv.csv.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Pattern; @NoArgsConstructor @AllArgsConstructor @Data public class VendorVo { private Long id; @NonNull @NotEmpty private String firstName; @NonNull @NotEmpty private String lastName; @NonNull @NotEmpty @Email private String email; private Integer age; @NonNull @NotEmpty @Length(min = 10, max = 10) private String mobile; private String address; private String city; private String state; private String zip; private String country; private Double salary; }
Python
UTF-8
1,642
2.53125
3
[]
no_license
"""analyzing EIA data """ from climate.eia import base as b from functools import cached_property import pandas as pd from typing import List, Dict class GenFuel(b.GenFuel): def __init__(self, loc: str): super().__init__(loc=loc) @cached_property def df_nys(self) -> pd.DataFrame: return self.df[self.df.plant_state == "NY"] @cached_property def df_nyc(self) -> pd.DataFrame: return self.df.query("nyc == 1") @cached_property def df_nyc_plants(self) -> pd.DataFrame: return self.df_nyc.groupby( ["plant_id", "plant_name", "operator_name", "borough"], as_index=False ).agg({"gwh": "sum"}) @cached_property def df_nyc_plants_top(self) -> pd.DataFrame: return self.df_nyc_plants.sort_values("gwh", ascending=False).iloc[:10] @cached_property def df_nyc_plants_top_queens(self) -> pd.DataFrame: return self.df_nyc_plants_top.query("borough == 'Queens'") @cached_property def list_nyc_plants_top_queens(self) -> List[Dict]: return self.df_nyc_plants_top_queens.to_dict(orient="records") @cached_property def df_queens(self) -> pd.DataFrame: return self.df_nyc.query("borough == 'Queens'") @cached_property def df_queens_plants(self) -> pd.DataFrame: return self.df_nyc_plants.query("borough == 'Queens'") @cached_property def df_queens_top(self) -> pd.DataFrame: return self.df_nyc.merge( right=self.df_nyc_plants_top_queens[["plant_id"]], on=["plant_id"], how="inner", validate="many_to_one", )
C
UTF-8
973
3.46875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once #include <libmath/Math.h> typedef struct { double x; double y; double z; } Vec3f; static inline Vec3f vec3f_norm(Vec3f vector) { double length = sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); vector.x /= length; vector.y /= length; vector.z /= length; return vector; } static inline Vec3f vec3f_sub(Vec3f left, Vec3f right) { return (Vec3f){left.x - right.x, left.y - right.y, left.z - right.z}; } static inline Vec3f vec3f_cross(Vec3f left, Vec3f right) { Vec3f result = {}; result.x = left.y * right.z - left.z * right.y; result.y = left.z * right.x - left.x * right.z; result.z = left.x * right.y - left.y * right.x; result = vec3f_norm(result); return result; } static inline double vec3f_dot(Vec3f left, Vec3f right) { return left.x * right.x + left.y * right.y + left.z * right.z; }
Java
UTF-8
4,423
2.6875
3
[]
no_license
package hu.oe.nik.szfmv.automatedcar.model; import hu.oe.nik.szfmv.automatedcar.model.objects.CrossWalk; import hu.oe.nik.szfmv.automatedcar.model.objects.NpcCar; import hu.oe.nik.szfmv.automatedcar.model.objects.NpcPedestrian; import hu.oe.nik.szfmv.automatedcar.model.objects.ParkingPlace; import hu.oe.nik.szfmv.automatedcar.virtualfunctionbus.packets.camera.SimpleDetector; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; public class World { private static final Logger LOGGER = LogManager.getLogger(); public static final int WIDTH = 5120; public static final int HEIGHT = 3000; private static World instance; private List<WorldObject> worldObjects = new ArrayList<>(); private List<ScriptedPath> npcPaths = new ArrayList<>(); public static World getInstance() { // Thread safety is not needed in this singleton if (instance == null) { instance = new World(); } return instance; } private World() { worldObjects = createWorld(); SimpleDetector det = SimpleDetector.getDetector(); det.setWorldObjects(this.worldObjects); } public List<WorldObject> createWorld() { try { File xml = new File(ClassLoader.getSystemResource("test_world.xml").getFile()); return XmlParser.build(xml); } catch (Exception e) { System.out.printf(e.getMessage()); return new ArrayList<WorldObject>(); } } public List<WorldObject> getWorldObjects() { return worldObjects; } /** * Add an object to the virtual world. * * @param o {@link WorldObject} to be added to the virtual world */ public void addObjectToWorld(WorldObject o) { worldObjects.add(o); } public void initializeNpcsAndPaths() { List<WorldObject> worldObjects = List.copyOf(this.worldObjects); for (WorldObject worldObject : worldObjects) { if (worldObject instanceof CrossWalk) { CrossWalk crossWalk = (CrossWalk) worldObject; Waypoint startPoint = crossWalk.getStartPoint(); Waypoint endPoint = crossWalk.getEndPoint(); NpcPedestrian pedestrian = new NpcPedestrian(1000, 1000, "man.png", "man.png", "man.png"); ScriptedPath path = new ScriptedPath(pedestrian); List<Waypoint> waypoints = new ArrayList<>(); waypoints.add(startPoint); waypoints.add(endPoint); path.setWaypoints(waypoints); path.setMovementSpeed(300); path.setLoopType(ScriptedPath.LoopType.PINGPONG); path.init(); this.addObjectToWorld(pedestrian); npcPaths.add(path); pedestrian.setPath(path); path.start(); } } } public void initializeParkingPlaces() { List<WorldObject> worldObjects = List.copyOf(this.worldObjects); for (WorldObject worldObject : worldObjects) { if (worldObject instanceof ParkingPlace) { ParkingPlace parkingPlace = (ParkingPlace) worldObject; parkingPlace.initializePaths(parkingPlace); placeCar(parkingPlace); } } } public void placeCar(ParkingPlace parkingPlace) { Random r = new Random(); boolean upper = r.nextBoolean(); Vector2D position; if (upper) { position = parkingPlace.getCenterUpper(); parkingPlace.setUpperEmpty(false); parkingPlace.setLowerEmpty(true); } else { position = parkingPlace.getCenterLower(); parkingPlace.setLowerEmpty(false); parkingPlace.setUpperEmpty(true); } NpcCar car = new NpcCar((int) position.getX(), (int) position.getY(), "car_1_blue.png", "car_1_blue.png", "car_1_blue.png"); car.setRotation(parkingPlace.getRotation() + (float) Math.toRadians(-90)); addObjectToWorld(car); } public List<ScriptedPath> getNpcPaths() { return npcPaths; } }
C++
UTF-8
1,044
2.859375
3
[]
no_license
#ifndef __MODEL_ACTION_HPP__ #define __MODEL_ACTION_HPP__ #include "Stream.hpp" #include "model/BuildingAction.hpp" #include "model/BuildingType.hpp" #include "model/MoveAction.hpp" #include "model/Resource.hpp" #include "model/Specialty.hpp" #include <optional> #include <sstream> #include <stdexcept> #include <string> #include <vector> namespace model { // Player's actions class Action { public: // List of movement orders std::vector<model::MoveAction> moves; // List of building orders std::vector<model::BuildingAction> buildings; // Choosing specialty std::optional<model::Specialty> chooseSpecialty; Action(std::vector<model::MoveAction> moves, std::vector<model::BuildingAction> buildings, std::optional<model::Specialty> chooseSpecialty); // Read Action from input stream static Action readFrom(InputStream& stream); // Write Action to output stream void writeTo(OutputStream& stream) const; // Get string representation of Action std::string toString() const; }; } #endif
JavaScript
UTF-8
2,150
3.046875
3
[ "MIT" ]
permissive
'use strict'; const utils = require('./utils'); /** * A wrapper to collect errors * @class */ class Errors extends Error { constructor() { super(); this.isOvt = true; this.hasErrors = false; this.name = 'ValidationError'; this._errors = {}; } /** * reset errors */ reset() { this.hasErrors = false; this._errors = {}; return this; } /** * add a new error * { * isEmail: ['not a valid email'] * } */ add(name, msg) { this.hasErrors = true; msg = msg || this.defaultMessage(name); let messages = this._errors[name] || []; this._errors[name] = messages.concat(msg); return this; } get(name) { return this._errors[name]; } concat(errors) { let newErrors = new Errors(); if (this.any()) newErrors = newErrors.concat(this); if (errors && errors.any()) { for (let key in errors._errors) { newErrors.add(key, errors.get(key)); } } return newErrors; } /** * To human readable format * example: email is not a valid; name is required */ toHuman(wrapper) { return this.flatten(wrapper).join('; '); } /** * Flatten Error Message * example: ['email is not a valid', 'name is required'] */ flatten(wrapper) { wrapper = wrapper || function(name, msg) { return `${name} ${msg}`; }; utils.assert( typeof wrapper === 'function', `${wrapper} is not a valid wrapper function` ); let errors = []; for (let name in this._errors) { let messages = this._errors[name] || []; for(let i = 0; i < messages.length; i++) { let msg = messages[i] || this.defaultMessage(name); if (msg instanceof Error) msg = msg.message; errors.push(wrapper(name, msg)); } } return errors; } /** * To JSON format */ asJSON() { return this._errors; } /** * Default message format */ defaultMessage(name) { return 'Validation ' + name + ' failed'; } /** * Check if there exists any error */ any() { return this.hasErrors; } } module.exports = Errors;
C
UTF-8
370
3.59375
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> /** * main - Entry point * * Return: Always 0 (Success) */ int main(void) { int i; int a = 0; int b; for (i = 0; i < 10; i++) { for (a = a; a < 10; a++) { if (i != a) { putchar(i + '0'); putchar(a + '0'); if (i != 8 || a != 9) { putchar(','); putchar(' '); } } } b++; a = b; } putchar('\n'); return (0); }
PHP
UTF-8
1,085
2.59375
3
[ "MIT" ]
permissive
<?php namespace Payum2\Heartland\Soap\Base; /** * This class is generated from the following WSDL: * https://heartlandpaymentservices.net/BillingDataManagement/v3/BillingDataManagementService.svc?xsd=xsd0 */ class RegisterTokenToAdditionalMerchant { /** * request * * The property has the following characteristics/restrictions: * - SchemaType: q43:RegisterTokenToAdditionalMerchantRequest * * @var RegisterTokenToAdditionalMerchantRequest */ protected $request = null; /** * @param RegisterTokenToAdditionalMerchantRequest $request * * @return RegisterTokenToAdditionalMerchant */ public function setRequest(RegisterTokenToAdditionalMerchantRequest $request) { $this->request = $request; return $this; } /** * @return RegisterTokenToAdditionalMerchantRequest */ public function getRequest() { if (null === $this->request) { $this->request = new RegisterTokenToAdditionalMerchantRequest(); } return $this->request; } }
Python
UTF-8
1,177
3.84375
4
[]
no_license
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.ans = None def find_lowest_common_ancestor(self, node: 'TreeNode', a: 'TreeNode', b: 'TreeNode') -> 'TreeNode': def helper(curr: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> bool: if curr is None: return False left = helper(curr.left, p, q) right = helper(curr.right, p, q) mid = curr == p or curr == q if left + right + mid >= 2: self.ans = curr return left or right or mid helper(node, a, b) return self.ans if __name__ == '__main__': root = TreeNode(1) root.left = TreeNode(2) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right = TreeNode(3) root.right.right = TreeNode(7) root.right.left = TreeNode(6) root.right.right.left = TreeNode(8) root.right.right.right = TreeNode(9) print(Solution().find_lowest_common_ancestor(root, root.right.left, root.right.right.right).val)
Java
UTF-8
1,631
2.34375
2
[]
no_license
package ir.abrstudio.negarkhaneh; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import com.bumptech.glide.Glide; import java.util.List; public class ImagesAdapter extends BaseAdapter { private final Context context; List<Image> images; private class ViewHolder { public ImageView image; } public ImagesAdapter(Context context, List<Image> images) { this.context = context; this.images = images; } private Context getContext() { return context; } @Override public int getCount() { return images.size(); } @Override public Object getItem(int i) { return this.images.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { View toReturn = view; Image image = (Image) this.getItem(i); if (toReturn == null) { LayoutInflater inflater = (LayoutInflater) this.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); toReturn = inflater.inflate(R.layout.grid_image_item, viewGroup, false); } ViewHolder holder = null; if (toReturn.getTag() != null && toReturn.getTag() instanceof ViewHolder) { holder = (ViewHolder) toReturn.getTag(); } if (holder == null) { holder = new ViewHolder(); holder.image = (ImageView) toReturn.findViewById(R.id.tile_image); toReturn.setTag(holder); } Glide.with(getContext()).load(image.getImageAddress()).asBitmap() .fitCenter().into(holder.image); return toReturn; } }
Java
UTF-8
473
3
3
[]
no_license
package cz.itstep; import java.util.Scanner; public class WhileExample1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true) { System.out.print("vstup: "); String input = scanner.nextLine(); if ("x".equals(input)) { break; } System.out.println("zadali jste -> " + input); } System.out.println("konec"); } }
Python
UTF-8
103
3.609375
4
[]
no_license
# Getting the last # character of a string str = 'Hello, World!' # ^ print(str[-1])
Java
UTF-8
5,178
2
2
[ "Apache-2.0" ]
permissive
package com.jd.management.condition; import java.io.Serializable; import java.lang.String; /** * 资源 * @org ${entityMeta.projectMeta.domainName} * @author jiaodong * @Date 2017-01-06 15:05:16 */ public class ResourcesCondition implements Serializable { private static final long serialVersionUID = 1L; /** * 唯一标识 */ private String id; /** * 资源编码 */ private String resourceCode; /** * 资源名称 */ private String resourceName; /** * 资源类型 1:菜单资源 2:功能资源 3:虚拟资源 */ private String resourceType; /** * 资源路径 */ private String resourceUrl; /** * 资源Level */ private String resourceLevel; /** * 资源图标名 */ private String resourceIcon; /** * 资源排序 */ private String resourceOrder; /** * 资源状态 */ private String status; /** * 资源描述 */ private String description; /** * 资源父节点ID */ private String parentId; /** * 创建时间 */ private String createTime; /** * 更新时间 */ private String updateTime; /** * 创建用户 */ private String createUser; /** * 更新用户 */ private String updateUser; /** * 默认时间 */ private String ts; /** * 刪除标志 */ private String yn; /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the resourceCode */ public String getResourceCode() { return resourceCode; } /** * @return the resourceName */ public String getResourceName() { return resourceName; } /** * @return the resourceType */ public String getResourceType() { return resourceType; } /** * @return the resourceUrl */ public String getResourceUrl() { return resourceUrl; } /** * @return the resourceLevel */ public String getResourceLevel() { return resourceLevel; } /** * @return the resourceIcon */ public String getResourceIcon() { return resourceIcon; } /** * @return the resourceOrder */ public String getResourceOrder() { return resourceOrder; } /** * @return the status */ public String getStatus() { return status; } /** * @return the description */ public String getDescription() { return description; } /** * @return the parentId */ public String getParentId() { return parentId; } /** * @return the createTime */ public String getCreateTime() { return createTime; } /** * @return the updateTime */ public String getUpdateTime() { return updateTime; } /** * @return the createUser */ public String getCreateUser() { return createUser; } /** * @return the updateUser */ public String getUpdateUser() { return updateUser; } /** * @return the ts */ public String getTs() { return ts; } /** * @return the yn */ public String getYn() { return yn; } /** * @param resourceCode the resourceCode to set */ public void setResourceCode(String resourceCode) { this.resourceCode = resourceCode; } /** * @param resourceName the resourceName to set */ public void setResourceName(String resourceName) { this.resourceName = resourceName; } /** * @param resourceType the resourceType to set */ public void setResourceType(String resourceType) { this.resourceType = resourceType; } /** * @param resourceUrl the resourceUrl to set */ public void setResourceUrl(String resourceUrl) { this.resourceUrl = resourceUrl; } /** * @param resourceLevel the resourceLevel to set */ public void setResourceLevel(String resourceLevel) { this.resourceLevel = resourceLevel; } /** * @param resourceIcon the resourceIcon to set */ public void setResourceIcon(String resourceIcon) { this.resourceIcon = resourceIcon; } /** * @param resourceOrder the resourceOrder to set */ public void setResourceOrder(String resourceOrder) { this.resourceOrder = resourceOrder; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @param parentId the parentId to set */ public void setParentId(String parentId) { this.parentId = parentId; } /** * @param createTime the createTime to set */ public void setCreateTime(String createTime) { this.createTime = createTime; } /** * @param updateTime the updateTime to set */ public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } /** * @param createUser the createUser to set */ public void setCreateUser(String createUser) { this.createUser = createUser; } /** * @param updateUser the updateUser to set */ public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } /** * @param ts the ts to set */ public void setTs(String ts) { this.ts = ts; } /** * @param yn the yn to set */ public void setYn(String yn) { this.yn = yn; } }
Java
UTF-8
1,193
2.015625
2
[]
no_license
package net.sunwukong.www.api.config; import com.sdkinfo.www.setting.dialect.Props; import java.util.Properties; /** * @author swk * @Description :配置文件 * @Date 2018/8/1321:38 * @Email :ideacoding@163.com * @Version 1.0 **/ public class SwkConfig { /** * FTP地址 */ public static String FTP_HOSTNAME; /** * FTP端口 */ public static int FTP_PORT; /** * FTP用户名 */ public static String FTP_USERNAME; /** * FTP密码 */ public static String FTP_PASSWORD; /** * 生成URL地址前缀 */ public static String FTP_PATH; /** * H5文件主域名 */ public static String HTML_PATH; static { Properties prop = Props.getProp("swk.properties"); FTP_HOSTNAME = prop.getProperty("swk.ftp.hostname"); FTP_PORT = Integer.parseInt(prop.getProperty("swk.ftp.port")); FTP_USERNAME = prop.getProperty("swk.ftp.username"); FTP_PASSWORD = prop.getProperty("swk.ftp.password"); FTP_PATH = prop.getProperty("swk.ftp.path"); HTML_PATH = prop.getProperty("swk.host.html"); } }
Java
UTF-8
894
2.59375
3
[]
no_license
package cn.idea360.demo.enums; import lombok.Getter; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * 二维码状态 */ @Getter //@JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum QrCodeEnum implements Serializable { NOT_SCAN(1, "未被扫描"), SCANNED(2, "被扫描"), VERIFIED(3, "确认完后"), EXPIRED(4, "过期"), FINISH(5, "完成"), ; private final int value; private final String text; QrCodeEnum(int value, String text) { this.value = value; this.text = text; } private static final Map<Integer, QrCodeEnum> map = new HashMap<>(); static { Arrays.stream(QrCodeEnum.values()).forEach(e -> map.put(e.getValue(), e)); } public static QrCodeEnum getEnumByValue(int value) { return map.getOrDefault(value, null); } }
Java
UTF-8
859
1.851563
2
[]
no_license
package com.example.demojersey; import com.example.demojersey.common.UserSvcConfigBean; import com.example.demojersey.services.HelloService; import com.example.demojersey.services.ReverseService; import com.example.demojersey.services.UserService; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import javax.ws.rs.Path; import javax.ws.rs.core.Feature; @Configuration //@Path("/") public class ApplicationConfig extends ResourceConfig { public ApplicationConfig() { register(HelloService.class); register(ReverseService.class); register(UserService.class); register(MultiPartFeature.class); } }
Rust
UTF-8
646
2.609375
3
[ "MIT" ]
permissive
mod rodio; use crate::source::Source; #[derive(Debug)] pub struct Player { #[cfg(target_arch = "wasm32")] backend: (), #[cfg(not(target_arch = "wasm32"))] backend: rodio::Rodio, } impl Player { pub fn new() -> Option<Self> { Backend::new().map(|backend| Player { backend }) } pub fn play<S>(&self, stream: S) where S: Source + 'static, { self.backend.play(stream) } pub fn wait(&self) { self.backend.wait() } } trait Backend: Sized { fn new() -> Option<Self>; fn play<S>(&self, stream: S) where S: Source + 'static; fn wait(&self); }
Java
UTF-8
1,036
2.375
2
[]
no_license
package Day15; import Day8.ChromeBrowser; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; import java.util.concurrent.TimeUnit; public class CapitalLetterActions2 { public static void main(String[] args) { ChromeBrowser myBrowser=new ChromeBrowser(); WebDriver driver=myBrowser.invokeChromeBrowser(); driver.get("http://www.facebook.com"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); Actions myActions=new Actions(driver); WebElement myElement=driver.findElement(By.cssSelector("input#email")); Action action=myActions.moveToElement(myElement) .click() .keyDown(myElement,Keys.SHIFT) .sendKeys("mustafa") .keyUp(myElement,Keys.SHIFT) .build(); action.perform(); } }
Go
UTF-8
2,017
3.359375
3
[]
no_license
package parser import ( "fmt" "strconv" "strings" "unicode" ) type Member struct { Name string Coeff float64 Exp int Operand string } type Equation struct { LMembers []Member RMember Member } func parseMember(str string, memberPos int) (Member, error) { var member Member var err error str = strings.Trim(str, " ") fSplit := strings.Split(str, "^") if len(fSplit) == 2 { member.Name = string(fSplit[0][len(fSplit[0])-1]) Exp, err := strconv.Atoi(string(fSplit[1][0])) if err != nil { return member, fmt.Errorf("Error parsing member n°%d: Exp is not a int", memberPos) } member.Exp = Exp } switch string(str[0]) { case "-": member.Operand = "-" default: member.Operand = "+" } i := 0 for unicode.IsDigit(rune(str[i])) || string(str[i]) == "+" || string(str[i]) == "-" || string(str[i]) == " " || string(str[i]) == "." { i++ } Coeff, err := strconv.ParseFloat(strings.Replace(string(str[0:i]), " ", "", -1), 64) if err != nil { return member, fmt.Errorf("Error parsing member n°%d: Coeff is not a int", memberPos) } member.Coeff = Coeff return member, nil } func getOperandPos(side string) []int { var positions []int positions = append(positions, 0) for i, c := range side { if string(c) == "+" || string(c) == "-" { positions = append(positions, i) } } positions = append(positions, len(side)-1) return positions } func ParseEquation(equation string) (Equation, error) { var members []Member sides := strings.Split(equation, "=") if len(sides) > 2 || len(sides) == 1 { return Equation{}, fmt.Errorf("Equation malformatted") } positions := getOperandPos(sides[0]) i := 0 for i < len(positions)-1 { var err error var member Member member, err = parseMember(string(sides[0][positions[i]:positions[i+1]]), i+1) if err != nil { return Equation{}, err } members = append(members, member) i++ } rightMember, _ := parseMember(string(sides[1]), -1) return Equation{LMembers: members, RMember: rightMember}, nil }
Python
UTF-8
1,900
2.9375
3
[]
no_license
""" 监控代码:监控服务器的内存、cpu、网络、磁盘等。与租车系统部署到一起 """ from asyncio import sleep from datetime import datetime import psutil print(psutil.cpu_percent()) # 获取cpu的信息 print(psutil.virtual_memory()) # 虚拟的内存 print(psutil.virtual_memory().percent) # 虚拟内存的百分比 print(psutil.disk_usage("d:/")) # 租车系统所在的磁盘 print(psutil.disk_usage("d:/").percent) # 租车系统所在的磁盘百分比 print(psutil.net_io_counters()) # 网络 print(psutil.net_io_counters().bytes_sent) # 发送的字节数 print(psutil.net_io_counters().bytes_recv) # 接收的字节数 print(333) # for i in range(3): # print(psutil.cpu_percent()) # 获取cpu的信息 # print(psutil.virtual_memory()) # 虚拟的内存 # print(psutil.virtual_memory().percent) # 虚拟内存的百分比 # print(psutil.disk_usage("d:/")) # 租车系统所在的磁盘 # print(psutil.disk_usage("d:/").percent) # 租车系统所在的磁盘百分比 # print(psutil.net_io_counters()) # 网络 # print(psutil.net_io_counters().bytes_sent) # 发送的字节数 # print(psutil.net_io_counters().bytes_sent) # 接收的字节数 with open("d:/资源占用情况.txt", mode='a', encoding='utf-8') as file: file.write("时间戳\tcpu%\t内存%\t磁盘\t发送字节数\t接收字节数\n") print() while True: print("监控中。。。。。") file.write(datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S") + '\t') file.write(str(psutil.cpu_percent()) + "%\t") file.write(str(psutil.virtual_memory().percent) + "%\t") file.write(str(psutil.disk_usage("d:/").percent) + "%\t") file.write(str(psutil.net_io_counters().bytes_sent) + "%\t") file.write(str(psutil.net_io_counters().bytes_recv) + "%\n") file.flush() sleep(3)
Shell
UTF-8
268
3.203125
3
[ "MIT" ]
permissive
#!/bin/bash if [ $# -lt 1 ]; then echo -e "\e[31mUsage: $0 [cmd]\e[m" exit 1 fi show-versions if [[ "${INPUT_DANGERFILE}" == '' ]]; then DANGERFILE_ARGS='' else DANGERFILE_ARGS="--dangerfile ${INPUT_DANGERFILE}" fi danger-swift $@ $DANGERFILE_ARGS
Java
UTF-8
3,087
2.3125
2
[]
no_license
package com.tdc.poa.integration; import static org.junit.Assert.assertEquals; import java.util.HashSet; import java.util.Set; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.transaction.api.annotation.TransactionMode; import org.jboss.arquillian.transaction.api.annotation.Transactional; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.runner.RunWith; import com.tdc.poa.crud.Crud; import com.tdc.poa.model.Attendee; import com.tdc.poa.model.Talk; import com.tdc.poa.service.AttendeeService; import com.tdc.poa.service.TalkService; import cucumber.api.java.Before; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.runtime.arquillian.ArquillianCucumber; import cucumber.runtime.arquillian.api.Features; /** * mais exemplos em: https://github.com/cukespace/cukespace e aqui: * https://github.com/cukespace/cukespace/tree/master/examples * * @author RAFAEL-PESTANO * */ @RunWith(ArquillianCucumber.class) @Features("features/talk/insert-talk.feature") @Transactional(TransactionMode.DISABLED) public class InsertTalkBdd { @Inject TalkService talkService; @Inject AttendeeService attendeeService; Talk talk; int numTalks; @Deployment public static WebArchive createDeployment() { WebArchive war = ShrinkWrap .create(WebArchive.class, "test.war") .addPackage("com.tdc.poa.service") .addClass(Crud.class) .addPackages(true, Talk.class.getPackage()) // .addAsWebInfResource(new // File("src/main/webapp/WEB-INF/web.xml"), "web.xml") .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); System.out.println(war.toString(true)); return war; } @Before public void setup() { talkService.clearTalks(); attendeeService.clearAttendees(); } // não podemos usar DBUnit(@UsingDataset) com cucumber // ainda:https://github.com/cukespace/cukespace/issues/37 @Given("^a talk with title \"([^\"]*)\" with (\\d+) slots and (\\d+) attenddes$") public void given(String title, int slots, int numAtendees) { //talkService.clearTalks();//@Before executed one time for all scenarios talk = new Talk(); talk.setTitle(title); talk.setSlots(slots); talk.setAttendees(initAttendees(numAtendees)); } @When("^i persist the talk$") public void when() { try { talkService.store(talk); } catch (RuntimeException e) { e.printStackTrace(); } } @Then("^i should have (\\d+) talk$") public void then(int numTalks) { assertEquals(numTalks, talkService.crud().countAll()); } private Set<Attendee> initAttendees(int numAtendees) { Set<Attendee> attendees = new HashSet<Attendee>(); for (int i = 0; i < numAtendees; i++) { Attendee attendee = new Attendee(); attendee.setName("attendee" + i); attendee.setAge(i); attendees.add(attendee); } return attendees; } }
C++
UTF-8
1,562
3.15625
3
[]
no_license
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE426_Untrusted_Search_Path__char_popen_83_bad.cpp Label Definition File: CWE426_Untrusted_Search_Path.label.xml Template File: sources-sink-83_bad.tmpl.cpp */ /* * @description * CWE: 426 Untrusted Search Path * BadSource: Don't specify the full path in the OS command * GoodSource: Specify the full path in the OS command * Sinks: popen * BadSink : Execute the popen function * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE426_Untrusted_Search_Path__char_popen_83.h" #ifdef _WIN32 #define POPEN _popen #define PCLOSE _pclose #else /* NOT _WIN32 */ #define POPEN popen #define PCLOSE pclose #endif namespace CWE426_Untrusted_Search_Path__char_popen_83 { CWE426_Untrusted_Search_Path__char_popen_83_bad::CWE426_Untrusted_Search_Path__char_popen_83_bad(char * dataCopy) { data = dataCopy; /* FLAW: the full path is not specified */ strcpy(data, BAD_OS_COMMAND); } CWE426_Untrusted_Search_Path__char_popen_83_bad::~CWE426_Untrusted_Search_Path__char_popen_83_bad() { { FILE *pipe; /* POTENTIAL FLAW: Executing the popen() function without specifying the full path to the executable * can allow an attacker to run their own program */ pipe = POPEN(data, "wb"); if (pipe != NULL) { PCLOSE(pipe); } } } } #endif /* OMITBAD */
Java
UTF-8
1,141
1.898438
2
[]
no_license
package rta.ae.sharekni; import android.annotation.TargetApi; import android.graphics.Color; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.widget.TextView; import rta.ae.sharekni.R; public class Destination_Activity extends AppCompatActivity { Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_destination_); initToolbar(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void initToolbar() { toolbar = (Toolbar) findViewById(R.id.app_bar); toolbar.setTitle(""); toolbar.setTitleTextColor(Color.WHITE); TextView textView = (TextView) toolbar.findViewById(R.id.mytext_appbar); textView.setText("Set Direction"); // toolbar.setElevation(10); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } }
PHP
UTF-8
1,142
2.828125
3
[ "Apache-2.0" ]
permissive
<?php $base_url = 'https://kodecentral.com'; // basic xml header info echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL. '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL; foreach ($urls as $url) { echo '<url>' . PHP_EOL; echo '<loc>'.$base_url.$url.'</loc>' . PHP_EOL; echo '<changefreq>daily</changefreq>' . PHP_EOL; echo '</url>' . PHP_EOL; } // posts foreach ($posts as $post) { echo '<url>' . PHP_EOL; echo '<loc>'.$base_url.'/post/'. $post->getHyperlink() .'</loc>' . PHP_EOL; echo '<changefreq>daily</changefreq>' . PHP_EOL; echo '</url>' . PHP_EOL; } // users foreach ($users as $user) { echo '<url>' . PHP_EOL; echo '<loc>'.$base_url.'/profile/'. urlencode($user->getUsername()) .'</loc>' . PHP_EOL; echo '<changefreq>daily</changefreq>' . PHP_EOL; echo '</url>' . PHP_EOL; } // libraries foreach ($libs as $lib) { echo '<url>' . PHP_EOL; echo '<loc>'.$base_url.'/lib/'. urlencode($lib->getName()) .'</loc>' . PHP_EOL; echo '<changefreq>daily</changefreq>' . PHP_EOL; echo '</url>' . PHP_EOL; } // close tag echo '</urlset>' . PHP_EOL;
JavaScript
UTF-8
2,321
3.0625
3
[]
no_license
let newBtn = document.getElementsByClassName('buttonNew') let div = null let arr = [] localStorage.clear(); function addNote() { document.getElementById('noteField').style.visibility = 'visible' let newNote = document.createElement('div'); document.getElementById('noteList').appendChild(newNote) document.getElementsByClassName('buttonNew').style.disabled = true } function SaveNote() { let currentTitle = document.getElementById('title').value let currentDescription = document.getElementById('description').value let notes = localStorage.getItem('inputField') if (notes == null) { arr = [] } else { arr = JSON.parse(notes) } arr.push({ title: currentTitle, description: currentDescription }) localStorage.setItem('inputField', JSON.stringify(arr)) showNoteList() resetNote() } function showNoteList() { let list = document.getElementById('noteList') list.innerHTML = '' for (let i = 0; i < arr.length; i++) { let newNoteDiv = document.createElement('div'); newNoteDiv.innerHTML = arr[i].title newNoteDiv.className = 'noteItem' newNoteDiv.addEventListener('click', (e) => { editNote(newNoteDiv) }) document.getElementById('noteList').appendChild(newNoteDiv) } } function resetNote() { document.getElementById('title').value = '' document.getElementById('description').value = '' } function editNote(div) { document.getElementById('title').value = div.innerHTML document.getElementById('description').value = arr.find(item => div.innerHTML === item.title).description } function deleteNote() { let notes = localStorage.getItem('inputField') if (notes == null) { arr = [] } else { arr = JSON.parse(notes) } arr.splice('inputField', 1); localStorage.setItem('inputField', JSON.stringify(arr)) showNoteList() } function sortByTitle() { if (localStorage.length > 0) { arr = new Array(); for (i = 0; i < localStorage.length; i++) { arr[i] = localStorage.key(i) + localStorage.getItem(localStorage.key(i)); } } var sortedArray = arr.sort(); return sortedArray; }
Markdown
UTF-8
1,210
2.75
3
[ "MIT" ]
permissive
# Weld CDI and Jetty There may be issues with Jetty and Weld. This is the minimal working setup. There is no special configuration in `web.xml` but `jetty-web.xml` is required. Because `jetty-web.xml` may be needed only for development purposes, but not for production (we might want to deploy it to Tomcat for example) I have created a special `dev` folder on the same level as `main` and `test`. To pickup this directory `maven-war-plugin` configuration was altered in `pom.xml` To run jetty, you need to activate dev profile and `jetty:run-war` instead of `jetty:run`, because the latter does not pick up `maven-war-plugin` configuration: > mvn -Pdev jetty:run-war ## "But dev profile complicates this minimal setup" In case you don't want all these problems with profiles: 1. move `jetty-web.xml` from `src/dev/webapp/WEB-INF` into `src/main/webapp/WEB-INF`, 2. remove `profiles` from the `pom.xml` 3. delete `src/dev` folder. Then setup will really be minimal. ## "What about Tomcat?" mvn verify And deploy the `.war` file to Tomcat > `verify` is the stage after `package` and before `install`. We do not always need to install the `.war` file to the repository.
Java
UTF-8
564
2.125
2
[]
no_license
package com.uiu.helper.KidsHelper.mvp.model.response; import com.google.gson.annotations.SerializedName; import com.uiu.helper.KidsHelper.mvp.model.Setting; import java.util.List; public class GetSettingsResponse extends BaseResponse { @SerializedName("setting") public Setting settings; public Setting getSettings() { return settings; } @Override public String toString(){ return "GetSettingsResponse{" + "settings = '" + settings + '\'' + "}"; } }
Java
UTF-8
3,433
3.46875
3
[]
no_license
package com.company.producerconsumer; public class Main { public static final int N_OF_RESOURCES_TOTAL = 5; public static void main(String[] args) { ResourceHolder resourceHolder = new ResourceHolder(); Producer producer = new Producer(resourceHolder); Consumer consumer = new Consumer(resourceHolder); new Thread(producer).start(); new Thread(consumer).start(); } } class ResourceHolder { private int nOfResources = 0; public synchronized void get() { while (nOfResources < 1) { try { wait(); } catch (InterruptedException e) { } } nOfResources--; System.out.println("-----------------------"); System.out.println("//Consumer just made -1"); System.out.println(">>>>>Current resources: " + nOfResources); notify(); } public synchronized void put() { while (nOfResources >= 3) { try { wait(); } catch (InterruptedException e) { } } nOfResources++; System.out.println("-----------------------"); System.out.println("//Producer just made +1"); System.out.println(">>>>>Current resources: " + nOfResources); notify(); } } class Producer implements Runnable { private ResourceHolder resourceHolder; Producer(ResourceHolder resourceHolder) { this.resourceHolder = resourceHolder; } public void run() { for (int i = 0; i < Main.N_OF_RESOURCES_TOTAL; i++) { resourceHolder.put(); } } } class Consumer implements Runnable { private ResourceHolder resourceHolder; Consumer(ResourceHolder resourceHolder) { this.resourceHolder = resourceHolder; } public void run() { for (int i = 0; i < Main.N_OF_RESOURCES_TOTAL; i++) { resourceHolder.get(); } } } //public class Main { // // private static final int N_OF_THREADS = 5; // // public static void main(String[] args) { // // CommonResource commonResource = new CommonResource(); // for (int i = 0; i < N_OF_THREADS; i++) { // // Thread t = new Thread(new CountThread(commonResource)); // t.setName("Thread #" + i+1); // t.start(); // } // } //} // //class CountThread implements Runnable { // // private CommonResource res; // // CountThread(CommonResource res) { // this.res = res; // } // // public void run() { // res.increment(); // } //} // //class CommonResource { // // private int x; // private static final int INCREMENT_LIMIT = 5; // // synchronized void increment() { // x = 0; // for (int i = 0; i < INCREMENT_LIMIT; i++) { // System.out.printf("%s has res = %d; \n", Thread.currentThread().getName(), x); // x++; // try { // Thread.sleep(100); // } catch (InterruptedException e) { // //e.printStackTrace(); // System.out.println(Thread.currentThread().getName() + " has been interrupted"); // System.out.println(Thread.currentThread().isInterrupted()); // false // Thread.currentThread().interrupt(); // } // } // System.out.println("____________________________________________"); // } //}
SQL
UTF-8
997
3.203125
3
[]
no_license
# A table for mapping variations to variation_sets CREATE TABLE IF NOT EXISTS variation_set_variation ( variation_id int(10) unsigned NOT NULL, variation_set_id int(10) unsigned NOT NULL, PRIMARY KEY (variation_id,variation_set_id), KEY variation_set_idx (variation_set_id,variation_id) ); # A table containing variation_set information CREATE TABLE IF NOT EXISTS variation_set ( variation_set_id int(10) unsigned NOT NULL AUTO_INCREMENT, name VARCHAR(255), description TEXT, PRIMARY KEY (variation_set_id), KEY name_idx (name) ); # A table containing relashionship between variation sets CREATE TABLE IF NOT EXISTS variation_set_structure ( variation_set_super int(10) unsigned NOT NULL, variation_set_sub int(10) unsigned NOT NULL, PRIMARY KEY (variation_set_super,variation_set_sub), KEY sub_idx (variation_set_sub,variation_set_super) ); # patch identifier INSERT INTO meta (species_id, meta_key, meta_value) VALUES (NULL,'patch', 'patch_56_57_e.sql|variation set tables');
Java
UTF-8
9,492
1.96875
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 1998-2018 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.ft.coverage; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ucar.ma2.Array; import ucar.ma2.InvalidRangeException; import ucar.nc2.constants.FeatureType; import ucar.nc2.ft2.coverage.*; import ucar.nc2.time.CalendarDate; import ucar.nc2.util.Misc; import ucar.unidata.util.test.Assert2; import ucar.unidata.util.test.category.NeedsCdmUnitTest; import ucar.unidata.util.test.TestDir; import java.io.IOException; import java.lang.invoke.MethodHandles; /** * Test Grib Collection reading. * LOOK: Tests are flakey, is there a caching issue? * * @author caron * @since 2/9/2016. */ @Category(NeedsCdmUnitTest.class) public class TestGribCoverageRead { private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); CalendarDate useDate = CalendarDate.parseISOformat(null, "2014-10-27T06:00:00Z"); @Test public void TestTwoDRead() throws IOException, InvalidRangeException { String endpoint = TestDir.cdmUnitTestDir + "gribCollections/gfs_conus80/gfsConus80_file.ncx4"; logger.debug("open {}", endpoint); try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) { assert cc != null; Assert.assertEquals(2, cc.getCoverageCollections().size()); CoverageCollection gds = cc.getCoverageCollections().get(0); Assert.assertEquals(FeatureType.FMRC, gds.getCoverageType()); String covName = "Temperature_isobaric"; Coverage cover = gds.findCoverage(covName); Assert.assertNotNull(covName, cover); long size = cover.getSizeInBytes(); Assert.assertEquals(6 * 36 * 29 * 65 * 93 * 4, size); // LOOK if we dont set the runtime, assume latest. driven by Cdmrf spec. could be different. SubsetParams subset = new SubsetParams().setVertCoord(300.0).setTime(useDate); GeoReferencedArray geo = cover.readData(subset); Array data = geo.getData(); logger.debug("{}", Arrays.toString(data.getShape())); Assert.assertArrayEquals(new int[] {1, 1, 1, 65, 93}, data.getShape()); float first = data.getFloat(0); float last = data.getFloat((int) data.getSize() - 1); logger.debug("data first = {} last = {}", first, last); Assert2.assertNearlyEquals(241.699997, first); Assert2.assertNearlyEquals(225.099991, last); } } @Test public void TestBestRead() throws IOException, InvalidRangeException { String endpoint = TestDir.cdmUnitTestDir + "gribCollections/gfs_conus80/gfsConus80_file.ncx4"; logger.debug("open {}", endpoint); try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) { assert cc != null; Assert.assertEquals(2, cc.getCoverageCollections().size()); CoverageCollection gds = cc.getCoverageCollections().get(1); Assert.assertEquals(FeatureType.GRID, gds.getCoverageType()); String covName = "Temperature_isobaric"; Coverage cover = gds.findCoverage(covName); Assert.assertNotNull(covName, cover); long size = cover.getSizeInBytes(); Assert.assertEquals(41 * 29 * 65 * 93 * 4, size); SubsetParams subset = new SubsetParams().setVertCoord(300.0).setTime(useDate); GeoReferencedArray geo = cover.readData(subset); Array data = geo.getData(); logger.debug("{}", Arrays.toString(data.getShape())); Assert.assertArrayEquals(new int[] {1, 1, 65, 93}, data.getShape()); float first = data.getFloat(0); float last = data.getFloat((int) data.getSize() - 1); logger.debug("data first = {} last = {}", first, last); Assert2.assertNearlyEquals(241.699997, first); Assert2.assertNearlyEquals(225.099991, last); } } @Test public void TestSRCRead() throws IOException, InvalidRangeException { String endpoint = TestDir.cdmUnitTestDir + "gribCollections/gfs_conus80/20141025/GFS_CONUS_80km_20141025_0000.grib1.ncx4"; logger.debug("open {}", endpoint); try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) { assert cc != null; Assert.assertEquals(1, cc.getCoverageCollections().size()); CoverageCollection gds = cc.getCoverageCollections().get(0); Assert.assertEquals(FeatureType.GRID, gds.getCoverageType()); String covName = "Temperature_isobaric"; Coverage cover = gds.findCoverage(covName); Assert.assertNotNull(covName, cover); long size = cover.getSizeInBytes(); Assert.assertEquals(25243920, size); SubsetParams subset = new SubsetParams().setVertCoord(200.0).setTimeOffset(42.0); GeoReferencedArray geo = cover.readData(subset); Array data = geo.getData(); logger.debug("{}", Arrays.toString(data.getShape())); Assert.assertArrayEquals(new int[] {1, 1, 65, 93}, data.getShape()); float first = data.getFloat(0); float last = data.getFloat((int) data.getSize() - 1); logger.debug("data first = {} last = {}", first, last); Assert2.assertNearlyEquals(219.5f, first); Assert2.assertNearlyEquals(218.6f, last); } } @Test public void TestMRUTCRead() throws IOException, InvalidRangeException { String endpoint = TestDir.cdmUnitTestDir + "gribCollections/anal/HRRRanalysis.ncx4"; logger.debug("open {}", endpoint); try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) { assert cc != null; Assert.assertEquals(1, cc.getCoverageCollections().size()); CoverageCollection gds = cc.getCoverageCollections().get(0); Assert.assertEquals(FeatureType.GRID, gds.getCoverageType()); String covName = "Temperature_isobaric"; Coverage cover = gds.findCoverage(covName); Assert.assertNotNull(covName, cover); long size = cover.getSizeInBytes(); Assert.assertEquals(4 * 5 * 1377 * 2145 * 4, size); SubsetParams subset = new SubsetParams().setVertCoord(70000).setTimeOffset(2); GeoReferencedArray geo = cover.readData(subset); Array data = geo.getData(); logger.debug("{}", Arrays.toString(data.getShape())); Assert.assertArrayEquals(new int[] {1, 1, 1377, 2145}, data.getShape()); float val = data.getFloat(40600); logger.debug("data val at {} = {}", 40600, val); Assert2.assertNearlyEquals(281.627563, val); val = data.getFloat(55583); logger.debug("data val at {} = {}", 55583, val); Assert2.assertNearlyEquals(281.690063, val); } } @Test public void TestMRUTPRead() throws IOException, InvalidRangeException { String endpoint = TestDir.cdmUnitTestDir + "gribCollections/tp/GFSonedega.ncx4"; logger.debug("open {}", endpoint); try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) { assert cc != null; Assert.assertEquals(1, cc.getCoverageCollections().size()); CoverageCollection gds = cc.getCoverageCollections().get(0); Assert.assertEquals(FeatureType.GRID, gds.getCoverageType()); String covName = "Relative_humidity_sigma"; Coverage cover = gds.findCoverage(covName); Assert.assertNotNull(covName, cover); long size = cover.getSizeInBytes(); Assert.assertEquals(2 * 181 * 360 * 4, size); SubsetParams subset = new SubsetParams().setTimeOffset(6); GeoReferencedArray geo = cover.readData(subset); Array data = geo.getData(); logger.debug("{}", Arrays.toString(data.getShape())); Assert.assertArrayEquals(new int[] {1, 1, 181, 360}, data.getShape()); float val = data.getFloat(3179); logger.debug("data val at {} = {}", 3179, val); Assert2.assertNearlyEquals(98.0, val); val = data.getFloat(5020); logger.debug("data val at {} = {}", 5020, val); Assert2.assertNearlyEquals(60.0, val); } } @Test public void TestPofPRead() throws IOException, InvalidRangeException { String endpoint = TestDir.cdmUnitTestDir + "gribCollections/gfs_conus80/gfsConus80_file.ncx4"; logger.debug("open {}", endpoint); try (FeatureDatasetCoverage cc = CoverageDatasetFactory.open(endpoint)) { assert cc != null; Assert.assertEquals(2, cc.getCoverageCollections().size()); CoverageCollection gds = cc.getCoverageCollections().get(0); Assert.assertEquals(FeatureType.FMRC, gds.getCoverageType()); String covName = "Vertical_velocity_pressure_isobaric"; Coverage cover = gds.findCoverage(covName); Assert.assertNotNull(covName, cover); long size = cover.getSizeInBytes(); Assert.assertEquals(6 * 35 * 9 * 65 * 93 * 4, size); SubsetParams subset = new SubsetParams().setRunTime(CalendarDate.parseISOformat(null, "2014-10-24T12:00:00Z")) .setTimeOffset(42).setVertCoord(500); GeoReferencedArray geo = cover.readData(subset); Array data = geo.getData(); logger.debug("{}", Arrays.toString(data.getShape())); Assert.assertArrayEquals(new int[] {1, 1, 1, 65, 93}, data.getShape()); float val = data.getFloat(0); logger.debug("data val first = {}", val); Assert2.assertNearlyEquals(-0.10470009f, val); val = data.getFloat((int) data.getSize() - 1); logger.debug("data val last = {}", val); Assert2.assertNearlyEquals(0.18079996f, val); } } }
C++
UTF-8
403
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int r, n; cin >> r >> n; vector<int> used(r, 0); while (n--) { int num; cin >> num; used[num - 1] = 1; } bool empty = false; for (int i = 0; i < r; i++) { if (used[i] == 0) { empty = true; cout << i + 1 << endl; break; } } if (!empty) { cout << "too late" << endl; } return 0; }
Markdown
UTF-8
1,364
3.109375
3
[]
no_license
--- layout: default title: Logging into GitLab using LDAP --- ## Logging into GitLab using LDAP Recently, we deployed a GitLab instance, and my colleague discovered that when he logged in using our LDAP service account credentials, he ended up logging in as me; i.e., two different LDAP users with two pairs of usernames/passwords end up being the same user. I didn't want that to be the case, so I dug into this a bit. Using `ldapsearch` with the `sAMAccountName` attribute resulted in two users (correct), and the `gitlab-rake gitlab:ldap:check` output proved similarly unhelpful, so [I filed an issue](https://gitlab.com/gitlab-org/gitlab/issues/208138). Very quickly, I got a response that clued me to the problem. On our LDAP, we had two accounts bearing the same `email` attribute: > GitLab assumes that LDAP users have unique email addresses, otherwise it is possible for LDAP users with the same email address to share the same GitLab account. This from [https://docs.gitlab.com/ee/administration/auth/ldap.html#security](https://docs.gitlab.com/ee/administration/auth/ldap.html#security). This gels with my experience with GitLab so far. The technical documentation is excellent, it just works. And now I can say that my personal support experience was similarly great. TLDR: Correcting the email attributes resolved the issue I faced, not a bug.
PHP
UTF-8
2,124
2.546875
3
[]
no_license
<?php namespace App\Http\Controllers\Api; use App\Access\Repository\User\UserRepository; use App\Exceptions\Api\ApiException; use App\Http\Controllers\Controller; use App\Http\Requests\Api\User\UserLoginRequest; use App\Modules\Enums\ErrorCode; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; /** * Class UserController * @package App\Http\Controllers\Api */ class UserController extends Controller { /** * @var UserRepository */ protected $users; /** * @param UserRepository $users **/ public function __construct(UserRepository $users) { $this->users = $users; } /** * @param UserLoginRequest $request * @return \Illuminate\Http\JsonResponse * @throws \App\Exceptions\Api\ApiException */ public function login(UserLoginRequest $request) { Log::info("params".json_encode($request->all())); $response = $this->users->login($request->only("username", "password")); return $this->responseSuccess($response); } /** * Get current user info * @param Request $request * @return string */ public function current(Request $request) { $user = Auth('api')->user()->load('restaurant'); return response()->json($user); } /** * Logout User * @param Request $request * @return string */ public function logout(Request $request) { $this->users->logout(); return $this->responseSuccess(); } /** * @param Request $request * @return \Illuminate\Http\JsonResponse * @throws \App\Exceptions\Api\ApiException */ public function refreshToken(Request $request){ $response = $this->users->refreshToken(); return $this->responseSuccess($response); } /** * @param Request $request * @return \Illuminate\Http\JsonResponse * @throws \App\Exceptions\Api\ApiException */ public function validateToken(Request $request){ $response = $this->users->validateToken(); return $this->responseSuccess($response); } }
Shell
UTF-8
1,382
3.34375
3
[ "BSD-3-Clause" ]
permissive
#!/bin/bash # This script is meant to be called by the "script" step defined in # .travis.yml. See http://docs.travis-ci.com/ for more details. # The behavior of the script is controlled by environment variabled defined # in the .travis.yml in the top level folder of the project. # License: 3-clause BSD set -e set -v python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" python -c "import pandas; print('pandas %s' % pandas.__version__)" python -c "import multiprocessing as mp; print('%d CPUs' % mp.cpu_count())" run_tests() { TEST_CMD="pytest --showlocals --pyargs" # Get into a temp directory to run test from the installed scikit learn # and # check if we do not leave artifacts mkdir -p $TEST_DIR pushd $TEST_DIR if [[ "$COVERAGE" == "true" ]]; then TEST_CMD="$TEST_CMD --cov=iced --cov-report=xml" fi $TEST_CMD iced popd } run_ice_scripts() { pushd examples/HiC-pro bash launch_tests.sh popd } run_doc() { pushd doc mkdir -p _build/html make touch _build/html/.nojekyll popd } if [[ "$RUN_FLAKE8" == "true" ]]; then source build_tools/travis/flake8_diff.sh fi if [[ "$SKIP_TESTS" != "true" ]]; then run_tests run_ice_scripts fi if [[ "$DOC" == "true" ]]; then run_doc fi
Java
UTF-8
1,456
3.265625
3
[]
no_license
/** * This is the assignment of finding many genes in DNA for * Java programming: solving problems with software course. * @author Hsingyi Lin * @version 08/29/2019 */ import edu.duke.*; import java.io.File; public class Part2 { public double cgRatio(String dna) { int countCG = 0; int startIndex = 0; while (true) { int indexCG; int indexC = dna.indexOf("C", startIndex); int indexG = dna.indexOf("G", startIndex); if (indexC == -1 || (indexG != -1 && indexG < indexC)) { indexCG = indexG; } else { indexCG = indexC; } if (indexCG == -1) { break; } countCG++; startIndex += indexCG - startIndex + 1; } return (double) countCG / dna.length(); } public int countCTG(String dna) { int countCTG = 0; int startIndex = 0; while (true) { int indexCTG = dna.indexOf("CTG", startIndex); if (indexCTG == -1) { break; } countCTG++; startIndex += indexCTG - startIndex + 3; } return countCTG; } public void test() { double t1 = cgRatio("ATGCCATAG"); System.out.println(t1); int t2 = countCTG("ATGCCTGCTGATAGCTGAA"); System.out.println(t2); } }
SQL
UTF-8
277
3.640625
4
[]
no_license
SELECT cohorts.name AS cohort, SUM(completed_at - started_at) AS total_duration FROM assistance_requests JOIN students ON students.id = assistance_requests.student_id JOIN cohorts ON cohorts.id = students.cohort_id GROUP BY cohorts.name ORDER BY total_duration ASC ;
Rust
UTF-8
13,132
2.53125
3
[]
no_license
extern crate rand; extern crate input; use input::Key; use rand::Rng; use std::fs::File; use std::io::Read; use utils::*; const PC_START: usize = 0x200; static FONTSET: [u8; 80] = [ 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80 // F ]; #[allow(dead_code)] pub struct Chip8 { pub debug: bool, pub draw_flag: bool, pub delay_timer: u8, pub sound_timer: u8, pub key: [u8; 16], pub addr: u16, pub pc: u16, pub sp: u16, pub v: [u8; 16], pub stack: [u16; 16], pub memory: [u8; 4096], pub gfx: [u8; 64 * 32], pub rng: rand::ThreadRng, } #[allow(dead_code)] impl Chip8 { pub fn new() -> Chip8 { let mut chip8 = Chip8 { debug: false, draw_flag: true, delay_timer: 0, sound_timer: 0, key: [0; 16], addr: 0, pc: PC_START as u16, sp: 0, v: [0; 16], stack: [0; 16], memory: [0; 4096], gfx: [0; 64 * 32], rng: rand::thread_rng(), }; chip8.memory[0..0x50].copy_from_slice(&FONTSET); chip8 } pub fn load(&mut self, filename: &str) { let mut file = File::open(filename).unwrap(); let mut buf = [0u8; 1024]; let mut n = file.read(&mut buf).unwrap(); let mut i = PC_START; while n > 0 { self.memory[i..i + n].copy_from_slice(&buf[0..n]); i += n; n = file.read(&mut buf).unwrap(); } } pub fn emulate_cycle(&mut self) { let opcode = self.fetch_opcode(); self.handle_opcode(opcode); } pub fn handle_button_press(&mut self, key: Key) { match key { Key::D1 => self.key[0x1] = 1, Key::D2 => self.key[0x2] = 1, Key::D3 => self.key[0x3] = 1, Key::D4 => self.key[0xC] = 1, Key::Q => self.key[0x4] = 1, Key::W => self.key[0x5] = 1, Key::E => self.key[0x6] = 1, Key::R => self.key[0xD] = 1, Key::A => self.key[0x7] = 1, Key::S => self.key[0x8] = 1, Key::D => self.key[0x9] = 1, Key::F => self.key[0xE] = 1, Key::Z => self.key[0xA] = 1, Key::X => self.key[0x0] = 1, Key::C => self.key[0xB] = 1, Key::V => self.key[0xF] = 1, _ => {}, } } pub fn handle_button_release(&mut self, key: Key) { match key { Key::D1 => self.key[0x1] = 0, Key::D2 => self.key[0x2] = 0, Key::D3 => self.key[0x3] = 0, Key::D4 => self.key[0xC] = 0, Key::Q => self.key[0x4] = 0, Key::W => self.key[0x5] = 0, Key::E => self.key[0x6] = 0, Key::R => self.key[0xD] = 0, Key::A => self.key[0x7] = 0, Key::S => self.key[0x8] = 0, Key::D => self.key[0x9] = 0, Key::F => self.key[0xE] = 0, Key::Z => self.key[0xA] = 0, Key::X => self.key[0x0] = 0, Key::C => self.key[0xB] = 0, Key::V => self.key[0xF] = 0, _ => {}, } } #[inline(always)] fn fetch_opcode(&self) -> u16 { (self.memory[self.pc as usize] as u16) << 8 | self.memory[self.pc as usize + 1] as u16 } #[inline(always)] fn handle_opcode(&mut self, opcode: u16) { match opcode & 0xF000 { 0x0000 => match opcode & 0x000F { 0x0000 => { for i in 0..2048 { self.gfx[i] = 0x0; } self.draw_flag = true; self.pc += 2; }, 0x000E => { self.sp -= 1; self.pc = self.stack[self.sp as usize]; self.pc += 2; }, _ => panic!("unimplemented {:x}", opcode), }, 0x1000 => self.pc = get_addr(opcode), 0x2000 => { self.stack[self.sp as usize] = self.pc; self.sp += 1; self.pc = get_addr(opcode); }, 0x3000 => { if self.v[get_vx(opcode)] == (opcode & 0x00FF) as u8 { self.pc += 4; } else { self.pc += 2; } }, 0x4000 => { if self.v[get_vx(opcode)] != (opcode & 0x00FF) as u8 { self.pc += 4; } else { self.pc += 2; } }, 0x5000 => { if self.v[get_vx(opcode)] == self.v[get_vy(opcode)] { self.pc += 4; } else { self.pc += 2; } }, 0x6000 => { self.v[get_vx(opcode)] = (opcode & 0x00FF) as u8; self.pc += 2; }, 0x7000 => { let vx = get_vx(opcode); self.v[vx] = self.v[vx].wrapping_add((opcode & 0x00FF) as u8); self.pc += 2; }, 0x8000 => match opcode & 0x000F { 0x0000 => { self.v[get_vx(opcode)] = self.v[get_vy(opcode)]; self.pc += 2; }, 0x0001 => { self.v[get_vx(opcode)] |= self.v[get_vy(opcode)]; self.pc += 2; }, 0x0002 => { self.v[get_vx(opcode)] &= self.v[get_vy(opcode)]; self.pc += 2; }, 0x0003 => { self.v[get_vx(opcode)] ^= self.v[get_vy(opcode)]; self.pc += 2; }, 0x0004 => { let vx = get_vx(opcode); let vy = get_vy(opcode); if self.v[vy] > 0xFF - self.v[vx] { self.v[0xF] = 1; } else { self.v[0xF] = 0; } self.v[vx] = self.v[vx].wrapping_add(self.v[vy]); self.pc += 2; }, 0x0005 => { let vx = get_vx(opcode); let vy = get_vy(opcode); if self.v[vy] > self.v[vx] { self.v[0xF] = 0; } else { self.v[0xF] = 1; } self.v[vx] = self.v[vx].wrapping_sub(self.v[vy]); self.pc += 2; }, 0x0006 => { let vx = get_vx(opcode); self.v[0xF] = self.v[vx] & 0x1; self.v[vx] >>= 1; self.pc += 2; }, 0x0007 => { let vx = get_vx(opcode); let vy = get_vy(opcode); if self.v[vx] > self.v[vy] { self.v[0xF] = 0; } else { self.v[0xF] = 1; } self.v[vx] = self.v[vy].wrapping_sub(self.v[vx]); self.pc += 2; }, 0x000E => { let vx = get_vx(opcode); self.v[0xF] = self.v[vx] >> 7; self.v[vx] <<= 1; self.pc += 2; }, _ => panic!("unimplemented {:x}", opcode), }, 0x9000 => { if self.v[get_vx(opcode)] != self.v[get_vy(opcode)] { self.pc += 4; } else { self.pc += 2; } }, 0xA000 => { self.addr = get_addr(opcode); self.pc += 2; }, 0xB000 => self.pc = get_addr(opcode).wrapping_add(self.v[0] as u16), 0xC000 => { self.v[get_vx(opcode)] = ((self.rng.next_u32() % 0xFF) as u16 & opcode & 0xFF) as u8; self.pc += 2; }, 0xD000 => { let vx = self.v[get_vx(opcode)] as usize; let vy = self.v[get_vy(opcode)] as usize; let height = (opcode & 0x000F) as usize; self.v[0xF] = 0; for y in 0..height { let pixel = self.memory[self.addr as usize + y]; for x in 0..8 { if pixel & (0x80 >> x as u8) != 0 { let i = vx + x + (vy + y) * 64; if i < 2048 { if self.gfx[i] != 0 { self.v[0xF] = 1; } self.gfx[i] ^= 1; } } } } self.draw_flag = true; self.pc += 2; }, 0xE000 => match opcode &0x00FF { 0x009E => { if self.key[self.v[get_vx(opcode)] as usize] != 0 { self.pc += 4; } else { self.pc += 2; } }, 0x00A1 => { if self.key[self.v[get_vx(opcode)] as usize] == 0 { self.pc += 4; } else { self.pc += 2; } }, _ => panic!("unimplemented {:x}", opcode), }, 0xF000 => match opcode & 0x00FF { 0x0007 => { self.v[get_vx(opcode)] = self.delay_timer; self.pc += 2; }, 0x000A => { let vx = get_vx(opcode); let mut pressed = false; for i in 0..16 { if self.key[i] != 0 { self.v[vx] = i as u8; pressed = true; } } if pressed { self.pc += 2; } else { return; } }, 0x0015 => { self.delay_timer = self.v[get_vx(opcode)]; self.pc += 2; }, 0x0018 => { self.sound_timer = self.v[get_vx(opcode)]; self.pc += 2; }, 0x001E => { let vx = self.v[get_vx(opcode)] as u16; self.v[0xF] = if self.addr.wrapping_add(vx) > 0xFFF { 1 } else { 0 }; self.addr = self.addr.wrapping_add(vx); self.pc += 2; }, 0x0029 => { self.addr = (self.v[get_vx(opcode)] as u16) * 0x5; self.pc += 2; }, 0x0033 => { let vx = get_vx(opcode); let addr = self.addr as usize; self.memory[addr] = self.v[vx] / 100; self.memory[addr + 1] = (self.v[vx] / 10) % 10; self.memory[addr + 2] = (self.v[vx] % 100) % 10; self.pc += 2; }, 0x0055 => { let vx = get_vx(opcode) + 1; let addr = self.addr as usize; for i in 0..vx { self.memory[i + addr] = self.v[i]; } self.addr += vx as u16; self.pc += 2; }, 0x0065 => { let vx = get_vx(opcode) + 1; let addr = self.addr as usize; for i in 0..vx { self.v[i] = self.memory[i + addr]; } self.addr += vx as u16; self.pc += 2; }, _ => panic!("unimplemented {:x}", opcode), }, _ => panic!("unimplemented {:x}", opcode), } if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { self.sound_timer -= 1; } } }
Swift
UTF-8
562
3.1875
3
[]
no_license
// // ColorPalette.swift // Yelp // // Created by Hector Monserrate on 19/09/14. // Copyright (c) 2014 CodePath. All rights reserved. // import Foundation enum ColorPalette { case Red, Gray, White func get(alpha: CGFloat = 1.0) -> UIColor { switch self { case .Red: return UIColor(red: 212/255, green: 0.0, blue: 0.0, alpha: alpha) case .Gray: return UIColor(red: 232/256, green: 232/256, blue: 232/256, alpha: alpha) case .White: return UIColor.whiteColor() } } }
TypeScript
UTF-8
2,578
2.71875
3
[]
no_license
import { Component, OnInit } from "@angular/core"; import * as _ from "lodash"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements OnInit { name = "Angular"; trs = []; directions = ["t", "r", "b", "l"]; data = [ { question: "Question 1", answer: "Hello", span: 0, x: -1, y: -1 }, { question: "Question 2", answer: "World", span: 0, x: -1, y: -1 }, { question: "Question 3", answer: "Alaksanda", span: 0, x: -1, y: -1 }, { question: "Question 4", answer: "Jesus", span: 0, x: -1, y: -1 }, { question: "Question 5", answer: "Gene", span: 0, x: -1, y: -1 }, { question: "Question 6", answer: "Maria", span: 0, x: -1, y: -1 }, { question: "Question 7", answer: "Susai", span: 0, x: -1, y: -1 }, { question: "Question 8", answer: "Bibiana", span: 0, x: -1, y: -1 }, { question: "Question 9", answer: "Diana", span: 0, x: -1, y: -1 }, { question: "Question 10", answer: "Kirubai", span: 0, x: -1, y: -1 } ]; // answer should not exceed 10 characters ngOnInit() { this.initTrs(); _.forEach(this.data, item => (item.span = item.answer.length)); this.data = _.reverse(_.sortBy(this.data, "span")); this.setFirstTds(); } initTrs() { const tds = ["", "", "", "", "", "", "", "", "", ""]; for (let i = 0; i < 10; i++) { this.trs.push(tds); } } setFirstTds() { const first = this.data[0]; const direction:any = 'r'; //this.directions[_.random(0, this.directions.length - 1)]; console.log("direction", direction); let fits = false; for (let i = 0; i < 10; i++) { const coordinates = this.getCoordinates(); switch (direction) { case "t": break; case "r": if(first.span >= coordinates[1]){ console.log("span",first.span); console.log(coordinates[0], coordinates[1]); } break; case "b": break; case "l": break; } } } getCoordinates() { let x = _.random(0, 10); let y = _.random(0, 10); if (x < 0) x = x * -1; if (y < 0) y = y * -1; return [x, y]; } }
C
UTF-8
1,254
2.53125
3
[]
no_license
#include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #include <X11/Xatom.h> #include <stdio.h> #define DUMP_ERR printf static void draw(Display *display, Window win, GC gc, int width, int height); int main() { Display *display; int screennum; int width; int height; Atom protocols; const char *strdraw = "hello world"; Window win; GC gc; display = XOpenDisplay(NULL); if (!display) { DUMP_ERR("call XOpenDisplay(%s) fail\n", XDisplayName(NULL)); return 1; } screennum = DefaultScreen(display); printf("Screen:%s\tScreenCount:%d\n", DisplayString(display), ScreenCount(display)); win = RootWindow(display, screennum); char name[256]; name[255] = 0; XFetchName(display, win, (char**)&name); printf("Root Window:%s\n", name); XRaiseWindow(display, win); Window ewin; unsigned int ewidth, eheight; // Window size int x, y; // Window position ewidth = 600, eheight = 400; ewin = XCreateSimpleWindow(display, RootWindow(display, screennum), x, y, ewidth, eheight, 4, BlackPixel(display, screennum), WhitePixel(display, screennum)); XMapWindow(display, ewin); XFlush(display); getchar(); }
Python
UTF-8
2,569
3.03125
3
[ "MIT" ]
permissive
import gym from gym import spaces from gym.utils import seeding import numpy as np class DeepSeaEnv(gym.Env): def __init__(self, n=20, random=True): self._size = n self._move_cost = 0.01 / (n - 1) self._goal_reward = 1. self._column = 0 self._row = 0 self.seed() if random: self._action_mapping = self.np_random.binomial(1, 0.5, n) else: self._action_mapping = np.ones(n) self.action_space = spaces.Discrete(2) self.flat_size = self._size ** 2 obs_shape = self.flat_size * 2 self.observation_space = spaces.Discrete(obs_shape) self.observation_space.shape = (obs_shape, ) def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] # make sure this aligns with hindsight def compute_reward(self, action_right, achieved_goal, goal, info): success = list(achieved_goal) == list(goal) if success: reward = self._goal_reward - self._move_cost else: reward = -self._move_cost if action_right else 0 info['is_success'] = float(success) info['achieved_goal'] = np.array(achieved_goal) info['desired_goal'] = np.array(goal) return float(success) - 1.0 def step(self, action): # Remap actions according to column (action_right = go right) action_right = action == self._action_mapping[self._column] # State dynamics self._row += 1 if action_right: # right self._column = np.clip(self._column + 1, 0, self._size - 1) else: # left self._column = np.clip(self._column - 1, 0, self._size - 1) info = {} done = self._row == self._size - 1 obs = self._get_observation(self._row, self._column) reward = self.compute_reward(action_right, obs[:self.flat_size], obs[self.flat_size:], info) return obs, reward, done, info def reset(self): self._column = 0; self._row = 0 return self._get_observation(self._row, self._column) def _get_observation(self, row, column): observation = np.zeros(shape=(self._size, self._size), dtype=np.float32) observation[row, column] = 1 goal = np.zeros(shape=(self._size, self._size), dtype=np.float32) goal[-1, -1] = 1 return np.concatenate((observation.flatten(), goal.flatten())) @property def optimal_return(self): return self._goal_reward - (self._size - 1) * self._move_cost
PHP
UTF-8
4,204
2.75
3
[]
no_license
<?php ob_start(); //========================================= // Class Management //========================================= include_once 'App Code/Class_People.php'; $c_People = new Class_People(); include_once 'App Code/Class_Object.php'; $c_Object = new Class_Object(); //========================================== // Variable //========================================== $s_ErrorMessage = ""; $s_PeopleID = $_COOKIE["cookie_Akun"]; $s_OldPassword = ""; if(isset($_POST["txt_OldPassword"]) && strlen(trim($_POST["txt_OldPassword"])) != 0) $s_OldPassword = trim($_POST["txt_OldPassword"]); $s_NewPassword = ""; if(isset($_POST["txt_NewPassword"]) && strlen(trim($_POST["txt_NewPassword"])) != 0) $s_NewPassword = trim($_POST["txt_NewPassword"]); $s_VerifyPassword = ""; if(isset($_POST["txt_VerifyPassword"]) && strlen(trim($_POST["txt_VerifyPassword"])) != 0) $s_VerifyPassword = trim($_POST["txt_VerifyPassword"]); //========================================== // Event Submit //========================================== $b_Validation = true; if(isset($_POST["btn_Submit"])) { /* * Validasi Old Password */ if(strlen($s_OldPassword) == 0) { $s_ErrorMessage .= "Please field old password<br/>"; $b_Validation = false; } else if(!$c_People->bool_Check_PeopleLogin_ByPassword($s_PeopleID, $s_OldPassword)) { $s_ErrorMessage .= "Old password invalid<br/>"; $b_Validation = false; } /* * Validasi New Password */ if(strlen($s_NewPassword) == 0) { $s_ErrorMessage .= "Please field New password<br/>"; $b_Validation = false; } else if(strlen($s_NewPassword) < 6) { $s_ErrorMessage .= "New password min 6 character<br/>"; $b_Validation = false; } /* * Verify New Password */ if(strlen($s_VerifyPassword) == 0) { $s_ErrorMessage .= "Please field verify password<br/>"; $b_Validation = false; } else if($s_NewPassword !== $s_VerifyPassword) { $s_ErrorMessage .= "Verify password not match<br/>"; $b_Validation = false; } /* * Validation True */ if($b_Validation) { $b_Check = $c_People->bool_Update_PeopleLogin_Password($s_PeopleID, $s_NewPassword); if($b_Check) { echo $c_Object->string_Set_MessageBox("Password updated"); echo "<script>window.location.href='index.php'</script>"; /* * jika data berhasil dimasukkan * maka akan berpindah halaman */ } else { $s_ErrorMessage = "Can not manage this data"; } } } ?> <div class="Form"> <style> .Form .Lable { width: 150px; } </style> <form action="" method="post" enctype="multipart/form-data" name="form_Manage"> <div class="Row"> <span class="TitleName">Change Password</span> </div> <div class="Row"> <span class="ErrorMessage"><?=$s_ErrorMessage?></span> </div> <div class="Row"> <span class="Lable">Old Password</span> <input type="password" name="txt_OldPassword" class="TextBox" value="<?=$s_OldPassword?>" /> </div> <div class="Row"> <span class="Lable">New Password</span> <input type="password" name="txt_NewPassword" class="TextBox" value="<?=$s_NewPassword?>" /> </div> <div class="Row"> <span class="Lable">Verify Password</span> <input type="password" name="txt_VerifyPassword" class="TextBox" value="<?=$s_VerifyPassword?>" /> </div> <div class="Row"> <input type="submit" name="btn_Submit" value="Submit" class="ButtonSubmit" /> <span>&nbsp;</span> <input type="reset" value="Reset" class="ButtonReset" /> <span>&nbsp;</span> <input type="button" value="Back" onclick="window.history.back()" class="ButtonBack" /> </div> </form> </div> <?php ob_flush(); ?>
Markdown
UTF-8
4,066
2.875
3
[ "MIT" ]
permissive
--- page_type: sample languages: - csharp products: - azure - azure-storage - dotnet-core description: "A simple sample project to help you get started using Azure Storage with .NET Core and C# as the development language." --- ## Azure SDK Versions To use the latest Azure SDK version [storage-blobs-dotnet-quickstart-v3](./storage-blobs-dotnet-quickstart-V3), please add the following dependency: - [Microsoft.Azure.Storage.Blob](https://www.nuget.org/packages/Microsoft.Azure.Storage.Blob/) For the previous Azure SDK version [storage-blobs-dotnet-quickstart-v12](./storage-blobs-dotnet-quickstart-V12), please add the following dependency: - [Azure.Storage.Blobs](https://www.nuget.org/packages/Azure.Storage.Blobs/) ## Prerequisites To complete this tutorial: * Install .NET core 2.1 for [Linux](https://dotnet.microsoft.com/download/dotnet-core/2.1) or [Windows](https://dotnet.microsoft.com/download/dotnet-core/2.1) If you don't have an Azure subscription, create a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F) before you begin. ## Create a Storage Account using the Azure Portal Step 1 : Create a new general-purpose Storage Account to use for this tutorial. * Go to the [Azure Portal](https://portal.azure.com) and log in using your Azure account. * Select **New** > **Storage** > **Storage account**. * Select your Subscription. * For `Resource group`, create a new one and give it a unique name. * Enter a name for your storage Account. * Select the `Location` to use for your Storage Account. * Set `Account kind` to **StorageV2(general purpose v2)**. * Set `Performance` to **Standard**. * Set `Replication` to **Locally-redundant storage (LRS)**. * Set `Secure transfer required` to **Disabled**. * Check **Review + create** and click **Create** to create your Storage Account. Step 2 : Copy and save Connection string. After your Storage Account is created. Click on it to open it. Select **Settings** > **Access keys** > **Key1/key**, copy the associated **Connection string** to the clipboard, then paste it into a text editor for later use. ## Put the connection string in an environment variable This solution requires a connection string be stored in an environment variable securely on the machine running the sample. Follow one of the examples below depending on your operating system to create the environment variable. If using Windows close your open IDE or shell and restart it to be able to read the environment variable. ### Linux ```bash export AZURE_STORAGE_CONNECTIONSTRING="<YourConnectionString>" ``` ### Windows ```cmd setx AZURE_STORAGE_CONNECTIONSTRING "<YourConnectionString>" ``` At this point, you can run this application. It creates its own file to upload and download, and then cleans up after itself by deleting everything at the end. ## Run the application First, clone the repository on your machine: ```bash git clone https://github.com/Azure-Samples/storage-blobs-dotnet-quickstart.git ``` Then, switch to the appropriate folder: Navigate to your directory where the project file (.csproj) resides and run the application with the `dotnet run` command. ```console dotnet run ``` ## This Quickstart shows how to do following operations of Storage Blobs. - Create a Storage Account using the Azure Portal. - Create a container. - Upload a file to block blob. - List blobs. - Download a blob to file. - Delete a blob. - Delete the container. ## More information The [Azure Storage documentation](https://docs.microsoft.com/azure/storage/) includes a rich set of tutorials and conceptual articles, which serve as a good complement to the samples. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
Java
UTF-8
1,974
3.40625
3
[]
no_license
package ic.doc.co575; import java.util.Random; public class ExpressionFactory { public static Expression randomExpression(int maxDepth) { Random random = new Random(); if (maxDepth == 0) { return new NaturalNumber(random.nextInt(9) + 1); //the reason for which the return has this value is to prevent having an // invalid // integer as a parameter for NaturalNumber creation. } else { int expSelector = random.nextInt(4); try { if (expSelector == 0) { return new Addition(randomExpression(maxDepth - 1), randomExpression(maxDepth - 1)); } else if (expSelector == 1) { return new Product(randomExpression(maxDepth - 1), randomExpression(maxDepth - 1)); } else if (expSelector == 2) { return new Subtraction(randomExpression(maxDepth - 1), randomExpression(maxDepth - 1)); } else { return new Division(randomExpression(maxDepth - 1), randomExpression(maxDepth - 1)); } } catch (InvalidNaturalNumber e) { System.out.println(e.toString()); if (expSelector < 2) { return new Addition(randomExpression(maxDepth - 1), randomExpression(maxDepth - 1)); } else { return new Product(randomExpression(maxDepth - 1), randomExpression(maxDepth - 1)); } // we decided here to fix the mistake by adding either a // new multiplication or a new addition. We could also have returned a //NaturalNumber, // which would have been easier but less fun :) } } } }
C++
UTF-8
6,436
2.59375
3
[]
no_license
/** * Chad Manning's file for Iron Curtain * @author: Chad Manning * Course: CMPS 3350 * Instructor: Gordon Griesel */ #include <GL/glx.h> #include <X11/Xlib.h> #include <stdio.h> #include <cmath> #include <ctime> #include <cstdlib> #include "core.h" #include "chadM.h" #include "fonts.h" extern Global& gl; extern double timeDiff(struct timespec *start, struct timespec *end); extern EnemyShip *headShip; extern EnemyShip *tailShip; extern EnemyShip *eShip; //Global variables enum MOVETYPE { RUSH, STRAFE, CIRCLING, BANK, DIAG_RUSH }; double lastSpawnTime = 0.0; /* Displays Chads picture and name on the title screen */ void displayChad (float x , float y, GLuint textid) { float wid = 100.0; glPushMatrix(); glTranslatef(x, y, 0.0); glBindTexture(GL_TEXTURE_2D, textid); glColor3ub(255, 255, 255); glBegin(GL_QUADS); glTexCoord2f(0.0f, 1.0f); glVertex2i(-wid, -wid); glTexCoord2f(0.0f, 0.0f); glVertex2i(-wid, wid); glTexCoord2f(1.0f, 0.0f); glVertex2i(wid, wid); glTexCoord2f(1.0f, 1.0f); glVertex2i(wid, -wid); glEnd(); glPopMatrix(); unsigned int color = 0xffff0000; Rect r; r.width = 250.0; r.height = 100.0; r.center = x; r.left = x - 10; r.bot = y - 125; ggprint16(&r, 16, color, "Chad Manning"); } /* Constructor for EnemyShip class If you want to make the ship behave differently call the config class from nickJA.cpp to modify path. Ex. eShip = new EnemyShip(x, y, movType); tailShip->config$NAME_OF_PATTERN$; */ EnemyShip::EnemyShip(int x, int y, int movType) { pos[0] = x; pos[1] = y; pos[2] = 1; color[0] = color[1] = color[2] = 0.35; health = 1; deathScore = 10; movPattern = movType; eWpn = new EnemyStd(); if (headShip == NULL) { headShip = tailShip = this; prevShip = nextShip = NULL; } else { prevShip = tailShip; prevShip->nextShip = tailShip = this; } nextShip = NULL; } /* Destructor for EnemyShip class Readjusts linked list depending on which ship was destroyed. */ EnemyShip::~EnemyShip() { if (prevShip != NULL) { prevShip->nextShip = nextShip; } else { headShip = nextShip; } if (nextShip != NULL) { nextShip->prevShip = prevShip; } else { tailShip = prevShip; } } /* Returns radius of bounding circle for the ship */ float EnemyShip::getRadius() { return detRadius; } int EnemyShip::getHealth() { return health; } /* Returns deathScore for each this type of ship */ int EnemyShip::getDeathScore() { return deathScore; } /* Destroys the ship when its health reaches zero. KABOOM. "But Chad all this does is call the destructor." Yeah but destroyShip makes more sense than delete. */ void EnemyShip::destroyShip() { delete this; } /* Deducts damage from this ship */ void EnemyShip::takeDamage(int damageTaken) { health -= damageTaken; } /* Takes a Ship class as input and renders it to screen. used for both player ship and all enemy ships. */ void renderShip(Ship* ship) { glColor3fv(ship->color); glPushMatrix(); glTranslatef(ship->pos[0], ship->pos[1], ship->pos[2]); glBegin(GL_QUADS); glVertex2f(-20.0f, -20.0f); glVertex2f(-20.0f, 20.0f); glVertex2f(20.0f, 20.0f); glVertex2f(20.0, -20.0); glEnd(); glPopMatrix(); } /* Altered function for EnemyShip fire rate */ double EnemyShip::getTimeSlice(timespec *bt) { clock_gettime(CLOCK_REALTIME, bt); return timeDiff(&bulletTimer, bt); } /* Constructor for lowest level of enemies spawned */ Grunt::Grunt(int x, int y, int movType) : EnemyShip(x, y, movType) { deathScore = 10; } /* Constructor for final boss of level, can take multiple hits */ Boss::Boss(int x, int y, int movType) : Grunt(x, y, movType) { deathScore = 1000; health = 50; eWpn = new Pinwheel(); } /* Helper function for mainLevel, gets x-coord that is within game bounds */ int getRandXSpawn() { return rand() % 800 + 50; } /* Helper function for mainLevel, gets x-coord that is within game bounds */ int getRandYSpawn() { return rand() % 900 + 20; } void resetSpawnTimer() { lastSpawnTime = 0.0; } /* Main level for the game, determines which enemy to spawn at certain times. @param gameTime total elapsed time in the game */ bool mainLevel(double gameTime) { //gl.xres == 900 //g.yres == 1000 const int ySpawn = 1100; static bool bossSpawned = false; bool bossDefeated = false; if (gameTime - lastSpawnTime > 2) { lastSpawnTime = gameTime; // if ((int) gameTime % 5 == 0) // eShip = new Grunt(getRandXSpawn(), ySpawn, RUSH); if (gameTime < 10.0) { eShip = new Grunt(100, ySpawn, DIAG_RUSH); tailShip->configDiagRush(gl.xres, 0, 1); eShip = new Grunt(gl.xres, ySpawn+10, DIAG_RUSH); tailShip->configDiagRush(0, 0, 1); } else if ( gameTime > 20 && gameTime < 50) { eShip = new Grunt(getRandXSpawn(), ySpawn, CIRCLING); tailShip->configCircle(50, 90, 1, 1, -1); eShip = new Grunt(getRandXSpawn(), ySpawn, CIRCLING); tailShip->configCircle(100, 90, 1.5, 1, 1); } else if (gameTime > 60 && gameTime < 80) { eShip = new Grunt(-15, 700, DIAG_RUSH); tailShip->configDiagRush(1000, -20, 2); eShip = new Grunt(915, 800, DIAG_RUSH); tailShip->configDiagRush(-100, -20, 2); } else if (gameTime > 90) { if (!bossSpawned) { eShip = new Boss(gl.xres / 2, ySpawn, DIAG_RUSH); tailShip->configDiagRush(gl.xres / 2, 800, -1); bossSpawned = true; } if (tailShip->pos[1] < 750) { tailShip->configDiagRush(800, 800, 1); } else if (tailShip->pos[0] > 750) { tailShip->configDiagRush(100, 800, 1); } else if (tailShip->pos[0] < 100){ tailShip->configDiagRush(600, 800, 1); } if (headShip == NULL) { bossDefeated = true; bossSpawned = false; } } } return bossDefeated; }
JavaScript
UTF-8
213
4.09375
4
[]
no_license
// Write a function that takes a number as argument // Round the number to the 2nd digit after the comma // Return the rounded number const round = num => { return num.toFixed(2) }; console.log(round(32.12397));
Markdown
UTF-8
3,194
3.015625
3
[]
no_license
# Pokedex A Pokedex implementation by various contributors. Welcome to our Pokedex. We collaborate on this fun project to build one of the best Pokedexes in the world. It's Open Source and it's free! We at Refocus give this task to our prospective team-mates. It's not easy, it is challenging at it's best and you'll have to push yourselves to meet the expectations of the expected finished product. This Pokedex needs to be built from scratch without using any frameworks or tools! Pure HTML, CSS and JavaScript. Let's see what greatness awaits, looking forward to seeing you contribute some great code and help you learn quite a bit through these tasks. # What you'll be building You'll be building a Pokdex from scratch or extending it. Read the instructions of the TODO index you've been assigned and work on it. It's a web version of Pokdex, so it doesn't need to be responsive(yet). # Guidelines to follow - Clone the repository and work on local in your Nodejs environment. This is mandatory. - Feel free to add files, but also make sure you heavily document your code. Explain everything with details. - Use the folder structure provided and keep your code modular and organized - index.html is entry point into your app, so this needs to be served via Jerkyll. Make sure you know how to use GitHub pages for serving static files before submitting your contributions. - You need to send us a pull request once you're done. ## TODO: ![Pokedex Reference Image](https://github.com/Refocus/Pokedex/blob/master/pokedex-kanto-1.jpg) 1) A UI that is similar to the cartoon version of pokedex. This needs to be built entirely with CSS, so make sure you're handy with CSS before attempting this. You should be good with layouts, positioning and creating shapes out of CSS. You can add interactivity by plugging in event listeners to your HTML with plain JavaScript. - The Skeleton of the Pokdex must be pure CSS too. You're first task would be to build a open/close/flip Pokedex. Notice the dark yellow triangle when the Pokdex is closed? That's where you need to attach your event listeners to open/close the Pokedex. - Once you're done with Opening the Pokedex, it needs to turn on automatically. (Make sure the transitions of the dark screen turns to a different color when it's turned on) - Build every button that you see in the image through CSS. This concludes your task 1. 2) Parse the Data from js/pokedex.json and display the below listed fields on the Pokedex. // Replace the 'XXX' in <https://assets.pokemon.com/assets/cms2/img/pokedex/full/XXX.png> with the pokemon ID to request an image of the pokemon, instead of using the img in the json file(has better quality pictures!). Checkout https://www.pokemon.com/us/pokedex/bulbasaur for Pokedex reference A list of 151 Pokemon are present in the js/pokedex.json file. These following fields need to be displayed. ### Pokemon Data ##### Attributes - - Number - Name - img - type - height - weight - candy - candy count - egg - spawn_chance - avg_spawns - multipliers - weaknesses - next_evolution ## CONTRIBUTING Send a pull request with what you worked on and we'll do a merge if everything seems fine.
Java
UTF-8
375
1.835938
2
[]
no_license
package com.yzcx.api.vo.highchat; import com.fasterxml.jackson.annotation.JsonInclude; /** * Created by LiuDongguang on 2017/5/24. * 子标题 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Subtitle { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } }
Java
UTF-8
6,442
2.234375
2
[]
no_license
package test; import static org.junit.Assert.*; import java.awt.Point; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import elements.Investigator; import elements.Monster; import enums.FieldTyps; import enums.MonsterNames; import enums.Path; import enums.Skills; import enums.Space; import gameItems.Field; import gameItems.GameBoard; import gameItems.Skill; import gameMechanics.Event; public class GameBoardTest { Field fieldA=new Field("a",Space.city,new Point(0,0),FieldTyps.City); Field fieldB=new Field("b",Space.city,new Point(0,0),FieldTyps.City); Field fieldC=new Field("c",Space.city,new Point(0,0),FieldTyps.City); Field fieldD=new Field("d",Space.city,new Point(0,0),FieldTyps.City); Field fieldE=new Field("e",Space.city,new Point(0,0),FieldTyps.City); Field fieldF=new Field("f",Space.city,new Point(0,0),FieldTyps.City); Field fieldG=new Field("g",Space.city,new Point(0,0),FieldTyps.City); Field fieldH=new Field("h",Space.city,new Point(0,0),FieldTyps.City); Field fieldI=new Field("i",Space.city,new Point(0,0),FieldTyps.City); Investigator investigator1= new Investigator("AkachiOnyele"); Investigator investigator2= new Investigator("CharlieKane"); Investigator investigator3= new Investigator("CharlieKane"); Monster monster1 = new Monster(MonsterNames.cultist, 2, 2, 1, 0, -1, new Event(),"Cthulhu"); GameBoard gameBoard; Map<Field,Space> fields= new HashMap<Field,Space>(); @Before public void setUp() throws Exception { fieldA.addNeighbour(fieldB, Path.ship); fieldA.addNeighbour(fieldC, Path.ship); fieldB.addNeighbour(fieldA, Path.ship); fieldB.addNeighbour(fieldC, Path.ship); fieldB.addNeighbour(fieldE, Path.ship); fieldC.addNeighbour(fieldA, Path.ship); fieldC.addNeighbour(fieldB, Path.ship); fieldC.addNeighbour(fieldD, Path.ship); fieldC.addNeighbour(fieldE, Path.ship); fieldD.addNeighbour(fieldC, Path.ship); fieldD.addNeighbour(fieldH, Path.ship); fieldE.addNeighbour(fieldC, Path.ship); fieldE.addNeighbour(fieldB, Path.ship); fieldE.addNeighbour(fieldF, Path.ship); fieldE.addNeighbour(fieldG, Path.ship); fieldF.addNeighbour(fieldE, Path.ship); fieldF.addNeighbour(fieldH, Path.ship); fieldF.addNeighbour(fieldG, Path.ship); fieldG.addNeighbour(fieldE, Path.ship); fieldG.addNeighbour(fieldF, Path.ship); fieldG.addNeighbour(fieldI, Path.ship); fieldH.addNeighbour(fieldD, Path.ship); fieldH.addNeighbour(fieldF, Path.ship); fieldH.addNeighbour(fieldI, Path.ship); fieldI.addNeighbour(fieldG, Path.ship); fieldI.addNeighbour(fieldH, Path.ship); fields.put(fieldA, fieldA.getSpace()); fields.put(fieldB, fieldB.getSpace()); fields.put(fieldC, fieldC.getSpace()); fields.put(fieldD, fieldD.getSpace()); fields.put(fieldE, fieldE.getSpace()); fields.put(fieldF, fieldF.getSpace()); fields.put(fieldG, fieldG.getSpace()); fields.put(fieldH, fieldH.getSpace()); fields.put(fieldI, fieldI.getSpace()); fieldC.addInvestigator(investigator1); fieldF.addInvestigator(investigator2); fieldI.addInvestigator(investigator3); fieldD.addMonster(monster1); gameBoard = new GameBoard(fields); } @Test public void testGetInvestigatorField() { assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldC); assertTrue(gameBoard.getInvestigatorField(investigator2) ==fieldF); assertTrue(gameBoard.getInvestigatorField(investigator3) ==fieldI); assertFalse(gameBoard.getInvestigatorField(investigator1) ==fieldF); } @Test public void testGetMonsterField() { assertTrue(gameBoard.getMonsterField(monster1)==fieldD); assertFalse(gameBoard.getMonsterField(monster1)==fieldA); } @Test public void testMoveInvestigator() { assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldC); gameBoard.moveInvestigator(investigator1, fieldB); assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldB); assertFalse(gameBoard.getInvestigatorField(investigator1) ==fieldC); gameBoard.moveInvestigator(investigator1, fieldA); assertFalse(gameBoard.getInvestigatorField(investigator1) ==fieldA); assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldB); } @Test public void testMoveInvestigatorWithTickets() { investigator1.addShipTickets(); investigator1.addTrainTickets(); assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldC); gameBoard.moveInvestigator(investigator1, fieldB); assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldB); assertFalse(gameBoard.getInvestigatorField(investigator1) ==fieldC); gameBoard.moveInvestigator(investigator1, fieldA); assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldA); assertFalse(gameBoard.getInvestigatorField(investigator1) ==fieldB); gameBoard.moveInvestigator(investigator1, fieldC); assertTrue(gameBoard.getInvestigatorField(investigator1) ==fieldA); assertFalse(gameBoard.getInvestigatorField(investigator1) ==fieldC); } @Test public void testMoveMonster() { gameBoard.moveMonster(monster1, fieldA); assertFalse(gameBoard.getMonsterField(monster1)==fieldD); assertTrue(gameBoard.getMonsterField(monster1)==fieldA); } @Test public void testNextInvestigatorField() { System.out.println("N�chster Ermittler von Feld A aus: " + gameBoard.nextInvestigatorField(fieldA)); System.out.println("N�chster Ermittler von Feld B aus: " + gameBoard.nextInvestigatorField(fieldB)); System.out.println("N�chster Ermittler von Feld C aus: " + gameBoard.nextInvestigatorField(fieldC)); System.out.println("N�chster Ermittler von Feld D aus: " + gameBoard.nextInvestigatorField(fieldD)); System.out.println("N�chster Ermittler von Feld E aus: " + gameBoard.nextInvestigatorField(fieldE)); System.out.println("N�chster Ermittler von Feld F aus: " + gameBoard.nextInvestigatorField(fieldF)); System.out.println("N�chster Ermittler von Feld G aus: " + gameBoard.nextInvestigatorField(fieldG)); System.out.println("N�chster Ermittler von Feld H aus: " + gameBoard.nextInvestigatorField(fieldH)); System.out.println("N�chster Ermittler von Feld I aus: " + gameBoard.nextInvestigatorField(fieldI)); } @Test public void testShortestWaysFieldField() { System.out.println(gameBoard.shortestWays(fieldA, fieldF)); } }
C++
UTF-8
1,955
3.203125
3
[]
no_license
/************************************************************************* > File Name: thread-safe-counter.cpp > Author: Jason > Mail: jie-email@jie-trancender.org > Created Time: 2017年03月27日 星期一 18时36分52秒 ************************************************************************/ #include <iostream> #include <mutex> #include <thread> #include <vector> #include <functional> #include <chrono> //#include <boost/noncopyable> namespace mtl { class noncopyable { protected: #if __cplusplus > 201103L constexpr noncopyable() = default; ~noncopyable() = default; noncopyable(const noncopyable&) = delete; noncopyable& operator=(const noncopyable&) = delete; #else noncopyable() {}; ~noncopyable() {}; private: noncopyable(const noncopyable&); noncopyable& operator=(const noncopyable&); #endif }; } //class Counter : boost::noncopyable class Counter : mtl::noncopyable { public: Counter() : value_(0) {} //no content int64_t value() const; int64_t getAndIncrease(); void print() { std::cout << getAndIncrease() << std::endl; } private: int64_t value_; mutable std::mutex mutex_; //mutable 意味着const成员函数也可以使用non-const成员变量 }; int64_t Counter::value() const { std::lock_guard<std::mutex> lock(mutex_); return value_; } int64_t Counter::getAndIncrease() { std::lock_guard<std::mutex> lock(mutex_); int64_t ret = value_++; return ret; } int main(int argc, char* argv[]) { //since -std=c++14 using namespace std::chrono_literals; Counter counter; std::vector<std::thread*> vecThread(10); for (auto i = 0; i < 10; ++i) { vecThread.push_back(new std::thread(&Counter::print, std::ref(counter))); } for (auto i = vecThread.begin(); i != vecThread.end(); ++i) { (*i)->join(); std::this_thread::sleep_for(2s); } }
Python
UTF-8
5,632
3.296875
3
[]
no_license
import os import time import numpy as np import matplotlib.pyplot as plt from scipy.cluster.vq import kmeans2 from sympy import symbols, Eq, solve from scipy.optimize import minimize, fsolve from scipy.integrate import trapz from src.utils import get_project_root root = get_project_root() class FourthLab: def __init__(self): print(f'result: \n{self.exercise1()}') print(f'result: \n{self.exercise2()}') print(f'result: \n{self.exercise3()}') print(f'result: \n{self.exercise4()}') exercise5 = self.exercise5() print(f'result: \n{exercise5[0]}\n{exercise5[1]}') @staticmethod def exercise1(): print("~~~~~~~~~~~~~~~~~~~~~~~Exercise 1~~~~~~~~~~~~~~~~~~~~") t1 = time.time() x, y, z = symbols('x y z') eq1 = Eq(5 * (x ** -1) - 2 * (y ** -1) + 3 * (z ** -1), (-9 / 4)) eq2 = Eq(2 * (x ** -1) + 3 * (y ** -1) + 1 * (z ** -1), (5 / 12)) eq3 = Eq(1 * (x ** -1) + 4 * (y ** -1) - 2 * (z ** -1), (5 / 3)) print(f'{eq1}\n{eq2}\n{eq3}') t2 = time.time() print(f"~Exercise 1~~~~~~~~~~DONE~~~~~~~~~~[TIME: {t2 - t1}s]") return solve((eq1, eq2, eq3), (x, y, z)) @staticmethod def exercise2(): print("~~~~~~~~~~~~~~~~~~~~~~~Exercise 2~~~~~~~~~~~~~~~~~~~~") t1 = time.time() cons = ( {'type': 'ineq', 'fun': lambda x: -x[0]}, {'type': 'ineq', 'fun': lambda x: -x[1]}, {'type': 'ineq', 'fun': lambda x: x[1] + x[0] + 3} ) result_min = minimize( lambda x: x[0] ** 2 + x[1] ** 2 - x[0] * x[1] + x[0] + x[1], np.array([-1, -2]), method='SLSQP', constraints=cons ) result_max = minimize( lambda x: -(x[0] ** 2 + x[1] ** 2 - x[0] * x[1] + x[0] + x[1]), np.array([-1, -2]), method='SLSQP', constraints=cons ) print(f'Point: {result_min.x}, Value min:{result_min.fun}') print(f'Point: {result_max.x}, Value max:{-result_max.fun}') t2 = time.time() print(f"~Exercise 2~~~~~~~~~~DONE~~~~~~~~~~[TIME: {t2 - t1}s]") return result_min.fun, -result_max.fun @staticmethod def exercise3(): print("~~~~~~~~~~~~~~~~~~~~~~~Exercise 3~~~~~~~~~~~~~~~~~~~~") t1 = time.time() cons = ( {'type': 'ineq', 'fun': lambda x: 4 - x[0] ** 2 - x[1] ** 2} ) result_min = minimize( lambda x: -((4 - x[0] ** 2 - x[1] ** 2) ** 1 / 2), np.array([1, 1]), method='SLSQP', constraints=cons ) result_max = minimize( lambda x: (4 - x[0] ** 2 - x[1] ** 2) ** 1 / 2, np.array([1, 1]), method='SLSQP', constraints=cons ) print(f'Point: {result_min.x}, Value min:{result_min.fun}') print(f'Point: {result_max.x}, Value max:{-result_max.fun}') t2 = time.time() print(f"~Exercise 3~~~~~~~~~~DONE~~~~~~~~~~[TIME: {t2 - t1}s]") return result_min.fun, -result_max.fun @staticmethod def exercise4(): print("~~~~~~~~~~~~~~~~~~~~~~~Exercise 4~~~~~~~~~~~~~~~~~~~~") t1 = time.time() f, g, h = lambda arg: -arg + 1, lambda arg: arg ** 2 - 1, lambda arg: np.sin(arg) x0 = fsolve(lambda arg: g(arg) - h(arg), np.array([-0.5])) x1 = fsolve(lambda arg: f(arg) - h(arg), np.array([0.5])) x2 = fsolve(lambda arg: f(arg) - g(arg), np.array([0.5])) int_step = 0.001 xx1, xx2 = np.arange(x0, x1, int_step), np.arange(x1, x2, int_step) a = trapz(h(xx1) - g(xx1), xx1, int_step) + trapz(f(xx2) - g(xx2), xx2, int_step) c = trapz( (h(xx1) + g(xx1)) / 2 * (h(xx1) - g(xx1)), xx1, int_step ) + trapz( (f(xx2) + g(xx2)) / 2 * (f(xx2) - g(xx2)), xx2, int_step ) y_cm = 1 / a * c print("Central moment: " + str(y_cm)) t2 = time.time() print(f"~Exercise 4~~~~~~~~~~DONE~~~~~~~~~~[TIME: {t2 - t1}s]") return y_cm @staticmethod def exercise5(): data2d_path = os.path.join(root, os.path.join('data', 'dane_2D.txt')) data3d_path = os.path.join(root, os.path.join('data', 'dane_3D.txt')) print("~~~~~~~~~~~~~~~~~~~~~~~Exercise 5~~~~~~~~~~~~~~~~~~~~") t1_main = time.time() print("~~~~~~~~~~~~~~~~~~~Exercise 5 DATA 2D~~~~~~~~~~~~~~~~") t1 = time.time() m = np.loadtxt(data2d_path) centroid_2d, label_2d = kmeans2(m, 2) print(centroid_2d) plt.scatter(m[:, 0], m[:, 1], marker='o', c=label_2d) plt.plot(centroid_2d[:, 0], centroid_2d[:, 1], 'g*') plt.title(data2d_path) plt.show() t2 = time.time() print(f"~Exercise 5 DATA 2D~~~~~~DONE~~~~~~[TIME: {t2 - t1}s]") print("~~~~~~~~~~~~~~~~~~~Exercise 5 DATA 3D~~~~~~~~~~~~~~~~") t1 = time.time() m = np.loadtxt(data3d_path) centroid_3d, label_3d = kmeans2(m, 3) print(centroid_3d) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(m[:, 0], m[:, 1], m[:, 2], marker='o', c=label_3d) ax.plot(centroid_3d[:, 0], centroid_3d[:, 1], centroid_3d[:, 2], 'g*') plt.title(data3d_path) plt.show() t2 = time.time() print(f"~Exercise 5 DATA 3D~~~~~~DONE~~~~~~[TIME: {t2 - t1}s]") t2_main = time.time() print(f"~Exercise 4~~~~~~~~~~DONE~~~~~~~~~~[TIME: {t2_main - t1_main}s]") return centroid_2d, centroid_3d
Python
UTF-8
6,731
2.828125
3
[]
no_license
#!/usr/bin/python import tkinter as tk import os class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.checkFiles() self.findSettings() self.createSettings() self.createFunctions() # Menu System def createSettings(self): self.sTitle = tk.Label(self) self.sTitle["text"] = "Settings" self.sTitle.grid(column = 0, row = 0, ipadx = 30, padx = 5, pady = 1, sticky = 'EW') self.loc = tk.Button(self) self.loc["text"] = "Refresh Settings" self.loc["command"] = self.findSettings self.loc.grid(column = 0, row = 1, padx = 5, pady = 1, sticky = 'EW') self.dir = tk.Button(self) self.dir["text"] = "Directory..." self.dir["command"] = self.setDir self.dir.grid(column = 0, row = 2,padx = 5, pady = 1, sticky = 'EW') self.reset = tk.Button(self) self.reset["text"] = "Defaults" self.reset["command"] = self.default self.reset.grid(column = 0, row = 3,padx = 5, pady = 1, sticky = 'EW') def createFunctions(self): self.wTitle = tk.Label(self) self.wTitle["text"] = "Functions" self.wTitle.grid(column = 1, row = 0, ipadx = 29, padx = 5, pady = 1, sticky = 'EW') self.css = tk.Button(self) self.css["text"] = "Add Site" self.css["command"] = self.addSite self.css.grid(column = 1, row = 1, padx = 5, pady = 1, sticky = 'EW') self.edit = tk.Button(self) self.edit["text"] = "Edit Site" self.edit["command"] = self.editSite self.edit.grid(column = 1, row = 2, padx = 5, pady = 1, sticky = 'EW') self.rem = tk.Button(self) self.rem["text"] = "Remove Site" self.rem["command"] = self.remSite self.rem.grid(column = 1, row = 3, padx = 5, pady = 1, sticky = 'EW') self.uc = tk.Button(self) self.uc["text"] = "Generate" self.uc["command"] = self.generate self.uc.grid(column = 1, row = 4, padx = 5, pady = 1, sticky = 'EW') # Functions def checkFiles(self): if "Settings.txt" not in os.listdir(): file = open("Settings.txt", "x") file.write("directory:.") file.close() if "raw.txt" not in os.listdir(): file = open("raw.txt", "x") file.close() self.findSettings() def findSettings(self): file = open("Settings.txt", 'r') global types types = {} for l in file.readlines(): section = l[:l.find(':')] types[section] = l[l.find(':') + 1:] file.close() def default(self): if tk.messagebox.askyesno("Warning", "This will reset everything. Continue?") == True: file = open("Settings.txt", 'w') file.write("directory:.") file.close() self.findSettings() def setDir(self): question = types["directory"] if question == ".": question = "root" answer = tk.simpledialog.askstring("Directory", question) if answer != None: if answer == "root": answer = "." types["directory"] = answer file = open("Settings.txt", 'w') file.write("directory:%s" % answer) file.close() def listSites(self): file = open("raw.txt", "r") data = file.readline() file.close() data = data.split("`") for i in range(len(data)): data[i] = data[i][:data[i].find('~')] data.pop() return(", ".join(data)) def addSite(self): site = tk.simpledialog.askstring("Domain", "Existing: %s" % self.listSites()) if site != None: tk.messagebox.showinfo("Alert", "This grabs the CSS from clipboard. Copy before continuing.") css = tk.Text.clipboard_get(self) css = css.replace("\n","~newline~") css = "%s~%s`" % (site, css) file = open("raw.txt", "r") tempStorage = file.readline() file.close() if site not in tempStorage: file = open("raw.txt", "w") file.write(tempStorage + css) file.close() else: tk.messagebox.showerror("Error", "Site exists!") def editSite(self): site = tk.simpledialog.askstring("Domain", "Existing: %s" % self.listSites()) if site != None: tk.messagebox.showinfo("Alert", "This grabs the CSS from clipboard. Copy before continuing.") file = open("raw.txt", "r") data = file.readline() file.close() data = data.split("`") for i in range(len(data)): if site in data[i]: css = tk.Text.clipboard_get(self) css = css.replace("\n","~newline~") data.pop(i) data.pop(len(data)-1) data.append("%s~%s`" % (site, css)) break file = open("raw.txt", "w") data = "`".join(data) file.write(data) file.close() def remSite(self): site = tk.simpledialog.askstring("Domain", "Existing: %s" % self.listSites()) if site != None: file = open("raw.txt", "r") data = file.readline() file.close() file = open("raw.txt", "w") data = data.split("`") for i in range(len(data) - 1): if site in data[i]: data.pop(i) file.write("`".join(data)) file.close() def generate(self): file = open("raw.txt", "r") data = file.readline() file.close() if data != "": if "chrome" not in os.listdir(types["directory"]): os.mkdir(types["directory"] + "\\chrome") file = open(types["directory"] + "\\chrome\\userContent.css", "x") else: file = open(types["directory"] + "\\chrome\\userContent.css", "w") data = data.split("`") converted = [] for i in range(len(data) - 1): site = data[i][:data[i].find("~")] css = data[i][data[i].find("~") + 1:] css = css.replace("~newline~","\n") css = css.replace(";", " !important;") converted.append("@-moz-document domain(%s) {\n%s\n}\n" % (site, css)) file.write("".join(converted)) file.close() root = tk.Tk("",""," User Stylesheet") app = Application(master=root) app.mainloop()
Java
UTF-8
415
1.671875
2
[]
no_license
package com.techsignage.techsignmeetings.Models; import com.google.gson.annotations.SerializedName; /** * Created by heat on 3/10/2017. */ public class WF_POI { @SerializedName("POI_ID") public String POI_ID; @SerializedName("POI_NAME_E") public String POI_NAME_E; @SerializedName("POI_NAME_A") public String POI_NAME_A; @SerializedName("ROOM_NO") public Integer ROOM_NO; }
PHP
UTF-8
2,808
2.5625
3
[]
no_license
<?php namespace App\Http\Controllers; Use Illuminate\Http\Request; use App\Reservation; use App\ConferenceRoom; use Carbon\Carbon; class ReservationController extends Controller { public function index(){ return Reservation::whereDate('start_time_date', Carbon::today())->get(); } public function store(Request $request){ $validator = $this->validateCustom($request); $query = Reservation::searchPrevius($request)->get(); if(count($query)){ return response()->json(['message' => 'sala de reuniões ocupada','previus'=>$query], 422); } return response()->json(['message' => 'reserva criada com sucesso ', 'reserva'=> Reservation::create($validator)], 200); } public function update($id){ $reservation = Reservation::find($id); if(!$reservation){ return response()->json(['message' => 'esta reserva não existe'], 422); } if($reservation->status === 'cancelado'){ return response()->json(['message' => 'esta reserva já foi cancelada', 'reserva'=> $reservation], 422); } $reservation->status = 'cancelado'; $reservation->save(); return response()->json(['message' => 'reserva cancelada com sucesso', 'reserva'=> $reservation], 200); } protected function validateCustom($request){ return $this->validate($request, [ 'conference_room_id'=>'required', 'email_applicant'=> 'required|email', 'start_time_date'=> 'required|date_format:Y-m-d H:i:s', 'finish_time_date'=> 'required|date_format:Y-m-d H:i:s|after:start_time_date', 'status'=> 'required', 'description'=> 'required' ],[ 'conference_room_id.required'=> 'O campo de sala de reunião é obrigatório.', 'email_applicant.required'=> 'O campo de requerente de email é obrigatório.', 'email_applicant.email'=> 'O requerente de email deve ser um endereço de email válido.', 'start_time_date.required'=> 'O campo de data e hora do início da reunião é obrigatório.', 'start_time_date.date_format'=> 'A data de hora de início não corresponde ao formato Y-m-d H:i:s', 'finish_time_date.required'=> 'O campo de data e hora do término da reunião é obrigatório.', 'finish_time_date.date_format'=> 'A data de hora de término não corresponde ao formato Y-m-d H:i:s', 'finish_time_date.after' => 'A data de término deve ser uma hora após a data de início.', 'status.required'=> 'O campo de situação do agendamento é obrigatório.', 'description.required' => 'O campo de descrição do agendamento é obrigatório.' ]); } }
Markdown
UTF-8
1,217
3
3
[]
no_license
# Report on the memory line test This is a report on the file scad/test-memory-line.scad as of revision c7d5a33b9fb6b9c075aeb098dcb14b1a78f85e44 and prepared with MadFadLab's LaserScript cutter. Brass strips are from Albion Alloys, labelled 6mm * 0.8mm * 305mm and 12mm * 0.4 * 305mm. 12mm strip is 12.1mm and 6mm strip is 6.3mm wide as measured on my vernier micrometer, other measurements are accurate. Cuts for memory profiles are too wide; the 0.4mm strip fits loosely within the smallest cut. However, this is not necessarily a problem. It would be better to err on the side of a wider slot. Forming the metal for the memory profiles is very difficult by hand and we will need some sort of former for them. The brass required is 44mm long, meaning we will get 6 (maybe just 7) out of a strip, meaning we would need 42 packs at a price of £269 (not assuming any volume discount) . We should find a cheaper metal or a different supplier. The 6.3mm strips fit into all the holes width-wise; the smallest hole (0.08mm offset, hence 0.8-0.16mm wide) is only slightly too big; we should do another run starting from 0.8-0.16mm and downwards. The strip fits snugly into the 6th slot which would be 6+0.04mm tall.
Python
UTF-8
298
3.03125
3
[]
no_license
# -*- coding: utf-8 -*- S = list(input()) K = int(input()) for i in range(len(S)): if S[i] == 'a': continue d = ord('z') - ord(S[i]) + 1 if K >= d: S[i] = 'a' K -= d # print(K, d) if K > 0: j = ord(S[-1]) + K % 26 S[-1] = chr(j) print(''.join(S))
Java
UTF-8
594
2.140625
2
[]
no_license
package com.example.quitquick; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; public class SliderPagerAdapter extends FragmentPagerAdapter { public SliderPagerAdapter(@NonNull FragmentManager fm, int behavior) { super(fm, behavior); } @NonNull @Override public Fragment getItem(int position) { return SliderItemFragment.newInstance(position); } // size is hardcoded @Override public int getCount() { return 11; } }
PHP
UTF-8
738
2.765625
3
[ "MIT" ]
permissive
<?php require_once 'validador_acesso.php'; // Para recuperar os dados obtidos via requisição http inseridos na url de valida_login, é bem simples, basta: /* echo $_GET['email']; echo "<br>"; echo $_GET['senha']; echo "<pre>"; print_r($_GET); echo "</pre>"; */ /* echo "<pre>"; print_r($usuarios_app); echo "</pre>"; Utilizando a variável global $_POST, que é um array, podemos acessar os índices e recuperar os valores contidos dentro do formulário. print_r($_POST); echo $_POST['email']; echo "<br>"; echo $_POST['senha']; */ /* // Após a instância de session_start, temos acesso a uma variável super global: $_SESSION['x'] = 'Valor de uma seção'; print_r($_SESSION); echo "<br /> <hr />"; */ ?>
Ruby
UTF-8
912
3.5625
4
[]
no_license
# method removed:)- class Double @@methods_removed = [] def self.methods_removed @@methods_removed end def self.method_removed(name) p @@methods_removed << name end def happie end def birthday end end p Double.new.self.method_removed(progton) # singleton method:)- class Extra @@singleton_methods_removed = [] def self.singleton_methods_removed @@singleton_methods_removed end def self.singleton_method_removed(name) @@singleton_methods_removed << name end def apple end def mango end end p Extra.new.self.singleton_method_removed(progton) # undefined method:)- class Double @@methods_undefined = [] def self.methods_undefined @@methods_undefined end def self.method_undefined(name) @@methods_undefined << name end def happie end def birthday end end p Double.new.self.method_undefined(progton)
Java
UTF-8
7,808
2.421875
2
[]
no_license
package internet.smtp; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.util.List; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.xml.bind.DatatypeConverter; public class MailSender { private static MailSenderLogger logger = new MailSenderLogger( ); //Default private String _userName = "vyrostkoolga@yandex.ru"; private String _userPassword = "Admin000"; //Default private String _host = "smtp.yandex.ru"; private int _port = 465; //Determine if authorization is necessary private boolean _auth = false; private boolean _wantAuth = false; //Determine if we could use some extensions private boolean _size = false; private boolean _pipelining = false; private boolean _starttls = false; //Message to send private MimeMessage _message; private BufferedReader _reader; private BufferedWriter _writer; private Socket _sock; public MailSender( ) { //TODO: future initialization if it's necessary } public MailSender( String host, int port ) { _host = host; _port = port; } public MailSender( String host, int port, String userName, String userPassword ) { _host = host; _port = port; _userName = userName; _userPassword = userPassword; _wantAuth = true; } public static MailSenderLogger getLogger( ) {return logger;} private void createSocket( ) throws Exception { SSLSocketFactory ssf = ( SSLSocketFactory ) SSLSocketFactory.getDefault(); try { _sock = ssf.createSocket( ); _sock.connect(new InetSocketAddress( _host, _port ), 6000); _reader = new BufferedReader( new InputStreamReader(_sock.getInputStream())); _writer = new BufferedWriter( new OutputStreamWriter( _sock.getOutputStream())); connect( ); } catch ( SSLException ex ) { _sock = new Socket( ); _sock.connect( new InetSocketAddress( _host, _port ), 6000 ); _reader = new BufferedReader( new InputStreamReader(_sock.getInputStream())); _writer = new BufferedWriter( new OutputStreamWriter( _sock.getOutputStream())); connect( ); } _sock.setSoTimeout( 5000 ); } public void send( String text, List<String> to, String subject ) throws Exception { try { createSocket( ); if ( _sock == null ) { throw new Exception( "Could not connect" ); } try { if ( _pipelining ) { pipelining( _userName, to, subject, text ); disconnect( ); } else { sendData( to, subject, text ); disconnect( ); } } finally { _writer.flush(); _writer.close(); _reader.close(); _sock.close(); } } catch ( Exception ex ) { logger.writeClientLog(String.format("Could not send message: %s", ex) ); throw ex; } } private void connect( ) throws Exception { //Hello writeAndFlush( "ehlo host" ); String resp = _reader.readLine(); logger.writeServerLog( resp ); String code = resp.substring(0, 3); if (code.startsWith("5")) { throw new IOException( resp ); } resp = _reader.readLine( ); readExtensions( resp ); if ( _starttls ) { writeAndFlush( "STARTTLS" ); resp = _reader.readLine( ); readMultiLine( resp ); SSLSocketFactory ssf = ( SSLSocketFactory ) SSLSocketFactory.getDefault(); SSLSocket s = (SSLSocket) ssf.createSocket( _sock, _sock.getInetAddress().getHostAddress(), _sock.getPort(), true); s.startHandshake( ); _sock = s; _reader = new BufferedReader( new InputStreamReader(_sock.getInputStream())); _writer = new BufferedWriter( new OutputStreamWriter( _sock.getOutputStream())); } if ( _auth ) { if ( ! _wantAuth ) { throw new Exception( "Need auth to send letter, but auth is necessary"); } //Authorization writeAndFlush( "auth login" ); resp = _reader.readLine(); readMultiLine( resp ); writeAndFlush(DatatypeConverter.printBase64Binary(_userName.getBytes())); resp = _reader.readLine(); readMultiLine( resp ); writeAndFlush(DatatypeConverter.printBase64Binary(_userPassword.getBytes())); resp = _reader.readLine(); readMultiLine( resp ); } } private void sendHeaders( String from, List<String> to ) throws Exception { if ( _size ) { String mes = _message.getMessage( ); writeAndFlush( String.format("mail from: <%s> SIZE=%s", from, mes.getBytes().length ) ); } else { writeAndFlush( String.format("mail from: <%s>", from ) ); } String resp = _reader.readLine(); readMultiLine(resp); for (String one: to) { _writer.write(String.format( "RCPT TO:<%s>\n", one ) ); logger.writeClientLog(String.format( "RCPT TO:<%s>\n", one ) ); } _writer.flush( ); resp = _reader.readLine(); readMultiLine( resp ); } private void sendData( List<String> to, String subject, String text ) throws Exception { _message = new MimeMessage( to, _userName, subject, text ); sendHeaders( _userName, to ); writeAndFlush("DATA"); String resp = _reader.readLine(); readMultiLine( resp ); String mes = _message.getMessage( ); _writer.write( mes ); _writer.write("\r\n"); _writer.write(".\r\n"); _writer.flush(); resp = _reader.readLine(); readMultiLine( resp ); } private void disconnect( ) throws IOException { writeAndFlush("QUIT"); String resp = _reader.readLine(); readMultiLine( resp ); } private void pipelining( String from, List<String> to, String subject, String text ) throws Exception { _message = new MimeMessage( to, _userName, subject, text ); String mes = _message.getMessage( ); StringBuffer buffer = new StringBuffer( ); if ( _size ) { long length = mes.getBytes( ).length; buffer.append(String.format("MAIL FROM: <%s> SIZE=%s\n", from, length ) ); } else { buffer.append(String.format("MAIL FROM: <%s>\n", from ) ); } for (String one: to) { buffer.append( String.format("RCPT TO: <%s>\n", one) ); } buffer.append("DATA"); writeAndFlush( new String( buffer ) ); //For from String resp = _reader.readLine( ); readMultiLine( resp ); //For to resp = _reader.readLine( ); readMultiLine( resp ); //For data resp = _reader.readLine( ); readMultiLine( resp ); _writer.write( _message.getMessage( ) ); _writer.flush( ); _writer.write("\r\n.\r\n"); _writer.flush( ); resp = _reader.readLine( ); readMultiLine( resp ); } private void readMultiLine( String resp ) throws IOException { logger.writeServerLog( resp ); String code = resp.substring(0, 3); if (code.startsWith("5")) { throw new IOException( resp ); } String start = String.format("%s ", code); while (! resp.startsWith( start ) ) { resp = _reader.readLine(); logger.writeServerLog( resp ); } } private void readExtensions( String resp ) throws IOException { logger.writeServerLog( resp ); String code = resp.substring(0, 3); if (code.startsWith("5")) { throw new IOException( resp ); } String start = String.format("%s ", code); while (! resp.startsWith( start ) ) { if ( resp.contains( "SIZE" ) ) { _size = true; } else if (resp.contains("PIPELINING")) { _pipelining = true; } else if ( resp.contains( "STARTTLS") ) { _starttls = true; } else if ( resp.contains("AUTH") ) { _auth = true; } resp = _reader.readLine( ); logger.writeServerLog( resp ); } } private void writeAndFlush( String line ) throws IOException { logger.writeClientLog(line); _writer.write( String.format("%s\n", line ) ); _writer.flush( ); } }
Python
UTF-8
382
2.640625
3
[]
no_license
from abc import ABC, abstractmethod import pandas as pd class DataSource(ABC): @abstractmethod def get_features(self) -> pd.DataFrame: """ Gets the features for the dataset """ pass @abstractmethod def get_label(self) -> pd.Series: """ Gets the label for the dataset """ pass
Python
UTF-8
275
2.984375
3
[]
no_license
for tc in range(1, int(input())+1): s = [input() for _ in range(5)] l = [len(i) for i in s] ml = max(l) temp = "" for c in range(ml): for r in range(5): if l[r] > c: temp += s[r][c] print("#{} {}".format(tc, temp))
Java
UTF-8
4,387
2.984375
3
[]
no_license
package edu.upenn.cis.cis455.crawler.info; import edu.upenn.cis.cis455.crawler.queue.ReadyQueueInstance; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; public class URLInfo implements Serializable { private String hostName; private int portNo; private String filePath; private boolean isSecure = false; private boolean isValid = false; private URL url; /** * Constructor called with raw URL as input - parses URL to obtain host name and file path */ public URLInfo(String docURL) { if (docURL == null || docURL.equals("")) return; docURL = docURL.trim(); try { url = new URL(docURL); } catch (MalformedURLException e) { return; } if (docURL.startsWith("https://")) { this.isSecure = true; docURL = docURL.replaceFirst("https:", "http:"); } if (!docURL.startsWith("http://") || docURL.length() < 8) return; // Stripping off 'http://' docURL = docURL.substring(7); /*If starting with 'www.' , stripping that off too if(docURL.startsWith("www.")) docURL = docURL.substring(4);*/ int i = 0; while (i < docURL.length()) { char c = docURL.charAt(i); if (c == '/') break; i++; } String address = docURL.substring(0, i); if (i == docURL.length()) filePath = "/"; else filePath = docURL.substring(i); //starts with '/' if (address.equals("/") || address.equals("")) return; if (address.indexOf(':') != -1) { String[] comp = address.split(":", 2); hostName = comp[0].trim(); try { portNo = Integer.parseInt(comp[1].trim()); } catch (NumberFormatException nfe) { if(isSecure) { portNo = 443; } else { portNo = 80; } } } else { hostName = address; if(isSecure) { portNo = 443; } else { portNo = 80; } } isValid = true; } public URLInfo(String hostName, String filePath) { this.hostName = hostName; this.filePath = filePath; this.portNo = 80; } public URLInfo(String hostName, int portNo, String filePath) { this.hostName = hostName; this.portNo = portNo; this.filePath = filePath; } public String getHostName() { return hostName; } public void setHostName(String s) { hostName = s; } public int getPortNo() { return portNo; } public void setPortNo(int p) { portNo = p; } public String getFilePath() { return filePath; } public void setFilePath(String fp) { filePath = fp; } public boolean isSecure() { return this.isSecure; } public void setSecure(boolean sec) { this.isSecure = sec; } public boolean isValid() { return isValid; } public static void main(String[] args) { URLInfo urlInfo = new URLInfo("http://www.google.com/"); //System.out.println(urlInfo.filePath); } public boolean equals(Object obj) { if(obj instanceof URLInfo) { URLInfo instance = (URLInfo) obj; if(((this.getHostName() == null && instance.getHostName() == null) || (this.getHostName()!=null && this.getHostName().equals(instance.getHostName()))) && this.getPortNo() == instance.getPortNo() && ((this.getFilePath() == null && instance.getFilePath() == null) || (this.getFilePath()!=null && this.getFilePath().equals(instance.getFilePath()))) && this.isSecure == instance.isSecure) { return true; } } return false; } public int hashCode() { String protocol = isSecure() ? "https" : "http"; String output = protocol + "://" + this.hostName + ":" + this.portNo + "/"+ this.filePath; return output.hashCode(); } public URL getUrl() { return url; } }
Java
UTF-8
4,309
2.546875
3
[]
no_license
package control; import com.google.gson.*; import comm.*; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.*; import model.*; import view.PlayerWindow; import comm.Receptor.OnMessageListener; public class PlayerController implements OnMessageListener { private PlayerWindow view; private TCPConnection connection; private String id; public PlayerController(PlayerWindow view) { this.view = view; init(); } public void init() { connection = TCPConnection.getInstance(); connection.setListenerOfMessages(this); view.getTakeCard().setOnAction(event -> { Gson gson = new Gson(); String json = gson.toJson(new AdditionalCards(id, "")); TCPConnection.getInstance().getEmisor().sendMessage(json); view.notMyTurn(); }); view.getStand().setOnAction(event -> { Gson gson = new Gson(); String json = gson.toJson(new Stand(id, view.getScore().getText())); TCPConnection.getInstance().getEmisor().sendMessage(json); view.stand(); }); view.getRestart().setOnAction(event -> { Gson gson = new Gson(); String json = gson.toJson(new Restart()); TCPConnection.getInstance().getEmisor().sendMessage(json); }); } public void winner(){ view.updateStatus("¡Ganaste!"); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("¡Ganaste!"); alert.setHeaderText(null); alert.setContentText("Ganaste la partida, si desea jugar de nuevo reinice"); alert.show(); view.stand(); } public void lost(){ view.updateStatus("¡Perdiste!"); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("¡Perdiste!"); alert.setHeaderText(null); alert.setContentText("El adversario ganó la partida, si desea jugar de nuevo reinice"); alert.show(); view.stand(); } public void countScore(){ Gson gson = new Gson(); if(Integer.parseInt(view.getScore().getText()) == 21){ Win uWin = new Win(id, "Winner"); String json = gson.toJson(uWin); TCPConnection.getInstance().getEmisor().sendMessage(json); view.stand(); } else if (Integer.parseInt(view.getScore().getText()) > 21){ MoreTO moreTO = new MoreTO(id, view.getScore().getText()); String json = gson.toJson(moreTO); TCPConnection.getInstance().getEmisor().sendMessage(json); view.stand(); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("¡Puntaje mayor a 21!"); alert.setHeaderText(null); alert.setContentText("Perdiste. A la espera de que el adversario termine de jugar"); alert.show(); view.stand(); } } public void notifyImReady(){ Gson gson = new Gson(); StartGame startGame = new StartGame(id); String json = gson.toJson(startGame); TCPConnection.getInstance().getEmisor().sendMessage(json); } public void deadHeat(){ view.updateStatus("¡Empate!"); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("¡Empate!"); alert.setHeaderText(null); alert.setContentText("Usted y el adversario empataron la partida"); alert.show(); view.stand(); } @Override public void OnMessage(String msg) { Platform.runLater(() -> { Gson gson = new Gson(); Generic msjObj = gson.fromJson(msg, Generic.class); System.out.println(msjObj.getType()); switch (msjObj.getType()){ case "BaseCards": BaseCards bc = gson.fromJson(msg, BaseCards.class); this.id = bc.getId(); String[] tempBC = bc.getBody().split(","); view.showBaseCards(tempBC[0], tempBC[1]); if(bc.isFirstPlayer() == true){ view.myTurn(); } notifyImReady(); countScore(); break; case "AdditionalCards": AdditionalCards ac = gson.fromJson(msg, AdditionalCards.class); view.showAdditionalCard(ac.getBody()); countScore(); break; case "Turn": view.myTurn(); break; case "Win": winner(); view.activeRestartBtn(); break; case "DeadHeat": deadHeat(); view.activeRestartBtn(); break; case "Restart": view.reboot(); break; case "Lost": lost(); view.activeRestartBtn(); break; case "StartGame": view.startGame(); break; } } ); } }
Python
UTF-8
271
3.78125
4
[]
no_license
# saludo1 = "hello" # print (saludo) # print("hola") saludo = input("escribe un saludo: ") print(saludo) age = input("ingresa tu edad: ") # age = int(input("ingresa tu edad: ")) tambien puede ser asi para convertir el dato en int new_age = int(age) + 50 print(new_age)
Java
UTF-8
1,310
2.3125
2
[]
no_license
package com.shape100.gym.adapter; import android.annotation.SuppressLint; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.shape100.gym.R; public class TimeAdapter extends BaseAdapter { private Context context; private String[] data; private boolean flag; public TimeAdapter(Context context, String[] data,boolean flag) { this.context = context; this.data = data; this.flag=flag; } @Override public int getCount() { return data.length; } @Override public Object getItem(int position) { return data[position]; } @Override public long getItemId(int position) { return position; } @SuppressLint("ViewHolder") @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; view = LayoutInflater.from(context).inflate(R.layout.list_time, parent,false); TextView time = (TextView) view.findViewById(R.id.tv_time); ImageView imageView=(ImageView) view.findViewById(R.id.img_pic); if (flag) { imageView.setVisibility(View.VISIBLE); }else { imageView.setVisibility(View.GONE); } time.setText(data[position]); return view; } }
TypeScript
UTF-8
334
2.59375
3
[]
no_license
export interface Ratio { diameters: Diameter[]; kind: string; _id: string; value: number; widthId: string; } export interface Diameter { ratios?: Ratio[]; kind: string; _id: string; value: number; ratioId?: string; } export interface Width { ratios?: Ratio[]; kind: string; _id: string; value: number; }
Java
UTF-8
1,640
2.6875
3
[]
no_license
package com.cookandroid.mobileprogramming; import java.util.Calendar; import java.util.GregorianCalendar; import android.app.Activity; import android.app.DatePickerDialog; import android.os.Bundle; import android.view.View; import android.widget.DatePicker; import android.widget.TextView; public class MainActivity extends Activity { int mYear, mMonth, mDay; TextView mTxtDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail_1); mTxtDate = (TextView)findViewById(R.id.txtdate); Calendar cal = new GregorianCalendar(); mYear = cal.get(Calendar.YEAR); mMonth = cal.get(Calendar.MONTH); mDay = cal.get(Calendar.DAY_OF_MONTH); UpdateNow(); } public void OnClickbtn(View v){ switch(v.getId()){ case R.id.btnchangedate: new DatePickerDialog(MainActivity.this, mDateSetListener, mYear, mMonth, mDay).show(); break; } } DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; UpdateNow(); } }; void UpdateNow(){ mTxtDate.setText(String.format("%d/%d/%d", mYear, mMonth + 1, mDay)); } }
Java
UTF-8
7,276
2.671875
3
[]
no_license
package com.crtvu.dto; public class FinalPoint { private int id; private String name; private int mid; private int year; private double point; private double point1; private double point11; private double point12; private double point13; private double point14; private double point101; private double point102; private double point103; private double point104; private double point105; private double point106; private double point107; private double point108; private double point109; public double getPoint109() { return point109; } public void setPoint109(double point109) { this.point109 = point109; } private double point2; private double point21; private double point22; private double point23; private double point24; private double point25; public void init(){ this.setPoint(0); this.setPoint1(0); this.setPoint2(0); this.setPoint11(0); this.setPoint12(0); this.setPoint13(0); this.setPoint14(0); this.setPoint101(0); this.setPoint102(0); this.setPoint103(0); this.setPoint104(0); this.setPoint105(0); this.setPoint106(0); this.setPoint107(0); this.setPoint108(0); this.setPoint109(0); this.setPoint21(0); this.setPoint22(0); this.setPoint23(0); this.setPoint24(0); this.setPoint25(0); } public FinalPoint(int id, String name, int mid, int year, double point, double point1, double point11, double point12, double point13, double point14, double point101, double point102, double point103, double point104, double point105, double point106, double point107, double point108, double point109, double point2, double point21, double point22, double point23, double point24, double point25) { this.id = id; this.name = name; this.mid = mid; this.year = year; this.point = point; this.point1 = point1; this.point11 = point11; this.point12 = point12; this.point13 = point13; this.point14 = point14; this.point101 = point101; this.point102 = point102; this.point103 = point103; this.point104 = point104; this.point105 = point105; this.point106 = point106; this.point107 = point107; this.point108 = point108; this.point109 = point109; this.point2 = point2; this.point21 = point21; this.point22 = point22; this.point23 = point23; this.point24 = point24; this.point25 = point25; } @Override public String toString() { return "FinalPoint{" + "id=" + id + ", name='" + name + '\'' + ", mid=" + mid + ", year=" + year + ", point=" + point + ", point1=" + point1 + ", point11=" + point11 + ", point12=" + point12 + ", point13=" + point13 + ", point14=" + point14 + ", point101=" + point101 + ", point102=" + point102 + ", point103=" + point103 + ", point104=" + point104 + ", point105=" + point105 + ", point106=" + point106 + ", point107=" + point107 + ", point108=" + point108 + ", point2=" + point2 + ", point21=" + point21 + ", point22=" + point22 + ", point23=" + point23 + ", point24=" + point24 + ", point25=" + point25 + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMid() { return mid; } public void setMid(int mid) { this.mid = mid; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public double getPoint() { return point; } public void setPoint(double point) { this.point = point; } public double getPoint1() { return point1; } public void setPoint1(double point1) { this.point1 = point1; } public double getPoint11() { return point11; } public void setPoint11(double point11) { this.point11 = point11; } public double getPoint12() { return point12; } public void setPoint12(double point12) { this.point12 = point12; } public double getPoint13() { return point13; } public void setPoint13(double point13) { this.point13 = point13; } public double getPoint14() { return point14; } public void setPoint14(double point14) { this.point14 = point14; } public double getPoint101() { return point101; } public void setPoint101(double point101) { this.point101 = point101; } public double getPoint102() { return point102; } public void setPoint102(double point102) { this.point102 = point102; } public double getPoint103() { return point103; } public void setPoint103(double point103) { this.point103 = point103; } public double getPoint104() { return point104; } public void setPoint104(double point104) { this.point104 = point104; } public double getPoint105() { return point105; } public void setPoint105(double point105) { this.point105 = point105; } public double getPoint106() { return point106; } public void setPoint106(double point106) { this.point106 = point106; } public double getPoint107() { return point107; } public void setPoint107(double point107) { this.point107 = point107; } public double getPoint108() { return point108; } public void setPoint108(double point108) { this.point108 = point108; } public double getPoint2() { return point2; } public void setPoint2(double point2) { this.point2 = point2; } public double getPoint21() { return point21; } public void setPoint21(double point21) { this.point21 = point21; } public double getPoint22() { return point22; } public void setPoint22(double point22) { this.point22 = point22; } public double getPoint23() { return point23; } public void setPoint23(double point23) { this.point23 = point23; } public double getPoint24() { return point24; } public void setPoint24(double point24) { this.point24 = point24; } public double getPoint25() { return point25; } public void setPoint25(double point25) { this.point25 = point25; } public FinalPoint() { } }
SQL
UTF-8
415
3.609375
4
[]
no_license
create table doc_tag ( doc_id bigint not null, tag_id bigint not null, primary key (doc_id, tag_id) ) engine=InnoDB; create table tag ( id bigint not null, value varchar(255), primary key (id) ) engine=InnoDB; alter table doc_tag add constraint doc_tag_fk_tag foreign key (tag_id) references tag (id); alter table doc_tag add constraint doc_tag_fk_doc foreign key (doc_id) references doc (id);
C#
UTF-8
20,627
2.84375
3
[ "MIT" ]
permissive
using System; using System.Linq; using Xunit; namespace VersionTools.Lib.Test { public class SemverTest { public class Parse_method { [Fact] public void should_parse_a_normal_version_without_prerelease_and_build_info() { var semver = Semver.Parse("1.2.3"); Assert.Equal(1, semver.Major); Assert.Equal(2, semver.Minor); Assert.Equal(3, semver.Patch); } [Fact] public void should_parse_a_version_with_prerelese_information() { var semver = Semver.Parse("1.2.3-beta.2"); Assert.Equal("beta.2", semver.PreRelease); } [Fact] public void should_parse_a_version_with_build_meta_data_but_no_prerelase_info() { var semver = Semver.Parse("1.2.3+master.c34fede"); Assert.Equal("master.c34fede", semver.Build); } [Fact] public void should_parse_a_version_with_both_prerelease_and_build_info() { var semver = Semver.Parse("1.2.3-beta+master"); Assert.Equal(1, semver.Major); Assert.Equal(2, semver.Minor); Assert.Equal(3, semver.Patch); Assert.Equal("beta", semver.PreRelease); Assert.Equal("master", semver.Build); } [Fact] public void should_throw_a_format_exception_when_the_input_string_is_an_invalid_semver() { Assert.Throws<FormatException>(() => Semver.Parse("1.2-foo")); } [Fact] public void should_trim_trailing_whitespace() { var semver = Semver.Parse("1.0.0 "); Assert.Equal(semver, new Semver(1,0,0)); } [Fact] public void should_trim_starting_whitespace() { var semver = Semver.Parse(" 1.0.0"); Assert.Equal(semver, new Semver(1,0,0)); } } public class IsValidSemver_method { [Fact] public void should_return_true_when_arg_is_a_valid_semver_version() { Assert.True( Semver.IsValidSemver("1.2.3-pre+build")); } [Fact] public void should_return_false_when_args_is_not_a_valid_semver_version() { Assert.False( Semver.IsValidSemver("foobar")); } } public class OverrideBuild_method { [Fact] public void should_create_a_new_version_with_the_specified_build() { var version = "1.2.3-pre+build"; var semver = Semver.Parse(version); var newSemver = semver.OverrideBuild("new.build"); Assert.Equal("1.2.3-pre+new.build", newSemver.FullVersion); } } public class FullVersion_property { [Fact] public void should_display_the_full_version_including_prerelease_and_build_info() { var version = "1.2.3-pre+build"; var semver = Semver.Parse(version); Assert.Equal(version, semver.FullVersion); } } public class Version_property { [Fact] public void should_display_the_string_value_of_the_normal_version() { var version = "1.2.3-pre+build"; var semver = Semver.Parse(version); Assert.Equal("1.2.3", semver.Version); } } public class ToString_method { [Fact] public void should_display_the_full_version_when_called_without_argument() { var semver = new Semver(1,2,3,"pre", "build"); Assert.Equal("1.2.3-pre+build", semver.ToString()); } [Fact] public void should_display_prerelease_version_when_called_with_P_argument() { var semver = new Semver(1,2,3,"pre", "build"); Assert.Equal("1.2.3-pre", semver.ToString("P")); } [Fact] public void should_display_full_version_when_called_with_F_argument() { var semver = new Semver(1,2,3,"pre", "build"); Assert.Equal("1.2.3-pre+build", semver.ToString("F")); } [Fact] public void should_display_normal_version_when_called_with_V_argument() { var semver = new Semver(1,2,3,"pre", "build"); Assert.Equal("1.2.3", semver.ToString("V")); } [Fact] public void should_throw_format_exception_when_format_is_not_a_valid_value() { var semver = new Semver(1,2,3,"pre", "build"); Assert.Throws<FormatException>(() => semver.ToString("X")); } [Fact] public void should_display_normal_version_when_called_with_P_argument_and_version_is_not_prerelease() { var semver = new Semver(1,2,3,"", "build"); Assert.Equal("1.2.3", semver.ToString("P")); } } public class IsPreRelease_property { [Fact] public void should_return_true_when_version_is_a_pre_release() { var semver = new Semver(1,2,3,"pre"); Assert.True( semver.IsPreRelease ); } [Fact] public void should_return_false_when_version_is_not_a_pre_release() { var semver = new Semver(1, 2, 3); Assert.False( semver.IsPreRelease ); } } public class CompareTo_method { [Fact] public void should_return_0_when_versions_are_equal() { var v1 = Semver.Parse("1.2.3"); var v2 = Semver.Parse("1.2.3"); var compared = v1.CompareTo(v2); Assert.Equal(0, compared); } [Fact] public void should_not_include_build_in_comparison() { var v1 = Semver.Parse("1.2.3+fuu"); var v2 = Semver.Parse("1.2.3+bar"); var compared = v1.CompareTo(v2); Assert.Equal(0, compared); } [Fact] public void should_return_minus_1_when_args_patch_nr_is_greater_than_own_patch_nr_other_things_equal() { var v1 = Semver.Parse("1.2.1"); var v2 = Semver.Parse("1.2.2"); var compared = v1.CompareTo(v2); Assert.Equal(-1, compared); } [Fact] public void should_return_minus_1_when_args_minor_nr_is_greater_than_own_minor_nr_other_things_equal() { var v1 = Semver.Parse("1.0.0"); var v2 = Semver.Parse("1.1.0"); var compared = v1.CompareTo(v2); Assert.Equal(-1, compared); } [Fact] public void should_return_minus_1_when_args_major_nr_is_greater_than_own_major_nr_other_things_equal() { var v1 = Semver.Parse("2.1.0"); var v2 = Semver.Parse("3.1.0"); var compared = v1.CompareTo(v2); Assert.Equal(-1, compared); } [Fact] public void should_return_1_when_args_patch_nr_is_less_than_own_patch_nr_other_things_equal() { var v1 = Semver.Parse("1.2.3"); var v2 = Semver.Parse("1.2.2"); var compared = v1.CompareTo(v2); Assert.Equal(1, compared); } [Fact] public void should_return_1_when_args_minor_nr_is_less_than_own_minor_nr_other_things_equal() { var v1 = Semver.Parse("1.2.0"); var v2 = Semver.Parse("1.1.0"); var compared = v1.CompareTo(v2); Assert.Equal(1, compared); } [Fact] public void should_return_1_when_args_major_nr_is_less_than_own_major_nr_other_things_equal() { var v1 = Semver.Parse("2.1.0"); var v2 = Semver.Parse("1.1.0"); var compared = v1.CompareTo(v2); Assert.Equal(1, compared); } [Fact] public void should_return_1_when_arg_is_prerelease() { var v1 = Semver.Parse("1.2.3"); var v2 = Semver.Parse("1.2.3-pre"); var compared = v1.CompareTo(v2); Assert.Equal(1, compared); } [Fact] public void should_return_minus_1_when_self_is_prerelease() { var v1 = Semver.Parse("1.2.3-pre"); var v2 = Semver.Parse("1.2.3"); var compared = v1.CompareTo(v2); Assert.Equal(-1, compared); } [Fact] public void should_return_1_when_own_prerelease_has_more_fields_than_other() { var v1 = Semver.Parse("1.2.3-pre.1"); var v2 = Semver.Parse("1.2.3-pre"); var compared = v1.CompareTo(v2); Assert.Equal(1, compared); } [Fact] public void should_return_minus_1_when_own_prerelease_has_less_fields_than_other() { var v1 = Semver.Parse("1.2.3-pre"); var v2 = Semver.Parse("1.2.3-pre.1"); var compared = v1.CompareTo(v2); Assert.Equal(-1, compared); } [Fact] public void should_return_1_when_own_numeric_prerelease_is_greater_than_other() { var v1 = Semver.Parse("1.2.3-2"); var v2 = Semver.Parse("1.2.3-1"); var compared = v1.CompareTo(v2); Assert.Equal(1, compared); } [Fact] public void should_return_minus_1_when_own_numeric_prerelease_is_less_than_other() { var v1 = Semver.Parse("1.2.3-1"); var v2 = Semver.Parse("1.2.3-2"); var compared = v1.CompareTo(v2); Assert.Equal(-1, compared); } [Fact] public void should_return_1_when_own_prerelease_is_alphanum_and_other_is_numeric() { var v1 = Semver.Parse("1.2.3-alpha"); var v2 = Semver.Parse("1.2.3-1"); var compared = v1.CompareTo(v2); Assert.Equal(1, compared); } [Fact] public void should_return_minus_1_when_own_prerelease_is_numeric_and_other_is_alphanum() { var v1 = Semver.Parse("1.2.3-1"); var v2 = Semver.Parse("1.2.3-alpha"); var compared = v1.CompareTo(v2); Assert.Equal(-1, compared); } [Fact] public void should_return_1_when_own_prerelease_is_lexically_greater_than_other() { var v1 = Semver.Parse("1.2.3-beta"); var v2 = Semver.Parse("1.2.3-alpha"); var compared = v1.CompareTo(v2); Assert.Equal(1,compared); } [Fact] public void should_return_minus_1_when_own_prerelease_is_lexically_less_than_other() { var v1 = Semver.Parse("1.2.3-alpha"); var v2 = Semver.Parse("1.2.3-beta"); var compared = v1.CompareTo(v2); Assert.Equal(-1,compared); } [Fact] public void should_ignore_case_when_comparing_prereleases() { var v1 = Semver.Parse("1.2.3-alpha"); var v2 = Semver.Parse("1.2.3-ALPHA"); var compared = v1.CompareTo(v2); Assert.Equal(0, compared); } [Fact] public void should_handle_the_example_precedence_chain_on_the_semver_webpage() { var versions = new[] { "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0" } .Select(Semver.Parse) .ToArray(); for (var i = 1; i < versions.Length; i++) { var comparedToPrevious = versions[i].CompareTo(versions[i - 1]); Assert.Equal(1, comparedToPrevious); } } } public class Equals_method { [Fact] public void should_return_true_when_versions_are_lexically_equal() { var v1 = Semver.Parse("1.2.3-beta"); var v2 = Semver.Parse("1.2.3-beta"); var areEqual = v1.Equals(v2); Assert.True(areEqual); } [Fact] public void should_ignore_build_info() { var v1 = Semver.Parse("1.2.3-beta+foo"); var v2 = Semver.Parse("1.2.3-beta"); var areEqual = v1.Equals(v2); Assert.True(areEqual); } [Fact] public void should_ignore_case() { var v1 = Semver.Parse("1.2.3-beta"); var v2 = Semver.Parse("1.2.3-BETA"); var areEqual = v1.Equals(v2); Assert.True(areEqual); } [Fact] public void should_return_false_when_versions_are_not_equal() { var v1 = Semver.Parse("1.2.4-beta"); var v2 = Semver.Parse("1.2.3-beta"); var areEqual = v1.Equals(v2); Assert.False(areEqual); } [Fact] public void should_return_false_when_other_object_is_null() { var v1 = Semver.Parse("1.2.4-beta"); Assert.False( v1.Equals(null)); } [Fact] public void should_return_false_when_other_object_is_not_a_semver() { var v1 = Semver.Parse("1.2.4-beta"); Assert.False( v1.Equals(new object())); } } public class GetHashCode_method { [Fact] public void should_return_the_same_code_for_equal_versions() { var code1 = Semver.Parse("1.2.3-beta"); var code2 = Semver.Parse("1.2.3-beta"); Assert.Equal( code1.GetHashCode(), code2.GetHashCode()); } [Fact] public void should_return_different_codes_for_different_versions() { var code1 = Semver.Parse("1.3.3-beta"); var code2 = Semver.Parse("1.2.3-beta"); Assert.NotEqual( code1.GetHashCode(), code2.GetHashCode()); } [Fact] public void should_ignore_build_meta_data() { var code1 = Semver.Parse("1.2.3-beta+build1"); var code2 = Semver.Parse("1.2.3-beta+build2"); Assert.Equal( code1.GetHashCode(), code2.GetHashCode()); } } public class operator_equals { [Fact] public void should_return_true_when_versions_are_equal() { var ver1 = Semver.Parse("1.2.3-beta"); var ver2 = Semver.Parse("1.2.3-beta"); Assert.True( ver1 == ver2 ); } [Fact] public void should_return_false_when_versions_are_not_equal() { var ver1 = Semver.Parse("1.2.3-beta"); var ver2 = Semver.Parse("1.2.3-charlie"); Assert.False( ver1 == ver2 ); } } public class operator_not_equals { [Fact] public void should_return_false_when_versions_are_equal() { var ver1 = Semver.Parse("1.2.3-beta"); var ver2 = Semver.Parse("1.2.3-beta"); Assert.False( ver1 != ver2 ); } [Fact] public void should_return_true_when_version_are_not_equal() { var ver1 = Semver.Parse("1.2.3-beta"); var ver2 = Semver.Parse("1.2.3-charlie"); Assert.True( ver1 != ver2 ); } } public class operator_greater_than { [Fact] public void should_return_true_when_left_operand_is_greater_than_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("1.9.9"); Assert.True( ver1 > ver2 ); } [Fact] public void should_return_false_when_left_operand_is_less_than_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("2.9.9"); Assert.False( ver1 > ver2 ); } [Fact] public void should_return_false_when_left_operand_is_equal_to_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("2.0.0"); Assert.False( ver1 > ver2 ); } } public class operator_less_than { [Fact] public void should_return_true_when_left_operand_is_less_than_right_operand() { var ver1 = Semver.Parse("1.0.0"); var ver2 = Semver.Parse("1.9.9"); Assert.True( ver1 < ver2 ); } [Fact] public void should_return_false_when_left_operand_is_greater_than_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("1.9.9"); Assert.False( ver1 < ver2 ); } [Fact] public void should_return_false_when_left_operand_is_equal_to_right_operand() { var ver1 = Semver.Parse("2.0.0-beta"); var ver2 = Semver.Parse("2.0.0-beta"); Assert.False( ver1 < ver2 ); } } public class operator_less_than_or_equal { [Fact] public void should_return_true_when_left_operand_is_less_than_right_operand() { var ver1 = Semver.Parse("1.0.0"); var ver2 = Semver.Parse("1.9.9"); Assert.True( ver1 <= ver2 ); } [Fact] public void should_return_false_when_left_operand_is_greater_than_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("1.9.9"); Assert.False( ver1 <= ver2 ); } [Fact] public void should_return_true_when_left_operand_is_equal_to_right_operand() { var ver1 = Semver.Parse("2.0.0-beta"); var ver2 = Semver.Parse("2.0.0-beta"); Assert.True( ver1 <= ver2 ); } } public class operator_greater_than_or_equal { [Fact] public void should_return_true_when_left_operand_is_greater_than_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("1.9.9"); Assert.True( ver1 >= ver2 ); } [Fact] public void should_return_false_when_left_operand_is_less_than_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("2.9.9"); Assert.False( ver1 >= ver2 ); } [Fact] public void should_return_true_when_left_operand_is_equal_to_right_operand() { var ver1 = Semver.Parse("2.0.0"); var ver2 = Semver.Parse("2.0.0"); Assert.True( ver1 >= ver2 ); } } } }
Python
UTF-8
172
3.71875
4
[]
no_license
C_temperature = float(input("섭씨 온도를 입력해주세요: ")) F_temperature = C_temperature * 9/5 + 32 print("화씨 온도는 ", F_temperature, "입니다.")
Python
UTF-8
691
2.53125
3
[]
no_license
import pandas as pd import plotly import plotly.graph_objs as go def multiDScatterPlot(): col_list = ["age", "freetime", "goout", "studytime"] data = pd.read_csv("student-mat.csv", usecols=col_list) markercolor = data['age'] figure = go.Scatter3d(x=data['freetime'], y=data['goout'], z=data['studytime'], marker=dict(color=markercolor,opacity=1,reversescale=True,colorscale='Blues',size=5),line=dict (width=0.02), mode='markers') layout = go.Layout(scene=dict(xaxis =dict( title="Free Time"), yaxis=dict( title="Go Out"), zaxis=dict( title="Study Time")),) plotly.offline.plot({"data": [figure], "layout": layout}, auto_open=True, filename=("4DPlot.html"))
Java
UTF-8
1,856
2.1875
2
[]
no_license
package edu.multi.member; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MemberController { @Autowired MemberDAO dao; //메인화면 @RequestMapping("/session") public String main(){ return "mybatis/main"; } //로그인폼 @RequestMapping("/session/login") public String loginform(){ return "mybatis/login"; } //로그인폼 입력 - db member 테이블 존재 - 세션 저장 @RequestMapping("/session/loginprocess") public String loginprocess(HttpServletRequest request, String userid, String password){ MemberVO vo = dao.selectMember(userid, password); HttpSession session = request.getSession(); session.setAttribute("member", vo); return "mybatis/loginprocess"; } @RequestMapping("/session/mypage") public String getMyPage() { return "mybatis/mypage"; } //로그아웃 @RequestMapping("/session/logout") public String logout(HttpSession session) { //HttpSession객체 저장 정보 삭제 //HttpSession session = request.getSession(); //session.removeAttribute("member"); return "mybatis/logout"; } //회원가입 @RequestMapping("/session/add") public String add(){ return "mybatis/add"; } //회원가입폼 입력 @RequestMapping("/session/addprocess") public String addprocess(MemberVO vo){ try{ dao.insertMemeber(vo); return "mybatis/success"; }catch (Exception e) { return "mybatis/fail"; } } //회원가입 성공 @RequestMapping("/session/success") public String success(){ return "mybatis/success"; } //회원가입 실패 @RequestMapping("/session/fail") public String fail(){ return "mybatis/fail"; } }
Java
UTF-8
12,393
2.1875
2
[]
no_license
package com.development.georgemcl.binaryapp; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.Random; /** * A simple {@link Fragment} subclass. */ public class PracticeFragment extends Fragment { TextView numberTxt; EditText answerTf; TextView isCorrectTxt; FloatingActionButton newNumFab; Spinner rangeSpin; Spinner modeSpin; Button checkBtn; InputFilter binaryFilter; InputFilter hexFilter; public PracticeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_practice, container, false); numberTxt = (TextView) view.findViewById(R.id.numberTxt); answerTf = (EditText) view.findViewById(R.id.answerTxt); isCorrectTxt = (TextView) view.findViewById(R.id.isCorrectTxt); newNumFab = (FloatingActionButton) view.findViewById(R.id.newNumFab); checkBtn = (Button) view.findViewById(R.id.checkBtn); initialiseInputFilters(); newNumberClick(); checkAnswerClick(); editTextButtonClick(); return view; } //Toolbar @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_practice, menu); //Spinner Initialisation MenuItem item = menu.findItem(R.id.action_rangeSpin); rangeSpin = (Spinner) MenuItemCompat.getActionView(item); MenuItem modeItem = menu.findItem(R.id.action_modeSpin); modeSpin = (Spinner) MenuItemCompat.getActionView(modeItem); String[] modes = {"Decimal to Binary", "Decimal to Hexadecimal", "Binary to Decimal", "Binary to Hexadecimal", "Hexadecimal to Decimal", "Hexadecimal to Binary"}; ArrayAdapter modeAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, modes); modeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); modeSpin.setAdapter(modeAdapter); String[] numRanges = {"1-15","16-63", "64-127", "128-512"}; ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, numRanges); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); rangeSpin.setAdapter(adapter); SharedPreferences sharedPref = getActivity().getSharedPreferences("PracticeSpinners", Context.MODE_PRIVATE); int modeSpinnerVal = sharedPref.getInt("ModeSpinnerVal",-1); int rangeSpinnerVal = sharedPref.getInt("RangeSpinnerVal",-1); if(modeSpinnerVal != -1 && rangeSpinnerVal != -1) { // set the selected value of the spinner modeSpin.setSelection(modeSpinnerVal); rangeSpin.setSelection(rangeSpinnerVal); } //listeners for the spinners modeSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //make toolbar text white ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE); if (position == 2 || position == 4){ answerTf.setInputType(InputType.TYPE_CLASS_NUMBER); answerTf.setFilters(new InputFilter[]{}); answerTf.setHint("enter decimal answer"); } else if (position == 0 || position == 5){ answerTf.setInputType(InputType.TYPE_CLASS_NUMBER); answerTf.setFilters(new InputFilter[]{binaryFilter}); answerTf.setHint("enter binary answer"); } else if (position == 1 || position == 3){ answerTf.setInputType(InputType.TYPE_CLASS_TEXT); answerTf.setFilters(new InputFilter[]{hexFilter}); answerTf.setHint("enter hexadecimal answer"); } SharedPreferences sharedPreferences = getActivity().getSharedPreferences("PracticeSpinners",0); SharedPreferences.Editor prefEditor = sharedPreferences.edit(); prefEditor.putInt("ModeSpinnerVal",position); prefEditor.apply(); setNewQuestion(); } @Override public void onNothingSelected(AdapterView<?> parent) {} }); rangeSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { ((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE); SharedPreferences sharedPreferences = getActivity().getSharedPreferences("PracticeSpinners",0); SharedPreferences.Editor prefEditor = sharedPreferences.edit(); prefEditor.putInt("RangeSpinnerVal",position); prefEditor.apply(); setNewQuestion(); } @Override public void onNothingSelected(AdapterView<?> parent) {} }); } //Procedures private void setNewQuestion(){ answerTf.setText(""); isCorrectTxt.setText(""); Random questionRan = new Random(); if (rangeSpin == null) return; String range = rangeSpin.getSelectedItem().toString(); int num; //generate a random number within the range selected if (range.equals("1-15")) { num = questionRan.nextInt(14) + 1; }else if (range.equals("16-63")){ num = questionRan.nextInt(47) + 16; }else if (range.equals("64-127")){ num = questionRan.nextInt(63)+64; }else if (range.equals("128-512")) { num = questionRan.nextInt(384)+128; } else num = 0; String mode = modeSpin.getSelectedItem().toString(); //Convert the random decimal to the appropriate base if converting from binary/hex if (mode.equals("Binary to Decimal") || mode.equals("Binary to Hexadecimal")){ numberTxt.setText(separateBinaryBytes(Integer.toBinaryString(num))); } else if (mode.equals("Hexadecimal to Decimal") || mode.equals("Hexadecimal to Binary")){ numberTxt.setText(Integer.toHexString(num)); } else{ String numStr = num+""; numberTxt.setText(numStr); } } private void checkAnswer(){ String answer = ""; String userAnswer; String question = numberTxt.getText().toString().replace(" ",""); userAnswer = answerTf.getText().toString(); String mode = modeSpin.getSelectedItem().toString(); if (mode.equals("Decimal to Binary")) { //convert the decimal question into its binary answer answer = Integer.toBinaryString(Integer.parseInt(question)); } else if (mode.equals("Decimal to Hexadecimal")){ answer = Integer.toHexString(Integer.parseInt(question)); } else if (mode.equals("Binary to Decimal")){ answer = Integer.parseInt(question, 2) +""; } else if (mode.equals("Binary to Hexadecimal")){ int decimal = Integer.parseInt(question, 2); answer = Integer.toHexString(decimal); } else if (mode.equals("Hexadecimal to Decimal")){ answer = Integer.parseInt(question,16) +""; } else if (mode.equals("Hexadecimal to Binary")){ int decimal = Integer.parseInt(question, 16); answer = Integer.toBinaryString(decimal); } userAnswer = deleteLeadingZeros(userAnswer); if (answer.equals(userAnswer)){ isCorrectTxt.setText(R.string.correctTxt); isCorrectTxt.setTextColor(Color.parseColor("#08a534")); }else{ isCorrectTxt.setText(R.string.incorrectTxt); isCorrectTxt.setTextColor(Color.parseColor("#ce0606")); } } private String deleteLeadingZeros(String userAnswer){ StringBuilder sb = new StringBuilder(userAnswer); while (sb.length() > 0 && sb.charAt(0) == '0') { sb.deleteCharAt(0); } return sb.toString(); } //ISSUE private String separateBinaryBytes(String original){ StringBuilder sb = new StringBuilder(original); int count = 0; for (int i = sb.length(); i > 0; i--) { if (count % 4 == 0) { sb.insert(i, ' '); } count++; } return sb.toString(); } private void initialiseInputFilters() { binaryFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++){ char current = source.charAt(i); if (current != '0' && current != '1') {return "";} } return null; } }; hexFilter = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++){ //convert the current character into ascii format int current = (int) source.charAt(i); //check if it doesnt fall between 0-9 or a-f if (current < 47 || (current >57 && current <97) || current > 102) { return source.subSequence(0, source.length() -1); } } return null; } }; } //BUTTON HANDLERS private void checkAnswerClick(){ checkBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkAnswer(); } }); } private void editTextButtonClick() { answerTf.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_GO) { checkAnswer(); return true; } return false; } }); } private void newNumberClick(){ newNumFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setNewQuestion(); } }); newNumFab.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getContext(), "Click for a new number", Toast.LENGTH_SHORT).show(); return true; } }); } }
Markdown
UTF-8
1,890
2.6875
3
[]
no_license
--- layout: gym title: Gym permalink: /gym/ hero-banner: media: video: image: /assets/image/gym-hero.jpg title: In Struggle There's Growth description: cta: text: link: row-banner: image: /assets/image/gym-row.jpg title: Our Gym description: Level Ground Mixed Martial Arts empowers and connects our community through health and fitness. Our 6,500 square foot facility includes a dedicated mat space and weight area. In addition to our classes, we provide Personal Training as well as Private Lessons in Martial Arts, Self-Defense, and Yoga (pricing available upon request.) text-cta-banner: title: 22 or under? Check out our Success Tracks. description: If you are 22 or under, you qualify for free training by joining one of our Success Tracks. Our College Access programs includes tutoring and connection to 2 and 4 year university options. Our Student Trainer program trains you to become a fitness professional, and links you to an internship with a Boston-based gym. cta: text: View Tracks link: /success-tracks lists: - title: Class Schedule bullets: - title: description: "Mondays: 6 pm Mixed Martial Arts" - title: description: "Tuesdays: 5:45 pm Yoga, 7 pm Brazilian Jiu Jitsu" - title: description: "Thursdays: 7 pm Muay Thai + No Gi Jiu Jitsu" footnote: We offer a diverse set of classes suited for Martial Arts and Yoga practitioners of all skill levels. Jiu Jitsu uniforms and all necessary equipment is provided. - title: Pricing bullets: - title: Youth under 22 description: Free (participation in Success Tracks encouraged) - title: Adults description: "Community Membership: $30/month for residents of Dorchester, Roxbury, and Mattapan" footnote: ---
C++
UTF-8
567
3.09375
3
[]
no_license
#ifndef DEQUE_H #define DEQUE_H #include <string> struct deque { struct iterator { }; struct const_iterator { }; deque(); deque(deque const& other); deque& operator=(deque const& other); size_t size() const; bool empty() const; void clear(); std::string& back(); std::string const& back() const; void pop_back(); void pop_front(); void push_back(std::string const& a); void push_front(std::string const& a); std::string& operator[](size_t index); std::string const& operator[](size_t index) const; private: }; #endif // DEQUE_H
TypeScript
UTF-8
678
2.75
3
[]
no_license
import { Action, ActionReducer } from '@ngrx/store'; import { State } from './state'; import { TransferStateAction } from './state-transfer.actions'; export function stateTransferReducer (reducer: ActionReducer<State>): ActionReducer<State> { return function (state: State, action: Action) { if (action.type === TransferStateAction.TYPE) { return transferStateHandler(state, action as TransferStateAction); } return reducer(state, action); }; } function transferStateHandler (currentState: State, action: TransferStateAction): State { const { state } = action; return { ...currentState, ...state }; }
Java
UTF-8
11,045
2.78125
3
[]
no_license
package gameplay; import controllers.ControllerGroup; import controllers.character.VillainController; import helpers.Directions; import helpers.GeneralHelpers; import helpers.TextColors; import models.artefact.Artefact; import models.character.villains.Villain; import models.character.villains.VillainClass; import models.character.villains.VillainNames; import views.console.character.VillainView; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.ThreadLocalRandom; public final class Actions { public static void SelectMove(ControllerGroup controllerGroup, Scanner in, ArrayList<String> errors) { GeneralHelpers.ClearScreen(); errors.forEach(System.out::println); errors.clear(); controllerGroup.heroController.ShowPosition(); controllerGroup.mapController.ShowMap(); controllerGroup.gameStateController.ShowOptions(); String selectMove = in.nextLine(); try { if (((controllerGroup.heroController.GetX() == 1) || (controllerGroup.heroController.GetY() == 1) || (controllerGroup.heroController.GetX() == controllerGroup.mapController.GetDimensions()) || (controllerGroup.heroController.GetY() == controllerGroup.mapController.GetDimensions()))) { WinMap(controllerGroup, in, errors); } else { if (selectMove.matches("w|W|a|A|s|S|d|D")) { int fightChance = ThreadLocalRandom.current().nextInt(1,4); if (fightChance == 1) { Villain villain = new Villain(VillainNames.getRandomVillainName(), VillainClass.getVillainRandomClass(), controllerGroup.heroController.GetHero()); if (controllerGroup.getVillainController() == null) { VillainView villainView = new VillainView(); VillainController villainController = new VillainController (villain, villainView); controllerGroup.setVillainController(villainController); } else { controllerGroup.villainController.NewVillain(villain); } FightOrFlight(controllerGroup, in, errors); } if (selectMove.matches("w|W")) { controllerGroup.heroController.Move(Directions.Up); } else if (selectMove.matches("d|D")) { controllerGroup.heroController.Move(Directions.Right); } else if (selectMove.matches("s|S")) { controllerGroup.heroController.Move(Directions.Down); } else if (selectMove.matches("a|A")) { controllerGroup.heroController.Move(Directions.Left); } } else if (selectMove.matches("x|X")) { controllerGroup.heroController.UpdateHero(); controllerGroup.mapController.UpdateMap(); controllerGroup.gameStateController.UpdateGameState(controllerGroup.heroController.GetHero()); errors.add(TextColors.ANSI_GREEN + "Game saved successfully..." + TextColors.ANSI_RESET); } else if (selectMove.matches("p|P")) { controllerGroup.heroController.ShowHero(); System.out.println(TextColors.ANSI_BLUE + "[B]" + TextColors.ANSI_RESET + "ack | " + TextColors.ANSI_RED + "[Q]" + TextColors.ANSI_RESET + "uit\n"); String option = in.nextLine(); while (!(option.matches("b|B|q|Q"))) { System.out.println(TextColors.ANSI_RED + "\nPlease select a valid option!\n" + TextColors.ANSI_RESET); System.out.println(TextColors.ANSI_BLUE + "[B]" + TextColors.ANSI_RESET + "ack | " + TextColors.ANSI_RED + "[Q]" + TextColors.ANSI_RESET + "uit\n"); option = in.nextLine(); } if (option.matches("b|B")) { SelectMove(controllerGroup, in, errors); } else if (option.matches("q|Q")) { System.exit(0); } } else if (selectMove.matches("q|Q")) { System.exit(0); } else { GeneralHelpers.ClearScreen(); errors.add(TextColors.ANSI_RED + "\nPlease select a valid option!\n" + TextColors.ANSI_RESET); } SelectMove(controllerGroup, in, errors); } } catch (Exception e) { GeneralHelpers.ClearScreen(); errors.add(TextColors.ANSI_RED + "\nPlease select a valid option!\n" + TextColors.ANSI_RESET); SelectMove(controllerGroup, in, errors); } } public static void WinMap(ControllerGroup controllerGroup, Scanner in, ArrayList<String> errors) throws ClassNotFoundException { GeneralHelpers.ClearScreen(); controllerGroup.heroController.ShowMapWin(); int level = controllerGroup.heroController.GetLevel(); controllerGroup.heroController.SetXP((level-1)*5+9-(level%3)); controllerGroup.heroController.LevelCheck(); controllerGroup.mapController.UpdateMapDimensions(((level-1)*5+10-(level%2))); controllerGroup.heroController.ResetPosition(controllerGroup.mapController.GetDimensions()); controllerGroup.heroController.UpdateHero(); controllerGroup.gameStateController.UpdateGameState(controllerGroup.heroController.GetHero()); try { Thread.sleep(1500); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } SelectMove(controllerGroup, in, errors); } public static void FightOrFlight(ControllerGroup controllerGroup, Scanner in, ArrayList<String> errors) { GeneralHelpers.ClearScreen(); controllerGroup.villainController.VillainEncounter(); errors.forEach(System.out::println); errors.clear(); String fightOrFlight = in.nextLine(); try { if (fightOrFlight.matches("f|F")) { boolean win = controllerGroup.gameStateController.Fight(controllerGroup.heroController.GetHero(), controllerGroup.villainController.GetVillain(), "You've chosen to fight!", true); if (!win) { controllerGroup.heroController.SetXP(controllerGroup.villainController.GetXP()); controllerGroup.heroController.LevelCheck(); controllerGroup.gameStateController.UpdateGameState(controllerGroup.heroController.GetHero()); controllerGroup.gameStateController.Lose(); } else { WinArtefact(controllerGroup, in, errors); controllerGroup.heroController.SetXP(controllerGroup.villainController.GetXP()); controllerGroup.heroController.LevelCheck(); controllerGroup.gameStateController.UpdateGameState(controllerGroup.heroController.GetHero()); errors.add(TextColors.ANSI_GREEN + "\nWoo! You won that one... Keep moving." + TextColors.ANSI_RESET); } } else if (fightOrFlight.matches("r|R")) { int runChance = ThreadLocalRandom.current().nextInt(1,3); if (!(runChance == 1)) { GeneralHelpers.ClearScreen(); errors.add(TextColors.ANSI_GREEN + "\nPhew! You got away successfully!" + TextColors.ANSI_RESET); } else { boolean win = controllerGroup.gameStateController.Fight(controllerGroup.heroController.GetHero(), controllerGroup.villainController.GetVillain(), "No running this time...", false); if (!win) { controllerGroup.heroController.SetXP(controllerGroup.villainController.GetXP()); controllerGroup.heroController.LevelCheck(); controllerGroup.gameStateController.UpdateGameState(controllerGroup.heroController.GetHero()); controllerGroup.gameStateController.Lose(); } else { WinArtefact(controllerGroup, in, errors); controllerGroup.heroController.SetXP(controllerGroup.villainController.GetXP()); controllerGroup.heroController.LevelCheck(); controllerGroup.gameStateController.UpdateGameState(controllerGroup.heroController.GetHero()); errors.add(TextColors.ANSI_GREEN + "\nWoo! You won that one... Keep moving." + TextColors.ANSI_RESET); } } } else { GeneralHelpers.ClearScreen(); errors.add(TextColors.ANSI_RED + "\nPlease select a valid option!\n" + TextColors.ANSI_RESET); FightOrFlight(controllerGroup, in, errors); } } catch (NumberFormatException | ClassNotFoundException exception) { GeneralHelpers.ClearScreen(); errors.add(TextColors.ANSI_RED + "\nPlease select a valid option!\n" + TextColors.ANSI_RESET); FightOrFlight(controllerGroup, in, errors); } } public static void WinArtefact(ControllerGroup controllerGroup, Scanner in, ArrayList<String> errors) { GeneralHelpers.ClearScreen(); errors.forEach(System.out::println); errors.clear(); int artefactChance = ThreadLocalRandom.current().nextInt(1,6); if (!(artefactChance == 1)) { try { Artefact artefact = Artefact.getRandomArtefact(); int artefactValue = controllerGroup.gameStateController.GetArtefactValue(artefact, controllerGroup.villainController.GetVillain()); controllerGroup.gameStateController.ShowArtefactValue(artefact, artefactValue); String artefactChoice = in.nextLine(); if (artefactChoice.matches("k|K")) { switch (artefact) { case Armor: controllerGroup.heroController.SetDefense(artefactValue); break; case Helm: controllerGroup.heroController.SetHP(artefactValue); break; case Weapon: controllerGroup.heroController.SetAttack(artefactValue); break; } } else { errors.add(TextColors.ANSI_RED + "Shoulda said KEEP... Better luck next time." + TextColors.ANSI_RESET); } } catch (Exception e) { errors.add(TextColors.ANSI_RED + "Shoulda said KEEP... Better luck next time." + TextColors.ANSI_RESET); } } } }
C
UTF-8
1,331
4.0625
4
[]
no_license
/*Escreva uma especificação de tipos abstratos de dados (TAD) para os números complexos, a + bi, onde abs(a + bi) => sqrt(a^2 + b^2) (a + bi) + (c + di) => (a + c) + (b + d)i (a + bi) * (c + di) => (a * c – b * d) + (a * d + b * c)i –(a + bi) => (-a) + (-b)i. */ #include <stdio.h> #include "numeroComplexo.h" int main(void) { float parte_real, parte_imaginaria; printf("Digite o valor da parte real e imaginaria: "); scanf("%f %f", &parte_real, &parte_imaginaria); TComplexo numero1 = criarNumeroComplexo(parte_real, parte_imaginaria); imprimeComplexo(&numero1); printf("Digite o valor da parte real e imaginaria do segundo numero: "); scanf("%f %f", &parte_real, &parte_imaginaria); TComplexo numero2 = criarNumeroComplexo(parte_real, parte_imaginaria); imprimeComplexo(&numero2); printf("Absoluto\n\n"); printf("O valor absoluto do numero 1: %f\n\n", absComplexo(numero1)); printf("O valor absoluto do numero 2: %f\n\n", absComplexo(numero2)); printf("Soma\n\n"); TComplexo numero3 = soma(numero1, numero2); imprimeComplexo(&numero3); printf("Multiplicação\n\n"); numero3 = multiplicacao(numero1, numero2); imprimeComplexo(&numero3); printf("Negacao\n\n"); numero3 = negacao(numero1); imprimeComplexo(&numero3); return 0; }