language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
11,396
2.515625
3
[]
no_license
from agent_dir.agent import Agent import scipy import numpy as np import tensorflow as tf import os # Ref: https://github.com/openai/baselines/blob/master/baselines/ppo2/ppo2.py # Simplified version of PPO2 (Ignore vloss in original paper) # Action values to send to gym environment to move paddle up/down UP_ACTION = 2 DOWN_ACTION = 3 # Mapping from action values to outputs from the policy network action_dict = {DOWN_ACTION: 0, UP_ACTION: 1} UPDATE_TIMES = 8 def prepro(o,image_size=[80,80]): """ Call this function to preprocess RGB image to grayscale image if necessary This preprocessing code is from https://github.com/hiwonjoon/tf-a3c-gpu/blob/master/async_agent.py Input: RGB image: np.array RGB screen of game, shape: (210, 160, 3) Default return: np.array Grayscale image, shape: (80, 80, 1) """ y = 0.2126 * o[:, :, 0] + 0.7152 * o[:, :, 1] + 0.0722 * o[:, :, 2] y = y.astype(np.uint8) resized = scipy.misc.imresize(y, image_size) return np.expand_dims(resized.astype(np.float32),axis=2) def dense_layer(input_tensor, input_dim, output_dim, name, activation=tf.nn.relu): with tf.variable_scope(name): W = tf.get_variable('weights', [input_dim, output_dim], dtype=tf.float32) b = tf.get_variable('bias', [output_dim], dtype=tf.float32) output = tf.nn.bias_add(tf.matmul(input_tensor, W), b) return activation(output) class Model: def __init__(self, states, hidden_size, name='model', reuse=None): with tf.variable_scope(name, reuse=reuse): fc1 = dense_layer(states, 80*80, hidden_size, 'dense1') up_prob = dense_layer(fc1, hidden_size, 1, 'up_prob', tf.nn.sigmoid) self.up_prob = up_prob class Agent_PPO2(Agent): def __init__(self, env, args): """ Initialize every things you need here. For example: building your model """ super(Agent_PPO2,self).__init__(env) ################## # YOUR CODE HERE # ################## print('Build Model Architecture...') self.lr = 2e-5 self.hidden_size = 256 self.env = env self.ep2save = 10 self.batch_episodes = 4 self.max_grad_norm = 0.5 if args.render: self.render=True else: self.render=False self.sess = tf.Session() self.states = tf.placeholder(tf.float32, [None, 80*80], name='input_state') self.sampled_actions = tf.placeholder(tf.float32, [None, 1], name='sampled_actions') self.advantage = tf.placeholder(tf.float32, [None, 1], name='advantage') new_model = Model(self.states, self.hidden_size) old_model = Model(self.states, self.hidden_size, reuse=True) ### For ppo2 algorithm ##### # PPO2 seems to be sensitive to hyperparameters self.old_pred = tf.placeholder(tf.float32, [None, 1], name='old_pred') self.prob = new_model.up_prob self.old_p = old_model.up_prob # output prob of old model action_prob = self.sampled_actions*self.prob - (self.sampled_actions-1.)*(1.-self.prob) old_action_p = self.sampled_actions*self.old_pred - (self.sampled_actions - 1.)*(1.-self.old_pred) ratio = action_prob/old_action_p self.cliprange = tf.convert_to_tensor(0.2) pg_losses = -self.advantage * ratio pg_losses2 = -self.advantage * tf.clip_by_value(ratio, 1. - self.cliprange, 1. + self.cliprange) pg_loss = tf.reduce_mean(tf.maximum(pg_losses, pg_losses2)) entropy = tf.losses.log_loss(labels=self.sampled_actions, predictions=self.prob) self.loss = (pg_loss - entropy*0.01)/self.batch_episodes ############################ with tf.variable_scope('model'): params = tf.trainable_variables() opt = tf.train.AdamOptimizer(self.lr, epsilon=1e-5) grads = tf.gradients(self.loss, params) grads, _grad_norm = tf.clip_by_global_norm(grads, self.max_grad_norm) grads = list(zip(grads, params)) self.train_op = opt.apply_gradients(grads) self.saver = tf.train.Saver() init = tf.global_variables_initializer() self.sess.run(init) self.model_dir = 'ppo2_save/' if not os.path.exists(self.model_dir): os.makedirs(self.model_dir) if args.train_ppo2: self.log_dir = 'ppo2_log/' if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) self.writer = tf.summary.FileWriter(self.log_dir, self.sess.graph) if args.test_ppo2: #you can load your model here print('Yo! This is ppo2 model~~') model_path = 'ppo2_save/ppo2_net.ckpt-10000' # Greatest rewards: 10000 self.saver.restore(self.sess, model_path) print('loading trained model') def init_game_setting(self): """ Testing function will call this function at the begining of new game Put anything you want to initialize if necessary """ ################## # YOUR CODE HERE # ################## self.observation_memory = [] def forward_pass(self, up_prob, states): prob = self.sess.run(up_prob, feed_dict={self.states: states.reshape([1, -1])}) return prob def train(self): """ Implement your training algorithm here """ # Action list: https://github.com/openai/gym/blob/master/gym/envs/atari/atari_env.py ################## # YOUR CODE HERE # ################## discount_factor = 0.99 smoothed_reward = None total_episode = 10000 states_history = [] actions_history = [] rewards_history = [] old_prob = [] # batch of data b_states = [] b_actions = [] b_rewards = [] b_old_p = [] for episode_n in range(1, total_episode+1): print("\nstarting episode",episode_n) n_steps = 1 done = False episode_reward_sum = 0 round_n = 1 last_observation = self.env.reset() last_observation = prepro(last_observation) action = self.env.action_space.sample() observation, _, _, _ = self.env.step(action) observation = prepro(observation) while not done: if self.render: self.env.env.render() residual = observation - last_observation last_observation = observation up_prob = self.forward_pass(self.old_p, residual)[0] if np.random.uniform() < up_prob: action = UP_ACTION else: action = DOWN_ACTION observation, reward, done, _ = self.env.step(action) observation = prepro(observation) episode_reward_sum += reward n_steps += 1 states_history.append(residual) actions_history.append(action_dict[action]) rewards_history.append(reward) old_prob.append(up_prob) if reward != 0: round_n += 1 n_steps = 0 summary = tf.Summary(value=[tf.Summary.Value(tag="Episode_Rewards", simple_value=episode_reward_sum)]) self.writer.add_summary(summary, episode_n) if smoothed_reward is None: smoothed_reward = episode_reward_sum else: smoothed_reward = smoothed_reward * 0.99 + episode_reward_sum * 0.01 print("Reward total was {}; discounted moving average of reward is {}".format(episode_reward_sum, smoothed_reward)) # Normalize the rewards rewards = self.discount_rewards(rewards_history, discount_factor) rewards -= np.mean(rewards) rewards /= np.std(rewards) b_states.append(np.array(states_history)) b_actions.append(np.array(actions_history)) b_rewards.append(np.array(rewards)) b_old_p.append(np.array(old_prob)) states_history = [] actions_history = [] rewards_history = [] old_prob = [] if (episode_n % self.ep2save == 0 and episode_n > 1000): self.saver.save(self.sess, os.path.join(self.model_dir, 'ppo2_net.ckpt'), global_step=episode_n) if episode_n % self.batch_episodes == 0: for _ in range(UPDATE_TIMES): print('Update parameters No.{} time at No.{} Episodes'.format(_+1, episode_n)) for b in range(self.batch_episodes): self.update(b_states[b], b_actions[b], b_rewards[b], b_old_p[b]) b_states = [] b_actions = [] b_rewards = [] b_old_p = [] def discount_rewards(self, rewards, discount_factor): discounted_rewards = np.zeros_like(rewards) for t in range(len(rewards)): discounted_reward_sum = 0 discount = 1 for k in range(t, len(rewards)): discounted_reward_sum += rewards[k] * discount discount *= discount_factor if rewards[k] != 0: # Don't count rewards from subsequent rounds break discounted_rewards[t] = discounted_reward_sum return np.reshape(discounted_rewards, [-1,1]) def update(self, states, actions, rewards, old_prob): print('\tUpdate with {} (states, actions, rewards)'.format(len(actions))) states = states.reshape(-1,6400) actions = actions.reshape(-1,1) rewards = rewards.reshape(-1,1) old_prob = old_prob.reshape(-1,1) feed_dict = { self.states: states, self.sampled_actions: actions, self.advantage: rewards, self.old_pred: old_prob } self.sess.run(self.train_op, feed_dict) def make_action(self, observation, test=True): """ Return predicted action of your agent Input: observation: np.array current RGB screen of game, shape: (210, 160, 3) Return: action: int the predicted action from trained model """ ################## # YOUR CODE HERE # ################## if self.observation_memory == []: init_observation = prepro(observation) action = self.env.get_random_action() second_observation, _, _, _ = self.env.step(action) second_observation = prepro(second_observation) residual = second_observation - init_observation self.observation_memory = second_observation else: observation = prepro(observation) residual = observation - self.observation_memory self.observation_memory = observation up_prob = self.forward_pass(self.prob, residual)[0] if up_prob > 0.5: action = UP_ACTION else: action = DOWN_ACTION return action
Python
UTF-8
517
2.953125
3
[ "MIT" ]
permissive
import hashlib, sys, glob, argparse import os def read_txt(fname): f = open(fname, 'r') content = f.readlines() print(content) return content def sha1(fname): sha1hash = hashlib.sha1() with open(fname,errors='ignore') as handle: #opening the file one line at a time for memory considerations for line in handle: sha1hash.update(line.encode('utf-8')) return(sha1hash.hexdigest()) def look_files(path): list_files = glob.glob(path+"\*") return list_files
Markdown
UTF-8
12,789
2.78125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "Другие конструкции в регулярных выражениях | Microsoft Docs" ms.custom: "" ms.date: "03/30/2017" ms.prod: ".net" ms.reviewer: "" ms.suite: "" ms.technology: - "dotnet-standard" ms.tgt_pltfrm: "" ms.topic: "article" helpviewer_keywords: - "регулярные выражения .NET Framework, прочие конструкции" - "конструкции, прочее" - "регулярные выражения, прочие конструкции" ms.assetid: 7d10d11f-680f-4721-b047-fb136316b4cd caps.latest.revision: 9 author: "rpetrusha" ms.author: "ronpet" manager: "wpickett" caps.handback.revision: 9 --- # Другие конструкции в регулярных выражениях Регулярные выражения в платформе .NET Framework включают три различные языковые конструкции. Позволяет включить или отключить определенные параметры соответствия в середине шаблона регулярного выражения. Оставшиеся два позволяют включить примечания в регулярное выражение. ## Встроенные параметры Задать или отключить конкретные параметры сопоставления шаблонов для части регулярного выражения можно с помощью синтаксиса ``` (?imnsx-imnsx) ``` Список параметров, которые нужно включить, приводится после вопросительного знака, а параметры, которые требуется отключить, перечисляются после знака "минус". В таблице ниже представлено описание каждого из этих параметров. Дополнительные сведения о каждом параметре см. в разделе [Параметры регулярных выражений](../../../docs/standard/base-types/regular-expression-options.md). |Команда|Описание| |-------------|--------------| |`i`|Соответствие без учета регистра.| |`m`|Многострочный режим.| |`n`|Только явные захваты. \(Скобки не действуют как захватываемые группы.\)| |`s`|Однострочный режим.| |`x`|Игнорировать не преобразованные в escape\-последовательность пробелы и разрешить комментарии в режиме x.| Любое изменение параметров регулярных выражений, заданное конструкцией `(?imnsx-imnsx)`, остается в силе до конца содержащей группы. > [!NOTE] > Конструкция группировки `(?imnsx-imnsx:`*subexpression*`)` предоставляет части выражения одинаковые функциональные возможности. Для получения дополнительной информации см. [Конструкции группирования](../../../docs/standard/base-types/grouping-constructs-in-regular-expressions.md). В следующем примере параметры `i`, `n` и `x` используются для отключения чувствительности к регистру символов и включения явных захватов, чтобы игнорировать пробелы в шаблоне регулярного выражения в его середине. [!code-csharp[RegularExpressions.Language.Miscellaneous#1](../../../samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous1.cs#1)] [!code-vb[RegularExpressions.Language.Miscellaneous#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/regularexpressions.language.miscellaneous/vb/miscellaneous1.vb#1)] В примере определяются два регулярных выражения. Первый, `\b(D\w+)\s(d\w+)\b`, выделяет два последовательных слова, начинающиеся со строчной буквы d и прописной буквы D. Второе регулярное выражение `\b(D\w+)(?ixn) \s (d\w+) \b` использует встроенные параметры для изменения этого шаблона, как описано в следующей таблице. Сравнение результатов подтверждает влияние конструкции `(?ixn)`. |Шаблон|Описание| |------------|--------------| |`\b`|Начало на границе слова.| |`(D\w+)`|Выделяет прописную букву "D" c одной или несколькими последующими буквами. Это первая группа записи.| |`(?ixn)`|С этого момента делайте сравнения без учета регистра, делайте только явные захваты и игнорируйте пробелы в шаблоне регулярного выражения.| |`\s`|Соответствует пробелу.| |`(d\w+)`|Выделяет прописную или строчную букву "d", за которой следует один или несколько букв. Эта группа не записывается, поскольку включен параметр `n` \(явная запись\).| |`\b`|Соответствует границе слова.| ## Встроенное примечание Конструкция `(?#` *comment*`)` позволяет включить встроенные комментарии в регулярное выражение. Обработчик регулярных выражений не использует какую\-либо часть комментария при выделении шаблонов, хотя комментарий включается в строку, которая возвращается методом <xref:System.Text.RegularExpressions.Regex.ToString%2A?displayProperty=fullName>. Примечание заканчивается первой закрывающей скобкой. В следующем примере повторяется первый шаблон регулярного выражения из примера, указанного в предыдущем разделе. В регулярное выражение добавляются два встроенных комментария, чтобы указать, учитывается ли в сравнении регистр. Шаблон регулярного выражения `\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b` определяется следующим образом. |Шаблон|Описание| |------------|--------------| |`\b`|Начало на границе слова.| |`(?# case-sensitive comparison)`|Комментарий. Не влияет на алгоритм выделения шаблона.| |`(D\w+)`|Выделяет прописную букву "D" c одной или несколькими последующими буквами. Это первая группа записи.| |`\s`|Соответствует пробелу.| |`(?ixn)`|С этого момента делайте сравнения без учета регистра, делайте только явные захваты и игнорируйте пробелы в шаблоне регулярного выражения.| |`(?#case-insensitive comparison)`|Комментарий. Не влияет на алгоритм выделения шаблона.| |`(d\w+)`|Выделяет прописную или строчную букву "d", за которой следует один или несколько букв. Это вторая группа записи.| |`\b`|Соответствует границе слова.| [!code-csharp[RegularExpressions.Language.Miscellaneous#2](../../../samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous2.cs#2)] [!code-vb[RegularExpressions.Language.Miscellaneous#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/regularexpressions.language.miscellaneous/vb/miscellaneous2.vb#2)] ## Комментарий в конце строки. Знак номера \(`#`\) помечает комментарий режима x, который начинается символом \#, не преобразованным в escape\-последовательность, в конце шаблона регулярного выражения и продолжается до конца строки. Для использования этой конструкции следует включить параметр `x` \(во встроенных параметрах\) или передать значение <xref:System.Text.RegularExpressions.RegexOptions?displayProperty=fullName> в параметр `option` при создании экземпляра <xref:System.Text.RegularExpressions.Regex> или вызове статического метода <xref:System.Text.RegularExpressions.Regex>. В следующем примере показана конструкция комментария в конце строки. Определяет, является ли строка составного форматирования строкой, которая включает по крайней мере один элемент формата. В следующей таблице описаны конструкции шаблона регулярного выражения. `\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.` |Шаблон|Описание| |------------|--------------| |`\{`|Совпадает с открывающей фигурной скобкой.| |`\d+`|Совпадение с одной или несколькими десятичными цифрами.| |`(,-*\d+)*`|Выделить ноль или одно вхождение запятой, за которой следует минус \(необязательно\), за которым идет одна или несколько десятичных цифр.| |`(\:\w{1,4}?)*`|Выделить ноль или одно вхождение двоеточие, за которым следуют как можно меньшее число символов пробела \(от одного до четырех\).| |`(?#case insensitive comparison)`|Встроенное примечание. Не влияет на алгоритм выделения шаблона.| |`\}`|Выделяет закрывающую фигурную скобку.| |`(?x)`|Включите игнорирование параметра пробела шаблона, чтобы распознавался комментарий в конце строки.| |`# Looks for a composite format item.`|Конец строки комментария.| [!code-csharp[RegularExpressions.Language.Miscellaneous#3](../../../samples/snippets/csharp/VS_Snippets_CLR/regularexpressions.language.miscellaneous/cs/miscellaneous3.cs#3)] [!code-vb[RegularExpressions.Language.Miscellaneous#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/regularexpressions.language.miscellaneous/vb/miscellaneous3.vb#3)] Обратите внимание, что вместо предоставления конструкции `(?x)` в регулярном выражении комментарий также можно распознать путем вызова метода <xref:System.Text.RegularExpressions.Regex.IsMatch%28System.String%2CSystem.String%2CSystem.Text.RegularExpressions.RegexOptions%29?displayProperty=fullName> и передачи ему значения перечисления <xref:System.Text.RegularExpressions.RegexOptions?displayProperty=fullName>. ## См. также [Элементы языка регулярных выражений — краткий справочник](../../../docs/standard/base-types/regular-expression-language-quick-reference.md)
Python
UTF-8
9,199
3.078125
3
[ "MIT" ]
permissive
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import pdb class MagnetLoss(nn.Module): """ Magnet loss technique presented in the paper: ''Metric Learning with Adaptive Density Discrimination'' by Oren Rippel, Manohar Paluri, Piotr Dollar, Lubomir Bourdev in https://research.fb.com/wp-content/uploads/2016/05/metric-learning-with-adaptive-density-discrimination.pdf? Args: r: A batch of features. classes: Class labels for each example. clusters: Cluster labels for each example. cluster_classes: Class label for each cluster. n_clusters: Total number of clusters. alpha: The cluster separation gap hyperparameter. Returns: total_loss: The total magnet loss for the batch. losses: The loss for each example in the batch. """ def __init__(self, alpha=1.0, epsilon=1e-8): super(MagnetLoss, self).__init__() self.alpha = alpha self.epsilon = epsilon def forward(self, r, classes, assigned_clusters): # This is the STOCHASTIC APPROXIMATION to the loss of the paper # 'within_batch_classes' need not be the actual classes. They are just # arbitrary IDs that say, in the batch of features, r, which examples # correspond to the same class # Need to compute the centroids we can from the representations passed # Take cluster means within the batch # r.shape == [batch_size, emb_dimension] # This line breaks r into groups belonging to the same cluster lengths, unique_clusts = compute_partition(assigned_clusters) cluster_examples = torch.split(r, lengths) # cluster_examples[i].shape == [num of instances sampled for ith cluster, emb_dimension] # By taking the mean of each entry in cluster_examples # we get the center of mass of each cluster cluster_means = torch.stack([torch.mean(x, dim=0) for x in cluster_examples]) # cluster_means.shape == [m (clusters sampled), emb_dimension] # Compute distance from all instances to all clusters sample_costs = torch.cdist(r, cluster_means, p=2)**2 # sample_costs.shape == [batch_size, self.tot_clusters] clusters_tensor = torch.from_numpy(assigned_clusters).to(r.device) n_clusters_tensor = torch.from_numpy(unique_clusts).to(r.device) # Kind-of binary mask that states, for each instance, the cluster it belongs to intra_cluster_mask = comparison_mask(clusters_tensor, n_clusters_tensor) # (Squared) Distance from each instance to its own cluster # intra_cluster_costs.shape == [batch_size] intra_cluster_costs = torch.sum(intra_cluster_mask * sample_costs, dim=1) # This is the batch size N = r.size(0) # Average variance (mean of the variances of the points to their corresponding mean) # variance is a SCALAR! variance = torch.sum(intra_cluster_costs) / float(N - 1) var_normalizer = -1 / (2 * variance) # Compute numerator # numerator.shape == [batch_size] numerator = torch.exp(var_normalizer * intra_cluster_costs - self.alpha) # Get the class for each cluster # like [4, 0, 1, 2, 3, 5, 5, 6, 7, 8, 9, 8] (12 clusters here) cluster_classes = torch.from_numpy(classes[np.cumsum(lengths)-1]).to(r.device) # The classes for each instance classes = torch.from_numpy(classes).to(r.device) # Compute denominator (compare in terms of class -- not cluster) # diff_class_mask.shape == [batch_size, n_clusters] equal_class_mask = comparison_mask(classes, cluster_classes) # diff_class_mask says, for each instance, which clusters are # of a different class than that of the instance diff_class_mask = torch.logical_not(equal_class_mask) # logical not denom_sample_costs = torch.exp(var_normalizer * sample_costs) denominator = torch.sum(diff_class_mask * denom_sample_costs, dim=1) # Compute main term. losses.shape == [batch_size] losses = torch.relu(-torch.log(numerator / (denominator + self.epsilon) + self.epsilon)) # Compute the mean (Eq. 5) total_loss = torch.mean(losses) return total_loss, losses, variance def compute_total_loss(self, r, labels, magnet_data, variance=None): centroids = magnet_data['cluster_centers'] centroid_classes = magnet_data['cluster_classes'] # centroids.shape == [k*c, emb_dim] # where k = num of clusters per class # and c = num of classes # the first k clusters belong to label 0, the # second k to label 1 and so on # for each instance in r we must find the closest # centroid OF ITS OWN CLASS # Compute assignments # r.shape == [num_samples, emb_dim] # centroids.shape == [num_centroids (classes*args.k), emb_dim] # sq_dists.shape == [r.size(0) (batch_size), num_centroids] sq_dists = torch.cdist(r, centroids, p=2)**2 # Check, for each instance, the centroids that are of its same class labels = labels.to(r.device) where_same_class = comparison_mask(labels, centroid_classes) # Extract those distance (view to make them of appropiate size) # dists_to_same_class_clust.shape == [r.size(0), num_cluster per class] dists_to_same_class_clust = sq_dists[where_same_class].view(r.size(0), -1) dist_to_assigned_clust, assigned_cluster_ind = dists_to_same_class_clust.min(dim=1) N = r.size(0) # Compute index of the assigned cluster for each instance clust_inds = torch.arange(centroid_classes.size(0), device=r.device).unsqueeze(0) clust_inds = clust_inds.expand(where_same_class.size(0), clust_inds.size(1)) clust_inds = clust_inds[where_same_class].view(r.size(0), -1) # These are the indices of the clusters to which each instance belongs assigned_cluster_ind = assigned_cluster_ind.unsqueeze(1) clust_inds = torch.gather(clust_inds, dim=1, index=assigned_cluster_ind).squeeze() # If the variance was not given, compute it if variance is None: assert N != 1, 'Number of samples must be != 1 for variance computation' variance = dist_to_assigned_clust.sum() / float(N - 1) # Expand so that dimensions are consistent when computing individual variances variance = variance.unsqueeze(0).expand(centroids.size(0)) # this is equivalent to having all the clusters with the SAME variance variance = variance.detach() # # Compute numerator var_normalizer = -1 / (2 * variance) assigned_clust_var_normalizer = torch.gather(var_normalizer, dim=0, index=clust_inds) numerator = torch.exp(assigned_clust_var_normalizer * dist_to_assigned_clust - self.alpha) # numerator.shape == [batch_size] # # Compute denominator # Check which clusters are from OTHER CLASSES num_centroids = centroids.size(0) repeated_classes = centroid_classes.unsqueeze(0).expand(N, num_centroids) labels = labels.unsqueeze(1).expand(N, num_centroids).to(repeated_classes.device) other_class_mask = labels != repeated_classes denominator_terms = torch.exp(var_normalizer.unsqueeze(0) * (other_class_mask * sq_dists)) denominator = torch.sum(denominator_terms, dim=1) # Compute loss losses = torch.relu(-torch.log(numerator / (denominator + self.epsilon) + self.epsilon)) return losses.mean(), variance def expand_dims(var, dim=0): """ Is similar to [numpy.expand_dims](https://docs.scipy.org/doc/numpy/reference/generated/numpy.expand_dims.html). var = torch.range(0, 9).view(-1, 2) torch.expand_dims(var, 0).size() # (1, 5, 2) """ sizes = list(var.size()) sizes.insert(dim, 1) return var.view(*sizes) def comparison_mask(a_labels, b_labels): """Computes boolean mask for distance comparisons""" return torch.eq(expand_dims(a_labels, 1), expand_dims(b_labels, 0)) def dynamic_partition(X, n_clusters): """Partitions the data into the number of cluster bins""" cluster_bin = torch.chunk(X, n_clusters) return cluster_bin def compute_partition(clust_assigns): # clust_assign is something like # Y == np.array([4,6,6,6,7,7,1]) where_change = np.nonzero(np.diff(clust_assigns))[0] # where_change = np.nonzero(np.diff(Y))[0] == array([0, 3, 5]) # add index for last group -> array([0, 3, 5, 6]) where_change = np.append(where_change, len(clust_assigns)-1) # extract unique clusters unique_clusts = clust_assigns[where_change] # add index for first group -> array([-1, 0, 3, 5, 6]) where_change = np.append(-1, where_change) # compute lengths -> array([1, 3, 2, 1]) lengths = np.diff(where_change) return lengths.tolist(), unique_clusts def compute_euclidean_distance(x, y): return torch.sum((x - y)**2, dim=2)
Python
UTF-8
1,698
3.265625
3
[]
no_license
global stackEnd; global stackDataLength; stackEnd = 8; stackDataLength = 4; class Stack: def __init__(self,items): self.items = items #items = [[itemSize, item], [itemSize, ...] ...] def error_check(self): for i in range(0,len(self.items)): #returns error message if error encountered, otherwise returns if (self.items[i][0] * 8) < self.items[i][1].bit_length(): return("".join(("Invalid object length in stack object " , '<%s.%s object at %s>' % ( self.__class__.__module__, self.__class__.__name__, hex(id(self))), " at index " , str(i) , ". Length given is " , str(self.items[i][0]), " bytes. Length of item is ", str((self.items[i][1].bit_length() + (self.items[i][1].bit_length() % 8)) // 8), " bytes."))) return None def hex_to_stack(hexinput): if type(hexinput) == str: newStack = [] index = 0 while 1: dataLength = int("0x" + hexinput[index:index + (stackDataLength * 2)],16) newStack.append([int("0x" + hexinput[index:index + (stackDataLength * 2)],16),int("0x" + hexinput[index + (stackDataLength * 2):index + (stackDataLength * 2) + (2 * dataLength)],16)]) index += (dataLength * 2) + (stackDataLength * 2) if hexinput[index:index + (stackEnd * 2)] == "00" * stackEnd: break return Stack(newStack) else: raise NotImplementedError("Invalid type given to create a instance of the Stack class.")
Java
UTF-8
849
2.71875
3
[]
no_license
package com.dkit.oopca5.core; import java.time.LocalDate; public class Student { private int caoNumber; private String dateOfBirth; private String password; public Student(int caoNumber, String dateOfBirth, String password) { this.caoNumber = caoNumber; this.dateOfBirth = dateOfBirth; this.password = password; } public int getCaoNumber() { return caoNumber; } public void setCaoNumber(int caoNumber) { this.caoNumber = caoNumber; } public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Java
UTF-8
1,836
2.65625
3
[]
no_license
package br.edu.infnet.dominio; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; public class Time { private ArrayList<Profissional> profissionais; private Confederacao confederacao; private String nome; private String nacionalidade; private boolean ligaProfissional; private LocalDateTime data; public Time() { data = LocalDateTime.now(); } public Time(String nome) { this(); this.nome = nome; } @Override public String toString() { DateTimeFormatter formato = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"); return String.format("%s; %s; %b; %s; %s", this.getNome(), this.getNacionalidade(), this.isLigaProfissional() ? "S" : "N", this.data.format(formato), this.confederacao.toString() ); } public ArrayList<Profissional> getProfissionais() { return profissionais; } public void setProfissionais(ArrayList<Profissional> profissionais) { this.profissionais = profissionais; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getNacionalidade() { return nacionalidade; } public void setNacionalidade(String nacionalidade) { this.nacionalidade = nacionalidade; } public boolean isLigaProfissional() { return ligaProfissional; } public void setLigaProfissional(boolean ligaProfissional) { this.ligaProfissional = ligaProfissional; } public Confederacao getConfederacao() { return confederacao; } public void setConfederacao(Confederacao confederacao) { this.confederacao = confederacao; } public void adicionaProfissional(Profissional profissional) { profissionais.add(profissional); } public void adicionaProfissional(ArrayList<Profissional> profissional) { profissionais.addAll(profissional); } }
Markdown
UTF-8
7,057
2.671875
3
[]
no_license
# Block Generation FAQ This article describes possible solutions for the issues that can happen during block generation. ## My node is running but it does not generate blocks **Question**: My node is running fine (appending microblocks) and the block height signatures compared with [wavesexplorer.com](https://wavesexplorer.com/) are correct which indicates that the node is not on fork. Suddenly the node failed to generate blocks. The `waves.log` contains messages indicating that the node will try to generate block in xxx seconds (`Next attempt for acc=<your_node_address> in <xxx> seconds`) but the generating does not actually happen. What can I do? **Answer**: Your node may fail to generate blocks because the block generation process is probabilistic. Such log messages (`Next attempt for acc=<your_node_address> in <xxx> seconds`) indicate that your node scheduled generating blocks according to [LPoS](/en/blockchain/glossary#lpos) formula after the last key block is received. However, there is always a chance that another node had scheduled to generate the block at earlier time. You can use [wavesexplorer.com](https://wavesexplorer.com/) website to check the actual generation timestamp and the ID of the node that succeeded (was the first one) to generate a block. The chances of a node to generate next block are proportional to the share of WAVES belonging or staked to the node. **Note**: You can use [dev.pywaves.org](https://dev.pywaves.org/) website to review block generators performance ratio (Performance ratio = Generated blocks / Estimated blocks). Please keep in mind that short-term (daily) estimates are for reference only. **Example**: At 11:59:20 your node planned an attempt to generate block at 12:00:05, but when you check at [wavesexplorer.com](https://wavesexplorer.com/), you see that another node generated block at 12:00:03. You can find the records of your node generating attempts and check what node actually succeeded to generate a block in your `waves.log` file. If your node is installed from Deb package by default the log file is located in `/var/log/waves/` folder in other cases `${waves.directory}/logs/`. For more details about node logging, see [Logging Configuration](/en/waves-node/logging-configuration) article. To find the records with generating attempts in `waves.log` file, execute the following grep command: **Note**: By default the log files can be read only by the user running the node. ```bash sudo grep "Next attempt\|Forging\| Block(" /var/log/waves/waves.log ``` **Response example with unsuccessful attempt**: ```bash 2020-09-07 10:27:55,076 DEBUG [appender-52] c.w.mining.MinerImpl - Next attempt for acc=3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N in 508.710 seconds 2020-09-07 10:27:55,147 DEBUG [ecution-context-global-48] c.w.s.a.BlockAppender$ - [2ecdf572 134.209.30.86:56992] Appended Block(DeB2bwPeJkpDMpLEvHm8MRg3axpYtwupMZi5uRigrLZo,CPX3P6rvYttUhUFtM2MTHdJ4AALFyfdfDey5oH9CGJXP,3PJEPHsDNtfDRxxaja8wEp3mCXp5kpLYsLS,1599474474614,[]) 2020-09-07 10:29:50,072 DEBUG [appender-52] c.w.mining.MinerImpl - Next attempt for acc=3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N in 457.722 seconds 2020-09-07 10:29:50,161 DEBUG [ecution-context-global-48] c.w.s.a.BlockAppender$ - [7895562c 173.249.1.184:60940] Appended Block(2fXUoLdh4XmDkuTfdZ7bPyvubBfEdhQ989X5P27nbHby,8hs8fTy52sJyzJwxMb75A38JAxsEPjycMTyfCbbrW9XB,3PEFQiFMLm1gTVjPdfCErG8mTHRcH2ATaWa,1599474589929,[],600000000) ``` This example response indicates that the node `3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N` received block `DeB2bwPeJkpDMpLEvHm8MRg3axpYtwupMZi5uRigrLZo` and at `2020-09-07 10:27:55,076` the node planned an attempt to generate the next block in `508.710` seconds (~ at 10:34:23). The response also says that the processing of block `DeB2bwPeJkpDMpLEvHm8MRg3axpYtwupMZi5uRigrLZo` is complete and then the node received the next validated block `2fXUoLdh4XmDkuTfdZ7bPyvubBfEdhQ989X5P27nbHby` generated by `3PEFQiFMLm1gTVjPdfCErG8mTHRcH2ATaWa` node at `2020-09-07 10:29:50,072` (earlier than the node `3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N` planned generating the next block). In this case the node `3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N` did not succeed to generate new block at 10:34:23 because the new block was generated earlier by another node `3PEFQiFMLm1gTVjPdfCErG8mTHRcH2ATaWa`. **Response example with successful attempt**: ```bash 2020-09-06 04:06:13,517 DEBUG [appender-52] c.w.mining.MinerImpl - Next attempt for acc=3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N in 41.305 seconds 2020-09-06 04:06:13,556 DEBUG [ecution-context-global-48] c.w.s.a.BlockAppender$ - [560c392d 5.189.182.6:52504] Appended Block(3bQwytTjwQCkQs2DWuoR5oqNKFtjAyDSftHQXrW2ALLQ29MpVBuX96231JW9joTGsYbbuyHaEuhrfUVvgFxdnJBs,2rTRaJqMrp2L3HvUfJ4FRQQGZGPM23kHVdhy1pAQucHLAvyG7QEHy6mMw9MfV7cjf7r2BDWYeyv7Eih3Uz83yVog,3P2HNUd5VUPLMQkJmctTPEeeHumiPN2GkTb,1599365173456,[],600000000) 2020-09-06 04:06:54,829 DEBUG [block-miner-35] c.w.mining.MinerImpl - Forging with <3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N>, Time 41369 > Estimated Time 41361, balance 3485157657499, prev block 2qNW6zpp419atqZbstbwnAijUAmk55ggWiSvFLu6eDDSMuMciMta9f8aNXWh1HybQe2i2R2KwMcRrhHwd8by2Ya7 at 2228616 with target 61 2020-09-06 04:06:54,842 DEBUG [appender-52] c.w.mining.MinerImpl - Next attempt for acc=3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N in 412.766 seconds 2020-09-06 04:06:54,887 DEBUG [block-miner-35] c.w.mining.MinerImpl - Forged and applied Block(5sWqTZbHP2p5T1ss31FnGx4s48an8Uf1czTbcHrkBwomRnN9j4HU9zw4Y7YvB1yWeHx3a17up3rF8397Upmbdntm,2qNW6zpp419atqZbstbwnAijUAmk55ggWiSvFLu6eDDSMuMciMta9f8aNXWh1HybQe2i2R2KwMcRrhHwd8by2Ya7,<3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N>,1599365214825,[],2000000000) with cumulative score 525712542186004822512224 ``` This example response indicates that at `2020-09-06 04:06:13,517` the node `3PMj3yGPBEa1Sx9X4TBAFeJCMMaE3wvKR4N` planned to generate block in `41.305` seconds and then in `41.305` seconds it started generating block and succeeded (`Forged and applied Block 5sWqTZbHP2p5T1ss31FnGx4s48an8Uf1czTbcHrkBwomRnN9j4HU9zw4Y7YvB1yWeHx3a17up3rF8397Upmbdntm`). In some cases, a block can be successfully generated by your node and that is indicated in the log, however that does not guarantee that the block will be accepted by the blockchain. There is a chance that another node generated new block simultaneously with yours and sent it to the blockchain faster. To avoid this, use fast internet connection and up-to-date hardware that suits node system requirements. Use [wavesexplorer.com](https://wavesexplorer.com/) website to check block generation timestamps and the IDs of the nodes that succeeded to finally generate blocks that have been added to the blockchain. **Note**: Failure to generate blocks may also be caused by problems with you wallet or node configuration. In this case the `Next attempt acc=...` messages will have wrong address (`acc=`). ## Other Issues If you have other node-related issues to report or discuss with Waves community, see [Keep in Touch](/en/keep-in-touch/) chapter for contact information.
Java
UTF-8
6,967
2
2
[ "Apache-2.0" ]
permissive
package com.xd.demi.view; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.animation.LinearInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.xd.demi.R; import com.xd.demi.utils.ViewSizeChangeAnimation; /** * Created by demi on 2019/1/30 下午3:15. */ public class PercentView extends LinearLayout { private static int LEFT_HEAD = 0; private static int CENTER_HEAD = 1; private static int RIGHT_HEAD = 2; private int leftHead = 60; private int rightHead = 40; private int centerHead; private int flagMax = LEFT_HEAD; private RelativeLayout center_rl; private FrameLayout left_fr; private FrameLayout right_fr; private ImageView left_iv; private ImageView right_iv; private ImageView center_iv_left; private ImageView center_iv_right; private ObjectAnimator animatorL; private ObjectAnimator animatorR; private ObjectAnimator animatorCL; private ObjectAnimator animatorCR; public PercentView(Context context) { super(context); init(context); } public PercentView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public PercentView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { View view = inflate(context, R.layout.view_percent, this); left_fr = view.findViewById(R.id.left_fr); left_iv = view.findViewById(R.id.left_iv); right_fr = view.findViewById(R.id.right_fr); right_iv = view.findViewById(R.id.right_iv); center_rl = view.findViewById(R.id.center_rl); center_iv_left = view.findViewById(R.id.center_iv_left); center_iv_right = view.findViewById(R.id.center_iv_right); confirmFlagMax(); setArrowAnimator(); setPercentMoveAnimator(); } public void startLeftGunDong() { if (animatorL != null && animatorL.isRunning()) { return; } PropertyValuesHolder xholder = PropertyValuesHolder.ofInt("scrollX", 0, -220); animatorL = ObjectAnimator.ofPropertyValuesHolder(left_iv, xholder); setAnimatorProperty(animatorL); animatorL.start(); } public void startRightGunDong() { if (animatorR != null && animatorR.isRunning()) { return; } PropertyValuesHolder xholder = PropertyValuesHolder.ofInt("scrollX", 0, 220); animatorR = ObjectAnimator.ofPropertyValuesHolder(right_iv, xholder); setAnimatorProperty(animatorR); animatorR.start(); } public void startCenterGunDong() { if (animatorCL != null && animatorCL.isRunning()) { return; } PropertyValuesHolder xLeftholder = PropertyValuesHolder.ofInt("scrollX", 0, 220); PropertyValuesHolder xRightholder = PropertyValuesHolder.ofInt("scrollX", 0, -220); animatorCL = ObjectAnimator.ofPropertyValuesHolder(center_iv_left, xLeftholder); animatorCR = ObjectAnimator.ofPropertyValuesHolder(center_iv_right, xRightholder); setAnimatorProperty(animatorCL); setAnimatorProperty(animatorCR); animatorCL.start(); animatorCR.start(); } private void setAnimatorProperty(ObjectAnimator animator) { animator.setRepeatCount(ValueAnimator.INFINITE); animator.setRepeatMode(ValueAnimator.RESTART); animator.setDuration(4000); animator.setInterpolator(new LinearInterpolator()); } private void clearLeftGunDong(){ if(animatorL != null){ animatorL.cancel(); } } private void clearRightGunDong(){ if(animatorR != null){ animatorR.cancel(); } } private void clearCenterGunDong(){ if(animatorCL != null){ animatorCL.cancel(); } if(animatorCR != null){ animatorCR.cancel(); } } public void setPercent(int left, int right) { this.leftHead = left; this.rightHead = right; this.centerHead = 100 - rightHead - leftHead; confirmFlagMax(); setArrowAnimator(); setPercentMoveAnimator(); } public void confirmFlagMax() { int max; if (leftHead > rightHead) { max = leftHead; flagMax = LEFT_HEAD; } else { max = rightHead; flagMax = RIGHT_HEAD; } if (max < centerHead) { flagMax = CENTER_HEAD; } } public void setArrowAnimator() { if (flagMax == LEFT_HEAD) { startLeftGunDong(); clearRightGunDong(); clearCenterGunDong(); left_iv.setVisibility(View.VISIBLE); right_iv.setVisibility(View.GONE); center_iv_left.setVisibility(View.GONE); center_iv_right.setVisibility(View.GONE); } else if (flagMax == RIGHT_HEAD) { startRightGunDong(); clearLeftGunDong(); clearCenterGunDong(); left_iv.setVisibility(View.GONE); right_iv.setVisibility(View.VISIBLE); center_iv_left.setVisibility(View.GONE); center_iv_right.setVisibility(View.GONE); } else { startCenterGunDong(); clearLeftGunDong(); clearRightGunDong(); right_iv.setVisibility(View.GONE); left_iv.setVisibility(View.GONE); center_iv_left.setVisibility(View.VISIBLE); center_iv_right.setVisibility(View.VISIBLE); } } public void setPercentMoveAnimator() { LinearLayout.LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT, leftHead); LinearLayout.LayoutParams cp = new LayoutParams(0, LayoutParams.MATCH_PARENT, centerHead); LinearLayout.LayoutParams rp = new LayoutParams(0, LayoutParams.MATCH_PARENT, rightHead); ViewSizeChangeAnimation animationL = new ViewSizeChangeAnimation(left_fr, (int) (lp.weight / 100 * getWidth())); animationL.setDuration(500); left_fr.startAnimation(animationL); ViewSizeChangeAnimation animationC = new ViewSizeChangeAnimation(center_rl, (int) (cp.weight / 100 * getWidth())); animationC.setDuration(500); center_rl.startAnimation(animationC); ViewSizeChangeAnimation animationR = new ViewSizeChangeAnimation(right_fr, (int) (rp.weight / 100 * getWidth())); animationR.setDuration(500); right_fr.startAnimation(animationR); } }
Markdown
UTF-8
2,876
2.859375
3
[]
no_license
# Tucil4-StrAlgo -- Ekstraksi Informasi dari Artikel Berita dengan Algoritma Pencocokan String Program ini adalah contoh pengaplikasian strategi algoritma Knuth-Morris-Pratt (KMP), Boyer-Moore (BM) dan Regular Expression untuk mengektraksi informasi dari sebuah artikel berita berdasarkan keyword yang dimasukkan ## Instalasi Program Program ini dibuat menggunakan bahasa pemrograman Python oleh karena itu dibutuhkan Python interpreter versi 3.7.4 atau lebih tinggi. Interpreter dapat diunduh melalui https://www.python.org/downloads/release/python-374/ Setelah Python diinstall, lakukan clone pada repository ini, atau download dalam file .zip dan extract ke folder yang diinginkan. ### Prerequisites Sebelum menjalankan program, terdapat library yang harus diunduh dan diinstall melalui Command Prompt agar program bisa berjalan dengan benar. Berikut adalah daftar command untuk menginstall library-library ini dapat menggunakan pip. ``` pip install --upgrade pip pip install virtualenv ``` ### Cara Menjalankan Kode Program Untuk mengompilasi program, buka terminal komputer Anda dan pergi ke directory di mana program disimpan. Kemudian silakan ketikkan perintah seperti di bawah ini: #### Untuk sistem operasi Windows ``` C:\Users\<user>\Documents\Tucil4StrAlgo-13518135> # cd src C:\Users\<user>\Documents\Tucil4StrAlgo-13518135\src> # venv\Scripts\activate (venv) C:\Users\<user>\Documents\Tucil4StrAlgo-13518135\src> # py app.py atau #python3 ``` #### Untuk sistem operasi Linux ```bash home/Tucil4StrAlgo-13518135 $ cd src home/Tucil4StrAlgo-13518135/src $ source env/bin/activate (venv) home/Tucil4StrAlgo-13518135/src $ py app.py atau $ python3 app.py ``` Perintah di atas akan menjalankan sebuah virtual environment yang sudah memuat prerequisite untuk menjalankan program. ## Cara Menggunakan Program Setelah program dijalankan dengan benar, akan muncul beberapa tulisan pada command prompt, contohnya sebagai berikut: ``` * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 820-239-708 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ``` Untuk menjalankan program, diperlukan juga web browser. Silakan mengcopy address localhost yang muncul pada command prompt ke address bar web browser. Kemudian program akan berjalan dan memunculkan tampilan sebagai berikut: ![Tampilan Utama]('tampilanutama.png' "Tampilan Utama") Perlu diingat bahwa program hanya dapat membaca berita paling banyak 4 buah sekaligus karena limitasi program ## Kontributor Program ini dibuat untuk memenuhi salah satu Tugas Kecil IF2211 Strategi Algoritma Teknik Informatika ITB. Adapun pembuat dari program ini adalah: - Gregorius Jovan Kresnadi - 13518135
Python
UTF-8
4,223
2.890625
3
[]
no_license
# -*- coding: Latin-1 -*- # # This file created July 7 2015 by Jim Kornelsen # # 13-Jul-15 JDK "Load" methods don't return a value. # 06-Aug-15 JDK Fixed bug: Don't call setText() unless needed. # 24-Aug-15 JDK Don't need a special copy method for this class. # 18-Dec-15 JDK Added comparison methods. # 11-Feb-16 JDK Option to always change control prop. # 01-Aug-18 JDK Fixed bug: loadUserVar() should not specify if empty user var. """ Operations related to font size defaults and form input. """ import functools import logging DEFAULT_VAL = 12.0 LOWER_LIMIT = 1 UPPER_LIMIT = 99 logger = logging.getLogger("lingt.utils.fontsize") @functools.total_ordering class FontSize: def __init__(self, default=DEFAULT_VAL, propSuffix="", spec=False): """ :param default: may be used when loading new values :param propSuffix: empty, Complex or Asian :param spec: To specify the size on initialization, pass the size as the first parameter and set spec to True. """ self.defaultVal = default self.size = float(default) self.propSuffix = propSuffix self.specified = spec def setPropSuffix(self, newVal): self.propSuffix = newVal def setSize(self, newVal): self.size = newVal def isSpecified(self): """Has a size been specified or is it empty? For example, empty means that no change is needed for Data Conversion. """ return self.specified def changeCtrlProp(self, ctrl, always_change=False): """For dialog controls including labels. Sets the control's font size. :param always_change: true to change even if size is unspecified """ if self.specified or always_change: logger.debug( "set %s.FontHeight %1.1f", ctrl.getModel().Name, self.size) ctrl.getModel().FontHeight = self.size def loadCtrl(self, textctrl): """Load from text control input. Modifies text of control. """ self.loadVal(textctrl.getText()) if self.specified: self.changeCtrlVal(textctrl) def changeCtrlVal(self, textctrl): """ Set value of text control. Useful even if value is unspecified. """ newVal = self.getString() if textctrl.getText() != newVal: logger.debug("ctrl from %r to %r", textctrl.getText(), newVal) textctrl.setText(newVal) def changeElemProp(self, styleObj): """For document elements such as styles and cursors. Sets the element's font size. """ if self.specified: propName = 'CharHeight%s' % self.propSuffix logger.debug("set %s %1.1f", propName, self.size) styleObj.setPropertyValue(propName, self.size) def loadElemProp(self, styleObj): """For document elements such as styles and cursors.""" propName = 'CharHeight%s' % self.propSuffix self.loadVal( styleObj.getPropertyValue(propName)) def loadUserVar(self, userVars, varName): self.loadVal(userVars.get(varName)) def loadVal(self, newVal): """Set size based on the specified value.""" if not newVal: self.size = self.defaultVal self.specified = False return try: self.size = float(newVal) except ValueError: self.size = self.defaultVal if self.size < LOWER_LIMIT or self.size > UPPER_LIMIT: self.size = self.defaultVal self.specified = True def getFloat(self): return self.size def getString(self): if not self.specified: return "" strval = "%1.1f" % self.size if strval.endswith(".0"): strval = strval[:-2] # remove trailing ".0" return strval def attrs(self): """Used for several magic methods below.""" return self.size, self.propSuffix, self.specified def __lt__(self, other): return self.attrs() < other.attrs() def __eq__(self, other): return self.attrs() == other.attrs() def __hash__(self): return hash(self.attrs())
Python
UTF-8
6,234
2.6875
3
[]
no_license
#!/usr/bin/python # # mem-usage.py - detailed process memory statistics. # # Based on mem_usage perl script in public domain by Andy Wingo <wingo@pobox.com> # # 2015 Nelson Yen, Simplified BSD License # import argparse import re # CONSTANTS INODE_NONE = 0 class ProcMaps: # Supported 'keys' all_keys = ('writeable_code', 'data', 'rodata', 'rxdata', 'unreadable', 'anon_unknown', 'anon_shared', 'mapped_exe', 'mapped_wrexe', 'mapped_rodata', 'mapped_rwdata', 'mapped_unreadable', 'mapped_unknown', 'mapped_shared') def __init__(self): self.maps = {} self.keys_anon = [] self.keys_mapped = [] self.DEBUG=False for key in self.all_keys : self.maps[key] = 0 for key in self.all_keys: if key.find('mapped') == 0 : self.keys_mapped.append(key) else : self.keys_anon.append(key) if self.DEBUG : print [elem for elem in self.keys_mapped] print [elem for elem in self.keys_anon] def add_count(self, key, count): assert(key in self.all_keys) self.maps[key] += count def total_anon(self): total = 0 for key in self.keys_anon : if key != 'anon_shared' : total += self.maps[key] return total def total_mapped(self): total = 0 for key in self.keys_mapped: if key != 'mapped_shared' : total += self.maps[key] return total def total(self): total = 0 for key in self.maps: if (key != 'mapped_shared') and (key != 'anon_shared'): total += self.maps[key] return total def print_stats(self): print "Mapped memory:" print " Executable r-x {0:>8} kB".format(self.maps['mapped_exe']) print " Write/Exec (jump tables) rwx {0:>8} kB".format(self.maps['mapped_wrexe']) print " Data rw- {0:>8} kB".format(self.maps['mapped_rwdata']) print " RO data r-- {0:>8} kB".format(self.maps['mapped_rodata']) print " Unreadable --- {0:>8} kB".format(self.maps['mapped_unreadable']) print " Unknown {0:>8} kB".format(self.maps['mapped_unknown']) print print " Shared {0:>8} kB".format(self.maps['mapped_shared']) print " Total {0:>8} kB".format(self.total_mapped()) print print "Anonymous memory (not file backed):" print " Executable r-x {0:>8} kB".format(self.maps['rxdata']) print " Writable code (stack) rwx {0:>8} kB".format(self.maps['writeable_code']) print " Data (malloc, mmap) rw- {0:>8} kB".format(self.maps['data']) print " RO data r-- {0:>8} kB".format(self.maps['rodata']) print " Unreadable --- {0:>8} kB".format(self.maps['unreadable']) print " Unknown {0:>8} kB".format(self.maps['anon_unknown']) print print " Shared {0:>8} kB".format(self.maps['anon_shared']) print " Total {0:>8} kB".format(self.total_anon()) print print "All:" print " Shared {0:>8} kB".format(self.maps['mapped_shared']+self.maps['anon_shared']) print " Total {0:>8} kB".format(self.total()) print # End class ProcMaps def parse_line(line, proc_maps): match = re.search(r'^(\w+)-(\w+) (....) (\w+) (\S+) (\d+) *(.*)$', line); if match: start_addr = int(match.group(1).strip(), 16) end_addr = int(match.group(2).strip(), 16) perms = match.group(3).strip() offset = match.group(4).strip() dev = match.group(5).strip() inode = int(match.group(6).strip()) pathname = match.group(7).strip() # Size in kB vma_size = (end_addr - start_addr) / 1024 # Anonymous, not file mapped if INODE_NONE == inode: if perms.find('rwx') >= 0: proc_maps.add_count('writeable_code', vma_size) pass elif perms.find('rw-') >= 0: proc_maps.add_count('data', vma_size) elif perms.find('r-x') >= 0: proc_maps.add_count('rxdata', vma_size) elif perms.find('r--') >= 0: proc_maps.add_count('rodata', vma_size) elif perms.find('---') >= 0: proc_maps.add_count('unreadable', vma_size) else : proc_maps.add_count('anon_unknown', vma_size) print 'anon_unknown:', line if perms.find('s') >= 0: proc_maps.add_count('anon_shared', vma_size) else : if perms.find('r-x') >= 0: proc_maps.add_count('mapped_exe', vma_size) elif perms.find('rwx') >= 0: proc_maps.add_count('mapped_wrexe', vma_size) elif perms.find('rw-') >= 0: proc_maps.add_count('mapped_rwdata', vma_size) elif perms.find('r--') >= 0: proc_maps.add_count('mapped_rodata', vma_size) elif perms.find('---') >= 0: proc_maps.add_count('mapped_unreadable', vma_size) else : proc_maps.add_count('mapped_unknown', vma_size) print 'mapped_unknown', line if perms.find('s') >= 0: proc_maps.add_count('mapped_shared', vma_size) else : print 'reject: ', line, match.group() def parse_maps_from_pid(pid, proc_maps): fio = open('/proc/'+pid+'/maps', 'r') for line in fio: parse_line(line, proc_maps) def parse_mapsfile(filename, proc_maps): fio = open(filename, 'r') for line in fio: parse_line(line, proc_maps) def main(): parser = argparse.ArgumentParser() # Add mutually exclusive group group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-p", "--pid", help="pid") group.add_argument("-m", "--maps", help="maps file") # Get args args = parser.parse_args() pid = args.pid mapsfile = args.maps # Use ProcMaps to record stats proc_maps_info = ProcMaps() if pid: parse_maps_from_pid(pid, proc_maps_info) elif mapsfile: parse_mapsfile(mapsfile, proc_maps_info) else : print 'bad params' proc_maps_info.print_stats() if __name__ == '__main__': main()
PHP
UTF-8
1,072
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Services\Device; use App\Models\Device; class DeviceService { public function getCreateDevice($request) { return Device::query()->create([ 'name'=>$request->name, 'filial_name'=>$request->filial_name, 'company_id'=>$request->company_id, 'code'=>$request->code, 'cocoa'=>'100', 'coffee'=>'100', 'water'=>'100', 'milk'=>'100', 'status'=>10, 'city_id'=>$request->city_id, 'error_id'=>$request->error_id, 'user_id'=>auth()->user()->id ]); } public function getUpdateDevice($request,$device) { $device->name = $request->name; $device->filial_name = $request->filial_name; $device->company_id = $request->company_id; $device->code = $request->code; $device->cocoa = $request->cocoa; $device->coffee = $request->coffee; $device->water = $request->water; $device->milk = $request->milk; $device->status = $request->status; $device->city_id = $request->city_id; $device->error_id = $request->error_id; $device->user_id = auth()->user()->id; $device->update(); return $device; } }
C
UTF-8
801
3.53125
4
[]
no_license
/************************************************************************* > File Name: 10-max_int.c > Author: chenyueze > Mail: chen_buzhou@163.com > Created Time: 三 9/ 2 20:58:46 2020 ************************************************************************/ #include <stdarg.h> #include <inttypes.h> #include<stdio.h> #define P(func) {\ printf("%s : %d\n", #func, func);\ } int max_int(int n, ...){ int ans = INT32_MIN; int temp; va_list arg; va_start(arg, n); while(n--){ temp = va_arg(arg, int); temp > ans && (ans = temp); } va_end(arg); return ans; } int main(){ P( max_int(4, 1, 2, 3, 4)); P( max_int(3, 17, 21, 4)); P( max_int(2, 31, 24)); P( max_int(5, 11, 42, 63, 34, 24)); P( max_int(4, 4, 3, 2, 1)); return 0; }
Python
UTF-8
4,070
2.859375
3
[]
no_license
import cv2 # working with, mainly resizing, images import numpy as np # dealing with arrays import os # dealing with directories import tflearn # dealing with making CNN model import sys # Package to deal with commandline arguments import tensorflow as tf # dealing with making CNN model from os import listdir # dealing with importing images from os.path import isfile, join from random import shuffle # mixing up or currently ordered data that might lead our network astray in training. from tqdm import tqdm # a nice pretty percentage bar for tasks. from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression ############################################################################ #argList = sys.argv TRAIN_DIR = r'C:\Users\praveen94\Desktop\Emotion_Recognition\train' IMG_SIZE = 48 # Compressing Image Size to 48*48 LR = 5e-4 # Learning Rate MODEL_NAME = 'emotionRecognition-{}-{}.model'.format(LR, 'mymodel') labels = ['AN', 'SA', 'SU', 'HA', 'DI', 'FE', 'NE'] ############################################################################ # A function to extract the softnet(Outputs) def label_img(img): onehot = [0,0,0,0,0,0,0] if labels[0] in str(img): onehot[0] = 1 if labels[1] in str(img): onehot[1] = 1 if labels[2] in str(img): onehot[2] = 1 if labels[3] in str(img): onehot[3] = 1 if labels[4] in str(img): onehot[4] = 1 if labels[5] in str(img): onehot[5] = 1 if labels[6] in str(img): onehot[6] = 1 return onehot ############################################################################ # A function to process the train data def create_train_data(): training_data = [] for img in tqdm(os.listdir(TRAIN_DIR)): label = label_img(img) path = os.path.join(TRAIN_DIR,img) img = cv2.imread(path) img = cv2.resize(img, (IMG_SIZE,IMG_SIZE)) # Resizing the image to 48*48 training_data.append([np.array(img),np.array(label)]) shuffle(training_data) np.save('train_data.npy', training_data) return training_data ############################################################################# # Building the model tf.reset_default_graph() train_data = create_train_data() convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 3], name='input') convnet = conv_2d(convnet, 10, 5, activation='relu') # Convolution Layer-1 with 5 Filters of size 10*10 convnet = max_pool_2d(convnet, 2) # Max Pooling with filter size of 5*5 convnet = conv_2d(convnet, 10, 5, activation='relu') # Convolution Layer-2 with 5 Filters of size 64*64 convnet = max_pool_2d(convnet, 2) # Max pooling with filter size of 5*5 convnet = conv_2d(convnet, 10, 3, activation='relu') # Convolution Layer-3 with 3 Filters of size 32*32 convnet = max_pool_2d(convnet, 2) # Max pooling with filter size of 5*5 convnet = fully_connected(convnet, 256, activation='relu') # Fully Connected Layer-4 with 256 neurons convnet = dropout(convnet, 0.4) # Dropout rate set to 0.4 convnet = fully_connected(convnet, 128, activation='relu') # Fully Connected Layer-4 with 128 neurons convnet = dropout(convnet, 0.4) # Dropout rate set to 0.4 convnet = fully_connected(convnet, 7, activation='softmax') convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets') model = tflearn.DNN(convnet, tensorboard_dir='log') ############################################################################## # Modelling the training data train = train_data X = np.array([i[0] for i in train]) Y = [i[1] for i in train] model.fit({'input': X}, {'targets': Y}, n_epoch=20, snapshot_step=500, show_metric=True, run_id=MODEL_NAME) model.save(MODEL_NAME) ##############################################################################
Java
UTF-8
4,168
1.8125
2
[]
no_license
package ca.uoguelph.socs.uog_mobile.ui.activity; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.Toolbar; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import ca.uoguelph.socs.uog_mobile.R; import ca.uoguelph.socs.uog_mobile.data.web_advisor.WebAdvisorService; import ca.uoguelph.socs.uog_mobile.events.LoggedIn; import ca.uoguelph.socs.uog_mobile.events.RefreshSchedule; import ca.uoguelph.socs.uog_mobile.injection.HasComponent; import ca.uoguelph.socs.uog_mobile.injection.component.DaggerWebAdvisorComponent; import ca.uoguelph.socs.uog_mobile.injection.component.WebAdvisorComponent; import ca.uoguelph.socs.uog_mobile.injection.module.WebAdvisorModule; import ca.uoguelph.socs.uog_mobile.ui.fragment.WebAdvisorLoginFragment; import ca.uoguelph.socs.uog_mobile.ui.fragment.WebAdvisorScheduleFragment; import ca.uoguelph.socs.uog_mobile.util.RxUtils; import javax.inject.Inject; import rx.Subscription; import rx.subscriptions.CompositeSubscription; public class WebAdvisorActivity extends BaseActivity implements HasComponent { @Inject SharedPreferences prefs; @Inject FragmentManager supportFragmentManager; @Bind(R.id.toolbar) Toolbar toolbar; private WebAdvisorComponent webAdvisorComponent; private CompositeSubscription eventSub; private Parcelable user; private Fragment currentFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setSupportActionBar(toolbar); this.initializeInjection(); if (savedInstanceState == null) { user = getIntent().getParcelableExtra("user"); replaceFragment(prefs.contains(WebAdvisorService.SCHEDULE_KEY) ? WebAdvisorScheduleFragment.newInstance() : WebAdvisorLoginFragment.newInstance(user)); } else { user = savedInstanceState.getParcelable("user"); } } @Override protected void onResume() { super.onResume(); eventSub = new CompositeSubscription(); eventSub.add(loggedInSub()); eventSub.add(refreshScheduleSub()); } @Override protected void onPause() { super.onPause(); RxUtils.resetSub(eventSub); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable("user", user); } @Override public Object getComponent() { return this.webAdvisorComponent; } private Subscription refreshScheduleSub() { return bus.observeEvent(RefreshSchedule.class) .subscribe(refresh -> replaceFragment(WebAdvisorLoginFragment.newInstance(user))); } private Subscription loggedInSub() { return bus.observeEvent(LoggedIn.class) .subscribe(loggedIn -> replaceFragment(WebAdvisorScheduleFragment.newInstance())); } private void replaceFragment(Fragment fragment) { FragmentTransaction transaction = supportFragmentManager.beginTransaction(); if (currentFragment != null) { transaction = transaction.remove(currentFragment); } transaction.add(R.id.frag_container, fragment).addToBackStack(null).commit(); currentFragment = fragment; } private void initializeInjection() { webAdvisorComponent = DaggerWebAdvisorComponent.builder() .applicationComponent(getApplicationComponent()) .activityModule(getActivityModule()) .webAdvisorModule(new WebAdvisorModule()) .build(); webAdvisorComponent.inject(this); } }
C++
UTF-8
3,201
3.5625
4
[]
no_license
#include <iostream> #include <cstring> using namespace std; class Node{ public: char* text; Node* next; }; class TextList{ public: Node* head; TextList(){ head = nullptr; }; TextList(const TextList &o1){ Node *tmp = o1.head,*gdzie; head = new Node; size_t size = strlen(tmp->text); head->text = new char[size+1]; memcpy(head->text, tmp->text, size); head->text[size] = '\0'; head->next = nullptr; gdzie=head; tmp=tmp->next; while(tmp != nullptr){ Node * dodaj = new Node; size = strlen(tmp->text); dodaj->text = new char[size+1]; memcpy(dodaj->text, tmp->text, size); dodaj->text[size] = '\0'; dodaj->next= nullptr; gdzie->next = dodaj; gdzie = dodaj; tmp=tmp->next; } } ~TextList(){ if(head!= nullptr) { Node *tmp = head, *nast; while (tmp != nullptr) { nast = tmp->next; delete[] tmp->text; delete tmp; tmp = nast; } head = nullptr; } } void pushBack(const char*t){ if(head == nullptr) { head = new Node; size_t size = strlen(t); head->text = new char[size+1]; memcpy(head->text, t, size); head->text[size] = '\0'; head->next = nullptr; } else { Node *tmp=head; while(tmp->next != nullptr) { tmp=tmp->next; } tmp->next = new Node; tmp=tmp->next; size_t size = strlen(t); tmp->text = new char[size+1]; memcpy(tmp->text, t, size); tmp->text[size] = '\0'; tmp->next = nullptr; } } void show(){ Node *tmp=head; while(tmp != nullptr) { cout << tmp->text << " "; tmp=tmp->next; } } TextList &operator=(const TextList &o1) { if(this==&o1) return *this; (*this).~TextList(); Node *tmp = o1.head,*gdzie; head = new Node; size_t size = strlen(tmp->text); head->text = new char[size+1]; memcpy(head->text, tmp->text, size); head->text[size] = '\0'; head->next = nullptr; gdzie=head; tmp=tmp->next; while(tmp != nullptr){ Node * dodaj = new Node; size = strlen(tmp->text); dodaj->text = new char[size+1]; memcpy(dodaj->text, tmp->text, size); dodaj->text[size] = '\0'; dodaj->next= nullptr; gdzie->next = dodaj; gdzie = dodaj; tmp=tmp->next; } return *this; } }; int main() { TextList o1; o1.pushBack("Robsonikus"); o1.pushBack("Oli"); o1.pushBack("Bobi"); o1.show(); cout << endl; TextList kopia(o1); kopia.pushBack("Rob"); kopia.pushBack("kop"); o1=kopia; o1.show(); }
Java
UHC
1,264
2.890625
3
[]
no_license
package Controller; import java.util.ArrayList; import java.util.Vector; import Entity.RoomInfo; // 濡 ϴ Ʈѷ public class RoomController { public ArrayList<RoomInfo> allRoom(){ return RoomInfo.getRoomList(); } public RoomInfo getRoom(int roomNum){ RoomInfo ri = new RoomInfo(); return ri.getRoom(roomNum); } //  Ǵ ޼ҵ public boolean enterRoom(String id, int roomNum) { RoomInfo ri = new RoomInfo(); return ri.enterRoom(id, roomNum); } // ʿ ޼ҵ public void deleteRoom(int RoomNo) { RoomInfo ri = new RoomInfo(); ri.deleteRoom(RoomNo); } // ߰ϴ ޼ҵ public int addRoom(String roomName, String school, int max) { RoomInfo ri = new RoomInfo(); return ri.addRoom(roomName, school, max); } // Ǵ ޼ҵ public void exitRoom(String id, int roomNum) { RoomInfo ri = new RoomInfo(); ri.exitRoom(id, roomNum); } // ̾ƿ Լ public ArrayList<String> inUser(int roomNum){ RoomInfo ri = new RoomInfo(); return ri.getInUser(roomNum); } public boolean isFull(int roomNum) { RoomInfo ri = new RoomInfo(); return ri.isFull(roomNum); } }
SQL
UTF-8
160
3.625
4
[]
no_license
SELECT Customers.CustomerName, Orders.OrderName FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY CustomerS.CustomerName;
Go
UTF-8
2,465
2.609375
3
[]
no_license
package sqs_test import ( "encoding/json" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" sqsSDK "github.com/aws/aws-sdk-go/service/sqs" "github.com/ngavinsir/golangtraining" "github.com/ngavinsir/golangtraining/internal/sqs" "github.com/pkg/errors" "github.com/stretchr/testify/require" ) func TestPublisherPublish(t *testing.T) { if testing.Short() { t.Skip("Skip the Test for SQS Publisher") } region := "ap-southeast-1" endpoint := "http://localhost:4566/000000000000/payments" queue := "payments" sess, err := session.NewSession(&aws.Config{ Region: &region, Endpoint: &endpoint, }) if err != nil { panic(err) } mockPayment := golangtraining.Payment{ ID: "1", PaymentCode: "code", TransactionID: "1", Name: "name", Amount: "12345", } type resType struct { Res golangtraining.Payment Err error } tests := []struct { desc string publisher *sqs.Publisher msg interface{} expectedRes resType }{ { desc: "publish - success", publisher: func() *sqs.Publisher { p, err := sqs.NewPublisher(sess, queue) if err != nil { panic(err) } return p }(), msg: mockPayment, expectedRes: resType{ Res: mockPayment, Err: nil, }, }, } for _, tC := range tests { t.Run(tC.desc, func(t *testing.T) { _, err = tC.publisher.SQS.PurgeQueue(&sqsSDK.PurgeQueueInput{ QueueUrl: tC.publisher.QueueUrl, }) if err != nil { t.Error(err) } err := tC.publisher.Publish(tC.msg) if tC.expectedRes.Err != nil { require.Equal(t, tC.expectedRes.Err.Error(), errors.Cause(err).Error()) } else { timeout := int64(5) msgResult, err := tC.publisher.SQS.ReceiveMessage(&sqsSDK.ReceiveMessageInput{ AttributeNames: []*string{ aws.String(sqsSDK.MessageSystemAttributeNameSentTimestamp), }, QueueUrl: tC.publisher.QueueUrl, MaxNumberOfMessages: aws.Int64(10), VisibilityTimeout: &timeout, }) if err != nil { t.Error(err) } var msgPayment golangtraining.Payment err = json.Unmarshal([]byte(*msgResult.Messages[0].Body), &msgPayment) if err != nil { t.Error(err) } require.Equal(t, tC.expectedRes.Res, msgPayment) } _, err = tC.publisher.SQS.PurgeQueue(&sqsSDK.PurgeQueueInput{ QueueUrl: tC.publisher.QueueUrl, }) if err != nil { t.Error(err) } }) } }
Python
UTF-8
123
4.15625
4
[]
no_license
def repeater(string, n): repeated = string * n return '"{}" repeated {} times is: "{}"'.format(string, n, repeated)
C++
UTF-8
17,027
2.65625
3
[]
no_license
#include "gamestate.h" #include <SDL_ttf.h> #include "util.h" #include "mazeoflife.h" #include "highscore.h" #include "titlestate.h" #include <fstream> #include "hslist.h" #include <set> #include <bitset> #include <tuple> #include <algorithm> #include <vector> #include <deque> #include <iostream> #include <sstream> #include <list> #include <unordered_map> #include <unordered_set> class GameBoard { public: GameBoard(int level, int playerx, int playery); void tick(int playerx, int playery); void render(SDL_Renderer* renderer, int level) const; bool isObstructed(int x, int y) const; bool operator<(const GameBoard& other) const; using coord = std::tuple<int, int>; private: void initialize(int level); bool solve(int playerx, int playery) const; std::string dump() const; using board_type = std::bitset<WIDTH*HEIGHT>; void incrementIfNeighbor( int x, int y, const board_type& temp, int playerx, int playery, int& tick) const; bool applyNeighbors( int x, int y, const board_type& temp, int playerx, int playery) const; board_type blocks; board_type updateable; int oldx; int oldy; }; class LoadGameState : public State { public: LoadGameState(int level); State* operator() (SDL_Window* window, SDL_Renderer* renderer); private: int level; }; class PlayGameState : public State { public: PlayGameState(int level, GameBoard* board, int playerx, int playery); State* operator() (SDL_Window* window, SDL_Renderer* renderer); private: bool move(int x, int y); int level; GameBoard* board; int playerx; int playery; }; void setRendererAliveColor(SDL_Renderer* renderer, int level) { switch ((level/10)%5) { case 0: SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); break; // Black case 1: SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); break; // Red case 2: SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); break; // Green case 3: SDL_SetRenderDrawColor(renderer, 85, 85, 85, 255); break; // Dark Gray case 4: SDL_SetRenderDrawColor(renderer, 255, 0, 255, 255); break; // Magenta } } void setRendererDeadColor(SDL_Renderer* renderer, int level) { switch ((level/10)%5) { case 0: SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); break; // White case 1: SDL_SetRenderDrawColor(renderer, 255, 192, 203, 255); break; // Pink case 2: SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); break; // Cyan case 3: SDL_SetRenderDrawColor(renderer, 170, 170, 170, 255); break; // Light Gray case 4: SDL_SetRenderDrawColor(renderer, 255, 128, 0, 255); break; // Orange } } void GameBoard::incrementIfNeighbor( int x, int y, const board_type& temp, int playerx, int playery, int& tick) const { int nx = x; int ny = y; wrap(x, y); if (!((nx!=x)&&(ny!=y))) { if ((temp[x+y*WIDTH])||((playerx==x)&&(playery==y))||((x==15)&&(y==15))) { ++tick; } } } State* GameState::operator() (SDL_Window* window, SDL_Renderer* renderer) { return new LoadGameState(0); } LoadGameState::LoadGameState(int m_level) { level = m_level; } State* LoadGameState::operator() (SDL_Window* window, SDL_Renderer* renderer) { char* wintitle = new char[50]; sprintf(wintitle, "Maze Of Life - Level %d", level); SDL_SetWindowTitle(window, wintitle); // Randomly place the player in a corner int playerx, playery; switch (rand()%4) { case 0: playerx = 1; playery = 1; break; case 1: playerx = 1; playery = HEIGHT-2; break; case 2: playerx = WIDTH-2; playery = HEIGHT-2; break; case 3: playerx = WIDTH-2; playery = 1; break; } // Display the level number setRendererDeadColor(renderer, level); SDL_RenderClear(renderer); TTF_Font* font = loadFont(100); SDL_Color fontColor = {0, 0, 0, 0}; char levelnum[8]; sprintf(levelnum, "%d", level); SDL_Surface* dispsurf = TTF_RenderText_Solid(font, levelnum, fontColor); SDL_Texture* disptext = SDL_CreateTextureFromSurface(renderer, dispsurf); SDL_FreeSurface(dispsurf); SDL_Rect pos; SDL_QueryTexture(disptext, NULL, NULL, &pos.w, &pos.h); pos.x = 240-(pos.w/2); pos.y = 240-(pos.h/2); SDL_RenderCopy(renderer, disptext, NULL, &pos); SDL_RenderPresent(renderer); // Do 50 gens of Conway GameBoard* board = new GameBoard(level, playerx, playery); // Wait a bit SDL_Delay(500); // Start the level return new PlayGameState(level, board, playerx, playery); } PlayGameState::PlayGameState(int m_level, GameBoard* m_board, int m_playerx, int m_playery) { level = m_level; board = m_board; playerx = m_playerx; playery = m_playery; } State* PlayGameState::operator() (SDL_Window* window, SDL_Renderer* renderer) { SDL_Event e; for (;;) { // Tick board board->tick(playerx, playery); // Paint board board->render(renderer, level); // Paint event SDL_Rect block; block.w = 16; block.h = 16; block.x = 15*16; block.y = 15*16; SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255); SDL_RenderFillRect(renderer, &block); // Paint player block.x = playerx*16; block.y = playery*16; SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255); SDL_RenderFillRect(renderer, &block); SDL_RenderPresent(renderer); while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { return NULL; } else if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym) { case SDLK_LEFT: if (move(playerx-1, playery)) { return new LoadGameState(level+1); } else { break; } case SDLK_RIGHT: if (move(playerx+1, playery)) { return new LoadGameState(level+1); } else { break; } case SDLK_UP: if (move(playerx, playery-1)) { return new LoadGameState(level+1); } else { break; } case SDLK_DOWN: if (move(playerx, playery+1)) { return new LoadGameState(level+1); } else { break; } case SDLK_ESCAPE: SDL_SetWindowTitle(window, ""); std::ifstream exists(getDataFile()); if (exists) { FILE* hslist = fopen(getDataFile(), "r"); int scores; Highscore* h; fscanf(hslist, "%d%*c", &scores); if (scores < 10) { fclose(hslist); return new EnterHighscoreState(level); } else { for (int i=0; i<scores; i++) { int namelen; char namelens[4]; char* name = (char*) calloc(25, sizeof(char)); int score; fscanf(hslist, "%d", &namelen); sprintf(namelens, "%%%dc", namelen); fscanf(hslist, namelens, name); fscanf(hslist, "%d%*c", &score); h = new Highscore(name, score); } fclose(hslist); if (h->getLevel() < level) { return new EnterHighscoreState(level); } else { return new DisplayAndReturnLocalHighscoreListState(); } } } else { return new EnterHighscoreState(level); } } } } SDL_Delay(5); } } bool PlayGameState::move(int x, int y) { wrap(x, y); // Are we at the event? if ((x==15)&&(y==15)) { return true; } // Can we even go there? if (!board->isObstructed(x,y)) { playerx = x; playery = y; } return false; } GameBoard::GameBoard(int level, int playerx, int playery) { for (;;) { initialize(level); updateable.set(); oldx = playerx; oldy = playery; for (int i=0; i<50; i++) { tick(playerx, playery); } if (solve(playerx, playery)) { break; } else { std::cout << "Impossible board: " << playerx << "," << playery << "," << dump() << std::endl; } } } void GameBoard::tick(int playerx, int playery) { board_type temp {blocks}; board_type tempdateable {updateable}; if ((playerx != oldx) || (playery != oldy)) { for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <=1; dx++) { int tdx = oldx+dx; int tdy = oldy+dy; wrap(tdx, tdy); tempdateable.set(tdx+tdy*WIDTH); tdx = playerx+dx; tdy = playery+dy; wrap(tdx, tdy); tempdateable.set(tdx+tdy*WIDTH); } } } oldx = playerx; oldy = playery; updateable.reset(); for (int y=0;y<HEIGHT;y++) { for (int x=0;x<WIDTH;x++) { if (((x==15)&&(y==15)) || (!tempdateable[x+y*WIDTH])) { continue; } blocks[x+y*WIDTH] = applyNeighbors(x, y, temp, playerx, playery); if (temp[x+y*WIDTH] != blocks[x+y*WIDTH]) { for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <=1; dx++) { int tdx = x+dx; int tdy = y+dy; wrap(tdx, tdy); updateable.set(tdx+tdy*WIDTH); } } } } } } bool GameBoard::applyNeighbors( int x, int y, const board_type& temp, int playerx, int playery) const { int neighbors = 0; incrementIfNeighbor(x-1, y-1, temp, playerx, playery, neighbors); incrementIfNeighbor(x-1, y , temp, playerx, playery, neighbors); incrementIfNeighbor(x-1, y+1, temp, playerx, playery, neighbors); incrementIfNeighbor(x , y-1, temp, playerx, playery, neighbors); incrementIfNeighbor(x , y+1, temp, playerx, playery, neighbors); incrementIfNeighbor(x+1, y-1, temp, playerx, playery, neighbors); incrementIfNeighbor(x+1, y , temp, playerx, playery, neighbors); incrementIfNeighbor(x+1, y+1, temp, playerx, playery, neighbors); if (temp[x+y*WIDTH]) { return ((neighbors >= 1) && (neighbors <= 4)); } else { return (neighbors == 3); } } void GameBoard::render(SDL_Renderer* renderer, int level) const { SDL_Rect block; block.w = 16; block.h = 16; for (int y=0; y<HEIGHT; y++) { for (int x=0; x<WIDTH; x++) { block.x = x*16; block.y = y*16; if (blocks[x+y*WIDTH]) { setRendererAliveColor(renderer, level); } else { setRendererDeadColor(renderer, level); } SDL_RenderFillRect(renderer, &block); } } } bool GameBoard::isObstructed(int x, int y) const { return blocks[x+y*WIDTH] || (x == 15 && y == 15); } void GameBoard::initialize(int level) { for (int y=0; y<HEIGHT; y++) { for (int x=0; x<WIDTH; x++) { blocks[x+y*WIDTH] = false; switch (level/10+1) { case 1: if ((x>13)&&(x<17)&&(y>13)&&(y<17)) { blocks[x+y*WIDTH] = rand() % 2; } break; case 2: case 3: if ((x>12)&&(x<18)&&(y>12)&&(y<18)) { blocks[x+y*WIDTH] = rand() % 2; } break; case 4: case 5: if ((x>11)&&(x<19)&&(y>11)&&(y<19)) { blocks[x+y*WIDTH] = rand() % 2; } break; default: blocks[x+y*WIDTH] = rand() % 2; } } } blocks[15+15*WIDTH] = false; } bool GameBoard::operator<(const GameBoard& other) const { for (int i = WIDTH*HEIGHT-1; i >= 0; i--) { if (blocks[i] ^ other.blocks[i]) { return other.blocks[i]; } } return false; } bool GameBoard::solve(int playerx, int playery) const { std::deque<std::tuple<GameBoard, coord, int>> search; std::unordered_map<board_type, board_type> done; // Assume that the player will not move while the board is changing, so tick // the board until it either stops changing, or it reaches a state that it has // already been in (in the case of alternating systems). { GameBoard original = *this; std::unordered_set<board_type> pastStates; pastStates.insert(original.blocks); while (original.updateable.any()) { original.tick(playerx, playery); if (pastStates.count(original.blocks)) { break; } pastStates.insert(original.blocks); } search.emplace_front(std::move(original), coord{playerx, playery}, 0); } // Use breadth first search to find a solution. bool exists = false; while (!search.empty()) { auto cur = std::move(search.front()); search.pop_front(); GameBoard& cbr = std::get<0>(cur); coord& cpl = std::get<1>(cur); int cns = std::get<2>(cur); // If it has been over 100 generations, give up. if (cns > 100) { continue; } int cplx = std::get<0>(cpl); int cply = std::get<1>(cpl); // If this section of this board state has already been checked, skip it. if (done.count(cbr.blocks) && done.at(cbr.blocks)[cplx+cply*WIDTH]) { continue; } // Use a flood fill to find a set of positions accessible to the player // without modifying the board state, as well as a set of positions adjacent // to the flood that /will/ modify the board state. board_type flood; std::deque<coord> front; front.push_front(cpl); flood[cplx+cply*WIDTH] = true; std::set<coord> edges; while (!front.empty()) { coord frontLoc = std::move(front.front()); front.pop_front(); // Iterate over the positions 4-adjacent to the current one. for (coord& fc : std::list<coord>{ {std::get<0>(frontLoc) - 1, std::get<1>(frontLoc) }, {std::get<0>(frontLoc) + 1, std::get<1>(frontLoc) }, {std::get<0>(frontLoc) , std::get<1>(frontLoc) - 1}, {std::get<0>(frontLoc) , std::get<1>(frontLoc) + 1}, }) { wrap(std::get<0>(fc), std::get<1>(fc)); int fcx = std::get<0>(fc); int fcy = std::get<1>(fc); // If this position is already in the flood, skip it. if (flood[fcx+fcy*WIDTH]) { continue; } // If the player could not move into this position, skip it. if (cbr.isObstructed(fcx, fcy)) { continue; } // If this position is adjacent to the event, then the board is // solvable. if (((fcx == 15) && ((fcy == 14) || (fcy == 16))) || ((fcy == 15) && ((fcx == 14) || (fcx == 16)))) { exists = true; break; } // Check if the player moving would cause any positions 8-adjacent to // the start or end positions to change. This is more efficient than // copying the board state and then running tick. bool changed = false; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <=1; dx++) { if (dx == 0 && dy == 0) { continue; } int cpldx = cplx + dx; int cpldy = cply + dy; wrap(cpldx, cpldy); if (cbr.isObstructed(cpldx, cpldy) != applyNeighbors( cpldx, cpldy, cbr.blocks, fcx, fcy)) { changed = true; break; } int fcxdx = fcx + dx; int fcydy = fcy + dy; wrap(fcxdx, fcydy); if (cbr.isObstructed(fcxdx, fcydy) != applyNeighbors( fcxdx, fcydy, cbr.blocks, fcx, fcy)) { changed = true; break; } } if (changed) { break; } } // If moving to this position would change the board state, add it to // the set of edges; otherwise, add it to the flood and the flood front. if (changed) { edges.insert(fc); } else { flood[fcx+fcy*WIDTH] = true; front.push_back(fc); } } if (exists) { break; } } if (exists) { break; } // Add the flood to the set of checked positions for this board state. done[cbr.blocks] |= flood; // Add the edges to the search queue. for (const coord& newLoc : edges) { GameBoard nextState1 = cbr; nextState1.tick(std::get<0>(newLoc), std::get<1>(newLoc)); // Assume that the player will not move while the board is changing, so // tick the board until it either stops changing, or it reaches a state // that it has already been in (in the case of alternating systems). std::unordered_set<board_type> pastStates; pastStates.insert(nextState1.blocks); while (nextState1.updateable.any()) { nextState1.tick(std::get<0>(newLoc), std::get<1>(newLoc)); if (pastStates.count(nextState1.blocks)) { break; } pastStates.insert(nextState1.blocks); } if (!done.count(nextState1.blocks) || !done.at(nextState1.blocks) [std::get<0>(newLoc) + std::get<1>(newLoc)*WIDTH]) { search.emplace_back(std::move(nextState1), newLoc, cns+1); } } } return exists; } std::string GameBoard::dump() const { std::stringstream output; output << std::hex; for (int i=0; i<WIDTH*HEIGHT/4; i++) { int chunk = (8 * blocks[i*4]) + (4 * blocks[i*4+1]) + (2 * blocks[i*4+2]) + blocks[i*4+3]; output << chunk; } return output.str(); }
Python
UTF-8
1,465
3.90625
4
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/8/31 10:27 # @Author : tc # @File : PermutationsII.py """ 给定一个可包含重复数字的序列,返回所有不重复的全排列。 Input1:[1,1,2] Output1: [ [1,1,2], [1,2,1], [2,1,1] ] 关键:回溯+剪 "一个数组中去掉重复元素,除了使用哈希表,更容易想到的是将原始数组排序" 参考:https://leetcode-cn.com/problems/permutations-ii/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liwe-2/ """ def permuteUnique(nums): if not len(nums): return [] # 修改 1:首先排序,之后才有可能发现重复分支,升序、倒序均可 nums.sort() res = [] used = [False] * len(nums) __dfs(0, nums, used, [], res) return res def __dfs(index, nums, used, pre, res): if index == len(nums): res.append(pre.copy()) return for i in range(len(nums)): if not used[i]: # 修改 2:因为排序以后重复的数一定不会出现在开始,故 i > 0 # 和之前的数相等,并且之前的数还未使用过,只有出现这种情况,才会出现相同分支 # 这种情况跳过即可 if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue used[i] = True pre.append(nums[i]) __dfs(index + 1, nums, used, pre, res) used[i] = False pre.pop()
C++
UTF-8
4,497
4.09375
4
[]
no_license
/******************************************************************* * Filename: lab7.cpp * Email: kniffina@oregonstate.edu * Author: Adam Kniffin * Email: kniffina@oregonstate.edu * Date: 2/18/2016 * Description: This is the cpp file for lab7 of CS 199. It contains two function * declarations, binarySearch, and linearSearch. Each of these functions take * an integer array, int size, and int value, as its parameters. If the value * is found, it is returned, if it is not -1 is returned. These two functions are * used to see which one is faster, in terms of finding the correct value. **********************************************************************/ #include <iostream> #include <ctime> #include <stdlib.h> using std::cout; //declare linearSearch function. int linearSearch(int arr[], int size, int value); //declare binarySearch function. int binarySearch(int arr[], int size, int value); //main function. Where the two functions are implemented. The functions are used // 100,000,000 and the total time is calculated then displayed for each function //respectively. int main() { //set seed so we can create random numbers srand(static_cast<unsigned int>(time(NULL))); //create two integer arrays with 1000 integers int arr[1000]; int arr2[1000]; for (int i = 0; i < 1000; i++)//fill the array with values from 0 - 999 { int randomNumber1 = rand() % 999; int randomNumber2 = rand() % 999; arr[i] = randomNumber1; arr2[i] = randomNumber2; } time_t linStart = time(0);//set time before running function in forloop for (int i = 0; i < 100000000; i++) //loop and use function call 100,000,000 times { int randomNum = rand() % 999; //create random number between 0 -999 linearSearch(arr, 1000, randomNum); //run function } time_t linEnd = time(0);//get time after run time_t totalLinearSearch = linEnd - linStart;//calculate the difference time_t binStart = time(0);//set time before running binary function for (int j = 0; j < 100000000; j++) { int randomNum = rand() % 999;//create random number between 0 - 999 linearSearch(arr, 1000, randomNum); //run function } time_t binEnd = time(0);//get time after time_t totalBinarySearch = binEnd - binStart;//calculate total time to run all the functions cout << "It took the linear sort " << totalLinearSearch << " seconds to complete 100,000,00 searches.\n"; cout << "It took the binary sort " << totalBinarySearch << " seconds to complete 100,000,00 searches.\n"; return 0; } /************************************************************************* * linearSearch function takes an array, int, and int as parameters and searches * through the array starting at the beginning until the end, designated by the size * integer. If the value is found then it is returned, if it is not, then -1 is returned. *************************************************************************/ int linearSearch(int arr[], int size, int value) { for (int i = 0; i < size; i++)//loop through the array { if (arr[i] == value)//if we find the value return its value return i; } return -1; } /************************************************************************* * binarySearch function takes an array, int, and int as parameters and searches * through the array starting at the beginning until the end. It finds the * location of the value being passed in by cutting the array in half and * searching in that half. It continues to cut the array in hafl until it finds * the value, or -1 is returned. This binary search function was taken from the book * Starting out with C++: Early objects (8th edition). *************************************************************************/ int binarySearch(int arr[], int size, int value) { int first = 0,//first array element last = size - 1,//last array element middle,//midpoint of the search position = -1;//position of search value, if found the value is stored, if not it is -1 bool found = false;//bool to say if the value has been found while (found == false && first <= last) { middle = (first + last) / 2; //calculate midpoint if (arr[middle] == value) //if value is found at mid { found = true;//set bool to true position = middle;// } else if (arr[middle] > value)//if value is in lower half last = middle - 1; else //if value is in upper half first = middle + 1; } return position;//return where the value is located }
JavaScript
UTF-8
4,097
2.75
3
[]
no_license
import React, {Component} from "react"; import PropTypes from 'prop-types'; import styled from "styled-components"; import gotService from "../../services/gotServices"; import Spinner from "../spinner"; import ErrorMessage from "../error"; export default class RandomChar extends Component { gotService = new gotService(); state = { character: {}, loading: true, error: false } /* ------------------------- методы жизненого цикла ------------------------- */ componentDidMount() { this.updateCharacter(); this.timerId = setInterval(this.updateCharacter, 2000); } componentWillUnmount() { clearInterval(this.timerId); } /* --------------------------------- methods -------------------------------- */ onCharacterLoaded = (character) => { this.setState({ character, loading: false, }); } onError = (err) => { this.setState({ error: true, loading: false, }); clearInterval(this.timerId); } updateCharacter = () => { const id = Math.floor(Math.random() * 100 + 25); this.gotService .getCharacter(id) .then(this.onCharacterLoaded) .catch(this.onError); } /* --------------------------------- Render --------------------------------- */ render() { const {character, loading, error} = this.state; const errorMessage = error ? <ErrorMessage /> : null; const spinner = loading ? <SpinnerBlock /> : null; const content = !(loading || error) ? <View character={character} /> : null; return ( <RandomCharacterBlock> {errorMessage} {spinner} {content} </RandomCharacterBlock> ); } } /* ---------------------------------- View ---------------------------------- */ const View = ({character}) => { const {name, gender, born, died, culture} = character; return ( <> <RandomCharacterBlock> <RandomCharacterTitle>Random Character: {name}</RandomCharacterTitle> <RandomCharacterList> <RandomCharacterListItem> <Span>Gender </Span> <Span>{gender}</Span> </RandomCharacterListItem> <RandomCharacterListItem> <Span>Born </Span> <Span>{born}</Span> </RandomCharacterListItem> <RandomCharacterListItem> <Span>Died </Span> <Span>{died}</Span> </RandomCharacterListItem> <RandomCharacterListItem> <Span>Culture </Span> <Span>{culture}</Span> </RandomCharacterListItem> </RandomCharacterList> </RandomCharacterBlock> </> ) } const SpinnerBlock = () => { return ( <> <RandomCharacterBlock> <RandomCharacterTitle>Random Character: </RandomCharacterTitle> <RandomCharacterList> <RandomCharacterListItem> <Span>Gender </Span> </RandomCharacterListItem> <RandomCharacterListItem> <Span>Born </Span> </RandomCharacterListItem> <RandomCharacterListItem> <Span>Died </Span> </RandomCharacterListItem> <RandomCharacterListItem> <Span>Culture </Span> </RandomCharacterListItem> </RandomCharacterList> <Spinner /> </RandomCharacterBlock> </> ); } /* ---------------------------- styled-component ---------------------------- */ const RandomCharacterBlock = styled.div` position: relative; background-color: #fff; padding: 25px 25px 15px 25px; margin-bottom: 40px; `; const RandomCharacterList = styled.ul` display: flex; flex-direction: column; padding-left: 0; margin-bottom: 0; border-radius: 0; `; const RandomCharacterListItem = styled.li` display: flex; justify-content: space-between; position: relative; padding: 0.75rem 1.25rem; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); border-width: 0 0 1px; cursor: pointer; &:first-child { border-top-left-radius: inherit; border-top-right-radius: inherit; } &:last-child { border-bottom-width: 0; } `; const RandomCharacterTitle = styled.h4` margin-bottom: 20px; text-align: center; `; const Span = styled.span` &:first-child { font-weight: bold; } `; /* ------------------------------- check props ------------------------------ */ View.propTypes = { character: PropTypes.object }
Java
UTF-8
3,260
3.171875
3
[]
no_license
package com.lando.gameoflife.models; import java.util.ArrayList; import com.lando.gameoflife.utils.EnumUtils; public class GameStateData { private static final String ARGUMENT_EXCEPTION_MESSAGE = "Indicies out of bounds for the grid"; public final int width; public final int height; private final LifeState[][] gridOfLifeStates; private final GridOffset[] neighbourIndexOffsets = new GridOffset[8]; public GameStateData(int width, int height) { this.width = width; this.height = height; gridOfLifeStates = new LifeState[width][height]; initGridOfLifeStates(); initNeighbourIndexOffsets(); } private void initGridOfLifeStates() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { gridOfLifeStates[i][j] = EnumUtils.randomEnum(LifeState.class); } } } private void initNeighbourIndexOffsets() { neighbourIndexOffsets[0] = new GridOffset(-1, -1); neighbourIndexOffsets[1] = new GridOffset(-1, 0); neighbourIndexOffsets[2] = new GridOffset(-1, 1); neighbourIndexOffsets[3] = new GridOffset(0, -1); neighbourIndexOffsets[4] = new GridOffset(0, 1); neighbourIndexOffsets[5] = new GridOffset(1, -1); neighbourIndexOffsets[6] = new GridOffset(1, 0); neighbourIndexOffsets[7] = new GridOffset(1, 1); } public ArrayList<LifeState> getNeighbours(int xPosition, int yPosition) { if (!isValidArrayPosition(xPosition, yPosition)) { throw new IllegalArgumentException(ARGUMENT_EXCEPTION_MESSAGE); } ArrayList<LifeState> neighbours = new ArrayList<LifeState>(); for (GridOffset gridOffset : neighbourIndexOffsets) { if (!isValidArrayPosition(xPosition + gridOffset.deltaX, yPosition + gridOffset.deltaY)) { continue; } LifeState lifeState = getLifeState(xPosition + gridOffset.deltaX, yPosition + gridOffset.deltaY); neighbours.add(lifeState); } return neighbours; } public LifeState getLifeState(int xPosition, int yPosition) { if (!isValidArrayPosition(xPosition, yPosition)) { throw new IllegalArgumentException(ARGUMENT_EXCEPTION_MESSAGE); } return gridOfLifeStates[xPosition][yPosition]; } public void setLifeState(int xPosition, int yPosition, LifeState state) { if (!isValidArrayPosition(xPosition, yPosition)) { throw new IllegalArgumentException(ARGUMENT_EXCEPTION_MESSAGE); } gridOfLifeStates[xPosition][yPosition] = state; } private boolean isValidArrayPosition(int xPosition, int yPosition) { return isValidXPosition(xPosition) && isValidYPosition(yPosition); } private boolean isValidXPosition(int xPosition) { return xPosition >= 0 && xPosition < width; } private boolean isValidYPosition(int yPosition) { return yPosition >= 0 && yPosition < height; } private class GridOffset { int deltaX; int deltaY; GridOffset(int deltaX, int deltaY) { this.deltaX = deltaX; this.deltaY = deltaY; } } }
Python
UTF-8
104
2.75
3
[]
no_license
array = ["one", "two", "one"] oneset = set(array) print (oneset) if "one" in oneset: print("great")
Java
UTF-8
720
2.234375
2
[]
no_license
package com.bookstore.dao.Impl; import com.bookstore.dao.BookDAO; import com.bookstore.model.Book; import com.bookstore.util.HibernateUtil; import java.util.List; /** * Created by googo on 19/03/2017. */ public class BookDAOImpl{ public boolean addBook(Book book){ //todo return HibernateUtil.save(book); } public boolean deleteBook(Book book){ //todo return HibernateUtil.delete(book); } public boolean updateBook(Book book){ //todo return HibernateUtil.update(book); } public Book getBookByISBN(String isbn){ //todo return null; } public List<Book> getAllBooks(){ //todo return null; } }
C++
UTF-8
2,386
3.375
3
[]
no_license
#include <iostream> #include <pthread.h> #include <chrono> using namespace std; const unsigned long N = 900000; void one_thread_sum(long* begin, long* end) { auto tstart = chrono::high_resolution_clock::now(); unsigned long sum = 0; for(; begin < end; ++begin) sum += *begin; auto tend = chrono::high_resolution_clock::now(); float micros = chrono::duration_cast<chrono::microseconds>(tend-tstart).count(); std::cout << "Total time: " << micros << " us" << std::endl; std::cout << "Sum: " << sum << std::endl; } // multithreaded version struct range_t { long* start; long* end; unsigned long partial_sum; }; void* partial_sum(void *rng) { unsigned long sum; range_t *range = (range_t*)rng; for(; range->start < range->end; ++range->start) range->partial_sum += *range->start; pthread_exit(NULL); } void multithread_sum(long* begin, long* end) { auto tstart = chrono::high_resolution_clock::now(); unsigned long sum = 0; const unsigned int N = 4; pthread_t threads[N]; range_t ranges[N]; size_t block_size = (end-begin)/4; long* block_start = begin; for (unsigned int i = 0 ; i < N-1 ; ++i) { long* block_end = block_start; block_end += block_size; ranges[i].start = block_start; ranges[i].end = block_end; ranges[i].partial_sum = 0; block_start = block_end; } ranges[N-1].start = block_start; ranges[N-1].end = end; ranges[N-1].partial_sum = 0; for (int i = 0 ; i < N ; ++i) { pthread_create(&threads[i], NULL, partial_sum, (void*)&ranges[i]); } for (int i = 0 ; i < N ; ++i) { pthread_join(threads[i], NULL); sum += ranges[i].partial_sum; } auto tend = chrono::high_resolution_clock::now(); float micros = chrono::duration_cast<chrono::microseconds>(tend-tstart).count(); std::cout << "Total time: " << micros << " us" << std::endl; std::cout << "Sum: " << sum << std::endl; } int main() { long *table; table = new long[N]; for (size_t i = 0 ; i < N ; ++i) table[i] = i; std::cout << N << std::endl; one_thread_sum(table, table+N); std::cout << "\n-----------------------------\n" << std::endl; multithread_sum(table, table+N); std::cout << "\n-----------------------------\n" << std::endl; }
Java
UTF-8
9,626
1.804688
2
[ "Apache-2.0" ]
permissive
/* * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://duracloud.org/license/ */ package org.duracloud.security.vote; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.duracloud.common.model.AclType; import org.duracloud.common.model.RootUserCredential; import org.duracloud.security.domain.HttpVerb; import org.duracloud.security.impl.DuracloudUserDetails; import org.duracloud.storage.error.NotFoundException; import org.duracloud.storage.error.StorageException; import org.duracloud.storage.provider.StorageProvider; import org.duracloud.storage.util.StorageProviderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.FilterInvocation; /** * @author Andrew Woods * Date: Mar 19, 2010 */ public abstract class SpaceAccessVoter implements AccessDecisionVoter { private final Logger log = LoggerFactory.getLogger(SpaceAccessVoter.class); private StorageProviderFactory storageProviderFactory; private UserDetailsService userDetailsService; public SpaceAccessVoter(StorageProviderFactory storageProviderFactory, UserDetailsService userDetailsService) { this.storageProviderFactory = storageProviderFactory; this.userDetailsService = userDetailsService; } protected StorageProviderFactory getStorageProviderFactory(){ return this.storageProviderFactory; } protected boolean isOpenResource(HttpServletRequest httpRequest) { String spaceId = getSpaceId(httpRequest); if (null == spaceId) { return false; } return spaceId.equals("spaces") || spaceId.equals("stores") || spaceId.equals("acl") || spaceId.equals("init"); } protected String getStoreId(HttpServletRequest httpRequest) { String storeId = null; String query = httpRequest.getQueryString(); if (null == query) { return null; } query = query.toLowerCase(); String name = "storeid"; int storeIdIndex = query.indexOf(name); if (storeIdIndex > -1) { int idIndex = query.indexOf("=", storeIdIndex) + 1; if (idIndex == storeIdIndex + name.length() + 1) { int nextParamIndex = query.indexOf("&", idIndex); int end = nextParamIndex > -1 ? nextParamIndex : query.length(); storeId = query.substring(idIndex, end); } } return storeId; } protected String getSpaceId(HttpServletRequest httpRequest) { String spaceId = httpRequest.getPathInfo(); if (null == spaceId) { return null; } if (spaceId.startsWith("/")) { spaceId = spaceId.substring(1); } if (spaceId.startsWith("acl/")) { spaceId = spaceId.substring("acl/".length()); } int slashIndex = spaceId.indexOf("/"); if (slashIndex > 0) { spaceId = spaceId.substring(0, slashIndex); } return spaceId; } protected boolean hasContentId(HttpServletRequest httpRequest) { String spaceId = getSpaceId(httpRequest); if (null != spaceId) { String path = httpRequest.getPathInfo(); return !path.endsWith(spaceId); } return false; } /** * This method returns the ACLs of the requested space, or an empty-map if * there is an error or for certain 'keyword' spaces, or null if the space * does not exist. * * @param request containing spaceId and storeId * @return ACLs, empty-map, or null */ protected Map<String, AclType> getSpaceACLs(HttpServletRequest request) { Map<String, AclType> emptyACLs = new HashMap<String, AclType>(); String storeId = getStoreId(request); String spaceId = getSpaceId(request); if (null == spaceId) { return emptyACLs; } if (spaceId.equals("security") || spaceId.equals("init")) { return emptyACLs; } StorageProvider store = getStorageProvider(storeId); if (null == store) { return emptyACLs; } try { return store.getSpaceACLs(spaceId); } catch (NotFoundException nfe) { log.info("Space !exist: {}, exception: {}", spaceId, nfe); return emptyACLs; } catch (StorageException e) { log.warn("Error getting space ACLs: {}, exception: {}", spaceId, e); return emptyACLs; } } protected HttpVerb getHttpVerb(HttpServletRequest httpRequest) { String method = httpRequest.getMethod(); try { return HttpVerb.valueOf(method); } catch (RuntimeException e) { log.error("Error determining verb: {}, exception: {}", method, e); return null; } } protected List<String> getUserGroups(Authentication auth) { DuracloudUserDetails userDetails = (DuracloudUserDetails) auth.getPrincipal(); return userDetails.getGroups(); } protected boolean groupsHaveReadAccess(List<String> userGroups, Map<String, AclType> acls) { return groupsHaveAccess(userGroups, acls, true); } protected boolean groupsHaveWriteAccess(List<String> userGroups, Map<String, AclType> acls) { return groupsHaveAccess(userGroups, acls, false); } private boolean groupsHaveAccess(List<String> userGroups, Map<String, AclType> acls, boolean isRead) { if (null != userGroups) { for (String group : userGroups) { if (isRead && hasReadAccess(group, acls)) { return true; } else if (!isRead && hasWriteAccess(group, acls)) { return true; } } } return false; } protected boolean hasReadAccess(String name, Map<String, AclType> acls) { return hasAccess(name, acls, true); } protected boolean hasWriteAccess(String name, Map<String, AclType> acls) { return hasAccess(name, acls, false); } private boolean hasAccess(String name, Map<String, AclType> acls, boolean isRead) { if (RootUserCredential.getRootUsername().equals(name)) { return true; } if (null == acls) { return false; } String aclName = StorageProvider.PROPERTIES_SPACE_ACL + name; if (acls.containsKey(aclName)) { AclType acl = acls.get(aclName); if (isRead) { return AclType.READ.equals(acl) || AclType.WRITE.equals(acl); } else { return AclType.WRITE.equals(acl); } } return false; } protected boolean isAdmin(String name) { UserDetails userDetails; try { userDetails = userDetailsService.loadUserByUsername(name); } catch (UsernameNotFoundException e) { log.debug("Not admin: {}, error: {}", name, e); return false; } for (GrantedAuthority authority : userDetails.getAuthorities()) { if ("ROLE_ADMIN".equals(authority.getAuthority())) { return true; } } return false; } /** * This method provides entry-point for alternate implementations of * StorageProvider. */ protected StorageProvider getStorageProvider(String storeId) { return storageProviderFactory.getStorageProvider(storeId); } protected HttpServletRequest getHttpServletRequest(Object resource) { FilterInvocation invocation = (FilterInvocation) resource; HttpServletRequest request = invocation.getHttpRequest(); if (null == request) { String msg = "null request: '" + resource + "'"; log.warn("HttpServletRequest was null! " + msg); } return request; } /** * This method always returns true because all configAttributes are able * to be handled by this voter. * * @param configAttribute any att * @return true */ public boolean supports(ConfigAttribute configAttribute) { return true; } /** * This methods returns true if the arg class is an instance of or * subclass of FilterInvocation. * No other classes can be handled by this voter. * * @param aClass to be analyized for an AuthZ vote. * @return true if is an instance of or subclass of FilterInvocation */ public boolean supports(Class aClass) { return FilterInvocation.class.isAssignableFrom(aClass); } }
Java
UTF-8
490
1.984375
2
[]
no_license
package kz.akmarzhan.nationaltest.bus.events; import java.util.List; import kz.akmarzhan.nationaltest.models.UserPredmet; /** * Created by Akmarzhan Raushanova on 5/20/2017. * Working on NationalTest. MobiLabs * You can contact me at: akmarzhan.raushnanova@is.sdu.edu.kz */ public class UserPredmetsLoadedEvent { public List<UserPredmet> mPredmets; public int mUserExp; public UserPredmetsLoadedEvent(List<UserPredmet> predmets, int userExp) { mPredmets = predmets; mUserExp = userExp; } }
Java
UTF-8
2,280
2.03125
2
[]
no_license
/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.tools.xjc.generator.bean.field; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import com.sun.tools.xjc.generator.bean.ClassOutlineImpl; import com.sun.tools.xjc.model.CPropertyInfo; import com.sun.tools.xjc.outline.FieldOutline; /** * Creates * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public final class GenericFieldRenderer implements FieldRenderer { private Constructor constructor; public GenericFieldRenderer( Class fieldClass ) { try { constructor = fieldClass.getDeclaredConstructor(new Class[]{ClassOutlineImpl.class,CPropertyInfo.class}); } catch (NoSuchMethodException e) { throw new NoSuchMethodError(e.getMessage()); } } public FieldOutline generate(ClassOutlineImpl context, CPropertyInfo prop) { try { return (FieldOutline)constructor.newInstance(new Object[]{context,prop}); } catch (InstantiationException e) { throw new InstantiationError(e.getMessage()); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if(t instanceof RuntimeException) throw (RuntimeException)t; if(t instanceof Error) throw (Error)t; // impossible throw new AssertionError(t); } } }
JavaScript
UTF-8
1,244
2.6875
3
[]
no_license
'use strict'; // process links. currently they have no geometry information module.exports = function(nodes, lookup) { var removeList = []; nodes.forEach(function(node){ if( node.geometry !== null ) { return; } if( node.properties.origin && node.properties.terminus ) { var origin = lookup[node.properties.origin]; var terminus = lookup[node.properties.terminus]; if( !origin || !terminus ) { if( global.debug ) { console.log(' --Found link but nodes are missing geo: '+node.properties.prmname); } return; } else if( !origin.geometry || !terminus.geometry ) { if( global.debug ) { console.log(' --Found link but nodes are missing geo: '+node.properties.prmname); } return; } node.geometry = { 'type': 'LineString', 'coordinates': [ origin.geometry.coordinates, terminus.geometry.coordinates ] }; } else { if( global.debug ) { console.log(' --Found node with missing geo but not link: '+node.properties.prmname); } removeList.push(node); } }); removeList.forEach(function(node){ nodes.splice(nodes.indexOf(node), 1); }); };
PHP
UTF-8
1,986
2.609375
3
[]
no_license
<?php namespace App\Entity\Admin; use App\Entity\Admin\Permission; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Entity(repositoryClass="App\Repository\Admin\SubjectRepository") * @UniqueEntity(fields="name",message="Ce nom est déjà utilisé") */ class Subject { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255, unique=true) */ private $name; /** * @ORM\OneToMany(targetEntity="Permission", mappedBy="subject") * @ORM\JoinColumn(onDelete="CASCADE") */ private $permissions; public function __construct() { $this->permissions = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } /** * @return Collection|Permission[] */ public function getPermissions(): Collection { return $this->permissions; } public function addPermission(Permission $permission): self { if (!$this->permissions->contains($permission)) { $this->permissions[] = $permission; $permission->setSubject($this); } return $this; } public function removePermission(Permission $permission): self { if ($this->permissions->contains($permission)) { $this->permissions->removeElement($permission); // set the owning side to null (unless already changed) if ($permission->getSubject() === $this) { $permission->setSubject(null); } } return $this; } }
Java
UTF-8
1,035
3.203125
3
[ "Apache-2.0" ]
permissive
package org.openstack4j.model.common; /** * Represents an identifier which can either be an ID or Name * * @author Jeremy Unruh */ public class Identifier { private final Type type; private final String id; private Identifier(Type type, String id) { this.type = type; this.id = id; } /** * Creates a new identifier which is an ID based value * * @param id the ID value * @return identifier object */ public static Identifier byId(String id) { return new Identifier(Type.ID, id); } /** * Creates an identifier which is NAME based identification * * @param name the name value * @return the identifier */ public static Identifier byName(String name) { return new Identifier(Type.NAME, name); } public Type getType() { return type; } public String getId() { return id; } public boolean isTypeID() { return type == Type.ID; } public enum Type {ID, NAME} }
PHP
UTF-8
6,332
2.8125
3
[]
no_license
<?php class crudUmum { private $db; public $sel_q=""; public $table_q=""; public $where_q=""; public $join_q=""; public $query=""; function __construct($DB_con) { $this->db = $DB_con; $this->query=""; } public function query() { if (!$this->sel_q) { $this->sel_q='SELECT * '; } if (!$this->table_q) { echo "table empty "; die(); } $this->query = $this->sel_q. $this->table_q. $this->join_q. $this->where_q; return $this->query; } public function sel($sel) { $this->sel_q .= "SELECT $sel"; } public function getTable($tabel=0) { if (!$tabel) { echo "table empty "; die(); } $this->table_q .= " from $tabel "; } public function where($kol,$val) { if ($this->where_q) { $this->where_q .= " AND $kol='$val' "; }else{ $this->where_q .= " WHERE $kol='$val' "; } } public function join($table,$on,$join='inner') { $this->join_q .= " $join JOIN $table on $on "; } public function eksekusi() { try { $q=$this->query(); $stmt = $this->db->prepare($q); $stmt->execute(); $data=$stmt->fetchAll(); $this->query=''; return $data; } catch(PDOException $e) { echo $e->getMessage(); die();//return false; } } public function eksekusiStmt() { try { $q=$this->query(); $stmt = $this->db->prepare($q); $stmt->execute(); return $stmt; } catch(PDOException $e) { echo $e->getMessage(); die();//return false; } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public function get_id_admin_by_token($token) { try { $query = "SELECT id_admin FROM admin where token='$token'"; $stmt = $this->db->prepare($query); $stmt->execute(); $row = $stmt->fetch(); return $row['id_admin']; } catch (PDOException $e) { echo $e->getMessage(); return false; } } public function SelectWhere($table,$kolom,$val) { try { $q="SELECT * from $table where $table.$kolom='$val'"; $stmt = $this->db->prepare($q); $stmt->execute(); $data=$stmt->fetchAll(PDO::FETCH_ASSOC); return $data; } catch(PDOException $e) { echo $e->getMessage(); return false; } } public function Delete($table,$kolom,$val) { try { $q="SELECT * from $table where $table.$kolom='$val'"; $stmt = $this->db->prepare($q); $stmt->execute(); $data=$stmt->fetch(); if ($data) { $q="DELETE from $table where $table.$kolom='$val'"; $stmt = $this->db->prepare($q); $stmt->execute(); }else{ echo "data tidak delete ditemukan"; return false; } return $data; } catch(PDOException $e) { echo $e->getMessage(); return false; } } public function SelectAll($table) { try { $q="SELECT * from $table"; $stmt = $this->db->prepare($q); $stmt->execute(); $data=$stmt->fetchAll(); return $data; } catch(PDOException $e) { echo $e->getMessage(); return false; } } public function insert($table,$data) { $key_array=array_keys($data); $key=implode(',',$key_array); $VALUE=array();; for ($i=0; $i <sizeof($key_array) ; $i++) { //$VALUE[$i]=":".$key_array[$i]; $VALUE[$i]="?"; } $isi=implode(',', $VALUE); try { $q="INSERT INTO $table ($key) VALUES ($isi);"; $stmt = $this->db->prepare($q); for ($i=0; $i <sizeof($key_array) ; $i++) { $stmt->bindparam(($i+1),$data[$key_array[$i]]); } //print_r($q);die(); $stmt->execute(); //$stmt->debugDumpParams(); return true; } catch(PDOException $e) { echo $e->getMessage(); die(); return false; } } public function insert_id($table,$data) { $key_array=array_keys($data); $key=implode(',',$key_array); $VALUE=array();; for ($i=0; $i <sizeof($key_array) ; $i++) { $VALUE[$i]=":".$key_array[$i]; } $isi=implode(',', $VALUE); try { $q="INSERT INTO $table ($key) VALUES ($isi);"; $stmt = $this->db->prepare($q); for ($i=0; $i <sizeof($key_array) ; $i++) { $stmt->bindparam(":".$key_array[$i],$data[$key_array[$i]]); } //print_r($q);die(); $stmt->execute(); $id = $this->db->lastInsertId(); return $id; } catch(PDOException $e) { echo $e->getMessage(); return false; } } public function update($table,$data,$id,$kolom_id) { $key_array=array_keys($data); $key=implode(',',$key_array); $setKey=array(); $VALUE=array(); for ($i=0; $i <sizeof($key_array) ; $i++) { $VALUE[$i]=":".$key_array[$i]; } for ($i=0; $i <sizeof($key_array) ; $i++) { $setKey[$i]=$key_array[$i]."=:".$key_array[$i]; } $setKeyisi=implode(',', $setKey); try { $q="UPDATE $table SET $setKeyisi WHERE $table.$kolom_id='$id';"; $stmt = $this->db->prepare($q); for ($i=0; $i <sizeof($key_array) ; $i++) { $stmt->bindparam(":".$key_array[$i],$data[$key_array[$i]]); } //print_r($q);die(); $stmt->execute(); return true; } catch(PDOException $e) { echo $e->getMessage(); return false; } } function MultiInsert($tableName, $data, $pdoObject=""){ $pdoObject = ($pdoObject =="") ? $this->db : $pdoObject ; //Will contain SQL snippets. $rowsSQL = array(); //Will contain the values that we need to bind. $toBind = array(); //Get a list of column names to use in the SQL statement. $columnNames = array_keys($data[0]); //Loop through our $data array. foreach($data as $arrayIndex => $row){ $params = array(); foreach($row as $columnName => $columnValue){ $param = ":" . $columnName . $arrayIndex; $params[] = $param; $toBind[$param] = $columnValue; } $rowsSQL[] = "(" . implode(", ", $params) . ")"; } //Construct our SQL statement $sql = "INSERT INTO `$tableName` (" . implode(", ", $columnNames) . ") VALUES " . implode(", ", $rowsSQL); //Prepare our PDO statement. $pdoStatement = $pdoObject->prepare($sql); //Bind our values. foreach($toBind as $param => $val){ $pdoStatement->bindValue($param, $val); } //Execute our statement (i.e. insert the data). return $pdoStatement->execute(); } }
C++
UTF-8
500
3.109375
3
[]
no_license
// // Created by Karl on 12/12/2015. // #include "position.h" int Position::posX() { return x; } int Position::posY() { return y; } int Position::posZ() { return z; } Position::Position() { x = y = z = 0; } Position::Position(int suppliedX, int suppliedY, int suppliedZ) { x = suppliedX; y = suppliedY; z = suppliedZ; } void Position::setX(int newX) { x = newX; } void Position::setY(int newY) { y = newY; } void Position::setZ(int newZ) { z = newZ; }
Python
UTF-8
3,028
2.703125
3
[]
no_license
import scaling_model from testutil import gae_model #from testutil import testsize #import logging from google.appengine.ext import ndb class VotesCounter(scaling_model.ScalingModel): """An example of something that might be sharded. If a lot of people will be voting on an item then it could easily cause contention if a vote might be written more often than once per second. """ upvotes = ndb.IntegerProperty(default=0) downvotes = ndb.IntegerProperty(default=0) @staticmethod def combine(x, y): upvotes = x.upvotes + y.upvotes downvotes = x.downvotes + y.downvotes return VotesCounter(upvotes=upvotes, downvotes=downvotes) class ScalingShardTest(gae_model.GAEModelTestCase): """Tests to verify that Scaling Shards behave as expected.""" def setUp(self): super(ScalingShardTest, self).setUp() self.set_consistency_probability(1) self.id = "vote" def tearDown(self): super(ScalingShardTest, self).tearDown() def test_get_no_results(self): vc = VotesCounter.get_results(self.id) self.assertEquals(vc, None) def test_get_one_result(self): VotesCounter(scaling_shard_id=self.id).put() vc = VotesCounter.get_results(self.id) self.assertIsNotNone(vc) def test_get_multiple_results(self): shard1 = VotesCounter._new_shard(self.id) shard2 = VotesCounter._new_shard(self.id) shard1.upvotes = 1 shard1.downvotes = 1 shard2.upvotes = -1 shard2.downvotes = 100 ndb.put_multi([shard1, shard2]) votes = VotesCounter.get_results(self.id) self.assertEqual(votes.upvotes, 0) self.assertEqual(votes.downvotes, 101) def test_sharding_occurs(self): VotesCounter(scaling_shard_id=self.id).put() for i in range(50): shard = VotesCounter.get_shard(self.id) shard.upvotes += 1 shard.put() count = VotesCounter.query(VotesCounter.scaling_shard_id == self.id).count() self.assertTrue(count > 1) self.assertTrue(count < 50) res = VotesCounter.get_results(self.id) self.assertEqual(res.upvotes, 50) self.assertEqual(res.downvotes, 0) def test_get_shard_iff_shard_exists(self): shard = VotesCounter.get_shard(self.id) self.assertEquals(shard, None) VotesCounter(scaling_shard_id=self.id).put() shard = VotesCounter.get_shard(self.id) self.assertIsNotNone(shard) def test_shard_groups_dont_interact(self): VotesCounter(scaling_shard_id="vc1", upvotes=1).put() vc1_ = VotesCounter._new_shard("vc1") vc1_.upvotes = 1 vc1_.put() VotesCounter(scaling_shard_id="vc2", downvotes=1).put() vc2_ = VotesCounter._new_shard("vc2") vc2_.downvotes = 1 vc2_.put() self.assertEqual(VotesCounter.get_results("vc1").upvotes, 2) self.assertEqual(VotesCounter.get_results("vc2").downvotes, 2)
Python
UTF-8
1,084
3.828125
4
[]
no_license
# 一、叠加多个装饰器的加载,运行分析 def deco1(func): def wrapper1(*args, **kwargs): print('正在运行===>deco1.wrapper1') res1 = func(*args, **kwargs) return res1 return wrapper1 def deco2(func): def wrapper2(*args, **kwargs): print('正在运行===>deco2.wrapper2') res2 = func(*args, **kwargs) return res2 return wrapper2 def deco3(x): def outter3(func): def wrapper3(*args, **kwargs): print('正在运行===>deco3.wrapper3') res3 = func(*args, **kwargs) return res3 return wrapper3 return outter3 # 加载顺序自下而上(了解) @deco1 # func->wrapper2, @deco1装时候返回wrapper1,最后index->wrapper1 @deco2 # func->wrapper3,@deco2装饰后返回wrapper2,最后index->wrapper2 @deco3(111) # @deco3(111)相当于@outter3,@outter3装饰后返回wrapper3,最后index->wrapper3 def index(x, y): print('from index %s %s' % (x, y)) print(index) # 运行顺序自上而下 index(5, 6)
Java
UTF-8
3,547
2.015625
2
[]
no_license
package com.nexttech.easybusinesscard.Fragments; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.budiyev.android.codescanner.CodeScanner; import com.budiyev.android.codescanner.CodeScannerView; import com.budiyev.android.codescanner.DecodeCallback; import com.google.zxing.Result; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import com.nexttech.easybusinesscard.Activity.MainActivity; import com.nexttech.easybusinesscard.Activity.ViewActivity; import com.nexttech.easybusinesscard.R; public class ScanFragment extends Fragment { CodeScanner codeScanner; CodeScannerView scannView; String scannedvalue; Context context; public ScanFragment(Context context) { this.context = context; } @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_scan, container, false); scannView = view.findViewById(R.id.scannerView); codeScanner = new CodeScanner(context,scannView); codeScanner.setDecodeCallback(new DecodeCallback() { @Override public void onDecoded(@NonNull final Result result) { ((Activity)context).runOnUiThread(new Runnable() { @Override public void run() { scannedvalue = result.getText(); Intent i =new Intent(context,ViewActivity.class); i.putExtra("data",scannedvalue); startActivity(i); } }); } }); scannView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { codeScanner.startPreview(); } }); return view; } @Override public void onResume() { super.onResume(); requestForCamera(); } @Override public void onPause() { codeScanner.releaseResources(); super.onPause(); } public void requestForCamera() { Dexter.withActivity(getActivity()).withPermission(Manifest.permission.CAMERA).withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { codeScanner.startPreview(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { Toast.makeText(getContext(), "Camera Permission is Required.", Toast.LENGTH_SHORT).show(); } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { token.continuePermissionRequest(); } }).check(); } }
C++
UTF-8
8,480
3.296875
3
[]
no_license
// Project Name: Final Project // Name: Allysa Sewell // Date: 6/9/18 // Class: CS 172 #include <iostream> #include <iomanip> #include <fstream> #include "Ecosystem.h" #include "Species.h" #include "IndependentSpecies.h" #include "PredatorPrey.h" using namespace std; //displays the genetic makeup of a population in a file void printStats(Ecosystem& ecosystem, fstream& output) { vector<Species*> allSpecies = ecosystem.getAllSpecies(); for (int i = 0; i < allSpecies.size(); i++) { output << "Proportion homozygous dominant for " << allSpecies[i]->getName() << ": " << allSpecies[i]->findHomozygousDominant() << endl; output << "Proportion heterozygous for " << allSpecies[i]->getName() << ": " << allSpecies[i]->findHeterozygous() << endl; output << "Proportion homozygous recessive for " << allSpecies[i]->getName() << ": " << allSpecies[i]->findHomozygousRecessive() << endl; output << "Number with dominant phenotype for " << allSpecies[i]->getName() << ": " << allSpecies[i]->findNumberDominant() << endl; output << "Number with recessive phenotype for " << allSpecies[i]->getName() << ": " << allSpecies[i]->findNumberRecessive() << endl; } output << endl; } void displayMinMaxAverage(vector<double> vector, fstream& stream) { double min = vector[0]; double max = vector[0]; int maxIndex = 0; int minIndex = 0; double sum = 0; //finds minimum and maximum values and the sum for (int i = 0; i < vector.size(); i++) { if (vector[i] < min) { min = vector[i]; minIndex = i; } if (vector[i] > max) { max = vector[i]; maxIndex = i; } sum += vector[i]; } double average = sum / vector.size(); stream << "The minimum population size is " << static_cast<int>(min) << " at time " << minIndex << endl; stream << "The maximum population size is " << static_cast<int>(max) << " at time " << maxIndex << endl; stream << "The average population size is " << average << endl; } //displays a table of population size at different times void printTable(Ecosystem& ecosystem, fstream& output) { vector<Species*> allSpecies = ecosystem.getAllSpecies(); for (int i = 0; i < allSpecies.size(); i++) { if (typeid(*allSpecies[i]) == typeid(IndependentSpecies)) { double initialSize = dynamic_cast<IndependentSpecies*> (allSpecies[i])-> getSize(); double time = dynamic_cast<IndependentSpecies*>(allSpecies[i]) ->getTime(); vector<double> populations; output << "time " <<dynamic_cast<IndependentSpecies*>(allSpecies[i]) ->getName() << " population size " << endl; for (int j = 0; j <= time; j++) { dynamic_cast<IndependentSpecies*>(allSpecies[i]) ->setTime(j); output << dynamic_cast<IndependentSpecies*>(allSpecies[i]) ->getTime() << setw(8) << dynamic_cast<IndependentSpecies*>(allSpecies[i]) ->calculatePopulationSize() << endl; populations.push_back(dynamic_cast<IndependentSpecies*>(allSpecies[i]) ->getSize()); //resets to the initial size for use in the calculatePopulationSize //equation dynamic_cast<IndependentSpecies*>(allSpecies[i]) ->setSize(initialSize); } output << endl; displayMinMaxAverage(populations, output); } } } //prints a table of prey population size and predator population size at // different times. void printPredatorPreyTable(Ecosystem& ecosystem, fstream& output) { vector<Species*> allSpecies = ecosystem.getAllSpecies(); for (int i = 0; i < allSpecies.size(); i++) { if (typeid (*allSpecies[i]) == typeid (PredatorPrey)) { double initialSize = allSpecies[i]->getSize(); double initialPredatorSize = dynamic_cast<PredatorPrey*> (allSpecies[i])->getPredatorSize(); double time = dynamic_cast<PredatorPrey*> (allSpecies[i])->getTime(); vector<double> preyPopulations; vector<double> predatorPopulations; output << "time " << allSpecies[i]->getName() << " population size " << dynamic_cast<PredatorPrey*> (allSpecies[i])->getPredatorName() << " population size" << endl; for (int j = 0; j <= time; j++) { dynamic_cast<PredatorPrey*> (allSpecies[i])->setTime(j); output << dynamic_cast<PredatorPrey*> (allSpecies[i])->getTime() << setw(8) << dynamic_cast<PredatorPrey*> (allSpecies[i])->calculatePreyPopulation() << setw(21) << dynamic_cast<PredatorPrey*> (allSpecies[i])->calculatePredatorPopulation() << endl; preyPopulations.push_back( allSpecies[i]->getSize()); predatorPopulations.push_back(dynamic_cast<PredatorPrey*> (allSpecies[i])->getPredatorSize()); allSpecies[i]->setSize(initialSize); dynamic_cast<PredatorPrey*> (allSpecies[i])->setPredatorSize(initialPredatorSize); } output << endl; output << "For " << allSpecies[i]->getName() << " :" << endl; displayMinMaxAverage(preyPopulations, output); output << "For " << dynamic_cast<PredatorPrey*> (allSpecies[i])->getPredatorName() << " :" << endl; displayMinMaxAverage(predatorPopulations, output); } } } //frees memory void deleteVector(Ecosystem& ecosystem) { for (int i = 0; i < ecosystem.getAllSpecies().size(); i++) delete ecosystem.getAllSpecies()[i]; } int main() { //creates independentspecies and predatorprey objects IndependentSpecies robin("robin", 1000, 12, 0.25, 5000, 0.25); PredatorPrey rabbit_coyote; //adjusts values for predatorprey object rabbit_coyote.setPredatorName("coyote"); rabbit_coyote.setSize(1050); rabbit_coyote.setPredatorSize(80); //creates an ecosystem object and adds species to it Ecosystem myBackyard; myBackyard.addIndependentSpecies(robin); myBackyard.addPredatorPrey(rabbit_coyote); vector<Species*> allSpecies = myBackyard.getAllSpecies(); fstream output; if (output.fail()) { cout << "Could not open file" << endl; return -1; } output.open("Results", ios::out); //displays statistics for the species in a file printStats(myBackyard, output); printTable(myBackyard, output); printPredatorPreyTable(myBackyard, output); deleteVector(myBackyard); output.close(); string filename, name; double size, pAlleleFrequency, time, growthRate, carryingCapacity; //opens file with information for independentspecies cout << "Enter a file name: " << endl; cin >> filename; fstream input; input.open(filename.c_str(), ios::in); if (input.fail()) { cout << "Could not open file" << endl; return -1; } Ecosystem ecosystem; //inputs information and creates independentspecies object while (!input.eof()) { input >> name >> size >> time >> growthRate >> carryingCapacity >> pAlleleFrequency; IndependentSpecies species(name, size, time, growthRate, carryingCapacity, pAlleleFrequency); ecosystem.addIndependentSpecies(species); } input.close(); fstream output2; string filename2, name2, predatorName; double size2, predatorSize, time2, preyGrowthRate, deathRate, alpha, gamma; //opens a file and inputs predatorprey information cout << "Enter a predator/prey file: " << endl; cin >> filename2; fstream input2; input2.open(filename2.c_str(), ios::in); if (input2.fail()) { cout << "Could not open file" << endl; return -1; } while (!input2.eof()) { input2 >> name2 >> predatorName >> size2 >> predatorSize >> time2 >> preyGrowthRate >> deathRate >> alpha >> gamma; PredatorPrey species2(name2, predatorName, size2, predatorSize, time2, preyGrowthRate, deathRate, alpha, gamma); ecosystem.addPredatorPrey(species2); } //displays information in a file //can create or append the file output2.open("Results2", ios::out | ios::app); if (output2.fail()) { cout << "Could not open file" << endl; return -1; } printStats(ecosystem, output2); printTable(ecosystem, output2); printPredatorPreyTable(ecosystem, output2); deleteVector(ecosystem); output2.close(); return 0; }
Java
UTF-8
96
1.523438
2
[ "Apache-2.0" ]
permissive
package com.p2p.directions; //. by Haseem Saheed public interface Parser { public Route parse(); }
Java
UTF-8
1,959
1.820313
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.spring.test.transaction; import org.activiti.engine.RepositoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; public class DeployBean { @Autowired protected RepositoryService repositoryService; @Transactional public void deployProcesses() { repositoryService .createDeployment() .addString( "process01.bpmn20.xml", "<definitions xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' targetNamespace='http://activiti.org/BPMN20'>" + "<process id='process01' name='Insurance Damage Report' /></definitions>").deploy(); repositoryService .createDeployment() .addString( "process01.bpmn20.xml", "<definitions xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' targetNamespace='http://activiti.org/BPMN20'>" + "<process id='process01' name='Insurance Damage Report' this_should='fail' /></definitions>").deploy(); } public RepositoryService getRepositoryService() { return repositoryService; } public void setRepositoryService(RepositoryService repositoryService) { this.repositoryService = repositoryService; } }
JavaScript
UTF-8
883
2.5625
3
[]
no_license
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; const { Wizard } = require('./models'); const model = require('./models'); app.use('/*', async (req, res) => { let transaction = await model.sequelize.transaction(); try { const createdWizard = await Wizard.create({ name: 'woahh' }, { transaction }); await transaction.commit(); return res.status(200).json({ model: createdWizard }); } catch (err) { if (transaction.finished != 'commit') await transaction.rollback(); console.log(err); return res.status(500).json({ message: 'something went wrong' }); } // return res.status(500).json({ message: 'hello from the other side ~' }); }); app.listen(PORT, () => { console.log('========='); console.log('YEAHHHHH!'); console.log('========='); });
Shell
UTF-8
1,214
2.984375
3
[]
no_license
#!/bin/bash # install python3 apt-get install python3.9 python3-pip # install docker apt-get install \\n apt-transport-https \\n ca-certificates \\n curl \\n gnupg \\n lsb-release curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg echo \\n "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian \\n $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null apt-get update apt-get install docker-ce docker-ce-cli # nastavení docker registry docker login -u $USER -p $PASS registry.caspiatech.cz # instalace caspia pip repository mkdir -p $HOME/.config/pip/ cat <<EOF >> $HOME/.config/pip/pip.conf [global] index-url = https://$USER:$PASS@pypi.caspiatech.cz/simple extra-index-url = https://pypi.python.org/simple EOF export PIP_INDEX_URL=https://$USER:$PASS@pypi.caspiatech.cz/simple export PIP_EXTRA_INDEX_URL=https://pypi.python.org/simple # instalace caspia-app pip install caspia-app git clone http://repo.caspiatech.cz/configuration/simple-mock mkdir simple-mock-storage cd simple-mock caspia-app create --mock caspia-app start
C#
UTF-8
781
3.03125
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using WildFarm.Foods; namespace WildFarm.Animals { public class Dog : Mammal { private static double GainValue = 0.4; public Dog(string name, double weight, string livingRegion) : base(name, weight, livingRegion) { } public override void AskForFood() { Console.WriteLine("Woof!"); } public override void Eat(Food food) { BaseEat(food, new List<string> { nameof(Meat) }, GainValue); } //public override string ToString() //{ // return $"{this.GetType().Name} [{this.Name}, {this.Weight}, {this.LivingRegion}, {this.FoodEaten}]"; //} } }
Java
UTF-8
9,402
2.890625
3
[]
no_license
package com.example.lenovo.textviewspannerdalogexercise.utils; import android.text.TextUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class DateUtils { public static final String FORMAT_YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static final String FORMAT_COMMON = "yyyy-MM-dd HH:mm:ss"; public static final String FORMAT_COMMON_TIME = "HH:mm:ss"; public static final String FORMAT_NO_SECOND_TIME = "HH:mm"; public static final String FORMAT_COMMON_DAY = "yyyy-MM-dd"; public static final String FORMAT_8_DAY = "yyyyMMdd"; public static final String FORMAT_MMDDHHMM = "MM-dd HH:mm"; public static final String FORMAT_CHINESE = "yyyy年MM月dd日"; public static String formatDate(Date inDate, String pattern) { String ret = null; if (inDate != null && pattern != null) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); ret = sdf.format(inDate); } return ret; } public static String formatDate(Long inDate, String pattern) { return formatDate(new Date(inDate), pattern); } public static Date parseString(String dateString, String pattern) { Date ret = null; try { if (dateString != null && pattern != null) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); ret = sdf.parse(dateString); } } catch (ParseException e) { e.printStackTrace(); } return ret; } public static String convertDateString(String fromFormat, String toFormat, String dateString) { String retString = ""; if (TextUtils.isEmpty(fromFormat) || TextUtils.isEmpty(toFormat) || TextUtils.isEmpty(dateString)) { return ""; } SimpleDateFormat fromformat = new SimpleDateFormat(fromFormat); SimpleDateFormat toformat = new SimpleDateFormat(toFormat); try { Date date = fromformat.parse(dateString); retString = toformat.format(date); } catch (ParseException e) { e.printStackTrace(); } return retString; } /** * 系统时间格式设置 * * @param year * @param month * @param day * @param hourOfDay * @param minute * @param secend * @return */ public static long setTime(String year, String month, String day, String hourOfDay, String minute, String secend) { try { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, Integer.parseInt(year)); c.set(Calendar.MONTH, Integer.parseInt(month) - 1); c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day)); c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourOfDay)); c.set(Calendar.MINUTE, Integer.parseInt(minute)); c.set(Calendar.SECOND, Integer.parseInt(secend)); c.set(Calendar.MILLISECOND, 0); long when = c.getTimeInMillis(); if (when / 1000 < Integer.MAX_VALUE) { // SystemClock.setCurrentTimeMillis(when); return when; } return -1; } catch (Exception e) { e.printStackTrace(); return -1; } } /** * 系统时间格式设置 * * @param pattern 时间格式 * @param day 减去的天数 * @return 减去后的时间 */ public static String getFormatedAddDateTime(String pattern, int day) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date beginDate = new Date(); Calendar date = Calendar.getInstance(); date.setTime(beginDate); date.set(Calendar.DATE, date.get(Calendar.DATE) - day); return sdf.format(date.getTime()); } /** * 将当前时间转化成String型 * * @return */ public static String getToday8() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_8_DAY, Locale.CHINA); String dateString = formatter.format(currentTime); return dateString; } /** * 将当前时间转化成String型 * * @return */ public static String getToday10() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_COMMON_DAY, Locale.CHINA); String dateString = formatter.format(currentTime); return dateString; } /** * 将当前时间转化成String型 * * @return */ public static String getTodayTiemNoSecond() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_NO_SECOND_TIME, Locale.CHINA); String dateString = formatter.format(currentTime); return dateString; } /** * 将当前时间转化成String型 * * @return */ public static String getTodayCommon() { Date currentTime = new Date(System.currentTimeMillis()); SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_COMMON, Locale.CHINA); String dateString = formatter.format(currentTime); return dateString; } /** * 将当前时间转化成String型 * * @return */ public static String getTodayOrderShow() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_MMDDHHMM, Locale.CHINA); String dateString = formatter.format(currentTime); return dateString; } public static String getTodayTiemYesSecond() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_COMMON_TIME, Locale.CHINA); String dateString = formatter.format(currentTime); return dateString; } public static long getNowLong() { return System.currentTimeMillis(); } /** * 时间 计算 * 正常带日期的时间 * * @return */ private static long getNormalTimeMillis(String strTime) { long returnMillis = 0; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date d = null; if(TextUtils.isEmpty(strTime)){ return 0; } try { d = sdf.parse(strTime); returnMillis = d.getTime(); } catch (ParseException e) { e.printStackTrace(); } return returnMillis; } /** * 时间 计算 * * @return */ private static long getTimeMillis(String strTime) { long returnMillis = 0; // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); Date d = null; try { d = sdf.parse(strTime); returnMillis = d.getTime(); } catch (ParseException e) { e.printStackTrace(); } return returnMillis; } /** * 时间是三位的 */ private static long getTimeMillisThree(String strTime) { long returnMillis = 0; SimpleDateFormat sdf = new SimpleDateFormat("H:mm"); Date d = null; try { d = sdf.parse(strTime); returnMillis = d.getTime(); } catch (ParseException e) { e.printStackTrace(); } return returnMillis; } public static String getTimeDifference(String startTime, String endTime) { long longStart = getNormalTimeMillis(startTime); long longEnd = getNormalTimeMillis(endTime); long longExpend = longEnd - longStart; long longMinutes = longExpend / (60 * 1000); return longMinutes + ""; } public static long getTimeDifferenceLng(String startTime, String endTime) { long longStart = getNormalTimeMillis(startTime); long longEnd = getNormalTimeMillis(endTime); long longExpend = longEnd - longStart; long longMinutes = longExpend / (60 * 1000); return longMinutes ; } /*** * 时间比较大小 * @param planTime * @param realTime * @return */ public static boolean timeOut(String planTime, String realTime) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//年-月-日 时-分 try { Date planCanTime = dateFormat.parse(planTime); Date getRealTime = dateFormat.parse(realTime); if (!(getRealTime.getTime() < planCanTime.getTime())) {//后面的时间不小于前面的时间 return true; } } catch (ParseException e) { e.printStackTrace(); } return false; } public static SimpleDateFormat commonDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); public static boolean nowIsLaterThanTarget(String commonFormatTime) { try { long now = System.currentTimeMillis(); long target = commonDateFormat.parse(commonFormatTime).getTime(); if (now > target) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); } return true; } }
PHP
UTF-8
1,391
2.53125
3
[]
no_license
<?php class Login extends Controller { public function index() { if (isset($_SESSION['pseudo'])) { header('Location: ' . WEBROOT); } $data = array( 'error' => "", 'pseudo' => "", 'password' => "", ); $this->loadModel('UserModel'); if (isset($_POST['pseudo']) && isset($_POST['password']) && isset($_POST['token']) && $_POST['token'] == $_SESSION['token']) { $data['pseudo'] = trim(htmlspecialchars($_POST['pseudo'])); $data['password'] = trim(htmlspecialchars($_POST['password'])); if ($this->UserModel->user_exists($data['pseudo']) == false) { $data['error'] = 'Invalid credentials.'; } else { $user = $this->UserModel->get_user('pseudo', $data['pseudo']); if ($user['mail_confirm'] == 0) { header('Location: /index.php/register/confirm'); } else if ($this->UserModel->login($user['pseudo'], $data['password']) == false) { $data['error'] = "Wrong login or password."; } else { header('Location: ' . WEBROOT); } } } $this->loadView('Templates/header'); $this->loadView('Login/index', $data); $this->loadView('Templates/footer'); } }
Python
UTF-8
1,536
2.953125
3
[ "MIT" ]
permissive
"""Map postonal chord names to symbols commonly found on lead sheets.""" from copy import deepcopy from music21.chord import Chord from orbichord.identify import chordSymbolIndex from orbichord.maps import SYMBOL_INDEX_TO_FIGURE def hasChordSymbolFigure(chord : Chord) -> bool: """Return true if the chord has figure. This only applies to chords commonly found on lead sheets. Parameters ---------- chord : Chord Chord to be identified. Return ------ bool: Return if symbol figure exist (named chord). """ key = chordSymbolIndex(chord) return key in SYMBOL_INDEX_TO_FIGURE def chordSymbolFigure( chord : Chord, inversion : int = None, enharmonic : int = 0 ) -> str: """Identify chords based chord symbol figure. This only applies to chords commonly found on lead sheets. Parameters ---------- chord : Chord Chord to be identified. inversion : int, optional Inversion index. enharmonic : int, optional Enharmonic index Return ------ str A string with with the chord symbol figure. """ key = chordSymbolIndex(chord) if key not in SYMBOL_INDEX_TO_FIGURE: return chord.pitchClasses figure, inversions = SYMBOL_INDEX_TO_FIGURE[key] if inversion is None: return figure[enharmonic] key = inversions[inversion] figure, _ = SYMBOL_INDEX_TO_FIGURE[key] return figure[enharmonic]
Ruby
UTF-8
2,429
3.546875
4
[]
no_license
# frozen_string_literal: true module ConnectFour # Board handles the state of the board class Board def initialize @board = Array.new(6) { Array.new(7) { '.' } } end def display display = "\n" @board.each do |line| line.each_with_index do |e, i| display += '| ' if i.zero? display += "#{e} | " end display += "\n" end display += ' 1 2 3 4 5 6 7' end def invalid(pos) if /\A[1-7]\z/.match(pos) && @board[0][pos.to_i - 1] == '.' false else true end end def drop(symbol, pos) row = row(pos - 1) @board[row][pos - 1] = symbol winner?(row, pos - 1) end private def row(pos) 6.times do |i| return 5 - i if @board[5 - i][pos] == '.' end end def winner?(x, y) vertical(x, y) || horizontal(x, y) || diagonal1(x, y) || diagonal2(x, y) end def vertical(x, y) return false if x > 2 @board[x][y] == @board[x + 1][y] && @board[x][y] == @board[x + 2][y] && @board[x][y] == @board[x + 3][y] end def horizontal(x, y) a = Array.new(7) { false } 7.times do |i| j = y + i - 3 a[i] = true if j >= 0 && j < 7 && @board[x][y] == @board[x][j] end a[0] && a[1] && a[2] && a[3] || a[1] && a[2] && a[3] && a[4] || a[2] && a[3] && a[4] && a[5] || a[3] && a[4] && a[5] && a[6] end def diagonal1(x, y) a = Array.new(7) { false } i = 0 while i < 7 j = x + i - 3 k = y + i - 3 a[i] = true if j >= 0 && j < 6 && k >= 0 && k < 7 && @board[x][y] == @board[j][k] i += 1 end a[0] && a[1] && a[2] && a[3] || a[1] && a[2] && a[3] && a[4] || a[2] && a[3] && a[4] && a[5] || a[3] && a[4] && a[5] && a[6] end def diagonal2(x, y) a = Array.new(7) { false } i = 0 while i < 7 j = x - i + 3 k = y + i - 3 a[i] = true if j >= 0 && j < 6 && k >= 0 && k < 7 && @board[x][y] == @board[j][k] i += 1 end a[0] && a[1] && a[2] && a[3] || a[1] && a[2] && a[3] && a[4] || a[2] && a[3] && a[4] && a[5] || a[3] && a[4] && a[5] && a[6] end end end
Shell
UTF-8
589
2.625
3
[]
no_license
#!/usr/bin/env bash echo "initializing submodules" git submodule init git submodule update echo "Deleting the old files" rm ~/.bashrc rm ~/.bash_prompt rm ~/.gitconfig rm ~/.gitignore rm ~/.githelpers rm ~/bin rm ~/.inputrc echo "Symlinking files" ln -s `pwd`/bashrc ~/.bashrc ln -s `pwd`/bash_prompt ~/.bash_prompt ln -s `pwd`/gitconfig ~/.gitconfig ln -s `pwd`/gitignore ~/.gitignore ln -s `pwd`/githelpers ~/.githelpers ln -s `pwd`/bin ~/ ln -s `pwd`/inputrc ~/.inputrc echo "Updating submodules" git submodule foreach git pull origin master --recurse-submodules echo "All done."
Java
UTF-8
347
2.390625
2
[]
no_license
import org.jetbrains.annotations.Contract; public class Task_5 { @Contract("_ -> fail") public static void main(String[] args) { iCanThrowException(); } @Contract(" -> fail") private static void iCanThrowException() { Object ref = null; assert false; final String s = ref.toString(); } }
Python
UTF-8
233
2.640625
3
[]
no_license
secret = [0x46,0x4D,0x43,0x4A,0x31,0x7C,0x6E,0x3B,0x7C,0x68,0x3E,0x6A,0x79,0x40,0x81,0x82,0xA1] string = '' for i in range(len(secret)): print(secret[i]) print(i) print(chr(secret[i]-i)) string += chr(secret[i]-i) print(string)
Java
UTF-8
935
2.71875
3
[ "Apache-2.0" ]
permissive
package com.kevoroid.andhackernews.helpers; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Created by kevin on 5/27/17. */ public class TimeHelper { public static long getCurrentEpochTime() { return System.currentTimeMillis(); } public static long getUnixEpochTime() { return getCurrentEpochTime() / 1000L; } public static boolean isTimePassed(long startTime, long thresholdMills) { return getCurrentEpochTime() - startTime > thresholdMills; } public static String returnActualDate(String epoch) { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()); long actualDate = Long.parseLong(epoch) * 1000L; return sdf.format(new Date(actualDate)); } // used for UnitTest public String returnActualDateNonStatic(String epoch) { return returnActualDate(epoch); } }
Java
UTF-8
2,472
2.65625
3
[]
no_license
package com.alimuya.kevvy.reflect.field; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.VarInsnNode; import com.alimuya.kevvy.reflect.utils.AsmUtils; /** * @author ov_alimuya * */ final class AnalyzerUtils implements Opcodes{ static boolean isReturnNode(AbstractInsnNode node,boolean isVoid){ if(node instanceof InsnNode){ InsnNode var = (InsnNode)node; int opcode = var.getOpcode(); if(isVoid){ return isVoidReturnOpcode(opcode); }else{ return isDataReturnOpcode(opcode); } } return false; } static boolean isThisFieldGet(AbstractInsnNode node,Class<?> claz,String methodDesc){ return isThisFieldOperate(node, claz, true,methodDesc); } static boolean isThisFieldSet(AbstractInsnNode node,Class<?> claz,String methodDesc){ return isThisFieldOperate(node, claz, false,methodDesc); } private static boolean isThisFieldOperate(AbstractInsnNode node,Class<?> claz,boolean isGet,String methodDesc){ if(node instanceof FieldInsnNode){ FieldInsnNode feildNode=(FieldInsnNode)node; boolean isGetDesc = methodDesc!=null && methodDesc.equals("()"+feildNode.desc); boolean isSetDesc = methodDesc!=null && methodDesc.equals("("+feildNode.desc+")V"); if((isGet && isGetDesc) || (!isGet && isSetDesc)){ int opcode=isGet?GETFIELD:PUTFIELD; if(feildNode.getOpcode()==opcode){ String owner = feildNode.owner; String classname = AsmUtils.toAsmCls(claz); return classname.equals(owner); } } } return false; } static boolean isThisPointerLoadNode(AbstractInsnNode node){ if(node instanceof VarInsnNode){ VarInsnNode var = (VarInsnNode)node; return var.getOpcode()==ALOAD && var.var==0; } return false; } static boolean isDataLoadNode(AbstractInsnNode node){ if(node instanceof VarInsnNode){ VarInsnNode var = (VarInsnNode)node; return isNormalLoadOpcode(var.getOpcode()) && var.var==1; } return false; } private static boolean isDataReturnOpcode(int opcode){ return opcode==ARETURN || opcode==IRETURN || opcode==FRETURN || opcode==DRETURN || opcode==LRETURN ; } private static boolean isVoidReturnOpcode(int opcode){ return opcode==RETURN; } private static boolean isNormalLoadOpcode(int opcode){ return opcode==ILOAD || opcode==ALOAD || opcode==FLOAD || opcode==DLOAD || opcode==LLOAD; } }
Markdown
UTF-8
606
2.671875
3
[]
no_license
# Carplanner REST API for making reservations for a rent car ## Setting up the enviroment These instuction are made as a simple reminder how to install pyton virtual enviroment. Also how to get started on your localmachine to create a virtual enviroment: ``` python3 -m venv [NAME OF THE ENVIROMENT] ``` How to start the enviroment: ``` . [NAME OF THE ENVIROMENT]/bin/activate ``` ## Setting up Django How to set up django ``` pip install django ``` If you want to install a specific version of django: ``` pip install django==[VERSION] ``` running the server: ``` python manage.py runserver ```
Java
UTF-8
369
1.945313
2
[]
no_license
package com.hkk.toolsmanage.lickdog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class LickDogBiz { @Autowired private LickDogManager lickDogManager; /** * 新增学生信息 */ public void addStudent() { lickDogManager.addStudent(); } }
Python
UTF-8
1,339
3.40625
3
[ "MIT" ]
permissive
import sys from PyQt5.QtWidgets import * class Window(QWidget): def __init__(self): super().__init__() # Set the window size self.setGeometry(50, 50, 600, 400) # Set the window title self.setWindowTitle("Window") self.UI() def UI(self): # Creating a label widgets self.text = QLabel("Hello world", self) # Create a Enter button enterButton = QPushButton("Enter", self) # Create a Exit button exitButton = QPushButton("Exit", self) # Set Text X, Y Position self.text.move(160, 50) # Set Enter Button X, Y enterButton.move(100, 80) # Set Exit Button X, Y exitButton.move(200, 80) # Enter Button connect/Action enterButton.clicked.connect(self.enterFun) # Exit Button connect/Action exitButton.clicked.connect(self.exitFun) # show self.show() def enterFun(self): self.text.setText("You clicked Enter") self.text.resize(150, 20) def exitFun(self): self.text.setText("You clicked Exit") self.text.resize(150, 20) # Main method def main(): App = QApplication(sys.argv) window = Window() sys.exit(App.exec_()) if __name__ == "__main__": main()
Java
UTF-8
166
1.765625
2
[]
no_license
package com.yue.service; import java.util.List; import com.yue.model.Teacher; public interface ITeacherService { public List<Teacher> queryTeachers(); }
SQL
UTF-8
454
2.5625
3
[]
no_license
set search_path to kaggle_see_click_predict_fix; create view votes_labels as select num_votes from raw_train order by id asc; create view comments_labels as select num_comments from raw_train order by id asc; create view views_labels as select num_views from raw_train order by id asc; \copy (select * from votes_labels) to 'votes.labels' \copy (select * from comments_labels) to 'comments.labels' \copy (select * from views_labels) to 'views.labels'
PHP
UTF-8
777
3.296875
3
[]
no_license
<?php /* Listing 15-2 A PHP Nested Array Being First Encoded to JSON and Then Decoded Back to PHP */ $books = array( array("author" => "Lewis Carroll", "title" => "Alice's Adventures in Wonderland", "year" => 1865), array("author" => "Yann Martel", "title" => "Life of Pi", "year" => 2001), array("author" =>"Junot Diaz", "title" => "The Brief Wondrous Life of Oscar Wao", "year" => 2007), array("author" => "Joseph Heller", "title" => "Catch-22", "year" => 1961), array("author" => "Timothy Findley", "title" => "Pilgrim", "year" => 1999), array("author" => "Fyodor Dostoyevsky", "title" => "Brothers Karamazov", "year" => 1880), ); $json_books = json_encode($books); $decoded_json_books = json_decode($json_books); ?> <pre> <?php var_dump($json_books); ?> <br><br> <?php var_dump($decoded_json_books); ?> </pre>
SQL
UTF-8
3,713
2.90625
3
[ "MIT" ]
permissive
drop sequence weather.zseq_vantage_pro_loop_data; create sequence weather.zseq_vantage_pro_loop_data increment by 1 no minvalue no maxvalue cache 1 start 1; drop table weather.vantage_pro_loop_data; create table weather.vantage_pro_loop_data ( id bigint, eventtime timestamp with time zone not null, bar_trend bigint not null, bar float not null, temp_inside float not null, humidity_inside float not null, temp_outside float not null, wind_speed float not null, wind_speed_ten_min_avg float not null, wind_direction float not null, temp_extra1 float not null, temp_extra2 float not null, temp_extra3 float not null, temp_extra4 float not null, temp_extra5 float not null, temp_extra6 float not null, temp_extra7 float not null, temp_soil1 float not null, temp_soil2 float not null, temp_soil3 float not null, temp_soil4 float not null, temp_leaf1 float not null, temp_leaf2 float not null, temp_leaf3 float not null, temp_leaf4 float not null, humidity_outside float not null, humidity_extra1 float not null, humidity_extra2 float not null, humidity_extra3 float not null, humidity_extra4 float not null, humidity_extra5 float not null, humidity_extra6 float not null, humidity_extra7 float not null, rain_hour_rate float not null, uv float not null, solar_radiation float not null, storm_rain float not null, start_rain_date date not null, rain_day_rate float not null, rain_month_rate float not null, rain_year_rate float not null, et_day float not null, et_month float not null, et_year float not null, moisture_soil1 float not null, moisture_soil2 float not null, moisture_soil3 float not null, moisture_soil4 float not null, wetness_leaf1 float not null, wetness_leaf2 float not null, wetness_leaf3 float not null, wetness_leaf4 float not null, alarm_inside_falling_bar_trend boolean not null, alarm_inside_rising_bar_trend boolean not null, alarm_inside_low_temp boolean not null, alarm_inside_high_temp boolean not null, alarm_inside_low_humidity boolean not null, alarm_inside_high_humidity boolean not null, alarm_rain_high_rate boolean not null, alarm_rain_fifteen_minutes boolean not null, alarm_rain_day_alarm boolean not null, alarm_rain_storm_total boolean not null, alarm_rain_daily_et boolean not null, alarm_outside_low_temp boolean not null, alarm_outside_high_temp boolean not null, alarm_outside_wind_speed boolean not null, alarm_outside_wind_ten_minutes boolean not null, alarm_outside_dew_point_low boolean not null, alarm_outside_dew_point_high boolean not null, alarm_outside_high_heat boolean not null, alarm_outside_low_wind_chill boolean not null, alarm_outside_high_thsw boolean not null, alarm_outside_high_solar_radiation boolean not null, alarm_outside_high_uva boolean not null, alarm_outside_uv_dose boolean not null, alarm_outside_uv_dose_enabled boolean not null, alarms_extra_temp_humidity bigint not null, alarms_soil_leaf bigint not null, transmitter_battery_status bigint not null, cosole_battery_voltage bigint not null, forecast_icon_rain boolean not null, forecast_icon_cloud boolean not null, forecast_icon_partly_cloudy boolean not null, forecast_icon_sun boolean not null, forecast_icon_snow boolean not null, forecast_rule_number bigint not null, time_sunrise time without time zone not null, time_sunset time without time zone not null, constraint zidx_vantage_pro_loop_data_pk_id primary key (id), constraint zidx_vantage_pro_loop_data_uk_eventtime unique (eventtime) ); create index zidx_vantage_pro_loop_data_ik_eventtime on weather.vantage_pro_loop_data (eventtime);
C++
UTF-8
771
2.578125
3
[]
no_license
#include<stdio.h> #define for(p,x,y) for(p=x;p<=y;p++) #define ll long long int ll num=0; bool check(ll a) { if (a<0||a>9) return false; return true; } int solve(ll p,ll q,ll r,ll s) { ll a,b,c,d,count=0; for(a,0,9) { if(check(b=p-a)) if(check(c=q-a)) if(check(d=r-b)) if(c+d==s) count++; } return count; } int main() { ll i[8]={0},sum,a,b; for(i[0],0,9) for(i[1],0,9) for(i[2],0,9) for(i[3],0,9) for(i[4],0,9) for(i[5],0,9) for(i[6],0,9) { sum=i[0]+i[1]+i[2]+i[3]; i[7]=sum-i[4]-i[5]-i[6]; if(!check(i[7])) continue; a=solve(sum-i[0]-i[7],sum-i[1]-i[5],sum-i[2]-i[6],sum-i[3]-i[4]); b=solve(sum-i[0]-i[4],sum-i[1]-i[6],sum-i[2]-i[5],sum-i[3]-i[7]); num+=a*b; } printf("%lld",num); }
Markdown
UTF-8
12,571
2.921875
3
[ "MIT" ]
permissive
# stduuid A C++17 cross-platform single-header library implementation **for universally unique identifiers**, simply know as either UUID or GUID (mostly on Windows). A UUID is a 128-bit number used to uniquely identify information in computer systems, such as database table keys, COM interfaces, classes and type libraries, and many others. [![Build Status](https://travis-ci.org/mariusbancila/stduuid.svg?branch=master)](https://travis-ci.org/mariusbancila/stduuid) [![Tests status](https://ci.appveyor.com/api/projects/status/0kw1n2s2xqxu5m62?svg=true&pendingText=tests%20-%20pending&failingText=tests%20-%20FAILED&passingText=tests%20-%20OK)](https://ci.appveyor.com/project/mariusbancila/stduuid) For information about UUID/GUIDs see: * [Universally unique identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier) * [A Universally Unique IDentifier (UUID) URN Namespace](https://www.ietf.org/rfc/rfc4122.txt) ## Library overview Although the specification puts the uuid library in the `std` namespace, this implementation uses the namespace `uuids` for this purpose, in order to make the library usable without violating the restrictions imposed on the `std` namespace. The following types and utilities are available: Basic types: | Name | Description | | ---- | ----------- | | `uuid` | a class representing a UUID; this can be default constructed (a nil UUID), constructed from a range (defined by a pair of iterators), or from a `span`. | | `uuid_variant` | a strongly type enum representing the type of a UUID | | `uuid_version` | a strongly type enum representing the version of a UUID | Generators: | Name | Description | | ---- | ----------- | | `basic_uuid_random_generator` | a function object that generates version 4 UUIDs using a pseudo-random number generator engine. | | `uuid_random_generator` | a `basic_uuid_random_generator` using the Mersenne Twister engine (`basic_uuid_random_generator<std::mt19937>`) | | `uuid_name_generator` | a function object that generates version 5, name-based UUIDs using SHA1 hashing. | | `uuid_system_generator` | a function object that generates new UUIDs using operating system resources (`CoCreateGuid` on Windows, `uuid_generate` on Linux, `CFUUIDCreate` on Mac) <br><br> **Note**: This is not part of the standard proposal. It is available only if the `UUID_SYSTEM_GENERATOR` macro is defined. | | `uuid_time_generator` | an experimental function object that generates time-based UUIDs.<br><br> **Note**:This is an experimental feature and should not be used in any production code. It is available only if the `UUID_TIME_GENERATOR` macro is defined. | Utilities: | Name | Description | | ---- | ----------- | | `std::swap<>` | specialization of `swap` for `uuid` | | `std::hash<>` | specialization of `hash` for `uuid` (necessary for storing UUIDs in unordered associative containers, such as `std::unordered_set`) | Constants: | Name | Description | | ---- | ----------- | | `uuid_namespace_dns` | Namespace ID for name-based uuids when name string is a fully-qualified domain name. | | `uuid_namespace_url` | Namespace ID for name-based uuids when name string is a URL. | | `uuid_namespace_oid` | Namespace ID for name-based uuids when mame string is an ISO OID (See https://oidref.com/, https://en.wikipedia.org/wiki/Object_identifier). | | `uuid_namespace_x500` | Namespace ID for name-based uuids when name string is an X.500 DN, in DER or a text output format (See https://en.wikipedia.org/wiki/X.500, https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One). | Other: | Name | Description | | ---- | ----------- | | `operator==` and `operator!=` | for UUIDs comparison for equality/inequality | | `operator<` | for comparing whether one UUIDs is less than another. Although this operation does not make much logical sense, it is necessary in order to store UUIDs in a std::set. | | `operator<<` | to write a UUID to an output stream using the canonical textual representation. | | `to_string()` | creates a string with the canonical textual representation of a UUID. | ## Library history This library is an implementation of the proposal [P0959](P0959.md). **As the proposal evolves based on the standard committee and the C++ community feedback, this library implementation will reflect those changes.** See the revision history of the proposal for history of changes. ## Using the library The following is a list of examples for using the library: * Creating a nil UUID ```cpp uuid empty; assert(empty.is_nil()); ``` * Creating a new UUID ```cpp uuid const id = uuids::uuid_system_generator{}(); assert(!id.is_nil()); assert(id.version() == uuids::uuid_version::random_number_based); assert(id.variant() == uuids::uuid_variant::rfc); ``` * Creating a new UUID with a default random generator ```cpp std::random_device rd; auto seed_data = std::array<int, std::mt19937::state_size> {}; std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd)); std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); std::mt19937 generator(seq); uuids::uuid_random_generator gen{generator}; uuid const id = gen(); assert(!id.is_nil()); assert(id.as_bytes().size() == 16); assert(id.version() == uuids::uuid_version::random_number_based); assert(id.variant() == uuids::uuid_variant::rfc); ``` * Creating a new UUID with a particular random generator ```cpp std::random_device rd; auto seed_data = std::array<int, 6> {}; std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd)); std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); std::ranlux48_base generator(seq); uuids::basic_uuid_random_generator<std::ranlux48_base> gen(&generator); uuid const id = gen(); assert(!id.is_nil()); assert(id.as_bytes().size() == 16); assert(id.version() == uuids::uuid_version::random_number_based); assert(id.variant() == uuids::uuid_variant::rfc); ``` * Creating a new UUID with the name generator ```cpp uuids::uuid_name_generator gen(uuids::uuid::from_string("47183823-2574-4bfd-b411-99ed177d3e43").value()); uuid const id = gen("john"); assert(!id.is_nil()); assert(id.version() == uuids::uuid_version::name_based_sha1); assert(id.variant() == uuids::uuid_variant::rfc); ``` * Create a UUID from a string ```cpp auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s; auto id = uuids::uuid::from_string(str); assert(id.has_value()); assert(uuids::to_string(id.value()) == str); // or auto str = L"47183823-2574-4bfd-b411-99ed177d3e43"s; uuid id = uuids::uuid::from_string(str).value(); assert(uuids::to_string<wchar_t>(id) == str); ``` * Creating a UUID from a sequence of 16 bytes ```cpp std::array<uuids::uuid::value_type, 16> arr{{ 0x47, 0x18, 0x38, 0x23, 0x25, 0x74, 0x4b, 0xfd, 0xb4, 0x11, 0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43}}; uuid id(arr); assert(uuids::to_string(id) == "47183823-2574-4bfd-b411-99ed177d3e43"); // or uuids::uuid::value_type arr[16] = { 0x47, 0x18, 0x38, 0x23, 0x25, 0x74, 0x4b, 0xfd, 0xb4, 0x11, 0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 }; uuid id(std::begin(arr), std::end(arr)); assert(uuids::to_string(id) == "47183823-2574-4bfd-b411-99ed177d3e43"); // or uuids::uuid id{{ 0x47, 0x18, 0x38, 0x23, 0x25, 0x74, 0x4b, 0xfd, 0xb4, 0x11, 0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43}}; assert(uuids::to_string(id) == "47183823-2574-4bfd-b411-99ed177d3e43"); ``` * Comparing UUIDs ```cpp uuid empty; uuid id = uuids::uuid_system_generator{}(); assert(empty == empty); assert(id == id); assert(empty != id); ``` * Swapping UUIDs ```cpp uuid empty; uuid id = uuids::uuid_system_generator{}(); assert(empty.is_nil()); assert(!id.is_nil()); std::swap(empty, id); assert(!empty.is_nil()); assert(id.is_nil()); empty.swap(id); assert(empty.is_nil()); assert(!id.is_nil()); ``` * Converting to string ```cpp uuid empty; assert(uuids::to_string(empty) == "00000000-0000-0000-0000-000000000000"); assert(uuids::to_string<wchar_t>(empty) == L"00000000-0000-0000-0000-000000000000"); ``` * Using with an orderered associative container ```cpp std::random_device rd; auto seed_data = std::array<int, std::mt19937::state_size> {}; std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd)); std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); std::mt19937 engine(seq); uuids::uuid_random_generator gen(&engine); std::set<uuids::uuid> ids{uuid{}, gen(), gen(), gen(), gen()}; assert(ids.size() == 5); assert(ids.find(uuid{}) != ids.end()); ``` * Using in an unordered associative container ```cpp std::random_device rd; auto seed_data = std::array<int, std::mt19937::state_size> {}; std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd)); std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); std::mt19937 engine(seq); uuids::uuid_random_generator gen(&engine); std::unordered_set<uuids::uuid> ids{uuid{}, gen(), gen(), gen(), gen()}; assert(ids.size() == 5); assert(ids.find(uuid{}) != ids.end()); ``` * Hashing UUIDs ```cpp using namespace std::string_literals; auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s; uuid id = uuids::uuid::from_string(str).value(); auto h1 = std::hash<std::string>{}; auto h2 = std::hash<uuid>{}; assert(h1(str) == h2(id)); ``` ### Random uuids If you generate uuids using the `basic_uuid_random_generator` and [std::random_device](https://en.cppreference.com/w/cpp/numeric/random/random_device) to seed a generator, keep in mind that this might not be non-deterministic and actually generate the same sequence of numbers: > std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence. This could be a problem with MinGW. See [Bug 85494 - implementation of random_device on mingw is useless](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85494). This was fixed in GCC 9.2. A portable alternative is to use the [Boost.Random](https://www.boost.org/doc/libs/1_78_0/doc/html/boost_random.html) library. ## Support The library is supported on all major operating systems: Windows, Linux and Mac OS. ## Dependencies If you use the library in a project built with C++20, then you can use `std::span`. This is used by default, if the header is supported by your compiler. The check is done with the [__cpp_lib_span](https://en.cppreference.com/w/cpp/utility/feature_test) feature-test macro. Otherwise, such as when building with C++17, `std::span` is not available. However, the [Microsoft Guidelines Support Library](https://github.com/Microsoft/GSL) (aka GSL) can be used for its `span` implementation (from which the standard version was defined). The stduuid library defaults to use this implementation if `std::span` is not available. To ensure `gsl::span` can be used, make sure the GSL library is available, and the GSL include directory is listed in the include directories for the project. If you use cmake to build the test project, make sure the variable called `UUID_USING_CXX20_SPAN` is not defined, or it's value is `OFF` (this is the default value). This will ensure the `gsl` directory will be included in the search list of header directories. ## Testing A testing project is available in the sources. To build and execute the tests do the following: * Clone or download this repository * Create a `build` directory in the root directory of the sources * Run the command `cmake ..` from the `build` directory; if you do not have CMake you must install it first. * Build the project created in the previous step * Run the executable. **Examples** To generate a project files for Visual Studio 2019, you can run the following commands: ``` cd build cmake -G "Visual Studio 17" -A x64 .. ``` To enable the operating system uuid generator set the `UUID_SYSTEM_GENERATOR` variable to `ON`. ``` cd build cmake -G "Visual Studio 17" -A x64 -DUUID_SYSTEM_GENERATOR=ON .. ``` To enable the experimental time-based uuid generator set the `UUID_TIME_GENERATOR` variable to `ON`. ``` cd build cmake -G "Visual Studio 17" -A x64 -DUUID_TIME_GENERATOR=ON .. ``` ## Credits The SHA1 implementation is based on the [TinySHA1](https://github.com/mohaps/TinySHA1) library.
Java
UTF-8
1,506
2.875
3
[]
no_license
/** * Guitar.java * 22-Feb-2014 : 11:13:26 pm * */ package head.first.OOAD.chapter01.RicksGuitarV01; /** * @author ubuntu * @packageName = head.first.OOAD.chapter01.RicksGuitarV01:Guitar.java * @createdOn: 22-Feb-2014 : 11:13:26 pm * * This is a file for my practice and notes of "Head First * OOAD, 1nd edition.". * Anyone can fork this repo, also the official code is available * @(http://www.headfirstlabs.com/books/hfooad/) */ public class Guitar { private String serialNumber, builder, model, type, backWood, topWood; private double price; public Guitar(String serialNumber, double price, String builder, String model, String type, String backWood, String topWood){ this.serialNumber = serialNumber; this.price = price; this.builder = builder; this.model = model; this.type = type; this.backWood = backWood; this.topWood = topWood; } /** * @return the serialNumber */ public String getSerialNumber() { return serialNumber; } /** * @return the builder */ public String getBuilder() { return builder; } /** * @return the model */ public String getModel() { return model; } /** * @return the type */ public String getType() { return type; } /** * @return the backWood */ public String getBackWood() { return backWood; } /** * @return the topWood */ public String getTopWood() { return topWood; } /** * @return the price */ public double getPrice() { return price; } }
JavaScript
UTF-8
8,579
3.015625
3
[]
no_license
'use strict' var gCurrScore; var gBoard = []; var gLevel = { SIZE: 8, MINES: 15 }; var gState = { score: 0, marked: 0 } var gCellExpandedCounter = 0; var gIsGameOver = false; var gIsGameWon = false; var isTimerOn = false; var unsetTime = false; var MINE = '*'; var EMPTY = ' '; var MAXSHOWNCELLS = (gLevel.SIZE * gLevel.SIZE) - gLevel.MINES; function initGame() { gBoard = buildBoard(); renderBoard(gBoard); var elMinesReminder = document.querySelector('.minesReminder'); elMinesReminder.innerText = gLevel.MINES; var elAllCells = document.querySelectorAll('.cell'); for (var i = 0; i < elAllCells.length; i++) { if (elAllCells[i].innerText === MINE) elAllCells[i].classList.add('mineHere'); } var elScoreCounter = document.querySelector('.score'); elScoreCounter.innerHTML = localStorage.getItem('bScore'); elScoreCounter.style = "font-weight:bold;" } function getRandomMines() { var randI = parseInt(Math.random() * gLevel.SIZE); var randJ = parseInt(Math.random() * gLevel.SIZE); var mineCount = 0; // put a mine in a random place, untill mineCount is larger or equal to gLevel.MINES while (mineCount < gLevel.MINES) { if (gBoard[randI][randJ] !== MINE) { mineCount++; gBoard[randI][randJ] = MINE; } randI = parseInt(Math.random() * gLevel.SIZE); randJ = parseInt(Math.random() * gLevel.SIZE); } } function buildBoard() { for (var i = 0; i < gLevel.SIZE; i++) { gBoard.push([]) for (var j = 0; j < gLevel.SIZE; j++) { gBoard[i][j] = EMPTY; } } getRandomMines(); for (var i = 0; i < gBoard.length; i++) { for (var j = 0; j < gBoard.length; j++) { if (gBoard[i][j] === MINE) continue; var countMinesNgbrs = countMinesNgbSpecificCell(i, j); if (countMinesNgbrs) gBoard[i][j] = countMinesNgbrs; } } return gBoard; } function renderBoard(board) { var elBoard = document.querySelector('.elBoard'); var strHTML = ''; for (var i = 0; i < board.length; i++) { strHTML += '<tr>'; for (var j = 0; j < board[i].length; j++) { strHTML += '<td id="' + i + '-' + j + '" class="cell showen cellBorder" onclick="cellClicked(this,' + i + ',' + j + ')" oncontextmenu="cellMarked(this);return false" > ' + board[i][j] + ' </td>'; } strHTML += '</tr>' } elBoard.innerHTML = strHTML; } function countMinesNgbSpecificCell(i, j) { var minesNegCount = 0; for (var a = i - 1; a <= i + 1; a++) { if (a < 0 || a >= gLevel.SIZE) continue; for (var b = j - 1; b <= j + 1; b++) { if (b < 0 || b >= gLevel.SIZE) continue; if (a === i && b === j) continue; if (gBoard[a][b] === MINE) minesNegCount++; } } return minesNegCount; } function cellClicked(elCell, i, j) { if (gIsGameOver) return; var elCellValue = elCell.innerText; if (elCellValue === MINE) { elCell.innerText = ' '; elCell.classList.add('mine'); gIsGameOver = true; var elMineCells = document.querySelectorAll('.mineHere'); for (var i = 0; i < elMineCells.length; i++) { elMineCells[i].classList.remove('showen'); elMineCells[i].classList.add('mine'); } timerToggle(); var elRestartBtn = document.querySelector('.restrtBtn'); elRestartBtn.style.visibility = 'visible'; alert('GAME OVER'); } if (!elCell.classList.contains('flagged')) { if (elCell.classList.contains('showen')) elCell.classList.remove('showen'); var cellHasExpanded = elCell.classList.contains('ngbExpand'); if (cellHasExpanded || gIsGameOver) return; elCell.style.textIndent = "0px"; if (elCellValue !== MINE) { elCell.style.backgroundColor = 'grey'; if (!cellHasExpanded) { if (!elCell.classList.contains('flagged')) { elCell.classList.add('ngbExpand'); gCellExpandedCounter++; } } } if (+elCell.innerHTML === 0) { if (!elCell.classList.contains('flagged')) expandShown(gBoard, elCellValue, i, j); } checkIfGameFinished(); } } function cellMarked(elCell) { if (gIsGameOver) return; if (!elCell.classList.contains('ngbExpand')) { if (elCell.classList.contains('flagged')) { elCell.classList.remove('flagged'); gState.marked--; updateMarkedCounter(-1); } else { elCell.classList.add('flagged'); gState.marked++; updateMarkedCounter(1); } } } function getMineCount() { var mCount = 0; for (var i = 0; i < gBoard.length; i++) { for (var j = 0; j < gBoard[i].length; j++) { if (gBoard[i][j] === MINE) mCount++; } } return mCount; } function checkIfGameFinished() { if (gCellExpandedCounter === MAXSHOWNCELLS) { gIsGameOver = true; gIsGameWon = true; timerToggle(); var elMins = document.getElementById('cMinutes').innerHTML; var elSecs = document.getElementById('cSeconds').innerHTML; gCurrScore = elMins + ':' + elSecs; checkAbsoluteBestScore(); var elRestartBtn = document.querySelector('.restrtBtn'); elRestartBtn.style.visibility = 'visible'; alert('YOU WIN!!!!'); } } function expandShown(board, elCell, i, j) { for (var a = i - 2; a <= i + 2; a++) { if (a < 0 || a >= gLevel.SIZE) continue; for (var b = j - 2; b <= j + 2; b++) { if (b < 0 || b >= gLevel.SIZE) continue; if (a === i && b === j) continue; if (board[a][b] !== MINE) { var elNgbrCell = document.getElementById(a + '-' + b); var cellHasExpanded = elNgbrCell.classList.contains('ngbExpand'); if (!cellHasExpanded) { if (!elNgbrCell.classList.contains('flagged')) { elNgbrCell.classList.add('ngbExpand'); elNgbrCell.classList.remove('showen'); gCellExpandedCounter++; if (gCellExpandedCounter === MAXSHOWNCELLS) gIsGameOver = true; } } if (!elNgbrCell.classList.contains('flagged')) { elNgbrCell.style.textIndent = "0px"; elNgbrCell.style.backgroundColor = 'grey'; } } } } } function updateMarkedCounter(value) { gState.score += value; document.querySelector('.markedCounter').innerText = gState.score; } function timerToggle() { if (isTimerOn) { unsetTime = true; setTime(); } isTimerOn = true; var minutesLabel = document.getElementById("cMinutes"); var secondsLabel = document.getElementById("cSeconds"); var totalSeconds = 0; var timerVar = setInterval(setTime, 1000); function setTime() { if (unsetTime === true) { clearInterval(timerVar); return; } ++totalSeconds; secondsLabel.innerHTML = pad(totalSeconds % 60); minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60)); } function pad(val) { var valString = val + ""; if (valString.length < 2) return "0" + valString; else return valString; } } function checkAbsoluteBestScore() { var bestScore = localStorage.getItem('bScore'); var elScoreCounter = document.querySelector('.score'); if (bestScore === null) elScoreCounter.innerText = '00:00'; else elScoreCounter.innerText = bestScore; if (bestScore === null) { var elMins = document.getElementById('cMinutes').innerHTML; var elSecs = document.getElementById('cSeconds').innerHTML; var elScoreCounter = document.querySelector('.score'); elScoreCounter.innerHTML = elMins + ':' + elSecs; localStorage.setItem('bScore', gCurrScore); } else { var gCurrScoreArr = gCurrScore.split(':'); var bestScoreArr = bestScore.split(':'); if (+gCurrScoreArr[0] < +bestScoreArr[0] || +gCurrScoreArr[1] < +bestScoreArr[1]) { localStorage.setItem('bScore', gCurrScore); elScoreCounter.innerHTML = localStorage.getItem('bScore'); elScoreCounter.style = "font-weight:bold;" } } }
Markdown
UTF-8
3,520
2.828125
3
[]
no_license
--- title: How to configure this blog layout: page comments: yes --- There are three big steps listed below to construct a jekyll blog if I understand right. * Accomplish the first step, you can write blogs already. * For me, the second step is only used for testing. A local server may also be useful for you to browse blogs when you are off line. * The third step gives shows how to correlate github blog with a domain name. #### Basic three steps 1. Create a Github repository, names as `USERNAME`.github.com. 2. Clone a constructed jekyll repository. * Linux: ```git clone https://github.com/plusjade/jekyll-bootstrap.git USERNAME.github.com``` * Windows: Fork the repository [jekyll-bootstrap](https://github.com/plusjade/jekyll-bootstrap/fork) at [github](https://github.com) and clone it to local computer and put it into your local github repository. 3. Write blogs in _post folder according to Markdown syntax and push to Github. *Attention: Please be patient, it may take a while (about `10` minutes) for your blog to be accessed.* Congratulations! You can write things now. #### Install local server Here only lists instructions for Windows system since I am not familar with it. (For Unix-like system, it should be very easy.) 1. Download portable servers from [Madhur](http://www.madhur.co.in/blog/2013/07/20/buildportablejekyll.html) *Set environmental variable from My computer->property->Advanced system settings ->Environmental Variables->PATH `for each program`* 2. Open a `cmd` window and set UTF-8 character by running `chcp 65001` to support Chinese characters if there is any. 3. Go to the directory contains the Github repository locally and run `jekyll serve` to run local server. *Local sever may be helpful for debugging you posts.* #### Get another domain name 1. Get a free domain name from [dot.tk](http://dot.tk). _Forward this domain to USERNAME.github.com may be worked well_ *Remember set the global domain name in _config.xml* 2. Use [DNSpod](https://www.dnspod.cn/) to support domain name parsing. * Register at DNSpod and add the applied tk domain name. * Use DNSpod supported DNS server like `f1g1ns.dnspod.net.` to set your domain name DNS at [dot.tk](http://dot.tk). ![Set tk DNA server]({{ site.img_url }}/tk-set.png) * Manage domain `CNAME` and `A record` at DNApod. ![Set DNSpod]({{ site.img_url }}/DNApod-set.png) #### Refs [http://jekyllbootstrap.com/usage/jekyll-quick-start.html](http://jekyllbootstrap.com/usage/jekyll-quick-start.html) [http://jekyllrb.com/docs/templates/](http://jekyllrb.com/docs/templates/) [http://thinkinside.tk/2013/05/27/jekyll_mysite.html](http://thinkinside.tk/2013/05/27/jekyll_mysite.html) [http://jiyeqian.github.io/2012/07/host-your-pages-at-github-using-jekyll/](http://jiyeqian.github.io/2012/07/host-your-pages-at-github-using-jekyll/) [http://www.madhur.co.in/blog/2013/07/20/buildportablejekyll.html](http://www.madhur.co.in/blog/2013/07/20/buildportablejekyll.html) [http://www.mceiba.com/develop/jekyll-introduction.html](http://www.mceiba.com/develop/jekyll-introduction.html) [http://jiyeqian.github.io/2012/07/host-your-pages-at-github-using-jekyll/](http://jiyeqian.github.io/2012/07/host-your-pages-at-github-using-jekyll/) [http://realasking.github.io/%E7%BD%91%E7%BB%9C%E5%86%B2%E6%B5%AA/2013/07/15/makeblog2/](http://realasking.github.io/%E7%BD%91%E7%BB%9C%E5%86%B2%E6%B5%AA/2013/07/15/makeblog2/)
TypeScript
UTF-8
4,721
2.96875
3
[ "MIT" ]
permissive
import { mat4 as glMat4, vec3 as glVec3, quat as glQuat, vec4 as glVec4 } from "gl-matrix"; import { quat } from "./quat"; import { vec3 } from "./vec3"; import { vec4 } from "./vec4"; import { vec2 } from "./vec2"; export type mat4 = glMat4; export function Matrix4x4(values: number[]) { const mat = glMat4.clone(values as any as glMat4); return mat; } Matrix4x4.identity = () => { const mat = glMat4.create(); return glMat4.identity(mat); } Matrix4x4.rts = (rotation: quat, translation: vec3, scale: vec3) => { const m = mat4.identity(); glMat4.fromRotationTranslationScale(m, rotation, translation, scale); return m; } Matrix4x4.translate = (translate: vec3) => { const m = mat4.identity(); return glMat4.translate(m, glMat4.identity(m), translate); } Matrix4x4.invert = (m: mat4) => { const out = glMat4.create(); glMat4.invert(out, m); return out; } Matrix4x4.getTranslation = (m: mat4) => { let out = vec3(0, 0, 0); glMat4.getTranslation(out as any as glVec3, m); return out; } Matrix4x4.getRotation = (m: mat4) => { let out = glQuat.create(); glMat4.getRotation(out, m); return out; } Matrix4x4.getScaling = (m: mat4) => { let out = vec3(0, 0, 0); glMat4.getScaling(out as any as glVec3, m); return out; }; Matrix4x4.mulPoint = (m: mat4, p: vec3) => { let v = vec4(p.x, p.y, p.z, 1); let out = vec4.zero(); glVec4.transformMat4(out as any as glVec4, v, m); return vec3(out.x, out.y, out.z); } Matrix4x4.mulVector = (m: mat4, v: vec3) => { let v4 = vec4(v.x, v.y, v.z, 0); let out = vec4.zero(); glVec4.transformMat4(out as any as glVec4, v4, m); return vec3(out.x, out.y, out.z); }; Matrix4x4.mulVec4 = (m: mat4, v: vec4) => { let out = vec4.zero(); glVec4.transformMat4(out as any as glVec4, v, m); return out; } Matrix4x4.perspective = (fov: number, aspect: number, near: number, far: number) => { const out = glMat4.create(); return glMat4.perspective(out, fov, aspect, near, far); }; Matrix4x4.transpose = (m: mat4)=> { return glMat4.transpose(glMat4.create(), m); } function simpleOrthogonal(height: number, aspect: number, near: number, far: number) { const out = glMat4.create(); glMat4.ortho(out, -aspect * height, aspect * height, -height, height, near, far); return out; } function orthogonal(height: number, aspect: number, near: number, far: number): mat4 function orthogonal(left: number, right: number, bottom: number, top: number, near: number, far: number): mat4 function orthogonal(...args: number[]): mat4 { if (args.length === 4) return simpleOrthogonal(...(args as [number, number, number, number])); const out = glMat4.create(); glMat4.ortho(...([out, ...args] as Parameters<typeof glMat4.ortho>)); return out; } Matrix4x4.ortho = orthogonal; // (height: number, aspect: number, near: number, far: number) => // { // const out = glMat4.create(); // glMat4.ortho(out, -aspect * height, aspect * height, -height, height, near, far); // return out; // out[0] = 2 / (aspect * height); // out[1] = 0; // out[2] = 0; // out[3] = 0; // out[4] = 0; // out[5] = 2 / height; // out[6] = 0; // out[7] = 0; // out[8] = 0; // out[9] = 0; // out[10] = -2 / (far - near); // out[11] = -(far + near) / (far - near); // out[12] = 0; // out[13] = 0; // out[14] = 0; // out[15] = 1; // return out; // } Matrix4x4.rotate = (m: mat4, axis: vec3, rad: number) => { return glMat4.rotate(glMat4.create(), m, rad, axis); } Matrix4x4.scale = (m: mat4, scaling: vec3) => { return glMat4.scale(glMat4.create(), m, scaling); }; Matrix4x4.fromRotation = (axis: vec3, rad: number) => { return glMat4.fromRotation(glMat4.create(), rad, axis); } Matrix4x4.fromScaling = (scaling: vec3) => { return glMat4.fromScaling(glMat4.create(), scaling); } Matrix4x4.equal = (a: any, b: any) => { if (a === undefined || b === undefined) return false; if (!(a instanceof Array || a instanceof Float32Array) || !(b instanceof Array || b instanceof Float32Array)) return false; return glMat4.exactEquals(a as glMat4, b as glMat4); } type ArithmetricFunction<T> = { (out: T, a: T, b: T): T; (a: T, b: T): T; }; Matrix4x4.mul = ((out: mat4, a: mat4, b: mat4) => { if (!b) { b = a; a = out; out = glMat4.create(); } return glMat4.mul(out, a, b); }) as ArithmetricFunction<mat4>; export const mat4 = Matrix4x4;
Markdown
UTF-8
1,051
2.703125
3
[]
no_license
如果你看到这个页你可以关注下{79px} ==== 可以直接在这里看Demo:http://eternityspring.github.io/79px-html/ <del>这里的东西是{79px}的静态框架。终于花时间整理了一下。大家可以自己下载学习和使用这里的代码和设计。 接下来我会专心的整理基于这里静态页的Drupal模版。然后开始着手下一次的改版。因为我打算每年改版一次,一年就那么任性的折腾自己一次。</del> <del>当然,如果时间允许,我也会考虑基于这个静态文件做一个WordPress主题。当然了,接下来做的Drupal和WordPress主题不是开源的。可能会考虑收费。价格待定。不过肯定在365*2¥以内</del> <del>不过,相信我,接下来的Drupal主题会比这个静态的效果要精致的多。希望大家能多多关注,相信一段忙碌的整理和完善,一定能给你一个big surprise!-.-。</del> --- 以下内容呢更新于 2016年3月15日 -- {79px}改版了。用nodejs做了一个更接近我想法的79px。
TypeScript
UTF-8
517
2.96875
3
[]
no_license
import oneEditAway from "./exercicio1"; import getCharAndCount from "./exercicio2"; //Exercicio 1 console.log(oneEditAway("banan", "banana")); console.log(oneEditAway("bananak", "banana")); console.log(oneEditAway("banara", "banana")); console.log(oneEditAway("bananaaa", "banana")); //Exercicio 2 console.log(getCharAndCount("aabbb")); console.log(getCharAndCount("aabcccccaaa")); console.log(getCharAndCount("accurate")); console.log(getCharAndCount("escola")); console.log(getCharAndCount("accuraaaaaaaaaate"));
C#
UTF-8
1,297
2.8125
3
[ "MIT" ]
permissive
using System; using MyCompiler.Core.Exceptions; using MyCompiler.Core.Models.ConstructionSubsets; using MyCompiler.Core.Models.LexicalAnalyzer; using MyCompiler.Core.Models.SyntacticAnalyzes; namespace MyCompiler.RegularExpressionApp { public class Program { private static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; try { Console.WriteLine("Write your Input: "); var input = Console.ReadLine(); var lexicalAnalyzer = new RegularExpressionLexicalAnalyzer(); var sintaxAnalyzer = new RegularExpressionSyntacticAnalyzer(); var constructionSubsets = new ConstructionSubsets(); var tokens = lexicalAnalyzer.LoadTokens(input); var thompsonConstruction = sintaxAnalyzer.Check(tokens); var locks = constructionSubsets.Generate(thompsonConstruction); constructionSubsets.PrintMatriz(locks); // a(a|b)* } catch (CompilationException) { } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); } } }
Markdown
UTF-8
27,464
3.09375
3
[]
no_license
# 6 작동 위임 Prototoype 체계 - 한 객체가 다른 객체를 참조하기 위한 내부 링크. 이러한 링크는 처음 참조하는 객체에 존재하지 않는 프로퍼티/메서드를 참조하려고 할 경우에 활용됨 엔진은 Prototype 링크를 따라가며 연결된 객체마다 프로퍼티/메서드가 있는지 탐색. 발견되지 않으면 다음 Prototype 링크에 연결된 객체를 타고 이동하며 수색 - 한 무더기의 객체 간 연결고리가 '프로토타입 연쇄' 자바스크립트의 가장 중요한 핵심 기능이자 실제적인 체계는 '객체를 다른 객체와 연결하는 것'에서 비롯 ## 6.1 위임 지향 디자인으로 가는 길 Prototype 사용 방법의 이해를 위해 Prototype이 클래스와는 다른 디자인 패턴이라는 것을 인지해야 함 ### 6.1.1 클래스 이론 클래스 기반 디자인 설계 과정 - 3개의 유사한 태스크(Task, XYZ, ABC)가 있다고 가정 가장 일반적인 부모 클래스와 유사한 태스크의 공통 작동을 정의하는 것부터 착수 Task를 상속받은 2개의 자식 클래스 XYZ, ABC를 정의한 후 이들에 특화된 작동은 두 클래스에 각각 추가함 클래스 디자인 패턴에서는 메서드 오버라이딩(다형성)을 권장하고, 작동 추가뿐 아니라 때에 따라 오버라이드 이전 원본 메서드를 super 키워드로 호출할 수 있게 지원함 공통 요소는 추상화하여 부모 클래스의 일반 메서드로 구현하고 자식클래스는 이를 더 세분화(오버라이드)하여 사용 이러한 과정에 대한 의사 코드 ``` class Task { id; // 'Task()' 생성자 Task(ID) { id = ID; } outputTask() { output(id); } } class XYZ inherits Task { label; // 'XYZ()' 생성자 XYZ(ID, Label) { super(ID); label = Label; } outputTask() { super(); output(label); } } class ABC inherits Task { // ... } ``` 자식 클래스 XYZ의 인스턴스화를 통해 생성된 인스턴스는 XYZ 태스크를 수행 이 인스턴스는 Task의 일반 작동과 XYZ의 특수 작동 사본을 모두 포함, ABC 클래스의 인스턴스 또한 동일한 과정으로 작동 인스턴스가 생성되면 원하는 작동은 인스턴스에 모두 복사되어 옮겨진 상태이므로 일반적으로 (클래스가 아닌) 인스턴스와 상호작용을 하게 됨 ### 6.1.2 위임 이론 동일한 문제에 대한 작동 위임 방식 적용 Task 객체 정의 - 다양한 태스크에서 사용할 유틸리티 메서드가 포함된 구체적인 작동이 기술됨 태스크별(XYZ, ABC) 객체를 정의하여 고유한 데이터와 작동을 정의, Task 유틸리티 객체에 연결해 필요할 때 특정 태스크 객체가 Task에 작동을 위임하도록 작성 XYZ 태스크 하나를 실행하기 위해 2개의 형제, 동료 객체(XYZ, Task)로부터 작동을 가져옴 - 그러나 클래스 복사를 통해 이 둘을 조합하지 않아도 각자 별개의 객체로 분리된 상태에서 필요할 때마다 XYZ 객체가 Task 객체에 작동을 위임하는 구조 ```javascript Task = { setID: function(ID) { this.id = ID; }, outputID: function() { console.log(this.id); } }; // 'XYZ'가 'Task'에 위임 XYZ = Object.create(Task); XYZ.prepareTask = function(ID, Label) { this.setID(ID); this.label = Label; }; XYZ.outputTaskDetails = function() { this.outputID(); console.log(this.label); }; // ABC = Object.create(Task); // ABC... = ... ``` Task와 XYZ는 클래스나 함수가 아닌 평범한 객체 XYZ는 Object.create() 메서드로 Task 객체에 Prototype 위임 OOLO(Objects Lined to Other Objects) 스타일 코드 1. id, label 두 데이터 멤버는 XYZ의 직속 프로퍼티. 일반적으로 Prototype 위임 시 상태값은 위임하는 쪽(XYZ, ABC)에 두고 위임반는 쪽(Task)에는 두지 않음 2. 클래스 디자인 패턴에서는 부모(Task)/자식(XYZ) 양쪽에 메서드 이름을 outputTask로 똑같이 붙여 오버라이드(다형성)를 이용함. 작동 패턴은 정반대. 서로 다른 수준의 Prototype 연쇄에서 같은 명칭이 뒤섞이는 일(가려짐)은 되도록 피해야 함. 같은 이름끼리 충돌하면 레퍼런스를 정확히 가려낼 수 없는 부자연스럽고 취약한 구문이 만들어지므로 작동 위임 패턴에서는 오버라이드하기 좋은 일반적인 메서드 명칭보다는 각 객체의 작동 방식을 잘 설명하는 서술적 명칭이 필요. 메서드 이름으로 작동과 의미를 분명하게 하여 코드의 가독성과 유지 보수성 향상 3. this.setID(ID);는 일단 XYZ 객체 내부에서 setID()를 찾지만 XYZ에는 이 메서드가 존재하지 않으므로 Prototype 위임 링크가 체결된 Task로 이동하여 setID()를 발견. 암시적 호출부에 따른 this 바인딩 규칙에 따라 Task에서 발견한 메서드지만 setID() 실행 시 this는 XYZ로 바인딩 됨. 그 다음 this.oudputID()도 동일. XYZ가 Task에 작동을 위임하므로 Task가 가진 일반적인 유틸리티 메서드는 XYZ가 얼마든지 이용 가능해짐 작동 위임: 찾으려는 프로퍼티/메서드 레퍼런스가 객체에 없으면 다른 객체로 수색 작업을 위임하는 것 부모/자식 클래스, 상속, 다형성 등의 사상과는 완전히 구별되는 디자인 패턴 #### 상호 위임(허용되지 않음) 복수의 객체가 양방향으로 상호 위임을 하면 발생하는 사이클은 허용되지 않음 B->A로 링크된 상태에서 A->B로 링크 시도 시 에러 발생 #### 디버깅 크롬 개발자 툴 기준 (브라우저나 툴마다 보이는 결과가 같지 않음) 전통적인 클래스 생성자 스타일 자바스크립트 코드를 크롬 개발자 툴 콘솔창에 입력한 결과 ```javascript function Foo() {} var a1 = new Foo(); a1; //Foo {} ``` a1는 Foo{}로 평가됨 동일한 코드가 파이어폭스 콘솔창에서는 Object {}로 표시됨 크롬 관점 - {}는 Foo라고 명명된 함수가 생성한 빈 객체임 파이어폭스 관점 - {}는 Object에 의해 일반적으로 생성된 빈 객체 크롬은 실제로 생성을 일으킨 함수명을 내부 프로퍼티로 간주하여 추적하는 반면, 파이어폭스 등 다른 브라우저는 이러한 추가 정보까지 추적하지는 않음 ```javascript function Foo() {} var a1 = new Foo(); a.constructor; // Foo(){} a.constructor.name; // "Foo" ``` 크롬은 Foo 객체 출력 시 .constructor.name만 들여보는가? ```javascript function Foo() {} var a1 = new Foo(); Foo.prototype.constructor = function Gotcha() {}; a.constructor; // Gotcha(){} a.constructor.name; // "Gotcha" a1; // Foo {} ``` a1.constructor.name을 문법에 맞춰 다르게 바꿨으나 크롬 콘솔창에는 Foo라고 표시됨 - 앞의 질문에 대한 답은 'No' OOLO 스타일로 변경한 코드 ```javascript var Foo = {}; var a1 = Object.create(Foo); a1; // Object {} Object.defineProperty(Foo, "constructor", { enumerable: false, value: function Gotcha(){} }); a1; // Gotcha {} ``` 크롬 콘솔창은 .constructor.name을 찾고 이용 크롬의 내부적인 '생성자명' 추적 기능은 자바스크립트 명세 요건과는 별개로 크론 전용 확장 프로그램을 위해 의도적으로 삽입된 것 객체 생성 시 '생성자'를 쓰지 않으면 크롬 내부적으로 생성자명을 추적하지 않는 객체 생성, 그런 객체는 Object {}로 제대로 출력되어 'Object()에 의해 생성된 객체'임을 알 수 있음 OOLO 스타일 코딩의 결함이 아님 - OOLO와 작동 위임 패턴으로 코딩하는 것은 누가 어떤 객체를 생성했는지(어느 함수가 new로 호출됐는지)는 중요하지 않음 크롬의 내부 생성자명 추적 기능은 클래스 스타일 코딩을 포괄하는 경우에는 유용하나 OOLO 위임만 사용하는 경우 고려할 만한 대상은 아님 ### 6.1.3 멘탈 모델 비교 고전적인 (프로토타입) OO 스타일 코드 ```javascript function Foo(who) { this.me = who; } Foo.prototype.identify = function() { return "I am " + this.me; }; function Bar(who) { Foo.call(this, who); } Bar.prototype = Object.create(Foo.prototype); Bar.prototype.speak = function() { alert("Hello, " + this.identify() + "."); }; var b1 = new Bar("b1"); var b2 = new Bar("b2"); b1.speak(); b2.speak(); ``` 자식 클래스 Bar는 부모 클래스 Foo를 상속한 뒤 b1과 b2로 인스턴스화 b1은 Bar.prototype으로 위임되며 이는 다시 Foo.prototype으로 위임됨 동일한 기능의 OOLO 스타일 코드 ```javascript Foo = { init: function(who) { this.me = who; }, identify = function() { return "I am " + this.me; } }; Bar = Object.create(Foo); Bar.speak = function() { alert("Hello, " + this.identify() + "."); }; var b1 = Object.create(Bar); b1.init("b1"); var b2 = Object.create(Bar); b2.init("b2"); b1.speak(); b2.speak(); ``` b1->Bar->Foo로 Prototype 위임 활용, 세 객체는 서로 단단히 연결됨 생성자, 프로토타입, new 호출을 하면서 클래스처럼 보이게 한 장치들을 쓰지 않고 객체를 서로 연결해주기만 함 동일한 기능이라면 클래스 스타일보다 OOLO 스타일의 코드 사용이 더 간단하고 편리 두 예제 코드의 멘탈 모델 개체간 관계 모델링 클래스 스타일 코드(p.153, 154) OOLO 스타일 코드(p.155) - 다른 객체와의 연결에만 집중 ## 6.2 클래스 vs 객체 UI 위젯(버튼, 드롭다운 등) 생성 예제 ### 6.2.1 위젯 클래스 고전적 클래스 디자인 코드 ```javascript // 부모 클래스 function Widget(width, height) { this.width = width || 50; this.height = height || 50; this.$elem = null; } Widget.prototype.render = function($where) { if (this.$elem) { this.$elem.css({ width: this.width + "px", height: this.height + "px", }).appendTo($where); } }; // 자식 클래스 function Button(width, height, label) { // super 생성자 호출 Widget.call(this, width, height); this.label = label || "Default"; this.$elem = $("<button>").text(this.label); } // Button은 Widget으로부터 상속받음 Button.prototype = Object.create(Widget.prototype); // 상속받은 render() 오버라이드 Button.prototype.render = function($where) { // super 호출 Widget.prototype.render.call(this, $where); this.$elem.click(this.onClick.bind(this)); }; Button.prototype.onClick = function(evt) { console.log(this.label + " 버튼이 클릭됨"); }; $(document).ready(function() { var $body = $(document.body); var btn1 = new Button(125, 30, "Hello"); var btn2 = new Button(150, 40, "World"); btn1.render("$body"); btn2.render("$body"); }); ``` 부모 클래스에는 기본 render()만 선언해두고 자식 클래스가 이를 오버라이드하도록 유도 기본 기능을 갈아치우기보다 버튼에만 해당하는 작동을 덧붙여 기본 기능을 증강함 자식 클래스 메서드에서 부모 클래스의 기본 메서드 사용을 위해 가짜 super 호출을 통한 명시적 의사다형성 #### ES6 class 간편 구문 ```javascript class Widget { constructor(width, height) { this.width = width || 50; this.height = height || 50; this.$elem = null; } render($where) { if (this.$elem) { this.$elem.css({ width: this.width + "px", height: this.height + "px" }).appendTo($where); } } } class Button extends Widget { constructor(width, height, label) { super(width, height); this.label = label || "Default"; this.$elem = $("<button>").text(this.label); } render($where) { super($where); this.$elem.click(this.onClick.bind(this)); } onClick(evt) { console.log(this.label + " 버튼이 클릭됨"); } } $(document).ready(function() { var $body = $(document.body); var btn1 = new Button(125, 30, "Hello"); var btn2 = new Button(150, 40, "World"); btn1.render($body); btn2.render($body); }); ``` Prototype 체계에서 실행되므로 진짜 클래스는 아님 ### 6.2.2 위젯 객체의 위임 OLOO 스타일의 위임 적용 ```javascript var Widget = { init: function(width, height) { this.width = width || 50; this.height = height || 50; this.$elem = null; }, insert: function($where) { if (this.$elem) { this.$elem.css({ width: this.width + "px", height: this.height + "px" }).appendTo($where); } } }; var Button = Object.create(Widget); Button.setup = function(width, height, label) { // 위임 호출 this.init(width, height); this.label = label || "Default"; this.$elem = $("<button>").text(this.label); }; Button.build = function($where) { // 위임 호출 this.insert($where); this.$elem.click(this.onClick.bind(this)); }; Button.onClick = function(evt) { console.log(this.label + " 버튼이 클릭됨"); }; $(document).ready(function() { var $body = $(document.body); var btn1 = Object.create(Button); btn1.setup(125, 30, "Hello"); var btn2 = Object.create(Button); btn2.setup(150, 40, "World"); btn1.build($body); btn2.build($body); }); ``` OOLO 관점에서는 Widget이 부모도, Button이 자식도 아님 Widget은 보통 객체 - 갖가지 유형의 위젯이 위임하여 사용할 수 있는 유틸리티 창고 역할 Button - 단독으로 존재하는 객체에 불과(Widget과의 위임 링크는 맺어진 상태) render() 메서드를 공유할 필요는 없으며, 대신 각자 수행하는 임무를 구체적으로 드러낼 수 있는 다른 이름(insert, build)들을 메서드에 부여 init()과 setup() 등 초기화 메서드 이름이 제각각인 이유 위임 디자인 패턴에서는 이름을 공유하지 않고 각각을 더 서술적으로 명명 가능 생성자, .prototype, new 등의 구문도 불필요 클래스 생성 시 한 차례 호출 -> OOLO 패턴에서 호출 부분이 추가됨 클래스 생성자로는 생성과 초기화를 한 번에 해야 하지만 실제로 OOLO 방식처럼 두 단계로 나누어 실행하면 더 유연해지는 경우가 많음 필요에 따라 다른 장소에서 다른 시점에 각자 호출하여 사용 관심사 분리의 원칙(Principle of Seperation of Concerns)이 더 잘 반영된 패턴 ## 6.3 더 간단한 디자인 작동 위임 패턴은 코드의 간결성 향상 뿐만 아니라 더 간단한 코드 아키텍처를 가능하게 함 로그인 페이지 예 - 입력 폼 처리 객체, 서버와 직접 인증(통신)을 수행하는 객체 두 컨트롤러 객체 전형적인 클래스 디자인 패턴 - Controller 클래스에 기본 기능 포함, 이를 상속받은 LoginController와 AuthController 두 자식 클래스가 상황에 맞게 구체적인 작동 로직을 구현하는 식으로 구성됨 ```javascript // 부모 클래스 function Controller() { this.errors = []; } Controller.prototype.showDialog(title, msg) { // 사용자에게 다이얼로그 창으로 타이틀과 메시지를 표시 }; Controller.prototype.success = function (msg) { this.showDialog("Success", msg); }; Controller.prototype.failure = function (err) { this.errors.push(err); this.showDialog("Error", err); }; // 자식 클래스 function LoginController() { Controller.call(this); } // 자식 클래스를 부모 클래스에 연결 LoginController.prototype = Object.create(Controller.prototype); LoginController.prototype.getUser = function () { return document.getElementById("login_username").value; }; LoginController.prototype.getPassword = function () { return document.getElementById("login_password").value; }; LoginController.prototype.validateEntry = function (user, pw) { user = user || this.getUser(); pw = pw || this.getPassword(); if (!(user && pw)) { return this.failure("ID와 비밀번호를 입력하여 주십시오"); } else if (user.length < 5) { return this.failure("비밀번호는 5자 이상이어야 합니다"); } // 검증 통과 return true; }; // 기본 failure() 확장을 위한 오버라이드 LoginController.prototype.failure = function (err) { // super 호출 Controller.prototype.failure.call(this, "로그인 실패: " + err); }; function AuthController(login) { Controller.call(this); // 상속 + 구성 this.login = login; } // 자식 클래스를 부모 클래스에 연결 AuthController.prototype = Object.create(Controller.prototype); AuthController.prototype.server = function (url, data) { return $.ajax({ url: url, data: data }); }; AuthController.prototype.checkAuth = function () { var user = this.login.getUser(); var pw = this.login.getPassword(); if (this.login.validateEntry(user, pw)) { this.server("/check-auth", { user: user, pw: pw }) .then(this.success.bind(this)) .fail(this.failure.bind(this)); } }; // 기본 success() 확장을 위한 오버라이드 AuthController.prototype.success = function () { // super 호출 Controller.prototype.success.call(this, "인증 성공"); }; // failure() 확장을 위한 오버라이드 AuthController.prototype.failure = function (err) { // super 호출 Controller.prototype.failure.call(this, "인증 실패 " + err); }; var auth = new AuthController(); auth.checkAuth( // 상속 + 구성 new LoginController() ); ``` success(), failure(), showDialog() - 모든 컨트롤러가 공유하는 기본 작동이 구현된 메서드 LoginController와 AuthController는 failure()와 success()를 오버라이드하여 기본 작동을 증강시킴 AuthController가 로그인 폼과 연동하기 위해 LoginController 인스턴스 필요 - 멤버 프로퍼티로 보유 AuthController는 LoginController에 대해 알고 있어야 하므로 new LoginController()로 인스턴스화한 뒤 this.login이라는 클래스 멤버 프로퍼티로 참조함 ### 6.3.1 탈클래스화 OOLO 스타일 - 작동 위임 활용 ```javascript var LoginController = { errors: [], getUser: function () { return document.getElementById("login_username").value; }, getPassword: function () { return document.getElementById("login_password").value; }, validateEntry: function (user, pw) { user = user || this.getUser(); pw = pw || this.getPassword(); if (!(user && pw)) { return this.failure("ID와 비밀번호를 입력하여 주십시오"); } else if (user.length < 5) { return this.failure("비밀번호는 5자 이상이어야 합니다"); } // 검증 통과 return true; }, showDialog: function (title, msg) { // 사용자 다이얼로그에 성공했다는 메시지 표시 }, failure: function (err) { this.errors.push(err); this.showDialog("에러", "로그인 실패: " + err); } }; // AuthController가 LoginController에 위임하도록 연결 var AuthController = Object.create(LoginController); AuthController.errors = []; AuthController.checkAuth = function () { var user = this.getUser(); var pw = this.getPassword(); if (this.validateEntry(user, pw)) { this.server("/check-auth", { user: user, pw: pw }) .then(this.accepted.bind(this)) .fail(this.rejected.bind(this)); } }; AuthController.server = function (url, data) { return $.ajax({ url: url, data: data }); }; AuthController.accepted = function () { this.showDialog("성공", "인증 성공"); }; AuthController.rejected = function (err) { this.failure("인증 실패: " + err); }; ``` AuthController, LoginController는 평범한 객체 - 어떤 작업을 시키기 전에 인스턴스화할 필요 없음 ```javascript AuthController.checkAuth(); ``` OOLO 위임 연쇄에 하나 또는 그 이상의 객체를 추가로 생성해야 할 경우 ```javascript var controller1 = Object.create(AuthController); var controller2 = Object.create(AuthController); ``` 작동 위임 패턴에서 AuthController, LoginController는 수평적 객체 - 클래스 지향 패턴처럼 부모/자식 관계를 억지로 맺을 필요 없음 둘 사이 작동을 공유하기 위해 징검다리 역할 Controller가 필요 없음 클래스 자체가 없으므로 클래스 인스턴스화 과정도 생략됨 필요 시 위임을 통해 두 객체가 서로 협조 가능 형태 - 구성 또한 필요 없음 success(), failure() 메서드를 똑같은 이름으로 포함하지 않아도 됨 - 클래스 지향 디자인의 다형성 문제 해결 OOLO 스타일 코드 - 같은 기능을 더 간단한 디자인으로 설계 가능 ## 6.4 더 멋진 구문 ES6 class - 클래스 메서드를 짧은 구문으로 선언 가능 ```javascript class Foo { methodName() {} } ``` 객체 리터럴에 단축 메서드 선언이 가능 - 다음과 같은 OOLO 스타일 객체 선언 가능 ```javascript var Logincontroller = { errors: [], getUser() { // 'function'이 없음 }, getPassword() { } }; ``` 유일한 차이점 - 객체 리터럴에서는 콤마(,)로 원소를 구분지어야 하지만 class 구문은 그럴 필요가 없음 ES6부터 프로퍼티를 하나씩 할당할 때 단축 메서드를 사용하여 객체 리터럴로 나타낼 수 있고 객체 Prototype을 Object.setPrototypeOf()로 간단히 수정 가능 ```javascript var AuthController = { errors: [], checkAuth() { }, server(url, data) { } // ... }; // AuthController를 LoginController에 위임 Object.setPrototypeOf(AuthController, LoginController); ``` ### 6.4.1 비어휘적 식별자 단축 메서드의 결점 ```javascript var Foo = { bar() {} baz: function baz() {} }; ``` 일반 표현식으로 변환 ```javascript var Foo = { bar: function() {} baz: function baz() {} }; ``` 단축 메서드 bar()가 bar 프로퍼티에 붙여진 익명 함수 표현식이 됨 함수 객체 자신에 이름 식별자가 없기 때문 익명 함수에 이름 식별자가 없을 경우의 단점 1. 스택 추적을 통한 디버깅 곤란 2. 재귀, 이벤트 (언)바인딩 등에서 자기 참조가 어려워짐 3. 코드 가독성이 나빠짐 1, 3번은 단축 메서드에 해당되지 않음 비간편 구문에서는 스택 추적 시 이름이 나오지 않는 익명 함수 표현식을 사용, 단축 메서드는 내부 프로퍼티 name에 해당 함수 객체를 정확히 지정하므로 스택 추적에 활용 가능 2번은 단축 메서드의 단점 - 자기 참조에 사용할 수 있는 어휘적 식별자가 없음 ```javascript var Foo = { bar: function(x) { if (x < 10) { return Foo.bar(x * 2); } return x; }, baz: function baz(x) { if (x < 10) { return baz(x * 2); } return x; } }; ``` 여러 객체가 this 바인딩을 통해 위임을 공유하는 함수처럼 할 수 없는 경우도 많음 자기 참조가 필요한 상황에 대비하여 함수 객체의 이름 식별자는 지정하는 것을 권장 단순 함수 선언이라면 단축 메서드보다 baz: function baz(){}와 같이 이름 붙은 함수 표현식 사용이 권장됨 ## 6.5 인트로스펙션 타입 인트로스펙션 - 인스턴스를 조사해 객체 유형을 거꾸로 유추하는 것 클래스 인스턴스에서 타입 인트로스펙션은 주로 인스턴스가 생성된 소스 객체의 구조와 기능을 추론하는 용도로 쓰임 instanceof 연산자로 객체 a1의 기능을 추론하는 코드 ```javascript function Foo() { //... } Foo.prototype.something = function() { //... } var a1 = new Foo(); //중략 if (a1 instanceof Foo) { a1.something(); } ``` Foo.prototype - a1의 Prototype 연쇄에 존재 -> instanceof 연산자는 a1이 Foo 클래스의 인스턴스인 것 같은 결과를 반환 Foo는 일반 객체에 불과, Foo가 참조한 임의의 객체(Foo.prototype)가 우연히 a1에 위임 연결됐을 뿐 instanceof가 a1과 Foo의 관계를 조사하는 듯 보이지만 실제로는 a1과 Foo.prototype 사이의 관계를 알려주는 것 instanceof에 의존하여 인트로스펙션을 하는 것은 혼동을 유발하면서 간접적인 방식이므로 해당 객체를 참조하는 레퍼런스를 지닌 함수가 필요 ```javascript function Foo() {} Foo.prototype... function Bar() {} Bar.prototype = Object.create(Foo.prototype); var b1 = new Bar("b1"); ``` instanceof 연산자와 .prototype을 이용하여 타입 인트로스펙션 실시 ```javascript // Foo와 Bar 관계를 대조 Bar.prototype instanceof Foo; //true Object.getPrototypeOf(Bar.prototype) === Foo.prototype; //true Foo.prototype.isPrototypeOf(Bar.prototype); //true // b1과 Foo, Bar의 관계를 대조 b1 instanceof Foo; //true b1 instanceof Bar; //true Object.getPrototypeOf(b1) === Bar.prototype; //true Foo.prototype.isPrototypeOf(b1); //true Bar.prototype.isPrototypeOf(b1); //true ``` 덕 타이핑(Duck Typing) - 또 다른 타입 인트로스펙션 방식 위임 가능한 something() 함수를 가진 객체와 a1의 관계를 조사하는 대신 a1.something을 테스트해보고 이것을 통과하면 a1은 .something()을 호출할 수 있다고 간주하는 것 ```javascript if (a1.something) { a1.something(); } ``` 덕 타이핑은 원래 테스트 결과 이외에 객체의 다른 기능까지 확장하여 추정하는 경향이 있어 리스크가 더해짐(취약한 디자인) 덕 타이핑 위험성 사례 - ES6 프라미스 어떤 임의의 객체 레퍼런스가 프라미스인지를 판단해야 할 경우 해당 객체가 then() 함수를 가졌는지 조사하는 식으로 테스트 어떤 객체에 then() 메서드가 있으면 ES6 프라미스는 무조건 이 객체를 thenable 하다고 단정, 모든 표준 프라미스 작동 로직을 갖추고 있을 것이라고 예상 우연히 then이라는 이름의 메서드를 가진 non-promise 객체가 있다면 ES6 프라미스 체계와는 분리하여 혼동을 최소화하여야 함 OOLO 스타일 코드의 타입 인트로스펙션 ```javascript var Foo = {}; var Bar = Object.create(Foo); Bar... var b1 = Object.create(Bar); // Foo와 Bar의 관계를 비교 Foo.isPrototypeOf(Bar); //true Object.getPrototypeOf(Bar) === Foo; // true // b1을 Foo, Bar와 비교 Foo.isPrototypeOf(b1); //true Bar.isPrototypeOf(b1); //true Object.getPrototypeOf(b1) === Bar; //true ``` 클래스와의 연관성과 관련된 혼동을 줄 수 있는 instanceof을 사용하지 않음 Foo.prototype, Foo.prototye.isPrototypeOf() 등의 구문도 사용되지 않음 덜 복잡하고 혼동의 여지가 없음
Shell
UTF-8
3,763
2.921875
3
[]
no_license
unset AWS_ACCESS_KEY_ID unset AWS_SECRET_ACCESS_KEY unset AWS_SESSION_TOKEN DURATION=3600 NAME="${4:-$LOGNAME@`hostname -s`}" echo echo USER=$(aws sts get-caller-identity --profile default --query 'Arn' --output text | awk -F: '{print $6}' | awk -F/ '{print $2}') echo echo -e "Hey, \e[1;32m$USER\e[0m!" echo echo "Please enter the PrivateIP/InstanceID/NameTag/KeyName/InstanceState/InstanceSize/Platform that you would like to search... " echo read userinput echo echo "Searching \"$userinput\" across 10 AWS accounts with 15 regions each and will return the prompt within 4 mins..." echo echo account=$(aws iam list-account-aliases --query 'AccountAliases[]' --output text) for region in $(aws ec2 describe-regions --output text | cut -f3) do aws ec2 describe-instances --region $region --profile default --query 'Reservations[].Instances[].{IID:InstanceId,PIP:PrivateIpAddress,Name:Tags[?Key==`Name`]|[0].Value,KeyName:KeyName,InstanceState:State.Name,InstanceType:InstanceType,Platform:Platform}' --output text | grep -i --color=always "$userinput" if [ $? == 0 ] then HITS=$(aws ec2 describe-instances --region $region --profile default --query 'Reservations[].Instances[].{IID:InstanceId,PIP:PrivateIpAddress,Name:Tags[?Key==`Name`]|[0].Value,KeyName:KeyName,InstanceState:State.Name,InstanceType:InstanceType,Platform:Platform}' --output text | grep -i "$userinput" | wc -l) echo echo "The output above is sorted by: InstanceID InstanceState InstanceSize KeyPairName NameTag PrivateIpAddress Platform" echo echo -e "AWS Account : \e[1;32m$account\e[0m (Output Above)" echo "Region Name : $region" echo "Hits : $HITS" echo fi done for ROLE in {arn:aws:iam::101670012301:role/EP-Root-Admin-Role,arn:aws:iam::150121783959:role/EP-Root-Admin-Role,arn:aws:iam::203357732924:role/EP-Root-Admin-Role,arn:aws:iam::589011911289:role/EP-Root-Admin-Role,arn:aws:iam::638857906187:role/EP-Root-Admin-Role,arn:aws:iam::653733036938:role/EP-Root-Admin-Role,arn:aws:iam::760840840568:role/EP-Root-Admin-Role,arn:aws:iam::780477102795:role/EP-Root-Admin-Role,arn:aws:iam::911183197493:role/EP-Root-Admin-Role} do ASSUMEROLE=(`aws sts assume-role --role-arn $ROLE --role-session-name $NAME --duration-seconds $DURATION --profile default --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' --output text`) export AWS_ACCESS_KEY_ID=${ASSUMEROLE[0]} export AWS_SECRET_ACCESS_KEY=${ASSUMEROLE[1]} export AWS_SESSION_TOKEN=${ASSUMEROLE[2]} ACCOUNT=$(aws iam list-account-aliases --query 'AccountAliases[]' --output text) for REGION in $(aws ec2 describe-regions --output text | cut -f3) do aws ec2 describe-instances --region $REGION --query 'Reservations[].Instances[].{IID:InstanceId,PIP:PrivateIpAddress,Name:Tags[?Key==`Name`]|[0].Value,KeyName:KeyName,InstanceState:State.Name,InstanceType:InstanceType,Platform:Platform}' --output text | grep -i --color=always "$userinput" if [ $? == 0 ] then HITS2=$(aws ec2 describe-instances --region $REGION --query 'Reservations[].Instances[].{IID:InstanceId,PIP:PrivateIpAddress,Name:Tags[?Key==`Name`]|[0].Value,KeyName:KeyName,InstanceState:State.Name,InstanceType:InstanceType,Platform:Platform}' --output text | grep -i "$userinput" | wc -l) echo echo "The output above is sorted by: InstanceID InstanceState InstanceSize KeyPairName NameTag PrivateIpAddress Platform" echo echo -e "AWS Account : \e[1;32m$ACCOUNT\e[0m (Output Above)" echo "Region Name : $REGION" echo "Hits : $HITS2" echo fi done done
C#
UTF-8
2,180
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using backEnd.Models; using backEnd.Persistence.IRepositories; using Microsoft.EntityFrameworkCore; namespace backEnd.Persistence.Repositories { public class EmployeeDesignationRepository : Repository<EmployeeDesignation>, IEmployeeDesignationRepository { public EmployeeDesignationRepository(QuonDbContext context) :base(context) { } public async Task<EmployeeDesignation> Find(int id) { return await _context.EmployeeDesignations.FindAsync(id); } public async Task<IEnumerable<EmployeeDesignation>> GetAll() { return await _context.EmployeeDesignations.ToListAsync(); } public async Task<IEnumerable<EmployeeDesignation>> GetAll(Expression<Func<EmployeeDesignation, bool>> predicate) { return await _context.EmployeeDesignations .Where(predicate) .ToListAsync(); } public async Task<IEnumerable<EmployeeDesignation>> GetAll(int pageIndex, int pageSize, Expression<Func<EmployeeDesignation, bool>> predicate) { return await _context.EmployeeDesignations .Where(predicate) .Skip(pageSize * (pageIndex - 1)) .Take(pageSize) .ToListAsync(); } public async Task<int> GetCount() { return await _context.EmployeeDesignations .CountAsync(); } public async Task<int> GetCount(Expression<Func<EmployeeDesignation, bool>> predicate) { return await _context.EmployeeDesignations .CountAsync(predicate); } public async Task<EmployeeDesignation> SingleOrDefault(Expression<Func<EmployeeDesignation, bool>> predicate) { return await _context.EmployeeDesignations .SingleOrDefaultAsync(predicate); } public QuonDbContext _context { get { return dbContext as QuonDbContext; } } } }
Java
UTF-8
39,103
2.0625
2
[]
no_license
package com.artqiyi.dahuashai.payment.domain; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Generated; @Generated("coin_translog") public class CoinTranslogExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; private Integer limit; private Integer offset; public CoinTranslogExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } public void setLimit(Integer limit) { this.limit = limit; } public Integer getLimit() { return limit; } public void setOffset(Integer offset) { this.offset = offset; } public Integer getOffset() { return offset; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andCoinTranslogIdIsNull() { addCriterion("coin_translog_id is null"); return (Criteria) this; } public Criteria andCoinTranslogIdIsNotNull() { addCriterion("coin_translog_id is not null"); return (Criteria) this; } public Criteria andCoinTranslogIdEqualTo(Integer value) { addCriterion("coin_translog_id =", value, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdNotEqualTo(Integer value) { addCriterion("coin_translog_id <>", value, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdGreaterThan(Integer value) { addCriterion("coin_translog_id >", value, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdGreaterThanOrEqualTo(Integer value) { addCriterion("coin_translog_id >=", value, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdLessThan(Integer value) { addCriterion("coin_translog_id <", value, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdLessThanOrEqualTo(Integer value) { addCriterion("coin_translog_id <=", value, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdIn(List<Integer> values) { addCriterion("coin_translog_id in", values, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdNotIn(List<Integer> values) { addCriterion("coin_translog_id not in", values, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdBetween(Integer value1, Integer value2) { addCriterion("coin_translog_id between", value1, value2, "coinTranslogId"); return (Criteria) this; } public Criteria andCoinTranslogIdNotBetween(Integer value1, Integer value2) { addCriterion("coin_translog_id not between", value1, value2, "coinTranslogId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Long value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Long value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Long value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Long value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Long value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Long value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Long> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Long> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Long value1, Long value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Long value1, Long value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserNameIsNull() { addCriterion("user_name is null"); return (Criteria) this; } public Criteria andUserNameIsNotNull() { addCriterion("user_name is not null"); return (Criteria) this; } public Criteria andUserNameEqualTo(String value) { addCriterion("user_name =", value, "userName"); return (Criteria) this; } public Criteria andUserNameNotEqualTo(String value) { addCriterion("user_name <>", value, "userName"); return (Criteria) this; } public Criteria andUserNameGreaterThan(String value) { addCriterion("user_name >", value, "userName"); return (Criteria) this; } public Criteria andUserNameGreaterThanOrEqualTo(String value) { addCriterion("user_name >=", value, "userName"); return (Criteria) this; } public Criteria andUserNameLessThan(String value) { addCriterion("user_name <", value, "userName"); return (Criteria) this; } public Criteria andUserNameLessThanOrEqualTo(String value) { addCriterion("user_name <=", value, "userName"); return (Criteria) this; } public Criteria andUserNameLike(String value) { addCriterion("user_name like", value, "userName"); return (Criteria) this; } public Criteria andUserNameNotLike(String value) { addCriterion("user_name not like", value, "userName"); return (Criteria) this; } public Criteria andUserNameIn(List<String> values) { addCriterion("user_name in", values, "userName"); return (Criteria) this; } public Criteria andUserNameNotIn(List<String> values) { addCriterion("user_name not in", values, "userName"); return (Criteria) this; } public Criteria andUserNameBetween(String value1, String value2) { addCriterion("user_name between", value1, value2, "userName"); return (Criteria) this; } public Criteria andUserNameNotBetween(String value1, String value2) { addCriterion("user_name not between", value1, value2, "userName"); return (Criteria) this; } public Criteria andAccountTypeIsNull() { addCriterion("account_type is null"); return (Criteria) this; } public Criteria andAccountTypeIsNotNull() { addCriterion("account_type is not null"); return (Criteria) this; } public Criteria andAccountTypeEqualTo(Integer value) { addCriterion("account_type =", value, "accountType"); return (Criteria) this; } public Criteria andAccountTypeNotEqualTo(Integer value) { addCriterion("account_type <>", value, "accountType"); return (Criteria) this; } public Criteria andAccountTypeGreaterThan(Integer value) { addCriterion("account_type >", value, "accountType"); return (Criteria) this; } public Criteria andAccountTypeGreaterThanOrEqualTo(Integer value) { addCriterion("account_type >=", value, "accountType"); return (Criteria) this; } public Criteria andAccountTypeLessThan(Integer value) { addCriterion("account_type <", value, "accountType"); return (Criteria) this; } public Criteria andAccountTypeLessThanOrEqualTo(Integer value) { addCriterion("account_type <=", value, "accountType"); return (Criteria) this; } public Criteria andAccountTypeIn(List<Integer> values) { addCriterion("account_type in", values, "accountType"); return (Criteria) this; } public Criteria andAccountTypeNotIn(List<Integer> values) { addCriterion("account_type not in", values, "accountType"); return (Criteria) this; } public Criteria andAccountTypeBetween(Integer value1, Integer value2) { addCriterion("account_type between", value1, value2, "accountType"); return (Criteria) this; } public Criteria andAccountTypeNotBetween(Integer value1, Integer value2) { addCriterion("account_type not between", value1, value2, "accountType"); return (Criteria) this; } public Criteria andTransTypeIsNull() { addCriterion("trans_type is null"); return (Criteria) this; } public Criteria andTransTypeIsNotNull() { addCriterion("trans_type is not null"); return (Criteria) this; } public Criteria andTransTypeEqualTo(String value) { addCriterion("trans_type =", value, "transType"); return (Criteria) this; } public Criteria andTransTypeNotEqualTo(String value) { addCriterion("trans_type <>", value, "transType"); return (Criteria) this; } public Criteria andTransTypeGreaterThan(String value) { addCriterion("trans_type >", value, "transType"); return (Criteria) this; } public Criteria andTransTypeGreaterThanOrEqualTo(String value) { addCriterion("trans_type >=", value, "transType"); return (Criteria) this; } public Criteria andTransTypeLessThan(String value) { addCriterion("trans_type <", value, "transType"); return (Criteria) this; } public Criteria andTransTypeLessThanOrEqualTo(String value) { addCriterion("trans_type <=", value, "transType"); return (Criteria) this; } public Criteria andTransTypeLike(String value) { addCriterion("trans_type like", value, "transType"); return (Criteria) this; } public Criteria andTransTypeNotLike(String value) { addCriterion("trans_type not like", value, "transType"); return (Criteria) this; } public Criteria andTransTypeIn(List<String> values) { addCriterion("trans_type in", values, "transType"); return (Criteria) this; } public Criteria andTransTypeNotIn(List<String> values) { addCriterion("trans_type not in", values, "transType"); return (Criteria) this; } public Criteria andTransTypeBetween(String value1, String value2) { addCriterion("trans_type between", value1, value2, "transType"); return (Criteria) this; } public Criteria andTransTypeNotBetween(String value1, String value2) { addCriterion("trans_type not between", value1, value2, "transType"); return (Criteria) this; } public Criteria andTransTypeSubIsNull() { addCriterion("trans_type_sub is null"); return (Criteria) this; } public Criteria andTransTypeSubIsNotNull() { addCriterion("trans_type_sub is not null"); return (Criteria) this; } public Criteria andTransTypeSubEqualTo(String value) { addCriterion("trans_type_sub =", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubNotEqualTo(String value) { addCriterion("trans_type_sub <>", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubGreaterThan(String value) { addCriterion("trans_type_sub >", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubGreaterThanOrEqualTo(String value) { addCriterion("trans_type_sub >=", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubLessThan(String value) { addCriterion("trans_type_sub <", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubLessThanOrEqualTo(String value) { addCriterion("trans_type_sub <=", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubLike(String value) { addCriterion("trans_type_sub like", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubNotLike(String value) { addCriterion("trans_type_sub not like", value, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubIn(List<String> values) { addCriterion("trans_type_sub in", values, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubNotIn(List<String> values) { addCriterion("trans_type_sub not in", values, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubBetween(String value1, String value2) { addCriterion("trans_type_sub between", value1, value2, "transTypeSub"); return (Criteria) this; } public Criteria andTransTypeSubNotBetween(String value1, String value2) { addCriterion("trans_type_sub not between", value1, value2, "transTypeSub"); return (Criteria) this; } public Criteria andTransFlagIsNull() { addCriterion("trans_flag is null"); return (Criteria) this; } public Criteria andTransFlagIsNotNull() { addCriterion("trans_flag is not null"); return (Criteria) this; } public Criteria andTransFlagEqualTo(Integer value) { addCriterion("trans_flag =", value, "transFlag"); return (Criteria) this; } public Criteria andTransFlagNotEqualTo(Integer value) { addCriterion("trans_flag <>", value, "transFlag"); return (Criteria) this; } public Criteria andTransFlagGreaterThan(Integer value) { addCriterion("trans_flag >", value, "transFlag"); return (Criteria) this; } public Criteria andTransFlagGreaterThanOrEqualTo(Integer value) { addCriterion("trans_flag >=", value, "transFlag"); return (Criteria) this; } public Criteria andTransFlagLessThan(Integer value) { addCriterion("trans_flag <", value, "transFlag"); return (Criteria) this; } public Criteria andTransFlagLessThanOrEqualTo(Integer value) { addCriterion("trans_flag <=", value, "transFlag"); return (Criteria) this; } public Criteria andTransFlagIn(List<Integer> values) { addCriterion("trans_flag in", values, "transFlag"); return (Criteria) this; } public Criteria andTransFlagNotIn(List<Integer> values) { addCriterion("trans_flag not in", values, "transFlag"); return (Criteria) this; } public Criteria andTransFlagBetween(Integer value1, Integer value2) { addCriterion("trans_flag between", value1, value2, "transFlag"); return (Criteria) this; } public Criteria andTransFlagNotBetween(Integer value1, Integer value2) { addCriterion("trans_flag not between", value1, value2, "transFlag"); return (Criteria) this; } public Criteria andTransAmountIsNull() { addCriterion("trans_amount is null"); return (Criteria) this; } public Criteria andTransAmountIsNotNull() { addCriterion("trans_amount is not null"); return (Criteria) this; } public Criteria andTransAmountEqualTo(Integer value) { addCriterion("trans_amount =", value, "transAmount"); return (Criteria) this; } public Criteria andTransAmountNotEqualTo(Integer value) { addCriterion("trans_amount <>", value, "transAmount"); return (Criteria) this; } public Criteria andTransAmountGreaterThan(Integer value) { addCriterion("trans_amount >", value, "transAmount"); return (Criteria) this; } public Criteria andTransAmountGreaterThanOrEqualTo(Integer value) { addCriterion("trans_amount >=", value, "transAmount"); return (Criteria) this; } public Criteria andTransAmountLessThan(Integer value) { addCriterion("trans_amount <", value, "transAmount"); return (Criteria) this; } public Criteria andTransAmountLessThanOrEqualTo(Integer value) { addCriterion("trans_amount <=", value, "transAmount"); return (Criteria) this; } public Criteria andTransAmountIn(List<Integer> values) { addCriterion("trans_amount in", values, "transAmount"); return (Criteria) this; } public Criteria andTransAmountNotIn(List<Integer> values) { addCriterion("trans_amount not in", values, "transAmount"); return (Criteria) this; } public Criteria andTransAmountBetween(Integer value1, Integer value2) { addCriterion("trans_amount between", value1, value2, "transAmount"); return (Criteria) this; } public Criteria andTransAmountNotBetween(Integer value1, Integer value2) { addCriterion("trans_amount not between", value1, value2, "transAmount"); return (Criteria) this; } public Criteria andBalanceIsNull() { addCriterion("balance is null"); return (Criteria) this; } public Criteria andBalanceIsNotNull() { addCriterion("balance is not null"); return (Criteria) this; } public Criteria andBalanceEqualTo(Integer value) { addCriterion("balance =", value, "balance"); return (Criteria) this; } public Criteria andBalanceNotEqualTo(Integer value) { addCriterion("balance <>", value, "balance"); return (Criteria) this; } public Criteria andBalanceGreaterThan(Integer value) { addCriterion("balance >", value, "balance"); return (Criteria) this; } public Criteria andBalanceGreaterThanOrEqualTo(Integer value) { addCriterion("balance >=", value, "balance"); return (Criteria) this; } public Criteria andBalanceLessThan(Integer value) { addCriterion("balance <", value, "balance"); return (Criteria) this; } public Criteria andBalanceLessThanOrEqualTo(Integer value) { addCriterion("balance <=", value, "balance"); return (Criteria) this; } public Criteria andBalanceIn(List<Integer> values) { addCriterion("balance in", values, "balance"); return (Criteria) this; } public Criteria andBalanceNotIn(List<Integer> values) { addCriterion("balance not in", values, "balance"); return (Criteria) this; } public Criteria andBalanceBetween(Integer value1, Integer value2) { addCriterion("balance between", value1, value2, "balance"); return (Criteria) this; } public Criteria andBalanceNotBetween(Integer value1, Integer value2) { addCriterion("balance not between", value1, value2, "balance"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andAwardPercentInvitorIsNull() { addCriterion("award_percent_invitor is null"); return (Criteria) this; } public Criteria andAwardPercentInvitorIsNotNull() { addCriterion("award_percent_invitor is not null"); return (Criteria) this; } public Criteria andAwardPercentInvitorEqualTo(Integer value) { addCriterion("award_percent_invitor =", value, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorNotEqualTo(Integer value) { addCriterion("award_percent_invitor <>", value, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorGreaterThan(Integer value) { addCriterion("award_percent_invitor >", value, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorGreaterThanOrEqualTo(Integer value) { addCriterion("award_percent_invitor >=", value, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorLessThan(Integer value) { addCriterion("award_percent_invitor <", value, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorLessThanOrEqualTo(Integer value) { addCriterion("award_percent_invitor <=", value, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorIn(List<Integer> values) { addCriterion("award_percent_invitor in", values, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorNotIn(List<Integer> values) { addCriterion("award_percent_invitor not in", values, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorBetween(Integer value1, Integer value2) { addCriterion("award_percent_invitor between", value1, value2, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardPercentInvitorNotBetween(Integer value1, Integer value2) { addCriterion("award_percent_invitor not between", value1, value2, "awardPercentInvitor"); return (Criteria) this; } public Criteria andAwardFromUserIdIsNull() { addCriterion("award_from_user_id is null"); return (Criteria) this; } public Criteria andAwardFromUserIdIsNotNull() { addCriterion("award_from_user_id is not null"); return (Criteria) this; } public Criteria andAwardFromUserIdEqualTo(Long value) { addCriterion("award_from_user_id =", value, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdNotEqualTo(Long value) { addCriterion("award_from_user_id <>", value, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdGreaterThan(Long value) { addCriterion("award_from_user_id >", value, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdGreaterThanOrEqualTo(Long value) { addCriterion("award_from_user_id >=", value, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdLessThan(Long value) { addCriterion("award_from_user_id <", value, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdLessThanOrEqualTo(Long value) { addCriterion("award_from_user_id <=", value, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdIn(List<Long> values) { addCriterion("award_from_user_id in", values, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdNotIn(List<Long> values) { addCriterion("award_from_user_id not in", values, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdBetween(Long value1, Long value2) { addCriterion("award_from_user_id between", value1, value2, "awardFromUserId"); return (Criteria) this; } public Criteria andAwardFromUserIdNotBetween(Long value1, Long value2) { addCriterion("award_from_user_id not between", value1, value2, "awardFromUserId"); return (Criteria) this; } public Criteria andTransTimeIsNull() { addCriterion("trans_time is null"); return (Criteria) this; } public Criteria andTransTimeIsNotNull() { addCriterion("trans_time is not null"); return (Criteria) this; } public Criteria andTransTimeEqualTo(Date value) { addCriterion("trans_time =", value, "transTime"); return (Criteria) this; } public Criteria andTransTimeNotEqualTo(Date value) { addCriterion("trans_time <>", value, "transTime"); return (Criteria) this; } public Criteria andTransTimeGreaterThan(Date value) { addCriterion("trans_time >", value, "transTime"); return (Criteria) this; } public Criteria andTransTimeGreaterThanOrEqualTo(Date value) { addCriterion("trans_time >=", value, "transTime"); return (Criteria) this; } public Criteria andTransTimeLessThan(Date value) { addCriterion("trans_time <", value, "transTime"); return (Criteria) this; } public Criteria andTransTimeLessThanOrEqualTo(Date value) { addCriterion("trans_time <=", value, "transTime"); return (Criteria) this; } public Criteria andTransTimeIn(List<Date> values) { addCriterion("trans_time in", values, "transTime"); return (Criteria) this; } public Criteria andTransTimeNotIn(List<Date> values) { addCriterion("trans_time not in", values, "transTime"); return (Criteria) this; } public Criteria andTransTimeBetween(Date value1, Date value2) { addCriterion("trans_time between", value1, value2, "transTime"); return (Criteria) this; } public Criteria andTransTimeNotBetween(Date value1, Date value2) { addCriterion("trans_time not between", value1, value2, "transTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
Markdown
UTF-8
1,667
3.109375
3
[]
no_license
# Prettier 代码格式化程序。 ## 使用方式 1. 在`Visual Studio Code`中安装插件[Prettier - Code formatter](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)。 2. 在`Visual Studio Code`系统设置中,将选择`editor.formatOnSave`改为`true`;同时选项`files.autoSave`的值不能为`autoSaveDelay`。 3. 在项目中使用命令`yarn add prettier --dev`或`npm install prettier --save-dev`安装依赖。 4. 在项目根目录添加`prettier`的配置文件`.prettierrc`,带有可选扩展名:(`.json/.yaml/.yml/.js`无扩展名优先)。 5. 在配置文件中添加如下配置。(为了示例中的注释,使用的`js`代码,实际运用请改为`json`格式)。 推荐的配置项: ```js module.exports = { printWidth: 80, // 一行代码的长度 tabWidth: 2, // 缩进的空格数 useTabs: false, // 使用制表符而不是空格进行缩进 semi: true, // 在语句末尾加上分号 singleQuote: true, // 使用单引号而不是双引号 quoteProps: 'as-needed', // 对对象中key的引号规范 jsxSingleQuote: false, // 在JSX中使用单引号而不是双引号 trailingComma: 'es5', // 多行时尽可能打印尾随逗号(例如:单行数组永远不会出现逗号结尾) bracketSpacing: true, // 在对象文字中的括号之间打印空格(例如:{ age: 18 }) jsxBracketSameLine: false, // JSX Brackets。文档有例子,转去文档看直观一些 arrowParens: 'always', // 在单独的箭头函数参数周围包括括号 endOfLine: 'lf', // 行结束 }; ``` 更多配置请查阅[文档](https://prettier.io/docs/en/options.html)。
Java
UTF-8
189
1.585938
2
[ "Apache-2.0" ]
permissive
package com.stackroute.bookingservice.service; import com.stackroute.kafka.domain.CardDetails; public interface CardService { CardDetails saveCardDetails(CardDetails cardDetails); }
Markdown
UTF-8
952
3.078125
3
[ "MIT" ]
permissive
### Clonando ramas remotas Primero tenemos que clonar el repositorio git correspondiente y meternos en su carpeta: $ git clone git://example.com/myproject $ cd myproject Luego, miramos las ramas que tenemos en local: $ git branch * master Si hubiera alguna rama remota, esta no aparece. Para ver qué ramas hay en remoto tenemos que usar: $ git branch -a * master remotes/origin/HEAD remotes/origin/master remotes/origin/experimental Si queremos obtener en local la rama `experimental` tendremos que ejecutar: $ git checkout experimental Obteniendo por pantalla: Rama 'experimental' configurada para hacer seguimiento a la rama remota 'experimental' de 'origin'. Cambiado a nueva rama 'experimental' Ahora, si miramos las ramas que tenems en local, ya aparecerá nuestra rama `experimental` y podremos trabajar con ella sin problemas: $ git branch * experimental master
Java
UTF-8
5,982
2.296875
2
[]
no_license
package org.hopto.eriksen.controller; import org.hopto.eriksen.domain.SshLogEntry; import org.hopto.eriksen.domain.UserNameStatistics; import org.hopto.eriksen.service.SshLogEntryRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; /** * Created by jens on 2016-10-05. */ @RestController @RequestMapping(value="/sshlog") public class SshLogEntryController { private static final int PAGE_SIZE = 5; private final Logger log = LoggerFactory.getLogger(this.getClass()); private final SshLogEntryRepository sshLogEntryRepository; @Autowired SshLogEntryController(SshLogEntryRepository sshLogEntryRepository) { this.sshLogEntryRepository = sshLogEntryRepository; } /** * Responds with all sshLogEntry sorted by date in descending order. * The first page == 1 * * curl -i http://localhost:8080/sshlog * curl -i http://localhost:8080/sshlog?page=2 * */ @RequestMapping(method = RequestMethod.GET) Page<SshLogEntry> getAllEntries( @RequestParam(value="page", defaultValue = "1") Integer pageNumber) { log.debug("Received a get request to /sshlog with page number " + pageNumber); PageRequest pageRequest = new PageRequest(pageNumber - 1, PAGE_SIZE, Sort.Direction.ASC, "date"); return sshLogEntryRepository.findAll(pageRequest); } /** * Search endpoint using Example.of() * * TODO: This method can't handle a request param which contains "&ipNumber=91.224.161.103" * It would also be great if a more advance search functionality was implemented, e.g Specification<T> * * curl -i http://localhost:8080/sshlog/search?page=1&loggedIn=false&userName=root * */ @RequestMapping(value="/search", method= RequestMethod.GET) Page<SshLogEntry> searchEntries( @RequestParam(value="page", defaultValue = "1") Integer pageNumber, SshLogEntry search) { log.debug("In search endpoint, received number=" + pageNumber); log.debug("In search endpoint, received a search= " + search); PageRequest pageRequest = new PageRequest(pageNumber - 1, PAGE_SIZE, Sort.Direction.ASC, "date"); Example<SshLogEntry> example = Example.of(search); return sshLogEntryRepository.findAll(example, pageRequest); } /** * curl -i -H "Content-Type: application/json" -X POST \ * -d '{"ipNumber":"192.168.1.1", "date":"2016-10-05T12:13:14", "userName":"root", "loggedIn":"false"}' http://localhost:8080/sshlog */ @RequestMapping(method = RequestMethod.POST, consumes = APPLICATION_JSON_VALUE) public ResponseEntity<SshLogEntry> createSshLogEntry(@Valid @RequestBody SshLogEntry sshLogEntry) { log.debug("SshLogEntry received for storage: " + sshLogEntry.toString()); // TODO check for second order injection here?!! // See e.g. https://github.com/coverity/coverity-security-library Example<SshLogEntry> example = Example.of(sshLogEntry); if(sshLogEntryRepository.exists(example)) { log.debug("The SshLogEntry " + sshLogEntry + " already existed, will not store it"); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } else { sshLogEntryRepository.save(sshLogEntry); } HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(ServletUriComponentsBuilder .fromCurrentRequest().path("/{id}") .buildAndExpand(sshLogEntry.getId()).toUri()); return new ResponseEntity<>(sshLogEntry, responseHeaders, HttpStatus.CREATED); } // TODO not complete, see the SshLogEntryRepository.class for fault reason /** * GET - Returns the number of times a user has (tried) to log in. * * curl -i http://localhost:8080/sshlog/userstat */ @RequestMapping(value="/userstat", method= RequestMethod.GET) public ResponseEntity<Map<String, Integer>> getMostFrequentLoginNames() { // Couldn't get this to work // List<UserNameStatistics> respons = sshLogEntryRepository.mostFrequentLoginNames(); // This is a ugly hack to get around the mapping problem above Map<String, Long> usersVsLogin = new HashMap<>(); List<Object[]> foo = sshLogEntryRepository.mostFrequentLoginNames(); for(Object[] obj : foo) { String keyStr = (String) obj[0]; Long value = (Long) obj[1]; usersVsLogin.put(keyStr, value); } HttpHeaders responseHeaders = new HttpHeaders(); return new ResponseEntity(usersVsLogin, responseHeaders, HttpStatus.OK); } /** * GET - a specific item * * curl -i http://localhost:8080/sshlog/1 */ @RequestMapping(value="/{id}", method= RequestMethod.GET) public SshLogEntry getSshLogEntry(@PathVariable("id") long id) { SshLogEntry sshLogEntry = sshLogEntryRepository.findOne(id); if(sshLogEntry != null) { log.debug("Will return a sshLogEntry: " + sshLogEntry); return sshLogEntry; } throw new NotFoundException("A ssh log entry with id " + id + " wasn't found"); } }
C#
UTF-8
4,205
3
3
[ "BSD-2-Clause" ]
permissive
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace LargeSort { class Program { static void Main(string[] args) { FileInfo tSortFile = new FileInfo("data.dat"); int tSortFileLines = 18765432; int tSortAtOnce = 700000; var tQuickSorter = new LargeQuickSorter(new DirectoryInfo("temp_quick"), tSortAtOnce); var tRadixSorter = new LargeRadixSorter(new DirectoryInfo("temp_raix"), tSortAtOnce); var tNopSorter = new NopLargeSorter(new DirectoryInfo("temp_nop"), tSortAtOnce); FileInfo tQuickSortedFile = new FileInfo("quick_sorted.dat"); FileInfo tRadixSortedFile = new FileInfo("radix_sorted.dat"); FileInfo tNopSortedFile = new FileInfo("nop_sorted.dat"); CreateFile(tSortFile, tSortFileLines); Console.WriteLine("radix sort"); Sort(tRadixSorter, tSortFile, tRadixSortedFile, 2); Console.WriteLine(); Console.WriteLine("quick sort"); Sort(tQuickSorter, tSortFile, tQuickSortedFile, 2); Console.WriteLine(); Console.WriteLine("nop sort"); Sort(tNopSorter, tSortFile, tNopSortedFile, 2); Console.WriteLine("owata"); Console.Read(); } private static void Sort(LargeSorter aSorter, FileInfo aSortFile, FileInfo aOutputFile, int aSortIndex) { using(var tReader = new StreamReader(aSortFile.OpenRead())) using (var tWriter = new StreamWriter(aOutputFile.OpenWrite())) { Console.WriteLine(DateTime.Now + "ソートを開始します。"); var tSorter = aSorter; tSorter.Sort(tReader, tWriter, aSortIndex); Console.WriteLine(DateTime.Now + "ソート完了。"); } } private static void CreateFile(FileInfo aFile, int aLineCount) { if (aFile.Exists) aFile.Delete(); Console.WriteLine(DateTime.Now + "ソート対象ファイルを生成します。"); Random tRnd = new Random(34456); using (var tWriter = new StreamWriter(aFile.OpenWrite())) { for (int i = 0; i < aLineCount; i++) { tWriter.WriteLine(CreateLine(tRnd)); } } Console.WriteLine(DateTime.Now + "生成完了 " + aLineCount + "行"); } private static char[] ALPHABET = new char[]{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; private static string CreateRandomString(Random aRnd, int aLength){ StringBuilder tBuilder = new StringBuilder(); for (int i = 0; i < aLength; i++) { tBuilder.Append(ALPHABET[aRnd.Next(ALPHABET.Length)]); } return tBuilder.ToString(); } private static string CreateLine(Random aRnd) { StringBuilder tBuilder = new StringBuilder(); tBuilder.Append(CreateRandomString(aRnd, 10)); tBuilder.Append(','); tBuilder.Append(CreateRandomString(aRnd, 10)); tBuilder.Append(','); tBuilder.Append(CreateRandomString(aRnd, 50)); tBuilder.Append(','); tBuilder.Append(CreateRandomString(aRnd, 21)); tBuilder.Append(','); tBuilder.Append(CreateRandomString(aRnd, 15)); tBuilder.Append(','); tBuilder.Append(CreateRandomString(aRnd, 16)); return tBuilder.ToString(); } } }
Java
UTF-8
191
2.640625
3
[]
no_license
public class Hellojava2 { public static void main(String[] args) { int i = 100; double d = 10.5555; boolean b = true; System.out.println(i); System.out.println(d); } }
Java
UTF-8
2,410
2.453125
2
[]
no_license
package test; import domain.User2; import junit.framework.TestCase; import mappertest9_23.UserMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; /** * Created by tarena on 2016/10/5. */ public class CacheTest extends TestCase { private SqlSessionFactory sqlSessionFactory=null; protected void setUp() throws Exception { InputStream input= Resources.getResourceAsStream("SqlMapConfig.xml"); sqlSessionFactory=new SqlSessionFactoryBuilder().build(input); } /*测试一级缓存*/ public void testCache1(){ SqlSession sqlSession=sqlSessionFactory.openSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); //第一次发起请求,查询id为1的用户 System.out.println(userMapper.findUserById(1)); //中间执行一次更新操作 User2 user=new User2(); user.setId(2); user.setUsername("高健"); user.setAddress("古县"); user.setSex("男"); userMapper.updateUser2(user); sqlSession.commit(); //第二次发起请求,查询id为1的用户 System.out.println(userMapper.findUserById(1)); sqlSession.close(); } public void testCache2(){ SqlSession sqlSession1=sqlSessionFactory.openSession(); SqlSession sqlSession2=sqlSessionFactory.openSession(); SqlSession sqlSession3=sqlSessionFactory.openSession(); //第一次发起请求,查询id为1的用户 UserMapper userMapper1=sqlSession1.getMapper(UserMapper.class); System.out.println(userMapper1.findUserById(1)); sqlSession1.close(); //中间执行一次更新操作 /* UserMapper userMapper3=sqlSession3.getMapper(UserMapper.class); User2 user=new User2(); user.setId(1); user.setUsername("李石锐"); user.setAddress("古县"); user.setSex("男"); userMapper3.updateUser2(user); sqlSession3.commit(); sqlSession3.close();*/ //第二次发起请求,查询id为1的用户 UserMapper userMapper2=sqlSession2.getMapper(UserMapper.class); System.out.println(userMapper2.findUserById(1)); sqlSession2.close(); } }
Java
ISO-8859-2
2,207
2.6875
3
[]
no_license
package H2; import H2.Profiler.Profiles; import Other.UTools; import ij.ImagePlus; import ij.gui.Plot; import ij.io.FileSaver; import ij.io.Opener; public class E2 { public static void main(String[] args) { String PATH = "C:/Users/walup/Documents/Imgenes/skeleton.png"; String PATH_2 = "C:/Users/walup/Documents/Imgenes"; //Open the image Opener opener = new Opener(); ImagePlus img = opener.openImage(PATH); ArrayImageSocket socket = new ArrayImageSocket(img); int[][] imgArray = socket.getPixels(); Profiler profiler = new Profiler(); int midCol = (int)(socket.getWidth()/2.0); int midRow = (int)(socket.getHeight()/2.0); //Get the profiles int[] horizProfile = profiler.getProfile(Profiles.HORIZONTAL, midRow, imgArray,socket.getWidth(),socket.getHeight()); int[] vertProfile = profiler.getProfile(Profiles.VERTICAL, midCol, imgArray,socket.getWidth(),socket.getHeight()); int[] diagProfile = profiler.getProfile(Profiles.DIAGONAL_LEFT, 0, imgArray,socket.getWidth(),socket.getHeight()); //Plot them Plot horizPlot = new Plot("Perfil horizontal,fila: "+midRow,"Pixel","Valor"); Plot vertPlot = new Plot("Perfil vertical,columna: "+midCol,"Pixel","Valor"); Plot diagPlot = new Plot("Perfil diagonal","Pixel","Valor"); UTools tools = new UTools(); //for(int value:horizProfile) { //System.out.println(value); //} socket.meshToGrayImage().show(); horizPlot.add("dot", tools.copyFromIntArray(horizProfile)); vertPlot.add("dot",tools.copyFromIntArray(vertProfile)); diagPlot.add("dot",tools.copyFromIntArray(diagProfile)); ImagePlus horiz = horizPlot.getImagePlus(); ImagePlus vert = vertPlot.getImagePlus(); ImagePlus diag = diagPlot.getImagePlus(); FileSaver saverHoriz = new FileSaver(horiz); saverHoriz.saveAsPng(PATH_2+"/horiz.png"); FileSaver saverVert = new FileSaver(vert); saverVert.saveAsPng(PATH_2+"/vert.png"); FileSaver saverDiag = new FileSaver(diag); saverDiag.saveAsPng(PATH_2+"/diag.png"); FileSaver saverSkel = new FileSaver(socket.meshToGrayImage()); saverSkel.saveAsPng(PATH_2+"/skel_grey.png"); horizPlot.show(); vertPlot.show(); diagPlot.show(); } }
C++
UTF-8
1,981
3.25
3
[]
no_license
#include <algorithm> #include "line_segment.h" LineSegment::LineSegment(const Point3& p1, const Point3& p2) : _p1(p1), _p2(p2) { } std::string LineSegment::to_str(void) const { return _p1.to_str() + std::string(" -- ") + _p2.to_str(); } static inline double clamp(const double val, const double minval, const double maxval) { return std::max(minval, std::min(maxval, val)); } static double parallel_dist(const Point3& p1, const Point3& p2, const Point3& d1, const Point3& d2) { Point3 d1_cross_d2 = d1.cross(d2); return abs(d1_cross_d2.dot(p1 - p2) / d1_cross_d2.norm2()); } double LineSegment::min_dist(const LineSegment& seg) const { const double PARALLEL_THRESHOLD = 0.000001; // Randomly chosen. Point3 d1 = _p2 - _p1; Point3 d2 = seg._p2 - seg._p1; Point3 p1(_p1), p2(seg._p1); Point3 p = p1 - p2; // Pre-compute dot-products. double d1_dot_d2 = d1.dot(d2); double d1_2 = d1.sqnorm2(); double d2_2 = d2.sqnorm2(); double d1_dot_p = d1.dot(p); double d2_dot_p = d2.dot(p); // Compute common denominator for both lambdas. double denom = d1_dot_d2 * d1_dot_d2 - d1_2 * d2_2; // TODO(nitikaaggarwal): If `denom` approaches zero, the segments // are parallel. Use standard formulation to compute minimum distance. if (abs(denom) < PARALLEL_THRESHOLD) { return parallel_dist(p1, p2, d1, d2); } double lambda1 = (d2_2 * d1_dot_p - d1_dot_d2 * d2_dot_p) / denom; double lambda2 = (d1_dot_d2 * d1_dot_p - d1_2 * d2_dot_p) / denom; // Clamp the lambda values to lie between 0 and 1. lambda1 = clamp(lambda1, 0.0, 1.0); lambda2 = clamp(lambda2, 0.0, 1.0); // Get the endpoints of the shortest line-segment joining // the two segments. Point3 endpt1 = p1 + d1 * lambda1; Point3 endpt2 = p2 + d2 * lambda2; return (endpt1 - endpt2).norm2(); }
Java
UTF-8
2,092
2.734375
3
[ "Apache-2.0" ]
permissive
package org.esupportail.ws.remote.beans; import java.io.Serializable; /** * The class that represents accounts. */ public class MsgIdAndPhone implements Serializable { /** * */ private static final long serialVersionUID = -7187358986757940568L; /** * message Id */ private java.lang.Integer msgId; /** * message phone number */ private java.lang.String phoneNumber; /** * Bean constructor. */ public MsgIdAndPhone() { super(); } public MsgIdAndPhone(final java.lang.Integer smsId, final java.lang.String phoneNumber) { super(); this.setMsgId(smsId); this.setPhoneNumber(phoneNumber); } /** * @param smsId the msgId to set */ public void setMsgId(final Integer smsId) { this.msgId = smsId; } /** * @return the msgId */ public Integer getMsgId() { return msgId; } /** * @param phoneNumber the phoneNumber to set */ public void setPhoneNumber(final java.lang.String phoneNumber) { this.phoneNumber = phoneNumber; } /** * @return the phoneNumber */ public java.lang.String getPhoneNumber() { return phoneNumber; } /** * @see java.lang.Object#hashCode() */ @Override public boolean equals(final Object obj) { if (null == obj) { return false; } if (!(obj instanceof MsgIdAndPhone)) { return false; } else { MsgIdAndPhone m = (MsgIdAndPhone) obj; if (null == this.getMsgId() || null == m.getMsgId()) return false; if (null == this.getPhoneNumber() || null == m.getPhoneNumber()) return false; if (!this.getMsgId().equals(m.getMsgId())) return false; if (!this.getPhoneNumber().equals(m.getPhoneNumber())) return false; return true; } } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return super.hashCode(); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "MsgIdAndPhone#" + hashCode() + "[msgId=[" + msgId + "], [phoneNumber=[" + phoneNumber + "]]"; } }
C++
UTF-8
1,023
2.78125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int a[32],b[32]; struct tree{ int n; tree *l,*r; }*root; void build(int as,int ae,int bs,int be,tree*& root) { root->n=b[bs]; int t=find(a+as,a+ae,b[bs])-a; if(t-1<as) root->l=NULL; else{ root->l = new tree; build(as,t-1,bs+1,bs+t-as,root->l); } if(t+1>ae) root->r=NULL; else{ root->r = new tree; build(t+1,ae,bs+1+t-as,be,root->r); } } void level() { queue<tree*> q; q.push(root); vector<int> ans; while(!q.empty()){ ans.push_back(q.front()->n); if(q.front()->r) q.push(q.front()->r); if(q.front()->l) q.push(q.front()->l); q.pop(); } for(int i=0;i<ans.size();++i) cout<<ans[i]<<(i==ans.size()-1?'\n':' '); } int main() { int n; cin>>n; root=new tree; for(int i=0;i<n;++i) cin>>a[i]; for(int i=0;i<n;++i) cin>>b[i]; build(0,n-1,0,n-1,root); level(); return 0; }
Python
UTF-8
1,338
3.390625
3
[ "ISC" ]
permissive
# -*- coding: utf-8 -*- """Defines `json.JSONEncoder` subclass that makes parsed object (including bytes and bitarray) JSON-serializable """ import bitarray import json import sys class JSONEncoder(json.JSONEncoder): """JSON encoder with additional support for bytes and bitarray Examples: >>> JSONEncoder().encode({"field1": 123}) '{"field1": 123}' >>> JSONEncoder().encode({"field1": b'\x12\x34'}) '{"field1": "1234"}' >>> JSONEncoder().encode({"field1": bitarray.bitarray('01010')}) '{"field1": "01010"}' >>> JSONEncoder(compact_bitarray=True).encode({"field1": bitarray.bitarray('01010')}) '{"field1": {"value": "50", "length": 5}}' >>> JSONEncoder().encode({"field1": {"Type": 567}}) '{"field1": {"Type": 567}}' """ def __init__(self, compact_bitarray=False, *args, **kwargs): super().__init__(*args, **kwargs) self._compact_bitarray = bool(compact_bitarray) def default(self, o): if isinstance(o, (bytes, bytearray)): return o.hex() elif isinstance(o, bitarray.bitarray): if self._compact_bitarray: return {'value': o.tobytes().hex(), 'length': len(o)} else: return o.to01() else: super().default(o)
C++
UTF-8
1,121
3.140625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int fence(int left, int right); vector<int> stick; int main(){ int c; cin >> c; vector<int> result; while(c--){ int n; cin >> n; stick.clear(); for(int i=0; i<n; i++){ int temp; cin >> temp; stick.push_back(temp); } result.push_back(fence(0, n-1)); } for(int i=0; i<result.size(); i++){ cout << result[i] << endl; } return 0; } int fence(int left, int right){ if(left>=right){ return stick[left]; } int mid = (left+right)/2; int res = max(fence(left, mid), fence(mid+1, right)); int oL = mid; int oR = mid+1; int minH = min(stick[oL], stick[oR]); res = max(res, minH * 2); while(oL > left || oR < right){ if(oR < right && (oL == left || stick[oL-1] < stick[oR+1])){ minH = min(minH, stick[++oR]); } else{ minH = min(minH, stick[--oL]); } res = max(res, minH * (oR-oL+1)); } return res; }
Shell
UTF-8
2,325
3.53125
4
[]
no_license
# Get SSL Certificates from Let's Encrypt who provides Free SSL Certificates. # Refer to the details for Let's Encrypt official site below. # ⇒ https://letsencrypt.org/ # By the way, expiration date of a cert is 90 days, so you must update within next 90 days later. # ## Install Certbot Client which is the tool to get certificates from Let's Encrypt. # apt -y install certbot # ## Get certificates. # # It needs Web server like Apache httpd or Nginx must be runing on the server you work. # If no Web server is running, skip this section and Refer to the next one # Furthermore, it needs that it's possible to access from the Internet to your working server on port 80 because of verification from Let's Encrypt. # for the option [--webroot], use a directory under the webroot on your server as a working temp # -w [document root] -d [FQDN you'd like to get certs] # FQDN (Fully Qualified Domain Name) : Hostname.Domainname # if you'd like to get certs for more than 2 FQDNs, specify all like below # ex : if get [srv.world] and [www.srv.world] # ⇒ -d srv.world -d dlp.srv.world certbot certonly --webroot -w /var/www/html -d srv.world # for only initial using, register your email address and agree to terms of use # specify valid email address: root@mail.srv.world # agree to the terms of use # success if [Congratulations] is shown # certs are created under the [/etc/letsencrypt/live/(FQDN)/] directory # cert.pem ⇒ SSL Server cert(includes public-key) # chain.pem ⇒ intermediate certificate # fullchain.pem ⇒ combined file cert.pem and chain.pem # privkey.pem ⇒ private-key file # ## If no Web Server is running on your working server # # it's possbile to get certs with using Certbot's Web Server feature. Anyway, it needs that it's possible to access from the Internet to your working server on port 80 because of verification from Let's Encrypt. # for the option [--standalone], use Certbot's Web Server feature # -d [FQDN you'd like to get certs] # FQDN (Fully Qualified Domain Name) : Hostname.Domainname certbot certonly --standalone -d dlp.srv.world # ## For Updating existing certs, Do like follows. # # update all certs which has less than 30 days expiration # if you'd like to update certs which has more than 30 days expiration, add [--force-renew] option certbot renew
JavaScript
UTF-8
2,936
2.640625
3
[]
no_license
// *********************************** // React: // *********************************** import React, {useState,useEffect,useReducer} from 'react'; // *********************************** // Components: // *********************************** import RenderProductCard from './RenderProductCard'; import Filter from './Filter'; // *********************************** // Helpers: // *********************************** import getFetchedData from '../model/getFetchedData'; import getCategories from '../model/getCategories'; // State: // *********************************** import tegState from '../model/tegState'; import chipState from '../model/chipState'; const App = () => { const [searchResult, setSearchData] = useState([]); const [categories, setCategories] = useState([]); const [chips, dispatchChips] = useReducer(chipState,categories); const [teg, dispatchTeg] = useReducer(tegState,[]); // ****************************************************** const selectedChips = (selectdChip) => { /* Checked */ if(selectdChip.status === true){ return dispatchChips({ type : 'CHIPS_CHECKED', playload : { name : selectdChip.name, id : selectdChip.id } }) } /* Unchecked */ if(selectdChip.status === false){ return dispatchChips({ type : 'CHIPS_UNCHECKED', playload : { id : selectdChip.id } }); } /* Selected Teg of Product Card:*/ return dispatchChips({playload: selectdChip}); } const selectedTeg = (teg) => { if(teg.state === true){ return dispatchTeg({ status : 'TEG_CLICKED', playload : { id : teg.id, name : teg.name } }) } if(teg.state === false){ return dispatchTeg({ status : 'TEG_REMOVE', }) } } // ****************************************************** /* Fetch Data */ useEffect(() => { async function useProductData () { setSearchData( await getFetchedData()); } useProductData () }, []); /* Set Filter Chips */ useEffect(() => { setCategories(getCategories(searchResult)); }, [searchResult]); // ****************************************************** return ( <div data-testid="app-wrapper" className="app" data-testid="arr-wrapper" > <Filter categories={categories} teg={teg} selectChips={selectedChips} clickedTeg={selectedTeg}/> <RenderProductCard cardList={searchResult} chipList={chips} clickedTeg={selectedTeg} /> </div> ) } export default App;
JavaScript
UTF-8
1,228
4.25
4
[]
no_license
//Destructuring Assignment array // let number = [1,2,3,4]; // let [a,b,c,d] = number; // console.log(4); // Destructuring Assignment Object // const mhs = { // nama: `Fadli`, // nim: 20102050051, // email: `stupidlearner0407@gmail.com` // } // const {nama,nim,email} = mhs; // console.log(nama); Fadli // console.log(nim); 20102050051 // console.log(email); stupidlearner0407@gmail.com // skipping items // let number = [1,2,3,4]; // let [a,,,d] = number; // console.log(a,d); // Rest parameter // const mhs = { // nama: `Fadli`, // nim: 20102050051, // email: `stupidlearner0407@gmail.com` // } // const {nama,...values}= mhs; // console.log(nama); // console.log(values); // const [a, ...values] = [1,2,3,4,5,6,7,8,] // console.log(a,values); //Assignment tanpa deklarasi object ({nama, nim, email} = {nama:`Fadli`, nim: 1020051, email:`stupidlearner0407@gmail.com`}) console.log(nama,nim,email); // assign ke variable baru const mhs = { nama: `Fadli`, nim: 20102050051, email: `stupidlearner0407@gmail.com` } // const {nama: n, nim: i, email: em = `default@default.com`} = mhs; // console.log(em); function destructuringF({nama,nim}) { return `nama saya ${nama}, nim saya ${nim}.` } console.log(destructuringF(mhs));
C++
UTF-8
4,717
2.625
3
[]
no_license
#include "mpfi.h" #ifndef INTERVAL_H #define INTERVAL_H class Interval { mpfi_t x; bool leftexact; bool rightexact; public: Interval(); Interval(const mp_prec_t); Interval(const mpfi_t); Interval(const double); Interval(const double,const mp_prec_t); Interval(double,double); Interval(double,double,const mp_prec_t); Interval(const mpq_t); Interval(const mpq_t,const mp_prec_t); Interval(const mpq_t,const mpq_t); Interval(const mpq_t,const mpq_t,const mp_prec_t); Interval(const mpfr_t); Interval(const mpfr_t,const mp_prec_t); Interval(const mpfr_t,const mpfr_t); Interval(const mpfr_t,const mpfr_t, const mp_prec_t); ~Interval(); Interval& operator=(const Interval& ); int is_pos(){return mpfi_is_pos(x);}; int is_neg(){return mpfi_is_neg(x);}; int get_left(mpfr_t & Left) const; int get_right(mpfr_t & Right) const; int get_mid(mpfr_t & Mid) const; int get_interval(mpfi_t &) const; mp_prec_t get_precision() const { return mpfi_get_prec(x);}; double get_left_d() const; double get_right_d() const; double get_diam_d() const; int bisect(Interval &,Interval &); friend Interval intersect(const Interval &a,const Interval &b); friend Interval operator+ (const Interval &a, const Interval &b); friend Interval operator+ (const Interval &a, const double &b); friend Interval operator+ (const Interval &a, const unsigned int &b); friend Interval operator+ (const Interval &a, const signed int &b); friend Interval operator+ (const Interval &a, const mpq_t &b); friend Interval operator+ (const Interval &a, const mpfr_t &b); friend Interval operator+ (const double &b, const Interval &a); friend Interval operator+ (const unsigned int &b, const Interval &a); friend Interval operator+ (const signed int &b, const Interval &a); friend Interval operator+ (const mpq_t &b, const Interval &a); friend Interval operator+ (const mpfr_t &b, const Interval &a); friend Interval operator- (const Interval &a, const Interval &b); friend Interval operator- (const Interval &a, const double &b); friend Interval operator- (const Interval &a, const unsigned int &b); friend Interval operator- (const Interval &a, const signed int &b); friend Interval operator- (const Interval &a, const mpq_t &b); friend Interval operator- (const Interval &a, const mpfr_t &b); friend Interval operator- (const double &b, const Interval &a); friend Interval operator- (const unsigned int &b, const Interval &a); friend Interval operator- (const signed int &b, const Interval &a); friend Interval operator- (const mpq_t &b, const Interval &a); friend Interval operator- (const mpfr_t &b, const Interval &a); friend Interval operator* (const Interval &a, const Interval &b); friend Interval operator* (const Interval &a, const double &b); friend Interval operator* (const Interval &a, const unsigned int &b); friend Interval operator* (const Interval &a, const signed int &b); friend Interval operator* (const Interval &a, const mpq_t &b); friend Interval operator* (const Interval &a, const mpfr_t &b); friend Interval operator* (const double &b, const Interval &a); friend Interval operator* (const unsigned int &b, const Interval &a); friend Interval operator* (const signed int &b, const Interval &a); friend Interval operator* (const mpq_t &b, const Interval &a); friend Interval operator* (const mpfr_t &b, const Interval &a); friend Interval operator/ (const Interval &a, const Interval &b); friend Interval operator/ (const Interval &a, const double &b); friend Interval operator/ (const Interval &a, const unsigned int &b); friend Interval operator/ (const Interval &a, const signed int &b); friend Interval operator/ (const Interval &a, const mpq_t &b); friend Interval operator/ (const Interval &a, const mpfr_t &b); friend Interval operator/ (const double &b, const Interval &a); friend Interval operator/ (const unsigned int &b, const Interval &a); friend Interval operator/ (const signed int &b, const Interval &a); friend Interval operator/ (const mpq_t &b, const Interval &a); friend Interval operator/ (const mpfr_t &b, const Interval &a); friend Interval sin(const Interval &); friend Interval cos(const Interval &); friend Interval exp(const Interval &); friend Interval log(const Interval &); friend Interval power(const Interval &,const Interval &); friend Interval power(const Interval &,const double &); friend Interval power(const Interval &,const mpq_t &); friend Interval power(const Interval &,const mpfr_t &); friend Interval abs(const Interval &); }; std::ostream& operator<<(std::ostream&, const Interval&); #endif
Markdown
UTF-8
5,432
2.78125
3
[]
no_license
# Impression Calculator Project solves a [knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem) with repetition via async REST API. The knapsack problem is optimized by reducing input data and finding common divisor for size of knapsack and item. The application is a microservice created in [Dropwizard framework](http://www.dropwizard.io/0.9.2/docs/). In application is used a dependency injection framewrok [Google Guice](https://en.wikipedia.org/wiki/Google_Guice). ## Project Desccription [Impression](https://en.wikipedia.org/wiki/Impression_%28online_media%29) is a measure which is telling how many times a particular advertisement was displayed. It is used in the context of an online advertising. In the beginning we have a number of maximum impressions which you can display in a month. Impressions are selled in campain - it means that there are selled only multiple of campaign from customer. The application calculates how many packages customers should buy to be as close as possible to month's impression quantity and get the greatest price. ### Project input In input to service is JSON: 1. mounthImpressionQuantity - number of maximum impressions which you can display 2. list of a company which buy the impression of an advertisement 1. clientName - customer's name 2. impressionInCampaignQuantity - number of impressions in a single campaign 3. campaignPrice - price of a single campaign ```JSON { "mounthImpressionQuantity":2000000000, "inputImpressionDatas":[ { "clientName":"Test1", "impressionInCampaignQuantity":1000000, "campaignPrice":5000 }, { "clientName":"Test2", "impressionInCampaignQuantity":2000000, "campaignPrice":9000 }, { "clientName":"Test3", "impressionInCampaignQuantity":3000000, "campaignPrice":20000 } ] } ``` ### Project output Calculation output is JSON: 1. list of a company which calculates impressions 1. clientName - customer's name 2. campainToSellQuantity - number of a campain which is selled to the customer 3. impressionSellerSummary - summary of impression's number which is selled to the customer 4. totalProfit - total profit of selling impressions to the customer 2. monthlyTotalProfit - monthly total profit from impressions selled to all customers 3. impressionSummary - summary of impression's number which is selled to the customer. Its value must be less than or equal mounthImpressionQuantity from input. ```JSON { "outputImpressionDatas": [ { "clientName": "Test3", "campainToSellQuantity": 666, "impressionSellerSummary": 1998000000, "totalProfit": 13320000 }, { "clientName": "Test2", "campainToSellQuantity": 0, "impressionSellerSummary": 0, "totalProfit": 0 }, { "clientName": "Test1", "campainToSellQuantity": 2, "impressionSellerSummary": 2000000, "totalProfit": 10000 } ], "monthlyTotalProfit": 13330000, "impressionSummary": 2000000000 } ``` ## Application requirements 1. Java 8 2. Apache Maven 3.3.3 to compile a project 2. To run example increase java memory to 1 Gb ## Run application To run application it is needed to do: Build project in maven. In root folder execute: ``` bash mvn clean install ``` To run application go to ic-rest/target and execute: ``` bash java -Xmx1g -jar ic-rest-1.0-SNAPSHOT.jar server ``` Application is running now. ## Use application ### Use guidline The example input service is in request-soapui-project.xml. It is soapUI project. To start calculation send POST http method with json input to endpoint: ``` http://localhost:8080/impressionCalculator/calculateAsync ``` If server accepts input then send to client: ``` HTTP/1.1 202 Accepted Content-Location: http://localhost:8080/impressionCalculator/calculateAsync/1454841278003 Content-Length: 0 ``` In `Content-Location` server returns link where client gets calculation results. If server occurs error (eg. wrong input format, timeout etc.), server returns suitable http error code. To get calculation results send GET http methot to endpoint: ``` http://localhost:8080/impressionCalculator/calculateAsync/1454841278003 ``` If server calculates correctly results, it returns: ``` HTTP/1.1 200 OK ``` and json output. If during calculation server occurs error (eg. timeout, cache error etc.), server returns suitable http error code. ### Server health checks In dropwizard you can implement a server [health checks](https://dropwizard.github.io/metrics/3.1.0/manual/healthchecks/) to check server's condition in production. Health check is available via rest API. To check a server health check use GET http method and this address: ```bash curl -i localhost:8081/healthcheck ``` Output is: ``` HTTP/1.1 200 OK Date: Sun, 07 Feb 2016 11:04:33 GMT Content-Type: application/json Cache-Control: must-revalidate,no-cache,no-store Content-Length: 61 { "CacheHealth":{ "healthy":true }, "deadlocks":{ "healthy":true } } ``` In this project implement health check to check a size of cache where the application saves calculation results. This health check is named `CacheHealth`. The cache size is full when `CacheHealth` return `"healthy":false`. `Deadlocks` health check is default dropwizard health check.
Shell
UTF-8
1,410
3.796875
4
[ "MIT" ]
permissive
#!/bin/sh ### BEGIN INIT INFO # Provides: looker # Required-Start: $remote_fs $all # Required-Stop: # Default-Start: 2 3 4 5 # Default-Stop: # Short-Description: Looker Web Application ### END INIT INFO # /etc/init.d/looker: start and stop the Looker Web application test -x {{ deploy_dir }}/looker || exit 0 umask 022 # Set some defaults LOOKERDIR={{ deploy_dir }} LOOKERUSER=looker USER=`whoami` if test -f /etc/default/looker; then . /etc/default/looker fi . /lib/lsb/init-functions pidfile=${LOOKERDIR}/.tmp/looker.pid if [ -r ${pidfile} ]; then looker_pid=`cat ${pidfile}` fi if [ "$USER" != "${LOOKERUSER}" ]; then if [ "$USER" = "root" ]; then exec su -l ${LOOKERUSER} -c "$0 $@" fi echo "Script must be run from ${LOOKERUSER} or root. You are '${USER}'" exit 1 fi export PATH="${PATH:+$PATH:}/usr/sbin:/sbin" cd ${LOOKERDIR} start() { log_daemon_msg "Starting Looker Web Application" "looker" || true ./looker start } stop() { log_daemon_msg "Stopping Looker Web Application" "looker" || true ./looker stop } case "$1" in start) start ;; stop) stop ;; restart) log_daemon_msg "Restarting Looker Web Application" "looker" || true ./looker restart ;; status) ./looker status exit $? ;; *) log_action_msg "Usage: /etc/init.d/looker {start|stop|restart|status}" || true exit 1 esac exit 0
Markdown
UTF-8
3,265
3.84375
4
[]
no_license
# 426. Binary Tree Vertical Order Traversal Given a binary tree, return the vertical order traversal of its nodes' values. \(ie, from top to bottom, column by column\). If two nodes are in the same row and column, the order should be from left to right. Examples: 1. Given binary tree `[3,9,20,null,null,15,7]`, ```text 3 /\ / \ 9 20 /\ / \ 15 7 ``` return its vertical order traversal as: ```text [9,3,15,20,7] ``` 2. Given binary tree `[3,9,8,4,0,1,7]`, ```text 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7 ``` return its vertical order traversal as: ```text [4,9,3,0,1,8,7] ``` 3. Given binary tree `[3,9,8,4,0,1,7,null,null,null,2,5]` \(0's right child is 2 and 1's left child is 5\), ```text 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7 /\ / \ 5 2 ``` return its vertical order traversal as: ```text [4,9,5,3,0,1,8,2,7] ``` ### 思路: 用treeMap, key是horizontal distance(hd\) , value 是 list of node 在这个vertical上。 同过level order traverse 来保证top-to-bottom的顺序, 在通过treemap的ascending order 性质,保证从左到右的顺序,也就是hd从小到大。这里hd以root为中心\(即0\), 往左一个verical 就-1, 往右一个vertical就+1 额外data structure 除了treeMap, 还需要2个queue,一个用来做level order traverse存node, 另一个queue用来同步存每个node的hd,方便traverse的时候调用。 最后把node从treemap里按顺序拿出来就好了,不管是打印还是放入result list里。 ### code: ```java public class Solution { public List<Integer> verticalOrder(TreeNode root) { // Write your solution here List<Integer> res = new ArrayList<>(); if(root == null){ return res; } // horizontalDistance(hd) -> list of node. use tree map to keep the hd sorted. Map<Integer, ArrayList<TreeNode>> treeMap = new TreeMap<>(); Queue<TreeNode> elQ = new LinkedList<>(); Queue<Integer> hdQ = new LinkedList<>(); elQ.offer(root); hdQ.offer(0); //level order traverse while(!elQ.isEmpty()){ TreeNode cur = elQ.poll(); int hd = hdQ.poll(); //if the map doesnt contain this hd if(treeMap.get(hd) == null){ treeMap.put(hd, new ArrayList()); } //add current node to the map ArrayList<TreeNode> temp = treeMap.get(hd); temp.add(cur); treeMap.put(hd,temp); //如果左边不为空,加左边,记录对应hd。 if(cur.left != null){ elQ.offer(cur.left); hdQ.offer(hd - 1); } //如果右边不为空,加入queue用来lvl order traverse, 同时加入对应的hd, 用来记录node与其对应的hd。 if(cur.right != null){ elQ.offer(cur.right); hdQ.offer(hd + 1); } } //postprocess put value in map into our result list for(Map.Entry<Integer, ArrayList<TreeNode>> entry: treeMap.entrySet()){ ArrayList<TreeNode> list = entry.getValue(); for(TreeNode node : list){ res.add(node.key); } } return res; } } ```
JavaScript
UTF-8
1,242
2.875
3
[]
no_license
window.onload=function(){ writeAll(); document.getElementById("search").addEventListener("blur", function(){ $.ajax({ url:"course.php", dataType:"json", method:"post", success:function(data){ let html=$("#search").val(); data=data.filter(p=>p.name.toUpperCase().indexOf(html.toUpperCase())!=-1); writeAll(data); }, error:function(error){ console.log(error); } }) }) } function writeAll(){ $.ajax({ url:"course.php", method: "post", dataType: "json", data:{ }, success: function(data){ let ispis=""; for(let item of data){ ispis+=` <h4 class="heading">${item.name}</h4> <img src="images/${item.src}" alt="${item.name}"> <a href="course/${item.link}"><button type="button" class="btn btn-info btn-lg courseBtn">Look</button></a> `; } $("#item").html(ispis); }, error:function(error){ console.log(error); } }) }
JavaScript
UTF-8
105
3.046875
3
[]
no_license
let lowerCaseString = str => str.toLowerCase(); let test = lowerCaseString("AsHkAn"); console.log(test);
C++
UTF-8
23,109
2.515625
3
[]
no_license
#ifndef __SUBFUNC_CPP__ #define __SUBFUNC_CPP__ #include "ConstPara.h" #include "matrix3D.h" // #include <math.h> #include <cmath> using namespace std; // ########################## // Define initial condition // ########################## matrix InitialCondition(double x, double y, double z) { // Sod shock tube matrix temp(5); if (sqrt(x * x + y * y + z * z) < 0.5 * L) { temp(1) = 1.0; // density temp(2) = 0.0; // velocity x temp(3) = 0.0; // velocity y temp(4) = 0.0; // velocity z double P = 1.0; // pressure temp(5) = P / (mygamma - 1.0) + 0.5 * temp(1) * (pow(temp(2), 2.0) + pow(temp(3), 2.0) + pow(temp(4), 2.0)); // energy density } else { temp(1) = 0.125; // density temp(2) = 0.0; // velocity x temp(3) = 0.0; // velocity y temp(4) = 0.0; // velocity z double P = 0.1; // pressure temp(5) = P / (mygamma - 1.0) + 0.5 * temp(1) * (temp(3) * temp(3)); // energy density } // conserved variables [0/1/2/3/4] <--> [density/momentum x/momentum y/momentum z/energy] temp(2) = temp(1) * temp(2); temp(3) = temp(1) * temp(3); temp(4) = temp(1) * temp(4); return temp; } // ########################## // Define boundary condition by setting ghost zones // ########################## void BoundaryCondition(matrix &U) { // outflow x for (int i = 1; i <= nghost; i++) { for (int j = 1; j <= NY_In; j++) { for (int k = 1; k <= foo_In; k++) { U(1, i, j + nghost, k + nghost) = U(1, nghost + 1, j + nghost, k + nghost); U(2, i, j + nghost, k + nghost) = U(2, nghost + 1, j + nghost, k + nghost); U(3, i, j + nghost, k + nghost) = U(3, nghost + 1, j + nghost, k + nghost); U(4, i, j + nghost, k + nghost) = U(4, nghost + 1, j + nghost, k + nghost); U(5, i, j + nghost, k + nghost) = U(5, nghost + 1, j + nghost, k + nghost); U(1, N - i + 1, j + nghost, k + nghost) = U(1, N - nghost, j + nghost, k + nghost); U(2, N - i + 1, j + nghost, k + nghost) = U(2, N - nghost, j + nghost, k + nghost); U(3, N - i + 1, j + nghost, k + nghost) = U(3, N - nghost, j + nghost, k + nghost); U(4, N - i + 1, j + nghost, k + nghost) = U(4, N - nghost, j + nghost, k + nghost); U(5, N - i + 1, j + nghost, k + nghost) = U(5, N - nghost, j + nghost, k + nghost); } } } // outflow y for (int i = 1; i <= N_In; i++) { for (int j = 1; j <= nghost; j++) { for (int k = 1; k <= foo_In; k++) { U(1, i + nghost, j, k + nghost) = U(1, i + nghost, nghost + 1, k + nghost); U(2, i + nghost, j, k + nghost) = U(2, i + nghost, nghost + 1, k + nghost); U(3, i + nghost, j, k + nghost) = U(3, i + nghost, nghost + 1, k + nghost); U(4, i + nghost, j, k + nghost) = U(4, i + nghost, nghost + 1, k + nghost); U(5, i + nghost, j, k + nghost) = U(5, i + nghost, nghost + 1, k + nghost); U(1, i + nghost, N - j + 1, k + nghost) = U(1, i + nghost, N - nghost, k + nghost); U(2, i + nghost, N - j + 1, k + nghost) = U(2, i + nghost, N - nghost, k + nghost); U(3, i + nghost, N - j + 1, k + nghost) = U(3, i + nghost, N - nghost, k + nghost); U(4, i + nghost, N - j + 1, k + nghost) = U(4, i + nghost, N - nghost, k + nghost); U(5, i + nghost, N - j + 1, k + nghost) = U(5, i + nghost, N - nghost, k + nghost); } } } // // outflow z // for (int i = 1; i <= N_In; i++) // { // for (int j = 1; j <= NY_In; j++) // { // for (int k = 1; k <= nghost; k++) // { // U(1, i + nghost, j + nghost, k) = U(1, i + nghost, j + nghost, nghost + 1); // U(2, i + nghost, j + nghost, k) = U(2, i + nghost, j + nghost, nghost + 1); // U(3, i + nghost, j + nghost, k) = U(3, i + nghost, j + nghost, nghost + 1); // U(4, i + nghost, j + nghost, k) = U(4, i + nghost, j + nghost, nghost + 1); // U(5, i + nghost, j + nghost, k) = U(5, i + nghost, j + nghost, nghost + 1); // U(1, i + nghost, j + nghost, N - k + 1) = U(1, i + nghost, j + nghost, N - nghost); // U(2, i + nghost, j + nghost, N - k + 1) = U(2, i + nghost, j + nghost, N - nghost); // U(3, i + nghost, j + nghost, N - k + 1) = U(3, i + nghost, j + nghost, N - nghost); // U(4, i + nghost, j + nghost, N - k + 1) = U(4, i + nghost, j + nghost, N - nghost); // U(5, i + nghost, j + nghost, N - k + 1) = U(5, i + nghost, j + nghost, N - nghost); // } // } // } } // ########################## // Compute pressure // ########################## double ComputePressure(double d, double px, double py, double pz, double e) { double P; P = (mygamma - 1.0) * (e - 0.5 * (pow(px, 2.0) + pow(py, 2.0) + pow(pz, 2.0) / d)); if (P <= 0) { printf("negative pressure in compute pressure !!\t%f\n", P); exit(1); } return P; } // ########################## // Compute time-step by the CFL condition // ########################## double ComputeTimestep(matrix &U) { double dt_cfl = 0.0; double max_info_speed = 0.0; double P, a, u, v, w; for (int i = 1; i <= N; i++) { for (int j = 1; j <= NY; j++) { for (int k = 1; k <= foo; k++) { P = ComputePressure(U(1, i, j, k), U(2, i, j, k), U(3, i, j, k), U(4, i, j, k), U(5, i, j, k)); a = pow((mygamma * P / U(1, i, j, k)), 0.5); u = std::abs(U(2, i, j, k) / U(1, i, j, k)); v = std::abs(U(3, i, j, k) / U(1, i, j, k)); w = std::abs(U(4, i, j, k) / U(1, i, j, k)); if (max_info_speed < u + a) max_info_speed = u + a; if (max_info_speed < v + a) max_info_speed = v + a; // if (max_info_speed < w + a) // max_info_speed = w + a; } } } dt_cfl = cfl * dx / max_info_speed; return dt_cfl; } // ########################## // Compute limited slope // ########################## matrix ComputeLimitedSlope(matrix L, matrix C, matrix R) { // compute the left and right slopes matrix slope_L(5); matrix slope_R(5); matrix slope_LR(5); matrix slope_limited(5); slope_L = C - L; slope_R = R - C; // apply the van-Leer limiter slope_LR = dotprod(slope_L, slope_R); for (int i = 1; i <= 5; i++) { if (slope_LR(i) > 0.0) { slope_limited(i) = 2.0 * slope_LR(i) / (slope_L(i) + slope_R(i)); } else { slope_limited(i) = 0.0; } } return slope_limited; } // ########################## // Convert conserved variables to primitive variables // ########################## matrix Conserved2Primitive(matrix U) { matrix W(5); W(1) = U(1); W(2) = U(2) / U(1); W(3) = U(3) / U(1); W(4) = U(4) / U(1); W(5) = ComputePressure(U(1), U(2), U(3), U(4), U(5)); return W; } // ########################## // Convert primitive variables to conserved variables // ########################## matrix Primitive2Conserved(matrix W) { matrix U(5); U(1) = W(1); U(2) = W(1) * W(2); U(3) = W(1) * W(3); U(4) = W(1) * W(4); U(5) = W(5) / (mygamma - 1.0) + 0.5 * W(1) * (pow(W(2), 2.0) + pow(W(3), 2.0) + pow(W(4), 2.0)); return U; } // ########################## // Piecewise-linear data reconstruction (PLM) // ########################## void DataReconstructionX_PLM(matrix &U, matrix &L, matrix &R) { // allocate memory matrix W(5, N, NY, foo); matrix slope(5, N, NY, foo); // conserved variables-- > primitive variables for (int i = 1; i <= N; i++) for (int j = nghost + 1; j <= NY - nghost; j++) for (int k = nghost + 1; k <= foo - nghost; k++) W.SetRow(i, j, k, Conserved2Primitive(U.GetRow(i, j, k))); // compute the left and right states of each cell for (int i = 2; i <= N - 1; i++) for (int j = nghost + 1; j <= NY - nghost; j++) for (int k = nghost + 1; k <= foo - nghost; k++) slope.SetRow(i, j, k, ComputeLimitedSlope(W.GetRow(i - 1, j, k), W.GetRow(i, j, k), W.GetRow(i + 1, j, k))); matrix slope_limited(5); for (int i = 2; i <= N - 1; i++) { for (int j = nghost + 1; j <= NY - nghost; j++) { for (int k = nghost + 1; k <= foo - nghost; k++) { // get the face-centered variables slope_limited = slope.GetRow(i, j, k); L.SetRow(i, j, k, W.GetRow(i, j, k) - 0.5 * slope_limited); R.SetRow(i, j, k, W.GetRow(i, j, k) + 0.5 * slope_limited); // ensure face-centered variables lie between nearby volume-averaged (~cell-centered) values for (int n = 1; n <= 5; n++) { L(n, i, j, k) = max(L(n, i, j, k), min(W(n, i - 1, j, k), W(n, i, j, k))); L(n, i, j, k) = min(L(n, i, j, k), max(W(n, i - 1, j, k), W(n, i, j, k))); R(n, i, j, k) = 2.0 * W(n, i, j, k) - L(n, i, j, k); R(n, i, j, k) = max(R(n, i, j, k), min(W(n, i + 1, j, k), W(n, i, j, k))); R(n, i, j, k) = min(R(n, i, j, k), max(W(n, i + 1, j, k), W(n, i, j, k))); L(n, i, j, k) = 2.0 * W(n, i, j, k) - R(n, i, j, k); } // primitive variables --> conserved variables L.SetRow(i, j, k, Primitive2Conserved(L.GetRow(i, j, k))); R.SetRow(i, j, k, Primitive2Conserved(R.GetRow(i, j, k))); } } } } void DataReconstructionY_PLM(matrix &U, matrix &L, matrix &R) { // allocate memory matrix W(5, N, NY, foo); matrix slope(5, N, NY, foo); // conserved variables-- > primitive variables for (int i = nghost + 1; i <= N - nghost; i++) for (int j = 1; j <= NY; j++) for (int k = nghost + 1; k <= foo - nghost; k++) W.SetRow(i, j, k, Conserved2Primitive(U.GetRow(i, j, k))); // compute the left and right states of each cell for (int i = nghost + 1; i <= N - nghost; i++) for (int j = 2; j <= NY - 1; j++) for (int k = nghost + 1; k <= foo - nghost; k++) slope.SetRow(i, j, k, ComputeLimitedSlope(W.GetRow(i, j - 1, k), W.GetRow(i, j, k), W.GetRow(i, j + 1, k))); matrix slope_limited(5); for (int i = nghost + 1; i <= N - nghost; i++) { for (int j = 2; j <= NY - 1; j++) { for (int k = nghost + 1; k <= foo - nghost; k++) { // get the face-centered variables slope_limited = slope.GetRow(i, j, k); L.SetRow(i, j, k, W.GetRow(i, j, k) - 0.5 * slope_limited); R.SetRow(i, j, k, W.GetRow(i, j, k) + 0.5 * slope_limited); // ensure face-centered variables lie between nearby volume-averaged (~cell-centered) values for (int n = 1; n <= 5; n++) { L(n, i, j, k) = max(L(n, i, j, k), min(W(n, i, j - 1, k), W(n, i, j, k))); L(n, i, j, k) = min(L(n, i, j, k), max(W(n, i, j - 1, k), W(n, i, j, k))); R(n, i, j, k) = 2.0 * W(n, i, j, k) - L(n, i, j, k); R(n, i, j, k) = max(R(n, i, j, k), min(W(n, i, j + 1, k), W(n, i, j, k))); R(n, i, j, k) = min(R(n, i, j, k), max(W(n, i, j + 1, k), W(n, i, j, k))); L(n, i, j, k) = 2.0 * W(n, i, j, k) - R(n, i, j, k); } // primitive variables --> conserved variables L.SetRow(i, j, k, Primitive2Conserved(L.GetRow(i, j, k))); R.SetRow(i, j, k, Primitive2Conserved(R.GetRow(i, j, k))); } } } } void DataReconstructionZ_PLM(matrix &U, matrix &L, matrix &R) { // allocate memory matrix W(5, N, NY, foo); matrix slope(5, N, NY, foo); // conserved variables-- > primitive variables for (int i = nghost + 1; i <= N - nghost; i++) for (int j = nghost + 1; j <= NY - nghost; j++) for (int k = 1; k <= foo; k++) W.SetRow(i, j, k, Conserved2Primitive(U.GetRow(i, j, k))); // compute the left and right states of each cell for (int i = nghost + 1; i <= N - nghost; i++) for (int j = nghost + 1; j <= NY - nghost; j++) for (int k = 2; k <= foo - 1; k++) slope.SetRow(i, j, k, ComputeLimitedSlope(W.GetRow(i, j, k - 1), W.GetRow(i, j, k), W.GetRow(i, j, k + 1))); matrix slope_limited(5); for (int i = nghost + 1; i <= N - nghost; i++) { for (int j = nghost + 1; j <= NY - nghost; j++) { for (int k = 2; k <= foo - 1; k++) { // get the face-centered variables slope_limited = slope.GetRow(i, j, k); L.SetRow(i, j, k, W.GetRow(i, j, k) - 0.5 * slope_limited); R.SetRow(i, j, k, W.GetRow(i, j, k) + 0.5 * slope_limited); // ensure face-centered variables lie between nearby volume-averaged (~cell-centered) values // primitive variables --> conserved variables L.SetRow(i, j, k, Primitive2Conserved(L.GetRow(i, j, k))); R.SetRow(i, j, k, Primitive2Conserved(R.GetRow(i, j, k))); } } } // L.display(); } // // ########################## // // Piecewise-parabolic data reconstruction (PPM) // // ########################## // void DataReconstruction_PPM(matrix &U, matrix &L, matrix &R) // { // // allocate memory // matrix W(N, 3); // matrix slope(N, 3); // matrix acc(N, 3); // // conserved variables-- > primitive variables // for (int j = 1; j <= N; j++) // W.SetRow(j, Conserved2Primitive(U.GetRow(j))); // // compute the left and right states of each cell // for (int j = 2; j <= N - 1; j++) // slope.SetRow(j, ComputeLimitedSlope(W.GetRow(j - 1), W.GetRow(j), W.GetRow(j + 1))); // // compute the left and right states of each cell // for (int j = 3; j <= N - 2; j++) // acc.SetRow(j, ComputeLimitedSlope(slope.GetRow(j - 1), slope.GetRow(j), slope.GetRow(j + 1))); // matrix slope_limited(1, 3); // matrix acc_limited(1, 3); // for (int j = 2; j <= N - 1; j++) // { // // get the face-centered variables // slope_limited = slope.GetRow(j); // acc_limited = acc.GetRow(j); // L.SetRow(j, W.GetRow(j) - 0.5 * slope_limited + 0.125 * acc_limited); // R.SetRow(j, W.GetRow(j) + 0.5 * slope_limited + 0.125 * acc_limited); // // ensure face-centered variables lie between nearby volume-averaged (~cell-centered) values // // primitive variables --> conserved variables // L.SetRow(j, Primitive2Conserved(L.GetRow(j))); // R.SetRow(j, Primitive2Conserved(R.GetRow(j))); // } // } // ########################## // Convert conserved variables to fluxes // ########################## matrix Conserved2FluxX(matrix U) { matrix flux(5); double P = ComputePressure(U(1), U(2), U(3), U(4), U(5)); double v = U(2) / U(1); flux(1) = U(2); flux(2) = v * U(2) + P; flux(3) = v * U(3); flux(4) = v * U(4); flux(5) = v * (U(5) + P); return flux; } matrix Conserved2FluxY(matrix U) { matrix flux(5); double P = ComputePressure(U(1), U(2), U(3), U(4), U(5)); double v = U(3) / U(1); flux(1) = U(3); flux(2) = v * U(2); flux(3) = v * U(3) + P; flux(4) = v * U(4); flux(5) = v * (U(5) + P); return flux; } matrix Conserved2FluxZ(matrix U) { matrix flux(5); double P = ComputePressure(U(1), U(2), U(3), U(4), U(5)); double v = U(4) / U(1); flux(1) = U(4); flux(2) = v * U(3); flux(3) = v * U(3); flux(4) = v * U(4) + P; flux(5) = v * (U(5) + P); return flux; } matrix Conserved2FluxAddressX(matrix &U) { matrix flux(5); double P = ComputePressure(U(1), U(2), U(3), U(4), U(5)); double v = U(2) / U(1); flux(1) = U(2); flux(2) = v * U(2) + P; flux(3) = v * U(3); flux(4) = v * U(4); flux(5) = v * (U(5) + P); return flux; } matrix Conserved2FluxAddressY(matrix &U) { matrix flux(5); double P = ComputePressure(U(1), U(2), U(3), U(4), U(5)); double v = U(3) / U(1); flux(1) = U(2); flux(2) = v * U(2); flux(3) = v * U(3) + P; flux(4) = v * U(4); flux(5) = v * (U(5) + P); return flux; } matrix Conserved2FluxAddressZ(matrix &U) { matrix flux(5); double P = ComputePressure(U(1), U(2), U(3), U(4), U(5)); double v = U(4) / U(1); flux(1) = U(2); flux(2) = v * U(2); flux(3) = v * U(3); flux(4) = v * U(4) + P; flux(5) = v * (U(5) + P); return flux; } // ########################## // Roe's Riemann solver // ########################## matrix RoeX(matrix L, matrix R) { // compute the enthalpy of the left and right states: H = (E+P)/rho matrix flux(5); double P_L = ComputePressure(L(1), L(2), L(3), L(4), L(5)); double P_R = ComputePressure(R(1), R(2), R(3), R(4), R(5)); double H_L = (L(5) + P_L) / L(1); double H_R = (R(5) + P_R) / R(1); // compute Roe average values double rhoL_sqrt = pow(L(1), 0.5); double rhoR_sqrt = pow(R(1), 0.5); double u = (L(2) / rhoL_sqrt + R(2) / rhoR_sqrt) / (rhoL_sqrt + rhoR_sqrt); double v = (L(3) / rhoL_sqrt + R(3) / rhoR_sqrt) / (rhoL_sqrt + rhoR_sqrt); double w = (L(4) / rhoL_sqrt + R(4) / rhoR_sqrt) / (rhoL_sqrt + rhoR_sqrt); double H = (rhoL_sqrt * H_L + rhoR_sqrt * H_R) / (rhoL_sqrt + rhoR_sqrt); double V2 = u * u + v * v + w * w; double a = 0.0; // check negative pressure if (H - 0.5 * V2 > 0.0) { a = pow(((mygamma - 1.0) * (H - 0.5 * V2)), 0.5); } else { printf("negative pressure in Roe !\t%f\n", H - 0.5 * V2); exit(1); } // compute the amplitudes of different characteristic waves matrix dU(5); matrix amp(5); dU = R - L; amp(3) = dU(3) - v * dU(1); amp(4) = dU(4) - w * dU(1); amp(2) = (mygamma - 1.0) / pow(a, 2.0) * (dU(1) * (H - pow(u, 2.0)) + u * dU(2) - dU(5) + v * amp(3) + w * amp(4)); amp(1) = 0.5 / a * (dU(1, 1) * (u + a) - dU(2) - a * amp(2)); amp(5) = dU(1) - amp(1) - amp(2); // compute the eigenvalues and right eigenvector matrix matrix EigVal(5); matrix EigVec(5, 5); EigVal(1) = std::abs(u - a); EigVal(2) = std::abs(u); EigVal(3) = std::abs(u); EigVal(4) = std::abs(u); EigVal(5) = std::abs(u + a); EigVec(1, 1) = 1.0; EigVec(2, 1) = u - a; EigVec(3, 1) = v; EigVec(4, 1) = w; EigVec(5, 1) = H - u * a; EigVec(1, 2) = 1.0; EigVec(2, 2) = u; EigVec(3, 2) = v; EigVec(4, 2) = w; EigVec(5, 2) = 0.5 * V2; EigVec(3, 3) = 1.0; EigVec(5, 3) = v; EigVec(4, 4) = 1.0; EigVec(5, 4) = w; EigVec(1, 5) = 1.0; EigVec(2, 5) = u + a; EigVec(3, 5) = v; EigVec(4, 5) = w; EigVec(5, 5) = H + u * a; // compute the fluxes of the left and right states matrix flux_L(5); matrix flux_R(5); flux_L = Conserved2FluxAddressX(L); flux_R = Conserved2FluxAddressX(R); // // compute the Roe flux amp = dotprod(amp, EigVal); flux = 0.5 * (flux_L + flux_R) - 0.5 * EigVec * amp; return flux; } matrix RoeY(matrix L, matrix R) { // compute the enthalpy of the left and right states: H = (E+P)/rho matrix flux(5); double P_L = ComputePressure(L(1), L(2), L(3), L(4), L(5)); double P_R = ComputePressure(R(1), R(2), R(3), R(4), R(5)); double H_L = (L(5) + P_L) / L(1); double H_R = (R(5) + P_R) / R(1); // compute Roe average values double rhoL_sqrt = pow(L(1), 0.5); double rhoR_sqrt = pow(R(1), 0.5); double u = (L(2) / rhoL_sqrt + R(2) / rhoR_sqrt) / (rhoL_sqrt + rhoR_sqrt); double v = (L(3) / rhoL_sqrt + R(3) / rhoR_sqrt) / (rhoL_sqrt + rhoR_sqrt); double w = (L(4) / rhoL_sqrt + R(4) / rhoR_sqrt) / (rhoL_sqrt + rhoR_sqrt); double H = (rhoL_sqrt * H_L + rhoR_sqrt * H_R) / (rhoL_sqrt + rhoR_sqrt); double V2 = u * u + v * v + w * w; double a = 0.0; // check negative pressure if (H - 0.5 * V2 > 0.0) { a = pow(((mygamma - 1.0) * (H - 0.5 * V2)), 0.5); } else { printf("negative pressure in Roe !\t%f\n", H - 0.5 * V2); exit(1); } // compute the amplitudes of different characteristic waves matrix dU(5); matrix amp(5); dU = R - L; amp(2) = dU(2) - u * dU(1); amp(4) = dU(4) - w * dU(1); amp(3) = (mygamma - 1.0) / pow(a, 2.0) * (dU(1) * (H - pow(v, 2.0)) + v * dU(3) - dU(5) + u * amp(2) + w * amp(4)); amp(1) = 0.5 / a * (dU(1, 1) * (v + a) - dU(3) - a * amp(3)); amp(5) = dU(1) - amp(1) - amp(3); // compute the eigenvalues and right eigenvector matrix matrix EigVal(5); matrix EigVec(5, 5); EigVal(1) = std::abs(v - a); EigVal(2) = std::abs(v); EigVal(3) = std::abs(v); EigVal(4) = std::abs(v); EigVal(5) = std::abs(v + a); EigVec(1, 1) = 1.0; EigVec(2, 1) = u; EigVec(3, 1) = v - a; EigVec(4, 1) = w; EigVec(5, 1) = H - v * a; EigVec(2, 2) = 1.0; EigVec(5, 2) = u; EigVec(1, 3) = 1.0; EigVec(2, 3) = u; EigVec(3, 3) = v; EigVec(4, 3) = w; EigVec(5, 3) = 0.5 * V2; EigVec(4, 4) = 1.0; EigVec(5, 4) = w; EigVec(1, 5) = 1.0; EigVec(2, 5) = u; EigVec(3, 5) = v + a; EigVec(4, 5) = w; EigVec(5, 5) = H + v * a; // compute the fluxes of the left and right states matrix flux_L(5); matrix flux_R(5); flux_L = Conserved2FluxAddressY(L); flux_R = Conserved2FluxAddressY(R); // // compute the Roe flux amp = dotprod(amp, EigVal); flux = 0.5 * (flux_L + flux_R) - 0.5 * EigVec * amp; return flux; } #endif //__SUBFUNC_CPP__
Python
UTF-8
938
2.6875
3
[]
no_license
import asyncio from confluent_kafka import Consumer import logging logger = logging.getLogger(__name__) BROKER_URL = "PLAINTEXT://localhost:9092" TOPIC = "com.udacity.crime" async def consume(topic_name): c = Consumer({"bootstrap.servers": BROKER_URL, "group.id": "31", 'auto.offset.reset': 'earliest'}) c.subscribe([topic_name]) while True: messages = c.consume(5, timeout=1.0) for message in messages: print(f"consume message {message.key()}: {message.value()}") await asyncio.sleep(1.0) async def create_task(topic_name): """Runs the Producer and Consumer tasks""" task = asyncio.create_task(consume(topic_name)) await task def main(): """Checks for topic and creates the topic if it does not exist""" try: asyncio.run(create_task(TOPIC)) except KeyboardInterrupt as e: logger.info("shutting down") if __name__ == "__main__": main()
Markdown
UTF-8
3,190
3.140625
3
[]
no_license
[上一章](./第5章.md) # 库和API设计 ## 第53条 保持一致的约定 - 在变量命名和函数形参中使用一致的约定 - 不要偏离用户在他们的开发平台中很可能遇到的约定 ## 第54条 将undefined看作没有值 - 使用描述性的字符串或者命名布尔属性的对象, 而不要使用undefined或null来代表特定应用标志 - 提供参数默认值应当采用测试undefined的方式,而不是检查arguments.length ## 第55条 接收关键字参数的选项对象 - 使用选项对象使得API更具可读性,更容易记忆 - 所有通过选项对象提供的参数应当被视为可选的,如果有一两个必选参数,最好使他们独立于选项对象 - 使用extend函数抽象出从选项对象中提取值的逻辑 ## 第56条 避免不必要的状态 - 无状态的API提供的函数或方法的行为只取决于输入,而与程序的状态改变无关 ```js "abc".toUpperCase(); // "ABC" var now = new Date(); var str1 = now.toString(); now.setDate(now.getDate()+1); var str2 = now.toString(); str1 === str2; // false ``` - 尽可能地使用无状态的API - 如果API是有状态的,标示出每个操作与哪些状态有关联 ## 第57条 使用结构类型设计灵活的接口 - 使用结构类型(也称为鸭子类型)来设计灵活的对象接口 ```js var app = new Wiki(Wiki.formats.MEDIAWIKI); function Wiki(format){ this.format = format; } Wiki.prototype.displayPage = function(source){ var page = this.format(source); var title = page.getTitle(); var author = page.getAuthor(); var output = page.toHTML(); //... } Wiki.formats.MEDIAWIKI = function(source){ //... return { getTitle: function(){/*...*/}, getAuthor: function(){/*...*/}, toHTML: function(){/*...*/} }; }; ``` - 结构接口更灵活,更轻量,所以应该避免使用继承. - 灵活的结构类型有利于单元测试 ## 第58条 区分数组对象和类数组对象 - 猜测一个对象是否实现了结构类型有时被称为鸭子测试,这是不好的实践. - API绝不应该重载与其他类型有重叠的类型 - 当重载一个结构类型与其他类型时,先测试其他类型 - 当重载其他对象类型时, 接收真数组而不是类数组对象 - 文档标注API是否接收真数组或类数组值 - 使用ES5提供的Array.isArray方法测试真数组 ## 第59条 避免过度的强制转换 - 无符号右移位运算符会将其第一个参数转换为一个32位的无符号整数,移入零位对整数值无影响 ```js 2.333 >>> 0; // 2 -2.333 >>> 0 // 4294967294 2.333 >> 0 // 2 -2.333 >> 0 // -2 2.333 <<< 0 // Uncaught SyntaxError: Unexpected token < ``` - 避免强制转换和重载的混用 - 防御性编程试图以额外的检查来抵御潜在的错误.一般情况下,抵御所有可能的错误是不可能的. - 考虑防御性地监视非预期的输入 ## 第60条 支持方法链 - 通过方法链来连接无状态的操作 - 通过在无状态的方法中返回新对象来支持方法链 - 通过在有状态的方法中返回this来支持方法链 [下一章](./第7章.md)