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
Markdown
UTF-8
1,089
2.53125
3
[ "MIT" ]
permissive
# Templates [![Twitter: @fromkk](https://img.shields.io/badge/contact-@fromkk-00801D.svg?style=flat)](https://twitter.com/fromkk) [![Swift 4.2](https://img.shields.io/badge/Swift-4.2-F16D39.svg?style=flat)](https://developer.apple.com/swift/) ![Platforms](https://img.shields.io/badge/platform-macOS-lightgrey.svg) [![GitHub license](https://img.shields.io/badge/license-MIT-lightgrey.svg)](https://raw.githubusercontent.com/fromkk/Templates/master/LICENSE.md) ## What CLI tool for replace keywods of multi files. ## Install ```sh git clone git@github.com:fromkk/Templates.git cd ./Templates make install ``` ## Usage ```sh # Configure Usage: templates set --key ${KEY} --value ${VALUE} Options: --key Key string --value Value string # Remove key Usage: templates remove --key ${KEY} Options: --key Key string # Show Usage: templates show --key ${KEY} Options: --key Key string(optional) # Convert Usage: templates convert --source ${TEMPLATE_DIR} --output ${OUTPUT_DIR} --prefix ${PREFIX} Options: --source Templates directory --output Output directory --prefix Prefix string ```
Python
UTF-8
480
3.625
4
[]
no_license
#!/usr/bin/env python import pygame #player ship """ def draw_player(surf, color): rect = surf.get_rect() #what does this do? d = min(rect.width, rect.height) pygame.draw.rect(surf, color, (0,0, (d/8), rect.height)) """ def draw_player(surf, x, y): YELLOW = (255,255,0) #yellow rect = surf.get_rect() #returns a rectangle covering the surface d = min(rect.width, rect.height) pygame.draw.rect(surf, YELLOW, (x, y, (d/8), rect.height))
Python
UTF-8
1,128
3.484375
3
[]
no_license
#!/usr/bin/env python3 import sys class Solution: def max_profit(self, prices): """ :type prices: List[int] :rtype: int 超时 """ maximum = 0 indexes = [i for i in range(len(prices))] pri_ind = zip(prices, indexes) sorted_prices = sorted(pri_ind) for i in indexes: for j in range(indexes[-1], i, -1): if sorted_prices[j][1] > sorted_prices[i][1] and \ sorted_prices[j][0] - sorted_prices[i][0] > maximum: maximum = sorted_prices[j][0] - sorted_prices[i][0] return maximum def maxProfit(self, prices): """ :type prices: List[int] :rtype: int 别人的 """ min_v = sys.maxsize max_d = 0 for p in prices: if p < min_v: min_v = p elif p - min_v > max_d: max_d = p - min_v return max_d def main(): solution = Solution() prices = [7, 1, 5, 3, 6, 4] print(solution.max_profit(prices)) if __name__ == '__main__': main()
C#
UTF-8
2,602
2.515625
3
[ "MIT" ]
permissive
#nullable enable using Cybtans.Proto.AST; using Cybtans.Proto.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Cybtans.Proto.Generators.CSharp { public class MessageClassInfo { readonly MessageDeclaration _msg; readonly SortedList<string, MessageFieldInfo> _fields; public MessageClassInfo(MessageDeclaration msg, OutputOption outputOption, ProtoFile proto) { this._msg = msg; Name = msg.Name.Pascal(); Namespace = outputOption.Namespace ?? $"{proto.Option.Namespace ?? proto.Filename.Pascal()}.Models"; _fields = new SortedList<string, MessageFieldInfo>(); foreach (var item in msg.Fields.Select(x => new MessageFieldInfo(x))) { _fields.Add(item.Field.Name, item); } Proto = proto; } public MessageDeclaration Message => _msg; public SortedList<string, MessageFieldInfo> Fields => _fields; public string Name { get; } public string Namespace { get; } public ProtoFile Proto { get; } public List<MessageFieldInfo>? GetPathBinding(string template) { if (template == null) return null; var regex = new Regex(@"{(\w+)}"); MatchCollection matches = regex.Matches(template); if (matches.Any(x => x.Success)) { List<MessageFieldInfo> fields = new List<MessageFieldInfo>(); foreach (Match? match in matches) { if (match != null && match.Success) { var name = match.Groups[1].Value; var field = Fields[name]; fields.Add(field); } } return fields; } return null; } } public class MessageFieldInfo { private readonly FieldDeclaration _field; public MessageFieldInfo(FieldDeclaration field) { _field = field; Name = field.Name.Pascal(); Type = field.Type.GetTypeName(); if (field.Option.Optional && field.Type.TypeDeclaration.IsValueType) { //check ist the type is nullable Type += "?"; } } public FieldDeclaration Field => _field; public string Name { get; } public string Type { get; } } }
Markdown
UTF-8
4,985
2.78125
3
[ "MIT" ]
permissive
--- layout: post title: Ubiquity command Say tags: ubiquity --- So It's being a long time I haven't posted anything and bla bla bla... (Not going to go on with this useless text). Finally I managed to work on something interesting and think it makes sense to blog about it... So the topic will be another Ubiquity command [Say], which I've implemented recently. I got inspiration from the command line tool on OSX, called "**say**". For some of you who had not seen this app it just an app which converts text to speech. I wanted to play with a cool new feature from HTML5 - [Video & Audio elements] presented in Firefox 3.1. Besides I noticed some noise regarding some restrictions to this elements so I really wanted to try all this out to get a personal opinion on that. Here are some links from this discussion <http://www.bluishcoder.co.nz/2008/11/video-audio-and-cross-domain-usage.html> <http://blog.mozilla.com/schrep/2008/08/08/building-the-world-we-want-not-the-one-we-have/> <http://ajaxian.com/archives/video-audio-cross-origin"> Well I had an idea, had cool new feature to play with. Only thing that I was missing was some online free text-to-speech service I could use for that. It appeared quite hard to find cause most of the services were non free. Among the free once some had pure quality, and the rest were using unsupported (by new elements) audio formats. I was really close to give up on this this idea after 6hrs of googleing, when another idea came to my mind it was bit sneaky, but still it was not illegal so I decided to go for it. The idea was to use demo pages for the non free text-to-speech services. Most of the restrictions for this sites are restricting API's for the use from other domains. But non of them are restricting to open their pages in the browser without showing the content of the page to the user :) Think most of you got the point. Finally I found service which could feet my needs >:) <http://www.research.ibm.com/tts/coredemo.shtml> As you might imagine there was a restriction to the service. It was possible to convert only 200 chars at a time. Well it just made my work more interesting only thing I had to do was to build a play-list from the selection to pronounce. It could be a very simple (thanks to the event listeners you can set to the video element), but I suddenly discovered that there was restriction to the video element even for the use from chrome. Well this made me very upset, I did not liked idea of restrictions at all but restriction for the use from chrome is even more stupid from my point of view. I could not believe that I was not able to play audio from the remote server, I thought I was doing something wrong, but apparently I was not :( So I went back to the old ugly but tested way of using plugins. Unfortunately I was not able to convert more then 200 char length text but still it was cool command and still useful for me, as my goal was to find how to pronounce words i don't know correctly. (As you might guess from the part you've already read my English is quite poor and of course I'm not native English speaker). I was not satisfied, so I was searching the way for work around it... And there was a quite simple way :). If you are using beta or nightly of Firefox 3.1 you might noticed that .wav, .ogg files are opened by Firefox in a new tab in the Video tag (No matter if the file is local or remote one) :) If some of you did not got the idea yet it is - an iframe where you load remote wav files. That's what I did basically say command on preview creates hidden iframe inside the preview block, and is loads there the wav files which was generated by text-to-speech service. As I did not liked the restriction of the 200 chars I am splitting selected text into the parts, where each part contains several complete words and it's length is <= 200 chars. While loading each part into the hidden iframe I also set event listener to the video tag inside the iframe to load next part in the frame when the video element will finish playing.Unfortunately it was not the last hack as I discovered soon that the text-to-speech service I mentioned above had a restriction on the server as well. (They block ip for their service after heavy use of the service). In this case solution was simple I just jumped to another service with bit worth API and without this restriction. Cool thing is that in this case restriction from 200 chars had grew till 300 chars. To avoid the new restrictions from the service owners I will not mention it in this blog! After all this you can enjoy nice Ubiquity command Say. If some of you want look for the source you can get it here <http://github.com/Gozala/ubiquity/tree/master/commands/say> [Say]:http://gozala.github.com/ubiquity/commands/say/ [Video & Audio elements]:https://developer.mozilla.org/En/HTML/Element/Video
C++
UTF-8
324
2.5625
3
[]
no_license
#include "ReplayViewer.h" #include <iostream> using namespace std; int main(int argc, char** argv) { const char* title = "Artificial Life Replay Viewer"; int width = 1100; int height = 800; ReplayViewer application; if (!application.Initialize(title, width, height)) return 1; application.Run(); return 0; }
C#
UTF-8
1,079
2.765625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class WindowSystem : MonoBehaviour { #region public methods public void ShowWindow(string windowId) { WindowUI targetWindow = GetWindow(windowId); ShowWindow(targetWindow); } public void ShowWindow(WindowUI window) { window.Show(); } public void HideWindow(string windowId) { WindowUI targetWindow = GetWindow(windowId); HideWindow(targetWindow); } public void HideWindow(WindowUI window) { window.Hide(); } //Buscar una ventana dentro de la lista, que tenga el ID buscado public WindowUI GetWindow(string windowId) { return System.Array.Find(_windowList, window => window.ID == windowId); } #endregion #region public variables #endregion #region private methods #endregion #region private variables //Lista de todas las ventanas del juego [SerializeField] private WindowUI[] _windowList; #endregion }
Python
UTF-8
4,428
2.859375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Apr 16 08:13:25 2020 @author: Administrator The generic Sliding Window algorithm Algorithm Seg_TS = Sliding_Window(T, max_error) anchor = 1; while not finished segmenting time series i = 2; while caculate_error(T[anchor: anchor + i]) < max_error i = i + 1; end; Seg_TS = concat(Seg_TS,create_segment(T[anchor: anchor+(i-1)])); anchor = anchor + i; end; """ #定义全局最大误差 import pandas as pd import numpy as np import methods as md import matplotlib.pyplot as plt import time max_error = 0.4 #-----------滑动窗口算法--------------- #加载数据函数 def loadDataSet(fileName): dataSetList = [] df = pd.read_csv(fileName) #dataSetList = df.drop(['Date'], axis = 1) dataSetList = df return dataSetList def Sliding_Window(T, max_error,X): Seg_TS = [] anchor = 0 while(anchor < len(T)-1 ):#分段结束条件,锚点到达最后一个点 i = 1 #定义初始分段相对于锚点anchor的结束点 while calculate_error(X[anchor:anchor + i + 1],T[anchor:anchor + i + 1]) < max_error: i = i + 1 if anchor+i-1==len(T): break Seg_TS.append(T[anchor:anchor+i-1]) anchor = anchor + i -1 return Seg_TS #-----------------------计算拟合误差--------------------- def calculate_error(X,Ts): #1.获取拟合直线的方程y = a*x + b----这里自变量的量纲问题如何处理,用Ts下的坐标岂不是忽略了它本身的时间序列坐标 #Ts = Ts.tolist() #X = X.tolist() #a = abs((Ts[-len(Ts)]-Ts[-1])/len(Ts)) #b = Ts[-1] - a a,b = md.min_error_func(X,Ts) sum_error = 0 for i in range(len(Ts)): sum_error += (Ts[i] - (a*X[i] + b))**2 sum_error = sum_error/len(Ts) return sum_error#返回垂直方向的均方误差 if __name__=='__main__': start =time.clock() TS = md.loadDataSet(r'C:\Users\Administrator\Desktop\论文\神经网络\test2.csv') TS_x = md.loadDataSet(r'C:\Users\Administrator\Desktop\论文\神经网络\test2.csv') ts = np.array(TS_x['Close']) ts = ts.tolist() ts_x = np.array(TS_x['Date']) TS_x = np.array(TS_x['Date']) TS_x = md.time_translate(TS_x) std_TS_x = np.std(TS_x)#时间序列的原始数据方差 mean_TS_x = np.mean(TS_x)#时间序列的原始数据均值 x = (TS_x - mean_TS_x)/std_TS_x #将时间戳x做标准化处理,便于传参进行后续计算 TS_1 = np.array(TS['Close']) std_TS_1 = np.std(TS_1)#收盘价的原始数据方法 mean_TS_1 = np.mean(TS_1)#收盘价的原始数据均值 y = (TS_1 - mean_TS_1)/std_TS_1 ans_T=[] ans_T=Sliding_Window(y,max_error,x) #取出ans_T中的分段点 ans_seg_point=[] for i in range(len(ans_T)): ans_seg_point.append(ans_T[i][0]) ans_seg_point.append(ans_T[i][-1]) #将归一化后的数据还原 ans_seg_point_date=[] y1 = [] x1 = [] for i in range(len(ans_seg_point)): y1.append(ans_seg_point[i]) ans_seg_point_date1=[] for i in range(len(ans_seg_point)): ans_seg_point[i]=ans_seg_point[i] * std_TS_1 + mean_TS_1 ans_seg_point_date.append(ts_x[ts.index(ans_seg_point[i])]) x1.append(x[ts.index(ans_seg_point[i])]) plt.figure(figsize=(12,6)) plt.plot(ts_x,ts,'r--',label='raw_data') plt.scatter(ans_seg_point_date,ans_seg_point,color='blue',label='seg_point') plt.plot(ans_seg_point_date,ans_seg_point,color='green',label='fitting_line') plt.legend() plt.xticks(ts_x, ts_x, rotation=90, fontsize=10) plt.show() #----------------------计算拟合误差--------------------- #用插值直线与原数据的均方差来表示error #参数描述: x #在原始序列中找到ans_seg_point_date 数组的标准值 #ans_seg_point_date1 = md.norm_data(ans_seg_point_date1) #ans_seg_point = md.norm_data(ans_seg_point) error = md.calculate_fitting_error(x1,y1,y,x) error2 = md.calculate_vertical_error(x1,y1,y,x) print("the sliding window fitting error1: ",error) print("the sliding window fitting error2: ",error2) #T = loadDataSet(r'C:\Users\Administrator\Desktop\论文\神经网络\test.csv') #T = np.array(T['Close']) #ans_T = [] #ans_T = Sliding_Window(T,max_error) end = time.clock() print('Running time: %s Seconds'%(end-start))
C++
UTF-8
386
3.390625
3
[]
no_license
/* Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. */ class Solution { public: bool isPalindrome(int x) { if (x < 0){ return false; } int a = 0, y = x; while (x > 0) { a = a * 10 + x % 10; x /= 10; } return a == y; } };
C++
UTF-8
14,808
2.53125
3
[ "BSD-2-Clause" ]
permissive
#ifndef CHARGE_COMMON_NODE_LABEL_CONTAINER_HPP #define CHARGE_COMMON_NODE_LABEL_CONTAINER_HPP #include "common/adapter_iter.hpp" #include "common/constants.hpp" #include "common/function_graph.hpp" #include "common/interpolating_function.hpp" #include "common/linear_function.hpp" #include "common/piecewise_function.hpp" #include "common/range.hpp" #include "common/statistics.hpp" #include "common/tuple_helper.hpp" #include <algorithm> #include <tuple> #include <vector> namespace charge::common { namespace detail { template <typename T> void shrink_cost(T &) {} template <typename T, typename MinBoundT, typename MaxBoundT, typename MonoticityT> void shrink_cost(PiecewieseFunction<T, MinBoundT, MaxBoundT, MonoticityT> &cost) { cost.shrink_to_fit(); } } // namespace detail template <typename CostT, typename NodeIDT> struct LabelEntry { using cost_t = CostT; using node_id_t = NodeIDT; LabelEntry(key_t key, const cost_t cost) : LabelEntry(key, cost, INVALID_ID, INVALID_ID) {} LabelEntry(key_t key, const cost_t cost, const node_id_t, const node_id_t) : key(key), cost(cost) {} LabelEntry() = default; LabelEntry(const LabelEntry &) = default; LabelEntry(LabelEntry &&) = default; LabelEntry &operator=(const LabelEntry &) = default; LabelEntry &operator=(LabelEntry &&) = default; inline bool operator<(const LabelEntry &other) const { return cost < other.cost; } inline bool operator==(const LabelEntry &other) const { return cost == other.cost; } inline bool operator!=(const LabelEntry &other) const { return !operator==(other); } key_t key; cost_t cost; }; template <typename CostT, typename NodeIDT> struct LabelEntryWithParent { using cost_t = CostT; using node_id_t = NodeIDT; LabelEntryWithParent(key_t key, const cost_t cost, const node_id_t parent, const node_id_t parent_entry) : key(key), cost(cost), parent(parent), parent_entry(parent_entry) {} LabelEntryWithParent() = default; LabelEntryWithParent(const LabelEntryWithParent &) = default; LabelEntryWithParent(LabelEntryWithParent &&) = default; LabelEntryWithParent &operator=(const LabelEntryWithParent &) = default; LabelEntryWithParent &operator=(LabelEntryWithParent &&) = default; inline bool operator<(const LabelEntryWithParent &other) const { return std::tie(cost, parent, parent_entry) < std::tie(other.cost, other.parent, other.parent_entry); } inline bool operator==(const LabelEntryWithParent &other) const { return std::tie(cost, parent, parent_entry) == std::tie(other.cost, other.parent, other.parent_entry); } inline bool operator!=(const LabelEntryWithParent &other) const { return !operator==(other); } key_t key; cost_t cost; node_id_t parent; node_id_t parent_entry; }; template <typename FnT> struct LabelEntry<LimitedFunction<FnT, inf_bound, clamp_bound>, typename FunctionGraph<FnT>::node_id_t> { using GraphT = FunctionGraph<FnT>; using cost_t = PiecewieseFunction<FnT, inf_bound, clamp_bound, monotone_decreasing>; using delta_t = InterpolatingFunction<inf_bound, clamp_bound, monotone_increasing>; using node_id_t = typename GraphT::node_id_t; LabelEntry(key_t key, cost_t cost) noexcept : LabelEntry(key, std::move(cost), {}, INVALID_ID, INVALID_ID) {} LabelEntry(key_t key, cost_t cost_, delta_t, const node_id_t, const node_id_t) noexcept : key(key), cost(std::move(cost_)) {} LabelEntry() noexcept = default; LabelEntry(const LabelEntry &) noexcept = default; LabelEntry(LabelEntry &&) noexcept = default; LabelEntry &operator=(const LabelEntry &) noexcept = default; LabelEntry &operator=(LabelEntry &&) noexcept = default; inline bool operator<(const LabelEntry &other) const { return cost.min_x() < other.cost.min_x(); } inline bool operator==(const LabelEntry &other) const { return cost.min_x() == other.cost.min_x(); } inline bool operator!=(const LabelEntry &other) const { return !operator==(other); } key_t key; cost_t cost; }; template <typename FnT> struct LabelEntryWithParent<LimitedFunction<FnT, inf_bound, clamp_bound>, typename FunctionGraph<FnT>::node_id_t> { using GraphT = FunctionGraph<FnT>; using cost_t = PiecewieseFunction<FnT, inf_bound, clamp_bound, monotone_decreasing>; using delta_t = InterpolatingFunction<inf_bound, clamp_bound, monotone_increasing>; using node_id_t = typename GraphT::node_id_t; LabelEntryWithParent(key_t key, cost_t cost_, delta_t delta_, const node_id_t parent, const node_id_t parent_entry) : key(key), cost(std::move(cost_)), delta(std::move(delta_)), parent(parent), parent_entry(parent_entry) {} LabelEntryWithParent() noexcept = default; LabelEntryWithParent(const LabelEntryWithParent &) noexcept = default; LabelEntryWithParent(LabelEntryWithParent &&) noexcept = default; LabelEntryWithParent &operator=(const LabelEntryWithParent &) noexcept = default; LabelEntryWithParent &operator=(LabelEntryWithParent &&) noexcept = default; inline bool operator<(const LabelEntryWithParent &other) const { return cost.min_x() < other.cost.min_x(); } inline bool operator==(const LabelEntryWithParent &other) const { return (cost.min_x() == other.cost.min_x()) && std::tie(parent, parent_entry) == std::tie(other.parent, other.parent_entry); } inline bool operator!=(const LabelEntryWithParent &other) const { return !operator==(other); } key_t key; cost_t cost; delta_t delta; node_id_t parent; node_id_t parent_entry; }; template <typename T, typename = int> struct is_parent_label : std::false_type {}; template <typename T> struct is_parent_label<T, decltype((void)T::parent, 0)> : std::true_type {}; template <typename T, typename = int> struct is_delta_label : std::false_type {}; template <typename T> struct is_delta_label<T, decltype((void)T::delta, 0)> : std::true_type {}; // Label container for every every node. // // Labels for nodes are split into two lists: // // 1/ unsettled labels (labels that have been inserted vis push() but not removed via pop() again) // 2/ settled labels (labels that have been removed via pop()) // // The life-cycle of a label is: // push -> unsettled labels -> pop -> settled labels // // The invariants that govern these labels sets are: // 1. The minimal unsettled label is not dominated by any unsettled labels. // 1. The minimal unsettled label is not dominated by any settled labels. // // To ensure 1. we use a sorting in the heap that only places undominated labels as min. // To ensure 2. we need do dominance checks every time we updated the minimum (push or pop) template <typename PolicyT> class NodeLabels { public: using label_t = typename PolicyT::label_t; using cost_t = typename label_t::cost_t; using node_id_t = typename label_t::node_id_t; NodeLabels(const std::size_t num_nodes) : unsettled_labels(num_nodes, std::vector<label_t>{}), settled_labels(num_nodes, std::vector<label_t>{}) {} void clear() { for (auto &labels : unsettled_labels) { labels.clear(); } for (auto &labels : settled_labels) { labels.clear(); } } void shrink_to_fit() { for (auto &labels : unsettled_labels) { labels.shrink_to_fit(); } for (auto &labels : settled_labels) { labels.shrink_to_fit(); } } template <typename NodePotentialsT> auto push(const node_id_t node, label_t label, const PolicyT &policy, const NodePotentialsT &potentials) { Statistics::get().count(StatisticsEvent::LABEL_PUSH); auto &unsettled = unsettled_labels[node]; bool modified_min = true; if (unsettled.size() > 0) { auto old_key = unsettled.front().key; if (policy.dominates(unsettled.front().cost, label.cost)) { modified_min = false; } else { unsettled.push_back(std::move(label)); std::push_heap(unsettled.begin(), unsettled.end(), [&](const auto &lhs, const auto &rhs) { return rhs.key < lhs.key; }); // we updated the minium, we need to ensure consitency of the second invariant auto new_key = unsettled.front().key; modified_min = old_key != new_key; } } else { unsettled.push_back(std::move(label)); } if (modified_min) { ensure_undominated_minium(node, policy, potentials); } return modified_min; } void cleanup_unsettled(const node_id_t node) { // clang-format off if constexpr(std::is_same_v<typename label_t::cost_t, std::tuple<std::int32_t, std::int32_t>>) { Statistics::get().count(StatisticsEvent::LABEL_CLEANUP); unsettled_labels[node] = lower_envelop(std::move(unsettled_labels[node])); std::make_heap(unsettled_labels[node].begin(), unsettled_labels[node].end(), [&](const auto &lhs, const auto &rhs) { return rhs.key < lhs.key; }); } // clang-format on } bool dominated(const node_id_t node, const cost_t &tentative_cost, const PolicyT &policy) const { const auto label_to_cost = [](const label_t &label) -> const cost_t & { return label.cost; }; auto labels_begin = make_adapter_iter(settled_labels[node].begin(), label_to_cost); auto labels_end = make_adapter_iter(settled_labels[node].end(), label_to_cost); auto range = make_range(labels_begin, labels_end); return policy.dominates(range, tentative_cost); } template <typename NodePotentialsT> std::tuple<bool, bool> clip_dominated(const node_id_t node, label_t &label, const PolicyT &policy, const NodePotentialsT &potentials) const { const auto label_to_cost = [](const label_t &label) -> const cost_t & { return label.cost; }; auto labels_begin = make_adapter_iter(settled_labels[node].begin(), label_to_cost); auto labels_end = make_adapter_iter(settled_labels[node].end(), label_to_cost); auto range = make_range(labels_begin, labels_end); auto[dominated, modified] = policy.clip_dominated(range, label.cost); if (modified && !dominated) { label.key = potentials.key(node, PolicyT::key(label.cost), label.cost); } return std::make_tuple(dominated, modified); } auto &min(const node_id_t node) const { assert(!unsettled_labels[node].empty()); return unsettled_labels[node].front(); } auto &min(const node_id_t node) { assert(!unsettled_labels[node].empty()); return unsettled_labels[node].front(); } auto empty(const node_id_t node) const { return unsettled_labels[node].empty(); } auto size(const node_id_t node) const { return unsettled_labels[node].size(); } template <typename NodePotentialsT> auto pop(const node_id_t node, const PolicyT &policy, const NodePotentialsT &potentials) { Statistics::get().count(StatisticsEvent::LABEL_POP); auto &unsettled = unsettled_labels[node]; auto &settled = settled_labels[node]; assert(!unsettled.empty()); std::pop_heap(unsettled.begin(), unsettled.end(), [&](const auto &lhs, const auto &rhs) { return rhs.key < lhs.key; }); auto top_entry_id = settled.size(); // assert(!dominated(node, unsettled.back().cost)); settled.push_back(std::move(unsettled.back())); unsettled.pop_back(); ensure_undominated_minium(node, policy, potentials); return std::tuple<const label_t &, std::size_t>{settled.back(), top_entry_id}; } // Returns all _settled_ labels of the given node const std::vector<label_t> &operator[](const node_id_t node) const { return settled_labels[node]; } template <typename NodePotentialsT> void ensure_undominated_minium(const node_id_t node, const PolicyT &policy, const NodePotentialsT &potentials) { auto &unsettled = unsettled_labels[node]; bool modified_min = true; while (!unsettled.empty() && modified_min) { auto &current_min = min(node); auto old_key = current_min.key; auto[is_dominated, was_modified] = clip_dominated(node, current_min, policy, potentials); if (is_dominated) { modified_min = true; } else if (was_modified) { // FIXME this is not true since the order in which // we test the domination matters // assert(!dominated(node, current_min.cost)); // clang-format off if constexpr(is_delta_label<label_t>::value) { current_min.delta.limit_from_x(current_min.cost.min_x(), current_min.cost.max_x()); current_min.delta.shrink_to_fit(); } detail::shrink_cost(current_min.cost); // clang-format on auto new_key = current_min.key; assert(new_key+to_fixed(0.01) >= old_key); modified_min = new_key > old_key; } else { modified_min = false; assert(current_min.key == old_key); } if (modified_min) { std::pop_heap(unsettled.begin(), unsettled.end(), [&](const auto &lhs, const auto &rhs) { return rhs.key < lhs.key; }); // either remove or re-insert if (is_dominated) { unsettled.pop_back(); } else { std::push_heap( unsettled.begin(), unsettled.end(), [&](const auto &lhs, const auto &rhs) { return rhs.key < lhs.key; }); } } } // assert(unsettled.empty() || !dominated(node, min(node).cost)); } std::vector<std::vector<label_t>> settled_labels; std::vector<std::vector<label_t>> unsettled_labels; }; } // namespace charge::common #endif
Java
UTF-8
29,300
1.796875
2
[]
no_license
package unsw.dungeon.DungeonBuilder; import java.io.File; import java.io.FileNotFoundException; import java.awt.AWTException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Accordion; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TitledPane; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.robot.Robot; import javafx.scene.shape.Circle; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Popup; import javafx.stage.Stage; import unsw.dungeon.Dungeon; import unsw.dungeon.Entity; import unsw.dungeon.StartScreen; import unsw.dungeon.StartScreenController; import unsw.dungeon.EntityList.Door; import unsw.dungeon.EntityList.Key; import unsw.dungeon.EntityList.Player; import unsw.dungeon.EntityList.Potion; import unsw.dungeon.EntityList.Sword; import unsw.dungeon.EntityList.Treasure; import unsw.dungeon.EntityList.StaffList.Staff; import unsw.dungeon.Goals.Goal; import unsw.dungeon.Goals.GoalComponent; import unsw.dungeon.Goals.GoalGroup; import unsw.dungeon.InventoryPopup.InventoryController; import unsw.dungeon.InventoryPopup.InventoryLoader; import unsw.dungeon.InventoryPopup.Item; import unsw.dungeon.CustomImage; import unsw.dungeon.Direction; /** * A JavaFX controller for the dungeon. * @author Robert Clifton-Everest * */ public class DungeonController { @FXML private GridPane squares; // @FXML // private HBox Hbox; @FXML private BorderPane borderPane; @FXML private StackPane stackPane; @FXML private TableView<Goal> goal; @FXML public TableColumn <Goal, String> entity; @FXML public TableColumn <Goal, Integer> status; @FXML public TableColumn <Goal, String> aimGoal; @FXML public TableColumn <Goal, Integer> idGoal; @FXML private TableView <String> instruction; @FXML public TableColumn <String, String> keybind; @FXML public TableColumn <String, String> action; @FXML public Accordion sidebar; @FXML public TitledPane Goals; @FXML public TitledPane Keybindings; @FXML public TableView<glossaryItems> glossary; @FXML public TableColumn<glossaryItems, ImageView> items; @FXML public TableColumn<glossaryItems, String> descriptions; private List<ImageView> initialEntities; boolean inventoryOpen; private InventoryLoader inventory; private Player player; private Dungeon dungeon; private Stage dungeonStage; private VBox sideMenu; //Table for GoalComponent private TableView gc; private TableView instructions; private DungeonApplication dungeonApp; private ArrayList<String> dungeonz = new ArrayList<>(); private StackPane textPane; private String currMap; public void setDungeonApp(DungeonApplication app) { this.dungeonApp = app; } public void setReset(String s) { this.currMap = s; } public GridPane getSquares() { return this.squares; } public void setStage(Stage stage) { this.dungeonStage = stage; } public Stage getStage() { return this.dungeonStage; } public DungeonController(Dungeon dungeon, List<ImageView> initialEntities) { this.dungeon = dungeon; this.player = dungeon.getPlayer(); this.initialEntities = new ArrayList<>(initialEntities); this.inventoryOpen = false; inventory = new InventoryLoader(); dungeon.setController(this); } /** * General initizer to call each different component of Dungeon. */ @FXML public void initialize() { initializeDungeon(); initializeSideMenu(); initializeGlossary(); // Use to return control and focus to Dungeon Game Platform.runLater(new Runnable() { @Override public void run() { // focus on grid squares.requestFocus(); } }); } @FXML public void GoalClick() { squares.setFocusTraversable(true); Robot robot = new Robot(); // Simulate a key press robot.keyPress(KeyCode.LEFT); robot.keyRelease(KeyCode.LEFT); } @FXML public void KeybindingClick() { squares.setFocusTraversable(true); Robot robot = new Robot(); // Simulate a key press robot.keyPress(KeyCode.LEFT); robot.keyRelease(KeyCode.LEFT); } @FXML public void initializeGlossary() { ObservableList<glossaryItems> dataItems = FXCollections.observableArrayList (); ArrayList<glossaryItems> inventory = new ArrayList<>(); inventory = this.getItems(); items.setCellValueFactory(new PropertyValueFactory<glossaryItems, ImageView>("ItemImage")); descriptions.setCellValueFactory(new PropertyValueFactory<glossaryItems, String>("description")); for (glossaryItems item: inventory) { dataItems.add(item); } glossary.setItems(dataItems); } public ArrayList<glossaryItems> getItems() { ArrayList<glossaryItems> list = new ArrayList<>(); ImageView playerImage = new ImageView (new Image("/images/nakedman.png")); ImageView wallImage1 = new ImageView (new Image("/images/yellowtree.png")); ImageView wallImage2 = new ImageView (new Image("/images/orangetree.png")); ImageView wallImage3 = new ImageView (new Image("/images/greentree.png")); ImageView exitImage = new ImageView (new Image("/images/exit.png")); ImageView treasureImage = new ImageView (new Image("/images/Treasure Chest closed 32x32.png")); ImageView doorcloseImage =new ImageView (new Image("/images/closedoor.png")); ImageView dooropenImage = new ImageView (new Image("/images/opendoor.png")); ImageView keyImage = new ImageView (new Image("/images/key.png")); ImageView boulderImage =new ImageView (new Image("/images/boulder.png")); ImageView floorswitchImage = new ImageView (new Image("/images/pressure_plate.png")); ImageView portalImage =new ImageView (new Image("/images/portal.png")); ImageView enemyImage = new ImageView (new Image("/images/enemyaxe.png")); ImageView swordImage =new ImageView (new Image("/images/bigsword.png")); ImageView potionImage = new ImageView (new Image("/images/brilliant_blue_new.png")); ImageView bloodImage = new ImageView (new Image("/images/blood.png")); ImageView manaImage = new ImageView (new Image("/images/mana.png")); ImageView rodImage = new ImageView (new Image("/images/rod.png")); ImageView fireImage = new ImageView (new Image("/images/fire.png")); ImageView airImage =new ImageView (new Image("/images/air.png")); ImageView waterImage = new ImageView (new Image("/images/water.png")); ImageView wizardImage =new ImageView (new Image("/images/wizard.png")); ImageView baImage = new ImageView(new Image("/images/bloodair.png")); ImageView bwImage = new ImageView(new Image("/images/bloodwater.png")); ImageView bfImage = new ImageView(new Image("/images/bloodfire.png")); ImageView maImage = new ImageView(new Image("/images/manaair.png")); ImageView mwImage = new ImageView(new Image("/images/manawater.png")); ImageView mfImage = new ImageView(new Image("/images/manafire.png")); glossaryItems playerItem = new glossaryItems(playerImage, "this is the player model"); glossaryItems wallItem1 = new glossaryItems(wallImage1, "this is a wall"); glossaryItems wallItem2 = new glossaryItems(wallImage2, "this is a wall"); glossaryItems wallItem3 = new glossaryItems(wallImage3, "this is a wall"); glossaryItems exitItem = new glossaryItems(exitImage, "this is the exit for th elevel"); glossaryItems treasureItem = new glossaryItems(treasureImage, "this is the treasure"); glossaryItems doorcloseItem = new glossaryItems(doorcloseImage, "this is a locked door"); glossaryItems dooropenItem = new glossaryItems(dooropenImage, "this is an unlocked door"); glossaryItems keyItem = new glossaryItems(keyImage, "this is a key"); glossaryItems boulderItem = new glossaryItems(boulderImage, "this is a boulder"); glossaryItems switchItem = new glossaryItems(floorswitchImage, "this is a floorswitch"); glossaryItems portalItem = new glossaryItems(portalImage, "this is a portal"); glossaryItems enemyItem = new glossaryItems(enemyImage, "this is an enemy"); glossaryItems swordItem = new glossaryItems(swordImage, "this is sword"); glossaryItems potionItem = new glossaryItems(potionImage, "this is potion"); glossaryItems bloodItem = new glossaryItems(bloodImage, "this is blood crystal"); glossaryItems manaItem = new glossaryItems(manaImage, "this is mana crystal"); glossaryItems rodItem = new glossaryItems(rodImage, "this is a rod"); glossaryItems fireItem = new glossaryItems(fireImage, "this is fire element"); glossaryItems airItem = new glossaryItems(airImage, "this is air element"); glossaryItems waterItem = new glossaryItems(waterImage, "this is water element"); glossaryItems wizardItem = new glossaryItems(wizardImage, "this is wizard model"); glossaryItems baItem = new glossaryItems(baImage, "this is blood air staff (press u to kill all enemies)"); glossaryItems bwItem = new glossaryItems(bwImage, "this is blood water staff (press u to make enemies stupid)"); glossaryItems bfItem = new glossaryItems(bfImage, "this is blood fire staff (press u to kill all enemies)"); glossaryItems maItem = new glossaryItems(maImage, "this is mana air staff (press u to activate 10 turn potino)"); glossaryItems mwItem = new glossaryItems(mwImage, "this is mana water staff (press u to freeze all enemies)"); glossaryItems mfItem = new glossaryItems(mfImage, "this is mana fire model (press u to teleport to random entity)"); list.add(playerItem); list.add(wallItem1); list.add(wallItem2); list.add(wallItem3); list.add(exitItem); list.add(treasureItem); list.add(doorcloseItem); list.add(dooropenItem); list.add(keyItem); list.add(boulderItem); list.add(switchItem); list.add(portalItem); list.add(enemyItem); list.add(swordItem); list.add(potionItem); list.add(bloodItem); list.add(manaItem); list.add(rodItem); list.add(fireItem); list.add(airItem); list.add(waterItem); list.add(wizardItem); list.add(baItem); list.add(bwItem); list.add(bfItem); list.add(maItem); list.add(mwItem); list.add(mfItem); return list; } @FXML public void initializeDungeon() { Image ground1 = new Image("/images/grass1.png"); Image ground2 = new Image("/images/grass2.png"); Image ground3 = new Image("/images/grass3.png"); Image ground4 = new Image("/images/grass4.png"); Image ground5 = new Image("/images/grass5.png"); // Add the ground first so it is below all other entities for (int x = 0; x < dungeon.getWidth(); x++) { for (int y = 0; y < dungeon.getHeight(); y++) { ArrayList<Image> groundImages = new ArrayList<>(); groundImages.add(ground1); groundImages.add(ground2); groundImages.add(ground3); groundImages.add(ground4); groundImages.add(ground5); Random rand = new Random(); Image randomImage = groundImages.get(rand.nextInt(groundImages.size())); squares.add(new ImageView(randomImage), x, y); } } //need to add into goals first, goal list for (ImageView entity : initialEntities) squares.getChildren().add(entity); dungeon.makeGraph(); } /** * Initialize the size menu to display game information */ public void initializeSideMenu() { initializeGoals(); initializeInstructions(); sidebar.setFocusTraversable(false); Goals.setFocusTraversable(false); Keybindings.setFocusTraversable(false); glossary.setFocusTraversable(false); // System.out.println("Side Menu Active"); // add into side //borderPane.getChildren().add(sideMenu); } /** * Update Goals on the SideMenu in a table format */ public void initializeGoals() { // Create columns // TableColumn<String, String> goalsColumn = new TableColumn<String, String>("Dungeon Goal!"); // goalsColumn.setCellValueFactory(new PropertyValueFactory<>("typeEntity")); // Read descriptions // // TableColumn<String, SimpleBooleanProperty> completenessColumn = new TableColumn<String, SimpleBooleanProperty>("Have you Achieved?"); // completenessColumn.setCellValueFactory(new PropertyValueFactory<>("Completed")); // Read status of each goal // // gc.getColumns().setAll(goalsColumn, completenessColumn); // add columns to table GoalComponent dungeonGoals = this.dungeon.getGoals(); // fetch list of goals from dungeon ArrayList<GoalComponent> SingleGoals = dungeonGoals.getSingleGoals(); ObservableList<Goal> data = FXCollections.observableArrayList(); // temporary container for data for (GoalComponent goal: SingleGoals) { //System.out.println("========== IN IN IN =========="); SimpleIntegerProperty tableGoal = ((Goal)goal).NeedCompleteProperty(); tableGoal.addListener((ChangeListener) (observable, oldValue, newValue) -> { if (oldValue != newValue) { data.remove((Goal)goal); data.add((Goal)goal); } }); data.add((Goal)goal); } entity.setCellValueFactory(new PropertyValueFactory<Goal, String>("typeEntity")); status.setCellValueFactory(new PropertyValueFactory<Goal, Integer>("NeedComplete")); aimGoal.setCellValueFactory(new PropertyValueFactory<Goal, String>("goalAim")); idGoal.setCellValueFactory(new PropertyValueFactory<Goal, Integer>("ID")); goal.setItems(data); goal.setFocusTraversable(false); goal.setMouseTransparent(true); } public void initializeInstructions() { // Columns descriptors keybind.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(splitter(cellData.getValue())[0])); action.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(splitter(cellData.getValue())[1])); // Add the respective columns to table instruction.getColumns().setAll(keybind, action); // Add rows of instruction to table splitted by colon instruction.getItems().add("Up arrow key:Move up"); instruction.getItems().add("Down arrow key:Move down"); instruction.getItems().add("Left arrow key:Move left"); instruction.getItems().add("Right arrow key:Move right"); instruction.getItems().add("R key:restart level"); instruction.getItems().add("Q key:quit level"); instruction.getItems().add("I key:open inventory"); instruction.getItems().add("U key:activate staff"); instruction.setFocusTraversable(false); //instruction.setMouseTransparent(true); } // Instruction reading, separate the columns private String[] splitter(String string) { // TODO Auto-generated method stub return string.split(":",2); } // // // Structure format for Menu // public void initializeSideMenuFormat(TableView table) { // // // Table format structure // table.setFixedCellSize(30); // size of each cell // table.minHeightProperty().bind(table.prefHeightProperty()); // min height // table.maxHeightProperty().bind(table.prefHeightProperty()); // min height // table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); // table.prefWidthProperty().setValue(300); // table.minWidthProperty().bind(table.prefWidthProperty()); // table.maxWidthProperty().bind(table.prefWidthProperty()); // // // UI Restrictions // table.setFocusTraversable(false); // User cannot click list // table.setMouseTransparent(true); // Cannot click or alter table // sideMenu.getChildren().add(table); // add table to the side menu // // } @FXML public void handleKeyPress(KeyEvent event) throws IOException, InterruptedException { boolean moveCase = false; Direction direction = null; switch (event.getCode()) { case UP: direction = Direction.UP; moveCase = dungeon.move(player.getX(), player.getY() - 1, direction); if (moveCase == true) { player.moveUp(); } break; case DOWN: direction = Direction.DOWN; moveCase = dungeon.move(player.getX(), player.getY() + 1, direction); if (moveCase == true) { player.moveDown(); } break; case LEFT: direction = Direction.LEFT; moveCase = dungeon.move(player.getX() - 1, player.getY(), direction); if (moveCase == true) { player.moveLeft(); } break; case RIGHT: direction = Direction.RIGHT; moveCase = dungeon.move(player.getX() + 1, player.getY(), direction); if (moveCase == true) { player.moveRight(); } break; case I: if (inventoryOpen == false) { ArrayList<Entity> inventoryItems = (ArrayList<Entity>) player.getInventory(); //inventory.show(dungeonStage); //inventory.showInventoryView(dungeonStage); inventory.showInventory(dungeonStage, inventoryItems); //inventory.showInventoryImage(dungeonStage); //System.out.println("hi"); inventoryOpen = true; } else { //System.out.println("hi"); inventory.hideInventory(); //inventory.hideInventoryImage(); //inventory.hide(); inventoryOpen = false; } break; case K: System.out.println("Heres a cookie"); break; case Q: dungeonStage.close(); break; case R: dungeonReset(); break; case U: Staff staff = player.getStaff(); if (staff != null) { staff.useStaff(dungeon); } break; case D: dungeon.dropKey(); break; case N: stackPane.getChildren().remove(textPane); // remove pane to allow for reset try { continueDungeon(); } catch (IOException e) { System.out.println("Exception in showMessage "+ e); e.printStackTrace(); } // restart game break; default: break; } if (moveCase) { dungeon.playerInteract(player.getX(), player.getY(), direction); } if(player.isAlive() == false) playerDead(); if(dungeon.dungeonComplete()) dungeonFinish(); } public void removeEntity(Entity entity) { ObservableList<Node> childrens = squares.getChildren(); if (childrens.size() == 0) { //System.out.println("no nodes"); } for(Node node : childrens) { //System.out.println("x is: " + squares.getRowIndex(node) + "y is: " + squares.getRowIndex(node)); if(node instanceof ImageView && squares.getRowIndex(node) == entity.getX() && squares.getColumnIndex(node) == entity.getY()) { //System.out.println("foundimage"); squares.getChildren().remove(entity.getImageView()); break; } } } public void changeEntity(Entity entity) { ObservableList<Node> childrens = squares.getChildren(); if (childrens.size() == 0) { //System.out.println("no nodes"); } for(Node node : childrens) { //System.out.println("x is: " + squares.getRowIndex(node) + "y is: " + squares.getRowIndex(node)); if(node instanceof ImageView && squares.getRowIndex(node) == entity.getX() && squares.getColumnIndex(node) == entity.getY()) { //System.out.println("foundimage"); squares.getChildren().remove(((Entity)entity).getImageView()); ImageView door = new ImageView (new Image("/images/opendoor.png")); squares.add(door, squares.getRowIndex(node), squares.getColumnIndex(node)); break; } } } public void openDoor(Door door) { ObservableList<Node> childrens = squares.getChildren(); if (childrens.size() == 0) { //System.out.println("no nodes"); } for(Node node : childrens) { //System.out.println("x is: " + squares.getRowIndex(node) + "y is: " + squares.getRowIndex(node)); if(node instanceof ImageView && squares.getRowIndex(node) == door.getX() && squares.getColumnIndex(node) == door.getY()) { //System.out.println("foundimage"); squares.getChildren().remove(door.getImageView()); ImageView openDoor = new ImageView("/images/open_door.png"); squares.getChildren().add(openDoor); break; } } } /** * Show user message on game status, * prints message or warning to screen and stops game (unless R restarted) * @param string */ public void showMessage(String string) { // Create message String message = "Press R to reset the Level!!!!"; Text text = new Text(string + "\n" + message); // text object textPane = new StackPane(); // message // Style settings text.setFill(Color.WHITE); text.setStrokeWidth(2); text.setStroke(Color.PURPLE); text.setFont(Font.font("Times New Roman", FontWeight.BOLD, FontPosture.REGULAR, 30)); // Add text to textPane textPane.getChildren().add(text); // Align message textPane.setAlignment(Pos.CENTER); // Key listener to check request on stackPane focused when game stops textPane.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { // Check which key is pressed switch (event.getCode()) { case R: stackPane.getChildren().remove(textPane); // remove pane to allow for reset try { dungeonReset(); } catch (IOException e) { System.out.println("Exception in showMessage "+ e); e.printStackTrace(); } // restart game break; case N: stackPane.getChildren().remove(textPane); // remove pane to allow for reset try { continueDungeon(); } catch (IOException e) { System.out.println("Exception in showMessage "+ e); e.printStackTrace(); } // restart game break; default: } } }); stackPane.getChildren().add(textPane); // add message to screen stackPane.setFocusTraversable(false); // disable interaction with rest of game textPane.requestFocus(); // force message to be focus } public void playerDead() { showMessage("YOU ARE DEAD"); } public void dungeonFinish() throws IOException, InterruptedException { showMessage("LEVEL COMPLETE!!! ~ PRESS N FOR NEXT LEVEL"); } public void dungeonReset() throws FileNotFoundException, IOException { dungeonStage.close(); dungeonStage.setTitle("Dungeon"); System.out.println(currMap); DungeonControllerLoader dungeonLoader = new DungeonControllerLoader(currMap); DungeonController controller = dungeonLoader.loadController(); //set curr Map to resetted map again controller.setReset(currMap); FXMLLoader loader = new FXMLLoader(getClass().getResource("DungeonView.fxml")); controller.setStage(dungeonStage); loader.setController(controller); Parent root = loader.load(); Scene scene = new Scene(root); root.requestFocus(); dungeonStage.setScene(scene); dungeonStage.show(); } public void continueDungeon() throws IOException { getMaps(); Random rand = new Random(); String map = dungeonz.get(rand.nextInt(dungeonz.size())); dungeonStage.close(); dungeonStage.setTitle("Dungeon NEW LEVEL!!! EXTRAWUWODINARY !!!"); DungeonControllerLoader dungeonLoader = new DungeonControllerLoader(map); DungeonController controller = dungeonLoader.loadController(); controller.setReset(map); //set curr Map to resetted map again controller.setReset(currMap); FXMLLoader loader = new FXMLLoader(getClass().getResource("DungeonView.fxml")); controller.setStage(dungeonStage); loader.setController(controller); Parent root = loader.load(); Scene scene = new Scene(root); root.requestFocus(); dungeonStage.setScene(scene); dungeonStage.show(); } /** * Read from dungeons folder and return arraylist of map * map to be used to generate next map once level complete */ public void getMaps() { File maps = new File("dungeons/"); File[] listOfFiles = maps.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && !listOfFiles[i].getName().contentEquals(".DS_Store")) { //add each file name to list dungeonz.add(listOfFiles[i].getName()); //System.out.println("File " + listOfFiles[i].getName()); } else if (listOfFiles[i].isDirectory()) { //System.out.println("Directory " + listOfFiles[i].getName()); } } } public void displayKeyError() { final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); dialog.initOwner(dungeonStage); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("Wrong Key! Press d to drop current key")); Scene dialogScene = new Scene(dialogVbox, 300, 200); dialog.setScene(dialogScene); dialog.show(); } public void displayNoKey() { final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); dialog.initOwner(dungeonStage); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("You have no key! please find the correct key!")); Scene dialogScene = new Scene(dialogVbox, 300, 200); dialog.setScene(dialogScene); dialog.show(); } public void addEntity(Key key) { ObservableList<Node> childrens = squares.getChildren(); if (childrens.size() == 0) { //System.out.println("no nodes"); } for(Node node : childrens) { //System.out.println("x is: " + squares.getRowIndex(node) + "y is: " + squares.getRowIndex(node)); if(node instanceof ImageView && squares.getRowIndex(node) == key.getX() && squares.getColumnIndex(node) == key.getY()) { squares.add((key).getImageView(), squares.getRowIndex(node), squares.getColumnIndex(node)); break; } } } public void finishExit() { final Stage dialog = new Stage(); dialog.initModality(Modality.APPLICATION_MODAL); dialog.initOwner(dungeonStage); VBox dialogVbox = new VBox(20); dialogVbox.getChildren().add(new Text("Please finish the other goal first!")); Scene dialogScene = new Scene(dialogVbox, 300, 200); dialog.setScene(dialogScene); dialog.show(); } }
Java
UTF-8
479
2.375
2
[]
no_license
package lessonFiles; import java.nio.file.Path; import java.nio.file.Paths; import java.io.File; public class Main { public static void main(String[] args) { Path path = Paths.get("taskTreeSer.txt"); File file = new File("G:\\Ira_student/", "Hello.txt"); System.out.println("hello" + file.getName()); System.out.println(path.getFileName()); System.out.println(file.getParent()); System.out.println(path.getRoot()); } }
C
UTF-8
353
3.625
4
[]
no_license
/* Hailstone sequence */ #include <stdio.h> void hailstone() { int ch; printf("Enter a non-zero natural number: "); scanf("%d",&ch); if(ch <= 0) { printf("Invalid input.\n"); return; } while(ch != 1) { printf("%d, ",ch); if(ch%2 == 1) ch = 3*ch + 1; else ch /= 2; } printf("1\n"); } int main() { hailstone(); return 0; }
Markdown
UTF-8
1,407
2.84375
3
[ "MIT" ]
permissive
--- id: Dominate Monster title: 支配怪物Dominate Monster --- **8 环** 附魔 施法时间:1 动作 施法距离:60 尺 法术成分:V、S 持续时间:专注,至多 1 小时 你试图安抚一个施法距离内你能看见的生物,必须成功通过一次感知豁免,否则将在法术持续时间内被你魅惑。若它正与你或你的友方生物战斗,则其进行该豁免时具有优势。 该生物被魅惑时,只要你与其处于同一位面就可以与之保持心灵感应。你在有意识时,可以通过心灵感应命令该生物(不需要作动作),而它则会尽量服从。你可以描述一个简单具体的行为指令,比如“攻击那个生物”“跑到那个位置”或是“去拿那个物品”。生物完成一项指令却未收到你的进一步指示时,将会使用其本身的能力尽可能的保护自己。 你可以使用动作以彻底而精确的控制目标。而该生物则只能作你选择的动作,且不能作任何你没有允许的动作,并持续至你下回合结束。在此期间,你还可以要求该生物作一个反应, 但这需要你使用自己的反应来实现。 每次目标受到伤害时,都可以尝试进行一次感知豁免,豁免成功则法术终止。 升环施法效应 。使用 9 环法术位施展该法术时,持续时间变为:专注,至多 8 小时。
C
UTF-8
1,004
3.578125
4
[ "MIT" ]
permissive
#include <stdio.h> double leia_numero(char *msg) { int i =0; double num = 0; // printf("%c - %d - %s\n", msg[i], msg[i], msg); while(msg[i]!=0 && msg[i] > '0' && msg[i] < '9'){ num = num*10; num = num + msg[i] - 48; i++; } if ((msg[i] < '0' || msg[i] > '9') && msg[i]!=0){ // printf("Digite um número!\n"); return num = -1; } if (num > 100 || num < 0){ return num = -2; } return num; } int main(void) { double n; char v[20]; printf("n: "); fflush(stdin); scanf("%s", v); n = leia_numero(v); while(n == -1){ fflush(stdin); printf("Digite um número!\n"); printf("n: "); scanf("%s", v); n = leia_numero(v); } while(n == -2){ fflush(stdin); printf("Escolha um número entre 0 e 100!\n"); printf("n: "); scanf("%s", v); n = leia_numero(v); } if (n != -1){ printf("%.3f\n", n + 1); } }
C++
UTF-8
334
2.765625
3
[]
no_license
class Solution { public: int jump(vector<int>& nums) { int cnt=0; for(int i=nums.size()-1;i>0;){ for(int j=0;j<i;j++){ if(nums[j]>=i-j){ cnt++; i=j; break; } } } return cnt; } };
Java
UTF-8
2,588
3.671875
4
[]
no_license
package usta.sistemas; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { /*Author: Andres Nicolas Morales Perez Date: 2020 - April - 27 Description: program that, Using repetitive cycles build a program that prints the multiplication tables from number 1 to number 10 in the range from 1 to 10. */ f_menu(); int aleatory_number = f_aleatory_number(); int number_user = f_input_number(); int attempt = 5; while (number_user != aleatory_number && attempt > 1) { attempt--; System.err.println("The number is different than the generated number (Attempt = " + attempt + " )"); number_user = f_input_number(); } if (attempt > 1) { System.out.println("YOU WIN A HAMBURGER"); } else { System.out.println("SORRY YOU LOST, THE RANDOM NUMBER WAS " + aleatory_number); } } public static void f_menu() { //This method show the menu of this software System.out.println("╔══════════════════════════════╗"); System.out.println("║ SoftRandomBurger ║"); System.out.println("║ Version 1.0 20200427 ║"); System.out.println("║ Created by: Nicolas Morales ║"); System.out.println("╚══════════════════════════════╝"); } public static int f_aleatory_number() { //This method generate one number aleatory int number = (int) Math.floor(Math.random() * 100 + 1); if (number < 50) { System.out.println("Hint: The number is minor than 50"); } else { System.out.println("Hint: The number is grater than 50"); } if (number % 2 == 0) { System.out.println("Hint 2: the number is pair"); } else { System.out.println("Hint 2: The number is odd"); } return number; } public static int f_input_number() { //This method ask one number Scanner keyboard = new Scanner(System.in); int input; System.out.println("Type number to compare (0 - 100)"); input = keyboard.nextInt(); while (input < 0 || input > 100) { System.err.println("ERR: the input must be between 0 and 100\nRetry"); input = keyboard.nextInt(); } return input; } }
C#
UTF-8
394
2.671875
3
[]
no_license
using System; using System.Net; namespace Pokemon.Models { public class ApiException : Exception { public string ErrorMessage { get; set; } public HttpStatusCode ErrorCode { get; set; } public ApiException(HttpStatusCode code, string errorMessage) { this.ErrorCode = code; this.ErrorMessage = errorMessage; } } }
C#
UTF-8
692
3.078125
3
[]
no_license
private static Task<bool> CreateTask(CancellationTokenSource cts) { return Task.Run(async () => { var result = await TaskAction(cts.Token); // If result is false, cancel all tasks if (!result) cts.Cancel(); return result; }); } private static async Task<bool> TaskAction(CancellationToken token) { // Check for cancellation token.ThrowIfCancellationRequested(); var delay = Rnd.Next(2, 5); // Pass the cancellation token to Task.Delay() await Task.Delay(delay * 1000, token); var taskResult = Rnd.Next(10) < 4; // Check for cancellation token.ThrowIfCancellationRequested(); return taskResult; }
C++
UTF-8
562
2.875
3
[]
no_license
#include<bits/stdc++.h> using namespace std ; vector<vector<int> > adj ; vector<bool> visited(1000) ; void BFS(int n){ queue<int> q ; visited[n] = true ; q.push(n) ; while(!q.empty()){ int node = q.front() ; cout<< node << " " ; q.pop() ; for(int i=0; i<adj[node].size(); i++){ int adjNode = adj[node][i] ; if(!visited[adjNode]){ visited[adjNode] = true ; q.push(adjNode) ; } } } } int main(){ bfs(10) ; return 0 ; }
TypeScript
UTF-8
582
3
3
[]
no_license
export const stripTrailingSlash = (str: string) => { return str.endsWith('/') ? str.slice(0, -1) : str } export const getBasicAuthString = (username: string, password: string) => { const token = username + ':' + password const hash = Buffer.from(token).toString('base64') return 'Basic ' + hash } export const formatDate = (date: Date) => { let month = '' + (date.getMonth() + 1) let day = '' + date.getDate() const year = date.getFullYear() if (month.length < 2) month = '0' + month if (day.length < 2) day = '0' + day return [year, month, day].join('-') }
Ruby
UTF-8
474
3
3
[]
no_license
class Complement def self.of_dna(s) ns = '' for i in 0...s.length case s[i] when 'G' then ns+='C' when 'C' then ns+='G' when 'T' then ns+='A' when 'A' then ns+='U' end end ns end def self.of_rna(s) ns = '' for i in 0...s.length case s[i] when 'C' then ns+='G' when 'G' then ns+='C' when 'A' then ns+='T' when 'U' then ns+='A' end end ns end end
Java
UTF-8
522
2.40625
2
[ "MIT" ]
permissive
package net.openid.conformance.variant; @VariantParameter( name = "sender_constrain", displayName = "Sender Constraining", description = "The method to use to sender constrain access tokens. FAPI2 allows the use of MTLS or DPoP as proof-of-possession methods, select the one you support. MTLS was the mechanism used in FAPI1. If your software supports both, test both one at a time." ) public enum FAPI2SenderConstrainMethod { MTLS, DPOP; @Override public String toString() { return name().toLowerCase(); } }
JavaScript
UTF-8
8,638
3.25
3
[]
no_license
let canvas = document.getElementById('canvas') let ctx = canvas.getContext('2d') let snakeWidth = 20 let snake = [{x: 0, y: snakeWidth}, {x: snakeWidth, y: snakeWidth}, {x: snakeWidth * 2, y: snakeWidth}] let snakeMaxLen = 1000 let head = 2 let len = 3 let directions = [[0, -1], [0, 1], [-1, 0], [1, 0]] let direction = directions[3] let food, score = 0, gameOver = false, paused = false, win = false let speed = 5 let result = document.getElementById('result') let snakeXCnt = canvas.width / snakeWidth let snakeYCnt = canvas.height / snakeWidth let colors = ['red', 'orange', 'blue', 'purple', 'pink', 'salmon', 'black'] refresh() function eatFoodCheck(x, y) { if (food && food.x > x && food.x < x + snakeWidth && food.y > y && food.y < y + snakeWidth) { food = undefined len++ score += 10 document.getElementById('score').innerText = score if(len === snakeMaxLen) { win = true } } } function boundaryCheck(x, y) { gameOver = x < snakeWidth || y < snakeWidth || x + snakeWidth * 2 > canvas.width || y + snakeWidth * 2 > canvas.height if(gameOver) { console.log('boundary'+x+';'+y) } } function snakeCheck(x, y) { for(let i = len; i > 0; i--) { let idx = (i + head - len + snake.length) % snake.length if(x === snake[idx].x && y === snake[idx].y) { gameOver = true console.log('snake') break } } } function refresh() { if(gameOver) { return } if(!paused) { let x = snake[head].x + snakeWidth * direction[0] let y = snake[head].y + snakeWidth * direction[1] eatFoodCheck(x, y) boundaryCheck(x, y) snakeCheck(x, y) if(win) { result.style.display = 'block' document.getElementById('fail').style.display = 'none' document.getElementById('success').style.display = 'block' return } if(gameOver) { result.style.display = 'block' document.getElementById('fail').style.display = 'block' document.getElementById('success').style.display = 'none' return } if(snake.length < snakeMaxLen) { snake.push({x: x, y: y}) head++ } else { head = (head + 1) % snake.length snake[head] = {x: x, y: y} } clearAll() drawBoundary() drawSnake() drawFood() } setTimeout(refresh, 1000 / speed) } function isInSnake(x, y) { for(let i = len; i > 0; i--) { let idx = (i + head - len + snake.length) % snake.length if(x > snake[idx].x && x < snake[idx].x + snakeWidth && y > snake[idx].y && y < snake[idx].y + snakeWidth) { return true } } return false } function drawFood() { if(!food) { food = {} food.x = Math.floor(Math.random() * (snakeXCnt - 2) + 1) * snakeWidth + snakeWidth / 2 food.y = Math.floor(Math.random() * (snakeYCnt - 2) + 1) * snakeWidth + snakeWidth / 2 while(isInSnake(food.x, food.y)) { food.x = Math.floor(Math.random() * (snakeXCnt - 2) + 1) * snakeWidth + snakeWidth / 2 food.y = Math.floor(Math.random() * (snakeYCnt - 2) + 1) * snakeWidth + snakeWidth / 2 } food.color = randomAColor() } /*ctx.beginPath() ctx.arc(food.x, food.y, 4, 0, Math.PI * 2, true) ctx.fillStyle = 'orange' ctx.fill()*/ drawFLower(food.x, food.y, food.color) } function randomAColor() { return colors[Math.floor(Math.random() * colors.length)] } document.addEventListener('keyup', e => { if(gameOver || paused) { return } if(e.key === 'ArrowUp') { updateDirection(0) } else if(e.key === 'ArrowDown') { updateDirection(1) } else if(e.key === 'ArrowLeft') { updateDirection(2) } else if(e.key === 'ArrowRight') { updateDirection(3) } }) function isOpposite(newDirect, direction) { return newDirect[0] + direction[0] === 0 && newDirect[1] + direction[1] === 0; } function updateDirection(idx) { let newDirect = directions[idx] if(!isOpposite(newDirect, direction)) { direction = newDirect } } function clearAll() { ctx.clearRect(0, 0, canvas.width, canvas.height) } function drawSnake() { ctx.beginPath() let last = null for(let i = len; i > 0; i--) { let idx = (i + head - len + snake.length) % snake.length //console.log(snake[idx]) if(idx === head) { drawHead(snake[idx].x, snake[idx].y) } else { drawBody(snake[idx].x, snake[idx].y, {x: last.x - snake[idx].x, y: last.y - snake[idx].y}) } last = snake[idx] } } function drawBoundary() { ctx.fillStyle = '#eeeeee' ctx.beginPath() ctx.rect(0,0,canvas.width, snakeWidth) ctx.fill() ctx.rect(0, canvas.height - snakeWidth,canvas.width, snakeWidth) ctx.fill() ctx.rect(0,0, snakeWidth, canvas.height) ctx.fill() ctx.rect(canvas.width - snakeWidth,0, snakeWidth, canvas.height) ctx.fill() } function restart() { snake = [{x: 0, y: snakeWidth}, {x: snakeWidth, y: snakeWidth}, {x: snakeWidth * 2, y: snakeWidth}] head = 2 len = 3 direction = directions[3] food = undefined score = 0 gameOver = false win = false speed = 5 paused = false document.getElementById('pause').innerText = paused ? 'Resume' : 'Pause' document.getElementById('speed').innerText = speed document.getElementById('score').innerText = score result.style.display = 'none' refresh() } function pause() { paused = !paused document.getElementById('pause').innerText = paused ? 'Resume' : 'Pause' } function speedUp(increment) { if(speed + increment >= 1 && speed + increment <= 20) { speed += increment document.getElementById('speed').innerText = speed } } function getRadialGradient(x,y,r) { var radial = ctx.createRadialGradient(x+r/2, y + r/2, r/4,x + r,y + r, r); radial.addColorStop(0,'rgb(108,172,108)') radial.addColorStop(0.9,'rgb(90,150,90)') radial.addColorStop(1, 'rgba(90,150,90,0)') return radial } function drawCircle(x, y, r) { ctx.beginPath() ctx.fillStyle = getRadialGradient(x,y,r) ctx.fillRect(x, y, 2*r, 2*r) } function drawHead(x, y) { drawCircle(x,y, snakeWidth / 2) let xC = x + snakeWidth / 2; let yC = y + snakeWidth / 2; let x1, y1, x2, y2 if(direction === directions[3]) { x1 = xC + 2 x2 = xC + 3 y1 = y2 = yC x3 = x + 3 * snakeWidth / 2 y3 = yC x4 = x + 3 * snakeWidth / 2 y4 = y - snakeWidth / 2 sA = 7/6 * Math.PI eA = 3/2 * Math.PI } else if(direction === directions[2]) { x1 = xC - 2 x2 = xC - 3 y1 = y2 = yC x3 = x - snakeWidth / 2 y3 = yC x4 = x - snakeWidth / 2 y4 = y - snakeWidth / 2 sA = 3/2 * Math.PI eA = 11/6 * Math.PI } else if(direction === directions[1]) { y1 = yC + 2 y2 = yC + 3 x1 = x2 = xC x3 = xC y3 = y + 3 * snakeWidth / 2 x4 = x + 3 * snakeWidth / 2 y4 = y + 3 * snakeWidth / 2 sA = 10/6 * Math.PI eA = 2 * Math.PI } else { y1 = yC - 2 y2 = yC - 3 x1 = x2 = xC x3 = xC y3 = y - snakeWidth / 2 x4 = x + 3 * snakeWidth / 2 y4 = y - snakeWidth / 2 sA = 0 eA = 1/3 * Math.PI } //眼睛 ctx.fillStyle='white' ctx.arc(x1, y1,5,0, Math.PI * 2,true) ctx.fill() ctx.beginPath() ctx.fillStyle='black' ctx.arc(x2, y2,2,0,Math.PI*2,true) ctx.fill() //触角 ctx.beginPath() ctx.arc(x3, y3, 20, sA, eA, false) ctx.stroke() ctx.beginPath() ctx.arc(x4, y4, 5, 0, 2 * Math.PI, false) ctx.fill() } function drawBody(x, y, direct) { let r = snakeWidth / 2 * 0.8 if(direct.x > 0) { //right drawCircle(x + snakeWidth / 2,y + snakeWidth/ 2 - r, r) drawCircle(x, y + snakeWidth/ 2 - r, r) } else if(direct.x < 0) { // left drawCircle(x + snakeWidth/2 - 2 * r, y + snakeWidth/ 2 - r, r) drawCircle(x + snakeWidth - 2 * r, y + snakeWidth/ 2 - r, r) } else if (direct.y > 0) { //down drawCircle(x + snakeWidth / 2 - r, y + snakeWidth / 2, r) drawCircle(x + snakeWidth / 2 - r, y, r) } else { //up drawCircle(x + snakeWidth / 2 - r, y + snakeWidth/2 - 2 * r, r) drawCircle(x + snakeWidth / 2 - r, y + snakeWidth - 2 * r, r) } } function drawFLower(x, y, color = 'orange') { ctx.save() ctx.translate(x,y) ctx.scale(0.5,0.5) ctx.fillStyle = color ctx.rotate(72/180 * Math.PI);ctx.beginPath();ctx.arc(0, -10, 6, 0, 2 * Math.PI, true);ctx.fill() ctx.rotate(72/180 * Math.PI);ctx.beginPath();ctx.arc(0, -10, 6, 0, 2 * Math.PI, true);ctx.fill() ctx.rotate(72/180 * Math.PI);ctx.beginPath();ctx.arc(0, -10, 6, 0, 2 * Math.PI, true);ctx.fill() ctx.rotate(72/180 * Math.PI);ctx.beginPath();ctx.arc(0, -10, 6, 0, 2 * Math.PI, true);ctx.fill() ctx.rotate(72/180 * Math.PI);ctx.beginPath();ctx.arc(0, -10, 6, 0, 2 * Math.PI, true);ctx.fill() ctx.restore() }
Markdown
UTF-8
4,391
3.390625
3
[]
no_license
# Observer パターン ## 課題 高度に統合されたシステムをつくりたい。システムの各部分が、システム全体の状態についての関心や知識を持つといったものだ。またメンテナンスしやすいようにしたい。そのためにクラス同士の密結合は避けるべきだ。 ## 解決策 別のコンポーネント (subjectコンポーネント) の挙動を知っているコンポーネント (observerコンポーネント) がほしい場合、単純に両方のクラスを強固に繋ぎ合わせて、subjectコンポーネントの挙動をobserverコンポーネントに知らせることはできる。つまりsubjectコンポーネントをつくるときにobserverコンポーネントの参照を渡し、subjectコンポーネントに変化が起きたときにobserverオブジェクトのメソッドを呼ぶということだ。しかしこのやり方だと密結合を増やすことになる。これは避けたい状況だ。さらに他のobserverにも通知したい場合、subjectコンポーネントの実装を変更しなければならない。subjectコンポーネント自体はなにも変わっていないにも関わらず。より良いやり方は、subjectコンポーネントの変化に関心のあるオブジェクトのリストをキープしておき、ニュース発信元 (subjectコンポーネント) とニュース購読者 (observerコンポーネント) とのきれいなインターフェイスを定義することだ。こうすればsubjectコンポーネントに変化があったときには、observerリストの各オブジェクトにインターフェイスを通して通知するだけだ。 ## 例 `salary`プロパティーをもつ`Employee`オブジェクトを考えよう。従業員給与名簿 (payroll) のシステムに変更を知らせながら、salaryを変更したい。もっともシンプルなやり方は、payrollの参照を渡して、従業員の`salary`を変更したときに payroll に通知することだ。 ```ruby class Employee attr_reader :name, :title attr_reader :salary def initialize(name, title, salary, payroll) @name = name @title = title @salary = salary @payroll = payroll end def salary=(new_salary) @salary = new_salary @payroll.update(self) end end ``` 問題は、別のオブジェクト (例えば`TaxMan`) に通知したいとき、`Employee`を変更しなければならないことだ。つまり他のクラスが`Employee`クラスの変更の直接原因となっているのだ。`Employee`クラス自体にはなんの変更もないのに。salaryの変更に関心をもつオブジェクトのリストを保持する方法を考えよう。 ```ruby class Employee attr_reader :name, :title attr_reader :salary def initialize(name, title, salary) @name = name @title = title @salary = salary @observers = [] end def salary=(new_salary) @salary = new_salary notify_observers end def add_observer(observer) @observers << observer end def delete_observer(observer) @observers.delete(observer) end def notify_observers @observers.each do |observer| observer.update(self) end end end ``` これで`add_observer`メソッドでobserverリストにどんなオブジェクトでも追加できるし、salaryが変更されたときはobserverリストの全オブジェクトに知らせることができる。 ```ruby fred = Employee.new('Fred', 'Crane Operator', 30000.0) payroll = Payroll.new fred.add_observer(payroll) tax_man = TaxMan.new fred.add_observer(tax_man) fred.salary=35000.0 ``` 自分でもこのパターンを実装できるが、Rubyの標準ライブラリを使えばどんなオブジェクトでもobservableなオブジェクトにできる。いろんなところで同じメソッドを定義しなくてよくなるのだ。`Observable`モジュールを使って`Employee`クラスをリファクタリングしよう。 ```ruby require 'observer' class Employee include Observable attr_reader :name, :title attr_reader :salary def initialize(name, title, salary) @name = name @title = title @salary = salary end def salary=(new_salary) @salary = new_salary changed notify_observers(self) end end ```
PHP
UTF-8
4,202
2.921875
3
[]
no_license
<?php class MenyNgPlaceWebsiteAlgorithmParser extends NgPlaceWebsiteAlgorithmParser { // VARIABLES private static $REGEX_HOURS_WEEKDAYS = '/Hverdager/i'; private static $REGEX_HOURS_STAURDAY = '/L&#248;rdag/i'; private static $REGEX_HOURS_SUNDAY = '/S&#248;ndag/i'; private static $REGEX_HOURS_HOURS = '/(\d{2}:\d{2}).?-.?(\d{2}:\d{2})/i'; private static $REGEX_HOURS_CLOSED = '/stengt/i'; private static $HTML_REGEX_HOURS = '/pningstider.+?<p>(.+?)<\/p>/ims'; private static $HTML_REGEX_HOURS_GROUP = '/(.+?)\:(.+?)<br \/>/ims'; private static $HTML_REGEX_INFO_PHONE = '/Telefon:.+?<a.+?>(\d+)<\/a>/ims'; private static $HTML_REGEX_INFO_EMAIL = '/Epost:.+?<a.+?>(.+?)<\/a>/ims'; // <p>Hverdager:&nbsp;10:00 - 21:00<br />L&#248;rdag:&nbsp;09:00 - 18:00<br /> S&#248;ndag:&nbsp;stengt<br /> </p> // /VARIABLES // CONSTRUCTOR // /CONSTRUCTOR // FUNCTIONS /** * @see NgPlaceWebsiteAlgorithmParser::getPlaceType() */ protected function getPlaceType() { return GroupPlaceModel::$TYPE_MENY; } /** * @see PlaceWebsiteAlgorithmParser::isAddSinglePlaceToQueue() */ public function isAddSinglePlaceToQueue() { return true; } /** * @see PlaceWebsiteAlgorithmParser::getSinglePlaceUrl() */ public function getSinglePlaceUrl( PlaceModel $place, $url ) { return sprintf( $url, str_replace( array ( " ", "æ", "ø", "å", "Æ", "Ø", "Å" ), array ( "-", "a", "o", "a", "A", "O", "A" ), $place->getName() ) ); } // ... PLACE /** * @see PlaceWebsiteAlgorithmParser::parsePlace() */ public function parsePlace( $html ) { if ( !$this->place ) throw new ParserException( "Place not set" ); // Hours if ( preg_match( self::$HTML_REGEX_HOURS, $html, $hoursMatches ) ) { if ( preg_match_all( self::$HTML_REGEX_HOURS_GROUP, Core::trimWhitespace( $hoursMatches[ 1 ] ), $hoursGroupMatches ) ) { $hours = new HoursPlaceContainer(); for ( $i = 0; $i < count( $hoursGroupMatches ); $i++ ) { $time = null; if ( preg_match( self::$REGEX_HOURS_HOURS, $hoursGroupMatches[ 2 ][ $i ], $hourMatch ) ) $time = array ( $hourMatch[ 1 ], $hourMatch[ 2 ] ); else if ( preg_match( self::$REGEX_HOURS_CLOSED, $hoursGroupMatches[ 2 ][ $i ] ) ) $time = HoursPlaceContainer::CLOSED; if ( preg_match( self::$REGEX_HOURS_WEEKDAYS, $hoursGroupMatches[ 1 ][ $i ] ) && $time ) { $hours->regular[ HoursPlaceContainer::MONDAY ] = $time; $hours->regular[ HoursPlaceContainer::TUESDAY ] = $time; $hours->regular[ HoursPlaceContainer::WEDNESDAY ] = $time; $hours->regular[ HoursPlaceContainer::THURSDAY ] = $time; $hours->regular[ HoursPlaceContainer::FRIDAY ] = $time; } else if ( preg_match( self::$REGEX_HOURS_STAURDAY, $hoursGroupMatches[ 1 ][ $i ] ) && $time ) $hours->regular[ HoursPlaceContainer::SATURDAY ] = $time; else if ( preg_match( self::$REGEX_HOURS_SUNDAY, $hoursGroupMatches[ 1 ][ $i ] ) && $time ) $hours->regular[ HoursPlaceContainer::SUNDAY ] = $time; } $this->place->setHours( $hours ); } } // Info if ( preg_match( self::$HTML_REGEX_INFO_EMAIL, $html, $infoEmail ) ) $this->place->info->email = Core::trimWhitespace( $infoEmail[ 1 ] ); if ( preg_match( self::$HTML_REGEX_INFO_PHONE, $html, $infoPhone ) ) $this->place->info->phone = Core::trimWhitespace( $infoPhone[ 1 ] ); $result = new PlaceAlgorithmResultParser(); $result->getPlaces()->add( $this->place ); return $result; } // ... /PLACE // /FUNCTIONS } ?>
C++
UTF-8
1,407
3.125
3
[]
no_license
#include "move.hpp" Move::Move(int start, int end) : start_(start) , end_(end) { } Move::Move(int start, int end, int eatIdx) : start_(start) , end_(end) { eatIdxs_.push_back(eatIdx); } Move::Move(Move move, int end, int eatIdx) : start_(move.start_) , end_(end) , eatIdxs_(move.eatIdxs_) { eatIdxs_.push_back(eatIdx); } Move::Move(int start, int end, std::vector<int> vEat) : start_(start) , end_(end) , eatIdxs_(vEat) { } int Move::execute(grid_t* grid) const { if(end_ < SEGMENT || end_ >= GRID_SIZE - SEGMENT) grid[end_] = grid[start_] | IS_KING; //Make king if the piece arrives at the other end else grid[end_] = grid[start_]; grid[start_] = EMPTY; //Eat pices for(auto i : eatIdxs_) { grid[i] = EMPTY; } //Return how many pieces were eaten return eatIdxs_.size(); } /* int Move::undo(grid_t* grid) { grid[start_] = grid[end_]; grid[end_] = EMPTY; //Put back pieces for(int i = 0; i < eatIdxs_.size(); i++) { grid[i] == eatPieces_[i]; } eatPieces_.clear(); return eatIdxs_.size(); } */ std::ostream& operator<<(std::ostream& os, const Move& b) { os << "Move: s: " << std::setw(3) << b.start_ << " e: " << std::setw(3) << b.end_ << " eat:"; for(auto idx : b.eatIdxs_) { os << " " << idx; } return os; }
C++
UTF-8
1,720
3.25
3
[]
no_license
#include "pieces.h" Pieces::~Pieces(){LegalMoves.clear();} Pieces::Pieces(Board *theBoard, bool White, Position Location): theBoard{theBoard}, White{White}, Location{Location}, LegalMoves{}, Protected{false}, Pinned{nullptr}, availableMoveCount{0}, hasMoved{false}, enPassant{nullptr}{} bool Pieces::canMove(Position target) const{ for(auto i : this->LegalMoves){ if(i.equals(target)){ return true; } } return false; } bool Pieces::canAttack(Position target) const{ for(auto i : this->LegalMoves){ if(i.equals(target)){ return true; } } return false; } Position Pieces::getPos() const{ return this->Location; } void Pieces::setPos(Position newPos){ this->Location = newPos; } bool Pieces::getMoved() const{ return this->hasMoved; } void Pieces::setMoved(bool move){ this->hasMoved = move; } Pieces* Pieces::getEnPassant() const{ return this->enPassant; } void Pieces::setEnPassant(Pieces* move){ this->enPassant = move; } bool Pieces::isWhite() const{ return this->White; } void Pieces::setProtected(bool val){ this->Protected = val; } void Pieces::setPinned(Pieces* pin){ this->Pinned = pin; } void Pieces::resetProtectedPinned(){ this->Protected = false; this->Pinned = nullptr; } bool Pieces::isProtected() const{ return this->Protected; } Pieces* Pieces::isPinned() const{ return this->Pinned; } int Pieces::getMoveCount() const{ return this->availableMoveCount; } int Pieces::getAttackCount() const{ return this->availableAttackCount; } std::vector<Position> Pieces::getLegalMoves() const{ return this->LegalMoves; }
C#
UTF-8
5,428
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace SlideShow { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } public string Path { get; set; } public bool IsStop { get; set; } private int numImage { get; set; } List<string> ls_Image = new List<string>(); int dem = 0; private void Button1_Click(object sender, EventArgs e) { IsStop = true; using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) { folderBrowserDialog.SelectedPath = AppDomain.CurrentDomain.BaseDirectory; if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { Path = folderBrowserDialog.SelectedPath; string[] directories = Directory.GetFiles(Path); if (directories.Length == 0) { MessageBox.Show("Không có ảnh", "Thông Báo!", MessageBoxButtons.OK); return; } else { foreach (string item in directories) { if (item.Contains(".png")) { ls_Image.Add(item); } } Run(); } } } } private void Run() { if (ls_Image.Count == 0) { MessageBox.Show("Không có ảnh", "Thông Báo!", MessageBoxButtons.OK); } else { numImage = ls_Image.Count; picMain.Image = Image.FromFile(ls_Image[0]); ShowImage(); } } private void ShowImage() { Thread thread = new Thread(() => { while (IsStop) { picMain.Image = Image.FromFile(ls_Image[dem]); pic3.Image = Image.FromFile(ls_Image[dem]); Thread.Sleep(3000); dem++; if (dem == numImage) { dem = 0; } if (dem > 0 && ls_Image.Count > 3) { pic2.Image = Image.FromFile(ls_Image[dem - 1]); } if (dem > 1) { pic1.Image = Image.FromFile(ls_Image[dem - 2]); } if (dem <= ls_Image.Count - 3) { pic4.Image = Image.FromFile(ls_Image[dem + 1]); pic5.Image = Image.FromFile(ls_Image[dem + 2]); } else { pic4.Image = Image.FromFile(ls_Image[0]); pic5.Image = Image.FromFile(ls_Image[1]); } } }); thread.Start(); } private void PictureBox1_Click(object sender, EventArgs e) { } private void Pic3_Click(object sender, EventArgs e) { Image image = pic3.Image; picMain.Image = image; } private void Pic1_Click(object sender, EventArgs e) { Image image = pic1.Image; picMain.Image = image; } private void Pic2_Click(object sender, EventArgs e) { Image image = pic2.Image; picMain.Image = image; } private void Pic4_Click(object sender, EventArgs e) { Image image = pic4.Image; picMain.Image = image; } private void Pic5_Click(object sender, EventArgs e) { Image image = pic5.Image; picMain.Image = image; } private void HscrollBall_Scroll(object sender, ScrollEventArgs e) { if (hscrollBall.Value > 0 && hscrollBall.Value <20) { Image image = pic5.Image; picMain.Image = image; } if (hscrollBall.Value > 20 && hscrollBall.Value < 40) { Image image = pic4.Image; picMain.Image = image; } if (hscrollBall.Value > 40 && hscrollBall.Value < 60) { Image image = pic3.Image; picMain.Image = image; } if (hscrollBall.Value > 60 && hscrollBall.Value < 80) { Image image = pic2.Image; picMain.Image = image; } if (hscrollBall.Value > 80 && hscrollBall.Value < 100) { Image image = pic1.Image; picMain.Image = image; } } private void LoadClick() { } private void Pic3_DragLeave(object sender, EventArgs e) { } } }
Python
UTF-8
11,308
2.640625
3
[]
no_license
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/common/Lib/email/_parseaddr.py __all__ = ['mktime_tz', 'parsedate', 'parsedate_tz', 'quote'] import time, calendar SPACE = ' ' EMPTYSTRING = '' COMMASPACE = ', ' _monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] _timezones = {'UT': 0, 'UTC': 0, 'GMT': 0, 'Z': 0, 'AST': -400, 'ADT': -300, 'EST': -500, 'EDT': -400, 'CST': -600, 'CDT': -500, 'MST': -700, 'MDT': -600, 'PST': -800, 'PDT': -700} def parsedate_tz(data): data = data.split() if data[0].endswith(',') or data[0].lower() in _daynames: del data[0] else: i = data[0].rfind(',') if i >= 0: data[0] = data[0][i + 1:] if len(data) == 3: stuff = data[0].split('-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = s.find('+') if i > 0: data[3:] = [s[:i], s[i + 1:]] else: data.append('') if len(data) < 5: return else: data = data[:5] dd, mm, yy, tm, tz = data mm = mm.lower() if mm not in _monthnames: dd, mm = mm, dd.lower() if mm not in _monthnames: return mm = _monthnames.index(mm) + 1 if mm > 12: mm -= 12 if dd[-1] == ',': dd = dd[:-1] i = yy.find(':') if i > 0: yy, tm = tm, yy if yy[-1] == ',': yy = yy[:-1] if not yy[0].isdigit(): yy, tz = tz, yy if tm[-1] == ',': tm = tm[:-1] tm = tm.split(':') if len(tm) == 2: thh, tmm = tm tss = '0' elif len(tm) == 3: thh, tmm, tss = tm else: return try: yy = int(yy) dd = int(dd) thh = int(thh) tmm = int(tmm) tss = int(tss) except ValueError: return if yy < 100: if yy > 68: yy += 1900 else: yy += 2000 tzoffset = None tz = tz.upper() if tz in _timezones: tzoffset = _timezones[tz] else: try: tzoffset = int(tz) except ValueError: pass if tzoffset: if tzoffset < 0: tzsign = -1 tzoffset = -tzoffset else: tzsign = 1 tzoffset = tzsign * (tzoffset // 100 * 3600 + tzoffset % 100 * 60) return (yy, mm, dd, thh, tmm, tss, 0, 1, -1, tzoffset) def parsedate(data): t = parsedate_tz(data) if isinstance(t, tuple): return t[:9] else: return t def mktime_tz(data): if data[9] is None: return time.mktime(data[:8] + (-1,)) else: t = calendar.timegm(data) return t - data[9] return def quote(str): return str.replace('\\', '\\\\').replace('"', '\\"') class AddrlistClass(): def __init__(self, field): self.specials = '()<>@,:;."[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r\n' self.FWS = self.LWS + self.CR self.atomends = self.specials + self.LWS + self.CR self.phraseends = self.atomends.replace('.', '') self.field = field self.commentlist = [] def gotonext(self): while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': self.pos += 1 if self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) break def getaddrlist(self): result = [] while self.pos < len(self.field): ad = self.getaddress() if ad: result += ad result.append(('', '')) return result def getaddress(self): self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if self.pos >= len(self.field): if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in '.@': self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif self.field[self.pos] == ':': returnlist = [] fieldlen = len(self.field) self.pos += 1 while self.pos < len(self.field): self.gotonext() if self.pos < fieldlen and self.field[self.pos] == ';': self.pos += 1 break returnlist = returnlist + self.getaddress() elif self.field[self.pos] == '<': routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [(SPACE.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] elif plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in self.specials: self.pos += 1 self.gotonext() if self.pos < len(self.field) and self.field[self.pos] == ',': self.pos += 1 return returnlist def getrouteaddr(self): if self.field[self.pos] != '<': return expectroute = False self.pos += 1 self.gotonext() adlist = '' while self.pos < len(self.field): if expectroute: self.getdomain() expectroute = False elif self.field[self.pos] == '>': self.pos += 1 break elif self.field[self.pos] == '@': self.pos += 1 expectroute = True elif self.field[self.pos] == ':': self.pos += 1 else: adlist = self.getaddrspec() self.pos += 1 break self.gotonext() return adlist def getaddrspec(self): aslist = [] self.gotonext() while self.pos < len(self.field): if self.field[self.pos] == '.': aslist.append('.') self.pos += 1 elif self.field[self.pos] == '"': aslist.append('"%s"' % quote(self.getquote())) elif self.field[self.pos] in self.atomends: break else: aslist.append(self.getatom()) self.gotonext() if self.pos >= len(self.field) or self.field[self.pos] != '@': return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() domain = self.getdomain() return EMPTYSTRING if not domain else EMPTYSTRING.join(aslist) + domain def getdomain(self): sdlist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS: self.pos += 1 if self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) if self.field[self.pos] == '[': sdlist.append(self.getdomainliteral()) if self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') if self.field[self.pos] == '@': return EMPTYSTRING if self.field[self.pos] in self.atomends: break sdlist.append(self.getatom()) return EMPTYSTRING.join(sdlist) def getdelimited(self, beginchar, endchars, allowcomments=True): if self.field[self.pos] != beginchar: return '' slist = [''] quote = False self.pos += 1 while self.pos < len(self.field): if quote: slist.append(self.field[self.pos]) quote = False elif self.field[self.pos] in endchars: self.pos += 1 break elif allowcomments and self.field[self.pos] == '(': slist.append(self.getcomment()) continue elif self.field[self.pos] == '\\': quote = True else: slist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(slist) def getquote(self): return self.getdelimited('"', '"\r', False) def getcomment(self): return self.getdelimited('(', ')\r', True) def getdomainliteral(self): return '[%s]' % self.getdelimited('[', ']\r', False) def getatom(self, atomends=None): atomlist = [''] if atomends is None: atomends = self.atomends while self.pos < len(self.field): if self.field[self.pos] in atomends: break else: atomlist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(atomlist) def getphraselist(self): plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 if self.field[self.pos] == '"': plist.append(self.getquote()) if self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) if self.field[self.pos] in self.phraseends: break plist.append(self.getatom(self.phraseends)) return plist class AddressList(AddrlistClass): def __init__(self, field): AddrlistClass.__init__(self, field) if field: self.addresslist = self.getaddrlist() else: self.addresslist = [] def __len__(self): return len(self.addresslist) def __add__(self, other): newaddr = AddressList(None) newaddr.addresslist = self.addresslist[:] for x in other.addresslist: if x not in self.addresslist: newaddr.addresslist.append(x) return newaddr def __iadd__(self, other): for x in other.addresslist: if x not in self.addresslist: self.addresslist.append(x) return self def __sub__(self, other): newaddr = AddressList(None) for x in self.addresslist: if x not in other.addresslist: newaddr.addresslist.append(x) return newaddr def __isub__(self, other): for x in other.addresslist: if x in self.addresslist: self.addresslist.remove(x) return self def __getitem__(self, index): return self.addresslist[index]
Python
UTF-8
1,505
3.8125
4
[]
no_license
''' Online Python Compiler. Code, Compile, Run and Debug python program online. Write your code in this editor and press "Run" button to execute it. ''' class Stack: def __init__(self): self.items = [] self.length = 0 def push(self, val): self.items.append(val) self.length += 1 def pop(self): if self.empty(): return null self.length -= 1 return self.items.pop() def size(self): return self.length def peek(self): if self.empty(): return null return self.items[0] def empty(self): return self.length == 0 priority = {} priority['*'] = 2 priority['/'] = 2 priority['+'] = 1 priority['-'] = 1 def convert(expression): print(convert1(expression.split())) def convert1(exp): postfix = [] op = Stack() for i in exp: if i.isidentifier(): postfix.append(i) else: if not op.empty(): temp = op.peek() while not op.empty() and priority[temp] >= priority[i] and i.isidentifier(): postfix.append(op.pop()) temp = op.peek() op.push(i) while not op.empty(): postfix.append(op.pop()) return postfix convert(input("Enter any Expression:\n"))
Java
UTF-8
470
2.15625
2
[]
no_license
package com.m2i.poe; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TBmardi { // public static void main(String[] args) { // public static void main (String[]args){ // // ArrayList<Integer> 1 = new ArrayList<Integer>(); // l.add(1); // l.add(2); // l.add(3); // l.add(4); // l.add(5); // // System.out.println(l); // // } // } }
PHP
UTF-8
1,510
2.671875
3
[ "MIT" ]
permissive
<?php namespace PHPDataGen\Node; class File extends \PHPDataGen\Node { use \PHPDataGen\DataClassTrait; private const FIELDS = ['namespace' => 'Namespace', 'uses' => 'Uses', 'class' => 'Class']; private $namespace = null; private $uses = []; private $class = null; public function __construct(array $init = []) { $this->_PDG_construct($init); } public function &getNamespace() : ?\PhpParser\Node\Name { return $this->namespace; } protected function validateNamespace($value) : ?\PhpParser\Node\Name { return $value; } public function setNamespace($value) : ?\PhpParser\Node\Name { $oldValue = $this->namespace; $this->namespace = $this->validateNamespace($value); return $oldValue; } public function &getUses() : array { return $this->uses; } protected function validateUses($value) : array { return $value; } public function setUses($value) : array { $oldValue = $this->uses; $this->uses = $this->validateUses($value); return $oldValue; } public function &getClass() : ?\PHPDataGen\Node { return $this->class; } protected function validateClass($value) : ?\PHPDataGen\Node { return $value; } public function setClass($value) : ?\PHPDataGen\Node { $oldValue = $this->class; $this->class = $this->validateClass($value); return $oldValue; } }
SQL
UTF-8
2,000
2.75
3
[]
no_license
--Datos departamentos insert into departamento (nombre) values ('Artigas'); insert into departamento (nombre) values ('Canelones'); insert into departamento (nombre) values ('Cerro Largo'); insert into departamento (nombre) values ('Colonia'); insert into departamento (nombre) values ('Durazno'); insert into departamento (nombre) values ('Flores'); insert into departamento (nombre) values ('Florida'); insert into departamento (nombre) values ('Lavalleja'); insert into departamento (nombre) values ('Maldonado'); insert into departamento (nombre) values ('Montevideo'); insert into departamento (nombre) values ('Paysandú'); insert into departamento (nombre) values ('Río Negro'); insert into departamento (nombre) values ('Rivera'); insert into departamento (nombre) values ('Rocha'); insert into departamento (nombre) values ('Salto'); insert into departamento (nombre) values ('San José'); insert into departamento (nombre) values ('Soriano'); insert into departamento (nombre) values ('Tacuarembó'); insert into departamento (nombre) values ('Treinta y Tres'); --Datos roles insert into rol (id, nombre, descripcion) values (1, 'ROLE_ESTUDIANTE', 'Rol de estudiante'); insert into rol (id, nombre, descripcion) values (2, 'ROLE_PROFESOR', 'Rol de profesor'); --Datos usuarios insert into usuario (login, password) values ('estudiante', 'estudiante'); insert into usuario (login, password) values ('est', 'est'); insert into usuario (login, password) values ('profesor', 'profesor'); insert into usuario (login, password) values ('prof', 'prof'); --Datos roles usuarios insert into usuario_roles (usuario_id, roles_id) values (1, 1); insert into usuario_roles (usuario_id, roles_id) values (2, 1); insert into usuario_roles (usuario_id, roles_id) values (3, 2); insert into usuario_roles (usuario_id, roles_id) values (4, 2); --Datos estudiante insert into estudiante (direccion, email, nombre, telefono, departamento_id) values ('Cerro Largo', 'estudiante@class.com', 'Adan C.', '092123123', 10);
Markdown
UTF-8
1,378
2.6875
3
[]
no_license
How to get started =========== A spawned cloud instance should close itself at 6:30PM everyday, this is for your own sake to stop you burning out! Any vagrant up executions past that time require a 'sudo shutdown -H now' inside the instance before you finish your session. ^^^ This is your first given responsibility. - [ ] 'Fill in required secrets in Vagrantfile at the top of the file' - [ ] 'vagrant up' - [ ] 'vagrant ssh' - [ ] 'vagrant rsync-auto' (In a shell outside the container, this watches and writes file locally to the cloud dev environment) - [ ] '/vagrant/./provision.sh' inside the instance (THEN exit and vagrant ssh again to use docker without sudo!) - [ ] 'cd /vagrant; docker-compose run -e host='public-dns goes here' --service-ports web bash' (Inside the instance in your vagrant ssh session) Start coding! ## Pros and Cons === TODO ## Alternative local laptop dev environment scaffold - [ ] 'git clone this repo' - [ ] [Install docker toolbox](https://docs.docker.com/mac/step_one/) - [ ] 'docker-machine create --driver virtualbox default' - [ ] 'eval "$(docker-machine env default)" - [ ] 'cd /ecommerce-scaffold; docker-compose run web npm install' - [ ] Edit your etc/hosts file to map 'docker-machine ip default' to localhost - [ ] 'docker-compose run --service-ports web bash' or 'docker-compose run --service-ports -d web' Start coding!
Markdown
UTF-8
10,139
2.734375
3
[ "Apache-2.0" ]
permissive
--- layout: post101 title: Synchronous Replication categories: XAP101ADM parent: replication.html weight: 200 --- {% summary %} {% endsummary %} In a synchronous replication, the client receives acknowledgement for any replicated operations only after all the space instances in the replication group have performed the operation. This topology is most fitting for the Primary backup topology, where the application needs a guarantee that during a failure of the primary space instance, no already executed operations or saved data will be lost. As a result, this replication type has the highest performance penalty because each operation is not completed until all the target space instances in the group have received and acknowledge the operation. # How to Turn on Synchronous Replication? In general you should have the `cluster-config.groups.group.repl-policy.replication-mode` property set to `sync`. See below example: {% highlight xml %} <os-core:embedded-space id="space" name="mySpace"> <os-core:properties> <props> <prop key="cluster-config.groups.group.repl-policy.replication-mode">sync</prop> </props> </os-core:properties> </os-core:embedded-space> {% endhighlight %} # When to Use Synchronous Replication Synchronous replication is most beneficial in the following scenarios: - Whenever an application must replicate highly sensitive, mission critical data as soon as it arrives at the source space. - Whenever any space operation must be duplicated with 100% data integrity to the target space. # How Synchronous Replication Works 1. A destructive space operation is called. 1. The source space: 1. Performs the operation. 1. Replicates the operation to all the targets and wait for acknowledgement from the targets. 1. The target space receives a replication packet: 1. Makes sure parallel operations are processed in the correct order. 1. Once the replication packet is processed, the target space sends a confirmation to the source space. 1. The source space sends acknowledgement to the client. ![replication-matrix-IMG503.jpg](/attachment_files/replication-matrix-IMG503.jpg) # Handling Disconnections and Errors When a replication target space instance is unavailable (disconnection) or some error occurred during the processing of the replication data at the target, a synchronous replication channel (between the source and the specific target space instance) moves to asynchronous operating state. During that time, all the replicated operations are accumulated at a backlog (named replication redolog) and a special worker attempts to replicate the items from the redolog to the target space instance in batches. This worker will succeed sending the accumulated replication data once the connection is re-established or the error is resolved at the target and once the redolog is replicated, the channel will return to synchronous operation state. During the asynchronous operating state time period, the client will receive acknowledgements for the operations without them being replicated, thus not halting the cluster when a replication target is down. {% info %} The current operating mode of a replication channel can be retrieved via the [Administration and Monitoring API]({%currentjavaurl%}/administration-and-monitoring-api.html) by getting the [Space Instance](http://www.gigaspaces.com/docs/JavaDoc{% currentversion %}/org/openspaces/admin/space/SpaceInstance.html) [Replication Statistics](http://www.gigaspaces.com/docs/JavaDoc{% currentversion %}/com/j_spaces/core/filters/ReplicationStatistics.html) of the specific replication channel and calling the following getter [OutgoingChannel.getOperatingMode()](http://www.gigaspaces.com/docs/JavaDoc{% currentversion %}/com/j_spaces/core/filters/ReplicationStatistics.OutgoingChannel.html#getOperatingMode()) {% endinfo %} # Behavior During Recovery In the previous scenario, a target space instance might become unavailable because it has been restarted or relocated due to various reason (failure, manual/automatic relocation). In the default settings, when that target space instance will restart, it will perform a recovery from a source space instance. In primary backup topology it will be the primary space instance, in active active topology it can be any space instance. During the recovery process the replication channel will operate in asynchronous state until the redolog is replicated as in the above scenario. The target space instance will not be available until the source channel operating state was restored to synchronous, thus making sure that once the target space is available and visible, a backup or other space instance target is fully synchronized with its source. # Throttling When a synchronous replication channel is operating in asynchronous state, a special throttling takes place that will throttle the replicated operation rate to make sure two things: 1. Once the target is reachable or the error is resolved, the redolog increase rate will be lower than the asynchronous replication completion. That is to make sure the asynchronous state will end at a finite time. 1. In order to try and maintain a consistent throughput so that the application will not gain a dramatic performance boost because the replication is disconnected, and have more operation at risk. This throttling can be configured with the following parameters: {: .table .table-bordered .table-condensed} | Property | Description | Default Value | |:---------|:------------|:--------------| | throttle-when-inactive | Boolean value. Set to `true` if you want to throttle replicated operations when the channel is in-active (disconnection) | `true` in primary backup `false` in full sync replicated | | <nobr>max-throttle-tp-when-inactive</nobr> | Integer value. If the above is true, this will specify the maximum operations per second the throttle will maintain when the channel is in-active (disconnection), if the last measured throughput when the channel was active was higher than that, the measured throughput will be used instead. | 50,000 operations/second | {%warning%} Prefix the property with 'cluster-config.groups.group.repl-policy.sync-replication. {%endwarning%} To change the default replication settings you should modify the space properties when deployed. You may set these properties via the pu.xml or programmatically. Here is an example how you can set the replication parameters when using the pu.xml: {% highlight xml %} <os-core:embedded-space id="space" name="mySpace"> <os-core:properties> <props> <prop key="cluster-config.groups.group.repl-policy.sync-replication.throttle-when-inactive">false</prop> </props> </os-core:properties> </os-core:embedded-space> {% endhighlight %} ## Asynchronous Operating State Related Configuration While the replication channel is operating at asynchronous state due to the reasons mentioned above, the worker that sends the data from the redolog asynchronously is affected by the following configuration (which also relates to asynchronous replication): {: .table .table-bordered .table-condensed} | Property | Description | Default Value | |:---------|:------------|:--------------| | repl-chunk-size | Number of packets that are replicated as a single chuck each time. | 500 | | <nobr>repl-interval-millis</nobr> | Time (in milliseconds) to wait from last replication iteration if there are no more packets to replicate (while disconnected) or if the last iteration was not successful due to error | 3000 \[ms\] | {%warning%} Prefix the property with 'cluster-config.groups.group.repl-policy.async-replication.` {%endwarning%} ## Splitting Replication of Large Batches into Smaller Batches When performing batch operations (`writeMultiple`, `takeMultiple`, `clear`), using a synchronous replication mode , the actual data (space objects/UID) is replicated to the target spaces in batches during the single space operation. This is done in order to avoid to issues, one of them is to run out of memory due to all the data that is generated in the redolog for the replication or cause the redolog capacity limitation being breached. For example, when performing the take (clear) operation, you don't necessarily know how many space objects exist in the space, and all of these need to be removed. Therefore, these operations are split into several chunks, thus providing better memory usage, stability, and scalability. Splitting large batches into chunks is defined using the `cluster-config.groups.group.repl-policy.sync-replication.multiple-opers-chunk-size` parameter. This parameter default value is 10000. This means that by default the operation is performed using chunks of 10000 objects each. To split the replication activity into smaller chunks, you can do so by overriding this property, for instance, using the pu configuration file. {%accordion id=acc1%} {%accord title=Java ... pu.xml | parent=acc1%} {% highlight xml %} <os-core:embedded-space id="space" name="mySpace"> <os-core:properties> <props> <prop key="cluster-config.groups.group.repl-policy.sync-replication.multiple-opers-chunk-size">5000</prop> </props> </os-core:properties> </os-core:embedded-space> {% endhighlight %} {%endaccord%} {%accord title=.NET ... pu.config | parent=acc1%} {% highlight xml %} <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="GigaSpaces" type="GigaSpaces.Core.Configuration.GigaSpacesCoreConfiguration, GigaSpaces.Core"/> </configSections> <GigaSpaces> <SystemProperties> <add Name="cluster-config.groups.group.repl-policy.sync-replication.multiple-opers-chunk-size" Value="5000"/> </SystemProperties> </GigaSpaces> </configuration> {% endhighlight %} {%endaccord%} {%endaccordion%} {% note %} Splitting large batches into smaller chunks is not supported for transactional operations. {%endnote%}
Java
UTF-8
4,803
2.390625
2
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
/* * Tencent is pleased to support the open source community by making Angel available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.tencent.angel.worker.storage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; /** * The type Memory and Disk storage. * <p> * The values will store on memory is available,and then on disk * </p> * * @param <VALUE> the type parameter */ public class MemoryAndDiskDataBlock<VALUE> extends DataBlock<VALUE> { private static final Log LOG = LogFactory.getLog(MemoryAndDiskDataBlock.class); private MemoryDataBlock<VALUE> memoryStorage; private DiskDataBlock<VALUE> diskStorage; private boolean memoryWriteInUse; private boolean memoryReadInUse; private final int memoryCheckInterval; private int memoryCheckCounter; private final int taskIndex; public MemoryAndDiskDataBlock(int taskIndex) { super(); this.taskIndex = taskIndex; memoryStorage = new MemoryDataBlock<VALUE>(-1); diskStorage = null; memoryReadInUse = true; memoryWriteInUse = true; memoryCheckInterval = 1000; memoryCheckCounter = 0; } @Override public VALUE read() throws IOException { VALUE value = null; readIndex++; if (memoryReadInUse) { value = memoryStorage.read(); if (value != null) { return value; } else { if (diskStorage == null) { return null; } memoryReadInUse = false; } } return diskStorage.read(); } @Override protected boolean hasNext() throws IOException { if (readIndex < memoryStorage.writeIndex) { return true; } else { if (diskStorage != null) { memoryReadInUse = false; return diskStorage.hasNext(); } else { return false; } } } @Override public VALUE get(int index) throws IOException { if (index < memoryStorage.writeIndex) { return memoryStorage.get(index); } else { throw new IOException("dose not support this get random operation for DiskDataBlock"); } } @Override public void put(VALUE value) throws IOException { if (memoryWriteInUse) { memoryStorage.put(value); writeIndex++; memoryCheckCounter++; if (memoryCheckCounter == memoryCheckInterval) { if (memoryStorage.checkIsOverMaxMemoryUsed()) { diskStorage = new DiskDataBlock<VALUE>(taskIndex); diskStorage.registerType(valueClass); memoryWriteInUse = false; } memoryCheckCounter = 0; } } else { diskStorage.put(value); writeIndex++; } } @Override public void resetReadIndex() throws IOException { readIndex = 0; if (memoryReadInUse) { memoryStorage.resetReadIndex(); } else { memoryReadInUse = true; memoryStorage.resetReadIndex(); diskStorage.resetReadIndex(); } } @Override public void clean() throws IOException { memoryStorage.clean(); if (diskStorage != null) { diskStorage.clean(); } memoryReadInUse = true; memoryWriteInUse = true; memoryCheckCounter = 0; readIndex = writeIndex = 0; } @Override public void shuffle() throws IOException { memoryStorage.shuffle(); } @Override public void flush() throws IOException { if (memoryWriteInUse) { memoryStorage.flush(); } else { diskStorage.flush(); } } @Override public DataBlock<VALUE> slice(int startIndex, int length) throws IOException { if (startIndex + length <= memoryStorage.writeIndex) { return memoryStorage.slice(startIndex, length); } else { throw new IOException("does not support this slice operation for DiskDataBlock"); } } @Override public String toString() { return "MemoryAndDiskDataBlock [memoryStorage=" + memoryStorage + ", diskStorage=" + diskStorage + ", memoryWriteInUse=" + memoryWriteInUse + ", memoryReadInUse=" + memoryReadInUse + ", memoryCheckInterval=" + memoryCheckInterval + ", memoryCheckCounter=" + memoryCheckCounter + ", taskIndex=" + taskIndex + ", toString()=" + super.toString() + "]"; } }
Markdown
UTF-8
3,619
2.875
3
[]
no_license
# Текст 49 असक्तबुद्धिः सर्वत्र जितात्मा विगतस्पृहः । नैष्कर्म्यसिद्धिं परमां संन्यासेनाधिगच्छति ॥४९॥ асакта-буддхит̣ сарватра джита̄тма̄ вигата-спр̣хат̣ наишкармйа-сиддхим̇ парама̄м̇ саннйа̄сена̄дхигаччхати _асакта-буддхит̣_ — тот, чей разум свободен от привязанностей; _сарватра_ — везде; _джита-а̄тма̄_ — тот, чей ум побежден; _вигата- спр̣хат̣_ — не имеющий материальных желаний; _наишкармйа- сиддхим_ — совершенство, состоящее в отсутствии последствий деятельности; _парама̄м_ — высшее; _саннйа̄сена_ — отречением от мира; _адхигаччхати_ — обретает. ### Перевод: **Тот, кто обуздал ум и чувства, кто избавился от привязанностей и стремления к материальным удовольствиям, может, отрекшись от мира, достичь высшей ступени совершенства — свободы от кармы.** ### Комментарий: Поистине отречься от мира — значит всегда помнить о том, что мы являемся частицами Верховного Господа и потому не имеем права наслаждаться результатами своего труда. Поскольку мы частицы Всевышнего, плоды нашей деятельности предназначены для того, чтобы доставлять наслаждение Господу. Это настоящее сознание Кришны. Человек, действующий в сознании Кришны, — истинный _санньяси,_ отрекшийся от мира. Действуя в подобном умонастроении, он обретает удовлетворение, ибо все, что он делает, он делает ради Верховного Господа. Поэтому такой человек не привязан ни к чему материальному; он не ищет других удовольствий, помимо духовного блаженства, которое приносит ему служение Господу. Считается, что _санньяси_ свободен от всех последствий своей прошлой деятельности, однако тот, кто действует в сознании Кришны, естественным образом достигает этого совершенства, даже не давая так называемого обета отречения. Такое состояние ума называют _йога̄рӯд̣ха,_ совершенством _йоги_. Аналогичное утверждение есть в третьей главе: _йас тв а̄тма-ратир эва сйа̄т_. Тому, кто черпает удовлетворение в самом себе, не нужно бояться никаких последствий своих поступков.
SQL
UTF-8
1,008
4.375
4
[]
no_license
-- Q1 SELECT CASE WHEN COUNT(*) = (SELECT COUNT(*) FROM tbl_A) AND COUNT(*) = (SELECT COUNT(*) FROM tbl_B) THEN '相等' ELSE '不相等' END AS result FROM (SELECT * FROM tbl_A UNION SELECT * FROM tbl_B) TMP; -- Q2 SELECT DISTINCT emp FROM EmpSkills ES1 WHERE NOT EXISTS (SELECT skill FROM Skills EXCEPT SELECT skill FROM EmpSkills ES2 WHERE ES1.emp = ES2.emp) AND NOT EXISTS (SELECT skill FROM EmpSkills ES3 WHERE ES1.emp = ES3.emp EXCEPT SELECT skill FROM Skills); SELECT emp FROM EmpSkills ES1 WHERE NOT EXISTS (SELECT skill FROM Skills EXCEPT SELECT skill FROM EmpSkills ES2 WHERE ES1.emp = ES2.emp) GROUP BY emp HAVING COUNT(*) = (SELECT COUNT(*) FROM Skills);
C++
UTF-8
454
3.578125
4
[]
no_license
// Book: C++ Primer Plus // Chapter: 5 // Exercise: 2 #include <iostream> #include <array> const unsigned int arraySize = 101; int main(void) { std::array<long double, arraySize> factorials {{1.0, 1.0, 0.0}}; for (unsigned int i = 2; i < arraySize; ++i) { factorials.at(i) = i * factorials.at(i - 1); } for (unsigned int i = 0; i < arraySize; ++i) { std::cout << i << "! = " << factorials[i] << std::endl; } return 0; }
C#
UTF-8
2,182
2.546875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using System; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; using System.IO; public class SavedProgression : MonoBehaviour { private string filePath = ""; public Setting setting; private Dictionary<string, bool []> levelComplete; private string GetFilePath() { if (filePath.CompareTo("") == 0) { filePath = Application.persistentDataPath + "/levelProg.dat"; } return filePath; } public void Save() { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.OpenWrite(GetFilePath()); SaveData data = new SaveData(); data.setting = this.setting; data.levelComplete = this.levelComplete; bf.Serialize(file, data); file.Close(); } public void load() { if (File.Exists(GetFilePath())) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.OpenRead(GetFilePath()); SaveData data = (SaveData)bf.Deserialize(file); file.Close(); this.setting = data.setting; this.levelComplete = data.levelComplete; } else { this.setting = new Setting(); this.levelComplete = new Dictionary<string, bool[]>(); } } public void LevelCompleted(LevelWorld world, int levelNumber){ if (!levelComplete.ContainsKey(world.getKey())) { levelComplete.Add(world.getKey(), new bool[world.levelCount]); } levelComplete[world.getKey()][levelNumber] = true; } public bool IsLevelCompleted(LevelWorld world, int levelNumber) { if (levelComplete.ContainsKey(world.getKey())) { return levelComplete[world.getKey()][levelNumber]; } return false; } } [Serializable] class SaveData { public Setting setting; public Dictionary<string, bool []> levelComplete; } [Serializable] public class Setting { public float volume; public Setting() { volume = 1; } }
C++
UTF-8
3,047
3.625
4
[]
no_license
// 21. Modify the program from exercise 19 so that when you enter an integer, the program will output all the names with // that score or score not found. #include "std_lib_facilities.h" #include <string> bool is_int(string str, int base = 0) { // if base == 0, base is auto-detected size_t pos = 0 ; try { // http://en.cppreference.com/w/cpp/string/basic_string/stol std::stoi(str, std::addressof(pos), base); return pos == str.size(); // true if the entire string was consumed } catch (const std::exception&) { return false; } } int main(){ vector<string> names; vector<int> scores; vector<string> entered_twice; string name = ""; int score = 0; bool flag = false; int score_print = 0; string name_print = ""; cout << "Введите набор пар, состоящих из имени и значения (прекращение ввода NoName 0): " << endl; while (cin >> name && name != "NoName" && cin >> score && score != 0) { names.push_back(name); scores.push_back(score); } for (size_t i = 0; i < names.size(); i++) { for (size_t j = 0; j < names.size(); j++) { if (i != j && names[i] == names[j]) { // skip when it finds itself // check if names[i] is already on the list int m = 0; for (size_t k = 0; k < entered_twice.size(); k++) { if (entered_twice[k] == names[i]) { m++; cout << "ОШИБКА! Имя " << entered_twice[k] << " введено дважды." << endl; exit(0); } } if (m == 0) entered_twice.push_back(names[i]); } } } cout << "Введите имя или количество баллов: " << endl; while (cin.get() != '\n') continue; cin >> name; if (!is_int(name, 10)) { // Not an integer string(score) = name; for (size_t index = 0; index < names.size() && index < scores.size(); index++) { if (names[index] == name) { flag = true; score_print = scores[index]; } } if (flag == true) cout << "Количество баллов: " << score_print << endl; else cout << "Имя не найдено" << endl; } else { cout << "Имена всех студентов, получивших указанное количество баллов: " << endl; for (size_t index = 0; index < names.size() && index < scores.size(); index++) { if (scores[index] == std::stoi(name)) { flag = true; cout << (name_print = names[index]) << endl; } } if (flag == true) exit(0); else cout << "Баллы не найдены" << endl; } return 0; }
Java
UTF-8
186
1.679688
2
[]
no_license
package cc.messcat.service.system; import cc.messcat.vo.AdvertisementVo; public interface AdvertisementManagerDao { public abstract AdvertisementVo getAdvertisement(int paramInt); }
C#
UTF-8
2,146
3.296875
3
[]
no_license
using System; namespace estruturasDeDados.estruturas { public class ListaDupla { Posicao cabeça; int tamanho = 0; private void checaLista(int posicao) { if (this.tamanho < posicao) { throw new InvalidOperationException("Posicao não disponivel para inserção"); } } // percorre a lista até o elemento anterior a posição private Posicao percorreLista(int posicao) { Posicao aux = cabeça; for (int i = 0; i < posicao - 1; ++i) { aux = aux.proximo; } return aux; } public void adiciona(int valor, int posicao) { checaLista(posicao); Posicao no = new Posicao(valor, null, null); if (posicao == 0) { if (cabeça != null) { cabeça.anterior = no; } no.proximo = cabeça; cabeça = no; } else { Posicao aux = percorreLista(posicao); no.proximo = aux.proximo; no.anterior = aux; aux.proximo = no; if (posicao < tamanho) { no.proximo.anterior = no; } } ++tamanho; } public void removePos(int posicao) { checaLista(posicao); if (posicao == 0) { cabeça = cabeça.proximo; cabeça.anterior = null; } else { Posicao aux = percorreLista(posicao); aux.proximo = aux.proximo.proximo; aux.proximo.anterior = aux; } --tamanho; } public void percorreLista() { Posicao aux = cabeça; for (int i = 0; i < tamanho; ++i) { Console.WriteLine(aux.valor); aux = aux.proximo; } } } }
PHP
UTF-8
4,219
2.75
3
[]
no_license
<?php namespace autoPushWebsite; include_once "Db.php"; include_once "Helper.php"; use swoole_process; class Robot { //CPU核心数目 public $workerMaxNum = 32; public $works = []; public $masterPid; public $urls = []; public $engines = []; public $engineIndex = 0; //构造函数 public function __construct() { try { Db::$config['spider'] = [ 'server' => '127.0.0.1', 'port' => '3306', 'username' => 'root', 'password' => '296b1654c32ceb03', // 'password' => 'newlife', 'database_name' => 'spider', 'database_type' => 'mysql', 'charset' => 'utf8', ]; $this->urls = Db::instance('spider')->select("urls", ["url"]); $this->engines = Db::instance('spider')->select("engines", ["engine"]); $this->masterPid = posix_getpid(); echo "主线程启动: Pid " . $this->masterPid . PHP_EOL; $this->run(); $this->processWait(); } catch (\Exception $e) { die('ALL ERROR: ' . $e->getMessage()); } } //运行 public function run() { for ($i = 0; $i < $this->workerMaxNum; $i++) { $this->createProcess(); } } public function createProcess() { $engineIndex = $this->engineIndex; $this->engineIndex += 1; $process = new swoole_process(function (swoole_process $worker) use ($engineIndex) { for ($j = 0; $j < 16000; $j++) { $this->checkMasterPid($worker); } $this->getStatus($this->engines[$engineIndex], $engineIndex); //echo "engineIndex:" . $engineIndex . PHP_EOL; }, false, false); $pid = $process->start(); //echo "worker pid:" . $pid . PHP_EOL; $this->works[$pid] = $pid; return $pid; } public function getStatus($engine, $engineIndex) { if ($engineIndex >= count($this->engines)) { // echo "engines max" . PHP_EOL; return; } foreach ($this->urls as $value) { $ch = curl_init($engine["engine"] . $value["url"]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000); curl_setopt($ch, CURLOPT_USERAGENT, Helper::randUserAgent("pc")); curl_exec($ch); $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($statusCode != 200) { echo $statusCode . ":" . $engine["engine"] . $value["url"]; } curl_close($ch); } echo $engine["engine"] . " 搜索引擎处理结束" . PHP_EOL; return; } public function processWait() { while (1) { if (count($this->works)) { $ret = swoole_process::wait(); if ($ret) { $this->rebootProcess($ret); } } else { break; } } } public function rebootProcess($ret) { $pid = $ret['pid']; //echo "rb pid:" . $pid . PHP_EOL; $index = in_array($pid, $this->works); if ($index) { unset($this->works[$pid]); $pid = intval($pid); if ($this->engineIndex < count($this->engines)) { $new_pid = $this->createProcess($pid); //echo "rebootProcess: {$pid}={$new_pid} Done\n"; } else { //echo "rb engines max,engineIndex:" . $this->engineIndex . ",engines count:" . count($this->engines) . PHP_EOL; } return; } elseif ($pid == $this->masterPid) { return; } throw new \Exception('rebootProcess Error: no pid'); } //主线程退出,自己跟着退出 public function checkMasterPid(&$worker) { if (!swoole_process::kill($this->masterPid, 0)) { $worker->exit(); echo "Master process exited, I [{$worker['pid']}] also quit\n"; sleep(1); } } } $m = new Robot(); $m->run();
Python
UTF-8
332
2.546875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import web def jsonify(*args, **kwargs): """Dumps input arguments into a JSON object. Note that the 'Content-Type' header is automatically set to JSON. """ web.header('Content-Type', 'application/json') return json.dumps(dict(*args, **kwargs))
Markdown
UTF-8
1,138
3.21875
3
[]
no_license
# ***\#aggressive*** adj 英音 ə'ɡresɪv 英音 <audio src="./media/aggressive-B.aac" controls="controls"></audio> 美音 ə'ɡresɪv 美音 <audio src="./media/aggressive.aac" controls="controls"></audio> | 词频 3 | 口语 1 | 阅读 2 | 英文释义 --- ### 1.*高义频:* **好斗的;侵略性的;攻击性的:** > aggressive behaviour > 攻击性行为 > Every culture has developed a formal way to greet strangers, to show them we are not aggressive. > 所有文化都形成了一种向陌生人打招呼的礼节,以表明自己是友好的。 (外研④ – 3) <audio src="./media/1-aggressive.aac" controls="controls"></audio> ### 2.*高义频:* **有进取心的;有冲劲的:** > A good salesman has to be aggressive. > 好的推销员要有股闯劲。 <audio src="./media/2-aggressive.aac" controls="controls"></audio> 真题解析 --- 1. Some people maintain that watching violence on TV is one of the major causes of ________ behaviour and crime in society. (2008 上海) A.childish B.artificial C.aggressive D.heroic 答案: 1. C
Java
UTF-8
1,745
2.453125
2
[]
no_license
package io.egen.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import io.egen.entity.Customer; import io.egen.exception.CustomerAlreadyExistsException; import io.egen.exception.CustomerNotFoundException; import io.egen.repository.CustomerRespository; @Service public class CustomerServiceImpl implements CustomerService{ @Autowired private CustomerRespository customerRepository; @Override public Customer findCustomer(String id) { return customerRepository.findCustomer(id); } @Override public List<Customer> findAllCustomers() { return customerRepository.findAllCustomers(); } @Override @Transactional public Customer createCustomer(Customer customer) { Customer existing = customerRepository.findCustomerByEmail(customer.getEmailId()); if(existing != null) throw new CustomerAlreadyExistsException("Customer with Email ID:" + existing.getEmailId() + " already exists"); return customerRepository.createCustomer(customer); } @Override @Transactional public Customer updateCustomer(Customer customer) { Customer existing = customerRepository.findCustomer(customer.getId()); if(existing != null) return customerRepository.updateCustomer(customer); throw new CustomerNotFoundException("Customer with id:" + customer.getId() + " not found"); } @Override @Transactional public Customer deleteCustomer(String id) { Customer existing = customerRepository.findCustomer(id); if(existing != null) return customerRepository.deleteCustomer(existing); throw new CustomerNotFoundException("Customer with id:" + id + " not found"); } }
Go
UTF-8
374
2.671875
3
[]
no_license
package database import ( "database/sql" "fmt" "github.com/go-sql-driver/mysql" ) var DB *sql.DB func Connect() { cfg := mysql.Config{ User: "debian-sys-maint", Passwd: "YZkKRHnDn0I8XsvK", Net: "tcp", DBName: "test", } db, err := sql.Open("mysql", cfg.FormatDSN()) DB = db fmt.Println("Database connected") if err != nil { panic(err.Error()) } }
Python
UTF-8
7,712
2.90625
3
[]
no_license
### EDF --- An Autograd Engine for instruction ## (based on joint discussions with David McAllester) import numpy as np from numpy import newaxis # Global list of different kinds of components ops = [] params = [] values = [] # Global forward def Forward(): for c in ops: c.forward() # Global backward def Backward(loss): for c in ops: c.grad = np.zeros_like(c.top) for c in params: c.grad = np.zeros_like(c.top) loss.grad = np.ones_like(loss.top) for c in ops[::-1]: c.backward() # SGD def SGD(lr): for p in params: p.top = p.top - lr*p.grad ## Fill this out def init_momentum(): for x in params: x.velocity = 0 ## Fill this out def momentum(lr,mom=0.9): for x in params: x.velocity = mom * x.velocity + lr * x.grad x.top -= x.velocity ###################### Different kinds of nodes # Values (Inputs) class Value: def __init__(self): values.append(self) def set(self,value): self.top = np.float32(value).copy() # Parameters (Weights we want to learn) class Param: def __init__(self): params.append(self) def set(self,value): self.top = np.float32(value).copy() ### Operations # Add layer (x + y) where y is same shape as x or is 1-D class add: def __init__(self,x,y): ops.append(self) self.x = x self.y = y def forward(self): self.top = self.x.top + self.y.top def backward(self): if self.x in ops or self.x in params: self.x.grad = self.x.grad + self.grad if self.y in ops or self.y in params: if len(self.y.top.shape) < len(self.grad.shape): ygrad = np.sum(self.grad,axis=tuple(range(len(self.grad.shape)-1))) else: ygrad= self.grad self.y.grad = self.y.grad + ygrad # Matrix multiply (fully-connected layer) class matmul: def __init__(self,x,y): ops.append(self) self.x = x self.y = y def forward(self): self.top = np.matmul(self.x.top,self.y.top) def backward(self): if self.x in ops or self.x in params: self.x.grad = self.x.grad + np.matmul(self.y.top,self.grad.T).T if self.y in ops or self.y in params: self.y.grad = self.y.grad + np.matmul(self.x.top.T,self.grad) # Rectified Linear Unit Activation class RELU: def __init__(self,x): ops.append(self) self.x = x def forward(self): self.top = np.maximum(self.x.top,0) def backward(self): if self.x in ops or self.x in params: self.x.grad = self.x.grad + self.grad * (self.top > 0) # Reduce to mean class mean: def __init__(self,x): ops.append(self) self.x = x def forward(self): self.top = np.mean(self.x.top) def backward(self): if self.x in ops or self.x in params: self.x.grad = self.x.grad + self.grad*np.ones_like(self.x.top) / np.float32(np.prod(self.x.top.shape)) # Soft-max + Loss (per-row / training example) class smaxloss: def __init__(self,pred,gt): ops.append(self) self.x = pred self.y = gt def forward(self): y = self.x.top y = y - np.amax(y,axis=1,keepdims=True) yE = np.exp(y) yS = np.sum(yE,axis=1,keepdims=True) y = y - np.log(yS); yE = yE / yS truey = np.int64(self.y.top) self.top = -y[range(len(truey)),truey] self.save = yE def backward(self): if self.x in ops or self.x in params: truey = np.int64(self.y.top) self.save[range(len(truey)),truey] = self.save[range(len(truey)),truey] - 1. self.x.grad = self.x.grad + np.expand_dims(self.grad,-1)*self.save # No backprop to labels! # Compute accuracy (for display, not differentiable) class accuracy: def __init__(self,pred,gt): ops.append(self) self.x = pred self.y = gt def forward(self): truey = np.int64(self.y.top) self.top = np.float32(np.argmax(self.x.top,axis=1)==truey) def backward(self): pass # Downsample by 2 class down2: def __init__(self,x): ops.append(self) self.x = x def forward(self): self.top = self.x.top[:,::2,::2,:] def backward(self): if self.x in ops or self.x in params: grd = np.zeros_like(self.x.top) grd[:,::2,::2,:] = self.grad self.x.grad = self.x.grad + grd # Flatten (conv to fc) class flatten: def __init__(self,x): ops.append(self) self.x = x def forward(self): self.top = np.reshape(self.x.top,[self.x.top.shape[0],-1]) def backward(self): if self.x in ops or self.x in params: self.x.grad = self.x.grad + np.reshape(self.grad,self.x.top.shape) # Convolution Layer ## Fill this out class conv2: def __init__(self,x,k): ops.append(self) self.x = x self.k = k def forward(self): img = self.x.top knl = self.k.top b = img.shape[0] y = img.shape[1] x = img.shape[2] c1 = img.shape[3] ky = knl.shape[0] kx = knl.shape[1] c2 = knl.shape[3] g = np.zeros((b,y,x,c2)) for Ky in range(ky): for Kx in range(kx): rolled = np.roll(img, (0, -Ky, -Kx, 0)) rolled_newDim = rolled[:,:,:,:,newaxis] f = np.concatenate([rolled_newDim for x in range(c2)], axis=4) h = knl[Ky, Kx, :, :].reshape(1,1,1,c1,c2) g += np.sum(f * h, axis=3) self.top = g[:, :-ky+1, :-kx+1, :] def backward(self): img = self.x.top knl = self.k.top grad = self.grad b = img.shape[0] y = img.shape[1] x = img.shape[2] c1 = img.shape[3] ky = knl.shape[0] kx = knl.shape[1] c2 = knl.shape[3] if self.x in ops or self.x in params: kFlip = np.flip(knl, (0, 1)) gImg = np.zeros((b, ky+y+1, kx+x+1, c1)) padgrad = np.pad(grad, ((0,0), (ky, ky), (kx,kx), (0,0)), mode="constant") for Ky in range(min(ky, y)): for Kx in range(min(kx, x)): rolled = np.roll(padgrad, (0, -Ky, -Kx, 0)) rolled_newDim = rolled[:, :, :, :, newaxis] f = np.concatenate([rolled_newDim for x in range(c1)], axis=4) fSwap = np.swapaxes(f, 3,4) k = np.repeat(np.expand_dims(kFlip[Ky,Kx,:,:].reshape(1,1,c1,c2), axis=0), b, axis=0) gImg += np.sum(fSwap * k, axis=4) self.x.grad = gImg[:, ky:-ky+1, kx:-kx+1, :] if self.k in ops or self.k in params: gKnl = np.zeros((ky,kx,c1,c2)) dim1 = y-ky+1 dim2 = x-kx+1 for Ky in range(min(ky,y)): for Kx in range(min(kx,x)): rolled = np.roll(img, (0, -Ky, -Kx, 0)) rolled_sliced = rolled[:, :dim1, :dim2, :] rs_newDim = rolled_sliced[:,:,:,:, newaxis] f = np.concatenate([rs_newDim for x in range(c2)], axis=4) grad_newDim = grad[:,:,:,:,newaxis] fp = np.concatenate([grad_newDim for x in range(c1)], axis=4) fpSwap = np.swapaxes(fp, 3, 4) reduce = np.sum(f * fpSwap, axis=0) reduce = np.sum(reduce, axis=0) gKnl[Ky, Kx, :, :] = np.sum(reduce, axis=0) self.k.grad = gKnl
Markdown
UTF-8
1,052
2.515625
3
[]
no_license
# ubuntu-debian ## How to autoupdate ubuntu&amp;debian ### Install the required packages apt-get install unattended-upgrades apt-listchanges #### Put the lines below into the configuration file /etc/apt/apt.conf.d/50unattended-upgrades, #### everything that was originally inside the generated file can be removed before you add the lines below. Unattended-Upgrade::Origins-Pattern { "origin=Debian,codename=${distro_codename},label=Debian-Security"; "origin=TorProject"; }; Unattended-Upgrade::Package-Blacklist { }; ### If you want to automatically reboot add the following at the the end of the file /etc/apt/apt.conf.d/50unattended-upgrades Unattended-Upgrade::Automatic-Reboot "true"; ### Create the file /etc/apt/apt.conf.d/20auto-upgrades with the following content APT::Periodic::Update-Package-Lists "1"; APT::Periodic::AutocleanInterval "5"; APT::Periodic::Unattended-Upgrade "1"; APT::Periodic::Verbose "1"; ### Test your unattended-upgrades setup with the following command. sudo unattended-upgrade -d
Java
UTF-8
2,682
2.609375
3
[]
no_license
package edu.rosehulman.rafinder.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import edu.rosehulman.rafinder.R; import edu.rosehulman.rafinder.UserType; import edu.rosehulman.rafinder.controller.HomeFragment; import edu.rosehulman.rafinder.model.person.Employee; /** * Models a list of lists of employees, for use with {@link edu.rosehulman.rafinder.adapter.EmployeeListAdapter}. */ public class EmployeeList { private final List<EmployeeSubList> employees; public EmployeeList(HomeFragment.HomeListener context, String hallName) { this.employees = new ArrayList<>(); UserType userType = context.getUserType(); if (!userType.equals(UserType.RESIDENT)) { this.employees.add(new EmployeeSubList( context.getString(R.string.my_profile), Collections.singletonList(context.getUser()))); } else if (hallName.equals(context.getHallName())) { List<Employee> myRAs = context.getMyRAs(); String key = myRAs.size() > 1 ? context.getString(R.string.my_ras) : context.getString(R.string.my_ra); this.employees.add(new EmployeeSubList(key, myRAs)); } this.employees.add(new EmployeeSubList(context.getString(R.string.hall_ras), context.getRAsForHall(hallName))); if (isFreshmanHall(hallName)) { this.employees.add(new EmployeeSubList(context.getString(R.string.hall_sas), context.getSAsForHall(hallName))); } } private boolean isFreshmanHall(String hallName) { return hallName.equalsIgnoreCase("Mees") || hallName.equalsIgnoreCase("Blumberg") || hallName.equalsIgnoreCase("Scharpenberg") || hallName.equalsIgnoreCase("Speed") || hallName.equalsIgnoreCase("Deming") || hallName.equalsIgnoreCase("BSB"); } public List<EmployeeSubList> getEmployees() { return employees; } /** * Models a single list of employees within the larger list. */ public class EmployeeSubList { private final String key; private final List<Employee> employees; public EmployeeSubList(String key, List<Employee> employees) { this.key = key; this.employees = employees; } public String getKey() { return key; } public List<Employee> getEmployees() { return employees; } public int size() { return this.employees.size(); } public Employee get(int i) { return this.employees.get(i); } } }
C++
UTF-8
646
3.0625
3
[ "BSD-2-Clause" ]
permissive
#include "Anim.hpp" // Par défaut Anim::Anim() { } // déstructeur Anim::~Anim() { } // Par copie Anim::Anim(const Anim& Cpy) { myFrame = Cpy.myFrame; } // Ajouter une frame void Anim::PushFrame(const Frame& NewFrame) { myFrame.push_back(NewFrame); } // Nombre de frame(s) size_t Anim::Size() const { return myFrame.size(); } // Accès a la frame numéro N Frame& Anim::operator [] (size_t N) { return myFrame[N]; } void Anim::clear() { myFrame.clear(); } // Plus tard, nous pourrons ajouter différentes fonctions liées au fait qu'une 'Anim' est une ressource // Par exemple : LoadFromFile, SaveToFile etc...
Java
UTF-8
1,753
2.703125
3
[]
no_license
package org.optimization.service.model.validation; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import org.optimization.service.model.Problem; import org.optimization.service.model.validation.ProblemValidator.Issue; /** Validates if problem is correct KnapsackProblem. */ public class ProblemValidator implements Validate<Issue> { public enum Issue { WEIGHT_AND_VALUE_ARE_NOT_OF_SAME_SIZE, WEIGHT_CANNOT_BE_NEGATIVE, CAPACITY_CANNOT_BE_NEGATIVE_OR_NULL; } private List<Issue> issues = new ArrayList<>(); private final Problem problem; private ProblemValidator(Problem problem) { this.problem = problem; } public static ProblemValidator create(Problem problem) { Objects.requireNonNull(problem); return new ProblemValidator(problem); } @Override public boolean isValid() { Predicate<Problem> capacityNotNullAndNegative = p -> p.getCapacity() != null && p.getCapacity() > 0; Predicate<Problem> weightAndValueOfSameSize = p -> p.getWeights() != null && p.getValues() != null && (p.getWeights().size() == p.getValues().size()); Predicate<Problem> weightCannotBeNegative = p -> p.getWeights().stream().filter(w -> w < 0).count() == 0; if (!capacityNotNullAndNegative.test(problem)) issues.add(Issue.CAPACITY_CANNOT_BE_NEGATIVE_OR_NULL); if (!weightAndValueOfSameSize.test(problem)) issues.add(Issue.WEIGHT_AND_VALUE_ARE_NOT_OF_SAME_SIZE); if (!weightCannotBeNegative.test(problem)) issues.add(Issue.WEIGHT_CANNOT_BE_NEGATIVE); return issues.isEmpty(); } @Override public List<Issue> issues() { return issues; } }
C#
UTF-8
1,963
2.765625
3
[]
no_license
 using Atom.Api.Application.Interfaces; using LazZiya.ImageResize; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Threading.Tasks; namespace Atom.Api.Application.Utilities { public class FileHandler : IFileHandler { public byte[] GetResizedImage(string imagePathAndName, int width, int height, string waterMark="", string backgroundColor="") { byte[] resizeImageByte; using (Image img = Image.FromFile(imagePathAndName)) { var scaledImage = img.Scale(width, height, new GraphicOptions() { PageUnit=GraphicsUnit.Pixel }); var tOps = new TextWatermarkOptions(); tOps = ApplyWaterMark(waterMark, backgroundColor, scaledImage, tOps); resizeImageByte = GetImageByteArray(scaledImage); } return resizeImageByte; } private byte[] GetImageByteArray(Image scaledImage) { byte[] resizeImageByte; using (var stream = new MemoryStream()) { scaledImage.Save(stream, ImageFormat.Png); resizeImageByte = stream.ToArray(); } return resizeImageByte; } private TextWatermarkOptions ApplyWaterMark(string waterMark, string backgroundColor, Image scaledImage, TextWatermarkOptions tOps) { if (!string.IsNullOrEmpty(backgroundColor)) { tOps = new TextWatermarkOptions { BGColor = Color.FromName(backgroundColor) }; } if (!string.IsNullOrEmpty(waterMark)) { scaledImage.AddTextWatermark(waterMark, tOps); } return tOps; } } }
Java
UTF-8
1,079
3.34375
3
[]
no_license
package com.it.api; /** * @author LY * @PackageName:com.it.api * @ClassName:TopoLogical * @date 2021/6/1 10:47 * 类说明: <br> */ public class TopoLogical { /**顶点的拓扑排序*/ private Stack<Integer> order; /** * 功能说明:构造拓扑排序对象 * @Param [G] */ public TopoLogical(Digraph G) { //创建检测环对象,检测图G中是否有环 DirectedCycle dCycle = new DirectedCycle(G); if (!dCycle.hasCycle()){ //如果没有环,创建顶点排序对象,进行顶点排序 DepthFirstOrder depthFirstOrder = new DepthFirstOrder(G); order = depthFirstOrder.reversePost(); } } /** * 功能说明:判断图G是否有环 * @Param [] * @return boolean */ private boolean isCycle(){ return order==null; } /** * 功能说明:获取拓扑排序的所有顶点 * @Param [] * @return com.it.api.Stack<java.lang.Integer> */ public Stack<Integer> order(){ return order; } }
Java
UTF-8
447
1.929688
2
[]
no_license
package com.prospect.druid.mapper; import com.prospect.druid.bean.db.Account; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @author: ant * @Date: 2021/11/9 2:07 下午 */ @Mapper public interface AccountMapper { /** * 保存 * @param record 账户 * @return */ int insert(Account record); /** * 查询所有账户 * @return List */ List<Account> findAll(); }
Python
UTF-8
970
4.34375
4
[]
no_license
''' Create a program that: Contains information on currency conversion rates from USD to four other currencies User can enter in an amount in USD and the currency they want to convert it into The programme then outputs the amount in the new currency ''' print('This is a Currency Converter') country_currency={'Philippines':49.03,'Japan':105.48,'UAE':3.67,'Taiwan':29.36} your_money=int(input('Enter amount in USD:')) currency=input('Enter country name (Philippines,Japan,UAE,Taiwan): ') converter = your_money * country_currency[currency] print('The currency conversion is {}.'.format(converter)) ''' if currency == 'Philippines': print('The currency conversion is {} pesos.'.format(converter)) elif currency == 'Japan': print('The currency conversion is {} yen.'.format(converter)) elif currency == 'UAE': print('The currency conversion is {} dirham.'.format(converter)) else: print('The currency conversion is {} NT dollar.'.format(converter)) '''
JavaScript
UTF-8
1,838
2.65625
3
[ "MIT" ]
permissive
import axios from 'axios'; let axiosOpts = { headers: { 'Content-Type': 'application/json; charset=utf-8' } }; export class Result { data; errors; get hasErrors() { return this.errors !== null && Array.isArray(this.errors) && this.errors.length > 0; } constructor(data, ...errors) { this.data = data; this.errors = errors[0] === undefined || errors[0] === null ? [] : errors; } } export default class ContactService { static async list() { var axiosResult = null; var result = null; try { axiosResult = await axios.get('/api/contacts/getAll'); result = new Result(axiosResult.data.contacts, axiosResult.data.errors); } catch(error){ result = new Result(null, error.message); } return result; } static async update(values) { var axiosResult = null; var result = null; try { axiosResult = await axios.put(`/api/contacts/update/${values.id}`, values, axiosOpts); result = new Result(axiosResult.data, axiosResult.data.errors); } catch(error) { result = new Result(null, error.message); } return result; } static async delete(id) { var axiosResult = null; var result = null; try { axiosResult = await axios.delete(`/api/contacts/delete/${id}`, axiosOpts) result = new Result(axiosResult.data, axiosResult.data.errors); } catch (error) { result = new Result(null, error.message); } return result; } static async add(values) { var axiosResult = null; var result = null; try { axiosResult = await axios.post(`/api/contacts/create`, values, axiosOpts); result = new Result(axiosResult.data, axiosResult.data.errors); } catch (error) { result = new Result(null, error.message); } return result; } }
C#
UTF-8
1,553
2.84375
3
[]
no_license
<Query Kind="Program"> <Namespace>System.Security.Cryptography</Namespace> </Query> void Main() { var dictStrings = File.ReadLines(@"C:\Users\and\Downloads\wordlist.txt") // .Take(10) .Select(x => CalculateMD5Hash(x)) // .Dump() ; var lookupString = "AAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAASDDXSXXXXXXXX"; dictStrings.Contains(CalculateMD5Hash(lookupString).Dump()).Dump(); } // Define other methods and classes here public int CalculateMD5Hash(string input) //public string CalculateMD5Hash(string input) { // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string // StringBuilder sb = new StringBuilder(); byte[] returnVal = new byte[hash.Length]; for (int i = 0; i < hash.Length; i++) { bool resultByteHash = true; resultByteHash = resultByteHash & GetBit(hash[i], 0); resultByteHash = resultByteHash & GetBit(hash[i], 1); resultByteHash = resultByteHash & GetBit(hash[i], 2); resultByteHash = resultByteHash & GetBit(hash[i], 3); returnVal[i] = resultByteHash ? (byte) 1 : (byte) 0; // sb.Append(hash[i].ToString("X2")); // sb.Append(hash[i].ToString("x2")); } // return sb.ToString(); return BitConverter.ToInt32(returnVal, 0); } public static bool GetBit(byte b, int bitNumber) { return (b & (1 << bitNumber)) != 0; }
Java
UTF-8
427
2.21875
2
[]
no_license
package uk.me.conradscott.maths; import org.jetbrains.annotations.NotNull; import java.util.List; public interface PointIfc { int x(); int y(); @NotNull PointIfc plus( int dx, int dy ); @NotNull PointIfc plus( @NotNull PointIfc point ); @NotNull PointIfc minus( int x, int y ); @NotNull PointIfc minus( @NotNull PointIfc point ); @NotNull List<PointIfc> neighbors8(); }
Java
UTF-8
147
1.640625
2
[]
no_license
package com.huaxin.regexp; /** * Created by Administrator on 2016/5/6. */ public interface ExpFetcher { public String parse(String str); }
C#
UTF-8
477
2.546875
3
[]
no_license
using System.Text.RegularExpressions; namespace StoicDreams.FileProxy.Filter { public static class Filters { public static readonly Regex RemoveFromPath = new Regex(@"[A-Za-z]+\:\/\/[^\/]+", RegexOptions.IgnoreCase & RegexOptions.Singleline); public static string FilterURLToRoutePath(this string input) { string result = input.Split('?')[0]; if (result.Contains("#")) { result = result.Split('#')[0]; } return RemoveFromPath.Replace(result, ""); } } }
Python
UTF-8
473
3.171875
3
[]
no_license
exam_results = [21, 11, 4, 96, 48, 5, 13, 64, 28, 33, 43, 20, 70, 24, 88, 57, 31, 9, 35, 47, 56, 45, 14, 74, 35, 6, 79, 62, 17, 83, 5, 8, 44, 56, 60, 47, 17, 23, 96, 66, 17, 43, 7, 21, 18, 100, 30, 8, 15, 15] new_results = [] for n in exam_results: if n >= 50: new_results.append(n) print new_results # or def bigger_than(n): return n >= 50 # filter(function, list) print filter(bigger_than, exam_results) print filter(lambda n: n>=50, exam_results)
Java
UTF-8
1,391
3.4375
3
[]
no_license
package aptech; import java.util.ArrayList; import java.util.Scanner; public class PersonManager { private ArrayList<Person> persons = new ArrayList<>(); Scanner getScanner() { return new Scanner(System.in); } public void setPersons() throws Exception{ System.out.println("Enter number of persons: "); int numberOfPersons = getScanner().nextInt(); if(numberOfPersons < 0) { throw new Exception("number must be > 0"); } for(int i = 0; i < numberOfPersons; i++) { Person person = new Person(); person.input(); persons.add(person); } } public void getPersons() { for (Person person: this.persons) { person.display(); } } public void findPerson() { int index = 0; System.out.println("Enter index to search: "); //cach 1: duyet thuan tuy index = getScanner().nextInt(); for(int i = 0; i < this.persons.size(); i++) { if(index == i) { this.persons.get(i).display(); } } //filter trong truong hop muon tim theo tieu chi nao do lien quan den property cua object //VD: sinh vien co age > 18 && age < 30 //lam menu => mn xem vi du cua buoi 2(lam menu), su dung switch-case } }
C
UTF-8
696
4.03125
4
[]
no_license
/* 编写程序实现从键盘读入文件名,计算该文件的行数(换行符的个数)并显示在界面上。 */ #include <stdio.h> #include <stdlib.h> #ifdef FILENAME_MAX #undef FILENAME_MAX #endif #define FILENAME_MAX 1024 int main() { char fname[FILENAME_MAX]; printf("输入文件名:"); scanf("%s", fname); FILE* fp = fopen(fname, "r"); if (NULL == fp) { printf("文件打开失败\n"); return -1; } char c; unsigned int count = 0; while( EOF != (c = fgetc(fp)) ) { if (c == '\n') { count++; } } printf("文件%s共有%d行。\n", fname, count); fclose(fp); return 0; }
Python
UTF-8
913
3.96875
4
[]
no_license
class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def __repr__(self): # string representation return self.val def deepest(node): if not node: return levels = find_height(node) deepest_(node, levels) return levels def deepest_(node, levels): if not node: return if levels == 1: print(node.val, end=" ") else: deepest_(node.left, levels - 1) deepest_(node.right, levels - 1) def find_height(node): if not node: return 0 leftHeight = find_height(node.left) rightHeight = find_height(node.right) return max(leftHeight, rightHeight) + 1 root = Node('a') root.left = Node('b') root.left.left = Node('d') root.right = Node('c') root.right.right = Node('e') root.right.right.right = Node('f') print(deepest(root)) # (d, 3)
Java
UTF-8
1,928
2.78125
3
[ "Apache-2.0" ]
permissive
package com.example.morro.FastBuyApp.UI; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.support.v7.widget.helper.ItemTouchHelper.Callback; /** * Handle the gestures by calling adapter's ActionCompletionContract methods */ public class SwipeAndDragHelper extends Callback { private ActionCompletionContract contract; // passed object which will implement the interface /** Constructor */ public SwipeAndDragHelper(ActionCompletionContract contract) { this.contract = contract; } /** Define flags for IDLE, DRAG and SWIPE */ @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; return makeMovementFlags(dragFlags, swipeFlags); } /** gets called when a view is dragged from its position to other positions */ @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { //contract.onViewMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition()); //we don't really need this feature as of now return true; } /** let's disable item dragging since we won't need it. */ @Override public boolean isLongPressDragEnabled() { return false; } /** gets called when a view is completely swiped out */ @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { contract.onViewSwiped(viewHolder.getAdapterPosition()); } /* Action completion contract interface definition */ public interface ActionCompletionContract { void onViewMoved(int oldPosition, int newPosition); void onViewSwiped(int position); } }
JavaScript
UTF-8
4,225
2.65625
3
[]
no_license
const initialState = { item: [], postsLoading: false, }; export const postsReducer = (state = initialState, action) => { switch (action.type) { case 'get/posts/start': return { postsLoading: true, }; case 'get/posts/successes': return { postsLoading: false, item: action.payload, }; case 'add/new/post/successes': return { ...state, item: [...state.item, action.payload], }; case 'delete/post/successes': return { ...state, item: state.item.filter((post) => post.id !== action.payload), }; case 'approved/post/successes': return { ...state, item: state.item.map((post) => post.id === action.payload.id ? action.payload : post, ), }; default: return state; } }; export const getPosts = () => { //получение постов страницы Feed return (dispatch) => { dispatch({ type: 'get/posts/start' }); fetch(`/posts`) .then((res) => res.json()) .then((posts) => { dispatch({ // принимается в postsReducer type: 'get/posts/successes', payload: posts, }); }); }; }; export const addNewPostWindowOpenClose = () => { // открывает и закрывает панель добавления поста на странице feed return (dispatch) => { dispatch({ // принимается в addPostReducer type: 'add/new/post/window/open/ore/close', }); }; }; export const addNewPostWindowClose = () => { //закрывает панель добавления поста на странице feed return (dispatch) => { dispatch({ // принимается в addPostReducer type: 'add/new/post/window/close', }); }; }; export const addTitleNewPost = (title) => { //отправляет заголовок новго поста в редюсер return (dispatch) => { dispatch({ // принимается в addPostReducer type: 'add/title/new/post', payload: title, }); }; }; export const addTextNewPost = (text) => { //отправляет текст новго поста в редюсер return (dispatch) => { dispatch({ // принимается в addPostReducer type: 'add/text/new/post', payload: text, }); }; }; export const addNewPost = (title, text, userName, userId) => { // добавление нового поста из компонента AddNewPost return (dispatch) => { fetch(`/posts`, { method: 'POST', body: JSON.stringify({ title: title, text: text, author: userName, userId: userId, approved: false, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }) .then((response) => response.json()) .then((json) => dispatch({ // принимается в postsReducer type: 'add/new/post/successes', payload: json, }), ); }; }; export const adminDeletePost = (id) => { //удаление админом неодобренного поста передается айди на сервер return (dispatch) => { fetch(`/posts/${id}`, { method: 'DELETE', }) .then((res) => res.json()) .then(() => { dispatch({ // принимается в postsReducer type: 'delete/post/successes', payload: id, }); }); }; }; export const adminApprovedPost = (id) => { //одобрение админом неодобренного поста передается айди на сервер return (dispatch) => { fetch(`/posts/${id}`, { method: 'PATCH', body: JSON.stringify({ approved: true, }), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }) .then((res) => res.json()) .then((json) => { dispatch({ // принимается в postsReducer type: 'approved/post/successes', payload: json, }); }); }; };
Python
UTF-8
1,062
2.953125
3
[]
no_license
#!/usr/bin/env python #coding:utf-8 import wx class MyWindow(wx.Frame): def __init__(self, parent=None, id=-1, title=None): wx.Frame.__init__(self, parent, id, title) self.panel = wx.Panel(self, size=(300, 200)) self.panel.SetBackgroundColour('WHITE') font = wx.Font(60, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) self.stext = wx.StaticText(self.panel) self.stext.SetFont(font) self.stext.SetWindowStyle(wx.BORDER_SIMPLE) self.stext.CenterOnParent() self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer) self.Fit() self.counter = 20 self.timer.Start(500) def OnTimer(self, event): self.stext.SetLabel("%02d" % self.counter) self.stext.CenterOnParent() if self.counter == 0: self.timer.Stop() else: self.counter -= 1 if __name__ == '__main__': app = wx.PySimpleApp() w = MyWindow(title='wx-timer') w.Center() w.Show() app.MainLoop()
Java
UTF-8
866
3.90625
4
[]
no_license
package com.cheneyin.design.mode.iterator; /** * @ClassName: Main * @Description: ToDo * @Author: CheneyIn * @Date: 2019-12-23 */ public class Main { public static void main(String[] args) { /* 先初始化来一个存放书的书架 */ BookShelf bookShelf = new BookShelf(4); bookShelf.appendBook(new Book("firstOneBook")); bookShelf.appendBook(new Book("firstTwoBook")); bookShelf.appendBook(new Book("firstThreeBook")); bookShelf.appendBook(new Book("firstFourBook")); /* 通过Iterator拿到遍历书架的实例 */ Iterator iterator = bookShelf.iterator(); /* 没有下一个元素就停止遍历 */ while (iterator.hasNext()) { /* 通过next()方法拿出下一本书 */ System.out.println(((Book) iterator.next()).getName()); } } }
Java
UTF-8
1,650
1.789063
2
[]
no_license
package com.appleframework.ras.api; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.gitee.easyopen.ApiConfig; import com.gitee.easyopen.AppSecretManager; import com.gitee.easyopen.support.ApiController; /** * 文档地址:http://localhost:8080/api/doc */ @Controller @RequestMapping("router") public class IndexController extends ApiController { @Resource private AppSecretManager appSecretManager; @Override protected void initApiConfig(ApiConfig apiConfig) { String appName = "apple-ras-api"; apiConfig.setShowDoc(true); // 显示文档页面 // 配置国际化消息 apiConfig.setAppSecretManager(appSecretManager); apiConfig.setApiName("method"); apiConfig.setAppKeyName("appkey"); apiConfig.setSignName("sign"); apiConfig.setVersionName("v"); apiConfig.setTraceId("traceId"); apiConfig.setIgnoreValidate(true); apiConfig.setAppName(appName); apiConfig.setDataMode(false); apiConfig.setIgnoreValidate(true); // apiConfig.setOauth2Manager(oauth2Manager); // String docUrl = "http://localhost:8080/api/doc"; // ConfigClient configClient = new ConfigClient(appName, configHost, Integer.parseInt(configPort), docUrl); // apiConfig.setConfigClient(configClient); // apiConfig.setAppSecretManager(configClient.getAppSecretManager()); // // apiConfig.setInterceptors(new ApiInterceptor[] { // // 限流拦截器(配置中心) // new LimitInterceptor() // }); } }
Java
UTF-8
990
2.59375
3
[]
no_license
package com.example.demo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.model.Company; import com.example.demo.repository.CompanyRepository; import com.example.exceptions.CompanyException; @Service("companyService") public class CompanyServiceImpl implements CompanyService { @Autowired CompanyRepository companyRepository; @Override public boolean createCompany(String name, String address) throws CompanyException { Company company = new Company(); if(name.isEmpty()) throw new CompanyException("company name is empty"); company.setName(name); company.setAddress(address); companyRepository.save(company); return false; } @Override public Company getCompany(String id) throws CompanyException { Company company = companyRepository.getOne(id); if(company == null) throw new CompanyException("No company exists with given id : " + id); return company; } }
Python
UTF-8
243
3.5625
4
[]
no_license
def findelem(word,litter): output=[] for i,j in enumerate(word): if litter == j: output.append(i) return output # word=input('input the word ') # litter=input('input the litter ') # print(findelem(word,litter))
JavaScript
UTF-8
378
4.03125
4
[]
no_license
let num = [5,4,8] console.log (`Nosso vetor é o ${num}`) num.push(1) console.log (`Nosso vetor é o ${num}`) // comprimento do vetor : let tamanho = num.length console.log (`Nosso vetor é o ${num} e possui ${tamanho} elemento(s)`) // ordenação de vetor let numordenado = num.sort() console.log (`Nosso vetor é o ${num} e seu correspondente ordenado é ${numordenado}`)
Markdown
UTF-8
4,578
3.265625
3
[]
no_license
> 최초작성 : 2021.02.07 ## ******Level2 - 위장**** (java/kotlin)**  [코딩테스트 연습 - 위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | **문제 설명** | | --- | | 스파이들은 매일 다른 옷을 조합하여 입어 자신을 위장합니다.<br>예를 들어 스파이가 가진 옷이 아래와 같고 오늘 스파이가 동그란 안경, 긴 코트, 파란색 티셔츠를 입었다면 다음날은 청바지를 추가로 입거나 동그란 안경 대신 검정 선글라스를 착용하거나 해야 합니다.| | **종류** | **이름** | | --- | --- | | 얼굴 | 동그란 안경, 검정 선글라스 | | 상의 | 파란색 티셔츠 | | 하의 | 청바지 | | 겉옷 | 긴 코트 | || | --- | | 스파이가 가진 의상들이 담긴 2차원 배열 clothes가 주어질 때 서로 다른 옷의 조합의 수를 return 하도록 solution 함수를 작성해주세요.| | **제한 조건** | | --- | |- clothes의 각 행은 \[의상의 이름, 의상의 종류\]로 이루어져 있습니다.| |- 스파이가 가진 의상의 수는 1개 이상 30개 이하입니다.| |- 같은 이름을 가진 의상은 존재하지 않습니다.| |- clothes의 모든 원소는 문자열로 이루어져 있습니다.| |- 모든 문자열의 길이는 1 이상 20 이하인 자연수이고 알파벳 소문자 또는 '\_' 로만 이루어져 있습니다.| |- 스파이는 하루에 최소 한 개의 의상은 입습니다.| | **​입출력 예** | | | :---: | :---: | | clothes | return | | \[\["yellow\_hat", "headgear"\], \["blue\_sunglasses", "eyewear"\], \["green\_turban", "headgear"\]\] | 5 | | \[\["crow\_mask", "face"\], \["blue\_sunglasses", "face"\], \["smoky\_makeup", "face"\]\] | 3 | 입출력 예#1 - headgear에 해당하는 의상이 yellow\_hat, green\_turban이고 eyewear에 해당하는 의상이 blue\_sunglasses이므로 아래와 같이 5개의 조합이 가능합니다. 1. yellow\_hat 2. blue\_sunglasses 3. green\_turban 4. yellow\_hat + blue\_sunglasses 5. green\_turban + blue\_sunglasses 입출력 예#2 - face에 해당하는 의상이 crow\_mask, blue\_sunglasses, smoky\_makeup이므로 아래와 같이 3개의 조합이 가능합니다. 1. crow\_mask 2. blue\_sunglasses 3. smoky\_makeup ​ <center> |결국 나는 포기...<br>map 혹은 조합을 사용해서 이것저것 해보았으나...<br>진짜 도저히 모르겠다 ㅠㅠ<br>내가 제일 싫어한게 확통이었어 ㅠㅜㅠㅠㅠㅠ😪| |:--:| </center> ### _**JAVA1 코드 정리**_ ```java import java.util.*; import static java.util.stream.Collectors.*; class Solution { public int solution(String[][] clothes) { return Arrays.stream(clothes) .collect(groupingBy(p -> p[1], mapping(p -> p[0], counting()))) .values() .stream() .collect(reducing(1L, (x, y) -> x * (y + 1))).intValue() - 1; } } ``` **\* reduce() : 엘리먼트를 비교하고 컬렉션에서 하나의 값으로 연산** | 결국은 뒤에서 정리할 JAVA2의 코드를 stream을 이용하여 한줄로 풀었다. 음... 대충 어느 풀이이다 감은 오는데 잘 모르겠는 ㅠㅜ | | --- | ### _**JAVA2 코드 정리**_ **[2ssue.github.io/algorithm/programmers\_42578/](https://2ssue.github.io/algorithm/programmers_42578/)** 1\. 옷의 종류를 map의 키로 지정하고 종류의 개수를 value로 넣는다. _(map.get(clothes\[i\]\[1\])+1)_ 2\. 경우의 수를 구한다. 3\. 하나도 안 입는 경우는 없으므로 answer에서 -1을 해주고 리턴한다. ```java import java.util.HashMap; class Solution { public int solution(String[][] clothes) { int answer = 1; HashMap<String, Integer> map = new HashMap<>(); for(int i = 0; i < clothes.length; i++) { if(map.get(clothes[i][1]) == null) map.put(clothes[i][1], 1); else map.put(clothes[i][1], map.get(clothes[i][1]) + 1); } for(String keys: map.keySet()) { answer *= (map.get(keys) + 1); } answer -= 1; return answer; } } ``` <center> | 경우의 수와 map만 이용한다면 참 간단하게 풀리는 문제였구나...<br>괜히 이상한데서 삽질 한 것 같다 ㅠㅜ<br>map을 이용해서 옷 종류의 개수를 구할 생각은 못했다. | | --- | </center> <center> | JAVA2의 풀이법을 Kotlin으로 변환한 버전 | | :---: | </center>
C++
UTF-8
549
3.421875
3
[]
no_license
#include<iostream> using namespace std; template<typename T> T Max(T a,T b) { return (a > b) ? a : b; } bool isAnagram(string s1,string s2) { int n = s1.length(); if(n!=s2.length()) return false; int count[26] = {0}; for(int i = 0;i<n;i++) { count[s1[i]-'a']++; count[s2[i]-'a']--; } for(int i = 0;i<26;i++) if(count[i]) return false; return true; } int main() { isAnagram("dog","god") ? cout<<"Yes\n" : cout<<"No\n"; cout<<Max(10,20)<<endl; cout<<Max(3.5,7.3)<<endl; cout<<Max('d','w')<<endl; return 0; }
Markdown
UTF-8
4,138
2.9375
3
[ "MIT" ]
permissive
--- layout: post title: 애니메이션 구현에 CSS가 자바스크립트보다 더 좋은 이유 categories: JavaScript --- 브라우저에서 하나의 애니메이션 프레임을 처리한다는 것은 애니메이션 구현에 필요한 모든 계산 과정과 계산을 통해 얻어진 픽셀 자리를 업데이트 하는 것까지 포함합니다. 버벅이지 않는 애니메이션을 보려면 프레임별 렌더링이 문제없이 잘 이루어져야합니다. 애니메이션을 어떻게 적용하느냐에 따라 렌더링성능은 달라지게 되고 자연스럽지 못한 애니메이션을 경험하게 될지도 모릅니다. 특히 자바스크립트보다 CSS로 애니메이션을 적용하는것이 더 부드럽게 보여질 수 있는데 그 이유에 대해 알아봅니다. <hr /> <!-- vscode-markdown-toc --> - [렌더링 프로세스](#렌더링-프로세스) - [메인스레드와 컴포지터 스레드](#메인스레드와-컴포지터-스레드) - [애니메이션 대상](#애니메이션-대상) - [자바 스크립트보다 CSS 사용하는 이유](#자바-스크립트보다-css-사용하는-이유) - [transform & opacity](#transform-&-opacity) <!-- vscode-markdown-toc-config numbering=false autoSave=true /vscode-markdown-toc-config --> <!-- /vscode-markdown-toc --> ## <a name='렌더링-프로세스'></a>렌더링 프로세스 먼저 브라우저의 렌더링 절차를 되새겨 봅시다. - 스타일 재 계산: 요소를 적절한 CSS 선택자 (예: .heading > span, .title)와 일치시키고 적용 할 스타일을 계산합니다. - 레이아웃: 크기와 위치를 생성합니다 . 기본적으로 너비, 높이 및 페이지에서 이동해야하는 위치입니다. - 페인트: 배경, 테두리, 그림자, 텍스트 등 보이는 모든 픽셀을 채 웁니다. 요소는 일반적으로 레이어로 칠해집니다. - 합성 레이어: 페인트로 만든 레이어를 올바른 순서로 결합하여 화면에 출력합니다. ### <a name='메인스레드와-컴포지터-스레드'></a>메인스레드와 컴포지터 스레드 브라우저에는 기본 스레드와 합성 스레드의 두 스레드가 있습니다. 메인 스레드는 대부분의 작업은 자바 스크립트, 재 계산 스타일, 레이아웃 및 페인트를 포함하여, 발생하는 곳입니다. 가장 집약적 인 작업이 모두 그곳에서 실행되므로 한 번에 수십에서 수백 밀리 초 동안 일상적으로 중단됩니다. 컴포지터 스레드는 복합 레이어 및 기타 렌더링 작업을 담당합니다. ## <a name='애니메이션-대상'></a>애니메이션 대상 애니메이션 대상은 레이아웃을 재 조정하기보다는 합성만을 담당하도록 하면 렌더링 성능은 빨라질 것입니다. 많은 것을 담당하여 바쁜 메인스레드보다는 GPU 가속을 활용하는 컴포지터 스레드에게 작업을 맡기면 그만큼 좋은 성능을 경험합니다. 따라서 애니메이션 대상은 다음과 같은 조건을 가집니다. - 렌더링 폭포의 상단(스타일 재걔산 / 레이아웃 / 페인트)보다는 합성을 담당하도록 한다. - 메인 스레드를 피한다. - 컴포지터 스레드와 GPU를 활용한다. ### <a name='자바-스크립트보다-css-사용하는-이유'></a>자바 스크립트보다 CSS 사용하는 이유 이제 결론입니다. 자바 스크립트는 항상 메인 스레드에서 실행되므로 다른 작업으로 인해 스레드가 정체 될 경우, 프레임이 떨어질 가능성이 더 높으므로 자바 스크립트로 애니메이션을 사용하는 것 보다는 GPU를 활용할 수 있는 CSS를 사용하면 더 좋은 성능을 낼 수 있습니다. #### <a name='transform-&-opacity'></a>transform & opacity transform, opacity와 같은 속성을 사용하면, CPU 대신 GPU를 사용해 웹 브라우저가 애니메이션을 수행할 수 있도록 할 수 있습니다. --- 해당 내용은 다음 글을 참고 하였습니다. - https://www.viget.com/articles/animation-performance-101-browser-under-the-hood/
Python
UTF-8
1,703
2.984375
3
[ "MIT" ]
permissive
import numpy as np MAX_MOVING_AVG_LEN = 10 class predict: def __init__(self, trend_block): self.data = [] self.trend_block = trend_block def push_data(self, price): self.data.append(price) def _cal_moving_avg(self, day): total = 0 for index in range(MAX_MOVING_AVG_LEN): if ((day - index) < 0): total += self.data[0] else: total += self.data[day-index] return (total / MAX_MOVING_AVG_LEN) - self.data[0] def _cal_avg_change_trend(self, _avg_diff): if (_avg_diff > self.trend_block[0]): _avg_change_period = 3 elif(_avg_diff < self.trend_block[1]): _avg_change_period = 0 elif(_avg_diff < self.trend_block[2]): _avg_change_period = 1 else: _avg_change_period = 2 return _avg_change_period def get_new_state(self, day, state): _moving_avg = self._cal_moving_avg(day) _avg_diff = _moving_avg - state[0] _avg_change_trend = self._cal_avg_change_trend(_avg_diff) _state = [_moving_avg, _avg_diff, _avg_change_trend] return np.array(_state) def action(self, hold, trend): if(hold == 0): if(trend > 1): action = 1 else: action = -1 elif(hold == 1): if(trend > 1): action = 0 else: action = -1 else: if(trend < 3): action = 0 else: action = 1 return action def check_money(self, hold, action, money, price): if (action == 1): money -= price if (hold == 0): hold = 1 else: hold = 0 elif (action == -1): money += price if (hold == 0): hold = -1 else: hold = 0 return (money, hold)
Java
UTF-8
1,987
2.0625
2
[]
no_license
package com.winxuan.ec.admin.controller.order; import java.util.Date; import com.winxuan.ec.model.area.Area; /** * 订单发货报表-FORM * @author heyadong * @version 1.0, 2012-8-9 下午03:24:20 */ public class OrderDeliveryReportForm { private Long[] channels; private Area[] areas; private String orders; private Date startDeliveryTime; private Date endDeliveryTime; private Long[] country; private Long[] province; private Long[] city; private Long[] district; //包件回填状态 private Integer state; public Long[] getCountry() { return country; } public void setCountry(Long[] country) { this.country = country; } public Long[] getProvince() { return province; } public void setProvince(Long[] province) { this.province = province; } public Long[] getCity() { return city; } public void setCity(Long[] city) { this.city = city; } public Long[] getDistrict() { return district; } public void setDistrict(Long[] district) { this.district = district; } public Long[] getChannels() { return channels; } public void setChannels(Long[] channels) { this.channels = channels; } public Date getStartDeliveryTime() { return startDeliveryTime; } public void setStartDeliveryTime(Date startDeliveryTime) { this.startDeliveryTime = startDeliveryTime; } public Date getEndDeliveryTime() { return endDeliveryTime; } public void setEndDeliveryTime(Date endDeliveryTime) { this.endDeliveryTime = endDeliveryTime; } public Area[] getAreas() { return areas; } public void setAreas(Area[] areas) { this.areas = areas; } public boolean ignore(){ return country == null && province == null && city == null && district == null; } public String getOrders() { return orders; } public void setOrders(String orders) { this.orders = orders; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } }
C++
UTF-8
1,716
2.578125
3
[]
no_license
/*************************************************** file: Scheduler.h class: CPTR 352 - OS Design purpose: Provide the class to represent the CPU scheduler. creators: Howard Heaton & Blake Kruppa date: June 2016 ***************************************************/ #include "Analyzer.cpp" class Scheduler { private: int current_time; int oldest_task_pid; int schedule_method; int task_num; void UpdateWaitStates(); // First Come First Serve void FCFS(); int FindOldestReadyTask(); // Round Robin void RR(); int current_serviced_amount; int GetNextTaskRR(); int NumAvailableCPUS(); // Shortest Remaining Time void SRT(); int shortest_task_pid; int FindShortestTask(); // Highest Response Ratio Next void HRRN(); int GetIndexHRR(); float TaskResponseRatio(int); public: Scheduler(); Analyzer analysis_tool; // Object for analyzing performance ProcessTable p_table; // Process Control Block void SetSchedulingMethod(int); // Determine Scheduling Mode void PassProcessesToCPU(int); // Process the tasks float MeanTurnaroundTime(); // Out mean turnaround time float MeanResponseRatio(); // Output mean response ratio void OutputAnalysis(); };
Java
UTF-8
386
2.015625
2
[]
no_license
package com.nt.test; import com.nt.comps.Flipkart; import com.nt.factory.FlipkartFactory; public class StrategyDPtest { public static void main(String[] args) { Flipkart fpkt=null; fpkt=FlipkartFactory.getInstant("EcomExp"); System.out.println(fpkt.getInstant(new String[] {"Tv","Refrigetor","WashingMachine"}, new float[] {25000,15000,20000})); } }
Python
UTF-8
4,550
2.78125
3
[ "MIT" ]
permissive
import os import sys from pathlib import Path from sys import stderr from typing import Any, Optional, Tuple import numpy as np from numba import jit from numpy import float64 as f64 from numpy import ndarray class ConvergenceError(Exception): def __init__(self, *args: object) -> None: super().__init__(*args) def res(path: Path) -> str: return str(path.absolute().resolve()) def eprint(*args: Any, **kwargs: Any) -> None: print(*args, file=stderr, **kwargs) def log(label: str, var: Any) -> None: eprint(f"{label}: {var}") # https://stackoverflow.com/a/42913743 def is_symmetric(a: ndarray, rtol: float = 1e-05, atol: float = 1e-08) -> bool: return bool(np.allclose(a, a.T, rtol=rtol, atol=atol)) # def make_cheaty_nii(orig: Nifti1Image, array: ndarray) -> Nifti1Image: # """clone the header and extraneous info from `orig` and data in `array` # into a new Nifti1Image object, for plotting # """ # affine = orig.affine # header = orig.header # return nib.Nifti1Image(dataobj=array, affine=affine, header=header) def mkdirp(path: Path) -> None: try: os.makedirs(path, exist_ok=True) except Exception as e: print( f"Error making directory {path}. Another program may have modified the file " "while this script was running.", file=sys.stderr, ) print("Original error:", file=sys.stderr) raise e def make_directory(path: Path) -> Path: if not os.path.exists(path): try: os.makedirs(path) return path except Exception as e: print( f"Error making directory {path}. Another program likely " "modified it while this script was running.", file=sys.stderr, ) print("Original error:", file=sys.stderr) raise e else: return path def make_parent_directories(path: Path) -> None: path = path.absolute() paths = [] for folder in path.parents: if folder != Path.home(): paths.append(folder) else: break paths.reverse() for path in paths: make_directory(path) @jit(nopython=True) def kahan_add(current_sum: f64, update: f64, carry_over: f64) -> Tuple[f64, f64]: """ Returns ------- updated_sum: float Updated sum. carry_over: float Carried-over value (often named "c") in pseudo-code. """ remainder = update - carry_over lossy = current_sum + remainder c = (lossy - current_sum) - remainder updated_sum = lossy return updated_sum, c @jit(nopython=True, fastmath=True) def nd_find(arr: ndarray, value: Any) -> Optional[int]: for i, val in np.ndenumerate(arr): if val == value: return i # type: ignore return None @jit(nopython=True) def find_first(arr: ndarray, value: Any) -> int: for i, val in enumerate(arr): if val == value: return i # type: ignore return -1 @jit(nopython=True) def find_last(arr: ndarray, value: Any) -> int: for i in range(len(arr)): j = len(arr) - i - 1 if arr[j] == value: return j # type: ignore return -1 def flatten_4D(img4D: ndarray) -> np.ndarray: if isinstance(img4D, ndarray): return img4D.reshape((np.prod(img4D.shape[0:-1]),) + (img4D.shape[-1],)) @jit(nopython=True, fastmath=True) def slope(x: ndarray, y: ndarray) -> np.float64: x_mean = np.mean(x) y_mean = np.mean(y) x_dev = x - x_mean y_dev = y - y_mean cov = np.sum(x_dev * y_dev) var = np.sum(x_dev * x_dev) if var == 0: return np.float64(0.0) return np.float64(cov / var) @jit(nopython=True, fastmath=True) def variance(arr: ndarray) -> np.float64: """i.e. s^2""" n = len(arr) scale = 1.0 / (n - 1.0) mean = np.mean(arr) diffs = arr - mean squares = diffs ** 2 summed = np.sum(squares) return np.float64(scale * summed) @jit(nopython=True, fastmath=True) def intercept(x: ndarray, y: ndarray, slope: np.float64) -> np.float64: return np.float64(np.mean(y) - slope * np.mean(x)) @jit(nopython=True, fastmath=True) def fast_r(x: ndarray, y: ndarray) -> np.float64: n = len(x) num = x * y - n * np.mean(x) * np.mean(y) denom = (n - 1) * np.sqrt(variance(x)) * np.sqrt(variance(y)) if denom == 0: return np.float64(0.0) return np.float64(num / denom) # termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
Java
UTF-8
1,726
3.21875
3
[]
no_license
/** * Project: A00973569Lab2 * File: PlayerReport.java * Date: May 2, 2016 * Time: 9:16:26 PM */ package a00973569.lab2.report; import a00973569.lab2.data.Player; /** * PlayerReport class prints out Player details in a certain * format and spaces out each column to align with the headers * * @author Ronnie Manimtim, A00973569 * @version 2.0 */ public class PlayerReport { private static final int INDEX_ZERO = 0; /** * Default constructor */ public PlayerReport() { super(); } /** * Method prints out the player details * * @param players * details that are given */ public void printReport(final Player[] players) { System.out.println("Player Report"); System.out.println("----------------------------------------------------------------------------------"); System.out.println(" #. ID First name Last name Email Gamertag"); System.out.println("----------------------------------------------------------------------------------"); for (int i = INDEX_ZERO; i < players.length; i++) { final int listNumber = players[i].getListNumber(); final int id = players[i].getId(); final String firstName = players[i].getFirstName(); final String lastName = players[i].getLastName(); final String email = players[i].getEmailAddress(); final String gamerTag = players[i].getGamerTag(); System.out.format("%3d. %06d %-15s %-15s %-25s %-20s%n", listNumber, id, firstName, lastName, email, gamerTag); // System.out.println(listNumber + ". " + String.format("%06d", id) + " " + String.format("%-15s", firstName) + " " + String.format("%-15s", lastName) + " " // + String.format("%-25s", email) + " " + gamerTag); } } }
Python
UTF-8
2,040
2.515625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Oct 9 12:38:22 2020 @author: Fabian """ import uuid import csv from LatLon23 import LatLon, Longitude, Latitude, string2latlon import pyproj with open('file.xml', 'w') as f: print("<?xml version=\"1.0\"?>\n<FSData version=\"9.0\">", file=f) f.close() with open('Bergnamen.cup', newline='', encoding="ANSI") as csvfile: spamreader = csv.reader(csvfile, delimiter=',') for row in spamreader: if ("name" != row[0]) and ("-----Related Tasks-----" != row[0]): #print(', '.join(row)) print(row[0]) #Name print(row[3]) #Lat DDMM.MMM print(row[4]) #Long DDDMM.MMM print(row[5]) #Height m print(str(uuid.uuid1())) latdeg = row[3][:2] print(latdeg) latmin = row[3][2:].replace('N', '') print(latmin) longdeg = row[4][:3] print(longdeg) longmin = row[4][3:].replace('E', '') print(longmin) latlonobj = LatLon(Latitude(degree = latdeg, minute =latmin),Longitude(degree = longdeg, minute = longmin)) print(latlonobj.to_string('D')) # Print coordinates to degree minute second lat = str(latlonobj.lat) long = str(latlonobj.lon) alt = float(row[5].replace('m', ''))*0.1 alt = str(alt) newline = " <LandmarkLocation instanceId=\"{" + str(uuid.uuid1()) + "}\" type=\"POI\" name=\"" + row[0] + "\" lat=\"" + lat + "\" lon=\"" + long + "\" alt=\"" + alt + "\"/>" with open('file.xml','a') as f: print(newline, file=f) f.close() with open('file.xml', 'a') as f: print("</FSData>", file=f) f.close() """ <?xml version="1.0"?> <FSData version="9.0"> <LandmarkLocation instanceId="{CD544AFF-EF0D-4398-BA1F-5510298690E2}" type="POI" name="Zugspitzetest" lat="47.42111976520967" lon="10.98492037240454" alt="2913.99726566113532"/> </FSData> """
Ruby
UTF-8
414
3.46875
3
[]
no_license
# raw_data = $stdin.readlines().map { |data| data.chomp.to_i } # number_of_test_case = raw_data[0] # test_cases = raw_data[1..-1] def add_digits(number) total = 0 number.to_s.split("").each do |n| total += n.to_i end if total.to_s.length > 1 div_by_3(@total) end total end def div_by_3(number) if add_digits(number) % 3 == 0 puts true end end div_by_3(39999)
Markdown
UTF-8
4,706
3.265625
3
[]
no_license
# Instructions for the Re-Exam To pass the course, you have to prepare a software project and a written report on it. Everything has to be uploaded as a single zip file containing the following: - `report.pdf`: this is the written report. - `code`: a directory containing all source code of the software project. Detailed instructions on the two items are given below. ## Hand-in An assignment will be opened on Blackboard for handing in the project. The deadline for uploading the project on Blackboard will be: 19 June 2016 at midnight. ## Report The report must be written in English and be at the most 3 page long. Use 1.5 line spacing and ensure that the page margins are at least of 2cm (in all directions). For the body text, use Times new roman as family and at least 11pt as font size. In the first page, you must state the name of the course, your name, your e-mail address, and the date (in which you last edited the document). The report must contain the following sections: - Methodology. Here you explain how you designed your software. Give a brief overview of how it works and then focus on how you handle concurrency. For example, did you use futures, executors, manual control over threads, and/or monitors? How did you use them? - Advantages. Here you explain the nice points of your implementation, i.e., the advantages that come out of your design choices. - Limitations. Here you explain the limitations of your approach and, possibly, how they could be overcome. Did you sacrifice performance for achieving better readability of your code? Or, did you sacrifice readability for improving efficiency? Is there a way to improve how you coordinate concurrent computation? Inspiration points to discuss advantages and limitations: - Readability - Speed - Memory consumption - Reusability (the code can be reused in different contexts) - Scalability (scales well with the number of cores, or amount of memory) - Reliability (handling of errors/exceptions) ## Software project The `code` subdirectory in the zip file must contain a `numfinder` subdirectory that implements the `NumFinder` class found in this directory (see `NumFinder` in the subdirectory `numfinder/src/cp`). To be sure that you are getting the class names and method signatures right, copy the `numfinder` subdirectory from this repository and start from there. Concretely, you must implement the methods `findAll`, `findAny` and `stats` in class `NumFinder`. The class contains documentation about what these methods are supposed to do. I suggest that you use the [NetBeans IDE](https://netbeans.org/) to develop the project. The easiest way is to follow the steps below: - Open the project `numfinder` that you have just copied in your filesystem. - Edit method `main` in class `Main` to test the methods you have implemented in `NumFinder`. Your code in `Main.main` will be completely disregarded in the evaluation. Only the implementation of `NumFinder` will be evaluated. Using NetBeans is an easy way to ensure that I will be able to compile your code correctly. If the code does not compile the exam is automatically failed, so make sure that it does! # Frequently Asked Questions and Comments - What version of NetBeans should we use? Use at least version 8. - The project will be tested using Java 8. - Only text files should be looked into. A text file is a file ending with the `.txt` suffix. - Including external libraries is forbidden. You can only use the Java standard library. - Be careful: when I measure the time it takes your method calls to terminate, having threads that have not terminated may slow down the measurement. - How do I traverse directories? There are different ways to traverse directories in Java. See: [http://www.adam-bien.com/roller/abien/entry/listing_directory_contents_with_jdk](http://www.adam-bien.com/roller/abien/entry/listing_directory_contents_with_jdk) and [https://docs.oracle.com/javase/tutorial/essential/io/walk.html](https://docs.oracle.com/javase/tutorial/essential/io/walk.html). There is no "best" way for the project, since maybe one way will play nicer than the others with how you intend to program concurrency. You can also see the (simple!) example in `lectures`. - What about the storage? I will use an SSD for testing the projects. - What encoding will the files be in? UTF-8. I will not use any weird characters that require thinking of more than a Java `char`. I do not recommend using byte representations of strings. - How do I de-activate CPU cores in Linux? See [http://www.cyberciti.biz/faq/debian-rhel-centos-redhat-suse-hotplug-cpu/](http://www.cyberciti.biz/faq/debian-rhel-centos-redhat-suse-hotplug-cpu/).
Java
UTF-8
939
2.5
2
[]
no_license
package com.salutation.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * Created by khayapro on 2016/06/21 */ @Entity public class Attendee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String title; private String companyName; /** * Default constructor */ public Attendee(){ super(); } public Attendee(final String name, final String title, final String companyName){ this.name = name; this.title = title; this.companyName = companyName; } public Long getId() { return id; } public String getName() { return name; } public String getTitle() { return title; } public String getCompanyName() { return companyName; } }
Java
UTF-8
1,427
2.515625
3
[]
no_license
package eu.ase.proiect.util; import java.util.HashMap; import java.util.Map; import eu.ase.proiect.database.model.Book; public class User { private int idUser; private String email; private String username; private String password; // 0 - barbat, 1 -feminin private String sex; public static Map<Long, Book> mapFavoriteBook= new HashMap<Long, Book>(); public static Map<Integer,Book> mapBookRead = new HashMap<Integer, Book>(); public User(int idUser, String email, String username, String password, String sex) { this.idUser = idUser; this.email = email; this.username = username; this.password = password; this.sex = sex; } public int getIdUser() { return idUser; } public void setIdUser(int idUser) { this.idUser = idUser; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
C++
UTF-8
816
2.796875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; vector<vector<int>> g; vector<int> value; vector<bool> visited; void dfsMax(int u, int &c) { visited[u] = true; c += value[u]; int t = c; for (auto i : g[u]) { if (!visited[i]) { dfsMax(i, c); c = max(c, t); } } } int main(int argc, char const *argv[]) { int n, k, u, v; cin >> n >> k; g = vector<vector<int>>(n + 1); value = vector<int>(n + 1); for (int i = 1; i < n; i++) { cin >> u >> v; g[u].emplace_back(v); g[v].emplace_back(u); } for (int i = 1; i <= n; i++) { cin >> value[i]; } visited = vector<bool>(n + 1, false); int re = 0; dfsMax(1, re); cout << max(re + k, k); return 0; }
Java
UTF-8
633
2.0625
2
[ "MIT" ]
permissive
package test; import org.junit.experimental.categories.Category; import test.categories.Integration; /** * @author mikegarts * Learning test to get famliar with the project */ @Category({Integration.class}) public class TestLearning extends TestCommon { final static boolean REAL_CRYPTO_OPS = true; @Override protected boolean useSecureOps() { return REAL_CRYPTO_OPS; } @Override protected CodeDescription getCodeDescription() { return new CodeDescription( "/testLearning/learning-asm.txt", null, null, "/testLearning/big-mul-right-data.txt", "/testLearning/learning-result.txt" ); } }
Markdown
UTF-8
7,456
3.15625
3
[]
no_license
分布式锁概述: 在多线程的环境下,为了保证一个代码块在同一时间只能由一个线程访问,Java中我们一般可以使用synchronized语法和ReetrantLock去保证,这实际上是本地锁的方式。但是现在公司都是流行分布式架构,在分布式环境下,如何保证不同节点的线程同步执行呢? 实际上,对于分布式场景,我们可以使用分布式锁,它是控制分布式系统之间互斥访问共享资源的一种方式。 比如说在一个分布式系统中,多台机器上部署了多个服务,当客户端一个用户发起一个数据插入请求时,如果没有分布式锁机制保证,那么那多台机器上的多个服务可能进行并发插入操作,导致数据重复插入,对于某些不允许有多余数据的业务来说,这就会造成问题。而分布式锁机制就是为了解决类似这类问题,保证多个服务之间互斥的访问共享资源,如果一个服务抢占了分布式锁,其他服务没获取到锁,就不进行后续操作。大致意思如下图所示(不一定准确): ![](../../img/redisLock.png) 分布式锁的特点 分布式锁一般有如下的特点: - 互斥性: 同一时刻只能有一个线程持有锁 - 可重入性: 同一节点上的同一个线程如果获取了锁之后能够再次获取锁 - 锁超时:和J.U.C中的锁一样支持锁超时,防止死锁 - 高性能和高可用: 加锁和解锁需要高效,同时也需要保证高可用,防止分布式锁失效 - 具备阻塞和非阻塞性:能够及时从阻塞状态中被唤醒 分布式锁的实现方式 我们一般实现分布式锁有以下几种方式: - 基于数据库 - 基于Redis - 基于zookeeper 本篇文章主要介绍基于Redis如何实现分布式锁 Redis的分布式锁实现 1 . 利用setnx+expire命令 (错误的做法) Redis的SETNX命令,setnx key value,将key设置为value,当键不存在时,才能成功,若键存在,什么也不做,成功返回1, 失败返回0 。 SETNX实际上就是SET IF NOT Exists的缩写 因为分布式锁还需要超时机制,所以我们利用expire命令来设置,所以利用setnx+expire命令的核心代码如下: ``` public boolean tryLock(String key,String requset,int timeout) { Long result = jedis.setnx(key, requset); // result = 1时,设置成功,否则设置失败 if (result == 1L) { return jedis.expire(key, timeout) == 1L; } else { return false; } } ``` 实际上上面的步骤是有问题的,setnx和expire是分开的两步操作,**不具有原子性**,如果执行完第一条指令应用异常或者重启了,锁将无法过期。 一种改善方案就是使用Lua脚本来保证原子性(包含setnx和expire两条指令) 2 . 使用Lua脚本(包含setnx和expire两条指令) 代码如下: ``` public boolean tryLock_with_lua(String key, String UniqueId, int seconds) { String lua_scripts = "if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then" + "redis.call('expire',KEYS[1],ARGV[2]) return 1 else return 0 end"; List<String> keys = new ArrayList<>(); List<String> values = new ArrayList<>(); keys.add(key); values.add(UniqueId); values.add(String.valueOf(seconds)); Object result = jedis.eval(lua_scripts, keys, values); //判断是否成功 return result.equals(1L); } ``` 3 . 使用 set key value [EX seconds][PX milliseconds][NX|XX] 命令 (正确做法) Redis在 2.6.12 版本开始,为 SET 命令增加一系列选项: ``` SET key value[EX seconds][PX milliseconds][NX|XX] ``` EX seconds: 设定过期时间,单位为秒 PX milliseconds: 设定过期时间,单位为毫秒 NX: 仅当key不存在时设置值 XX: 仅当key存在时设置值 set命令的nx选项,就等同于setnx命令,代码过程如下: ``` public boolean tryLock_with_set(String key, String UniqueId, int seconds) { return "OK".equals(jedis.set(key, UniqueId, "NX", "EX", seconds)); } ``` value必须要具有唯一性,我们可以用UUID来做,设置随机字符串保证唯一性,至于为什么要保证唯一性? 假如value不是随机字符串,而是一个固定值,那么就可能存在下面的问题: 1.客户端1获取锁成功 2.客户端1在某个操作上阻塞了太长时间 3.设置的key过期了,锁自动释放了 4.客户端2获取到了对应同一个资源的锁 5.客户端1从阻塞中恢复过来,因为value值一样,所以执行释放锁操作时就会释放掉客户端2持有的锁,这样就会造成问题 所以通常来说,在释放锁时,我们需要对value进行验证 释放锁的实现 释放锁时需要验证value值,也就是说我们在获取锁的时候需要设置一个value, 不能直接用del key这种粗暴的方式,因为直接del key任何客户端都可以进行解锁了, 所以解锁时,我们需要判断锁是否是自己的,基于value值来判断,代码如下: ``` public boolean releaseLock_with_lua(String key,String value) { String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + "return redis.call('del',KEYS[1]) else return 0 end"; return jedis.eval(luaScript, Collections.singletonList(key), Collections.singletonList(value)).equals(1L); } ``` 这里使用Lua脚本的方式,尽量保证原子性。 使用 set key value [EX seconds][PX milliseconds][NX|XX] 命令 看上去很OK, 实际上在Redis集群的时候也会出现问题,比如说A客户端在Redis的master节点上拿到了锁, 但是这个加锁的key还没有同步到slave节点,master故障,发生故障转移, 一个slave节点升级为master节点,B客户端也可以获取同个key的锁, 但客户端A也已经拿到锁了,这就导致多个客户端都拿到锁。 4 . Redlock算法 与 Redisson 实现 假设有5个独立的Redis节点(注意这里的节点可以是5个Redis单master实例,也可以是5个Redis Cluster集群, 但并不是有5个主节点的cluster集群): - 获取当前Unix时间,以毫秒为单位 - 依次尝试从5个实例,使用相同的key和具有唯一性的value(例如UUID)获取锁,当向Redis请求获取锁时, 客户端应该设置一个网络连接和响应超时时间,这个超时时间应用小于锁的失效时间, 例如你的锁自动失效时间为10s,则超时时间应该在5~50毫秒之间,这样可以避免服务器端Redis已经挂掉的情况下, 客户端还在死死地等待响应结果。如果服务端没有在规定时间内响应,客户端应该尽快尝试去另外一个Redis实例请求获取锁 - 客户端使用当前时间减去开始获取锁时间(步骤1记录的时间)就得到获取锁使用的时间, 当且仅当从大多数(N/2+1,这里是3个节点)的Redis节点都取到锁,并且使用的时间小于锁失败时间时,锁才算获取成功。 - 如果取到了锁,key的真正有效时间等于有效时间减去获取锁所使用的时间(步骤3计算的结果) - 如果某些原因,获取锁失败(没有在至少N/2+1个Redis实例取到锁或者取锁时间已经超过了有效时间), 客户端应该在所有的Redis实例上进行解锁(即便某些Redis实例根本就没有加锁成功, 防止某些节点获取到锁但是客户端没有得到响应而导致接下来的一段时间不能被重新获取锁)
Java
UTF-8
4,240
1.976563
2
[]
no_license
package com.github.wxiaoqi.security.jinmao.controller.web; import com.github.wxiaoqi.security.auth.client.annotation.CheckClientToken; import com.github.wxiaoqi.security.auth.client.annotation.CheckUserToken; import com.github.wxiaoqi.security.common.msg.ObjectRestResponse; import com.github.wxiaoqi.security.common.msg.TableResultResponse; import com.github.wxiaoqi.security.common.util.StringUtils; import com.github.wxiaoqi.security.jinmao.biz.BizSubscribeBiz; import com.github.wxiaoqi.security.jinmao.entity.BizSubscribe; import com.github.wxiaoqi.security.jinmao.feign.NoticeFeign; import com.github.wxiaoqi.security.jinmao.mapper.BizSubscribeMapper; import com.github.wxiaoqi.security.jinmao.vo.order.SubExcel; import com.github.wxiaoqi.security.jinmao.vo.propertybill.UserBillVo; import io.swagger.annotations.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("web/propertyBill") @CheckClientToken @CheckUserToken @Api(tags="物业缴费") public class UserBillAppController { @Autowired private BizSubscribeBiz bizSubscribeBiz; @Autowired private NoticeFeign noticeFeign; @Autowired private BizSubscribeMapper bizSubscribeMapper; @RequestMapping(value = "/getPropertyBillList" ,method = RequestMethod.GET) @ResponseBody @ApiOperation(value = "获取物业账单列表---web端", notes = "获取物业账单列表---web端",httpMethod = "GET") @ApiImplicitParams({ @ApiImplicitParam(name="projectId",value="项目ID",dataType="String",paramType = "query",example="1sdsgsfdghsfdgsd"), @ApiImplicitParam(name="subStatus",value="缴费状态(0-已下单、1-处理中、2-待支付、3-已取消、4-已完成、5-待确认、6-退款中、7-退款完成)",dataType="String",paramType = "query",example="1"), @ApiImplicitParam(name="searchVal",value="根据编码、账单名称,客户名称,联系方式模糊查询",dataType="String",paramType = "query",example="1sdsgsfdghsfdgsd"), @ApiImplicitParam(name="page",value="当前页码",dataType="Integer",paramType = "query",example="4"), @ApiImplicitParam(name="limit",value="每页条数",dataType="Integer",paramType = "query",example="1sdsgsfdghsfdgsd") }) public TableResultResponse getPropertyBillList(String projectId,String subStatus,String syncStatus,String searchVal, Integer page, Integer limit) { List<UserBillVo> propertyBillList = bizSubscribeBiz.getPropertyBillList(projectId, subStatus, syncStatus,searchVal, page, limit); int count = bizSubscribeBiz.getPropertyBillCount(projectId, subStatus, searchVal); return new TableResultResponse(count,propertyBillList); } @RequestMapping(value = "/getPropertyBillDetail",method = RequestMethod.GET) @ApiOperation(value = "获取物业账单详情---web端", notes = "获取物业账单详情---web端",httpMethod = "GET") @ApiImplicitParam(name="id",value="账单ID",dataType="String",required = true ,paramType = "query",example="") public ObjectRestResponse getPropertyBillList(String id) { ObjectRestResponse response = new ObjectRestResponse(); if (StringUtils.isEmpty(id)) { response.setStatus(101); response.setMessage("id不能为空!"); return response; } return bizSubscribeBiz.getPropertyDetailById(id); } @RequestMapping(value = "/getProSubExcel" ,method = RequestMethod.POST) @ResponseBody @ApiOperation(value = "导出物业订单Excel---web端", notes = "导出物业订单Excel---web端",httpMethod = "POST") public ObjectRestResponse getProSubExcel(@RequestBody @ApiParam SubExcel subExcel) throws Exception { return bizSubscribeBiz.getSubExcel(subExcel.getProjectId(), subExcel.getSubStatus(), subExcel.getSyncStatus(),subExcel.getSearchVal(),null, null); } @RequestMapping(value = "/sycPropertyToCrm", method = RequestMethod.POST) @ResponseBody public ObjectRestResponse sycPropertyToCrm(@RequestBody @ApiParam BizSubscribe bizSubscribe) { return noticeFeign.syncPropertyToCrm(bizSubscribe); } }
JavaScript
UTF-8
900
2.765625
3
[]
no_license
/** * @author user */ // upload JPEG files function UploadFile(file) { var xhr = new XMLHttpRequest(); if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) { // create progress bar var o = $id("progress"); var progress = o.appendChild(document.createElement("p")); progress.appendChild(document.createTextNode("upload " + file.name)); // progress bar xhr.upload.addEventListener("progress", function(e) { var pc = parseInt(100 - (e.loaded / e.total * 100)); progress.style.backgroundPosition = pc + "% 0"; }, false); // file received/failed xhr.onreadystatechange = function(e) { if (xhr.readyState == 4) { progress.className = (xhr.status == 200 ? "success" : "failure"); } }; // start upload xhr.open("POST", $id("upload").action, true); xhr.setRequestHeader("X-FILENAME", file.name); xhr.send(file); } }
Python
UTF-8
1,244
2.578125
3
[]
no_license
from exts import db from datetime import datetime class User(db.Model): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(50), nullable=False) password = db.Column(db.String(100), nullable=False) class Reporter(db.Model): __tablename__ = "Reporter" id = db.Column(db.Integer,primary_key=True,autoincrement=True) title= db.Column(db.String(100),nullable=False) content =db.Column(db.Text,nullable=False) create_time=db.Column(db.DateTime,default=datetime.now)#不加括号是调用函数 加了括号是调用值 author_id=db.Column(db.Integer,db.ForeignKey('user.id')) author=db.relationship('User',backref=db.backref('reporters')) class Comment(db.Model): __tablename__="Comment" id =db.Column(db.Integer,primary_key=True,autoincrement=True) content=db.Column(db.Text,nullable=False) comment_time=db.Column(db.DateTime,default=datetime.now) reporter_id=db.Column(db.Integer,db.ForeignKey('Reporter.id')) author_id=db.Column(db.Integer,db.ForeignKey('user.id')) reporter=db.relationship('Reporter',backref=db.backref('comments')) author = db.relationship('User', backref=db.backref('comments'))
Markdown
UTF-8
4,297
2.546875
3
[ "NTP", "RSA-MD", "LicenseRef-scancode-pcre", "Apache-2.0", "MIT", "LicenseRef-scancode-rsa-1990", "Beerware", "LicenseRef-scancode-other-permissive", "Spencer-94", "BSD-3-Clause", "LicenseRef-scancode-rsa-md4", "metamail", "HPND-sell-variant", "LicenseRef-scancode-zeusbench" ]
permissive
# Introduction From **release 6.7** we have the possibility to pre-process the site descriptor file before execute it to coordinate its deployment. Such processor (or _template engine_) can be plugged into processing using a module (i.e. _java library_) containing processor implementation that is published using [Java Service Provide Interface (SPI)](https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html) specification. ## Site processor usage ### Configure a site processor To plug a **markdown processor** you have to declare library **as plugin's dependency**. > Currently a processor based on [Freemarker](https://freemarker.apache.org/) template engine is already available trought the module **maven-confluence-processor-freemarker** #### Example below declare freemarker as site processor ```xml <plugin> <groupId>org.bsc.maven</groupId> <artifactId>confluence-reporting-maven-plugin</artifactId> <version>${confluence.plugin.version}</version> <dependencies> <!-- Plug the freemarker processor --> <dependency> <groupId>org.bsc.maven</groupId> <artifactId>maven-confluence-processor-freemarker</artifactId> <version>${confluence.plugin.version}</version> <scope>runtime</scope> </dependency> <configuration> <wikiFilesExt>.confluence</wikiFilesExt> <siteDescriptor>${basedir}/src/site/confluence/site_to_process.yml</siteDescriptor> <failOnError>true</failOnError> </configuration> </dependencies> </plugin> ``` ### Use the markup language in site definition After declared a site processor in plugin's configuration we can start to use the related markup language in site's definition #### Example below use freemarker markup language in site definition ```yaml #freemaker home: name: "issue202" uri: issue202.md attachments: <#if Files.exists(Paths.get(project.basedir, 'src/site/confluence/issue202/images/dashboard.png')) == true> - name: "dashboard.png" uri: images/dashboard.png contentType: "image/png" version: 1 comment: image </#if> <#if Files.exists(Paths.get(project.basedir, 'src/site/confluence/issue202/images/unknown.png')) == true> - name: "unknown.png" uri: images/dashboard.png contentType: "image/png" version: 1 comment: unknown image </#if> ``` ## Implement a new 'site processor' service To implement a new **site processor service** we have to follow steps below: ### 1. Create a new Project Create a simple java library project maven compliant ### 2. Add dependency to **maven-confluence-core** module ```xml <dependency> <groupId>org.bsc.maven</groupId> <artifactId>maven-confluence-core</artifactId> <version>${version}</version> </dependency> ``` ### 3. Implement the interface `org.bsc.preprocessor.SiteProcessorService` ```java public interface SiteProcessorService { /** * name of Preprocessor service * */ String getName(); /** * Handles preprocessing of the input using a markup library * * Variables are added to the markup model */ CompletableFuture<String> process(String input, Map<String, Object> variables); } ``` ### 4. Publish implementation following [SPI](https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html) specification The [SPI](https://docs.oracle.com/javase/tutorial/sound/SPI-intro.html) specification **publish a service creating a mapping file a mapping file in a specially named directory `META-INF/services`**. The name of the file is the name of the SPI class being subclassed, and the file contains the names of the new subclasses of that SPI abstract class (see documentation for more details). #### META-INF/services generator However there is a great library that extremely simplify publishing of SPI service named [META-INF/services generator](http://metainf-services.kohsuke.org/) that use behind the scene a **java annotation processor** that automatically generates the required mapping file using a java annotation `@MetaInfServices` as shown below ```java @MetaInfServices(SiteProcessorService.class) public class PreprocessorImpl implements SiteProcessorService { } ```
Python
UTF-8
199
3.03125
3
[]
no_license
n = int(input()) a = list(map(int, input().split())) m = 10 ** 9 for i in range(n): s = 0 for j in range(n): s += (abs(i - j) + j + i) * 2 * a[j] if s < m: m = s print(m)
Java
UTF-8
984
2.359375
2
[]
no_license
import java.util.ArrayList; interface ViewInterface { // 初期データ読み込み完了メソッド public void successStart(); // 更新データ再読み込み完了メソッド public void successRestart(); // 推論順に探索結果返却メソッド public ArrayList<StepResult> showStepResult(ArrayList<StepResult> stepresults); // 検索探索結果返却メソッド public ArrayList<ArrayList<SearchStep>> showSearchAssertion(ArrayList<ArrayList<SearchStep>> resultList); // ルール追加完了メソッド public void successAddRule(boolean result); // ルール削除完了メソッド public void successDeleteRule(boolean result); // ルール編集完了メソッド public void successUpdateRule(boolean result); //一覧表示メソッド public ArrayList<Rule> showRuleList(ArrayList<Rule> resultList); // 例外処理表示メソッド public void showError(String errorText); }
Go
UTF-8
2,452
2.546875
3
[ "MIT" ]
permissive
package showname import ( "context" "log" "github.com/jmoiron/sqlx" "github.com/opentracing/opentracing-go" "go.uber.org/zap" jaegerLog "showname/pkg/log" "showname/pkg/tracing" ) type ( // Data ... Data struct { mysql *sqlx.DB stmtMySQL map[string]*sqlx.Stmt tracer opentracing.Tracer logger jaegerLog.Factory } // statement ... statement struct { key string query string } ) const ( // MySQL Statement // updateStockSuccess = "UpdateStockSuccess" // qUpdateStockSuccess = `INSERT INTO reporting_crawling.download_stock_ecommerce (OutletID, EcommerceID, EcommerceProductID, ProductID, Stock, Price, Stock_OldDown, DownloadDate) VALUES (?, 0, '000', ?, ?, 0, 0, NOW())ON DUPLICATE KEY UPDATE Stock = VALUES(Stock), Price = VALUES(Price), Stock_OldDown = VALUES(Stock_OldDown), DownloadDate = NOW()` ) var ( readStmtMySQL = []statement{ // {updateStockSuccess, qUpdateStockSuccess}, } ) // New ... func New(mysql *sqlx.DB, logger jaegerLog.Factory) Data { d := Data{ mysql: mysql, logger: logger, } d.initTracer() d.initStmt() return d } func (d *Data) initTracer() { tracer, _ := tracing.Init("mysql", d.logger) d.tracer = tracer } func (d *Data) initStmt() { var ( err error stmtsMySQL = make(map[string]*sqlx.Stmt) ) for _, v := range readStmtMySQL { stmtsMySQL[v.key], err = d.mysql.PreparexContext(context.Background(), v.query) if err != nil { log.Fatalf("[DB] Failed to initialize statement key %v, err : %v", v.key, err) } } d.stmtMySQL = stmtsMySQL } // GetShowname ... func (d Data) GetShowname(ctx context.Context, movieID string) (string, error) { var ( showname string err error ) // Check if have span on context if span := opentracing.SpanFromContext(ctx); span != nil { span := d.tracer.StartSpan("SQL SELECT", opentracing.ChildOf(span.Context())) span.SetTag("mysql.server", "123.72.156.4") span.SetTag("mysql.database", "movie") span.SetTag("mysql.table", "showname") span.SetTag("mysql.query", "SELECT * FROM movie.showname WHERE movie_id="+movieID) defer span.Finish() ctx = opentracing.ContextWithSpan(ctx, span) } // assumed data fetched from database showname = "Joni Bizarre Adventure" d.logger.For(ctx).Info("SQL Query Success", zap.String("showname", showname)) // case if err // if err != nil { // d.logger.For(ctx).Error("SQL Query Failed", zap.Error(err)) // return showname, err // } return showname, err }
Markdown
UTF-8
2,501
3.515625
4
[]
no_license
# TIL 200707(Tue) # BOJ 7576 토마토 c++ 백준 7576 토마토 문제 <br> 먼저 X, Y는 pair<int, int>를 위해 define 한다. <br> dx[n] + dy[n] 는 항상 상, 하, 좌, 우 중 하나를 나타낸다. <br> 토마토가 배치된 맵을 담을 board 2차원 배열을 선언하고, 또 거리를 나타낼 dist 2차원 배열을 선언한다. <br> main함수에서는 먼저 board에 값을 채워넣는다. 안 익은 토마토만 넣고, 익은 토마토는 큐에 넣는다. <br> while Q가 비지 않을 때까지 반복하는데, cur에는 Q의 맨 첫 번째 pair를 담는다. <br> nx, ny는 현재 위치의 상, 하, 좌, 우를 반영한 값이다. 그 상하좌우 좌표에 대해 범위를 벗어난 경우와 이미 방문한 경우는 모두 continue 해버리고, 그렇지 않은 경우에 대해 dist[nx][ny]에 현재좌표, 즉 dist[cur.X][cur.Y] + 1을 해준다. <br> 마지막으로 dist배열에 -1이 남아있는 경우, 즉 익지 않은 토마토가 남아 있는 경우 -1을 출력하고, 그런 경우가 없을 때에는 dist배열 중 가장 큰 값이 들어있는 칸의 값을 출력한다. <br> ```c++ c++#include <bits/stdc++.h> using namespace std; # define X first # define Y second int n; int m; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; int board[1002][1002]; int dist[1002][1002]; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> m >> n; queue<pair<int, int>> Q; /*board에 채워넣기*/ int i, j; for (i = 0; i < n; i++){ for (j = 0; j < m; j++){ cin >> board[i][j]; if (board[i][j] == 1) Q.push({i, j}); if (board[i][j] == 0) dist[i][j] = -1; } } int nx; int ny; while (!Q.empty()) { auto cur = Q.front(); Q.pop(); for (int dir = 0; dir < 4; dir++) { nx = cur.X + dx[dir]; ny = cur.Y + dy[dir]; if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; if (dist[nx][ny] >= 0) continue; dist[nx][ny] = dist[cur.X][cur.Y] + 1; Q.push({nx, ny}); } } int ans = 0; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (dist[i][j] == -1) { cout << -1; return 0; } ans = max(dist[i][j], ans); } } cout << ans; } ```