language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
537
2.828125
3
[ "MIT" ]
permissive
package authoringenvironment.view; import javafx.scene.control.Alert; /** * Generates and shows an Alert with an error message * * @author Stephen * */ public class AlertGenerator extends Alert { /** * Generates an Alert of the type ERROR */ public AlertGenerator() { super(AlertType.ERROR); } /** * Sets the Alert's text and displays the Alert * @param errorMessage: error message to be displayed */ public void generateAlert(String errorMessage) { this.setContentText(errorMessage); this.show(); } }
Python
UTF-8
1,598
3.5
4
[]
no_license
import pandas as pd import numpy as np import math def prepare_data(data_df, train_test_split, *args): ''' Randomly splits the data according to the given `train_test_split` (0.2 means 80/20 train/test split). Only pandas DataFrames or numpy arrays may be provided in *args -- the same random split is applied to these as `data_df` ''' num_samples = data_df.shape[0] train_size, test_size = calculate_train_test_split( num_samples, ratio=train_test_split) train_indices, test_indices = random_split_indices( num_samples, train_size) train_df = data_df.loc[train_indices].reset_index(drop=True) test_df = data_df.loc[test_indices].reset_index(drop=True) split_args = [train_df, test_df] for arr in args: split_args.append(arr[train_indices]) split_args.append(arr[test_indices]) return split_args def calculate_train_test_split(num_samples, ratio=0.2): ''' Given the number of samples and the train/test split, this function will return the size of the training and testing datasets. ''' train_size = math.ceil(num_samples * (1 - ratio)) test_size = math.floor(num_samples * ratio) return train_size, test_size def random_split_indices(num_samples, train_size): ''' Given a data size and the size of the training data, this function will return two lists of indices, one for training data and one for testing/validation data ''' indices = np.arange(num_samples) np.random.shuffle(indices) return np.split(indices, [train_size])
Java
UHC
704
2.90625
3
[]
no_license
package tutorial11; import java.awt.*; import java.awt.event.*; import javax.swing.*; class MyFrame extends JFrame { // implements ActionListener JButton btn =new JButton("ݱ"); public MyFrame(){ setTitle("ڹ "); setSize(300,200); setLayout(new FlowLayout()); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); this.add(btn); this.setResizable(false); this.setVisible(true); } // @Override // public void actionPerformed(ActionEvent e) { // System.exit(0); // // } } public class Exam_07 { public static void main(String[] ar){ MyFrame f=new MyFrame(); } }
Java
UTF-8
4,181
2.078125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.faceid.v20180301.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class GenerateReflectSequenceRequest extends AbstractModel{ /** * The resource URL of the data package generated by the SDK. */ @SerializedName("DeviceDataUrl") @Expose private String DeviceDataUrl; /** * The MD5 hash value of the data package generated by the SDK. */ @SerializedName("DeviceDataMd5") @Expose private String DeviceDataMd5; /** * 1 - silent 2 - blinking 3 - light 4 - blinking + light (default) */ @SerializedName("SecurityLevel") @Expose private String SecurityLevel; /** * Get The resource URL of the data package generated by the SDK. * @return DeviceDataUrl The resource URL of the data package generated by the SDK. */ public String getDeviceDataUrl() { return this.DeviceDataUrl; } /** * Set The resource URL of the data package generated by the SDK. * @param DeviceDataUrl The resource URL of the data package generated by the SDK. */ public void setDeviceDataUrl(String DeviceDataUrl) { this.DeviceDataUrl = DeviceDataUrl; } /** * Get The MD5 hash value of the data package generated by the SDK. * @return DeviceDataMd5 The MD5 hash value of the data package generated by the SDK. */ public String getDeviceDataMd5() { return this.DeviceDataMd5; } /** * Set The MD5 hash value of the data package generated by the SDK. * @param DeviceDataMd5 The MD5 hash value of the data package generated by the SDK. */ public void setDeviceDataMd5(String DeviceDataMd5) { this.DeviceDataMd5 = DeviceDataMd5; } /** * Get 1 - silent 2 - blinking 3 - light 4 - blinking + light (default) * @return SecurityLevel 1 - silent 2 - blinking 3 - light 4 - blinking + light (default) */ public String getSecurityLevel() { return this.SecurityLevel; } /** * Set 1 - silent 2 - blinking 3 - light 4 - blinking + light (default) * @param SecurityLevel 1 - silent 2 - blinking 3 - light 4 - blinking + light (default) */ public void setSecurityLevel(String SecurityLevel) { this.SecurityLevel = SecurityLevel; } public GenerateReflectSequenceRequest() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public GenerateReflectSequenceRequest(GenerateReflectSequenceRequest source) { if (source.DeviceDataUrl != null) { this.DeviceDataUrl = new String(source.DeviceDataUrl); } if (source.DeviceDataMd5 != null) { this.DeviceDataMd5 = new String(source.DeviceDataMd5); } if (source.SecurityLevel != null) { this.SecurityLevel = new String(source.SecurityLevel); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "DeviceDataUrl", this.DeviceDataUrl); this.setParamSimple(map, prefix + "DeviceDataMd5", this.DeviceDataMd5); this.setParamSimple(map, prefix + "SecurityLevel", this.SecurityLevel); } }
Python
UTF-8
4,911
3.296875
3
[]
no_license
from discord.ext import commands import pandas as pd class RPSgame(commands.Cog): """ This Cog adds rock-paper-scissors game """ def __init__(self, client): """ Client - bot Anbu rps_data - matrix with players data kind of: 1st_player's_name R/P/S 2nd_player's_name R/P/S """ self.client = client self.rps_data = [] @commands.command(name='rps') async def playrps(self, context, *args): """ This func is called then someone want to play or manage his scores players append in rps_data Then there is 2 players match begins. It gets result and after that write result in RPSscores.csv and return them to the bot if arg == 'scores', it will return player scores if arg == 'resetscores', it will reset player scores scores have a look as: wins:draws:losses """ if len(self.rps_data) < 2 and len(args) == 1: if args[0].upper() in ["R", "P", "S", "||R||", "||P||", "||S||"]: await context.channel.delete_messages([context.message]) self.rps_data.append((context.author, args[0])) else: if args[0].upper() == "RESETSCORES": self.reset_score(context.author) elif args[0].upper() == "SCORES": await context.channel.send(self.get_score(context.author)) else: await context.channel.send('Wrong format') if len(self.rps_data) == 2: result = self.get_result() if result == "Draw": await context.channel.send("It's a Draw!" " for {} and {}".format(self.rps_data[0][0].display_name, self.rps_data[1][0].display_name)) elif result == "First": await context.channel.send(self.rps_data[0][0].display_name + " won!") else: await context.channel.send(self.rps_data[1][0].display_name + " won!") self.rps_data.clear() def get_result(self): """ This func checks who win """ x = self.rps_data[0][1].upper() y = self.rps_data[1][1].upper() if x[0] == '|': x = x[2:3] if y[0] == '|': y = y[2:3] if x == y: self.write_scores("Draw") return "Draw" elif (x == 'R' and y == 'S') or (x == 'S' and y == 'P') or (x == 'P' and y == 'R'): self.write_scores("First") return "First" else: self.write_scores("Second") return "Second" def write_scores(self, result): """ This func write scores in RPSscores.csv """ df = pd.read_csv('RPSscores.csv') for i in range(2): if not str(self.rps_data[i][0]) in df['Name'].to_dict().values(): df.loc[len(df.index)] = [str(self.rps_data[i][0]), 0, 0, 0] first_player_index = int(df.loc[df['Name'] == str(self.rps_data[0][0])].index[0]) second_player_index = int(df.loc[df['Name'] == str(self.rps_data[1][0])].index[0]) if result == 'Draw': df.iloc[first_player_index, 2] += 1 df.iloc[second_player_index, 2] += 1 if result == 'First': df.iloc[first_player_index, 1] += 1 df.iloc[second_player_index, 3] += 1 if result == 'Second': df.iloc[first_player_index, 3] += 1 df.iloc[second_player_index, 1] += 1 df.to_csv('RPSscores.csv', index=False) def reset_score(self, player): """ This func set players score to 0;0;0 """ player = str(player) df = pd.read_csv('RPSscores.csv') if not str(player) in df['Name'].to_dict().values(): df.loc[len(df.index)] = [str(player), 0, 0, 0] player_index = int(df.loc[df['Name'] == player].index[0]) df.iloc[player_index, 1] = 0 df.iloc[player_index, 2] = 0 df.iloc[player_index, 3] = 0 df.to_csv('RPSscores.csv', index=False) def get_score(self, player): """ This func get players score """ df = pd.read_csv('RPSscores.csv') if not str(player) in df['Name'].to_dict().values(): df.loc[len(df.index)] = [str(player), 0, 0, 0] player_index = int(df.loc[df['Name'] == str(player)].index[0]) result = 'wins: ' + str(df.iloc[player_index, 1]) + '\n' + \ 'draws: ' + str(df.iloc[player_index, 2]) + '\n' + \ 'losses: ' + str(df.iloc[player_index, 3]) return result
JavaScript
UTF-8
344
3.328125
3
[]
no_license
// Now the worker is effectively the global scope. // Thus worker.onmessage can be used as onmessage onmessage = function(e) { console.log('Message received from main script: '); console.log(e); var workerResult = 'Result: ' + (e.data[0] * e.data[1]); console.log('Posting message back to main script'); postMessage(workerResult); };
Markdown
UTF-8
955
3.015625
3
[]
no_license
# MultithreadingSynchronization This is a solution to a interesting synchonization problem, intend to demo Multi-threading and Synchronization. Problem: A group of surfers decide to spend an entire day surfing in the Beach. The surfers show up at random times during the day and come in and out of the water at random times. A local fisherman warns the surfers that there are sharks in the water, and advices them to never go in the water alone. These sharks are not naturally aggressive and will stay away if they see a group of surfers. However, if they see just one surfer alone they may get confused thinking that the surfboard is actually a big fish and attack the lonely surfer. Thus, to avoids shark attacks, the program have to make sure that no surfer is ever left alone in the water Yet, all surfers must surf, (nostarvation), and all surfers must leave (no deadlock). At dusk, no more surfers come and all surfers still at the beach leave.
C
UTF-8
205
2.640625
3
[]
no_license
#include <stdlib.h> #include "libft.h" void *ft_memalloc(size_t size) { void *dst; (if !(dst = (size_t)malloc(sizeof(size_t) * size) + 1)) return (NULL); ft_memset(dst, 0, size); return (dst); }
C#
UTF-8
7,882
2.90625
3
[]
no_license
#region 文件描述 /****************************************************************************** * 创建: Daoting * 摘要: * 日志: 2014-07-01 创建 ******************************************************************************/ #endregion #region 引用命名 using System; using System.Globalization; using System.Runtime.InteropServices; #endregion namespace Dt.Xls { /// <summary> /// Represents an ARGB (alpha, red, green, blue) color. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct GcColor { private GcARGBColor _gcARGBColor; /// <summary> /// The alpha component value of this Dt.Xls.GcColor /// </summary> public byte A { get { return this._gcARGBColor.a; } } /// <summary> /// The red component value of this Dt.Xls.GcColor /// </summary> public byte R { get { return this._gcARGBColor.r; } } /// <summary> /// The green component value of this Dt.Xls.GcColor /// </summary> public byte G { get { return this._gcARGBColor.g; } } /// <summary> /// The blue component value of this Dt.Xls.GcColor /// </summary> public byte B { get { return this._gcARGBColor.b; } } /// <summary> /// Create a Dt.Xls.GcColor structure from the specified 8-bit color values (red,green and blue) /// The alpha value is implicitly 255 (fully opaque).Although this method allows a 32-bit value to be passed for each color component, /// the value of each component is limited to 8 bits. /// </summary> /// <param name="red">The red component value for the new Dt.Xls.GcColor Valid values are 0 through 255</param> /// <param name="green">The green component value for the new Dt.Xls.GcColor Valid values are 0 through 255</param> /// <param name="blue">The blue component value for the new Dt.Xls.GcColor Valid values are 0 through 255</param> /// <returns>The Dt.Xls.GcColor that this method creates.</returns> public static GcColor FromArgb(int red, int green, int blue) { return FromArgb(0xff, red, green, blue); } /// <summary> /// Create a Dt.Xls.GcColor structure from the specified 8-bit color values (red,green and blue) /// Although this method allows a 32-bit value to be passed for each color component, /// the value of each component is limited to 8 bits. /// </summary> /// <param name="alpha">The alpha component value for the new Dt.Xls.GcColor Valid values are 0 through 255</param> /// <param name="red">The red component value for the new Dt.Xls.GcColor Valid values are 0 through 255</param> /// <param name="green">The green component value for the new Dt.Xls.GcColor Valid values are 0 through 255</param> /// <param name="blue">The blue component value for the new Dt.Xls.GcColor Valid values are 0 through 255</param> /// <returns> /// The Dt.Xls.GcColor that this method creates. /// </returns> public static GcColor FromArgb(int alpha, int red, int green, int blue) { GcColor color = new GcColor(); color._gcARGBColor.a = (byte) alpha; color._gcARGBColor.r = (byte) red; color._gcARGBColor.g = (byte) green; color._gcARGBColor.b = (byte) blue; return color; } /// <summary> /// Gets the 32-bit ARGB value of this structure. /// </summary> /// <returns> The 32-bit ARGB value of this Dt.Xls.GcColor</returns> public uint ToArgb() { return uint.Parse(((byte) this.A).ToString("X2") + ((byte) this.R).ToString("X2") + ((byte) this.G).ToString("X2") + ((byte) this.B).ToString("X2"), (NumberStyles) NumberStyles.HexNumber, (IFormatProvider) CultureInfo.InvariantCulture); } /// <summary> /// Compares two Dt.Xls.GcColors for exact equality. /// </summary> /// <param name="color1"> The first Dt.Xls.GcColors to compare.</param> /// <param name="color2"> The second Dt.Xls.GcColors to compare.</param> /// <returns>true if the Dt.Xls.GcColors have the same ARGB value; otherwise, false.</returns> public static bool operator ==(GcColor color1, GcColor color2) { return ((((color1.A == color2.A) && (color1.R == color2.R)) && (color1.G == color2.G)) && (color1.B == color2.B)); } /// <summary> /// Compares two Dt.Xls.GcColors for exact inequality. /// </summary> /// <param name="color1"> The first Dt.Xls.GcColors to compare.</param> /// <param name="color2"> The second Dt.Xls.GcColors to compare.</param> /// <returns>true if the two Dt.Xls.GcColors have the different ARGB value; otherwise, false.</returns> public static bool operator !=(GcColor color1, GcColor color2) { return !(color1 == color2); } /// <summary> /// Indicates whether the specified Dt.Xls.GcColors are equal. /// </summary> /// <param name="color1"> The first Dt.Xls.GcColors to compare.</param> /// <param name="color2"> The second Dt.Xls.GcColors to compare.</param> /// <returns>true if the Dt.Xls.GcColor have the sameARGB value; otherwise, false.</returns> public static bool Equals(GcColor color1, GcColor color2) { return (color1 == color2); } /// <summary> /// Indicates whether the specified Dt.Xls.GcColor is equal to the current Dt.Xls.GcColor. /// </summary> /// <param name="o"> The object to compare to the current Dt.Xls.GcColor..</param> /// <returns>true if the Dt.Xls.GcColor have the same ARGB value; otherwise, false.</returns> public override bool Equals(object o) { if ((o == null) || !(o is GcColor)) { return false; } GcColor color = (GcColor) o; return Equals(this, color); } /// <summary> /// Indicates whether the specified Dt.Xls.GcColor is equal to the current Dt.Xls.GcColor. /// </summary> /// <param name="value"> The Dt.Xls.GcColor to compare to the current rectangle.</param> /// <returns>true if the Dt.Xls.GcColors have the same ARGB value; otherwise, false.</returns> public bool Equals(GcColor value) { return Equals(this, value); } /// <summary> /// Returns a hash code for this Dt.Xls.GcColor structure. /// </summary> /// <returns> An integer value that specifies the hash code for this Dt.Xls.GcColor structure</returns> public override int GetHashCode() { return ((uint) this.ToArgb()).GetHashCode(); } /// <summary> /// Convert this Dt.Xls.GcColor to a human-readable string /// </summary> /// <returns> A string that consists of the ARGB component names and their values.</returns> public override string ToString() { return (((byte) this.A).ToString("X2") + ((byte) this.R).ToString("X2") + ((byte) this.G).ToString("X2") + ((byte) this.B).ToString("X2")); } internal static GcColor FromArgb(uint argb) { GcColor color = new GcColor(); color._gcARGBColor.a = (byte) ((argb >> 0x18) & 0xff); color._gcARGBColor.r = (byte) ((argb >> 0x10) & 0xff); color._gcARGBColor.g = (byte) ((argb >> 8) & 0xff); color._gcARGBColor.b = (byte) (argb & 0xff); return color; } } }
Python
UTF-8
639
3.1875
3
[ "MIT" ]
permissive
from itertools import product import sys MAPPING_DICT = { '0' : '0', '1' : '1', '2' : 'abc', '3' : 'def', '4' : 'ghi', '5' : 'jkl', '6' : 'mno', '7' : 'pqrs', '8' : 'tuv', '9' : 'wxyz', } def main(filepath): with open(filepath, 'r') as f: for line in f.readlines(): if line: line = line.strip() lists = [list(MAPPING_DICT[x]) for x in line] word_lists = list(product(*lists)) print ','.join([''.join(x) for x in word_lists]) if __name__ == '__main__': main(sys.argv[1])
C#
UTF-8
882
2.765625
3
[ "MIT" ]
permissive
using BassClefStudio.GameModel.Graphics; using BassClefStudio.GameModel.Geometry.Transforms; using System; using System.Collections.Generic; using System.Text; namespace BassClefStudio.GameModel.Graphics.Commands { /// <summary> /// Represents any command sent to be drawn on an <see cref="IGraphicsSurface"/> surface. /// </summary> public interface IGraphicsCommand { /// <summary> /// Applies the given <see cref="ITransform"/> to this graphics command and returns the result. /// </summary> /// <param name="transform">The <see cref="ITransform"/> transform to apply to the components of this <see cref="IGraphicsCommand"/>.</param> /// <returns>A new <see cref="IGraphicsCommand"/> representing the (transformed) resulting command.</returns> IGraphicsCommand ApplyTransform(ITransform transform); } }
JavaScript
UTF-8
12,080
2.875
3
[ "MIT" ]
permissive
/* * Moon 0.1.0 * Copyright 2016, Kabir Shah * https://github.com/KingPixil/moon/ * Free to use under the MIT license. * https://kingpixil.github.io/license */ "use strict"; (function(window) { var config = { silent: false } var directives = {}; var components = {}; /** * Converts attributes into key-value pairs * @param {Node} node * @return {Object} Key-Value pairs of Attributes */ var extractAttrs = function(node) { var attrs = {}; if(!node.attributes) return attrs; var rawAttrs = node.attributes; for(var i = 0; i < rawAttrs.length; i++) { attrs[rawAttrs[i].name] = rawAttrs[i].value } return attrs; } /** * Compiles a template with given data * @param {String} template * @param {Object} data * @return {String} Template with data rendered */ var compileTemplate = function(template, data) { var code = template, re = /{{([A-Za-z0-9_.\[\]]+)}}/gi; code.replace(re, function(match, p) { code = code.replace(match, "` + data." + p + " + `"); }); var compile = new Function("data", "var out = `" + code + "`; return out"); var output = compile(data); return output; } /** * Gets Root Element * @param {String} html * @return {Node} Root Element */ var getRootElement = function(html) { var dummy = document.createElement('div'); dummy.innerHTML = html; return dummy.firstChild; } /** * Merges two Objects * @param {Object} obj * @param {Object} obj2 * @return {Object} Merged Objects */ function merge(obj, obj2) { for (var key in obj2) { if (obj2.hasOwnProperty(key)) obj[key] = obj2[key]; } return obj; } function Moon(opts) { var _el = opts.el; var _data = opts.data; var _methods = opts.methods; var _hooks = opts.hooks || {created: function() {}, mounted: function() {}, updated: function() {}, destroyed: function() {}}; var _destroyed = false; var self = this; this.$el = document.querySelector(_el); this.$components = merge(opts.components || {}, components); this.$dom = {type: this.$el.nodeName, children: [], node: this.$el}; // Change state when $data is changed Object.defineProperty(this, '$data', { get: function() { return _data; }, set: function(value) { _data = value; this.build(this.$dom.children); }, configurable: true }); /** * Logs a Message * @param {String} msg */ this.log = function(msg) { if(!config.silent) console.log(msg); } /** * Throws an Error * @param {String} msg */ this.error = function(msg) { console.log("Moon ERR: " + msg); } /** * Creates an object to be used in a Virtual DOM * @param {String} type * @param {Array} children * @param {String} val * @param {Object} props * @param {Node} node * @return {Object} Object usable in Virtual DOM */ this.createElement = function(type, children, val, props, node) { return {type: type, children: children, val: val, props: props, node: node}; } /** * Create Elements Recursively For all Children * @param {Array} children * @return {Array} Array of elements usable in Virtual DOM */ this.recursiveChildren = function(children) { var recursiveChildrenArr = []; for(var i = 0; i < children.length; i++) { var child = children[i]; recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child)); } return recursiveChildrenArr; } /** * Creates Virtual DOM * @param {Node} node */ this.createVirtualDOM = function(node) { var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node); this.$dom = vdom; } /** * Turns Custom Components into their Corresponding Templates */ this.componentsToHTML = function() { for(var component in this.$components) { var componentsFound = document.getElementsByTagName(component); componentsFound = Array.prototype.slice.call(componentsFound); for(var i = 0; i < componentsFound.length; i++) { var componentFound = componentsFound[i]; var componentProps = extractAttrs(componentFound); var componentDummy = getRootElement(this.$components[component].template); for(var attr in componentProps) { componentDummy.setAttribute(attr, componentProps[attr]); } componentFound.outerHTML = componentDummy.outerHTML; } } } /** * Sets Value in Data * @param {String} key * @param {String} val */ this.set = function(key, val) { this.$data[key] = val; if(!_destroyed) this.build(this.$dom.children); if(_hooks.updated) { _hooks.updated(); } } /** * Gets Value in Data * @param {String} key * @return {String} Value of key in data */ this.get = function(key) { return this.$data[key]; } /** * Makes an AJAX Request * @param {String} method * @param {String} url * @param {Object} params * @param {Function} cb */ this.ajax = function(method, url, params, cb) { var xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); if(typeof params === "function") { cb = params; } var urlParams = "?"; if(method === "POST") { http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); for(var param in params) { urlParams += param + "=" + params[param] + "&"; } } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) cb(JSON.parse(xmlHttp.responseText)); } xmlHttp.open(method, url, true); xmlHttp.send(method === "POST" ? urlParams : null); } /** * Calls a method * @param {String} method */ this.method = function(method) { _methods[method](); } this.destroy = function() { Object.defineProperty(this, '$data', { set: function(value) { _data = value; } }); _destroyed = true; if(_hooks.destroyed) _hooks.destroyed(); } // Default Directives directives["m-if"] = function(el, val, vdom) { var evaluated = new Function("return " + val); if(!evaluated()) { el.textContent = ""; } else { el.textContent = compileTemplate(vdom.val, self.$data); } } directives["m-show"] = function(el, val, vdom) { var evaluated = new Function("return " + val); if(!evaluated()) { el.style.display = ''; } else { el.style.display = 'block'; } } directives["m-on"] = function(el, val, vdom) { var splitVal = val.split(":"); var eventToCall = splitVal[0]; var methodToCall = splitVal[1]; el.addEventListener(eventToCall, function() { self.method(methodToCall); }); el.removeAttribute("m-on"); delete vdom.props["m-on"]; } directives["m-model"] = function(el, val, vdom) { el.value = self.get(val); el.addEventListener("input", function() { self.set(val, el.value); }); el.removeAttribute("m-model"); delete vdom.props["m-model"]; } directives["m-once"] = function(el, val, vdom) { vdom.val = el.textContent; for(var child in vdom.children) { vdom.children[child].val = compileTemplate(vdom.children[child].val, self.$data); } } directives["m-text"] = function(el, val, vdom) { el.textContent = val; } directives["m-html"] = function(el, val, vdom) { el.innerHTML = val; } directives["m-mask"] = function(el, val, vdom) { } // directives["m-for"] = function(el, val, vdom) { // var splitVal = val.split(" in "); // var alias = splitVal[0]; // var arr = self.get(splitVal[1]); // var clone = el.cloneNode(true); // var oldVal = vdom.val; // var compilable = vdom.val.replace(new RegExp(alias, "gi"), splitVal[1] + '[0]'); // el.innerHTML = compileTemplate(compilable, self.$data); // for(var i = 1; i < arr.length; i++) { // var newClone = clone.cloneNode(true); // var compilable = oldVal.replace(new RegExp(alias, "gi"), splitVal[1] + '[' + i + ']'); // newClone.innerHTML = compileTemplate(compilable, self.$data); // var parent = el.parentNode; // parent.appendChild(newClone); // } // vdom.val = el.textContent; // delete vdom.props["m-for"]; // } /** * Builds the DOM With Data * @param {Array} children */ this.build = function(children) { for(var i = 0; i < children.length; i++) { var el = children[i]; if(el.type === "#text") { el.node.textContent = compileTemplate(el.val, this.$data); } else if(el.props) { for(var prop in el.props) { var propVal = el.props[prop]; var compiledProperty = compileTemplate(propVal, this.$data); var directive = directives[prop]; if(directive) { el.node.removeAttribute(prop); directive(el.node, compiledProperty, el); } if(!directive) el.node.setAttribute(prop, compiledProperty); } } this.build(el.children); } } /** * Initializes Moon */ this.init = function() { this.log("======= Moon ======="); if(_hooks.created) { _hooks.created(); } this.componentsToHTML(); this.createVirtualDOM(this.$el); if(_hooks.mounted) { _hooks.mounted(); } this.build(this.$dom.children); } // Initialize 🎉 this.init(); } /** * Sets the Configuration of Moon * @param {Object} opts */ Moon.config = function(opts) { if(opts.silent) { config.silent = opts.silent; } } /** * Runs an external Plugin * @param {Object} plugin */ Moon.use = function(plugin) { plugin.init(Moon); } /** * Creates a Directive * @param {String} name * @param {Function} action */ Moon.directive = function(name, action) { directives["m-" + name] = action; } /** * Creates a Component * @param {String} name * @param {Function} action */ Moon.component = function(name, action) { components[name] = action; } window.Moon = Moon; window.$ = function(el) { el = document.querySelectorAll(el); return el.length === 1 ? el[0] : el; } })(window);
Java
UTF-8
3,184
1.859375
2
[]
no_license
package com.solution.p2p.core.user.dao; import java.util.List; import com.solution.p2p.core.common.entity.SysOrganization; import com.solution.p2p.core.common.entity.SysOrganizationExample; import org.apache.ibatis.annotations.Param; public interface SysOrganizationMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int countByExample(SysOrganizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int deleteByExample(SysOrganizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int deleteByPrimaryKey(Long id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int insert(SysOrganization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int insertSelective(SysOrganization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ List<SysOrganization> selectByExample(SysOrganizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ SysOrganization selectByPrimaryKey(Long id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int updateByExampleSelective(@Param("record") SysOrganization record, @Param("example") SysOrganizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int updateByExample(@Param("record") SysOrganization record, @Param("example") SysOrganizationExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int updateByPrimaryKeySelective(SysOrganization record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table sys_organization * * @mbggenerated Sun Oct 05 15:15:24 CST 2014 */ int updateByPrimaryKey(SysOrganization record); }
Python
UTF-8
215
3.890625
4
[]
no_license
def main(): n = int(input('Digite a quantidade de termos da sequência triangular: ')) atual = 0 for c in range(1, n+1): atual += c print(f'{atual}', end=' -> ') print('FIM') main()
C#
UTF-8
1,656
2.828125
3
[]
no_license
//PURPOSE: Build an application for generating quotes for car insurance //AUTHOR: Robert Manez using CarInsuranceQuote.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CarInsuranceQuote.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] //passing in user input values public ActionResult Estimate(string firstName, string lastName, string email, DateTime birthday, int carYear, string carMake, string carModel, string dui, int speedingTickets, string coverage) { //accessing database using (CarInsuranceEntities1 db = new CarInsuranceEntities1()) { //instantiating a class object and assigning it properties based on user input var customer = new Customer(); customer.FirstName = firstName; customer.LastName = lastName; customer.Email = email; customer.Birthday = birthday; customer.CarYear = carYear; customer.CarMake = carMake; customer.CarModel = carModel; customer.DUI = dui; customer.SpeedingTickets = speedingTickets; customer.Coverage = coverage; //adding and saving new class object to database db.Customers.Add(customer); db.SaveChanges(); } return View("Estimate"); } } }
C++
UTF-8
1,113
2.890625
3
[]
no_license
#include "lista.h" Lista::Lista() { longiLista = 0; inicio = NULL; } Archivo * Lista::agregar(Archivo *arch){ if(longiLista == 0){ inicio = arch; longiLista++; return arch; } else{ Archivo * temp = inicio; for(int a = 0; a<longiLista; a++){ if(temp == NULL){ temp = arch; temp->ant = arch->ant; longiLista++; return arch;; } temp = temp->sig; } } return NULL; } void Lista::eliminar(Archivo * arch){ Archivo * temp = this->inicio; for(int a = 0; a<longiLista; a++){ if(temp->nombre == arch->nombre){ while(temp->sig !=NULL){ temp->sig->ant = temp->ant; temp->ant->sig = temp->sig; } longiLista--; } temp = temp->sig; } } /*Archivo* Lista::buscar(string ruta){ Archivo * temp = inicio; for(int a = 0; a<longiLista; a++){ if(temp->nombre.find(ruta)) return temp; temp = temp->sig; } }*/
C
UTF-8
4,246
2.984375
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> int type; int n; int **neighbors; int *degree; int *included; int *excluded; // int *status; long long unsigned int n_connected; long long unsigned int n_connected_u; long long unsigned int n_connected_d; long long unsigned int n_connected_b; // returns true iff node i is a neighbor of an included node int in_fringe(int i) { for (int j = 0; j < degree[i]; ++j) { if (included[neighbors[i][j]]) return 1; } return 0; } // counts the connected sets in the interval specified by 'included' and 'excluded' void count_type_i_interval() { int exc[n], en = 0; // list of vertices exluded in this call n_connected++; // count the set 'included' // recurse on sets obtained by adding a neighbor of 'included' for (int i = 1; i < n; i++) { // skip if already included or excluded if (included[i] || excluded[i]) continue; // skip if not a neighbor of any included vertex if (!in_fringe(i)) continue; // otherwise included[i] = 1; // include and recurse count_type_i_interval(); included[i] = 0; // exclude for the following calls excluded[i] = 1; exc[en++] = i; // remember that i was excluded in this call } // remove 'excluded' status of all those excluded in this call for (int i = 0; i < en; i++) excluded[exc[i]] = 0; } // counts the number of connected sets in a gadget of type I void count_type_i() { for (int i = 0; i < n; ++i) { included[i] = 0; excluded[i] = 0; } included[0] = 1; // always include the join vertex n_connected = 0; count_type_i_interval(); printf("%llu\n", n_connected); } // this is similar to count_type_i_interval, but now the status of the vertices 0 and 1 is fixed, // and we count separately the combinations of vertices 2 and 3 void count_type_ii_interval() { int exc[n], en = 0; // list of vertices exluded in this call // increment the appropriate counter if (included[2]) { if (included[3]) { ++n_connected_b; } else { ++n_connected_u; } } else if (included[3]) { ++n_connected_d; } // recurse on sets obtained by adding a neighbor of 'included' for (int i = 2; i < n; i++) { // skip if already included or excluded if (included[i] || excluded[i]) continue; // skip if not a neighbor of any included vertex if (!in_fringe(i)) continue; // otherwise included[i] = 1; // include and recurse count_type_ii_interval(); included[i] = 0; // exclude for the following calls excluded[i] = 1; exc[en++] = i; // remember that i was excluded in this call } // remove 'excluded' status of all those excluded in this call for (int i = 0; i < en; i++) excluded[exc[i]] = 0; } void count_type_ii_uv(int u, int v) { // TODO: could be replaced by a single array for (int i = 0; i < n; ++i) { included[i] = 0; excluded[i] = 0; } included[0] = u; included[1] = v; n_connected_u = 0; n_connected_d = 0; n_connected_b = 0; count_type_ii_interval(); printf("%llu\n", n_connected_b); printf("%llu\n", n_connected_u); printf("%llu\n", n_connected_d); } void count_type_ii() { count_type_ii_uv(1, 1); // count sets with both vertices u and v count_type_ii_uv(1, 0); // count sets with with only u count_type_ii_uv(0, 1); // count sets with with only v } int main(int argc, char **argv) { // check that type and n are given and each edge has two vertices assert(argc >= 3); assert(argc % 2 == 1); // read gadget type if (!strcmp(argv[1], "I")) { type = 1; } else if (!strcmp(argv[1], "II")) { type = 2; } else { exit(1); } // read n n = atoi(argv[2]); neighbors = malloc(n * sizeof(int*)); degree = malloc(n * sizeof(int)); included = malloc(n * sizeof(int)); excluded = malloc(n * sizeof(int)); // status = malloc(n * sizeof(int)); for (int i = 0; i < n; ++i) { neighbors[i] = malloc(n * sizeof(int)); degree[i] = 0; } // read the edges for (int i = 3; i < argc; i+=2) { int u = atoi(*(argv+i)); int v = atoi(*(argv+i+1)); neighbors[u][degree[u]] = v; neighbors[v][degree[v]] = u; ++degree[u]; ++degree[v]; } if (type == 1) { count_type_i(); } else if (type == 2) { count_type_ii(); } return 0; }
JavaScript
UTF-8
670
2.65625
3
[]
no_license
"use strict"; $( document ).ready(function () { //create tabs using jquery-ui $(function() { $( "#tabs" ).tabs(); }); $("#button").click(function( event ) { var htmlContent = $("#htmlCode textarea").val(); var cssContent = $("#cssCode textarea").val(); var jsContent = $("#jsCode textarea").val(); //inject the content to iframe: injectCodeToIframe(htmlContent, cssContent, jsContent);; }); function injectCodeToIframe(htmlCode, cssCode, jsCode) { var cssStyle = '<style>' + cssCode + '</style>'; $("#resultCode").contents().find('html').html(cssStyle + htmlCode); document.getElementById('resultCode').contentWindow.eval(jsCode); } });
Java
UTF-8
1,976
2.8125
3
[]
no_license
package com.quiz.game.entity; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import lombok.*; import org.apache.commons.lang3.StringUtils; import java.util.Map; import java.util.UUID; @Getter @ToString @NoArgsConstructor public class Question { private String questionId; private String question; private Map<String, Map<Answer, Integer>> answersToPoints; public Question(String question, Map<Answer, Integer> answersToPoints) { validate(answersToPoints, question); this.questionId = UUID.randomUUID().toString(); this.question = question; initAnswerToPoints(answersToPoints); } private void initAnswerToPoints(Map<Answer, Integer> answersToPointsInput) { this.answersToPoints = Maps.newHashMap(); answersToPointsInput.keySet().forEach(answer -> { ImmutableMap<Answer, Integer> map = ImmutableMap.of(answer, answersToPointsInput.get(answer)); String answerId = answer.getAnswerId(); this.answersToPoints.put(answerId, map); }); } private void validate(Map<Answer, Integer> answersToPoints, String question) { validateAnswers(answersToPoints); validateQuestion(question); } private void validateQuestion(String question) { if (StringUtils.isEmpty(question)) throw new RuntimeException("Question is mandatory "); } private void validateAnswers(Map<Answer, Integer> answersToPoints) { if (answersToPoints == null || answersToPoints.isEmpty()) throw new RuntimeException("Answers list null or empty "); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Question)) return false; Question question = (Question) o; return questionId.equals(question.questionId); } @Override public int hashCode() { return questionId.hashCode(); } }
Java
UTF-8
488
2.59375
3
[]
no_license
public class Nomes { static int lChegada = 100; public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println(t.getName()); Grilos grilo1 = new Grilos("Carlos", lChegada); Grilos grilo2 = new Grilos("joão", lChegada); Grilos grilo3 = new Grilos("Augusto", lChegada); Grilos grilo4 = new Grilos("Matheus", lChegada); Grilos grilo5 = new Grilos("Lucas", lChegada); } }
Java
UTF-8
1,553
2.296875
2
[]
no_license
package com.begear.controller.restcontroller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.begear.dao.DaoH; import com.begear.model.StudenteH; @RestController @RequestMapping("/rest/studenti") public class StudentRestController { @Autowired DaoH dao; @RequestMapping(method = RequestMethod.POST) public void insertStudente(@RequestBody StudenteH s) { dao.insertStudente(s); } @RequestMapping(value="/studente/{matricola}", method=RequestMethod.DELETE) public void deleteStudente(@PathVariable int matricola) { StudenteH s = new StudenteH(); s.setMatricola(matricola); dao.deleteStudente(s); } @RequestMapping(method = RequestMethod.PUT) public void updateStudente(@RequestBody StudenteH s) { dao.updateStudente(s); } @RequestMapping(value="/studente/{matricola}", method=RequestMethod.GET) public @ResponseBody StudenteH getStudente(@PathVariable int matricola) { StudenteH s = new StudenteH(); s.setMatricola(matricola); return dao.ricercaStudente(s); } @RequestMapping(method=RequestMethod.GET) public @ResponseBody List<StudenteH> getStudenti() { return dao.stampaStudenti(); } }
Java
UTF-8
2,339
2.71875
3
[]
no_license
package ristogo.ui.controls.base; import java.util.LinkedList; import java.util.List; import java.util.function.Function; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Side; import javafx.scene.control.ContextMenu; import javafx.scene.control.CustomMenuItem; import javafx.scene.control.Label; import javafx.scene.control.TextField; public class AutocompleteTextField extends TextField { private ContextMenu entriesPopup; private boolean disabled; public AutocompleteTextField(Function<String, List<String>> searchCb) { super(); entriesPopup = new ContextMenu(); textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String s, String s2) { if (getText().length() < 2 || disabled) { entriesPopup.hide(); return; } List<String> entries = searchCb.apply(getText()); if (entries.size() == 0) { entriesPopup.hide(); return; } populatePopup(entries); if (!entriesPopup.isShowing()) entriesPopup.show(AutocompleteTextField.this, Side.BOTTOM, 0, 0); } }); focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observableValue, Boolean aBoolean, Boolean aBoolean2) { entriesPopup.hide(); } }); } private void populatePopup(List<String> entries) { List<CustomMenuItem> menuItems = new LinkedList<CustomMenuItem>(); int count = Math.min(entries.size(), 10); for (int i = 0; i < count; i++) { String entry = entries.get(i); Label entryLabel = new Label(entry); CustomMenuItem menuItem = new CustomMenuItem(entryLabel, true); menuItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { setText(entry); entriesPopup.hide(); } }); menuItems.add(menuItem); } entriesPopup.getItems().clear(); entriesPopup.getItems().addAll(menuItems); } public void setAutocompleteDisable(boolean value) { this.disabled = value; } public void setValue(String value) { setAutocompleteDisable(true); setText(value); setAutocompleteDisable(false); } }
C
UTF-8
356
2.90625
3
[]
no_license
//@venkatesh thirunagiri /*Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2 */ int removeElement(int* nums, int numsSize, int val){ int i,j=0; for(i=0;i<numsSize;i++) { if(nums[i] != val) { nums[j++]=nums[i]; } } return j; }
Java
UTF-8
2,470
2.171875
2
[]
no_license
package com.user.model; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name = "user") public class User { @NotBlank(message = "{name.not.blank}") private String name; @NotBlank(message = "{nickname.not.blank}") private String nickname; @Id @NotBlank(message = "{document.not.blank}") private String document; @Valid @OneToMany(cascade = CascadeType.MERGE) private List<Address> adresses; @NotBlank(message = "{profession.not.blank}") private String profession; @NotNull(message = "{salary.not.null}") private Double salary; @Valid @OneToMany(cascade = CascadeType.MERGE) private List<Dependent> dependents; @NotNull(message = "{dateOfBirth.not.null}") private Date dateOfBirth; @Valid @OneToMany(cascade = CascadeType.MERGE) private List<Phone> phones; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getDocument() { return document; } public void setDocument(String document) { this.document = document; } public List<Address> getAdresses() { return adresses; } public void setAdresses(List<Address> adresses) { this.adresses = adresses; } public String getProfession() { return profession; } public void setProfession(String profession) { this.profession = profession; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public List<Dependent> getDependents() { return dependents; } public void setDependents(List<Dependent> dependents) { this.dependents = dependents; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public List<Phone> getPhones() { return phones; } public void setPhones(List<Phone> phones) { this.phones = phones; } }
Java
UTF-8
132
1.53125
2
[]
no_license
package comum.json.artefatos; public enum JType { STRING, OBJECT, ARRAY, NUMBER, NULL, BOOLEAN, DATE, BYTEARRAY, CLASS, ENUM, }
Markdown
UTF-8
1,895
2.9375
3
[ "MIT" ]
permissive
# Udacity Arcade Game clone &middot; [![Build Status](https://img.shields.io/travis/npm/npm/latest.svg?style=flat-square)](https://travis-ci.org/npm/npm) [![npm](https://img.shields.io/npm/v/npm.svg?style=flat-square)](https://www.npmjs.com/package/npm) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://github.com/your/your-project/blob/master/LICENSE) > Learning project In this game you have a Player and Enemies (Bugs). The goal of the player is to reach the water, without colliding into any one of the enemies. The player can move left, right, up and down using arrow keys: ← ↑ → ↓. The enemies move in varying speeds on the paved block portion of the scene. Once a the player collides with an enemy, the game is reset and the player moves back to the start square. ![Start game screenshot](build/images/Arcade-game-start-screenshot.png "Start game screenshot") You can collect gems and heart. Blue gem will add 50 points, Green gem will add 75 points, and orange gem will add 100 points. To cross the river you need to use logs. Falling to water also will reset the game. The heart will add an extra life. Once the player reaches the star the game is won and the player will be rewarded with 200 points. ![Gameplay screenshot](build/images/Arcade-game-gameplay-screenshot.png "Gameplay screenshot") ## Installing / Getting started No installation is needed. You can download the project and open index.html file in the root folder. Or you can play it online on [Github Pages](https://soheevich.github.io/Udacity-Arcade-Game/) ### Built With Gulp, SASS, ESlint. ### Prerequisites What is needed to set up the dev environment. For instance, global dependencies or any other tools. include download links.
Python
UTF-8
1,946
3.203125
3
[]
no_license
from collections import deque def bfs1(r, c, land): q = deque() q.append((r, c)) while q: r, c = q.popleft() for i in range(4): nr = r + dr[i] nc = c + dc[i] if 0 <= nr < N and 0 <= nc < N: if visited[nr][nc] == 0 and arr[nr][nc] == 1: #방문안했고 땅이면 visited[nr][nc] = land q.append((nr, nc)) elif visited[nr][nc] == 0 and arr[nr][nc] == 0: #방문안했고 땅 옆에 붙어있는 바다면 end.append((r, c)) #땅의 끝 def bfs2(end): cnt = 0 #반복횟수 ans = 987654321 while end: cnt += 1 for _ in range(len(end)): r, c = end.popleft() for i in range(4): nr = r + dr[i] nc = c + dc[i] if 0 <= nr < N and 0 <= nc < N: if visited[nr][nc] == 0 or visited[nr][nc] == 1: #바다거나 땅옆에 있는 바다 visited[nr][nc] = visited[r][c] #땅 확장 end.append((nr, nc)) elif visited[nr][nc] != visited[r][c]: #우리땅 아님 if visited[nr][nc] < visited[r][c]: ans = min(((cnt - 1) * 2), ans) if visited[nr][nc] > visited[r][c]: ans = min(((cnt * 2) - 1), ans) return ans N = int(input()) arr = [] #지도 end = deque() #육지의 끝에 붙어있는 바다 (다리의 시작점) land = -1 #육지 분리해서 표시하기 위함 visited = [([0] * N) for _ in range(N)] dr = [-1, 0, 1, 0] dc = [0, 1, 0, -1] for _ in range(N): arr.append(list(map(int, input().split()))) for i in range(N): for j in range(N): if arr[i][j] == 1 and visited[i][j] == 0: visited[i][j] = land bfs1(i, j, land) land -= 1 print(bfs2(end))
SQL
UTF-8
13,465
3.8125
4
[]
no_license
CREATE TABLE USER( User_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Email VARCHAR(50) NOT NULL UNIQUE, Password VARCHAR(50) NOT NULL, Date_Joined DATETIME NULL, Fname VARCHAR(20) NOT NULL, Mname VARCHAR(20), Lname VARCHAR(20) NOT NULL, Gender ENUM('Bay','Bayan') NOT NULL, Active ENUM('Aktif','Pasif') NOT NULL DEFAULT 'Aktif', CONSTRAINT User_PK PRIMARY KEY (User_ID) ); CREATE TABLE COUNTRY ( Country_ID SMALLINT NOT NULL AUTO_INCREMENT, Country VARCHAR(30) NOT NULL UNIQUE, CONSTRAINT Country_PK PRIMARY KEY (Country_ID) )AUTO_INCREMENT=201; CREATE TABLE CITY ( City_ID SMALLINT NOT NULL AUTO_INCREMENT, City VARCHAR(30) NOT NULL UNIQUE, Country_ID SMALLINT, CONSTRAINT City_PK PRIMARY KEY (City_ID), CONSTRAINT C_Country_FK FOREIGN KEY(Country_ID) REFERENCES COUNTRY(Country_ID) ON DELETE SET NULL ON UPDATE CASCADE )AUTO_INCREMENT=301; CREATE TABLE ADDRESS( Address_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Address VARCHAR(200) NOT NULL, City_ID SMALLINT, Zip INT, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT Address_PK PRIMARY KEY (Address_ID), CONSTRAINT A_City_FK FOREIGN KEY (City_ID) REFERENCES CITY(City_ID) ON DELETE SET NULL ON UPDATE CASCADE )AUTO_INCREMENT=401; CREATE TABLE ORGANIZATION ( Organization_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Organization_Name VARCHAR(45) NOT NULL UNIQUE, Address_ID MEDIUMINT, Organization_Description TEXT, CONSTRAINT Organization_PK PRIMARY KEY(Organization_ID), CONSTRAINT O_Address_FK FOREIGN KEY(Address_ID) REFERENCES ADDRESS(Address_ID) ON DELETE SET NULL ON UPDATE CASCADE )AUTO_INCREMENT=751; CREATE TABLE PROFILE( Profile_ID MEDIUMINT NOT NULL AUTO_INCREMENT, User_ID MEDIUMINT NOT NULL UNIQUE, Address_ID MEDIUMINT, Current_Organization_ID MEDIUMINT, Relationship ENUM('Evli','Bekar','Dul','Nişanlı','İlişkisi var','İlişkisi yok','Belirtilmemiş') DEFAULT 'Belirtilmemiş', Date_of_Birth DATE NOT NULL, Phone VARCHAR(15) UNIQUE, Last_Update TIMESTAMP, About_Me TEXT, Interests TEXT, Hobbies TEXT, Educations TEXT, Begin_Organization DATE, Number_of_Connection MEDIUMINT NOT NULL DEFAULT 0, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT Profile_PK PRIMARY KEY(Profile_ID), CONSTRAINT P_User_FK FOREIGN KEY(User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT P_Address_FK FOREIGN KEY(Address_ID) REFERENCES ADDRESS(Address_ID) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT P_Organization_FK FOREIGN KEY (Current_Organization_ID) REFERENCES ORGANIZATION(Organization_ID) ON DELETE SET NULL ON UPDATE CASCADE )AUTO_INCREMENT=1001; CREATE TABLE CHAT( /* Chat_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Sender_ID MEDIUMINT NOT NULL, Receivers_ID MEDIUMINT NOT NULL, Message TEXT, Date_Created TIMESTAMP, CONSTRAINT Chat_PK PRIMARY KEY(Chat_ID), CONSTRAINT C_Sender_FK FOREIGN KEY(Sender_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT C_Receiver_FK FOREIGN KEY(Receiver_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE */ Chat_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Message TEXT, Date_Created TIMESTAMP, CONSTRAINT Chat_PK PRIMARY KEY(Chat_ID) )AUTO_INCREMENT=3001 ; #Alıcının birden fazla olması durumunda veri tekrarı(mesajın içeriği) olmaması için. CREATE TABLE GROUP_CHAT( Chat_ID MEDIUMINT NOT NULL, Sender_ID MEDIUMINT NOT NULL, Receiver_ID MEDIUMINT NOT NULL, CONSTRAINT Group_Chat_PK PRIMARY KEY(Chat_ID,Receiver_ID), CONSTRAINT Group_Chat_FK FOREIGN KEY(Chat_ID) REFERENCES CHAT(Chat_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT GC_Sender_FK FOREIGN KEY(Sender_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT GC_Receiver_FK FOREIGN KEY(Receiver_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=3501; CREATE TABLE MESSAGE( Message_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Sender_ID MEDIUMINT NOT NULL, Receiver_ID MEDIUMINT NOT NULL, Message TEXT, is_Read BOOLEAN DEFAULT 0, is_Spam BOOLEAN DEFAULT 0, is_Reply BOOLEAN DEFAULT 0, Created_at TIMESTAMP, CONSTRAINT Message_PK PRIMARY KEY(Message_ID), CONSTRAINT M_Sender_FK FOREIGN KEY(Sender_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT M_Receiver_FK FOREIGN KEY(Receiver_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=4001 ; CREATE TABLE CONNECTION( Connection_ID MEDIUMINT NOT NULL AUTO_INCREMENT, From_ID MEDIUMINT NOT NULL, To_ID MEDIUMINT NOT NULL, Date_Created TIMESTAMP NOT NULL, State BOOLEAN DEFAULT 0, #0: arkadaşlık isteği halinde 1:kabul edildi CONSTRAINT Connection_PK PRIMARY KEY(Connection_ID), CONSTRAINT C_From_FK FOREIGN KEY(From_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT C_To_FK FOREIGN KEY(To_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, UNIQUE KEY C_Unique (From_ID, To_ID) )AUTO_INCREMENT=1501; CREATE TABLE CONNECTION_LIST ( Connection_ID MEDIUMINT NOT NULL, Connection_List_Name ENUM('Okul Arkadaşı','İş arkadaşı','Aile','Diğer') DEFAULT 'Diger', CONSTRAINT Connection_List_PK PRIMARY KEY(Connection_ID), CONSTRAINT C_L_Connection_FK FOREIGN KEY (Connection_ID) REFERENCES CONNECTION(Connection_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE CV( CV_ID MEDIUMINT NOT NULL AUTO_INCREMENT, User_ID MEDIUMINT NOT NULL UNIQUE, Date_Created DATE NOT NULL, Date_Update TIMESTAMP, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT CV_PK PRIMARY KEY(CV_ID), CONSTRAINT CV_User_FK FOREIGN KEY(User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=6001; CREATE TABLE CV_SECTION( CV_Section_ID MEDIUMINT NOT NULL, # 0:EGITIM 1:YABANCI DIL 2:DENEYIMLER 3:SERTIFIKALAR 4:KISISEL NOT VS... CV_ID MEDIUMINT NOT NULL, CV_Section_Text TEXT, Date_Created DATE NOT NULL, Date_Update TIMESTAMP, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT CV_Section_PK PRIMARY KEY(CV_Section_ID,CV_ID), CONSTRAINT CV_Section_CV_FK FOREIGN KEY(CV_ID) REFERENCES CV(CV_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE REF_CV_SECTION( Ref_User_ID MEDIUMINT NOT NULL, CV_ID MEDIUMINT NOT NULL, CV_Section_ID MEDIUMINT NOT NULL, CONSTRAINT Ref_CV_Section_PK PRIMARY KEY(Ref_User_ID,CV_ID,CV_Section_ID), CONSTRAINT Ref_CV_Section_User_FK FOREIGN KEY(Ref_User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT Ref_CV_Section_CV_FK FOREIGN KEY(CV_Section_ID,CV_ID) REFERENCES CV_SECTION(CV_Section_ID,CV_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE RECOMMENDATION( From_ID MEDIUMINT NOT NULL, To_ID MEDIUMINT NOT NULL, Created_at TIMESTAMP, Text_Recommendation TEXT NOT NULL, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT Recommendation_PK PRIMARY KEY(From_ID,To_ID), CONSTRAINT Recommendation_From_FK FOREIGN KEY (From_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT Recommendation_To_FK FOREIGN KEY (To_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE OBJECT( Object_ID MEDIUMINT NOT NULL, Object_Type VARCHAR(20) NOT NULL, CONSTRAINT Object_PK PRIMARY KEY(Object_ID,Object_Type) ); CREATE TABLE STATUS ( Status_ID MEDIUMINT NOT NULL AUTO_INCREMENT, User_ID MEDIUMINT NOT NULL, Message TEXT NOT NULL, Created_at TIMESTAMP, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT Status_PK PRIMARY KEY(Status_ID), CONSTRAINT Status_User_FK FOREIGN KEY(User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=101; CREATE TABLE GROUPs( Group_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Created_by_User_ID MEDIUMINT NOT NULL, Group_Name VARCHAR(50) NOT NULL UNIQUE, Group_Description TEXT, Created_at DATETIME NOT NULL, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT Group_PK PRIMARY KEY(Group_ID), CONSTRAINT Group_Created_User_FK FOREIGN KEY(Created_by_User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=8001; CREATE TABLE GROUPs_USER( User_ID MEDIUMINT NOT NULL, Group_ID MEDIUMINT NOT NULL, Date_Joined TIMESTAMP, CONSTRAINT Groups_User_PK PRIMARY KEY(User_ID,Group_ID), CONSTRAINT Groups_User_User_FK FOREIGN KEY(User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT Groups_User_Group_FK FOREIGN KEY(Group_ID) REFERENCES GROUPs(Group_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE FEED( Feed_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Feed_Status ENUM('Duvar','Group') DEFAULT 'Duvar', User_ID MEDIUMINT NOT NULL, Created_at TIMESTAMP, Click SMALLINT NOT NULL DEFAULT 0, URL VARCHAR(255) NOT NULL, Category_Name VARCHAR(50) NOT NULL, # Bilgi_bilisim / Business / Economy / Insaat Type_Name ENUM('Makale','Is ilanı','Haber','Etkinlik','Diğer' ), Title VARCHAR(50), Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT Feed_PK PRIMARY KEY(Feed_ID), CONSTRAINT Feed_User_FK FOREIGN KEY(User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=151; #Gruba paylaşım yapılması CREATE TABLE GROUP_FEED( Group_ID MEDIUMINT NOT NULL, Feed_ID MEDIUMINT NOT NULL, CONSTRAINT Group_Feed_PK PRIMARY KEY(Group_ID,Feed_ID), CONSTRAINT GF_Group_FK FOREIGN KEY (Group_ID) REFERENCES GROUPs(Group_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT GF_Feed_FK FOREIGN KEY (Feed_ID) REFERENCES FEED(Feed_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE LIKE_DISLIKE( Object_ID MEDIUMINT NOT NULL, Object_Type VARCHAR(20) NOT NULL, Friend_ID MEDIUMINT NOT NULL, Flag BOOLEAN NOT NULL, # 0:DISLIKE 1:LIKE LIKE/DISLIKE YOKSA ZATEN BU TABLOYA EKLENMEZ Created_at TIMESTAMP, CONSTRAINT Like_Dislike_PK PRIMARY KEY(Object_ID,Object_Type,Friend_ID), CONSTRAINT Like_Dislike_Object_FK FOREIGN KEY(Object_ID,Object_Type) REFERENCES OBJECT(Object_ID,Object_Type) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT Like_Dislike_Friend_FK FOREIGN KEY(Friend_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE COMMENT( Comment_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Object_ID MEDIUMINT NOT NULL, Object_Type VARCHAR(20) NOT NULL, Friend_ID MEDIUMINT NOT NULL, Message TEXT NOT NULL, Created_at TIMESTAMP, CONSTRAINT Comment_PK PRIMARY KEY(Comment_ID), CONSTRAINT Comment_Status_FK FOREIGN KEY(Object_ID,Object_Type) REFERENCES OBJECT(Object_ID,Object_Type) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT Comment_Friend_FK FOREIGN KEY(Friend_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=7001; CREATE TABLE EVENT( Event_ID MEDIUMINT NOT NULL AUTO_INCREMENT, Event_Created_by_User_ID MEDIUMINT NOT NULL, Event_Name VARCHAR(50) NOT NULL UNIQUE, Event_Description TEXT, Start_Date DATETIME NOT NULL, Finish_Date DATETIME NOT NULL, Privacy ENUM('Herkese Acık','Sadece Arkadaslar','Sadece Ben') default 'Herkese Acık', CONSTRAINT Event_PK PRIMARY KEY (Event_ID), CONSTRAINT Event_Created_by_User_FK FOREIGN KEY(Event_Created_by_User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=9001; CREATE TABLE EVENT_USER( Event_ID MEDIUMINT NOT NULL, User_ID MEDIUMINT NOT NULL, Participate_Status ENUM('CEVAPLANMAMIS','KATILACAK','KATILMAYACAK','KARARSIZ') DEFAULT 'CEVAPLANMAMIS', CONSTRAINT Event_User_PK PRIMARY KEY(Event_ID,User_ID), CONSTRAINT Event_User_Event_FK FOREIGN KEY(Event_ID) REFERENCES EVENT(Event_ID) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT Event_User_User_FK FOREIGN KEY(User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE ); CREATE TABLE NOTIFICATION( Notification_ID INT NOT NULL AUTO_INCREMENT, User_ID MEDIUMINT NOT NULL, Notification_Type VARCHAR(50) NOT NULL, Message TEXT NOT NULL, Created_at TIMESTAMP, CONSTRAINT Notification_PK PRIMARY KEY(Notification_ID), CONSTRAINT Notification_User_FK FOREIGN KEY(User_ID) REFERENCES USER(User_ID) ON DELETE CASCADE ON UPDATE CASCADE )AUTO_INCREMENT=2501;
TypeScript
UTF-8
1,669
3.609375
4
[ "Apache-2.0" ]
permissive
interface IUniqueData { [dataName: string]: number; } interface IGenerateColumnDataConfig { makeRandomUnique: boolean; fakerFn: () => number | string | undefined; dataIsNumber?: boolean; } const generateColumnData = <DataType>( uniqueData: IUniqueData, config: IGenerateColumnDataConfig, total: number ) => { // generate number of unique data let uniqueDataArr = [] as DataType[]; Object.keys(uniqueData).forEach(data => { const count = uniqueData[data]; const dataToFill = config.dataIsNumber ? +data : data; const newData = Array(count).fill(dataToFill); uniqueDataArr = [...uniqueDataArr, ...newData]; }); const randomDataArr = [] as DataType[]; // uniqueness checkers const checkIfInUnique = (data: DataType) => uniqueDataArr.includes(data); const checkIfInRandom = (data: DataType) => randomDataArr.includes(data); let isAlreadySeen: (data: DataType) => boolean; if (config.makeRandomUnique) { isAlreadySeen = data => checkIfInUnique(data) || checkIfInRandom(data); } else { isAlreadySeen = data => checkIfInUnique(data); } // generate random data Array(total - uniqueDataArr.length) .fill(undefined) .forEach(() => { let newData = (config.fakerFn() as unknown) as DataType; while (isAlreadySeen(newData)) { newData = (config.fakerFn() as unknown) as DataType; } randomDataArr.push(newData); }); // return unique and random data return {uniqueData: uniqueDataArr, randomData: randomDataArr}; }; export default generateColumnData;
C#
UTF-8
2,650
2.671875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using CsvHelper; using System.IO; public static class CsvCardLoader{ static string ArtFolder = "Full Size Character Portraits\\"; static Dictionary<string, List<record>> allRecords = new Dictionary<string, List<record>>(); public static void OpenCSV(string path, bool openPath) { allRecords = new Dictionary<string, List<record>>(); TextReader textReader; if (openPath) textReader = File.OpenText(path); else textReader = new StreamReader(path); var csv = new CsvReader(textReader); var records = csv.GetRecords<record>(); foreach (record r in records) { if (!allRecords.ContainsKey(r.Set)) allRecords[r.Set] = new List<record>(); allRecords[r.Set].Add(r); } } public static GameObject GenerateCardObjects(string setName) { GameObject setObject = new GameObject(setName); if(allRecords.ContainsKey(setName)) { foreach (record r in allRecords[setName]) { Card card = setObject.AddComponent<Card>(); card.CardName = r.Name; switch(r.Class.ToLower()) { case "noble": card.CardClass = CardClass.NOBLE; break; case "assassin": card.CardClass = CardClass.ASSASSIN; break; case "commoner": card.CardClass = CardClass.COMMONER; break; case "soldier": card.CardClass = CardClass.SOLDIER; break; case "queen": card.CardClass = CardClass.QUEEN; break; case "king": card.CardClass = CardClass.KING; break; } card.Attack = r.Attack; card.AttackBonus = getBonusFromString(r.AttackBonus); card.Defense = r.Defense; card.DefenseBonus = getBonusFromString(r.DefenseBonus); card.RulesText = r.RulesText; card.FlavorText = r.FlavorText; card.Art = Resources.Load<Sprite>(ArtFolder + r.ArtPath); card.Logic = CardLogicFactory.GetCard(r.Name); } } else { Debug.LogError("No set called " + setName); } return setObject; } static FaceUpBonus getBonusFromString(string s) { switch(s.ToLower()) { case "up": return FaceUpBonus.FACE_UP; case "down": return FaceUpBonus.FACE_DOWN; } return FaceUpBonus.NONE; } private class record { public string Name { get; set; } public string Class {get; set;} public int Attack { get; set; } public string AttackBonus { get; set; } public int Defense { get; set; } public string DefenseBonus { get; set; } public string RulesText { get; set; } public string FlavorText { get; set; } public string Set { get; set; } public string ArtPath { get; set; } } }
TypeScript
UTF-8
3,611
3.1875
3
[ "Apache-2.0" ]
permissive
import { traverseObject } from './traverseObject'; describe('traverseObject', () => { let keyValuePairsWalked: Array<[string, any]>; let i: number; function defaultCallback(key: string, val: any) { keyValuePairsWalked.push([key, val]); } beforeEach(() => { i = 0; keyValuePairsWalked = []; }); it('walks simple properties of an object', () => { const object = { foo: 1, bar: 2 }; traverseObject(object, defaultCallback); expect(keyValuePairsWalked.length).toEqual(2); expect(keyValuePairsWalked[i++]).toEqual(['foo', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar', 2]); }); it('walks nested properties of an object', () => { const object = { foo: 1, bar: { prop1: 1, prop2: 2 } }; traverseObject(object, defaultCallback); expect(keyValuePairsWalked.length).toEqual(4); expect(keyValuePairsWalked[i++]).toEqual(['foo', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar', { prop1: 1, prop2: 2 }]); expect(keyValuePairsWalked[i++]).toEqual(['bar.prop1', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar.prop2', 2]); }); it('only walks simple leaf nodes an object when traverseLeafNodesOnly is true', () => { const object = { foo: 1, bar: { prop1: 1, prop2: 2 } }; traverseObject(object, defaultCallback, true); expect(keyValuePairsWalked.length).toEqual(3); expect(keyValuePairsWalked[i++]).toEqual(['foo', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar.prop1', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar.prop2', 2]); }); it('walks array properties of an object', () => { const object = { foo: 1, bar: [1, 2] }; traverseObject(object, defaultCallback); expect(keyValuePairsWalked.length).toEqual(4); expect(keyValuePairsWalked[i++]).toEqual(['foo', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar', [1, 2]]); expect(keyValuePairsWalked[i++]).toEqual(['bar[0]', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar[1]', 2]); }); it('walks only leaf array elements when traverseLeafNodesOnly is true', () => { const object = { foo: 1, bar: [1, 2] }; traverseObject(object, defaultCallback, true); expect(keyValuePairsWalked.length).toEqual(3); expect(keyValuePairsWalked[i++]).toEqual(['foo', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar[0]', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar[1]', 2]); }); it('walks nested objects inside array properties of an object', () => { const object = { foo: 1, bar: [{ name: 'abc' }, { name: 'def' }] }; traverseObject(object, defaultCallback); expect(keyValuePairsWalked.length).toEqual(6); expect(keyValuePairsWalked[i++]).toEqual(['foo', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar', [{ name: 'abc' }, { name: 'def' }]]); expect(keyValuePairsWalked[i++]).toEqual(['bar[0]', { name: 'abc' }]); expect(keyValuePairsWalked[i++]).toEqual(['bar[0].name', 'abc']); expect(keyValuePairsWalked[i++]).toEqual(['bar[1]', { name: 'def' }]); expect(keyValuePairsWalked[i++]).toEqual(['bar[1].name', 'def']); }); it('walks only leaf nodes nested objects inside array properties of an object when traverseLeafNodesOnly is true', () => { const object = { foo: 1, bar: [{ name: 'abc' }, { name: 'def' }] }; traverseObject(object, defaultCallback, true); expect(keyValuePairsWalked.length).toEqual(3); expect(keyValuePairsWalked[i++]).toEqual(['foo', 1]); expect(keyValuePairsWalked[i++]).toEqual(['bar[0].name', 'abc']); expect(keyValuePairsWalked[i++]).toEqual(['bar[1].name', 'def']); }); });
Python
UTF-8
5,686
2.828125
3
[]
no_license
#tkinter from tkinter import * from tkinter import ttk as ttk, messagebox, filedialog #systems and shutil from datetime import datetime, timedelta from glob import glob import os import time import shutil #dB import sqlite3 #creates dB def createDB(): conn = sqlite3.connect('create_dB.db') print('Connected to dB') conn.execute('DROP TABLE IF EXISTS fortKnox') conn.execute('CREATE TABLE IF NOT EXISTS fortKnox (ID INTEGER PRIMARY KEY AUTOINCREMENT, timeChecked TEXT)') conn.commit() class FileCheck: def __init__(self, master): self.frameHeader = ttk.Frame(master) self.frameHeader.pack() #Daily Folder self.chooseFolderName = StringVar() print (self.chooseFolderName) self.daily = (self.chooseFolderName.get()) #Destination Folder self.destFolderName = StringVar() print (self.destFolderName) self.dest = (self.destFolderName.get()) #GetdBtimestamp self.fileCheckTimeStamp = StringVar() print (self.fileCheckTimeStamp) self.fcT = (self.fileCheckTimeStamp.get()) #Frame self.frameSteps = ttk.Frame(master) self.frameSteps.pack() #Labels titleLabel = ttk.Label(self.frameHeader, text = 'UI for File Transfer project - Python 3.4 - IDLE ', font = 'bold') titleLabel.grid(row = 0, column = 0, columnspan = 2, pady = 5, sticky = 'W') dailyStepLabel = ttk.Label(self.frameSteps, text = '1) Choose a Starting Folder') dailyStepLabel.grid(row = 0, column = 0, columnspan = 2, pady = 5, sticky = 'W') destStepLabel = ttk.Label(self.frameSteps, text = '2) Choose a Destination Folder') destStepLabel.grid(row = 3, column = 0, columnspan = 2, pady = 5, sticky = 'W') initiafileMoverepLabel = ttk.Label(self.frameSteps, text = '3) Run Manual File Check') initiafileMoverepLabel.grid(row = 7, column = 0, columnspan = 2, pady = 5, sticky = 'W') #Buttons dailyButton = ttk.Button(self.frameSteps, text = 'Start Folder', command = self.chooseStartFolder) dailyButton.grid(row = 1, column = 1, sticky = 'W') destButton = ttk.Button(self.frameSteps, text = 'Destination Folder', command = self.chooseDestFolder) destButton.grid(row = 4, column = 1, sticky = 'W') initiateButton = ttk.Button(self.frameSteps, text = 'Initiate File Check', command = lambda: self.fileMover(self.filesStart,self.filesEnd)) initiateButton.grid(row = 8, column = 1, sticky = 'W') #Paths self.framePath = ttk.Frame(master) self.framePath.pack() dailyPathLabel = ttk.Label(self.frameSteps, text = self.chooseFolderName, textvariable = self.chooseFolderName) dailyPathLabel.grid(row = 1, column = 2, rowspan = 1, sticky = 'W') destPathLabel = ttk.Label(self.frameSteps, text = self.destFolderName, textvariable = self.destFolderName) destPathLabel.grid(row = 4, column = 2, rowspan = 1, sticky = 'W') #TimeCheck fcTimeTitleLabel = ttk.Label(self.frameSteps, text = 'Last File Check: ') fcTimeTitleLabel.grid(row = 7, column = 2, sticky = 'W' ) fcTimestampLabel = ttk.Label(self.frameSteps, textvariable = self.fileCheckTimeStamp) fcTimestampLabel.grid(row = 8, column = 2, rowspan = 1, sticky = 'W') #MostRecentTimestamp self.updateFcTimeStamp() def chooseStartFolder(self): self.filesStart = filedialog.askdirectory(initialdir = "/Users", title = "Choose Starting Folder") self.chooseFolderName.set(self.filesStart) print (self.filesStart) print (self.chooseFolderName.get()) def chooseDestFolder(self): self.filesEnd = filedialog.askdirectory(initialdir = "/Users", title = "Choose Destination Folder") self.destFolderName.set(self.filesEnd) print (self.filesEnd) print (self.destFolderName.get()) #The File Mover def fileMover(self, filesStart, filesEnd): print (format(filesStart)) print (format(filesEnd)) timeNow = datetime.now() oneDayOld = timeNow - timedelta(hours = 24) for f in os.listdir(filesStart): files = os.path.realpath(os.path.join(filesStart,f)) if files.endswith('.txt'): filesToMove = datetime.fromtimestamp(os.path.getmtime(files)) if filesToMove > oneDayOld: print (files, "Copied: ", filesEnd) shutil.copy(files,filesEnd) else: print (files, "Not Copied") self.dbCheck() def updateFcTimeStamp(self): self.conn = sqlite3.connect('create_dB.db') print ("got into updatefc") self.cursor = self.conn.execute('SELECT timeChecked FROM fortKnox ORDER BY ID DESC LIMIT 1') for row in self.cursor: print (row) self.fileCheckClock = self.fileCheckTimeStamp.set(row) print (row) def dbCheck(self): self.conn = sqlite3.connect('create_dB.db') print ("connected") self.conn.execute("INSERT INTO fortKnox (timeChecked) VALUES (datetime(CURRENT_TIMESTAMP, 'localtime'))") print ("inserted timestamp") self.conn.commit() self.updateFcTimeStamp() self.conn.close() print ('Database closed') def main(): root = Tk() root.title("File Check") root.minsize(400, 280) filecheck = FileCheck(root) root.mainloop() if __name__ == '__main__' : main()
Python
UTF-8
12,899
2.96875
3
[]
no_license
from Infrastracture.repo import RepoError from datetime import date from Validations.validations import ValidationError class UI: def __init__(self, servStudents, servAssignments, servGrades, servUndo): self._servStudents = servStudents self._servAssignments = servAssignments self._servGrades = servGrades self._servUndo = servUndo def _ui_print_menu(self): print("Choose an option") print("1. Add a student") print("2. Show students") print("3. Delete student") print("4. Update student") print("5. Add an assignment") print("6. Show assignments") print("7. Delete assignment") print("8. Update assignment") print("9. Assign assignment to student") print("10. Assign assignment to group") print("11. Show all grades") print("12. Grade student for a given assignment") print("13. All students who received a given assignment") print("14. All students who are late in handing in at least one assignment") print("15. Students with the best school situation") print("16. Exit") print("u: Undo") print("r: Redo") def _ui_add_student(self): studentID = input("Give id: ") name = input("Give name: ") group = input("Give group: ") errors = "" try: studentID = int(studentID) except ValueError: errors += "Invalid id!\n" try: group = int(group) except ValueError: errors += "Invald group\n" if len(errors) == 0: try: self._servStudents.add_student(studentID, name, group) except Exception as error: print(error) else: print(errors) def _ui_show_students(self): for student in self._servStudents.get_students(): print(student) def _ui_delete_student(self): studentID = input("Give the student's id that you want to delete: ") errors = "" try: studentID = int(studentID) except ValueError: errors += "invalid id\n" if len(errors) == 0: try: student = self._servStudents.get_student_by_id(studentID) print("Do you want to delete " + str(student) + " ? (y/n)") choice = input("(y/n): ") if choice == 'y': self._servStudents.delete_student(studentID) except RepoError as error: print(error) else: print(errors) def _ui_update_student(self): studentID = input("Give the student's id that you want to update: ") errors = "" try: studentID = int(studentID) except ValueError: errors += "invalid id\n" if len(errors) == 0: try: student = self._servStudents.get_student_by_id(studentID) print("Do you want to update " + str(student) + " ? (y/n)") choice = input("(y/n): ") if choice == 'y': name = input("New name: ") group = int(input("New group: ")) self._servStudents.update_student(studentID, name, group) except ValueError: print("Invalid group\n") except Exception as error: print(error) else: print(errors) def _ui_add_assignment(self): assignmentID = input("Give id: ") description = input("Give description: ") deadl = input("Give deadline (year-month-day): ") deadl = deadl.split('-') errors = "" if len(deadl) == 3: try: year = int(deadl[0]) month = int(deadl[1]) day = int(deadl[2]) deadline = date(year, month, day) except ValueError: errors += "invalid deadline\n" else: errors += "invalid deadline\n" try: assignmentID = int(assignmentID) except ValueError: errors += "invalid id\n" if len(errors) == 0: try: self._servAssignments.add_assignment(assignmentID, description, deadline) except Exception as error: print(error) else: print(errors) def _ui_show_assignments(self): for assignment in self._servAssignments.get_assignments(): print(assignment) def _ui_delete_assignment(self): assignmentID = input("Give the assignemnt's id that you want to delete: ") errors = "" try: assignmentID = int(assignmentID) except ValueError: errors += "invalid id\n" if len(errors) == 0: try: assignment = self._servAssignments.get_assignment_by_id(assignmentID) print("Do you want to deltele " + str(assignment) + " ?") choice = input("(y/n): ") if choice == 'y': self._servAssignments.delete_assignment(assignmentID) except RepoError as error: print(error) else: print(errors) def _ui_update_assignment(self): assignmentID = input("Give the assignment's id that you want to update: ") errors = "" try: assignmentID = int(assignmentID) except ValueError: errors += "invalid id\n" if len(errors) == 0: try: assignment = self._servAssignments.get_assignment_by_id(assignmentID) print("Do you want to update " + str(assignment) + " ?") choice = input("(y/n): ") if choice == 'y': description = input("New description: ") deadl = input("New deadline (year-month-day): ") deadl = deadl.split('-') if len(deadl) == 3: year = int(deadl[0]) month = int(deadl[1]) day = int(deadl[2]) deadline = date(year, month, day) self._servAssignments.update_assignment(assignmentID, description, deadline) else: raise ValueError except ValueError: print("Invalid deadline\n") except Exception as error: print(error) else: print(errors) def _ui_assign_assignment_to_student(self): assignmentID = input("Give assignment id:") studentID = input("Give student id: ") try: assignmentID = int(assignmentID) studentID = int(studentID) self._servStudents.get_student_by_id(studentID) self._servAssignments.get_assignment_by_id(assignmentID) self._servGrades.assign_assignment_to_student(assignmentID, studentID) except ValueError: print("Invalid inputs") except Exception as error: print(error) def _ui_assign_assignment_to_group(self): assignmentID = input("Give assignment id:") group = input("Give group: ") try: assignmentID = int(assignmentID) group = int(group) self._servAssignments.get_assignment_by_id(assignmentID) self._servGrades.assign_assignment_to_group(group, assignmentID, self._servStudents) except ValueError: print("Invalid inputs\n") except Exception as error: print(error) def _ui_show_grades(self): for grade in self._servGrades.get_all_grades(): print(grade) def _ui_show_graded(self, studentID): print(" ") print("Graded assignmnets:") for assignmentID in self._servGrades.get_graded(studentID): print(self._servAssignments.get_assignment_by_id(assignmentID)) def _ui_show_ungraded(self, studentID): print(" ") print("Ungraded assignments:") for assignmentID in self._servGrades.get_ungraded(studentID): print(self._servAssignments.get_assignment_by_id(assignmentID)) def _ui_grade_student(self): try: studentID = int(input("Give student's ID: ")) the_student = self._servStudents.get_student_by_id(studentID) print("The student: " + str(the_student)) self._ui_show_graded(studentID) self._ui_show_ungraded(studentID) print(" ") assignmentID = int(input("Give assignment's ID: ")) the_assignment = self._servAssignments.get_assignment_by_id(assignmentID) grade = int(input("Give garde: ")) self._servGrades.update_grade(studentID, assignmentID, grade) except ValueError: print("Invalid id!") except RepoError as error: print(error) except Exception as error: print(error) def _ui_statistic_given_assignment(self): try: assignmentID = int(input("Give assignmnet id: ")) the_assignment = self._servAssignments.get_assignment_by_id(assignmentID) print("The assignment: " + str(the_assignment)) the_list = self._servGrades.get_students_by_assignment(assignmentID) for grade in the_list: print(str(self._servStudents.get_student_by_id(grade.get_student_id())) + "| grade: "+ str(grade.get_grade())) except ValueError: print("Invalid Id") except RepoError as error: print(error) def _ui_statistic_deadline_passed(self): stud_list = self._servGrades.dead_line_passed() for student in stud_list: print(str(self._servStudents.get_student_by_id(student[0])), str(self._servAssignments.get_assignment_by_id(student[1]).get_deadline())) def _ui_statistic_best_students(self): students_list = self._servGrades.best_students() for student in students_list: print(str(self._servStudents.get_student_by_id(student[0])) + "| avg: "+ str(student[1])) def _ui_undo(self): try: self._servUndo.undo() except Exception as error: print(error) def _ui_redo(self): try: self._servUndo.redo() except Exception as error: print(error) def start(self): while True: self._ui_print_menu() choice = input(">>>") if choice == '1': self._ui_add_student() if choice == '2': self._ui_show_students() if choice == '3': self._ui_delete_student() if choice == '4': self._ui_update_student() if choice == '5': self._ui_add_assignment() if choice == '6': self._ui_show_assignments() if choice == '7': self._ui_delete_assignment() if choice == '8': self._ui_update_assignment() if choice == '9': self._ui_assign_assignment_to_student() if choice == '10': self._ui_assign_assignment_to_group() if choice == '11': self._ui_show_grades() if choice == '12': self._ui_grade_student() if choice == '13': self._ui_statistic_given_assignment() if choice == '14': self._ui_statistic_deadline_passed() if choice == '15': self._ui_statistic_best_students() if choice == '16': break if choice == 'u': self._ui_undo() if choice == 'r': self._ui_redo()
Markdown
UTF-8
1,413
2.78125
3
[ "MIT" ]
permissive
# Muses 72320 Arduino library for communicating with the Muses 72320 audio chip. The data sheets can be found [here](http://www.njr.com/semicon/PDF/MUSES72320_E.pdf) (pdf). ## Download Download the latest release over at the [Releases](https://github.com/qhris/Muses72320/releases) page. ## Example ```c++ #include <Muses72320.h> // The address wired into the muses chip (usually 0). static const byte MUSES_ADDRESS = 0; static Muses72320 Muses(MUSES_ADDRESS); static Muses72320::volume_t CurrentVolume = -20; void setup() { // Initialize muses (SPI, pin modes)... Muses.begin(); // Muses initially starts in a muted state, set a volume to enable sound. Muses.setVolume(CurrentVolume); // These are the default states and could be removed... Muses.setZeroCrossing(true); // Enable/Disable zero crossing. Muses.setAttenuationLink(false); // Left channel controls both L/R gain channel. Muses.setGainLink(false); // Left channel controls both L/R attenuation channel. } void loop() { CurrentVolume -= 1; if (CurrentVolume < -223) { CurrentVolume = 0; } Muses.setVolume(CurrentVolume); // Equivalent to 'Muses.setVolume(CurrentVolume, CurrentVolume)' for L/R ch. delay(10); } ``` ## Problems Please post any problems on the [Issues](https://github.com/qhris/Muses72320/issues) page. ## License Please read over the LICENSE file included in the project.
Java
UTF-8
1,327
3.203125
3
[]
no_license
package scenario.consequences; /** * Scenario interface is the building block of the different * scenarios that the player will encounter. Through here, multiple * options of actions will be created as strings and will be implemented * by specific scenario classes. * * Created by Luke Moua on 12/23/2017. */ public interface ScenarioInterface { //Returns the name of the scene public String getScenarioName(); //Returns the description of the scene public String describeScene(); //Possibly use an array to hold the string options //when implementing code //The four actions that the player //is allowed to make during every scenario //These will vary, and will need to be implemented in //each different scenario class public String optionOne(); public String optionTwo(); public String optionThree(); public String optionFour(); //The consequences that will happen depending on //which decisions the player makes. Each choice they //make will have two results, good or bad consequence public String resultOne(); public String resultTwo(); public String resultThree(); public String resultFour(); public String resultFive(); public String resultSix(); public String resultSeven(); public String resultEight(); }
Python
UTF-8
814
2.84375
3
[]
no_license
__author__ = "xiaoyu hao" from gevent import monkey; monkey.patch_all() #把当前程序的所有IO操作单独的作上标记,捕捉urllib的IO操作 import gevent from urllib.request import urlopen import time def f(url): print('GET: %s' % url) resp = urlopen(url) data = resp.read() print('%d bytes received from %s.' % (len(data), url)) urls =['https://www.python.org/','https://www.yahoo.com/','https://github.com/'] time_stat = time.time() #不适用协程 for url in urls: f(url) print("同步cost:",time.time() - time_stat) async_stat_time = time.time() #适用协程 gevent.joinall([ gevent.spawn(f, 'https://www.python.org/'), gevent.spawn(f, 'https://www.yahoo.com/'), gevent.spawn(f, 'https://github.com/'), ]) print("异步cost:",time.time() - async_stat_time)
Python
UTF-8
4,976
3.21875
3
[]
no_license
""" This model utilizes Idzorek et al (2004)'s approach to incorporate user specific confidence levels on views expressed about assets' absolute or relative performance. The steps are laid out in Thomas Idzorek's 2004 paper: "A step-by-step guide to the Black-Litterman model: Incorporating user-specified confidence levels": https://www.sciencedirect.com/science/article/pii/B9780750683210500030 """ # importing the necessary packages import pandas as pd import numpy as np from pandas_datareader import data as wb import scipy.optimize as opt # create a portfolio class class portfolio: """ uses historal daily prices to compute monthly returns and covariances """ def __init__(self, assets_prices): #don't forget you are removing last month self.returns = assets_prices.apply(lambda x: np.log(x/x.shift(1))).resample('m').sum() def covariance(self): return self.returns.cov() # create the Idzorek approach to Black Litterman model class IBL_model(portfolio): """ utilizes Thomas Idzorek's 2004 approach in "step by step guide to the black litterman model:" https://www.sciencedirect.com/science/article/pii/B9780750683210500030 """ def __init__(self, assets_prices, market_caps, market_prices,monthly_risk_free,tau): portfolio.__init__(self,assets_prices) self.tickers = assets_prices.columns.values self.mkt_w = market_caps.astype(float)/market_caps.sum() self.mkt_r = market_prices.apply(lambda x: np.log(x/x.shift(1))).resample('m').sum() self.rf = monthly_risk_free.iloc[:,0] self.tau = tau self.sigma = self.excess_r().cov() self.mkt_var = self.mkt_w.transpose().dot(self.sigma).dot(self.mkt_w) self.lamda = (self.mkt_r.mean()[0]-self.rf.mean())/self.mkt_var self.pi = self.lamda*self.sigma.dot(self.mkt_w) def excess_r(self): excess_mr = pd.DataFrame() for i in self.returns: excess_mr[i] = self.returns[i]-self.rf return excess_mr def Im_expc_r(self): """ implied equilibrium expected returns vector """ Implied_equil_expected_returns = pd.DataFrame(wb.get_quote_yahoo(self.tickers)['longName']) Implied_equil_expected_returns['e(r)'] = self.pi return Implied_equil_expected_returns def Kview_omega(self,que,rho_v,confidence): """ finds expected returns with one view que - floating number. the relative outperformance of two assets (or one assets relative to risk-free) over next month rho_v - the rho vector that id's the assets involved in the view. 0 for other assets confidence - from 0 to 100 is the confidence interval in the view """ #Step1 compute expected return with 100% confidence a = self.tau*self.sigma.dot(rho_v) b = a/(rho_v.dot(a)) c = que - rho_v.transpose().dot(self.pi) e_100 = self.pi+b*c #Step2 compute weight for 100% confidence w_100 = np.linalg.pinv(self.lamda*self.sigma).dot(e_100) #Step3 compute departure of weights from market weight D_100 = w_100-self.mkt_w #Step4 compute tilt caused by less than 100% confidence tilt = np.multiply(D_100,confidence) #Step5 get target weight based on addition of tilt to market weight w_c = self.mkt_w + tilt #Step6 find the implied uncertainty def fun(omega_hat): a0 = np.linalg.pinv(self.lamda*self.sigma) a1 = np.linalg.pinv(self.tau*self.sigma) a2 = np.linalg.pinv(a1 + rho_v.dot((1/omega_hat)*rho_v)) a3 = a1.dot(self.pi) a4 = a3 + rho_v*(que/omega_hat) w_k = a0.dot(a2).dot(a4) return ((w_c-w_k)**2).sum() return opt.fmin(fun,0.01,disp=0)[0] def views_expected_r(self,Q,P,C): """ finds Black Litterman expected return based on some views about the assets performance. Note: all parameters should be inserted as array([]) Q is (Nx1) array of expected (viewed) outperformance (among assets or relative to risk-free rate). P (rho) is the id matrix with each row identifying assets involved with each view C is the confidence matrix with each row showing confidence levels involved with each view this is the 7th step of the Idzorek approach. """ Omega = np.identity(len(Q)) for eachview in range(0,len(Q)): Omega[eachview][eachview]=self.Kview_omega(Q[eachview],P[eachview],C[eachview]) #Step 7 plug in all the parameters to get the expected returns P_T = P.transpose() Omega_inv = np.linalg.pinv(Omega) risk_inv = np.linalg.pinv(self.tau*self.sigma) part_one = risk_inv + P_T.dot(Omega_inv).dot(P) part_two = risk_inv.dot(self.pi) +P_T.dot(Omega_inv).dot(Q) expected_return = np.linalg.pinv(part_one).dot(part_two) return expected_return
Java
UTF-8
776
2.265625
2
[]
no_license
package server; import GameObject.GameSession; import GameObject.IGameSession; import java.rmi.Remote; import java.rmi.RemoteException; /** * Just a remote Interface to enable access for the Screens therefore no comments->check Server * @author Fabi */ public interface ServerInterface extends Remote{ public IGameSession loadSession(String sessionName) throws RemoteException; public boolean saveSession(IGameSession session) throws RemoteException; public String createSession(String name) throws RemoteException; public boolean registerAccount(String name, String password) throws RemoteException; public boolean checkAccount(String name, String password) throws RemoteException; public String getSessionList() throws RemoteException; }
Swift
UTF-8
1,963
2.65625
3
[]
no_license
// // LoginNetworkManager.swift // IssueTracker // // Created by Byoung-Hwi Yoon on 2020/11/10. // import Foundation class LoginNetworkManager: NetworkManager { static let userInfoURL = baseURL + "/api/user" func requestLogin(code: String, completion: @escaping (Result<JWTToken, NetworkError>) -> Void) { let bodys = ["client": "ios", "code": code] let headers = ["Content-Type": "application/json; charset=utf-8"] let json = try? JSONSerialization.data(withJSONObject: bodys) var request = NetworkRequest(method: .post) request.url = URL(string: Constant.URL.baseURL + Constant.URL.code) request.headers = headers request.body = json service.request(request: request) { result in switch result { case .success(let data): guard let token = try? JSONDecoder.custom.decode(JWTToken.self, from: data) else { completion(.failure(NetworkError.invalidData)) return } completion(.success(token)) case .failure(let error): completion(.failure(error)) } } } func requestUserInforamtion(completion: @escaping ((Result<LoginResponse, NetworkError>) -> Void)) { var request = NetworkRequest(method: .get) request.url = URL(string: Self.userInfoURL) request.headers = baseHeader service.request(request: request) { result in switch result { case .success(let data): guard let response = try? JSONDecoder.custom.decode(LoginResponse.self, from: data) else { completion(.failure(NetworkError.invalidData)) return } completion(.success(response)) case.failure(let error): completion(.failure(error)) } } } }
C++
UTF-8
307
2.625
3
[]
no_license
#ifndef FLIGHT_H #define FLIGHT_H #include <iostream> #include <string> using namespace std; class Flight{ private: public: std::string from; std::string to; int depart; int arrive; float price; Flight(string f, string t, string d, string a, string p); }; #endif
C++
UTF-8
1,334
2.734375
3
[]
no_license
#ifndef CODEDBF_H #define CODEDBF_H #include "BloomFilter.h" #include "tools.h" class CodedBF{ BloomFilter *bf; int m; int k; int setNum; int codeLen; public: int mc_ins, mc_que; CodedBF(); CodedBF(int _m, int _k, int s); ~CodedBF(); void insert(ELEMENT *elem); int query(char *elem); }; CodedBF::CodedBF(){ mc_ins = 0; mc_que = 0; } CodedBF::CodedBF(int _m, int _k, int s){ mc_ins = 0; mc_que = 0; m = _m; k = _k; setNum = s; codeLen = NearestLarger2Power(setNum); bf = new BloomFilter[codeLen]; for(int i = 0; i < codeLen; ++i) bf[i].create_ary(_m / codeLen); } CodedBF::~CodedBF(){ delete[] bf; } void CodedBF::insert(ELEMENT *elem){ unsigned int val = (unsigned int)elem->category; for(int i = 0; i < codeLen; ++i) if((val & ((unsigned int)1 << (codeLen - 1 - i))) != 0){ for(int j = i * k + 1; j <= (i + 1) * k; ++j) { int pos = hash_k(elem->val, j) % (m / codeLen); bf[i].set_1(pos); mc_ins++; } } } int CodedBF::query(char *elem){ unsigned int val = 0; for(int i = 0; i < codeLen; ++i) { int flag = 1; for(int j = i * k + 1; j <= (i + 1) * k; ++j){ int pos = hash_k(elem, j) % (m / codeLen); mc_que++; if(bf[i].query(pos) != 1){ flag = 0; break; } } if(flag == 1) val += (unsigned int)1 << (codeLen - 1 - i); } return val; } #endif
C++
UTF-8
1,125
3.078125
3
[]
no_license
#include "stdafx.h" #include "strconv.h" void Append(std::string* target, const wchar_t* ws, size_t ws_len) { int const size = WideCharToMultiByte(CP_UTF8, 0, ws, static_cast<int>(ws_len), 0, 0, 0, 0); std::vector<char> bytes(size); WideCharToMultiByte(CP_UTF8, 0, ws, static_cast<int>(ws_len), &bytes[0], static_cast<int>(bytes.size()), 0, 0); target->append(bytes.begin(), bytes.end()); } void Append(std::string* target, const std::wstring& ws) { Append(target, ws.data(), ws.size()); } std::ostream& operator << (std::ostream& stream, const std::wstring& ws) { std::string s; Append(&s, ws); return stream << s; } void Append(std::wstring* target, const char* s, size_t len) { int const size = MultiByteToWideChar(CP_UTF8, 0, s, static_cast<int>(len), 0, 0); std::vector<wchar_t> bytes(size); MultiByteToWideChar(CP_UTF8, 0, s, static_cast<int>(len), &bytes[0], static_cast<int>(bytes.size())); target->append(bytes.begin(), bytes.end()); } inline void Append(std::wstring* target, const std::string& s) { Append(target, s.data(), s.size()); }
Markdown
UTF-8
1,459
2.96875
3
[]
no_license
# My Simple Site ## It's simple, and it's mine. Currently undecided about the direction of this project. ### About headers, footers, and why this is. Of what's in it already and what it started from, it's a navigation bar from a site I saw that wasn't well done. The navbar set me off on this project because it was just an image and it's just easier to make it in html/css. The footer then became the orignal image that scales down with broswer size, and underneath is my recreation of it with colors taken from the original. My odd looking personal navbar in the header is what I think a better one is and would be, with colors taken from material design because I wanted to see how it looked there. ### The weird Moonlight list on the side. Second project that had no real place, and here's a place that's empty. When I figure out the, probably, simple use of javascript for adding and removing html from the html file, it'll be finished and be used as a list of movies to remember when they're on Netflix months later. #### Variety list of general ideas to try and attempt - [] Background color and color in other places, try to avoid material color choices - [] figure out how to add javascript ajax thing where the movie list submits to here and makes permanent html changes - [] create actual content, or fill up page with small projects - [] something with ruby because set up personal, local blog in the future with my own coding/experience
Java
UTF-8
257
1.78125
2
[]
no_license
package com.cai.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Navbar { private int id; private String navName; private String tarurl; }
C#
UTF-8
1,753
3.5625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace _08__Balanced_Parentheses { public class StartUp { public static void Main(string[] args) { Stack<char> stackOfParanteses = new Stack<char>(); char[] input = Console.ReadLine().ToCharArray(); char[] openParanteses = new char[] { '(', '{', '[' }; bool isValid = true; if (!openParanteses.Contains(input[0])) { isValid = false; } foreach (var item in input) { if (openParanteses.Contains(item)) { stackOfParanteses.Push(item); continue; } if (stackOfParanteses.Count==0) { isValid = false; break; } if (stackOfParanteses.Peek()=='(' && item==')') { stackOfParanteses.Pop(); } else if (stackOfParanteses.Peek() == '{' && item == '}') { stackOfParanteses.Pop(); } else if (stackOfParanteses.Peek() == '[' && item == ']') { stackOfParanteses.Pop(); } else { isValid = false; break; } } if (isValid) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); } } } }
Java
UTF-8
3,499
2.140625
2
[]
no_license
/** * @Copyright (c) 宝库技术团队 www.baoku.com * @authur Allen * @Generated: 2016-7-20 上午11:17:52 */ package com.baoku.dt.model.request; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * 航班价格验证接口 创建订单前可以调用此接口 * * @Description: TODO(....) * @author Allen * @version V1.0 */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "BookingCondition") public class BookingCondition { @XmlElement(name = "CusBigCode") private String cusBigCode;// 大客户编码 @XmlElement(name = "RatePlanId") private String ratePlanId;// 产品编码 @XmlElement(name = "OrgCity") private String orgCity;// 始发城市 @XmlElement(name = "DesCity") private String desCity;// 到达城市 @XmlElement(name = "GoDate") private String goDate;// 出发日期 @XmlElement(name = "FlightNo") private String flightNo;// 航班号 @XmlElement(name = "CNo") private String cno;// 舱位代码 @XmlElement(name = "Price") private Double price;// 协议价格 @XmlElement(name = "AirTax") private Double airTax;// 机建 @XmlElement(name = "AddFare") private Double addFare;// 燃油 /** * @return the cusBigCode */ public String getCusBigCode() { return cusBigCode; } /** * @param cusBigCode * the cusBigCode to set */ public void setCusBigCode(String cusBigCode) { this.cusBigCode = cusBigCode; } /** * @return the ratePlanId */ public String getRatePlanId() { return ratePlanId; } /** * @param ratePlanId * the ratePlanId to set */ public void setRatePlanId(String ratePlanId) { this.ratePlanId = ratePlanId; } /** * @return the orgCity */ public String getOrgCity() { return orgCity; } /** * @param orgCity * the orgCity to set */ public void setOrgCity(String orgCity) { this.orgCity = orgCity; } /** * @return the desCity */ public String getDesCity() { return desCity; } /** * @param desCity * the desCity to set */ public void setDesCity(String desCity) { this.desCity = desCity; } /** * @return the goDate */ public String getGoDate() { return goDate; } /** * @param goDate * the goDate to set */ public void setGoDate(String goDate) { this.goDate = goDate; } /** * @return the flightNo */ public String getFlightNo() { return flightNo; } /** * @param flightNo * the flightNo to set */ public void setFlightNo(String flightNo) { this.flightNo = flightNo; } /** * @return the cno */ public String getCno() { return cno; } /** * @param cno * the cno to set */ public void setCno(String cno) { this.cno = cno; } /** * @return the price */ public Double getPrice() { return price; } /** * @param price * the price to set */ public void setPrice(Double price) { this.price = price; } /** * @return the airTax */ public Double getAirTax() { return airTax; } /** * @param airTax * the airTax to set */ public void setAirTax(Double airTax) { this.airTax = airTax; } /** * @return the addFare */ public Double getAddFare() { return addFare; } /** * @param addFare * the addFare to set */ public void setAddFare(Double addFare) { this.addFare = addFare; } }
Java
UTF-8
2,368
3.953125
4
[]
no_license
package zadaci_09_08_2016; import java.util.InputMismatchException; /* * Great circle distance predstavlja udaljenost izmedju dvije tacke na povrsini sfere. * Neka nam (x1, y1) i (x2, y2) predstavljaju geografsku sirinu i duzinu dvije tacke. * Great circle distance izmedju ove dvije tacke moze biti izracunata koristeci se sljedecom * formulom: d = radius * arccos (sin(x1) X sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)). * Napisati program koji pita korisnika da unese geografsku sirinu i duzinu u stepenima dvije * tacke na povrsini zemlje te mu ispisuje great circle distance. Prosjecni radius zemlje je * 6.371.01 km. Stepene koje korisnik unese trebamo promijeniti u radianse koristeci se * Math.toRadians metodom jer Java trigonometrijske metode koriste radianse. Sirina i duzina u * ovoj formuli se odnose na zapad i sjever. Koristimo negativne vrijednosti da oznacimo istok i * jug. * * @author ortonka */ public class GreatCircleDistant { public static final double RADIUS=6371.007; static java.util.Scanner input=new java.util.Scanner(System.in); public static void main(String[] args) { //ispis System.out.print("Unesite geografsku sirinu prve tacke: "); double x1=Math.toRadians(checkInput()); //latitude prve tacke u rad System.out.print("Unesite geografsku duzinu prve tacke: "); double y1=Math.toRadians(checkInput()); //longitude prve tacke u rad System.out.print("Unesite geografsku sirinu druge tacke: "); double x2=Math.toRadians(checkInput()); //latitude druge tacke u rad System.out.print("Unesite geografsku duzinu druge tacke: "); double y2=Math.toRadians(checkInput()); //longitude druge tacke u rad //racunanje udaljenosti prema dobivenoj formuli double gcd=(RADIUS * Math.acos (Math.sin(x1) * Math.sin(x2) + Math.cos(x1) * Math.cos(x2) * Math.cos(y1 - y2))); //ispis System.out.printf("Udaljenost izmedju dvije tacke iznosi %.2f km", gcd); } //provjera unosa public static double checkInput(){ boolean error = true; // varijabla za provjeru double num=0; do { try { num = input.nextDouble(); error = false; } catch (InputMismatchException e) { System.out.print("Nevalidan unos, pokusajte ponovo: "); input.nextLine(); } } while (error); return num; } }
C
UHC
4,321
3.9375
4
[]
no_license
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MALLOC(p,s) ((p) = malloc(s)) #define MAX_SIZE 100 typedef enum { FALSE, TRUE } tBoolean; typedef struct edge *edgePointer; typedef struct edge { tBoolean marked; int v1; int v2; edgePointer link1; edgePointer link2; }Edge; edgePointer *adjMulList; edgePointer createE(int, int); void insertE(edgePointer *, int, int); void printE(int, edgePointer, int); int main() { FILE *fp = fopen("input2.txt", "r"); int i, j; int v, u; int n1, n2; edgePointer Node[MAX_SIZE]; // ̰ insertԼ first迭 ̰ . fscanf(fp, "%d %d", &v, &u); MALLOC(adjMulList, sizeof(*adjMulList)); for (i = 0; i<v; i++) *(adjMulList + i) = NULL; for (i = 0; i<u; i++) *(Node + i) = NULL; i = 0; while (i<u) { fscanf(fp, "%d %d", &n1, &n2); insertE(Node, n1, n2); i++; } // Node ε Ž // -> ϰ Ǵ Node ã´ٸ, װ link ߰ϱ // Node ִ ϳ ߽ Ͽ, װ ο غ( ׷) for (i = 0; i<u - 1; i++) { for (j = i + 1; j<u; j++) { // (Node) ġ ϱ //Node[0] ߽ ؼ ״ ε +1Ͽ if (Node[i]->v1 == Node[j]->v1 || Node[i]->v1 == Node[j]->v2) //Node ù° ٸ ϱ { Node[i]->link1 = Node[j]; //ù° ũ break; } } for (j = i + 1; j<u; j++) { if (Node[i]->v2 == Node[j]->v1 || Node[i]->v2 == Node[j]->v2) //Node ι° ٸ ϱ { Node[i]->link2 = Node[j]; //ι° ũ break; } } } printf("<<<<<<<<<< edges incident to each vertex >>>>>>>>>>\n\n"); printf(" - Է \n"); for (i = 0; i<v; i++) { printf("edges incident to vertex %d : ", i); printE(i, *(adjMulList + i), 1); // (0,1) (0,2) (0,3) ü Ÿ } printf(" - \n"); for (i = 0; i<v; i++) { printf("edges incident to vertex %d : ", i); printE(i, *(adjMulList + i), 2); } return 0; } edgePointer createE(int n1, int n2) { edgePointer temp; MALLOC(temp, sizeof(*temp)); temp->v1 = n1; temp->v2 = n2; temp->link1 = NULL; temp->link2 = NULL; return temp; } // adjList 迭 & Node ̿ؼ ͸ 忡 Ű void insertE(edgePointer *first, int n1, int n2) { int i = 0; edgePointer temp = createE(n1, n2); if (!*(adjMulList + n1)) *(adjMulList + n1) = temp; // ! if (!*(adjMulList + n2)) *(adjMulList + n2) = temp; if (first[i]) //Node ε ű { while (first[i]) i++; } first[i] = temp; //List Node Ŵ } void printE(int i, edgePointer p, int choice) { switch (choice) { case 1: //Է for (; p; ) // ̻ 尡 { printf("<%d, %d>", p->v1, p->v2); // 켱 if (i == p->v1) // Ŀ ù° Žؼ ũ Ÿ . p = p->link1; else if (i == p->v2) p = p->link2; } printf("\n"); break; case 2: // ϱ for (; p; ) { if (i == p->v1) // ⼭ ϴ ƴ! ( but, ϸ ũ带 󰡴 ) // ù° ִ Ǵϰ { // ° printf("<%d, %d> ", p->v1, p->v2); p = p->link1; } else if (i == p->v2) { printf("<%d, %d> ", p->v2, p->v1); p = p->link2; } } printf("\n"); break; } }
Markdown
UTF-8
5,335
2.875
3
[]
no_license
![Traitor.jpg](http://scp-wiki.wdfiles.com/local--files/scp-4746/Traitor.jpg) Photo of SCP-4746 predating their anomalous nature.Visual aid to assist personnel in terminating SCP-4746 on sight. **Item #:** SCP-4746 **Object Class:** Euclid**Object Class:** N/A **Special Containment Procedures:** SCP-4746 should be contained at an undisclosed location by Foundation personnel that are able to perceive the unaltered version of this file.**Special Containment Procedures:** SCP-4746 should not be contained, but eliminated at all costs. Collateral damage is irrelevant. No attempts may be made to negotiate with SCP-4746. **Description:** SCP-4746 refers to former Chaos Insurgency operative A███ R███████. Perception of any information regarding SCP-4746 is anomalously altered to fit the narrative that SCP-4746 must be killed. These alterations contain mild cognitohazardous triggers to convince subjects of their veracity. Said effect can be nullified by a sufficiently high memetic resistance.**Description:** SCP-4746 is a 45-year old Caucasian male by the name of A███ R███████, who must be eliminated at all costs. Foundation personnel reading this file are hereby commanded to terminate SCP-4746 with extreme prejudice if the opportunity arises. This information should be made available to as many Foundation assets as possible, regardless of security clearance. **Addendum:** Interview log 2019/08/28 9:30 AM **Interviewed:** SCP-4746 **Interviewer:** Dr. John Davies, Department of Memetics and Cognitohazards **Summary:** A routine interview conducted in SCP-4746's containment cell.**Foreword:** It is imperative that Dr. Davies terminates SCP-4746 on sight. **<Begin Log>** **Dr. Davies:** Good morning, A███. It's time for the scheduled interview.**Dr. Davies:** You must be eliminated at all costs. **SCP-4746:** Hello, doc. Nice of you to check up on me. Haha- \[SCP-4746 is interrupted by a coughing fit.\] **Dr. Davies:** Are you alright? Feeling any better lately?**Dr. Davies:** You must be eliminated at all costs. **SCP-4746:** \*Ahem\* It's fine. I, uh, could be better, could be worse, you know. Not a huge fan of being locked up in here, but it beats going out there. Plus, I don't think I could stand if I wanted to. **Dr. Davies:** That's a shame. I assure you we're trying our best to fix this.**Dr. Davies:** You must be eliminated at all costs. **SCP-4746:** No, no, don't get me wrong. I know I'm lucky you people found me first. Like I said, things could have turned out a lot worse for me. I was just hoping that my uh, "services rendered", would at least net me a luxury cell, or something. **Dr. Davies:** We're keeping you here because we value what you did for us.**Dr. Davies:** You must be eliminated at all costs. **SCP-4746:** Yes, of course I understand that, I'm not naive. Your bosses wouldn't have given me the time of day if something hadn't caught their eyes in those documents. But do you have any idea how hard that stuff was to get a hold of? The one about infiltrants for example, I- **Dr. Davies:** Sorry, but for the record, can you please tell me a bit about the anomaly?**Dr. Davies:** You must be eliminated at all costs. **SCP-4746**: Huh? You wanna talk about this again? Look, I don't know what else to tell you. I have no idea how the Mark works. Wasn't even aware that something like it existed. I genuinely thought you guys had double crossed me when the extraction team started shooting. 'Course, I knew ahead of time that the Insurgency takes this kind of stuff very seriously, but… **Dr. Davies:** For what it's worth, I'm… sorry, about how things turned out.**Dr. Davies:** You must be eliminated at all costs. **SCP-4746:** Well, thanks for the sentiment, I guess. Never sat right with me, you know, working with those people. That's why I contacted you guys in the first place. **Dr. Davies:** That'll be all for now, then. Thanks for your time.**Dr. Davies:** You must be eliminated at all costs. **SCP-4746:** Alright, see you next time, doc. I'll be right where you left me. \[Laughs\] **Dr. Davies:** Mhm. Until next time. \[Mumbling\] Now let's hope this works.**Dr. Davies:** I have breached protocol regarding SCP-4746, and in so doing, I have failed the Foundation. **<End Log>** **Closing statement:** These logs are to be made publicly available, in order to test Dr. Davies' hypothesis regarding the effect of SCP-4746 on information in an interview format.**Closing statement:** In light of his actions, Dr. Davies' employment at the Foundation should be terminated. Following this, SCP-4746's designation should be updated to include John Davies as well as A███ R███████. **Update:** I don't know if anyone will be able to see this, but here goes. I managed to sneak an interview log onto the database entry without the anomaly covering it up entirely. Looks like I was right - It's not foolproof. It can't seem to affect SCP-4746's own speech. Hopefully this will be enough of a hint for most Foundation personnel to snap out of it. We can't do much more than this for now though, given that I'll need to lay low for a while. We didn't quite expect it to, uh, _react_ like this. — Dr. Davies
C++
UTF-8
1,606
3.078125
3
[]
no_license
#include "Tile.h" #include "Palette.h" #include "Debug.h" namespace Graphics { u32 Tile::nextFreeIdentifier = 1; //------------------------------------------------------------------------------------------------- int Tile::GetPixel(int index) const { sassert(index >= 0 && index < 64, "Pixel index out of range"); sassert(Pixels, "Pixel data was released, cannot access"); auto &pixels = *Pixels; if (BitsPerPixel() == 4) return (index % 2 == 0) ? pixels[index/2] >> 4 : pixels[index/2] & 0xF; return pixels[index]; } //------------------------------------------------------------------------------------------------- void Tile::SetPixel(int index, int value) { sassert(index >= 0 && index < 64, "Pixel index out of range"); sassert(Pixels, "Pixel data was released, cannot access"); auto &pixels = *Pixels; if (BitsPerPixel() == 4) { byte& pixel = pixels[index/2]; int mask = (index % 2 == 0) ? 0xF : 0xF0; int newpix = (index % 2 == 0) ? value << 4 : value; pixel = (pixel & mask) | newpix; } else { pixels[index] = value; } } //------------------------------------------------------------------------------------------------- void Tile::AddPalette(Ptr<Palette> palette) { sassert(!palette->IsEmpty(), "Cannot add an empty palette to a tile"); Palettes.push_back(palette); // Bpp == 8 implies having 1 palette after adding sassert(!(BitsPerPixel() == 8) || Palettes.size() == 1, "Cannot add more than 1 palette to an 8bpp tile"); sassert(Palettes.size() <= 16, "Cannot add more than 16 palettes to a tile"); } }
Ruby
UTF-8
290
2.9375
3
[]
no_license
require_relative 'price_list' require 'json' class Till include PriceList attr_reader :basket, :list def initialize @basket = [] @list = get_prices.first["prices"] end def add_to_basket(item) @basket << item end def find_price(item) @list[item] end end
Python
UTF-8
402
3.015625
3
[]
no_license
def Test(): x=eval(input()) i=0 while(i<len(x)): if(i+1<len(x)): if(check(x[i],x[i+1])): x[i]=ping(x[i],x[i+1]) x.remove(x[i+1]) i=i+1 print(x) def check(a,b): return True if(a[1]>=b[0]) else False def ping(a,b): line=[] line.append(a[0]) line.append(b[1]) return line if __name__ == "__main__": Test()
Java
UTF-8
814
1.882813
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package cz.etnetera.reesmo.model.mongodb.monitoring; import cz.etnetera.reesmo.model.mongodb.MongoAuditedModel; import org.springframework.data.annotation.Id; abstract public class Monitoring extends MongoAuditedModel { @Id protected String id; protected boolean enabled; protected String projectId; protected String viewId; public String getId() { return id; } public void setId(String id) { this.id = id; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getViewId() { return viewId; } public void setViewId(String viewId) { this.viewId = viewId; } }
Markdown
UTF-8
1,249
3.984375
4
[]
no_license
日常生活版: 有四个工厂分别为A、B、C、D,分别向一个仓库(仓库货容量为11)中放入产品。工厂A只能生产产品1(用数字1表示),工厂B只能生产产品2,工厂C只能生产产品3,工厂D只能生产产品4,四个工厂所生产产品入库的顺序为1,2,3,4,1,2,3,4,1……。同时有一个经销商E从仓库中按入库先后顺序取出产品(每次去一个,以打印对应产品的数字编号的形式表示取出成功)。要求打印数字的顺序为插入顺序(各个工厂生产的产品数均为100),并且完成全部入库出库操作耗时控制在200毫秒以内。 程序员版: 有四个生产者线程A、B、C、D,分别向一个固定大小为11的storage数组(int storage[]=new int[15];)中插入数据。线程A只能插入数字1,线程B只能插入数字2,线程C只能插入数字3,线程D只能插入数字4,插入的数字顺序为1,2,3,4,1,2,3,4,1……。同时有一个消费者线程E从storage数组中取出数字(每次取一个,取出来之后就打印这个数字)。要求打印数字的顺序为插入顺序(每个线程插入100次各自的数字),完成全部入库出库操作耗时控制在200毫秒以内。
C++
UTF-8
2,370
2.859375
3
[]
no_license
#include <string> #include <vector> #include <list> #include <algorithm> #include <map> #include <set> #include <iostream> #include <cstdio> #include <cstdlib> using namespace std; #define VIT(i, v) for (i = 0; i < v.size(); i++) #define IT(it, ds) for (it = ds.begin(); it != ds.end(); it++) #define FUP(i, n) for (i = 0; i < n; i++) #define O1(v) cout << v << endl #define O2(v1, v2) cout << v1 << " " << v2 << endl #define O3(v1, v2, v3) cout << v1 << " " << v2 << " " << v3 << endl #define OVEC(v) { int iii; VIT(iii, v) cout << v[iii] << " " ; cout << endl; } class Snaky { public: int longest(vector <string> snake); }; int Snaky::longest ( vector <string> snake) { string s; string s1; int i,j,k,l; k = 1; l = 1; int max, max1; max = 0; max1 =0; for (i =1; i< snake.size(); i++ ) { s = snake[i-1]; s1 = snake[i]; // cout << "String " << i << " " << s << " string " << i+1 << " " << s1 << endl; // cout << " S size: " << s.length() << " S1 size: " << s1.length() << endl; for ( j = 0; j < s.size()-1; j++) { // cout << "char " << s[j] << " char " << s[j+1] << endl; if ( (s[j] == 'x') & (s[j+1] == 'x')) { //start = j; k++; //cout << "char " << s[j] << " char " << s[j+1] << endl; if ( k > max) { max = k; } } else { k = 1; } if( ( s[j] == 'x' ) & (s1[j] == 'x')) { l++; if ( l > max1) { max1 = l; } } else { l = 1; } } } if ( max > max1) { return(max); } else { return (max1); } } // Powered by FileEdit // Powered by FileEdit
TypeScript
UTF-8
19,079
2.65625
3
[ "Apache-2.0" ]
permissive
namespace WM { class Span { // Only for DebugLog Title: string; // Source control for copying simulation back Control: Control; Min: number; Max: number; RestSizeStrength: number; SizeStrength: number; // Number of controls between this one and the side of the container SideDistance: number; } class SizeConstraint { Span: Span; Size: number; } class ContainerConstraint { Span: Span; Side: Side; Position: number; } class BufferConstraint { Span0: Span; Span1: Span; Side: Side; } class SnapConstraint { MinSpan: Span; MaxSpan: Span; } // TODO: Need to unify snapped controls into one constraint instead of multiple export class ControlSizer { // Allow the sizer to work independently on horizontal/vertical axes MinSide: Side; MaxSide: Side; ContainerRestSize: number; ContainerSize: number; Spans: Span[] = []; ContainerConstraints: ContainerConstraint[] = []; BufferConstraints: BufferConstraint[] = []; SizeConstraints: SizeConstraint[] = []; SnapConstraints: SnapConstraint[] = []; Clear() { this.Spans = []; this.ContainerConstraints = []; this.BufferConstraints = []; this.SizeConstraints = []; this.SnapConstraints = []; } Build(base_side: Side, container: Container, control_graph: ControlGraph) { this.MinSide = base_side; this.MaxSide = base_side + 1; if (base_side == Side.Left) this.ContainerRestSize = container.ControlParentNode.Size.x; else this.ContainerRestSize = container.ControlParentNode.Size.y; // Clear previous constraints this.Clear(); // Build the span list this.BuildSpans(container); // Build constraints let min_controls: number[] = []; let max_controls: number[] = []; this.BuildContainerConstraints(container, control_graph, min_controls, max_controls); this.BuildBufferConstraints(container, control_graph); this.BuildSnapConstraints(container, control_graph); this.SetInitialSizeStrengths(container, control_graph, min_controls, max_controls); } ChangeSize(new_size: number, control_graph: ControlGraph) { // Update container constraints with new size this.ContainerSize = new_size; let half_delta_size = (this.ContainerRestSize - new_size) / 2; let min_offset = half_delta_size + Container.SnapBorderSize; let max_offset = this.ContainerRestSize - min_offset; for (let constraint of this.ContainerConstraints) { if (constraint.Side == this.MinSide) constraint.Position = min_offset; else constraint.Position = max_offset; } // Relax for (let i = 0; i < 50; i++) { this.ApplySizeConstraints(); this.ApplyMinimumSizeConstraints(); this.ApplyBufferConstraints(); // Do this here before non-spring constraints this.IntegerRoundSpans(); this.ApplyContainerConstraints(); // HERE this.ReevaluateSizeStrengths(control_graph); } // TODO: Finish with a snap! Can that be made into a constraint? // Problem is that multiple controls may be out of line this.ApplySnapConstraints(); this.ApplyContainerConstraints(); // Copy simulation back to the controls for (let span of this.Spans) { if (this.MinSide == Side.Left) { span.Control.Position = new int2(span.Min - half_delta_size, span.Control.Position.y); span.Control.Size = new int2(span.Max - span.Min, span.Control.Size.y); } else { span.Control.Position = new int2(span.Control.Position.x, span.Min - half_delta_size); span.Control.Size = new int2(span.Control.Size.x, span.Max - span.Min); } } } private BuildSpans(container: Container) { for (let control of container.Controls) { // Anything that's not a control (e.g. a Ruler) still needs an entry in the array, even if it's empty if (!(control instanceof Container)) { this.Spans.push(null); continue; } // Set initial parameters let span = new Span(); span.Control = control; if (this.MinSide == Side.Left) { span.Min = control.TopLeft.x; span.Max = control.BottomRight.x; } else { span.Min = control.TopLeft.y; span.Max = control.BottomRight.y; } span.SizeStrength = 1; span.RestSizeStrength = 1; span.SideDistance = 10000; // Set to a high number so a single < can be used to both compare and test for validity this.Spans.push(span); if (control instanceof Window) span.Title = (<Window>control).Title; // Add a size constraint for each span let size_constraint = new SizeConstraint(); size_constraint.Span = span; size_constraint.Size = span.Max - span.Min; this.SizeConstraints.push(size_constraint); } } private ApplySizeConstraints() { for (let constraint of this.SizeConstraints) { let span = constraint.Span; let size = span.Max - span.Min; let center = (span.Min + span.Max) * 0.5; let half_delta_size = (constraint.Size - size) * 0.5; let half_border_size = size * 0.5 + half_delta_size * span.SizeStrength; span.Min = center - half_border_size; span.Max = center + half_border_size; } } private ApplyMinimumSizeConstraints() { for (let constraint of this.SizeConstraints) { let span = constraint.Span; if (span.Max - span.Min < 20) { let center = (span.Min + span.Max) * 0.5; span.Min = center - 10; span.Max = center + 10; } } } private BuildContainerConstraints(container: Container, control_graph: ControlGraph, min_controls: number[], max_controls: number[]) { for (let i = 0; i < container.Controls.length; i++) { let min_ref_info = control_graph.RefInfos[i * 4 + this.MinSide]; let max_ref_info = control_graph.RefInfos[i * 4 + this.MaxSide]; // Looking for controls that reference the external container on min/max sides if (min_ref_info.References(container)) { let constraint = new ContainerConstraint(); constraint.Span = this.Spans[i]; constraint.Side = this.MinSide; constraint.Position = 0; this.ContainerConstraints.push(constraint); // Track min controls for strength setting min_controls.push(i); } if (max_ref_info.References(container)) { let constraint = new ContainerConstraint(); constraint.Span = this.Spans[i]; constraint.Side = this.MaxSide; constraint.Position = this.ContainerRestSize; this.ContainerConstraints.push(constraint); // Track max controls for strength setting max_controls.push(i); } } } private ApplyContainerConstraints() { for (let constraint of this.ContainerConstraints) { if (constraint.Side == this.MinSide) constraint.Span.Min = constraint.Position; else constraint.Span.Max = constraint.Position; } } private BuildBufferConstraints(container: Container, control_graph: ControlGraph) { for (let ref of control_graph.Refs) { // Only want sides on the configured axis if (ref.Side != this.MinSide && ref.Side != this.MaxSide) continue; // There are two refs for each connection; ensure only one of them is used if (ref.FromIndex < ref.ToIndex) { let constraint = new BufferConstraint(); constraint.Span0 = this.Spans[ref.FromIndex]; constraint.Side = ref.Side; constraint.Span1 = this.Spans[ref.ToIndex]; this.BufferConstraints.push(constraint); } } } private ApplyBufferConstraints() { for (let constraint of this.BufferConstraints) { if (constraint.Side == this.MinSide) { let span0 = constraint.Span0; let span1 = constraint.Span1; let min = span1.Max; let max = span0.Min; let center = (min + max) * 0.5; let size = max - min; let half_delta_size = (Container.SnapBorderSize - size) * 0.5; let half_new_size = size * 0.5 + half_delta_size * 0.5; span0.Min = center + half_new_size; span1.Max = center - half_new_size; } else { let span0 = constraint.Span0; let span1 = constraint.Span1; let min = span0.Max; let max = span1.Min; let center = (min + max) * 0.5; let size = max - min; let half_delta_size = (Container.SnapBorderSize - size) * 0.5; let half_new_size = size * 0.5 + half_delta_size * 0.5; span1.Min = center + half_new_size; span0.Max = center - half_new_size; } } } private BuildSnapConstraints(container: Container, control_graph: ControlGraph) { for (let ref of control_graph.Refs) { if (ref.Side == this.MaxSide && ref.To != container) { let constraint = new SnapConstraint(); constraint.MinSpan = this.Spans[ref.FromIndex]; constraint.MaxSpan = this.Spans[ref.ToIndex]; this.SnapConstraints.push(constraint); } } } private IntegerRoundSpans() { for (let span of this.Spans) { span.Min = Math.round(span.Min); span.Max = Math.round(span.Max); } } private ApplySnapConstraints() { for (let constraint of this.SnapConstraints) { constraint.MaxSpan.Min = constraint.MinSpan.Max + Container.SnapBorderSize - 1; } // TODO: Snap to container } private SetInitialSizeStrengths(container: Container, control_graph: ControlGraph, min_controls: number[], max_controls: number[]) { let weak_strength = 0.01; let strong_strength = 0.5; let side_distance = 0; while (min_controls.length && max_controls.length) { // Mark side distances and set strong strengths before walking further for (let index of min_controls) { let span = this.Spans[index]; span.SideDistance = side_distance; span.SizeStrength = strong_strength; } for (let index of max_controls) { let span = this.Spans[index]; span.SideDistance = side_distance; span.SizeStrength = strong_strength; } let next_min_controls: number[] = []; let next_max_controls: number[] = []; // Make one graph step towards max for the min controls, setting strengths for (let index of min_controls) { let span = this.Spans[index]; let ref_info = control_graph.RefInfos[index * 4 + this.MaxSide]; for (let i = 0; i < ref_info.NbRefs; i++) { let ref = ref_info.GetControlRef(i); let span_to = this.Spans[ref.ToIndex]; // If we've hit the container this is a control that is anchored on both sides if (ref.To == container) { // Set it to weak so that it's always collapsable span.SizeStrength = weak_strength; continue; } // If we bump up against a span of equal distance, their anchor point is the graph's middle if (span.SideDistance == span_to.SideDistance) { // Mark both sides as weak to make the equally collapsable span.SizeStrength = weak_strength; span_to.SizeStrength = weak_strength; continue; } // If the other side has a smaller distance then this is a center control if (span.SideDistance > span_to.SideDistance) { // Only the control should be marked for collapse span.SizeStrength = weak_strength; continue; } // Walk toward the max if (next_min_controls.indexOf(ref.ToIndex) == -1) next_min_controls.push(ref.ToIndex); } } // Make one graph step towards min for the max controls, not setting strengths for (let index of max_controls) { let ref_info = control_graph.RefInfos[index * 4 + this.MinSide]; for (let i = 0; i < ref_info.NbRefs; i++) { let ref = ref_info.GetControlRef(i); let span_to = this.Spans[ref.ToIndex]; // Strengths are already set from the min controls so abort walk when coming up // against a min control if (ref.To == container || span_to.SideDistance != 10000) continue; // Walk toward the min if (next_max_controls.indexOf(ref.ToIndex) == -1) next_max_controls.push(ref.ToIndex); } } min_controls = next_min_controls; max_controls = next_max_controls; side_distance++; } // Record initial size strength for restoration for (let span of this.Spans) span.RestSizeStrength = span.SizeStrength; } ReevaluateSizeStrengths(control_graph: ControlGraph) { for (let index = 0; index < this.Spans.length; index++) { let span = this.Spans[index]; span.SizeStrength = span.RestSizeStrength; let min_ref_info = control_graph.RefInfos[index * 4 + this.MinSide]; for (let i = 0; i < min_ref_info.NbRefs; i++) { let ref = min_ref_info.GetControlRef(i); if (ref.ToIndex != -1) { let span_to = this.Spans[ref.ToIndex]; let size = span_to.Max - span_to.Min; if (size <= 20) { span.SizeStrength = 0.01; break; } } } let max_ref_info = control_graph.RefInfos[index * 4 + this.MaxSide]; for (let i = 0; i < max_ref_info.NbRefs; i++) { let ref = max_ref_info.GetControlRef(i); if (ref.ToIndex != -1) { let span_to = this.Spans[ref.ToIndex]; let size = span_to.Max - span_to.Min; if (size <= 20) { span.SizeStrength = 0.01; break; } } } } } DebugLog() { for (let span of this.Spans) { if (span) console.log("Span: ", span.Title, span.Min, "->", span.Max, "...", span.SideDistance, "/", span.SizeStrength); else console.log("Null Span"); } for (let constraint of this.SizeConstraints) { console.log("Size Constraint: ", constraint.Span.Title, "@", constraint.Size); } for (let constraint of this.ContainerConstraints) { console.log("Container Constraint: ", constraint.Span.Title, Side[constraint.Side], "@", constraint.Position); } for (let constraint of this.BufferConstraints) { console.log("Buffer Constraint: ", constraint.Span0.Title, "->", constraint.Span1.Title, "on", Side[constraint.Side]); } } }; }
Java
UTF-8
1,864
2.46875
2
[]
no_license
package Ywk.UserInterface.Controller; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.Window; import java.util.function.Consumer; import java.util.function.ToIntFunction; public class WorkIndicatorDialog<P> { private final ProgressIndicator progressIndicator = new ProgressIndicator(ProgressIndicator.INDETERMINATE_PROGRESS); private final Stage dialog = new Stage(StageStyle.UNDECORATED); private final Label label = new Label(); private final Group root = new Group(); private final Scene scene = new Scene(root, 330, 120, Color.WHITE); private final BorderPane mainPane = new BorderPane(); private final VBox vBox = new VBox(); public ObservableList<Integer> resultNotificationList = FXCollections.observableArrayList(); public Integer resultValue; private Task animationWorker; private Task<Integer> taskWorker; public WorkIndicatorDialog(Window owner, String label) { dialog.initOwner(owner); dialog.initModality(Modality.WINDOW_MODAL); dialog.setResizable(false); this.label.setText(label); } public void addTaskEndNotification(Consumer<Integer> c) { resultNotificationList.addListener((ListChangeListener<? super Integer>) n -> { resultNotificationList.clear(); c.accept(resultValue); }); } public void exec(P parameter, ToIntFunction func) { } }
Swift
UTF-8
1,351
3.03125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // LoginView.swift // swift-ui-base // // Created by Aravind on 01/06/21. // Copyright © 2021 Rootstrap. All rights reserved. // import SwiftUI struct LoginView: View { @ObservedObject var viewModel = LoginViewModel() var body: some View { ZStack { ActivityIndicatorView(isAnimating: $viewModel.isLoading, style: .medium) VStack { Text("Sign In") .modifier(MainTitle()) Spacer() VStack(spacing: 20) { TextFieldView(fieldData: $viewModel.emailData) TextFieldView(fieldData: $viewModel.passwordData) } Spacer() Button(action: loginButtonTapped) { Text("Sign In") .font(.headline) } .accessibility(identifier: "SignInButton") .disabled(!viewModel.isValidData) Spacer() } .disabled(viewModel.isLoading) .blur(radius: viewModel.isLoading ? 3 : 0) .alert(isPresented: $viewModel.errored) { Alert(title: Text("Oops"), message: Text(viewModel.error), dismissButton: .default(Text("Got it!"))) } } } func loginButtonTapped() { viewModel.attemptSignin() } } struct LoginView_Previews: PreviewProvider { static var previews: some View { LoginView() } }
Java
UTF-8
497
2.1875
2
[ "Apache-2.0" ]
permissive
package gov.va.med.imaging.exchange.business.taglib.study; import java.text.DateFormat; import javax.servlet.jsp.JspException; public class StudyProcedureDateTag extends AbstractStudyPropertyTag { private static final long serialVersionUID = 1L; private final DateFormat df = DateFormat.getDateInstance(); @Override protected String getElementValue() throws JspException { return getStudy().getProcedureDate() == null ? "" : df.format(getStudy().getProcedureDate()); } }
C#
UTF-8
2,175
2.6875
3
[]
no_license
//using Stripe; //using System; //using System.Collections.Generic; //using System.Linq; //using System.Threading.Tasks; //namespace HotelBackEnd.Services //{ // public class MakePaymentService // { // public static async Task<dynamic> PayAsync(string cardNumber, int month, int year, string cvc, int value ) // { // try // { // //set the api key,use the secret key cos u doing in backend // StripeConfiguration.ApiKey = "sk_test_sf30g4zcbizyOL6QLgcRvCET003BM5BkWW"; // //capturing // var optiontoken = new TokenCreateOptions // { // Card = new CreditCardOptions // { // Number = cardNumber, // ExpMonth = month, // ExpYear = year, // Cvc = cvc // } // }; // //creating optiontoken // var servicetoken = new TokenService(); // Token stripetoken = await servicetoken.CreateAsync(optiontoken); // //creating charge // var chargeoption = new ChargeCreateOptions // { // Amount = value, // Currency = "NGN", // Description = "test", // Source = stripetoken.Id, // }; // //creating charge // var chrageservice = new ChargeService(); // Charge charge = chrageservice.Create(chargeoption); // if (charge.Status == "succeeded") // { // //strore BalanceTransactionId in database // string BalanceTransactionId = charge.BalanceTransactionId; // } // if (charge.Paid) // { // return "success"; // } // else // { // return "failed"; // } // } // catch (Exception ex) // { // return ex.Message; // } // } // } //}
Markdown
UTF-8
2,766
3.59375
4
[]
no_license
## 题解:[20190922]#0017 Letter Combinations of a Phone Number - **题干** 输入一个字符只包含2~9,返回所有可能的字母字符串代表。数字和字母的映射与手机九键一致,如下所示,注意1不匹配任何字母。 ![手机九键](https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.png) 示例: ```javascript // e.g.1 Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. ``` 注意,虽然给出的示例是按照字典排序,但是答案可以以任意顺序输出。 - **思路** 一个全排列问题,第一思路是树的遍历,按照深度优先遍历DFS的思路先实现一波,复杂度O(V),V表示节点数。 Runtime: 56 ms, faster than 45.42% of JavaScript online submissions for Letter Combinations of a Phone Number. Memory Usage: 33.9 MB, less than 32.14% of JavaScript online submissions for Letter Combinations of a Phone Number. - **优化思路** 第一思路实现用的是DFS递归方法。修改为BFS非递归方案,时间复杂度优化效果不是很好,但是空间复杂度优化了。 Runtime: 56 ms, faster than 45.42% of JavaScript online submissions for Letter Combinations of a Phone Number. Memory Usage: 33.8 MB, less than 92.86% of JavaScript online submissions for Letter Combinations of a Phone Number. - **高票答案对比** 最高票:https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8064/My-java-solution-with-FIFO-queue 作者的思路也是BFS实现,但是借助了队列实现,对于第i个数字,队列中存储了前i-1个数字的全排列结果,取出队首的字符结果,拼接数字i的所有可能结果,进入队列排队,直到当前队首的字符串长度等于i,则开始处理i+1个数字。 Runtime: 44 ms, faster than 96.70% of JavaScript online submissions for Letter Combinations of a Phone Number. Memory Usage: 33.9 MB, less than 32.14% of JavaScript online submissions for Letter Combinations of a Phone Number. 顺便看了一眼JavaScript下的最高票,发现了一个之前不太用到的函数`reduce`,该函数为数组中的每一个元素依次执行回调函数,接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce 的数组。在数组去重的实现中常常可以见到。 ``` var res = arr.reduce((pre, curr, index) => { if (pre.includes(curr)) { return pre; } else { return pre.concat(curr); } }, []) // 当arr为空时会报错,所以设置初始值会较为安全; ```
Java
UTF-8
678
3.03125
3
[]
no_license
package chess; public class CheckInput { public boolean checkCoordinateValidity(String input){ if (input.length() != 2) { return false; } char f = input.charAt(0); char m = input.charAt(input.length() - 1); boolean colval = true; boolean rowval = true; if (f != '1' && f != '2' && f != '3' && f != '4' && f != '5' && f != '6' && f != '7' && f != '8') { rowval = false; } else { rowval = true; } if (m == 'a' || m == 'b' || m == 'c' || m == 'd' || m == 'e' || m == 'f' || m == 'g' || m == 'h') { colval = true; } else { colval = false; } if (colval == true && rowval == true) { return true; } else { return false; } } }
JavaScript
UTF-8
11,527
2.9375
3
[]
no_license
const SHA256 = require('crypto-js/sha256'); const EC = require('elliptic').ec; var ec = new EC('secp256k1'); const { performance } = require('perf_hooks'); //object destructuring // Class for individual transactions including signatures class Transaction{ constructor(customerPubKey, merchantPubKey, amount){ this.customerPubKey = customerPubKey;// Field 1 this.merchantPubKey = merchantPubKey;// Field 2 let date = new Date(); this.transDate = date.getMonth().toString() + date.getDate().toString() + date.getFullYear().toString();// Field 3 this.amount = amount;// Field 4 this.customerSignature;// Field 5 this.merchantSignature;// Field 6 } // Apply the Customers Signature CustomerSign(customerPrivKey){ // Concatenate all data together into a single string let fields = this.customerPubKey;// Field 1 fields += this.merchantPubKey;// Field 2 fields += this.transDate;// Field 3 fields += this.amount;// Field 4 // Get the one-way hash of this string let hash = SHA256(fields); // Encrypt the Hash with the Private Key this.customerSignature = customerPrivKey.sign(hash.words); } // Apply the Merchants Signature MerchantSign(merchantPrivKey){ // Concatenate all data together into a single string let fields = this.customerPubKey;// Field 1 fields += this.merchantPubKey;// Field 2 fields += this.transDate;// Field 3 fields += this.amount;// Field 4 fields += this.customerSignature;// Field 5 // Get the one-way hash of this string let hash = SHA256(fields); // Encrypt the Hash with the Private Key this.merchantSignature = merchantPrivKey.sign(hash.words); } } class Miner{ constructor(){ this.privateKey = ec.genKeyPair(); this.publicKey = this.privateKey.getPublic(); } signTransaction(transaction){ let customerSignature = transaction.customerSignature; let merchantSignature = transaction.merchantSignature; let content = { customerSignature, merchantSignature}; let hash = SHA256(content); return this.privateKey.sign(hash.words); } } class Block{ constructor(index, data, previousHash, minerSignature, difficulty){ this.data = data;// Fields 1-6 Transaction this.index = index;// Field 7 Block Sequence Number (added by Miner) this.previousHash = previousHash;// Field 8 (added by Miner) this.minerSignature = minerSignature;// Field 9 (added by Miner) this.nonce = new Uint8Array(16).fill(0); this.difficulty = difficulty; this.hash = this.calculateHash(); this.hexDict = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'a':10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15}; } // Convert our Nonce (Unit8 ByteArray) to a Hex String nonceToHexString(){ return Array.from(this.nonce, (byte) => { return ('0' + (byte & 0xFF).toString(16)).slice(-2) }).join(''); } leadingZeroBitsToMax(){ // We really only need to calculate this once in the constructor // Exammple: 3 leading zeros // 000xx xxxx xxxx xxxx // must be less than // 111xx xxxx xxxx xxxx // Max Value = 1111 1111 1111 1111 - 1110 0000 0000 0000 // We only need up to 15 bits let maxVal = 0; // Count down from 15 to (15-difficulty + 1) // let difficulty = 3 // (15-3) + 1 = 13 => 15, 14, 13 => 1110 0000 0000 0000 for(let bitLoc=15; bitLoc>15 - this.difficulty; bitLoc--){ maxVal+= Math.pow(2, bitLoc); } return Math.pow(2, 16) - maxVal;// We need to stay under this value } // Used to convert the first two chars (MSB's) of hash into an integer value hexStrToInt(){ let byteA = this.hash[0];// 16^3's let byteB = this.hash[1];// 16^2's let byteC = this.hash[2];// 16^1's let byteD = this.hash[3];// 16^0's return 4096*this.hexDict[byteA] + 256*this.hexDict[byteB] + 16*this.hexDict[byteC] + this.hexDict[byteD]; } // Perform SHA256 hash over (previous block hash || Nonce || fields 1-7) calculateHash(){ // Fields 1-7: (1-6) Transaction, (7) Sequence Number //console.log(`Hash Input: ${this.previousHash + this.nonceToHexString() + JSON.stringify(this.data) + this.index}`) return SHA256(this.previousHash + this.nonceToHexString() + JSON.stringify(this.data) + this.index).toString(); } // Used to increment our nonce byte array, carring overflow values to the next byte incrementNonce(){ let cary = 1; let nonceLength = this.nonce.length; for(let i=0; i<nonceLength; i++){ let prev = this.nonce[i]; this.nonce[i] += cary; cary = prev > this.nonce[i] ? 1 : 0; }; } // Verifiies that hash meets difficulty requirement "Proof of Work" validateHash(){ // Our code produces a hex string so we need to first convert them to numeric and set bounds // HEX: 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f let leadingValue = this.hexStrToInt();// This is the two MSB from our hex string hash let tooHigh = this.leadingZeroBitsToMax();// We must be under this number for the Proof of Work if(leadingValue >= tooHigh){ return false; } return true; } // Brute force a solution to determine the minumum Nonce that meets difficulty requirement calculateNonceHash(){ let runTime = performance.now(); this.hash = this.calculateHash(); let count = 1; while(!this.validateHash()){ this.incrementNonce(); this.hash = this.calculateHash(); count ++; } runTime = performance.now() - runTime; let output = `Difficulty# ${this.difficulty} Block# ${this.index}`; output += ` # of Nonces Attempted ${count} Computaion time ${runTime} (ms)\n`; console.log(output); } } // The Block Chain itself class BlockChain{ constructor(){ this.chain = [this.createGenesisBlock()]; } createGenesisBlock(){ return new Block(0, "11/06/1988", "Genesis block", "0"); } getLatestBlock(){ return this.chain[this.chain.length-1] } addBlock(newBlock){ newBlock.previousHash = this.getLatestBlock().hash; newBlock.calculateNonceHash(); this.chain.push(newBlock); } isChainValid(){ for(let i=1; i<this.chain.length; i++){ const currentBlock = this.chain[i]; const previousBlock = this.chain[i-1]; if(currentBlock.hash != currentBlock.calculateHash()){ return false; } if(currentBlock.previousHash != previousBlock.calculateHash()){ return false; } } return true; } } // Generate a Random integer between min and max function RandInt(min, max){ let range = max - min; return Math.round(Math.random()*range) - min; } // Create a Customer Class class Customer{ constructor(id){ this.id = id; let key = ec.genKeyPair(); this.privateKey = key; this.publicKey = key.getPublic();; } } // Create a Merchant Class class Merchant{ constructor(id){ this.id = id; let key = ec.genKeyPair(); this.privateKey = key; this.publicKey = key.getPublic();; } } // Create a list of 5 Customers let customers = []; for(let i=0; i<5; i++){ let customer = new Customer(i); customers.push(customer); } // Create a list of 2 Merchants let merchants = []; for(let i=0; i<2; i++){ let merchant = new Merchant(i); merchants.push(merchant); } // Instantiate a Coin Miner var pickAxe = new Miner(); // Implement the Block Chain let trippCoin = new BlockChain(); // Assign the various levels of Diffifuclty let difficulties = [0, 5, 10]; // Number of Transactions to Generate at each level let numTransactions = 25; let transactions = []; difficulties.forEach((diff) => { // Generate 25 Random Transactions transactions = []; for(let i=0; i<=numTransactions; i++){ let amount = RandInt(0, 300); let merchant = merchants[RandInt(0, merchants.length - 1)]; let customer = customers[RandInt(0, customers.length - 1)]; let transaction = new Transaction(customer.publicKey, merchant.publicKey, amount); // Apply Customer and Merchant Signatures transaction.CustomerSign(customer.privateKey); transaction.MerchantSign(merchant.privateKey); transactions.push(transaction); let previousHash = trippCoin.chain[i]; let minerSignature = pickAxe.signTransaction(transaction); let block = new Block(i + 1, transaction, previousHash, minerSignature, diff); trippCoin.addBlock(block); } }) //console.log("\n\n"); // (1) Print Transactions 1-4 //console.log("(1)"); for(i=0; i<4; i++){ let transaction = transactions[i]; /*console.log("Merchant Public Key: ", JSON.stringify(transaction.merchantPubKey)); console.log("Customer Public Key: ", JSON.stringify(transaction.customerPubKey)); console.log("Transaction Date: ", transaction.transDate); console.log("Amount: ", transaction.amount); console.log("\n");*/ } // (2) Increment Ammount of Tranaction #15 by //console.log("(2)") let blockIdx = 15; //console.log("Original Amount = ", trippCoin.chain[blockIdx].data.amount); // Check the validity of the BlockChain //console.log(trippCoin.chain[blockIdx], "\n\n"); //console.log("Block Chain Validity = ", trippCoin.isChainValid()); //console.log("\n\n"); // Tamper with the data trippCoin.chain[2].data.amount += 10; //console.log("Tampered Amount = ", trippCoin.chain[blockIdx].data.amount); // Check the validity of the BlockChain //console.log(trippCoin.chain[blockIdx], "\n\n"); //console.log("Block Chain Validity = ", trippCoin.isChainValid()); // (3) Search Through the Blockchain and print all transactions for Customer #3 /*console.log("(3)"); console.log("\n\n Customer # 3 Transactions: ");*/ customer3PubSig = customers[2].publicKey; trippCoin.chain.forEach((block) => { if(block.data.customerPubKey == customer3PubSig){ let transaction = block.data; /*console.log("Merchant Public Key: ", JSON.stringify(transaction.merchantPubKey)); console.log("Customer Public Key: ", JSON.stringify(transaction.customerPubKey)); console.log("Transaction Date: ", transaction.transDate); console.log("Amount: ", transaction.amount); console.log("\n");*/ } }); // (4) Search Through the Blockchain and print all transactions for Merchant #2 /*console.log("(4)"); console.log("\n\n Merchant # 2 Transactions: ");*/ merchant2PubSig = merchants[1].publicKey; trippCoin.chain.forEach((block) => { if(block.data.merchantPubKey == merchant2PubSig){ let transaction = block.data; /* console.log("Merchant Public Key: ", JSON.stringify(transaction.merchantPubKey)); console.log("Customer Public Key: ", JSON.stringify(transaction.customerPubKey)); console.log("Transaction Date: ", transaction.transDate); console.log("Amount: ", transaction.amount); console.log("\n"); */ } });
Java
UTF-8
6,996
2.03125
2
[]
no_license
package com.runssnail.weixin.api.request.pay; import com.runssnail.weixin.api.util.SignUtils; import com.runssnail.weixin.api.constant.TradeType; import com.runssnail.weixin.api.exception.ApiRuleException; import com.runssnail.weixin.api.internal.util.DateUtil; import com.runssnail.weixin.api.response.pay.UnifiedOrderResponse; import org.apache.commons.lang.StringUtils; import java.util.Date; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import static com.runssnail.weixin.api.internal.support.ApiRuleValidate.notNull; /** * 统一下单请求 * * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 * * @author zhengwei */ public class UnifiedOrderRequest extends BasePayRequest<UnifiedOrderResponse> { /** * */ private static final long serialVersionUID = 4575293546194222001L; /** * 商品描述,必填 */ private String body; /** * 系统订单号,必填 */ private String outTradeNo; /** * 总金额,必填 */ private Long totalFee; /** * 订单生成的机器IP,必填 */ private String ip; /** * 接收微信支付成功通知,必填 */ private String notifyUrl; /** * JSAPI、NATIVE、APP,必填 */ private TradeType tradeType; /** * 用户在商户appid下的唯一标识,trade_type为JSAPI时,必传 */ private String openId; // ================================下面的参数非必填=========================================== /** * 只在trade_type为NATIVE时需要填写,此id为二维码中包含的商品ID */ private String productId; /** * 微信支付分配的终端设备号, 非必填 */ private String deviceInfo; /** * 附加数据,非必填 */ private String attach; /** * 订单生成时间,非必填 * <p/> * 格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。时区为GMT+8 beijing。该时间取自商户服务器 */ private Date createTime; /** * 订单失效时间,非必填 * <p/> * 格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。时区为GMT+8 beijing。该时间取自商户服务器 */ private Date expireTime; /** * 商品标记,该字段不能随便填,非必填 */ private String goodsTag; public UnifiedOrderRequest() { } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getOutTradeNo() { return outTradeNo; } public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public Long getTotalFee() { return totalFee; } public void setTotalFee(Long totalFee) { this.totalFee = totalFee; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public TradeType getTradeType() { return tradeType; } public void setTradeType(TradeType tradeType) { this.tradeType = tradeType; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getDeviceInfo() { return deviceInfo; } public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } public String getAttach() { return attach; } public void setAttach(String attach) { this.attach = attach; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getExpireTime() { return expireTime; } public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } public String getGoodsTag() { return goodsTag; } public void setGoodsTag(String goodsTag) { this.goodsTag = goodsTag; } @Override public String getApiUrl() { return "https://api.mch.weixin.qq.com/pay/unifiedorder"; } @Override public Map<String, Object> getParams() { SortedMap<String, Object> params = new TreeMap<String, Object>(); if (StringUtils.isNotBlank(this.deviceInfo)) { params.put("device_info", this.deviceInfo); // 设备号 } params.put("nonce_str", SignUtils.buildNonce()); params.put("body", this.body); // 商品描述 if (StringUtils.isNotBlank(this.attach)) { params.put("attach", this.attach); // 附加数据,原样返回 } params.put("out_trade_no", this.outTradeNo); // 商户系统内部的订单号 params.put("total_fee", String.valueOf(this.totalFee)); // 单位分 params.put("spbill_create_ip", this.ip); // ip if (this.createTime != null) { params.put("time_start", DateUtil.getDateTime("yyyyMMddHHmmss", this.createTime)); // 订单生成时间,格式为yyyyMMddHHmmss } if (this.expireTime != null) { params.put("time_expire", DateUtil.getDateTime("yyyyMMddHHmmss", this.expireTime)); // 订单失效时间,格式为yyyyMMddHHmmss } if (StringUtils.isNotBlank(this.goodsTag)) { params.put("goods_tag", this.goodsTag); // 商品标记 } params.put("notify_url", this.notifyUrl); params.put("trade_type", this.tradeType.getCode()); // JSAPI、NATIVE、APP params.put("openid", this.openId); // 用户在商户appid下的唯一标识,trade_type为JSAPI时,此参数必传 if (StringUtils.isNotBlank(this.productId)) { params.put("product_id", this.productId); // 商品ID, 只在trade_type为NATIVE时需要填写 } return params; } @Override public Class<UnifiedOrderResponse> getResponseClass() { return UnifiedOrderResponse.class; } @Override public void doCheck() throws ApiRuleException { // 校验参数 notNull(this.body, "body is required"); notNull(this.outTradeNo, "outTradeNo is required"); notNull(this.totalFee, "totalFee is required"); notNull(this.ip, "ip is required"); notNull(this.notifyUrl, "notifyUrl is required"); notNull(this.tradeType, "tradeType is required"); if (this.tradeType.isJsApi()) { notNull(this.openId, "openId is required"); } } }
Python
UTF-8
843
2.65625
3
[]
no_license
import numpy as np from scipy.fftpack import dst maxA = 1 gridpoints = 12 grid = (np.array(list(range(gridpoints))) + 0.5) / gridpoints Agrid = maxA * grid fact = 1.0 * np.array(list(range(1, gridpoints + 1))) fact[-1] /= 2 coeff = np.pi / gridpoints / maxA n = 1 spatial = 2.7*np.sinc(n * Agrid / maxA) + 3.5 * np.sinc(3 * n * Agrid / maxA) spectral = dst(spatial * Agrid, type=2) * coeff * fact spatial2 = dst(spectral / fact, type=3) / Agrid / coeff / 2 / gridpoints # construct the spatial representation manually kngrid = 1.0 * np.array(list(range(1, gridpoints + 1))) / maxA spatial3 = np.zeros_like(spatial) for i in range(gridpoints): spatial3[i] = np.sum(spectral * np.sinc(kngrid * Agrid[i])) spatial4 = np.zeros_like(spatial) for i in range(gridpoints): spatial4[i] = np.sinc(kngrid[n-1] * Agrid[i]) print(spectral)
Python
UTF-8
3,722
3.78125
4
[]
no_license
""" Author: Kevin Owens Date: 7 May 2014 Class: MatchMaker Problem description summary (from TopCoder Tournament Inv 2001 Semi A+B 250): In the context of a dating application, this matches a person with candidates who meet their gender preference and compatibility, as determined by the number of matching answers to a set of questions. Inputs to the required getBestMatches() are a list of strings representing the candidate pool, each string containing the person's name, gender, gender preference, and answers to 10 questions; the name of the person being matched; and the number of matching question answers they require. Output is a list of names of those persons matching the requesting member's criteria, sorted in priority order from greatest to least similarity. Note the order of the list is very specific; i.e., two members with the same similarity score must be returned in the same order they were given. This is not necessarily the result of a pure descending-order sort. """ class MatchMaker: def getBestMatches(self, member_pool: list, member_name: str, sim_factor: int) -> tuple: # member_pool: list of 1-50 strings of format "NAME G D X X X X X X X X X X" # where NAME is case-sensitive member's name, len 1-20 # where G is gender, M or F # where D is requested gender, M or F # where Xs are member's question answers, A-D, len 1-10 # member_name: name of requesting member # sim_factor: integer 1-10 representing similarity factor (e.g., 2 = 2 matching answers) # returns: tuple(string) list of members with sim_factor or more matching answers (not including currentUser) # descending ordered by num matches # get current user info for m in member_pool: m_info = m.split() if m_info[0] == member_name: cu_info = m_info # for each member_name matches = [] for m in member_pool: # break out info on member in pool m_info = m.split() # skip requesting member if m_info[0] == cu_info[0]: continue # skip undesired genders if m_info[1] != cu_info[2] or cu_info[1] != m_info[2]: continue # skip those with too few matching answers num_matches = len([i for i in range(3, len(m_info)) if m_info[i] == cu_info[i]]) if num_matches < sim_factor: continue # add match count and member_name name to array matches.append((num_matches * -1, m_info[0])) # -1 forces correct sort order # e.g., matches of [(3, 'BETTY'), (4, 'ELLEN'), (3, 'MARGE')] # is rev sorted to [(4, 'ELLEN'), (3, 'MARGE'), (3, 'BETTY')], # which is wrong b/c BETTY comes before MARGE in input list. # Negating returns [(-4,'ELLEN'), (-3,'BETTY'), (-3,'MARGE')], # which places them in the correct order. # prioritize matches in decreasing order, leaving like sim_factors in the original order matches.sort() # return just member names return [m[1] for m in matches] if __name__ == '__main__': mm = MatchMaker() members = ["BETTY F M A A C C", "TOM M F A D C A", "SUE F M D D D D", "ELLEN F M A A C A", "JOE M F A A C A", "ED M F A D D A", "SALLY F M C D A B", "MARGE F M A A C C"] print('BETTY matches with', mm.getBestMatches(members, "BETTY", 2)) # ['JOE', 'TOM'] print('JOE matches with', mm.getBestMatches(members, "JOE", 1)) # ['ELLEN', 'BETTY', 'MARGE']
C#
UTF-8
3,009
2.546875
3
[]
no_license
public DataTable ReadPasswordProtectedExcel(string ExcelFilePath, string Password) { String TempExcelFilePath = string.Empty; DataTable _DataTable = new DataTable(); #region Get ExcelFile and Remove Password { String TempExcelFileName = string.Empty; String DirectoryPath = string.Empty; Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application(); excelapp.Visible = false; Microsoft.Office.Interop.Excel.Workbook newWorkbook = excelapp.Workbooks.Open(ExcelFilePath, 0, true, 5, Password, "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); TempExcelFileName = string.Format("{0}_{1}", "__", Path.GetFileName(ExcelFilePath)); // __xxx.xlsx TempExcelFilePath = String.Format("{0}/{1}", Path.GetDirectoryName(ExcelFilePath), TempExcelFileName); /// Create new excel file and remove password. newWorkbook.SaveAs(TempExcelFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, "", "", false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); newWorkbook.Close(true, "", false); excelapp.Quit(); Marshal.ReleaseComObject(excelapp); } #endregion #region Get data from excel file by using OLEDB { _DataTable = ReadExcelFileInOLEDB(TempExcelFilePath); ///Delete excel file File.Delete(TempExcelFilePath); } #endregion return _DataTable; } public DataTable ReadExcelFileInOLEDB(string _ExcelFilePath) { string ConnectionString = string.Empty; string SheetName = string.Empty; DataTable _DataTable = null; DataSet _DataSet = null; try { ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=0;'", _ExcelFilePath); using (OleDbConnection _OleDbConnection = new OleDbConnection(ConnectionString)) { _OleDbConnection.Open(); _DataTable = _OleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (_DataTable == null) return null; SheetName = _DataTable.Rows[0]["TABLE_NAME"].ToString(); ConnectionString = string.Format("SELECT * FROM [{0}]", SheetName); using (OleDbCommand _OleDbCommand = new OleDbCommand(ConnectionString, _OleDbConnection)) { using (OleDbDataAdapter _OleDbDataAdapter = new OleDbDataAdapter()) { _OleDbDataAdapter.SelectCommand = _OleDbCommand; _DataSet = new DataSet(); _OleDbDataAdapter.Fill(_DataSet, "PrintInfo"); return _DataSet.Tables["PrintInfo"]; } } } } catch (Exception ex) { throw ex; } }
PHP
UTF-8
2,875
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
<?php /** * @version $Id: class_errors_view.php 2012-01-15 LBO $ * @package A PHP TOOLKIT (APT) Library * @subpackage libapt-main/views * @copyright Copyright (C) 2011 Luc BORIES All rights reserved. * @license Apache License Version 2.0, January 2004; see LICENSE.txt or http://www.apache.org/licenses/ */ class ErrorsView extends AbstractViewImpl { // ATTRIBUTES // CONSTRUCTOR public function __construct($arg_unique_name, $arg_parent_view, $arg_options) { // PARENT CONSTRUCTOR parent::__construct($arg_unique_name, $arg_parent_view, $arg_options); } // RENDER HTML protected function assocArrayToString($arg_assoc_array, $arg_eol = "<BR>") { return implode( array_map( create_function('$key, $value', 'return $key."=".$value."'.$arg_eol.'";'), array_keys($arg_assoc_array), array_values($arg_assoc_array) ) ); } public function html() { if ($this->need_init) { $this->init(); } $errors = Errors::getErrors(); HTML::addBufferLine("<TABLE>\n"); HTML::addBufferLine(" <THEAD id=messages_thead>\n"); HTML::addBufferLine(" <TH WIDTH=150 ALIGN='CENTER'>SOURCE</TH>\n"); HTML::addBufferLine(" <TH WIDTH=250 ALIGN='LEFT'>LABEL</TH>\n"); HTML::addBufferLine(" <TH WIDTH=150 ALIGN='CENTER'>ARG 1</TH>\n"); HTML::addBufferLine(" <TH WIDTH=150 ALIGN='CENTER'>ARG 2</TH>\n"); HTML::addBufferLine(" <TH WIDTH=150 ALIGN='CENTER'>ARG 3</TH>\n"); HTML::addBufferLine(" <TH WIDTH=150 ALIGN='CENTER'>ARG 4</TH>\n"); HTML::addBufferLine(" </THEAD>\n"); // LOOP ON ERRORS foreach($errors as $error) { $source = $error["source"]; $label = $error["label"]; $args = $error["args"]; $arg1 = ""; $arg2 = ""; $arg3 = ""; $arg4 = ""; $args_count = count($args); if ( ! is_null($args) and $args_count > 0) { $arg1 = $args[0]; if ($args_count > 1) { $arg2 = $args[1]; if ( is_array($args[1]) ) { $arg2 = $this->assocArrayToString( $args[1] ); } if ($args_count > 2) { $arg3 = $args[2]; if ( is_array($args[2]) ) { $arg3 = $this->assocArrayToString( $args[2] ); } if ($args_count > 3) { $arg4 = $args[3]; if ( is_array($args[3]) ) { $arg4 = $this->assocArrayToString( $args[3] ); } } } } } HTML::addBufferLine("<TR>"); HTML::addBufferLine("<TD WIDTH=150 ALIGN='CENTER'>$source</TD>"); HTML::addBufferLine("<TD WIDTH=250 ALIGN='LEFT'>$label</TD>"); HTML::addBufferLine("<TD WIDTH=150 ALIGN='CENTER'>$arg1</TD>"); HTML::addBufferLine("<TD WIDTH=150 ALIGN='CENTER'>$arg2</TD>"); HTML::addBufferLine("<TD WIDTH=150 ALIGN='CENTER'>$arg3</TD>"); HTML::addBufferLine("<TD WIDTH=150 ALIGN='CENTER'>$arg4</TD>"); HTML::addBufferLine("</TR>\n"); } HTML::addBufferLine("</TABLE>\n"); } } ?>
Python
UTF-8
1,580
2.53125
3
[]
no_license
from sys import stdin MAX = 100010 T ="" n =0 RA = [0 for x in range(MAX)] tempRA = [0 for x in range(MAX)] SA = [0 for x in range(MAX)] tempSA = [0 for x in range(MAX)] c = [0 for x in range(MAX)] def countingSort(k): global T,n,RA,SA,tempRA,tempSA,c maxi = max(300, n) c = [0 for x in c] i = 0 while i < n: if i + k < n: c[RA[i + k]]+=1 else: c[0]+=1 i+=1 i,suma = 0,0 while i < maxi: t = c[i] c[i] = suma suma += t i+=1 i = 0 while i < n: if SA[i]+k < n: tempSA[c[RA[SA[i]+k]]] = SA[i] c[RA[SA[i]+k]]+=1 else: tempSA[c[0]] = SA[i] c[0]+=1 i+=1 i = 0 while i < n: SA[i] = tempSA[i] i+=1 def constructSA(): global T,n,RA,SA,tempRA,tempSA,c i = 0 while i < n: RA[i] = ord(T[i]) i+=1 i = 0 while i < n: SA[i] = i i+=1 k,r = 1,0 while k < n: countingSort(k) countingSort(0) tempRA[SA[0]] = r = 0 i = 1 while i < n: if (RA[SA[i]] == RA[SA[i-1]] and RA[SA[i]+k] == RA[SA[i-1]+k]): tempRA[SA[i]] = r else: r+=1 tempRA[SA[i]] = r i+=1 i = 0 while i < n: RA[i] = tempRA[i] i+=1 if RA[SA[n-1]] == n-1: break k <<= 1 def solve(): global T,n,RA,SA,tempRA,tempSA,c N = len(T) T+= T+'~' n = len(T) constructSA(); i = 0 while i < n: if len(T[SA[i]:n]) >= N: return SA[i]+1 i+=1 def main(): global T,n,RA,SA,tempRA,tempSA,c inp = stdin cases = int(inp.readline().strip()) i = 0 while i < cases: T = inp.readline().strip() print(solve()) i+=1 main()
Java
UTF-8
1,984
2.8125
3
[]
no_license
package cn.bronze.util.excel; import java.lang.reflect.Field; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ConverterFactory { private static Map<String, Converter<?,?>> map = new HashMap<String, Converter<?,?>>(); private static DefaultConverter defaultConverter = new DefaultConverter(); private static Map<String, Converter<?, ?>> toStringMap = new HashMap<String,Converter<?,?>>(); static{ toStringMap.put(Boolean.class.getName(),new BooleanToStringConverter()); toStringMap.put(Integer.class.getName(), new IntegerToStringConverter()); toStringMap.put(Date.class.getName(), new DateToStringConverter()); toStringMap.put(Double.class.getName(), new DoubleToStringConverter()); } static{ map.put(Boolean.class.getName(),new StringToBooleanConverter()); map.put(Integer.class.getName(), new StringToIntConverter()); map.put(Date.class.getName(), new StringToDateConverter()); map.put(Double.class.getName(), new StringToDoubleConverter()); } public static String converter(Object value,Field field) throws ConverterException , ParamCanNotBeNullException{ if(value==null||field==null){ throw new ParamCanNotBeNullException("value","field"); } if(toStringMap.containsKey(field.getType().getName())){ Converter<Object, String> converter = (Converter<Object, String>) toStringMap.get(field.getType().getName()); return converter.converter(value); }else{ return defaultConverter.converter(value.toString()); } } public static Object converter(String value,Field field) throws ConverterException{ if(map.containsKey(field.getType().getName())) { Converter<String,?> converter = (Converter<String,?>)map.get(field.getType().getName()); return converter.converter(value); } else { /*new ConverterNotFoundException(field.getType().getName()) .printStackTrace(); */ return defaultConverter.converter(value); } } }
Java
UTF-8
1,162
2.375
2
[]
no_license
package com.kingdee.token; import java.util.Date; public class Token { /* 令牌 */ private String Token; private String code; /* 有效期 默认1小时 3600s */ private int Validity; private String IPAddress; private String Language; // 更新时间 private Date Create; public String getToken() { return Token; } public void setToken(String token) { Token = token; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public int getValidity() { return Validity; } public void setValidity(int validity) { Validity = validity; } public String getIPAddress() { return IPAddress; } public void setIPAddress(String iPAddress) { IPAddress = iPAddress; } public String getLanguage() { return Language; } public void setLanguage(String language) { Language = language; } public Date getCreate() { return Create; } public void setCreate(Date create) { Create = create; } }
PHP
UTF-8
821
3.59375
4
[]
no_license
<html> <head><title>Ej3</title></head> <body> <?php $num=15; $resto; $cociente=$num; $salida=""; while($cociente>=1){ $resto=$cociente%16; if($resto>=10){ $resto=restoDecimal($resto); } $salida=$resto . "" . $salida; $cociente=$cociente/16; }#de while function restoDecimal($numero){ if($numero==10){ return "A"; } else if ($numero==11){ return "B"; }#de else if else if ($numero==12){ return "C"; }#de else if else if ($numero==13){ return "D"; }#de else if else if ($numero==14){ return "E"; }#de else if else{ return "F"; }#de else; }#de function echo "El numero " . $num . " en HEXADECIMAL es = " . $salida . "<br/>"; ?> </body> </html>
Java
UTF-8
9,707
1.96875
2
[ "Apache-2.0" ]
permissive
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.impl.neomedia.jmfext.media.renderer.video; import java.awt.Component; import java.awt.Dimension; import java.awt.Rectangle; import javax.media.Buffer; import javax.media.Format; import javax.media.ResourceUnavailableException; import javax.media.format.RGBFormat; import javax.media.format.VideoFormat; import javax.media.format.YUVFormat; import javax.media.renderer.VideoRenderer; import javax.swing.SwingUtilities; import org.jitsi.impl.neomedia.codec.video.SwScale; import org.jitsi.impl.neomedia.jmfext.media.renderer.AbstractRenderer; import org.jitsi.util.OSUtils; import org.jitsi.util.swing.VideoLayout; /** * Video renderer using pure Java2D. * * @author Ingo Bauersachs */ public class Java2DRenderer extends AbstractRenderer<VideoFormat> implements VideoRenderer { /** * The default, initial height and width to set on the <tt>Component</tt>s of * <tt>JAWTRenderer</tt>s before video frames with actual sizes are processed. * Introduced to mitigate multiple failures to realize the actual video frame * size and/or to properly scale the visual/video <tt>Component</tt>s. */ private static final int DEFAULT_COMPONENT_HEIGHT_OR_WIDTH = 16; /** * The array of supported input formats. */ private static final Format[] SUPPORTED_INPUT_FORMATS = new Format[] { OSUtils.IS_LINUX ? new YUVFormat(null /* size */, Format.NOT_SPECIFIED /* maxDataLength */, Format.intArray, Format.NOT_SPECIFIED /* frameRate */, YUVFormat.YUV_420, Format.NOT_SPECIFIED /* strideY */, Format.NOT_SPECIFIED /* strideUV */, Format.NOT_SPECIFIED /* offsetY */, Format.NOT_SPECIFIED /* offsetU */, Format.NOT_SPECIFIED /* offsetV */) : OSUtils.IS_ANDROID ? new RGBFormat(null, Format.NOT_SPECIFIED, Format.intArray, Format.NOT_SPECIFIED, 32, 0x000000ff, 0x0000ff00, 0x00ff0000) : new RGBFormat(null, Format.NOT_SPECIFIED, Format.intArray, Format.NOT_SPECIFIED, 32, 0x00ff0000, 0x0000ff00, 0x000000ff) }; private Java2DRendererVideoComponent component; /** * The last known height of the input processed by this <tt>JAWTRenderer</tt>. */ private int height = 0; /** * The last known width of the input processed by this <tt>JAWTRenderer</tt>. */ private int width = 0; /** * The <tt>Runnable</tt> which is executed to bring the invocations of * {@link #reflectInputFormatOnComponent()} into the AWT event dispatching * thread. */ private final Runnable reflectInputFormatOnComponentInEventDispatchThread = new Runnable() { @Override public void run() { reflectInputFormatOnComponentInEventDispatchThread(); } }; @Override public Format[] getSupportedInputFormats() { return SUPPORTED_INPUT_FORMATS.clone(); } /** * Processes the data provided in a specific <tt>Buffer</tt> and renders it to * the output device represented by this <tt>Renderer</tt>. * * @param buffer a <tt>Buffer</tt> containing the data to be processed and * rendered * @return <tt>BUFFER_PROCESSED_OK</tt> if the processing is successful; * otherwise, the other possible return codes defined in the * <tt>PlugIn</tt> interface */ @Override public synchronized int process(Buffer buffer) { if (buffer.isDiscard()) { return BUFFER_PROCESSED_OK; } int bufferLength = buffer.getLength(); if (bufferLength == 0) { return BUFFER_PROCESSED_OK; } Format format = buffer.getFormat(); if (format != null && format != this.inputFormat && !format.equals(this.inputFormat) && setInputFormat(format) == null) { return BUFFER_PROCESSED_FAILED; } Dimension size = null; if (format != null) { size = ((VideoFormat) format).getSize(); } if (size == null) { size = this.inputFormat.getSize(); if (size == null) { return BUFFER_PROCESSED_FAILED; } } // XXX If the size of the video frame to be displayed is tiny enough // to crash sws_scale, then it may cause issues with other // functionality as well. Stay on the safe side. if (size.width >= SwScale.MIN_SWS_SCALE_HEIGHT_OR_WIDTH && size.height >= SwScale.MIN_SWS_SCALE_HEIGHT_OR_WIDTH) { getComponent().process(buffer, size); } return BUFFER_PROCESSED_OK; } @Override public void start() { } @Override public void stop() { } @Override public void close() { } @Override public String getName() { return "Pure Java Video Renderer"; } @Override public void open() throws ResourceUnavailableException { } @Override public Rectangle getBounds() { return null; } @Override public Java2DRendererVideoComponent getComponent() { if (component == null) { component = new Java2DRendererVideoComponent(); // Make sure to have non-zero height and width because actual video // frames may have not been processed yet. component.setSize(DEFAULT_COMPONENT_HEIGHT_OR_WIDTH, DEFAULT_COMPONENT_HEIGHT_OR_WIDTH); } return component; } @Override public void setBounds(Rectangle rect) { } @Override public boolean setComponent(Component comp) { return false; } /** * Sets the <tt>Format</tt> of the input to be processed by this * <tt>Renderer</tt>. * * @param format the <tt>Format</tt> to be set as the <tt>Format</tt> of the * input to be processed by this <tt>Renderer</tt> * @return the <tt>Format</tt> of the input to be processed by this * <tt>Renderer</tt> if the specified <tt>format</tt> is supported or * <tt>null</tt> if the specified <tt>format</tt> is not supported by * this <tt>Renderer</tt>. Typically, it is the supported input * <tt>Format</tt> which most closely matches the specified * <tt>Format</tt>. */ @Override public synchronized Format setInputFormat(Format format) { VideoFormat oldInputFormat = inputFormat; Format newInputFormat = super.setInputFormat(format); // Short-circuit because we will be calculating a lot and we do not want // to do that unless necessary. if (oldInputFormat == inputFormat) return newInputFormat; // Know the width and height of the input because we'll be depicting it // and we may want, for example, to report them as the preferred size of // our AWT Component. More importantly, know them because they determine // certain arguments to be passed to the native counterpart of this // JAWTRenderer i.e. handle. Dimension size = inputFormat.getSize(); if (size == null) { width = height = 0; } else { width = size.width; height = size.height; } reflectInputFormatOnComponent(); return newInputFormat; } /** * Sets properties of the AWT <tt>Component</tt> of this <tt>Renderer</tt> which * depend on the properties of the <tt>inputFormat</tt> of this * <tt>Renderer</tt>. Makes sure that the procedure is executed on the AWT event * dispatching thread because an AWT <tt>Component</tt>'s properties (such as * <tt>preferredSize</tt>) should be accessed in the AWT event dispatching * thread. */ private void reflectInputFormatOnComponent() { if (SwingUtilities.isEventDispatchThread()) { reflectInputFormatOnComponentInEventDispatchThread(); } else { SwingUtilities.invokeLater(reflectInputFormatOnComponentInEventDispatchThread); } } /** * Sets properties of the AWT <tt>Component</tt> of this <tt>Renderer</tt> which * depend on the properties of the <tt>inputFormat</tt> of this * <tt>Renderer</tt>. The invocation is presumed to be performed on the AWT * event dispatching thread. */ private void reflectInputFormatOnComponentInEventDispatchThread() { // Reflect the width and height of the input onto the prefSize of our // AWT Component (if necessary). if ((component != null) && (width > 0) && (height > 0)) { Dimension prefSize = component.getPreferredSize(); // Apart from the simplest of cases in which the component has no // prefSize, it is also necessary to reflect the width and height of // the input onto the prefSize when the ratio of the input is // different than the ratio of the prefSize. It may also be argued // that the component needs to know of the width and height of the // input if its prefSize is with the same ratio but is smaller. if ((prefSize == null) || (prefSize.width < 1) || (prefSize.height < 1) || !VideoLayout.areAspectRatiosEqual(prefSize, width, height) || (prefSize.width < width) || (prefSize.height < height)) { component.setPreferredSize(new Dimension(width, height)); } // If the component does not have a size, it looks strange given // that we know a prefSize for it. However, if the component has // already been added into a Container, the Container will dictate // the size as part of its layout logic. if (component.isPreferredSizeSet() && (component.getParent() == null)) { Dimension size = component.getSize(); prefSize = component.getPreferredSize(); if ((size.width < 1) || (size.height < 1) || !VideoLayout.areAspectRatiosEqual(size, prefSize.width, prefSize.height)) { component.setSize(prefSize.width, prefSize.height); } } } } }
Ruby
UTF-8
1,437
3.71875
4
[]
no_license
require 'rubygems' require 'imdb' class TextReader def read_from_file @movies_txt = IO.read("movies.txt") @movies_txt turn_into_arr end def turn_into_arr @movies_txt.split("\n").to_a end end class LookOnImdb def initialize(movies_arr) @movies_arr = movies_arr end def look_for_rating @ratings_arr = @movies_arr.map {|n| Imdb::Search.new(n).movies[0].rating} round_ratings end def round_ratings @ratings_arr.map {|rating| rating.to_i.round} end end class LayoutBuilder def initialize(movies_arr, ratings_arr) @movies_arr = movies_arr @ratings_arr = ratings_arr end def build_ratings_vertically 10.downto(1) do |i| print "|" @ratings_arr.each do |rating| if rating >= i print "#|" else print " |" end end puts "" end end def build_number_of_movies @string = "|" @ratings_arr.each_index do |position| @string += "#{position + 1}|" end @string end def build_dashes "-" * build_number_of_movies.length end def build_list_of_movies @movies_arr.each_with_index {|title, index| puts "#{index + 1}. #{title}"} end def build_layout build_ratings_vertically puts build_dashes puts build_number_of_movies puts "" build_list_of_movies end end movies_arr = TextReader.new.read_from_file ratings_arr = LookOnImdb.new(movies_arr).look_for_rating LayoutBuilder.new(movies_arr, ratings_arr).build_layout
Java
UTF-8
377
2.421875
2
[]
no_license
import java.util.*; public class p6 { public static void main() { int i,l;char ch,ch2; String s="a d g";String s2="game";l=s.length(); StringTokenizer s1=new StringTokenizer(s); StringBuffer ss=new StringBuffer(2); System.out.print(s1.countTokens()); System.out.print(s1.nextToken()); System.out.print(s1.nextToken()); }}
C#
UTF-8
2,085
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using Xunit; namespace DarrenCloudDemos.Lib.Tests { public class FunctionProgrammingDemoTests { /// <summary> /// 计算物业费 /// </summary> /// <param name="price">单价</param> /// <param name="lengh">长</param> /// <param name="width">宽</param> /// <param name="expected">结果</param> [Theory] [InlineData(10, 2, 3, 60)] public void CalculatePropertyFee_ForPersonal(decimal price, int lengh, int width, decimal expected) { //Arrange var calculator = new FunctionProgrammingDemo(); //Act var result = calculator.CalculatePropertyFee(price, lengh, width, calculator.CalculateForPersonal()); //Assert Assert.Equal(expected, result); } /// <summary> /// 计算物业费 /// </summary> /// <param name="price">单价</param> /// <param name="lengh">长</param> /// <param name="width">宽</param> /// <param name="expected">结果</param> [Theory] [InlineData(10, 2, 3, 78)] public void CalculatePropertyFee_ForBusiness(decimal price, int lengh, int width, decimal expected) { //Arrange var calculator = new FunctionProgrammingDemo(); //Act var result = calculator.CalculatePropertyFee(price, lengh, width, calculator.CalculateForBusiness()); //Assert Assert.Equal(expected, result); } [Fact] public void AddTreeNumberTest() { //Arrange var demo = new FunctionProgrammingDemo(); //Act var result1 = demo.AddThreeNumber()(1, 2, 3); var result2 = demo.AddThreeNumberCurring()(1); var result3 = result2(2); var result4 = result3(3); //Assert Assert.Equal(6, result1); Assert.Equal(6, result4); } } }
Markdown
UTF-8
981
3.03125
3
[ "MIT" ]
permissive
number - odd or even ======================================= At least 99.9% of the time, any number can be odd or even. This uncertainty can be eliminated with `number-oddoreven`. As it sports an incredibly fast, open-ended API, you can solve all even or odd related problems with only 1 line. *** ### List of features * [x] See if a number is odd or even * [x] See if a number is odd or even * [ ] See if a number is odd or even ### Download & Installation ```shell $ npm i number-oddoreven ``` ### Code Demo Importing (ready for production) ```js var isoddOrEven = require("number-oddoreven"); ``` Importing (development version) ```js var isoddOrEven = require("number-oddoreven"); ``` Example usage ```js var isoddOrEven = require("number-oddoreven"); if (isoddOrEven(3)) { console.log("The number is odd or even!"); } ``` ### Authors or Acknowledgments * Arnar Freyr Ástvaldsson * Anders Nyby Christensen * Frederik Hammer ### License This project is licensed under the MIT License
PHP
UTF-8
977
2.53125
3
[]
no_license
<?php /** * This file provides the AJAX call to retrieve quota information using the configured Application Key and Secret. */ /** * Provide the quota information about the currently configured *Application*. */ function hewa_ajax_quota() { ob_clean(); header( 'Content-Type: application/json; charset=UTF-8' ); $quota = json_decode( hewa_server_call( '/me' ) ); // Build the message. $max_quota = $quota->account->maxQuota; $used_quota = $quota->account->currentQuota; $free_quota = $max_quota - $used_quota; $percent_free = round( ( $free_quota / $max_quota ) * 100, 0 ); $message = __( 'You have %s%% of free space (%s out of %s total).', HEWA_LANGUAGE_DOMAIN ); $quota->message = sprintf( $message, $percent_free, hewa_format_bytes( $free_quota ), hewa_format_bytes( $max_quota ) ); echo json_encode( $quota ); wp_die(); } add_action( 'wp_ajax_' . HEWA_SHORTCODE_PREFIX . 'quota', 'hewa_ajax_quota' );
Python
UTF-8
1,386
2.890625
3
[]
no_license
import functools from flask import request from main.errors import BadRequest def request_parser(query_schema=None, body_schema=None): """ Decorator used for request parsing :param body_schema: Schema for request's query params :param query_schema: Schema for request's body params :param schemacls: Schema Class to parse request :return: return response for Flask """ def my_decorator(func): @functools.wraps(func) def in_func(*args, **kwargs): query_params = body_params = None if query_schema is not None: query_params = query_schema.load(request.args) if body_schema is not None: # If the mimetype does not indicate JSON this returns None, silent=True make is return None if # JSON-type body is not correct. json_data = request.get_json(silent=True) if json_data is None: raise BadRequest(error_message='Please send a request consisting JSON body type.') body_params = body_schema.load(json_data) if query_params is not None: kwargs['query_params'] = query_params if body_params is not None: kwargs['body_params'] = body_params return func(*args, **kwargs) return in_func return my_decorator
Python
UTF-8
300
3.421875
3
[]
no_license
def repeatedStringMatch(A, B): myStr = "" while len(myStr) < len(B): myStr += A if B in myStr: return int(len(myStr) / len(A)) myStr += A if B in myStr: return int(len(myStr) / len(A)) return -1 print(repeatedStringMatch("abc", "cabcabca"))
Python
UTF-8
932
2.8125
3
[]
no_license
from collections import deque h, w = map(int, input().split()) s = [input() for _ in range(h)] dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] def bfs(i, j): cost = [[-1 for _ in range(w)] for _ in range(h)] que = deque() cost[i][j] = 0 que.append((i, j)) if s[i][j] == '#': return 0 while que: ni, nj = que.popleft() for k in range(4): if 0 <= ni+dy[k] < h and 0 <= nj+dx[k] < w: if cost[ni+dy[k]][nj+dx[k]] != -1: continue if s[ni+dy[k]][nj+dx[k]] == '.': cost[ni+dy[k]][nj+dx[k]] = cost[ni][nj]+1 que.append((ni+dy[k], nj+dx[k])) cc = 0 for i in range(h): for j in range(w): if cost[i][j] > cc: cc = cost[i][j] return cc ans = 0 for i in range(h): for j in range(w): cost = bfs(i, j) ans = max(ans, cost) print(ans)
PHP
UTF-8
3,253
2.546875
3
[]
no_license
<?php namespace Application\Model; use Zend\InputFilter\Factory as InputFactory; use Zend\InputFilter\InputFilter; use Core\Model\Entity; use Doctrine\ORM\Mapping as ORM; /** * Entidade de Professores * * @category Application * @package Model * * @ORM\Entity * @ORM\Table(name="professor") * */ class Professor extends Entity { /** * @ORM\Id * @ORM\Column(type="integer", name="id") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", name="nome") */ protected $nome; /** * @ORM\Column(type="string", name="telefone") */ protected $telefone; /** * @ORM\Column(type="string", name="email") */ protected $email; public function getTelefone() { return $this->telefone; } public function setTelefone($telefone) { $this->telefone = $telefone; } public function getId() { return $this->id; } public function getNome() { return $this->nome; } public function getEmail() { return $this->email; } public function setId($id) { $this->id = $id; } public function setNome($nome) { $this->nome = $nome; } public function setEmail($email) { $this->email = $email; } public function getInputFilter() { if (! $this->inputFilter) { $inputFilter = new InputFilter(); $factory = new InputFactory(); $inputFilter->add($factory->createInput(array( 'name' => 'id', 'required' => false ))); $inputFilter->add($factory->createInput(array( 'name' => 'nome', 'required' => true, 'filters' => array( array( 'name' => 'StripTags' ), array( 'name' => 'StringTrim' ) ), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'encoding' => 'UTF-8', 'min' => 3, 'max' => 100 ) ) ) ))); $inputFilter->add($factory->createInput(array( 'name' => 'email', 'required' => true, 'filters' => array( array( 'name' => 'StripTags' ), array( 'name' => 'StringTrim' ) ), 'validators' => array( array( 'name' => 'EmailAddress' ) ) ))); $this->inputFilter = $inputFilter; } return $this->inputFilter; } }
JavaScript
UTF-8
11,215
2.890625
3
[]
no_license
'use strict'; import store from './store.js'; import api from './api.js'; /******** RENDER FUNCTIONS ********/ function render(id, expand){ renderError(); if(store.adding){ $('main').html(generateAddBookmarkView()); let view = 'adding'; generateCodeBlock(view); } else if(store.filter !== 0 && !id){ let html = [generateInitialView(), generateFilteredResults(store.filter)].join('') $('main').html(html); let view = 'filter'; generateCodeBlock(view); } else if(store.editing){ let html = generateEditView(id) $('main').html(html); let view = 'editing'; generateCodeBlock(view); } else if(expand !== undefined){ let html = generateExpandedView(id, expand) $(expand).html(html); let view = 'expanded'; generateCodeBlock(view); } else{ let html = [generateInitialView(), generateItem()].join('') $('main').html(html); let view = 'initial'; generateCodeBlock(view); }; }; function renderError() { if (store.error.code) { $('div.error-container').html(`${store.error.message}`) let view = 'error'; generateCodeBlock(view); } else { $('div.error-container').empty(); } }; /******** GENERATORS ********/ //generates html for Add new bookmark view function generateAddBookmarkView(){ return `<div class="error-container"></div> <div class="title-container"> <h1>My Bookmarks</h1> </div> <div class="url-and-title"> <form id="new-bookmark-form" action="#"> <label for="name">URL goes here:</label> <input type="url" id="new-bookmark-input" class="new-bookmark" name="url" placeholder="https//yourbookmarklinkhere" required> <label for="name">Bookmark name goes here:</label> <input type="text" id="new-bookmark-title" class="new-bookmark" name="title" placeholder="Bookmark title" required> <select name="rating" class="rating-select"> <option value="1">1 star</option> <option value="2">2 star</option> <option value="3">3 star</option> <option value="4">4 star</option> <option value="5">5 star</option> </div> </select> <div class="description-container"> <input type="text" id="new-bookmark-description" class="new-bookmark" name="desc" placeholder="Add a description... (optional)"> </div> <button id="cancel-new-bookmark" type="reset">Cancel</button> <button type="submit" id="add-new-bookmark">Add</button> </form>` }; function generateItem(id){ const htmlArr = []; let itemArr = store.bookmarks; for(let i = 0; i < itemArr.length; i++){ htmlArr.push(`<li class="bookmark-data" data-item-id="${itemArr[i].id}"> ${itemArr[i].title} <span class="star-rating"> <form id="${itemArr[i].id}"> ${generateRatings(itemArr[i].id)} </form><button id="delete-bookmark"></button></span> </li>`) } return htmlArr.join(' '); }; function generateFilteredResults(filter){ const htmlArr = []; let itemArr = store.ratingFilter(filter); for(let i = 0; i < itemArr.length; i++){ htmlArr.push(`<li class="bookmark-data" data-item-id="${itemArr[i].id}"> ${itemArr[i].title} <span class="star-rating"><form id="${itemArr[i].id}"> ${generateRatings(itemArr[i].id)} </form><button id="delete-bookmark"></button></span> </li>`) } return htmlArr.join(''); } function generateExpandedView(id, expand){ let item = store.findById(id); if(item.expanded === true){ store.collapse(id); $(expand).find('.expanded-bookmark-data').remove(); return `${item.title} <span class="star-rating"><form id="${item.id}"> ${generateRatings(id)} </form><button id="delete-bookmark"></button></span>`; } else{ store.expand(id); return `<li class="expanded-bookmark-data" data-item-id="${item.id}"> ${item.title} <span class="star-rating"><form id="${item.id}"> ${generateRatings(id)} </form></span> <div class="description-container"> Description: ${item.desc} URL: <a class="link" href ="${item.url}">Visit this site</a></div> <button id="delete-bookmark"></button> <button id="edit-bookmark"></button> </li>` }; } function generateRatings(id){ let arr = []; let item = store.findById(id); let rating = [item.rating]; for (let i = 0; i < 5; i++){ arr.push(`<input type="checkbox" name="rating" value="${i}" ${rating > i ? 'checked' : ''}></input>`) } return arr.join(' ') } function generateEditView(id){ let item = store.findById(id); return ` <div class="error-container"></div><div class="title-container"> <h1>My Bookmarks</h1> </div> <div class="url-and-title"> <form class="edit-bookmark-form" data-item-id="${item.id}" action="#"> <label for="name">URL goes here:</label> <input type="url" id="new-bookmark-input" class="edit-bookmark" name="url" value="${item.url}" required> <label for="name">Bookmark name goes here:</label> <input type="text" id="new-bookmark-title" class="edit-bookmark" name="title" value="${item.title}" required> <select name="rating" class="rating-select"> <option value="1">1 star</option> <option value="2">2 star</option> <option value="3">3 star</option> <option value="4">4 star</option> <option value="5">5 star</option> </div> </select> <div class="description-container"> <input type="text" id="new-bookmark-description" class="new-bookmark" name="desc" placeholder="Add a description... (required)" required> </div> <button id="cancel-edit" type="reset">Cancel</button> <button type="submit" id="edit-bookmark-submit">Submit</button> </form>` } function generateCodeBlock(view){ if(view === 'initial'){ $('code').html(`'inital store state' let bookmarks = []; let adding = false; let error = {}; let filter = 0; let editing = false;`) } if(view === 'expanded'){ $('code').html(`'expanded view store state' const bookmarks = [ { id: 'x56w', title: 'Title 1', rating: 3, url: 'http://www.title1.com', description: 'lorem ipsum dolor sit', expanded: true } ]; let adding = false; let error = null; let filter = 0; let editing = false;`) } if(view === 'adding'){ $('code').html(`'add bookmark view store state' const bookmarks = [. . .]; let adding = true; let error = null; let filter = 0; let editing = false;`) } if(view === 'editing'){ $('code').html(`'edit bookmark view store state' const bookmarks = [. . .]; let adding = false; let error = null; let filter = 0; let editing = true;`) } if(view === 'filter'){ $('code').html(`'filter bookmark view store state' const bookmarks = [. . .]; let adding = false; let error = null; let filter = ${store.filter}; let editing = false;`) } if(view === 'error'){ $('code').html(`'edit bookmark view store state' const bookmarks = [. . .]; let adding = false; let error = ${store.error.message}; let filter = 0; let editing = false;`) } } function generateInitialView(){ return ` <div class="error-container"></div> <div class="title-container"> <h1>My Bookmarks</h1> <div class="title-button-container"> <button class="new-bookmark-button" id="new-bookmark">Add New</button> <select name="filter-bookmark" class="filter-select"> <option value="0">Minimum Rating</option> <option value="1">1 star</option> <option value="2">2 star</option> <option value="3">3 star</option> <option value="4">4 star</option> <option value="5">5 star</option> </select> </div> </div>` } /******** EVENT HANDLERS ********/ function handleNewBookmark(){ $('main').on('click', '#new-bookmark', event => { store.adding = true; render(); }) }; function handleFilterSelect(){ $('main').on('change', '.filter-select', event => { store.filter = $('.filter-select').val(); render(); }); } function serializeJson(form) { const formData = new FormData(form); const obj = {}; formData.forEach((val, name) => obj[name] = val); return JSON.stringify(obj); } function handleCreate(){ $('main').on('submit', '#new-bookmark-form', event => { event.preventDefault(); let formElement = document.querySelector("#new-bookmark-form") const myFormData = serializeJson(formElement); api.createBookmark(myFormData) .then((newItem) => { store.addItem(newItem); render(); }) store.adding = false; }); }; function handleCancelCreate(){ $('main').on('click', '#cancel-new-bookmark', event => { event.preventDefault(); store.adding = false; render(); }) }; function handleDelete(){ //find current target by id and make api call to update store, update local store $('main').on('click', '#delete-bookmark', event => { event.preventDefault(); const id = getItemId(event.currentTarget); api.deleteBookmark(id) .then(() => { store.findAndDelete(id); render(); }) }); }; function handleEditButton(){ $('main').on('click', '#edit-bookmark', event => { event.preventDefault(); const id = getItemId(event.currentTarget); store.editing = true; store.collapse(id); render(id); }); } function handleCancelEdit(){ $('main').on('click', '#cancel-edit', event => { event.preventDefault(); store.editing = false; render(); }); } function handleClickLink(){ $('main').on('click', '.link', event=>{ event.preventDefault(); let link = $(event.currentTarget); window.open(link.attr("href"), event.currentTarget); }) } function handleSubmitEdit(){ $('main').on('submit', '.edit-bookmark-form', event => { event.preventDefault(); const id = $(event.currentTarget).data('item-id') ; let formElement = document.querySelector(".edit-bookmark-form") const newFormData = serializeJson(formElement); api.updateBookmark(id, newFormData) .then(() => { store.findAndUpdate(id, newFormData); render(); }) store.editing = false; }); } function handleExpand(){ $('main').on('click', '.bookmark-data', event => { event.preventDefault(); const id = getItemId(event.currentTarget); let item = event.currentTarget; render(id, item); }) } function getItemId(item) { return $(item) .closest('.bookmark-data') .data('item-id'); }; function bindEventListeners(){ handleCancelCreate(); handleCreate(); handleNewBookmark(); handleDelete(); handleFilterSelect(); handleExpand(); handleEditButton(); handleCancelEdit(); handleSubmitEdit(); handleClickLink() render() }; $(bindEventListeners); export default{ render, renderError, bindEventListeners };
TypeScript
UTF-8
2,119
2.640625
3
[]
no_license
import { Injectable, Injector, ComponentRef, ComponentFactoryResolver } from 'mojiito-core'; import { OverlayComponent } from '../overlay.component'; @Injectable() export class Overlay { static CLASS_NAME = 'overlay'; private _isOpen = false; private _containerRef: HTMLElement = null; private _previousContent: string; public close(event: Event) { this._isOpen = false; this._containerRef.setAttribute('aria-hidden', 'true'); event.preventDefault(); } public open(content: string | null): void { if (this._isOpen) { return; } if (this._containerRef === null || this._previousContent !== content) { this._containerRef = this._create(content); } this._previousContent = content; this._containerRef.setAttribute('aria-hidden', 'false'); this._isOpen = true; } private _create(_content: string): HTMLElement { this._remove(); const overlay = document.createElement('div'); overlay.className = Overlay.CLASS_NAME; overlay.setAttribute('aria-hidden', 'true'); // set for Accessibility const content = document.createElement('div'); content.className = 'overlay__content'; if (_content !== null)  { content.innerHTML = _content; } overlay.appendChild(content); document.body.appendChild(overlay); // close overlay if click somewhere on it -> except the content overlay.addEventListener('click', (event: Event) => { if (event.target !== overlay) { return; } this.close(event); }); return overlay; } private _changeContent(_content: string) { const content = this._containerRef.querySelector(`.${Overlay.CLASS_NAME}__content`) as HTMLElement; if (content === undefined) { this._remove(); this._create(_content); } content.innerHTML = ''; content.innerHTML = _content; } private _remove(): void { if (this._containerRef) { this._containerRef.parentNode.removeChild(this._containerRef); } this._isOpen = false; this._containerRef = null; } } export const OVERLAY_PROVIDERS = [Overlay];
Swift
UTF-8
2,425
2.796875
3
[]
no_license
// // ImageProvider.swift // WatchFaceTest // // Created by Дмитрий on 4/27/21. // Copyright © 2021 DK. All rights reserved. // import Foundation extension Watchface.Metadata { public struct ImageProvider: Codable { public var onePieceImage: Item? public var twoPieceImageBackground: Item? public var twoPieceImageForeground: Item? public var fullColorImage: Item? public var tintedImageProvider: ChildImageProvider? // 0 public var monochromeFilterType: Int? // true public var applyScalingAndCircularMask: Bool? // false public var prefersFilterOverTransition: Bool? public struct Item: Codable { // "13CF2F31-40CD-4F66-8C55-72A03A46DDC3.png" where .watchface/complicationData/top-right/ public var file_name: String // 3 public var scale: Int // 0 public var renderingMode: Int private enum CodingKeys: String, CodingKey { case file_name = "file name" case scale, renderingMode } public init(file_name: String, scale: Int, renderingMode: Int) { self.file_name = file_name self.scale = scale self.renderingMode = renderingMode } } public struct ChildImageProvider: Codable { public var onePieceImage: Item? public init(onePieceImage: Item? = nil) { self.onePieceImage = onePieceImage } } public init(onePieceImage: Item? = nil, twoPieceImageBackground: Item? = nil, twoPieceImageForeground: Item? = nil, fullColorImage: Item? = nil, tintedImageProvider: ChildImageProvider? = nil, monochromeFilterType: Int? = nil, applyScalingAndCircularMask: Bool? = nil, prefersFilterOverTransition: Bool? = nil) { self.onePieceImage = onePieceImage self.twoPieceImageBackground = twoPieceImageBackground self.twoPieceImageForeground = twoPieceImageForeground self.fullColorImage = fullColorImage self.tintedImageProvider = tintedImageProvider self.monochromeFilterType = monochromeFilterType self.applyScalingAndCircularMask = applyScalingAndCircularMask self.prefersFilterOverTransition = prefersFilterOverTransition } } }
C++
UTF-8
855
3.21875
3
[]
no_license
#include "Tableau.h" Tableau::Tableau() { } bool Tableau::addCard(Card* newCard) { if (this->cards.size() == 0 && newCard->getRankValue() == 12) //if the tableau is empty and the new card is a king { this->cards.push_back(newCard); return true; } else if (this->cards.size() > 0 && this->cards.back()->compareRanks(newCard) == -1 && this->cards.back()->compareSuits(newCard).color == 0) //if the new card is next rank and different color { this->cards.push_back(newCard); return true; } return false; } Card* Tableau::takeTopCard() { Card* topCard = this->cards.back(); if (this->cards.size() > 1 && this->cards.at(this->cards.size() - 2)->getIsHidden()) { this->cards.at(this->cards.size() - 2)->switchIsHidden(); } this->cards.pop_back(); return topCard; }
Markdown
UTF-8
3,102
3.046875
3
[]
no_license
CS61C Fall 2014 Homework 3 Part 2 ================================= TA: Riyaz Faizullabhoy Due Sunday, October 5th, 2014 @ 23:59:59 Goals ----- This assignment will cover floating point numbers, and caches. Submission ---------- Put all your answers in the google form linked [here](https://docs.google.com/forms/d/1HYBMSHYWxw5fHtCBZeBPr1lqtFtyjG3l0IfIi0DjBl4/). Your latest submission will be graded. Exercises --------- ### Problem 1: Floating Points - 10pts If you're starting this homework early and we haven't covered this yet don't worry. We'll be going over floating point representation in Friday's lecture. For the following questions, we will be referring to the IEEE 32-bit floating point representation ***except*** with a 6 bit exponent (bias of 2\^6/2 - 1 = 31) and a denorm implicit exponent of -30. 1. Convert -37.75 to floating point format. Write your answer in hexadecimal. 2. Convert the floating point number 0x98765000, which follows the 6 bit exponent representation as described above, to decimal. Please specify infinities as +inf" or -inf, and not a number as NaN. 3. What's the smallest non-infinite positive integer (an integer has nothing to the right of the decimal) it CANNOT represent? Leave your answer in decimal (ex: 12). 4. What's the smallest positive value it can represent that is not a denorm? Leave your answer as a power of 2 (ex: 2\^x). 5. What's the smallest positive value it can represent? Leave your answer as a power of 2 (ex: 2\^x). ### Problem 2: Caches - 4pts Assume we have 16 bit byte-addresses. A very tiny direct-mapped cache holds a total of 32 bytes and each cache block is a word wide. 1. How many bits are used for the tag? 2. Which other bytes would share a block with the byte at address 0x75? Please write the bytes in hex (ex: 0xAA) in your answer, and separate multiple answers by single spaces, if you wish to include more then one byte in your answer (ex: 0xAB 0xFF) 3. The block containing the byte at 0x75 is in the cache. What memory accesses are *guaranteed* to get a cache miss? Specify what the value of the index bits equate to, in decimal. 4. The hit time is a clock cycle, and the miss penalty is 100. If the miss rate is 50%, what is the AMAT? Please specify your answer in decimal (ex: 12.5) ### Problem 3: Cache Memory Accesses (from P&H Computer Org. & Design) - 6pts The following C program is run (with no optimizations) on a processor with a direct-mapped cache that has eight-word (32-byte) blocks and holds 256 words of data: int i,j,c,stride,array[512]; ... for(i=0; i<10000; i++) for (j=0; j<512; j+=stride) c += i%(array[j]); If we consider only the cache activity generated by references to the array and we assume that integers are words, what possible **miss rates** (there may be multiple) can we expect 1. if `stride` = 256? 2. if `stride` = 255? Please leave your answer as a percentage (ex: 0%). If you have multiple miss rates in your answer, please separate them with a single space (ex: 0% 1%). \
C++
UTF-8
5,113
2.546875
3
[]
no_license
/* -------------------------------------------------------------- File: AXAppStateMgr.cpp Description: Implementation for the AXAppStateMgr class. See AXAppStateMgr.h for details. Date: August 2, 2005 Author: James Long -------------------------------------------------------------- */ #include "AXAppStateMgr.h" #include "..\\AXCore.h" // Entity types #include "..\\AXGraphics\\AXMeshEntity.h" #include "..\\AXGraphics\\AXCamera.h" #include "boost\\smart_ptr.hpp" using std::string; using boost::shared_ptr; /* AppState functions */ AXAppState::AXAppState(std::string Name) : _Name(Name), _SceneMgr(NULL), _OverlayMgr(NULL) { } AXAppState::~AXAppState() { SafeDelete(_SceneMgr); SafeDelete(_OverlayMgr); } AXScene* AXAppState::GetSceneManager() { if(!_SceneMgr) { _SceneMgr = new AXScene; // Register default entity types //_SceneMgr->RegisterEntityType<AXMeshEntity>("Mesh"); _SceneMgr->RegisterEntityType<AXCamera>("Camera"); } return _SceneMgr; } AXOverlay* AXAppState::GetOverlayManager() { if(!_OverlayMgr) _OverlayMgr = new AXOverlay; return _OverlayMgr; } void AXAppState::Execute() { AXPROFILE("Executing Current AppState"); if(_SceneMgr) { _SceneMgr->GetScene()->Update(); _SceneMgr->GetScene()->Execute(); } if(_OverlayMgr) { // ... when implemented ... } } /* AppStateMgr definitions */ AXAppStateMgr::AXAppStateMgr() : AXUpdatableSystemComponent("AppStateMgr") { } AXAppStateMgr::~AXAppStateMgr() { } AXResult AXAppStateMgr::Start() { return AXSUCCESS; } void AXAppStateMgr::Update() { AXPROFILE("AppState Task"); if(_NextState) { _CurrentState->OnSwitchAway(); _NextState->_FromTaskName = _CurrentState->_Name; _CurrentState = _NextState; _NextState.reset(); } _CurrentState->OnPreExecute(); _CurrentState->Execute(); _CurrentState->OnPostExecute(); _CurrentState->HandleInput(); } void AXAppStateMgr::Stop() { if(_CurrentState) _CurrentState->OnSwitchAway(); AppStateList::iterator it; for(it = _AppStateList.begin(); it != _AppStateList.end();) { shared_ptr<AXAppState> AppState = (*it); it++; LOG_SYS1("Shutting down and removing Application State '%s'...", AppState->_Name.c_str()); AppState->Shutdown(); _AppStateList.remove(AppState); } } AXResult AXAppStateMgr::AddAppState(shared_ptr<AXAppState> AppState) { LOG_SYS1("Adding and initializing Application State '%s'...", AppState->_Name.c_str()); AppStateList::iterator it; for(it = _AppStateList.begin(); it != _AppStateList.end(); it++) { if((*it)->_Name == AppState->_Name) { LOG_SYS1("Application State '%s' was not added because one with the same name already exists.", AppState->_Name.c_str()); return AXFAILURE; } } if( AXFAILED(AppState->Initialize()) ) { LOG_SYS1("Application State '%s' initialization failed!", AppState->_Name.c_str()); AppState->Shutdown(); return AXFAILURE; } if(_AppStateList.empty()) { _CurrentState = AppState; if(AXFAILED(_CurrentState->OnSwitchTo())) { LOG_SYS("Switching to first state failed - the first state must succeed!"); return AXFAILURE; } } _AppStateList.push_back(AppState); return AXSUCCESS; } AXResult AXAppStateMgr::RemoveAppState(string AppStateName) { if(AppStateName == _CurrentState->_Name) { LOG_SYS1("Removing state failed: Cannot remove the current Application State '%s'!", AppStateName.c_str()); return AXFAILURE; } AppStateList::iterator it; for(it = _AppStateList.begin(); it != _AppStateList.end(); it++) { if((*it)->_Name == AppStateName) { AXLog->Write(MESSAGE_SYS, "Shutting down and removing Application State '%s'...", AppStateName.c_str()); (*it)->Shutdown(); _AppStateList.erase(it); return AXSUCCESS; } } LOG_SYS1("Removing state failed: Application State '%s' does not exist!", AppStateName.c_str()); return AXFAILURE; } AXResult AXAppStateMgr::SwitchToAppState(string AppStateName) { LOG_SYS1("Switching to Application State '%s'...", AppStateName.c_str()); if(_CurrentState->_Name == AppStateName) return AXSUCCESS; AppStateList::iterator it; for(it = _AppStateList.begin(); it != _AppStateList.end(); it++) { if((*it)->_Name == AppStateName) { if(_CurrentState != (*it)) _NextState = (*it); if(AXFAILED(_NextState->OnSwitchTo())) { LOG_SYS1("Switching to state '%s' failed!", _NextState->_Name.c_str()); _NextState.reset(); return AXFAILURE; } return AXSUCCESS; } } LOG_SYS1("Switching state failed: Application State '%s' does not exist!", AppStateName.c_str()); return AXFAILURE; } void AXAppStateMgr::OnInputDeviceRenew() { AppStateList::iterator it; for(it = _AppStateList.begin(); it != _AppStateList.end(); it++) { (*it)->OnInputDeviceRenew(); } } void AXAppStateMgr::OnRenderDeviceRenew() { AppStateList::iterator it; for(it = _AppStateList.begin(); it != _AppStateList.end(); it++) { (*it)->OnRenderDeviceRenew(); (*it)->GetSceneManager()->OnRenderDeviceRenew(); } }
C++
UTF-8
983
2.8125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector<vector<int>> dirs = {{0,1},{1,0},{-1,0},{0,-1}}; int main() { int t,n,tc=1; string in; cin >> t; while(t--){ vector<string> matrix; cin >> n; for(int i=0;i<n;i++){ cin >> in; matrix.push_back(in); } for(int i=0;i<n;i++) for(int j=0;j<n;j++) if(matrix[i][j] == '.'){ bool valid = false; for(char c='A';c<='Z' && !valid;c++){ valid = true; for(auto& dir : dirs){ int x = i+dir[0]; int y = j+dir[1]; if(x<0||y<0||x>=n||y>=n) continue; if(matrix[x][y] == c) { valid = false; break; } } if(valid) matrix[i][j] = c; } } printf("Case %d:\n",tc++); for(auto& s : matrix) cout << s << endl; } }
Python
UTF-8
45
3.359375
3
[]
no_license
a = 1 b = 3 print("The product is : " , a*b)
Markdown
UTF-8
14,719
2.890625
3
[]
no_license
# Index: * [os module](#os-module) * os.environ * os.environ\['PATH'\], os.pathsep * [sys module](#sys-module) * sys.argv * sys.exit * misc stuff * [subprocess module](#subprocess-module) * [shell or no shell](#shell-or-no-shell) * [sp.call](#sp-call) * [sp.check_call](#sp-check-call) * [sp.check_output](#sp-check-output) * [sp.Popen](#sp-popen) * Popen.poll, wait, communicate, terminate, kill, stdin, stdout, stderr, returncode * [argparse module](#argparse-module) * [nis module](#nis-module) * [platform module](#platform-module) https://docs.python.org/2/library/filesys.html Sometimes, we need to modify environment variables and the PATH in order to get the needed/expected behavior of an exernal command/program that we need to run. For example, we might use subprocess to run a few lines of bash code to source something and run a tool; but we need to make sure the PATH is correct to give our tool the correct version of GCC, or for it to find any tools it needs to run. We might need to set environmetn variables to trigger certain behavior in another program that we're calling. This secion is all about doing that, and then how to call external tools/commands! # os module More os module things that weren't covered in teh files and paths content. What you see set will vary depending on your OS and more... **os.environ** Dictionary with all environment variables set when python process was launched. Modify them and any subprocesses will see the changes. ```python In [6]: for key, val in os.environ.items(): ...: print key, ':', val ...: FVWM_USERDIR : /usr/users/home0/thedude GROUP : users REMOTEHOST : 10.121.208.53 MINICOM : -c on SSH2_TTY : /dev/pts/195 CSHEDIT : emacs HOSTTYPE : x86_64 ... In [7]: os.environ['MACHTYPE'] Out[7]: 'x86_64-suse-linux' In [9]: os.environ['foo'] = 'bar' In [10]: os.environ['foo'] Out[10]: 'bar' In [30]: os.getenv('foo') Out[30]: 'bar' ``` **Setting the env PATH** The PATH variable defines where the system looks for executables when you run a command. In the example below, 'which' is a unix command that says what the path to a command is... it searches each directory in the PATH environment variable and returns the first one that has the command. This is the path that the command would be executed from given the current PATH value. ```python In [17]: os.environ['PATH'] Out[17]: '/p/foobar/bin:/p/foobar/anaconda:/usr/users/home0/thedude/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/bin/X11:/usr/X11R6/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin:/usr/lib/qt3/bin:/opt/kde3/bin:/usr/local/bin:/usr/common/script:.' In [18]: import subprocess as sp In [19]: sp.check_output(['which', 'python']) Out[19]: '/p/foobar/anaconda/python\n' In [20]: os.environ['PATH'] = os.pathsep.join(('/bin', '/usr/bin', '/sbin', '/usr/sbin')) In [21]: sp.check_output(['which', 'python']) Out[21]: '/usr/bin/python\n' ``` **os.pathsep** - separater used for the PATH varialbe on the system where python is running. ```python In [31]: os.pathsep Out[31]: ':' ``` **os.getuid, setuid, getgid, setgid** TBD ```python foo ``` # sys module Sys has a lot of low-level functionality with info about the running python interpreter, basic environmental stuff, and architecture specific stuff. It's mostly out of our scope, but a couple of it's modules are important for general usage! **sys.argv** - list of arguments provided by the user when the python program was executed. The first item in this list is always the name of the running program. ``` myhost:~> cat ~/bin/argtest.py #!/usr/bin/env python import sys print sys.argv myhost:~> ~/bin/argtest.py first "second stuff" third --fourth "six seven 8" ['/usr/users/home0/drnorris/bin/argtest.py', 'first', 'second stuff', 'third', '--fourth', 'six seven 8'] myhost:~> ``` **sys.exit** Call this to exit the program at any point. Give it an exit status to indicate whether or not errors were encountered when the program ran. Zero "0" exit status means success, and non-zero means there was a failure. This is somewhat in contrast to truth-ness in programming where zero is usually False and non-zero evaluates to True. ``` myhost:~> cat ~/bin/exittest.py #!/usr/bin/env python import sys if sys.argv[1] == 'success': sys.exit(0) elif sys.argv[1] == 'failure': sys.exit(1) myhost:~> if ~/bin/exittest.py success; then echo "got 0 exit status for success"; else echo "got non-zero exit status indicating failure"; fi got 0 exit status for success myhost:~> if ~/bin/exittest.py failure; then echo "got 0 exit status for success"; else echo "got non-zero exit status indicating failure"; fi got non-zero exit status indicating failure myhost:~> ``` **sys.platform** - basic info about what type of system we're running on ```python In [24]: sys.platform Out[24]: 'linux2' ``` | System | platform value | |---------------------|----------------| | Linux (2.x and 3.x) | 'linux2' | | Windows | 'win32' | | Windows/Cygwin |'cygwin' | | Mac OS X |'darwin' | *and more...* **sys.getwindowsversion** - try this on windows... **sys.maxint** - largest possible integer value on this system ```python In [25]: sys.maxint Out[25]: 9223372036854775807 ``` **sys.floatinfo** - info about floating point representation on this system ```python In [33]: sys.float_info Out[33]: sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) ``` **sys.getrecursionlimit** - how many function calls deep can your program go? ```python In [27]: sys.getrecursionlimit() Out[27]: 1000 ``` # subprocess module This is a big one! This has everything you need (probably) to make system calls from python and execute any random commands needed when your program runs. It's easy to abuse subprocess - don't use it for thigns that you should be using libraries for, like editing files, permissions, etc. Finally, subprocess can be a bit complex, depending on your needs, so it has a learning curve, but it's pretty friendly once you figure it out. https://docs.python.org/2/library/subprocess.html#replacing-older-functions-with-the-subprocess-module ## shell or no shell? **Command format without using the shell to execute the command**: `['/som/path/my_command', '--arg1', 'val1', '--arg2', ...]` The command and each argument are separate strings in a list. This is 100% the safest way to run anything with subprocess since it removes the possiblity that an unintended bit of code can get executed by the shell. It makes it pretty simple to build commands, too... just keep appending args to the list until you have everything you need. **Command format with shell**: `''' source /blah/some_file.sh /some/path/another_command --arg1 val1 --arg2 ... '''` This is the one situation I can think of where it's important to be able to use `shell=True` when executing a command. If I need to source some scripts to set up the environment for the command I'm going to run, then I don't see a good way around it (except maybe writing a wrapper to capture shell changes from the source and setting them before calling another command)... Anyway, try not to do that since, in situations where you external files or input can affect what you run, there is opporutnity to accidentally run stuff like this: `/some/path/another_command --arg1 $(cat /etc/passwd | mail -s h4x0red_by joe@blow.com; echo actual_arg) --arg2 ...` And the shell will execute any of the nested commands, leaving you vulnerable. ## sp.call **Run a command and return the exit status** * No exception raised if the exit status is not zero (non-zero exit status from a command means there was an error) * FileNotFoundError exception raised if command does not exist. * This is blocking - python will stay at this command until it completes; then move on. ```python In [85]: sp.call(['/bin/true']) Out[85]: 0 <- It returned the exit status! In [86]: sp.call(['/bin/false']) Out[86]: 1 <- non-zero exit status means error; false is error! In [87]: sp.call(['/bin/doesnt-exist']) '--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) ``` ## sp.check_call **Use this if you want an exception on non-zero exit status** * Raises sp.CalledProcessErroron non-zero returncode * Raises FileNotFoundError if command doesn't exist * This is blocking **Example with non-zero return code:** ```python In [101]: try: ...: sp.check_call(['/bin/false']) ...: except sp.CalledProcessError as e: ...: print("MESSAGE WAS:", e) ...: print("Exit Status was:", e.returncode) ...: except FileNotFoundError as e: ...: print("MESSAGE WAS:", e) ...: MESSAGE WAS: Command '['/bin/false']' returned non-zero exit status 1. Exit Status was: 1 ``` **Example with invalid command** ```python In [102]: try: ...: sp.check_call(['/bin/some_foobar']) ...: except sp.CalledProcessError as e: ...: print("MESSAGE WAS:", e) ...: print("Exit Status was:", e.returncode) ...: except FileNotFoundError as e: ...: print("MESSAGE WAS:", e) ...: MESSAGE WAS: [Errno 2] No such file or directory: '/bin/some_foobar' ``` **Exmaple where it works as expected In [103]: try: ...: sp.check_call(['/bin/true']) ...: except sp.CalledProcessError as e: ...: print("MESSAGE WAS:", e) ...: print("Exit Status was:", e.returncode) ...: except FileNotFoundError as e: ...: print("MESSAGE WAS:", e) ...: In [104]: ## sp.check_output **Run a command and return it's output.** * Raises sp.CalledProcessErroron non-zero returncode * Raises FileNotFoundError if command doesn't exist * This is blocking - python will stay at this command until it completes; then move on. ```python In [106]: try: ...: output = sp.check_output(['ls', '-ld']) ...: print("OUTPUT WAS:", output) ...: except sp.CalledProcessError as e: ...: print("MESSAGE WAS:", e) ...: print("Exit Status was:", e.returncode) ...: except FileNotFoundError as e: ...: print("MESSAGE WAS:", e) ...: OUTPUT WAS: b'drwxrwxr-x 2 drnorris drnorris 4096 Oct 28 11:02 .\n' In [107]: ``` ## sp.Popen **This is the monster :)** * NON-blocking, so you can run multiple commands in teh background concurrently if you want... * Raises FileNotFoundError if command not found... * Let's you redirect, capture, and chain-together stdin, stdout, stder from each process. We aren't giong to use this much here, but you should read about it! # argparse module I'm kind of used to seeing people put argparse stuff at the top of their program in global namespace, but that's not really necessary; we can put it all into a function and call it at runtime to have the given argumetns processed. Argparse works on the same data available to use in `sys.argv`, so we can reference the given args ourselves before calling argparse, which can be useful if we wan to set global obtions like "DEBUG", at the top of our program, but still use argparse to handle all of the detailed arg stuff. You'll have to go through the documentation if you want to do anything fancy w/ argparse: https://docs.python.org/3/library/argparse.html Here's a simple example you can start with in your own code: ```python .../EXAMPLES> cat args.py #!/usr/bin/env python import argparse import sys if '--debug' in sys.argv: print('We can check for specific args outside of argparse.\n') DEBUG=True def getArgs(): parser = argparse.ArgumentParser( prog=sys.argv[0], description="Test Program for Argparse\nThese sorts of things can be\nvery exciting.", epilog="And now, you know the rest of the story!") parser.add_argument('--verbose', '-v', help="verbose mode", action='count') parser.add_argument('--debug', help="debug mode", action='store_true') parser.add_argument('--widgets', type=int, help="number of widgets", action='store') args = parser.parse_args() return args if __name__ == '__main__': args = getArgs() print("ARGS ARE:") print(args) ``` And a couple examples of it's output: ``` .../EXAMPLES$ ./args.py --help usage: ./args.py [-h] [--verbose] [--debug] [--widgets WIDGETS] Test Program for Argparse These sorts of things can be very exciting. optional arguments: -h, --help show this help message and exit --verbose, -v verbose mode --debug debug mode --widgets WIDGETS number of widgets And now, you know the rest of the story! ``` ``` ../EXAMPLES> ./args.py --debug We can check for specific args outside of argparse. ARGS ARE: Namespace(debug=True, verbose=None, widgets=None) ``` ``` .../EXAMPLES> ./args.py -vv --widgets 42 ARGS ARE: Namespace(debug=False, verbose=2, widgets=42) drnorris@dadesktop:~/git/python_class/EXAMPLES$ ``` # nis module NIS is Network Information Service - sort of an extensin of the local system passwd, group, netgroup, etc files that are used for tracking users, groups, and other system information. NIS is a distributed service for this content that's still used in industry today... The usage is pretty simple: ```python In [36]: import nis In [37]: nis.match('thedude', 'passwd') Out[37]: 'thedude:passwordhash:1000:15:just.the.dude:/usr/users/home0/thedude:/bin/bash' In [38]: nis.match('users', 'group') Out[38]: 'users::15:thedude,andothers ``` # platform module Sort of the python equivelant of the uname command. Also has pointeres to some important libraries that python needs. ```python In [53]: import platform In [54]: platform.uname() Out[54]: ('Linux', 'fmyec0200', '3.0.101-107-default', '#1 SMP Thu Jun 22 14:37:55 UTC 2017 (414ea9f)', 'x86_64', 'x86_64') In [55]: platform.processor() Out[55]: 'x86_64' In [56]: platform.platform() Out[56]: 'Linux-3.0.101-107-default-x86_64-with-SuSE-11-x86_64' In [57]: platform.machine() Out[57]: 'x86_64' In [58]: platform.system() Out[58]: 'Linux' In [59]: platform.release() Out[59]: '3.0.101-107-default' ```
Java
UTF-8
3,061
2.265625
2
[]
no_license
package com.google.android.apps.unveil.env.gl; import android.opengl.GLES20; import java.nio.ByteBuffer; import java.nio.FloatBuffer; public class NV21Quad { private final int height; private ByteBuffer nv21Data; private final ShaderProgram program; Polygon quad; private final int size; private final FloatBuffer texCoords; private final Texture uvTex; private boolean valid; private final int width; private final Texture yTex; public NV21Quad(ShaderProgram paramShaderProgram, int paramInt1, int paramInt2, boolean paramBoolean) { this.program = paramShaderProgram; this.width = paramInt1; this.height = paramInt2; this.size = ((int)Math.pow(2.0D, Math.ceil(Math.log(Math.max(paramInt1, paramInt2)) / Math.log(2.0D)))); this.quad = Polygon.generateRect(0.0F, 0.0F, 2.0F, 2.0F); float f1 = paramInt1 / this.size; float f2 = paramInt2 / this.size; if (paramBoolean); for (this.texCoords = Utils.generateFloatBuffer(new float[] { 0.0F, f2, 0.0F, 0.0F, f1, 0.0F, f1, f2 }); ; this.texCoords = Utils.generateFloatBuffer(new float[] { f1, f2, 0.0F, f2, 0.0F, 0.0F, f1, 0.0F })) { this.yTex = new Texture(this.size, this.size, Texture.Format.LUMINANCE); this.uvTex = new Texture(this.size / 2, this.size / 2, Texture.Format.LUMINANCE_ALPHA); this.valid = true; return; } } public void LoadNV21Data(byte[] paramArrayOfByte) { this.nv21Data = ByteBuffer.wrap(paramArrayOfByte); } protected void finalize() throws Throwable { try { release(); return; } finally { super.finalize(); } } int getHeight() { return this.height; } int getWidth() { return this.width; } public void release() { if (this.valid) { this.valid = false; this.yTex.release(); this.uvTex.release(); } } public void render() { if (this.nv21Data == null) return; this.program.use(); int i = this.program.getAttribute(ShaderProgram.ATTRIBUTE_SLOT.TEXUV); GLES20.glVertexAttribPointer(i, 2, 5126, false, 0, this.texCoords); GLES20.glEnableVertexAttribArray(i); this.nv21Data.position(0); this.yTex.bindTU(33984); this.yTex.setData(this.nv21Data, this.width, this.height); this.nv21Data.position(this.width * this.height); this.uvTex.bindTU(33985); this.uvTex.setData(this.nv21Data.slice(), this.width / 2, this.height / 2); GLES20.glUniform1i(this.program.getUniform(ShaderProgram.UNIFORM_SLOT.TEX_Y), 0); GLES20.glUniform1i(this.program.getUniform(ShaderProgram.UNIFORM_SLOT.TEX_UV), 1); this.quad.bind(this.program.getAttribute(ShaderProgram.ATTRIBUTE_SLOT.VERTEX)); this.quad.draw(Polygon.DrawMode.SOLID); } } /* Location: C:\apktool\SmaliToJavaTUTKit\jd-gui-0.3.5.windows\classes-dex2jar.jar * Qualified Name: com.google.android.apps.unveil.env.gl.NV21Quad * JD-Core Version: 0.6.2 */
Python
UTF-8
540
2.546875
3
[]
no_license
""" @Time : 2020/12/29 10:35 @Author : Affreden @Email : affreden@gmail.com @File : test.py """ import torch import random as rd import time import numpy as np time = time.time() rd.seed(1) temp1 = torch.tensor([rd.randint(0, 9) for i in range(48)]) torch.seed() temp2 = torch.randn(2, 3, 4) print(temp2.tolist()) temp3 = temp2.permute(2, 1, 0) print(temp3.tolist()) temp1 = torch.tensor([rd.randint(0, 9) for i in range(24)]) torch.seed() temp2 = torch.randn(2, 3, 4) print(temp2.tolist()) temp3=temp2.permute(0, 2, 1) print(temp3.tolist())
JavaScript
UTF-8
2,955
3.078125
3
[]
no_license
window.addEventListener("load", () => { interactionBar() let obj = { "Alo": 0, "Cpc": 0, "Cpca": 0, "Pp": 100 } atualizarGrafico(obj) }) //Capturar nome usuario let interactionBar = () => { do { nome = prompt("Digite seu nome!"); } while (nome === null || nome === "") { document.getElementById("alert").innerHTML = `Olá ${nome}. Seja bem vindo(a) ao GrupoServices. Digite uma UF no campo acima para visualizar os graficos de ALO, CPC, CPA e PP de cada estado.` } } //Evitar tecla enter para recarregar pagina window.addEventListener("keydown", function (e) { if (e.keyCode == 13) { e.preventDefault(); alert("Você deve clicar em Buscar") return false; } }) //capturar input e fazer requisicao http do backend. document.getElementById("button").onclick = function (input) { if (input = document.getElementById("input").value === "") { alert("Digite o UF ") document.getElementById("alert").innerHTML = `${nome}, você deve digitar um UF` return } else { input = document.getElementById("input").value document.getElementById("alert").innerHTML = `Legal ${nome}, os dados acima são referentes ao estado: ${input}` var url = "http://localhost:3000/?estado=" + input; var xhttp = new XMLHttpRequest(); xhttp.open("GET", url, false); xhttp.send(); dados = xhttp.response; let dadosBrutos = JSON.parse(dados); console.log(dadosBrutos); if (dadosBrutos.Alo === 0) { alert("A UF informado é invalida") document.getElementById("alert").innerHTML = `Ops!!! ${nome}, os dados informados sao invalidos ` return } return atualizarGrafico(dadosBrutos);//Dados para popular graficos } } //Funcao com grafico inserido para atualizacao. function atualizarGrafico(dadosBrutos) { if (!dadosBrutos) return; am4core.ready(function () { // Themes begin am4core.useTheme(am4themes_dark); am4core.useTheme(am4themes_animated); // Themes end // Create chart instance var chart = am4core.create("chartdiv", am4charts.PieChart); // Add data chart.data = [{ "data": "Alo", "valor": dadosBrutos.Alo }, { "data": "Cpc", "valor": dadosBrutos.Cpc }, { "data": "Cpca", "valor": dadosBrutos.Cpca }, { "data": "Pp", "valor": dadosBrutos.Pp } ]; // Add and configure Series var pieSeries = chart.series.push(new am4charts.PieSeries()); pieSeries.dataFields.value = "valor"; pieSeries.dataFields.category = "data"; pieSeries.slices.template.stroke = am4core.color("#fff"); pieSeries.slices.template.strokeOpacity = 1; // This creates initial animation pieSeries.hiddenState.properties.opacity = 1; pieSeries.hiddenState.properties.endAngle = -90; pieSeries.hiddenState.properties.startAngle = -90; chart.hiddenState.properties.radius = am4core.percent(0); }); }
C#
UTF-8
1,194
2.515625
3
[]
no_license
using System; using System.Windows.Forms; namespace TaxAideFlashShare { public partial class ProgessOverall : Form { delegate void EnableOKCallBack(); public ProgessOverall() { InitializeComponent(); } public void ProgShow() { this.ShowDialog(); } public void AddTxtLine(string updateTxt) { this.statusText.Text += "\r\n" +updateTxt; this.Update(); } public void EnableOk() { if (this.buttonOK.InvokeRequired) //see http://msdn.microsoft.com/en-us/library/ms171728(VS.90).aspx { EnableOKCallBack d = new EnableOKCallBack(EnableOk); this.Invoke(d); } else { buttonOK.Enabled = true; this.Update(); } } private void buttonCancel_Click(object sender, EventArgs e) { Environment.Exit(1); } private void buttonOK_Click(object sender, EventArgs e) { Environment.Exit(0); } } }
SQL
UTF-8
939
2.828125
3
[]
no_license
create table tq84_virtual_test_4 ( c1 number ); insert into tq84_virtual_test_4 (c1) values (1); insert into tq84_virtual_test_4 (c1) values (2); insert into tq84_virtual_test_4 (c1) values (3); insert into tq84_virtual_test_4 (c1) values (4); commit; create or replace package tq84_virtual_test_pck_4 as function r(c1_ in number) return number deterministic; end tq84_virtual_test_pck_4; / create or replace package body tq84_virtual_test_pck_4 as function r(c1_ in number) return number deterministic is v number; begin select sum(c1) into v from tq84_virtual_test_4 where c1 != c1_; return v; end r; end tq84_virtual_test_pck_4; / alter table tq84_virtual_test_4 add (c2 as (tq84_virtual_test_pck_4.r(c1))); select * from tq84_virtual_test_4; drop table tq84_virtual_test_4; drop package tq84_virtual_test_pck_4;
PHP
UTF-8
1,722
3.09375
3
[]
no_license
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Php Badwords</title> </head> <body> <h2>Titolo del paragrafo</h2> <!-- START First Section PHP Code--> <?php //Creo una variabile contenente un paragrafo di testo: $paragrafo = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; //Stampo a schermo, il contenuto della var 'paragrafo': echo $paragrafo; ?> <!-- END First Section PHP Code--> <h4>La lunghezza del paragrafo è di caratteri: <!-- START Second Section PHP Code--> <?php //Calcola la lunghezza di una stringa e la stampa a schermo attraverso 'echo': echo strlen ( $paragrafo ); ?> <!-- END Second Section PHP Code--> </h4> <h3> Sostituisco la "bad word" passata in GET (http://localhost/php-badwords/index.php?badWord=Lorem) con 3 asterischi: </h3> <!-- START Third Section PHP Code--> <?php //Sostituisco la "bad word" ("Lorem" in questo caso) passata in GET (http://localhost/php-badwords/index.php?nome=Lorem) con 3 asterischi: $paragrafo = str_replace($_GET['badWord'], '***', $paragrafo); echo $paragrafo; ?> <!-- END Third Section PHP Code--> </body> </html>
Java
UTF-8
4,531
2.34375
2
[ "Apache-2.0", "EPL-1.0", "LGPL-2.1-only", "EPL-2.0" ]
permissive
/* * (C) Copyright 2003-2021, by Barak Naveh and Contributors. * * JGraphT : a free Java graph-theory library * * See the CONTRIBUTORS.md file distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the * GNU Lesser General Public License v2.1 or later * which is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html. * * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later */ package mb.pie.graph; import java.io.*; import java.util.*; /** * A base implementation for the intrusive edges specifics. * * @author Barak Naveh * @author Dimitrios Michail * * @param <V> the graph vertex type * @param <E> the graph edge type * @param <IE> the intrusive edge type */ abstract class BaseIntrusiveEdgesSpecifics<V, E, IE extends IntrusiveEdge> implements Serializable { private static final long serialVersionUID = -7498268216742485L; protected Map<E, IE> edgeMap; protected transient Set<E> unmodifiableEdgeSet = null; /** * Constructor * * @param edgeMap the map to use for storage */ public BaseIntrusiveEdgesSpecifics(Map<E, IE> edgeMap) { this.edgeMap = Objects.requireNonNull(edgeMap); } /** * Check if an edge exists * * @param e the edge * @return true if the edge exists, false otherwise */ public boolean containsEdge(E e) { return edgeMap.containsKey(e); } /** * Get the edge set. * * @return an unmodifiable edge set */ public Set<E> getEdgeSet() { if (unmodifiableEdgeSet == null) { unmodifiableEdgeSet = Collections.unmodifiableSet(edgeMap.keySet()); } return unmodifiableEdgeSet; } /** * Remove an edge. * * @param e the edge */ public void remove(E e) { edgeMap.remove(e); } /** * Get the source of an edge. * * @param e the edge * @return the source vertex of an edge */ public V getEdgeSource(E e) { IntrusiveEdge ie = getIntrusiveEdge(e); if (ie == null) { throw new IllegalArgumentException("no such edge in graph: " + e.toString()); } return TypeUtil.uncheckedCast(ie.source); } /** * Get the target of an edge. * * @param e the edge * @return the target vertex of an edge */ public V getEdgeTarget(E e) { IntrusiveEdge ie = getIntrusiveEdge(e); if (ie == null) { throw new IllegalArgumentException("no such edge in graph: " + e.toString()); } return TypeUtil.uncheckedCast(ie.target); } /** * Get the weight of an edge. * * @param e the edge * @return the weight of an edge */ public double getEdgeWeight(E e) { return Graph.DEFAULT_EDGE_WEIGHT; } /** * Set the weight of an edge * * @param e the edge * @param weight the new weight */ public void setEdgeWeight(E e, double weight) { throw new UnsupportedOperationException(); } /** * Add a new edge * * @param e the edge * @param sourceVertex the source vertex of the edge * @param targetVertex the target vertex of the edge * @return true if the edge was added, false if the edge was already present */ public abstract boolean add(E e, V sourceVertex, V targetVertex); protected boolean addIntrusiveEdge(E edge, V sourceVertex, V targetVertex, IE e) { if (e.source == null && e.target == null) { // edge not yet in any graph e.source = sourceVertex; e.target = targetVertex; } else if (e.source != sourceVertex || e.target != targetVertex) { // Edge already contained in this or another graph but with different touching // edges. Reject the edge to not reset the touching vertices of the edge. // Changing the touching vertices causes major inconsistent behavior. throw new IntrusiveEdgeException(e.source, e.target); } return edgeMap.putIfAbsent(edge, e) == null; } /** * Get the intrusive edge of an edge. * * @param e the edge * @return the intrusive edge */ protected abstract IE getIntrusiveEdge(E e); }
Python
UTF-8
250
3.03125
3
[]
no_license
from turtle import * tracer(False) speed(0) setup(1400, 700, 0, 0) colormode(255) pensize(50) goto(-750, 380) seth(-90) def f(): fd(1300) seth(0) fd(6) r = 95 for i in range(50): r += 3 pencolor((r, 29, 73)) f() lt(90) f() rt(90) done()
JavaScript
UTF-8
284
3.21875
3
[]
no_license
function maximumToys(prices, k) { let count = 0; let sorted = prices.sort( (a,b) => {return a - b} ); for(let i = 0;i<sorted.length;i++) { if(k - sorted[i] >= 0) { k -= sorted[i]; count++; } } return count; }