language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 525 | 2.140625 | 2 |
[] |
no_license
|
package br.com.findposto.model;
import java.io.Serializable;
/**
* Created by Fernando on 14/05/2017.
*/
public class TipoServico implements Serializable {
private static final long serialVersionUID = 6601006766832473959L;
public int id;
public Login idLogin;
public String nome;
@Override
public String toString (){
return "TipoServico{" +
"id=" + id +
", login='" + idLogin + '\'' +
", nome='" + nome + '\'' +
'}';
}
}
|
Markdown
|
UTF-8
| 351 | 2.65625 | 3 |
[] |
no_license
|
# npm-flames
An NPM module to calculate flames game relationship, given 2 names.
const flames = require('npm-flames'); const result = flames('name1', 'name2'); console.log(result);
example
const flames = require('npm-flames');
const result = flames('jagadeep', 'chiradep');
console.log(result);
output
Affection
see project file for how to use
|
Java
|
UTF-8
| 5,522 | 2.046875 | 2 |
[] |
no_license
|
package in.jploft.esevak.ui.components.fragments.orderHistory;
import android.annotation.SuppressLint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import in.jploft.esevak.R;
import in.jploft.esevak.databinding.FragmentOrderHistoryBinding;
import in.jploft.esevak.network.ApiResponse;
import in.jploft.esevak.pojo.MyOrdersData;
import in.jploft.esevak.ui.base.BaseFragment;
import in.jploft.esevak.ui.components.activities.home.HomeActivity;
import in.jploft.esevak.ui.components.adapters.OrderHistoryAdapter;
import in.jploft.esevak.utils.Constants;
import in.jploft.esevak.utils.ProgressDialog;
import in.jploft.esevak.utils.Utility;
public class OrderHistoryFragment extends BaseFragment {
private static final String TAG = OrderHistoryFragment.class.getName();
private FragmentOrderHistoryBinding binding;
private OrderHistoryViewModel viewModel;
private View.OnClickListener onClickListener = null;
private HomeActivity homeActivity;
private ArrayList<MyOrdersData.Order> myOrdersData;
private OrderHistoryAdapter orderHistoryAdapter;
@Override
protected ViewDataBinding setBinding(LayoutInflater inflater, ViewGroup container) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_order_history, container, false);
onClickListener = this;
binding.setLifecycleOwner(this);
return binding;
}
@Override
protected void createActivityObject() {
mActivity = (AppCompatActivity) getActivity();
}
@Override
protected void initializeObject() {
myOrdersData = new ArrayList<>();
myOrdersAPI();
}
@Override
public void onResume() {
super.onResume();
Utility.setAppBar(mActivity);
binding.appBar.tvTitle.setText("Order History");
binding.appBar.ivCart.setVisibility(View.GONE);
}
@Override
protected void initializeOnCreateObject() {
homeActivity = (HomeActivity) getActivity();
viewModel = new ViewModelProvider(this).get(OrderHistoryViewModel.class);
viewModel.responseLiveData.observe(this, new Observer<ApiResponse<MyOrdersData>>() {
@Override
public void onChanged(ApiResponse<MyOrdersData> it) {
handleResult(it);
}
});
}
@Override
protected void setListeners() {
binding.appBar.ivBack.setOnClickListener(this);
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.ivBack:
homeActivity.onBackPressed();
break;
}
}
private void myOrdersAPI() {
String userId = sessionManager.getUserData().getId();
if (userId != null && !userId.equals("")) {
HashMap<String, String> reqData = new HashMap<>();
reqData.put("userId", userId);
Log.e(TAG, "Api parameters - " + reqData.toString());
viewModel.myOrdersApi(reqData);
}
}
private void handleResult(ApiResponse<MyOrdersData> result) {
switch (result.getStatus()) {
case ERROR:
ProgressDialog.hideProgressDialog();
Utility.showToastMessageError(mActivity, result.getError().getMessage());
Log.e(TAG, "error - " + result.getError().getMessage());
break;
case LOADING:
ProgressDialog.showProgressDialog(mActivity);
break;
case SUCCESS:
ProgressDialog.hideProgressDialog();
if (result.getData().getStatusCode() == Constants.Success) {
Log.e(TAG, "Response - " + new Gson().toJson(result));
binding.rvOrderHistory.setVisibility(View.VISIBLE);
binding.layoutError.rlerror.setVisibility(View.GONE);
if (result.getData().getData().getOrders() != null && !result.getData().getData().getOrders().isEmpty()) {
binding.rvOrderHistory.setVisibility(View.VISIBLE);
binding.layoutError.rlerror.setVisibility(View.GONE);
myOrdersData.clear();
myOrdersData.addAll(result.getData().getData().getOrders());
if (myOrdersData.size() != 0) {
orderHistoryAdapter = new OrderHistoryAdapter(mActivity, onClickListener, myOrdersData);
binding.rvOrderHistory.setAdapter(orderHistoryAdapter);
}
} else {
binding.rvOrderHistory.setVisibility(View.GONE);
binding.layoutError.rlerror.setVisibility(View.VISIBLE);
}
} else {
binding.rvOrderHistory.setVisibility(View.GONE);
binding.layoutError.rlerror.setVisibility(View.VISIBLE);
}
break;
}
}
@Override
public void onDestroy() {
viewModel.disposeSubscriber();
super.onDestroy();
}
}
|
Python
|
UTF-8
| 6,686 | 2.578125 | 3 |
[] |
no_license
|
import numpy as np
import pandas as pd
import datetime
#Open and read csv's, filter all non-robotic batch numbers from df1 and save as df3
##FUTURE: Try open using relative directory positions not full dir path.
datapath = r"C:\Users\BHSB\Dropbox\Programming\Python\Projects\MolGen\SeqSucess\data"
df1 = pd.read_csv(datapath + '\\seq17_full.csv') #'seqdata_test_5.csv'
df2 = pd.read_csv(datapath + '\\seqbatches17_full.csv') #'seqbatches_test_5.csv'
seqworkno = []
for index, row in df2.iterrows():
if row['SeqNumbers'] not in seqworkno:
seqworkno.append(row['SeqNumbers'])
df3 = df1[df1['Workbatch'].isin(seqworkno)] #Should be just robotic sequencing batches.
#batches with no QQ's
batches_no_qq = []
#batches that have NTC QQ but has failed
batches_failed_ntc = []
batches_passed_ntc = []
#number of batches at start of analysis
#number of batches excluded from analysis due to lack or NTC's and failed NTC's
def find_ntc(batch):
temp_df = df1[df1['Workbatch'] == batch]
qq_dict = {}
for index, row in temp_df.iterrows():
if row['SampleID'].startswith('Q'):
qq_dict.update({index : row['SampleID']})
if len(qq_dict) >= 1:
return max(qq_dict.keys())
elif len(qq_dict) == 0:
batches_no_qq.append(batch)
return "No NTC"
def ntc_passed(batch, index):
if df1.iloc[index]['Result'].startswith("Fail") or df1.iloc[index]['Result'].startswith('#'):
batches_passed_ntc.append(batch)
return True
else:
batches_failed_ntc.append(batch)
return False
def ntc_check(batch):
qq_result = find_ntc(batch)
if qq_result == "No NTC":
return "No NTC"
elif qq_result > 1:
return ntc_passed(batch, qq_result)
for num in seqworkno:
ntc_check(num)
print(batches_no_qq, batches_failed_ntc)
print(len(seqworkno), len(batches_no_qq), len(batches_failed_ntc), len(batches_passed_ntc))
print(len(seqworkno) - len(batches_no_qq) - len(batches_failed_ntc))
test_df = df1[df1['Workbatch'] == 1706190]
test_df.shape
find_ntc(1706190)
def num_sample(batch):
temp_df = df1[df1['Workbatch'] == batch]
return temp_df.shape[0]
def num_fails(batch):
temp_df = df1[df1['Workbatch'] == batch]
count = 0
for index, row in temp_df.iterrows():
if row['Result'].startswith('Fail'):
count += 1
return count
def num_retest(batch):
temp_df = df1[df1['Workbatch'] == batch]
count = 0
for index, row in temp_df.iterrows():
if row['Result'].startswith('#'):
count += 1
return count
num_sample(1706190)
def num_patients(batch):
#Excluding positive controls (QQ's)
temp_df = df1[df1['Workbatch'] == batch]
patient_ids = []
for index, row in temp_df.iterrows():
if row['SampleID'].startswith('EX') and row['SampleID'] not in patient_ids:
patient_ids.append(row['SampleID'])
return patient_ids, len(patient_ids)
def num_controls(batch):
temp_df = df1[df1['Workbatch'] == batch]
qq_ids = []
#if find_ntc(batch) == 1
for index, row in temp_df.iterrows():
if row['SampleID'].startswith('Q') and row['SampleID'] not in qq_ids:
qq_ids.append(row['SampleID'])
return qq_ids, len(qq_ids)
num_patients(1706190)
def unique_pts(batch):
temp_df = df1[df1['Workbatch'] == batch]
unique_pt = []
for index, row in temp_df.iterrows():
if row['SampleID'] not in unique_pt:
unique_pt.append(row['SampleID'])
return unique_pt
def patient_fail(batch):
temp_df = df1[df1['Workbatch'] == batch]
total_pts = num_patients(batch)[0] + num_controls(batch)[0]
total_pts.pop()
fail_count = 0
pass_count = 0
total_fail = 0
patient_fail_count = 0
for sample in total_pts:
pt_df = temp_df[temp_df['SampleID'] == sample]
for index, row in pt_df.iterrows():
if row['Result'].startswith('Fail') or row['Result'].startswith('#'):
fail_count += 1
else:
pass_count += 1
if fail_count == 0:
pass_count = 0
fail_count = 0
elif fail_count / (fail_count + pass_count) >= 0.5:
patient_fail_count += 1
total_fail += fail_count
pass_count = 0
fail_count = 0
else:
pass_count = 0
fail_count = 0
return total_fail, patient_fail_count
if 1700003 in batches_passed_ntc:
print("Yes")
else:
print("No")
def seq_success_rate(batch):
total_samples = num_sample(batch) - 1
total_fails = num_fails(batch) + num_retest(batch)
deduct_fails = patient_fail(batch)[0]
success_rate = ((total_samples - (total_fails - deduct_fails)) / total_samples) * 100
return(total_samples, total_fails, deduct_fails, success_rate)
seq_success_rate(1706190)
#Function to create dataframes to create output csv files
def output1(): #Batches with an NTC that has passed
print("Processing...")
final_data = []
for i, batch in enumerate(batches_passed_ntc):
temp_dict = {"1. SF No." : batch, \
"2. No. Samples" : seq_success_rate(batch)[0], \
"3. No. Fails" : seq_success_rate(batch)[1], \
"4. No. Patient Fails" : patient_fail(batch)[1], \
"5. Removed Fails" : seq_success_rate(batch)[2], \
"6. Success Rate" : seq_success_rate(batch)[3]}
final_data.append(temp_dict)
if i == 210:
print("Data compiling complete")
return final_data
def output2(): #Batches with a failed NTC or no NTC
print("Processing...")
final_data = []
for batch in batches_no_qq:
temp_dict = {"1. SF No." : batch, "2. No. Samples" : num_sample(batch),\
"3. No Fails" : num_fails(batch) + num_retest(batch)}
final_data.append(temp_dict)
for batch in batches_failed_ntc:
temp_dict = {"1. SF No." : batch, "2. No. Samples" : num_sample(batch),\
"3. No Fails" : num_fails(batch) + num_retest(batch)}
final_data.append(temp_dict)
print("Data compiling complete.")
return final_data
def total_avg():
avg_total = 0
for index, row in output1.iterrows():
avg_total += row['6. Success Rate']
print(output1.shape[0])
return (avg_total / output1.shape[0])
output1 = pd.DataFrame(output1())
output2 = pd.DataFrame(output2())
date_now = datetime.datetime.now()
datestamp = str(date_now.year) + str(date_now.month) + str(date_now.day)
output1.to_csv("C:\\Users\\BHSB\\Desktop\\Seq files\\" + "output1_" + datestamp + ".csv")
output2.to_csv("C:\\Users\\BHSB\\Desktop\\Seq files\\" + "output2_" + datestamp + ".csv")
|
Java
|
UTF-8
| 608 | 2 | 2 |
[] |
no_license
|
package com.lankydan.cassandra.movie.repository;
import com.lankydan.cassandra.movie.entity.MovieByGenre;
import com.lankydan.cassandra.movie.entity.MovieByGenreKey;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@Repository
public interface MovieByGenreRepository extends CassandraRepository<MovieByGenre, MovieByGenreKey> {
List<MovieByGenre> findByKeyGenreAndKeyReleaseDateAndKeyMovieId(String genre, LocalDateTime releaseDate, UUID movieId);
}
|
C++
|
UTF-8
| 866 | 2.703125 | 3 |
[] |
no_license
|
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
vector<int> adj[100005];
bool gomgom[100005];
queue<int> q;
int main() {
int N, M;
scanf("%d %d", &N, &M);
for (int m = 0; m < M; m++) {
int u, v;
scanf("%d %d", &u, &v);
adj[u].push_back(v);
}
int S;
scanf("%d", &S);
for (int s = 0; s < S; s++) {
int value;
scanf("%d", &value);
gomgom[value] = true;
}
bool result = false;
q.push(1);
while (!q.empty()) {
int cur = q.front();
q.pop();
if (gomgom[cur]) {
continue;
}
if (adj[cur].empty()) {
result = true;
break;
}
for (int next : adj[cur]) {
q.push(next);
}
}
printf("%s\n", result ? "yes" : "Yes");
return 0;
}
|
Java
|
UTF-8
| 326 | 2.84375 | 3 |
[] |
no_license
|
class CarriageReturn
{
public static void main(String[] args) throws Exception
{
System.out.println("Syed \r Moonis \n Haider \f Abdi");
//Carriage Return will only move the cursor back to the beginning of the current line
for(int i=0;i<=10;i++)
{
System.out.print(i+"\r");
Thread.sleep(250);
}
}
}
|
Java
|
UTF-8
| 1,563 | 2.609375 | 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 br.edu.ifpb.psd.lovymetal.DAO.managers;
import br.edu.ifpb.psd.lovymetal.DAO.DAOFactory;
import br.edu.ifpb.psd.lovymetal.DAO.interfaces.DAOFactoryInter;
import br.edu.ifpb.psd.lovymetal.DAO.interfaces.AmizadeDAOinter;
import br.edu.ifpb.psd.lovymetal.entidades.Amizade;
import javax.persistence.PersistenceException;
/**
*
* @author JuliermeH
*/
public class GerenciadorAmizade {
/* Declarando os respectivos atributos para esta entidade */
private DAOFactoryInter fabrica = null;
private AmizadeDAOinter amizadedao = null;
/* Construtor responsável por criar uma nova Amizade */
public GerenciadorAmizade(){
fabrica = DAOFactory.criarFactory();
try{
amizadedao = fabrica.novaAmizade();
} catch (PersistenceException e){}
}
/* Método responsável por adicionar uma nova Amizade e fazer a persistência no BD */
public boolean novaAmizade(int usuario,int amigo) throws PersistenceException{
Amizade amizade = new Amizade();
amizade.setUsuario(usuario);
amizade.setAmigo(amigo);
return amizadedao.adiciona(amizade);
}
/* Método responsável por remover a Amizade do BD usando o id do usuario e do amigo */
public void removeAmizade(int usuario, int amigo) throws PersistenceException{
amizadedao.desfaz(usuario, amigo);
}
}
|
C++
|
UTF-8
| 601 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
/*
* SortTree.h
* 二叉排序树
* Created on: 2014年5月19日
* Author: Jayin Ton
*/
#ifndef SORTTREE_H_
#define SORTTREE_H_
#include <iostream>
using namespace std;
#ifndef struct_node
#define struct_node
typedef struct _Node {
int data;
_Node *lchild, *rchild;
} Node;
#endif
class SortTree {
public:
SortTree();
virtual ~SortTree();
void add(int data);
void inOrder();
Node* getTree();
private:
Node* root;
void inOrder(Node*);
Node* add(Node* p,int data);
Node* create(int data);
void released(Node* p);
};
#endif /* SORTTREE_H_ */
|
Java
|
UTF-8
| 904 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
/*
* Copyright (c) 2014, Lukas Tenbrink.
* http://lukas.axxim.net
*/
package ivorius.pandorasbox.random;
import java.util.Random;
/**
* Created by lukas on 04.04.14.
*/
public class ValueHelper
{
public static int[] getValueRange(IValue value, Random random)
{
int[] result = new int[2];
int val1 = value.getValue(random);
int val2 = value.getValue(random);
boolean val1F = val1 < val2;
result[0] = val1F ? val1 : val2;
result[1] = val1F ? val2 : val1;
return result;
}
public static double[] getValueRange(DValue value, Random random)
{
double[] result = new double[2];
double val1 = value.getValue(random);
double val2 = value.getValue(random);
boolean val1F = val1 < val2;
result[0] = val1F ? val1 : val2;
result[1] = val1F ? val2 : val1;
return result;
}
}
|
Python
|
UTF-8
| 2,474 | 3.609375 | 4 |
[
"MIT"
] |
permissive
|
import abc
from typing import Callable, Generic, Sequence, Tuple, TypeVar
class State:
def __init__(self, terminal: bool):
self.terminal = terminal
TState = TypeVar("TState", bound=State)
TAction = TypeVar("TAction")
class PSFAEnvironment(abc.ABC, Generic[TState, TAction]):
"""An environment with parametrized states and a finite set of actions (PSFA)
available at each state.
Such an environment does not support enumerating all states, but does allow
enumerating possible actions.
"""
@property
@abc.abstractmethod
def state(self) -> TState:
pass
@property
def terminated(self) -> bool:
return self.state.terminal
@abc.abstractmethod
def reset(self) -> None:
pass
@abc.abstractmethod
def get_actions(self, state: TState = None) -> Sequence[TAction]:
"""Return an iterable of available actions at state.
If state is not specified, default to the current state.
"""
pass
@abc.abstractmethod
def take_action(self, action: TAction) -> float:
"""Respond to an actor taking an action, returning a reward"""
pass
class PSFAAgent(abc.ABC, Generic[TState, TAction]):
"""A base class for an agent learning in a PSFA environment"""
@abc.abstractmethod
def action(self, state: TState) -> TAction:
pass
def act_and_train(self, t: int) -> Tuple[TState, TAction, float]:
"""Run a single act-and-train step.
Returns the tuple (S_t, A_t, R_{t+1}).
"""
pass
def episode_end(self) -> None:
pass
def train(
env: PSFAEnvironment[TState, TAction],
agent: PSFAAgent[TState, TAction],
n_episodes: int,
episode_length_cap: int,
on_action: Callable[[TState, TAction, float, int], None] = None,
on_episode_end: Callable[[int], None] = None,
) -> None:
"""Trains the agent in its environment.
At the end of each timestep, calls on_action(S_t, A_t, R_{t+1}, t)
At the end of each episode, calls on_episode_end(T)
"""
for ep in range(n_episodes):
t = 0
for step in range(episode_length_cap):
if env.terminated:
break
s, a, r = agent.act_and_train(t) # returns (S_t, A_t, R_t)
if on_action:
on_action(s, a, r, t)
t += 1
agent.episode_end()
if on_episode_end:
on_episode_end(t)
env.reset()
|
PHP
|
UTF-8
| 2,756 | 3.3125 | 3 |
[] |
no_license
|
<?php
//plik z definicjami klas potrzebnymi do projektu
//dane do polaczenia
require('../conection.php');
class User
{
private $id;
private $username;
private $hashPass;
private $email;
public function __construct()
{
$this->id = -1;
$this->username = "";
$this->hashPass = "";
$this->email = "";
}
//SETTERY
public function setUsername($username)
{
$this->username = $username;
}
public function setHashPass($newPass)
{
$newHashedPassword =
password_hash($newPass, PASSWORD_BCRYPT);
$this->hashPass = $newHashedPassword;
}
public function setEmail($email)
{
$this->email = $email;
}
//GETTERY
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function getHashPass()
{
return $this->hashPass;
}
public function getEmail()
{
return $this->email;
}
//METODY
public function saveToDB($conn)
{
//obiekt zapisywany jest do bazy tylko jeżeli jego id jest równe -1 (nowy uzytkownik)
if ($this->id == -1) {
//Saving new user to DB
$sql = "INSERT INTO users(email, username, hash_pass) VALUES (:email, :username, :pass)";
$stmt = $conn->prepare($sql);
$result = $stmt->execute(
[ 'email'=> $this->email, 'username' => $this->username, 'pass' => $this->hashPass ]
);
if ($result !== false) {
//Jeżeli udało się nam zapisać obiekt do bazy to przypisujemy mu klucz główny jako id
$this->id = $conn->lastInsertId();
return true;
}
}
return false;
}
}
//zmienna $conn do testowania metod
try {
$conn = new PDO(
"mysql:host=$host;dbname=$db;charset=UTF8",
$user,
$pass,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]
);
} catch (PDOException $e) {
echo $e->getMessage();
}
/*
testowanie metody saveToDB:
$test = new User();
$test->setUsername('jerzy');
$test->setEmail('jerzy@interia.pl');
$test->setHashPass('smok');
echo $test->getId();
echo '<br>';
echo $test->getUsername();
echo '<br>';
echo $test->getEmail();
echo '<br>';
echo $test->getHashPass();
echo '<br>';
$test->saveToDB($conn);
$test1 = new User();
$test1->setUsername('monika');
$test1->setEmail('monika.nowak@gmail.com');
$test1->setHashPass('smerfetka');
$test1->saveToDB($conn);
$test2 = new User();
$test2->setUsername('ada');
$test2->setEmail('ada@upcpoczta.pl');
$test2->setHashPass('dzidzia');
$test2->saveToDB($conn);
*/
$conn = null;
|
C++
|
UTF-8
| 809 | 3.5625 | 4 |
[] |
no_license
|
/*
* @lc app=leetcode id=172 lang=cpp
*
* [172] Factorial Trailing Zeroes
*/
// 由2和5的数量决定
// 这种复杂度高
class Solution1 {
public:
int trailingZeroes(int n) {
int two=0,five=0;
for (int i = 1; i <= n; i++)
{
int number = i;
while (number%2==0 && number>0)
{
two += 1;
number /= 2;
}
while (number%5==0 && number>0)
{
five += 1;
number /= 5;
}
}
return min(two, five);
}
};
// 受到5个个数限制
class Solution {
public:
int trailingZeroes(int n) {
int ret = 0;
while (n)
{
ret += n/5;
n/=5;
}
return ret;
}
};
|
Java
|
UTF-8
| 1,147 | 2.828125 | 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 moving.logic;
import java.util.ArrayList;
import java.util.List;
import moving.domain.Box;
import moving.domain.Thing;
/**
*
* @author Milos
*/
public class Packer {
private int boxesVolume;
public Packer(int boxesVolume){
this.boxesVolume = boxesVolume;
}
public List<Box> packThings(List<Thing> things) {
List<Box> listBoxes = new ArrayList<Box>();
Box firstBox = new Box(boxesVolume);
boolean lastBox = false;
int i =0;
boolean last = false;
for(Thing t: things){
if(!firstBox.addThing(t)){
listBoxes.add(firstBox);
firstBox = new Box(boxesVolume);
firstBox.addThing(t);
}
else {
if(i == things.size()-1){
listBoxes.add(firstBox);
}
}
i++;
}
return listBoxes;
}
}
|
Python
|
UTF-8
| 1,764 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
"""630. Knight Shortest Path II
"""
DIRECTIONS = [(-1, -2), (1, -2), (-2, -1), (2, -1)]
class Solution:
"""
@param grid: a chessboard included 0 and 1
@return: the shortest path
"""
def shortestPath2(self, grid):
# write your code here
###
m = len(grid)
n = len(grid[0])
dp = [[float('inf')] * n for _ in range(m)]
if grid[0][0] == 0:
dp[0][0] = 0
if grid[-1][-1] == 1 or grid[0][0] == 1:
return -1
for j in range(1, n):
for i in range(m):
if grid[i][j] == 1:
continue
for dx, dy in DIRECTIONS:
x = i + dx
y = j + dy
if not self.isValid(x, y, m, n):
continue
dp[i][j] = min(dp[x][y] + 1, dp[i][j])
return dp[-1][-1] if dp[-1][-1] != float('inf') else -1
def isValid(self, x, y, m , n):
if x < 0 or x >= m or y < 0 or y >= n:
return False
return True
####
m = len(grid)
n = len(grid[0])
dp = [[float('inf')] * n for _ in range(m)]
if grid[0][0] == 1:
return -1
dp[0][0] = 0
for j in range(n): # loop Y first then X
for i in range(m):
if grid[i][j] == 1:
continue
for x, y in DIRECTIONS:
x_prev = i + x
y_prev = j + y
if 0 <= x_prev < m and 0 <= y_prev < n:
dp[i][j] = min(dp[i][j], dp[x_prev][y_prev] + 1)
print(dp)
if dp[-1][-1] == float('inf'):
return -1
return dp[-1][-1]
####
|
Python
|
UTF-8
| 2,441 | 2.859375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
import pandas as pd
df = pd.read_csv('liver.csv')
# In[3]:
df
# In[4]:
train_data = df.drop(['Selector'],axis='columns')
train_label = pd.DataFrame(df['Selector'])
# In[5]:
#split the data into 70% training and 30% testing
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(train_data,train_label,test_size=0.3)
# In[6]:
X_train
# In[7]:
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression()
clf.fit(X_train,y_train)
clf.score(X_test,y_test)
# In[8]:
from sklearn.metrics import mean_squared_error
# In[9]:
mean_squared_error(y_test,clf.predict(X_test))
# In[10]:
from sklearn.naive_bayes import GaussianNB
# In[11]:
gnb = GaussianNB()
gnb.fit(X_train, y_train)
gnb.score(X_test,y_test)
# In[12]:
mean_squared_error(y_test,gnb.predict(X_test))
# In[13]:
import matplotlib.pyplot as plt
# In[14]:
plt.scatter(X_test.iloc[:,0], y_test.iloc[:,0], color='black')
plt.scatter(X_test.iloc[:,0], clf.predict(X_test))
# In[15]:
dfop = pd.DataFrame(df['GOT']/df['GPT'],columns=['GOT/GPT'])
# In[16]:
dfop
# In[17]:
dfpo = pd.DataFrame(df['GPT']/df['GOT'],columns=['GPT/GOT'])
# In[18]:
dfpo
# In[19]:
df2=pd.concat([dfpo,dfop,df['GOT'],df['GPT'],df['Selector']],axis=1)
# In[20]:
df2
# In[21]:
correlation_matrix = df2.corr()
# In[22]:
import seaborn as sns
ax = sns.heatmap(correlation_matrix, annot=True)
# In[23]:
df3=pd.concat([dfpo,dfop,df],axis=1)
df3=df3.drop(['GOT','GPT'],axis='columns')
# In[24]:
df3
# In[25]:
train_data = df3.drop(['Selector'],axis='columns')
train_label = pd.DataFrame(df3['Selector'])
# In[26]:
X_train, X_test, y_train, y_test = train_test_split(train_data,train_label,test_size=0.3)
# In[27]:
X_train
# In[28]:
clf = LogisticRegression()
clf.fit(X_train,y_train)
clf.score(X_test,y_test)
# In[29]:
mean_squared_error(y_test,clf.predict(X_test))
# In[30]:
plt.scatter(X_test.iloc[:,0], y_test.iloc[:,0], color='black')
plt.scatter(X_test.iloc[:,0], clf.predict(X_test))
# In[31]:
gnb = GaussianNB()
gnb.fit(X_train, y_train)
gnb.score(X_test,y_test)
# In[32]:
mean_squared_error(y_test,gnb.predict(X_test))
# In[33]:
plt.scatter(X_test.iloc[:,0], y_test.iloc[:,0], color='black')
plt.scatter(X_test.iloc[:,0], gnb.predict(X_test))
|
Java
|
UTF-8
| 7,487 | 1.890625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2017-2018 Runtime Inc.
* Copyright (c) Intellinium SAS, 2014-present
*
* SPDX-License-Identifier: Apache-2.0
*/
package io.runtime.mcumgr.managers;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;
import io.runtime.mcumgr.McuManager;
import io.runtime.mcumgr.McuMgrCallback;
import io.runtime.mcumgr.McuMgrTransport;
import io.runtime.mcumgr.exception.McuMgrException;
import io.runtime.mcumgr.response.McuMgrResponse;
import io.runtime.mcumgr.response.dflt.McuMgrEchoResponse;
import io.runtime.mcumgr.response.dflt.McuMgrMpStatResponse;
import io.runtime.mcumgr.response.dflt.McuMgrReadDateTimeResponse;
import io.runtime.mcumgr.response.dflt.McuMgrTaskStatResponse;
/**
* Default command group manager.
*/
@SuppressWarnings("unused")
public class DefaultManager extends McuManager {
// Command IDs
private final static int ID_ECHO = 0;
private final static int ID_CONS_ECHO_CTRL = 1;
private final static int ID_TASKSTATS = 2;
private final static int ID_MPSTATS = 3;
private final static int ID_DATETIME_STR = 4;
private final static int ID_RESET = 5;
/**
* Construct an default manager.
*
* @param transport the transport to use to send commands.
*/
public DefaultManager(@NotNull McuMgrTransport transport) {
super(GROUP_DEFAULT, transport);
}
//******************************************************************
// Default Commands
//******************************************************************
/**
* Echo a string (asynchronous).
*
* @param echo the string to echo.
* @param callback the asynchronous callback.
*/
public void echo(@Nullable String echo, @NotNull McuMgrCallback<McuMgrEchoResponse> callback) {
HashMap<String, Object> payloadMap = new HashMap<>();
payloadMap.put("d", echo);
send(OP_WRITE, ID_ECHO, payloadMap, McuMgrEchoResponse.class, callback);
}
/**
* Echo a string (synchronous).
*
* @param echo the string to echo.
* @return The response.
* @throws McuMgrException Transport error. See cause.
*/
@NotNull
public McuMgrEchoResponse echo(@Nullable String echo) throws McuMgrException {
HashMap<String, Object> payloadMap = new HashMap<>();
payloadMap.put("d", echo);
return send(OP_WRITE, ID_ECHO, payloadMap, McuMgrEchoResponse.class);
}
/**
* Set the console echo on the device (synchronous).
*
* @param echo whether or not to echo to the console.
* @param callback the asynchronous callback.
*/
public void consoleEcho(boolean echo, @NotNull McuMgrCallback<McuMgrResponse> callback) {
HashMap<String, Object> payloadMap = new HashMap<>();
payloadMap.put("echo", echo);
send(OP_WRITE, ID_CONS_ECHO_CTRL, payloadMap, McuMgrResponse.class, callback);
}
/**
* Set the console echo on the device (synchronous).
*
* @param echo whether or not to echo to the console.
* @return The response.
* @throws McuMgrException Transport error. See cause.
*/
@NotNull
public McuMgrResponse consoleEcho(boolean echo) throws McuMgrException {
HashMap<String, Object> payloadMap = new HashMap<>();
payloadMap.put("echo", echo);
return send(OP_WRITE, ID_CONS_ECHO_CTRL, payloadMap, McuMgrResponse.class);
}
/**
* Get task statistics from the device (asynchronous).
*
* @param callback the asynchronous callback.
*/
public void taskstats(@NotNull McuMgrCallback<McuMgrTaskStatResponse> callback) {
send(OP_READ, ID_TASKSTATS, null, McuMgrTaskStatResponse.class, callback);
}
/**
* Get task statistics from the device (synchronous).
*
* @return The response.
* @throws McuMgrException Transport error. See cause.
*/
@NotNull
public McuMgrTaskStatResponse taskstats() throws McuMgrException {
return send(OP_READ, ID_TASKSTATS, null, McuMgrTaskStatResponse.class);
}
/**
* Get memory pool statistics from the device (asynchronous).
*
* @param callback the asynchronous callback.
*/
public void mpstat(@NotNull McuMgrCallback<McuMgrMpStatResponse> callback) {
send(OP_READ, ID_MPSTATS, null, McuMgrMpStatResponse.class, callback);
}
/**
* Get memory pool statistics from the device (synchronous).
*
* @return The response.
* @throws McuMgrException Transport error. See cause.
*/
@NotNull
public McuMgrMpStatResponse mpstat() throws McuMgrException {
return send(OP_READ, ID_MPSTATS, null, McuMgrMpStatResponse.class);
}
/**
* Read the date and time on the device (asynchronous).
*
* @param callback the asynchronous callback.
*/
public void readDatetime(@NotNull McuMgrCallback<McuMgrReadDateTimeResponse> callback) {
send(OP_READ, ID_DATETIME_STR, null, McuMgrReadDateTimeResponse.class, callback);
}
/**
* Read the date and time on the device (synchronous).
*
* @return The response.
* @throws McuMgrException Transport error. See cause.
*/
@NotNull
public McuMgrReadDateTimeResponse readDatetime() throws McuMgrException {
return send(OP_READ, ID_DATETIME_STR, null, McuMgrReadDateTimeResponse.class);
}
/**
* Write the date and time on the device (asynchronous).
* <p>
* If date or timeZone are null, the current value will be used.
*
* @param date the date to set the device to.
* @param timeZone the timezone to use with the date.
* @param callback the asynchronous callback.
*/
public void writeDatetime(@Nullable Date date, @Nullable TimeZone timeZone,
@NotNull McuMgrCallback<McuMgrResponse> callback) {
HashMap<String, Object> payloadMap = new HashMap<>();
payloadMap.put("datetime", dateToString(date, timeZone));
send(OP_WRITE, ID_DATETIME_STR, payloadMap, McuMgrResponse.class, callback);
}
/**
* Write the date and time on the device (synchronous).
* <p>
* If date or timeZone are null, the current value will be used.
*
* @param date the date to set the device to.
* @param timeZone the timezone to use with the date.
* @return The response.
* @throws McuMgrException Transport error. See cause.
*/
@NotNull
public McuMgrResponse writeDatetime(@Nullable Date date, @Nullable TimeZone timeZone)
throws McuMgrException {
HashMap<String, Object> payloadMap = new HashMap<>();
payloadMap.put("datetime", dateToString(date, timeZone));
return send(OP_WRITE, ID_DATETIME_STR, payloadMap, McuMgrResponse.class);
}
/**
* Reset the device (asynchronous).
*
* @param callback the asynchronous callback.
*/
public void reset(@NotNull McuMgrCallback<McuMgrResponse> callback) {
send(OP_WRITE, ID_RESET, null, McuMgrResponse.class, callback);
}
/**
* Reset the device (synchronous).
*
* @return The response.
* @throws McuMgrException Transport error. See cause.
*/
@NotNull
public McuMgrResponse reset() throws McuMgrException {
return send(OP_WRITE, ID_RESET, null, McuMgrResponse.class);
}
}
|
Java
|
UTF-8
| 446 | 2.5625 | 3 |
[] |
no_license
|
package ch.zhaw.exercise.le04a.task1;
import java.io.Serializable;
public class Fahrzeug implements Serializable {
public static final long serialVersionUID = 1L;
private String nummer;
public Fahrzeug() {
}
public Fahrzeug(String nummer) {
this.nummer = nummer;
}
public String getNummer() {
return nummer;
}
public void setNummer(String nummer) {
this.nummer = nummer;
}
}
|
Java
|
UTF-8
| 6,131 | 2.140625 | 2 |
[
"MIT"
] |
permissive
|
package elasticsearchtest17;
import static org.junit.Assert.*;
import org.junit.*;
import java.util.*;
import java.io.*;
import org.elasticsearch.action.bulk.*;
import org.elasticsearch.common.transport.*;
import org.elasticsearch.client.transport.*;
import org.elasticsearch.common.settings.*;
import org.elasticsearch.common.xcontent.*;
public class ElasticsearchTests17 {
private String [] names={"checkout","order","search","payment"};
private String [] messages={"Incoming request from code","incoming operation succeeded with code","Operation completed time","transaction performed"};
private String [] severity={"info","warning","transaction","verbose"};
private String [] apps={"4D24BD62-20BF-4D74-B6DC-31313ABADB82","5D24BD62-20BF-4D74-B6DC-31313ABADB82","6D24BD62-20BF-4D74-B6DC-31313ABADB82","7D24BD62-20BF-4D74-B6DC-31313ABADB82"};
private String hostName = "";
private String indexName = "";
private String typeName = "";
private int port = 0;
private String clusterName = "";
private int node = 0;
private int itemsPerBatch = 0;
private static Random random = new Random();
@Before
public void setUp() throws Exception {
}
public ElasticsearchTests17(String params) {
/* params is a string containing a set of comma separated values for:
hostName
indexName
typeName
port
clustername
node
itemsPerBatch
*/
// Note: No checking/validation is performed
String delims = "[ ]*,[ ]*"; // comma surrounded by zero or more spaces
String[] items = params.split(delims);
hostName = items[0];
indexName = items[1];
typeName = items[2];
port = Integer.parseInt(items[3]);
clusterName = items[4];
node = Integer.parseInt(items[5]);
if (node!=0)
port = port+(random.nextInt(node)+1);
itemsPerBatch = Integer.parseInt(items[6]);
if(itemsPerBatch == 0)
{
itemsPerBatch = 1000;
}
}
@Test
public void BulkDataInsertTest17() throws IOException {
Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", clusterName).build();
TransportClient client;
client = new TransportClient(settings);
try {
client.addTransportAddress(new InetSocketTransportAddress(hostName, port));
BulkRequestBuilder bulkRequest = client.prepareBulk();
for(int i=1; i< itemsPerBatch; i++){
random.nextInt(10);
int host=random.nextInt(20);
bulkRequest.add(client.prepareIndex(indexName, typeName).setSource(XContentFactory.jsonBuilder()
.startObject()
.field("@timestamp", new Date())
.field("name", names[random.nextInt(names.length)])
.field("message", messages[random.nextInt(messages.length)])
.field("severityCode", random.nextInt(10))
.field("severity", severity[random.nextInt(severity.length)])
.field("hostname", "Hostname"+host)
.field("hostip", "10.1.0."+host)
.field("pid",random.nextInt(10))
.field("tid",random.nextInt(10))
.field("appId", apps[random.nextInt(apps.length)])
.field("appName", "application"+host)
.field("appVersion", random.nextInt(5))
.field("type", random.nextInt(6))
.field("subtype", random.nextInt(6))
.field("correlationId", UUID.randomUUID().toString())
.field("os", "linux")
.field("osVersion", "14.1.5")
.field("parameters", "{ke:value,key:value}")
.endObject()
)
);
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
assertFalse(bulkResponse.buildFailureMessage(), bulkResponse.hasFailures());
}
finally {
client.close();
}
}
@Test
public void BulkBigInsertTest17() throws IOException {
Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", clusterName).build();
TransportClient client;
client = new TransportClient(settings);
try {
client.addTransportAddress(new InetSocketTransportAddress(hostName, port));
BulkRequestBuilder bulkRequest = client.prepareBulk();
Random random = new Random();
char[] exmarks = new char[12000];
Arrays.fill(exmarks, 'x');
String dataString = new String(exmarks);
for(int i=1; i< itemsPerBatch; i++){
random.nextInt(10);
int host=random.nextInt(20);
bulkRequest.add(client.prepareIndex(indexName, typeName).setSource(XContentFactory.jsonBuilder()
.startObject()
.field("@timestamp", new Date())
.field("name", names[random.nextInt(names.length)])
.field("message", messages[random.nextInt(messages.length)])
.field("severityCode", random.nextInt(10))
.field("severity", severity[random.nextInt(severity.length)])
.field("hostname", "Hostname"+host)
.field("hostip", "10.1.0."+host)
.field("pid",random.nextInt(10))
.field("tid",random.nextInt(10))
.field("appId", apps[random.nextInt(apps.length)])
.field("appName", "application"+host)
.field("appVersion", random.nextInt(5))
.field("type", random.nextInt(6))
.field("subtype", random.nextInt(6))
.field("correlationId", UUID.randomUUID().toString())
.field("os", "linux")
.field("osVersion", "14.1.5")
.field("parameters", "{ke:value,key:value}")
.field("data1",dataString)
.field("data2",dataString)
.endObject()
)
);
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
assertFalse(bulkResponse.buildFailureMessage(), bulkResponse.hasFailures());
}
finally {
client.close();
}
}
@After
public void tearDown() throws Exception {
}
}
|
JavaScript
|
UTF-8
| 6,548 | 2.765625 | 3 |
[] |
no_license
|
const messageService = require('../services/message')
const {StatusCodes: HttpStatusCode} = require('http-status-codes');
const responseFormatter = require("../utils/response");
const { canConvertToPositiveInteger } = require('../utils/stringHelper');
const { isValidObjectId } = require("../utils/validator");
const debug = require('debug')('message-service:api');
/**
* Parent Route /api/v1
* Response will be either wrapped in responseFormatter.ok or responseFormatter.error function
*/
module.exports = {
/**
* POST /messages handler
* return newly created message
*/
create: async (req, res, next) => {
let message = req.body.message;
try {
if(typeof message === 'object' || typeof message === 'undefined'){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('malformed payload.'));
}
message = message.toString();
if(message.trim() === ''){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('message content missing.'));
}
const result = await messageService.create(message);
return res.status(HttpStatusCode.CREATED).json(responseFormatter.ok(result));
}
catch (err) {
return res
.status(HttpStatusCode.INTERNAL_SERVER_ERROR)
.json(responseFormatter.error("save message failed", err));
}
},
/**
* PUT /messages/:id handler
* return updated message
*/
updateById: async (req, res) => {
const { id } = req.params;
let message = req.body.message;
//validation request params
if(typeof message === 'object' || typeof message === 'undefined'){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('malformed payload.'));
}
message = message.toString();
if(!message || message.trim() === ''){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('message content missing.'));
}
if(!isValidObjectId(id)){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('invalid path params id.'));
}
try {
const searchResult = await messageService.getById(id);
if(searchResult === null){
return res
.status(HttpStatusCode.NOT_FOUND)
.json(responseFormatter.error(`record not found.`));
}
const result = await messageService.updateById(message, id);
return res.status(HttpStatusCode.OK).json(responseFormatter.ok(result));
}
catch (err) {
return res
.status(HttpStatusCode.INTERNAL_SERVER_ERROR)
.json(responseFormatter.error(`update message ${id} failed`, err));
}
},
/**
* DELETE /messages/:id handler
* return message :id deleted
*/
deleteById: async (req, res) => {
const { id } = req.params;
if (!isValidObjectId(id)) {
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error(
'invalid path params id.'));
}
try {
const searchResult = await messageService.getById(id);
if (searchResult === null) {
return res
.status(HttpStatusCode.NOT_FOUND)
.json(responseFormatter.error(`record not found.`));
}
await messageService.deleteById(id);
return res
.status(HttpStatusCode.OK)
.json(responseFormatter.ok(`message ${id} deleted`));
}
catch (err) {
return res
.status(HttpStatusCode.INTERNAL_SERVER_ERROR)
.json(responseFormatter.error(`delete message ${id} failed`, err));
}
},
/**
* Get /messages/:id handler
* return searched message id
*/
getById: async (req, res) => {
const { id } = req.params;
if (!isValidObjectId(id)) {
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error(
'invalid path params id.'));
}
try {
const message = await messageService.getById(id);
if (message === null) {
return res
.status(HttpStatusCode.NOT_FOUND)
.json(responseFormatter.error(`record not found.`));
}
return res.status(HttpStatusCode.OK).json(responseFormatter.ok(message));
}
catch (err) {
return res
.status(HttpStatusCode.INTERNAL_SERVER_ERROR)
.json(responseFormatter.error(`retrieve message ${id} failed`, err));
}
},
/**
* Get /messages handler
* return list of messages
*/
getList: async (req, res) => {
try {
let filter = {};
let page = req.query.page || 1;
let size = req.query.size || 10;
let sort = req.query.sort || "-createdAt";
//plain query will remove + char, urlencoded + sign will be converted correctly
if (sort.charAt(0) !== '-' && sort.charAt(0) !== '+') {
sort = "+" + sort;
}
//define searchable fileds
let sortable = ['createdAt', 'updatedAt', 'message', 'palindromic', '_id'];
if(sort.trim() === ""){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('invalid query params sort.'));
}
if(!sortable.includes(sort.substring(1))){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('invalid query params sort.'));
}
if(!canConvertToPositiveInteger(page)){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error(
'query params page must be a positive integer.'));
}
if(!canConvertToPositiveInteger(size)){
return res.status(HttpStatusCode.BAD_REQUEST).json(responseFormatter.error('invalid query params size.'));
}
size = (+size > 100) ? 100 : size;
page = +page;
if("palindromic" in req.query) {
//treat none "0" value to false
if (req.query.palindromic) {
filter.palindromic = req.query.palindromic === "0" ? false : true;
}
}
let pagination = {
page: page - 1,
size,
sort : sort
}
const messages = await messageService.getList(filter, pagination);
const totalRecords = await messageService.count(filter);
const response = {
data: messages,
currentPage: page,
totalPages: Math.ceil(totalRecords / size),
totalRecords: totalRecords,
currentSize: size
}
return res.status(HttpStatusCode.OK).json(responseFormatter.ok(response));
}
catch (err) {
debug(err)
return res
.status(HttpStatusCode.INTERNAL_SERVER_ERROR)
.json(responseFormatter.error("retrieve message list failed", err));
}
},
};
|
Java
|
UTF-8
| 18,877 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package file.util;
import com.yanghui.learn.common.IOUtils;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author YangHui
*/
@Slf4j
public class FileUtils {
private static int BUFFER_SIZE = 1024;
/**
* @param file
* @param response
*/
public static void downloadFile0(String file, HttpServletResponse response) {
OutputStream os = null;
try {
// 取得输出流
os = response.getOutputStream();
long start = System.currentTimeMillis();
Path path = Paths.get(file);
log.info("download0---file,cost {} ms",System.currentTimeMillis() - start);
String contentType = Files.probeContentType(path);
response.setHeader("Content-Type", contentType);
String fileName1 = URLEncoder.encode(new File(file).getName(), "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName1);
long start2 = System.currentTimeMillis();
Files.copy(path, os);
log.info("download0---copy,cost {} ms",System.currentTimeMillis() - start2);
} catch (IOException e) {
log.error("download0 error",e);
}
finally {
IOUtils.closeQuietly(os);
}
}
/**
* @param file
* @param response
*/
public static void downloadFile1(File file, HttpServletResponse response) {
FileInputStream fileInputStream = null;
OutputStream os = null;
FileChannel fileChannel = null;
WritableByteChannel writableByteChannel = null;
try {
// 取得输出流
os = response.getOutputStream();
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setHeader("Content-Type", contentType);
String fileName1 = URLEncoder.encode(file.getName(), "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName1);
writableByteChannel = Channels.newChannel(os);
long start = System.currentTimeMillis();
fileInputStream = new FileInputStream(file);
fileChannel = fileInputStream.getChannel();
log.info("download1---file,cost {} ms",System.currentTimeMillis() - start);
long size = fileChannel.size();
long position = 0;
long loaded;
long start2 = System.currentTimeMillis();
while((loaded = fileChannel.transferTo(position, size, writableByteChannel)) > 0){
position += loaded;
}
log.info("download1---copy,cost {} ms",System.currentTimeMillis() - start2);
} catch (IOException e) {
log.error("download1 error",e);
}
finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(writableByteChannel);
IOUtils.closeQuietly(fileChannel);
IOUtils.closeQuietly(os);
}
}
public static void downloadFile2(File file, HttpServletResponse response){
FileInputStream fileInputStream = null;
FileChannel fileChannel = null;
try {
long start = System.currentTimeMillis();
//拼接文件
fileInputStream = new FileInputStream(file);
long fileLength = file.length();
//对文件名进行编码,解决中文名乱码
String fileName1 = URLEncoder.encode(file.getName(), "UTF-8");
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setContentType("application/octet-stream");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//指定文件下载,并解决中文名乱码
response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName1);
response.setHeader("Content-Length", String.valueOf(fileLength));
response.setContentType(contentType);
fileChannel = fileInputStream.getChannel();
int bufferSize = BUFFER_SIZE;
ByteBuffer buff = ByteBuffer.allocateDirect(BUFFER_SIZE);
byte[] byteArr = new byte[bufferSize];
int nGet;
while(fileChannel.read(buff)!=-1){
buff.flip();
while (buff.hasRemaining()) {
nGet = Math.min(buff.remaining(), bufferSize);
// read bytes from disk
buff.get(byteArr, 0, nGet);
// write bytes to output
response.getOutputStream().write(byteArr);
}
buff.clear();
}
log.info("download2,cost {} ms",System.currentTimeMillis() - start);
} catch (Exception e) {
log.error("download2 error",e);
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(fileChannel);
}
}
/**
*
* @param file
* @param response
*/
public static void downloadFile3(File file, HttpServletResponse response){
FileInputStream fileInputStream = null;
OutputStream outputStream = null;
FileChannel fileChannel = null;
WritableByteChannel writableByteChannel = null;
try {
//拼接文件
long fileLength = file.length();
//对文件名进行编码,解决中文名乱码
String fileName1 = URLEncoder.encode(file.getName(), "UTF-8");
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setContentType("application/octet-stream");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//指定文件下载,并解决中文名乱码
response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName1);
response.setHeader("Content-Length", String.valueOf(fileLength));
response.setContentType(contentType);
long start = System.currentTimeMillis();
fileInputStream = new FileInputStream(file);
fileChannel = fileInputStream.getChannel();
log.info("download3---file,cost {} ms",System.currentTimeMillis() - start);
outputStream = response.getOutputStream();
writableByteChannel = Channels.newChannel(outputStream);
ByteBuffer buff = ByteBuffer.allocateDirect(BUFFER_SIZE);
long start2 = System.currentTimeMillis();
while(fileChannel.read(buff) != -1){
buff.flip();
while(buff.hasRemaining()){
writableByteChannel.write(buff);
}
buff.clear();
}
log.info("download3---copy,cost {} ms",System.currentTimeMillis() - start2);
} catch (Exception e) {
log.error("download3 error",e);
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(writableByteChannel);
IOUtils.closeQuietly(fileChannel);
IOUtils.closeQuietly(outputStream);
}
}
public static void downloadFile4(File file, HttpServletResponse response){
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
long start = System.currentTimeMillis();
//对文件名进行编码,解决中文名乱码
String fileName1 = URLEncoder.encode(file.getName(), "UTF-8");
long fileLength = file.length();
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setContentType("application/octet-stream");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//指定文件下载,并解决中文名乱码
response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName1);
response.setHeader("Content-Length", String.valueOf(fileLength));
response.setContentType(contentType);
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[BUFFER_SIZE];
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
log.info("download4,cost {} ms",System.currentTimeMillis() - start);
}catch (Exception e){
log.info("download4 error",e);
}finally {
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(bis);
IOUtils.closeQuietly(os);
}
}
/**
* 文件分片下载 fileChannel
* @param range http请求头Range,用于表示请求指定部分的内容。
* 格式为:Range: bytes=start-end [start,end]表示,即是包含请求头的start及end字节的内容
* @param response
*/
public static void fileChunkDownload1(File file, String range, HttpServletResponse response) {
//开始下载位置
long startByte = 0;
long fileEndByte = file.length() - 1;
//结束下载位置
long endByte = fileEndByte;
//有range的话
if (range != null && range.contains("bytes=") && range.contains("-")) {
range = range.substring(range.lastIndexOf("=") + 1).trim();
String ranges[] = range.split("-");
try {
//根据range解析下载分片的位置区间
if (ranges.length == 1) {
//情况1,如:bytes=-1024 从开始字节到第1024个字节的数据
if (range.startsWith("-")) {
endByte = Long.parseLong(ranges[0]);
}
//情况2,如:bytes=1024- 第1024个字节到最后字节的数据
else if (range.endsWith("-")) {
startByte = Long.parseLong(ranges[0]);
}
}
//情况3,如:bytes=1024-2048 第1024个字节到2048个字节的数据
else if (ranges.length == 2) {
startByte = Long.parseLong(ranges[0]);
endByte = Long.parseLong(ranges[1]);
}
} catch (NumberFormatException e) {
startByte = 0;
endByte = fileEndByte;
}
}
response.setHeader("Accept-Ranges", "bytes");
//Content-Range 表示响应了多少数据,格式为:[要下载的开始位置]-[结束位置]/[文件总大小]
response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + file.length());
if(startByte > fileEndByte || endByte > fileEndByte){
//416范围请求有误
response.setStatus(response.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
}else{
//要下载的长度
long contentLength = endByte - startByte + 1;
OutputStream os = null;
WritableByteChannel writableByteChannel = null;
FileInputStream fileInputStream = null;
FileChannel fileChannel = null;
try {
long start = System.currentTimeMillis();
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setHeader("Content-Type", contentType);
String fileName1 = URLEncoder.encode(file.getName(), "UTF-8");
//Content-Disposition 表示响应内容以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地。
//inline表示内联的形式,即:浏览器直接下载
response.setHeader("Content-Disposition", "inline;filename*=utf-8'zh_cn'" + fileName1);
//Content-Length 表示资源内容长度,即:文件大小
response.setHeader("Content-Length", String.valueOf(contentLength));
//206表示返回的body只是原数据的一部分
response.setStatus(response.SC_PARTIAL_CONTENT);
os = response.getOutputStream();
writableByteChannel = Channels.newChannel(os);
fileInputStream = new FileInputStream(file);
fileChannel = fileInputStream.getChannel();
long position = startByte;
//已传送数据大小
long transmitted = 0;
long loaded;
while((loaded = fileChannel.transferTo(position, contentLength - transmitted, writableByteChannel)) > 0){
position += loaded;
transmitted += loaded;
}
log.info("fileChunkDownload1---copy,cost {} ms",System.currentTimeMillis() - start);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(fileInputStream);
IOUtils.closeQuietly(writableByteChannel);
IOUtils.closeQuietly(fileChannel);
IOUtils.closeQuietly(os);
}
}
}
/**
* 文件分片下载 RandomAccessFile
* @param range http请求头Range,用于表示请求指定部分的内容。
* 格式为:Range: bytes=start-end [start,end]表示,即是包含请求头的start及end字节的内容
* @param response
*/
public static void fileChunkDownload2(File file, String range, HttpServletResponse response) {
//开始下载位置
long startByte = 0;
long fileEndByte = file.length() - 1;
//结束下载位置
long endByte = fileEndByte;
//有range的话
if (range != null && range.contains("bytes=") && range.contains("-")) {
range = range.substring(range.lastIndexOf("=") + 1).trim();
String ranges[] = range.split("-");
try {
//根据range解析下载分片的位置区间
if (ranges.length == 1) {
//情况1,如:bytes=-1024 从开始字节到第1024个字节的数据
if (range.startsWith("-")) {
endByte = Long.parseLong(ranges[0]);
}
//情况2,如:bytes=1024- 第1024个字节到最后字节的数据
else if (range.endsWith("-")) {
startByte = Long.parseLong(ranges[0]);
}
}
//情况3,如:bytes=1024-2048 第1024个字节到2048个字节的数据
else if (ranges.length == 2) {
startByte = Long.parseLong(ranges[0]);
endByte = Long.parseLong(ranges[1]);
}
} catch (NumberFormatException e) {
startByte = 0;
endByte = fileEndByte;
}
}
response.setHeader("Accept-Ranges", "bytes");
//Content-Range 表示响应了多少数据,格式为:[要下载的开始位置]-[结束位置]/[文件总大小]
response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + file.length());
if(startByte > fileEndByte || endByte > fileEndByte){
//416范围请求有误
response.setStatus(response.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
}else{
//要下载的长度
long contentLength = endByte - startByte + 1;
BufferedOutputStream outputStream = null;
RandomAccessFile randomAccessFile = null;
OutputStream os = null;
try {
long start = System.currentTimeMillis();
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setHeader("Content-Type", contentType);
String fileName1 = URLEncoder.encode(file.getName(), "UTF-8");
//Content-Disposition 表示响应内容以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地。
//inline表示内联的形式,即:浏览器直接下载
response.setHeader("Content-Disposition", "inline;filename*=utf-8'zh_cn'" + fileName1);
//Content-Length 表示资源内容长度,即:文件大小
response.setHeader("Content-Length", String.valueOf(contentLength));
//206表示返回的body只是原数据的一部分
response.setStatus(response.SC_PARTIAL_CONTENT);
//已传送数据大小
long transmitted = 0;
os = response.getOutputStream();
randomAccessFile = new RandomAccessFile(file, "r");
outputStream = new BufferedOutputStream(os);
byte[] buff = new byte[2048];
int len = 0;
randomAccessFile.seek(startByte);
//判断是否到了最后不足2048(buff的length)个byte
while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
outputStream.write(buff, 0, len);
transmitted += len;
}
//处理不足buff.length部分
if (transmitted < contentLength) {
len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
outputStream.write(buff, 0, len);
}
outputStream.flush();
response.flushBuffer();
log.info("fileChunkDownload2---copy,cost {} ms",System.currentTimeMillis() - start);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
C#
|
UTF-8
| 2,997 | 2.640625 | 3 |
[] |
no_license
|
using DataContextNamespace.Models;
using DataServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MyTerm.Api.Controllers
{
public class SubCategoryController : ApiController
{
// GET api/<controller>
public IHttpActionResult Get()
{
IHttpActionResult result = null;
SubCategoryService service = new SubCategoryService();
IEnumerable<SubCategory> subCategories = service.GetSubCategories();
if (subCategories.Count() > 0)
{
result = Ok(subCategories);
}
else
{
result = NotFound();
}
return result;
}
// GET api/<controller>/5
public IHttpActionResult Get(int id)
{
IHttpActionResult result = null;
SubCategoryService service = new SubCategoryService();
SubCategory subCategory = service.GetSubCategory(id);
if (subCategory != null)
{
result = Ok(subCategory);
}
else
{
result = NotFound();
}
return result;
}
// POST api/<controller>
[HttpPost()]
public IHttpActionResult Post(SubCategory subCategory)
{
IHttpActionResult result = null;
SubCategoryService service = new SubCategoryService();
SubCategory newSubCategory = service.InsertSubCategory(subCategory);
if (newSubCategory != null)
{
result = Created<SubCategory>(Request.RequestUri + newSubCategory.ID.ToString(), newSubCategory);
}
else
{
result = NotFound();
}
return result;
}
// PUT api/<controller>/5
public IHttpActionResult Put(SubCategory subCategory)
{
IHttpActionResult result = null;
SubCategoryService service = new SubCategoryService();
if (service.GetSubCategory(subCategory.ID) != null)
{
service.UpdateSubCategory(subCategory);
result = Ok(subCategory);
}
else
{
result = NotFound();
}
return result;
}
// DELETE api/<controller>/5
public IHttpActionResult Delete(int id)
{
IHttpActionResult result = null;
SubCategoryService service = new SubCategoryService();
SubCategory subCategory = service.GetSubCategory(id);
if (subCategory != null)
{
service.RemoveSubCategory(id);
result = Ok(true);
}
else
{
result = NotFound();
}
return result;
}
}
}
|
Java
|
UTF-8
| 1,443 | 2.46875 | 2 |
[] |
no_license
|
package com.szboanda.iot.hub.handler;
import io.netty.channel.ChannelHandler.*;
import com.szboanda.iot.hub.tools.ServerContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Server运行时channel连接和断开事件捕获
* @author 康庆
*
*/
@Sharable
public class ChannelStatusHandler extends ChannelInboundHandlerAdapter {
private ServerContext context;
public ChannelStatusHandler(ServerContext context){
this.context = context;
}
/**
* 捕获channelActive事件并将消息扩散到ServerContext中
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
this.context.fireChannelActive(ctx.channel().id().asShortText());
ctx.fireChannelActive();
}
/**
* 捕获channelInactive事件并将消息扩散到ServerContext中
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
this.context.fireChannelInactive(ctx.channel().id().asShortText());
ctx.fireChannelInactive();
}
/**
* 捕获消息读取事件
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
this.context.msgCounterPlus(ctx.channel().id().asShortText());
ctx.fireChannelRead(msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
ctx.close();
}
}
|
Markdown
|
UTF-8
| 13,659 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
---
title: 한국어 격조사
category: Korean Linguistics
tag: syntax
---
이번 글에서는 한국어의 격조사에 대해 살펴보도록 하겠습니다. 이번 글은 고려대 정연주 선생님 강의를 정리했음을 먼저 밝힙니다. 그럼 시작하겠습니다.
## 조사
조사란 주로 [명사구](https://ratsgo.github.io/korean%20linguistics/2017/07/13/syntax/) 뒤에 나타나서 선행하는 명사구가 다른 말과 맺는 문법적 관계를 나타내거나, 선행하는 명사구에 일정한 의미를 더하는 기능을 하는 말입니다. 예문을 보겠습니다.
> 아이들**이** 마당**에서** 공놀이**만** 한다.
조사에는 다른 말과의 문법적 관계를 표시하는 격조사, 둘 이상의 말을 같은 자격으로 이어주는 접속조사, 특수한 뜻(의미)을 더해주는 [보조사](https://ratsgo.github.io/korean%20linguistics/2017/10/23/josa/)로 나누어 생각해볼 수 있습니다. 위 예문에서 **이**, **에서**가 격조사, **만**이 보조사에 해당합니다. 이 글에서는 격조사를 중심으로 살펴보겠습니다.
## 격조사
격이란 핵이 있는 구성에서 핵에 의존적인 명사(구)가 핵에 대해 가지는 문법적, 의미적 관계의 유형을 가리킵니다. 다시 말해 명사구가 문장 내에서 갖는 자격이 바로 격입니다.
격조사란 격을 나타내는 조사입니다. 격조사는 조사의 형태만으로도 선행 명사구가 문장 내에서 수행하는 기능을 짐작할 수 있습니다. 예문을 보겠습니다.
> (1) 진이**가** 집**에서** 밥**을** 먹었다.
>
> (2) 진이**의** 집
(1)에 해당하는 절(節)의 핵은 '먹었다'라는 서술어입니다. (1)에 속한 명사구들이 서술어 핵과 어떤 문법적 관계를 맺고 있는지 분석해 보겠습니다. 서술어의 주체(주어)는 진이, 서술어가 가리키는 행위가 일어나는 공간은 집, 서술어의 대상(목적어)는 밥입니다. 이번엔 격조사가 격을 어떻게 나타내고 있는지 살펴보겠습니다. (1)에서 '가'는 앞말이 주어임을 표시하고 있습니다. '에서' 앞의 집은 부사어(장소), '을' 앞의 밥은 목적어라는 사실을 나타내고 있습니다.
(2)에 해당하는 명사구의 핵은 '집'이라는 명사입니다. '진이의'라는 명사구는 명사 핵 '집'과 의존(수식) 관계를 맺고 있습니다. 여기에서 격조사 '의'는 앞말이 관형어임을 표시하고 있습니다.
한편 격조사는 크게 문법격 조사와 의미격 조사 둘로 나뉩니다. 문법격 조사는 문장 내에서 선행 명사구의 문법적 자격을 나타내는 조사로, 그 예로 '가(앞말이 주어임을 나타냄)' '를(목적어)' '의(관형어)' 등이 있습니다. 의미격 조사는 문장 내에서 명사구의 의미적 자격을 나타내는 조사로, '에(장소)' '로(장소/도구)' '와(동반자)' 등이 있습니다.
## 주격조사
주격조사란 앞의 말이 그 문장의 주어임을 나타내는 것을 주된 기능으로 하는 조사입니다. '이/가'가 대표적입니다. 다음 예문과 같습니다.
> 학생들**이** 노래를 부르고 있다.
다만 주어로 해석할 수 없는 명사(구)에 '이/가'가 결합하는 경우도 있어서 분석에 주의를 기울여야 합니다. 아래 예문의 경우 전체 문장의 주어는 '진이'이지 '반장'이 아닙니다('반장'은 보어). 그런데도 반장이라는 명사에 '이'가 붙었습니다.
> 진이가 반장**이** 되었다.
>
> 진이가 반장**이** 아니지?
아래와 같은 '장형 부정 구문'에서도 이러한 현상을 발견할 수 있습니다. 아래 예문의 경우 '춥다'는 서술어(본용언)에 해당하는 데 '가'가 붙었습니다.
> 날씨가 춥지**가** 않다.
한편 '께서'는 존칭명사, '서'는 사람의 수를 나타내는 명사 뒤에 쓰이는 주격조사입니다. 다음 예문과 같습니다.
> 선생님**께서** 진이를 칭찬하셨다.
>
> 셋**이서** 길을 나섰다.
## 목적격조사
목적격조사란 앞의 말이 그 문장의 목적어임을 나타내는 것을 주된 기능으로 하는 조사입니다. 어떤 행위가 미치는 '대상'을 가리키는 격조사라는 취지로 대격조사라고 부르기도 합니다. 다음 예문과 같습니다.
> 아이들이 매미**를** 잡는구나.
목적격조사 '을/를' 역시 목적어로 해석할 수 없는 명사구에 '을/를'이 결합하는 경우도 있습니다.
> 진이는 밥을 먹지**를** 않았다.
## 관형격조사
앞의 말이 후행하는 체언의 관형어임을 나타내는 조사를 관형격조사라고 합니다. 명사와 명사 사이에 나타나 두 명사를 더 큰 명사구로 묶어줍니다. 한 명사가 다른 명사에 소속되는 관계에 있음을 나타내 주는 기능에 주목해 속격조사라고도 부릅니다.
> 소유 : 언니**의** 모자
>
> 주체 : 나**의** 연구
>
> 대상 : 향가**의** 연구
>
> 소속 : 한국**의** 사찰
>
> 속성 : 평화**의** 종소리
## 부사격조사
앞의 말이 그 문장의 부사어임을 나타내는 것을 주된 기능을 하는 격조사를 부사격조사라고 합니다. 하지만 부사격조사에는 다양한 종류가 있고, 문법적 기능보다는 이들이 표시하는 여러 의미 관계가 중요할 때가 많습니다. 부사격조사의 종류를 차례로 살펴보겠습니다.
### 처격조사
장소(처소)를 나타내는 것을 주된 임무로 하는 부사격조사입니다. 대표적으로 '에', '에게', '에서' 등이 있습니다.
'에'는 다음과 같이 쓰입니다. 아래 유형로 갈 수록 장소의 본래적 의미가 추상화돼 확장되고 있는 경향을 나타냅니다. '태풍에 나무가 쓰러졌다' 문장에서 나무가 쓰러진 배경(공간)에 태풍이 있었다, 는 정도로 해석할 수도 있다는 것입니다.
| 의미 | 예문 | 비고 |
| :-----: | -------------- | ---------------------------------------- |
| 처소 | 산에 나무가 많다 | 서술어가 있다, 없다, 많다, 적다, 살다, 남다, 흔하다, 드물다 등일 때 |
| 처소(지향점) | 진이는 도서관에 간다 | 서술어가 가다, 오다, 다니다, 도착하다 등일 때 |
| 처소(수여자) | 진이는 꽃에 물을 주었다 | 서술어가 주다, 보내다, 맡기다 등일 때 |
| 시간 | 진달래는 이른 봄에 핀다 | |
| 단위 | 한 반에 다섯 개씩 돌려라 | |
| 이유 | 태풍에 나무가 쓰러졌다 | |
'에게'는 '에'와 기능상 밀접합니다만 '에게'는 유정명사, '에'는 무정명사에 사용합니다. 아울러 '에게'는 '주다' 류의 동사와 어울려서 주는 일과 관련되어 쓰이는 일이 잦아서 여격조사라고 부르기도 합니다. 다음 예문과 같습니다.
| 의미 | 예문 | 비고 |
| :-----: | ---------------- | -------------------------------------- |
| 처소 | 진이에게 볼펜이 있다 | 서술어가 있다, 없다, 남다, 많다, 적다 등일 때 |
| 처소(지향점) | 진이는 민이에게 갔다 | 서술어가 가다, 오다 등일 때 |
| 처소(수여자) | 진이는 민이에게 물을 주었다 | 서술어가 주다, 보내다, 전화하다, 말하다, 묻다, 가르치다 등일 때 |
| 처소(출발점) | 진이는 친구에게 선물을 받았다 | 서술어가 받다, 얻다, 배우다 등일 때 |
'에서'는 이동성 및 방향성이 있는 서술어와 결합하는 경우 출발점을 가리킵니다.
> 선수단이 부산(출발점)에서 왔다
>
> 선수단이 부산(도착점)에 왔다
'에서'는 '에'와 마찬가지로 기본적으로 처소를 나타내나 그 분포가 서로 다릅니다.
> {거실에서, *거실에} 뛰었다.
>
> {*거실에서, 거실에} 화분이 있다.
그렇다면 위 예문의 '에'와 '에서'는 어떤 의미적 차이를 지니길래 분포가 달라지는 걸까요? 대체로 '에'는 위치나 존재를 나타내는 정적인 서술어와 결합하여 사람이나 물건이 존재하거나 위치하는 곳을 나타냅니다. '에서'는 동적인 서술어와 결합하여 활동이 일어나는 곳을 나타냅니다. 각 유형에 해당하는 서술어의 예시는 다음과 같습니다.
> 있다, 없다, 살다, 남다 : 에
>
> 놀다, 공부하다, 회의하다, 연설하다, 일하다, 근무하다, 싸우다, 자라다, 죽다, 만나다, 기다리다, 헤어지다 : 에서
하지만 '에'와 '에서'가 별 차이 없이 같이 쓰이는 경우도 많습니다. 역사적으로 '에'와 '에서'가 한 말에서 분화돼 현대에서는 둘이 공존하고 있다는 해석도 제기됩니다.
### 구격조사
구격조사는 무엇을 만들 때 쓰이는 도구나 재료 및 어떤 일을 하는 수단을 나타내는 것을 주된 임무로 하는 조사를 가리킵니다. 구격조사엔 '으로/로'가 있습니다. 다음 예문과 같습니다. 구격조사 역시 아래 유형으로 갈수록 본래의 도구, 재료, 수단에서 그 의미가 추상화, 확장되고 있는 경향을 확인할 수 있습니다.
예컨대 이유(=다른 사태를 유발하는 수단)와 경로(=다른 장소로 이동하는 수단)는 수단의 확장으로 볼 여지가 있습니다. 처소(=물리적으로 이동한 장소), 결과(=추상적으로 이동한 장소), 자격(=추상적으로 이동한 장소)은 경로의 의미에서 도출된 장소의 확장으로도 해석할 수 있을 것 같습니다.
| 의미 | 예문 |
| ------- | ----------------------- |
| 도구 | 가위로 색종이를 오린다 |
| 재료 | 어머니가 콩으로 메주를 쑤신다 |
| 수단 | 그 사람은 죽음으로 자신의 결백을 증명했다 |
| 이유 | 가뭄으로 금년 농사를 망쳤다 |
| 경로 | 산길로 가다가 여우를 만났다 |
| 처소(지향점) | 진이는 바다로 갔다 |
| 결과 | 황무지가 큰 도시로 바뀌었다 |
| 자격 | 김 선생은 진이를 사위로 삼았다 |
위 표에서 처소(지향점)로 쓰인 '로'가 처격조사 '에'와 쓰임이 유사한 걸 확인할 수 있습니다. 둘 모두 목적지를 나타내는 조사이기 때문입니다. 다음 예문과 같습니다.
> 수업이 끝나면 {식당에, 식당으로} 오세요.
그런데 둘은 분명 쓰임이 다릅니다. '에'는 도착점을 가리키는 반면 '로'는 방향을 가리킵니다.
> 나는 {서울에, *서울로} 도착했다.
>
> 화장실에 가려면 {*아래에, 아래로} 내려가세요.
## 공동격조사
두 명사가 서로 짝이 되어 어떤 일에 관여할 때 동반자를 표시하는 조사를 공동격조사라고 합니다. 대표적으로 '와/과'가 있습니다.
> 영희가 철수와 결혼했다.
>
> 진이는 동생과 사이좋게 지냈다.
'와/과'는 주로 문어에서 쓰이고, '하고'는 대개 구어에서 쓰입니다.
## 비교격조사
두 명사의 상태를 비교할 때 비교의 대상을 표시하는 조사를 비교격조사라고 합니다. '보다'와 '처럼, 만큼, 같이'가 대표적입니다. 전자는 두 명사의 상태에 차이가 있음을 전제로 하여 쓰이고, 후자는 두 명사의 상태에 우열의 차이가 없을 때 사용됩니다. 다음 예문과 같습니다.
> 오늘이 어제보다 덥다
>
> 호수가 거울처럼 맑다
>
> 키가 형만큼 컸다
>
> 곰같이 미련하다
'처럼, 만큼, 같이' 가운데 성격이 나머지와 다른 하나가 바로 '만큼'입니다. 앞말과 비교대상이 실제로 비슷해야 쓸 수 있고, 비유적인 상황에는 사용할 수 없습니다.
> (키가 190cm인 형과 180cm인 동생을 비교하며) 키가 {형처럼, 형같이, ?형만큼} 크네.
>
> 번개{처럼, 같이, *만큼} 빠르다.
## 인용격조사
인용격조사에는 '라고/이라고', '고' 두 가지 종류가 있습니다. 전자는 직접 인용, 후자는 간접 인용의 부사격조사입니다.
> "어서 오너라"라고 선생님께서 말씀하신다.
>
> 어서 오라고 선생님께서 말씀하신다.
## 호격조사
앞의 말이 부름말임을 나타내는 격조사로, 누구를 부를 때 이름이나 호칭 다음에 쓰는 조사입니다. '아/야'는 해라체를 쓸 상대에게만 쓰여 경어법 면에서 큰 제약을 받습니다. 손윗사람에게는 '아버님', '형'처럼 호격조사를 생략한 채 호칭만 씁니다. '여/이여', '시여/이시여'는 존대 의미를 나타내는 호격조사로 기도문이나 시적표현 등에 자주 쓰입니다.
## 서술격조사
학교문법에서는 '이다'를 서술격조사로 분류하고 있습니다. 하지만 '이다'의 문법적 특성은 매우 복잡해서 어느 하나의 범주로 분류하기 어렵다는 견해가 주류입니다. '이다'의 특성에 관련해서는 [이곳](https://ratsgo.github.io/korean%20linguistics/2017/06/21/ida/)을 참고하시면 좋을 것 같습니다.
|
Java
|
UTF-8
| 4,397 | 2.5 | 2 |
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2014 Derigible Enterprises.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Derigible Public License v1.0
* which accompanies this distribution, and is available at
* http://www.derigible.com/license
*
* Contributors:
* Derigible Enterprises - initial API and implementation
*******************************************************************************/
package derigible.transactions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.util.GregorianCalendar;
import org.junit.Test;
import derigible.controller.GUID;
/**
* @author marcphillips
*
*/
public class TransactTest {
@Test//This is a weak test
public void testTransactCreation(){
Transact t = new Transact(new GregorianCalendar(), "test desc",
150.00, "test", "testaccount", true);
t.setGUID(GUID.generate());
t.addNote("This is a test note");
assertNotNull("The transaction was not created", t);
}
@Test
public void testSubTransactionCreation(){
Transact t = new Transact(new GregorianCalendar(), "test desc",
150.00, "test", "testaccount", true);
t.setGUID(GUID.generate());
t.addNote("This is a test note");
SubTransaction st1 = new SubTransaction(t, 50);
String description = "This is a description.";
st1.setDescription(description);
assertEquals("Wrong amount divided.", 50.00, t.getDividedAmount(), .001);
assertEquals("Wrong description.", "This is a description.", st1.getDescription());
assertEquals("Wrong amount undivided.", 100, t.getUndividedAmount(), .001);
SubTransaction st2 = new SubTransaction(t, 25);
assertEquals("Wrong amount divided.", 75.00, t.getDividedAmount(), .001);
assertFalse("Wrong description.", st2.getDescription().isEmpty());
assertEquals("Wrong amount undivided.", 75, t.getUndividedAmount(), .001);
SubTransaction st3 = new SubTransaction(t, 80);
assertEquals("Wrong amount divided.", 150.00, t.getDividedAmount(), .001);
System.out.println(st3.getNotes());
assertEquals("Wrong description.", "SubTransaction amount truncated to fit allowed amount. Amount changed to: " + 75.00, st3.getNotes());
assertEquals("Wrong amount undivided.", 0.0, t.getUndividedAmount(), .001);
}
@Test
public void testSubTransactionRemoval(){
Transact t = new Transact(new GregorianCalendar(), "test desc",
150.00, "test", "testaccount", true);
t.setGUID(GUID.generate());
t.addNote("This is a test note");
SubTransaction st1 = new SubTransaction(t, 50);
String description = "This is a description.";
st1.setDescription(description);
SubTransaction st2 = new SubTransaction(t, 25);
SubTransaction st3 = new SubTransaction(t, 80);
assertEquals("Wrong amount divided.", 150.00, t.getDividedAmount(), .001);
t.removeSubTransaction(st1);
assertEquals("Wrong amount divided.", 100.00, t.getDividedAmount(), .001);
assertEquals("Wrong description.", "This is a description.", st1.getDescription());
assertEquals("Wrong amount undivided.", 50, t.getUndividedAmount(), .001);
t.removeSubTransaction(st2);
assertEquals("Wrong amount divided.", 75.00, t.getDividedAmount(), .001);
assertEquals("Wrong amount undivided.", 75, t.getUndividedAmount(), .001);
t.removeSubTransaction(st3);
assertEquals("Wrong amount divided.", 0.0, t.getDividedAmount(), .001);
assertEquals("Wrong amount undivided.", 150.0, t.getUndividedAmount(), .001);
}
@Test
public void testSubTransactionArrayResize(){
Transact t = new Transact(new GregorianCalendar(), "test desc",
150.00, "test", "testaccount", true);
t.setGUID(GUID.generate());
t.addNote("This is a test note");
SubTransaction st1 = new SubTransaction(t, 5);
String description = "This is a description.";
st1.setDescription(description);
new SubTransaction(t, 5);
new SubTransaction(t, 5);
new SubTransaction(t, 5);
new SubTransaction(t, 5);
new SubTransaction(t, 5);
new SubTransaction(t, 5);
assertEquals("Wrong amount divided.", 35.00, t.getDividedAmount(), .001);
assertEquals("Wrong amount undivided.", 115, t.getUndividedAmount(), .001);
assertEquals("Wrong size for array.", 9, t.getSubTransactions().length);
}
}
|
Python
|
UTF-8
| 2,919 | 3.15625 | 3 |
[] |
no_license
|
import pandas as pd
import numpy as np
# read full data
raw_data = pd.read_csv("accepted_2007_to_2017.csv")
# make a subset of data by randomly sampling (to work on it)
# subset = raw_data.sample(n=int(len(raw_data)/100))
# pre-processing steps
# 1 - find out null values
# raw_data.isnull().sum()
raw_data.info(verbose=True, null_counts=True)
raw_data.head()
for i in raw_data.columns:
if raw_data[i].isnull().sum() > (len(raw_data)/2):
# drop columns that contains more than half null values
raw_data = raw_data.drop(i, axis=1)
len(raw_data.columns)
# dropping columns that will be useless for EDA
# subset = subset.drop(["sub_grade", "pymnt_plan", "purpose", "zip_code",
# "addr_state"], axis=1)
# lets take a look at the loan_status variable of the data
raw_data["loan_status"].value_counts(dropna=False)
# in the output of above code, we can see that there are many status levels, but
# for this analysis we will be looking at loans that are either charged off or fully paid
# so, we will be dripping the rows that have status different than "Charged off" or "Fully Paid"
raw_data = raw_data.loc[raw_data["loan_status"].isin(["Fully Paid", "Charged Off"])]
print("We are now left with %d rows" % len(raw_data))
# check for NANs one more time
raw_data.info(verbose=True, null_counts=True)
# remove columns with NANs and columns that we don't need for further analysis
raw_data = raw_data.drop(["next_pymnt_d", "debt_settlement_flag", "disbursement_method", "hardship_flag",
"pymnt_plan", "title", ], axis=1)
# take a look at the basic stats of the numerical valued columns
raw_data.describe()
# drop the columns that do not have any significant amount of data related to them
# after going through every feature, i have compiled the following list of features to keep
# although i may have missed some important ones, but that wii not put any significant effect on the analysis
to_keep = ['addr_state', 'annual_inc', 'application_type', 'dti', 'earliest_cr_line', 'emp_length',
'emp_title', 'fico_range_high', 'fico_range_low', 'grade', 'home_ownership', 'id',
'initial_list_status', 'installment', 'int_rate', 'issue_d', 'loan_amnt', 'loan_status',
'mort_acc', 'open_acc', 'pub_rec', 'pub_rec_bankruptcies', 'purpose', 'revol_bal',
'revol_util', 'sub_grade', 'term', 'title', 'total_acc', 'verification_status', 'zip_code']
to_drop = [feat for feat in raw_data.columns if feat not in to_keep]
len(to_drop) # to be dropped
raw_data = raw_data.drop(to_drop, axis=1)
print("We are left with : ", raw_data.shape, "i.e %d rows(loans) and %d columns(features)" %(raw_data.shape))
# get rid of NANs everywhere
raw_data = raw_data.dropna()
raw_data.info(verbose=True, null_counts=True)
# this is the final data that we will be using for out analysis
raw_data.to_csv("cleaned_data.csv")
|
Java
|
UTF-8
| 563 | 2.65625 | 3 |
[] |
no_license
|
package epam.com.java.module1.collection.maintask.vegetables;
import epam.com.java.module1.collection.maintask.vegetables.categories.RootVegetables;
public class BeetRoot extends RootVegetables {
private static final int KCAL_PER_100G = 47;
public BeetRoot(){
super(VegetableName.BEET_ROOT, KCAL_PER_100G);
}
public BeetRoot(double weight) {
super(VegetableName.BEET_ROOT, KCAL_PER_100G, weight);
}
public BeetRoot(int kcalPer100g, double weight) {
super(VegetableName.BEET_ROOT, kcalPer100g, weight);
}
}
|
Java
|
UTF-8
| 9,638 | 2.953125 | 3 |
[] |
no_license
|
package com.comeaqui.eduardorodriguez.comeaqui.utilities;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static com.comeaqui.eduardorodriguez.comeaqui.App.USER;
public class DateFormatting {
static String[] WEEK_DAYS = {"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"};
public static Date convertToDate(String dateString) throws ParseException {
try {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
return format.parse(dateString);
} catch (Exception e){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
return format.parse(dateString);
}
}
public static String h(String dateString){
try {
Date date = convertToDate(dateString);
DateFormat df = new SimpleDateFormat("h:mm aa");
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
String dateTextString = df.format(date);
return dateTextString;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String hPost(String startDate){
try {
// https://stackoverflow.com/questions/32113211/saving-model-instance-with-datetimefield-in-django-admin-loses-microsecond-resol
Date date = convertToDate(startDate);
DateFormat df = new SimpleDateFormat("h:mm a");
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
String dateTextString = df.format(date);
return dateTextString;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static Date startOfToday(String timeZone) throws ParseException {
long now = System.currentTimeMillis();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setTimeZone(TimeZone.getTimeZone(timeZone));
String startTodayString = format.format(new Date(now));
return format.parse(startTodayString);
}
public static String todayYesterdayWeekDay(String dateString){
try {
Date date = convertToDate(dateString);
long now = System.currentTimeMillis();
long startOfDay = DateFormatting.startOfToday(USER.timeZone).getTime();
long differenceToDate = now - date.getTime();
long differenceToStartOrDay = now - startOfDay;
if (differenceToStartOrDay >= differenceToDate) {
return "TODAY";
} else if (differenceToStartOrDay + TimeUnit.DAYS.toMillis(1) >= differenceToDate && differenceToDate > differenceToStartOrDay) {
return "YESTERDAY";
} else if (differenceToStartOrDay + TimeUnit.DAYS.toMillis(7) >= differenceToDate && differenceToDate > differenceToStartOrDay + TimeUnit.DAYS.toMillis(1)) {
DateFormat dayNumberFormat = new SimpleDateFormat("u");
dayNumberFormat.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
return WEEK_DAYS[Integer.parseInt(dayNumberFormat.format(date)) - 1];
} else{
String pattern = "MM/dd/yyyy";
DateFormat df = new SimpleDateFormat(pattern);
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
return df.format(date);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String hhmmHappenedNowTodayYesterdayWeekDay(String dateString, String endDateString){
try {
Date date;
Date endDate;
try {
date = convertToDate(dateString);
endDate = convertToDate(endDateString);
} catch (ParseException e) {
try {
// https://stackoverflow.com/questions/32113211/saving-model-instance-with-datetimefield-in-django-admin-loses-microsecond-resol
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
date = format.parse(dateString);
endDate = format.parse(endDateString);
} catch (ParseException e2) {
return null;
}
}
long now = System.currentTimeMillis();
long startOfDay = DateFormatting.startOfToday(USER.timeZone).getTime();
long differenceToDate = now - date.getTime();
long differenceToStartOrDay = now - startOfDay;
String result;
if (now < date.getTime() - TimeUnit.DAYS.toMillis(2)){
DateFormat df = new SimpleDateFormat("EEE, MMM d");
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
result = df.format(date);
} else if (now < date.getTime() - TimeUnit.DAYS.toMillis(1)){
DateFormat df = new SimpleDateFormat("h:mm aa");
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
result = "TOMORROW";
} else if (now < date.getTime()) {
DateFormat df = new SimpleDateFormat("h:mm aa");
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
result = "TODAY";
} else if (date.getTime() <= now && now < endDate.getTime()){
result = "HAPPENING NOW";
} else if (differenceToDate <= differenceToStartOrDay) {
result = "HAPPENED TODAY";
} else if (differenceToDate <= differenceToStartOrDay + TimeUnit.DAYS.toMillis(1)) {
result = "YESTERDAY";
} else if (differenceToDate <= differenceToStartOrDay + TimeUnit.DAYS.toMillis(7)) {
int n = (int) (differenceToDate / TimeUnit.DAYS.toMillis(1));
result = n + " DAY" + (n > 1 ? "S " : " ") + "AGO";
} else if (differenceToDate <= differenceToStartOrDay + TimeUnit.DAYS.toMillis(30)) {
int n = (int) (differenceToDate / TimeUnit.DAYS.toMillis(7));
result = n + " WEEK" + (n > 1 ? "S " : " ") + " AGO";
} else if (differenceToDate <= differenceToStartOrDay + TimeUnit.DAYS.toMillis(30 * 12)) {
int n = (int) (differenceToDate / TimeUnit.DAYS.toMillis(30));
result = n + " MONTH" + (n > 1 ? "S " : " ") + " AGO";
} else {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
result = df.format(date);
}
return result.toUpperCase();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String timeRange(String dateString, String endDateString){
Date date;
Date endDate;
try {
date = convertToDate(dateString);
endDate = convertToDate(endDateString);
} catch (ParseException e) {
try {
// https://stackoverflow.com/questions/32113211/saving-model-instance-with-datetimefield-in-django-admin-loses-microsecond-resol
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
date = format.parse(dateString);
endDate = format.parse(endDateString);
} catch (ParseException e2) {
return null;
}
}
DateFormat df = new SimpleDateFormat("h:mm aa");
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
return df.format(date) + " - " + df.format(endDate);
}
public static String hYesterdayWeekDay(String dateString){
try {
Date date = convertToDate(dateString);
long now = System.currentTimeMillis();
long startOfDay = startOfToday(USER.timeZone).getTime();
long differenceToDate = now - date.getTime();
long differenceToStartOrDay = now - startOfDay;
if (differenceToStartOrDay >= differenceToDate) {
String pattern = "h:mm aa";
DateFormat df = new SimpleDateFormat(pattern);
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
return df.format(date);
} else if (differenceToStartOrDay + TimeUnit.DAYS.toMillis(1) >= differenceToDate && differenceToDate > differenceToStartOrDay) {
return "YESTERDAY";
} else if (differenceToStartOrDay + TimeUnit.DAYS.toMillis(7) >= differenceToDate && differenceToDate > differenceToStartOrDay + TimeUnit.DAYS.toMillis(1)) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return WEEK_DAYS[c.get(Calendar.DAY_OF_WEEK) - 1];
} else{
String pattern = "MM/dd/yyyy";
DateFormat df = new SimpleDateFormat(pattern);
df.setTimeZone(TimeZone.getTimeZone(USER.timeZone));
return df.format(date);
}
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
|
Shell
|
UTF-8
| 2,890 | 4.34375 | 4 |
[] |
no_license
|
#!/usr/bin/env bash
declare -r NAGIOS_SUCCESS=0 NAGIOS_WARNING=1 NAGIOS_CRITICAL=2 NAGIOS_UNKNOWN=3
declare -r NEW_LINE=$(echo -e '\n')
usage() {
echo "Usage: $0 [ OPTIONS ] <domain.tld>
Options
-d debug
-v verbosely print test steps (for testing only)
"
exit $NAGIOS_UNKNOWN
}
resolve_record() {
# params: server domain record_type
local server="$1"
local domain="$2"
local record_type="$3"
dig +short ${server:+"@$server"} "$domain" "$record_type" 2>/dev/null
}
error() {
local msg=${1:-""}
local code=${2:-$NAGIOS_UNKNOWN}
echo "Error: $msg" >&2
exit $code
}
is_in_array() {
local value="$1"
shift
local v
for v in "$@"; do
if [ "$v" == "$value" ]; then
return 0
fi
done
return 1
}
verbose_line() {
local line="$1"
if [ $verbose -eq 0 ]; then
return 1
fi
echo -e "$line\n"
}
# main
verbose=0
getopt_flags='vd'
while getopts $getopt_flags OPT; do
case $OPT in
d)
set -x
;;
v)
verbose=1
;;
*)
exit 1
;;
esac
done
shift $(( $OPTIND - 1 ))
[ -z "$1" ] && usage
if ! hash dig &>/dev/null; then
echo "Error: couldn't find binary dig in PATH. This script depends on it." >&2
exit $NAGIOS_UNKNOWN
fi
domain="$1"
verbose_line "Trying to get DNS servers for domain $domain..."
records=$(resolve_record '' "$1" ns)
status=$?
if [ $status -ne 0 ]; then
echo "CRITICAL - unable to resolve dns for domain '$1'. resolve_records() returned $status"
exit $NAGIOS_CRITICAL
elif [ -z "$records" ]; then
echo "CRITICAL - received an empty response while resolving NS servers for domain '$domain'"
exit $NAGIOS_CRITICAL
fi
verbose_line "Found `echo "$records" | wc -l` servers for domain $domain:\n$records"
declare -a servers_ar
read -d "$NEW_LINE" -a servers_ar <<< "$records"
declare -a serials_ar
declare -i n_successful_rsps=0
declare -i n_failed_rsps=0
for server in ${servers_ar[@]}; do
verbose_line "Testing server '$server'..."
soa=$(resolve_record "$server" "$domain" soa)
if [ $? -ne 0 -o -z "$soa" ]; then
n_failed_rsps+=1
verbose_line "Failed querying $server" >&2
continue
fi
verbose_line "Received SOA: $soa"
IFS=" " read dns1 email serial remaining <<< "$soa"
verbose_line "Serial: $serial"
if ! is_in_array "$serial" "${serials_ar[@]}"; then
serials_ar+=( "$serial" )
fi
done
n_serials=${#serials_ar[@]}
n_servers=${#servers_ar[@]}
if [ $n_serials -eq 0 ]; then
echo "CRITICAL - domain $domain, received no response from the $n_servers servers tested"
exit $NAGIOS_CRITICAL
elif [ $n_serials -eq 1 ]; then
echo "OK - domain $domain, received the same serial number from $n_servers servers. Serial: ${serials_ar[0]}"
exit $NAGIOS_OK
else
echo "CRITICAL - domain $domain, received $n_serials different serial numbers from $n_servers servers tested"
exit $NAGIOS_CRITICAL
fi
|
C++
|
UTF-8
| 949 | 2.765625 | 3 |
[] |
no_license
|
/*
* dataset obtained from https://pjreddie.com/projects/mnist-in-csv/
* Author: Shuhao Lai
* Date: 12/27/2018
* Main.cpp
*/
#include <iostream>
#include <ctime>
#include "DigitClassifier.h"
int main()
{
clock_t begin = clock();
std::vector<int> conditions = {784, 30, 10};
DigitClassifier test(conditions);
std::cout << "Training the neural network." << std::endl;
test.train("mnist_train.csv", 30, 20, 3);
std::cout << "Training complete." << std::endl;
test.toString("Trained1.txt");
std::clock_t trained = clock();
test.evaluate("mnist_test.csv");
std::cout << "Evaluation complete." << std::endl;
std::clock_t done = clock();
double timeToTrain = (double(trained-begin) / CLOCKS_PER_SEC)/60;
double timeToFinish = (double(done-begin) / CLOCKS_PER_SEC)/60;
std::cout << "Time to train: " << timeToTrain << " minutes" << std::endl;
std::cout << "Time to finish everything: " << timeToFinish << " minutes" << std::endl;
}
|
TypeScript
|
UTF-8
| 1,646 | 2.59375 | 3 |
[] |
no_license
|
import { checker } from "./checker"
import { observer } from "./observer"
import { render } from "./render"
export class validation{
private config:{"query":string} = {
"query": "input"
};
private chk: checker;
private obsrv: observer;
private r: render;
constructor(config:any = {}){
if (config['query']){
this.config["query"] = config['query'];
}
this.chk = new checker();
this.obsrv = new observer();
this.r = new render();
}
public check = ():void =>{
const inputAll = document.querySelectorAll(this.config.query);
Array.from(inputAll, input => {
this.chk.msg = [];
console.log("required:", input.getAttribute("required"));
//未入力
if (input.getAttribute("required")!==null){
this.obsrv.on(this.chk.require, {});
}
//メルアド
if (input.getAttribute("mail")!==null){
this.obsrv.on(this.chk.mail_address, {});
}
//郵便番号
if (input.getAttribute("postalcode")!==null){
this.obsrv.on(this.chk.postal_code, {});
}
//最小文字数
let min: any;
if (min = input.getAttribute("data-minlength")){
this.obsrv.on(this.chk.min_length, {min:min});
}
console.log("min:", min);
//最大文字数
let max: any;
if (max = input.getAttribute("data-maxlength")){
this.obsrv.on(this.chk.max_length, {max:max});
}
console.log("max:", max);
this.obsrv.trigger((input as HTMLInputElement).value);
console.log(this.chk.msg);
this.r.errorMsg(input, this.chk.msg);
});
}
}
|
Java
|
UTF-8
| 4,163 | 1.789063 | 2 |
[] |
no_license
|
import java.util.List;
import java.util.Random;
public class bng extends bnn {
private boolean a;
public bng() {}
public bng(bnk var1, int var2, Random var3, bjb var4, ej var5) {
super(var1, var2);
this.m = var5;
this.l = var4;
this.a = var3.nextBoolean();
}
protected void a(fn var1) {
super.a(var1);
var1.a("Terrace", this.a);
}
protected void b(fn var1) {
super.b(var1);
this.a = var1.n("Terrace");
}
public static bng a(bnk var0, List var1, Random var2, int var3, int var4, int var5, ej var6, int var7) {
bjb var8 = bjb.a(var3, var4, var5, 0, 0, 0, 5, 6, 5, var6);
return bms.a(var1, var8) != null?null:new bng(var0, var7, var2, var8, var6);
}
public boolean a(aqu var1, Random var2, bjb var3) {
if(this.h < 0) {
this.h = this.b(var1, var3);
if(this.h < 0) {
return true;
}
this.l.a(0, this.h - this.l.e + 6 - 1, 0);
}
this.a(var1, var3, 0, 0, 0, 4, 0, 4, aty.e.P(), aty.e.P(), false);
this.a(var1, var3, 0, 4, 0, 4, 4, 4, aty.r.P(), aty.r.P(), false);
this.a(var1, var3, 1, 4, 1, 3, 4, 3, aty.f.P(), aty.f.P(), false);
this.a(var1, aty.e.P(), 0, 1, 0, var3);
this.a(var1, aty.e.P(), 0, 2, 0, var3);
this.a(var1, aty.e.P(), 0, 3, 0, var3);
this.a(var1, aty.e.P(), 4, 1, 0, var3);
this.a(var1, aty.e.P(), 4, 2, 0, var3);
this.a(var1, aty.e.P(), 4, 3, 0, var3);
this.a(var1, aty.e.P(), 0, 1, 4, var3);
this.a(var1, aty.e.P(), 0, 2, 4, var3);
this.a(var1, aty.e.P(), 0, 3, 4, var3);
this.a(var1, aty.e.P(), 4, 1, 4, var3);
this.a(var1, aty.e.P(), 4, 2, 4, var3);
this.a(var1, aty.e.P(), 4, 3, 4, var3);
this.a(var1, var3, 0, 1, 1, 0, 3, 3, aty.f.P(), aty.f.P(), false);
this.a(var1, var3, 4, 1, 1, 4, 3, 3, aty.f.P(), aty.f.P(), false);
this.a(var1, var3, 1, 1, 4, 3, 3, 4, aty.f.P(), aty.f.P(), false);
this.a(var1, aty.bj.P(), 0, 2, 2, var3);
this.a(var1, aty.bj.P(), 2, 2, 4, var3);
this.a(var1, aty.bj.P(), 4, 2, 2, var3);
this.a(var1, aty.f.P(), 1, 1, 0, var3);
this.a(var1, aty.f.P(), 1, 2, 0, var3);
this.a(var1, aty.f.P(), 1, 3, 0, var3);
this.a(var1, aty.f.P(), 2, 3, 0, var3);
this.a(var1, aty.f.P(), 3, 3, 0, var3);
this.a(var1, aty.f.P(), 3, 2, 0, var3);
this.a(var1, aty.f.P(), 3, 1, 0, var3);
if(this.a(var1, 2, 0, -1, var3).c().r() == bof.a && this.a(var1, 2, -1, -1, var3).c().r() != bof.a) {
this.a(var1, aty.aw.a(this.a(aty.aw, 3)), 2, 0, -1, var3);
}
this.a(var1, var3, 1, 1, 1, 3, 3, 3, aty.a.P(), aty.a.P(), false);
if(this.a) {
this.a(var1, aty.aO.P(), 0, 5, 0, var3);
this.a(var1, aty.aO.P(), 1, 5, 0, var3);
this.a(var1, aty.aO.P(), 2, 5, 0, var3);
this.a(var1, aty.aO.P(), 3, 5, 0, var3);
this.a(var1, aty.aO.P(), 4, 5, 0, var3);
this.a(var1, aty.aO.P(), 0, 5, 4, var3);
this.a(var1, aty.aO.P(), 1, 5, 4, var3);
this.a(var1, aty.aO.P(), 2, 5, 4, var3);
this.a(var1, aty.aO.P(), 3, 5, 4, var3);
this.a(var1, aty.aO.P(), 4, 5, 4, var3);
this.a(var1, aty.aO.P(), 4, 5, 1, var3);
this.a(var1, aty.aO.P(), 4, 5, 2, var3);
this.a(var1, aty.aO.P(), 4, 5, 3, var3);
this.a(var1, aty.aO.P(), 0, 5, 1, var3);
this.a(var1, aty.aO.P(), 0, 5, 2, var3);
this.a(var1, aty.aO.P(), 0, 5, 3, var3);
}
int var4;
if(this.a) {
var4 = this.a(aty.au, 3);
this.a(var1, aty.au.a(var4), 3, 1, 3, var3);
this.a(var1, aty.au.a(var4), 3, 2, 3, var3);
this.a(var1, aty.au.a(var4), 3, 3, 3, var3);
this.a(var1, aty.au.a(var4), 3, 4, 3, var3);
}
this.a(var1, aty.aa.P().a(bbl.a, this.m), 2, 3, 1, var3);
for(var4 = 0; var4 < 5; ++var4) {
for(int var5 = 0; var5 < 5; ++var5) {
this.b(var1, var5, 6, var4, var3);
this.b(var1, aty.e.P(), var5, -1, var4, var3);
}
}
this.a(var1, var3, 1, 1, 2, 1);
return true;
}
}
|
PHP
|
UTF-8
| 2,340 | 3.0625 | 3 |
[] |
no_license
|
<?php
//Form Init
$title = '';
$email = '';
$ingredients = '';
//validation
$errors = array('email'=>'', 'title'=>'', 'ingredients'=>'');
if(isset($_POST['submit'])) {
if(empty($_POST['email'])) {
$errors['email'] = 'An Email is Required';
} else {
$email = $_POST['email'];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] ='Email must be a valid email address';
}
}
if(empty($_POST['title'])) {
$errors['title'] = 'A Recipe Name is Required';
} else {
$title = $_POST['title'];
//Letters and spaces only
if(!preg_match('/^[a-zA-Z\s]+$/', $title)) {
$errors['title'] ='Title must only contain letters';
}
}
if(empty($_POST['list'])) {
$erors['ingredients'] = 'At least one ingredient is Required';
} else {
$ingredients = $_POST['list'];
//Looking for a comma separated list
if(!preg_match('/(^[a-zA-Z\s]+)(,\s*[a-zA-Z\s]*)*$/', $ingredients)) {
$erors['ingredients'] = 'Each ingredient must be separated by a comma';
}
}
}
?>
<!DOCTYPE html>
<html>
<?php include('templates/header.php'); ?>
<section class="container grey-text">
<h4 class="center">
Add a Post
</h4>
<form action="add.php" method="post" class="white"
style="padding: 2rem 14rem;
margin: 2rem 0">
<label>Your Email</label>
<input type="text" name="email" value="<?php echo htmlspecialchars($email) ?>">
<p class="red-text">
<?php echo $errors['email'] ?>
</p>
<label>Recipe Name</label>
<input type="text" name="title" value="<?php echo htmlspecialchars($title) ?>">
<p class="red-text">
<?php echo $errors['title'] ?>
</p>
<label>Ingredients (comma separated):</label>
<input type="text" name="list" value="<?php echo htmlspecialchars($ingredients) ?>">
<p class="red-text">
<?php echo $errors['ingredients'] ?>
</p>
<div class="center">
<input type="submit" name="submit" value="submit" class="btn z-depth-0">
</div>
</form>
</section>
<?php include('templates/footer.php'); ?>
</html>
|
Python
|
UTF-8
| 7,927 | 2.71875 | 3 |
[] |
no_license
|
import os, datetime, json
class PresetFile:
def __init__(self, pathToFile):
self.lineDic = {}
self.maxTemp = 0
self.maxForce = 0
self.runTimeS = 0
self.minPressure = 99
self.lastAccess = ''
self.runTime = ''
self.loadFile(pathToFile)
def loadFile(self, pathToFile):
with open(pathToFile, 'r') as f: #NEEDS ERROR HANDLING
lines = f.readlines()
lenLines = len(lines)
linePtr = 0
while lines[linePtr].split(',')[0] != '':
obj = lines[linePtr].split(',')
if obj[2] != '':
self.lineDic[str(obj[0])] = ','.join(obj[1:])
else:
self.lineDic[str(obj[0])] = str(obj[1])
linePtr += 1
linePtr += 1
self.headers = [x.strip('\n') for x in lines[linePtr].split(',')]
lenHeaders = len(self.headers)
for header in self.headers:
self.lineDic[header.strip('\n')] = []
linePtr += 1
while linePtr < lenLines:
obj = lines[linePtr].split(',')
for i in range(lenHeaders):
if obj[i][0] != '~':
self.lineDic[self.headers[i]].append(float(obj[i]))
else:
self.lineDic[self.headers[i]].append(obj[i].strip('\n'))
linePtr += 1
self.getMaxForce()
self.getMaxTemp()
self.getLastAccess(pathToFile)
self.getTimeRead()
def getLastAccess(self, pathToFile=None):
#https://stackoverflow.com/questions/39359245/from-stat-st-mtime-to-datetime
if self.lastAccess == '' and pathToFile != None:
self.lastAccess = datetime.datetime.fromtimestamp(os.stat(pathToFile).st_atime)
return self.lastAccess
def getMaxTemp(self):
if self.maxTemp == 0:
self.maxTemp = self._getMax(self.getTempLst())
return self.maxTemp
def getMaxForce(self):
if self.maxForce == 0:
self.maxForce = self._getMax(self.getForceLst())
return self.maxForce
def getMinPressure(self):
if self.minPressure == 99:
self.minPressure = self._getMin(self.getPressLst())
return self.minPressure
def _getMin(self, lst):
currMin = 999999999999999999
for x in lst:
if x != '~' and x < currMin:
currMin = x
if currMin == 999999999999999999:
return '~'
return currMin
def _getMax(self, lst):
currMax = 0
for x in lst:
if x != '~' and x > currMax:
currMax = x
return currMax
def getForceLst(self, rep=0):
return [x if x != '~' else rep for x in self.lineDic['Force']]
def getPressLst(self, rep=0):
return [x if x != '~' else rep for x in self.lineDic['Press']]
def getTempLst(self, rep=0):
return [x if x != '~' else rep for x in self.lineDic['Temp']]
def getTimeLst(self, rep=0):
return [x if x != '~' else rep for x in self.lineDic['Time (min)']]
def getName(self):
return self.lineDic['Name']
def getDetails(self):
return self.lineDic['User Notes']
def getTimeS(self):
if self.runTimeS == 0:
obj = self.lineDic['Run Time'].split(':')
self.runTimeS = obj[0] * 60 * 60 + obj[1] * 60 + obj[2]
return self.runTimeS
def getTimeRead(self):
if self.runTime == '':
lst = self.getTimeLst()
lastTime = lst[-1]
hrs = str(int(lastTime // 60))
mins = str(int(lastTime % 60))
self.runTime = ':'.join([hrs, mins, '00'])
return self.runTime
class SettingsFile:
def __init__(self, filename="", load=True):
self.filename = filename
if load:
self.loadFile(filename)
def _contWithDefaults(self):
print("[WARNING] - Attempting to continue with hard coded defaults...")
defaultString = "{'Root_Directory': '/home/pi/Documents/GUI_PyQt_Combined', 'Network_Directory': '/home/pi/Documents/GUI_PyQt_Combined/Network/', 'Presets_Directory': '/home/pi/Documents/GUI_PyQt_Combined/Presets', 'Full_Screen_Mode': False, 'Width': 1240, 'Height': 1024}"
self.json = json.load(j)
def loadFile(self, filename=None):
try:
with open(filename) as j:
jsonTemp = json.load(j)
jsonDefaults = jsonTemp['DEFAULTS']
if not jsonTemp['use_defaults'] or jsonTemp['changes']: #defaults: false or changes: true, ie. custom settings
if "key_list" not in jsonDefaults:
print("[WARNING] - 'key_list' MUST be in 'DEFAULT' of settings file")
self._contWithDefaults()
else:
keyList = jsonDefaults['key_list']
self.json = {}
for key in keyList:
if key in jsonTemp:
self.json[key] = jsonTemp[key]
else:
self.json[key] = jsonDefaults[key]
else:
self.json = jsonTemp
except FileNotFoundError as e:
print("[WARNING] - File: {} not found!".format(filename))
self._contWithDefaults()
def setParam(self, param, value):
# print(self.json)
if param != 'DEFAULTS':
# if self.json['use_defaults']: # True, ie first modification
# self.json['DEFAULTS'] = json.dumps(self.json)
self.json['use_defaults'] = False
self.json['changes'] = True
self.json[param] = value
with open(self.filename, 'w') as f:
json.dump(self.json, f)
else:
print("Cannot override 'DEFAULT'")
def resetDefaults(self):
self.json['use_defaults'] = True
self.json['changes'] = False
with open(self.filename, 'w') as f:
json.dump(self.json, f)
def getRoot(self):
if not self.getDefault() and 'Root_Directory' in self.json:
return self.json['Root_Directory']
else:
return self.json['DEFAULTS']['Root_Directory']
def getNetwork(self):
if not self.getDefault() and 'Network_Directory' in self.json:
return self.json['Network_Directory']
else:
return self.json['DEFAULTS']['Network_Directory']
def getPreset(self):
if not self.getDefault() and 'Presets_Directory' in self.json:
return self.json['Presets_Directory']
else:
return self.json['DEFAULTS']['Presets_Directory']
def getWidth(self):
if not self.getDefault() and 'Width' in self.json:
return int(self.json['Width'])
else:
return int(self.json['DEFAULTS']['Width'] )
def getHeight(self):
if not self.getDefault() and 'Height' in self.json:
return int(self.json['Height'])
else:
return int(self.json['DEFAULTS']['Height'] )
def getFullScreen(self):
if not self.getDefault() and 'Full_Screen_Mode' in self.json:
return self.json['Full_Screen_Mode']
else:
return self.json['DEFAULTS']['Full_Screen_Mode']
def getDefault(self):
return self.json['use_defaults']
def getChanges(self):
return self.json['changes']
def getBk(self):
if not self.getDefault() and 'use_background' in self.json:
return self.json['use_background']
else:
return self.json['DEFAULTS']['use_background']
if __name__ == "__main__":
PresetFile('GUI_PyQt_Combined/Presets/test1.csv')
|
TypeScript
|
UTF-8
| 1,053 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
module Utils.Measurements {
export class Size{
constructor (public width: number, public height: number){}
}
export class Dimensions {
static fitRect(width1: number, height1: number, width2: number, height2: number): Size {
var ratio1 = height1 / width1;
var ratio2 = height2 / width2;
var width, height, scale;
if (ratio1 < ratio2) {
scale = width2 / width1;
width = width1 * scale;
height = height1 * scale;
}
if (ratio2 < ratio1) {
scale = height2 / height1;
width = width1 * scale;
height = height1 * scale;
}
return new Size(Math.floor(width), Math.floor(height));
}
static hitRect(x: number, y: number, w: number, h: number, mx: number, my: number) {
if (mx > x && mx < (x + w) && my > y && my < (y + h)) {
return true;
}
return false;
}
}
}
|
Python
|
UTF-8
| 605 | 2.828125 | 3 |
[] |
no_license
|
from tools.tools_module import *
from pyautogui import *
import webbrowser
query =""
def google_search(inputType,self):
speak('Now Google is ready. Please tell me, What do you want to search?')
global query
if inputType in ['userInput']:
query = prompt(text='Search Query', title='Say Something..' , default='').lower()
else:
query = takeCommand(self).lower()
speak('This query is searching on google, by using your web brawser.')
speak('Please wait....')
# print("Query Searching...")
webbrowser.open("https://www.google.com/search?q="+query)
|
C++
|
UTF-8
| 4,556 | 2.515625 | 3 |
[] |
no_license
|
#include "MQ_SQNodes.hpp"
#include "MQException.hpp"
#include "MQT.hpp"
namespace Galaxy
{
namespace AMQ
{
void CSQNode::Init()
{
_Next = 0L;
_PageLKTB = 0L;
_Length = 0U;
}
PBYTE CSQNode::NearPtr() const
{
return ((PBYTE)this)+ sizeof(*this);
}
void CSQNode::Next(const CSQNode *_TheNode) const
{
CSQNode *_This = (CSQNode *)this;
if(ISNULL(_TheNode))
{
_This->_Next = 0L;
}
else
{
_This->_Next = ((PBYTE)_TheNode) - ((PBYTE)this);
}
}
const CSQNode *CSQNode::Next() const
{
if(_Next == 0L)
{
return NULL;
}
else
{
return (CSQNode *)(((PBYTE)this) + _Next);
}
}
void CSQNode::Page(const CSQPage *_ThePage) const
{
CSQNode *_This = (CSQNode *)this;
if(ISNULL(_ThePage))
{
_This->_PageLKTB = 0L;
}
else
{
_This->_PageLKTB = ((PBYTE)_ThePage) - ((PBYTE)this);
}
}
const CSQPage *CSQNode::Page() const
{
if(_PageLKTB == 0L)
{
return NULL;
}
else
{
return (CSQPage *)(((PBYTE)this) + _PageLKTB);
}
}
void CSQNode::Length(UINT _TheLength) const
{
CSQNode *_This = (CSQNode *)this;
_This->_Length = _TheLength;
}
UINT CSQNode::Length() const
{
return _Length;
}
/*CSQNodeArray*/
void CSQNodeArray::Init(UINT _TheTotal)
{
_Total = _TheTotal;
{
CSQNode *_TheNode = NULL;
for(UINT i=0;i<_TheTotal;i++)
{
_TheNode = (CSQNode *)this->operator[](i);
if(_TheNode!=NULL)
{
_TheNode->Init();
//printf("%d -- this:0x%X;Total:%d;Node:0x%X\n",i,this,_Total,_TheNode);
}
}
}
{
PBYTE _TheMask = (PBYTE)&_MSK; //.ALC
_TheMask[0] = 0x2E;
_TheMask[1] = 0x4E;
_TheMask[2] = 0x44;
_TheMask[3] = 0x53;
}
}
bool CSQNodeArray::Check() const
{
{
const PBYTE _TheMask = (const PBYTE)&_MSK;
return (_TheMask[0] == 0x2E) && \
(_TheMask[1] == 0x4E) && \
(_TheMask[2] == 0x44) && \
(_TheMask[3] == 0x53);
}
}
PBYTE CSQNodeArray::NearPtr() const
{
return ((PBYTE)this)+ sizeof(*this);
}
UINT CSQNodeArray::Count() const
{
return _Total;
}
const CSQNode *CSQNodeArray::operator[](UINT _Index) const
{
CSQNode *_TheNode = NULL;
if(_Index < _Total)
{
PBYTE _PageEntry = NearPtr();
_TheNode = (CSQNode *) &_PageEntry[(sizeof(CSQNode) * _Index)];
}
return _TheNode;
}
/*CSQLockedList*/
void CSQLockedList::Init()
{
_Lock.Init();
_List.Init();
{
PBYTE _TheMask = (PBYTE)&_MSK; //.ALC
_TheMask[0] = 0x2E;
_TheMask[1] = 0x4C;
_TheMask[2] = 0x4B;
_TheMask[3] = 0x4C;
}
}
bool CSQLockedList::Check() const
{
{
const PBYTE _TheMask = (const PBYTE)&_MSK;
return (_TheMask[0] == 0x2E) && \
(_TheMask[1] == 0x4C) && \
(_TheMask[2] == 0x4B) && \
(_TheMask[3] == 0x4C);
}
}
PBYTE CSQLockedList::NearPtr() const
{
return ((PBYTE)this)+ sizeof(*this);
}
UINT CSQLockedList::Count() const
{
return _List.Count();
}
const CSQNode *CSQLockedList::Get() const
{
CMQLockGuard< CSQLock > _LGuard(_Lock);
const CSQNode *_TheNode = NULL;
if(_List.Count() > 0)
{
_TheNode = _List.Get();
if(ISNULL(_TheNode))
{
THROW_MQNULLEXCEPTION(_TheNode);
}
}
return (_TheNode);
}
void CSQLockedList::Put2Head(const CSQNode &_TheNode) const
{
CMQLockGuard< CSQLock > _LGuard(_Lock);
_List.Put2Head(_TheNode);
}
void CSQLockedList::Put2Tail(const CSQNode &_TheNode) const
{
CMQLockGuard< CSQLock > _LGuard(_Lock);
_List.Put2Head(_TheNode);
}
/*CSQPooler*/
void CSQPooler::Init(UINT _Nodes)
{
_Queue.Init();
_Array.Init(_Nodes);
{
const CSQNode *_TheNode = NULL;
for(UINT i=0;i<Nodes();i++)
{
_TheNode = _Array[i];
if(_TheNode)
{
_Queue.Put2Tail(*_TheNode);
}
}
}
if(Nodes()!=UsableNodes())
{
THROW_MQEXCEPTION("Init failed!");
}
{
PBYTE _TheMask = (PBYTE)&_MSK; //.ALC
_TheMask[0] = 0x2E;
_TheMask[1] = 0x50;
_TheMask[2] = 0x4C;
_TheMask[3] = 0x52;
}
}
bool CSQPooler::Check() const
{
{
const PBYTE _TheMask = (const PBYTE)&_MSK;
return _Queue.Check() && _Array.Check() && \
(_TheMask[0] == 0x2E) && \
(_TheMask[1] == 0x50) && \
(_TheMask[2] == 0x4C) && \
(_TheMask[3] == 0x52);
}
}
PBYTE CSQPooler::NearPtr() const
{
return ((PBYTE)this)+ sizeof(*this);
}
UINT CSQPooler::UsableNodes() const
{
return _Queue.Count();
}
UINT CSQPooler::Nodes() const
{
return _Array.Count();
}
const CSQNode *CSQPooler::Get() const
{
return _Queue.Get();
}
void CSQPooler::Put(const CSQNode &_TheNode) const
{
_Queue.Put2Head(_TheNode);
}
UINT EvaluatePooler(UINT _Nodes)
{
return sizeof(CSQPooler)+(sizeof(CSQNode) * _Nodes);
}
};
};
|
C++
|
UTF-8
| 664 | 3.328125 | 3 |
[] |
no_license
|
#ifndef Sofa_h
#define Sofa_h
#include <iostream>
#include "Mebel.h"
class Sofa : virtual public Mebel {
public:
friend std::ostream & operator<<(std::ostream &buffer, const Sofa &furniture) {
furniture.print(buffer);
return buffer;
}
Sofa(int w, int h, int l, int s) : Mebel(w, h, l), sedentary(s) {} // if Mebel...Sofa(s) then error - delegating doesn't work
Sofa(int s = 0) : sedentary(s) {}
virtual ~Sofa() { std::cout << "~Sofa\n"; }
virtual void print(std::ostream &b) const;
protected:
const int sedentary;
};
void Sofa::print(std::ostream &b) const {
b << "Sofa: ";
Mebel::print(b);
b << " siedzisko: " << sedentary;
}
#endif
|
JavaScript
|
UTF-8
| 1,094 | 2.734375 | 3 |
[] |
no_license
|
let express = require('express');
let router = express.Router();
let User = require('../models/user');
router.get('/form', ((req,res) =>{
res.render('form')
}));
// Register User
router.post('/form', function(req, res){
let firstName = req.body.firstName;
let lastName = req.body.lastName;
let email = req.body.email;
let major = req.body.major;
let diet = req.body.diet;
let gender = req.body.gender;
// Validation
req.checkBody('firstName', 'First Name is required').notEmpty();
req.checkBody('lastName', 'Last Name is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
let errors = req.validationErrors();
if(errors){
res.render('form',{
errors:errors
});
} else {
var newUser = new User({
firstName: firstName,
lastName: lastName,
email:email,
major:major,
diet:diet,
gender:gender,
});
User.addUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
res.redirect('/');
}
});
module.exports = router;
|
Python
|
UTF-8
| 1,095 | 2.796875 | 3 |
[] |
no_license
|
import sys
import random
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MyWidget(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 420, 400)
self.btn = QPushButton(self)
self.btn.move(180, 15)
self.btn.resize(100, 30)
self.btn.setText('Показать')
self.btn.clicked.connect(self.click)
self.flag = False
def click(self):
self.flag = True
self.update()
def paintEvent(self, event):
if self.flag:
qp = QPainter()
qp.begin(self)
self.draw(qp)
qp.end()
def draw(self, qp):
qp.setBrush(QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
a = random.randint(20, 180)
b = random.randint(25, 180)
f = random.randint(1, 180)
qp.drawEllipse(a, b, f, f)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec_())
|
Java
|
IBM852
| 472 | 2.484375 | 2 |
[] |
no_license
|
package store.wine.model.dto;
/**
* Classe que recebe os dados do servio REST de atualizar status do pedido
* @author eduardo
* @version 1.0
*
*/
public class OrderStateDTO {
private Integer orderId;
private String state;
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
|
C#
|
UTF-8
| 2,507 | 2.53125 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Brain : MonoBehaviour {
public float speed = 8 //Bale pos no voy a decir nada, me gusta la idea pero kcyo dejame esta bien T.T
, acceleration = 12
, jumpForce = 10
, currentSpeed
, playerSpeed;
private Player player;
private Vector2 amountToMove;
public bool ground,
spammingSpace;
void Start() {
player = GetComponent<Player>();
}
void Update() {
}
private void FixedUpdate()
{ //Todas las funciones o cosas que tengan que ver con fisicas, aca. Tanto colisiones como movimiento o lo que sea
playerSpeed = Input.GetAxisRaw("Horizontal") * speed;
currentSpeed = Move(currentSpeed, playerSpeed, acceleration); //Lo hace con aceleracion, esta a proposito? RTA: ¿Por? ¿Acaso afecta en algop?
amountToMove = new Vector2(currentSpeed, 0);
player.Move(amountToMove * Time.deltaTime);
if (player.body.velocity.y < -0.1 && ground) {
ground = false;
} else ground = true;
//Salto
if (Input.GetButton("Jump") && !spammingSpace) //Cambie esto, mirate el tema de los bools
{
float _tempJumpForce = jumpForce;
player.Jump(_tempJumpForce);
spammingSpace = true;
if (spammingSpace)
{
_tempJumpForce -= 1;
}
if (ground)
{
//spammingSpace = true;
ground = false;
}
}
}
public float Move(float n, float target, float a) {
if (n == target) return n;
else if(!ground) {
float dir = Mathf.Sign(target - n);
n += a * Time.deltaTime * dir;
print(((dir == Mathf.Sign(target - n)) ? n : target));
return ((dir == Mathf.Sign(target - n)) ? n : target);
}
else {
float dir = Mathf.Sign(target - n);
n += a * Time.deltaTime * dir;
return (dir == Mathf.Sign(target - n)) ? n : target;
}
}
void OnCollisionEnter2D(Collision2D c) {
if(c.gameObject.layer == LayerMask.NameToLayer("Floor")) {
// Delay to this ->
player.body.velocity = Vector3.zero;
player.body.angularVelocity = 0f;
ground = true;
spammingSpace = false;
}
}
}
|
Java
|
UTF-8
| 1,805 | 2.296875 | 2 |
[] |
no_license
|
package com.appsnipp.loginsamples;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import static com.appsnipp.loginsamples.R.id.img_back;
public class ProfileActivity extends AppCompatActivity {
TextView textViewId, textViewUsername, textViewName, textViewlevel;
ImageView btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
init();
}
void init(){
Button back = findViewById(R.id.btn_back);
textViewId = findViewById(R.id.textViewId);
textViewUsername = findViewById(R.id.textViewUsername);
textViewName = findViewById(R.id.textViewName);
textViewlevel = findViewById(R.id.textViewlevel);
btn = (ImageView)findViewById(img_back);
//getting the current user
User user = PrefManager.getInstance(this).getUser();
//setting the values to the textviews
textViewId.setText(String.valueOf(user.getId()));
textViewUsername.setText(user.getUsername());
textViewName.setText(user.getEmail());
textViewlevel.setText(user.getGroupID());
//when the user presses logout button calling the logout method
back.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
finish();
}
});
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
Java
|
UTF-8
| 572 | 4.40625 | 4 |
[
"MIT"
] |
permissive
|
// You are given a pointer to the root of a binary tree; print the values in inorder traversal.
// Print the values on a single line separated by space.
/* you only have to complete the function given below.
* Node is defined as
*
* class Node {
* int data;
* Node left;
* Node right;
* }
*/
void Inorder(Node root) {
// Check if the root is null
if(root != null) {
// Visit the left child
Inorder(root.left);
// Print the data
System.out.print(root.data + " ");
// Visit the right child
Inorder(root.right);
}
}
|
TypeScript
|
UTF-8
| 2,116 | 2.8125 | 3 |
[
"MIT",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
makeTextAnalyticsSuccessResult,
TextAnalyticsSuccessResult,
TextAnalyticsErrorResult,
makeTextAnalyticsErrorResult
} from "./textAnalyticsResult";
import {
TextAnalyticsError,
ExtractedDocumentSummary,
ExtractedSummarySentence as GeneratedSummarySentences
} from "./generated/models";
/**
* The result of the extract summary operation on a single document.
*/
export type ExtractSummaryResult = ExtractSummarySuccessResult | ExtractSummaryErrorResult;
/**
* The result of the extract summary operation on a single document,
* containing a collection of the summary identified in that document.
*/
export interface ExtractSummarySuccessResult extends TextAnalyticsSuccessResult {
/**
* A list of sentences composing a summary of the input document.
*/
sentences: SummarySentence[];
}
/**
* An extracted sentence as part of the summary of a document.
*/
export interface SummarySentence {
/** The extracted sentence text. */
text: string;
/** A double value representing the relevance of the sentence within the summary. Higher values indicate higher importance. */
rankScore: number;
/** The sentence offset from the start of the document, based on the value of the stringIndexType parameter. */
offset: number;
/** The length of the sentence. */
length: number;
}
/**
* An error result from the extract summary operation on a single document.
*/
export type ExtractSummaryErrorResult = TextAnalyticsErrorResult;
/**
* @internal
*/
export function makeExtractSummaryResult(
result: ExtractedDocumentSummary
): ExtractSummarySuccessResult {
const { id, warnings, statistics, sentences } = result;
return {
...makeTextAnalyticsSuccessResult(id, warnings, statistics),
sentences: sentences.map((sentence: GeneratedSummarySentences) => ({
...sentence
}))
};
}
/**
* @internal
*/
export function makeExtractSummaryErrorResult(
id: string,
error: TextAnalyticsError
): ExtractSummaryErrorResult {
return makeTextAnalyticsErrorResult(id, error);
}
|
C++
|
UTF-8
| 1,104 | 3.453125 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h> //<cstdlib>
#include <time.h> //<ctime>
using namespace std;
int main()
{
srand(time(NULL));
int myInt;
myInt = rand() % 5 + 1;
cout << myInt << endl;
switch (myInt)
{
case 1:
case 2:
case 3:
cout << "Oxen didn't like you, go to jail." << endl;
break;
case 4:
case 5:
cout << "Oxen and I movie coming Summer 2016" << endl;
break;
// default:
// cout << "What happened?" << endl;
// break;
}
string direction;
cout << "Walk to the left or right: ";
cin >> direction;
int chance = rand() % 5 + 1;
if (direction == "left")
chance += 5;
switch (chance)
{
case 1:
cout << "What were you thinking?!?! Always walk left!" << endl;
break;
case 2:
case 3:
case 4:
case 5:
cout << "You live a happy life on the right road!" << endl;
break;
case 6:
case 7:
cout << "The left path led to a marvelous city!" << endl;
break;
case 8:
cout << "The left-wing trolls ruin your day." << endl;
break;
case 9:
case 10:
cout << "You made it home!" << endl;
break;
}
return 0;
}
|
Rust
|
UTF-8
| 2,985 | 3.1875 | 3 |
[] |
no_license
|
/// From pythonesque
use list::Node;
mod list {
use std::mem;
#[derive(Show)]
pub struct Node<T> {
pub data: T,
prev: Option<Box<Node<T>>>,
next: Option<Box<Node<T>>>
}
impl<T> Node<T> {
pub fn new(data: T) -> Node<T> {
Node { data: data, prev: None, next: None }
}
pub fn insert_after(&mut self, mut new: Box<Node<T>>) -> Option<Box<Node<T>>> {
mem::swap(&mut new.next, &mut self.next);
mem::replace(&mut self.next, Some(new))
}
pub fn insert_before(&mut self, mut new: Box<Node<T>>) -> Option<Box<Node<T>>> {
mem::swap(&mut new.prev, &mut self.prev);
mem::replace(&mut self.prev, Some(new))
}
pub fn remove_after(&mut self) -> Option<Box<Node<T>>> {
match self.next.take() {
Some(mut next) => {
mem::swap(&mut self.next, &mut next.next);
Some(next)
},
None => None,
}
}
pub fn remove_before(&mut self) -> Option<Box<Node<T>>> {
match self.prev.take() {
Some(mut prev) => {
mem::swap(&mut self.prev, &mut prev.prev);
Some(prev)
},
None => None,
}
}
pub fn next(&mut self) -> Option<&mut T> {
let Node { ref mut data, ref mut prev, ref mut next } = *self;
match *next {
Some(ref mut next) => {
mem::swap(&mut next.data, data);
{
let mut next = &mut **next;
mem::swap(&mut next.next, &mut next.prev);
}
mem::swap(&mut next.prev, prev);
},
None => return None,
}
mem::swap(prev, next);
Some(data)
}
pub fn prev(&mut self) -> Option<&mut T> {
let Node { ref mut data, ref mut prev, ref mut next } = *self;
match *prev {
Some(ref mut prev) => {
mem::swap(&mut prev.data, data);
{
let mut prev = &mut **prev;
mem::swap(&mut prev.next, &mut prev.prev);
}
mem::swap(&mut prev.next, next);
},
None => return None
}
mem::swap(prev, next);
Some(data)
}
}
}
fn main() {
let mut list = Node::new(0i8);
list.insert_before(box Node::new(-1));
list.insert_after(box Node::new(1));
while let Some(_) = list.next() {
println!("{}", list);
}
list.insert_before(box Node::new(2));
while let Some(_) = list.prev() {
println!("{}", list.remove_before());
println!("{}", list);
}
println!("{}", list.remove_after());
}
|
C#
|
UTF-8
| 1,213 | 2.5625 | 3 |
[] |
no_license
|
using UnityEngine;
using UnityEngine.UI;
public class ScoreBoard : MonoBehaviour
{
public static int scoreValue = 0;
Text score;
private void Start()
{
score = GetComponent<Text>();
}
private void Update()
{
score.text = "SCORE: " + scoreValue;
}
}
/*
public int score;
public Text currentDisplay;
public Text highscoreDisplay;
void Start () {
score = 0;
if (currentDisplay != null) {
currentDisplay.text = score.ToString ();
}
if (highscoreDisplay != null)
highscoreDisplay.text = GetScore ().ToString ();
}
public void IncrementScoreBoard(int valUe){
score += valUe;
currentDisplay.text = score.ToString ();
}
public void SaveScore(){
//Check previous score
int oldScore = GetScore();
//if new score is higher than previous score
if(score > oldScore)
PlayerPrefs.SetInt ("HighScore", score);
}
public int GetScore(){
return PlayerPrefs.GetInt ("HighScore");
}
public void OnDisable(){
SaveScore ();
}
}
*/
|
C++
|
UTF-8
| 5,386 | 2.90625 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) 2015 Andrew Sutton
// All rights reserved
#include "beaker/graph.hpp"
#include "beaker/type.hpp"
#include "beaker/expr.hpp"
#include "beaker/decl.hpp"
#include "beaker/stmt.hpp"
#include "beaker/unit.hpp"
namespace beaker
{
namespace
{
using Id_map = std::unordered_map<Expr const*, int>;
int
put_node(Id_map& id, Expr const* e)
{
auto x = id.insert({e, 0});
if (x.second)
x.first->second = id.size();
return x.first->second;
}
int
get_node(Id_map const& id, Expr const* e)
{
auto iter = id.find(e);
return iter->second;
}
// -------------------------------------------------------------------------- //
// Node names
//
// Generate a textual label for a node.
String node_label(Id_map&, Expr const*);
String
node_label(Id_map& id, Constant_expr const* e)
{
return format("{}", e->value());
}
String
node_label(Id_map& id, Identifier_expr const* e)
{
return *e->name();
}
String
node_label(Id_map& id, Unary_expr const* e)
{
return get_spelling(e->op());
}
String
node_label(Id_map& id, Binary_expr const* e)
{
return get_spelling(e->op());
}
String
node_label(Id_map& id, Call_expr const* e)
{
return "call";
}
String
node_label(Id_map& id, Expr const* e)
{
struct Fn
{
Fn(Id_map& m)
: id(m)
{ }
String operator()(Constant_expr const* e) const { return node_label(id, e); }
String operator()(Identifier_expr const* e) const { return node_label(id, e); }
String operator()(Unary_expr const* e) const { return node_label(id, e); }
String operator()(Binary_expr const* e) const { return node_label(id, e); }
String operator()(Call_expr const* e) const { return node_label(id, e); }
Id_map& id;
};
return apply(e, Fn(id));
}
String
node_name(Id_map& id, Expr const* e)
{
return format("n{}", get_node(id, e));
}
// -------------------------------------------------------------------------- //
// List nodes
template<typename T>
void
list_node_common(Printer& p, Id_map& id, T const* e)
{
int n = put_node(id, e);
print(p, "n{} [label=\"{}\"]", n, node_label(id, e));
print_newline(p);
}
void list_nodes(Printer&, Id_map&, Expr const*);
void
list_nodes(Printer& p, Id_map& id, Constant_expr const* e)
{
list_node_common(p, id, e);
}
void
list_nodes(Printer& p, Id_map& id, Identifier_expr const* e)
{
list_node_common(p, id, e);
}
void
list_nodes(Printer& p, Id_map& id, Unary_expr const* e)
{
list_node_common(p, id, e);
list_nodes(p, id, e->arg());
}
void
list_nodes(Printer& p, Id_map& id, Binary_expr const* e)
{
list_node_common(p, id, e);
list_nodes(p, id, e->left());
list_nodes(p, id, e->right());
}
void
list_nodes(Printer& p, Id_map& id, Call_expr const* e)
{
list_node_common(p, id, e);
for (Expr const* ei : e->arguments())
list_nodes(p, id, ei);
}
void
list_nodes(Printer& p, Id_map& id, Expr const* e)
{
struct Fn
{
Fn(Printer& p, Id_map& m)
: p(p), id(m)
{ }
void operator()(Constant_expr const* e) const { list_nodes(p, id, e); }
void operator()(Identifier_expr const* e) const { list_nodes(p, id, e); }
void operator()(Unary_expr const* e) const { list_nodes(p, id, e); }
void operator()(Binary_expr const* e) const { list_nodes(p, id, e); }
void operator()(Call_expr const* e) const { list_nodes(p, id, e); }
Printer& p;
Id_map& id;
};
return apply(e, Fn(p, id));
}
// -------------------------------------------------------------------------- //
// List nodes
void list_arrows(Printer&, Id_map&, Expr const*);
void
list_arrows(Printer& p, Id_map& id, Constant_expr const* e)
{
}
void
list_arrows(Printer& p, Id_map& id, Identifier_expr const* e)
{
}
void
list_arrows(Printer& p, Id_map& id, Unary_expr const* e)
{
list_arrows(p, id, e->arg());
print(p, "{} -> {};", node_name(id, e), node_name(id, e->arg()));
print_newline(p);
}
void
list_arrows(Printer& p, Id_map& id, Binary_expr const* e)
{
list_arrows(p, id, e->left());
list_arrows(p, id, e->right());
String src = node_name(id, e);
print(p, "{} -> {};", src, node_name(id, e->left()));
print_newline(p);
print(p, "{} -> {};", src, node_name(id, e->right()));
print_newline(p);
}
void
list_arrows(Printer& p, Id_map& id, Call_expr const* e)
{
put_node(id, e);
for (Expr const* ei : e->arguments())
list_arrows(p, id, ei);
String src = node_name(id, e);
for (Expr const* ei : e->arguments()) {
print(p, "{} -> {};", src, node_name(id, ei));
print_newline(p);
}
}
void
list_arrows(Printer& p, Id_map& id, Expr const* e)
{
struct Fn
{
Fn(Printer& p, Id_map& m)
: p(p), id(m)
{ }
void operator()(Constant_expr const* e) const { list_arrows(p, id, e); }
void operator()(Identifier_expr const* e) const { list_arrows(p, id, e); }
void operator()(Unary_expr const* e) const { list_arrows(p, id, e); }
void operator()(Binary_expr const* e) const { list_arrows(p, id, e); }
void operator()(Call_expr const* e) const { list_arrows(p, id, e); }
Printer& p;
Id_map& id;
};
return apply(e, Fn(p, id));
}
} // namespace
void
graph(Expr const* e)
{
Printer p(std::cerr);
Id_map id;
print(p, "digraph G {\n");
list_nodes(p, id, e);
list_arrows(p, id, e);
print(p, "}\n");
}
} // namespace beaker
|
Java
|
ISO-8859-1
| 1,500 | 3.171875 | 3 |
[] |
no_license
|
import java.util.ArrayList;
public class Pedidos {
//ATRIBUTOS
ArrayList<Produto> produtos = new ArrayList <Produto>();
//ACESSORES
public ArrayList<Produto> getProdutos() {
return produtos;
}
public Produto getProdutos(int i) {
return produtos.get(i);
}
public void setProdutos(ArrayList<Produto> produtos) {
this.produtos = produtos;
}
public void setProdutos(int i,Produto produto) {
this.produtos.set(i,produto);
}
//CONSTRUTORES
public Pedidos(ArrayList<Produto> produtos) {
super();
this.produtos = produtos;
}
public Pedidos() {
super();
}
//METODOS
public String entregaRestaurante() {
return "Para comer no restaurante";
}
public String entregaFora() {
return "Para comer fora do restaurante";
}
public void add(Produto produto) {
produtos.add(produto);
}
public int contar() {
return produtos.size();
}
public String mostrarNome(int i) {
return produtos.get(i).getNome();
};
public String listarNomeQuantPreo() {
String texto = "";
for (int i = 0; i < produtos.size(); i++) {
texto += produtos.get(i).getNome() + ", Quantidade: " + produtos.get(i).getQuant() + ", Preo Individual: " + produtos.get(i).getPreo()+ ", Total: "+produtos.get(i).preo()+"\n";
}
return texto;
}
@Override
public String toString() {
return "Pedidos [produtos=" + produtos + "]";
};
}
//ATRIBUTOS
//ACESSORES
//CONSTRUTORES
//METODOS
|
Java
|
UTF-8
| 14,605 | 2 | 2 |
[] |
no_license
|
package com.example.bebo2.publisher_news;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.bebo2.publisher_news.WebServiceapi.API;
import com.example.bebo2.publisher_news.utils.Session;
import com.theartofdev.edmodo.cropper.CropImage;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class Post_activity extends AppCompatActivity {
private String server_url = "https://shehabosama.000webhostapp.com/upload_file.php"; // url to connection internet and server
private Uri orgUri;// variable to storage uri the image you select it from gallery
private Button upload,review;
private static final int REQUEST_PERMISSION = 1000 ;
private ImageView select_photo;
private EditText editText,editTextTitle;
private String recev;
private String check;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_activity);
recev = getIntent().getExtras().getString("message").toString();
RequestPermission();
Declaration();
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDialog.setTitle("wait minuet..");
progressDialog.setMessage("we will publish the post now");
progressDialog.setCancelable(false);
progressDialog.show();
getRealPathFromUri(orgUri);
}
});
select_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CropActivity();
}
});
review.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),View_news.class).putExtra("message",recev));
}
});
}
private void getRealPathFromUri(Uri orgUri)
{
if (orgUri != null)
{
if(!TextUtils.isEmpty(editText.getText().toString())||TextUtils.isEmpty(editTextTitle.getText().toString()))
{
String path = orgUri.toString();
if (path.toLowerCase().startsWith("file://"))
{
// Selected file/directory path is below
path = (new File(URI.create(path))).getAbsolutePath();
Log.e("ini", path);
String filename=path.substring(path.lastIndexOf("/")+1);
Toast.makeText(Post_activity.this, ""+filename, Toast.LENGTH_SHORT).show();
FileUpload(path,filename);
}
}else
{
Toast.makeText(Post_activity.this, "please writer title and description ", Toast.LENGTH_SHORT).show();
}
}else
{
Toast.makeText(Post_activity.this, "please select photo ", Toast.LENGTH_SHORT).show();
}
}
private void RequestPermission() // to request from the user permission to access file from his phone
{
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE
},REQUEST_PERMISSION);
}
}
private void Declaration()//to merge the design with programming to able handling the design
{
progressDialog = new ProgressDialog(this);
editText = findViewById(R.id.edt_desc);
upload = findViewById(R.id.btn_upload);
select_photo = findViewById(R.id.select);
review = findViewById(R.id.review);
editTextTitle = findViewById(R.id.edt_title);
}
private void CropActivity()// to open the gallery or camera or any app can take a photo and select the photo and crop the photo and submit crop
{
CropImage.activity()
// .setGuidelines(CropImageView.Guidelines.ON)
// .setAspectRatio(1, 1)
//.setMaxCropResultSize(700, 700)
.start(Post_activity.this);
}
/*this function take the post description and the file name and the categories post to insert it in database on the server */
private void InsertToDatabase(String title,String desc, String filename, String categories)
{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://shehabosama.000webhostapp.com/").build();
API _shehabAPI = retrofit.create(API.class);
Call<ResponseBody> addostconnection = _shehabAPI.addpost(title,desc,filename,categories);
addostconnection.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String res = response.body().string();
Toast.makeText(Post_activity.this, res, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(Post_activity.this, ""+t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
orgUri = result.getUri();
select_photo.setImageURI(orgUri);
// String convertedPath = getRealPathFromURI(orgUri);
//getRealPathFromURI(getApplicationContext(),orgUri);//path converted from Uri
// Toast.makeText(this, ""+convertedPath, Toast.LENGTH_SHORT).show();
}
}
}
/*this the function take the path and check the file if the file is already exist it will upload the file to the server in the uploads folder */
private void FileUpload(final String filepath , final String filename )
{
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection uploadConnection = null; // Declaration variable to allowed us to connection the internet and server through the url we declaration it above
DataOutputStream outputStream;// this the file's streaming transfer from app to server
String boundary = "********";// this the break between streams's parts
String CRLF = "\r\n"; // break between the header and body and it use with the boundary
String Hyphens ="--";// using with boundary to break between header and body
int bytesRead,bytesAvailable,bufferSize;// bytesread is the streams successfully read -- byteAvailable is the streams available not read
int maxBufferSize = 1024*1024;// this maxSize in the stack streams
byte[] buffer;// this is the array to storage all streams inside it
File outFile = new File(filepath);// this to access the the file we will uploaded and make sure the file is already exist or now
try {
FileInputStream fileInputStream = new FileInputStream(outFile);// this to converter File to streams to give file to the server in the form of streams
URL url = new URL(server_url);//set url variable in the Url class to convert the String url to url c
uploadConnection = (HttpURLConnection) url.openConnection();// now we will open connection
// uploadConnection.setConnectTimeout(40);
//uploadConnection.setConnectTimeout(60);
// uploadConnection.setReadTimeout(60);
uploadConnection.setDoInput(true);//here we will make the server accept the input which we send it
uploadConnection.setDoOutput(true);//here we will make the server accept the output which we receive it
uploadConnection.setRequestMethod("POST");// here we select the kind of method
uploadConnection.setRequestProperty("Connection", "Keep-Alive");// send server that it will stay open connection as long as there streams
uploadConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);//select the kind of data will sen it and set boundary to break between streams
uploadConnection.setRequestProperty("uploaded_file", filepath);//set file path who we will upload it
outputStream = new DataOutputStream(uploadConnection.getOutputStream());//here we will set the connection output stream to Data output stream because the DataoutputStream is help us to upload the file and connection to server as streams
outputStream.writeBytes(Hyphens + boundary + CRLF);// to lift line between the header and the body
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + filepath + "\"" + CRLF);// define the file here
outputStream.writeBytes(CRLF);// to make space
bytesAvailable= fileInputStream.available();// set the available stream in the bytesAvailable
bufferSize = Math.min(bytesAvailable, maxBufferSize);// select which what the minimum between bytesAvailable and maxbufferSize and set the minimum in the bufferSize
buffer = new byte[bufferSize];// set the result bufferSize in the array (buffer)
bytesRead = fileInputStream.read(buffer,0,bufferSize);//read the byte from the file stream
while (bytesRead>0){//as long as there bytes in the bytesread enter again and upload it
outputStream.write(buffer,0,bufferSize);//to write the stream in the server and take it from the app
bytesAvailable = fileInputStream.available();//set the available stream in the bytesAvailable after the write the outputStream
bufferSize = Math.min(bytesAvailable, maxBufferSize);// select which what the minimum between bytesAvailable and maxbufferSize and set the minimum in the bufferSize
bytesRead = fileInputStream.read(buffer,0,bufferSize);//read the byte from the file stream
}
outputStream.writeBytes(CRLF);//after end the line will move the new line
outputStream.writeBytes(Hyphens+boundary+Hyphens+CRLF);
InputStreamReader resultReader = new InputStreamReader(uploadConnection.getInputStream());
final BufferedReader reader = new BufferedReader(resultReader);
String line = "";
String response="";
while ((line = reader.readLine()) != null ){
response+= line;
}
final String finalResponse = response;
runOnUiThread(new Runnable() {
@Override
public void run() {
check = finalResponse;
Toast.makeText(Post_activity.this, check, Toast.LENGTH_LONG).show();
InsertToDatabase(editTextTitle.getText().toString(),editText.getText().toString(),filename,recev);
progressDialog.dismiss();
}
});
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
Log.e("MYAPP", "exception", e);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode)
{
case REQUEST_PERMISSION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this, "permission granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_manu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.logout:
Session.getInstance().logoutAndGoTologin(this);
}
return super.onOptionsItemSelected(item);
}
}
|
Java
|
UTF-8
| 829 | 2.40625 | 2 |
[] |
no_license
|
package com.souratech.beans;
import java.io.File;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class PropertyFileLoggingRepotConfiguration {
//Creating Logger Object
private static Logger logger=Logger.getLogger(PropertyFileLoggingRepotConfiguration.class);
public static void main(String[] args) {
//String log4jPrpertyfile=System.getProperty("user.dir")+File.separator+"log4j.properties";
//Configure Log4J Object
PropertyConfigurator.configure("log4j.properties");
logger.trace("This is TRACE");
logger.info("This is INFO");
logger.error("This is ERROR");
logger.debug("This is DEBUG");
logger.fatal("This is FATAL");
}
}
/*Here we will Learn ,How to Use Log4J in Our Project/application. For Documentation you can follow
* Goodle and apache docs also*/
|
Go
|
UTF-8
| 1,519 | 2.9375 | 3 |
[] |
no_license
|
package mycontainer
import (
"fmt"
"os"
"os/exec"
"syscall"
//"github.com/sirupsen/logrus"
)
//pid mount隔离 已经很像一个完整的系统了
//执行go run main.go run sh 发现系统彻底独立出来了
func MyPid() {
if len(os.Args) < 2 {
fmt.Printf("missing commands")
return
}
switch os.Args[1] {
case "run":
run3()
case "child":
child3()
default:
fmt.Printf("wrong command")
return
}
}
func run3() {
fmt.Printf("Setting up...")
cmd := exec.Command("/proc/self/exe", append([]string{"child"}, os.Args[2:]...)...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS,
}
check3(cmd.Run())
}
func child3() {
fmt.Printf("Running %v", os.Args[2:])
cmd := exec.Command(os.Args[2], os.Args[3:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
check3(syscall.Sethostname([]byte("xxx")))
check3(syscall.Chroot("/data/busybox"))
check3(os.Chdir("/"))
// func Mount(source string, target string, fstype string, flags uintptr, data string) (err error)
// 前三个参数分别是文件系统的名字,挂载到的路径,文件系统的类型
check3(syscall.Mount("proc", "proc", "proc", 0, ""))
check3(syscall.Mount("tempdir", "temp", "tmpfs", 0, ""))
check3(cmd.Run())
check3(syscall.Unmount("proc", 0))
check3(syscall.Unmount("temp", 0))
}
func check3(err error) {
if err != nil {
fmt.Println(err)
}
}
|
Java
|
UTF-8
| 1,025 | 3.203125 | 3 |
[] |
no_license
|
package com.epam.test.automation.java.practice6;
import java.math.BigDecimal;
public class Company {
private Employee[] staff;
public Company(Employee[] employees) {
this.staff = employees;
}
public void giveEverybodyBonus(BigDecimal companyBonus) {
for (Employee item: staff){
if (item!= null){
item.setBonus(companyBonus);
}
}
}
public BigDecimal totalToPay() {
BigDecimal amount = BigDecimal.ZERO;
for (Employee item: staff){
if (item!= null){
amount = amount.add(item.toPay());
}
}
return amount;
}
public String nameMaxSalary() {
String lastName = "";
BigDecimal max = new BigDecimal(-1);
for (Employee item: staff){
if (item!= null && item.toPay().compareTo(max) > 0){
lastName = item.getLastName();
max = item.toPay();
}
}
return lastName;
}
}
|
C#
|
UTF-8
| 2,252 | 2.828125 | 3 |
[] |
no_license
|
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace MemoryGame
{
/// <summary>
/// Lógica de interacción para Settings.xaml
/// </summary>
public partial class Settings : Window
{
private string _selectedTag;
/// <summary>
/// The <c>Settings</c> constructor.
/// </summary>
public Settings()
{
InitializeComponent();
}
/// <summary>
/// Specifies the behavior for then the "Save changes" button is clicked.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="routedEventArgs">The arguments of the event.</param>
public void SaveChangesButtonClicked(object sender, RoutedEventArgs routedEventArgs)
{
_selectedTag = ((ComboBoxItem)LanguageSelectionComboBox.SelectedItem).Tag.ToString();
try
{
var culture = new CultureInfo(_selectedTag);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
Properties.Settings.Default.LanguageSettings = _selectedTag;
Properties.Settings.Default.Save();
MessageBox.Show(Properties.Langs.Resources.ChangeLanguageSettingsSuccess);
}
catch (CultureNotFoundException)
{
MessageBox.Show(Properties.Langs.Resources.ChangeLanguageSettingsError);
}
GoToMainWindow();
}
/// <summary>
/// Specifies the behavior for when the "Back" button is clicked.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="routedEventArgs">The arguments for the event</param>
public void BackButtonClicked(object sender, RoutedEventArgs routedEventArgs)
{
GoToMainWindow();
}
private void GoToMainWindow()
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
}
}
|
Python
|
UTF-8
| 2,984 | 2.6875 | 3 |
[] |
no_license
|
import sys
import numpy as np
import keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
figsize = [10, 10]
seed = 0 if len(sys.argv) == 1 else int(sys.argv[1])
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
print('seed = {}'.format(seed))
print('x_train.shape = {}'.format(x_train.shape))
print('y_train.shape = {}'.format(y_train.shape))
print('x_test.shape = {}'.format(x_test.shape))
print('y_test.shape = {}'.format(y_test.shape))
train_datagen = ImageDataGenerator(
# featurewise_center=False, # set input mean to 0 over the dataset (Default: False)
# samplewise_center=False, # set each sample mean to 0 (Default: False)
# featurewise_std_normalization=False, # divide inputs by std of the dataset (Default: False)
# samplewise_std_normalization=False, # divide each input by its std (Default: False)
# zca_whitening=False, # apply ZCA whitening (Default: False)
# zca_epsilon=1e-06, # epsilon for ZCA whitening (Default: 1e-06)
rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180) (Default: 0.0)
width_shift_range=0.1, # randomly shift images horizontally (fraction of total width) (Default: 0.0)
height_shift_range=0.1, # randomly shift images vertically (fraction of total height) (Default: 0.0)
brightness_range=[0.6, 1.4], # Tuple or list of two floats. Range for picking a brightness shift value from. (Default: None)
shear_range=0.1, # set range for random shear (Default: 0.0)
zoom_range=0.2, # set range for random zoom (Default: 0.0)
channel_shift_range=10, # set range for random channel shifts (Default: 0.0)
fill_mode='nearest', # set mode for filling points outside the input boundaries (Default: 'nearest')
# cval=0.0, # value used for fill_mode = "constant" (Default: 0.0)
horizontal_flip=True, # randomly flip images (Default: False)
# vertical_flip=False, # randomly flip images (Default: False)
# rescale=None, # set rescaling factor (applied before any other transformation) (Default: None)
# preprocessing_function=None, # set function that will be applied on each input (Default: None)
data_format='channels_last', # image data format, either "channels_first" or "channels_last" (Default: 'channels_last')
# validation_split=0.0 # fraction of images reserved for validation (strictly between 0 and 1) (Default: 0.0)
)
# Compute quantities required for feature-wise normalization
# (std, mean, and principal components if ZCA whitening is applied).
train_datagen.fit(x_train, seed=seed)
train_datagen = train_datagen.flow(x_train, y_train, batch_size=25)
x_batch, y_batch = next(train_datagen)
plt.figure(figsize=figsize)
for num in range(25):
plt.subplot(5, 5, num + 1)
plt.imshow(x_batch[num].astype(np.uint8))
plt.show()
|
Python
|
UTF-8
| 548 | 3.234375 | 3 |
[] |
no_license
|
import urllib2
from bs4 import BeautifulSoup
quote_page = ‘http://www.bloomberg.com/quote/SPX:IND'
# gets the html code of that url
page = urllib2.urlopen(quote_page)
# parse the html with BeautifulSoup
soup = BeautifulSoup(page, ‘html.parser’)
#because <h1 class = 'name'> S&P 500 Index </h1>
name_box = soup.find('h1', attrs={'class': 'name'})
name = name_box.text.strip()
print name
#gets the price of S & P
price_box = soup.find('div', attrs={'class':'price'})
price = price_box.text
print price
#Too easy, im installing Scrapy
|
Python
|
UTF-8
| 2,678 | 2.71875 | 3 |
[] |
no_license
|
# Example parameters.
# * COPY THIS TO params.py TO USE *
CALENDARS_TO_SCRAPE = [
"mfranzs123@gmail.com",
]
# Time is broken down hierarchically. A tree is defined below.
# Each item is either:
# - A dictionary of sub-tasks
# (ex. "Working" has sub-tasks" "Classes", "Learning", "Thinking", etc.)
# - A specific task, represented by a list of alterntaive names for that task
# (ex. "Research" is represented in my calendar either by "Research", "Lab Meeting", or "Advisor Meeting")
categories = {
"Sleeping": {
"Prep to sleep": ["brush teeth"],
"Sleep": ["nap", "wake up", "wakeup"],
},
"Working": {
"Classes": {
"6.006": [],
"6.881": [],
},
"Learning": {
"Queue": [],
},
"Thinking": [],
"Research": ["Lab Meeting", "Advisor Meeting"],
"Projects": {
"Build Time Tracking Project": [],
},
"Family": {
}
},
"Sick": {},
"Homeostasis": {
"Exercise/Shower": ["Run", "Elliptical", "Shower", "Exercise"],
"Write": ["Writing", "Journal"],
"Biking": []
},
"Overhead": {
"Email": [],
"Organize": ["Work through todo list"],
"Trash": ["clean up"],
"Walking": ["walk", "get to", "get home"],
"Laundry": ["Clean room"],
"Flying": ["Pack",],
},
"Break": {
"Healthy": {
"Eating": {
"Lunch": [],
"Dinner": [],
},
"Consumption": {
"Movie": []
},
"Socializing": {
"Talking": [],
},
},
"Unhealthy": {
"Internet": {
"Waste Time": ["waste", "break"],
"Relax": [],
"Web Forums": ["Reddit", "Hacker News"],
},
"Video Games": ["Smash"],
},
"Vacation": {
"Travel": ["Flight", "Train", "Your Itinerary", "Airport"],
},
},
"UNKNOWN": ["?"],
}
categories_to_color = {
# These keys are the unique names in the hierarchy below. Deeper has precedence
"Sleeping": (0, 0, 0), # Black
"Overhead": (0, 0, 255), # Red
"Walking": (50, 0, 255), # Red
"Organize": (100, 0, 255), # Red
"Break": (255, 0, 0), # Blue
"Socializing": (255, 255, 0),
"Dinner": (255, 170, 0),
"Lunch": (255, 170, 0),
"Waste Time": (255, 100, 0),
"Relax": (255, 50, 50),
"Working": (0, 255, 0), # Green
"Classes": (0, 255, 50), #
"Project": (0, 255, 125), #
"Research": (0, 255, 180), #
"Studying": (50, 255, 180), #
}
|
Markdown
|
UTF-8
| 1,810 | 3.421875 | 3 |
[] |
no_license
|
# Quickstart using Docker
***
!!! attention
This guide assumes that docker and docker-compose are already installed on your system. ([click here to download Docker](https://docs.docker.com/get-docker/))
## Installing
The following commands will initialise the file structure used by the Engine. Run the commands in your terminal. You only need to do this once!
```
# Make a new directory
mkdir dema-engine
cd dema-engine
# Initialize the dema-engine workspace
docker run -v "$PWD:/usr/src/engine/output" dematrading/engine:stable init
```
The above snippet creates a new directory called 'dema-engine' and changes the working directory to the folder we just created.
Notice how a config file, a strategy file and a backtesting folder have been created. Those will be used when running the Engine.
## Backtesting
Once this is done, you're ready to start the first backtest. This can be done by running the command below.
```
# Run your first backtest
docker-compose up
```
By default, the backtest will run the sample strategy provided. This is just a reference to get you started. Don't expect
it to be profitable already, as you should adjust it to your own strategy!
## Updating the Engine with docker-compose
Updating is done by running the following command:
```
# Update the engine
docker-compose pull
```
The above command will pull the newest version of the Engine for you. Thats all there is to it! The next time you run a backtest, the newest version will be used.
## Whats next?
You are now ready to start developing your own strategies! Get started by reading [examples of strategies](https://docs.dematrading.ai/getting_started/strategies/strategyexamples/). Or have a look at [configuring backtesting](https://docs.dematrading.ai/getting_started/installation/configuring_backtest/)
|
Python
|
UTF-8
| 1,288 | 2.9375 | 3 |
[] |
no_license
|
import sys
sys.stdin = open('mine.txt','r')
def IsSafe(y,x):
if x>=0 and y>=0 and x<N and y<N:
return True
def mine_check(y,x):
mine_count = 0
for dir in range(8):
n_y = y + dy[dir]
n_x = x + dx[dir]
if IsSafe(n_y,n_x) and field[n_y][n_x] == '*':
mine_count += 1
return mine_count
def blow(y,x):
total_mine = mine_check(y,x)
if total_mine > 0:
field[y][x] = total_mine
else:
field[y][x] = 0
for dir in range(8):
n_y = y + dy[dir]
n_x = x + dx[dir]
if IsSafe(n_y,n_x) and field[n_y][n_x] == '.':
blow(n_y,n_x)
T = int(input())
for time in range(T):
N = int(input())
field = []
for rows in range(N):
row = list(input())
field.append(row)
# print(field)
dy = [-1,-1,0,1,1,1,0,-1]
dx = [0,1,1,1,0,-1,-1,-1]
total_click = 0
for y in range(N):
for x in range(N):
if field[y][x] == '.' and mine_check(y,x) == 0:
blow(y,x)
total_click += 1
for i in range(N):
for j in range(N):
if field[i][j] == '.':
blow(y,x)
total_click += 1
print('#{0} {1}'.format(time+1,total_click))
|
Java
|
UTF-8
| 29,425 | 2 | 2 |
[] |
no_license
|
package core.entity.warrior.base;
import api.core.Owner;
import api.entity.stuff.Artifact;
import api.enums.OwnerTypeEnum;
import api.enums.TargetTypeEnum;
import api.game.ability.Influencer;
import api.core.Result;
import api.game.ability.Ability;
import api.game.ability.Modifier;
import api.entity.warrior.*;
import api.entity.weapon.Weapon;
import api.enums.LifeTimeUnit;
import api.enums.PlayerPhaseType;
import api.geo.Coords;
import api.core.EventDataContainer;
import api.game.action.InfluenceResult;
import api.game.map.Player;
import core.entity.abstracts.AbstractOwnerImpl;
import core.game.action.InfluenceResultImpl;
import core.system.ResultImpl;
import core.system.error.GameError;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import static api.enums.EventType.*;
import static core.system.error.GameErrors.*;
// TODO добавить поддержку ограничения оружия по допустимому списку
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class WarriorImpl extends AbstractOwnerImpl<Player> implements Warrior {
protected Map<Integer, WarriorSHand> hands;
protected WarriorBaseClass warriorBaseClass;
protected volatile Coords coords;
protected boolean summoned;
protected WarriorSBaseAttributes attributes;
protected final Map<String, Influencer> influencers = new ConcurrentHashMap<>(50);
protected volatile boolean touchedAtThisTurn = false;
protected volatile Coords originalCoords;
protected volatile boolean moveLocked;
protected volatile boolean rollbackAvailable;
protected volatile int treatedActionPointsForMove;
protected final Map<String, Artifact<Warrior>> artifacts = new ConcurrentHashMap<>(10);
protected PlayerPhaseType warriorPhase = null;
protected final Map<String, Class<? extends Ability>> unsupportedAbilities = new ConcurrentHashMap<>(20);
@Autowired
private BeanFactory beanFactory;
//===================================================================================================
//===================================================================================================
//===================================================================================================
public WarriorImpl(Player owner, WarriorBaseClass warriorBaseClass, String title, Coords coords, boolean summoned) {
super(owner, OwnerTypeEnum.WARRIOR, "wrr", title, title);
this.warriorBaseClass = warriorBaseClass;
this.attributes = warriorBaseClass.getBaseAttributes().clone();
this.summoned = summoned;
this.coords = new Coords(coords);
int handsCount = warriorBaseClass.getHandsCount();
hands = new ConcurrentHashMap(2);
while (handsCount-- > 0) {
hands.put(hands.size(), new WarriorSHandImpl());
}
this.warriorBaseClass.attachToWarrior(this);
}
//===================================================================================================
@Override
public Player getOwner() {
return super.getOwner();
}
//===================================================================================================
@Override
public Result<Artifact<Warrior>> giveArtifactToWarrior(Class<? extends Artifact<Warrior>> artifactClass) {
Result<Artifact<Warrior>> result = ResultImpl.success(null);
return result.mapSafe(nullArt -> {
Artifact<Warrior> artifact = beanFactory.getBean(artifactClass
, this);
return attachArtifact(artifact);
});
}
//===================================================================================================
@Override
public Result<Artifact<Warrior>> attachArtifact(Artifact<Warrior> artifact) {
Result<Artifact<Warrior>> result;
if (artifacts.get(artifact.getTitle()) != null) {
// уже есть такой артефакт. даем ошибку
// "В игре %s. воин '%s %s' игрока '%s' уже владеет артефактом '%s'."
result = ResultImpl.fail(ARTIFACT_ALREADY_EXISTS.getError(
getContext().getGameName()
, warriorBaseClass.getTitle()
, title
, owner.getId()
, artifact.getTitle()));
} else {
artifact.attachToOwner(this);
artifacts.put(artifact.getTitle(), artifact);
// применить сразу действие артефакта
artifact.applyToOwner(warriorPhase);
// отправить сообщение
getContext().fireGameEvent(null, ARTIFACT_TAKEN_BY_WARRIOR, new EventDataContainer(this, artifact), null);
result = ResultImpl.success(artifact);
}
return result;
}
//===================================================================================================
@Override
public Result<List<Artifact<Warrior>>> getArtifacts() {
return ResultImpl.success(new ArrayList<Artifact<Warrior>>(artifacts.values()));
}
//===================================================================================================
@Override
public WarriorBaseClass getWarriorBaseClass() {
return warriorBaseClass;
}
//===================================================================================================
@Override
public boolean isSummoned() {
return summoned;
}
//===================================================================================================
@Override
public List<WarriorSHand> getHands() {
return new LinkedList(hands.values());
}
//===================================================================================================
@Override
public List<Weapon> getWeapons() {
Set<Weapon> weaponSet = new HashSet<>(5);
hands.values().stream().forEach(hand ->
hand.getWeapons().stream().forEach(weapon -> weaponSet.add(weapon)));
return new ArrayList<>(weaponSet);
}
//===================================================================================================
@Override
public Result<Weapon> findWeaponById(String weaponId) {
return hands.values().stream()
.filter(warriorSHand -> warriorSHand.hasWeapon(weaponId))
.findFirst().map(warriorSHand -> warriorSHand.getWeaponById(weaponId))
.map(weapon -> ResultImpl.success(weapon))
.orElse(ResultImpl.fail(generateWeapoNotFoundError(weaponId)));
}
//===================================================================================================
@Override
public Result<Artifact<Warrior>> findArtifactById(String artifactId) {
return artifacts.values().stream()
.filter(artifact -> artifact.getId().equals(artifactId))
.findFirst()
.map(artifact -> ResultImpl.success(artifact))
.orElse(ResultImpl.fail(generateArtifactNotFoundError(artifactId)));
}
//===================================================================================================
private Coords innerGetTranslatedToGameCoords() {
// если игра уже в стадии игры, а не расстановки, юнит не трогали или если не заблокирована возможность отката, то
// берем OriginalCoords в противном случае берем Coords
return getContext().isGameRan()
// игра идет
&& isRollbackAvailable() && !isMoveLocked()
? originalCoords
: coords;
}
//===================================================================================================
@Override
public Coords getTranslatedToGameCoords() {
return new Coords(innerGetTranslatedToGameCoords());
}
//===================================================================================================
@Override
public int calcMoveCost(Coords to) {
Coords from = innerGetTranslatedToGameCoords();
return (int) Math.round((double) getWarriorSMoveCost() * Math.sqrt((double) ((from.getX() - to.getX()) * (from.getX() - to.getX())
+ (from.getY() - to.getY()) * (from.getY() - to.getY()))) / (double) getContext().getLevelMap().getSimpleUnitSize());
}
//===================================================================================================
@Override
public int calcDistanceTo(Coords to) {
return getContext().calcDistanceTo(innerGetTranslatedToGameCoords(), to);
}
//===================================================================================================
@Override
public int calcDistanceToTarget(Coords to) {
return getContext().calcDistanceTo(coords, to);
}
//===================================================================================================
@Override
public Result<Warrior> moveWarriorTo(Coords to) {
Result result;
if (!moveLocked) {
treatedActionPointsForMove = calcMoveCost(to);
setTouchedOnThisTurn(true);
this.coords = new Coords(to);
result = ResultImpl.success(this);
} else {
// новые координаты воина уже заморожены и не могут быть отменены
// Воин %s (id %s) игрока %s в игре %s (id %s) не может более выполнить перемещение в данном ходе
result = ResultImpl
.fail(WARRIOR_CAN_T_MORE_MOVE_ON_THIS_TURN.getError(
getWarriorBaseClass().getTitle()
, getId()
, getOwner().getId()
, getContext().getGameName()
, getContext().getContextId()));
}
return result;
}
//===================================================================================================
@Override
public Coords getCoords() {
return new Coords(this.coords);
}
//===================================================================================================
@Override
public Result giveWeaponToWarrior(Class<? extends Weapon> weaponClass) {
Result result = null;
Weapon weapon = beanFactory.getBean(weaponClass);
if (weapon.getNeededHandsCountToTakeWeapon() > 0) {
int freePoints = 2 - hands.values().stream().map(hand -> hand.isFree() ? 0 : 1).reduce(0, (acc, chg) -> acc += chg);
if (freePoints < weapon.getNeededHandsCountToTakeWeapon()) {
result = ResultImpl.fail(WARRIOR_HANDS_NO_FREE_SLOTS.getError(String.valueOf(freePoints)
, weapon.getTitle()
, String.valueOf(weapon.getNeededHandsCountToTakeWeapon())));
}
}
if (result == null) {
AtomicInteger points = new AtomicInteger(weapon.getNeededHandsCountToTakeWeapon());
// место есть в руках. Ищем свободную руку
hands.values().stream()
.filter(hand -> hand.isFree() && points.get() > 0)
.forEach(hand -> {
points.decrementAndGet();
hand.addWeapon(weapon);
weapon.setOwner(this);
});
result = ResultImpl.success(weapon);
}
getContext().fireGameEvent(null, WEAPON_TAKEN, new EventDataContainer(this, weapon, result), null);
return result;
}
//===================================================================================================
@Override
public Result<Weapon> dropWeapon(String weaponInstanceId) {
Result result = hands.values().stream().filter(hand -> hand.hasWeapon(weaponInstanceId)).findFirst()
.map(warriorSHand -> ResultImpl.success(warriorSHand.removeWeapon(weaponInstanceId)))
.orElse(ResultImpl.fail(generateWeapoNotFoundError(weaponInstanceId)));
getContext().fireGameEvent(null
, result.isSuccess() ? WEAPON_DROPPED : WEAPON_TRY_TO_DROP
, new EventDataContainer(this, result.isSuccess() ? result.getResult() : weaponInstanceId, result)
, null);
return result;
}
//===================================================================================================
@Override
public Result<Artifact<Warrior>> dropArtifact(String artifactInstanceId) {
return findArtifactById(artifactInstanceId)
.map(artifact -> {
// долой из списка. Так как не может быть более одного одинакового артефакта, то тут они хранятся по именам
artifacts.remove(artifact.getTitle());
// сразу отменить действие.
restoreAttributesAvailableForRestoration(null);
// отправить сообщение
getContext().fireGameEvent(null, ARTIFACT_DROPPED_BY_WARRIOR, new EventDataContainer(this, artifact), null);
return ResultImpl.success(artifact);
});
}
//===================================================================================================
public Result<Warrior> ifWarriorAlied(Warrior warrior, boolean isAllied) {
Result<Warrior> warriorResult = owner.findWarriorById(warrior.getId());
if (warriorResult.isSuccess() == isAllied) {
// утверждение совпало
warriorResult = ResultImpl.success(warrior);
} else {
warriorResult = isAllied
// ждали дружественного, а он - враг
// "В игре %s (id %s) воин '%s %s' (id %s) не является врагом для воина '%s %s' (id %s) игрока %s %s"
? ResultImpl.fail(WARRIOR_ATTACK_TARGET_WARRIOR_IS_NOT_ALIED.getError(
getContext().getGameName()
, getContext().getContextId()
, warrior.getWarriorBaseClass().getTitle()
, warrior.getTitle()
, warrior.getId()
, getWarriorBaseClass().getTitle()
, getTitle()
, getId()
, getOwner().getId()
, ""))
// "В игре %s (id %s) воин '%s %s' (id %s) является враждебным для воина '%s %s' (id %s) игрока %s %s"
: ResultImpl.fail(WARRIOR_ATTACK_TARGET_WARRIOR_IS_ALIED.getError(
getContext().getGameName()
, getContext().getContextId()
, warrior.getWarriorBaseClass().getTitle()
, warrior.getTitle()
, warrior.getId()
, getWarriorBaseClass().getTitle()
, getTitle()
, getId()
, getOwner().getId()
, ""));
}
return warriorResult;
}
//===================================================================================================
public Result<InfluenceResult> attackWarrior(Warrior targetWarrior, String weaponId) {
// проверим, что это не дружественный воин
return ifWarriorAlied(targetWarrior, false)
// Найдем у своего воинаоружие
.map(fineTargetWarrior -> findWeaponById(weaponId)
// вдарим
.map(weapon -> weapon.attack(fineTargetWarrior)));
}
//===================================================================================================
@Override
public Result<InfluenceResult> defenceWarrior(InfluenceResult attackResult) {
// TODO реализовать рассчет защиты и особенностей воина
return ResultImpl.success(attackResult);
}
//===================================================================================================
private GameError generateWeapoNotFoundError(String weaponId) {
//"В игре %s (id %s) у игрока %s воин '%s %s' (id %s) не имеет оружия с id '%s'"
return WARRIOR_WEAPON_NOT_FOUND.getError(
getContext().getGameName()
, getContext().getContextId()
, getOwner().getId()
, getWarriorBaseClass().getTitle()
, getTitle()
, getId()
, weaponId);
}
//===================================================================================================
private GameError generateArtifactNotFoundError(String artifactId) {
//"В игре %s (id %s) у игрока %s воин '%s %s' (id %s) не имеет оружия с id '%s'"
return ARTIFACT_NOT_FOUND_BY_WARRIOR.getError(
getContext().getGameName()
, getContext().getContextId()
, getOwner().getId()
, getWarriorBaseClass().getTitle()
, getTitle()
, getId()
, artifactId);
}
//===================================================================================================
@Override
public WarriorSBaseAttributes getAttributes() {
return attributes;
}
//===================================================================================================
/**
* Применяет все влияния, оказываемые на юнит
*
* @param playerPhaseType
* @return
*/
private Result<Warrior> applayInfluences(PlayerPhaseType playerPhaseType) {
// TODO соберем все влияния, что наложены на воина.
return ResultImpl.success(this);
}
//===================================================================================================
/**
* Восстанавливает значения атрибутов, которые могут быть восстановлены на заданный режим.
* Например кол-во очков действия для режима хода или защиты, максимальный запас здоровья и прочее
*/
public void restoreAttributesAvailableForRestoration(PlayerPhaseType playerPhaseType) {
attributes.setAbilityActionPoints(attributes.getMaxAbilityActionPoints());
attributes.setActionPoints(playerPhaseType == PlayerPhaseType.ATACK_PHASE ? attributes.getMaxActionPoints() : attributes.getMaxDefenseActionPoints());
attributes.setLuckMeleeAtack(getWarriorBaseClass().getBaseAttributes().getLuckMeleeAtack());
attributes.setLuckRangeAtack(getWarriorBaseClass().getBaseAttributes().getLuckRangeAtack());
attributes.setLuckDefense(getWarriorBaseClass().getBaseAttributes().getLuckDefense());
attributes.setDeltaCostMove(getWarriorBaseClass().getBaseAttributes().getDeltaCostMove());
// движение не заблокировано
moveLocked = false;
// на перемещение не использованио ничего
treatedActionPointsForMove = 0;
// возврат в начальную координату возможен
rollbackAvailable = true;
// начальные координаты
originalCoords = new Coords(coords);
// не использовался в этом ходе / защите
setTouchedOnThisTurn(false);
// обновить спосоности
warriorBaseClass.getAbilities().values().stream().forEach(ability -> ability.revival());
// восстановить оружие.
getWeapons().stream().forEach(weapon -> weapon.revival());
// применить способности класса воина
InfluenceResult influenceResult = new InfluenceResultImpl(this.getOwner(), this, null, this.getOwner(), this, 0);
warriorBaseClass.getAbilities().values().stream()
.filter(ability -> ability.getOwnerTypeForAbility().equals(OwnerTypeEnum.WARRIOR))
.forEach(ability -> ability.buildForTarget(this).stream()
.forEach(influencer -> influencer.applyToWarrior(influenceResult)));
// применить влияния артефактов с учетом фаза атака/защита
artifacts.values().stream()
.forEach(artifact -> artifact.applyToOwner(playerPhaseType));
// применить влияния оружия. Те, которые направлены на воина-владельца оружия
getWeapons().stream().forEach(weapon -> weapon.getAbilities().stream()
.filter(ability -> ability.getTargetType().equals(TargetTypeEnum.THIS_WARRIOR)
&& ability.getActivePhase().contains(playerPhaseType))
.forEach(ability -> ability.buildForTarget(this).stream()
.forEach(influencer -> influencer.applyToWarrior(InfluenceResultImpl.forPositive(this))
)
)
);
}
//===================================================================================================
/**
* Плдготовить воина к одной из двух фаз
*
* @param playerPhaseType
*/
private Result<Warrior> prepareToPhase(PlayerPhaseType playerPhaseType) {
restoreAttributesAvailableForRestoration(playerPhaseType);
warriorPhase = playerPhaseType;
return applayInfluences(playerPhaseType)
.peak(warrior -> warrior.getOwner().findContext()
.peak(context -> getContext().fireGameEvent(null
, playerPhaseType == PlayerPhaseType.DEFENSE_PHASE ? WARRIOR_PREPARED_TO_DEFENCE : WARRIOR_PREPARED_TO_ATTACK
, new EventDataContainer(this), null)));
}
//===================================================================================================
@Override
public Result<Warrior> prepareToDefensePhase() {
return prepareToPhase(PlayerPhaseType.DEFENSE_PHASE);
}
//===================================================================================================
@Override
public Result<Warrior> prepareToAttackPhase() {
return prepareToPhase(PlayerPhaseType.ATACK_PHASE);
}
//===================================================================================================
@Override
public Result<Influencer> addInfluenceToWarrior(Modifier modifier, Owner source, LifeTimeUnit lifeTimeUnit, int lifeTime) {
Influencer influencer = new InfluencerImpl(this, source, lifeTimeUnit, lifeTime, modifier);
influencers.put(influencer.getId(), influencer);
getContext().fireGameEvent(null, WARRIOR_INFLUENCER_ADDED
, new EventDataContainer(influencer, this), null);
return ResultImpl.success(influencer);
}
//===================================================================================================
@Override
public Result<Influencer> addInfluenceToWarrior(Influencer influencer) {
influencer.attachToOwner(this);
influencers.put(influencer.getId(), influencer);
getContext().fireGameEvent(null, WARRIOR_INFLUENCER_ADDED
, new EventDataContainer(influencer, this), null);
return ResultImpl.success(influencer);
}
//===================================================================================================
@Override
public Result<List<Influencer>> getWarriorSInfluencers() {
return ResultImpl.success(new ArrayList<>(influencers.values()));
}
//===================================================================================================
/**
* Удаление влияния
*
* @param influencer
* @param silent не отправлять уведомления о действии
*/
void innerRemoveInfluencerFromWarrior(Influencer influencer, boolean silent) {
influencers.remove(influencer.getId());
if (!silent) {
getContext().fireGameEvent(null, WARRIOR_INFLUENCER_REMOVED
, new EventDataContainer(influencer, this), null);
}
}
//===================================================================================================
@Override
public Result<Influencer> removeInfluencerFromWarrior(Influencer influencer, boolean silent) {
influencer.removeFromWarrior(silent);
innerRemoveInfluencerFromWarrior(influencer, silent);
return ResultImpl.success(influencer);
}
//===================================================================================================
public int getWarriorSActionPoints(boolean forMove) {
return forMove // для перемещения (либо у юнита остатки после атаки и прочего, либо он свежак)
// он свежак. Им еще не действовали в этом ходу
|| !isMoveLocked()
// им действовали но есть возможности откатиться
|| isRollbackAvailable()
// для движения
? attributes.getActionPoints()
// для нанесения атаки
: (attributes.getActionPoints() - treatedActionPointsForMove);
}
//===================================================================================================
@Override
public Coords getOriginalCoords() {
return originalCoords;
}
//===================================================================================================
@Override
public int getWarriorSMoveCost() {
return getAttributes().getArmorClass().getMoveCost()
+ getAttributes().getDeltaCostMove();
}
//===================================================================================================
@Override
public boolean isMoveLocked() {
return moveLocked;
}
//===================================================================================================
@Override
public void lockMove() {
this.moveLocked = true;
}
//===================================================================================================
@Override
public void lockRollback() {
this.rollbackAvailable = false;
// спишем очки за еремещение
attributes.addActionPoints(-treatedActionPointsForMove);
treatedActionPointsForMove = 0;
this.originalCoords = new Coords(coords);
}
//===================================================================================================
@Override
public Result<Warrior> rollbackMove() {
Result<Warrior> result;
// если откат не заблокирован
if (isRollbackAvailable()) {
coords = new Coords(originalCoords);
// снять признак задействованности в данном ходе
setTouchedOnThisTurn(false);
// обнулить использованные очки
setTreatedActionPointsForMove(0);
result = ResultImpl.success(this);
// уведомление
getContext().fireGameEvent(null
, WARRIOR_MOVE_ROLLEDBACK
, new EventDataContainer(this, result)
, null);
} else {
// В игре %s (id %s) игрок %s не может откатить перемещение воина '%s %s' (id %s) так как откат
// заблокирован последующими действиями
result = ResultImpl.fail(WARRIOR_CAN_T_ROLLBACK_MOVE.getError(
getContext().getGameName()
, getContext().getContextId()
, getOwner().getId()
, getWarriorBaseClass().getTitle()
, getTitle()
, getId()));
}
return result;
}
//===================================================================================================
@Override
public boolean isTouchedAtThisTurn() {
return touchedAtThisTurn;
}
//===================================================================================================
@Override
public Warrior setTouchedOnThisTurn(boolean touchedAtThisTurn) {
this.touchedAtThisTurn = touchedAtThisTurn;
return this;
}
//===================================================================================================
@Override
public boolean isRollbackAvailable() {
return rollbackAvailable;
}
//===================================================================================================
@Override
public int getTreatedActionPointsForMove() {
return treatedActionPointsForMove;
}
//===================================================================================================
@Override
public Warrior setTitle(String title) {
this.title = title;
return this;
}
//===================================================================================================
@Override
public Map<String, Class<? extends Ability>> getUnsupportedAbilities() {
return new HashMap<>(unsupportedAbilities);
}
//===================================================================================================
@Override
public void setTreatedActionPointsForMove(int treatedActionPointsForMove) {
this.treatedActionPointsForMove = treatedActionPointsForMove;
}
//===================================================================================================
}
|
PHP
|
UTF-8
| 1,627 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace Tests;
use App\Models\User;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\TestCase as BaseTestCase;
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Prepare for Dusk test execution.
*
* @beforeClass
* @return void
*/
public static function prepare()
{
static::startChromeDriver();
}
/**
* Create the RemoteWebDriver instance.
*
* @return \Facebook\WebDriver\Remote\RemoteWebDriver
*/
protected function driver()
{
$options = (new ChromeOptions())->addArguments([
'--disable-gpu',
'--headless',
'--window-size=1920,1080'
]);
return RemoteWebDriver::create(
'http://localhost:9515',
DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY,
$options
)
);
}
/**
* Return the default user to authenticate.
*
* @return \App\User|int|null
*
* @throws \Exception
*/
protected function user()
{
return User::where('email', 'larhonda.hovis@foo.com')->first();
}
/**
* Before each test.
*
* @return void
*/
protected function setUp(): void
{
parent::setUp();
// Log users out of their browser session when done.
foreach (static::$browsers as $browser) {
$browser->driver->manage()->deleteAllCookies();
}
}
}
|
JavaScript
|
UTF-8
| 704 | 2.765625 | 3 |
[] |
no_license
|
// Export model functions as a module
const sha256 = require('js-sha256');
module.exports = (dbPoolInstance) => {
// `dbPoolInstance` is accessible within this function scope
const registerAccount = (name, password, callback) => {
//const hashedPassword = sha256(password);
const queryString = `INSERT INTO users (name, password) VALUES ($1, $2)`;
const queryValues = [name, password];
dbPoolInstance.query(queryString, queryValues, callback);
}
let loginUser = (name, password, callback) => {
console.log('received username: ' + name);
console.log('received password: ' + password);
callback();
}
return {
registerAccount,
loginUser
};
};
|
C#
|
UTF-8
| 1,959 | 3.734375 | 4 |
[] |
no_license
|
using System;
namespace Exercises
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Exercise2();
}
static void Exercise1()
{
const double MilimetersInOneInch = 25.4;
Console.WriteLine("Задача 1:\nЗадано значение длины отрезка в метрах и миллиметрах. Найти ее величину в дюймах.\n");
Console.WriteLine("Введите значение длины отрезка в метрах:");
double lenghtMeters = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите значение длины отрезка в миллиметрах:");
double lenghtMillimeters = Convert.ToDouble(Console.ReadLine());
double lenghtInches = (lenghtMeters * 1000 + lenghtMillimeters) / MilimetersInOneInch;
Console.WriteLine($"Значение в дюймах = {lenghtInches}");
}
static void Exercise2()
{
Console.WriteLine("Задача 2:\nЗадана длительность интервала времени в годах, месяцах и днях. Найти его величину в днях.");
Console.WriteLine("Введите значение в годах");
long yearsInput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите значение в месяцах");
long monthesInput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Введите значение в днях");
long daysInput = Convert.ToInt32(Console.ReadLine());
long valueInDays = yearsInput * 365 + monthesInput * 30 + daysInput;
Console.WriteLine($"Величина в днях {valueInDays}");
}
}
}
|
Python
|
UTF-8
| 7,076 | 2.703125 | 3 |
[] |
no_license
|
# import the necessary packages
from imutils.perspective import four_point_transform
from imutils import contours
import numpy as np
import imutils
import cv2
from cnn_load_inference import process_letter_field, process_digit_field
def rescale_frame(frame, percent=50):
width = int(frame.shape[1] * percent / 100)
height = int(frame.shape[0] * percent / 100)
dim = (width, height)
return cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
def crop_by_edges(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 75, 200)
# find contours in the edge map, then initialize
# the contour that corresponds to the document
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
docCnt = None
# ensure that at least one contour was found
if len(cnts) > 0:
# sort the contours according to their size in
# descending order
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
# loop over the sorted contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points,
# then we can assume we have found the paper
if len(approx) == 4:
docCnt = approx
break
# apply a four point perspective transform to both the
# original image and grayscale image to obtain a top-down
# birds eye view of the paper
return four_point_transform(frame, docCnt.reshape(4, 2))
def crop_by_lines(frame):
# find contours in the edge map, then initialize
# the contour that corresponds to the document
cnts = cv2.findContours(frame.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
docCnt = None
# ensure that at least one contour was found
if len(cnts) > 0:
# sort the contours according to their size in
# descending order
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
# loop over the sorted contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points,
# then we can assume we have found the paper
if len(approx) == 4:
docCnt = approx
break
# apply a four point perspective transform to both the
# original image and grayscale image to obtain a top-down
# birds eye view of the paper
return four_point_transform(frame, docCnt.reshape(4, 2))
def crop_questions(frame, x1, x2, y1, y2):
hight, width = frame.shape[:2]
xDim = 210 / width
yDim = 297 / hight
x1, x2 = int(x1 / xDim), int(x2 / xDim)
y1, y2 = int(y1 / yDim), int(y2 / yDim)
return frame[y1:y2, x1:x2]
def crop_input_field(frame, x1, x2, y1, y2):
return crop_by_lines(crop_questions(frame, x1, x2, y1, y2))
def check_bubbles(thresh):
# cv2.imshow("quiz", thresh)
# cv2.waitKey()
# find contours in the thresholded image, then initialize
# the list of contours that correspond to questions
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
questionCnts = []
# loop over the contours
for c in cnts:
# compute the bounding box of the contour, then use the
# bounding box to derive the aspect ratio
(x, y, w, h) = cv2.boundingRect(c)
ar = w / float(h)
# in order to label the contour as a question, region
# should be sufficiently wide, sufficiently tall, and
# have an aspect ratio approximately equal to 1
if w >= 20 and h >= 20 and 0.9 <= ar <= 1.1:
questionCnts.append(c)
# sort the question contours top-to-bottom, then initialize
# the total number of correct answers
questionCnts = contours.sort_contours(questionCnts,
method="top-to-bottom")[0]
Keys = {}
ans = []
# each question has 5 possible answers, to loop over the
# question in batches of 5
for (q, i) in enumerate(np.arange(0, len(questionCnts), 5)):
ans = []
# sort the contours for the current question from
# left to right, then initialize the index of the
# bubbled answer
cnts = contours.sort_contours(questionCnts[i:i + 5])[0]
bubbled = None
# loop over the sorted contours
for (j, c) in enumerate(cnts):
# construct a mask that reveals only the current
# "bubble" for the question
mask = np.zeros(thresh.shape, dtype="uint8")
cv2.drawContours(mask, [c], -1, 255, -1)
# apply the mask to the thresholded image, then
# count the number of non-zero pixels in the
# bubble area
mask = cv2.bitwise_and(thresh, thresh, mask=mask)
# cv2.imshow("maska", mask)
# cv2.waitKey()
total = cv2.countNonZero(mask)
# print(total)
# if the current total has a larger number of total
# non-zero pixels, then we are examining the currently
# bubbled-in answer
if total > 4200:
ans.append(j)
Keys[q] = ''.join(str(i) for i in ans)
return Keys
def core(str):
image = cv2.imread(str)
paper_color = crop_by_edges(image)
paper_gray = cv2.cvtColor(paper_color, cv2.COLOR_BGR2GRAY)
# apply Otsu's thresholding method to binarize the warped
# piece of paper
black = cv2.threshold(paper_gray, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
# reading names
ID = crop_input_field(black, 75, 143, 2, 17)
nameFrame = crop_input_field(black, 43, 150, 15, 28)
surname = crop_input_field(black, 44, 205, 28, 38)
fathername = crop_input_field(black, 44, 205, 28, 50)
studycalss = crop_input_field(black, 166, 220, 2, 17)
ID = process_digit_field(ID, 8)
studyclass = process_digit_field(studycalss, 4)
name = process_letter_field(nameFrame, 12)
surname = process_letter_field(surname, 20)
fathername = process_letter_field(fathername, 20)
# print(name, surname, fathername)
# reading questions
answers = check_bubbles(crop_questions(black, 0, 90, 50, 290))
other_answers1 = check_bubbles(crop_questions(black, 120, 200, 50, 290))
other_answers1 = other_answers1.items()
i = len(answers)
for j in other_answers1:
answers[i] = j[1]
i += 1
return ID, studyclass, name, surname, fathername, answers
ID, C, N, S, F, KEYS = core("scan/tsets1.jpg")
print(ID, C, N, S, F)
print(KEYS)
|
PHP
|
UTF-8
| 1,615 | 2.90625 | 3 |
[] |
no_license
|
<?php
require_once 'DatabaseHelper.php';
class Weather extends DatabaseHelper{
public function __construct() {
parent::__construct();
}
public function getWeather($town) {
$results = array();
if(empty($town)){
//Return an empty array
return $results;
}
else{
$date = new Date();
$today = $date.date("Y-m-d");
$query = "SELECT `hi`, `low`, `description` FROM `weather` WHERE `town` = '$town' AND DATE(`timestamp`) = '$today'";
$queryresult = mysqli_query($this->getConnection(), $query);
if($queryresult){
while($result_array = $queryresult->fetch_array()){
array_push($results, $result_array);
}
}
return $results;
}
}
public function getForecast($town) {
$key = "YOUR_KEY_HERE";
$forcast_days='3';
$url ="http://api.apixu.com/v1/forecast.json?key=$key&q=$town&days=$forcast_days";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$json_output = curl_exec($ch);
$weather = json_decode($json_output);
$days = $weather->forecast->forecastday;
$results = array();
foreach ($days as $day){
array_push($results, array('hi' => $day->day->maxtemp_c, 'low' => $day->day->mintemp_c, 'description' => $day->day->condition->text));
}
return $results;
}
}
|
TypeScript
|
UTF-8
| 1,366 | 2.625 | 3 |
[] |
no_license
|
import { Controller } from './controller';
import { TimeUtil } from '@util';
import * as moment from 'moment';
export abstract class RuleResponse {
Id: string;
RuleGroupId: string;
IsActive: boolean;
DisplayName?: string;
}
export abstract class Rule {
Id: string;
RuleGroupId: string;
IsActive = true;
DisplayName?: string;
protected getRuleBasics(source: RuleResponse) {
this.Id = source.Id;
this.RuleGroupId = source.RuleGroupId;
this.IsActive = source.IsActive;
this.DisplayName = source.DisplayName;
}
protected getControllerTimeString(prefer24: boolean, controller: Controller, dateTime: string): string {
const tzAbbr = TimeUtil.getTimezoneAbbr(controller.TimeZoneId);
if (dateTime.length !== 19) {
return `${moment
.tz(dateTime, 'HH:mm:ss', controller.TimeZoneId)
.format(TimeUtil.preferredTimeFormat(prefer24))} ${tzAbbr}`;
}
const adjustedTimestamp = moment.utc(dateTime).format('HH:mm:ss');
return `${moment
.utc(adjustedTimestamp, 'HH:mm:ss')
.tz(controller.TimeZoneId)
.format(TimeUtil.preferredTimeFormat(prefer24))} ${tzAbbr}`;
}
protected setRuleBasics(response: RuleResponse) {
response.Id = this.Id;
response.RuleGroupId = this.RuleGroupId;
response.IsActive = this.IsActive;
response.DisplayName = this.DisplayName;
}
}
|
Java
|
UTF-8
| 1,555 | 2.375 | 2 |
[] |
no_license
|
package cr.ac.ucr.kabekuritechstore.form;
import javax.validation.constraints.Min;
public class ProductForm {
private int id;
@Min(2)
private int unitsOnStock;
private int idCategory;
private String name, description, image_url;
private float price;
public ProductForm() {
}
public int getIdCategory() {
return idCategory;
}
public void setIdCategory(int idCategory) {
this.idCategory = idCategory;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUnitsOnStock() {
return unitsOnStock;
}
public void setUnitsOnStock(int unitsOnStock) {
this.unitsOnStock = unitsOnStock;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
|
Python
|
UTF-8
| 1,804 | 2.78125 | 3 |
[] |
no_license
|
# -*- coding:utf-8 -*-
import unittest
import json
class TestDictCompare(unittest.TestCase):
def test_json_same_keys(self):
self.maxDiff = None
oldJson = json.loads('{"hello":"world","success":true}')
newJson = json.loads('{"hello":"world","success":true}')
self.assertDictEqual(oldJson, newJson)
def test_json_diff_keyOrders(self):
self.maxDiff = None
oldJson = json.loads('{"hello":"world","success":true}')
newJson = json.loads('{"success":true,"hello":"world"}')
self.assertDictEqual(oldJson, newJson)
def test_json_diff_values(self):
self.maxDiff = None
oldJson = json.loads('{"hello":"world","success":true}')
newJson = json.loads('{"success":true,"hello":"wOrld"}')
self.assertDictEqual(oldJson, newJson)
def test_json_diff_sub_nodes(self):
self.maxDiff = None
oldJson = json.loads(
'{"user":{"name":"devops","age":10},"hello":"world","success":true}'
)
newJson = json.loads(
'{"success":true,"hello":"world","user":{"name":"test","age":10}}')
self.assertDictEqual(oldJson, newJson)
def test_json_with_chinese(self):
self.maxDiff = None
oldJson = json.loads('{"hello":"你好","success":true}')
newJson = json.loads('{"success":true,"hello":"你好吗"}')
self.assertDictEqual(oldJson, newJson)
def test_json_with_date(self):
self.maxDiff = None
oldJson = json.loads(
'{"hello":"你好","success":true,"birthDay":"1995-06-15 10:05:00"}')
newJson = json.loads(
'{"success":true,"hello":"你好","birthDay":"1995-06-15 10:05:00"}')
self.assertDictEqual(oldJson, newJson)
if __name__ == '__main__':
unittest.main()
|
Java
|
UTF-8
| 351 | 2.828125 | 3 |
[] |
no_license
|
package com.teamtter.simpleclient;
import com.teamtter.simpleservice.SimpleService;
public class SimpleClient {
public static void main(String args[]) {
System.out.println("SimpleClient running");
SimpleService service = new SimpleService();
int result = service.computePlus(2, 3);
System.out.println("SimpleClient done: " + result);
}
}
|
C++
|
UTF-8
| 1,272 | 3.578125 | 4 |
[] |
no_license
|
class Solution {
public:
bool canPermutePalindrome(string s) {
int num[128] = {0};
for(char c : s)
{
num[c]++;
}
bool odd = false;
for(int n = 0; n < 128; ++n)
{
if(num[n] % 2 == 1)
{
if(!odd)
{
odd = true;
}
else
{
return false;
}
}
}
return true;
}
};
/*
因为是字符串,所以可能用到0-127所有128个字符
暴力一下,3ms, 1.27% 太弱了
换成unordered_map, hash一下
0ms, 28.62%
*/
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> num;
for(char c : s)
{
num[c]++;
}
bool odd = false;
for(unordered_map<char, int>::iterator it = num.begin(); it != num.end(); ++it)
{
if(it->second % 2 == 1)
{
if(!odd)
{
odd = true;
}
else
{
return false;
}
}
}
return true;
}
};
|
C#
|
UTF-8
| 1,446 | 2.609375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using Model;
namespace BLL
{
public class ProductServices
{
ProductManager pm = new ProductManager();
public int Add(Product product)
{
return pm.Add(product);
}
public int Edit(Product product)
{
return pm.Edit(product);
}
public int PutTrash(Guid id)
{
return pm.PutTrash(id);
}
/// <summary>
/// 还原
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int Restore(Guid id)
{
return pm.Restore(id);
}
public int Delete(Guid id)
{
return pm.Delete(id);
}
public IList<Product> GetAll()
{
return pm.GetAll();
}
public IList<Product> GetProductByTitle(string title)
{
return pm.GetProductByTitle(title);
}
public Product GetProductById(Guid id)
{
return pm.GetProductById(id);
}
public IList<Product> GetAllInTrash()
{
return pm.GetAllInTrash();
}
public IList<Product> GetProductByTitleInTrash(string title)
{
return pm.GetProductByTitleInTrash(title);
}
}
}
|
Java
|
UTF-8
| 454 | 1.914063 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.researchspace.figshare.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Either name or id can be set.
* @author rspace
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Author {
private String name;
@JsonInclude(Include.NON_NULL)
private Integer id;
}
|
C++
|
UTF-8
| 211 | 2.796875 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
int main(){
cout<<"Please enter your first name:"<<endl;
string name;
cin >> name;
cout<<"Your name is" << name << " " << endl;
return 0;
}
|
Python
|
UTF-8
| 11,164 | 2.828125 | 3 |
[] |
no_license
|
#importation de toutes nos classes
import pygame
from bouton import*
from menu import*
from player import*
from ennemi import*
from sol import*
from random import*
from score import*
from gameover import*
from malus import *
from bonus import *
class Jeu:
def __init__(self,ecran,menu):
self.image_fond = pygame.image.load("images/fondmario.jpg")
self.ecran = ecran
self.FPS = 30
self.clock = pygame.time.Clock()
self.menu = menu
#-----------affichage du score-----------
self.score = Score(ecran)
#----------joueur------------
self.player_vitesse_x = 0
self.player = Player(ecran)
#----------ennemi------------
self.taille=140
self.taille1=100
self.ennemi_vitesse_y = 2
self.ennemi = Ennemi(randint(80,410),0,[self.taille,30]) #permet de faire varier les tailles
self.ennemi1=Ennemi(randint(70,430),0,[self.taille1,30]) #ajouter un deuxième ennemi
#tableau d'ennemis -------------------------------------------------------------------
self.tabennemi=[self.ennemi, self.ennemi1]
#variable de la gravite
self.valeurG=7.5
self.gravite = (0,self.valeurG) #pour impression joueur tombe
self.resistance = (0,0)
#---------- malus -----------
self.malus_vitesse_y = 4
self.malus = Malus(ecran,randint(80,410),0)
#----------- bonus ----------
self.bonus_vitesse_y = 6
self.bonus = Bonus(ecran,randint(80,410),0)
#--------------Sol-----------
self.sol=Sol()
def run(self):
self.ecran.blit(self.image_fond,(0,0))
# ---------------variables ----------------
res_score=True
res_score1=True
toucher_bomb=False
bomb_temps=0
score4=4
rep=randint(0,1)
#----affichage du joueur ------
self.player.affiche()
quitter = False
while not quitter:
self.clock.tick(self.FPS)
rep=randint(0,1)
for event in pygame.event.get():
# -------------pouvoir quitter la ecran ---------------
if event.type == pygame.QUIT:
RUNNING = False
quitter = True
#----------- les touches sont pressées ------------------
elif event.type == pygame.KEYDOWN:
# deplacement du joueur a gauche ou a droite ------------
if event.key == pygame.K_LEFT:
self.player_vitesse_x= - self.player.vitesseX
elif event.key == pygame.K_RIGHT:
self.player_vitesse_x= self.player.vitesseX
#-------------les touches sont relachées ----------------
elif event.type==pygame.KEYUP:
if event.key == pygame.K_RIGHT:
self.player_vitesse_x= 0
elif event.key==pygame.K_LEFT:
self.player_vitesse_x= 0
# changement de joueur ------------------------
elif event.key == pygame.K_SPACE:
self.player.playerChange()
#--------------les collisions des ennemis------------------
for i in self.tabennemi:
# l'obstacle arrive en bas de l'ecran (collision avec le sol)
if self.sol.rect.colliderect(i.rect):
i.rect.y = 0
# changement au hasard de la couleur du prochaine obstacle
i.color.couleur()
i.rect.x = randint(80,410)
# collision entre l'ennemi et le joueur
if self.player.rect.colliderect(i.rect) :
# le joueur de meme couleur que l'ostacle/ennemi
if i.color.color == self.player.color:
# incrementation du score---------
if res_score==True:
self.score.point +=1
res_score=False
else:
res_score=True
# le joueur n'a pas le meme couleur que l'ostacle/ennemi
if not i.color.color == self.player.color :
if self.score.isBestScore():
self.score.ajouterBestScore()
gameover = Gameover(self.ecran,self.menu,self.score)
gameover.run()
# superposition de sprite--------------------------------------
if self.malus.rect.colliderect(i.rect) :
if rep==1:
#mettre hors du champs le malus-----------------------
self.malus.x=600
#collision entre les 2 ennemis--------------------------------------
if self.ennemi1.rect.colliderect(self.ennemi.rect):
# pour evité cette collision on change l'emplacement d'un ennemis
self.ennemi1.rect.x=self.ennemi1.rect.x-self.taille1
#collision des pieces (bonus)---------------------------------
#si le bonus arrive en bas (sol)------------------------
if self.sol.rect.colliderect(self.bonus.rect):
#changement du bonus (étoile ou piece)------------------
self.bonus.bonusChange()
self.bonus.y=0
self.bonus.x=randint(80,410)
#collision entre un bonus et le joueur---------------------
if self.player.rect.colliderect(self.bonus.rect):
if self.bonus.effet(self.ecran)=="piece":
#incrementation du score ------------------------
if res_score1==True:
self.score.point +=1
res_score1=False
#hors de champs
self.bonus.x=600
else:
res_score1=True
elif self.bonus.effet(self.ecran)=="etoile":
#changement du joueur -----------------------
self.player.playerChange()
#collisions des malus------------------------------
#collision entre un malus et le joueur---------
if self.player.rect.colliderect(self.malus.rect):
# si le malus est une bomb -------------------
if self.malus.effet(self.ecran)=="bomb":
toucher_bomb=True
bomb_temps=0
#hors du champs
self.malus.x=600
# diminuer la vitesse du joueur (car toucher par le malus la bomb
self.player.malusChange(3)
else:
#sinon (touche le fantome) faire l'effet avec les cercles ----------
self.malus.effet(self.ecran)
# cette partie permet de gerer le temps durant lequel le joueur est ralenti par la bomb qui aurai touchée
if toucher_bomb==True and bomb_temps==500 :
self.player.malusChange(5)
toucher_bomb=False
# superposition de sprite---------------------------------
if self.malus.rect.colliderect(self.bonus.rect):
if rep==1:
#mettre hors du champs le bonus depend du hasard de la varaible rep
self.bonus.x=600
else:
#mettre hors du champs le malus depend du hasard de la varaible rep
self.malus.x=600
#si le malus arrive en bas (en contact avec la sol : --------------
if self.sol.rect.colliderect(self.malus.rect):
self.malus.malusChange()
self.malus.y=0
self.malus.x=randint(80,410)
# augmentation de la vitesse du jeu en fonction du score
if self.score.point == score4 :
# augementation de la vitesse des ennemis---------------
self.valeurG=self.valeurG+1.5
self.gravite=(0,self.valeurG)
# augmentation de la vitesse du joueur ----------------
self.player.vitesseX=self.player.vitesseX+1
score4=self.score.point+4
#-----------------------MOUVEMENT ---------------------
#mouvement ennemis -----------------------------------
for i in self.tabennemi:
i.mouvement(self.ennemi_vitesse_y)
#mouvement malus--------------------------------------
self.malus.mouvement(self.malus_vitesse_y)
#mouvement bonus----------------------------------------
self.bonus.mouvement(self.bonus_vitesse_y)
#mouvement joueur---------------------------------------
self.player.mouvement(self.player_vitesse_x)
#-----------------------AFFICHANGE ---------------------
#affichage de l'ecran------------------------------------
self.ecran.blit(self.image_fond,(0,0))
#affichage du score------------------------------------
self.score.afficherBestScore()
self.score.afficher()
#affichage du score------------------------------------
self.sol.afficher(self.ecran)
self.gravite_jeu()
self.player.affiche()
#affichage des ennemis-------------------------------
for i in self.tabennemi:
i.afficher(self.ecran)
#affichage malus---------------------------------------
self.malus.afficher()
#affichage bonus--------------------------------------
self.bonus.afficher()
#incrementation de la variable ------------------------
bomb_temps+=1
# rafrechissement de l'ecran ------------------------
pygame.display.update()
def gravite_jeu(self):
for i in self.tabennemi:
i.rect.y += self.gravite[1] + self.resistance[1]
self.malus.y += self.gravite[1] + self.resistance[1]
self.bonus.y += self.gravite[1] + self.resistance[1]
|
Python
|
UTF-8
| 1,627 | 3.234375 | 3 |
[] |
no_license
|
'''
Created on Dec 5, 2016
@author: Yovela
'''
'''
this is the main function for assignment9
'''
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from classes import *
from functions import *
# load the countries.csv file into a pandas DataFrame and name this data set "countries"
countries = pd.read_csv("countries.csv", sep=',')
# load the "indicator gapminder gdp_per_capita_ppp.xlsx" data set into a DataFrame called income
# transform the data set to have years as the rows and countries as the columns
income = pd.read_excel("indicator gapminder gdp_per_capita_ppp.xlsx", index_col = 0).transpose()
#show the head of this data set when it is loaded
income.head()
#user interaction
while True:
user_input = input("please enter a year between 1800 to 2012, or enter 'finish' to quit the program \n")
if user_input == "finish":
sys.exit()
else:
try:
input_year = int(user_input)
if len(user_input) == 4 and (input_year>=1800) and (input_year<=2012):
income_distribution(input_year, income)
break
else:
raise ValueError
except ValueError:
print("Invalid Input, please re-enter")
except KeyboardInterrupt:
sys.exit()
except EOFError:
sys.exit()
for year in range(2007, 2013):
year_graphs = exploring_data_analysis(year)
year_graphs.histogram_exploring()
year_graphs.boxplot_exploring()
print("Finished, please open your dictionary to check those saved graphs")
|
C
|
UTF-8
| 2,561 | 3.0625 | 3 |
[] |
no_license
|
#include<stdio.h>
int source, V, E, time, visited[20], G[20][20];
void DFS(int i)
{
int j;
visited[i]= 1;
printf("%d -> ", i+1);
for(j=0;j<V;j++)
{
if(G[i][j] == 1 && visited[j] == 0)
DFS(j);
}
}
int main()
{
int i,j,v1, v2;
printf("\t\t\tGraphs \n");
printf("Enter the number of edges: \n");
scanf("%d", &E);
printf("Enter number 0f vertices: \n");
scanf("%d", &V);
for(i=0;i<V;i++)
for(j=0;j<V;j++)
G[i][j] = 0;
for(i=0; i<E;i++)
{
printf("Enter edge (V1 V2) format: ");
scanf("%d %d", &v1, &v2);
G[v1-1][v2-1] = 1;
}
for(i = 0; i<V;i++)
{
for(j=0;j<V;j++)
printf("%d\t", G[i][j]);
printf("\n");
}
printf("Enter the source: ");
scanf("%d", &source);
DFS(source-1);
return 0;
}
#include<stdio.h>
int G[20][20],q[20],visited[20],n,front=1,rear=0;
void bfs(int v)
{
int i;
visited[v]=1;
for(i=1;i<=n;i++)
if(G[v][i] && !visited[i])
q[++rear]=i;
if(front <= rear)
bfs(q[front++]);
}
int main()
{
int v,i,j;
printf("\n Enter the number of vertices: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form: \n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&G[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The nodes which are reachable are:\n");
for(i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i);
else
printf("\n %d is not reachable",i);
return 0;
}
C:\TDM-GCC-64\dslab>gcc dfs.c -o dfs
C:\TDM-GCC-64\dslab>dfs
Graphs
Enter the number of edges:
12
Enter number 0f vertices:
5
Enter edge (V1 V2) format: 1 2
Enter edge (V1 V2) format: 2 1
Enter edge (V1 V2) format: 1 3
Enter edge (V1 V2) format: 3 1
Enter edge (V1 V2) format: 1 4
Enter edge (V1 V2) format: 4 1
Enter edge (V1 V2) format: 2 3
Enter edge (V1 V2) format: 3 2
Enter edge (V1 V2) format: 4 5
Enter edge (V1 V2) format: 5 4
Enter edge (V1 V2) format: 3 5
Enter edge (V1 V2) format: 5 3
0 1 1 1 0
1 0 1 0 0
1 1 0 0 1
1 0 0 0 1
0 0 1 1 0
Enter the source: 1
1 -> 2 -> 3 -> 5 -> 4 ->
C:\TDM-GCC-64\dslab>gcc bfs.c -o bfs
C:\TDM-GCC-64\dslab>bfs
Enter the number of vertices: 4
Enter graph data in matrix form:
0 1 0 1
1 0 1 1
0 1 0 1
1 1 1 0
Enter the starting vertex:1
The nodes which are reachable are:
1 2 3 4
|
Markdown
|
UTF-8
| 696 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
## PhotoPay SDK size report
This SDK size report is for all supported ABIs. We use the Android official [**apkanalyzer**](https://developer.android.com/studio/command-line/apkanalyzer) command line tool to calculate the sizes.
**NOTE**: Presented APK sizes are sums of the `base APK size` + `size of our SDK`. Roughly, the `base APK size` is about `1 MB`, which means that the APK size increase caused by our SDK in your application will be approximately `1 MB` less than presented.
| ABI | APK file size | APK download size |
| --- |:-------------:| :----------------:|
| armeabi-v7a | 15.5MB | 12.7MB |
| arm64-v8a | 16.7MB | 12.9MB |
| x86 | 18.7MB | 13.7MB |
| x86_64 | 18.1MB | 13.4MB |
|
Java
|
UTF-8
| 240 | 1.539063 | 2 |
[
"Apache-2.0"
] |
permissive
|
package io.github.r2d2project.core.dao;
import io.github.r2d2project.core.dto.api.logs.GetRequest;
import io.github.r2d2project.core.dto.api.logs.GetResponse;
public interface LogReadDao {
GetResponse readAdvance(GetRequest request);
}
|
C++
|
UTF-8
| 4,153 | 3.046875 | 3 |
[] |
no_license
|
#pragma once
#include <vector>
#include <string>
#include <unordered_map>
#include <exception>
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <limits>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include "Util.hpp"
// decode string to internal representation, specialized for UTF-8 strings and
// single-character UTF-8 strings (which are converted to uint32_t)
template<class T>
inline T decode(const std::string &str) {
// implicit type conversion, not used in this program
return str;
}
template<>
inline uint32_t decode(const std::string &str) {
// utf-8 characters
std::vector<uint32_t> chars = Util::utf8_to_unsigned32(str);
if (chars.size() != 1)
throw std::runtime_error("expected only one letter, found: " + str);
return chars[0];
}
template<>
inline std::vector<uint32_t> decode(const std::string &str) {
return Util::utf8_to_unsigned32(str);
}
template<class T>
class CostTable {
public:
CostTable(float insCost = 1.0, float delCost = 1.0, float subCost = 1.0) :
insCost_(insCost), delCost_(delCost), subCost_(subCost)
{}
void load(const std::string &file) {
std::ifstream in(file.c_str());
std::string line;
while (std::getline(in, line)) {
std::vector<std::string> cols;
boost::algorithm::split(cols, line, boost::algorithm::is_any_of("\t"));
if (cols.empty()) throw std::runtime_error("Empty line in costs table");
switch (cols[0][0]) {
case 's':
if (cols.size() != 4)
throw std::runtime_error("Bad number of arguments for substition");
subTable_[{decode<T>(cols[1]), decode<T>(cols[2])}] = boost::lexical_cast<float>(cols[3]);
break;
case 'd':
if (cols.size() != 3)
throw std::runtime_error("Bad number of arguments for deletion");
delTable_[decode<T>(cols[1])] = boost::lexical_cast<float>(cols[2]);
break;
case 'i':
if (cols.size() != 3)
throw std::runtime_error("Bad number of arguments for insertion");
insTable_[decode<T>(cols[1])] = boost::lexical_cast<float>(cols[2]);
break;
default:
throw std::runtime_error("Unrecognized operation type: " + cols[0]);
}
}
}
float del(T c) const {
auto it = delTable_.find(c);
if (it == delTable_.end())
return delCost_;
else
return it->second;
}
float ins(T c) const {
auto it = insTable_.find(c);
if (it == insTable_.end())
return insCost_;
else
return it->second;
}
float sub(T a, T b) const {
if (a == b) return 0;
auto it = subTable_.find({a, b});
if (it == subTable_.end())
return subCost_;
else
return it->second;
}
private:
float insCost_, delCost_, subCost_;
std::unordered_map<T, float> insTable_, delTable_;
std::unordered_map<std::pair<T, T>, float> subTable_;
};
template<class T>
float levenshtein(const T& s1, const T& s2, const CostTable<typename T::value_type> &costs,
float stopAt = std::numeric_limits<float>::max()) {
const int len1 = s1.size(), len2 = s2.size();
std::vector<std::vector<float> > d(len1 + 1, std::vector<float>(len2 + 1));
d[0][0] = 0;
float total = 0;
for (int i = 1; i <= len1; ++i) {
d[i][0] = costs.del(s1[i - 1]) + total;
total = d[i][0];
}
total = 0;
for (int i = 1; i <= len2; ++i) {
d[0][i] = costs.ins(s2[i - 1]) + total;
total = d[0][i];
}
for (int i = 1; i <= len1; ++i) {
float colMin = std::numeric_limits<float>::max();
for (int j = 1; j <= len2; ++j) {
d[i][j] = std::min(std::min(
d[i - 1][j] + costs.del(s1[i - 1]),
d[i][j - 1] + costs.ins(s2[j - 1])),
d[i - 1][j - 1] + costs.sub(s1[i - 1], s2[j - 1]));
colMin = std::min(colMin, d[i][j]);
// cerr << d[i][j] << " ";
}
if (colMin > stopAt) return std::numeric_limits<float>::max(); // lossless pruning used by closest_word
// cerr << "\n";
}
return d[len1][len2];
}
|
JavaScript
|
UTF-8
| 3,116 | 4.71875 | 5 |
[] |
no_license
|
/* 1. Declare uma variável de nome weight
R:
var weight
*/
//-----------------------------------------------------------------------------------
// 2. Que tipo de dado é a variavel acima?
//console.log(typeof weight)
//-----------------------------------------------------------------------------------
/* 3. Declare uma variavel e atribua valores para cada um dos dados:
* name: String
* age : Number
* stars: Number (float)
* isSubscrideb: Boolean
var name = "Ana";
var age = 20;
var stars = 10.0;
var isSubscrideb = true;
*/
//---------------------------------------------------------------------------------------
// 4. A variável student abaixo é que tipo de dado?
//let student = {};
//R:
//console.log(student)
//O console.log nos apresenta um objeto vazio
//---------------------------------------------------------------------------------------
/* 4.1 Atribua a ela as mesmas propriedades e valores do exercício 3.
R:
let student =
{
name : "Ana",
age : 20,
stars : 10.0,
isSubscrideb : true
};
console.log(student)
*/
//----------------------------------------------------------------------------------------
/* 4.2 Mostre no console a seguinte mensagem:
<name> de idade <age> pesa <weight> kg.
Atenção, substitua <name> <age> e <weight> pelos valores de cada propriedade do objeto
//R:
var student =
{
name : "Ana",
age : 20,
weight : 61
};
console.log(student.name + 'de idade' + student.age + 'pesa' + student.weight )
*/
//-----------------------------------------------------------------------------------
/* 5. Declare uma variável do tipo Array, de nome students e atribua a ela nenhum valor, ou seja,
somente o array vazio.
R:
var students = [];
console.log(students)
*/
//-------------------------------------------------------------------------------------------
/* 6. Reatribua valor para a variável acima, colocando dentro dela o objeto student da questão 4.
(Não copiar e colar o objeto, mas usar o objeto criado e inserir ele no Array).
R:
students = [
student
]
console.log(students)
*/
//---------------------------------------------------------------------------------------------
/* 7. Coloque no console o valor da posição zero do Array acima
R:
console.log(students[0])
*/
//---------------------------------------------------------------------------------------------
/* 8. Crie um novo student e coloque na posição 1 do Array students
R:
const john = {
name: "John",
age: 23,
weight: 60
}
students = [
student,
john
]
ou
students[1] = john
console.log(students[1])
*/
//-------------------------------------------------------------------------------------
/* 9. Sem rodar o codigo responda qual é a resposta do código abaixo e por que? Após sua resposta
rode o código e veja.
console.log(a)
var a = 1
R: undefined, porque ela sofre uma elevação (hoists), ou seja minha variavel é declarada, roda o console,
e logo depois o valor e setado. Funcionando assim:
var a
console.log(a)
a = 1
*/
|
C++
|
UTF-8
| 257 | 2.6875 | 3 |
[] |
no_license
|
//16. Program to print stars Sequence1.
//*
//**
//***
//****
//*****
#include<iostream>
using namespace std;
int main()
{
for(int i=0;i<=5;i++)
{
for(int j=0;j<i;j++)
{
cout<<"*";
}
cout<<" \n ";
}
return 0;
}
|
Python
|
UTF-8
| 3,869 | 3 | 3 |
[] |
no_license
|
import functools
import numpy as np
TILE_SIZE = 8
PUZZLE_SIZE = 12
ACTIONS = [
lambda tile: tile,
lambda tile: np.rot90(tile),
lambda tile: np.rot90(tile),
lambda tile: np.rot90(tile),
lambda tile: np.flip(tile, axis=0),
lambda tile: np.rot90(tile),
lambda tile: np.rot90(tile),
lambda tile: np.rot90(tile)
]
def get_orientations(tile):
orientations = []
for action in ACTIONS:
tile = action(tile)
orientations.append(tile)
return orientations
def check_valid(puzzle_list, tile):
idx = len(puzzle_list)
if idx % PUZZLE_SIZE != 0:
left_tile = puzzle_list[-1]
edge1 = left_tile[:, -1]
edge2 = tile[:, 0]
if not np.array_equal(edge1, edge2):
return False
if idx - PUZZLE_SIZE >= 0:
above_tile = puzzle_list[len(puzzle_list)-PUZZLE_SIZE]
edge1 = above_tile[-1]
edge2 = tile[0]
if not np.array_equal(edge1, edge2):
return False
return True
def order_tiles(tiles, puzzle_list, visited):
if len(puzzle_list) == len(tiles):
return puzzle_list, visited
for tile_id, orientations in tiles.items():
if tile_id not in visited:
for tile in orientations:
if check_valid(puzzle_list, tile):
try_next = order_tiles(tiles, puzzle_list + [tile], visited + [tile_id])
if try_next is not None:
return try_next
return None
def arrange_puzzle():
inp_f = open("input/day20.txt", "r")
inp = inp_f.read()
inp_list = [line for line in inp.split("\n\n") if line != ""]
tile_id_to_arr = {}
for tile in inp_list:
lines = [line for line in tile.split("\n") if line != ""]
original = np.array([list(line) for line in lines[1:]])
tile_id_to_arr[lines[0].split(" ")[1][:-1]] = original
tile_id_to_orientations = {}
for tile_id, tile in tile_id_to_arr.items():
tile_id_to_orientations[tile_id] = get_orientations(tile)
puzzle_list, visited = order_tiles(tile_id_to_orientations, [], [])
idx = 0
puzzle = np.empty((PUZZLE_SIZE * TILE_SIZE, PUZZLE_SIZE * TILE_SIZE), dtype=str)
puzzle_id = []
for row in range(0, PUZZLE_SIZE * TILE_SIZE, TILE_SIZE):
puzzle_id.append([])
for col in range(0, PUZZLE_SIZE * TILE_SIZE, TILE_SIZE):
puzzle_id[-1].append(visited[idx])
puzzle[row:row+TILE_SIZE,col:col+TILE_SIZE] = puzzle_list[idx][1:-1,1:-1]
idx += 1
return puzzle, puzzle_id
def is_monster(arr, monster):
all_pound = np.full(monster.shape, "#", dtype=str)
monster_true = all_pound == monster
return ((arr == monster) == monster_true).all()
def count_monsters(orig_puzzle, monster):
puzzles = get_orientations(orig_puzzle)
counts = []
for puzzle in puzzles:
count = 0
for i in range(puzzle.shape[0] - monster.shape[0]):
for j in range(puzzle.shape[1] - monster.shape[1]):
test_monster = puzzle[i:i+monster.shape[0], j:j+monster.shape[1]]
if is_monster(test_monster, monster):
count += 1
counts.append(count)
return max(counts)
def part1(puzzle_id):
corners = [puzzle_id[0][0], puzzle_id[0][-1], puzzle_id[-1][0], puzzle_id[-1][-1]]
return functools.reduce(lambda a,b : int(a)*int(b), corners)
def part2(puzzle):
monster = " # \n# ## ## ###\n # # # # # # "
monster_arr = np.array([list(row) for row in monster.split("\n")])
num_monsters = count_monsters(puzzle, monster_arr)
return np.count_nonzero(puzzle == "#") - num_monsters * np.count_nonzero(monster_arr == "#")
if __name__ == "__main__":
puzzle, puzzle_id = arrange_puzzle()
print(part1(puzzle_id))
print(part2(puzzle))
|
Shell
|
UTF-8
| 265 | 2.515625 | 3 |
[] |
no_license
|
#!/bin/bash
# Terminate already running bar instances
killall -q polybar
# Wait until the processes have been shut down
while pgrep -u $UID -x polybar >/dev/null; do sleep 1; done
# Launch bar
polybar bar --config=/home/chew/.config/i3/bar/polybar/config_bottom
|
Java
|
UTF-8
| 763 | 2.65625 | 3 |
[] |
no_license
|
package learn.how2j.io;
import com.sun.org.apache.xpath.internal.SourceTree;
import java.io.File;
import java.io.IOException;
/**
* Created by qqins on 2017/12/3 16:46
*/
public class Test {
public static void main(String[] args) throws IOException {
File f1 = new File("d:/111");
if(!f1.exists()){
System.out.println("f1不存在");
f1.createNewFile();
}
System.out.println(f1.exists());
System.out.println("f1的绝对路径:"+f1.getAbsolutePath());
File f2 = new File("LOL.exe");
System.out.println("f2的绝对路径:"+f2.getAbsolutePath());
File f3 = new File(f1, "LOL.exe");
System.out.println("f3的绝对路径:"+f3.getAbsolutePath());
}
}
|
Python
|
UTF-8
| 819 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
import os
import mayaunittest
from maya import cmds
import omtk
class NomenclatureTestCase(mayaunittest.TestCase):
def test(self):
from omtk.core.className import BaseName
# Construct a naming from scratch
n = BaseName(tokens=['eye', 'jnt'], side=BaseName.SIDE_L)
self.assertEqual(n.resolve(), 'l_eye_jnt')
# Construct a naming from another existing naming
n = BaseName('l_eye_jnt')
self.assertEqual(n.prefix, None)
self.assertEqual(n.suffix, None)
self.assertEqual(n.side, n.SIDE_L)
# Adding of tokens using suffix
n = BaseName(tokens=['eye'], side=BaseName.SIDE_L, suffix='jnt')
self.assertEqual(n.resolve(), 'l_eye_jnt')
n.tokens.append('micro')
self.assertEqual(n.resolve(), 'l_eye_micro_jnt')
|
C++
|
UTF-8
| 1,466 | 2.765625 | 3 |
[] |
no_license
|
/**
\file
Declaration of class erhic::VirtualEvent.
\author Thomas Burton
\date 2011-08-19
\copyright 2011 Brookhaven National Lab
*/
#ifndef INCLUDE_EICSMEAR_ERHIC_VIRTUALEVENT_H_
#define INCLUDE_EICSMEAR_ERHIC_VIRTUALEVENT_H_
#include <TObject.h>
#include <vector>
namespace erhic {
class VirtualParticle;
/**
\brief Abstract base class for a physics event.
\details Defines an "event" simply as a collection of tracks.
*/
class VirtualEvent : public TObject {
public:
/**
Destructor
*/
virtual ~VirtualEvent() { }
/**
Returns the nth track from the event.
Indices run from 0 to (n-1).
*/
virtual const VirtualParticle* GetTrack(UInt_t /* number */) const = 0;
/**
\overload
*/
virtual VirtualParticle* GetTrack(UInt_t /*number*/) = 0;
/**
Returns the number of tracks in the event.
*/
virtual UInt_t GetNTracks() const = 0;
/**
typedef for a track pointer collection.
*/
typedef std::vector<const erhic::VirtualParticle*> ParticlePtrList;
/**
Populate a track list with the hadronic final-state.
Note that the method is a bit of a misnomer - it will return ALL final
particles other than the scattered lepton
(intentionally, since you want to take decay products into account as well)
*/
virtual void HadronicFinalState(ParticlePtrList&) const { }
ClassDef(erhic::VirtualEvent, 1)
};
} // namespace erhic
#endif // INCLUDE_EICSMEAR_ERHIC_VIRTUALEVENT_H_
|
JavaScript
|
UTF-8
| 621 | 3.09375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import complement from './complement'
describe('complement', () => {
test('complements a given function', () => {
const isEven = (value) => value % 2 === 0
const isOdd = complement(isEven)
expect(isOdd(1)).toBe(true)
})
test('throws an error if complement does not receive a function', () => {
expect(() => {
complement(null)
}).toThrow(/^Expected 'fn' parameter to be a function/)
})
test('inverts the resolved value of a promise', async () => {
const isEven = async (value) => value % 2 === 0
const isOdd = complement(isEven)
expect(await isOdd(1)).toBe(true)
})
})
|
Java
|
UTF-8
| 509 | 2.21875 | 2 |
[
"WTFPL"
] |
permissive
|
package error998.tutor.items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import error998.tutor.Reference;
import error998.tutor.Tutor;
public class ItemCheeseCracker extends ItemFood
{
public ItemCheeseCracker()
{
// Hunger bar, saturation, isWolfFood
super(3, 0.5f, true);
setUnlocalizedName(Reference.TutorItems.CHEESECRACKER.getUnlocalizedName());
setRegistryName(Reference.TutorItems.CHEESECRACKER.getRegistryName());
setCreativeTab(Tutor.CREATIVE_TAB);
}
}
|
C++
|
UTF-8
| 3,616 | 2.71875 | 3 |
[] |
no_license
|
#include <iostream>
#include <sstream>
#include <string>
#include "vertex.h"
#include <vector>
#include "prim.h"
#include <map>
#include <algorithm>
using namespace std;
bool comparator(vertex &a, vertex &b){
if(a.x==b.x)
return a.y<b.y;
else
return a.x<b.x;
}
void prim::createMST(vector<vertex> vertices, vector<vertex> edges){
//push input verts to heap, increment to infinite cost except for first index?
//vertices[0].cost=0;
for(int i=0;i<vertices.size();i++){
vertices[i].cost=99999999;
}
/*
///remove below loop as we test heapmap
for(int i=0;i<vertices.size();i++){
//heap.insert(vertices[i]);
//insert vertices to heap
}
//heap.print();
//heap.popMin();
//heap.print();
for(int i=0;i<vertices.size();i++){
//cout<<heap[i].cost<<endl;
}*/
for(int i=0; i<vertices.size();i++){
used.push_back(false);
}/*
int now = 0;
used[0]=true;
while(MSTedges.size()<vertices.size()-1){
int mincos=99999999;///or does it need to be <vertices.size()-1?
for(int e=0; e<edges.size();e++){///go thru eges to find those attached to Now
if(edges[e].x==now||edges[e].y==now && !used[edges[e].x]){///check if now is on this edge, and make sure not cycle
if(edges[e].cost<mincos){
vertices[now].cost=edges[e].cost;
}
//change current mincost,
}
}
int min = 9999999;///max int to start
}*/
//cout<< "comparing costs "<< edges[]
used[0]=true;
parents.push_back(vertices[0]);
while(parents.size()<vertices.size()){
bool found=false;
float minc=9999999999;
int edgeToAdd=-1;
for(int i=0; i<parents.size();i++){//find min among viable edge options at this point
for(int e=0; e<edges.size();e++){
if((edges[e].x==parents[i].i||edges[e].y==parents[i].i) && (used[edges[e].x]+used[edges[e].y]<2)){///check if now is on this edge, and make sure not cycle
//cout<<"INSIDE THE viable if, does not create cycle"<<endl;
//cout<<"edge cost of e: "<< e <<" "<<edges[e].cost;///problem with calculating costs
if(edges[e].cost<minc){//parents[i].cost){
//cout<<"made it in as cheapest edge"<<endl;
minc=edges[e].cost;
edgeToAdd=e;
found=true;
//parents[i].cost=edges[e].cost;
// parents[i].minEdge=e;//////use this for the next loop
}
//cout<<endl;
}
}
}
//cout<<"looped, found an edge to add: "<< found<<endl;
MSTedges.push_back(edges[edgeToAdd]);
vertex adding;
if(used[edges[edgeToAdd].x])//////finding which vertex on edgeToAdd now is a parent
adding=vertices[edges[edgeToAdd].y];///do we need to deep copy here?
else
adding=vertices[edges[edgeToAdd].x];
parents.push_back(adding);
used[adding.i]=true;
//at this point, loop again thru parents to choose which updated minpath to follow?
//for(int i=0; i<parents.size();i++){}
}
//sort edges
sort(MSTedges.begin(), MSTedges.end(), comparator);
//cout<<endl;
//print
for(int i=0; i<MSTedges.size();i++){
cout<<MSTedges[i].x<<" "<<MSTedges[i].y<<endl;
}
}
|
JavaScript
|
UTF-8
| 17,494 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
'use strict';
/**
* The constructor for CSV.parse(); copies the syntax for JSON.parse()
* @constructor
* @param {stringResolvable} str - The raw CSV string to be parsed to a JavaScript object
* @param {[ParseOptions]} options - set of optional parameters to specify custom input data or change format of output data
*/
class Parse {
constructor(str, options = {}) {
this.str = str;
this.usedIndices = {};
for (let key of Object.keys(Parse.def)) {
this[key] = options[key] !== undefined ? options[key] : Parse.def[key];
}
return this.type === "array" ? Object.values(this.output) : this.output;
}
static get def () {
if (Parse._def) return Parse._def;
let def = {
separator: ",",
escape: '"',
untitledHeaders: "untitled",
hasHeaders: false,
allowNull: true,
type: "array",
skipColumns: [],
numberOnly: [],
correctDuplicates: false,
index: undefined
}
return Parse._def = def;
/**
* Options for using the Parse method
* @typedef {Object} ParseOptions
* @property {string} [separator=def.separator] The separator character for columns within a row
* @property {string} [escape=def.escape] The escape character to use as quotes around a whole cell containing the separator character
* @property {string} [untitledHeaders=def.untitledHeaders] What to name any columns without a header, assuming the output type is to be an object
* @property {boolean} [hasHeaders=def.hasHeaders] Whether the first line of the CSV file has its own headers
* @property {boolean} [allowNull=def.allowNull]
* @property {boolean} [correctDuplicates=def.correctDuplicates]
* @property {boolean} [force=def.force]
* @property {typeResolvable} [type=def.type] The output type
* @property {number[]} [skipColumns=def.skipColumns]
* @property {number[]} [numberOnly=def.numberOnly] List of columns to validate as being full of numbers only
* @property {indexResolvable} [index=def.index]
*/
}
/**
* Inherent properties of the string input
* Parse data ready for reformatting
*/
/**
* String input value to the parse constructor
* Input is stringResolvable - can be object with string property, buffer, number, boolean, or string
*/
get str () {
if (this._str) return this._str;
return "";
}
set str (str) {
if (typeof str === "object") str = str.string;
if (typeof str !== "string") str = str.toString();
if (typeof str !== "string") throw "TypeError: typeof parse() input must be a string resolvable.";
this._str = str.replace(/\r/g, "");
}
/**
* String lines split by newline
* Should produce an array of each row in the CSV
* @private
*/
get rawLines() {
if (this._rawLines) return this._rawLines;
return this._rawLines = this.str.split('\n');
}
/**
* Splits each row by the ',' separator
* Any columns which the user specifies to skip are skipped
* @private
* @example
* [["index", "name", "time", "timestamp"], ["1", "andy", "2019-03-25", "01:15"]]
*/
get splitLines() {
if (this._splitLines) return this._splitLines;
let splitLines = this.rawLines.map(line => line.trim().split(this.separator));
if (this.skipColumns.length > 0) splitLines.forEach(arr => this.skipColumns.forEach(i => arr.splice(i, 1)));
return this._splitLines = splitLines;
}
/**
* Runs through the rows crudely split by this.splitLines and returns the indices that need to be joined on account of the escape characters
* @private
* @example[[[0, 1], [3, 5]], [[0, 1], [3, 6]]
*/
get mergeIndices() {
if (this._mergeIndices) return this._mergeIndices;
let mergeIndices = this.splitLines.map((line, i) => {
let indices = new Map();
let start = null;
line.forEach((cell, j) => {
try {
if (cell.startsWith(this.escape)) {
if (typeof start === "number") throw "double start";
if (cell.endsWith(this.escape)) return;
start = j;
} else
if (cell.endsWith(this.escape)) {
if (typeof start !== "number") throw "double end";
indices.set(start, j);
start = null;
}
if (j >= line.length - 1 && typeof start === "number") throw "unfinished end";
} catch (e) {
console.error(Array.from(indices.entries()));
if (e) throw new SyntaxError(`unbalanced escape character (${e}) on line ${i + 1} column ${j + 1}\n${line}`);
}
});
return Array.from(indices.entries());
})
return this._mergeIndices = mergeIndices;
}
/**
* Merges the escaped value cells together from splitLines to produce a finalised 2D Array of rows and columns
* Represents the table in 2D Array form
* @public
*/
get lines () {
if (this._lines) return this._lines;
let lines = this.splitLines;
for (let i = 0; i < this.mergeIndices.length; i++) {
for (let [start, finish] of this.mergeIndices[i]) {
let arr1 = lines[i].slice(0, start);
let arr2 = lines[i].slice(start, finish + 1);
let arr3 = lines[i].slice(finish + 1);
lines[i] = [].concat(arr1, [arr2.join(this.separator)], arr3);
}
}
return this._lines = lines;
}
/**
* Slices off the first line of the CSV and turns it into the object's headers, unless options.hasHeaders is set to false, in which case returns no headers.
* @returns {string[]} Must have unique string values
* @private
*/
get rawHeaders() {
if (this._rawHeaders) return this._rawHeaders;
if (!this.hasHeaders) return this._rawHeaders = [];
return this._rawHeaders = this.lines[0].map(header => this.stripEscape(header.trim().toString()));
}
/**
* Lengthens out the headers so that all columns are given a header. If user didn't include table headers, numberOnly are used.
* @returns {string[]} An array the length of the longest row in the table with full and unique header names
* @private
*/
get headers () {
if (this._headers) return this._headers;
let headers = this.rawHeaders;
headers.reduce((acc, curr, i) => {
if (acc[curr]) throw new SyntaxError("Duplicate header " + curr + "specified in columns " + (acc[curr] + 1) + " and " + i);
acc[curr] = i;
return acc;
}, {})
let constant = headers.length ? this.untitledHeaders : "";
let i = 0;
while (headers.length < this.maxLength) {
i++;
if (headers.indexOf(constant + i.toString()) !== -1) continue; //generates unique key names
headers.push(constant + i.toString());
}
return this._headers = headers;
}
/**
* Grabs the main table from this.lines. Runs through each cell and removes extraneous quote marks from any
*/
get body () {
if (this._body) return this._body;
let body = this.lines.slice(this.hasHeaders ? 1 : 0);
for (let i = 0; i < body.length; i++) {
for (let j = 0; j < body[i].length; j++) {
if (typeof body[i][j] !== "string") continue;
body[i][j] = this.stripEscape(body[i][j].toString().trim());
if (this.numberOnly[j]) {
body[i][j] = Number(body[i][j]);
if (isNaN(body[i][j])) throw new SyntaxError(`column '${this.headers[j]}' is given as numberOnly, but couldn't find number value at row ${i}.\n${body[i]}}`);
}
}
}
return this._body = body;
}
set body (body) {
this._body = body;
}
get output () {
if (this._output) return this._output;
return this.body.reduce((acc, line, i) => {
let obj = {};
for (let j = 0; j < this.maxLength; j++) {
obj[this.headers[j]] = line[j];
}
let indexvalue = this.indices[i];
acc[indexvalue.toString()] = obj;
return acc;
}, {});
}
/**
* Parameter properties of the parse input
* These are each lazy loaded at some point and called by the above methods
*/
/**
* @returns {string} "array"|"Object"
* @default "array"
*/
get type () {
return this._type;
}
/**
* Function to resolve type parameter into a value of type for output
* @typedef {Array|Object|string} typeResolvable
* @returns {string} array|object
*/
set type (typeResolvable) {
if (Array.isArray(typeResolvable)) return 'array';
if (typeof typeResolvable === 'object') return 'object';
if (typeof typeResolvable !== 'string') throw new TypeError('Type parameter must be Array or Object');
if (!/^(array|object)$/i.test(typeResolvable)) throw new TypeError('type specified must be "Array" or "Object".');
return this._type = typeResolvable.match(/^(a(?:rray)|o(?:bject))$/i)[1].toLowerCase();
}
get index () {
return this._index;
}
/**
* A value for specifying a column. Can be done by a column name, a column number, or a function identifying the column for each row.
* @typedef {function|number|string} indexResolvable
*/
set index (indexResolvable) {
if (typeof indexResolvable === "undefined") return this._index = indexResolvable;
if (typeof indexResolvable === "function") return this._index = indexResolvable;
let index = this.resolveIndex(indexResolvable);
let body = this.body;
if (indexResolvable > this.minLength) {
let indices = body.map(line => line[index]);
let j = 1;
for (let i = 0; i < indices[i].length; i++) {
if (indices[i] === undefined) {
if (!this.force) throw new RangeError(`couldn't find index value for row ${i}. Use "force: true" in options to parse anyway, or modify data to correct.\n${this.body[i].join(",")}`);
while (indices.indexOf(j) !== -1) j++;
body[i][index] = j;
}
}
this.body = body;
}
this._index = index;
}
/**
* Function to resolve function, number, or string to column index value
* @param {indexResolvable} indexResolvable
* @returns {number}
*/
resolveIndex(indexResolvable) {
switch (typeof indexResolvable) {
case ("number"):
if (indexResolvable < 1) throw new RangeError(`cannot read column '${indexResolvable}' for index of CSV file: CSV columns begin at '1'`);
return indexResolvable - 1;
case("string"):
if (!this.hasHeaders) throw new Error(`cannot find index by header name when "hasHeaders: true" has not be given in options`)
let index = this.headers.indexOf(indexResolvable);
if (index === -1) throw new Error(`couldn't find header '${indexResolvable}', please specify a header name or a number.`);
return index;
case ("function"):
return indexResolvable;
default:
throw new TypeError('index specified must be a Number or String');
}
}
/**
* @returns {boolean[]}
*/
get numberOnly () {
if (this._numberOnly) return this._numberOnly;
}
/**
* Because the ignored columns get skipped over in the count, the numberOnly array needs to be modified to reduce for each skipped column
* @typedef {number[]} numberOnlyResolvable
*/
set numberOnly (numberOnlyResolvable) {
if (!Array.isArray(numberOnlyResolvable)) throw new TypeError();
let arr = numberOnlyResolvable.map((n) => {
let number = this.resolveIndex(n);
for (let column of this.skipColumns.reverse()) {
if (column === number) throw new Error(`cannot both read column '${this.headers[n]}' as numberOnly and ignore it`);
if (column < number) number--;
}
return number;
});
let numberOnly = new Array(this.maxLength);
for (let i of arr) numberOnly[i] = true;
for (let i = 0; i < this.maxLength; i++) if (!numberOnly[i]) numberOnly[i] = false;
return this._numberOnly = numberOnly;
}
/**
* @returns {number[]}
*/
get skipColumns () {
if (this._skipColumns) return this._skipColumns;
}
set skipColumns (columnsResolvable) {
if (!Array.isArray(columnsResolvable) || !columnsResolvable.every(c => typeof c === "number")) throw new TypeError('columns must be an array of columns that are numberOnly');
return this._skipColumns = columnsResolvable.map(n => n--); //maps them a
}
/**
* @private
*/
get lengths() {
if (this._lengths) return this._lengths;
return this._lengths = this.lines.map(row => row.length);
}
/**
* Returns the minimum number of columns in the CSV data-set for each row
*/
get minLength () {
if (this._minLength) return this._minLength;
return this._minLength = Math.min(...this.lengths);
}
/**
* Returns the maximum number of columns in the CSV data-set for each row. Throws an error if any are found and user specified not to allow undefined/null values
*/
get maxLength () {
if (this._maxLength) return this._maxLength;
let maxLength = Math.max(...this.lengths);
if (this.allowNull === false && maxLength !== this.minLength) {
let row = this.body.find(row => row.length > this.minLength);
throw new Error(`extra column in row ${row.length + 1}. Use "allowNull: true" in options to parse anyway, or modify data to correct.\n${row.join(",")}`);
};
return this._maxLength = maxLength;
}
/**
* Private methods called within the instance
*/
get regex () {
if (this._regex) return this._regex;
return this._regex = new RegExp(`^${this.escape}*([^${this.escape}]*)${this.escape}*$`);
}
/**
* Removes extraneous escape characters from a given cell (string value)
* @param {string} str
* @private
*/
stripEscape(str) {
try {
if (typeof (str) !== "string") return str;
return str.match(this.regex)[1] || "";
} catch (e) {
if (e) throw ([str, this.regex, e]);
}
}
get indices () {
if (this._indices) return this._indices;
if (this.index === undefined || this.type === "array") return this._indices = Array.from({length: this.body.length}, (x, i) => i);
let validator = {};
return this._indices = this.body.map((curr, i) => {
let index = this.resolveKey(curr);
if (!this.correctDuplicates) {
if (validator[index]) throw `SyntaxEror: Couldn't ${this.index !== undefined ? "use '" + index + "'" : "generate iterators"} as index because of duplicate index values at rows ${validator[index]} and ${i}. Use 'correctDuplicates: true' to automatically generate indices for duplicates.`;
else {
validator[index] = i;
return index;
}
} else {
if (!validator[index]) validator[index] = 1;
else validator[index]++;
return index + "-" + validator[index];
}
});
}
resolveKey(row) {
if (this.index === undefined) return "";
if (typeof this.index !== "function") return row[this.index];
let keys = Parse.getInputs(this.index);
let args = keys.map((input) => {
if (input === "iterator") return "";
return row[this.resolveIndex(input)];
});
let iterator;
if (keys.indexOf("iterator") !== -1) {
let raw = this.index(...args);
if (!this.usedIndices[raw]) this.usedIndices[raw] = 1;
else this.usedIndices[raw]++;
iterator = this.usedIndices[raw];
}
let args2 = keys.map((input) => {
if (input === "iterator") return iterator;
return row[this.resolveIndex(input)];
});
let index = this.index(...args2);
return index;
}
static getInputs (f) {
if (typeof f !== "function") throw new TypeError();
let str = f.toString().trim();
let input;
if (/^\(?([\w\s,]+)\)?\s*\=\>/.test(str)) input = str.match(/^\(?([\w\s,]+)\)?\s*\=\>/)[1];
else if (/^function[\w\s+]\(([\w\s,]+)\)/.test(str)) input = str.match(/^function[\w\s+]\(([\w\s,]+)\)/)[1];
if (!input) throw str;
let inputs = input.split(",").map(i => i.trim());
return inputs;
}
}
module.exports = Parse;
|
SQL
|
UTF-8
| 3,031 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Creation time: 03. Dez 2019 um 16:28
-- Server version: 10.4.8-MariaDB
-- PHP version: 7.3.11
-- Made by QuickWrite for the php-login-system generated by phpMyAdmin
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `lr`
--
-- --------------------------------------------------------
--
-- Tablestructure for the table `groups`
--
CREATE TABLE `groups` (
`id` int(11) NOT NULL,
`name` varchar(20) COLLATE utf8mb4_general_nopad_ci NOT NULL,
`permissions` text COLLATE utf8mb4_general_nopad_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_nopad_ci;
--
-- Data fo the table `groups`
--
INSERT INTO `groups` (`id`, `name`, `permissions`) VALUES
(1, 'standard_user', ''),
(2, 'administrator', '{\"admin\": 1}');
-- --------------------------------------------------------
--
-- Tablestructure for the table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(20) COLLATE utf8mb4_general_nopad_ci NOT NULL,
`password` varchar(64) COLLATE utf8mb4_general_nopad_ci NOT NULL,
`salt` varchar(64) COLLATE utf8mb4_general_nopad_ci NOT NULL,
`name` text COLLATE utf8mb4_general_nopad_ci NOT NULL,
`joined` datetime NOT NULL,
`group` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_nopad_ci;
--
-- Data for the Table `users`:
--
-- --------------------------------------------------------
--
-- Tablestructure for the table `users_session`
--
CREATE TABLE `users_session` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`hash` varchar(50) COLLATE utf8mb4_general_nopad_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_nopad_ci;
--
-- Indexes of the exported tables
--
--
-- Indexe of the table `groups`
--
ALTER TABLE `groups`
ADD PRIMARY KEY (`id`);
--
-- Indexe of the table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- Indexe of the table `users_session`
--
ALTER TABLE `users_session`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for every exported table
--
--
-- AUTO_INCREMENT for the table `groups`
--
ALTER TABLE `groups`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for the table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for the table `users_session`
--
ALTER TABLE `users_session`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 4,199 | 1.789063 | 2 |
[] |
no_license
|
package org.jboss.tools.bpmn2.ui.bot.complex.test.testcase;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.jboss.tools.bpmn2.reddeer.editor.ConnectionType;
import org.jboss.tools.bpmn2.reddeer.editor.ElementType;
import org.jboss.tools.bpmn2.reddeer.editor.Position;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.activities.UserTask;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.endevents.EndEvent;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.gateways.Direction;
import org.jboss.tools.bpmn2.reddeer.editor.jbpm.gateways.ParallelGateway;
import org.jboss.tools.bpmn2.ui.bot.complex.test.JBPM6ComplexTest;
import org.jboss.tools.bpmn2.ui.bot.complex.test.TestPhase;
import org.jboss.tools.bpmn2.ui.bot.complex.test.JBPM6ComplexTestDefinitionRequirement.JBPM6ComplexTestDefinition;
import org.jboss.tools.bpmn2.ui.bot.complex.test.TestPhase.Phase;
import org.jboss.tools.bpmn2.ui.bot.test.jbpm.JbpmAssertions;
import org.jboss.tools.bpmn2.ui.bot.test.jbpm.ParallelGatewaysListener;
import org.jboss.tools.bpmn2.ui.bot.test.jbpm.PersistenceWorkItemHandler;
import org.jboss.tools.bpmn2.ui.bot.test.jbpm.TriggeredNodesListener;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItem;
@JBPM6ComplexTestDefinition(projectName = "JBPM6ComplexTest", importFolder = "resources/bpmn2/model/base", openFile = "BaseBPMN2-ParalellSplitJoin.bpmn2", saveAs = "BPMN2-ParalellSplitJoin.bpmn2")
public class ComplexParalellSplitJoinTest extends JBPM6ComplexTest {
private static final String END = "End";
private static final String START = "Start";
private static final String GATEWAY_CON = "Gateway2";
private static final String GATEWAY_DIV = "Gateway1";
private static final String UT_PM_EVALUATION = "PM Evaluation";
private static final String UT_HR_EVALUATION = "HR Evaluation";
private static final String UT_SELF_EVALUATION = "Self Evaluation";
@TestPhase(phase = Phase.MODEL)
public void model() {
UserTask selfEvaluation = new UserTask("Self Evaluation");
UserTask hrEvaluation = new UserTask("HR Evaluation");
UserTask pmEvaluation = new UserTask("PM Evaluation");
ParallelGateway gateway1 = (ParallelGateway) selfEvaluation.append("Gateway1", ElementType.PARALLEL_GATEWAY,
ConnectionType.SEQUENCE_FLOW);
gateway1.setDirection(Direction.DIVERGING);
gateway1.connectTo(hrEvaluation);
gateway1.connectTo(pmEvaluation);
ParallelGateway gateway2 = (ParallelGateway) hrEvaluation.append("Gateway2", ElementType.PARALLEL_GATEWAY,
ConnectionType.SEQUENCE_FLOW, Position.SOUTH_EAST);
gateway2.setDirection(Direction.CONVERGING);
gateway2.connectTo(new EndEvent("End"));
pmEvaluation.connectTo(gateway2);
}
@TestPhase(phase = Phase.RUN)
public void run(KieSession kSession) {
PersistenceWorkItemHandler workItemHandler = new PersistenceWorkItemHandler();
kSession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
TriggeredNodesListener triggeredNodes = new TriggeredNodesListener(Arrays.asList(START, UT_PM_EVALUATION,
UT_HR_EVALUATION, UT_SELF_EVALUATION, GATEWAY_CON, GATEWAY_DIV, END), null);
ParallelGatewaysListener gatewaysEventListener = new ParallelGatewaysListener(GATEWAY_DIV, GATEWAY_CON);
kSession.addEventListener(gatewaysEventListener);
kSession.addEventListener(triggeredNodes);
ProcessInstance processInstance = kSession.startProcess("Evaluation");
JbpmAssertions.assertProcessInstanceActive(processInstance, kSession);
assertTrue(workItemHandler.getWorkItems().size() == 1);
WorkItem workItem = workItemHandler.getWorkItem(UT_SELF_EVALUATION);
assertNotNull(workItem);
workItemHandler.completeWorkItem(workItem, kSession.getWorkItemManager());
assertTrue(workItemHandler.getWorkItems().size() == 2);
workItemHandler.completeWorkItem(workItemHandler.getWorkItem(UT_HR_EVALUATION), kSession.getWorkItemManager());
workItemHandler.completeWorkItem(workItemHandler.getWorkItem(UT_PM_EVALUATION), kSession.getWorkItemManager());
JbpmAssertions.assertProcessInstanceCompleted(processInstance, kSession);
}
}
|
C++
|
UHC
| 1,346 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
#include "Shop.h"
Shop::Shop(int *energy)
:curEnergy(energy), itemNum(0)
{
for (int idx = 0; idx < ITEM_NUM; idx++)
{
itemCountList[idx] = 0;
}
}
Item* Shop::sell(int idx)
{
Item* tempItem = NULL;
if (0 <= idx && idx < itemNum) {
tempItem = itemList[idx];
}
else {
return NULL;
}
// ȮѴ.
if (*curEnergy >= tempItem->price)
{
itemCountList[idx] = tempItem->count;
*curEnergy -= tempItem->price;
return itemList[idx];
}
else
{
return NULL;
}
}
Item* Shop::getItem(int idx)
{
if (idx < itemNum)
{
return itemList[idx];
}
else
{
return NULL;
}
}
void Shop::addItem(Item* item)
{
itemList[itemNum] = item;
item->count = 0;
itemNum++;
}
void Shop::addItem(Item* item, int count)
{
itemList[itemNum] = item;
item->count = count;
itemNum++;
}
bool Shop::isAvailable(int idx) {
if (idx >= itemNum) // idx ʰ
{
return false;
}
if (*curEnergy < itemList[idx]->price) //
{
return false;
}
if (itemCountList[idx] > 0) // ð
{
return false;
}
return true;
}
void Shop::update()
{
for (int idx = 0; idx < ITEM_NUM; idx++)
{
if (itemCountList[idx] > 0)
{
itemCountList[idx] -= 1;
}
}
}
void Shop::start()
{
}
void Shop::draw()
{
}
|
Shell
|
UTF-8
| 393 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
set -e
DOWNLOAD_URL='http://registrationcenter-download.intel.com/akdlm/irc_nas/tec/16533/l_mkl_2020.1.217.tgz'
echo Installing Intel MKL 2020 Update 1
apt-get update && apt-get install -y \
build-essential cpio gcc g++ cmake doxygen
echo 'Downloading Intel MKL source code'
wget -O intel-mkl.zip "${DOWNLOAD_URL}"
unzip intel-mkl.zip
cd l_mkl_2020.1.217
./install.sh
|
JavaScript
|
UTF-8
| 527 | 2.578125 | 3 |
[] |
no_license
|
const customExpress = require("./config/configExpress");
const db = require("./config/configPostgreSQL")
const port = 3001;
db.connect(err => {
if (err) {
console.log(err)
} else {
db.query("SELECT * from NOW()", (err, res) => {
if (err) {
console.log(err)
} else{
console.log("Banco de dados conectado em " + res.rows[0].now)
}
})
const app = customExpress()
app.listen(port, () => console.log('Servidor rodando na porta ' + port))
}
})
|
Python
|
UTF-8
| 1,918 | 3.671875 | 4 |
[] |
no_license
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Задание 15.4a
Создать функцию convert_to_dict, которая ожидает два аргумента:
* список с названиями полей
* список кортежей с результатами отработки функции parse_sh_ip_int_br из задания 15.4
Функция возвращает результат в виде списка словарей (порядок полей может быть другой):
[{'interface': 'FastEthernet0/0', 'status': 'up', 'protocol': 'up', 'address': '10.0.1.1'},
{'interface': 'FastEthernet0/1', 'status': 'up', 'protocol': 'up', 'address': '10.0.2.1'}]
Проверить работу функции на примере файла sh_ip_int_br_2.txt:
* первый аргумент - список headers
* второй аргумент - результат, который возвращает функции parse_show из прошлого задания.
Функцию parse_sh_ip_int_br не нужно копировать.
Надо импортировать или саму функцию, и использовать то же регулярное выражение,
что и в задании 15.4, или импортировать результат выполнения функции parse_show.
Ограничение: Все задания надо выполнять используя только пройденные темы.
'''
from pprint import pprint
from task_15_4 import parse_sh_ip_int_br
lis = parse_sh_ip_int_br('sh_ip_int_br_2.txt')
head = ['interface', 'address', 'status', 'protocol']
def convert_to_dict(in_list,headres):
result=[]
for line in in_list:
dic={headres[0]:line[0],
headres[1]:line[1],
headres[2]:line[2],
headres[3]:line[3]}
result.append(dic)
return result
pprint(convert_to_dict(lis,head))
|
Java
|
UTF-8
| 1,777 | 2.921875 | 3 |
[] |
no_license
|
package practicestring;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
public class LocaleDemo {
public static void main(String[] args) {
Locale locale = new Locale("ru", "RU");
double lamboPrice = 180000.99;
NumberFormat numberInstance = NumberFormat.getNumberInstance(locale);
NumberFormat numberInstance1 = NumberFormat.getNumberInstance(Locale.getDefault());
NumberFormat numberInstance2 = NumberFormat.getNumberInstance(Locale.GERMAN);
NumberFormat germanCurrency = NumberFormat.getCurrencyInstance(Locale.GERMAN);
NumberFormat englishCurrency = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
DateFormat englishDateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.ENGLISH);
DateFormat germanDateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.GERMAN);
System.out.println(numberInstance.format(lamboPrice));
System.out.println(numberInstance1.format(lamboPrice));
System.out.println(numberInstance2.format(lamboPrice));
System.out.println();
System.out.println(germanCurrency.format(lamboPrice));
System.out.println(englishCurrency.format(lamboPrice));
Date date = new Date();
System.out.println(englishDateFormat.format(date));
System.out.println(germanDateFormat.format(date));
System.out.println(GreetingsReader.getInstance(Locale.FRANCE).getProperty(GreetingsReader.HELLO_WORD));
System.out.println(GreetingsReader.getInstance(Locale.US).getProperty(GreetingsReader.HELLO_WORD));
System.out.println(GreetingsReader.getInstance(Locale.getDefault()).getProperty(GreetingsReader.HELLO_WORD));
}
}
|
Java
|
UTF-8
| 11,114 | 2.0625 | 2 |
[] |
no_license
|
package com.els.romenext.api.preferences;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import com.els.romenext.api.errors.ApiResponseState;
import com.els.romenext.api.errors.ErrorResponse;
import com.els.romenext.api.errors.RomeNextResponseCodeEnum;
import com.els.romenext.api.preferences.req.AddPreferencePropertyRequest;
import com.els.romenext.api.preferences.req.AddPreferenceRequest;
import com.els.romenext.api.preferences.req.GetPreferenceByTypeRequest;
import com.els.romenext.api.preferences.req.UpdatePreferencePropertyRequest;
import com.els.romenext.api.preferences.service.AddPreferencePropertyService;
import com.els.romenext.api.preferences.service.AddPreferenceService;
import com.els.romenext.api.preferences.service.GetPreferenceByTypeService;
import com.els.romenext.api.preferences.service.GetPreferenceValueByTypeService;
import com.els.romenext.api.preferences.service.UpdatePreferencePropertyService;
import com.els.romenext.api.utils.RomeStringUtils;
@Path("/preference")
public class Preference {
private static Logger log = Logger.getLogger(Preference.class);
@GET
@Path("/type/find/typeid/{metadataid}/{groupname}/{grouphost}/{namespace}/{typeid}")
@Produces("application/json")
public Response getAllPreferencesAndConnectionsByGroup(@PathParam("metadataid") String id,
@PathParam("grouphost") String host,
@PathParam("groupname") String name,
@PathParam("namespace") String namespace,
@PathParam("typeid") String typeid ) {
ResponseBuilder responseBuilder;
Long idNum = null;
Long typeId = null;
try {
idNum = Long.valueOf(id);
} catch (Exception e) {
log.error("Invalid Number Format!", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
GetPreferenceValueByTypeService service = new GetPreferenceValueByTypeService();
return service.runService(idNum, host, name, namespace, typeId );
}
@POST
@Path("/type/find/all/bytypeid/{metadataid}")
@Consumes("application/json")
@Produces("application/json")
public Response getAllPreferencesByTypeId(@PathParam("metadataid") String metadataid,
String jsonString) {
ResponseBuilder responseBuilder;
if (RomeStringUtils.isAnyEmpty( jsonString )) {
log.error("JSON Missing!");
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
GetPreferenceByTypeRequest request = new GetPreferenceByTypeRequest();
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e) {
log.debug("Bad JSON Format ", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
String empty = request.validateRequest(json);
if(!StringUtils.isEmpty(empty)) {
log.debug("This is missing: " + empty);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
try {
request.parseRequest(json);
} catch (JSONException e) {
log.error("Bad JSON Format" + empty);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
Response response = request.preprocessor();
if (response != null) {
return response;
}
Long idNum = null;
try {
idNum = Long.valueOf( metadataid );
} catch (Exception e) {
log.error("Invalid Number Format!", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
GetPreferenceByTypeService service = new GetPreferenceByTypeService();
return service.runService( request, idNum );
}
@POST
@Path("/type/add/bytypeid/{metadataid}/")
@Consumes("application/json")
@Produces("application/json")
public Response addPreferencePropertiesViaId(@PathParam("metadataid") String metadataid,
String jsonString ) {
ResponseBuilder responseBuilder;
if (RomeStringUtils.isAnyEmpty( jsonString )) {
log.error("JSON Missing!");
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
AddPreferencePropertyRequest request = new AddPreferencePropertyRequest();
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e) {
log.debug("Bad JSON Format ", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
String empty = request.validateRequest(json);
if(!StringUtils.isEmpty(empty)) {
log.debug("This is missing: " + empty);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
try {
request.parseRequest(json);
} catch (JSONException e) {
log.error("Bad JSON Format" + empty);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
Response response = request.preprocessor();
if (response != null) {
return response;
}
Long idNum = null;
try {
idNum = Long.valueOf( metadataid );
} catch (Exception e) {
log.error("Invalid Number Format!", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
AddPreferencePropertyService service = new AddPreferencePropertyService();
return service.runService( request, idNum );
}
@POST
@Path("/create/bytypeid/{metadataid}/")
@Consumes("application/json")
@Produces("application/json")
public Response addPreference(@PathParam("metadataid") String metadataid,
String jsonString ) {
ResponseBuilder responseBuilder;
if (RomeStringUtils.isAnyEmpty( jsonString )) {
log.error("JSON Missing!");
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
AddPreferenceRequest request = new AddPreferenceRequest();
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e) {
log.debug("Bad JSON Format ", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
String empty = request.validateRequest(json);
if(!StringUtils.isEmpty(empty)) {
log.debug("This is missing: " + empty);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
try {
request.parseRequest(json);
} catch (JSONException e) {
log.error("Bad JSON Format" + empty);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
Response response = request.preprocessor();
if (response != null) {
return response;
}
Long idNum = null;
try {
idNum = Long.valueOf( metadataid );
} catch (Exception e) {
log.error("Invalid Number Format!", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
AddPreferenceService service = new AddPreferenceService();
return service.runService( request, idNum );
}
@PUT
@Path("/type/update/bytypeid/{metadataid}")
@Consumes("application/json")
@Produces("application/json")
public Response updatePreferenceAndProperties(@PathParam("metadataid") String metadataid,
String jsonString) {
ResponseBuilder responseBuilder;
if (RomeStringUtils.isAnyEmpty( jsonString )) {
log.error("JSON Missing!");
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
UpdatePreferencePropertyRequest request = new UpdatePreferencePropertyRequest();
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e) {
log.debug("Bad JSON Format ", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
String empty = request.validateRequest(json);
if(!StringUtils.isEmpty(empty)) {
log.debug("This is missing: " + empty);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.MISSING_MANDATORY_DATA, null).getResponseBuilder();
return responseBuilder.build();
}
try {
request.parseRequest(json);
} catch (JSONException e) {
log.error("Bad JSON Format", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
Response response = request.preprocessor();
if (response != null) {
return response;
}
Long idNum = null;
try {
idNum = Long.valueOf(metadataid);
} catch (Exception e) {
log.error("Invalid Number Format!", e);
responseBuilder = ErrorResponse.build(ApiResponseState.FAILURE, RomeNextResponseCodeEnum.BAD_JSON_FORMAT, null).getResponseBuilder();
return responseBuilder.build();
}
UpdatePreferencePropertyService service = new UpdatePreferencePropertyService();
return service.runService( request, idNum);
}
}
|
Shell
|
UTF-8
| 1,133 | 3.9375 | 4 |
[] |
no_license
|
#!/bin/sh
# __ _ _
# / _(_) | ___ ___
# | |_| | |/ _ \/ __|
# _| _| | | __/\__ \
# (_)_| |_|_|\___||___/
#
set -e
set -u
is_available() {
which "$1" >/dev/null 2>&1
return $?
}
if [ -z "${DOTPATH:-}" ]; then
DOTPATH=~/.dotfiles; export DOTPATH
fi
DOTGIT="https://github.com/nobuyo/dotfiles.git"; export DOTGIT
get_dotfile() {
if [ -d "$DOTPATH" ]; then
echo "$DOTPATH already exists"
exit 1
fi
if is_available "git"; then
git clone --recursive "$DOTGIT" "$DOTPATH"
elif is_available "curl"; then
local tarball="https://github.com/nobuyo/dotfiles/archive/master.tar.gz"
if is_available "curl"; then
curl -L "$tarball"
fi | tar xvz
if [ ! -d dotfiles-master ]; then
log_fail "dotfiles-master: not found"
exit 1
fi
command mv -f dotfiles-master "$DOTPATH"
else
echo "curl required"
exit 1
fi
echo "Done"
}
deploy() {
echo ""
echo "Deploying dotfiles..."
if [ ! -d $DOTPATH ]; then
echo "$DOTPATH: not found"
exit 1
fi
cd "$DOTPATH"
make deploy &&
echo "Done"
}
setup() {
get_dotfile && deploy
}
setup
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.