language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
1,471
2.890625
3
[]
no_license
// // EventBase.h // ObserverPattern // // Created by Mike Allison on 3/28/15. // // #pragma once using EventType = std::string; using EventBaseRef = std::shared_ptr<class EventBase>; class EventBase { public: const double& getTimeStamp(){ return mTimeStamp; } virtual const EventType& getType() = 0; virtual ~EventBase(){} protected: EventBase( const double& timeStamp ):mTimeStamp(timeStamp){} private: double mTimeStamp; }; using PrintNameEventRef = std::shared_ptr< class PrintNameEvent >; class PrintNameEvent : public EventBase { public: static PrintNameEventRef create(){ return PrintNameEventRef( new PrintNameEvent() ); } static EventType Type; const EventType& getType() override; ~PrintNameEvent(){} private: PrintNameEvent():EventBase( ci::app::getElapsedSeconds() ){} }; using SayThisEventRef = std::shared_ptr< class SayThisEvent >; class SayThisEvent : public EventBase { public: static SayThisEventRef create( const std::string& phrase ){ return SayThisEventRef( new SayThisEvent( phrase ) ); } static EventType Type; const EventType& getType() override; const std::string& getPhrase() { return mPhrase; } ~SayThisEvent(){} private: SayThisEvent( const std::string& phrase ):EventBase( ci::app::getElapsedSeconds() ), mPhrase(phrase) {} std::string mPhrase; };
Java
UTF-8
789
2.046875
2
[]
no_license
package com.edu.feicui.uidc.retrofit; import android.app.Activity; import android.os.Bundle; /** * Created by Administrator on 2017-1-9. */ public class RetrofitActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } // private void onClick() { // RetrofitNetClient.getInstances().register("123").enqueue(new Callback<ResponseBody>() { // @Override // public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { // ResponseBody body = response.body(); // // } // // @Override // public void onFailure(Call<ResponseBody> call, Throwable t) { // // } // }); // } }
C++
UTF-8
1,463
3.203125
3
[]
no_license
// ConsoleApplication12.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí. // #include "pch.h" #include <iostream> #include <conio.h> using namespace std; int main() { //variables int sueldo; char tipoV, tarjetaC, cargaF; int puntoS, puntosTv, puntosTc, puntosCf, puntosF; char prestamoA, prestamoB; bool otorgaP, prestamoX, prestamoY; //entrada cout << "Sueldo mensual : " << endl; cin >> sueldo; cout << "Tipo de vivienda (P: pariente; A: alquilada; M: propia) : " << endl; cin >> tipoV; cout << "Tarjeta de credito (N: no tiene; S: si tiene) : " << endl; cin >> tarjetaC; cout << "Tiene carga familiar (N: no tiene; S: si tiene) : " << endl; cin >> cargaF; //logica puntoS = ((sueldo < 1500) * 6) + (((1500 <= sueldo) && (sueldo <= 6000)) * 12) + ((6000 < sueldo) * 18); puntosTv = ((tipoV == 'P') * 2) + ((tipoV == 'A') * 5) + ((tipoV == 'M') * 10); puntosTc = ((tarjetaC == 'N') * 0) + ((tarjetaC == 'S') * 6); puntosCf = ((cargaF == 'S') * 6) + ((cargaF == 'N') * 3); puntosF = puntoS + puntosTv + puntosTc + puntosCf; otorgaP = (puntosF > 20); prestamoX = otorgaP; prestamoY = !otorgaP; prestamoA = prestamoX * 'S'; prestamoB = prestamoY * 'N'; //salida cout << "Puntaje Obtenido : " << puntosF << endl; cout << "Se le otorga el prestamos (N : no; S: si) : " << prestamoA << prestamoB << endl; _getch(); return 0; }
Java
UTF-8
793
2.515625
3
[ "Apache-2.0" ]
permissive
package com.communote.server.core.common.caching; /** * Common cache key class for cases where there is only one element per application that can be * cached. * * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> */ public class ApplicationSingleElementCacheKey implements CacheKey { /** * {@inheritDoc} */ public String getCacheKeyString() { // nothing special because there is only one cacheable configuration per client return "0"; } /** * {@inheritDoc} */ public boolean isUniquePerClient() { return false; } /** * {@inheritDoc} */ @Override public String toString() { return getCacheKeyString(); } }
C#
UTF-8
1,887
2.59375
3
[]
no_license
using RealPage.Properties.Domain.Entity; using RealPage.Properties.Domain.Interface; using RealPage.Properties.Infrastructure.Interface; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace RealPage.Properties.Domain.Core { public class UsersDomain : IUsersDomain { private readonly IUsersRepository _usersRepository; public UsersDomain(IUsersRepository usersRepository) { _usersRepository = usersRepository; } public async Task<User> Authenticate(string userName, string password) { return await _usersRepository.Authenticate(userName, password); } public async Task<bool> Add(User user) { try { await _usersRepository.AddAsync(user); return true; } catch (Exception) { return false; } } public async Task<bool> Update(User user) { try { await _usersRepository.UpdateAsync(user); return true; } catch (Exception) { return false; } } public async Task<bool> Delete(int userId) { try { var prop = await _usersRepository.GetByIdAsync(userId); await _usersRepository.DeleteAsync(prop); return true; } catch (Exception) { return false; } } public async Task<User> Get(int userId) { return await _usersRepository.GetByIdAsync(userId); } public async Task<IEnumerable<User>> GetAll() { return await _usersRepository.GetAllAsync(); } } }
Markdown
UTF-8
2,981
3.34375
3
[]
no_license
## Week Three - Module 4 Recap Fork this respository. Answer the questions to the best of your ability. Try to answer them with limited amount of external research. These questions cover the majority of what we've learned this week. Note: When you're done, submit a PR. 1. At a high level, what is Node? - Node is a Javascript that is capable of being written and run in a server environment. 2. What is Express? What is Express similar to in the Ruby world? - Express is a framework that allows Node written applications to be used as web applications. 3. How do we setup a route when creating an API with Node and Express? Please provide a code snippet. - The app (which is set to express along with other uses of functions) is set. The route is then set using the app. For example, a GET to a "Jobs" route would look like: ``` app.get('/jobs', callbackfunction() {}) ``` 4. What do we use Knex for? - Knex is used to connect server-side Node code to a database. 5. How could you organize your code to follow the MVC design pattern in your Quantified Self project? - The Server.js file can be used as the controller/routes. Server.js would house the actual route definitions (GET, POST, etc.). A separate folder containing database queries for given resources can be used as the "Models". Views are handled by the front end AJAX and API calls. However, we could house those in a views subdirectory should we want to pull the two applications together. 6. How do you execute raw SQL in node? - Use database.raw('SUPER AWESOME sql CODE goes HERE') 7. What are some advantages to having your front end and back end code live in separate applications? What are some disadvantages? - This is a tough one... - Advantages: Since all code lives in same application, theoretically, the communication between the front and back end would be faster than if they were housed on separate servers. - Disadvantages: Intertwining the code could get messy. A small "fix" on the back end could break the front end (vs just not send the correct data should the applications live separately.) #### Review 8. Describe DNS. - Domain Name Servers. DNS allows the navigation and look-up of websites by name (www.google.com) to be translated to the hardcoded IP address of that named website (i.e. 192.168.0.1). 9. What does writing clean code mean to you? - Writing clean code means readable, well-factored, reusable and not "esoteric", for lack of a better term. It needs to have potential future use for later development. 10. If you were building an application that models hotels, what classes would you need? What classes would be responsible for what functionality? - Room: Bed, Shower, Layout, Size - Floor: Consist of Rooms, Elevators, Layout, Size - Person: Names, Type (worker vs. customer) - Job: Job type, many persons - Hotel: Consist of Floors, jobs, customer - (This could be constructed in many different ways and at a lot of different levels of granularity)
Markdown
UTF-8
922
3.390625
3
[]
no_license
# 1217 有 n 个筹码。第 i 个筹码的位置是 position[i] 。 我们需要把所有筹码移到同一个位置。在一步中,我们可以将第 i 个筹码的位置从 position[i] 改变为: position[i] + 2 或 position[i] - 2 ,此时 cost = 0 position[i] + 1 或 position[i] - 1 ,此时 cost = 1 返回将所有筹码移动到同一位置上所需要的 最小代价 。 示例 1: 输入:position = [1,2,3] 输出:1 解释:第一步:将位置3的筹码移动到位置1,成本为0。 第二步:将位置2的筹码移动到位置1,成本= 1。 总成本是1。 示例 2: 输入:position = [2,2,2,3,3] 输出:2 解释:我们可以把位置3的两个筹码移到位置2。每一步的成本为1。总成本= 2。 示例 3: 输入:position = [1,1000000000] 输出:1 提示: 1 <= chips.length <= 100 1 <= chips[i] <= 10^9 Related Topics 贪心 数组 数学 👍 159 👎 0
Python
UTF-8
37,187
2.734375
3
[ "Apache-2.0" ]
permissive
# Copyright 2020 Google LLC # # 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 # # https://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. # Lint as: python3 """Utilities for geometric operations in tensorflow.""" import math import numpy as np import tensorflow as tf # ldif is an internal package, should be imported last. # pylint: disable=g-bad-import-order from ldif.util import np_util from ldif.util import camera_util from ldif.util import tf_util # pylint: enable=g-bad-import-order def ray_sphere_intersect(ray_start, ray_direction, sphere_center, sphere_radius, max_t): """Intersect rays with each of a set of spheres. Args: ray_start: Tensor with shape [batch_size, ray_count, 3]. The end point of the rays. In the same coordinate space as the spheres. ray_direction: Tensor with shape [batch_size, ray_count, 3]. The extant ray direction. sphere_center: Tensor with shape [batch_size, sphere_count, 3]. The center of the spheres. sphere_radius: Tensor with shape [batch_size, sphere_count, 1]. The radius of the spheres. max_t: The maximum intersection distance. Returns: intersections: Tensor with shape [batch_size, ray_count, sphere_count]. If no intersection is found between [0, max_t), then the value will be max_t. """ # We apply the algebraic solution: batch_size, ray_count = ray_start.get_shape().as_list()[:2] sphere_count = sphere_center.get_shape().as_list()[1] ray_direction = tf.reshape(ray_direction, [batch_size, ray_count, 1, 3]) ray_start = tf.reshape(ray_start, [batch_size, ray_count, 1, 3]) sphere_center = tf.reshape(sphere_center, [batch_size, 1, sphere_count, 3]) sphere_radius = tf.reshape(sphere_radius, [batch_size, 1, sphere_count, 1]) a = 1.0 b = 2.0 * ray_direction * (ray_start - sphere_center) ray_sphere_distance = tf.reduce_sum( tf.square(ray_start - sphere_center), axis=-1, keep_dims=True) c = ray_sphere_distance - tf.square(sphere_radius) discriminant = tf.square(b) - 4 * a * c # Assume it's positive, then zero out later: ta = tf.divide((-b + tf.sqrt(discriminant)), 2 * a) tb = tf.divide((-b - tf.sqrt(discriminant)), 2 * a) t0 = tf.minimum(ta, tb) t1 = tf.maximum(ta, tb) t = tf.where(t0 > 0, t0, t1) intersection_invalid = tf.logical_or( tf.logical_or(discriminant < 0, t < 0), t > max_t) t = tf.where(intersection_invalid, max_t * tf.ones_like(t), t) return t def to_homogeneous(t, is_point): """Makes a homogeneous space tensor given a tensor with ultimate coordinates. Args: t: Tensor with shape [..., K], where t is a tensor of points in K-dimensional space. is_point: Boolean. True for points, false for directions Returns: Tensor with shape [..., K+1]. t padded to be homogeneous. """ padding = 1 if is_point else 0 rank = len(t.get_shape().as_list()) paddings = [] for _ in range(rank): paddings.append([0, 0]) paddings[-1][1] = 1 return tf.pad( t, tf.constant(paddings), mode='CONSTANT', constant_values=padding) def transform_points_with_normals(points, tx, normals=None): """Transforms a pointcloud with normals to a new coordinate frame. Args: points: Tensor with shape [batch_size, point_count, 3 or 6]. tx: Tensor with shape [batch_size, 4, 4]. Takes column-vectors from the current frame to the new frame as T*x. normals: Tensor with shape [batch_size, point_count, 3] if provided. None otherwise. If the points tensor contains normals, this should be None. Returns: If tensor 'points' has shape [..., 6], then a single tensor with shape [..., 6] in the new frame. If 'points' has shape [..., 3], then returns either one or two tensors of shape [..., 3] depending on whether 'normals' is None. """ if len(points.shape) != 3: raise ValueError(f'Invalid points shape: {points.get_shape().as_list()}') if len(tx.shape) != 3: raise ValueError(f'Invalid tx shape: {tx.get_shape().as_list()}') are_concatenated = points.shape[-1] == 6 if are_concatenated: points, normals = tf.split(points, [3, 3], axis=-1) transformed_samples = apply_4x4( points, tx, are_points=True, batch_rank=1, sample_rank=1) if normals is not None: transformed_normals = apply_4x4( normals, tf.linalg.inv(tf.transpose(tx, perm=[0, 2, 1])), are_points=False, batch_rank=1, sample_rank=1) transformed_normals = transformed_normals / ( tf.linalg.norm(transformed_normals, axis=-1, keepdims=True) + 1e-8) if are_concatenated: return tf.concat([transformed_samples, transformed_normals], axis=-1) if normals is not None: return transformed_samples, transformed_normals return transformed_samples def transform_featured_points(points, tx): """Transforms a pointcloud with features. Args: points: Tensor with shape [batch_size, point_count, 3+feature_count]. tx: Tensor with shape [batch_size, 4, 4]. Returns: Tensor with shape [batch_size, point_count, 3+feature_count]. """ feature_count = points.get_shape().as_list()[-1] - 3 if feature_count == 0: xyz = points features = None else: xyz, features = tf.split(points, [3, feature_count], axis=2) xyz = apply_4x4(xyz, tx, are_points=True, batch_rank=1, sample_rank=1) if feature_count: return tf.concat([xyz, features], axis=2) return xyz def rotation_to_tx(rot): """Maps a 3x3 rotation matrix to a 4x4 homogeneous matrix. Args: rot: Tensor with shape [..., 3, 3]. Returns: Tensor with shape [..., 4, 4]. """ batch_dims = rot.get_shape().as_list()[:-2] empty_col = tf.zeros(batch_dims + [3, 1], dtype=tf.float32) rot = tf.concat([rot, empty_col], axis=-1) hom_row = tf.eye(4, batch_shape=batch_dims)[..., 3:4, :] return tf.concat([rot, hom_row], axis=-2) def extract_points_near_origin(points, count, features=None): """Returns the points nearest to the origin in a pointcloud. Args: points: Tensor with shape [batch_size, point_count, 3 or more]. count: The number of points to extract. features: Tensor with shape [batch_size, point_count, feature_count] if present. None otherwise. Returns: Either one tensor of size [batch_size, count, 3 or 6] or two tensors of size [batch_size, count, 3], depending on whether normals was provided and the shape of the 'points' tensor. """ are_concatenated = points.get_shape().as_list()[-1] > 3 if are_concatenated: feature_count = points.get_shape().as_list()[-1] - 3 original = points points, features = tf.split(points, [3, feature_count], axis=-1) else: assert points.get_shape().as_list()[-1] == 3 candidate_dists = tf.linalg.norm(points, axis=-1) _, selected_indices = tf.math.top_k(-candidate_dists, k=count, sorted=False) if are_concatenated: return tf.gather(original, selected_indices, batch_dims=1) else: selected_points = tf.gather(points, selected_indices, batch_dims=1) if features is not None: return selected_points, tf.gather( features, selected_indices, batch_dims=1) return selected_points def local_views_of_shape(global_points, world2local, local_point_count, global_normals=None, global_features=None, zeros_invalid=False, zero_threshold=1e-6, expand_region=True, threshold=4.0): """Computes a set of local point cloud observations from a global observation. It is assumed for optimization purposes that global_point_count >> local_point_count. Args: global_points: Tensor with shape [batch_size, global_point_count, 3]. The input observation point cloud in world space. world2local: Tensor with shape [batch_size, frame_count, 4, 4]. Each 4x4 matrix maps from points in world space to points in a local frame. local_point_count: Integer. The number of points to output in each local frame. Whatever this value, the local_point_count closest points to each local frame origin will be returned. global_normals: Tensor with shape [batch_size, global_point_count, 3]. The input observation point cloud's normals in world space. Optional. global_features: Tensor with shape [batch_size, global_point_count, feature_count]. The input observation point cloud features, in any space. Optional. zeros_invalid: Whether to consider the vector [0, 0, 0] to be invalid. zero_threshold: Values less than this in magnitude are considered to be 0. expand_region: Whether to expand outward from the threshold region. If false, fill with zeros. threshold: The distance threshold. Returns: local_points: Tensor with shape [batch_size, frame_count, local_point_count, 3]. local_normals: Tensor with shape [batch_size, frame_count, local_point_count, 3]. None if global_normals not provided. local_features: Tensor with shape [batch_size, frame_count, local_point_count, feature_count]. Unlike the local normals and points, these are not transformed because there may or may not be a good transformation to apply, depending on what the features are. But they will be the features associated with the local points that were chosen. None if global_features not provided. """ # Example use case: batch_size = 64, global_point_count = 100000 # local_point_count = 1000, frame_count = 25. Then: # global_points has size 64*100000*3*4 = 73mb # local_points has size 64*1000*25*3*4 = 18mb # If we made an intermediate tensor with shape [batch_size, frame_count, # global_point_count, 3] -> 64 * 25 * 100000 * 3 * 4 = 1.8 Gb -> bad. batch_size, _, _ = global_points.get_shape().as_list() if zeros_invalid: # If we just set the global points to be very far away, they won't be a # nearest neighbor abs_zero = False if abs_zero: is_zero = tf.reduce_all( tf.equal(global_points, 0.0), axis=-1, keepdims=True) else: is_zero = tf.reduce_all( tf.abs(global_points) < zero_threshold, axis=-1, keepdims=True) global_points = tf.where_v2(is_zero, 100.0, global_points) _, frame_count, _, _ = world2local.get_shape().as_list() local2world = tf.matrix_inverse(world2local) # *sigh* oh well, guess we have to do the transform: tiled_global = tf.tile( tf.expand_dims(to_homogeneous(global_points, is_point=True), axis=1), [1, frame_count, 1, 1]) all_local_points = tf.matmul(tiled_global, world2local, transpose_b=True) distances = tf.norm(all_local_points, axis=-1) # thresh = 4.0 # TODO(kgenova) This is potentially a problem because it could introduce # randomness into the pipeline at inference time. probabilities = tf.random.uniform(distances.get_shape().as_list()) is_valid = distances < threshold sample_order = tf.where(is_valid, probabilities, -distances) _, top_indices = tf.math.top_k( sample_order, k=local_point_count, sorted=False) local_points = tf.gather(all_local_points, top_indices, batch_dims=2, axis=-2) local_points = tf.ensure_shape( local_points[..., :3], [batch_size, frame_count, local_point_count, 3]) is_valid = tf.expand_dims(is_valid, axis=-1) # log.info('is_valid shape: ', is_valid.get_shape().as_list()) # log.info('top_indices shape: ', top_indices.get_shape().as_list()) # log.info('all_local_points shape: ', all_local_points.get_shape().as_list()) points_valid = tf.gather(is_valid, top_indices, batch_dims=2, axis=-2) # points_valid = tf.expand_dims(points_valid, axis=-1) points_valid = tf.ensure_shape( points_valid, [batch_size, frame_count, local_point_count, 1]) if not expand_region: local_points = tf.where_v2(points_valid, local_points, 0.0) # valid_feature = tf.cast(points_valid, dtype=tf.float32) if global_normals is not None: tiled_global_normals = tf.tile( tf.expand_dims(to_homogeneous(global_normals, is_point=False), axis=1), [1, frame_count, 1, 1]) # Normals get transformed by the inverse-transpose matrix: all_local_normals = tf.matmul( tiled_global_normals, local2world, transpose_b=False) local_normals = tf.gather( all_local_normals, top_indices, batch_dims=2, axis=-2) # Remove the homogeneous coordinate now. It isn't a bug to normalize with # it since it's zero, but it's confusing. local_normals = tf.math.l2_normalize(local_normals[..., :3], axis=-1) local_normals = tf.ensure_shape( local_normals, [batch_size, frame_count, local_point_count, 3]) else: local_normals = None if global_features is not None: feature_count = global_features.get_shape().as_list()[-1] local_features = tf.gather( global_features, top_indices, batch_dims=1, axis=-2) local_features = tf.ensure_shape( local_features, [batch_size, frame_count, local_point_count, feature_count]) else: local_features = None return local_points, local_normals, local_features, points_valid def chamfer_distance(pred, target): """Computes the chamfer distance between two point sets, in both directions. Args: pred: Tensor with shape [..., pred_point_count, n_dims]. target: Tensor with shape [..., target_point_count, n_dims]. Returns: pred_to_target, target_to_pred. pred_to_target: Tensor with shape [..., pred_point_count, 1]. The distance from each point in pred to the closest point in the target. target_to_pred: Tensor with shape [..., target_point_count, 1]. The distance from each point in target to the closet point in the prediction. """ with tf.name_scope('chamfer_distance'): # batching_dimensions = pred.get_shape().as_list()[:-2] # batching_rank = len(batching_dimensions) # pred_norm_squared = tf.matmul(pred, pred, transpose_b=True) # target_norm_squared = tf.matmul(target, target, transpose_b=True) # target_mul_pred_t = tf.matmul(pred, target, transpose_b=True) # pred_mul_target_t = tf.matmul(target, pred, transpose_b=True) differences = tf.expand_dims( pred, axis=-2) - tf.expand_dims( target, axis=-3) squared_distances = tf.reduce_sum(differences * differences, axis=-1) # squared_distances = tf.matmul(differences, differences, transpose_b=True) # differences = pred - tf.transpose(target, perm=range(batching_rank) + # [batching_rank+2, batching_rank+1]) pred_to_target = tf.reduce_min(squared_distances, axis=-1) target_to_pred = tf.reduce_min(squared_distances, axis=-2) pred_to_target = tf.expand_dims(pred_to_target, axis=-1) target_to_pred = tf.expand_dims(target_to_pred, axis=-1) return tf.sqrt(pred_to_target), tf.sqrt(target_to_pred) def dodeca_parameters(dodeca_idx): """Computes the viewpoint, centroid, and up vectors for the dodecahedron.""" gr = (1.0 + math.sqrt(5.0)) / 2.0 rgr = 1.0 / gr viewpoints = [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1], [0, gr, rgr], [0, gr, -rgr], [0, -gr, rgr], [0, -gr, -rgr], [rgr, 0, gr], [rgr, 0, -gr], [-rgr, 0, gr], [-rgr, 0, -gr], [gr, rgr, 0], [gr, -rgr, 0], [-gr, rgr, 0], [-gr, -rgr, 0]] viewpoint = 0.6 * np.array(viewpoints[dodeca_idx], dtype=np.float32) centroid = np.array([0., 0., 0.], dtype=np.float32) world_up = np.array([0., 1., 0.], dtype=np.float32) return viewpoint, centroid, world_up def get_camera_to_world(viewpoint, center, world_up): """Computes a 4x4 mapping from camera space to world space.""" towards = center - viewpoint towards = towards / np.linalg.norm(towards) right = np.cross(towards, world_up) right = right / np.linalg.norm(right) cam_up = np.cross(right, towards) cam_up = cam_up / np.linalg.norm(cam_up) rotation = np.stack([right, cam_up, -towards], axis=1) rotation_4x4 = np.eye(4) rotation_4x4[:3, :3] = rotation camera_to_world = rotation_4x4.copy() camera_to_world[:3, 3] = viewpoint return camera_to_world def get_dodeca_camera_to_worlds(): camera_to_worlds = [] for i in range(20): camera_to_worlds.append(get_camera_to_world(*dodeca_parameters(i))) camera_to_worlds = np.stack(camera_to_worlds, axis=0) return camera_to_worlds def gaps_depth_render_to_xyz(model_config, depth_image, camera_parameters): """Transforms a depth image to camera space assuming its dodeca parameters.""" # TODO(kgenova) Extract viewpoint, width, height from camera parameters. del camera_parameters depth_image_height, depth_image_width = depth_image.get_shape().as_list()[1:3] if model_config.hparams.didx == 0: viewpoint = np.array([1.03276, 0.757946, -0.564739]) towards = np.array([-0.737684, -0.54139, 0.403385]) # = v/-1.4 up = np.array([-0.47501, 0.840771, 0.259748]) else: assert False towards = towards / np.linalg.norm(towards) right = np.cross(towards, up) right = right / np.linalg.norm(right) up = np.cross(right, towards) up = up / np.linalg.norm(up) rotation = np.stack([right, up, -towards], axis=1) rotation_4x4 = np.eye(4) rotation_4x4[:3, :3] = rotation camera_to_world = rotation_4x4.copy() camera_to_world[:3, 3] = viewpoint camera_to_world = tf.constant(camera_to_world.astype(np.float32)) world_to_camera = tf.reshape(tf.matrix_inverse(camera_to_world), [1, 4, 4]) world_to_camera = tf.tile(world_to_camera, [model_config.hparams.bs, 1, 1]) xyz_image, _, _ = depth_image_to_xyz_image( depth_image, world_to_camera, xfov=0.5) xyz_image = tf.reshape( xyz_image, [model_config.hparams.bs, depth_image_height, depth_image_width, 3]) return xyz_image def angle_of_rotation_to_2d_rotation_matrix(angle_of_rotation): """Given a batch of rotations, create a batch of 2d rotation matrices. Args: angle_of_rotation: Tensor with shape [batch_size]. Returns: Tensor with shape [batch_size, 2, 2] """ c = tf.cos(angle_of_rotation) s = tf.sin(angle_of_rotation) top_row = tf.stack([c, -s], axis=1) bottom_row = tf.stack([s, c], axis=1) return tf.stack([top_row, bottom_row], axis=1) def fractional_vector_projection(e0, e1, p, falloff=2.0): """Returns a fraction describing whether p projects inside the segment e0 e1. If p projects inside the segment, the result is 1. If it projects outside, the result is a fraction that is always greater than 0 but monotonically decreasing as the distance to the inside of the segment increase. Args: e0: Tensor with two elements containing the first endpoint XY locations. e1: Tensor with two elements containing the second endpoint XY locations. p: Tensor with shape [batch_size, 2] containing the query points. falloff: Float or Scalar Tensor specifying the softness of the falloff of the projection. Larger means a longer falloff. """ with tf.name_scope('fractional-vector-projection'): batch_size = p.shape[0].value p = tf.reshape(p, [batch_size, 2]) e0 = tf.reshape(e0, [1, 2]) e1 = tf.reshape(e1, [1, 2]) e01 = e1 - e0 # Normalize for vector projection: e01_norm = tf.sqrt(e01[0, 0] * e01[0, 0] + e01[0, 1] * e01[0, 1]) e01_normalized = e01 / tf.reshape(e01_norm, [1, 1]) e0p = p - e0 e0p_dot_e01_normalized = tf.matmul( tf.reshape(e0p, [1, batch_size, 2]), tf.reshape(e01_normalized, [1, 1, 2]), transpose_b=True) e0p_dot_e01_normalized = tf.reshape(e0p_dot_e01_normalized, [batch_size]) / e01_norm if falloff is None: left_sided_inside = tf.cast( tf.logical_and(e0p_dot_e01_normalized >= 0, e0p_dot_e01_normalized <= 1), dtype=tf.float32) return left_sided_inside # Now that we have done the left side, do the right side: e10_normalized = -e01_normalized e1p = p - e1 e1p_dot_e10_normalized = tf.matmul( tf.reshape(e1p, [1, batch_size, 2]), tf.reshape(e10_normalized, [1, 1, 2]), transpose_b=True) e1p_dot_e10_normalized = tf.reshape(e1p_dot_e10_normalized, [batch_size]) / e01_norm # Take the maximum of the two projections so we face it from the positive # direction: proj = tf.maximum(e0p_dot_e01_normalized, e1p_dot_e10_normalized) proj = tf.maximum(proj, 1.0) # A projection value of 1 means at the border exactly. # Take the max with 1, to throw out all cases besides 'left' overhang. falloff_is_relative = True if falloff_is_relative: fractional_falloff = 1.0 / (tf.pow(falloff * (proj - 1), 2.0) + 1.0) return fractional_falloff else: # Currently the proj value is given as a distance that is the fraction of # the length of the line. Instead, multiply by the length of the line # to get the distance in pixels. Then, set a target '0' distance, (i.e. # 10 pixels). Divide by that distance so we express distance in multiples # of the max distance that gets seen. # threshold at 1, and return 1 - that to get linear falloff from 0 to # the target distance. line_length = tf.reshape(e01_norm, [1]) pixel_dist = tf.reshape(proj - 1, [-1]) * line_length zero_thresh_in_pixels = tf.reshape( tf.constant([8.0], dtype=tf.float32), [1]) relative_dist = pixel_dist / zero_thresh_in_pixels return 1.0 / (tf.pow(relative_dist, 3.0) + 1.0) def rotate_about_point(angle_of_rotation, point, to_rotate): """Rotates a single input 2d point by a specified angle around a point.""" with tf.name_scope('rotate-2d'): cos_angle = tf.cos(angle_of_rotation) sin_angle = tf.sin(angle_of_rotation) top_row = tf.stack([cos_angle, -sin_angle], axis=0) bottom_row = tf.stack([sin_angle, cos_angle], axis=0) rotation_matrix = tf.reshape( tf.stack([top_row, bottom_row], axis=0), [1, 2, 2]) to_rotate = tf.reshape(to_rotate, [1, 1, 2]) point = tf.reshape(point, [1, 1, 2]) to_rotate = to_rotate - point to_rotate = tf.matmul(rotation_matrix, to_rotate, transpose_b=True) to_rotate = tf.reshape(to_rotate, [1, 1, 2]) + point return to_rotate def interpolate_from_grid(samples, grid): grid_coordinates = (samples + 0.5) * 63.0 return interpolate_from_grid_coordinates(grid_coordinates, grid) def reflect(samples, reflect_x=False, reflect_y=False, reflect_z=False): """Reflects the sample locations across the planes specified in xyz. Args: samples: Tensor with shape [..., 3]. reflect_x: Bool. reflect_y: Bool. reflect_z: Bool. Returns: Tensor with shape [..., 3]. The reflected samples. """ assert isinstance(reflect_x, bool) assert isinstance(reflect_y, bool) assert isinstance(reflect_z, bool) floats = [-1.0 if ax else 1.0 for ax in [reflect_x, reflect_y, reflect_z]] mult = np.array(floats, dtype=np.float32) shape = samples.get_shape().as_list() leading_dims = shape[:-1] assert shape[-1] == 3 mult = mult.reshape([1] * len(leading_dims) + [3]) mult = tf.constant(mult, dtype=tf.float32) return mult * samples def z_reflect(samples): """Reflects the sample locations across the XY plane. Args: samples: Tensor with shape [..., 3] Returns: reflected: Tensor with shape [..., 3]. The reflected samples. """ return reflect(samples, reflect_z=True) def get_world_to_camera(idx): assert idx == 1 eye = tf.constant([[0.671273, 0.757946, -0.966907]], dtype=tf.float32) look_at = tf.zeros_like(eye) world_up = tf.constant([[0., 1., 0.]], dtype=tf.float32) world_to_camera = camera_util.look_at(eye, look_at, world_up) return world_to_camera def transform_depth_dodeca_to_xyz_dodeca(depth_dodeca): """Lifts a dodecahedron of depth images to world space.""" batch_size = depth_dodeca.get_shape().as_list()[0] cam2world = get_dodeca_camera_to_worlds() cam2world = np.reshape(cam2world, [1, 20, 4, 4]).astype(np.float32) world2cams = np.linalg.inv(cam2world) world2cams = np.tile(world2cams, [batch_size, 1, 1, 1]) world2cams = tf.unstack(tf.constant(world2cams, dtype=tf.float32), axis=1) depth_im_stack = tf.unstack(depth_dodeca, axis=1) assert len(depth_im_stack) == 20 assert len(world2cams) == 20 xyz_images = [] for i in range(20): world2cam = world2cams[i] depth_im = depth_im_stack[i] xyz_image = depth_image_to_xyz_image(depth_im, world2cam, xfov=0.5)[0] xyz_images.append(xyz_image) xyz_images = tf.stack(xyz_images, axis=1) xyz_images = tf.where_v2(depth_dodeca > 0.0, xyz_images, 0.0) return xyz_images def transform_depth_dodeca_to_xyz_dodeca_np(depth_dodeca): graph = tf.Graph() with graph.as_default(): depth_in = tf.constant(depth_dodeca) xyz_out = transform_depth_dodeca_to_xyz_dodeca(depth_in) with tf.Session() as session: out_np = session.run(xyz_out) return out_np def _unbatch(arr): if arr.shape[0] == 1: return arr.reshape(arr.shape[1:]) return arr def to_homogenous_np(arr, is_point=True): assert arr.shape[-1] in [2, 3] homogeneous_shape = list(arr.shape[:-1]) + [1] if is_point: coord = np.ones(homogeneous_shape, dtype=np.float32) else: coord = np.zeros(homogeneous_shape, dtype=np.float32) return np.concatenate([arr, coord], axis=-1) def depth_to_cam_np(im, xfov=0.5): """Converts a gaps depth image to camera space.""" im = _unbatch(im) height, width, _ = im.shape pixel_coords = np_util.make_coordinate_grid( height, width, is_screen_space=False, is_homogeneous=False) nic_x = np.reshape(pixel_coords[:, :, 0], [height, width]) nic_y = np.reshape(pixel_coords[:, :, 1], [height, width]) # GAPS nic coordinates have an origin at the center of the image, not # in the corner: nic_x = 2 * nic_x - 1.0 nic_y = 2 * nic_y - 1.0 nic_d = -np.reshape(im, [height, width]) aspect = height / float(width) yfov = math.atan(aspect * math.tan(xfov)) intrinsics_00 = 1.0 / math.tan(xfov) intrinsics_11 = 1.0 / math.tan(yfov) cam_x = nic_x * -nic_d / intrinsics_00 cam_y = nic_y * nic_d / intrinsics_11 cam_z = nic_d cam_xyz = np.stack([cam_x, cam_y, cam_z], axis=2) return cam_xyz def apply_tx_np(samples, tx, is_point=True): shape_in = samples.shape flat_samples = np.reshape(samples, [-1, 3]) flat_samples = to_homogenous_np(flat_samples, is_point=is_point) flat_samples = np.matmul(flat_samples, tx.T) flat_samples = flat_samples[:, :3] return np.reshape(flat_samples, shape_in) def depth_image_to_sdf_constraints(im, cam2world, xfov=0.5): """Estimates inside/outside constraints from a gaps depth image.""" im = _unbatch(im) cam2world = _unbatch(cam2world) height, width, _ = im.shape cam_xyz = depth_to_cam_np(im, xfov) world_xyz = apply_tx_np(cam_xyz, cam2world, is_point=True) ray_xyz = apply_tx_np(cam_xyz, cam2world, is_point=False) ray_xyz = ray_xyz / np.linalg.norm(ray_xyz, axis=-1, keepdims=True) delta = 0.005 pos_constraint = world_xyz - delta * ray_xyz neg_constraint = world_xyz + delta * ray_xyz sample_shape = [height * width, 3] pos_constraint = np.reshape(pos_constraint, sample_shape) neg_constraint = np.reshape(neg_constraint, sample_shape) sdf_shape = [height * width, 1] zero = np.zeros(sdf_shape, dtype=np.float32) # Filter out the background is_valid = np.reshape(im, [-1]) != 0.0 pos_constraint = pos_constraint[is_valid, :] neg_constraint = neg_constraint[is_valid, :] zero = zero[is_valid, :] samples = np.concatenate([pos_constraint, neg_constraint], axis=0) constraints = np.concatenate([zero + delta, zero - delta], axis=0) return samples, constraints def depth_dodeca_to_sdf_constraints(depth_ims): """Estimates inside/outside constraints from a depth dodecahedron.""" cam2world = np.split(get_dodeca_camera_to_worlds(), 20) depth_ims = np.split(_unbatch(depth_ims), 20) samps = [] constraints = [] for i in range(20): s, c = depth_image_to_sdf_constraints(depth_ims[i], cam2world[i]) samps.append(s) constraints.append(c) samps = np.concatenate(samps) constraints = np.concatenate(constraints) return samps, constraints def depth_dodeca_to_samples(dodeca): samples, sdf_constraints = depth_dodeca_to_sdf_constraints(dodeca) all_samples = np.concatenate([samples, sdf_constraints], axis=-1) return all_samples def depth_image_to_class_constraints(im, cam2world, xfov=0.5): samples, sdf_constraints = depth_image_to_sdf_constraints(im, cam2world, xfov) class_constraints = sdf_constraints > 0 return samples, class_constraints def depth_image_to_samples(im, cam2world, xfov=0.5): # pylint:disable=unused-argument """A wrapper for depth_image_to_sdf_constraints to return samples.""" samples, sdf_constraints = depth_image_to_sdf_constraints(im, cam2world) all_samples = np.concatenate([samples, sdf_constraints], axis=-1) return all_samples def apply_4x4(tensor, tx, are_points=True, batch_rank=None, sample_rank=None): """Applies a 4x4 matrix to 3D points/vectors. Args: tensor: Tensor with shape [batching_dims] + [sample_dims] + [3]. tx: Tensor with shape [batching_dims] + [4, 4]. are_points: Boolean. Whether to treat the samples as points or vectors. batch_rank: The number of leading batch dimensions. Optional, just used to enforce the shapes are as expected. sample_rank: The number of sample dimensions. Optional, just used to enforce the shapes are as expected. Returns: Tensor with shape [..., sample_count, 3]. """ expected_batch_rank = batch_rank expected_sample_rank = sample_rank batching_dims = tx.get_shape().as_list()[:-2] batch_rank = len(batching_dims) if expected_batch_rank is not None: assert batch_rank == expected_batch_rank # flat_batch_count = int(np.prod(batching_dims)) sample_dims = tensor.get_shape().as_list()[batch_rank:-1] sample_rank = len(sample_dims) if expected_sample_rank is not None: assert sample_rank == expected_sample_rank flat_sample_count = int(np.prod(sample_dims)) tensor = tf.ensure_shape(tensor, batching_dims + sample_dims + [3]) tx = tf.ensure_shape(tx, batching_dims + [4, 4]) assert sample_rank >= 1 assert batch_rank >= 0 if sample_rank > 1: tensor = tf.reshape(tensor, batching_dims + [flat_sample_count, 3]) initializer = tf.ones if are_points else tf.zeros w = initializer(batching_dims + [flat_sample_count, 1], dtype=tf.float32) tensor = tf.concat([tensor, w], axis=-1) tensor = tf.matmul(tensor, tx, transpose_b=True) tensor = tensor[..., :3] if sample_rank > 1: tensor = tf.reshape(tensor, batching_dims + sample_dims + [3]) return tensor def depth_image_to_xyz_image(depth_images, world_to_camera, xfov=0.5): """Converts GAPS depth images to world space.""" batch_size, height, width, channel_count = depth_images.get_shape().as_list() assert channel_count == 1 camera_to_world_mat = tf.matrix_inverse(world_to_camera) pixel_coords = np_util.make_coordinate_grid( height, width, is_screen_space=False, is_homogeneous=False) nic_x = np.tile( np.reshape(pixel_coords[:, :, 0], [1, height, width]), [batch_size, 1, 1]) nic_y = np.tile( np.reshape(pixel_coords[:, :, 1], [1, height, width]), [batch_size, 1, 1]) nic_x = 2 * nic_x - 1.0 nic_y = 2 * nic_y - 1.0 nic_d = -tf.reshape(depth_images, [batch_size, height, width]) aspect = height / float(width) yfov = math.atan(aspect * math.tan(xfov)) intrinsics_00 = 1.0 / math.tan(xfov) intrinsics_11 = 1.0 / math.tan(yfov) nic_xyz = tf.stack([nic_x, nic_y, nic_d], axis=3) flat_nic_xyz = tf.reshape(nic_xyz, [batch_size, height * width, 3]) camera_x = (nic_x) * -nic_d / intrinsics_00 camera_y = (nic_y) * nic_d / intrinsics_11 camera_z = nic_d homogeneous_coord = tf.ones_like(camera_z) camera_xyz = tf.stack([camera_x, camera_y, camera_z, homogeneous_coord], axis=3) flat_camera_xyzw = tf.reshape(camera_xyz, [batch_size, height * width, 4]) flat_world_xyz = tf.matmul( flat_camera_xyzw, camera_to_world_mat, transpose_b=True) world_xyz = tf.reshape(flat_world_xyz, [batch_size, height, width, 4]) world_xyz = world_xyz[:, :, :, :3] return world_xyz, flat_camera_xyzw[:, :, :3], flat_nic_xyz def interpolate_from_grid_coordinates(samples, grid): """Performs trilinear interpolation to estimate the value of a grid function. This function makes several assumptions to do the lookup: 1) The grid is LHW and has evenly spaced samples in the range (0, 1), which is really the screen space range [0.5, {L, H, W}-0.5]. Args: samples: Tensor with shape [batch_size, sample_count, 3]. grid: Tensor with shape [batch_size, length, height, width, 1]. Returns: sample: Tensor with shape [batch_size, sample_count, 1] and type float32. mask: Tensor with shape [batch_size, sample_count, 1] and type float32 """ batch_size, length, height, width = grid.get_shape().as_list()[:4] # These asserts aren't required by the algorithm, but they are currently # true for the pipeline: assert length == height assert length == width sample_count = samples.get_shape().as_list()[1] tf_util.assert_shape(samples, [batch_size, sample_count, 3], 'interpolate_from_grid:samples') tf_util.assert_shape(grid, [batch_size, length, height, width, 1], 'interpolate_from_grid:grid') offset_samples = samples # Used to subtract 0.5 lower_coords = tf.cast(tf.math.floor(offset_samples), dtype=tf.int32) upper_coords = lower_coords + 1 alphas = tf.floormod(offset_samples, 1.0) maximum_value = grid.get_shape().as_list()[1:4] size_per_channel = tf.tile( tf.reshape(tf.constant(maximum_value, dtype=tf.int32), [1, 1, 3]), [batch_size, sample_count, 1]) # We only need to check that the floor is at least zero and the ceil is # no greater than the max index, because floor round negative numbers to # be more negative: is_valid = tf.logical_and(lower_coords >= 0, upper_coords < size_per_channel) # Validity mask has shape [batch_size, sample_count] and is 1.0 where all of # x,y,z are within the [0,1] range of the grid. validity_mask = tf.reduce_min( tf.cast(is_valid, dtype=tf.float32), axis=2, keep_dims=True) lookup_coords = [[[], []], [[], []]] corners = [[[], []], [[], []]] flattened_grid = tf.reshape(grid, [batch_size, length * height * width]) for xi, x_coord in enumerate([lower_coords[:, :, 0], upper_coords[:, :, 0]]): x_coord = tf.clip_by_value(x_coord, 0, width - 1) for yi, y_coord in enumerate([lower_coords[:, :, 1], upper_coords[:, :, 1]]): y_coord = tf.clip_by_value(y_coord, 0, height - 1) for zi, z_coord in enumerate( [lower_coords[:, :, 2], upper_coords[:, :, 2]]): z_coord = tf.clip_by_value(z_coord, 0, length - 1) flat_lookup = z_coord * height * width + y_coord * width + x_coord lookup_coords[xi][yi].append(flat_lookup) lookup_result = tf.batch_gather(flattened_grid, flat_lookup) tf_util.assert_shape(lookup_result, [batch_size, sample_count], 'interpolate_from_grid:lookup_result x/8') print_op = tf.print('corner xyz=%i, %i, %i' % (xi, yi, zi), lookup_result, '\n', 'flat_lookup:', flat_lookup, '\n\n') with tf.control_dependencies([print_op]): lookup_result = 1.0 * lookup_result corners[xi][yi].append(lookup_result) alpha_x, alpha_y, alpha_z = tf.unstack(alphas, axis=2) one_minus_alpha_x = 1.0 - alpha_x one_minus_alpha_y = 1.0 - alpha_y # First interpolate a face along x: f00 = corners[0][0][0] * one_minus_alpha_x + corners[1][0][0] * alpha_x f01 = corners[0][0][1] * one_minus_alpha_x + corners[1][0][1] * alpha_x f10 = corners[0][1][0] * one_minus_alpha_x + corners[1][1][0] * alpha_x f11 = corners[0][1][1] * one_minus_alpha_x + corners[1][1][1] * alpha_x # Next interpolate a long along y: l0 = f00 * one_minus_alpha_y + f10 * alpha_y l1 = f01 * one_minus_alpha_y + f11 * alpha_y # Finally interpolate a point along z: p = l0 * (1.0 - alpha_z) + l1 * alpha_z tf_util.assert_shape(p, [batch_size, sample_count], 'interpolate_from_grid:p') p = tf.reshape(p, [batch_size, sample_count, 1]) validity_mask = tf.reshape(validity_mask, [batch_size, sample_count, 1]) return p, validity_mask
Java
UTF-8
1,608
1.914063
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.30 at 11:14:44 PM CEST // package org.promasi.protocol.messages; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.promasi.game.model.generated.ProjectModel; import org.promasi.protocol.client.Protocol; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "projectFinishedRequest", propOrder = { "project" }) public class ProjectFinishedRequest extends Message { protected ProjectModel project; public ProjectFinishedRequest() { } public ProjectFinishedRequest(ProjectModel project) { this.project = project; } @Override public Message dispatch(Protocol protocol) { return protocol.dispatch(this); } /** * Gets the value of the project property. * * @return possible object is {@link ProjectFinishedRequest.Project } * */ public ProjectModel getProject() { return project; } /** * Sets the value of the project property. * * @param value allowed object is {@link ProjectFinishedRequest.Project } * */ public void setProject(ProjectModel value) { this.project = value; } }
Markdown
UTF-8
14,213
2.625
3
[]
no_license
# MM_GMCP_Mapper_GMCP *Author: Ruthgul*<br /> *Original plugin by [Nick Gammon](http://www.gammon.com.au/forum/?id=10667)* ### A visual mini-map for towns and dungeons --- #### Features: * A visual map of towns, cities, and dungeons with a complete database of all Alyria and its planes. * GMCP-driven auto-mapper and database. #### Dependencies: * mm_mapper.lua * MM_GMCP_Handler.xml [f67c4339ed0591a5b010d05b] * Client output must convert IAC EOR/GA to newline * Set SHOW-EXISTS must be set to ON in the game (enabled by default) #### Aliases: * **mapper adjacent** \<room_name> > Display a list of rooms adjacent to the target room by name. * **mapper auto-open** [on | off] > Toggle or explicitly set mapper's speedwalk to automatically open doors. This feature is on by default. * **mapper bookmarks** > Display a list of nearby rooms that have been bookmarked, up to the maximum distance as configured. The maximum distance is 250 rooms by default. * **mapper color terrain** [on | off] > Toggle or explicitly set the mini-map to disregard the the colors of special rooms such as safe rooms, shops, trainers, and PVP areas. This feature is disabled by default. * **mapper cpks** > Display a list of nearby rooms flagged as CPK, up to the maximum distance as configured. The maximum distance is 250 rooms by default. * **mapper draw other floors** [on | off] > Toggle or explicitly set the drawing of overlays depicting floors above and below on the mini-map. This feature is on by default. * **mapper dts** > Display a list of nearby rooms flagged as death traps. * **mapper find** \<text> > Search the mapper database of rooms for those whose names contain the matching text. * **mapper findbm** \<text> > Search the mapper database of bookmarks whose names which contain the matching text. * **mapper flags** \<flags> > Search the mapper database of rooms for those which contain the matching flags. Multiple flags must be delimited by a space. * **mapper goto** \<id> > Speedwalk to the target room by its unique identifier. * **mapper hide** > Hide the mini-map if it is currently visible. * **mapper map wilds** [on | off] > Toggle or explicitly set the automatic mapping the wilds. Enabling this feature will add new rooms to the database as you explore the wilds. This should not be used outside of adding new roads to the database as they will be considered when building routes for speedwalking. This feature is off by default. * **mapper notflags** \<flags> > Search the mapper database of rooms for those which do not contain the matching flags. Multiple flags must be delimited by a space. * **mapper path** \<id1> [id2] > Display a line of text showing directions to the target room, from either the current room, or from one room to another, by its unique identifier. * **mapper peek** [id] > Temporarily redraw the mini-map centered the target room by its unique identifier. Using the `look` command or moving to another room will reset the mini-map to center on your current location. * **mapper purge area** \<area> > Delete an entire area from the database. Use with caution. * **mapper purge molehill** > Delete all rooms from the molehill maze from the database. * **mapper purge pursuer** > Delete all rooms from the orc pursuer maze from the database * **mapper purge sandbox** > Delete all housing sandbox rooms from the database. * **mapper purge wilds** \<plane> > Delete all rooms which are considered to be wilds from the target plane from the database. This will not purge rooms which are roads. * **mapper resume** > Resume the last interrupted mapper speedwalk. * **mapper safes** > Display a list of nearby rooms flagged as safe, up to the maximum distance as configured. The maximum distance is 250 rooms by default. * **mapper safewalk** [on | off] > Toggle or explicitly set mapper to avoid room flagged for PK and deathraps. This will only affect speedwalks performed by the `mapper goto` alias. * **mapper shops** > Display a list of nearby rooms which have been flagged as shops, up to the maximum distance as configured. The maximum distance is 250 rooms by default. * **mapper show flags** [on | off] > Toggle or explicitly set mapper to display a line above the room description identifying what flags it has set. This feature is set to off by default. * **mapper show numbers** [on | off] > Toggle or explicitly set mapper to display a line above the room description identifying its unique identifier. This feature is set to off by default. Note that the room id is only visible when `set visually-impaired` is set to `on`. * **mapper show road exits** [on | off] > Toggle or explicitly set mapper to display a line after `Visible Exits` for the current room identifying which adjacent rooms are along the road, if you are standing on one. This feature is set to off by default. Note that the room id is only visible when `set visually-impaired` is set to `on`. * **mapper show unmapped exits** [on | off] > Toggle or explicitly set mapper to display a line after `Visible Exits` for the current room identifying which adjacent rooms are accessible but unmapped. This feature is set to off by default. Note that the room id is only visible when `set visually-impaired` is set to `on`. * **mapper show** > Display the mini-map if it is currently hidden. * **mapper speedwalk next** > Display a line (or SAPI say for VI) the next direction of the current mapper speedwalk. This is useful if you don't know which direction to flee while preserving your existing path. * **mapper stop** > Cancel the current mapper speedwalk. * **mapper trainers** > Display a list of nearby rooms flagged as having a trainer, up to the maximum distance as configured. The maximum distance is 250 rooms by default. * **mapper where** \<text> > Search the database and display a list of unique identifiers for all room names which contain the matching text. Note that `%` may be used as a wildcard character. * **mapper zoom in** > Zoom the mini-map in. * **mapper zoom out** > Zoom the mini-map out. #### Advanced Aliases: * **mapper addbm** [id] \[b:\<name>] > Add a bookmark to the mapper database for the current room or for a target room by its unique identifier. If no name is specified then the default of 'x' will be used. * **mapper addexit** \<direction> [f:\<id_from>] t:\<id_to> > Add an exit to the mapper database for the current room or for a target room by its unique identifier. > <table> > <tr> > <td colspan="12">Directions:</td> > </tr> > <tr> > <td>n</td> > <td>e</td> > <td>s</td> > <td>e</td> > <td>ne</td> > <td>se</td> > <td>nw</td> > <td>sw</td> > <td>u</td> > <td>d</td> > <td>tprt</td> > <td>prtl</td> > </tr> > </table> * **mapper addroom** \<id> n:\<name> a:\<area> f:\<flags> t:\<terrain> ti:\<terraininfo> > Add a room to the mapper database by its unique identifier, name, area, flags, and terrain information. > <table> > <tr> > <td colspan="5">Flags:</td> > </tr> > <td>anti-magic</td> > <td>dark</td> > <td>disorient</td> > <td>double-pk-damage</td> > <td>energy-draining</td> > </tr> > <tr> > <td>fear</td> > <td>grapple-required</td> > <td>half-pk-damage</td> > <td>high-regen</td> > <td>icy-conditions</td> > </tr> > <tr> > <td>indoors</td> > <td>low-regen</td> > <td>magic-unstable</td> > <td>momentary-darkness</td> > <td>no-area-affects</td> > </tr> > <tr> > <td>no-chat</td> > <td>no-disguise</td> > <td>no-emote</td> > <td>no-fear</td> > <td>no-form</td> > </tr> > <tr> > <td>no-mount</td> > <td>no-npcs</td> > <td>no-outside-noise</td> > <td>no-recall</td> > <td>no-regen</td> > </tr> > <tr> > <td>no-teleview</td> > <td>no-track</td> > <td>no-trap</td> > <td>no-unforming-allowed</td> > <td>player-kill-chaotic</td> > </tr> > <tr> > <td>player-kill-lawful</td> > <td>player-kill-neutral</td> > <td>private</td> > <td>psychotic-combat</td> > <td>reinforced</td> > </tr> > <tr> > <td>safe</td> > <td>silence</td> > <td>solitary</td> > <td>tangle-vine</td> > <td>thunderstorm</td> > </tr> > <tr> > <td>Unknown</td> > <td>vanishing-items</td> > <td>windy</td> > </tr> > </table> > > <table> > <tr> > <td colspan="5">Terrain:</td> > </tr> > <tr> > <td>acid-pool</td> > <td>air</td> > <td>beach</td> > <td>bridge</td> > <td>chasm</td> > </tr> > <tr> > <td>city street</td> > <td>cliff</td> > <td>craggy mountain</td> > <td>deep water</td> > <td>dense forest</td> > </tr> > <tr> > <td>desert</td> > <td>dungeon</td> > <td>dusty road</td> > <td>foothills</td> > <td>fresh-water-swimmable</td> > </tr> > <tr> > <td>glacier</td> > <td>grassy field</td> > <td>gravel road</td> > <td>hay-ground</td> > <td>hills</td> > </tr> > <tr> > <td>ice</td> > <td>indoors</td> > <td>jungle</td> > <td>lava</td> > <td>light forest</td> > </tr> > <tr> > <td>mossy ground</td> > <td>mountainous</td> > <td>paved road</td> > <td>plain</td> > <td>rocky ground</td> > </tr> > <tr> > <td>salt water</td> > <td>savannah</td> > <td>shallow water</td> > <td>sheer mountain</td> > <td>slippery floor</td> > </tr> > <tr> > <td>snow</td> > <td>stream</td> > <td>swamp</td> > <td>trail</td> > <td>underwater-ground</td> > </tr> > <tr> > <td>underwater</td> > <td>Unknown</td> > <td>void</td> > </tr> > </table> > > <table> > <tr> > <td colspan="6">Terrain Info:</td> > </tr> > <tr> > <td>acid</td> > <td>climbable</td> > <td>copper-mineable</td> > <td>diggable</td> > <td>drinkable-water</td> > <td>fire</td> > </tr> > <tr> > <td>fishable</td> > <td>freezing</td> > <td>hard</td> > <td>iron-mineable</td> > <td>nothing</td> > <td>plains</td> > </tr> > <tr> > <td>poison-gas</td> > <td>sailable</td> > <td>salt-mineable</td> > <td>shallow</td> > <td>sheltered</td> > <td>silver-mineable</td> > </tr> > <tr> > <td>slippery</td> > <td>swimmable</td> > <td>underwater</td> > <td>Unknown</td> > <td>wooded</td> > </tr> > </table> * **mapper delbm** [id] > Delete a bookmark from the mapper database. * **mapper delexit** \<direction> [f:\<id>] > Delete an exit from the mapper database for the current room or for a target room by its unique identifier. > <table> > <tr> > <td colspan="12">Directions:</td> > </tr> > <tr> > <td>n</td> > <td>e</td> > <td>s</td> > <td>e</td> > <td>ne</td> > <td>se</td> > <td>nw</td> > <td>sw</td> > <td>u</td> > <td>d</td> > <td>tprt</td> > <td>prtl</td> > </tr> > </table> * **mapper delexits** \<id> > Delete all exits for the target room from the mapper database. * **mapper delroom** \<id> > Delete a room from the mapper database. * **mapper dt** [id] > Toggle the deathtrap flag for the current or explicitly defined room by its unique identifier. * **mapper export area** \<name> > Export the area matching the target name from the mapper database to a file. * **mapper export rooms** \<name> > Export all rooms matching the target name from the mapper database to a file. * **mapper no-speed** [id] > Toggle the no-speed flag for the current or explicitly defined room by its unique identifier. * **mapper purge bookmarks** > Purge all non-vmap bookmarks from the mapper database. * **mapper purge clanhalls** > All clanhall rooms from the mapper database. * **mapper purge homes** > Purge all player home rooms from the mapper database. * **mapper rebuild lookup** > Rebuild the rooms_lookup table for the mapper database. * **mapper recreate database** > Copy all information contained within the mapper database to a new file. * **mapper reset defaults** > Reset the mapper database to its default settings. * **mapper roominfo** [id] > Display a list of information about the current or target room by its unique identifier. * **mapper shop** [id] > Toggle the shop flag for the current or explicitly defined room by its unique identifier. * **mapper show database mods** [on | off] > Toggle or explicitly set the the notification of database updates. This feature is on by default. * **mapper trainer** [id] > Toggle the trainer flag for the current or explicitly defined room by its unique identifier. * **mapper trap** [id] > Toggle the trap flag for the current or explicitly defined room by its unique identifier. #### Screenshots: ![screenshot-captures](assets/images/mm_gmcp_mapper_gmcp_1.png) &nbsp;&nbsp; ![screenshot-captures](assets/images/mm_gmcp_mapper_gmcp_2.png) ![screenshot-captures](assets/images/mm_gmcp_mapper_gmcp_3.png)
JavaScript
UTF-8
2,038
2.609375
3
[]
no_license
/* * * 李文爽 2017/06/01 * 基于layer_mobile.js * 功能:封装了一些layer-mobile 的功能 * */ //关闭所有 function l_closeAll () { layer.closeAll(); } //提示信息 参数 (1内容,2时间 整数秒) function l_msg (txt,t){ var arg=arguments; if(arg.length>3){ console.error('l_msg()参数过多,最多3位'); return; }else if(arg.length==0){ console.error('l_msg()未传入参数'); return; } var txt=(function () { for(i=0;i<arg.length;i++){ if(typeof arg[i] == 'string'){ return arg[i]; } } return ''; })() var t=(function () { for(i=0;i<arg.length;i++){ if(typeof arg[i] == 'number'){ return arg[i]; } } return parseFloat(arg[1]); })() var end=(function () { for(i=0;i<arg.length;i++){ if(typeof arg[i] == 'function'){ return arg[i]; } } return null; })() layer.open({ content:txt ,skin:'footer' ,time:t || 2 ,shade:'background-color:rgba(30,30,30,0)' ,end:end }); } //加载中 loading 参数 (1时间,2内容可选) function l_loading (txt,t) { if(typeof txt=== 'number'){ if(typeof t==='string'){ var txt2=txt; txt=t; t=txt2; } }else if(typeof t==='string'){ t=parseInt(t); } layer.open({ type:2, time:t || 2000, content:txt || null, shade:'background-color:rgba(30,30,30,0)', shadeClose:false, }); } //警告框 alert function l_alert (txt,btnTxt,yesFn) { var arg=arguments; if(typeof arg[1] === 'string'){ var btxt=arg[1]; }else{ var btxt='我知道了'; } layer.open({ content:txt || ' ' ,btn:btxt ,shade:'background-color:rgba(30,30,30,.3)' ,yes:function (index) { for(i=0;i<arg.length;i++){ if(typeof arg[i] === 'function'){ arg[i](); } } layer.close(index); }, }); } //确认取消 框 function l_confirm (title,yesFn,noFn,btn) { layer.open({ content: title ,className:'l_confirm' ,btn:btn || ["确定","取消"] ,yes: yesFn ,no: noFn ,shade:'background-color:rgba(30,30,30,.3)' }); }
Ruby
UTF-8
386
2.546875
3
[]
no_license
module TodoManager module Commands class Complete < TodoManager::Commands::Base def run! todo = find(index) if todo todo.complete! database.dump(todos) puts "Completed #{index + 1}." else raise TodoManager::Errors::ModelNotFound, "No model found at index #{index}." end end end end end
Java
UTF-8
1,004
2.546875
3
[]
no_license
package ifmo.lab1; import ifmo.lab3.exception.CountriesServiceFault; import ifmo.lab3.exception.IllegalArgumentException; import ifmo.lab3.exception.NotFoundException; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebService; @WebService(serviceName = "CountriesService") public class CountriesWebService { @WebMethod(operationName = "getCountry") public Country getCountry(String code) throws IllegalArgumentException, NotFoundException { if (code == null || code.equals("")) { throw new IllegalArgumentException("Empty code", new CountriesServiceFault("Country code is empty")); } CountryDAO dao = new CountryDAO(ConnectionUtil.getConnection()); return dao.getCountry(code); } @WebMethod(operationName = "getCountries") public List<Country> getCountries(String term) { CountryDAO dao = new CountryDAO(ConnectionUtil.getConnection()); return dao.getCountries(term); } }
C#
UTF-8
1,952
3.375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace libetruga { /// <summary> /// Clase tortuga hereda de la clase corredor /// </summary> class Tortuga:Corredor { /// <summary> /// Se obtiene el numero del corredor de la clase corredor /// </summary> /// <param el numero de la tortuga="numero"></param> public Tortuga(int numero) : base(numero) { } /// <summary> /// Se crea la accion correr /// </summary> /// <returns>un avanse o decremento </returns> new public int correr() { /// Se guarda el numero aleatorio generado el clase correr en varable entera a int a = base.correr(); ///compara a con 12 ya que se usa del 13 a 20 como 40% if(a > 12) { ///Regresa un aumento de tres en posicion return _posicion += 3; } else { ///compara a con 8 ya que se usa 9 a 12 com 20% if (a > 8) { ///regresa un aumento del 6 en posicion return _posicion += 6; } else { ///compara a con 4 ya que se usa 5 a 8 como 20% if (a > 4) { ///regresa decremento del 5 en posicion return _posicion -= 5; } else { ///si no es ninguna de las otras entonces es entre 1 a 4 20% ///regresa decremento de 9 en posicion return _posicion -= 9; } } } } } }
JavaScript
UTF-8
85
2.84375
3
[]
no_license
let bool1 = 1; let bool2 = 2; let bool3 = ''; console.log(bool1 || bool2 || bool3);
Java
UTF-8
441
1.960938
2
[]
no_license
package com.epam.olukash.manager; import java.util.List; import java.util.Set; import com.epam.olukash.dto.Booking; import com.epam.olukash.dto.Seat; import com.epam.olukash.dto.Ticket; /** * @author Oleksii_Lukash */ public interface TicketManager extends BeanManager<Ticket> { List<Ticket> findByCinemaSessionID(long cinemaSessionID); List<Ticket> findByIds(Set<Long> ids); List<Ticket> getTicketsByBookingID(Long bookingID); }
Java
UTF-8
138
2.375
2
[]
no_license
package project.polimorfism; public class Cat extends Pet { void sleep(){ System.out.println("Cat is Sleeping"); } }
Java
UTF-8
252
1.78125
2
[]
no_license
package gitTest; public class TestGit { public static void main(String[] args) { System.out.println("sb"); System.out.println("吴浩鹏"); System.out.println("吴浩鹏"); System.out.println("是王雨松爸爸"); } }
Markdown
UTF-8
361
2.5625
3
[]
no_license
# simple-coin-detection This is an implementation of coin detection and counting on Python 3 and OpenCV. In addition to detecting the number of coins, the code also identifies and draws its borders and the center of each one. The results are as follows: ![result real](https://iili.io/2X9t4f.jpg) ![result dolar](https://i.ibb.co/dtv5p8D/dolar-result.png)
Python
UTF-8
203
3.140625
3
[]
no_license
from os import replace n = int(input()) s = input() k = int(input()) replace = s[k - 1] for i in range(n): if s[i] == replace: print(s[i],end="") else: print("*",end="") print()
Markdown
UTF-8
2,822
3
3
[]
no_license
# What is this? Hides and extracts arbitrary payloads in PNG images without adding any additional data to the image by using **L**east **S**ignificant **B**it (LSB) steganography. Steganography is the practice of hiding information within plain sight via another piece of information so that the existence of a secret payload is unknown or at least plausibly deniable. It's used for [international espionage](https://www.wired.com/2010/06/alleged-spies-hid-secret-messages-on-public-websites/), [data exfiltration](https://www.internetandtechnologylaw.com/trade-secrets-theft-steganography-picture/), [malware](https://www.welivesecurity.com/2016/12/06/readers-popular-websites-targeted-stealthy-stegano-exploit-kit-hiding-pixels-malicious-ads/), and [fingerprinting](https://www.businessinsider.nl/genius-accuses-google-of-copying-its-lyrics-and-diverting-traffic-2019-6?international=true&r=US)- pretty cool! LSB steganography works by replacing the least significant bits in each pixel with payload data. For a regular PNG image, each pixel is comprised of 4 bytes: one byte each for Red, Green, Blue, and Alpha (transparency). If you replace the last 2 bits of each byte with some payload bits, then the numeric value of that byte will change by at most 3 which is hard to casually notice since the values are out of 255. This way we can hide a byte of payload data per pixel while only affecting the pixel channel intensities by at most ~1%. LSB is pretty easy to detect via statistical analysis, even without access to the original image. There are other methods that are practically impossible to detect! If you want to learn more about better methods and countermeasures I recommend checking out [Simon Wiseman's Defenders Guide to Steganography](https://www.researchgate.net/publication/319943090_Defenders_Guide_to_Steganography), it's short and makes sense! # Usage ```bash # Get dependencies (opencv and numpy) pip install -r requirements.txt # Hide a payload in an image python3 lsb.py hide sunset.png launchcodes.txt -o steg.png # Extract a payload from an image python3 lsb.py extract steg.png -o thelaunchcodes.txt # Get full CLI documentation python3 lsb.py --help ``` # Example This picture of my dog is hiding Doom and an emulator for running it as a .7z file: https://drive.google.com/file/d/1ASs0Ww9uT7LCRYfwDVB8SDaoiNlB0Wn9/view?usp=sharing Comparison: ![Doom hidden in picture of my dog](https://i.imgur.com/MHpxk5x.png) # LSB caveats * Won't work with lossy compression (like JPEG) * Large payloads make PNG compression ineffective, so the compressed result image will most likely be larger than the compresed original * Easily detectable even without original image # TODO * Hide can be faster * ~~The extracted payload will usually have garbage data appended to it which is unnecessary~~
Java
UTF-8
5,380
2.03125
2
[]
no_license
package cn.v6.sixrooms.room.adapter; import android.content.Context; import android.net.Uri; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import cn.v6.sixrooms.R; import cn.v6.sixrooms.room.bean.OnHeadlineBean; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; public class DialogHeadLineAdapter extends BaseAdapter { private Context a; private List<OnHeadlineBean> b; public static class HeadLineSecondViewHolder { TextView a; SimpleDraweeView b; TextView c; TextView d; View e; } public static class HeadLineViewHolder { TextView a; SimpleDraweeView b; ImageView c; TextView d; View e; } public DialogHeadLineAdapter(Context context, List<OnHeadlineBean> list) { this.a = context; this.b = list; } public int getCount() { return this.b.size(); } public Object getItem(int i) { return this.b.get(i); } public long getItemId(int i) { return (long) i; } public View getView(int i, View view, ViewGroup viewGroup) { OnHeadlineBean onHeadlineBean; switch (getItemViewType(i)) { case 0: HeadLineViewHolder headLineViewHolder; if (view != null) { headLineViewHolder = (HeadLineViewHolder) view.getTag(); } else { view = View.inflate(this.a, R.layout.dialog_head_line_item, null); headLineViewHolder = new HeadLineViewHolder(); headLineViewHolder.c = (ImageView) view.findViewById(R.id.iv_rank); headLineViewHolder.b = (SimpleDraweeView) view.findViewById(R.id.iv_identity); headLineViewHolder.a = (TextView) view.findViewById(R.id.tv_name); headLineViewHolder.d = (TextView) view.findViewById(R.id.tv_num); headLineViewHolder.e = view.findViewById(R.id.division); view.setTag(headLineViewHolder); } if (this.a.getResources().getConfiguration().orientation == 2) { headLineViewHolder.a.setMaxEms(5); } else if (this.a.getResources().getConfiguration().orientation == 1) { headLineViewHolder.a.setMaxEms(20); } headLineViewHolder.e.setVisibility(0); int i2 = R.drawable.v6_ic_pop_rank_1; switch (i) { case 0: i2 = R.drawable.v6_ic_pop_rank_1; headLineViewHolder.e.setVisibility(8); break; case 1: i2 = R.drawable.v6_ic_pop_rank_2; break; case 2: i2 = R.drawable.v6_ic_pop_rank_3; break; } headLineViewHolder.c.setBackgroundResource(i2); onHeadlineBean = (OnHeadlineBean) this.b.get(i); headLineViewHolder.b.setImageURI(Uri.parse(onHeadlineBean.getPic())); headLineViewHolder.a.setText(onHeadlineBean.getAlias()); headLineViewHolder.d.setText(onHeadlineBean.getNum()); break; case 1: HeadLineSecondViewHolder headLineSecondViewHolder; if (view != null) { headLineSecondViewHolder = (HeadLineSecondViewHolder) view.getTag(); } else { view = View.inflate(this.a, R.layout.dialog_head_line_second_item, null); headLineSecondViewHolder = new HeadLineSecondViewHolder(); headLineSecondViewHolder.c = (TextView) view.findViewById(R.id.tv_rank); headLineSecondViewHolder.b = (SimpleDraweeView) view.findViewById(R.id.iv_identity); headLineSecondViewHolder.a = (TextView) view.findViewById(R.id.tv_name); headLineSecondViewHolder.d = (TextView) view.findViewById(R.id.tv_num); headLineSecondViewHolder.e = view.findViewById(R.id.division); view.setTag(headLineSecondViewHolder); } if (this.a.getResources().getConfiguration().orientation == 2) { headLineSecondViewHolder.a.setMaxEms(5); } else if (this.a.getResources().getConfiguration().orientation == 1) { headLineSecondViewHolder.a.setMaxEms(20); } headLineSecondViewHolder.e.setVisibility(0); headLineSecondViewHolder.c.setText((i + 1)); onHeadlineBean = (OnHeadlineBean) this.b.get(i); headLineSecondViewHolder.b.setImageURI(Uri.parse(onHeadlineBean.getPic())); headLineSecondViewHolder.a.setText(onHeadlineBean.getAlias()); headLineSecondViewHolder.d.setText(onHeadlineBean.getNum()); break; } return view; } public int getItemViewType(int i) { if (i <= 2) { return 0; } return 1; } public int getViewTypeCount() { return 2; } }
Markdown
UTF-8
5,157
3.234375
3
[]
no_license
## 常规的图像主要包括:Bitmap(位图)、Ectorgraph(矢量图) - Bitmap(位点图): 简单的说就是由很多像素点组成的图像,当放大位图时,可以看见很多像素方块,也就是马赛克形状。 - (EctorGraph)矢量图: 是用线段或曲线的特性来描述图像,可以将它缩放到任意大小和任意分辨率在输出设备打印出来,都不会影响清晰度。 - (graysacle value)灰度值: 一般来说,我们通过成像设备得到的图像都是位图,而灰度值是组成位图的像素点的特性,不同制式的图片可能会有不同的灰度值范围。灰度值梯度越高,显示的图像效果越细腻。 - 值得注意的是,成像设备拍摄的图像大多数是12 Bit,直接转换成Tiff文件为16Bit,而大部分显示器和印制品支持的是8Bit图像,因此我们常常需要把12Bit或者16Bit转换为8Bit的图像呈现。 - 对于彩图而言,通常是由几个彩色通道叠加而成,每个通道又有不同的灰度值,例如RGB图像是由红绿蓝三原色组成,可拆分成三种灰度图。 ## 图像显示概念: - 是谁把像素数据交给显示器? - 这个是显示控制器来实现的,它每发送一个像素数据给显示器,显示器就会点亮一个像素点,包括扫描时什么时候换行,什么时候显示下一屏(帧)图像,都是又控制器来控制的,显示器只负责得到像素数据显示。 - 压缩图像数据 - 给显示器使用的像素数据必须是RGB格式的数据,因为只有RGB的数据才能控制像素点的红绿蓝三部分,但是平时图片文件在存储图像数据时,存储的并不是RGB数据。 - 那是为什么呢? - 因为RGB数据的数据量太大了,占据大量的存储空间,因此图片文件中所存放的都是对RGB进行压缩后的“压缩图像数据”。 - 常见的压缩: bmp、jpg、tiff、git、pcx、tga、exif、fps、svg、psd、cdr、pcd、dxf、eps、ai、raw、png等其中bmp、jpg、png最为常见图片压缩格式。 - 视频浅述,视频也是由图片组成不过不是单张图片,而是由无数张连续图片构成的,视频的数据量就更加庞大,因此视频也需要被压缩,不过对视频的压缩是对无数张图片进行压缩和图片压缩只是一张图片压缩有一定的差别,压缩后常见的视频格式有AVI、mov、rmvb、rm、flv、mp4、3GP等,其中最常见的是MP4格式。 - 解压图片 - PC: 图片播放器(读取图片数据自动转换为RGB数据),OS调度驱动控制显示器显示相应图片数据; - 单片机: - 1). 单片机上运行解压程序,解压程序自动读出图片文件的数据,读出后对其进行解压得到RGB数据,然后在由控制器交给显示器显示。 - 图片文件放在哪: 一般放在SPI-flash、SD卡、Nandflash、U盘等存储器; - 2). 通过转换软件,将其解压转换为RGB数据,编程时在将数据存储在数组中,然后代码就可以使用数组中的RGB数据来控制显示器显示; - 解压视频 - PC:(视频播放器自动读取和解压压缩的视频文件数据,显示器显示) - 单片机:摄像头(视频) ## 常见RGB数据格式: RGB565、RGB555、ARGB1555、RGB24(RGB888)、RGB32(RGB8888) - RGB565: 用16Bit(2字节)来表示一个像素数据,5(红色)、6(绿)、5(蓝); - RGB色深: - 红色(R)的颜色深度:00000(0)- 11111(31) - 绿色(G)的颜色深度:000000(0)- 111111(63) - 蓝色(B)的颜色深度:00000(0)- 11111(31) - 颜色值:R G B (0-0-0(黑色) —— ¥-¥-¥(任意颜色) ——31-63-31(白色)) - RGB555: 用16Bit(2字节)表示一个像素数据,最高位未使用; - ARGB1555:与RGB555类似,只不过多了一位透明度A(Alpha),a=0全透明、a=1(不透明) - RGB32(RGB8888): 与RGB24(RGB888)类似,只不过多了8位用于表示透明度A(alpha),8位透明度分为0-255等级,0表示全透明,255表示完全不透明,0-255之间表示不同程度的透明状态; ## 透明度: - 透明度的作用:透明度用于实现两张图片的混合,混合的过程其实就是将两张图片对应像素点的RGB数据进行混合,而透明度则决定了混合时各自RGB数据占多少比例,已呈现出混合后的效果,不过混合时只要其中一张图片包含透明度就可以。(混合后的图像数据为纯 RGB数据不包含透明度,且显示器上显示的是纯RGB数据) ## 点距: - 描述的其实就是像素密度;像素点距越大,则对应的就是像素密度越小; ## 视频相关 ### 分量视频信号(色差信号),通常采用YCbCr和YPbPr两种标识;
Markdown
UTF-8
26,169
2.609375
3
[]
no_license
# Projeto - Entrega Final Link para o vídeo de apresentação: https://drive.google.com/file/d/1xflGr16gFOXJ_c8EqaECpAKUpvsCMGvj/view?usp=sharing ## 1. Grupo - Guilherme Locca Salomão - 758569 ## 2. Especificações Para este projeto, foram requisitadas as seguintes etapas: - Criação do repositório remoto no github - Testes funcionais e Relatórios de cobertura sobre as seguintes funções: - Função de Adicionar Artigos e Livros - Importar item bibliográfico a database via arquivos - Manutenção Perfectiva - Validação de campos na adição de Artigos e Livros - Permitir a importação via formato .CSV - Testes adicionais exercitando novas funcionalidades <span style="font-size: 0.75rem">Observação: pelo uso de um editor de <em>Markdown</em> não foi possível a numeração de páginas</span> ## 3. Repositório GitHub Para esta tarefa, foi criado um repositório remoto git no github. [https://github.com/Caotichazard/DC-UFSCar-ES2-202101-ENPE-3-NewJabRef](https://github.com/Caotichazard/DC-UFSCar-ES2-202101-ENPE-3-NewJabRef) Nele foram criadas os dois *issues* a serem resolvidos com as manutenções perfectivas - [iss01](https://github.com/Caotichazard/DC-UFSCar-ES2-202101-ENPE-3-NewJabRef/issues/1): Adição da funcionalidade de verificação de Ano e *BibTexKey* - [iss02](https://github.com/Caotichazard/DC-UFSCar-ES2-202101-ENPE-3-NewJabRef/issues/2): Adição da funcionalidade de importação de entradas através de arquivos CSV Para a realização, foram criados 2 *branches* novos, um para cada alteração e trabalhados sobre eles as alterações para as funções requisitadas. Após finalizada cada funcionalidade, foi solicitado o *pull request* e seguido pelo *merge* das funcionalidades novas. <div style="page-break-after: always; visibility: hidden"> \pagebreak </div> ## 4. Testes Funcionais e Relatórios de cobertura Para essa primeira etapa, foi primeiramente realizado uma análise básica de cada funcionalidade, após isso, em conjunto a uma leitura rápida da documentação referente a função, foram definidos os testes que então são realizados manualmente com a execução auxiliada pelo *EclEmma* para a geração dos relatórios de cobertura. ### 4.1 Adição de Artigos e Livros #### 4.1.2 Função Essa função possui 5 categorias de entradas diferentes: - Entradas Obrigatórias - Entradas Opcionais - Entradas Gerais - Entrada de Resumo - Entrada de Revisão Destas 5 categorias, apenas as Entradas Obrigatórias são obrigatórias a serem preenchidas para a adição de um Artigo ou Livro a base de dados. Para a adição de um Artigo, os seguintes campos são obrigatórios: - *Author* - *Title* - *Journal* - *Year* - *BibTexKey* e para adicionar um Livro: - *Title* - *Publisher* - *Year* - *Author* - *Editor* - *BibTexKey* Fazendo então uma leitura rápida da [documentação](https://docs.jabref.org/v/v4/general/entryeditor#field-consistency-checking) referente a essa funcionalidade, podemos observar que: - Todos os campos são campos de texto. - Há apenas uma categoria de entrada invalida, o símbolo #, permitido apenas o uso dele em pares. - Caso haja algum erro no campo inserido, ele deve se tornar vermelho indicando a presença de um erro. - Caso haja um erro, alterações não serão armazenadas. Durante os testes elaborados, é esperado receber uma das seguintes indicações de erro ou sucesso: Uma entrada processada com sucesso ![Adicionado com sucesso](./Projeto_imgs/input_with_no_error.png) Uma entrada processada com erro ![Adicionado com sucesso](./Projeto_imgs/input_error_on_field.png) #### 4.1.3 Testes ##### 4.1.3.1 Adicionar Artigo Para a funcionalidade de adicionar um Artigo, foram realizados os seguintes testes Utilizando o particionamento de equivalência, podemos dividir nossas entradas em 3 tipos: - um campo vazio (indicado por -) - um campo com uma entrada invalida (neste caso foi usado o caracter # indicado como invalido na documentação) - um campo com entrada válida e as saídas em 2 classes: - Erro em um campo - Entrada adicionada ID |Author | Title | Journal | Year | Bibtexkey | Saida esperada - |-|-|-|-|-|- 1 |-|-|-|-|-|todos campos em vermelho, indicando erro 2|author|-|-|-|-|todos os campos, exceto author, em vermelho, indicando erro 3|-|title|-|-|-|todos os campos, exceto title, em vermelho, indicando erro 4|-|-|journal|-|-|todos os campos, exceto author, em vermelho, indicando erro 5|-|-|-|year|-|todos os campos, exceto author, em vermelho, indicando erro 6|-|-|-|-|Bibtexkey|todos os campos, exceto author, em vermelho, indicando erro 7|-|title|journal|year|Bibtexkey|Apenas o campo author em vermelho, indicando erro 8|author|-|journal|year|Bibtexkey|Apenas o campo title em vermelho, indicando erro 9|author|title|-|year|Bibtexkey|Apenas o campo journal em vermelho, indicando erro 10|author|title|journal|-|Bibtexkey|Apenas o campo year em vermelho, indicando erro 11|author|title|journal|year|-|Apenas o campo author em bibtexkey, indicando erro 12|#|title|journal|year|Bibtexkey|Apenas o campo author em vermelho, indicando erro 13|author|#|journal|year|Bibtexkey|Apenas o campo title em vermelho, indicando erro 14|author|title|#|year|Bibtexkey|Apenas o campo journal em vermelho, indicando erro 15|author|title|journal|#|Bibtexkey|Apenas o campo year em vermelho, indicando erro 16|author|title|journal|year|#|Apenas o campo author em bibtexkey, indicando erro 17|author|title|journal|year|bibtexkey|Entrada adicionada a base de dados ##### 4.1.3.2 Adicionar Livro Para a funcionalidade de adicionar um Livro, foram realizados os seguintes testes Utilizando o particionamento de equivalência, podemos dividir nossas entradas em 3 tipos: - um campo vazio (indicado por -) - um campo com uma entrada invalida (neste caso foi usado o caracter # indicado como invalido na documentação) - um campo com entrada válida e as saídas em 2 classes: - Erro em um campo - Entrada adicionada ID |Title | Publisher | Year | Author | Editor | Bibtexkey | Saida esperada -| -|-|-|-|-|-|- 1|-|-|-|-|-|-|todos campos em vermelho, indicando erro 2|title|-|-|-|-|-|todos os campos, exceto title, em vermelho, indicando erro 3|-|publisher|-|-|-|-|todos os campos, exceto publisher, em vermelho, indicando erro 4|-|-|year|-|-|-|todos os campos, exceto year, em vermelho, indicando erro 5|-|-|-|author|-|-|todos os campos, exceto author, em vermelho, indicando erro 6|-|-|-|-|editor|-|todos os campos, exceto editor, em vermelho, indicando erro 7|-|-|-|-|-|bibtexkey|todos os campos, exceto bibtexkey, em vermelho, indicando erro 8|-|publisher|year|author|editor|bibtexkey|Apenas o campo title em vermelho, indicando erro 9|title|-|year|author|editor|bibtexkey|Apenas o campo publisher em vermelho, indicando erro 10|title|publisher|-|author|editor|bibtexkey|Apenas o campo year em vermelho, indicando erro 11|title|publisher|year|-|editor|bibtexkey|Apenas o campo author em vermelho, indicando erro 12|title|publisher|year|author|-|bibtexkey|Apenas o campo editor em vermelho, indicando erro 13|title|publisher|year|author|editor|-|Apenas o campo bibtexkey em vermelho, indicando erro 14|#|publisher|year|author|editor|bibtexkey|Apenas o campo title em vermelho, indicando erro 15|title|#|year|author|editor|bibtexkey|Apenas o campo publisher em vermelho, indicando erro 16|title|publisher|#|author|editor|bibtexkey|Apenas o campo year em vermelho, indicando erro 17|title|publisher|year|#|editor|bibtexkey|Apenas o campo author em vermelho, indicando erro 18|title|publisher|year|author|#|bibtexkey|Apenas o campo editor em vermelho, indicando erro 19|title|publisher|year|author|editor|#|Apenas o campo bibtexkey em vermelho, indicando erro 20|title|publisher|year|author|editor|bibtexkey|Entrada adicionada a base de dados #### 4.1.4 Comentários Durante os testes, foi notado que: Para casos onde havia campos incompletos ou errados, não havia uma janela de *pop-up* para avisar erro, exceto no caso de um erro na definição do campo *BibTexKey*, o qual não aceita o símbolo #. Quando esse simbolo era digitado em algum campo, se nele não era aceito, nada ocorria. Além disso, os campos *Title* e *Year* para adicionar Artigo aceitavam o símbolo #. Porem, o campo *Title* não aceitava # na função de adicionar um Livro Outro detalhe foi que, após fechar e abrir novamente o programa, havia uma única janela de aviso, notificando o usuário dos erros presentes nas entradas. Os relatórios de cobertura gerados, foram gerados no formato HTML. <div style="page-break-after: always; visibility: hidden"> 1 </div> ### 4.2 Importação de itens bibliográficos na base corrente #### 4.2.1 Função Para a funcionalidade de importação de itens, o programa nos da opção de importar baseado nos seguintes formatos de arquivos: - BibTeX : bibtex - BibTeXML : bibtexml - Biblioscape : biblioscape - Copac : cpc - INSPEC : inspec - ISI : isi - MSBib : msbib - Medline : medline - MedlinePlain : medlineplain - Ovid : ovid - PDFcontent : pdfcontent - REPEC New Economic Papers (NEP) : repecnep - RIS : ris - Refer/Endnote : refer - SilverPlatter : silverplatter - XMP-annotated PDF : xmpannotatedpdf - text citations : textcitations Por recomendação, será usado apenas o formato *BibTex* (*.bib) Com esse arquivo, o programa deve então processar e adicionar a base de dados atual as informações presentes no arquivo. #### 4.2.2 Testes Durante os testes são esperados encontrar os seguintes indicadores de erro ou sucesso: Uma entrada processada com erro ![Adicionado com sucesso](./Projeto_imgs/import_wrog_format.png) Uma entrada processada com sucesso ![Adicionado com sucesso](./Projeto_imgs/import_success.png) Para os testes dessa funcionalidade, utilizando o particionamente de equilvalência, separamos a entradas em 3 classes: - tipo do arquivo - Tipo de importação - Tipos de erros e para as as saidas, foram definidas duas classes: - Importação falhou - Importação com sucesso e Utilizando a analise de valor limite, foi definido o uso apenas do arquivo do tipo \*.bib para testar os tipos de importação. ID | Tipo do arquivo | Tipo de importação | Erros no arquivo | Saida esperada - |- |- |- |- 1 |\*.bib | Automatica | Nenhum | Importação com sucesso 2 |\*.bib | BibTeX | Nenhum | Importação com sucesso 3 |\*.bib | BibTeXML | Nenhum | Falha na importação 4 |\*.bib | Biblioscape | Nenhum | Falha na importação 5 |\*.bib | Copac | Nenhum | Falha na importação 6 |\*.bib | INSPEC | Nenhum | Falha na importação 7 |\*.bib | ISI | Nenhum | Falha na importação 8 |\*.bib | MSBib | Nenhum | Falha na importação 9 |\*.bib | Medline | Nenhum | Falha na importação 10 |\*.bib | MedlinePlain | Nenhum | Falha na importação 11 |\*.bib | Ovid | Nenhum | Falha na importação 12 |\*.bib | PDFcontent | Nenhum | Falha na importação 13 |\*.bib | REPEC New Economic Papers (NEP) | Nenhum | Falha na importação 14 |\*.bib | RIS | Nenhum | Falha na importação 15 |\*.bib | Refer/Endnote | Nenhum | Falha na importação 16 |\*.bib | SilverPlatter | Nenhum | Falha na importação 17 |\*.bib | XMP-annotated PDF | Nenhum | Falha na importação 18 |\*.bib | text citations | Nenhum | Falha na importação 19 |\*.bib | Automatica | Faltando campo obrigatorio | Falha na importação 20 |\*.bib | Automatica | Campos obrigatorios em branco | Importação com sucesso 21 |\*.bib | Automatica | Formato errado | Falha na importação 22 |\*.bib | Automatica | Arquivo vazio | Falha na importação #### 4.2.3 Comentários Durante os testes foi notado que em casos do arquivo com erro, principalmente faltando um campo ou com o mesmo vazio, ainda ocorria a importação. Já no caso de importar o arquivo com formatação errada, ele ainda tentava encontrar um formato de arquivo compatível e caso fosse haveria sucesso na importação. O único caso com erro que impediu a importação foi com o arquivo vazio. E como esperado, caso especificado o tipo do arquivo e fornecido um tipo diferente o mesmo não seria importado. <div style="page-break-after: always; visibility: hidden"> \pagebreak </div> ## 5. Manutenções Perfectivas ### 5.1 Validação de campos #### 5.1.1 Validação de Ano Para adicionar essa funcionalidade, foi alterado a função *setField* em *[jabref/src/main/java/net/sf/jabref/model/entry/BibEntry.java](https://github.com/Caotichazard/DC-UFSCar-ES2-202101-ENPE-3-NewJabRef/pull/4/commits/813dc205c780eb046981999f6bddd5b8676954c4#diff-0e97bf2bbf98406d4004bf7659ebcfb5d76c10dc8cf6ec830bee8b2a26f30d23 "jabref/src/main/java/net/sf/jabref/model/entry/BibEntry.java")* Onde a função analisa o valor a ser inserido no campo sendo editado, e caso o valor seja inválido, levanta uma excessão e indica ao usuário o erro reportado através de uma janela *pop-up*. A validação do ano é feita por comparar o ano inserido com os valores mínimo e máximo do campo *Year* em *java.time.Year*, sendo eles respectivamente, -999999999 e +999999999 (ambos os valores sendo fornecidos pelas constantes *Year.MIN_VALUE* e *Year.MAX_VALUE*). ![Adicionado com sucesso](./Projeto_imgs/changes_validate_year.png) #### 5.1.2 Validação de *BibTexKey* Para adicionar essa funcionalidade, foi alterada a função *checkLegalKey* em *[jabref/src/main/java/net/sf/jabref/logic/labelpattern/LabelPatternUtil.java](https://github.com/Caotichazard/DC-UFSCar-ES2-202101-ENPE-3-NewJabRef/pull/4/commits/13d3b1d5866e0d90a3bf8e924aceeeec3caadb20#diff-39080b92b95f4d2637d4f47ab24b159ac9ed98bf71d529271c16554064a715fd "jabref/src/main/java/net/sf/jabref/logic/labelpattern/LabelPatternUtil.java")* Onde está função já realiza verificação da validade de uma chave *BibTexKey*, então bastava adicionar a funcionalidade de recusar chaves com menos de 2 caracteres e chaves que não possuíam uma letra como seu primeiro caractere. ![Adicionado com sucesso](./Projeto_imgs/changes_validate_bibtexkey.png) ### 5.2 Importação por CSV Nesta manutenção foi requisitado a adição da funcionalidade de importar **Artigos** e **Livros** por meio do formato de arquivo CSV Para atingir isso foram realizadas as seguintes mudanças. Primeiramente foi criado o arquivo *CsvImporter.java* o qual realiza a lógica de importação Depois foi alterado o arquivo *ImportFormatReader.java* onde é incluído o construtor do importador de arquivos CSV Foi optado por realizar a importação por uso de uma *regex (regular expression)* a qual acessa linha por linha do arquivo e obtêm os nomes dos campos e seus valores. ![Adicionado com sucesso](./Projeto_imgs/changes_add_csvImporter.png) ![Adicionado com sucesso](./Projeto_imgs/csv_importer_logic.png) <div style="page-break-after: always; visibility: hidden"> \pagebreak </div> ## 6. Testes de regressão e evolução Após as manutenções, foram realizados testes para exercitar as funcionalidades novas. ### 6.1 Teste da validação de campos Para realizar os testes em validações de campos, é necessário testar também a inserção dos campos para garantir o funcionamento normal das funções anteriores, e serão adicionados novos testes para exercitar as funcionalidades novas. Além disso, é esperado encontrar agora duas novas telas de erro: Erro no campo *Year* ![Adicionado com sucesso](./Projeto_imgs/year_input_error_invalid.png) Erro no campo *Year*, ano fora dos limites do calendário em Java ![Adicionado com sucesso](./Projeto_imgs/year_input_error_invalid_year.png) Erro no campo *BibTexKey* ![Adicionado com sucesso](./Projeto_imgs/bibtexkey_invalid_input.png) ##### 6.1.1 Adicionar Artigo Para a funcionalidade de adicionar um Artigo, foram realizados os seguintes testes Utilizando o particionamento de equivalência, podemos dividir nossas entradas em 3 tipos: - um campo vazio (indicado por -) - um campo com uma entrada invalida (neste caso foi usado o caracter # indicado como invalido na documentação, o uso de caracteres para o campo *Year*, o qual só aceita números e entradas com menos de 2 caractéres ou o primeiro caracter diferente de uma letra em *BibTexKey*) - um campo com entrada válida e as saídas em 2 classes: - Erro em um campo - Entrada adicionada ID |Author | Title | Journal | Year | Bibtexkey | Saida esperada - |-|-|-|-|-|- 1 |-|-|-|-|-|todos campos em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 2|author|-|-|-|-|todos os campos, exceto author, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 3|-|title|-|-|-|todos os campos, exceto title, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 4|-|-|journal|-|-|todos os campos, exceto journal, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 5|-|-|-|year|-|todos os campos, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 6|-|-|-|-|Bibtexkey|todos os campos, exceto Bibtexkey, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 7|-|title|journal|year|Bibtexkey|Apenas o campo author e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 8|author|-|journal|year|Bibtexkey|Apenas o campo title e year em vermelho , indicando erro e um *pop-up* indicando erro no campo *year* 9|author|title|-|year|Bibtexkey|Apenas o campo journal e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 10|author|title|journal|-|Bibtexkey|Apenas o campo year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 11|author|title|journal|year|-|Apenas o campo bibtexkey e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 12|#|title|journal|year|Bibtexkey|Apenas o campo author e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 13|author|#|journal|year|Bibtexkey|Apenas o campo title e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 14|author|title|#|year|Bibtexkey|Apenas o campo journal e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 15|author|title|journal|#|Bibtexkey|Apenas o campo year e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 16|author|title|journal|year|#|Apenas o campo BibTexKey e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* e um *pop-up* indicando erro no campo *BibTexKey* 17|author|title|journal|9999999991|Bibtexkey|Apenas o campo year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 18|author|title|journal|1234567891|Bibtexkey|Apenas o campo year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 19|author|title|journal|999999999|Bibtexkey|Entrada adicionada a base de dados 20|author|title|journal|123456789|Bibtexkey|Entrada adicionada a base de dados 21|author|title|journal|123456789|B|Apenas o campo BibTexKey em vermelho, indicando erro e um *pop-up* indicando erro no campo *BibTexKey* 22|author|title|journal|123456789|1Bi|Apenas o campo BibTexKey em vermelho, indicando erro e um *pop-up* indicando erro no campo *BibTexKey* 23|author|title|journal|123456789|Bi|Entrada adicionada a base de dados 24|author|title|journal|123456789|bi|Entrada adicionada a base de dados 25|author|title|journal|1234|Bibtexkey|Entrada adicionada a base de dados ##### 6.1.2 Adicionar Livro Para a funcionalidade de adicionar um Livro, foram realizados os seguintes testes Utilizando o particionamento de equivalência, podemos dividir nossas entradas em 3 tipos: - um campo vazio (indicado por -) - um campo com uma entrada invalida (neste caso foi usado o caracter # indicado como invalido na documentação, o uso de caracteres para o campo *Year*, o qual só aceita números e entradas com menos de 2 caractéres ou o primeiro caracter diferente de uma letra em *BibTexKey*) - um campo com entrada válida e as saídas em 2 classes: - Erro em um campo - Entrada adicionada ID |Title | Publisher | Year | Author | Editor | Bibtexkey | Saida esperada -| -|-|-|-|-|-|- 1|-|-|-|-|-|-|todos campos em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 2|title|-|-|-|-|-|todos os campos, exceto title, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 3|-|publisher|-|-|-|-|todos os campos, exceto publisher, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 4|-|-|year|-|-|-|todos os campos, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 5|-|-|-|author|-|-|todos os campos, exceto author, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 6|-|-|-|-|editor|-|todos os campos, exceto editor, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 7|-|-|-|-|-|bibtexkey|todos os campos, exceto bibtexkey, em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 8|-|publisher|year|author|editor|bibtexkey|Apenas o campo title e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 9|title|-|year|author|editor|bibtexkey|Apenas o campo publisher e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 10|title|publisher|-|author|editor|bibtexkey|Apenas o campo year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 11|title|publisher|year|-|editor|bibtexkey|Apenas o campo author e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 12|title|publisher|year|author|-|bibtexkey|Apenas o campo editor e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 13|title|publisher|year|author|editor|-|Apenas o campo bibtexkey e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 14|#|publisher|year|author|editor|bibtexkey|Apenas o campo title e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 15|title|#|year|author|editor|bibtexkey|Apenas o campo publisher e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 16|title|publisher|#|author|editor|bibtexkey|Apenas o campo year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 17|title|publisher|year|#|editor|bibtexkey|Apenas o campo author e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 18|title|publisher|year|author|#|bibtexkey|Apenas o campo editor e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 19|title|publisher|year|author|editor|#|Apenas o campo bibtexkey e year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* e um *pop-up* indicando erro no campo *BibTexKey* 20|title|publisher|9999999991|author|editor|bibtexkey|Apenas o campo year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 21|title|publisher|1234567891|author|editor|bibtexkey|Apenas o campo year em vermelho, indicando erro e um *pop-up* indicando erro no campo *year* 22|title|publisher|999999999|author|editor|bibtexkey|Entrada adicionada a base de dados 23|title|publisher|123456789|author|editor|bibtexkey|Entrada adicionada a base de dados 24|title|publisher|123456789|author|editor|B|Apenas o campo BibTexKey em vermelho, indicando erro e um *pop-up* indicando erro no campo *BibTexKey* 25|title|publisher|123456789|author|editor|1Bi|Apenas o campo BibTexKey em vermelho, indicando erro e um *pop-up* indicando erro no campo *BibTexKey* 26|title|publisher|123456789|author|editor|Bi|Entrada adicionada a base de dados 27|title|publisher|123456789|author|editor|bi|Entrada adicionada a base de dados 28|title|publisher|1234|author|editor|bibtexkey|Entrada adicionada a base de dados ### 6.2 Teste da importação por CSV Como nos testes anteriores dessa funcionalidade, utilizando o particionamente de equilvalência, separamos a entradas em 3 classes: - tipo do arquivo - Tipo de importação - Tipos de erros e para as as saidas, foram definidas duas classes: - Importação falhou - Importação com sucesso e Utilizando a analise de valor limite, foi definido o uso apenas do arquivo do tipo \*.bib para testar os tipos de importação aleḿ de adicionar casos de uso com o arquivo do tipo \*.csv para exercitar a funcionalidade adicionada. ID | Tipo do arquivo | Tipo de importação | Erros no arquivo | Saida esperada - |- |- |- |- 1 |\*.bib | Automatica | Nenhum | Importação com sucesso 2 |\*.bib | BibTeX | Nenhum | Importação com sucesso 3 |\*.bib | BibTeXML | Nenhum | Falha na importação 4 |\*.bib | Biblioscape | Nenhum | Falha na importação 5 |\*.bib | Copac | Nenhum | Falha na importação 6 |\*.bib | INSPEC | Nenhum | Falha na importação 7 |\*.bib | ISI | Nenhum | Falha na importação 8 |\*.bib | MSBib | Nenhum | Falha na importação 9 |\*.bib | Medline | Nenhum | Falha na importação 10 |\*.bib | MedlinePlain | Nenhum | Falha na importação 11 |\*.bib | Ovid | Nenhum | Falha na importação 12 |\*.bib | PDFcontent | Nenhum | Falha na importação 13 |\*.bib | REPEC New Economic Papers (NEP) | Nenhum | Falha na importação 14 |\*.bib | RIS | Nenhum | Falha na importação 15 |\*.bib | Refer/Endnote | Nenhum | Falha na importação 16 |\*.bib | SilverPlatter | Nenhum | Falha na importação 17 |\*.bib | XMP-annotated PDF | Nenhum | Falha na importação 18 |\*.bib | text citations | Nenhum | Falha na importação 19 |\*.bib | CSV | Nenhum | Falha na importação 20 |\*.bib | Automatica | Faltando campo obrigatorio | Falha na importação 21 |\*.bib | Automatica | Campos obrigatorios em branco | Importação com sucesso 22 |\*.bib | Automatica | Formato errado | Falha na importação 23 |\*.bib | Automatica | Arquivo vazio | Falha na importação 24 |\*.csv | CSV | Nenhum | Importação com sucesso 25 |\*.csv | CSV | Faltando campo obrigatorio | Falha na importação 26 |\*.csv | Automatica | Campos obrigatorios em branco | Importação com sucesso 27 |\*.csv | Automatica | Formato errado | Falha na importação 28 |\*.csv | Automatica | Arquivo vazio | Falha na importação 29 |\*.csv | Automatica | Nenhum | Importação com sucesso
C#
UTF-8
2,320
2.65625
3
[ "Unlicense" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyInitializer : MonoBehaviour { public GameObject greenSlime; // the game object of green slime public List<Vector3Int> greenSlimeLocations; // the array of vector 3s corosponding with the positions to spawn in green slimes GameObject[] greenSlimes; // for use when deleting old green slimes public GameObject purpleSlime; // the game object of purple slime public List<Vector3Int> purpleSlimeLocations; // the array of vector 3s corosponding with the positions to spawn in purple slimes GameObject[] purpleSlimes; // for use when deleting old purple slimes void Start() { greenSlimes = new GameObject[0]; purpleSlimes = new GameObject[0]; } public void InitializeEnemies() { // this if and nested loop ensures their arent any currently existing slimes if (greenSlimes.Length > 0) { foreach (GameObject slime in greenSlimes) { Destroy(slime); } } // spawn in each green slime Quaternion roation = new Quaternion(0, 0, 0, 1); greenSlimes = new GameObject[greenSlimeLocations.Count]; int i = 0; foreach(Vector3 location in greenSlimeLocations) { location.Set(location.x, location.y + 0.5f, -0.1f); greenSlimes[i] = Instantiate(greenSlime, location, roation); greenSlimes[i++].GetComponent<GreenSlimeBehaviour>().player = transform.GetChild(0).gameObject; } // this if and nested loop ensures their arent any currently existing purple slimes if (purpleSlimes.Length > 0) { foreach (GameObject slime in purpleSlimes) { Destroy(slime); } } // spawn in each purple slime purpleSlimes = new GameObject[purpleSlimeLocations.Count]; i = 0; foreach(Vector3 location in purpleSlimeLocations) { location.Set(location.x, location.y + 0.5f, -0.1f); purpleSlimes[i] = Instantiate(purpleSlime, location, roation); purpleSlimes[i++].GetComponent<PurpleSlimeBehaviour>().player = transform.GetChild(0).gameObject; } } }
Java
UTF-8
828
2.0625
2
[]
no_license
package tickets.client; import java.util.List; import tickets.common.DestinationCard; import tickets.common.Lobby; import tickets.common.Route; import tickets.common.TrainCardWrapper; import tickets.common.UserData; public interface ITaskManager { void register(UserData userData); void login(UserData userData); void joinLobby(String id); void createLobby(Lobby lobby); void resumeLobby(String lobbyID); void resumeGame(String gameID); void logout(); void startGame(String lobbyID); void leaveLobby(String lobbyID); void addToChat(String message); void drawTrainCard(); void drawFaceUpCard(int position); void claimRoute(Route route, TrainCardWrapper cards); void drawDestinationCard(); void discardDestinationCard(List<DestinationCard> discard); }
Python
UTF-8
814
3.125
3
[]
no_license
__author__ = 'Lonja' import socket import sys import time HOST, PORT = "localhost", 9999 data = " ".join(sys.argv[1:]) # Create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((HOST, PORT)) except: pass print("could not connect to socket") while True: data = {} data["sysTime"] = time.strftime("%H:%M:%S") try: for key, value in data: sock.sendall((str(key) + "," + str(value)).encode("utf-8")) # Connect to server and send data #sock.sendall((data + "\n").encode('utf-8')) # Receive data from the server received = sock.recv(1024) except: print("could not send data") print("Sent: {}".format(data)) print("Received: {}".format(received))
Python
UTF-8
1,297
2.53125
3
[]
no_license
import discord from discord.ext import commands import os import random import common class Overwatch(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def owlootboxfarm(self, ctx): await ctx.send('<@' + str(ctx.message.author.id) + '> Have that itch to gamble but don\'t feel like spending money to do it? Then use this method to farm loot boxes while AFK!\nIt is recommended to start this method before you go to sleep. Please note that you cannot use your computer while using this method.\n1. Set region to Europe in Battle.net.\n2. Go to controls and bind \'Move forwards\' to spacebar.\n3. Go to video settings and put options to lowest quality possible, including resolution. Also put the game in windowed mode.\n4. Go to custom games and search for \'XP\'. Then join one that isn\'t full. If you can\'t find one that isn\'t full, then join the one with the least amount of spectators.\n5. Put a weight on your spacebar and walk away.\nThis yields roughly 2 - 3 loot boxes per night.\nIf at any point you encounter error BN-563, DO NOT ATTEMPT TO LOGIN THROUGH THE OVERWATCH CLIENT. CLOSE OVERWATCH AND REOPEN IT.\nImage tutorial: https://imgur.com/a/TOG4LFj') def setup(client): client.add_cog(Overwatch(client))
Python
UTF-8
1,456
3.5625
4
[]
no_license
from typing import List class Solution: def __init__(self): self.nums1 = None self.nums2 = None def findKthOfTwo(self, l1: int, l2: int, k: int) -> int: nums1 = self.nums1 nums2 = self.nums2 n = len(nums1) m = len(nums2) # nums1 is empty if l1 == n: return nums2[l2+k-1] # nums2 is empty if l2 == m: return nums1[l1+k-1] # both not empty if k == 1: return nums1[l1] if nums1[l1] <= nums2[l2] else nums2[l2] # to avoid the rest length of nums1/nums2 is shorter than k//2 k1 = k//2 if l1+k//2 <= n else n-l1 k2 = k//2 if l2+k//2 <= m else m-l2 if nums1[l1+k1-1] == nums2[l2+k2-1]: return nums1[l1+k1-1] if k-k1-k2 == 0 else self.findKthOfTwo(l1+k1, l2+k2, k-k1-k2) elif nums1[l1+k1-1] > nums2[l2+k2-1]: return self.findKthOfTwo(l1, l2+k2, k-k2) else: return self.findKthOfTwo(l1+k1, l2, k-k1) def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n = len(nums1) m = len(nums2) self.nums1 = nums1 self.nums2 = nums2 # median: the average of (n+m+1)//2 th and (n+m+2)//2 th return (self.findKthOfTwo(0, 0, (n+m+1)//2) + self.findKthOfTwo(0, 0, (n+m+2)//2)) / 2 a = Solution() nums1 = [2,3,9] nums2 = [6,7] print(a.findMedianSortedArrays(nums1, nums2))
Java
UTF-8
837
2.796875
3
[]
no_license
package com.cl.test; public class Knapsack{ public static void main(String[] args) { int[]w={1,4,3}; int[]val={1500,3000,2000}; int m=4; int n=val.length; int[][] v=new int[n+1][m+1]; int path[][]=new int[n+1][m+1]; for(int i=1;i<v.length;i++){ for(int j=1;j<v[0].length;j++){ if(w[i-1]>j){ v[i][j]=v[i-1][j]; }else{ v[i][j]=Math.max(v[i-1][j],val[i-1]+v[i-1][j-w[i-1]]); } } } for(int i=0;i<v.length;i++){ for(int j=0;j<v[0].length;j++){ System.out.print(v[i][j]+" "); } System.out.println(); } } }
Python
UTF-8
1,286
3.359375
3
[]
no_license
class Solution: # @param board, a list of lists of 1 length string # @param word, a string # @return a boolean def exist(self, board, word): m = len(board) n = len(board[0]) current = [[ False for i in range(n)] for j in range(m) ] board = [ [x for x in item] for item in board] for i in range(m): for j in range(n): if board[i][j] == word[0]: current[i][j] = True if self.exist_re(board,m,n,word,1,current,i,j): return True current[i][j] = False return False def exist_re(self,board,m,n,word,k,current,i,j): if k == len(word): return True for item in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]: if (item[0]>=0 and item[0]<m and item[1]>=0 and item[1]<n) and current[item[0]][item[1]] == False and board[item[0]][item[1]]==word[k]: current[item[0]][item[1]] = True if self.exist_re(board,m,n,word,k+1,current,item[0],item[1]): return True current[item[0]][item[1]] = False return False def isValid(self,m,n,i,j): return i>=0 and i<m and j>=0 and j<n
Python
UTF-8
2,670
3.875
4
[ "MIT" ]
permissive
# Practice Activity 2 for Principles of Computing class, by k., 07/07/2014 # simplified Nim (Monte Carlo solver) (see https://class.coursera.org/principlescomputing-001/wiki/view?page=nim_mc ) # template: http://www.codeskulptor.org/#poc_nim_mc_template.py # official solution: http://www.codeskulptor.org/#poc_nim_mc_student.py ''' a simple Monte Carlo solver for Nim (http://en.wikipedia.org/wiki/Nim#The_21_game ) ''' import random #import codeskulptor #codeskulptor.set_timeout(20) MAX_REMOVE = 3 TRIALS = 10000 def evaluate_position(num_items): ''' Monte Carlo evalation method for Nim ''' max_computer_wins = float('-inf') for move in range(1, (MAX_REMOVE) + 1): computer_wins = 0 for trial in range(TRIALS): initial_move = move current_items = num_items - initial_move while True: # play & evaluate player's move generated_move = random.choice(range(1, (MAX_REMOVE) + 1)) current_items -= generated_move if current_items <= 0: break # play & evaluate computer's move generated_move = random.choice(range(1, (MAX_REMOVE) + 1)) current_items -= generated_move if current_items <= 0: computer_wins += 1 break # keeping track of best value amongst (1, 2, 3) initial moves if max_computer_wins < computer_wins: result = move max_computer_wins = computer_wins #print 'For', move, 'Computer won:', computer_wins, 'Player won:', TRIALS - computer_wins return result #print evaluate_position(10) # optimal strategy: when your turn to move, remove exactly enough items so that the number of items # remaining in the heap has remainder zero when divided by four def play_game(start_items): ''' play a game of Nim against Monte Carlo bot ''' current_items = start_items print 'Starting game with value', current_items while True: comp_move = evaluate_position(current_items) current_items -= comp_move print 'Computer choose', comp_move, ', current value is', current_items if current_items <= 0: print 'Computer wins' break player_move = int(input('Enter your current move: ')) current_items -= player_move print 'Player choose', player_move, ', current value is', current_items if current_items <= 0: print 'Player wins' break #play_game(21) # quick test #play_game(10)
Java
UTF-8
908
1.90625
2
[]
no_license
package com.fmcna.fhpckd.beans.staging; /** * * @author vidhishanandhikonda * */ public class MemberSplitMergeResponse { private String type; private Long fhpId; private boolean success; private String failureCode; private String failureReason; public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getFhpId() { return fhpId; } public void setFhpId(Long fhpId) { this.fhpId = fhpId; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getFailureCode() { return failureCode; } public void setFailureCode(String failureCode) { this.failureCode = failureCode; } public String getFailureReason() { return failureReason; } public void setFailureReason(String failureReason) { this.failureReason = failureReason; } }
Java
UTF-8
2,019
2.125
2
[ "Apache-2.0" ]
permissive
package com.example.wealther.app.service; import com.example.wealther.app.receiver.AutoUpdateReceiver; import com.example.wealther.app.util.HttpCallbackListener; import com.example.wealther.app.util.HttpUtil; import com.example.wealther.app.util.Utility; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; public class AutoUpdateService extends Service{ @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub updatewealther(); } }).start(); AlarmManager manager=(AlarmManager) getSystemService(ALARM_SERVICE); int anHour=8*60*60*1000; long triggerAtTime=SystemClock.elapsedRealtime() + anHour; Intent i=new Intent(this,AutoUpdateReceiver.class); PendingIntent pi=PendingIntent.getBroadcast(this,0,i,0); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi); return super.onStartCommand(intent, flags, startId); } protected void updatewealther() { // TODO Auto-generated method stub SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); String wealtherCode=prefs.getString("wealther_code",""); String address="http://www.weather.com.cn/data/cityinfo/" + wealtherCode + ".html"; HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { // TODO Auto-generated method stub Utility.handleWealtherResponse(AutoUpdateService.this, response); } @Override public void onError(Exception e) { // TODO Auto-generated method stub e.printStackTrace(); } }); } }
Java
UTF-8
1,147
3.21875
3
[]
no_license
class Solution { private class Node { String word; Node[] succ; Node() { succ = new Node[26]; } Node getSuccNode(char ch) { return succ[ch - 'a']; } Node getOrCreateNode(char ch) { if (getSuccNode(ch) == null) succ[ch - 'a'] = new Node(); return getSuccNode(ch); } } public List<String> findAllConcatenatedWordsInADict(String[] words) { Node root = new Node(); for (String word : words) { Node cur = root; for (char ch : word.toCharArray()) { cur = cur.getOrCreateNode(ch); } cur.word = word; } List<String> res = new LinkedList<>(); for (String word : words) { if (word.isEmpty()) continue; if (helper(word, 0, root, root)) res.add(word); } return res; } private boolean helper(String word, int p, Node root, Node baseRoot) { if (root == null) return false; if (p == word.length()) { if (root.word != null && !word.equals(root.word)) return true; return false; } if (root.word != null) { if (helper(word, p + 1, baseRoot.getSuccNode(word.charAt(p)), baseRoot)) return true; } return helper(word, p + 1, root.getSuccNode(word.charAt(p)), baseRoot); } }
Java
UTF-8
433
2.34375
2
[ "Apache-2.0" ]
permissive
package team.lj.Tetris; public class I extends Tetromino { /** * �ṩ�����������г�ʼ�� * T�͵��ĸ񷽿��λ�� * */ public I() { cells[0]=new Cell(0,4,Tetris.I); cells[1]=new Cell(0,3,Tetris.I); cells[2]=new Cell(0,5,Tetris.I); cells[3]=new Cell(0,6,Tetris.I); states = new State[] { new State(0, 0, 0, -1, 0, 1, 0, 2), new State(0, 0, -1, 0, 1, 0, 2, 0)}; } }
PHP
UTF-8
3,497
2.953125
3
[]
no_license
<?php declare(strict_types = 1); /** * PHP version 7.4 * * @category PHP * @package Madsoft\Library * @author Gyula Madarasz <gyula.madarasz@gmail.com> * @copyright 2020 Gyula Madarasz * @license Copyright (c) All rights reserved. * @link this */ namespace Madsoft\Library; use RuntimeException; /** * Json * * @category PHP * @package Madsoft\Library * @author Gyula Madarasz <gyula.madarasz@gmail.com> * @copyright 2020 Gyula Madarasz * @license Copyright (c) All rights reserved. * @link this */ class Json { const DECODE_OPTIONS = ['array', 'object']; /** * Method encode * * @param mixed $data data * @param int $options options * @param int $depth depth * * @return string * @throws RuntimeException */ public function encode($data, int $options = 0, int $depth = 512): string { $str = json_encode($data, $options, $depth); if (false === $str) { throw new RuntimeException($this->getError($str)); } return $str; } /** * Method decode * * @param string $json json * @param string $option option * @param int $depth depth * @param int $options options * * @return mixed * @throws RuntimeException */ public function decode( string $json, string $option = 'array', int $depth = 512, int $options = 0 ) { if (!in_array($option, self::DECODE_OPTIONS, true)) { throw new RuntimeException( 'Invalid devode option "$assoc" given. Possible options: ' . implode(', ', self::DECODE_OPTIONS) ); } $data = json_decode( $json, $option === 'array' ? true : false, $depth, $options ); if (false === $data) { throw new RuntimeException($this->getError($data)); } return $data; } /** * Method getError * * @param mixed $result result * * @return string */ protected function getError($result): string { $error = 'Could not decode JSON!'; //Backwards compatability. if (!function_exists('json_last_error')) { return $error; } //Get the last JSON error. $jsonError = json_last_error(); //In some cases, this will happen. if (is_null($result) && $jsonError == JSON_ERROR_NONE) { return $error; } //If an error exists. if ($jsonError != JSON_ERROR_NONE) { $error .= ' ' . $this->getErrorDetails($jsonError); } return $error; } /** * Method getErrorDetails * * @param mixed $jsonError jsonError * * @return string */ protected function getErrorDetails($jsonError): string { //Use a switch statement to figure out the exact error. switch ($jsonError) { case JSON_ERROR_DEPTH: return 'Maximum depth exceeded!'; case JSON_ERROR_STATE_MISMATCH: return 'Underflow or the modes mismatch!'; case JSON_ERROR_CTRL_CHAR: return 'Unexpected control character found'; case JSON_ERROR_SYNTAX: return 'Malformed JSON'; case JSON_ERROR_UTF8: return 'Malformed UTF-8 characters found!'; } return 'Unknown error!'; } }
Ruby
UTF-8
2,679
3.078125
3
[]
no_license
require_relative 'questions_database' require_relative 'user' require_relative 'reply' require_relative 'question_follow' require_relative 'question_like' class Question attr_reader :id attr_accessor :title, :body, :author_id def self.all data = QuestionsDatabase.instance.execute("SELECT * FROM questions") data.map { |datum| Question.new(datum) } end def initialize(options) @id, @title, @body, @author_id = options.values_at("id", "title", "body", "author_id") end def save if @id # update QuestionsDatabase.instance.execute(<<-SQL, title: title, body: body, author_id: author_id, id: id) UPDATE questions SET title = :title, body = :body, author_id = :author_id WHERE questions.id = :id SQL else QuestionsDatabase.instance.execute(<<-SQL, title: title, body: body, author_id: author_id) INSERT INTO questions (title, body, author_id) VALUES (:title, :body, :author_id) SQL @id = QuestionsDatabase.instance.last_insert_row_id end self end def self.find(id) question_data = QuestionsDatabase.instance.get_first_row(<<-SQL, id: id) SELECT questions.* FROM questions WHERE questions.id = :id SQL question_data.nil? ? nil : Question.new(question_data) end def self.find_by_author_id(author_id) questions_data = QuestionsDatabase.instance.execute(<<-SQL, author_id: author_id) SELECT questions.* FROM questions WHERE questions.author_id = :author_id SQL return nil unless questions_data.length > 0 questions_data.map { |q_data| Question.new(q_data) } end def self.most_followed(n) QuestionFollow.most_followed_questions(n) end # Question::most_liked(n) def self.most_liked(n) QuestionLike.most_liked_questions(n) end def author User.find_by_id(id) end def replies Reply.find_by_question_id(id) end def followers QuestionFollow.followers_for_question_id(id) end def likers QuestionLike.likers_for_question_id(id) end def num_likes QuestionLike.num_likes_for_question_id(id) end def liked_questions QuestionLike.liked_questions_for_user_id(id) end end
Python
UTF-8
2,358
2.875
3
[]
no_license
__author__ = 'sdlee' import urllib import os import filecmp import re import hashlib import xml.etree.ElementTree as ET def string_to_md5(string): md5 = hashlib.md5(string) return md5.hexdigest() def print_site_title(rss_filename): tree = ET.parse(rss_filename) root = tree.getroot() channel = root.find("channel") site_title = channel.findtext("title") print site_title def print_feed_title(rss_filename): tree = ET.parse(rss_filename) root = tree.getroot() for iterator_item in root.iter("item"): print iterator_item.findtext("title") def remove_pubDate(filename): filename_tmp = filename + '_tmp' tree = ET.parse(filename) root = tree.getroot() channels = root.findall("channel") for parents in channels: for children in parents.findall("pubDate"): parents.remove(children) tree.write(filename_tmp) return filename_tmp def print_rss(result_file): print "==================== Site name ====================" print_site_title(result_file) print "==================== Title of Items ====================" print_feed_title(result_file) def rss_reader(rss_url, result_file): if not os.path.exists(result_file): # when downloaded file is not exist urllib.urlretrieve (rss_url, result_file) print "New RSS Feed is created succesfully.\n" print_rss(result_file) return urllib.urlretrieve (rss_url, "tmp.xml") no_pubDate_result_file = remove_pubDate(result_file) no_pubDate_tmp = remove_pubDate("tmp.xml") if not filecmp.cmp(no_pubDate_result_file, no_pubDate_tmp): print "Update!\n" # move tmp.xml to filename. ##### Move function is exist in library(os)? os.remove(result_file) os.rename("tmp.xml", result_file) else: print "Update is not available.\n" os.remove("tmp.xml") os.remove(no_pubDate_result_file) os.remove(no_pubDate_tmp) print_rss(result_file) url = raw_input('Enter RSS Feed url : ') # url = "http://onenable.tumblr.com/rss" # url = "http://blog.rss.naver.com/darkan84.xml" # url = "https://wikidocs.net/book/2/rss" result_file = string_to_md5(url) rss_reader(url, result_file) ##### rss_reader
Java
UTF-8
1,073
3.875
4
[]
no_license
package com.colin.mode; import java.util.Scanner; public class Goods { public Goods(Scanner input){ //构造方法,对每个需要存入的货物进行赋值,方法参数是Scanner input; System.out.print("请输入商品的名称:"); this.name = input.next(); System.out.print("请输入商品的价格:"); this.price = input.nextDouble(); System.out.print("请输入商品的库存:"); this.stock = input.nextInt(); //System.out.println("保存成功!!"); } /**名字*/ public String name; /** 商品价格*/ public double price; /** 商品数量*/ public int stock; /** * 把方法中字符串的值返回给主函数,在主函数中输出,主要动作方法都交给主函数; */ public String array(int i) { /**this. 就是主函数中temp. */ return ((i + 1) + "\t商品的名称:" + this.name + "\t 商品的的价格:" + this.price + "\t商品的库存:" + this.stock); } }
Markdown
UTF-8
2,473
2.71875
3
[]
no_license
# Zabracadabra capstone project # Team name: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Zabracadabra # Team members: - **Yurui Mu**: Yurui received her B.S. degree in Applied Mathematics and Statistics at SUNY Stony Brook. And she is now a second year full-time graduate student at NYU Center for Data Science. She has past research experience at National Supercomputing Center in Jinan, China. She has also worked as intern at MENUSIFU Inc. as data analyst. Having taken Machine Learning, Big Data, Deep Learning, Text As Data courses at CDS, she is interested in applications of machine learning in various fields of study. - **Wenqing Zhu**: Wenqing is also a second-year Data Science student at New York University. She has attained her B.A. degree in Mathematics and Economics at University of Illinois Urbana-Champaign. She has taken classes such as Machine Learning, Deep Learning, and Fundamentals of Algorithms for the past year. For coding, Wenqing has a programming background in Python and MapReduce. # Reason for teaming up: - We share same interest in working on natural language processing and the applications of machine learning . And we want to apply it in solving real world problems. # Top 4 project choices: - **Newspaper Coverage Data**: This project has two major research questions. The first question concerns how newspaper coverage has changed over time. The second question is about what newspaper coverage can tell us about the demand for information. The scope of project will be focused on tackling concrete question. - **NYU Langone Medical Center (with Narges Razavian)**: This project is on machine learning models on time series patient data to predict health outcomes. Some concrete initiatives include predict unidiagnosed diseases from electronic health records and medical notes, back-propagation or attention based modeks for visualization of machine learning model decisions per instance. - **NYUMC Population Health(with Judy Zhong)**: Our project proposes to use cutting edge deep learning methods to analyze the longitudinal data to predict CVD and disability development in PD/DM patients over time. These analyses will lead to practical population based methods to stratify people with DM for their individual risks of CVD and disability, helping to individualize care. - **Applied Bioinformatics Laboratories**: Classify lung cancer, breast cancer, prostate cancer and skin cancers and visualize features learned by models.
Python
UTF-8
1,714
3.390625
3
[]
no_license
import numpy as np """Checks to see if tree is valid.""" def check_tree(edges): if not len(edges) or edges.min() != 0 or edges.max() != len(edges): return False seen = set() for edge in edges: if edge[0] in seen and edge[1] in seen: return False else: seen.add(edge[0]) seen.add(edge[1]) return True """Checks if prufer code is valid.""" def check_prufer(prufer): return prufer.min() >= 0 and prufer.max() <= len(prufer) + 1 """ Input: A tree consisting of an (n, 2) numpy array of edges. Edges given by starting and ending vertex (undirected). Vertices should be labeled 0...n so all entries in tree should be between 0...n Output: A numpy array for the prufer code of the tree. """ def t2p(input_edges): edges = input_edges.copy() if not check_tree(edges): raise ValueError("Input is not a valid tree") deg = np.zeros(len(edges) + 1) prufer = [] for e in edges: deg[e[0]] += 1 deg[e[1]] += 1 while not np.sum(deg) == 2: v = np.where(deg == 1)[0][0] (row, col) = np.where(edges == v) row = row[0] col = col[0] prufer.append(edges[row, int(not col)]) deg[edges[row, 0]] -= 1 deg[edges[row, 1]] -= 1 return np.array(prufer) """ Input: Prufer code consisting of a numpy array of vertices. Output: Edges of tree corresponding to prufer code. """ def p2t(prufer): if len(prufer) == 0: return np.array([[0, 1]]) if not check_prufer(prufer): raise ValueError("Input is not valid prufer code") deg = np.array([np.sum(prufer == i) + 1 for i in range(len(prufer) + 2)]) edges = [] for code in prufer: v = np.where(deg == 1)[0][0] edges.append(sorted([v, code])) deg[v] -= 1 deg[code] -= 1 edges.append(np.where(deg == 1)[0]) return np.array(edges)
C
UTF-8
2,876
2.921875
3
[]
no_license
/* ** main.c for in /home/gomes_m//svn/google/arthrose-sensiblement-matricielle ** ** Made by mickael gomes ** Login <gomes_m@epitech.net> ** ** Started on Tue Mar 26 20:34:12 2013 mickael gomes ** Last update Thu Mar 28 22:06:17 2013 mickael gomes */ #include <string.h> #include <stdlib.h> #include <stdio.h> int my_strlen(char *); char *my_strchr(char *, char); void *my_memcpy(char*, char*, int); void *my_memset(char *, int, size_t); int my_strcmp(char *, char *); void *my_memmove(char*, char*, size_t); int my_strncmp(char*, char*, size_t); int my_strcasecmp(char *, char *); char *my_rindex(char *, int); char *my_strstr(char *, char *); char *my_strpbrk(char *, char *); size_t my_strcspn(char*, char*); char *get_word(char *str) { char *new_str; int len = strlen(str); int i = 0; new_str = malloc(7 * sizeof(char)); while (i < len) new_str[i] = str[i++]; new_str[i] = 0; return (new_str); } int main(int ac, char **av) { printf("Strlen => %d\n", strlen(get_word("Poulet"))); printf("My_Strlen => %d\n", my_strlen(get_word("Poulet"))); printf("\nStrchr => %s\n", strchr(get_word("Vache"), 'a')); printf("My_Strchr => %s\n", my_strchr(get_word("Vache"), 'a')); printf("\nMemset => %s\n", memset(get_word("Poulet"), 63, 3)); printf("My_Memeset => %s\n", my_memset(get_word("Poulet"), 63, 3)); printf("\nMemcpy => %s\n", memcpy(get_word("Poulet"), get_word("Vache"), 4)); printf("My_memcpy => %s\n", my_memcpy(get_word("Poulet"), get_word("Vache"), 4)); printf("\nStrcmp => %d\n", strcmp(get_word("Poulet"), get_word("Poulet"))); printf("My_Strcmp => %d\n", my_strcmp(get_word("Poulet"), get_word("Poulet"))); /* printf("\nMemmove => %s\n", memmove(get_word("Poulet"), get_word("Vache"), 4)); */ /* printf("My_Memmove => %s\n", my_memmove(get_word("Poulet"), get_word("Vache"), 4)); */ printf("\nStrncmp => %d\n", strncmp(get_word("Poulet"), get_word("Poulette"), 7)); printf("My_Strncmp => %d\n", my_strncmp(get_word("Poulet"), get_word("Poulette"), 7)); printf("\nStrcasecmp => %d\n", strcasecmp(get_word("Poulet"), get_word("PouLet"))); printf("My_Strcasecmp => %d\n", my_strcasecmp(get_word("Poulet"), get_word("PouLet"))); printf("\nRindex => %s\n", rindex(get_word("Vachalait"), 'a')); printf("My_Rindex => %s\n", my_rindex(get_word("Vachalait"), 'a')); printf("\nStrstr => %s\n", strstr(get_word("Vachalaitmarron"), get_word("lait"))); printf("My_Strstr => %s\n", my_strstr(get_word("Vachalaitmarron"), get_word("lait"))); printf("\nStrpbrk => %s\n", strpbrk(get_word("Cul de Vache"), get_word("z"))); printf("My_Strpbrk => %s\n", my_strpbrk(get_word("Cul de Vache"), get_word("z"))); printf("\nStrcspn => %d\n", strcspn(get_word("Cul de Vache"), get_word("C"))); printf("My_Strcspn => %d\n", my_strcspn(get_word("Cul de Vache"), get_word("C"))); return (0); }
Markdown
UTF-8
2,991
3.375
3
[ "Apache-2.0" ]
permissive
The plan for this report was to analyze the various ways big data is used in the sports betting industry both by bookmakers to determine the odds and by gamblers to gain a competitive edge while betting. It was started by examining the way big data is used by the bookmakers. Many of the algorithms and methods bookmakers use are not available for the public to see (for obvious reasons) but there is still a lot of information about the type of data that bookmakers use and where they get it. There are also various companies dedicated to gathering and analyzing sports data that work in collaboration with bookmakers. With the research, it was found that odds compiling starts with game prediction models that use historical sports data. Both player and team data is analyzed to come up with game predictions about the score of the game and player performance. After finding out the big data methods bookmakers use to come up with game predictions, research was done about different algorithms and models that gamblers and researchers use to predict winnings bets. One of the first ones found was an algorithm made by a researcher at the university of tokyo that used the odds available by different bookmakers as the primary data used for the algorithm. From this paper, information was found that the odds put out by bookmakers do not reflect the exact probability predicted for the game, and there is more to the way bookmakers determine their odds rather than just game prediction models. This led back to doing more research on how bookmakers come up with their odds. Research showed that game prediction probabilities are the basis of odds compiling, but it isn’t just the prediction models that determine the odds. In order for the expected return to always be in the favor of the bookmaker, bookmakers add a margin to the actual predicted probability of an outcome, often based on public opinion. This method is used to reduce risk and ensure a positive expected return for bookmakers. After this, more research into different prediction models for betting occurred which led to looking into a lot of different algorithms and projects. Finding details for the algorithms big companies have created proved to be challenging since these companies try to keep their methods private. An article from a former odds compiler guided the direction of looking into the Poisson distribution for soccer predictions. This was a very popular game prediction method for soccer, used by both bookmakers and gamblers. The original plan was to take premier league data and create a Poisson distribution model on R using one year's worth of data and compare how it did to actual games. This did not end up happening so this project was changed to a report since there was not a programming aspect to it. Further research was done into different betting models, some that proved to be more accurate than others. A lot of them used artificial intelligence and machine learning neural networks.
Markdown
UTF-8
1,295
2.765625
3
[]
no_license
# Laravel Dusk Demo This is a demo project for the Alpha version of [Laravel Dusk](https://github.com/laravel/dusk). It basically tests the register and login functionality from the default application scaffold from Laravel running `php artisan make:auth` using Dusk. You can find the tests in the `tests/Browser` directory. For more information on the functions see the [Laravel Dusk documentation](https://github.com/laravel/dusk/blob/master/readme.md). ## Travis This project is build on Travis and also runs the `php artisan dusk` command there which is really cool! ## Running Dusk! - Clone or fork and clone the project - Run `composer install` - Create a database, default database name is set to `dusk_test`. So if you use a different database you need to update `.env.dusk.local` - Make sure your application is accessible by the browser. I used [homestead](https://laravel.com/docs/5.3/homestead) to set everything up. - Run `php artisan dusk` to run the tests You might see some chrome windows popup! Dusk is doing that for you! How **awesome** is that? If you watch the windows carefully you can even see the fields being filled. > Note: You don't have to migrate the database since it will migrate the database for each test. See `use DatabaseMigrations` in the test classes.
JavaScript
UTF-8
887
3.71875
4
[]
no_license
var A=[]; A.push([1]); // A.push([4,5,6]); // A.push([7,8,9]); function spiral(A){ var a=[]; var row=A.length; var col=A[0].length; var dir=0; var t=0; var b=row-1; var l=0; var r= col-1; while(t<=b&&l<=r){ if(dir===0){ for(var i=l;i<=r;i++){ a.push(A[t][i]); } t++; dir=1; }else if(dir===1){ for(var i=t;i<=b;i++){ a.push(A[i][r]); } r--; dir=2; }else if(dir===2){ for(var i=r;i>=l;i--){ a.push(A[b][i]); } b--; dir=3 }else if(dir===3){ for(var i=b;i>=t;i--){ a.push(a.push(A[i][l])) } l++; dir=0; } } console.log(a); } spiral(A);
C
UTF-8
1,628
2.53125
3
[]
no_license
// // UART0_BLE_TEST_LCD : BLE Device Test Command with LCD // // EVB : NuMaker Uni // MCU : NANO100NE3BN // BLE : ITON_DM BT2710 // UART0 to Bluetooth module // PB0/UART0-RX to BT2710's TX // PB1/UART0-TX to BT2710's RX // JP2 connections (I2C0 to LCD) // PA9/I2C0-SCL to LCD's SCL // PA8/I2C0-SDA to LCD's SDA #include <stdio.h> #include <string.h> #include "Nano100Series.h" #include "MCU_init.h" #include "SYS_init.h" #include "BLE_BT2710.h" #include "I2C_SSD1306Z.h" #define CMD_TYPE "itcz" #define ACK_TYPE "itaz" #define PACKET_DATA "TEST" volatile char Text[16]; volatile uint8_t RX_buffer[13]; volatile char BT_CMD[13] = {'i','t','c','z',0,0,0,4,'T','E','S','T',0xc0}; volatile char RSP_FOR_CMD; volatile uint8_t ptr = 0; void UART0_IRQHandler(void) { uint8_t in_char; uint32_t u32IntSts= UART0->ISR; if(u32IntSts & UART_IS_RX_READY(UART0)) { in_char = UART_READ(UART0); RX_buffer[ptr] = in_char; if(in_char==0) in_char=0x30; if(in_char==1) in_char=0x31; print_C(1,ptr,in_char); ptr++; if (ptr==10) { if (RX_buffer[9]==1) print_Line(3, "TEST_PASS"); else print_Line(3, "TEST_FAIL"); } } } void Init_BLE(void) { UART_Open(UART0, 115200); // enable UART0 at 115200 baudrate UART_ENABLE_INT(UART0, UART_IER_RDA_IE_Msk); NVIC_EnableIRQ(UART0_IRQn); } void BLE_Test() { UART_Write(UART0, (uint8_t*)BT_CMD, 13); } int32_t main() { SYS_Init(); Init_BLE(); I2C_Open(I2C0, I2C0_CLOCK_FREQUENCY); init_LCD(); clear_LCD(); print_Line(0,"BLE CMD TEST"); BLE_Test(); while(1) { } }
C++
UTF-8
1,455
3
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <vector> #include "BasicTile.h" #include "Tile.h" namespace sim { class Maze { public: Maze(); int getWidth() const; int getHeight() const; bool withinMaze(int x, int y) const; Tile* getTile(int x, int y); const Tile* getTile(int x, int y) const; bool isValidMaze() const; bool isOfficialMaze() const; bool isCenterTile(int x, int y) const; private: // Vector to hold all of the tiles std::vector<std::vector<Tile>> m_maze; // Used for memoizing MazeChecker functions bool m_isValidMaze; bool m_isOfficialMaze; // Initializes all of the tiles of the basic maze static std::vector<std::vector<Tile>> initializeFromBasicMaze(const std::vector<std::vector<BasicTile>>& basicMaze); // Returns a basic maze of a particular width and height static std::vector<std::vector<BasicTile>> getBlankBasicMaze(int mazeWidth, int mazeHeight); // Basic maze geometric transformations static std::vector<std::vector<BasicTile>> mirrorAcrossVertical(const std::vector<std::vector<BasicTile>>& basicMaze); static std::vector<std::vector<BasicTile>> rotateCounterClockwise(const std::vector<std::vector<BasicTile>>& basicMaze); // (Re)set the distance values for the tiles in maze that are reachable from the center static std::vector<std::vector<Tile>> setTileDistances(std::vector<std::vector<Tile>> maze); }; } // namespace sim
C#
UTF-8
1,962
2.8125
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; namespace EuclideanGeometryLib.Collections.Finite.Natural { public sealed class NfcChainedEnumerator<T> : IEnumerator<T> { private readonly NfcChained<T> _chain; private int _currentCollectionIndex; private FiniteCollection<T> _currentCollection; private int _currentItemIndex; internal NfcChainedEnumerator(NfcChained<T> chain) { _chain = chain; _currentCollectionIndex = -1; _currentCollection = null; _currentItemIndex = -1; Current = default(T); } public void Dispose() { } private bool MoveToNextCollection() { _currentCollectionIndex++; _currentItemIndex = -1; while (_currentCollectionIndex < _chain.BaseCollections.Count) { _currentCollection = _chain.BaseCollections[_currentCollectionIndex]; if (_currentCollection != null) return true; } return false; } public bool MoveNext() { if (_currentCollectionIndex == -1 && MoveToNextCollection() == false) return false; _currentItemIndex++; if (_currentItemIndex >= _currentCollection.Count && MoveToNextCollection() == false) return false; Current = _currentCollection.GetItem( _currentCollection.MinIndex + _currentItemIndex ); return true; } public void Reset() { _currentCollectionIndex = -1; _currentCollection = null; _currentItemIndex = -1; Current = default(T); } public T Current { get; private set; } object IEnumerator.Current => Current; } }
Java
UTF-8
907
2.359375
2
[]
no_license
package com.music.wiraazharan.dcprojects.toptracks; /** * Created by wiraazharan on 7/17/15. */ public class DataTracker { String trackname; String trackplaycount; String artistname; public DataTracker(String name , String playcount ,String artist) { this.trackname = name; this.trackplaycount = playcount; this.artistname = artist; } public void setTrackname(String trackname) { this.trackname = trackname; } public void setTrackplaycount(String trackplaycount) { this.trackplaycount = trackplaycount; } public void setArtistname(String artistname) { this.artistname = artistname; } public String getTrackname() { return trackname; } public String getTrackplaycount() { return trackplaycount; } public String getArtistname() { return artistname; } }
Swift
UTF-8
6,933
2.859375
3
[]
no_license
// // HypeEventDetailView.swift // HypedList // // Created by Natalia Stele on 11/04/2021. // import SwiftUI struct HypeEventDetailView: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @ObservedObject var hypeEvent: HypedEvent @State var showingCreatingView = false @State var deleted = false var isDiscover = false var body: some View { if deleted { Text("Event deleted") } else { if (horizontalSizeClass == .regular) { regular } else { compact } } } var regular: some View { VStack { VStack(spacing: 0) { if let eventImage = hypeEvent.image() { eventImage .resizable() .aspectRatio(contentMode : .fit) } else { hypeEvent.color .aspectRatio(contentMode: .fit) } Text(hypeEvent.title) .font(.largeTitle) .padding(.top, 10) Text("\(hypeEvent.dateFromNow().capitalized) on \(hypeEvent.dateAsString())") .padding(.bottom, 10) .padding(.top, 10) .font(.title) } .background(Color.white) .cornerRadius(10) .shadow(radius: 10) .padding(40) HStack { if hypeEvent.validURL() != nil { Button(action: { UIApplication.shared.open(hypeEvent.validURL()!) }) { HypedEventDetailsButtonViewRegular(text: "Visite Site", backgroundColor: .orange, imageName: "link") } } if isDiscover { Button(action: { DataController.shared.addFromDiscover(hypedEvent: hypeEvent) }) { HypedEventDetailsButtonViewRegular(text: hypeEvent.hasBeenAdded ? "Added" : "Add", backgroundColor: .green, imageName: "plus.circle") } .disabled(hypeEvent.hasBeenAdded) .opacity(hypeEvent.hasBeenAdded ? 0.5 : 1.0) } else { Button(action: { showingCreatingView = true }) { HypedEventDetailsButtonViewRegular(text: "Edit", backgroundColor: .yellow, imageName: "pencil.circle") } .sheet(isPresented: $showingCreatingView, content: { CreateHypedEventView(event: hypeEvent) }) Button(action: { deleted = true DataController.shared.deleteHypeEvent(hypedEvent: hypeEvent) }) { HypedEventDetailsButtonViewRegular(text: "Delete", backgroundColor: .red, imageName: "trash") } } } .padding() } .padding(40) } var compact: some View { VStack(spacing: 0) { if let eventImage = hypeEvent.image() { eventImage .resizable() .aspectRatio(contentMode : .fit) } Rectangle() .foregroundColor(hypeEvent.color) .frame(height: 10) HStack { Spacer() Text(hypeEvent.title) .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/) .bold() .padding() } .background(Color.white) Text("\(hypeEvent.dateFromNow().capitalized) on \(hypeEvent.dateAsString())") .font(.title2) Spacer() if hypeEvent.validURL() != nil { Button(action: { UIApplication.shared.open(hypeEvent.validURL()!) }) { HypedEventDetailsButtonView(text: "Visite Site", backgroundColor: .orange, imageName: "link") } } if isDiscover { Button(action: { DataController.shared.addFromDiscover(hypedEvent: hypeEvent) }) { HypedEventDetailsButtonView(text: hypeEvent.hasBeenAdded ? "Added" : "Add", backgroundColor: .green, imageName: "plus.circle") } .disabled(hypeEvent.hasBeenAdded) .opacity(hypeEvent.hasBeenAdded ? 0.5 : 1.0) } else { Button(action: { showingCreatingView = true }) { HypedEventDetailsButtonView(text: "Edit", backgroundColor: .yellow, imageName: "pencil.circle") } .sheet(isPresented: $showingCreatingView, content: { CreateHypedEventView(event: hypeEvent) }) Button(action: { deleted = true DataController.shared.deleteHypeEvent(hypedEvent: hypeEvent) }) { HypedEventDetailsButtonView(text: "Delete", backgroundColor: .red, imageName: "trash") } } } .navigationBarTitleDisplayMode(.inline) } } struct HypedEventDetailsButtonView: View { var text: String var backgroundColor: Color var imageName: String var body: some View { HStack { Spacer() Image(systemName: imageName) Text(text) Spacer() } .font(.title) .padding(12) .background(backgroundColor) .foregroundColor(.white) .cornerRadius(5) .padding(.horizontal, 20) .padding(.bottom, 10) } } struct HypedEventDetailsButtonViewRegular: View { var text: String var backgroundColor: Color var imageName: String var body: some View { HStack { Image(systemName: imageName) Text(text) } .font(.title) .padding(12) .background(backgroundColor) .foregroundColor(.white) .cornerRadius(5) } } struct HypeEventDetailView_Previews: PreviewProvider { static var previews: some View { Group { HypeEventDetailView(hypeEvent: testHypeEvents2) .previewDevice("iPhone 11") HypeEventDetailView(hypeEvent: testHypeEvents1) HypedEventDetailsButtonView(text: "Testing", backgroundColor: .green, imageName: "clock").previewLayout(.sizeThatFits) HypedEventDetailsButtonViewRegular(text: "Compact", backgroundColor: .orange, imageName: "clock").previewLayout(.sizeThatFits) } } }
C
UTF-8
7,404
3.109375
3
[]
no_license
#pragma once #include "database.h" #include "test_runner.h" #include "condition_parser.h" void TestDatabase() { istringstream empty_is(""); auto empty_condition = ParseCondition(empty_is); auto empty_predicate = [empty_condition](const Date& date, const string& event) { return empty_condition->Evaluate(date, event); }; // Add 2 - Del 1 - Add deleted again { Database db; Date d(2019, 1, 1); db.Add(d, "e1"); db.Add(d, "e2"); istringstream is(R"(event == "e1")"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.RemoveIf(predicate), 1, "Db Add2-Del-Add 1"); db.Add(d, "e1"); AssertEqual(db.FindIf(empty_predicate).size(), 2, "Db Add2-Del-Add 2"); } // Add /* { Database db; Date d(2019, 1, 1); db.Add(d, "e1"); db.Add(d, "e1"); istringstream is("date == 2019-01-01");s auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.FindIf(predicate).size(), 1, "Db Add Duplicates 1"); }*/ // Last //{ // Database db; // Date d(2019, 1, 1); // Date d1(2019, 1, 2); // Date d2(2018, 12, 22); // db.Add(d1, "e1"); // db.Add(d2, "e2"); // AssertEqual(db.Last(d), "2018-12-22 e2", "Db Last 1"); // Date d3(2018, 12, 24); // db.Add(d3, "e3"); // AssertEqual(db.Last(d), "2018-12-24 e3", "Db Last 2"); // // Get last event for date before first event // try { // Date d4(2017, 2, 2); // db.Last(d4); // Assert(false, "Db Last 3"); // } // catch (invalid_argument e) { // // Pass // } // // Delete event and get last // istringstream is("date == 2018-12-24"); // auto condition = ParseCondition(is); // auto predicate = [condition](const Date& date, const string& event) { // return condition->Evaluate(date, event); // }; // db.RemoveIf(predicate); // AssertEqual(db.Last(d), "2018-12-22 e2", "Db Last 4"); // AssertEqual(db.Last(d1), "2019-01-02 e1", "Db Last 5"); // db.Add(d2, "e4"); // AssertEqual(db.Last(d2), "2018-12-22 e4", "Db Last 6"); //} //// Del { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is("date == 2018-01-07"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.RemoveIf(predicate), 2, "Db Del 1"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is("date >= 2018-01-07 AND date <= 2020-01-01"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.RemoveIf(predicate), 4, "Db Del 2"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); AssertEqual(db.RemoveIf(empty_predicate), 4, "Db Del 3"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is(R"(event == "e1")"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.RemoveIf(predicate), 1, "Db Del 4"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is(R"(event == "e1" OR date == 2019-01-01)"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.RemoveIf(predicate), 2, "Db Del 5"); } //// Find { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is("date == 2018-01-07"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.FindIf(predicate).size(), 2, "Db Find 1"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is("date >= 2018-01-07 AND date <= 2020-01-01"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.FindIf(predicate).size(), 4, "Db Find 2"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); AssertEqual(db.FindIf(empty_predicate).size(), 4, "Db Find 3"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is(R"(event == "e1")"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.FindIf(predicate).size(), 1, "Db Find 4"); } { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); db.Add({ 2018, 1, 7 }, "e3"); db.Add({ 2018, 1, 7 }, "e4"); istringstream is(R"(event == "e1" OR date == 2019-01-01)"); auto condition = ParseCondition(is); auto predicate = [condition](const Date& date, const string& event) { return condition->Evaluate(date, event); }; AssertEqual(db.FindIf(predicate).size(), 2, "Db Find 5"); } // Add - Del - Add - Del { Database db; db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); AssertEqual(db.RemoveIf(empty_predicate), 2, "Db Add-Del-Add-Del 1"); db.Add({ 2019, 1, 1 }, "e1"); db.Add({ 2019, 1, 1 }, "e2"); AssertEqual(db.RemoveIf(empty_predicate), 2, "Db Add-Del-Add-Del 1"); } }
PHP
UTF-8
6,088
2.765625
3
[]
no_license
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace GbiliLangModule\View\Helper; use Zend\Form\ElementInterface; use Zend\Form\Exception; use Zend\Stdlib\ArrayUtils; /** * @changes Allow specifying which attributes should be translated * by adding a 'translate' option with an array of attribute to boolan (true: translate) */ class FormSelect extends \Zend\Form\View\Helper\FormSelect { protected $translatableAttributes = array( 'label' => true, ); /** * @see parent */ public function render(ElementInterface $element) { $default = $this->translatableAttributes['label']; $elementOptions = $element->getOptions(); if (isset($elementOptions['translate']['label'])) { $this->translatableAttributes['label'] = (boolean) $elementOptions['translate']['label']; } $parentReturn = parent::render($element); $this->translatableAttributes['label'] = $default; return $parentReturn; } /** * Render an array of options * * Individual options should be of the form: * * <code> * array( * 'value' => 'value', * 'label' => 'label', * 'disabled' => $booleanFlag, * 'selected' => $booleanFlag, * ) * </code> * * @param array $options * @param array $selectedOptions Option values that should be marked as selected * @return string */ public function renderOptions(array $options, array $selectedOptions = array()) { $template = '<option %s>%s</option>'; $optionStrings = array(); $escapeHtml = $this->getEscapeHtmlHelper(); foreach ($options as $key => $optionSpec) { $value = ''; $label = ''; $selected = false; $disabled = false; if (is_scalar($optionSpec)) { $optionSpec = array( 'label' => $optionSpec, 'value' => $key ); } if (isset($optionSpec['options']) && is_array($optionSpec['options'])) { $optionStrings[] = $this->renderOptgroup($optionSpec, $selectedOptions); continue; } if (isset($optionSpec['value'])) { $value = $optionSpec['value']; } if (isset($optionSpec['label'])) { $label = $optionSpec['label']; } if (isset($optionSpec['selected'])) { $selected = $optionSpec['selected']; } if (isset($optionSpec['disabled'])) { $disabled = $optionSpec['disabled']; } if (ArrayUtils::inArray($value, $selectedOptions)) { $selected = true; } if ($this->translatableAttributes['label'] && null !== ($translator = $this->getTranslator())) { $label = $translator->translate( $label, $this->getTranslatorTextDomain() ); } $attributes = compact('value', 'selected', 'disabled'); if (isset($optionSpec['attributes']) && is_array($optionSpec['attributes'])) { $attributes = array_merge($attributes, $optionSpec['attributes']); } $this->validTagAttributes = $this->validOptionAttributes; $optionStrings[] = sprintf( $template, $this->createAttributesString($attributes), $escapeHtml($label) ); } return implode("\n", $optionStrings); } /** * Render an optgroup * * See {@link renderOptions()} for the options specification. Basically, * an optgroup is simply an option that has an additional "options" key * with an array following the specification for renderOptions(). * * @param array $optgroup * @param array $selectedOptions * @return string */ public function renderOptgroup(array $optgroup, array $selectedOptions = array()) { $template = '<optgroup%s>%s</optgroup>'; $options = array(); if (isset($optgroup['options']) && is_array($optgroup['options'])) { $options = $optgroup['options']; unset($optgroup['options']); } $this->validTagAttributes = $this->validOptgroupAttributes; $attributes = $this->createAttributesString($optgroup); if (!empty($attributes)) { $attributes = ' ' . $attributes; } return sprintf( $template, $attributes, $this->renderOptions($options, $selectedOptions) ); } /** * Ensure that the value is set appropriately * * If the element's value attribute is an array, but there is no multiple * attribute, or that attribute does not evaluate to true, then we have * a domain issue -- you cannot have multiple options selected unless the * multiple attribute is present and enabled. * * @param mixed $value * @param array $attributes * @return array * @throws Exception\DomainException */ protected function validateMultiValue($value, array $attributes) { if (null === $value) { return array(); } if (!is_array($value)) { return (array) $value; } if (!isset($attributes['multiple']) || !$attributes['multiple']) { throw new Exception\DomainException(sprintf( '%s does not allow specifying multiple selected values when the element does not have a multiple attribute set to a boolean true', __CLASS__ )); } return $value; } }
Java
UTF-8
2,116
2.21875
2
[]
no_license
package com.example.xiezilailai.headfootrecyclerview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.List; /** * Created by 19459 on 2016/9/21. */ public class MyBaseHeadFootAdapter extends BaseHeadFootAdapter { private Context context; private List<Data>list; public MyBaseHeadFootAdapter(Context context, List<Data> list) { this.context = context; this.list = list; } @Override protected void onBindHeaderView(View headerView) { headerView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context,"head was clicked",Toast.LENGTH_SHORT).show(); } }); } @Override protected void onBindFooterView(View footerView) { // footerView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Toast.makeText(context,"foot was clicked",Toast.LENGTH_SHORT).show(); // } // }); } @Override protected int getItemNum() { return list.size(); } @Override protected void onBindView(RecyclerView.ViewHolder holder, final int position) { MyViewholder viewholder= (MyViewholder) holder; viewholder.bigText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context,"big text "+position+"was clicked",Toast.LENGTH_SHORT).show(); } }); viewholder.bigText.setText(list.get(position).getBigText()); viewholder.smallText.setText(list.get(position).getSmallText()); } @Override public MyViewholder onCreateHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(context).inflate(R.layout.layout_item,null); return new MyViewholder(view); } }
C
UTF-8
3,711
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#include "debug.h" #include "dictionary.h" #include "hex_utils.h" #include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define CHUNK_SIZE_BUFFER_SIZE 10 int readLine(int fd, char *buffer, int maxLen); int read_body(int in, dictionaryType *headers, unsigned char **body_data, int max_size, int *received_size) { char chunk_size_hex[CHUNK_SIZE_BUFFER_SIZE]; int chunk_length = 0; int content_length = 0; int total_read; int read_length; int chunk_length_so_far; int ret; int memory_size = 1024; char *content_length_header; char temp_buff[5]; content_length_header = findDict(headers, "Content-Length"); if (content_length_header) { content_length = atoi(content_length_header); if (content_length > max_size) { debug("This entity body exceeds the max allowed size\n"); return 400; } *body_data = malloc(content_length + 1); if (*body_data == 0) { return 500; } debug("Reading %d bytes from the stream\n", content_length); total_read = 0; while (total_read != content_length) { read_length = read(in, (*body_data) + total_read, content_length - total_read); switch (read_length) { case -1: debug("Read error on socket\n"); return 400; break; case 0: if (total_read != content_length) { debug("Connection closed unexpectedly\n"); free(*body_data); (*body_data) = 0; return 400; } break; default: total_read += read_length; break; } } (*body_data)[content_length] = 0; *received_size = content_length; return 200; } else { total_read = 0; *body_data = calloc(1, memory_size); if (*body_data == 0) { debug("Unable to get memory\n"); return 500; } while (1) { ret = readLine(in, chunk_size_hex, CHUNK_SIZE_BUFFER_SIZE - 1); if (ret == -1) { debug("Line too long!\n"); return 414; } chunk_length = chunkHexToInt(chunk_size_hex); if (chunk_length == 0) { break; } if (chunk_length + total_read + 1 > memory_size) { if (memory_size + chunk_length + 1 > max_size) { debug("The current chunk will exceed the max entity size\n"); return 400; } *body_data = realloc(*body_data, memory_size + chunk_length + 1); if (*body_data == 0) { return 500; } memory_size += chunk_length + 1; } chunk_length_so_far = 0; while (chunk_length_so_far != chunk_length) { read_length = read(in, (*body_data) + total_read, chunk_length - chunk_length_so_far); debug("Read a chunk of size %d\n", read_length); switch (read_length) { case -1: debug("Read error on socket\n"); return 400; break; case 0: if (chunk_length_so_far != chunk_length) { debug("Connection closed unexpectedly\n"); free(*body_data); (*body_data) = 0; return 400; } break; default: total_read += read_length; chunk_length_so_far += read_length; break; } } readLine(in, temp_buff, 2); if ((temp_buff[0] != '\n') && (temp_buff[0] != '\r' || temp_buff[1] != '\n')) { debug("Line not terminated properly\n"); return 400; } } readLine(in, temp_buff, 4); debug("memory_size = %d\n, total_data = %d\n", memory_size, total_read); (*body_data)[total_read] = 0; *received_size = total_read; } return 200; }
Python
UTF-8
276
3.203125
3
[]
no_license
import pdb class simple_class: def __init__(self): self.astr = [] def get_str(self): self.astr = input("type again: ") def print_str(self): print(self.astr) if __name__ == '__main__': blah = simple_class() blah.get_str() blah.print_str() pdb.set_trace()
Java
UTF-8
4,648
3.0625
3
[ "Apache-2.0" ]
permissive
package org.rcl.theor.chord; import java.util.ArrayList; import java.util.regex.Matcher; import org.rcl.theor.TheorException; import org.rcl.theor.interval.Interval; /** * A ChordTemplate is a way of making chords from a template. Template tokens are text ways of representing chords relative * to a tonic. So a token would be "I" or "IVM7". Relative to C, the token I would be C major. The token IVM7 would be F maj 7. * @author moxious * */ public class ChordTemplate { protected static final java.util.regex.Pattern romanNumeralPattern = java.util.regex.Pattern.compile("([iIvV]+)"); protected String token = null; protected Interval [] intervals = null; protected Interval distanceFromTonic = null; protected boolean major; public ChordTemplate(String token, boolean major) throws TheorException { this.token = token; this.major = major; intervals = getChordIntervalsByToken(token); distanceFromTonic = getDistanceFromTonic(); } public Interval[] getIntervals() { return intervals; } public Interval getDistanceFromTonic() throws TheorException { String t = token.trim().toLowerCase(); if(t.contains("vii")) return Interval.SEVENTH; if(t.contains("vi")) return Interval.SIXTH; if(t.contains("iv")) return Interval.FOURTH; if(t.contains("v")) return Interval.FIFTH; if(t.contains("iii")) return Interval.THIRD; if(t.contains("ii")) return Interval.SECOND; if(t.contains("i")) return Interval.UNISON; throw new TheorException("Invalid token '" + token + "'"); } // End getDistanceFromTonic protected String getRomanNumeral(String tok) { Matcher m = romanNumeralPattern.matcher(tok); if(m.find()) return m.group(1); return null; } /** * Given a token and a key (major or minor) return a list of intervals corresponding to that chord. * @param tok a chord progression token, e.g. I, IV, V7, viidim, IVM7, etc. * @param major true if a major chord progression, false if a minor chord progression. * @return a set of intervals. * @throws TheorException */ protected Interval[] getChordIntervalsByToken(String tok) throws TheorException { if(tok == null || "".equals(tok)) { throw new TheorException("Illegal null or blank token"); } boolean diminished = tok.endsWith("dim") || tok.endsWith("o"); boolean majSeventh = tok.contains("M7"); boolean minSeventh = tok.contains("7") && !majSeventh; boolean fifth = tok.contains("5"); boolean augmented = tok.contains("+"); String numeral = getRomanNumeral(tok); if(numeral == null) throw new TheorException("Cannot find roman numeral in token " + tok); boolean major = numeral.toUpperCase().equals(numeral); boolean minor = numeral.toLowerCase().equals(numeral); if(!major && !minor) throw new TheorException("Mixed case illegal chord token '" + tok + "': can't be both minor and major"); if(!diminished && !majSeventh && !minSeventh && !augmented && !major && !minor) throw new TheorException("Illegal interval token '" + tok + "'"); if(fifth && minSeventh) return Interval.POWER_SEVENTH; if(fifth) return Interval.POWER_CHORD; if(augmented && majSeventh && major) return Interval.AUGMENTED_MAJOR_SEVENTH_TETRAD; if(augmented && minSeventh) return Interval.AUGMENTED_SEVENTH_TETRAD; if(major && majSeventh) return Interval.MAJOR_SEVENTH_TETRAD; if(minSeventh && major) return Interval.DOMINANT_SEVENTH_TETRAD; if(minor && minSeventh) return Interval.MINOR_SEVENTH_TETRAD; if(diminished && !minSeventh && !majSeventh) return Interval.DIMINISHED_TRIAD; if(major && !minSeventh && !majSeventh) return Interval.MAJOR_TRIAD; if(minor && !minSeventh && !minSeventh) return Interval.MINOR_TRIAD; if(augmented && major) return Interval.AUGMENTED_TRIAD; throw new TheorException("Unrecognized interval token '" + tok + "'"); } /** * Parse a string containing a series of chord tokens (separated by spaces or dashes) into a series of chord templates. * Example input strings are things like "I - IV - V" (the one four five chord progression). * @param toks * @param major * @return * @throws TheorException */ public static ChordTemplate[] parse(String toks, boolean major) throws TheorException { String [] pieces = toks.split("[\\s-]+"); ArrayList<ChordTemplate> l = new ArrayList<ChordTemplate>(); for(String p : pieces) { if("".equals(p.trim()) || "-".equals(p.trim())) continue; l.add(new ChordTemplate(p, major)); } return l.toArray(new ChordTemplate[]{}); } // End parse }
Java
UTF-8
1,739
3.5625
4
[]
no_license
package ie.gmit.sw; import java.io.*; import java.util.concurrent.BlockingQueue; /** * Each thread reads a separate file line by line, strips out punctuation, divides separate words * takes each word and puts it into a queue of words */ public class FileParser implements Runnable { private File file; private BlockingQueue<Word> q; private int fileCount; public FileParser() {}; public FileParser(File file, BlockingQueue<Word> q) { this.file = file; this.q = q; } public FileParser(BlockingQueue<Word> q, int fileCount) { this.q = q; this.fileCount = fileCount; } public BlockingQueue<Word> getQ() { return q; } @Override public void run() { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); } catch (FileNotFoundException e) { e.printStackTrace(); } String strLine; try { while ((strLine = br.readLine()) != null) { //get rid of punctuation, make all letters lowercase, split by space String[] words = strLine.replaceAll("[^a-zA-Z ]", "").toLowerCase().split(" ");//(?<=\\G.{"+3+"}) for (String s : words) { q.put(new Word(file, s)); }//for }//while //poison tells the queue where the file ends; just need the name of the file q.put(new Poison(file)); //Close the input stream br.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Java
UTF-8
3,668
2.171875
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.thespheres.betula.services.implementation.ui.impl; import java.awt.Color; import java.awt.Font; import javax.swing.DefaultCellEditor; import javax.swing.JTextField; import javax.swing.border.LineBorder; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.table.TableColumnExt; import org.openide.util.NbBundle; import org.thespheres.betula.adminconfig.layerxml.AbstractLayerFile; import org.thespheres.betula.adminconfig.layerxml.LayerFileSystem; import org.thespheres.betula.services.implementation.ui.layerxml.LayerFileAttribute; import org.thespheres.betula.ui.swingx.FontFaceHighlighter; import org.thespheres.betula.ui.swingx.treetable.NbPluggableSwingXTreeTableModel; import org.thespheres.betula.ui.util.PluggableTableColumn; /** * * @author boris.heithecker */ @NbBundle.Messages({"AttrValueColumn.displayName=Attributwert"}) class AttrValueColumn extends PluggableTableColumn<LayerFileSystem, AbstractLayerFile> implements StringValue { static final Highlighter UPDATED = new FontFaceHighlighter(Font.BOLD, (c, ca) -> ca.getValue() instanceof LayerFileAttribute && (((LayerFileAttribute) ca.getValue()).isModified() || ((LayerFileAttribute) ca.getValue()).isTemplate())); private final JTextField editor = new JTextField(); AttrValueColumn() { super("value", 1000, false, 200); editor.setBorder(new LineBorder(Color.black, 2)); } @Override public String getDisplayName() { return NbBundle.getMessage(AttrValueColumn.class, "AttrValueColumn.displayName"); } @Override public boolean isCellEditable(final AbstractLayerFile il) { return il instanceof LayerFileAttribute; } @Override public Object getColumnValue(final AbstractLayerFile il) { if (il instanceof LayerFileAttribute) { return (LayerFileAttribute) il; } return null; } @Override public String getString(Object value) { return value != null ? ((LayerFileAttribute) value).toString() : ""; } @Override public boolean setColumnValue(final AbstractLayerFile il, final Object value) { try { ((LayerFileAttribute) il).setAttribute(value.toString()); } catch (IllegalArgumentException e) { return false; } return true; } @Override public void configureTableColumn(final NbPluggableSwingXTreeTableModel<LayerFileSystem, AbstractLayerFile> model, final TableColumnExt col) { col.setCellRenderer(new DefaultTableRenderer(this)); final class KeyTextEditor extends DefaultCellEditor { KeyTextEditor() { super(editor); editor.removeActionListener(delegate); delegate = new DefaultCellEditor.EditorDelegate() { @Override public void setValue(final Object value) { editor.setText((value != null) ? ((LayerFileAttribute) value).toString() : ""); } @Override public Object getCellEditorValue() { return editor.getText(); } }; editor.addActionListener(delegate); } } col.setCellEditor(new KeyTextEditor()); col.addHighlighter(UPDATED); } }
Java
UTF-8
2,402
2.0625
2
[]
no_license
package com.example.dheoclaveria.projectos; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; /** * Created by Dheo Claveria on 10/1/2017. */ public class Custom_GridView_Subjectname extends BaseAdapter { private Activity activity; private LayoutInflater inflater; private List<GridView_Subjectname_Data> lstdata; Resource res = new Resource(); GridView_Subjectname_Data gsd; ImageView image; TextView title; LinearLayout panel; public static boolean isselectionmode = false; public Custom_GridView_Subjectname(Activity a, List<GridView_Subjectname_Data> e) { this.activity = a; this.lstdata = e; } @Override public int getCount() { return lstdata.size(); } @Override public Object getItem(int pos) { return lstdata.get(pos); } @Override public long getItemId(int pos) { return pos; } @Override public View getView(int pos, View view, ViewGroup vgroup ) { if (inflater == null) inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (view == null) { // if(isselectionmode == true){view = inflater.inflate(R.layout.grid_item_selection, null);} // else{view = inflater.inflate(R.layout.grid_item, null);} view = inflater.inflate(R.layout.grid_item, null); } // // if(isselectionmode == true) // { // image = view.findViewById(R.id.grid_item_selection_image); // title = view.findViewById(R.id.grid_item_selection_title); // panel = view.findViewById(R.id.grid_item_selection_panel); // } // else { image = view.findViewById(R.id.grid_item_image); title = view.findViewById(R.id.grid_item_title); panel = view.findViewById(R.id.grid_item_panel); // } gsd = lstdata.get(pos); image.setImageURI(res.forimagechoice(gsd.getImage())); panel.setBackgroundDrawable(res.forcolorchoice(gsd.getColor())); title.setText(gsd.getTitle()); return view; } }
Markdown
UTF-8
1,297
2.5625
3
[]
no_license
# Отчёт о тестировании приложения "Precision" ## Краткое описание 22.02.2020 было проведено тестирование Precision. На тестирование затрачено: ~ 1 часа. В результате тестирования выявлен следующий дефект - [Итоговое значение в выводе программы - неверное](https://github.com/viktoria-sap/Precision/issues/1) ## Описание теста Проведено функциональное тестирование. В качестве тестовых данных использовались: * Текст [домашнего задания](https://github.com/netology-code/javaqa-homeworks/tree/master/programming) ## Результаты Программа выводит неверную сумму. **Программное окружение** * Устройство: ПК (macOS Catalina версия 10.15.3, x64) * Браузер: Safari версия 13.0.5 (15608.5.11) * IntelliJ IDEA 2019.3.3 (Community Edition) * Java 13.0.1 - была предустановлена на моем компьютере. Не смогла удалить эту версию, чтобы установить 11ю.
Java
UTF-8
1,129
1.960938
2
[]
no_license
package tn.test; //copied from GameMethod import tn.Demand; import tn.TrafficNetwork; public class TrialError { private TrafficNetwork trafficNetwork;//<R>instance of the traffic network class private Demand demand;//<R>link demands on each link /* Public void run(){ for (int i=1; i<=numLinks; i++) { failureProbFile.printf(",link%d", i); routerProbFile.printf(",link%d", i); TFile.printf(",link%d", i); sFile.printf(",link%d", i); } vulnerability.println(); failureProbFile.println(); routerProbFile.println(); TFile.println(); linkflowFile.println(); sFile.println(); }*/ /* private void updateEdgeCosts(){ for(int link : trafficNetwork.getLinks()){ // C_ is the cost of edge e in a normal state double C_ = trafficNetwork.getFreeFlowTravelTime(link); if(rho.get(link)>0){ CF.set(link, beta*C_); //CF.set(link, (1.1*76)*C_);//added alpha*|E|*FFTT } else{ CF.set(link, C_); } } } // Class Trail{ // } public static void main(String[] args) { TrialError networkTest = new TrialError(); networkTest.test(); } */ }
Java
UTF-8
371
3.546875
4
[]
no_license
/** * EX6_1 */ public class EX6_1 { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { System.out.printf("%7d", getPentagonalNumber(i)); if (i % 10 == 0) System.out.println(); } } public static int getPentagonalNumber(int num) { return num * (3 * num - 1) / 2; } }
Java
UTF-8
3,114
2.796875
3
[ "Apache-2.0" ]
permissive
package com.twu.biblioteca; import com.twu.biblioteca.MenuOptions.*; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; class Console { private final ConsolePrinter consolePrinter; private ConsoleReader consoleReader; private ConsoleHelper consoleHelper; private UserValidator userValidator; private final ListItems listBook; private final ListItems listMovie; private final CheckOutItem checkOutBook; private final CheckOutItem checkOutMovie; private final ReturnItem returnBook; private final ReturnItem returnMovie; private GetDetails getDetails; private Login login; private Quit quit; private Map<String, IMenuOption> menuOptionMap; private static final String ERROR_MESSAGE = "Please select a valid option!"; private static final String WELCOME_MESSAGE = "Welcome to Biblioteca. Your one-stop-shop for great book titles in Bangalore!"; Console(ConsolePrinter consolePrinter, ConsoleReader reader, ConsoleHelper consoleHelper, UserValidator userValidator, ListItems listBook, ListItems listMovie, CheckOutItem checkOutBook, CheckOutItem checkOutMovie, ReturnItem returnBook, ReturnItem returnMovie, GetDetails getDetails, Login login, Quit quit) { this.consolePrinter = consolePrinter; this.consoleReader = reader; this.consoleHelper = consoleHelper; this.userValidator = userValidator; this.listBook = listBook; this.listMovie = listMovie; this.checkOutBook = checkOutBook; this.checkOutMovie = checkOutMovie; this.returnBook = returnBook; this.returnMovie = returnMovie; this.getDetails = getDetails; this.login = login; this.quit = quit; setUpOptions(); this.consolePrinter.printLine(WELCOME_MESSAGE); String menu = consoleHelper.getMenu(userValidator.userIsLoggedIn()); this.consolePrinter.print(menu); } private void setUpOptions() { menuOptionMap = new LinkedHashMap<String, IMenuOption>(){ { put("1", listBook); put("2", checkOutBook); put("3", returnBook); put("4", listMovie); put("5", checkOutMovie); put("6", returnMovie); put("L", login); put("D", getDetails); put("Q", quit); } }; } void processUserInput() throws IOException { String userInput = consoleReader.getNextLine(); if(menuOptionMap.containsKey(userInput)){ menuOptionMap.get(userInput).executeOption(); if(!userInput.equals("Q")){ returnToMenu(); } } else { getErrorMessage(); } } private void getErrorMessage() throws IOException { consolePrinter.printLine(ERROR_MESSAGE); returnToMenu(); } private void returnToMenu() throws IOException { consolePrinter.print(consoleHelper.getMenu(userValidator.userIsLoggedIn())); processUserInput(); } }
Markdown
UTF-8
4,459
2.640625
3
[]
no_license
## 简介 > IOS10中已经自带了homekit程序。现在由于支持该框架的硬件设备有限,所以homekit应用还是比较少的。 - HomeKit库是用来沟通和控制家庭自动化配件的,这些家庭自动化配件都支持苹果的HomeKit Accessory Protocol。 - HomeKit应用程序可让用户发现兼容配件并配置它们。用户可以创建一些action来控制智能配件(例如恒温或者光线强弱),对其进行分组,并且可以通过Siri触发。 - HomeKit 对象被存储在用户iOS设备的数据库中,并且通过iCloud还可以同步到其他iOS设备。 - HomeKit支持远程访问智能配件,并支持多个用户设备和多个用户。HomeKit 还对用户的安全和隐私做了处理。 ## 启用HomeKit HomeKit应用服务只提供给通过App Store发布的app应用程序。在你的Xcode工程中, HomeKit应用程序需要额外的配置,你的app必须有开发证书和代码签名才能使用HomeKit。 - 在Xcode中,选择View > Navigators > Show Project Navigator。 - 从Project/Targets弹出菜单中target(或者从Project/Targets的侧边栏) - 点击Capabilities查看你可以添加的应用服务列表。 - 滑到HomeKit 所在的行并打开关。 ## 模拟器 你将可以使用[*HomeKit Accessory Simulator*](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/HomeKitDeveloperGuide/EnablingHomeKit/EnablingHomeKit.html#//apple_ref/doc/uid/TP40015050-CH2-SW3)测试你的HomeKit应用程序 ## HMhome - HomeKit 允许用户创建一个或者多个Home布局。每个Home(HMHome)代表一个有网络设备的住所。 - 用户拥有Home的数据并可通过自己的任何一台iOS设备进行访问。用户也可以和客户共享一个Home,但是客户的权限会有更多限制。 - 被指定为primary home的home默认是Siri指令的对象,并且不能指定home。 - 我们可以通过创建一个HMHomeManager对象去管理home。使用这个HMHomeManager对象的访问home、room、配件、服务以及其他HomeKit对象 ## HMroom - 每个Home一般有多个room,并且每个room一般会有多个智能配件。在home中,每个房间是独立的room,并具有一个有意义的名字,这个名字是唯一的。 - (home的名字也是唯一的)例如“卧室”或者“厨房”,这些名字可以在Siri 命令中使用 ## HMAccessory - 一个accessory代表一个家庭中的自动化设备,例如一个智能插座,一个智能灯具等 ## HMService && HMCharacteristic - 服务(HMService)代表了一个配件(accessory)的某个功能和一些具有可读写的特性(HMCharacteristic)。 - 一个配件可以拥有多项服务,一个服务也可以有很多特性。 - 比如一个车库开门器可能拥有一个照明和开关的服务。照明服务可能拥有打开/关闭和调节亮度的特性。 - 用户不能制造智能家电配件和它们的服务-配件制造商会制造配件和它们的服务-但是用户可以改变服务的特性。 ## 场景自动化 - 需要Apple TV 或者家中的一台iPad开控制 ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2516123-e7152bd4c7c281d5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/400) ## Demo - 下面是的Demo,调试的时候打开模拟器HomeKit Accessory Simulator,需要在一个局域网下,打开蓝牙,先添加Home,然后添加设备。 - 设备的特性就支持了我自己模拟器添加的,所以如果想做别的控制,可以自己去添加适当的特征。 - 添加room和修改Home,room名字的功能没有做,可以用苹果的HomeKit APP "家庭"去修改 - 有问题可以给我留言 - 下面是效果图 ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2516123-12b8c08988f451f4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/400) ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2516123-4372be5542dc41db.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/400) ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2516123-d349d4965a940138.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/400) ![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2516123-871198c79d1539a3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/400) ![模拟器.png](http://upload-images.jianshu.io/upload_images/2516123-514a044d90ac9629.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Java
UTF-8
13,232
2.15625
2
[]
no_license
package org.team3132.rkouchoo.main; import javax.swing.JFrame; import java.awt.List; import javax.swing.JTextField; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import javax.swing.JButton; import javax.swing.JCheckBox; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import java.awt.event.ActionEvent; import javax.swing.JLabel; public class Main { private JFrame frmRobotconfigEditor; private JTextField dataEntryTextBox; private JTextField statusReadoutTextBox; private JButton btnUpdate; private List jKeyList; private JButton btnPushToRobot; private JButton btnConnect; private JButton btnDisconnect; private JLabel lblDataEntry; private JLabel lblLocalStatus; private JLabel lblAuthor; private JCheckBox babyMode; private static JSch javaSSH; private static Session session; private static InputStream blobIn; private static JSONObject json; private Constants.dataType jObjectType; /** * Launch the application. */ public static void main(String[] argss) { Main window = new Main(); window.frmRobotconfigEditor.setVisible(true); } /** * Create the application. */ public Main() { initialiseWindow(); // create the window javaSSH = new JSch(); // create and configure ssh library try { session = javaSSH.getSession(Constants.SSH_USER, Constants.HOST_ADDRESS, Constants.SSH_PORT); session.setPassword(Constants.SSH_PASSWORD); session.setConfig("StrictHostKeyChecking", "no"); } catch (JSchException e) { statusReadoutTextBox.setText("[ERR]: Failed to initiate SSH library"); disableAll(); e.printStackTrace(); // send exception to the console, will be a strange error if this fails } handleButtons(); } /** * Initialise the contents of the window. */ @SuppressWarnings("deprecation") private void initialiseWindow() { frmRobotconfigEditor = new JFrame(); frmRobotconfigEditor.setTitle("RobotConfig Editor"); frmRobotconfigEditor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmRobotconfigEditor.getContentPane().setLayout(null); frmRobotconfigEditor.setResizable(false); statusReadoutTextBox = new JTextField(); dataEntryTextBox = new JTextField(); jKeyList = new List(); btnUpdate = new JButton("Update locally"); btnPushToRobot = new JButton("Push to robot"); btnConnect = new JButton("Connect"); btnDisconnect = new JButton("Disconnect"); lblDataEntry = new JLabel("Data Entry:"); lblLocalStatus = new JLabel("Connection Status: DISCONNECTED"); lblAuthor = new JLabel("Author: @RKouchoo for Team3132. 2018"); babyMode = new JCheckBox("Baby mode (store in: RobotConfig.txt.test)"); babyMode.setSelected(true); // enable baby mode be default just in-case someone unknowingly makes a random change statusReadoutTextBox.setEditable(false); statusReadoutTextBox.setColumns(100); jKeyList.setMultipleSelections(false); dataEntryTextBox.setColumns(10); babyMode.setBounds(397, 210, 400, 15); jKeyList.setBounds(12, 10, 345, 680); dataEntryTextBox.setBounds(401, 50, 300, 76); frmRobotconfigEditor.setBounds(100, 100, 740, 747); btnUpdate.setBounds(401, 133, 132, 25); btnPushToRobot.setBounds(401, 160, 132, 25); btnConnect.setBounds(391, 609, 149, 62); btnDisconnect.setBounds(552, 609, 149, 62); lblDataEntry.setBounds(401, 27, 85, 15); lblLocalStatus.setBounds(391, 513, 400, 15); lblAuthor.setBounds(12, 696, 322, 15); statusReadoutTextBox.setBounds(391, 533, 310, 56); frmRobotconfigEditor.getContentPane().add(babyMode); frmRobotconfigEditor.getContentPane().add(btnUpdate); frmRobotconfigEditor.getContentPane().add(btnConnect); frmRobotconfigEditor.getContentPane().add(dataEntryTextBox); frmRobotconfigEditor.getContentPane().add(btnPushToRobot); frmRobotconfigEditor.getContentPane().add(statusReadoutTextBox); frmRobotconfigEditor.getContentPane().add(btnDisconnect); frmRobotconfigEditor.getContentPane().add(lblDataEntry); frmRobotconfigEditor.getContentPane().add(lblLocalStatus); frmRobotconfigEditor.getContentPane().add(lblAuthor); frmRobotconfigEditor.getContentPane().add(jKeyList); } /** * Handles all of the logic behind connecting and sending the data to the robot. */ private void handleButtons() { btnUpdate.addActionListener(new ActionListener() { @SuppressWarnings("unchecked") public void actionPerformed(ActionEvent e) { boolean keyNotPut = false; // Check if the json file actually contains data and keys are present. if (json == null) { statusReadoutTextBox.setText("[ERR]: Invalid JSON file! Connect & modify file!"); return; } switch (jObjectType) { case BOOLEAN: json.replace(jKeyList.getSelectedItem(), Boolean.valueOf(dataEntryTextBox.getText())); break; case DOUBLE: json.put(jKeyList.getSelectedItem(), Double.valueOf(dataEntryTextBox.getText())); break; case INVALID: statusReadoutTextBox.setText("[ERR]: Invalid datatype! not placing!"); System.err.println("Invalid data type. not placing into json"); keyNotPut = true; // make sure the put key log is not printed out, instead this key should be thrown away. break; case JSONArray: Object object = null; JSONArray arrayObj = null; JSONParser jsonParser = new JSONParser(); try { object = jsonParser.parse(dataEntryTextBox.getText()); } catch (ParseException ex) { ex.printStackTrace(); } arrayObj = (JSONArray) object; json.put(jKeyList.getSelectedItem(), arrayObj); break; case LONG: json.put(jKeyList.getSelectedItem(), Long.valueOf(dataEntryTextBox.getText())); break; case STRING: json.put(jKeyList.getSelectedItem(), dataEntryTextBox.getText()); break; } // Only print out if the key was valid and actually placed into the json if (!keyNotPut) { statusReadoutTextBox.setText(String.format("[WARN]: Put: %s in key: %s", dataEntryTextBox.getText(), jKeyList.getSelectedItem())); } dataEntryTextBox.setText(null); } }); btnConnect.addActionListener(new ActionListener() { @SuppressWarnings("unchecked") public void actionPerformed(ActionEvent e) { try { statusReadoutTextBox.setText("[WARN]: Trying to connect to the robot."); if (!session.isConnected()) { session.connect(); } else { statusReadoutTextBox.setText("[WARN]: Already connected to robot, re-fetching data."); } // Create a local SFTP connection. ChannelSftp sftpConnection = (ChannelSftp) session.openChannel("sftp"); sftpConnection.connect(); // Grab the remote file. blobIn = sftpConnection.get(Constants.SSH_REMOTE_FILE); // BROKEN! sftpConnection.put(blobIn, Constants.SSH_REMOTE_FILE + ".save"); // make a backup of the current file on connection. statusReadoutTextBox.setText(String.format("[WARN]: Got file: %s", Constants.SSH_REMOTE_FILE)); /** * Begin to convert the json blob into a json object. */ BufferedReader br = new BufferedReader(new InputStreamReader(blobIn)); StringBuilder s = new StringBuilder(); String line; // Read in the inputStream to a big json string. while ((line = br.readLine()) != null) { s.append(line); } // cast/convert the string to a json object. String JSONDump = s.toString(); JSONParser parser = new JSONParser(); json = (JSONObject) parser.parse(JSONDump); Set<String> keys = json.keySet(); java.util.Iterator<String> keyIterator = keys.iterator(); java.util.List<String> keysList = new ArrayList<String>(); while (keyIterator.hasNext()) { // take the keys out of the iterator and put it in a list keysList.add(keyIterator.next()); } jKeyList.removeAll(); // remove all of the keys so they are not duplicated on reconnect Collections.sort(keysList); // sort the keyList so it is easier to look for keys. // Add the keys to the jlist for (int i = 0; i < keysList.size(); i++) { jKeyList.add(keysList.get(i)); } br.close(); sftpConnection.disconnect(); lblLocalStatus.setText("Connection Status: CONNECTED"); } catch (Exception ex) { statusReadoutTextBox.setText("[ERR]: Failed to get a conneciton to the robot."); disableAll(); ex.printStackTrace(); // Sent to the console for further deubg } } }); btnDisconnect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boolean wasConnection = false; if (session.isConnected()) { session.disconnect(); wasConnection = true; statusReadoutTextBox.setText("[WARN]: Disconnected from robot."); lblLocalStatus.setText("Connection Status: DISCONNECTED"); } else { statusReadoutTextBox.setText("[WARN]: Not connected to robot, ignoring."); wasConnection = false; } /* * Disable EVERYTHING! if was last connected!!!! */ if (wasConnection) { disableAll(); } } }); btnPushToRobot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Check if a SSH session exists, exit if it doesn't. if (session == null) { statusReadoutTextBox.setText("[ERR]: Not connected to robot!"); return; } // Check if the json has been initialized previously and contains data. if (json == null) { statusReadoutTextBox.setText("[ERR]: No data in JSON file!"); return; } // Parse the json blob to make it pretty in-case of manual editing in vi. Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(json.toJSONString()); String prettyJsonString = gson.toJson(je); // Convert the string to a stream to send over ssh. InputStream jsonStream = new ByteArrayInputStream(prettyJsonString.getBytes(StandardCharsets.UTF_8)); // Only try an SFTP connection if SSH is connected. if (session.isConnected()) { try { ChannelSftp sftpConnection = (ChannelSftp) session.openChannel("sftp"); sftpConnection.connect(); if (babyMode.isSelected()) { sftpConnection.put(jsonStream, Constants.SSH_REMOTE_FILE + ".test"); // TODO: REMOVE baby mode when comfortable } else { sftpConnection.put(jsonStream, Constants.SSH_REMOTE_FILE); } statusReadoutTextBox.setText("[WARN]: Sent file to robot. SUCCESS!."); } catch (Exception ex) { statusReadoutTextBox.setText("[ERR]: Failed to create SFTP connection!."); ex.printStackTrace(); // send to console } } else { statusReadoutTextBox.setText("[ERR]: Disconnected from robot, CANNOT PUSH."); return; } } }); jKeyList.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Check if the json has been initialised previously and contains data. if (json == null) { statusReadoutTextBox.setText("[ERR]: No data in JSON file!"); return; } statusReadoutTextBox.setText(String.format("Selected key: %s", jKeyList.getSelectedItem())); dataEntryTextBox.setText(json.get(jKeyList.getSelectedItem()).toString()); Object testObjectType = json.get(jKeyList.getSelectedItem()); if (testObjectType instanceof Boolean) { jObjectType = Constants.dataType.BOOLEAN; } else if (testObjectType instanceof Long) { jObjectType = Constants.dataType.LONG; } else if (testObjectType instanceof Double) { jObjectType = Constants.dataType.DOUBLE; } else if (testObjectType instanceof JSONArray) { jObjectType = Constants.dataType.JSONArray; } else if (testObjectType instanceof String) { jObjectType = Constants.dataType.STRING; } else { jObjectType = Constants.dataType.INVALID; } return; } }); } /** * Disable every jObject when the application goes into panick mode. */ private void disableAll() { String text = "Restart tool!"; jKeyList.removeAll(); btnConnect.setEnabled(false); btnDisconnect.setEnabled(false); btnPushToRobot.setEnabled(false); btnUpdate.setEnabled(false); jKeyList.setEnabled(false); dataEntryTextBox.setEnabled(false); babyMode.setEnabled(false); lblLocalStatus.setText("Connection Status: " + text); btnUpdate.setText(text); btnPushToRobot.setText(text); btnDisconnect.setText(text); btnConnect.setText(text); jKeyList.add(text); dataEntryTextBox.setText(text); babyMode.setText(text); } }
C
UTF-8
704
3.328125
3
[]
no_license
#define N 3 int main() { int arrayIn[N][N]; for (int i = 0; i < N; i++) {//перебираємо елементи масиву for (int j = 0;j < N; j++) { arrayIn[i][j] = i * N + j; } } for (int i = 0; i < N; i++) {//за допомгою додаткової змінної k перебираємо строки заданої матриці int k = arrayIn[i][0]; for (int j = 0; j < N; j++) {//зміщуємо елементи масиву на 1 вправо arrayIn[i][j] = arrayIn[i][j + 1]; } arrayIn[i][N - 1] = k;//закінчуємо зміщення елементів, ставлячи останній елемент на місце першого } return 0; }
Markdown
UTF-8
578
2.515625
3
[]
no_license
# Mutual Aid Questions Form A very simple form to submit best effort anonymous questions on mutual aid and security. This is deployed automatically via Netlify to [https://mutual-aid-questions.netlify.com/](https://mutual-aid-questions.netlify.com/) ## Development This is raw HTML, but uses [Bulma](https://bulma.io/) for lightweight CSS styling. 1. Clone this repository locally and enter directory in a terminal. 2. `yarn` or `npm install` 3. `yarn start` or `npm start` to bring up a webserver on [http://localhost:8080](http://localhost:8080). Refresh to see changes.
Markdown
UTF-8
1,522
2.953125
3
[]
no_license
# Social-Web A twitter analysis report Nikolas Ioannou Paris Sfikouris Arsh Sadana Omer Osman Extracted from project Report """ ... Explanation of the code Our code for the project is Python object-oriented. We have two classes each of them responsible for distinct uses. In the first class, TwitterClient is responsible for the authentication of the user and for retrieving the client API. This helped with granting access to Twitter data. The second class, TweetAnalyzer, as it is stated by the name, is used for analyzing our tweets. It contains four(4) definitions. 1. Contain_hashtags - determine if a certain hashtag is present in the tweet 2. Filter_tweets - responsible for removing a tweet from data frame if a hashtag is not included 3. Clean_tweet - remove all non-essential characters 4. Tweets_to_dataframes - create a data frame and store information we chose from each tweet. The control flow of the script starts with creating two objects, one of each class mentioned before, triggering constructors that initialized the authentication process using our credentials stored in a different script. We created two arrays, accounts and hashtags which are the accounts that we would mine their tweets and the hashtags we would use to filter the tweets we needed. For each account, we acquired their tweets through the method user_timeline and we performed data cleaning and hashtag filtering before creating a data frame to store it. We then proceeded with concatenating all the data frames and exporting it to a CSV file. ... """
C#
UTF-8
806
3.453125
3
[]
no_license
using System; using System.Collections.Generic; namespace Teamers { public static class Worker { public static List<string> getList(string prefix, int count) { List<string> list = new List<string> { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE" }; List<string> result = new List<string>(); for (int index = 0; index < count; index++) { result.Add($"{prefix} {list[index % list.Count]}"); } return result; } } }
C
UTF-8
3,409
2.578125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* coreio.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sgardner <stephenbgardner@gmail.com> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/27 01:09:10 by sgardner #+# #+# */ /* Updated: 2018/11/10 03:42:26 by sgardner ### ########.fr */ /* */ /* ************************************************************************** */ #include "corewar.h" #include "gui.h" /* ** GUI - Increments all unmaxed age data by 1. */ void age_arena(t_byte *epoch) { size_t i; i = -1; while (++i < MEM_SIZE) { if (epoch[i] < LUM_MAX_STEPS) ++epoch[i]; } } /* ** Reads the argument for given index to a 32-bit signed integer and returns it. ** Register values are read from the register with no processing. ** Direct values are read from the core at the address provided. ** Indirect addresses are 2 bytes read from the core at the address provided, ** and that address is used to read the 4 byte (2 bytes if its an op that ** specifies truncation) return value from the core. */ int32_t read_arg(t_core *core, t_proc *p, int a) { t_instr *instr; t_byte *src; int32_t off; instr = &p->instr; if (instr->atypes[a] & T_R) return (*((int32_t *)instr->args[a])); if (instr->atypes[a] & T_I) { off = read_core(core, instr->args[a], IND_SIZE, FALSE); src = IDX_POS(core->arena, p->pc, off); return (read_core(core, src, DIR_SIZE, instr->op->trunc)); } return (read_core(core, instr->args[a], DIR_SIZE, instr->op->trunc)); } /* ** Reads data from the core. The core is in big endian, so the bytes must be ** read backwards. At this time, it is assumed that this code will be compiled ** on a little endian machine. ** If truncation is specified, the data is shifted into a 2 byte value. ** The return data is casted to a signed type of the appropriate size to ensure ** that the sign is preserved in the 4 byte register. */ int32_t read_core(t_core *core, t_byte *src, int n, t_bool trunc) { t_byte *dst; uint32_t res; int i; res = 0; dst = (t_byte *)&res; i = -1; while (++i < n) dst[(n - 1) - i] = *ABS_POS(core->arena, src, i); if (trunc) res >>= ((DIR_SIZE - IND_SIZE) << 3); if (n == IND_SIZE || trunc) res = (int16_t)res; return ((int32_t)res); } /* ** Writes data from instruction argument of given index (a) to the core. ** The data is assumed to be in little endian, and written to the core in ** reverse. ** If the GUI is enabled, the byte ownership is also set, and its age reset. */ void write_core(t_core *core, t_byte *dst, t_proc *p, int a) { t_instr *instr; t_uint off; int n; int i; instr = &p->instr; n = (instr->atypes[a] & T_I) ? IND_SIZE : REG_SIZE; i = -1; while (++i < n) { off = ABS_POS(core->arena, dst, ((n - 1) - i)) - core->arena; core->arena[off] = instr->args[a][i]; if (core->gui) { core->owner[off] = (p->champ - core->champions) + 1; core->epoch[off] = 0; } } }
Java
UTF-8
2,343
2.828125
3
[]
no_license
package com.jb.cs.model; import java.time.LocalDate; public class Coupon { //Fileds //Default argument for filed public static final int NO_ID = -1; private long id = NO_ID; private String title; private LocalDate startDate; private LocalDate endDate; private int amount; private int category; private String message; private double price; private String imageURL; //Empty constructor public Coupon() { } //Constructor initializing fildes public Coupon( long id,String title, LocalDate startDate, LocalDate endDate, int amount, int category, String message, double price, String imageURL) { this.id =id; this.title = title; this.startDate = startDate; this.endDate = endDate; this.amount = amount; this.category = category; this.message = message; this.price = price; this.imageURL = imageURL; } //Getters public long getId() { return id; } public String getTitle() { return title; } public LocalDate getStartDate() { return startDate; } public LocalDate getEndDate() { return endDate; } public int getAmount() { return amount; } public int getCategory() { return category; } public String getMessage() { return message; } public double getPrice() { return price; } public String getImageURL() { return imageURL; } //Setters public void setId(long id) { this.id = id; } public void setTitle(String title) { this.title = title; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public void setAmount(int amount) { this.amount = amount; } public void setCategory(int category) { this.category = category; } public void setMessage(String message) { this.message = message; } public void setPrice(double price) { this.price = price; } public void setImageURL(String imageURL) { this.imageURL = imageURL; } @Override public String toString() { return "this is the selected coupon id: " + id + " title: " + title + " start day: " + startDate + " end date: " + endDate + " amount: " + amount + " category: " + category + " messge: " + message + " price: " + price + " image url: " + imageURL; } }
C#
UTF-8
7,223
2.765625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Quantum_Gate.Game_Objects { class RoomBuilder //TODO: This is set to no build action, delete once Quantum Gate 1 initializer is working { private List<String> imageList = new List<string>(); private List<String> movieList = new List<string>(); private List<RoomExit> exitList = new List<RoomExit>(); public Room buildRoom(String roomName) { if(roomName == "drewQtrs") //Drew's quarters { imageList.Add("n3c"); //north (door) imageList.Add("n3b"); //east (militerm) imageList.Add("n3a"); //south (desk) imageList.Add("n3d"); //west (bed) movieList.Add("N3C_3B"); //north to east movieList.Add("N3B_3A"); //east to south movieList.Add("N3A_3D"); //south to west movieList.Add("N3D_3C"); //west to north movieList.Add("N3C_3D"); //north to east movieList.Add("N3D_3A"); //west to south movieList.Add("N3A_3B"); //south to west movieList.Add("N3B_3C"); //west to north var basePath = (@".\content\drewqtrs\"); var northExit = new RoomExit("north", "enlistedQtrs", "N3C_2C", basePath, "north", false); exitList.Add(northExit); var drewQtrs = new Room(imageList, movieList, exitList, basePath, "Drew's Quarters"); return drewQtrs; } if (roomName == "enlistedQtrs") //Enlisted Men's quarters { imageList.Add("n2c"); //north imageList.Add("n2b"); //east imageList.Add("n2a"); //south imageList.Add("n2d"); //west movieList.Add("N2C_2B"); //north to east movieList.Add("N2B_2A"); //east to south movieList.Add("N2A_2D"); //south to west movieList.Add("N2D_2C"); //west to north movieList.Add("N2C_2D"); //north to west movieList.Add("N2D_2A"); //west to south movieList.Add("N2A_2B"); //south to east movieList.Add("N2B_2C"); //east to north var basePath = (@".\content\drewqtrs\"); var exit1 = new RoomExit("east", "drewQtrs", "N2B_3A", basePath, "south", false); var exit2 = new RoomExit("north", "deck2area1", "N2C_1", basePath, "north", false); exitList.Add(exit1); exitList.Add(exit2); var enlistedQtrs = new Room(imageList, movieList, exitList, basePath, "Corporate Quarters"); return enlistedQtrs; } if (roomName.Substring(0,9) == "deck2area") //Deck 2 corridor { imageList.Add("NSI1"); //north imageList.Add("NHW1"); //east imageList.Add("NSO1"); //south imageList.Add("NHE1"); //west movieList.Add("NSIHW"); //north to east movieList.Add("NHWSO"); //east to south movieList.Add("NSOHE"); //south to west movieList.Add("NHESI"); //west to north movieList.Add("NSIHE"); //north to west movieList.Add("NHESO"); //west to south movieList.Add("NSOHW"); //south to east movieList.Add("NHWSI"); //east to north var basePath = (@".\content\main\"); int areaNumber = Convert.ToInt16(roomName.Substring(9, 1)); if (areaNumber == 1) { var exit1 = new RoomExit("south", "enlistedQtrs", "corpqrtrs", basePath, "south", false); var exit2 = new RoomExit("east", "deck2area5", "NHW", basePath, "east", false ); var exit3 = new RoomExit("west", "deck2area2", "NHE", basePath, "west", false); var exit4 = new RoomExit("north", "lift1deck2", "deck2lift1", basePath, "north", true); exitList.Add(exit1); exitList.Add(exit2); exitList.Add(exit3); exitList.Add(exit4); var corridor = new Room(imageList, movieList, exitList, basePath, "Corridor - Corporate Quarters"); return corridor; } else if(areaNumber == 2) { //RoomExit exit1 = new RoomExit("south", "enlistedQtrs", "corpqrtrs", basePath, "south"); var exit2 = new RoomExit("west", "deck2area3", "NHE", basePath, "west", false); var exit3 = new RoomExit("east", "deck2area1", "NHW", basePath, "east", false); //exitList.Add(exit1); exitList.Add(exit2); exitList.Add(exit3); var corridor = new Room(imageList, movieList, exitList, basePath, "Corridor - Sick Bay"); return corridor; } else if (areaNumber == 3) { //RoomExit exit1 = new RoomExit("south", "enlistedQtrs", "corpqrtrs", basePath, "south"); var exit2 = new RoomExit("west", "deck2area4", "NHE", basePath, "west", false); var exit3 = new RoomExit("east", "deck2area2", "NHW", basePath, "east", false); //exitList.Add(exit1); exitList.Add(exit2); exitList.Add(exit3); var corridor = new Room(imageList, movieList, exitList, basePath, "Corridor - Lounge"); return corridor; } else if (areaNumber == 4) { // RoomExit exit1 = new RoomExit("south", "enlistedQtrs", "corpqrtrs", basePath, "south"); var exit2 = new RoomExit("west", "deck2area5", "NHE", basePath, "west", false); var exit3 = new RoomExit("east", "deck2area3", "NHW", basePath, "east", false); //exitList.Add(exit1); exitList.Add(exit2); exitList.Add(exit3); var corridor = new Room(imageList, movieList, exitList, basePath, "Corridor - Kitchen/Mess"); return corridor; } else if (areaNumber == 5) { //RoomExit exit1 = new RoomExit("south", "enlistedQtrs", "corpqrtrs", basePath, "south"); var exit2 = new RoomExit("west", "deck2area1", "NHE", basePath, "west", false); var exit3 = new RoomExit("east", "deck2area4", "NHW", basePath, "east", false); //exitList.Add(exit1); exitList.Add(exit3); exitList.Add(exit2); var corridor = new Room(imageList, movieList, exitList, basePath, "Corridor - Science"); return corridor; } } return null; } } }
Java
UTF-8
2,011
2.265625
2
[]
no_license
package project.modules.Airplane.View.ActionListener; import project.modules.Application.Entity.ConfigurationEntity; import project.modules.Application.View.ActionListener.AbstractActionListener; import project.modules.Airplane.View.AirplaneRegisterRasterizeView; import java.awt.event.ActionEvent; import java.awt.Component; import java.util.Iterator; import javax.swing.JTextField; import javax.swing.JOptionPane; public class AirplaneRegisterRasterizeActionListener extends AbstractActionListener { public AirplaneRegisterRasterizeActionListener(ConfigurationEntity configuration) { configuration.setActionListener(this); setConfiguration(configuration); } public void actionPerformed(ActionEvent e) { String errorFields = ""; Integer errorCount = 0; Iterator<String> keySetIterator = getComponents().keySet().iterator(); while (keySetIterator.hasNext()) { String field = keySetIterator.next(); JTextField textField = (JTextField) getComponent(field); if (textField.getText().equals("")) { if (errorFields.equals("")) { errorFields += field; } else { errorFields += ", " + field; } errorCount++; } } if (errorCount > 0) { String errorMessage = errorCount > 1 ? "Preencha os campos" : "Preencha o campo"; JOptionPane.showMessageDialog( null, configuration.getTranslator().__(errorMessage) + ": [" + errorFields +"]", configuration.getTranslator().__("Campo Obrigatório"), JOptionPane.ERROR_MESSAGE ); } else { configuration.getView().dispose(); configuration.setParameter("airplane-register-form-data", getComponents()); new AirplaneRegisterRasterizeView(configuration); } } }
Markdown
UTF-8
669
3.671875
4
[]
no_license
# Randomly Group people The implemented code takes in the names of people to group in comma seperated format and also number of people per group and then group them randomly based on the entered parameters Example Code: Please enter the names you want to group together in comma seperated format Titi,Ade,Dara,Lola,Bola,Nina,Dobrev,Klaus,Nick,Elijah Please enter number of people per group 2 The groups are : Group 1 - Dara,Bola Group 2 - Dobrev,Ade Group 3 - Klaus,Lola Group 4 - Elijah,Nina Group 5 - Nick,Titi Process finished with exit code 0
C#
UTF-8
8,551
2.890625
3
[ "BSD-2-Clause" ]
permissive
#region Copyright /*Copyright (c) 2015, Katascope All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ #endregion using System; using System.Collections.Generic; namespace GlyphicsLibrary.Painters { //Taken from gist on github //https://gist.github.com/anonymous/828805 [Flags] enum Directions { N = 1, S = 2, E = 4, W = 8 } class MazeGrid { public const int WidthDimension = 0; public const int HeightDimension = 1; private static Random _rng; public int MinSize { get; private set; } public int MaxSize { get; private set; } public int[,] Cells { get; private set; } public MazeGrid(byte seed, int width, int height) { _rng = seed > 0 ? new Random(seed) : new Random(); MinSize = 0; MaxSize = height > width ? height : width; Cells = Initialise(width, height); Cells = Generate(); } private int[,] Initialise(int width, int height) { if (height < MinSize) height = MinSize; if (width < MinSize) width = MinSize; if (height > MaxSize) height = MaxSize; if (width > MaxSize) width = MaxSize; var cells = new int[width, height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { cells[x, y] = 0; } } return cells; } private readonly Dictionary<Directions, int> _directionX = new Dictionary<Directions, int> { {Directions.N, 0}, {Directions.S, 0}, {Directions.E, 1}, {Directions.W, -1} }; private readonly Dictionary<Directions, int> _directionY = new Dictionary<Directions, int> { {Directions.N, -1}, {Directions.S, 1}, {Directions.E, 0}, {Directions.W, 0} }; private readonly Dictionary<Directions, Directions> _opposite = new Dictionary<Directions, Directions> { {Directions.N, Directions.S}, {Directions.S, Directions.N}, {Directions.E, Directions.W}, {Directions.W, Directions.E} }; private int[,] Generate() { var cells = Cells; CarvePassagesFrom(0, 0, ref cells); return cells; } //Fisher-Yates shuffle public static void Shuffle<T>(ref List<T> list) { int n = list.Count; while (n > 1) { n--; int k = _rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } private static void Randomize(ref List<Directions> directions) { //Shuffle as many times as there are entries for (int i = 0; i < directions.Count; i++) { Shuffle(ref directions); } } private void CarvePassagesFrom(int currentX, int currentY, ref int[,] grid) { var directions = new List<Directions> { Directions.E, Directions.N, Directions.W, Directions.S }; Randomize(ref directions); foreach (Directions direction in directions) { var nextX = currentX + _directionX[direction]; var nextY = currentY + _directionY[direction]; if (IsOutOfBounds(nextX, nextY, grid)) continue; if (grid[nextX, nextY] != 0) // has been visited continue; grid[currentX, currentY] |= (int) direction; grid[nextX, nextY] |= (int) _opposite[direction]; CarvePassagesFrom(nextX, nextY, ref grid); } } private static bool IsOutOfBounds(int x, int y, int[,] grid) { if (x < 0 || x > grid.GetLength(WidthDimension) - 1) return true; if (y < 0 || y > grid.GetLength(HeightDimension) - 1) return true; return false; } public static string ToString(int[,] cells) { var columns = cells.GetLength(WidthDimension); var rows = cells.GetLength(HeightDimension); string str = ""; for (int y = 0; y < rows; y++) { str += " |"; for (int x = 0; x < columns; x++) { var directions = (Directions)cells[x, y]; var s = directions.HasFlag(Directions.S) ? " " : "_"; str += s; s = directions.HasFlag(Directions.E) ? " " : "|"; str += s; } str += "\n"; } return str; } public static string RemapCells(string cellStr) { string returnStr = ""; string[] strs = cellStr.Split('\n'); for (int i=0;i<strs.Length-1;i++) { string str = strs[i]; string nextStr = ""; for (int c =1;c<str.Length;c++) { if (str[c] == '_') { returnStr += " "; nextStr += '#'; } else { const char ch = '#'; if (str[c] == '|') returnStr += ch; else returnStr += str[c]; if (str[c] != ' ') nextStr += ch; else nextStr += ' '; } } if (i != 0) // skip first returnStr += "\n" + nextStr; returnStr += "\n"; } return returnStr; } } internal partial class CPainter { public void DrawMaze(IGridContext bgc, byte seed, int x1, int y, int z1, int x2, int z2) { if (bgc == null || bgc.Grid == null) return; IGrid grid = bgc.Grid; MinMax(ref x1, ref x2); MinMax(ref z1, ref z2); int width = x2 - x1; int depth = z2 - z1; //Scale down by two, to pickup walls var mg = new MazeGrid(seed, width/2, depth/2); string cells = MazeGrid.ToString(mg.Cells); string remappedCells = MazeGrid.RemapCells(cells); string[] remappedStrings = remappedCells.Split('\n'); int cursorZ = 0; ulong rgba = bgc.Pen.Rgba; foreach (string str in remappedStrings) { for (int i=0;i<str.Length;i++) { if (str[i] != ' ') grid.Plot(x1 + i, y, z1 + cursorZ, rgba); } cursorZ++; } } } }
Python
UTF-8
1,678
3.25
3
[]
no_license
''' 中国票房网数据: url = http://www.cbooo.cn/ ''' import pandas as pd import requests from bs4 import BeautifulSoup url = 'http://www.cbooo.cn/year?year=2018' datas = requests.get(url).text # print(datas) soup = BeautifulSoup(datas,'lxml') movies_table = soup.find_all('table',{'id':'tbContent'})[0] # print(movies_table) movies = movies_table.find_all('tr') # 获取电影名称 names = [tr.find_all('td')[0].a.get('title') for tr in movies[1:]] # print(names) # 获取电影url地址 hrefs = [tr.find_all('td')[0].a.get('href') for tr in movies[1:]] # print(hrefs) # 电影类型 types = [tr.find_all('td')[1].string for tr in movies[1:]] # print(types) # 总票房数据 boxoffice = [int(tr.find_all('td')[2].string) for tr in movies[1:]] # print(boxoffice) # 平均票价 mean_price = [int(tr.find_all('td')[3].string) for tr in movies[1:]] # print(mean_price) # 场均人次 mean_people = [int(tr.find_all('td')[4].string) for tr in movies[1:]] # 国家和地区 countries = [tr.find_all('td')[5].string for tr in movies[1:]] # 获取上映时间 times = [tr.find_all('td')[6].string for tr in movies[1:]] # 导演 def getInfo(url): datas = requests.get(url) soup = BeautifulSoup(datas.text,'lxml') daoyan = soup.select('dl.dltext dd')[0].get_text() return daoyan directors = [getInfo(url).strip('\n') for url in hrefs] # print(directors) df = pd.DataFrame({ 'name':names, 'href':hrefs, 'type':types, 'boxoffice':boxoffice, 'mean_price':mean_price, 'mean_people(万)':mean_people, 'countries':countries, 'time':times, 'director':directors }) # print(df) # print(df.head()) df.to_csv('movie.csv')
Shell
UTF-8
1,072
3.953125
4
[]
no_license
#!/bin/bash main_menu() { echo -e "Main menu\n" echo -e "1. Browse ERRORS" echo -e "2. Browse WARNINGS" echo -e "3. EXIT" } handle_main_menu() { case $choice in [1]) attention="ERROR" ;; [2]) attention="WARNING" ;; *) exit 0 ;; esac } handle_type() { IFS=$'\n' read -d '' -r -a LIST < workingdir/type/$choice echo $choice i=0 size=${#LIST[@]} echo "$size" less workingdir/reports/${LIST[0]} while [ 1 -eq 1 ]; do read dir if [ "$dir" = "n" ]; then (( i++ )) if [ $i -eq $size ]; then (( i-- )); fi elif [ "$dir" = "p" ]; then (( i-- )) if [ $i -eq -1 ]; then (( i++ )); fi elif [ "$dir" = "q" ]; then break fi v=${LIST[$i]} less workingdir/reports/$v done } while [ 1 -eq 1 ]; do main_menu read choice handle_main_menu cat workingdir/attention/${attention}_type read choice handle_type done
Java
UTF-8
1,647
2.5
2
[]
no_license
/** * */ package com.esb.network.client; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; /** * @author GongYining */ public class EsbNettyClient { private final String ip; private final String port; private final EventLoopGroup workerGroup; private final Bootstrap b; private ChannelFuture f; public EsbNettyClient(String ip, String port) { this.ip = ip; this.port = port; workerGroup = new NioEventLoopGroup(); b = new Bootstrap(); } public Bootstrap createBootStrap() throws InterruptedException { return createBootStrap(null,null); } public Bootstrap createBootStrap(Bootstrap bootstrap,EventLoopGroup loop) throws InterruptedException { if (bootstrap == null || loop == null) { bootstrap = b; loop = workerGroup; } bootstrap.group(loop); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.handler(new EsbClientChildChannelHandler(this)); bootstrap.remoteAddress(ip, Integer.valueOf(port)); f = bootstrap.connect(); f.addListener(new EsbNettyClientListener(this)); return bootstrap; } public void doClose() { try { f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } } }
PHP
UTF-8
426
3.09375
3
[]
no_license
<?php namespace Casts; class Datetime implements Cast { public static function cast($value, $args=[]) { if (!isset($value)) return $value; $args['format'] = array_key_exists('format', $args) ? $args['format'] : "Y-m-d H:i:s"; $value = str_replace("/", "-", $value); $value = date_create(date('Y-m-d', strtotime($value))); if ($value === false) return null; return date_format($value, $args['format']); } } ?>
Java
UTF-8
4,297
2
2
[]
no_license
package com.buffalocart.pages; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.buffalocart.utilities.PageUtility; import com.buffalocart.utilities.TableUtility; import com.buffalocart.utilities.WaitUtility; import com.buffalocart.utilities.WaitUtility.LocatorType; public class SalesCommisionAgentPage { WebDriver driver; /*** PageConstructor ***/ public SalesCommisionAgentPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } /*** WebElements ***/ private final String _addbutton = "//button[@class='btn btn-primary btn-modal pull-right']"; @FindBy(xpath = _addbutton) private WebElement addbutton; private final String _relement = "//table[@id='users_table']//tbody//tr"; @FindBy(xpath = _relement) private List<WebElement> rElement; private final String _celement = "//table[@id='users_table']//tbody//tr//td"; @FindBy(xpath = _celement) private List<WebElement> cElement; private final String _rElement = "//table[@id='sales_commission_agent_table']//tbody//tr"; @FindBy(xpath = _rElement) private List<WebElement> salesrElement; private final String _cElement = "//table[@id='sales_commission_agent_table']//tbody//tr//td"; @FindBy(xpath = _cElement) private List<WebElement> salescElement; private final String _salesagenttable = "//table[@id='sales_commission_agent_table']"; @FindBy(xpath = _salesagenttable) private WebElement salesagenttable; private final String _salesagentEdibutton = "//table[@id='sales_commission_agent_table']//tbody//tr//td[6]//button[1]"; @FindBy(xpath = _salesagentEdibutton) private WebElement salesagentEdibutton; private final String _salesagentdeletebutton = "//table[@id='sales_commission_agent_table']//tbody//tr//td[6]//button[2]"; @FindBy(xpath = _salesagentdeletebutton) private WebElement salesagentdeletebutton; /*** UserActionMethods ***/ public UpdateSalesCommisionAgentPage ClickonEditButton(String user) { List<ArrayList<WebElement>> grid=TableUtility.actionData(salesrElement, salescElement); System.out.println(grid); OUTER: for(int i=0;i<grid.size();i++) { for(int j=0;j<grid.get(0).size();j++) { String data=grid.get(i).get(j).getText(); if(data.equals(user)) { WebElement editbutton=driver.findElement(By.xpath("//table[@id='sales_commission_agent_table']//tbody//tr["+(i+1)+"]//td[6]//button[1]")); PageUtility.clickOnElement(editbutton); break OUTER; } } } return new UpdateSalesCommisionAgentPage(driver); } public DeleteSalesCommisionAgentPage ClickonDeleteButton(String user) { List<ArrayList<WebElement>> grid=TableUtility.actionData(salesrElement, salescElement); System.out.println(grid); OUTER: for(int i=0;i<grid.size();i++) { for(int j=0;j<grid.get(0).size();j++) { String data=grid.get(i).get(j).getText(); if(data.equals(user)) { WebElement deletebutton=driver.findElement(By.xpath("//table[@id='sales_commission_agent_table']//tbody//tr["+(i+1)+"]//td[6]//button[2]")); PageUtility.clickOnElement(deletebutton); break OUTER; } } } return new DeleteSalesCommisionAgentPage(driver); } public String getSalesCommisionAgentPageTitle() { return PageUtility.getPageTitle(driver); } public AddSalesCommisionAgentPage clickOnAddButton() { PageUtility.clickOnElement(addbutton); return new AddSalesCommisionAgentPage(driver); } public List<ArrayList<String>> getTableData() throws InterruptedException { PageUtility.hardWait(); return TableUtility.gridData(salesrElement, salescElement); } public void getHardWait() throws InterruptedException { PageUtility.hardWait(); } public void getSoftWaitsalesagenttable() { WaitUtility.waitForelementVisibility(driver,salesagenttable,LocatorType.Xpath); } public void getSoftWaitEditsalesagent() { WaitUtility.waitForelementVisibility(driver,salesagentEdibutton,LocatorType.Xpath); } public void getSoftWaitDeletesalesagent() { WaitUtility.waitForelementTobeClickable(driver,salesagentdeletebutton,LocatorType.Xpath); } }
TypeScript
UTF-8
618
2.890625
3
[]
no_license
module TextRight { enum NodeType { Heading, Style, Quote, Text, UnorderedList, OrderedList, Html, } /** * Represents a chunk of the document that has been parsed into a single block */ class Node { public type: NodeType; constructor(type: NodeType) { this.type = type; } } export interface IContentNode { content: string; } export class InlineParser { constructor(private options: Options = new Options()) { } public parse(block: LineFragment[]): IContentNode { return null; } } }
TypeScript
UTF-8
707
2.609375
3
[]
no_license
import { RequiredFieldValidation } from './required-field-validation' import { MissingParamError } from '../../presentation/errors' const makeSut = (): RequiredFieldValidation => { return new RequiredFieldValidation('field') } describe('RequiredField Validation', () => { test('Should return a MissinParamError if validation fails', () => { const sut = makeSut() const validationError = sut.validate({ name: 'any_name' }) expect(validationError).toEqual(new MissingParamError('field')) }) test('Should not return if validation succeeds', () => { const sut = makeSut() const validationError = sut.validate({ field: 'any_field' }) expect(validationError).toBeFalsy() }) })
Markdown
UTF-8
3,589
3.28125
3
[ "MIT" ]
permissive
# @cdxoo/mongodb-restore Simple module to restore MongoDB dumps from BSON files. ## Installation npm install --save @cdxoo/mongodb-restore ## Usage ```javascript const restore = require('@cdxoo/mongodb-restore'), uri = 'mongodb://127.0.0.1:27001/'; // restore multi-database dump await restore.dump({ uri, from: '../dumps/mydump/' }); // restore single database await restore.database({ uri, database: 'my-database-name', from: '../dumps/mydump/db-1/' }); // restore single collection await restore.collection({ uri, database: 'my-database-name', collection: 'foo', from: '../dumps/mydump/db-1/foo.bson' }); // restore from a buffer containing bson var myBuffer = fs.readFileSync('./foo.bson') await restore.buffer({ uri, database: 'my-database-name', collection: 'foo', from: myBuffer }); ``` ## Parameters ```javascript await restore.dump({ con: await MongoClient.connect(uri), // An existing mongodb connection to use. // Either this or "uri" must be provided uri: 'mongodb://127.0.0.1:27001/', // URI to the Server to use. // Either this or "con" must be provided. from: '../dumps/my-dump', // path to the server dump, contains sub-directories // that themselves contain individual database // dumps clean: true, // wether the collections should be cleaned before // inserting the documents from the dump files // optional; default = true onCollectionExists: 'throw', // how to handle collections that already exist // on the server; when set to "throw" (default) // the restore will throw an error; // when set to "overwrite" the restore will proceed // and insert the dump data to the collection // (and remove existing items when clean == true) // optional, default: 'throw' // available options: // 'throw' // 'overwrite' }); await retore.database({ con, uri, clean, onCollectionExists, // same as in dump() database: 'my-database-name', // name of the database that will be created // on the mongodb server from the dump from: '../dumps/mydump/db-1/', // path to the database dump directory // should contain one or more bson files // to restore }); await restore.collection({ con, uri, clean, onCollectionExists, database, // above are the same as in database() collection: 'my-collection-name', // name of the collection that the documents // will be restored into from: '../dumps/mydump/db-1/foo.bson', // bson file containing the documents // to be restored limit: 100, // optionally you can choose to not // restore all the documents but just // the first e.g. 100 // optional; default = no limit }); await restore.buffer({ con, uri, clean, onCollectionExists, database, collection, limit // above are the same as in collection() from: myBuffer, // a buffer with bson documents that was // created somehere in advance // e.g. by fs.readFileSync() }); ```
JavaScript
UTF-8
946
3.734375
4
[]
no_license
/** * 给定一个长度为 n+1 的数组nums,数组中所有的数均在 1∼n 的范围内,其中 n≥1。 请找出数组中任意一个重复的数,但不能修改输入的数组。 样例 给定 nums = [2, 3, 5, 4, 3, 2, 6, 7]。 返回 2 或 3。 思考题:如果只能使用 O(1) 的额外空间,该怎么做呢? * */ /** * @param {number[]} nums * @return {number} */ var duplicateInArray = function(nums) { let n = nums.length; let l = 1, r = nums.length-1; // 区间的取值范围 [1,n] while(l < r){ let mid = l + r >> 1; // [1,mid][mid+1,r] let s = 0; for(let i = 0; i < n; i++){ if(nums[i] >= l && nums[i] <= mid){ s++; } } if(s > mid - l + 1){ r = mid; // 在左边值的范围 } else { l = mid + 1; // 在右边值的范围 } } return r; };
C++
UTF-8
865
2.625
3
[]
no_license
#ifndef _TPOINT_H #define _TPOINT_H #include "tnumeric.h" TGEOMETRY_BEGIN class TVector2d; class TPoint { public: TPoint(); ~TPoint(); TPoint(const TPoint& point); TPoint(treal x, treal y); TPoint(const TVector2d& v); TPoint& operator=(const TPoint& pt); bool isNull(); treal& rx(); treal& ry(); void setX(treal x); void setY(treal y); treal x() const; treal y() const; TPoint& operator*=(treal factor); TPoint& operator+=(const TPoint& point); TPoint& operator-=(const TPoint& point); TPoint& operator/=(treal divisor); TPoint operator*(treal factor) const; TPoint operator+(const TPoint& pt) const; TPoint operator-(const TPoint& pt) const; TPoint operator/(treal factor) const; void move(const TVector2d& v); private: treal m_x; treal m_y; }; TGEOMETRY_END #endif// _TPOINT_H
C#
UTF-8
562
2.859375
3
[]
no_license
private void Loopy(int times) { if (this.InvokeRequired) { this.Invoke((MethodInvoker)delegate { Loopy(times); }); } else { count = times; timer = new Timer(); timer.Interval = 1000; timer.Tick += new EventHandler(timer_Tick); timer.Start(); } }
JavaScript
UTF-8
522
3.140625
3
[]
no_license
function allCaps() { var x = document.getElementById("form1"); var input = x.elements["name"].value.split(''); var output = []; for (var i = 0; i < input.length; i++) { var letter = input[i].toLowerCase(); if (!(letter === 'y' || letter === 'i' || letter === 'o' || letter === 'e' || letter === 'u' || letter === 'a' )) { output.push(letter); } } var stringedOutput = output.join(''); document.getElementById("demo").innerHTML=stringedOutput; }
Markdown
UTF-8
1,209
2.5625
3
[ "MIT" ]
permissive
--- topic: "MongoDB" desc: "A particular NoSQL database platform" category_prefix : "MongoDB: " --- * [MongoDB Javadoc](http://mongodb.github.io/mongo-java-driver/3.6/javadoc/) MongoDB is a particular implementation of a technology known as NoSQL databases. The basic idea is that you can store JSON objects in the cloud. Everything else is just sort of a riff on that theme. This article is a stub, a placeholder for more information about MongoDB that may be of interest to CS56 students. If you have suggestions for links, articles, information, demos etc. that should appear here, either post to Piazza, or better yet, fork this repo, add them, and do a pull request. There is already a LOT of info about MongoDB at this other website: <http://pconrad-webapps.github.io/topics/mongodb/> * In particular, this page about Java stuff: <http://pconrad-webapps.github.io/topics/mongodb_java/> * It also discusses how to get started with [MLab](http://pconrad-webapps.github.io/topics/mongodb_mlab/) which is a particular provider of MongoDB (e.g. Mlab is to MongoDB like github is to git) # Javadoc * <http://mongodb.github.io/mongo-java-driver/3.7/javadoc/com/mongodb/client/MongoCollection.html>
Markdown
UTF-8
8,891
2.765625
3
[ "MIT" ]
permissive
# Cirgonus Cirgonus is a go-related pun on [Circonus](http://circonus.com) and is a metrics collector for it (and anything else that can deal with json output). It also comes with `cstat`, a platform-independent `iostat` alike for gathering cirgonus metrics from many hosts. Most of the built-in collectors are linux-only for now, and probably the future unless pull requests happen. Many plugins very likely require a 3.0 or later kernel release due to dependence on system structs and other deep voodoo. Cirgonus does not need to be run as root to collect its metrics. Unlike other collectors that use fat tools like `netstat` and `df` which can take expensive resources on loaded systems, Cirgonus opts to use the C interfaces directly when it can. This allows it to keep a very small footprint; with the go runtime, it clocks in just above 5M resident and unnoticeable CPU usage at the time of writing. The agent can sustain over 8000qps with a benchmarking tool like `wrk`, so it will be plenty fine getting hit once per minute, or even once per second. ## Building Cirgonus Cirgonus due to its C dependencies must be built on a Linux box. I strongly recommend [godeb](http://blog.labix.org/2013/06/15/in-flight-deb-packages-of-go) for linux users. `cstat`, however, has no such requirement, so use it on OS X or windows if you choose. To build, type: `make cirgonus`. To build `cstat`, type `make cstat`. ## Running Cirgonus `cirgonus <config file|dir>` starts cirgonus with the configuration specified -- see the file and directory sections below for more information on how the configuration looks. You can also use `cirgonus generate` to generate a config file based on polled resources. ## Config File A config file is required to run Cirgonus. Check out `test.json` for an example of how it should look. You can also use `cirgonus generate` to generate a configuration file from monitors it can use and devices you have that it can monitor. This can be nice for automated deployments. ## Config Directory Cirgonus can also accept `conf.d` style directory configuration. There is an example of this form in the `config_dir_example` directory in this repository. Running cirgonus in this mode is basically the same as a configuration file, only you point at a directory instead. The rules are pretty basic, but surprising (sorry!): * `main.json` is the top-level configuration. * All other configuration files refer to plugins: * Metric names are named after the filename without the extension (so foo.json becomes metric "foo"). * Metrics are plain JSON objects. * Metrics must have a "Type" and "Params" element. ### Attributes All attributes are currently required. * Listen: `host:port` (host optional) designation on where the agent should listen. * Username: the username for basic authentication. * Password: the password for basic authentication. * Facility: the syslog facility to use. Controlling log levels is a function of your syslogd. * Plugins: An array of plugin definitions. See `Plugins`. ## Querying * GET querying the root will return all metrics. * POST querying with a `{ "Name": "metric name" }` json object will return just that metric. * PUT querying is handled by the "record" plugin. See it below. e.g., if Cirgonus is running on `ubuntu.local:8000`: ``` curl http://ubuntu.local:8000 -d '{ "Name": "tha load" }' ``` Will return just the "tha load" metric: ```json [0,0.01,0.05] ``` Otherwise a plain GET to the root: ``` curl http://ubuntu.local:8000 ``` Will return all the metrics (Example from `test.json` configuration): ```json { "cpu_usage": [0,4], "echo hello": { "hello": 1 }, "echo hi": { "hi": 1 }, "mem_usage": { "Free":845040, "Total":1011956, "Used":166916 }, "tha load": [0, 0.01, 0.05] } ``` ## cstat `cstat` is a small utility to gather statistics from cirgonus agents and display them in an `iostat`-alike manner. For example: ``` $ cstat -hosts linux-1.local,go-test.local,linux-2.local -metric "load_average" linux-1.local: [0,0.01,0.05] go-test.local: [0,0.01,0.05] linux-2.local: [0,0.01,0.05] linux-1.local: [0,0.01,0.05] go-test.local: [0,0.01,0.05] linux-2.local: [0,0.01,0.05] linux-1.local: [0,0.01,0.05] go-test.local: [0,0.01,0.05] linux-2.local: [0,0.01,0.05] ``` ## Plugins Plugins all have a type, an optional name (type and name are equivalent if only one or the other is supplied) and an optional set of parameters which depend on the type of metric collected. Plugin types are below. ### load\_average Returns a three float tuple of the load averages in classic unix form. Takes no parameters. ### mem\_usage Note that this plugin uses the cached/buffers values to determine ram usage. It also (currently) disregards swap. Returns an object with these parameters: * Free -- the amount of free ram. * Total -- the total amount of ram in the machine. * Used -- the amount of used ram. ### cpu\_usage This is a two element tuple -- the first is a decimal value which indicates how much of that is in use, and the second is the number of cpus (as measured by linux -- so hyperthreading cores are 2 cpus). For example: [1.5, 2] - two cores, 150% cpu usage (1 and a half cores are in use) Note that due to the way jiffies are treated, this plugin imposes a minimum granularity of 1 second. ### net\_usage This command gathers interface statistics between the time it was last polled for information. The parameter (A single string) is the name of the interface. Results (hopefully self-explanatory): ```json { "eth0 usage": { "Received (Bytes)": 2406, "Received (Packets)": 25, "Reception Errors": 0, "Transmission Errors": 0, "Transmitted (Bytes)": 1749, "Transmitted (Packets)": 13 } } ``` ### io\_usage Similar to `net_usage`, this computes the difference between polls. It provides a variety of IO statistics and works on both disk devices and partitions, including device mapper devices. Future patches will attempt to rein in other devices such as tmpfs and nfs. Results: ```json { "dm-0 usage": { "io time (ms)": 1768, "iops in progress": 0, "reads issued": 4513, "reads merged": 0, "sectors read": 36608, "sectors written": 55456, "time reading (ms)": 1688, "time writing (ms)": 127156, "weighted io time (ms)": 128844, "writes completed": 5399, "writes merged": 0 } } ``` ### fs\_usage Similar to the other usage metrics, takes a mount point (such as `/`) and returns a 4 element tuple represented as a JSON array. The first 3 elements are unsigned integers, the last is a boolean representing the read/write status of the filesystem. \[ percent used, free bytes, total bytes, read/write? \] ### command This is the catch-all. The command plugin runs a command, and accepts json output from it which it builds into the result. An example from `test.json`: ```json { "echo hi": { "Type": "command", "Params": [ "echo", "{\"hi\": 1}" ] } } ``` This results in this: ```json { "echo hi": {"hi":1} } ``` Note the value has been injected directly into the json form so that Circonus can treat it like a proper json value. ### record This allows you to inject values into cirgonus. When a PUT query is issued with a payload that looks like: ```json { "Name": "record parameter", "Value": { "key" : "value", "other" : ["data", "of any structure"]} } ``` It will show up when queried with GET or POST methods just like any other cirgonus metric. #### Configuration Configuration is a bit tricky; see `test.json` or see the below example. Note that the metric name and parameter are the same. This is critical to the accurate function of this plugin. For a given metric named "record_example", create a file named `record_example.json` ```json { "Type": "record", "Params": null } ``` #### record example usage You can try with the above configuration example with the following `curl` commands: To set the value: ``` curl http://cirgonus:cirgonus@localhost:8000 -X PUT -d '{ "Name": "record_example", "Value": 1 }' ``` To get the value: ``` curl http://cirgonus:cirgonus@localhost:8000 -d '{ "Name": "record_example" }' ``` Which will return `1`. ### json_poll This allows you to poll a service at a given URL to get metrics from that service in json format. Those metrics will be reflected to whomever polls us for state in the given poll interval. Parameter is just the URL. This could be used to "tunnel" metrics from a LXC or similar embedded system by chaining cirgonus monitors. Example: ```json "json_poll example": { "Type": "json_poll", "Params": "http://localhost:8080" } ``` ``` $ curl http://cirgonus:cirgonus@localhost:8000 -d '{ "Name": "json_poll example" }' { "test": "stuff" } # emitted by the service at http://localhost:8080 ``` ## License * MIT (C) 2013 Erik Hollensbe
TypeScript
UTF-8
25,026
3.171875
3
[ "Apache-2.0" ]
permissive
import { ArrayTypeName, Assignment, ASTContext, ASTNode, BinaryOperation, Block, Break, Conditional, Continue, ContractDefinition, DoWhileStatement, ElementaryTypeName, ElementaryTypeNameExpression, EmitStatement, EnumDefinition, EnumValue, ErrorDefinition, EventDefinition, ExpressionStatement, ForStatement, FunctionCall, FunctionCallOptions, FunctionDefinition, FunctionTypeName, Identifier, IdentifierPath, IfStatement, ImportDirective, IndexAccess, IndexRangeAccess, InheritanceSpecifier, InlineAssembly, Literal, Mapping, MemberAccess, ModifierDefinition, ModifierInvocation, NewExpression, OverrideSpecifier, ParameterList, PlaceholderStatement, PragmaDirective, Return, RevertStatement, SourceUnit, StructDefinition, StructuredDocumentation, Throw, TryCatchClause, TryStatement, TupleExpression, UnaryOperation, UncheckedBlock, UserDefinedTypeName, UsingForDirective, VariableDeclaration, VariableDeclarationStatement, WhileStatement } from "."; /** * Helper function to check if the node/nodes `arg` is in the `ASTContext` `ctx`. */ function inCtx(arg: ASTNode | ASTNode[], ctx: ASTContext): boolean { if (arg instanceof ASTNode) { return ctx.contains(arg); } for (const node of arg) { if (!inCtx(node, ctx)) { return false; } } return true; } /** * Error thrown by `checkSanity` that describes a problem with the AST */ export class InsaneASTError extends Error {} function pp(node: ASTNode | ASTContext | undefined): string { return node === undefined ? "undefined" : `${node.constructor.name}#${node.id}`; } /** * Check that the property `prop` of an `ASTNode` `node` is either an `ASTNode` * in the expected `ASTContext` `ctx` or an array `ASTNode[]` all of which are in * the expected `ASTContext` */ function checkVFieldCtx<T extends ASTNode, K extends keyof T>( node: T, prop: K, ctx: ASTContext ): void { const val: T[K] = node[prop]; if (val instanceof ASTNode) { if (!inCtx(val, ctx)) { throw new Error( `Node ${pp(node)} property ${prop} ${pp(val)} not in expected context ${pp( ctx )}. Instead in ${pp(val.context)}` ); } } else if (val instanceof Array) { for (let idx = 0; idx < val.length; idx++) { const el = val[idx]; if (!(el instanceof ASTNode)) { throw new Error( `Expected property ${prop}[${idx}] of ${pp(node)} to be an ASTNode not ${el}` ); } if (!inCtx(val, ctx)) { throw new Error( `Node ${pp(node)} property ${prop}[${idx}] ${pp( el )} not in expected context ${pp(ctx)}. Instead in ${pp(el.context)}` ); } } } else { throw new Error(`Expected property ${prop} of ${pp(node)} to be an ASTNode, not ${val}`); } } /** * Helper to check that: * * 1) the field `field` of `node` is either a number or array of numbers * 2) the field `vField` of `node` is either an `ASTNode` or an array of ASTNodes * 3) if field is a number then `vField` is an `ASTNode` and `field == vField.id` * 4) if field is an array of numbers then `vField` is an `ASTNode[]` and * `node.field.length === node.vField.length` and `node.field[i] === * node.vField[i].id` forall i in `[0, ... node.field.lenth)` * */ function checkFieldAndVFieldMatch<T extends ASTNode, K1 extends keyof T, K2 extends keyof T>( node: T, field: K1, vField: K2 ): void { const val1 = node[field]; const val2 = node[vField]; if (typeof val1 === "number") { if (!(val2 instanceof ASTNode)) { throw new Error( `Expected property ${vField} of ${pp( node )} to be an ASTNode when ${field} is a number, not ${val2}` ); } if (val1 != val2.id) { throw new InsaneASTError( `Node ${pp(node)} property ${field} ${val1} differs from ${vField}.id ${pp(val2)}` ); } } else if (val1 instanceof Array) { if (!(val2 instanceof Array)) { throw new Error( `Expected property ${vField} of ${pp( node )} to be an array when ${vField} is an array, not ${val2}` ); } if (val1.length !== val2.length) { throw new InsaneASTError( `Node ${pp(node)} array properties ${field} and ${vField} have different lengths ${ val1.length } != ${val2.length}` ); } for (let idx = 0; idx < val1.length; idx++) { const el1 = val1[idx]; const el2 = val2[idx]; if (typeof el1 !== "number") { throw new Error( `Expected property ${field}[${idx}] of ${pp(node)} to be a number not ${el1}` ); } if (!(el2 instanceof ASTNode)) { throw new Error( `Expected property ${vField}[${idx}] of ${pp(node)} to be a number not ${el2}` ); } if (el1 != el2.id) { throw new InsaneASTError( `Node ${pp( node )} property ${field}[${idx}] ${el1} differs from ${vField}[${idx}].id ${pp( el2 )}` ); } } } else { throw new Error( `Expected property ${field} of ${pp( node )} to be a number or array of numbers not ${val1}` ); } } /** * Helper to check that: * * 1. All ASTNodes that appear in each of the `fields` of `node` is a direct child of `node` * 2. All the direct children of `node` are mentioned in some of the `fields`. */ function checkDirectChildren<T extends ASTNode>(node: T, ...fields: Array<keyof T>): void { const directChildren = new Set(node.children); const computedChildren = new Set<ASTNode>(); for (const field of fields) { const val = node[field]; if (val === undefined) { continue; } if (val instanceof ASTNode) { if (!directChildren.has(val)) { throw new InsaneASTError( `Field ${field} of node ${pp(node)} is not a direct child: ${pp( val )} child of ${pp(val.parent)}` ); } computedChildren.add(val); } else if (val instanceof Array) { for (let i = 0; i < val.length; i++) { const el = val[i]; if (el === null) { continue; } if (!(el instanceof ASTNode)) { throw new Error( `Field ${field} of ${pp( node )} is expected to be ASTNode, array or map with ASTNodes - instead array containing ${el}` ); } if (!directChildren.has(el)) { throw new InsaneASTError( `Field ${field}[${i}] of node ${pp(node)} is not a direct child: ${pp( el )} child of ${pp(el.parent)}` ); } computedChildren.add(el); } } else if (val instanceof Map) { for (const [k, v] of val.entries()) { if (v === null) { continue; } if (!(v instanceof ASTNode)) { throw new Error( `Field ${field} of ${pp( node )} is expected to be ASTNode, array or map with ASTNodes - instead map containing ${v}` ); } if (!directChildren.has(v)) { throw new InsaneASTError( `Field ${field}[${k}] of node ${pp(node)} is not a direct child: ${pp( v )} child of ${pp(v.parent)}` ); } computedChildren.add(v); } } else { throw new Error( `Field ${field} of ${pp( node )} is neither an ASTNode nor an array of ASTNode or nulls: ${val}` ); } } if (computedChildren.size < directChildren.size) { let missingChild: ASTNode | undefined; for (const child of directChildren) { if (computedChildren.has(child)) { continue; } missingChild = child; break; } throw new InsaneASTError( `Fields ${fields.join(", ")} don't completely cover the direct children: ${pp( missingChild )} is missing` ); } } /** * Check that a single SourceUnit has a sane structure. This checks that: * * - all reachable nodes belong to the same context, have their parent/sibling set correctly, * - all number id properties of nodes point to a node in the same context * - when a number property (e.g. `scope`) has a corresponding `v` prefixed property (e.g. `vScope`) * check that the number proerty corresponds to the id of the `v` prefixed property. * - most 'v' properties point to direct children of a node * * NOTE: While this code can be slightly slow, its meant to be used mostly in testing so its * not performance critical. * * @param unit - source unit to check * @param ctxts - `ASTContext`s for each of the groups of units */ export function checkSane(unit: SourceUnit, ctx: ASTContext): void { for (const node of unit.getChildren(true)) { if (!inCtx(node, ctx)) { throw new InsaneASTError( `Child ${pp(node)} in different context: ${ctx.id} from expected ${ctx.id}` ); } const immediateChildren = node.children; for (const child of immediateChildren) { if (child.parent !== node) { throw new InsaneASTError( `Child ${pp(child)} has wrong parent: expected ${pp(node)} got ${pp( child.parent )}` ); } } if ( node instanceof PragmaDirective || node instanceof StructuredDocumentation || node instanceof EnumValue || node instanceof Break || node instanceof Continue || node instanceof InlineAssembly || node instanceof PlaceholderStatement || node instanceof Throw || node instanceof ElementaryTypeName || node instanceof Literal ) { /** * These nodes do not have any children or references. * There is nothing to check, so just skip them. */ continue; } if (node instanceof SourceUnit) { for (const [name, symId] of node.exportedSymbols) { const symNode = ctx.locate(symId); if (symNode === undefined) { throw new InsaneASTError( `Exported symbol ${name} ${symId} missing from context ${ctx.id}` ); } if (symNode !== node.vExportedSymbols.get(name)) { throw new InsaneASTError( `Exported symbol ${name} for id ${symId} (${pp( symNode )}) doesn't match vExportedSymbols entry: ${pp( node.vExportedSymbols.get(name) )}` ); } } checkDirectChildren( node, "vPragmaDirectives", "vImportDirectives", "vContracts", "vEnums", "vStructs", "vFunctions", "vVariables", "vErrors" ); } else if (node instanceof ImportDirective) { /** * Unfortunately due to compiler bugs in older compilers, when child.symbolAliases[i].foreign is a number * its invalid. When its an Identifier, only its name is valid. */ if ( node.vSymbolAliases.length !== 0 && node.vSymbolAliases.length !== node.symbolAliases.length ) { throw new InsaneASTError( `symbolAliases.length (${ node.symbolAliases.length }) and vSymboliAliases.length ${ node.vSymbolAliases.length } misamtch for import ${pp(node)}` ); } for (let i = 0; i < node.vSymbolAliases.length; i++) { const def = node.vSymbolAliases[i][0]; if (!inCtx(def, ctx)) { throw new InsaneASTError( `Imported symbol ${pp(def)} from import ${pp( node )} not in expected context ${pp(ctx)}` ); } } checkFieldAndVFieldMatch(node, "scope", "vScope"); checkVFieldCtx(node, "vScope", ctx); checkFieldAndVFieldMatch(node, "sourceUnit", "vSourceUnit"); checkVFieldCtx(node, "vSourceUnit", ctx); } else if (node instanceof InheritanceSpecifier) { checkDirectChildren(node, "vBaseType", "vArguments"); } else if (node instanceof ModifierInvocation) { checkVFieldCtx(node, "vModifier", ctx); checkDirectChildren(node, "vModifierName", "vArguments"); } else if (node instanceof OverrideSpecifier) { checkDirectChildren(node, "vOverrides"); } else if (node instanceof ParameterList) { checkVFieldCtx(node, "vParameters", ctx); checkDirectChildren(node, "vParameters"); } else if (node instanceof UsingForDirective) { checkDirectChildren(node, "vLibraryName", "vTypeName"); } else if (node instanceof ContractDefinition) { checkFieldAndVFieldMatch(node, "scope", "vScope"); checkVFieldCtx(node, "vScope", ctx); if (node.vScope !== node.parent) { throw new InsaneASTError( `Contract ${pp(node)} vScope ${pp(node.vScope)} and parent ${pp( node.parent )} differ` ); } checkFieldAndVFieldMatch(node, "linearizedBaseContracts", "vLinearizedBaseContracts"); checkVFieldCtx(node, "vLinearizedBaseContracts", ctx); checkFieldAndVFieldMatch(node, "usedErrors", "vUsedErrors"); checkVFieldCtx(node, "vUsedErrors", ctx); const fields: Array<keyof ContractDefinition> = [ "documentation", "vInheritanceSpecifiers", "vStateVariables", "vModifiers", "vErrors", "vEvents", "vFunctions", "vUsingForDirectives", "vStructs", "vEnums", "vConstructor" ]; if (node.documentation instanceof StructuredDocumentation) { checkVFieldCtx(node, "documentation", ctx); fields.push("documentation"); } checkDirectChildren(node, ...fields); } else if (node instanceof EnumDefinition) { checkVFieldCtx(node, "vScope", ctx); checkDirectChildren(node, "vMembers"); } else if (node instanceof ErrorDefinition) { checkVFieldCtx(node, "vScope", ctx); const fields: Array<keyof ErrorDefinition> = ["vParameters"]; if (node.documentation instanceof StructuredDocumentation) { checkVFieldCtx(node, "documentation", ctx); fields.push("documentation"); } checkDirectChildren(node, ...fields); } else if (node instanceof EventDefinition) { checkVFieldCtx(node, "vScope", ctx); const fields: Array<keyof EventDefinition> = ["vParameters"]; if (node.documentation instanceof StructuredDocumentation) { checkVFieldCtx(node, "documentation", ctx); fields.push("documentation"); } checkDirectChildren(node, ...fields); } else if (node instanceof FunctionDefinition) { checkFieldAndVFieldMatch(node, "scope", "vScope"); checkVFieldCtx(node, "vScope", ctx); const fields: Array<keyof FunctionDefinition> = [ "vParameters", "vOverrideSpecifier", "vModifiers", "vReturnParameters", "vBody" ]; if (node.documentation instanceof StructuredDocumentation) { checkVFieldCtx(node, "documentation", ctx); fields.push("documentation"); } checkDirectChildren(node, ...fields); } else if (node instanceof ModifierDefinition) { checkVFieldCtx(node, "vScope", ctx); const fields: Array<keyof ModifierDefinition> = [ "vParameters", "vOverrideSpecifier", "vBody" ]; if (node.documentation instanceof StructuredDocumentation) { checkVFieldCtx(node, "documentation", ctx); fields.push("documentation"); } checkDirectChildren(node, ...fields); } else if (node instanceof StructDefinition) { checkFieldAndVFieldMatch(node, "scope", "vScope"); checkVFieldCtx(node, "vScope", ctx); checkDirectChildren(node, "vMembers"); } else if (node instanceof VariableDeclaration) { checkFieldAndVFieldMatch(node, "scope", "vScope"); checkVFieldCtx(node, "vScope", ctx); const fields: Array<keyof VariableDeclaration> = [ "vType", "vOverrideSpecifier", "vValue" ]; if (node.documentation instanceof StructuredDocumentation) { checkVFieldCtx(node, "documentation", ctx); fields.push("documentation"); } checkDirectChildren(node, ...fields); } else if (node instanceof Block || node instanceof UncheckedBlock) { checkDirectChildren(node, "vStatements"); } else if (node instanceof DoWhileStatement) { checkDirectChildren(node, "vCondition", "vBody"); } else if (node instanceof EmitStatement) { checkDirectChildren(node, "vEventCall"); } else if (node instanceof RevertStatement) { checkDirectChildren(node, "errorCall"); } else if (node instanceof ExpressionStatement) { checkDirectChildren(node, "vExpression"); } else if (node instanceof ForStatement) { checkDirectChildren( node, "vInitializationExpression", "vLoopExpression", "vCondition", "vBody" ); } else if (node instanceof IfStatement) { checkVFieldCtx(node, "vCondition", ctx); checkVFieldCtx(node, "vTrueBody", ctx); if (node.vFalseBody !== undefined) { checkVFieldCtx(node, "vFalseBody", ctx); } checkDirectChildren(node, "vCondition", "vTrueBody", "vFalseBody"); } else if (node instanceof Return) { checkFieldAndVFieldMatch(node, "functionReturnParameters", "vFunctionReturnParameters"); checkVFieldCtx(node, "vFunctionReturnParameters", ctx); checkDirectChildren(node, "vExpression"); } else if (node instanceof TryCatchClause) { checkDirectChildren(node, "vParameters", "vBlock"); } else if (node instanceof TryStatement) { checkDirectChildren(node, "vExternalCall", "vClauses"); } else if (node instanceof VariableDeclarationStatement) { checkDirectChildren(node, "vDeclarations", "vInitialValue"); } else if (node instanceof WhileStatement) { checkDirectChildren(node, "vCondition", "vBody"); } else if (node instanceof ArrayTypeName) { checkDirectChildren(node, "vBaseType", "vLength"); } else if (node instanceof FunctionTypeName) { checkDirectChildren(node, "vParameterTypes", "vReturnParameterTypes"); } else if (node instanceof Mapping) { checkDirectChildren(node, "vKeyType", "vValueType"); } else if (node instanceof UserDefinedTypeName) { checkFieldAndVFieldMatch(node, "referencedDeclaration", "vReferencedDeclaration"); checkVFieldCtx(node, "vReferencedDeclaration", ctx); checkDirectChildren(node, "path"); } else if (node instanceof Assignment) { checkDirectChildren(node, "vLeftHandSide", "vRightHandSide"); } else if (node instanceof BinaryOperation) { checkDirectChildren(node, "vLeftExpression", "vRightExpression"); } else if (node instanceof Conditional) { checkDirectChildren(node, "vCondition", "vTrueExpression", "vFalseExpression"); } else if (node instanceof ElementaryTypeNameExpression) { if (!(typeof node.typeName === "string")) { checkDirectChildren(node, "typeName"); } } else if (node instanceof FunctionCall) { checkDirectChildren(node, "vExpression", "vArguments"); } else if (node instanceof FunctionCallOptions) { checkDirectChildren(node, "vExpression", "vOptionsMap"); } else if (node instanceof Identifier || node instanceof IdentifierPath) { if (node.referencedDeclaration !== null && node.vReferencedDeclaration !== undefined) { checkFieldAndVFieldMatch(node, "referencedDeclaration", "vReferencedDeclaration"); checkVFieldCtx(node, "vReferencedDeclaration", ctx); } } else if (node instanceof IndexAccess) { checkDirectChildren(node, "vBaseExpression", "vIndexExpression"); } else if (node instanceof IndexRangeAccess) { checkDirectChildren(node, "vBaseExpression", "vStartExpression", "vEndExpression"); } else if (node instanceof MemberAccess) { if (node.referencedDeclaration !== null && node.vReferencedDeclaration !== undefined) { checkFieldAndVFieldMatch(node, "referencedDeclaration", "vReferencedDeclaration"); checkVFieldCtx(node, "vReferencedDeclaration", ctx); } checkDirectChildren(node, "vExpression"); } else if (node instanceof NewExpression) { checkDirectChildren(node, "vTypeName"); } else if (node instanceof TupleExpression) { checkDirectChildren(node, "vOriginalComponents", "vComponents"); } else if (node instanceof UnaryOperation) { checkVFieldCtx(node, "vSubExpression", ctx); checkDirectChildren(node, "vSubExpression"); } else { throw new Error(`Unknown ASTNode type ${node.constructor.name}`); } } } /** * Check that a single SourceUnit has a sane structure. This checks that: * - All reachable nodes belong to the same context, have their parent/sibling set correctly. * - All number id properties of nodes point to a node in the same context. * - When a number property (e.g. `scope`) has a corresponding `v` prefixed property (e.g. `vScope`) * check that the number proerty corresponds to the id of the `v` prefixed property. * - Most 'v' properties point to direct children of a node. * * NOTE: While this code can be slightly slow, its meant to be used mostly in testing so its * not performance critical. */ export function isSane(unit: SourceUnit, ctx: ASTContext): boolean { try { checkSane(unit, ctx); } catch (e) { if (e instanceof InsaneASTError) { console.error(e); return false; } throw e; } return true; }
Python
UTF-8
2,921
3.046875
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 8 13:00:20 2019 @author: msr """ import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def read_files(files, columns): df_dict = {} for i, file in enumerate(files): df = pd.read_csv(file, names=columns, header=0) file_number = file[-5] df['source'] = file_number df_dict['df'+file_number] = df return df_dict def overlap(df1, df2, column): vals1 = df1[column] vals2 = df2[column] if any(vals1.isin(vals2)): return "Overlaps found for {}".format(column) else: return "There is no overlap" def barplot(df, groupby_col, metric, summary_type, axis, **kwargs): size = 52 if summary_type == "sum": df_summarised = df.groupby([groupby_col])[metric].sum().sort_values(ascending=False).to_frame() elif summary_type == "avg": df_summarised = df.groupby([groupby_col])[metric].mean().sort_values(ascending=False).to_frame() df_summarised = df_summarised.head(size) plot = sns.barplot(x = df_summarised.index.get_level_values(0), y=df_summarised[metric], ax=axis) plot.set_xlabel(groupby_col, fontsize = 20) plot.set_ylabel(metric, fontsize = 20) plot.set_xticklabels(plot.get_xticklabels(), rotation=45); return df_summarised, plot def week_number_from_start(df, start_year=0, to_add=0): week_number = [] year_count = start_year - 1 dates = [] for date in df.date.sort_values().unique(): date = pd.to_datetime(date) dates.append(date) if date.day == 1 and date.month == 1: year_count += 1 if year_count > start_year: to_add += 52 week_number.append(df[df['date'] == date]['date'].dt.week.unique()[0] + to_add) for i, j in zip(dates, week_number): df.loc[df['date'] == i, 'weeks_from_start'] = j df['weeks_from_start'] = df['weeks_from_start'].astype(int) return df def other_products(df, sku): bills = df[df['sku'] == sku]['bill'].unique() skus = df[df['bill'].isin(bills)]['sku'].unique().tolist() skus.remove(sku) return skus def rmse(preds, y_test): sq_errors = (preds - y_test)**2 mean_sq_error = sq_errors.mean() root_mean_sq_error = np.sqrt(mean_sq_error) return root_mean_sq_error
C++
UTF-8
2,496
2.734375
3
[]
no_license
// // Created by nim on 14.09.2021. // #include "../../../test_config.h" #include <common/helpers/string_helper.h> #include <codecvt> #include <crypto/data/providers/crypto_provider_imp.h> #include <gmock/gmock.h> #include <gtest/gtest.h> CryptoProvider *crypto_provider{nullptr}; class CryptoProviderImpTest : public ::testing::Test { protected: static void SetUpTestSuite() { crypto_provider = new CryptoProviderImp(); } static void TearDownTestSuite() { delete crypto_provider; } }; TEST_F(CryptoProviderImpTest, Md5HashSuccessTest) { auto const value_ = std::string{"123456"}; auto const data_ = std::vector<BYTE>{value_.begin(), value_.end()}; auto result_ = crypto_provider->Md5Hash(data_); ASSERT_TRUE(result_); ASSERT_EQ(typeid(result_), typeid(BytesEither)); result_.WhenRight([](const auto hash_data) { ASSERT_EQ(typeid(hash_data), typeid(Bytes)); ASSERT_THAT(hash_data, testing::ElementsAreArray(test_config::kKey)); }); } TEST_F(CryptoProviderImpTest, EncodeAesSuccessTest) { const auto key_data_ = Bytes{test_config::kKey, test_config::kKey + sizeof(test_config::kKey)}; auto data_ = string_helper::WStringToBytes(test_config::kEncodedTestWStr) | Bytes{}; auto result_ = crypto_provider->EncodeAes(key_data_, data_); result_.WhenRight([](const auto encoded) { ASSERT_EQ(typeid(encoded), typeid(Bytes)); ASSERT_THAT(encoded, testing::ElementsAreArray(test_config::kEncodedData)); // for (int item : encoded) { // std::cout << "0x" << std::hex << std::setfill('0') << std::setw(2) << item << ", "; // } // std::cout << std::endl; }); ASSERT_TRUE(result_); ASSERT_EQ(typeid(result_), typeid(BytesEither)); } TEST_F(CryptoProviderImpTest, DecodeAesSuccessTest) { const auto key_data_ = Bytes{test_config::kKey, test_config::kKey + sizeof(test_config::kKey)}; const auto data_ = Bytes{test_config::kEncodedData, test_config::kEncodedData + sizeof(test_config::kEncodedData)}; auto result_ = crypto_provider->DecodeAes(key_data_, data_); ASSERT_TRUE(result_); ASSERT_EQ(typeid(result_), typeid(BytesEither)); result_.WhenRight([](const auto decoded) { ASSERT_EQ(typeid(decoded), typeid(Bytes)); std::string value_{decoded.begin(), decoded.end()}; std::cout << value_ << std::endl; const auto encoded_value_ = helper::Utf16ToUtf8(test_config::kEncodedTestWStr) | ""; ASSERT_STREQ(value_.c_str(), encoded_value_.c_str()); }); }
Python
UTF-8
372
2.765625
3
[]
no_license
n,m=map(int,input().split()) o=[] for i in range(m): o.append(list(map(int,input().split()))) cost=10000000 f=0 for i in range(m):#loopstarts if o[i][0]==1: s=o[i][1] c=o[i][2] for j in range(i+1,m): if o[j][0]==s: s=o[j][1] c+=o[j][2] if c<cost and s==n: cost=c f+=1#loopends if f==0: print(-1) else: print(cost)
Python
UTF-8
468
2.8125
3
[ "BSD-3-Clause" ]
permissive
import ipaddress import socket def resolve_to_ips(hostname, port=80): try: address_tuples = socket.getaddrinfo(hostname, port) except socket.gaierror: raise CannotResolveHost(hostname) return [extract_ip(addr_info) for addr_info in address_tuples] INDEX_SOCKADDR = 4 INDEX_ADDRESS = 0 def extract_ip(addr_info): return ipaddress.ip_address(addr_info[INDEX_SOCKADDR][INDEX_ADDRESS]) class CannotResolveHost(Exception): pass
Java
UTF-8
1,139
3
3
[ "MIT" ]
permissive
import java.io.*; import java.util.*; public class FileDump { public static String readFASTA(String fileName) { String seq = ""; try { BufferedReader reader = new BufferedReader(new FileReader(new File(fileName))); String text = null; /* Dump the first line baby!*/ reader.readLine(); while ((text = reader.readLine()) != null) { text = text.toLowerCase(); seq = seq.concat(text); } } catch (IOException e) { e.printStackTrace(); } return seq; } private static int HEADER_ROWS = 1; private static int HEADER_COLS = 2; public static void dumpHiddenExons(String nameAndPath, ArrayList<HiddenExon> hiddenExons) throws FileNotFoundException { CsvOutputter outputter = new CsvOutputter(nameAndPath); String[][] header = new String[HEADER_ROWS][HEADER_COLS]; header[0][0] = "Start / End:"; header[0][1] = "Likelyhood"; outputter.write(header); for (HiddenExon e : hiddenExons) outputter.write(e.toCsv()); outputter.close(); } }
Java
UTF-8
5,239
1.710938
2
[]
no_license
package com.sos.joc.joe.impl; import java.time.Instant; import java.util.Date; import javax.ws.rs.Path; import com.sos.auth.rest.permission.model.SOSPermissionJocCockpit; import com.sos.hibernate.classes.SOSHibernateSession; import com.sos.jitl.joe.DBItemJoeObject; import com.sos.jobscheduler.model.event.CustomEvent; import com.sos.joc.Globals; import com.sos.joc.classes.JOCDefaultResponse; import com.sos.joc.classes.JOCResourceImpl; import com.sos.joc.classes.JOEHelper; import com.sos.joc.classes.calendar.SendCalendarEventsUtil; import com.sos.joc.db.joe.DBLayerJoeLocks; import com.sos.joc.db.joe.DBLayerJoeObjects; import com.sos.joc.db.joe.FilterJoeObjects; import com.sos.joc.exceptions.JocException; import com.sos.joc.exceptions.JoeFolderAlreadyLockedException; import com.sos.joc.joe.resource.IUnDeleteResource; import com.sos.joc.model.common.JobSchedulerObjectType; import com.sos.joc.model.joe.common.Filter; import com.sos.schema.JsonValidator; @Path("joe") public class UnDeleteResourceImpl extends JOCResourceImpl implements IUnDeleteResource { private static final String API_CALL = "./joe/undelete"; @Override public JOCDefaultResponse undelete(final String accessToken, final byte[] filterBytes) { SOSHibernateSession sosHibernateSession = null; try { JsonValidator.validateFailFast(filterBytes, Filter.class); Filter body = Globals.objectMapper.readValue(filterBytes, Filter.class); SOSPermissionJocCockpit sosPermissionJocCockpit = getPermissonsJocCockpit(body.getJobschedulerId(), accessToken); boolean permission = sosPermissionJocCockpit.getJobschedulerMaster().getAdministration().getConfigurations().isDelete(); JOCDefaultResponse jocDefaultResponse = init(API_CALL, body, accessToken, body.getJobschedulerId(), permission); if (jocDefaultResponse != null) { return jocDefaultResponse; } checkRequiredParameter("objectType", body.getObjectType()); checkRequiredParameter("path", body.getPath()); boolean isDirectory = body.getObjectType() == JobSchedulerObjectType.FOLDER; String folder = null; if (isDirectory) { body.setPath(normalizeFolder(body.getPath())); folder = body.getPath(); } else { body.setPath(normalizePath(body.getPath())); folder = getParent(body.getPath()); } if (!folderPermissions.isPermittedForFolder(folder)) { return accessDeniedResponse(); } sosHibernateSession = Globals.createSosHibernateStatelessConnection(API_CALL); LockResourceImpl.unForcelock(new DBLayerJoeLocks(sosHibernateSession), body.getJobschedulerId(), folder, getAccount()); DBLayerJoeObjects dbLayer = new DBLayerJoeObjects(sosHibernateSession); FilterJoeObjects filter = new FilterJoeObjects(); filter = new FilterJoeObjects(); filter.setSchedulerId(body.getJobschedulerId()); filter.setConstraint(body); DBItemJoeObject dbItem = dbLayer.getJoeObject(filter); Date now = Date.from(Instant.now()); if (dbItem != null) { //it happens if an object is marked to delete without any changes in the configuration boolean objectWithNullConfiguration = !"FOLDER".equals(dbItem.getObjectType()) && dbItem.getConfiguration() == null; if (objectWithNullConfiguration) { dbLayer.delete(dbItem); } else { dbItem.setOperation("store"); dbItem.setAccount(getAccount()); dbItem.setModified(now); dbLayer.update(dbItem); } if (body.getObjectType() == JobSchedulerObjectType.JOBCHAIN) { // restore orders, nodeparams JOEHelper.restoreOrdersAndNodeParams(dbLayer, dbLayer.getOrdersAndNodeParams(dbItem), getAccount(), now); } else if (body.getObjectType() == JobSchedulerObjectType.ORDER) { // restore nodeparams JOEHelper.restoreOrdersAndNodeParams(dbLayer, dbLayer.getNodeParams(dbItem), getAccount(), now); } } try { CustomEvent evt = JOEHelper.getJoeUpdatedEvent(folder); SendCalendarEventsUtil.sendEvent(evt, dbItemInventoryInstance, accessToken); } catch (Exception e) { // } return JOCDefaultResponse.responseStatusJSOk(Date.from(Instant.now())); } catch (JoeFolderAlreadyLockedException e) { return JOEHelper.get434Response(e); } catch (JocException e) { e.addErrorMetaInfo(getJocError()); return JOCDefaultResponse.responseStatusJSError(e); } catch (Exception e) { return JOCDefaultResponse.responseStatusJSError(e, getJocError()); } finally { Globals.disconnect(sosHibernateSession); } } }
C++
UTF-8
5,029
3.203125
3
[]
no_license
#include<iostream> #include<queue> using namespace std; /************** GRAPH STRUCT ************* */ //Graph using adjency matrix #define MAXV 1000 //Node Struct typedef struct edgenode_str{ int y; int weight; struct edgenode_str *next; }edgenode; typedef struct graph_str{ edgenode *edges[MAXV+1]; /*adjacency info*/ int degree[MAXV+1]; /**/ int nvertices; /*number of vertices in the graph*/ int nedges; /*number of edges in the graph*/ bool directed; /*is the graph directed?*/ }graph; /************** Graph Utilities ************* */ void initialize_graph(graph *g, bool directed){ g->nvertices=0; g->nedges=0; g->directed=directed; for(int i=1;i<=MAXV; i++)g->degree[i]=0; for(int i=1;i<=MAXV; i++)g->edges[i]=NULL; } void insert_edge(graph *g, int x, int y, bool directed){ // edgenode *p; p=(edgenode*)malloc(sizeof(edgenode)); p->weight=0; p->y = y; p->next=g->edges[x]; g->edges[x]=p; g->degree[x]++; if(directed==false) insert_edge(g,y,x,true); else g->nedges ++; } void insert_edge_w(graph *g, int x, int y, bool directed,int wx, int wy){ // edgenode *p; p=(edgenode*)malloc(sizeof(edgenode)); p->weight=wy; p->y = y; p->next=g->edges[x]; g->edges[x]=p; g->degree[x]++; if(directed==false) insert_edge_w(g,y,x,true,wy,wx); else g->nedges ++; } void printGraph(graph *g){ edgenode *p; cout<<"flag\n"; for(int i=1; i<=g->nvertices; i++){ printf("%d: ",i); p = g->edges[i]; while(p !=NULL){ printf("%d(%d)->",p->y,p->weight); p=p->next; } printf("\n"); } } /************** GRAPH traversal ************* */ bool processed [MAXV+1]; bool discovered [MAXV+1]; int parents[MAXV+1]; void initialize_search(graph *g){ for(int i=1; i<=g->nvertices;i++){ processed[i]=discovered[i]=false; parents[i]=-1; } } void traversal(graph *g, int start){ queue <int> q; int v; int y; edgenode *p; q.push(start); discovered[start] =true; while(q.size()!=0){ v=q.front(); q.pop(); //pre processing processed[v]=true; p=g->edges[v]; while(p!=NULL){ /*go over adjency list*/ y=p->y; if((processed[y]==false)||g->directed){ //Process edge here! } if(discovered[y]==false){ q.push(y); discovered[y]=true; parents[y]=v; } p=p->next; } //Post processing Vertex } } int MAXINT = numeric_limits<int>::max(); void dijkstra(graph *g, int start){ int i; edgenode *p; bool intree[MAXV+1]; int distance[MAXV+1]; int v; int w; int weight; int dist; for(int i=1; i<=g->nvertices; i++){ intree[i]=false; distance[i]=MAXINT; parents[i]=-1; } distance[start]=0; v=start; while(intree[v]==false){ intree[v]=true; p=g->edges[v]; while(p!=NULL){ w=p->y; weight=p->weight; if(distance[w]>(distance[v]+weight)){ distance[w]=distance[v]+weight; parents[w]=v; } p=p->next; } v=1; dist=MAXINT; for(i=1; i<=g->nvertices;i++){ if((intree[i]==false)&&(dist>distance[i]) ){ dist=distance[i]; v=i; } } } } /************** Path finder ************* */ void find_path_helper(int start, int end, int parents[]){ if((start==end)||(end==-1)) //Recursion base case printf("%d->",start); else{ //Track path find_path_helper(start,parents[end],parents); printf(" %d->", end); } } void find_path(int start, int end, int parents[]){ find_path_helper(start,end, parents); cout<<endl; } int main(){ /************** TEST 1: ASSIGN WEIGHTS TO VERTICES AND FIND THE LIGTHER PATH ************* */ /////////////GRAPH 1 graph *g=(graph*)malloc(sizeof(graph)); initialize_graph(g,false); g->nvertices=10; //Construction of test graph insert_edge_w(g,1,2,false,0,11); insert_edge_w(g,2,4,false,11,0); insert_edge_w(g,4,5,false,0,0); insert_edge_w(g,5,7,false,0,0); insert_edge_w(g,1,3,false,0,20); insert_edge_w(g,3,4,false,20,0); insert_edge_w(g,1,6,false,0,10); insert_edge_w(g,6,7,false,10,0); //Print adjacency information printGraph(g); initialize_search(g); dijkstra(g,1); int start=1; int end=5; cout<<"the path from "<<start<<" to "<<end<<endl; find_path(start,end,parents); /////////////GRAPH 2 graph *g2=(graph*)malloc(sizeof(graph)); initialize_graph(g2,false); g2->nvertices=10; //construction of graph test 2 insert_edge_w(g2,1,2,false,0,5); insert_edge_w(g2,2,8,false,5,0); insert_edge_w(g2,1,3,false,0,1); insert_edge_w(g2,3,5,false,1,1); insert_edge_w(g2,5,7,false,1,1); insert_edge_w(g2,7,8,false,1,0); insert_edge_w(g2,1,4,false,0,5); insert_edge_w(g2,4,6,false,5,5); insert_edge_w(g2,6,8,false,5,0); //print graph2 printGraph(g2); //Start search initialize_search(g2); dijkstra(g2,1); start=1; end=8; cout<<"the path from "<<start<<" to "<<end<<endl; find_path(start,end,parents); }
Python
UTF-8
2,728
3.03125
3
[]
no_license
import datetime from logger.util import date_to_str # Category node that contains log entries. class Tag: def __init__(self, id, name, entries): self.id = id self.name = name self.modified_at = datetime.datetime(year=1970, month=1, day=1) self.entries = entries self.children = [] self.parent = None self.total_entries = 0 def add_child(self, child): self.children.append(child) def add_entry(self, entry): self.entries.append(entry) entry.category = self parent = self while parent is not None: parent.total_entries += 1 if parent.modified_at < entry.modified_at: parent.modified_at = entry.modified_at parent = parent.parent def get_child_tags(self): tags = [] queue = [self] while queue: current = queue[-1] queue.pop() tags.append(current) queue += current.children tags.sort(key=lambda t: t.modified_at, reverse=True) return tags def get_entries(self): entries = [] for t in self.get_child_tags(): entries += t.entries entries.sort(key=lambda e: e.modified_at, reverse=True) return entries def delete_child(self, child_id): for i, c in enumerate(self.children): if int(c.id) == int(child_id): del self.children[i] return raise Exception('Child with id %d for tag %s does not exist' % (child_id, self.name)) def to_json(self): return { 'id': self.id, 'name': self.name, 'children': [t.id for t in self.children], 'entries': [e.id for e in self.get_entries()], 'total_entries': self.total_entries, 'modified_at': date_to_str(self.modified_at - datetime.timedelta(hours=3)), } def print_header(self): print('======================================') print('%s (%d entries)' % (self.name, len(self.entries))) print('======================================') def print_summary(self): self.print_header() entries_to_print = 3 if self.entries: self.entries[-1].print_detailed(print_tags=False) for e in reversed(self.entries[-entries_to_print:-1]): e.print_summarized(print_tags=False) print('\n') def print_snippet(self): dt = 'no entries' if self.entries: e = self.entries[0] dt = datetime.datetime.strftime(e.created_at, "%Y-%m-%d %H:%M:%S") print('%s: %d (%s)' % (self.name, len(self.entries), dt)) def print_detailed(self): tags = self.get_child_tags() for t in tags: print('============================================') t.print_snippet() print('============================================') for e in t.entries: e.print_detailed()
Shell
UTF-8
162
2.8125
3
[]
no_license
#!/usr/bin/env bash for version in 2.7.15 3.6.8; do echo "Running tests for python version: $version" pyenv local $version ./scripts/build.sh; done;