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
| 292
| 2.0625
| 2
|
[] |
no_license
|
package com.petbackend.api.service;
import java.util.List;
import java.util.Optional;
import com.petbackend.api.model.PetType;
public interface PetTypeService {
PetType save(PetType type);
Optional<PetType> findById(Long id);
void remove(PetType type);
List<PetType> getPetTypes();
}
|
Python
|
UTF-8
| 445
| 4.3125
| 4
|
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
length_feet = int(input("What is the length of the room in feet? "))
width_feet = int(input("What is the width of the room in feet? "))
square_feets = length_feet * width_feet
square_meters = square_feets * 0.09290304
print(f"You entered dimensions of {length_feet} feet by {width_feet} feet")
print("The area is")
print(f"{square_feets} square feet")
print(f"{square_meters:.3f} square meters")
|
C++
|
GB18030
| 348
| 2.78125
| 3
|
[] |
no_license
|
#ifndef _ENTITY_H
#define _ENTITY_H
class BassGameEntity
{
public:
BassGameEntity(int id)
{
SetID(id);
}
int GetiID() const
{
return m_ID;
}
void SetID(int val)
{
m_ID = val;
m_iNextValidID = m_ID + 1;
}
protected:
private:
int m_ID;
static int m_iNextValidID; // һЧ
};
#endif //_ENTITY_H
|
Python
|
UTF-8
| 1,852
| 2.640625
| 3
|
[] |
no_license
|
import re
from lxml import etree
class HtmlParser:
def parser(self, response):
items = []
try:
tree = etree.HTML(response.text)
house_list = tree.xpath('//ul[@id="house-lst"]/li')
for house in house_list:
title = ''.join(house.xpath('./div[2]/h2/a/text()'))
link = ''.join(house.xpath('./div[2]/h2/a/@href'))
house_type = ''.join(house.xpath('.//span[@class="zone"]/span/text()'))
area = ''.join(house.xpath('./div[2]/div[1]/div[1]/span[2]/text()'))
direction = ''.join(house.xpath('./div[2]/div[1]/div[1]/span[3]/text()'))
description = ''.join(house.xpath('./div[2]/div[1]/div[2]/div')[0].xpath('string(.)'))
tags = ''.join(house.xpath('./div[2]/div[1]/div[3]/div/div')[0].xpath('string(.)'))
rent = ''.join(house.xpath('./div[2]/div[2]/div[1]/span/text()'))
time = ''.join(house.xpath('./div[2]/div[2]/div[2]/text()'))
has_seen = ''.join(house.xpath('./div[2]/div[3]/div/div[1]/span/text()'))
items.append({'title': title, 'link': link, 'house_type': house_type, 'area': area,
'direction': direction, 'description': description, 'tags': tags,
'rent': rent, 'time': time, 'has_seen': has_seen})
page_num = re.findall(r'https://\S+/zufang/pg(\S*)/', response.url)
if page_num:
page_num = int(page_num[0])
else:
page_num = 1
if page_num > 100:
next_page = 'end'
else:
next_page = response.url[0: 30] + 'pg' + str(page_num + 1) + '/'
return items, next_page
except:
print(response.status_code)
|
Python
|
UTF-8
| 8,624
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
"""Shift amount activity for the simulation."""
import numpy as np
import openclsim.core as core
from .base_activities import GenericActivity
class ShiftAmountActivity(GenericActivity):
"""
ShiftAmountActivity Class forms a specific class for shifting material from an origin to a destination.
It deals with a single origin container, destination container and a single processor
to move substances from the origin to the destination. It will initiate and suspend processes
according to a number of specified conditions. To run an activity after it has been initialized call env.run()
on the Simpy environment with which it was initialized.
origin: container where the source objects are located.
destination: container, where the objects are assigned to
processor: resource responsible to implement the transfer.
amount: the maximum amount of objects to be transfered.
duration: time specified in seconds on how long it takes to transfer the objects.
id_: in case of MultiContainers the id_ of the container, where the objects should be removed from or assiged to respectively.
start_event: the activity will start as soon as this event is triggered
by default will be to start immediately
"""
def __init__(
self,
processor,
origin,
destination,
duration=None,
amount=None,
id_="default",
show=False,
phase=None,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
"""Initialization"""
self.origin = origin
self.destination = destination
self.processor = processor
self.amount = amount
self.duration = duration
self.id_ = id_
self.print = show
self.phase = phase
def _request_resource_if_available(
self,
env,
resource_requests,
site,
processor,
amount,
kept_resource,
activity_id,
id_="default",
engine_order=1.0,
verbose=False,
):
all_available = False
while not all_available and amount > 0:
# yield until enough content and space available in origin and destination
yield env.all_of(events=[site.container.get_available(amount, id_)])
yield from self._request_resource(resource_requests, processor.resource)
if site.container.get_level(id_) < amount:
# someone removed / added content while we were requesting the processor, so abort and wait for available
# space/content again
self._release_resource(
resource_requests, processor.resource, kept_resource=kept_resource
)
continue
if not processor.is_at(site):
# todo have the processor move simultaneously with the mover by starting a different process for it?
yield from self._move_mover(
processor,
site,
activity_id=activity_id,
engine_order=engine_order,
verbose=verbose,
)
if site.container.get_level(id_) < amount:
# someone messed us up again, so return to waiting for space/content
self._release_resource(
resource_requests,
processor.resource,
kept_resource=kept_resource,
)
continue
yield from self._request_resource(resource_requests, site.resource)
if site.container.get_level(id_) < amount:
self._release_resource(
resource_requests, processor.resource, kept_resource=kept_resource
)
self._release_resource(
resource_requests, site.resource, kept_resource=kept_resource
)
continue
all_available = True
def main_process_function(self, activity_log, env):
"""Origin and Destination are of type HasContainer."""
assert self.processor.is_at(self.origin)
assert self.destination.is_at(self.origin)
verbose = False
resource_requests = self.requested_resources
if not hasattr(activity_log, "processor"):
activity_log.processor = self.processor
if not hasattr(activity_log, "mover"):
activity_log.mover = self.origin
self.amount, all_amounts = self.processor.determine_processor_amount(
[self.origin], self.destination, self.amount, self.id_
)
if self.amount == 0:
raise RuntimeError(
f"Attempting to shift content from an empty origin ({self.origin.name}) or to a full destination ({self.destination.name}). ({all_amounts})"
)
yield from self._request_resource(resource_requests, self.destination.resource)
yield from self._request_resource_if_available(
env,
resource_requests,
self.origin,
self.processor,
self.amount,
None, # for now release all
activity_log.id,
self.id_,
1,
verbose=False,
)
if self.duration is not None:
rate = None
elif self.duration is not None:
rate = self.processor.loading
elif self.phase == "loading":
rate = self.processor.loading
elif self.phase == "unloading":
rate = self.processor.unloading
else:
raise RuntimeError(
"Both the pase (loading / unloading) and the duration of the shiftamount activity are undefined. At least one is required!"
)
start_time = env.now
args_data = {
"env": env,
"activity_log": activity_log,
"activity": self,
}
yield from self.pre_process(args_data)
activity_log.log_entry(
t=env.now,
activity_id=activity_log.id,
activity_state=core.LogState.START,
)
start_shift = env.now
yield from self._shift_amount(
env,
self.processor,
self.origin,
self.origin.container.get_level(self.id_) + self.amount,
self.destination,
activity_id=activity_log.id,
duration=self.duration,
rate=rate,
id_=self.id_,
verbose=verbose,
)
activity_log.log_entry(
t=env.now,
activity_id=activity_log.id,
activity_state=core.LogState.STOP,
)
args_data["start_preprocessing"] = start_time
args_data["start_activity"] = start_shift
yield from self.post_process(**args_data)
# release the unloader, self.destination and mover requests
self._release_resource(
resource_requests, self.destination.resource, self.keep_resources
)
if self.origin.resource in resource_requests:
self._release_resource(
resource_requests, self.origin.resource, self.keep_resources
)
if self.processor.resource in resource_requests:
self._release_resource(
resource_requests, self.processor.resource, self.keep_resources
)
def _move_mover(self, mover, origin, activity_id, engine_order=1.0, verbose=False):
"""Call the mover.move method, giving debug print statements when verbose is True."""
# Set activity_id to mover
mover.activity_id = activity_id
yield from mover.move(origin, engine_order=engine_order)
def _shift_amount(
self,
env,
processor,
origin,
desired_level,
destination,
activity_id,
duration=None,
rate=None,
id_="default",
verbose=False,
):
"""Call the processor.process method, giving debug print statements when verbose is True."""
amount = np.abs(origin.container.get_level(id_) - desired_level)
# Set activity_id to processor and mover
processor.activity_id = activity_id
origin.activity_id = activity_id
# Check if loading or unloading
yield from processor.process(
origin,
amount,
destination,
id_=id_,
duration=duration,
rate=rate,
)
|
Shell
|
UTF-8
| 406
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash -x
## For testing
APP_VERSION="v1000"
APP_ENVIRONMENT="default"
[ -z "$APP_ENVIRONMENT" ] && echo "APP_ENVIRONMENT is not set" && exit 1
[ -z "$APP_VERSION" ] && echo "APP_VERSION is not set" && exit 1
helm version || exit 1
if [[ "$DEBUG" == "true" ]]; then
DEBUG_MODE=" --dry-run --debug "
fi
helm delete ${DEBUG_MODE} app-sample-${APP_VERSION} --namespace ${APP_ENVIRONMENT}
|
C++
|
UTF-8
| 2,438
| 2.640625
| 3
|
[] |
no_license
|
#pragma once
/*
AWind.h - Arduino window library support for Color TFT LCD Boards
Copyright (C)2016 Andrei Degtiarev. All right reserved
You can always find the latest version of the library at
https://github.com/AndreiDegtiarev/AWind
This library is free software; you can redistribute it and/or
modify it under the terms of the CC BY-NC-SA 3.0 license.
Please see the included documents for further information.
Commercial use of this library requires you to buy a license that
will allow commercial use. This includes using the library,
modified or not, as a tool to sell products.
The license applies to all part of the library including the
examples and tools supplied with the library.
*/
#include <ITimerEventReceiver.h>
/**Timer class. Implement timer events in window classes.
If a Window need to receive timer events it need to be derived from ITimerEventReceiver and NotifyTimer meber function has to be implemented
See VacuumPump example for details
*/
class ATimer
{
ITimerEventReceiver *_timerEventReceiver; //!< call back event receiver
uint32_t _msStart; //!< time when timer was started
uint32_t _msInterval; //!< timer interval
bool _isAutoreset; //!< defines whether timer event will begenerated only once or continiously
bool _isEnabled; //!< defines whether timer is active
public:
ATimer()
{
_isAutoreset = false;
_isEnabled = false;
_timerEventReceiver = NULL;
}
///Registers event receiver.
void RegisterTimerEventReceiver(ITimerEventReceiver *timerEventReceiver)
{
_timerEventReceiver = timerEventReceiver;
}
///Set whether timer is in autoreset modus
void SetAutoReset(bool isAutoreset)
{
_isAutoreset = isAutoreset;
}
///Set timer interval in milliseconds
void SetInterval(uint32_t milliseconds)
{
_msInterval = milliseconds;
}
///Returns true if timer is active
bool IsEnabled()
{
return _isEnabled;
}
///Starts timer
void Enable()
{
_isEnabled = true;
_msStart = millis();
}
///Disabels timer
void Reset()
{
_isEnabled = false;
}
///Returns actual elapsed time
uint32_t Elapsed()
{
return millis() - _msStart;
}
//Is called by AWind framework
void loop()
{
if (_isEnabled && Elapsed() >= _msInterval && _timerEventReceiver != NULL)
{
_timerEventReceiver->NotifyTimer(this);
if (_isAutoreset)
Enable();
else
Reset();
}
}
};
|
Markdown
|
UTF-8
| 663
| 2.609375
| 3
|
[] |
no_license
|
<h1>ISports-C</h1>
<h3>What is this project?</h3>
<p>This is a simple real-time chat application built using Firebase Authentication and Firestore.</p>
<p>Built it mostly to use as a starting-point for other applications that have a real-time chat portion.</p>
<h3>Application features:</h3>
<ol>
<li>Register new users</li>
<li>Login with users that have registered</li>
<li>Create new games</li>
<li>Join games</li>
<li>Chat with other users</li>
</ol>
<h3> Created by </h3>
<ul>
<li>Ayush Shrestha- Team Leader</li>
<li>Daniel Stojanoski - Project Planner</li>
<li>Kenneth Yen - Project Researcher</li>
<li>Abi Kayode- Project Documentor</li>
</ull>
|
Markdown
|
UTF-8
| 9,611
| 3.953125
| 4
|
[
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
# Chapter 9
- Insertion sort is another sorting algorithm. Like bubble sort and selection sort its worst-case time is O(n2),but it has a different best-case. When the values are already nearly sorted, insertion sort runs in O(n).
- Quick sort, as its name would suggest, is one of the faster sorting algorithms. There are other algorithms with - a better worst-case complexity - merge sort and heap sort both run in O(n lg n) worst-case, whereas for quick sort the worst-case is O(n2), the same as bubble sort! However the average running time for quick sort is O(n lg n), and its worst case is highly improbable, so it's still a fast algorithm.
- Big-O doesn't tell you how much actual time an algorithm will take. It tells you how quickly that time increases as the size of the input increases.
- In addition to time complexity, you can also compare the space complexity of different algorithms, which concerns how much additional space an algorithm needs to use. There is often a tradeoff between the amount of time and the amount of space an algorithm requires.
- In coding interviews you'll be expected to be able to talk about running times. They'll ask you to figure out the code for something on a white board and often they'll ask you about its running time and whether you can think of a way to do it that uses less time or memory.
## Binary Search
```c++
int binarySearch(int arr[], int size, int target) {
int start = 0, end = size - 1;
while(start + 1 < end) {
int middle = start + (end - start) / 2;
if(target == arr[middle]) {
start = middle;
} else if(target > arr[middle]) {
start = middle;
} else {
end = middle;
}
}
```
***
## Bubble Sort
Works by comparing each element in the array with its neighbor and swapping then if they are not in the desired order.
```
Do
Set madeAswap flag to false
For count = 0 to the next-to-last array subscript
If array[count] is greater than array[count +1]
Swap the contents of array[count] and array[count+1]
set madeAswap flag to true
End if
End for
While the madeAswap flag is true
```
```c++
void bubbleSort(int *arr, int size) {
for(int curLargeIndex = size - 1; curLargeIndex >= 0; curLargeIndex--) {
// int curLarge = arr[curLargeIndex];
for(int j = 0; j < curLargeIndex; j++) {
if(arr[j] > arr[j + 1]) {
swap(arr, j, j+ 1);
}
}
}
}
void bubbleSort2(int arr[], int size) {
int count;
bool madeAswap = false;
do {
for(count = 0; count < size - 1; count++) {
madeAswap = false;
if(arr[count] > arr[count+1]) {
swap(arr, count, count + 1);
madeAswap = true;
}
}
} while (madeAswap);
}
void swap(int *arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
```
## Selection Sort
Bubble is inefficient for large arrays because repeated data swaps are often required to place a single item in its correct position on each pass. The selection sort, like the bubble sort, places just one item in its correct position on each pass. However it usually perform fewer exchanges because it moves items immedicately to their correct position in the array.
```
For startScan = 0 to the next-to-last array subscript
Set minIndex to startScan
Set minValue to array[startScan]
For index = (startScan + 1) to the last subscript in the array
If array[index] is less than minValue
Set minValue to array[index]
Set minIndex to indrx
End if
Increment index
End for
///////
Set array[minIndex] to array[startScan]
Set array[startScan] to minValue // Swap
End For
```
```c++
void selectSort2(int arr[], int size) {
int startScan, minIndex, minValue;
for(startScan = 0; startScan < size -1; startScan++) {
minIndex = startScan;
minValue = arr[startScan];
for(int currentIndex = startScan + 1; currentIndex < size; currentIndex++) {
if(arr[currentIndex] < minValue) {
minValue = arr[currentIndex];
minIndex = currentIndex;
}
}
swap(arr, minIndex, startScan);
}
}
void selectSort(int arr[], int size) {
for(int i = 0; i < size; i++) {
// Based on current index and search the rest of array
int minIndex = findMinIndex(arr, size, i);
swap(arr, i, minIndex);
}
}
int findMinIndex(int arr[], int size, int curInedx) {
int minIndex = curInedx;
for(int i = curInedx + 1; i < size; i++) {
if(arr[i] < arr[curInedx]) {
minIndex = i;
}
}
return minIndex;
}
void swap(int* arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
```
## Insertion Sort
```
_
2 4 5 3 1
next = 4
index = i
j = i
check if next < arr[j-1]
_ _ _ _
2 4 5 3 1
next = 3
index = 3
j = i
check if next < arr[j-1]
3 < arr[2]
3 < arr[1]
3 < arr[0]
- * - -
2 3 4 5
while(j > 0 and next < arr[j-1]) {
arr[j] = arr[j-1]; // 2 4 5 5 -> 2 4 4 5
j--
}
arr[j] = next; // 2 3 4 5
```
***
## Method to get const Object
The objects in the std::set are stored as const StudentT. So when you try to call getId() with the const object the compiler detects a problem, namely you're calling a non-const member function on const object which is not allowed because non-const member functions make NO PROMISE not to modify the object; so the compiler is going to make a safe assumption that getId() might attempt to modify the object but at the same time, it also notices that the object is const; so any attempt to modify the const object should be an error. Hence compiler generates error message.
```c++
std::string Person::getName() const {
return name;
}
```
***
## Vector with BubbleSort
```c++
// Function prototypes
void displayVector(vector<int>);
void sortVector(vector<int> &);
int main() {
const int SIZE = 6;
vector<int> values(SIZE);
cout << "Please enter " << SIZE << " Integers separated by spaces. \n";
for(int i = 0; i < SIZE; i++) {
cin >> values[i];
}
cout << "\n The unsorted values entered are : \n";
displayVector(values);
sortVector(values);
cout << "\n Sorted Vector are: \n";
displayVector(values);
return 0;
}
/*********************************************************************
** Function: sortVector(vector<int> &);
** Argument: The reference(Address) of vector
** Return : Void. But it will use passing by reference to change
** the origin value of vector in the main function stack
*********************************************************************/
void sortVector(vector<int> &number) {
int temp;
bool swaped = false;
do{
swaped = false;
for(int i = 0; i < number.size() - 1; i++) {
if(number.at(i) > number.at(i+1)) {
temp = number.at(i);
number.at(i) = number.at(i+1);
number.at(i+1) = temp;
swaped = true;
}
}
} while (swaped);
}
void displayVector(vector<int> number) {
for(int i = 0; i < number.size(); i++) {
cout << number.at(i) << endl;
}
}
```
## Computational Problems and Basic Step
Input: Dose not mean a set of data entered by the user. It means the form of the data used by the algorithm solving the problem.
Output: Means the result created by the algorithm that soves the problem.
## Asymptotic Complexity and the Big O Notation
### O(1)
A function f(n) is in this class if there is a constant K > 0 such that f(n) <= K for all n >= 1. An algorithm whose worst case complexity function is in this class is said to run in constant time.
### O(log2n)
Algorithm in this class run logarithmic time. A huge increase in the size of the problem results in only a small increase in the running time of the algorithm. (The Binary Search)
### O(n)
Algorithm in this class run in linear time. Any increase in the size of the problem results in a slight increase in the running time of the algorithm. Sequential search that make single pass, or a constant number of passes, over their input.
### O(nlogn)
The average case complexity of QuickSort and MergeSort.
### O(n^2)
Quadratic time. The performance is characteristic of algorithms that make multiple passes over the input data using two nested loops. The worst-case complexity funcitons of bubble sort, selection sort and QuickSort all lie in this case.
***
## Pointers
A variable that stores an address is called a pointer variable, but is often simply referred to as just a pointer. The definition of a pointer variable, say ptr, must specify the type of data taht ptr will point to.
```
int *ptr
```
'*' allows you to pass from a pointer to the variable being pointed to, it's called the indirection operator.
```
name |ptr | x |(address of x is 0x7300)
--------- --------
value |0x7300 | 25 |
```
You can use a pointer to indirectly access and modify the variable being pointed to. ptr could be used to change the contents of the variable x.
When the indirection opeartor is placed in front of a pointer variable name, it "deference" the pointers. When working with a deference pointer, you're actually working with the value the pointer is pointing to.
```c++
int x = 10, userInput;
int *ptr = &x;
cout << "X equal to: " << *ptr << endl;
cout << "Please input value to change x \n";
cin >> userInput;
*ptr = userInput;
cout << "New Value is :" << *ptr << endl;
```
## The Relationship between arrays and pointers
Array name can be used as pointer constants, and pointers can be used as array names.
```c++
int arr[] = {1,2,3,4};
int* arrPtr = NULL;
arrPtr = arr;
for(int i = 0; i < 4; i++) {
cout << *(arrPtr + i) << endl;
}
```
|
Markdown
|
UTF-8
| 1,464
| 3.078125
| 3
|
[] |
no_license
|
In R, if you want to convert a string representing an integer in base 16 to an integer, then you can simply use <code>as.integer</code> as long as you prefix the string with "0x". Here's an example:
<pre>
as.integer("0x4d2")
[1] 1234
</pre>
Originally, I had posted the following excerpt from <code>as.hexmode</code> because I found the implementation elegant and a good example of how to make use of R's functional and vectorized features. I didn't know that <code>as.integer</code> knew how to do that. It is documented, of course, but <code>help.search("hexadecimal")</code> does not give a hit there and led me astray. I received a comment on the original post that clued me in.
<pre lang="C">
## from R's as.hexmode, how to convert a hexadecimal string to an int
hex_to_int = function(h) {
xx = strsplit(tolower(h), "")[[1L]]
pos = match(xx, c(0L:9L, letters[1L:6L]))
sum((pos - 1L) * 16^(rev(seq_along(xx) - 1)))
}
</pre>
For another project, I needed to implement a base 62 conversion function to generate URL-safe strings for a URL shortener. Base 62 is what you can represent easily using [a-zA-Z0-9]. I wrote the function in Erlang and when I came across the above implementation in R, it made me wonder whether there was a cleaner approach perhaps using <code>lists:map</code> instead of recursion like:
<pre lang="C">
decode([C | T], N, Acc) ->
decode(T, N * 62, char_to_digit(C) * N + Acc);
decode([], _N, Acc) ->
Acc.
</pre>
|
Shell
|
UTF-8
| 1,589
| 3.78125
| 4
|
[] |
no_license
|
#!/bin/sh
#
# mfscgiserv MooseFS CGI monitor service
#
# chkconfig: 345 93 07
#
# description: MooseFS CGI server
#
# processname: mfscgiserv
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
if is_yes "${NETWORKING}"; then
if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
msg_network_down "mfscgiserv"
exit 1
fi
else
exit 0
fi
MFSCGISERV_USER=nobody
# Source initialization configuration.
[ -f /etc/sysconfig/mfscgiserv ] && . /etc/sysconfig/mfscgiserv
start () {
if [ -f /var/lock/subsys/mfscgiserv ]; then
msg_already_running "mfscgiserv"
return
fi
msg_starting "mfscgiserv"
daemon --user $MFSCGISERV_USER /usr/sbin/mfscgiserv start >/dev/null 2>&1
RETVAL=$?
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/mfscgiserv
}
stop () {
if [ ! -f /var/lock/subsys/mfscgiserv ]; then
msg_not_running "mfscgiserv"
return
fi
msg_stopping "mfscgiserv"
/usr/sbin/mfscgiserv stop >/dev/null 2>&1 && ok || killproc mfscgiserv >/dev/null 2>&1
rm -f /var/lock/subsys/mfscgiserv
}
condrestart() {
if [ ! -f /var/lock/subsys/mfscgiserv ]; then
msg_not_running "mfscgiserv"
RETVAL=$1
return
fi
stop
start
}
RETVAL=0
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
try-restart)
condrestart 0
;;
force-reload)
condrestart 7
;;
status)
status mfscgiserv
/usr/sbin/mfscgiserv test
RETVAL=$?
;;
*)
mfs_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
exit 3
esac
exit $RETVAL
|
Python
|
UTF-8
| 142
| 2.921875
| 3
|
[] |
no_license
|
'''Remove duplicates from list
'''
from collections import OrderedDict
def distinct(seq):
return list(OrderedDict.fromkeys(seq).keys())
|
TypeScript
|
UTF-8
| 851
| 2.96875
| 3
|
[] |
no_license
|
import * as t from "io-ts";
export class ValidationError extends Error {}
export type IoErrors = { [key: string]: [string, string] };
export function getIoErrors(errors: t.Errors): IoErrors {
return Object.fromEntries(
errors.map(error => [
error.context
.map(({ key }) => key)
.filter(key => key !== "")
.join("."),
[error.message || "Invalid value", `${error.value}`]
])
);
}
export function errorPairsToString(pairs: IoErrors): string {
return Object.entries(pairs)
.map(([key, [message, val]]) => `${message} for property '${key}': ${val}`)
.join("\n");
}
export class IoValidationError extends ValidationError {
public errors: IoErrors;
constructor(errors: t.Errors) {
const pairs = getIoErrors(errors);
super(errorPairsToString(pairs));
this.errors = pairs;
}
}
|
TypeScript
|
UTF-8
| 1,150
| 2.546875
| 3
|
[] |
no_license
|
import { Controller, Body, Delete, Param, Put, Get, Post } from '@nestjs/common';
import { OAuthLogin } from '../auth/decorators/oAuthLogin.decorator';
import { InputTag } from './interfaces/tag.dto';
import { TagService } from './tag.service';
@Controller('tags')
export class TagController {
constructor(public readonly service: TagService) {}
@Post()
createOne(@Body() inputTag: InputTag, @OAuthLogin() oAuthLogin: string) {
return this.service.createTag({
code: inputTag.code,
description: inputTag.description,
color: inputTag.color,
oAuthLogin,
});
}
@Get()
getAuthenticatedTags(@OAuthLogin() oAuthLogin: string) {
return this.service.getByLogin(oAuthLogin);
}
@Delete(':id/delete')
async deleteTagById(@Param('id') id: string, @OAuthLogin() oAuthLogin: string) {
const idNumber = Number(id);
return this.service.deleteTagById(idNumber, oAuthLogin);
}
@Put(':id/update')
async updateById(
@Param('id') id: string,
@Body() inputTag: InputTag,
@OAuthLogin() oAuthLogin: string,
) {
return this.service.updateById(inputTag, Number(id), oAuthLogin);
}
}
|
C
|
UTF-8
| 348
| 3.3125
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<string.h>
main()
{
char b[100];
int i;
printf("\n enter the string:");
gets(b);
for(i=0;i<=strlen(b);i++)
{
if((b[i]=='a')||(b[i]=='e')||(b[i]=='i')||(b[i]=='o')||(b[i]=='u')||(b[i]=='A')||(b[i]=='E')||(b[i]=='I')||(b[i]=='O')||(b[i]=='U'))
{
printf("\n yes");
}
else
{
printf("\n no");
}
}
return 0;
}
|
C++
|
UTF-8
| 382
| 4.03125
| 4
|
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
template <typename T, typename P>
void print_bigger(T a, P b) {
sizeof a > sizeof b ? cout << a : cout << b;
}
int main() {
//Create a function template that takes 2 different typenames, and prints out
//which one is stored in more bytes from then
int x = 1;
char y = 'a';
print_bigger(x, y);
return 0;
}
|
Markdown
|
UTF-8
| 801
| 2.84375
| 3
|
[] |
no_license
|
# Charset Auto Select
Simple extension to reopen files in the correct charset
(sad that I need to build this)
## How it works:
The idea is to change de vscode settings file with the correct encoding,
and then reopens de file with the charset output from
```
file -bi ${filename} | awk '{print toupper($0)}' | cut -d'=' -f2
```
## How the logic works
Simple, if there is a known output, utf-8 or iso-8859-1 the extension changes
the settings file with the matching output.
But,
IF it finds a ASCII/US-ACII charset (may happen due to creating on windows or ssh)
**THEN** it will check for a root project file **.ci-charset-exclude**
**IF** this file exists, assume *ALL FILES, EXCEPT BY ONES IN THE ci-charset-exclude FILE* are iso-8859-1
**ELSE** it *assumes that ALL PROJECT FILES* are utf8
|
Python
|
UTF-8
| 563
| 2.890625
| 3
|
[] |
no_license
|
# Header
"""
Programme pour jeu du Pendu
Réalisé par Adrien Corsetti et Quentin Melero le 01/12/2020
Fini
"""
# Importation des bibliothèques nécessaires
from Fonction import jeu_du_pendu, mot_aleatoire
# Fonction principale
score_max = 0 # Initialisation du score maximum de l'utilisateur qui n'a pas encore joué
mon_fichier = open("mots.txt",'r') # On ouvre le fichier mots.txt
mots_pendu = mon_fichier.readlines() # Liste des mots proposés au joueur
mon_fichier.close() # On ferme le fichier mots.txt
jeu_du_pendu(mots_pendu,score_max) # Une partie commence
|
Rust
|
UTF-8
| 1,269
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use ansi_term::Colour::*;
use toml::{map::Map, Value};
use crate::internal::handlers::utils::{exec_on_home, git_clone, is_dir, is_empty, CloneArgs};
pub fn init() -> bool {
let dot_monkey: &Path = Path::new(".monkey");
let base_path: PathBuf = exec_on_home(dot_monkey).unwrap();
let dir_exists = is_dir(base_path.as_path());
if dir_exists && !is_empty(base_path.as_path()) {
return false;
} else if dir_exists && is_empty(base_path.as_path()) {
}
true
}
fn scaffold(base_path: &Path) -> Result<bool, &'static str> {
// Create config file
let base_config = Map::new();
// Get the repo url
let mut buffer = String::new();
io::stdin().read_line(&mut buffer).unwrap();
let repo_url = match buffer.trim_end() {
"" => panic!(Red.paint("Error! No repo provided!")),
url => url,
};
println!("{}", Green.paint("Cloning github repository"));
let clone_args = CloneArgs {
url: repo_url.to_owned(),
path: base_path.to_str().unwrap().to_owned(),
};
match git_clone(&clone_args) {
Ok(()) => println!("{}", Green.paint("Cloned successfully")),
Err(e) => panic!(e),
}
Ok(true)
}
|
Java
|
UTF-8
| 325
| 2.578125
| 3
|
[] |
no_license
|
package javatuning.ch3.teststr.split.junit;
import org.junit.Test;
public class StringSplitFunctionTest {
@Test
public void testSplit() {
String str = "a;b,c:d";
String re[] = str.split("[;|,|:]");
for (String s : re) {
System.out.println(s);
}
}
}
|
Java
|
UTF-8
| 32,776
| 1.945313
| 2
|
[] |
no_license
|
package edu.missouri.chenglab.ClusterTAD;
import java.awt.FlowLayout;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.lang.model.element.Element;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import org.jmol.api.JmolViewer;
import weka.clusterers.SimpleKMeans;
import weka.core.Attribute;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.SparseInstance;
import weka.core.converters.CSVLoader;
import edu.missouri.chenglab.ClusterTAD.Parameter;
public class ClusterTAD{
public static int nRegion; // number of region
public static List<Double> list ;
public static String name = "30x30_data";//nij19" ;//"30x30_data";//nij.chr20
public static String inputfile = null; // input file
public static String outpath = null ;
public static String outputname = null ;
public static int ismatrix = 1;
public static int startloc = 0;
public static String chromosome = null; // specify the Chromosome number
JmolViewer viewer;
public static String Outputpath;
public static String Clusterpath = "Clusters/";
public static String ClusterFolder;
public static String TADFolder;
static BufferedWriter log_outputWriter = null;
public static ArrayList <Integer> ZeroRows= null;
static int min_TAD_size = 120000; //120kb
static int max_TAD_size = 800000 ; //800KB
public static int [][] Best_TAD = null;
public static double Best_Qscore = -Integer.MAX_VALUE;
public static int Best_K = 0;
public static String Bestname = null;;
public static int Resolution = 40000; // 1000 = 1KB
public static double [][] Feat = new double[nRegion][];
public static int status = 0;
public static double [][] RealData = null;
public static String reclustername = null;
public static String TADfile = null;
public static boolean global_isStopRunning = false;
// creates progress bar
final static JProgressBar pb = new JProgressBar();
final static int MAX = 150;
final static JFrame frame = new JFrame("Processing data..... Please wait");
static int current;
static int limit;
public static List<Double> Quality = new ArrayList<Double>();;
/**
* Read matrix from file
* @param Filename
* @return
* @throws FileNotFoundException
*/
public static double [][] readFile(String Filename, String sep) throws FileNotFoundException{
// pre-read in the number of rows/columns
int rows = 0;
int cols = 0;
try {
Scanner input = new Scanner (new File( Filename));
while(input.hasNextLine())
{ String [] line = null;
String rowdata = input.nextLine();
rowdata = rowdata.trim();
//System.out.println(rowdata);
line = rowdata.split(sep);
//System.out.println(String.format("col = %d", line.length));
++rows;
cols = line.length;
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(String.format("Number of row/col = %d", rows));
// read in the data
double [][] a = new double[rows][cols];
try {
int linesCounter = 0;
Scanner input = new Scanner (new File( Filename));
while(input.hasNextLine())
{
String [] line = null;
String rowdata = input.nextLine();
line = rowdata.split(sep);
for (int k = 0; k < cols; k++) {
a[linesCounter][k] = Double.parseDouble(line[k]);
}
linesCounter++;
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
nRegion = rows;
return a;
}
/**
* Return the data for a row
* @param mat
* @param row
* @param lencol
* @return
*/
public static void rowdata(double [][]mat, int row, int lencol ){
for (int j = 0; j < nRegion ; j++){
list.add( mat[row][j]);
}
}
/**
* Return the data for a col
* @param mat
* @param col
* @param lencol
*/
public static void coldata(double [][]mat, int col, int lencol){
for (int j = 0; j < nRegion ; j++){
list.add(mat[j][col]);
}
}
/**
* Create New dataset to use for Clustering
* @param mat
* @return
*/
public static double [][] CreateNewData(double [][]mat){
FindZeroRows(mat); //Add zero rows to list
System.out.println(String.format("The number of Zero Rows = %d ", ZeroRows.size()));
//find the size of ZeroRows
int size_Zero = ZeroRows.size();
int nrows = nRegion-size_Zero;
int ncols = nRegion + mat[0].length; // not necessarily 2*nRegion
list = new ArrayList<Double>();
int index = 0;
double [][] Feature = new double[nrows][ncols];
for (int diag = 0; diag < nRegion; diag++){
//check if arraylist contains index, if yes continue, otherwise create dataset
if (ZeroRows.contains(diag)) {
continue;
}else {
ClusterTAD.rowdata(mat, diag,ncols);
ClusterTAD.coldata(mat, diag,ncols);
for (int col_d = 0; col_d< ncols; col_d++){
Feature[index][col_d] = list.get(col_d);
}
index++;
list.clear();
}
}
return Feature;
}
/**
* Elbow method determine the number of clusters
* @param len
* @return
* @throws IOException
*/
public static int RoughEstimate(int len) throws IOException{
double K = Math.sqrt(len/2);
int k_opt = (int) Math.round(K);
System.out.println(String.format("Recommended Number of Cluster (K) = %d \n",k_opt));
log_outputWriter.write(String.format("Recommended Number of Cluster (K) = %d\n",k_opt));
return k_opt;
}
/**
* Perform kmeans clustering using weka-kmeans algorithm
* @param data
* @return
* @throws Exception
*/
public static int [] ClusteringAlgorithm(double[][]data, int ncluster) throws Exception {
int numDimensions = data.length;
int numInstances = data[0].length;
ArrayList<Attribute> atts = new ArrayList<Attribute>();
List<Instance> instances = new ArrayList<Instance>();
for(int dim = 0; dim < numDimensions; dim++)
{
Attribute current = new Attribute("Attribute" + dim, dim);
if(dim == 0)
{
for(int obj = 0; obj < numInstances; obj++)
{
instances.add(new SparseInstance(numDimensions));
}
}
for(int obj = 0; obj < numInstances; obj++)
{
instances.get(obj).setValue(current, data[dim][obj]);
}
atts.add(current);
if (Parameter.stoprunning) {
break;
}
}
Instances newDataset = new Instances("Dataset", atts, instances.size());
for(Instance inst : instances)
newDataset.add(inst);
SimpleKMeans kmeans = new SimpleKMeans();
kmeans.setSeed(10);
//important parameter to set: preserver order, number of cluster.
kmeans.setPreserveInstancesOrder(true);
try {
kmeans.setNumClusters(ncluster);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
kmeans.buildClusterer(newDataset);
// This array returns the cluster number (starting with 0) for each instance
// The array has as many elements as the number of instances
int[] assignments = kmeans.getAssignments();
int i=0;
/*for(int clusterNum : assignments) {
System.out.printf("Instance %d -> Cluster %d \n", i, clusterNum);
i++;
}*/
return assignments;
}
/**
* Get SumRow to Know if it contains Data or not
*
* @param matrix
* @param row
* @return
*/
public static double sumRow(double[][] matrix, int row)
{
double sum = 0;
int colSize = matrix[row].length;
for(int j = 0; j < colSize; j++){
sum += matrix[row][j];
}
return sum;
}
/**
* Find the Zero Rows from the Data
* @param data
*/
public static void FindZeroRows(double [][]data) {
ZeroRows = new ArrayList<Integer>();
int numDimensions = data.length;
int count;
for(int dim = 0; dim < numDimensions; dim++)
{
double sum = sumRow(data, dim);
if (sum == 0) {
ZeroRows.add(dim);
}
}
}
/**
* perform clustering on dataset range
* @param data
* @param minK
* @param maxK
* @return
* @throws Exception
*/
public static int[][] performclustering(double [][]data, int minK, int maxK, int row) throws Exception {
//Determine the best K in the range
int len = maxK - minK + 1;
int ncluster;
//Create a multidimensional array to store clusters
int [][] Clusters = new int[row][len];
int [] Cluster_assign = null;
ncluster = minK;
for (int i=0;i < len;i++) {
System.out.println(String.format("kmeans_Clustering :: K = %d .......", ncluster));
//========Perform Kmeans Clustering using Current K====================
if (Parameter.stoprunning) {
break; }
Cluster_assign = ClusteringAlgorithm(data,ncluster);
int h= 0; int k= 0;
while (h<row)
{
//check if arraylist contains index, if yes value equals zero, otherwise assign cluster value
if (ZeroRows.contains(h)) {
Clusters[h][i] =0;
}else {
Clusters[h][i] = Cluster_assign[k];
k++;
}
h++;
}
ncluster = ncluster + 1;
}
return Clusters;
}
/**
* EXtract the TAD from Clusters defined for the dataset
* @param Cluster
* @return
* @throws IOException
*/
public static int [][] ExtractTAD(int [] Cluster) throws IOException {
int count = 1;
int start = 0;
int len = Cluster.length;
ArrayList <Integer>Border = new ArrayList<Integer>();
System.out.println(String.format("Identify the TADs"));
for (int i=1; i<len;i++) {
if (Cluster[i]!=Cluster[start]) {
Border.add(start);
Border.add(i-1);
start = i;
count = count + 1;
}
}
Border.add(start); Border.add(len-1);
int nTAD = Border.size()/2;
//convert array list to array
Object[] objects = Border.toArray();
Integer [] border = new Integer[objects.length];
System.arraycopy(objects,0, border, 0, objects.length);
Border.clear();
//==========================================================
// Select the TADs with size > 3 from those classified above
//===========================================================
for (int i=0; i<border.length ;i+=2) {
int current =border[i];
int next = border[i+1];
int size = next - current + 1;
size = size * Resolution;
if (size > min_TAD_size) {
Border.add(current); //TAD start
Border.add(next); //TAD end
}
}
// Copy TAD to a 2D array
nTAD = Border.size()/2;
//convert array list to array
objects = Border.toArray();
ArrayList <Integer>TADlist = new ArrayList<Integer>();
for (int i=0; i<Border.size() ;i+=2) {
int identify_TAD = (int) objects[i+1];
//=========================================================
//Find the gaps classified as domain
//=========================================================
if (!ZeroRows.contains(identify_TAD)) {
TADlist.add((int) objects[i]);
TADlist.add((int) objects[i+1]);
}
}
nTAD = TADlist.size()/2;
//convert array list to array
objects = TADlist.toArray();
int [][] TAD = new int[nTAD][2]; // [start end identifier]
int ind= 0;
for (int i=0; i<TADlist.size() ;i+=2) {
TAD[ind][0] = (int) objects[i] ;
TAD[ind][1] = (int) objects[i+1] ;
int out1 = TAD[ind][0]* Resolution; //multiply by Resolution here
int out2 = TAD[ind][1] * Resolution;
System.out.println((String.format("%d %d ",out1 ,out2))); //Recognized as domain = 1
log_outputWriter.write((String.format("%d %d \n",out1 ,out2))); //Recognized as domain = 1
ind++;
}
return TAD;
}
/**
* Returns the Intra Quality of Domains
* @param dS - domain start
* @param dE - domain end
* @param Data - Input Data
* @return
*/
public static double IntraQuality(int dS,int dE, double[][] Data) {
double intra = 0;
double sum = 0;
int count = 0;
for (int i=dS; i<dE+1;i++) {
for (int j=i+1; j<dE+1;j++) {
count = count +1;
sum = sum + Data[i][j];
}
}
// compute intra
if (sum > 0 && count > 0) {
intra = sum/count;
}
else {
intra = 0;
}
return intra;
}
/**
* Returns the Inter Quality of Domains
* @param dS1
* @param dE1
* @param dS2
* @param dE2
* @param Data
* @return
*/
public static double [] InterQuality(int dS1,int dE1, int dS2,int dE2,double[][] Data) {
double [] output = new double[2];
double sum = 0;
int count = 0;
int incr = 0;
for (int i=dS1; i<=dS2-1;i++) {
incr = incr + 1;
int c= 0;
for (int j=dE1+1; j<=dE2;j++) {
c = c + 1;
count = count +1;
sum = sum + Data[i][j];
if(c==incr) {
break;
}
}
}
output[0] = sum; output[1] = count;
return output;
}
/**
* Determines the Quality of TAD set for one K value
* @param TAD
* @param Data
* @return
*/
public static double TAD_QA(int [][]TAD, double [][] Data) {
int TAD_len = TAD.length;
int domain1_start; int domain1_end,domain2_start; int domain2_end;
double [] outinter1 = new double[2];
double [] outinter2 = new double[2];
double avg = 0;
double Sum = 0;
for (int j=0; j<TAD_len;j++) {
/**
* ===============================================================
* For each Domain find intra-TD and inter-TD
* Intra(i) denote the average of contact frequencies between bins within the same TD i
* Inter(i, j) denote the average of contact frequencies between a bin in TD i and a bin in adjacent TD j, where |i�j | = 1
* ===============================================================
*/
// Intra
domain1_start = TAD[j][0];
domain1_end = TAD[j][1];
double intra = IntraQuality(domain1_start,domain1_end, Data) ;
double inter = 0;
// Inter
if (j==0) {
// Adjacent td is just the next one
domain2_start = TAD[j+1][0];
domain2_end = TAD[j+1][1];
outinter1 = InterQuality( domain1_start,domain1_end,domain2_start,domain2_end,Data) ;
inter = outinter1[0]/outinter1[1];
}
else if(j > 0 && j < TAD_len - 1) {
//Adjacent td includes prev and next
domain2_start = TAD[j-1][0];
domain2_end = TAD[j-1][1];
outinter1 = InterQuality( domain2_start,domain2_end,domain1_start,domain1_end,Data) ;
domain2_start = TAD[j+1][0];
domain2_end = TAD[j+1][1];
outinter2 = InterQuality( domain1_start,domain1_end,domain2_start,domain2_end,Data) ;
inter = (outinter1[0] + outinter2[0]) / (outinter1[1] + outinter2[1]);
}
else if (j==TAD_len - 1 ) {
// Adjacent td id just the prev one
domain2_start = TAD[j-1][0];
domain2_end = TAD[j-1][1];
outinter1 = InterQuality(domain2_start,domain2_end, domain1_start,domain1_end,Data) ;
inter = outinter1[0]/outinter1[1];
}
Sum += (intra - inter);
}
avg = Sum/TAD_len;
System.out.println(String.format("The Quality Score = %f", avg));
return avg;
}
/**
* Extract the TAD, Find the Quality and Send to File
* @param Clusters
* @param minK
* @param maxK
* @throws Exception
*/
public static void ClusterTAD_algorithm(int[][] Clusters, int minK, int maxK, double[][] Data) throws Exception {
int dim = Clusters.length;
int len = maxK - minK + 1; //Number of clusters
int [][] TAD =null;
double Qscore;
int [] Cluster = new int[dim];
int K = minK;
String namest= "";
TADwriter wt = new TADwriter();
TADFolder = Outputpath + "TADs/";
wt.make_folder(TADFolder ); //make folder
System.out.println("================================================");
System.out.println(String.format("TAD Identification and Quality Assessment"));
System.out.println("================================================");
for (int i=0; i<len;i++) {
System.out.print(String.format("k = %d ->", K));
log_outputWriter.write(String.format("k = %d ->", K));
for (int h=0; h<dim ;h++) {
Cluster[h] = Clusters[h][i];
}
// Order Clustering numbering based on index
Cluster = Order_ClusterNum(Cluster); // return a ordered label
//-----------------------------------------------------------
// Extract TAD based on the Order defined
log_outputWriter.write("TAD for Clustering Algorithm\n");
TAD = ExtractTAD(Cluster);
System.out.println(String.format("The Number of TAD = %d", TAD.length));
//-----------------------------------------------------------
// Write TAD identified to file
String TADfile="";
if (status==1) {
namest = reclustername ;
}
TADfile =TADFolder + "TAD_" + name + "_K="+ namest+String.valueOf(K) +".bed"; //file to hold TAD written to file
wt.delete_file(TADfile);
wt.writeTAD(TADfile,TAD,chromosome); //write matrix to file
//-----------------------------------------------------------
//Find the TAD Quality
Qscore = TAD_QA(TAD,Data);
Quality.add(Qscore);
if ( Qscore > Best_Qscore) {
Best_Qscore = Qscore; // current best Qscore
//Note the TADs identifies by Current
Best_TAD = twoDimensionalArrayClone(TAD);
Best_K = K;
Bestname="TAD_" + name + "_K="+ namest+String.valueOf(K) +".bed";
}
System.out.println("-----------------------------------------------------");
K++;
}
}
/**
* create SubData from Big Dataset
* @param array
* @return
*/
public static double [][] createSubData(int [] array){
int nrow = array.length;
int ncols = 2*nRegion;
double [][] Data = new double[nrow][ncols];
for (int i=0; i<nrow;i++) {
int ind = array[i];
Data[i] = Feat[ind];
}
return Data;
}
/**
* First Step for re-Clustering operation, check Data set dimension
* @param Cluster
* @param len
* @param sz
* @param label
* @throws Exception
*/
public static void Recluster(int []Cluster, int len, int []sz, int []label) throws Exception {
// Select 1/2
int limit_1 = (int)(0.1*len);
for (int i = 0; i < limit_1; i++) {
int size =sz[label[i]] * Resolution;
if(size < max_TAD_size) {
System.out.println("\t RECLUSTERING not Necessary...");
System.out.println("--------------------------------------------");
break;
}
System.out.println("--------------------------------------------");
System.out.println("\t RECLUSTERING...");
System.out.println("--------------------------------------------");
System.out.println(String.format("Clustering %d ........\n",i));
//find the index of the element and
int [] array = new int[sz[label[i]]];
int ind = 0;
for (int j=0; j<Cluster.length;j++) {
if (Cluster[j]==label[i]) {
array[ind] = j;
ind++;
}
}
//Find row in big data and create a new Dataset
double [][] Data = null;
Data = createSubData(array);
// Re-cluster Data
Reclustering( Cluster, Data, array);
}
}
/**
* Order the Cluster Assignment based on index
* @param Cluster
* @return
*/
public static int [] Order_ClusterNum(int []Cluster) {
int len = Cluster.length;
int [] New_Cluster = new int[len];
int i = 0;
int count = 0;
New_Cluster[i] =count;
for (i=1; i<len;i++) {
if (Cluster[i-1]==Cluster[i]) {
count = count + 0;}
else {
count = count + 1;
}
New_Cluster[i] = count;
}
return New_Cluster;
}
/**
* Perform Re-clustering of Cluster Subdata
* @param Cluster
* @param Data
* @param array
* @throws Exception
*/
public static void Reclustering(int [] Cluster, double[][]Data, int [] array) throws Exception {
status = 1; //means Reclustering done
//=========Determine an estimate of the Number of Cluster(K)==========
int size_Data = Data.length;//get the size of new data created
int K = RoughEstimate(size_Data);
//=====Create a Window for Flexibility around K, Hence K = upperLimit = K-10 and Lower Limit = K + 10
int Kmin = K-1; int Kmax=K+1;
if (Kmin < 0) { // less than zero
K = 2;
}
if (Kmax > size_Data ) { //Greater than size of the data
Kmax = size_Data - 1; }
//============Perform Clustering and Save Cluster assignment========
TADwriter wt = new TADwriter();
ClusterFolder = Outputpath + Clusterpath;
wt.make_folder(ClusterFolder); //make folder
String Clusterfile = ClusterFolder + "file_" + name + "_subcluster.txt"; //file to hold clusters
//transpose
Data = transpose(Data);
int row = Data[0].length;
int[][] labels = performclustering(Data,Kmin,Kmax,row);
wt.delete_file(Clusterfile);
wt.writeClusterMatrix(Clusterfile, labels); //write matrix to file
row = Cluster.length;
int col =labels[0].length;
int [][]Clusters = new int[row][col];
// Copy Cluster to the Length of the number of columns in Clusters
for ( int p = 0; p<col; p++) {
for (int i=0; i<row;i++) {
Clusters[i][p] = Cluster[i];
}
}
// Replace the rows of the reclustered with new defined cluster
int nrow = array.length;
for (int j=0; j<col;j++) {
int index = 0;
for (int i=0; i<nrow;i++) {
int ind = array[i];
Clusters[ind][j] = labels[index][j];
index++;
}
}
//======================== Quality Assessment==================
ClusterTAD_algorithm(Clusters,Kmin,Kmax,RealData);
//=============================================================
}
/**
* Transpose to genearate Dataset that can be clustered
* @param matrix
* @return
*/
public static double[][]transpose(double [][] matrix){
int m = matrix.length;
int n = matrix[0].length;
double[][] trasposedMatrix = new double[n][m];
for(int x = 0; x < n; x++)
{
for(int y = 0; y < m; y++)
{
trasposedMatrix[x][y] = matrix[y][x];
}
}
return trasposedMatrix;
}
/**
* Perform cluster TAD Iteration- Limit is Iteration 2
* @param Clusters
* @param minK
* @param maxK
* @throws Exception
*/
public static void ClusterTAD_Iteration(int[][] Clusters,int minK, int maxK) throws Exception {
//Find the TAD from the result
int dim = Clusters.length;
int size_Zero = ZeroRows.size();
int nrows = nRegion-size_Zero;
int [] Cluster = new int[nrows];
int len = maxK - minK + 1; //Number of clusters
ArrayList <Integer>cluster_size = new ArrayList<Integer>();
//--------------------------------------------------
// Update Labels - Remove the zerosRows
for (int i=0; i<len;i++) {
reclustername = String.valueOf(minK+i) + "_RECLUSTER_K=";
int index = 0;
for (int ind = 0; ind < nrows; ind++){
//check if arraylist contains index, if yes continue, otherwise create dataset
Cluster[ind] = Clusters[ind][i];
}
//---------------------------------------------------
// Order Clustering numbering based on index
Cluster = Order_ClusterNum(Cluster); // return a ordered label
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(Cluster).boxed().toArray(Integer[]::new));
// System.out.println(String.format("list size = %d",list.size()));
//Get the size of each cluster
int max = Arrays.stream(Cluster).max().getAsInt();
int min= Arrays.stream(Cluster).min().getAsInt();
// System.out.println(String.format("The Minimum label = %d and The Maximum label = %d ", min,max));
int sz = max-min + 1;
int [] freq = new int[sz];
int ind = 0;
for (int k=min;k<=max;k++) {
int occurence = Collections.frequency(list, k);
//System.out.println(String.format("%d %d",k,occurence));
freq[ind]= occurence;
ind++;
}
//---------------------------------------------------
// Rank the clusters based on the size, get index
int[] sortedlabel = IntStream.range(0, freq.length)
.boxed().sorted((x, y) -> freq[x] - freq[y])
.mapToInt(ele -> ele).toArray();
// Reverse the content, to get in descending order
for (int k = 0; k < sortedlabel.length/2; k++) {
int temp = sortedlabel[k];
sortedlabel[k] = sortedlabel[sortedlabel.length-(1+k)];
sortedlabel[sortedlabel.length-(1+k)] = temp;
}
// System.out.println(String.format("sorted list size %d", sortedlabel.length));
//------------------------------------------------------
Recluster(Cluster, sortedlabel.length, freq, sortedlabel) ;
}
}
/**
* Clone 2-Dimensional Array
* @param a
* @return
*/
public static int[][] twoDimensionalArrayClone(int [][] a) {
int[][] b = new int[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = a[i].clone();
}
return b;
}
/**
* Constructor for clusterTAD
* @param args
* @param Viewer
* @throws Exception
*/
public ClusterTAD(String[] args ) throws Exception{
// ==========PARAMETERS==================
inputfile = args[0];
outpath = args[1];
Resolution = Integer.parseInt(args[2]);
ismatrix = Integer.parseInt(args[3]);
startloc = Integer.parseInt(args[4]);
chromosome = args[5];
}
/**
*
* @param args
* @return
*/
public String Perform_operation(){
String msg = null;
System.out.println("Welcome to TAD identification from contact Matrix.");
System.out.println("INSTRUCTION:\n (1)Input is a Normalized Matrix. \n"
+ " (2) Specify the Data sperator for input data");
String[] tmp = inputfile.split("[\\/ \\. \\\\]");
if (inputfile.contains(".")){
name = tmp[tmp.length - 2];
}
else{
name = tmp[tmp.length - 1];
}
String namest = "";
String path = "data/";
JProgressBar progress = new JProgressBar(0, 100);
// Overlay a string showing the percentage done
progress.setStringPainted(true);
//==========================================================================
// Split process into stages and monitor with progress bar
// ============================================================================
//STAGE 1: data loading
try {
System.out.println("Reading Data from File......");
String seperator = "\\s+"; // specify the data seperator for dataset
System.out.println(String.format("Input = %s", inputfile));
try {
RealData= Parameter.readFile(inputfile,seperator,ismatrix);
System.out.println("File read successfully!!!\n");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//===================================================================
if (RealData!=null) {
//===================================================================
//STAGE 2: New data creation
System.out.println("File read successfully!!!\n");
//==========Create new Feature Data================
nRegion = RealData.length;
Feat = ClusterTAD.CreateNewData(RealData);
System.out.println("Feature Dataset Created Successfully!!!\n");
String filename = "Readme.txt";
Outputpath = outpath + "/Output/" ;
TADwriter wt = new TADwriter();
wt.make_folder(Outputpath);
log_outputWriter = new BufferedWriter(new FileWriter( Outputpath + filename));
//===================================================================
//===================================================================
//STAGE 3: Estimate number of Clusters
//=========Determine an estimate of the Number of Cluster(K)==========
int size_Feat = Feat.length;//get the size of new data created
int K = RoughEstimate(size_Feat);
//=====Create a Window for Flexibility around K, Hence K = upperLimit = K-10 and Lower Limit = K + 10
int Kmin = K-1; int Kmax=K+1;
if (Kmin < 0) { // less than zero
Kmin = 2; }
if (Kmax > size_Feat ) { //Greater than size of the data
Kmax = size_Feat - 1; }
//===================================================================
//===================================================================
//STAGE 4: Perform Clustering and Save
//============Perform Clustering and Save Cluster assignment========
ClusterFolder = Outputpath + Clusterpath;
wt.make_folder(ClusterFolder); //make folder
String Clusterfile = ClusterFolder + "file_" + name + "_cluster.txt"; //file to hold clusters
int row = Feat.length;
int[][] labels = performclustering(Feat,Kmin,Kmax,row);
wt.delete_file(Clusterfile);
wt.writeClusterMatrix(Clusterfile, labels); //write matrix to file
//============================================================
ClusterTAD_algorithm(labels,Kmin,Kmax,RealData); //Return this TAD, and find out if there are more interesting TADs
//=============================================================
// Perform Re-clustering
//----------------------------------------------------------------------
//STAGE 5: Extract Re-clustering and Extract
ClusterTAD_Iteration(labels,Kmin,Kmax); //Only enabled for
//======================Quality Assessment=======================
System.out.println(String.format("Best Quality Score for TAD identified at K = %d ",Best_K));
System.out.println(String.format("Quality score of best TAD identified = %f ",Best_Qscore));
System.out.println("TAD identified written to file");
TADfile =TADFolder + "Best" + Bestname ; //file to hold TAD written to file
wt.delete_file(TADfile);
wt.writeTAD(TADfile,Best_TAD,chromosome); //write matrix to file
System.out.println("=========== Quality Assessment Completed =========");
//write Quality score to file
String Qscorefile =TADFolder + name + "_TAD_QualityScore_List.txt"; //file to hold Quality score of TAD written to file
wt.delete_file( Qscorefile);
wt.writeList(Qscorefile, Quality);
JOptionPane.showMessageDialog(null, "<html><b>Successfully Completed</b>. Check the output directory for output files. <br /> The best TAD identified is saved in the <i>TADs</i> directory with Prefix = <b>BestTAD </b> </html>","Information",JOptionPane.INFORMATION_MESSAGE);
msg = "TAD extraction completed";
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
msg = "An error occured. File Not Found ";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
msg = "TAD extraction failed";
}
try {
log_outputWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
msg = "An error occured. Failed to write file to output directory";
e.printStackTrace();
}
try {
log_outputWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
msg = "An error occured. Failed to write file to output directory";
e.printStackTrace();
}
return msg;
}
}
|
Java
|
UTF-8
| 2,143
| 1.679688
| 2
|
[] |
no_license
|
package zte.net.ecsord.params.zb.vo.orderattr;
import java.io.Serializable;
import com.ztesoft.net.annotation.ZteSoftCommentAnnotationParam;
public class Resources implements Serializable{
@ZteSoftCommentAnnotationParam(name="附加产品编码",type="String",isNecessary="Y",desc="SubProCode:附加产品编码")
private String ResourcesBrand;
@ZteSoftCommentAnnotationParam(name="附加产品编码",type="String",isNecessary="Y",desc="SubProCode:附加产品编码")
private String ResourcesModel;
@ZteSoftCommentAnnotationParam(name="机型编码",type="String",isNecessary="Y",desc="SubProCode:附加产品编码")
private String ResourcesTypeId;
@ZteSoftCommentAnnotationParam(name="附加产品编码",type="String",isNecessary="Y",desc="SubProCode:附加产品编码")
private String ResourcesColor;
@ZteSoftCommentAnnotationParam(name="附加产品编码",type="String",isNecessary="Y",desc="SubProCode:附加产品编码")
private String ResourcesCode;
@ZteSoftCommentAnnotationParam(name="附加产品编码",type="String",isNecessary="Y",desc="SubProCode:附加产品编码")
private String ResourcesFittings;
public String getResourcesBrand() {
return ResourcesBrand;
}
public void setResourcesBrand(String resourcesBrand) {
ResourcesBrand = resourcesBrand;
}
public String getResourcesModel() {
return ResourcesModel;
}
public void setResourcesModel(String resourcesModel) {
ResourcesModel = resourcesModel;
}
public String getResourcesTypeId() {
return ResourcesTypeId;
}
public void setResourcesTypeId(String resourcesTypeId) {
ResourcesTypeId = resourcesTypeId;
}
public String getResourcesColor() {
return ResourcesColor;
}
public void setResourcesColor(String resourcesColor) {
ResourcesColor = resourcesColor;
}
public String getResourcesCode() {
return ResourcesCode;
}
public void setResourcesCode(String resourcesCode) {
ResourcesCode = resourcesCode;
}
public String getResourcesFittings() {
return ResourcesFittings;
}
public void setResourcesFittings(String resourcesFittings) {
ResourcesFittings = resourcesFittings;
}
}
|
C#
|
UTF-8
| 963
| 3.140625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace loginscreen
{
public class Hash
{
public string CriptografarSenha(string senha)
{
var valorCodificado = Encoding.UTF8.GetBytes(senha);
var senhaCriptografada = MD5.Create().ComputeHash(valorCodificado);
StringBuilder stringBuilder = new StringBuilder();
for (int count = 0; count < senhaCriptografada.Length; count++)
{
stringBuilder.Append(senhaCriptografada[count].ToString("X2"));
}
return stringBuilder.ToString();
}
public bool CompararSenha(string senhaDigitada, string SenhaCadastrada)
{
var senhaDigitadaCripto = CriptografarSenha(senhaDigitada);
return senhaDigitadaCripto == SenhaCadastrada;
}
}
}
|
JavaScript
|
UTF-8
| 4,988
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
var fs = require('fs');
var util = require('util');
var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
assert = require('assert');
// Connection url
var url = 'mongodb://localhost:27017/BlackHawk';
// Inserts many documents
var insertEvent = function(info, db, callback) {
// Get documents collection
var collection = db.collection('events');
// Insert some documents
collection.insertMany([
info
], function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
assert.equal(1, result.ops.length);
console.log("Inserted 1 documents into the collection");
callback(result);
});
};
/* Select all events */
var findEvents = function(db, callback) {
// Get the documents collection
var collection = db.collection('events');
// Find all events in sorted order based on date
collection.find({}).sort({date: 1}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
};
/* Select specific event */
var filterEvents = function(condition, db, callback) {
// Get the documents collection
var collection = db.collection('events');
// Find some documents
collection.find(condition).sort({date: 1}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found specific event(s) with condition " + condition);
console.log(docs);
callback(docs);
});
};
/* Update a row with some new data */
var updateEvent = function(info, key, db, callback) {
// Get the documents collection
var collection = db.collection('event');
console.log("Updating a single event...");
// Update event where id
collection.updateOne(
{ _id : key}, // filter
{ $set: info }, // data
{ upsert: true }, // insert if event not found
function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
callback(result)
});
};
/* Delete one event based on ID */
var removeDocument = function(id, db, callback) {
// Get the documents collection
var collection = db.collection('events');
var ObjectId = require('mongodb').ObjectId;
// Delete some documents
collection.remove(
{ _id : new ObjectId(id) }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Removed the event with the field _id equal to " + id);
callback(result);
});
};
/* Delete all events */
var clearEvents = function(db, callback) {
// Get the documents collection
var collection = db.collection('events');
// Delete some documents
collection.remove({}, function(err, result) {
assert.equal(err, null);
callback(result);
});
};
/* Indexing - currently unused; implement when scaling is needed */
var indexCollection = function(db, callback) {
db.collection('events').createIndex(
{ "a": 1 },
null,
function(err, results) {
console.log(results);
callback();
});
};
/* Wrapper function to insert data externally */
var insert = function(info) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertEvent(info, db, function() {
db.close();
});
});
};
/* Wrapper function to update data externally */
var update = function(info, key) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
updateEvent(info, key, db, function() {
db.close();
});
});
};
/* Wrapper function to remove a single event */
var removeOne = function(eventID, callback) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
removeDocument(eventID, db, function(result) {
if(callback) {
callback('The event has been removed.');
}
db.close();
});
});
};
/* Wrapper function to get all data externally */
var all = function(callback) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findEvents(db, function(result) {
db.close();
if (callback){
callback(result);
}
});
});
};
/* Wrapper function returns a single document */
var filter = function(condition, callback) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
filterEvents(condition, db, function(result) {
db.close();
if (callback){
callback(result);
}
});
});
};
exports.allEvents = all;
exports.insertEvent = insert;
exports.filter = filter;
exports.updateEvent = update;
exports.removeOneEvent = removeOne;
|
C#
|
UTF-8
| 4,050
| 3.640625
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeExercise.BFS
{
class CloneGraph
{
/// <summary>
/// 133 Clone Graph
/// https://leetcode.com/problems/clone-graph/description/
///
/// Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
///
/// Nodes are labeled uniquely.
///
/// We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
/// As an example, consider the serialized graph {
/// 0,1,2#1,2#2,2}.
///
/// The graph has a total of three nodes, and therefore contains three parts as separated by #.
///
/// First node is labeled as 0.Connect node 0 to both nodes 1 and 2.
/// Second node is labeled as 1.Connect node 1 to node 2.
/// Third node is labeled as 2.Connect node 2 to node 2(itself), thus forming a self-cycle.
///
///
/// Sol:
// first copy node by bfs to dictionary<orig, new>
/// for each dic keys, find orig neighbors and assign coped neighbor to new node
///
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public UndirectedGraphNode CloneGraphSolver(UndirectedGraphNode node)
{
if (node == null)
{
return node;
}
var que = new Queue<UndirectedGraphNode>();
var lookup = new Dictionary<UndirectedGraphNode, UndirectedGraphNode>();
var visited = new HashSet<UndirectedGraphNode>();
que.Enqueue(node);
lookup.Add(node, new UndirectedGraphNode(node.label));
visited.Add(node);
while (que.Count > 0)
{
var curr = que.Dequeue();
var copy = lookup[curr];
foreach (var nb in curr.neighbors)
{
if (!visited.Contains(nb))
{
lookup.Add(nb, new UndirectedGraphNode(nb.label));
visited.Add(nb);
que.Enqueue(nb);
}
var nbCpy = lookup[nb];
copy.neighbors.Add(nbCpy);
}
}
return lookup[node];
}
public UndirectedGraphNode CloneGraphSolver_old(UndirectedGraphNode node)
{
if (node == null)
{
return null;
}
Queue<UndirectedGraphNode> queue = new Queue<UndirectedGraphNode>();
Dictionary<UndirectedGraphNode, UndirectedGraphNode> lookup = new Dictionary<UndirectedGraphNode, UndirectedGraphNode>(); // old, new
queue.Enqueue(node);
lookup.Add(node, new UndirectedGraphNode(node.label));
// BFS to iterate nodes and copy and flattern it to dictionary
// (origin_node, new_node)
while (queue.Count > 0)
{
var curr = queue.Dequeue();
foreach(UndirectedGraphNode neighbor in curr.neighbors)
{
if (!lookup.ContainsKey(neighbor))
{
// enqueue neighbor
queue.Enqueue(neighbor);
// copy of neigobor
lookup.Add(neighbor, new UndirectedGraphNode(neighbor.label));
}
}
}
// link new neighbors by old neighbors
foreach(UndirectedGraphNode n in lookup.Keys)
{
var copiedNode = lookup[n];
foreach(var neighbor in n.neighbors)
{
copiedNode.neighbors.Add(lookup[neighbor]);
}
}
return lookup[node];
}
}
}
|
TypeScript
|
UTF-8
| 399
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
export function createSimpleSelector<TSource, TResult>(
sourceReader: () => TSource,
transformer: (source: TSource) => TResult,
): () => TResult {
let source: TSource | undefined;
let result: TResult | undefined;
return () => {
const _source = sourceReader();
if (_source !== source) {
result = transformer(_source);
source = _source;
}
return result!;
};
}
|
C++
|
GB18030
| 4,285
| 2.8125
| 3
|
[] |
no_license
|
#ifndef _MAIN_CPP_
#define _MAIN_CPP_
#include "Define.h"
#include "string.h"
#include "stdio.h"
#include "windows.h"
#include "SearchEngine.h"
//ȫֱ
MapType map; //¼Ϣ
MoveType bestMove; //صз
int ourcolor; //¼ҷɫ
int posx[8] = {0,0,3,3,6,6,9,9}; //¼˸ӵλãǰ4Ǻ췽4ǰ
int posy[8] = {3,6,0,9,0,9,3,6}; //¼˸ӵλãǰ4Ǻ췽4ǰ
//int posx[8] = {8,5,4,2,0,0,1,9}; //¼˸ӵλãǰ4Ǻ췽4ǰ
//int posy[8] = {0,4,4,7,0,9,3,0}; //¼˸ӵλãǰ4Ǻ췽4ǰ
SearchEngine Engine; //
int step = 1;
FILE *engine_output;
//ʼ
void init_map()
{
int i;
memset(map,NOSTONE,sizeof(map));
for (i = 0; i<4; i++)
{
map[posx[i]][posy[i]] = RED;
map[posx[i+4]][posy[i+4]] = WHITE;
}
/*
MapType m =
{
{2,3,0,0,0,3,3,3,3,2},
{3,3,0,2,0,3,3,3,3,3},
{3,3,0,0,0,3,3,1,0,3},
{3,0,3,3,3,3,3,3,3,3},
{3,3,0,3,1,0,3,0,0,0},
{3,0,3,3,1,3,3,3,3,3},
{3,3,3,3,3,3,3,3,3,3},
{3,3,3,3,0,3,3,3,0,3},
{1,3,3,3,3,3,3,3,3,3},
{2,3,3,3,3,0,3,3,3,3},
};
for (i = 0; i<MAXSIZE; i++)
for (int j = 0; j<MAXSIZE; j++)
map[i][j] = m[i][j];
*/
}
void load_map()
{
int whitechess,redchess,i,j;
for (i = 0; i<MAXSIZE; i++)
for (j = 0; j<MAXSIZE; j++)
scanf("%d",map[i][j]);
whitechess = 4;
redchess = 0;
for (i = 0; i<MAXSIZE; i++)
for (j = 0; j<MAXSIZE; j++)
if (map[i][j] == RED)
{
posx[redchess] = i;
posy[redchess] = j;
redchess++;
}
else if (map[i][j] == WHITE)
{
posx[whitechess] = i;
posy[whitechess] = j;
whitechess++;
}
}
//ƶӸ
void movechess(MoveType nowmove)
{
for (int i = 0; i<8; i++)
if (posx[i] == nowmove.x[0] && posy[i] == nowmove.y[0])
{
posx[i] = nowmove.x[1];
posy[i] = nowmove.y[1];
}
map[nowmove.x[1]][nowmove.y[1]] = map[nowmove.x[0]][nowmove.y[0]];
map[nowmove.x[0]][nowmove.y[0]] = NOSTONE;
map[nowmove.x[2]][nowmove.y[2]] = OBSTACLE;
}
//move
void cmd_move()
{
char move[] = "move AAAAAA\n"; //߷
if (Engine.search_a_goodmove(map,ourcolor,&bestMove))
{
//ŷ¼
movechess(bestMove);
//ŷתҪ͵ַʽ
move[5] = bestMove.x[0] + 'A';
move[6] = bestMove.y[0] + 'A';
move[7] = bestMove.x[1] + 'A';
move[8] = bestMove.y[1] + 'A';
move[9] = bestMove.x[2] + 'A';
move[10] = bestMove.y[2] + 'A';
step++;
//Ϣ
printf ("%s",move);
engine_output = fopen("engint_output.txt","a");
fprintf(engine_output,"%s",move);
fclose(engine_output);
fflush(stdout);
}
}
int main()
{
char Msg[500] = {0}; //յϢ
char name[] = "name Amazon3.1\n"; //Ϣ
init_map();
while (1)
{
//ѭղƽ̨͵Ϣ
//עҪ͵ַӦ'\n'ƽ̨ŻΪһ
//Ҫfflush(stdout)ʹַƽ̨
memset(Msg,0,500);
scanf("%s",Msg);
if (strcmp(Msg,"name?") == 0)
{
//name?
printf("%s",name);
fflush(stdout);
continue;
}
if (strcmp(Msg,"stop") == 0)
{
fflush(stdout);
return 0;
}
if (strcmp(Msg,"new") == 0)
{
//new
init_map();//ʼ
scanf("%s",Msg);
if (strcmp(Msg,"white") == 0)
{
//new white
ourcolor = WHITE;
cmd_move();
continue;
}
else
{
//new red
ourcolor = RED;
continue;
}
continue;
}
if (strcmp(Msg,"move") == 0)
{
//move
scanf("%s",Msg);
if (Msg[6] == '\0')
{
//move XX\n
bestMove.x[0] = Msg[0] - 'A';
bestMove.y[0] = Msg[1] - 'A';
bestMove.x[1] = Msg[2] - 'A';
bestMove.y[1] = Msg[3] - 'A';
bestMove.x[2] = Msg[4] - 'A';
bestMove.y[2] = Msg[5] - 'A';
movechess(bestMove);
}
cmd_move();
continue;
}
if (strcmp(Msg,"load") == 0)
load_map();
}
return 0;
}
#endif
|
C#
|
UTF-8
| 2,392
| 3.4375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 11泛型和委托 11.5 例题-多播委托
* 题目:
* 1)
* 要点:
* 1)委托对象可以使用"+"运算符进行合并
* 2)"-"运算符可用于从合并委托中移除组件委托
* 3)只有相同类型的委托可被合并
* 4)调用多播委托时,方法将按照添加顺序依次调用
* 时间:2019、06、25
***************************************************/
namespace EXAMPLE11_5
{
class Program
{
static void Main(string[] args)
{
Draw d1 = new Draw() { Stuid = 1, PenColor = ConsoleColor.Yellow };//【【【【对属性赋初值
Draw d2 = new Draw() { Stuid = 2, PenColor = ConsoleColor.Red };
Draw d3 = new Draw() { Stuid = 3, PenColor = ConsoleColor.Green };
Console.WriteLine("对象调用方法形式---->");
d1.DrawPicture();
d2.DrawPicture();
d3.DrawPicture();
Console.WriteLine("单播委托形式---->");
Action action1 = new Action(d1.DrawPicture);
Action action2 = new Action(d2.DrawPicture);
Action action3 = new Action(d3.DrawPicture);
action1(); action2(); action3();//调用单播委托
Console.WriteLine("多播委托形式---->");
action1 += action2;//相同类型的委托合并到委托action1
action1 += action3;
action1();//调用多播委托
Console.WriteLine("------");
action1 -= action2;
action1();//调用多播委托
}
}
class Draw
{
public int Stuid { get; set; }
public ConsoleColor PenColor { get; set; }
public void DrawPicture()
{
Console.ForegroundColor = PenColor;
Console.WriteLine("Stuid{0} draw a cat",Stuid);
}
}
}
//对象调用方法形式---->
//Stuid1 draw a cat
//Stuid2 draw a cat
//Stuid3 draw a cat
//单播委托形式---->
//Stuid1 draw a cat
//Stuid2 draw a cat
//Stuid3 draw a cat
//多播委托形式---->
//Stuid1 draw a cat
//Stuid2 draw a cat
//Stuid3 draw a cat
//------
//Stuid1 draw a cat
//Stuid3 draw a cat
//请按任意键继续. . .
|
Python
|
UTF-8
| 504
| 2.75
| 3
|
[] |
no_license
|
# https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/submissions/
def max_roduct(root):
result = total = 0
def dfs_sum(node):
if not node: return 0
left = dfs_sum(node.left)
right = dfs_sum(node.right)
result = max(result, left * (total - left), right * (total - right))
return left + right + node.val
total = dfs_sum(root)
dfs_sum(root)
return result % (10**9+7)
|
Markdown
|
UTF-8
| 1,856
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# Exemplos AdvPL REST
Este repositório contém um conjunto de implementações de serviços REST em AdvPL
cautelosamente comentados com o objetivo de servir de referência à construção
de novas aplicações e auxiliar no aprendizado das características dessa tecnologia.
Os exemplos estão ordenados por complexidade e nomeados de acordo com suas
características funcionais.
- [Olá mundo!](./01.ola_mundo.apw) - seu primeiro webservice com apenas uma rota `GET` simples e retorno em JSON.
- [Transformar palavra](./02.transformar_palavra.apw) - webservice com duas rotas `GET` para deixar palavras em caixa alta ou baixa.
- [Campos por tabela](./03.campos_por_tabela.apw) - uma única rota `GET` que permite trazer os campos definidos na `SX3` para uma tabela existente na `SX2` recebendo o identificador do arquivo da tabela na própria URL.
- [Headers](./04.headers.apw) - demonstração de como receber e enviar headers HTTP.
- [Status](./05.status.apw) - devolvendo códigos de status HTTP.
- [Receber JSON](./06.receber_json.apw) - recebendo JSON como corpo de uma requisição via `POST`.
- [Tarefas](./07.tarefas.apw) - cadastro completo de lista de tarefas contemplando `GET`, `POST`,
`PUT` e `DELETE` com múltiplos caminhos e validações.
- [Download de arquivo](./07.download_de_arquivo.apw) - `TODO` - demonstração de como podemos forçar o download de
um arquivo do servidor e customizar suas propriedades.
- [Renderizar imagem](./08.renderizar_imagem.apw) - `TODO` - utilizando a mesma técnica do download de arquivo, permitimos
renderização de imagens através de rotas específicas.
- [Upload de imagem](./09.upload_de_imagem.apw) - `TODO` - permitimos que nosso servidor seja capaz de receber
arquivos de imagem do cliente.
- [Cookies](./10.cookies.apw) - `TODO` - utilizando cookies para gerenciar sessões dos usuários.
|
Java
|
UTF-8
| 7,320
| 2.5
| 2
|
[] |
no_license
|
package com.mmall.component;
import com.google.common.base.Strings;
import com.google.common.io.ByteStreams;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;
/**
*
*日志Filter
* @author hyc
* @since 2018-09-15
*/
@Component
@Order(2)
public class LogFilter extends GenericFilterBean {
private static final Log log = LogFactory.getLog(LogFilter.class);
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// 不理会OPTIONS请求
if (((HttpServletRequest) req).getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.toString())) {
HttpServletResponse httpServletResponse = (HttpServletResponse) res;
httpServletResponse.setStatus(200);
chain.doFilter(req, res);
return;
}
BufferedRequestWrapper request = new BufferedRequestWrapper((HttpServletRequest) req);
BufferedResponseWrapper response = new BufferedResponseWrapper((HttpServletResponse) res);
chain.doFilter(request, response);
request.log();
response.log();
}
/*
* Request日志打印类.
* <p>
* 由于body的内容存储在InputStream中,
* 故先将InputStream中的数据进行存储,
* 再进行打印.
*/
private static final class BufferedRequestWrapper extends HttpServletRequestWrapper {
private byte[] bytes;
private ByteArrayInputStream inputStream;
public BufferedRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
bytes = ByteStreams.toByteArray(request.getInputStream());
inputStream = new ByteArrayInputStream(bytes);
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public boolean isFinished() {
return inputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
throw new RuntimeException("Not implemented");
}
};
}
public void log() {
StringBuilder builder = new StringBuilder();
builder.append(this.getRemoteAddr()).append(" ")
.append(this.getMethod()).append(": ")
.append(this.getRequestURI()).append(" ");
String contentType = this.getHeader("Content-Type");
if (Strings.isNullOrEmpty(contentType)
|| "application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) {
builder.append("[");
Map<String, String[]> map = this.getParameterMap();
for (Map.Entry<String, String[]> entry : map.entrySet()) {
builder.append(entry.getKey()).append(": ")
.append(entry.getValue()[0]).append(", ");
}
if (map.size() > 0) {
builder.delete(builder.length() - 2, builder.length());
}
builder.append("]");
LogFilter.log.info(builder.toString());
} else if ("application/json".equalsIgnoreCase(contentType)) {
builder.append(new String(bytes));
LogFilter.log.info(builder.toString());
}
}
}
/*
* Response日志打印类.
* <p>
* 由于Response中的返回内容存储在OutputStream和PrintWriter中,
* 故再额外保存一份, 使得能进行日志打印.
*/
private static class BufferedResponseWrapper extends HttpServletResponseWrapper {
private final ByteArrayOutputStream bos = new ByteArrayOutputStream();
private PrintWriter writer = new PrintWriter(bos);
public BufferedResponseWrapper(HttpServletResponse response) {
super(response);
}
@Override
public ServletResponse getResponse() {
return this;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
private TeeOutputStream teeOutputStream =
new TeeOutputStream(BufferedResponseWrapper.super.getOutputStream(), bos);
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener listener) {
throw new RuntimeException("Not implemented");
}
@Override
public void write(int b) throws IOException {
teeOutputStream.write(b);
}
};
}
@Override
public PrintWriter getWriter() throws IOException {
return new TeePrintWriter(super.getWriter(), writer);
}
public void log() {
if (bos.size() > 0) {
LogFilter.log.info(new String(bos.toByteArray(), Charset.forName("UTF-8")));
} else {
LogFilter.log.info(writer.toString());
}
}
}
/*
* 类似于TeeOutputStream, 每次write都写入到两个Writer中.*/
private static class TeePrintWriter extends PrintWriter {
PrintWriter branch;
public TeePrintWriter(PrintWriter main, PrintWriter branch) {
super(main, true);
this.branch = branch;
}
public void write(char buf[], int off, int len) {
super.write(buf, off, len);
super.flush();
branch.write(buf, off, len);
branch.flush();
}
public void write(String s, int off, int len) {
super.write(s, off, len);
super.flush();
branch.write(s, off, len);
branch.flush();
}
public void write(int c) {
super.write(c);
super.flush();
branch.write(c);
branch.flush();
}
public void flush() {
super.flush();
branch.flush();
}
}
}
|
Ruby
|
UTF-8
| 6,479
| 3.140625
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: stops
#
# id :integer not null, primary key
# name :string
#
# Table name: routes
#
# num :string not null, primary key
# company :string not null, primary key
# pos :integer not null, primary key
# stop_id :integer
require_relative './sqlzoo.rb'
def num_stops
# How many stops are in the database?
execute(<<-SQL)
select count(*)
from stops
SQL
end
def craiglockhart_id
# Find the id value for the stop 'Craiglockhart'.
execute(<<-SQL)
select id from stops where name = 'Craiglockhart'
SQL
end
def lrt_stops
# Give the id and the name for the stops on the '4' 'LRT' service.
execute(<<-SQL)
select s.id, s.name
from routes r
join stops s on r.stop_id = s.id
where r.num = '4' and r.company = 'LRT'
SQL
end
def connecting_routes
# Consider the following query:
#
# SELECT
# company,
# num,
# COUNT(*)
# FROM
# routes
# WHERE
# stop_id = 149 OR stop_id = 53
# GROUP BY
# company, num
#
# The query gives the number of routes that visit either London Road
# (149) or Craiglockhart (53). Run the query and notice the two services
# that link these stops have a count of 2. Add a HAVING clause to restrict
# the output to these two routes.
execute(<<-SQL)
SELECT
company,
num,
COUNT(*)
FROM
routes
WHERE
stop_id = 149 OR stop_id = 53
GROUP BY
company, num
HAVING count(*) > 1
SQL
end
def cl_to_lr
# Consider the query:
#
# SELECT
# a.company,
# a.num,
# a.stop_id,
# b.stop_id
# FROM
# routes a
# JOIN
# routes b ON (a.company = b.company AND a.num = b.num)
# WHERE
# a.stop_id = 53
#
# Observe that b.stop_id gives all the places you can get to from
# Craiglockhart, without changing routes. Change the query so that it
# shows the services from Craiglockhart to London Road.
execute(<<-SQL)
SELECT
a.company,
a.num,
a.stop_id,
b.stop_id
FROM
routes a
JOIN
routes b ON (a.company = b.company AND a.num = b.num)
WHERE
a.stop_id = 53 and b.stop_id = 149
SQL
end
def cl_to_lr_by_name
# Consider the query:
#
# SELECT
# a.company,
# a.num,
# stopa.name,
# stopb.name
# FROM
# routes a
# JOIN
# routes b ON (a.company = b.company AND a.num = b.num)
# JOIN
# stops stopa ON (a.stop_id = stopa.id)
# JOIN
# stops stopb ON (b.stop_id = stopb.id)
# WHERE
# stopa.name = 'Craiglockhart'
#
# The query shown is similar to the previous one, however by joining two
# copies of the stops table we can refer to stops by name rather than by
# number. Change the query so that the services between 'Craiglockhart' and
# 'London Road' are shown.
execute(<<-SQL)
SELECT
ra.company,
ra.num,
sa.name,
sb.name
FROM
routes ra
JOIN
routes rb ON (ra.company = rb.company AND ra.num = rb.num)
JOIN
stops sa ON (ra.stop_id = sa.id)
JOIN
stops sb ON (rb.stop_id = sb.id)
WHERE
sa.name = 'Craiglockhart' and sb.name = 'London Road'
SQL
end
def haymarket_and_leith
# Give the company and num of the services that connect stops
# 115 and 137 ('Haymarket' and 'Leith')
execute(<<-SQL)
SELECT
distinct ra.company,
ra.num
FROM
routes ra
JOIN
routes rb ON (ra.company = rb.company AND ra.num = rb.num)
JOIN
stops sa ON (ra.stop_id = sa.id)
JOIN
stops sb ON (rb.stop_id = sb.id)
WHERE
sa.name = 'Haymarket' and sb.name = 'Leith'
SQL
end
def craiglockhart_and_tollcross
# Give the company and num of the services that connect stops
# 'Craiglockhart' and 'Tollcross'
execute(<<-SQL)
SELECT
distinct ra.company,
ra.num
FROM
routes ra
JOIN
routes rb ON (ra.company = rb.company AND ra.num = rb.num)
JOIN
stops sa ON (ra.stop_id = sa.id)
JOIN
stops sb ON (rb.stop_id = sb.id)
WHERE
sa.name = 'Craiglockhart' and sb.name = 'Tollcross'
SQL
end
def start_at_craiglockhart
# Give a distinct list of the stops that can be reached from 'Craiglockhart'
# by taking one bus, including 'Craiglockhart' itself. Include the stop name,
# as well as the company and bus no. of the relevant service.
execute(<<-SQL)
SELECT
sb.name sbname,
ra.company rac,
ra.num ran
FROM
routes ra
JOIN
routes rb ON (ra.company = rb.company AND ra.num = rb.num)
JOIN
stops sa ON (ra.stop_id = sa.id)
JOIN
stops sb ON (rb.stop_id = sb.id)
WHERE
sa.name = 'Craiglockhart'
SQL
end
def craiglockhart_to_sighthill
# Find the routes involving two buses that can go from Craiglockhart to
# Sighthill. Show the bus no. and company for the first bus, the name of the
# stop for the transfer, and the bus no. and company for the second bus.
execute(<<-SQL)
SELECT distinct
left_midpoints.first_num fnum,
left_midpoints.first_comp fcompany,
stops.name transfer,
right_midpoints.last_num lnum,
right_midpoints.last_comp lcompany
FROM (
SELECT
first_comp,
first_num,
stop_id midpoint
FROM (
SELECT
first_route.company first_comp,
first_route.num first_num
FROM
stops first_stop
JOIN
routes first_route on first_stop.id = first_route.stop_id
WHERE first_stop.name = 'Craiglockhart'
) AS first_lines
JOIN routes middle_route
ON first_lines.first_comp = middle_route.company
AND first_lines.first_num = middle_route.num
ORDER BY first_num
) AS left_midpoints
JOIN (
SELECT
last_comp,
last_num,
stop_id midpoint
FROM (
SELECT
last_route.company last_comp,
last_route.num last_num
FROM
stops last_stop
JOIN
routes last_route on last_stop.id = last_route.stop_id
WHERE last_stop.name = 'Sighthill'
) AS last_lines
JOIN routes middle_route
ON last_lines.last_comp = middle_route.company
AND last_lines.last_num = middle_route.num
ORDER BY last_num
) AS right_midpoints
ON left_midpoints.midpoint = right_midpoints.midpoint
JOIN stops ON left_midpoints.midpoint = stops.id
SQL
end
|
Python
|
UTF-8
| 438
| 2.53125
| 3
|
[] |
no_license
|
import sys
import heapq, math
from itertools import zip_longest, permutations, combinations, combinations_with_replacement
from itertools import accumulate, dropwhile, takewhile, groupby
from functools import lru_cache
from copy import deepcopy
N = int(input())
cnt = 0
ans = 1
for i in range(1, N + 1):
x = i
c = 0
while x % 2 == 0:
x //= 2
c += 1
if cnt < c:
cnt = c
ans = i
print(ans)
|
C++
|
UTF-8
| 2,643
| 2.890625
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
/************************************************************************
* Description: Test for a 28BYJ-48 stepper motor
* Developer: Uri Leal
* Board: Arduino Nano/Uno
* I/O pins: D5-D8
* Motor step sequence: 2 coils at time
*
* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
* Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
************************************************************************/
// Motor controller pins
#define IN1 5
#define IN2 6
#define IN3 7
#define IN4 8
const byte nSteps = 125; // Number of steps required to make a 90 degree turn (Aprox.), try it with different values from 0 to 4096
const byte LED = 13; // D13 pin | PORTB = PB5
const byte speed = 5; // Max. turn speed of 100Hz specified in the 28BYJ-48 datasheet, try it with different speeds around 10 - 150
int i; // Auxiliar counter
byte step; // Auxiliar step counter
// Control sequence
const byte paso [4][4] = {
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}
};
void setup()
{
// Init I/O Pins
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(LED, OUTPUT);
// Init variables
step = i = 0;
}
void loop()
{
openGate(); // Execute forward test
delay(1000);
closeGate(); // Execute backward test
// Make sure all the motor-control pins are LOW
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
// Finish the test program
while(true)
{
// Blink an LED
digitalWrite(LED, LOW);
delay(2000);
digitalWrite(LED, HIGH);
delay(2000);
}
}
void openGate()
{
step = 0;
while(step++ < nSteps)
{
for(i = 0; i < 4; i++)
{
digitalWrite(IN1, paso[i][0]);
delay(speed);
digitalWrite(IN2, paso[i][1]);
delay(speed);
digitalWrite(IN3, paso[i][2]);
delay(speed);
digitalWrite(IN4, paso[i][3]);
delay(speed);
}
}
}
void closeGate()
{
step = nSteps;
while(step-- > 0)
{
for(i = 3; i >= 0; i--)
{
digitalWrite(IN1, paso[i][0]);
delay(speed);
digitalWrite(IN2, paso[i][1]);
delay(speed);
digitalWrite(IN3, paso[i][2]);
delay(speed);
digitalWrite(IN4, paso[i][3]);
delay(speed);
}
}
}
|
Java
|
UTF-8
| 5,042
| 3.703125
| 4
|
[] |
no_license
|
/*CS230 Final Project
*CourseTable.java
*Meher Vohra, Remi Kobayashi, Rosanne Hu
* 28/11/16
*
* Created by Rosanne Hu
*
* This class is what makes the actual schedule, it takes section objects
* from the priorityqueue in coursepriority and inputs them into the Schedule(Hastable)
* based on availibility.
*/
import java.util.*;
import javafoundations.*;
import java.io.*;
public class CourseSchedule{
//has multiple courses inwhich we add to the hashtable
private Hashtable schedule = new Hashtable();
private CoursePriority courses;
private char idTime;
private String idDist;
private LinkedList<Section> addedList;
/**
* Takes in idealTime and idealDist, and initializes a new CoursePriority and LinkedList.
*
* @param idealTime A character representing the time preference, as input by the user in the GUI
* @param idealDist A character representing the distribution preference, as input by the user in the GUI
*/
public CourseSchedule(char idealTime, String idealDist){
idTime = idealTime;
idDist = idealDist;
courses = new CoursePriority(idealTime, idealDist);
addedList = new LinkedList<Section>();
}
/**
* The addToQueue method takes in a file that we created
* with all the information about the courses. The course name
* and course priorities (rankings) come from user input.
*
* @param course A String of the course name
* @param priority An int of the rank, as input by the user
*/
public void addToQueue (String course, int priority) {
try {
Scanner fileScan = new Scanner (new File("courses.txt"));
boolean found = false;// have we found the course in our String file?
while (fileScan.hasNext()) {
String[] line = fileScan.nextLine().split(" ");
String first = line[0];
// System.out.println(first);
// System.out.println(course);
if(first.equals(course)){//when we find the course
Section section = new Section(first, line[1], line[2], line[3], priority);
courses.addSection(section);
found = true;
break;
}
}if (!found) throw new RuntimeException(); //if we can't find the course within our
} catch (IOException ex) {
System.out.println(ex);
}
}
public CoursePriority getQueue(){
return courses;
}
/**
* The addToschedule method takes in a section object that has been dequeued from
* the priority queue. If the Hashtable does not have the key then we add it
* and we change the boolean ableTo add
*
* @param cSection The Section object to be inserted into the hashtable
* @return a boolean that returns true if the coursehas been successfully added
*/
public boolean addToSchedule(Section cSection){
//String
String[] time = cSection.formattedTimes().split("\n");// need to split thetimes in getTimes and loop through the array
boolean ableToAdd = true;
for(String times: time){
//System.out.println(schedule.get(times));
if(schedule.get(times) != null)
ableToAdd=false;
}
if(ableToAdd){//add to the Hashtable
for(String times: time){
schedule.put(times,cSection);
}
}
return ableToAdd;
}
/**
* Adds each course inthe CoursePriority to the hashtable
*
*/
public void makeCourseSchedule(){
int size = 0;
while(size<4 && !courses.isEmpty()){// we can only have max 4 courses in here
Section thisCourse = courses.toSchedule();
boolean added = addToSchedule(thisCourse);//we dequeue and add it to the hashtab;e
if(added){ // So if the course wasn't able to be added because its already in the hashtable
size++;
addedList.add(thisCourse);
}
}
}
/**
* The toString method
*
* @return a string that prints all the courses that are able to be added to your schedule
*/
public String toString(){
String s = "";
Iterator<Section> keySetIterator = addedList.iterator();
//System.out.println(addedList.isEmpty());
while (keySetIterator.hasNext()){
Section here = keySetIterator.next();
if(here == null){
s+= "Nothing here";
}else{
s+=here.toString() + "\n";//calling the toString method of the section object
}
}
return s;
}
public static void main(String[] args){
//really only tests 2 functions: addToQueue and makeCourseSchedule
CourseSchedule sched = new CourseSchedule('a',"MM");
sched.addToQueue("MATH225",3);
sched.addToQueue("CS230",5);
sched.addToQueue("ECON103",4);
//all courses added previously should have been able to be added
sched.addToQueue("CS240",4);//time conflict and will not be added
sched.makeCourseSchedule();
System.out.println(sched.toString());
sched.addToQueue("MATH399",6);//Will not be added because it does not exist in courses.txt
System.out.println(sched.toString());//essentially unchanged
}
}
|
C
|
UTF-8
| 214
| 4.09375
| 4
|
[] |
no_license
|
#include <stdio.h>
/**
*main - printing the alphabet from a through z
*Return: The returned value is 0.
*/
int main(void)
{
char i;
for (i = 'a'; i <= 'z'; i++)
putchar(i);
putchar('\n');
return (0);
}
|
C++
|
UTF-8
| 852
| 2.671875
| 3
|
[] |
no_license
|
/***************************************************
* Copyright (c) 2020 Roee Xu. All Rights Reserved
****************************************************
* File: 1408.cpp
* Author: roeexu
* Date: 2020-06-24 15:47:16
* Brief:
****************************************************/
bool cmp(string& x, string& y) {
return x.length() < y.length();
}
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
vector<string> res;
sort(words.begin(), words.end(), cmp);
int n = words.size();
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if(words[j].find(words[i]) != -1) {
res.push_back(words[i]);
break;
}
return res;
}
};
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100 */
|
JavaScript
|
UTF-8
| 943
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
function openlogin() {
document.getElementById('mylogin').style.display = "block";
}
function closelogin(){
document.getElementById('mylogin').style.display = "none";
}
function openregis() {
document.getElementById('myregis').style.display = "block";
}
function closeregis(){
document.getElementById('myregis').style.display = "none";
}
window.onclick = function(event) {
if (event.target == document.getElementById('mylogin')) {
document.getElementById('mylogin').style.display = "none";
}
else if (event.target == document.getElementById('myregis')) {
document.getElementById('myregis').style.display = "none";
}
}
function alert(){
$.post("/login",function(data){
if (typeof data.alert == "string"){
alert(data.alert);
}else if (typeof data.redirect == "string"){
window.location = data.redirect;
}
});
}
|
Java
|
UTF-8
| 1,235
| 2.734375
| 3
|
[] |
no_license
|
package fr.eurecom.clouds.zklab;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class Process {
private static final String GROUP_NAME = "group07"; // <----- CHANGE THIS: substitute XX with your group number
public static void main(String[] args) throws IOException, InterruptedException
{
/* Check input arguments */
if(args.length < 1) {
System.err.println("Usage: java -jar <jar_file_name> <process id integer>");
System.exit(2);
}
/* Initialize Log4J to see ZooKeeper client messages */
BasicConfigurator.configure();
Logger logger = Logger.getRootLogger();
logger.setLevel(Level.INFO);
final int id = Integer.valueOf(args[0]);
final Elections myElection = new Elections(GROUP_NAME, id);
/* ... missing code here: the process should register and check if an election is needed */
myElection.register();
while (true) { // An infinite loop to keep the process alive
TimeUnit.SECONDS.sleep(1);
}
}
}
|
Shell
|
UTF-8
| 487
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
TERMUX_PKG_HOMEPAGE=https://curlie.io/
TERMUX_PKG_DESCRIPTION="The power of curl, the ease of use of httpie"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="@termux"
TERMUX_PKG_VERSION="1.7.1"
TERMUX_PKG_REVISION=1
TERMUX_PKG_SRCURL=git+https://github.com/rs/curlie
TERMUX_PKG_BUILD_IN_SRC=true
TERMUX_PKG_AUTO_UPDATE=true
termux_step_make() {
termux_setup_golang
go mod init || :
go mod tidy
go build
}
termux_step_make_install() {
install -Dm700 -t $TERMUX_PREFIX/bin curlie
}
|
Java
|
UTF-8
| 762
| 2.03125
| 2
|
[] |
no_license
|
package com.zyun.api.auth;
import com.zyun.model.auth.request.LoginRequest;
import com.zyun.model.auth.response.JwtResult;
import com.zyun.model.auth.response.LoginResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
/**
* @ClassName AuthControllerApi
* @Author: zsp
* @Date 2021/3/16 17:35
* @Description:
* @Version 1.0
*/
@Api("用户授权")
public interface AuthControllerApi {
@ApiOperation("登陆接口")
LoginResult login(LoginRequest loginRequest);
@ApiOperation("登出接口")
LoginResult logout();
@ApiOperation("根据jwt获取用户信息")
JwtResult getJwt();
@ApiOperation("刷新用户token")
LoginResult refresh();
}
|
TypeScript
|
UTF-8
| 828
| 2.53125
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class NewsApiService {
api_key = 'fc8e98b1afcf4a65a0f684da2acd9585';
constructor(private http:HttpClient) { }
// Prepare our left-side menu with some news resources.
initSources()
{
return this.http.get('https://newsapi.org/v2/sources?language=en&apiKey='+this.api_key);
}
//Retrieves the first articles from TechCrunch once the application gets started.
initArticles()
{
return this.http.get('https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey='+this.api_key);
}
// Bring some articles for the passing parameter.
getArticlesByID(source: String)
{
return this.http.get('https://newsapi.org/v2/top-headlines?sources='+source+'&apiKey='+this.api_key);
}
}
|
JavaScript
|
UTF-8
| 1,294
| 2.75
| 3
|
[] |
no_license
|
'use strict';
function getNextPlayerId(players, currentId) {
var ind = players.indexOf(_.findWhere(players, { id: currentId }));
return (ind + 1) % players.length;
}
angular.module('tonk')
.controller('GameCtrl', ['$scope', 'deck', 'HAND_SIZE', function($scope, Deck, HAND_SIZE) {
$scope.deck = new Deck();
$scope.discardPile = [];
$scope.newGame = function(playerToGo) {
$scope.resetPlayers();
$scope.turn = {
playerId: playerToGo || 0,
hasDrawn: false,
hasDiscarded: false,
};
$scope.deck.reset().shuffle();
$scope.deal(HAND_SIZE);
};
$scope.advanceTurn = function() {
if (!$scope.turn.hasDrawn || !$scope.turn.hasDiscarded) return;
$scope.turn.hasDrawn = false;
$scope.turn.hasDiscarded = false;
$scope.turn.playerId = getNextPlayerId($scope.players, $scope.turn.playerId);
};
/**
* iterates over players and reset their state for new game
*/
$scope.resetPlayers = function() {
$scope.players.forEach(function(player) {
player.hand = [];
player.isFrozen = false;
});
};
/**
* Gives each player some number of cards
*/
$scope.deal = function(numCards) {
_.times(numCards, function() {
$scope.players.forEach(function(player) {
player.hand.push($scope.deck.draw());
});
});
};
$scope.newGame();
}]);
|
Java
|
UTF-8
| 825
| 2.25
| 2
|
[] |
no_license
|
package com.xiaohu.blog.jpa.blog;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/")
@ResponseBody
public List<User> index(){
for (int i = 0; i < 10; i++) {
User user = new User();
user.setAge(10+i);
user.setPassword("454--"+i);
user.setUserName("小米"+i);
userService.save(user);
}
List<User> userList = userService.getUserList();
return userList; //重定向到 /list
}
}
|
C++
|
UTF-8
| 343
| 2.96875
| 3
|
[] |
no_license
|
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream new_file;
new_file.open("random_file_write.txt", ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else{
cout<<"New file created ";
new_file<<"Hey I am learning c++ file handling";
new_file.close();
}
return 0;
}
|
Python
|
UTF-8
| 425
| 3.015625
| 3
|
[] |
no_license
|
#coding:utf-8
"""
2019.03.14.Thur
<쿼드 트리>
분할정복 문제.
"""
a=[]
def dnq(n, i, j):
if n==1:
return a[i][j]
def main():
n=int(input())
for i in range(n):
a.append(input())
print(a[1])
for i in range(n):
temp=a[i]
a[i]=[]
for j in range(n):
a[i].append(int(temp[j]))
dnq(n, 0, 0)
if __name__=="__main__":
main()
|
Java
|
UTF-8
| 352
| 3.875
| 4
|
[] |
no_license
|
public class MyExp {
int base;
int exp;
public MyExp(int a, int b) {
this.base = a;
this.exp = b;
}
int getValue() {
int res = 1;
for(int i = 0; i < exp; i++)
res = res * base;
return res;
}
public static void main(String[] args) {
MyExp number1 = new MyExp(2, 3);
System.out.println("2의 3승 = "+number1.getValue());
}
}
|
C++
|
UTF-8
| 948
| 3.875
| 4
|
[] |
no_license
|
/* Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode *> nodes;
vector<int> ans;
if(root != NULL) nodes.push(root);
while(!nodes.empty()) {
TreeNode* current = nodes.top();
nodes.pop();
ans.push_back(current->val);
if(current->right != NULL) nodes.push(current->right);
if(current->left != NULL) nodes.push(current->left);
}
return ans;
}
};
|
C++
|
UHC
| 676
| 3.015625
| 3
|
[] |
no_license
|
#include "stdafx.h"
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS
void main()
{
char a = 65; // ƽŰڵ 'A'
char b = 'A'; // Ǹ鼭 char b 65; ڵ ˴ϴ.
printf("%d\n%d\n", a, b);
printf("%c\n%c\n", a, b); // %c ƽŰڵ忡 õǴ ڸ ش
char c = '8';
printf("%c\n%d\n", c, c);
for (int a = 0; a < 26; a++) {
printf("%c %d\n", 'A' + a, 65 + a); // 'A'+65 .
}
for (int i = 0; i < 26; i++) { //빮ڿ ҹ ƽŰڵ尪 ̴ 32̴.
printf("%d\n", ('a' + i) - ('A' + i));
}
}
|
C++
|
UTF-8
| 732
| 2.5625
| 3
|
[] |
no_license
|
// 执行用时 :
// 0 ms
// , 在所有 C++ 提交中击败了
// 100.00%
// 的用户
// 内存消耗 :
// 6.5 MB
// , 在所有 C++ 提交中击败了
// 100.00%
// 的用户
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m,vector<int> (n,1));
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(i >= 1 && j >= 1){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
else if(i >= 1 && j == 0){
dp[i][j] = dp[i-1][j];
}
else if(j >= 1 && i == 0){
dp[i][j] = dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
};
|
C++
|
UTF-8
| 807
| 2.671875
| 3
|
[] |
no_license
|
//By lxfly2000
#ifndef __SDL_PxString_H__
#define __SDL_PxString_H__
namespace ASCII_px_6x8 {
extern const unsigned ch_count;
extern const int px_count_horizonal, px_count_vertical;
//绘制单个字符的点阵
//字符不存在返回 -1, 否则为 0
extern int DrawPxChar(SDL_Renderer *renderer, unsigned ch, int x, int y, int pxsize);
//绘制点阵字符串
//str: 要显示的字符串
//strsize: 字符串长度(通过 SDL_arraysize 获取)
//x, y: 文字左上角的座标
//pxsize: 单个像素的边长
//color: 填充颜色
//multiline: 是否允许换行(默认允许)
//字符不存在返回 -1, 否则为 0
extern int DrawPxString(SDL_Renderer *renderer, const char *str, int strsize, int x, int y, int pxsize, const SDL_Color color, bool multiline = true);
}
#endif
|
Python
|
UTF-8
| 7,969
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
from .abstract import Array
_FULLARRAY_HANDLED_FUNCTIONS = {}
class FullArray(Array):
"""A array filled with a given value.
The array may be empty or all missing values.
.. versionadded:: 3.14.0
"""
def __init__(
self,
fill_value=None,
dtype=None,
shape=None,
units=False,
calendar=False,
source=None,
copy=True,
):
"""**Initialisation**
:Parameters:
fill_value : scalar, optional
The fill value for the array. May be set to
`cf.masked` or `np.ma.masked`.
dtype: `numpy.dtype`
The data type of the array.
shape: `tuple`
The array dimension sizes.
units: `str` or `None`, optional
The units of the netCDF variable. Set to `None` to
indicate that there are no units. If unset then the
units will be set to `None` during the first
`__getitem__` call.
calendar: `str` or `None`, optional
The calendar of the netCDF variable. By default, or if
set to `None`, then the CF default calendar is
assumed, if applicable. If unset then the calendar
will be set to `None` during the first `__getitem__`
call.
{{init source: optional}}
{{init copy: `bool`, optional}}
"""
super().__init__(source=source, copy=copy)
if source is not None:
try:
fill_value = source._get_component("full_value", None)
except AttributeError:
fill_value = None
try:
dtype = source._get_component("dtype", None)
except AttributeError:
dtype = None
try:
shape = source._get_component("shape", None)
except AttributeError:
shape = None
try:
units = source._get_component("units", False)
except AttributeError:
units = False
try:
calendar = source._get_component("calendar", None)
except AttributeError:
calendar = None
self._set_component("full_value", fill_value, copy=False)
self._set_component("dtype", dtype, copy=False)
self._set_component("shape", shape, copy=False)
self._set_component("units", units, copy=False)
self._set_component("calendar", calendar, copy=False)
def __array__(self, *dtype):
"""The numpy array interface.
.. versionadded:: 3.15.0
:Parameters:
dtype: optional
Typecode or data-type to which the array is cast.
:Returns:
`numpy.ndarray`
An independent numpy array of the data.
"""
array = self[...]
if not dtype:
return array
else:
return array.astype(dtype[0], copy=False)
def __array_function__(self, func, types, args, kwargs):
"""The `numpy` `__array_function__` protocol.
.. versionadded:: 3.15.0
"""
if func not in _FULLARRAY_HANDLED_FUNCTIONS:
return NotImplemented
# Note: This allows subclasses that don't override
# __array_function__ to handle FullArray objects
if not all(issubclass(t, self.__class__) for t in types):
return NotImplemented
return _FULLARRAY_HANDLED_FUNCTIONS[func](*args, **kwargs)
def __getitem__(self, indices):
"""x.__getitem__(indices) <==> x[indices]
Returns a numpy array.
"""
# If 'apply_indices' is False then we can make a filled numpy
# array that already has the correct shape. Otherwise we need
# to make one with shape 'self.shape' and then apply the
# indices to that.
apply_indices = False
if indices is Ellipsis:
array_shape = self.shape
else:
array_shape = []
for i, size in zip(indices, self.shape):
if not isinstance(i, slice):
continue
start, stop, step = i.indices(size)
a, b = divmod(stop - start, step)
if b:
a += 1
array_shape.append(a)
if len(array_shape) != self.ndim:
apply_indices = True
array_shape = self.shape
fill_value = self.get_full_value()
if fill_value is np.ma.masked:
array = np.ma.masked_all(array_shape, dtype=self.dtype)
elif fill_value is not None:
array = np.full(
array_shape, fill_value=fill_value, dtype=self.dtype
)
else:
array = np.empty(array_shape, dtype=self.dtype)
if apply_indices:
array = self.get_subspace(array, indices)
self._set_units()
return array
def __repr__(self):
"""Called by the `repr` built-in function.
x.__repr__() <==> repr(x)
"""
return f"<CF {self.__class__.__name__}{self.shape}: {self}>"
def __str__(self):
"""Called by the `str` built-in function.
x.__str__() <==> str(x)
"""
fill_value = self.get_full_value()
if fill_value is None:
return "Uninitialised"
return f"Filled with {fill_value!r}"
@property
def dtype(self):
"""Data-type of the data elements."""
return self._get_component("dtype")
@property
def shape(self):
"""Tuple of array dimension sizes."""
return self._get_component("shape")
def get_full_value(self, default=AttributeError()):
"""Return the data array fill value.
.. versionadded:: 3.14.0
.. seealso:: `set_full_value`
:Parameters:
default: optional
Return the value of the *default* parameter if the
fill value has not been set. If set to an `Exception`
instance then it will be raised instead.
:Returns:
The fill value.
"""
return self._get_component("full_value", default=default)
def set_full_value(self, fill_value):
"""Set the data array fill value.
.. versionadded:: 3.14.0
.. seealso:: `get_full_value`
:Parameters:
fill_value : scalar, optional
The fill value for the array. May be set to
`cf.masked` or `np.ma.masked`.
:Returns:
`None`
"""
self._set_component("full_value", fill_value, copy=False)
def fullarray_implements(numpy_function):
"""Register an __array_function__ implementation for FullArray objects.
.. versionadded:: 3.15.0
"""
def decorator(func):
_FULLARRAY_HANDLED_FUNCTIONS[numpy_function] = func
return func
return decorator
@fullarray_implements(np.unique)
def unique(
a, return_index=False, return_inverse=False, return_counts=False, axis=None
):
"""Version of `np.unique` that is optimised for `FullArray` objects.
.. versionadded:: 3.15.0
"""
if return_index or return_inverse or return_counts or axis is not None:
# Fall back to the slow unique. (I'm sure we could probably do
# something more clever here, but there is no use case at
# present.)
return np.unique(
a[...],
return_index=return_index,
return_inverse=return_inverse,
return_counts=return_counts,
axis=axis,
)
# Fast unique based on the full value
x = a.get_full_value()
if x is np.ma.masked:
return np.ma.masked_all((1,), dtype=a.dtype)
return np.array([x], dtype=a.dtype)
|
Java
|
UTF-8
| 1,354
| 3.359375
| 3
|
[] |
no_license
|
public class LC11ContainerWater {
public int maxArea(int[] height) {
int[][] heights_s = new int[height.length][2];
for (int i = 0; i < height.length; i++) {
System.out.println(height[i]);
heights_s[i][0]=i;
heights_s[i][1]=height[i];
}
for (int i = 0; i < height.length - 1; i++) {
for (int j = i; j < height.length; j++) {
if(heights_s[i][1]>=heights_s[j][1]){
int tmp = heights_s[i][0];
heights_s[i][0] = heights_s[j][0];
heights_s[j][0] = tmp;
int tmp2 = heights_s[i][1];
heights_s[i][1] = heights_s[j][1];
heights_s[j][1] = tmp2;
}
}
}
int maxs = 0;
if(height.length == 2){
maxs=(height[1]>=height[0])?height[0]:height[1];
}
for (int i = 0; i < height.length; i++) {
System.out.println(heights_s[i][0]+" : "+heights_s[i][1]);
}
for (int i = height.length-1; i >= 1; i--) {
for (int j = i; j >= 0; j--) {
int wall = (heights_s[i][1]>=heights_s[j][1])?heights_s[j][1]:heights_s[i][1];
int floor = Math.abs(heights_s[i][0]-heights_s[j][0]);
int maxh = wall * floor;
System.out.println(maxh);
maxs = (maxh>=maxs)?maxh:maxs;
System.out.println("wall: "+wall+" floor: "+floor+" max:"+maxs);
}
}
return maxs;
}
}
|
Java
|
UTF-8
| 1,782
| 2.234375
| 2
|
[] |
no_license
|
package org.vtb.edu.controllers;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.vtb.edu.database.dto.Product;
import org.vtb.edu.database.dto.User;
import org.vtb.edu.service.ProductService;
@Controller
@RequestMapping("/products")
@AllArgsConstructor
public class ProductController {
private ProductService productService;
@GetMapping("/all")
public String getAllProduct(Model model) {
model.addAttribute("frontProducts", productService.getAllProducts());
return "all_products";
}
@PostMapping("/add")
public String addNewProduct(@ModelAttribute Product product) {
productService.saveOrUpdateProduct(product);
return "redirect:/products/all";
}
@GetMapping({"/product/{id}", "/product"})
public String showProduct(@PathVariable(required = false) Long id, Model model) {
if (id == null) id = 0L;
Product product = productService.getProductById(id);
model.addAttribute("frontProduct", product);
return "product";
}
@GetMapping("/product/edit/{id}")
public String showEditUserForm(@PathVariable Long id, Model model) {
model.addAttribute("frontProduct", productService.getProductById(id));
return "/product_edit_page";
}
@PostMapping("product/edit")
public String editUser(@ModelAttribute Product product) {
productService.saveOrUpdateProduct(product);
return "redirect:/products/all";
}
@GetMapping("/product/remove/{id}")
public String removeUserById(@PathVariable Long id) {
productService.removeProductById(id);
return "redirect:/products/all";
}
}
|
Python
|
UTF-8
| 13,197
| 2.828125
| 3
|
[] |
no_license
|
import os
import sys
import csv
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from tkinter import *
from pathlib import Path
from stonks_sorter import stonks_sorter
class stonks_visualizer():
def __init__(self):
#Initialize vars
self.rootDir = Path(sys.path[0]).parent
self.company_links_path = str(self.rootDir) + "\\data\\company_symbols.dat"
self.prices_links_path = str(self.rootDir) + "\\data\\data.csv"
self.company_prefix = "/stocks/"
self.company_suffix = "-stock"
self.selected_company = None
#Get pricing data
if not os.path.isfile(self.company_links_path) or not os.path.isfile(self.prices_links_path):
raise Exception("Need the company names file and the data file to continue.")
with open(self.prices_links_path, "r") as file:
data_reader = csv.reader(file, delimiter=',')
self.data_contents = [row for row in data_reader]
#For sorting and other information
self.stonks_sorter = stonks_sorter(self.data_contents)
#Initialize GUI
self.gui = Tk()
self.gui.title('Stonks Visualizer')
#Mainframe for all widgets
self.mainframe = Frame(self.gui)
self.mainframe.grid(column=0,row=0, sticky=(N,W,E,S))
self.mainframe.pack(pady = 5, padx = 10)
#Popup menu to select a stock
self.tkvar = StringVar(self.mainframe)
self.tkvar.trace('w', self.change_dropdown)
self.choices = [line.strip() for line in open(self.company_links_path, "r").readlines()]
self.popupMenu = OptionMenu(self.mainframe, self.tkvar, *self.choices)
self.popupMenu.grid(row=0, column=1, sticky=E)
#Label and entry to go with popup menu
self.popupLabel = Label(self.mainframe, text="Choose a company")
self.popupLabel.grid(row=0, column=0, sticky=W)
self.companyEntry = Entry(self.mainframe)
self.companyEntry.grid(row=1, column=0, columnspan=2, sticky=(W,E,S))
#Button to visualize
self.displayStocks = Button(self.mainframe, text="Show stock", command=self.displayStockInfo)
self.displayStocks.grid(row=2, column=0, columnspan=1, pady=3, sticky=(W,S))
self.displayMultiple = Button(self.mainframe, text="More info", command=self.more_info)
self.displayMultiple.grid(row=2, column=1, columnspan=1, pady=3, sticky=(E,S))
#Date range
self.greatestIncreaseRange = StringVar()
self.graphRangeChoices = ["Day", "Week", "1 Month", "6 Months", "Year"]
self.graphRangeMenu = OptionMenu(self.mainframe, self.greatestIncreaseRange, *self.graphRangeChoices)
self.graphRangeMenu.grid(row=3, column=0, columnspan=2, sticky=(S,E,W))
def gui_initialize(self):
self.gui.mainloop()
def change_dropdown(self, *args):
self.companyEntry.delete(0, END)
self.companyEntry.insert(0, self.tkvar.get())
def displayStockInfo(self):
self.selected_company = self.companyEntry.get()
if not self.selected_company:
return
#Step 1: Find company.
if len(self.data_contents) > 0:
if self.selected_company not in self.data_contents[0]:
self.companyEntry.delete(0, END)
self.companyEntry.insert(0, "Company not in spreadsheet.")
return
else:
self.companyEntry.delete(0, END)
self.companyEntry.insert(0, "Company not in spreadsheet.")
return
#Step 2: Get index of company.
company_index = self.data_contents[0].index(self.selected_company)
#Step 3: Get all rows in that column, append to 2D list.
pricing_data = []
try:
#If earliest date is a think, then compare. If not, grab them all.
if self.greatestIncreaseRange.get():
self.earliestDate = self.stonks_sorter.get_earliest_date(self.greatestIncreaseRange.get())
for row in self.data_contents[1:]: #loop through each row except first
pastDate = datetime.datetime.strptime(row[company_index+1], "%m/%d/%Y %H:%M:%S").date()
if pastDate >= self.earliestDate:
pricing_data.append([row[company_index], row[company_index+1]])
else:
for row in self.data_contents[1:]: #loop through each row except first
pricing_data.append([row[company_index], row[company_index+1]])
except IndexError:
pass
except ValueError:
pass
#Step 4: Visualize
#Need if entry[i] on end for potential blank values
prices = [float(entry[0]) for entry in pricing_data if entry[0]]
#Convert from saved string to list of datetime.datetime objects for matplotlib
#print(pricing_data[1][1].seconds)
timestamps = []
#Need this; when importing datetime strings, if seconds are 00, they get removed.
for entry in pricing_data:
try:
if entry[1]:
timestamps.append(dates.date2num(datetime.datetime.strptime(entry[1], "%m/%d/%Y %H:%M:%S")))
except ValueError:
timestamps.append(dates.date2num(datetime.datetime.strptime(entry[1], "%m/%d/%Y %H:%M")))
priceDiff = max(prices) - min(prices)
minPrice = min(prices)
maxPrice = max(prices)
minLabel = minPrice + (priceDiff * 0.2)
maxLabel = maxPrice + (priceDiff * 0.2)
plt.figure(figsize=(9.6,7.2)).canvas.set_window_title(self.selected_company)
plt.plot_date(timestamps, prices, '-o', markersize=4)
if priceDiff != 0:
plt.ylim((minPrice,maxLabel))
plt.fill_between(timestamps, prices, color='blue', alpha=0.1)
plt.grid()
plt.show()
"""
Info displayed here:
1. Highest risers since (today, week, month, 6 months, 12 months)
2.
"""
def more_info(self):
self.increaseList = []
self.tableElems = []
self.tableRow = 3
#Create secondary GUI and frame
self.moreInfoGUI = Toplevel(self.gui)
self.moreInfoFrame = Frame(self.moreInfoGUI, borderwidth = 2)
self.moreInfoFrame.grid(column=0,row=0, sticky=(N,W,E,S))
self.moreInfoFrame.pack(pady = 5, padx = 10)
#Create options menu
self.rangeChoices = ["Day", "Week", "1 Month", "6 Months", "Year"]
self.greatestIncreaseRange = StringVar()
self.rangeMenu = OptionMenu(self.moreInfoFrame, self.greatestIncreaseRange, *self.rangeChoices)
self.rangeMenu.grid(row=1, column=0, sticky=(N,W))
#Create options menu
self.growthChoices = ["$", "%"]
self.growthVar = StringVar()
self.growthChoicesMenu = OptionMenu(self.moreInfoFrame, self.growthVar, *self.growthChoices)
self.growthChoicesMenu.grid(row=1, column=1, sticky=(N))
#Create options menu
self.growthDirectionChoices = ["Increase", "Decrease"]
self.growthDirectionVar = StringVar()
self.growthDirectionMenu = OptionMenu(self.moreInfoFrame, self.growthDirectionVar, *self.growthDirectionChoices)
self.growthDirectionMenu.grid(row=1, column=2, sticky=(N,E))
#Create button and input for range and number of companies
self.numberCompanies = IntVar()
self.greatestIncreaseNumCompanies = Entry(self.moreInfoFrame)
self.greatestIncreaseNumCompanies.insert(0, "Number of companies")
self.greatestIncreaseNumCompanies.grid(row=0, column=0, columnspan=3, sticky=(N,W,E))
self.greatestIncreaseButton = Button(self.moreInfoFrame, text="Search", command=self.greatest_increase)
self.greatestIncreaseButton.grid(row=2, column=0, columnspan=3, sticky=(S,W,E))
"""
Helper function
Get the 5 highest risers in a given frequency
Loop through each company, find the farthest acceptable date for range
Calculate difference from that entry to most current entry
Get top 5
"""
def greatest_increase(self):
#Need data to process
if not len(self.data_contents) > 0:
return
#If the list exists and no settings have changed, don't go through all the data again
if not self.increaseList:
#Get range for dates
self.earliestDate = self.stonks_sorter.get_earliest_date(self.greatestIncreaseRange.get())
#Go through every company, and get every value until the day is no longer in range
self.numberCompanies = int(self.greatestIncreaseNumCompanies.get())
self.increaseList = self.stonks_sorter.get_increase_list(
self.numberCompanies,
self.earliestDate,
self.growthDirectionVar.get(),
self.growthVar.get())
#Save current choices to determine if change was made
self.currentGrowth = self.growthVar.get()
self.currentGrowthDirection = self.growthDirectionVar.get()
else:
#See if earliest date changed
currentEarliestDate = self.earliestDate
self.earliestDate = self.stonks_sorter.get_earliest_date(self.greatestIncreaseRange.get())
changedRange = False if currentEarliestDate == self.earliestDate else True
#See if # companies changed
currentNumberCompanies = self.numberCompanies
self.numberCompanies = int(self.greatestIncreaseNumCompanies.get())
changedNumber = False if currentNumberCompanies == self.numberCompanies else True
#See if growth var changed
changedGrowthVar = False if self.growthVar.get() == self.currentGrowth else True
#See if growth direction changed
changedGrowthDirection = False if self.growthDirectionVar.get() == self.currentGrowthDirection else True
#Set current choices
self.currentGrowth = self.growthVar.get()
self.currentGrowthDirection = self.growthDirectionVar.get()
#print(changedRange, changedNumber, changedGrowthVar, changedGrowthDirection)
if changedRange or changedNumber or changedGrowthVar or changedGrowthDirection:
self.increaseList = self.stonks_sorter.get_increase_list(
self.numberCompanies,
self.earliestDate,
self.growthDirectionVar.get(),
self.growthVar.get())
#Remove all prior elements and clear list
for element in self.tableElems:
element.destroy()
self.tableElems.clear()
#Display table headers
tempName = Label(self.moreInfoFrame, text="Company", borderwidth=4, relief="ridge")
tempName.grid(row=self.tableRow, column=0, sticky=(N,S,E,W))
tempStart = Label(self.moreInfoFrame, text="Start", borderwidth=4, relief="ridge")
tempStart.grid(row=self.tableRow, column=1, sticky=(N,S,E,W))
tempEnd = Label(self.moreInfoFrame, text="End", borderwidth=4, relief="ridge")
tempEnd.grid(row=self.tableRow, column=2, sticky=(N,S,E,W))
tempDiff = Label(self.moreInfoFrame, text="Diff", borderwidth=4, relief="ridge")
tempDiff.grid(row=self.tableRow, column=3, sticky=(N,S,E,W))
tempDiffPercent = Label(self.moreInfoFrame, text="% Diff", borderwidth=4, relief="ridge")
tempDiffPercent.grid(row=self.tableRow, column=4, sticky=(N,S,E,W))
#Display info
for company in range(len(self.increaseList)):
tempName = Label(self.moreInfoFrame, text=self.increaseList[company][0], borderwidth=2, relief="groove")
tempName.grid(row=company + self.tableRow + 1, column=0, sticky=(N,S,E,W))
tempStart = Label(self.moreInfoFrame, text=self.increaseList[company][3], borderwidth=2, relief="groove")
tempStart.grid(row=company + self.tableRow + 1, column=1, sticky=(N,S,E,W))
tempEnd = Label(self.moreInfoFrame, text=self.increaseList[company][4], borderwidth=2, relief="groove")
tempEnd.grid(row=company + self.tableRow + 1, column=2, sticky=(N,S,E,W))
tempDiff = Label(self.moreInfoFrame, text="$" + str(self.increaseList[company][1]), borderwidth=2, relief="groove")
tempDiff.grid(row=company + self.tableRow + 1, column=3, sticky=(N,S,E,W))
tempDiffPercent = Label(self.moreInfoFrame, text=str(self.increaseList[company][2]) + "%", borderwidth=2, relief="groove")
tempDiffPercent.grid(row=company + self.tableRow + 1, column=4, sticky=(N,S,E,W))
self.tableElems.append(tempName)
self.tableElems.append(tempStart)
self.tableElems.append(tempEnd)
self.tableElems.append(tempDiff)
self.tableElems.append(tempDiffPercent)
if __name__ == '__main__':
visualizer = stonks_visualizer()
visualizer.gui_initialize()
|
Swift
|
UTF-8
| 1,782
| 2.796875
| 3
|
[] |
no_license
|
//
// LoadingView.swift
// Loodos
//
// Created by Doğan akdeniz on 1.05.2021.
//
import UIKit
final class LoadingView: UIView {
// MARK: - Private Variables
private var parentView: UIView!
private var activityIndicator: UIActivityIndicatorView!
// MARK: - Initialization Methods
init(parentView: UIView) {
super.init(frame: CGRect.zero)
self.parentView = parentView
// Configure
self.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.7000171586)
self.activityIndicator = UIActivityIndicatorView(frame: CGRect.zero)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.style = .large
activityIndicator.hidesWhenStopped = true
activityIndicator.color = .white
self.addSubview(self.activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor)
])
self.parentView.addSubview(self)
NSLayoutConstraint.activate([
self.trailingAnchor.constraint(equalTo: self.parentView.safeAreaLayoutGuide.trailingAnchor),
self.leadingAnchor.constraint(equalTo: self.parentView.safeAreaLayoutGuide.leadingAnchor),
self.bottomAnchor.constraint(equalTo: self.parentView.safeAreaLayoutGuide.bottomAnchor),
self.topAnchor.constraint(equalTo: self.parentView.safeAreaLayoutGuide.topAnchor)
])
self.hide()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Methods
func show() {
self.alpha = 1
self.activityIndicator.startAnimating()
}
func hide() {
self.alpha = 0
self.activityIndicator.stopAnimating()
}
}
|
C
|
UTF-8
| 1,730
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#ifndef __CLI_USAGE__
#define __CLI_USAGE__
static const char USAGE[] =
R"(
Usage:
skafos (setup|init|auth)...
skafos init [<name>] [--org <org_name>] [--template <template_name>] [--master]
skafos templates [--update] [--search <search_term>]
skafos env [<key>] [--set <value>] [--delete]
skafos create [<kind>] [<name>] [--project <token>]
skafos logs [<project_token>] [-n <num>] [--tail]
skafos fetch --table <table_name>
skafos kill [<project_token>] [--deployments <deployment_ids>] [--job_ids <job_ids>]
skafos remote info [<project_token>]
skafos orgs [<name>] [--set-default]
skafos whoami
skafos models (list [<name>] [--deployment <deployment_id>] [--job <job_id>]|download <name> [-o <output_path>]) [--project <token>] [--tag <tag>] [-v version]
skafos -h | --help
skafos --version
Commands:
setup Setup development environment.
init Create a new project.
auth Authenticate request.
templates Manage templates.
create Create a Job for a project.
env Get or set environment variables.
logs Get logs for a project.
fetch Fetch results from a given table.
kill Kill an entire project or specific jobs/deployments.
remote info Print command to add a new remote.
orgs List or set your default organization.
whoami List your current user info and settings.
models List or download models for a project.
Options:
--version Shows version.
If you need help, feel free to reach out:
https://metismachine.com
https://twitter.com/metismachine
https://github.com/metismachine
Fire it up!
)";
#endif
|
PHP
|
UTF-8
| 2,021
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace bestelServer\Http\Controllers;
use bestelServer\winkel;
use bestelServer\winkelItem;
use bestelServer\bestellingen;
use bestelServer\bestelItems;
use Illuminate\Http\Request;
class klantenController extends Controller
{
public function index()
{
$winkels = Winkel::all();
return view('klanten.index', compact('winkels'));
}
public function show($id)
{
$winkel = Winkel::find($id);
return view('klanten.show', compact('winkel'));
}
public function store(Request $request, $id)
{
$this->validate($request, [
'naam' => 'required',
'mail' => 'email',
'tel' => 'required',
'afhaalUur' => 'required',
'afhaalDatum' => 'required'
]);
$namen = $request->naamItem;
$hoeveelheden = $request->hoeveel;
$ids = $request->id;
$totaalPrijs = 0;
$teller = 0;
$bestelling = new bestellingen;
$bestelling->winkel_id = $id;
$bestelling->naam = $request->naam;
$bestelling->mail = $request->mail;
$bestelling->tel = $request->tel;
$bestelling->afhaalUur = $request->afhaalUur;
$bestelling->afhaalDatum = $request->afhaalDatum;
$bestelling->totaalPrijs = 0;
$bestelling->save();
foreach ($hoeveelheden as $hoeveelheid)
{
//Totaalprijs berekenen
if($hoeveelheid != 0)
{
$totaalPrijs += winkelItem::find($ids[$teller])->prijs * $hoeveelheid;
$bestelItem = new bestelItems;
$bestelItem->bestellingen_id = $bestelling->id;
$bestelItem->naam = $namen[$teller];
$bestelItem->aantal = $hoeveelheid;
$bestelItem->save();
}
$teller++;
}
$bestelling->totaalPrijs = $totaalPrijs;
$bestelling->save();
return view('klanten.einde');
//$table->totaalPrijs
}
}
|
Python
|
UTF-8
| 3,316
| 3.265625
| 3
|
[] |
no_license
|
# Spyder (Python) - Code C073
import matplotlib.pyplot as plt
import numpy as np
from numpy import arange,vstack,argmin,asarray
from numpy.random import normal,random
from warnings import catch_warnings, simplefilter
from scipy.stats import norm
from sklearn.gaussian_process import GaussianProcessRegressor
def fobjetivo(x, noise=0):
noise = normal(loc=0, scale=noise)
return (abs(x * np.sin(x) + 0.1 * x)) + noise
X = arange(-10, 10, 0.01)
# domínio definido sem ruído
y = [fobjetivo(x, 0) for x in X]
plt.plot(X, y,'g',label='f(x)=|xsin(x)+ x/10)|')
# melhor resultado
ix = argmin(y)
print('Optima: x=%.3f, y=%.3f' % (X[ix], y[ix]))
# aproximação da função (função substituta)
def surrogate(model, X):
# aviso de divisão por zero na previsão
with catch_warnings():
# ignorar advertência
simplefilter("ignore")
return model.predict(X, return_std=True)
# definir função de aquisição por PI
def acquisition(X, Xsamples, model):
# cálculo da melhor pontuação substituta encontrada até agora
yhat, _ = surrogate(model, X)
best = max(yhat)
# cálculo da média e stdev via função substituta
mu, std = surrogate(model, Xsamples)
mu = mu[:, 0]
# cálculo da PI
probs = norm.cdf((mu-best)/(std+1e-5))
return probs
# otimização da função de aquisição por amostra aleatória
def opt_acquisition(X, y, model):
# gerar espaço aletório com amostra aleatória
Xsamples = random(100)
Xsamples = Xsamples.reshape(len(Xsamples), 1)
# calcular a função de aquisição para cada amostra
scores = acquisition(X, Xsamples, model)
# localizar o índice das maiores pontuações
ix = argmin(scores)
return Xsamples[ix, 0]
# plotar as observações reais vs função substiruta
def plot(X, y, model):
# gráfico de dispersão de entradas e função objetivo real
plt.scatter(X, y)
# gráfico da função substituta no domínio considerad
Xsamples = asarray(arange(-10, 10, 0.01))
Xsamples = Xsamples.reshape(len(Xsamples), 1)
ysamples, _ = surrogate(model, Xsamples)
plt.plot(Xsamples, ysamples,'r',label='Função Substituta')
# amostrar o domínio esparsamente
X = random(100)
y = asarray([fobjetivo(x) for x in X])
# remodelar em linhas e colunas
X = X.reshape(len(X), 1)
y = y.reshape(len(y), 1)
# definir o modelo
model = GaussianProcessRegressor()
# ajustar o modelo
model.fit(X, y)
# realizar o processo de otimização
for i in range(100):
# selecionar o próximo ponto para a amostra
x = opt_acquisition(X, y, model)
# verificar o ponto na amostragem
actual = fobjetivo(x)
# resumir a descoberta
est, _ = surrogate(model, [[x]])
print('>x=%.3f, f()=%3f, actual=%.3f' % (x, est, actual))
# adicionar dados ao banco de dados
X = vstack((X, [[x]]))
y = vstack((y, [[actual]]))
# atualizar o modelo
model.fit(X, y)
# plotar todas as amostras e a função substitutiva final
plot(X, y, model)
plt.plot(X, y,'go',label='Regressão GP')
plt.legend(loc='upper right')
plt.grid(True)
plt.show()
#plt.savefig('Fig-7.4.png')
# melhor resultado
ix = argmin(y)
print('Best Result: x=%.3f, y=%.3f' % (X[ix], y[ix]))
|
C++
|
UTF-8
| 319
| 3.203125
| 3
|
[] |
no_license
|
#include<iostream>
#include<conio.h>
using namespace std;
int fact (int n)
{
if (n ==1)
{
return 1;
}
else
{
return n* fact(n-1);
}
}
int main()
{
int factorial = fact(6);
cout << "Factorial is = " << factorial << endl;
getch();
}
|
Shell
|
UTF-8
| 1,954
| 3.515625
| 4
|
[] |
no_license
|
#!/bin/bash
set -e
# Params
# - Config file
# - Map file
version="1.2"
unique=e09f3rp9ac09ajjrw3r09aemriwelkm
if [ $# -le 1 ]; then
echo "Usage: parse.sh <config.json> <action-map-file>"
exit 1
fi
kv_map=$(cat $2 | jq -c '.key_value' | sed "s/\"\././g; s/\"\,/,/g; s/\"\}/}/g")
kv_query="$kv_map | to_entries[] | select (.value | length > 0) | .key,.value"
#kv_map_quote=$(cat $2 | jq -c '.key_value_quote' | sed "s/\"\././g; s/\"\,/,/g; s/\"\}/}/g")
#kv_query_quote="$kv_map_quote | to_entries[] | select (.value | length > 0) | .key,.value"
bool_map=$(cat $2 | jq -c '.bool' | sed "s/\"\././g; s/\"\,/,/g; s/\"\}/}/g")
bool_query="$bool_map | to_entries[] | select (.value==true) | .key"
array_map=$(cat $2 | jq -c '.array' | sed "s/\"\././g; s/\"\,/,/g; s/\"\}/}/g")
array_query="$array_map | to_entries[] | select (.value | length > 0) | {key, value: .value[]} | .key,.value"
container_net_map=$(cat $2 | jq -c '.container_network' | sed "s/\"(/(/g; s/\"\,/,/g; s/\"\}/}/g; s/{\"query\":\"//; s/| ,\"/| {\"/; s/':'/\":\"/g")
container_net_query="$container_net_map | to_entries[] | select (.value | length > 0) | .key,.value"
kv_map_output=$(cat $1 | jq -c "$kv_query")
#kv_map_quote_output=$(cat $1 | jq -c "$kv_query_quote")
if [ "$bool_map" != "null" ]; then
bool_map_output=$(cat $1 | jq -c "$bool_query")
fi
if [ "$array_map" != "null" ]; then
array_map_output=$(cat $1 | jq -c "$array_query")
fi
if [ "$container_net_map" != "null" ]; then
container_net_map_output=$(cat $1 | jq -c "$container_net_query")
fi
combine_output=$kv_map_output" "$array_map_output" "$container_net_map_output
# Remove the quotes from just the keys, not the values - only works if bool args are not mixed in
remove_k_quotes=$(echo $combine_output | sed "s/\"--/--/g; s/\" \"/ \"/g; s/\"/\'/g")
# Remove quotes from keys and values
remove_all_quotes=$(echo $bool_map_output | sed "s/\"//g")
echo $remove_all_quotes" "$remove_k_quotes
|
Python
|
UTF-8
| 218
| 3
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 4 22:38:40 2020
@author: 16509
"""
def times3(var1):
return var1*3
seq1to10=[1,2,3,4,5,6,7,8,9,10]
newseq=[item*3 for item in seq1to10]
print(newseq)
|
JavaScript
|
UTF-8
| 6,868
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.jsonp = factory());
}(this, function () { 'use strict';
/**
* object check method
*
* @param {*} item variable will be check
* @param {string} type target type. Type value is 'String'|'Number'|'Boolean'|'Undefined'|'Null'|'Object'|'Function'|'Array'|'Date'|'RegExp'
* @return {boolean} true mean pass, false not pass
*/
function typeCheck(item, type) {
var itemType = Object.prototype.toString.call(item);
var targetType = "[object ".concat(type, "]");
if (itemType === targetType) {
return true;
} else {
return false;
}
}
function randNum() {
// get random number
var oT = new Date().getTime().toString();
var num = Math.ceil(Math.random() * 10000000000);
var randStr = num.toString();
return oT + randStr;
}
function removeChild(parent, child) {
var childNodes = parent.childNodes;
for (var i = 0; i < childNodes.length; i++) {
if (childNodes[i] === child) {
parent.removeChild(child);
}
}
}
/**
* Param info
* @param {string} url url path to get data, It support url include data.
* @param {Object=} options all options look down
* @param {(Object | string)=} options.data this data is data to send. If is Object, Object will become a string eg. "?key1=value1&key2=value2" . If is string, String will add to at the end of url string.
* @param {Function=} options.success get data success callback function.
* @param {Function=} options.error get data error callback function.
* @param {Function=} options.loaded when data loaded callback function.
* @param {string=} options.callback custom callback key string , default 'callback'.
* @param {string=} options.callbackName callback value string.
* @param {boolean} options.noCallback no callback key and value. If true no these params. Default false have these params
* @param {string=} options.charset charset value set, Default not set any.
* @param {number=} options.timeoutTime timeout time set. Unit ms. Default 60000
* @param {Function=} options.timeout timeout callback. When timeout run this function.
* When you only set timeoutTime and not set timeout. Timeout methods is useless.
*/
function index (url, options) {
var oHead = document.querySelector('head'),
script = document.createElement('script');
var timer,
dataStr = '',
_callback = 'callback',
_callbackName = "callback_".concat(randNum()),
_noCallback = false,
_timeoutTime = 60000,
_loaded,
_success;
var endMethods = [];
if (!url) {
throw new ReferenceError('No url ! Url is necessary !');
}
if (!typeCheck(url, 'String')) {
throw new TypeError('Url must be string !');
}
var methods = {
data: function data() {
var data = options.data;
if (typeCheck(data, 'Object')) {
for (var item in data) {
dataStr += "".concat(item, "=").concat(data[item], "&");
}
} else if (typeCheck(data, 'String')) {
dataStr = data + '&';
} else {
throw new TypeError('data must be object or string !');
}
},
success: function success() {
_success = options.success;
if (!typeCheck(_success, 'Function')) throw new TypeError('param success must be function !');
},
error: function error() {
if (!typeCheck(options.error, 'Function')) {
throw new TypeError('param error must be function !');
}
script.addEventListener('error', options.error);
},
loaded: function loaded() {
_loaded = options.loaded;
if (!typeCheck(_loaded, 'Function')) {
throw new TypeError('param loaded must be function !');
}
},
callback: function callback() {
_callback = options.callback;
if (!typeCheck(_callback, 'String')) {
throw new TypeError('param callback must be string !');
}
},
callbackName: function callbackName() {
_callbackName = options.callbackName;
if (!typeCheck(_callbackName, 'String')) {
throw new TypeError('param callbackName must be string !');
}
},
noCallback: function noCallback() {
_noCallback = options.noCallback;
if (!typeCheck(_noCallback, 'Boolean')) {
throw new TypeError('param noCallback must be boolean !');
}
},
charset: function charset() {
var charset = options.charset;
if (typeCheck(charset, 'String')) {
script.charset = charset;
} else {
throw new TypeError('param charset must be string !');
}
},
timeoutTime: function timeoutTime() {
_timeoutTime = options.timeoutTime;
if (!typeCheck(_timeoutTime, 'Number')) {
throw new TypeError('param timeoutTime must be number !');
}
},
timeout: function timeout() {
if (!typeCheck(options.timeout, 'Function')) {
throw new TypeError('param timeout must be function !');
}
function timeout() {
function outTime() {
// script.parentNode.removeChild(script);
removeChild(script.parentNode, script);
window.hasOwnProperty(_callbackName) && delete window[_callbackName];
clearTimeout(timer);
options.timeout();
}
timer = setTimeout(outTime, _timeoutTime);
}
endMethods.push(timeout);
}
};
for (var item in options) {
methods[item]();
}
endMethods.forEach(function (item) {
item();
}); // warn url include data
if (_noCallback && dataStr != '') {
url.indexOf('?') == -1 ? url += "?".concat(dataStr.slice(0, -1)) : url += "&".concat(dataStr.slice(0, -1));
}
if (!_noCallback) {
window[_callbackName] = function (data) {
_success && _success(data); // oHead.removeChild(script);
removeChild(oHead, script);
delete window[_callbackName];
};
url.indexOf('?') == -1 ? url += "?".concat(dataStr).concat(_callback, "=").concat(_callbackName) : url += "&".concat(dataStr).concat(_callback, "=").concat(_callbackName);
}
url = encodeURI(url);
function loadLis() {
script.removeEventListener('load', loadLis);
_loaded && _loaded();
clearTimeout(timer); // oHead.removeChild(script);
removeChild(oHead, script);
}
script.addEventListener('load', loadLis);
script.src = url;
oHead.appendChild(script);
}
return index;
}));
|
Python
|
UTF-8
| 4,604
| 2.75
| 3
|
[] |
no_license
|
#!/usr/bin/env python
from __future__ import division
from math import sqrt
import pickle, os
from uncertainties import ufloat
try:
from pyutils.nums import roundPair
except ImportError:
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),'../..'))
from pyutils.nums import roundPair
class Efficiency:
'''
Class to store and evaluate information about a single efficiency
'''
def __init__(self, eff=None, s_eff=None, n_gen=None, n_sel=None, s2_n_gen=None, s2_n_sel=None, cov_n_gen_sel=None, sumw2_sel=None, sumw2_gen=None):
self.eff = 0
self.s_eff = 0
if n_gen is not None and n_sel is not None:
try:
self.eff = n_sel/n_gen
if s2_n_gen is not None and s2_n_sel is not None and cov_n_gen_sel is not None:
self.s_eff = n_sel/n_gen * sqrt( s2_n_sel/n_sel**2 + s2_n_gen/n_gen**2 - 2*cov_n_gen_sel/(n_sel*n_gen) )
else: # self.s_eff = sqrt( self.eff * abs(1-self.eff) / n_gen )
if sumw2_sel is None: sumw2_sel = n_sel
if sumw2_gen is None: sumw2_gen = n_gen
self.s_eff = sqrt( ( (1 - 2 * n_sel/n_gen)*sumw2_sel + (n_sel/n_gen)**2 * sumw2_gen ) / n_gen**2 )
except ZeroDivisionError:
pass # keep default 0, 0
if eff is not None: self.eff = eff
if s_eff is not None: self.s_eff = s_eff
# Protection against wrong values given by sWeights and similar
if self.eff < 0: self.eff = 0
if self.s_eff < 0: self.s_eff = 0
if self.eff > 1: self.eff = 1
if self.s_eff > 1: self.s_eff = 1
@property
def s_rel_eff(self):
return self.s_eff/self.eff
@property
def ufloat(self):
return ufloat(self.eff,self.s_eff)
def __str__(self):
return 'efficiency = '+str(self.eff)+'\n'+\
'error = '+str(self.s_eff)+'\n'+\
'relative error = '+str(self.s_rel_eff)
def saveToFile(self, fileName = "efficiency.txt"):
'''
Use pickle to save to file
'''
pickle.dump(self, open( fileName, "wb" ))
def loadFromFile(self,fileName = "efficiency.txt"):
'''
Use pickle to load from to file
'''
return pickle.load( open( fileName, "rb" ) )
def __repr__(self):
val, err = roundPair(self.eff, self.s_eff)
return val+' +- '+err
#def __r
def __add__(self, other):
res = Efficiency()
res.eff = self.eff + other.eff
res.s_eff = sqrt(self.s_eff**2 + other.s_eff**2)
return res
def __sub__(self, other):
res = Efficiency()
res.eff = self.eff - other.eff
res.s_eff = sqrt(self.s_eff**2 + other.s_eff**2)
return res
def __mul__(self, other):
res = Efficiency()
if hasattr( other, 'eff'): # Multiply by another efficiency
res.eff = self.eff * other.eff
try:
res.s_eff = res.eff * sqrt( (self.s_eff/self.eff)**2 + (other.s_eff/other.eff)**2)
except ZeroDivisionError:
res.s_eff = 1
elif hasattr( other, 'std_dev'): # Multiply by a ufloat
self_ufloat = ufloat(self.eff, self.s_eff)
result = self_ufloat*other
res.eff = result.n
res.s_eff = result.s
else: # Multiply by a number
res.eff = self.eff * other
res.s_eff = self.s_eff * other
return res
def __div__(self, other):
res = Efficiency()
if hasattr( other, 'eff'): # Divide by another efficiency
res.eff = self.eff / other.eff if self.eff else self.eff
try:
res.s_eff = res.eff * sqrt( (self.s_eff/self.eff)**2 + (other.s_eff/other.eff)**2)
except ZeroDivisionError:
res.s_eff = 1
elif hasattr( other, 'std_dev'): # Divide by a ufloat
self_ufloat = ufloat(self.eff, self.s_eff)
result = self_ufloat / other
res.eff = result.n
res.s_eff = result.s
else: # Divide by a number
res.eff = self.eff / other
res.s_eff = self.s_eff / other
return res
__truediv__ = __div__
#################################################
# Import submodules
try:
from distrEffs import *
except ImportError: # When run PID I setup urania and do not have fancy python tools like root_numpy
print 'Not able to import distrEffs'
pass
#################################################
|
Markdown
|
UTF-8
| 1,710
| 2.65625
| 3
|
[] |
no_license
|
---
layout: post
title: "Introspection"
date: 2015-04-12 08:56:20 +0000
comments: true
categories: Ruby
---
### http://www.leighhalliday.com/ruby-introspection-metaprogramming
#### What data am I working on?
```ruby
puts spitty.inspect
#<Alpaca:0x007fd849166808 @name="Spitty", @birthdate=#<Date: 1984-11-11 ((2446016j,0s,0n),+0s,2299161j)>>
```
#### What type of class is this?
```ruby
puts spitty.class.name
# Alpaca
puts spitty.instance_of?(Alpaca)
# true
```
#### What methods are available to me?
```ruby
puts spitty.methods.inspect
[:name, :name=, :birthdate, :birthdate=, :spit, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
# methods except from parent object
7.methods.sort - Object.methods
puts spitty.respond_to?(:spit)
# true
```
#### Which instance variables are defined?
```ruby
puts spitty.instance_variables.inspect
[:@name, :@birthdate]
```
#### Which instance variables are defined?
```ruby
@name = "Mike"
test = "name"
2.2.0p0 :001 > puts instance_variable_get("@#{test}")
Mike
=> nil
2.2.0p0 :002 > puts instance_variable_set("@#{test}", "asdf")
asdf
=> nil
```
|
Ruby
|
UTF-8
| 7,909
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
module Ramaze
module Logger
##
# A logger that rotates log files based on the current date. Log files are
# named after the date on which they were created. If the date changes a new
# log file is used.
#
# In order to use this logger you'll have to specify a base directory for
# all log files. This directory will not be created for you so make sure it
# exists. Loading the class can be done as following:
#
# logger = Ramaze::Logger::RotatingInformer.new('./log')
#
# This creates a new instance that uses the directory ``./log`` for all it's
# log files.
#
# The default log format is ``%Y-%m-%d.log``. If you want to change this you
# can specify an alternative format (including the extension) as the
# secondary parameter of the ``.new()`` method:
#
# logger = Ramaze::Logger::RotatingInformer.new('./log', '%d-%m-%Y.log')
#
# In this case the instance will use the date format ``dd-mm-yyyy`` along
# with the ``.log`` extension.
#
# Besides the date format you can also customize the timestamp format as
# well as the format of each logged messages. Both these are set in a trait.
# The timestamp format is located in the trait ``:timestamp`` while the
# message format is stored in the ``:format`` trait. These can be set as
# following:
#
# logger = Ramaze::Logger::RotatingInformer.new('./log')
#
# logger.trait[:timestamp] = '...'
# logger.trait[:format] = '...'
#
# When setting the ``:format`` trait you can use 3 tags that will be
# replaced by their corresponding values. These are the following tags:
#
# * ``%time``: will be replaced by the current time.
# * ``%prefix``: the log level such as "ERROR" or "INFO".
# * ``%text``: the actual log message.
#
class RotatingInformer
include Innate::Traited
include Logging
attr_accessor :time_format, :log_levels
attr_reader :base_dir
# parameter for Time.now.strftime
trait :timestamp => "%Y-%m-%d %H:%M:%S"
# This is how the final output is arranged.
trait :format => "[%time] %prefix %text"
##
# Create a new instance of RotatingInformer.
#
# base_dir is the directory where all log files will be stored
#
# time_format is the time format used to name the log files. Possible
# formats are identical to those accepted by Time.strftime
#
# log_levelse is an array describing what kind of messages that the log
# receives. The array may contain any or all of the symbols :debug,
# :error, :info and/or :warn
#
# @example
# # Creates logs in directory called logs. The generated filenames
# # will be in the form YYYY-MM-DD.log
# RotatingInformer.new('logs')
#
# # Creates logs in directory called logs. The generated filenames
# # will be in the form YYYY-MM.txt
# RotatingInformer.new('logs', '%Y-%m.txt')
#
# # Creates logs in directory called logs. The generated filenames
# # will be in the form YYYY-MM.txt.
# # Only errors will be logged to the files.
# RotatingInformer.new('logs', '%Y-%m.txt', [:error])
#
# @param [String] base_dir The base directory for all the log files.
# @param [String] time_format The time format for all log files.
# @param [Array] log_levels Array containing the type of messages to log.
#
def initialize(base_dir, time_format = '%Y-%m-%d.log',
log_levels = [:debug, :error, :info, :warn])
# Verify and set base directory
send :base_dir=, base_dir, true
@time_format = time_format
@log_levels = log_levels
# Keep track of log shutdown (to prevent StackErrors due to recursion)
@in_shutdown = false
end
##
# Set the base directory for log files
#
# If this method is called with the raise_exception parameter set to true
# the method will raise an exception if the specified directory does not
# exist or is unwritable.
#
# If raise_exception is set to false, the method will just silently fail
# if the specified directory does not exist or is unwritable.
#
# @param [String] directory The base directory specified by the developer.
# @param [Bool] raise_exception Boolean that indicates if an exception
# should be raised if the base directory doesn't exist.
#
def base_dir=(directory, raise_exception = false)
# Expand directory path
base_dir = File.expand_path(directory)
# Verify that directory path exists
if File.exist?(base_dir)
# Verify that directory path is a directory
if File.directory?(base_dir)
# Verify that directory path is writable
if File.writable?(base_dir)
@base_dir = base_dir
else
raise Exception.new("#{base_dir} is not writable") if raise_exception
end
else
raise Exception.new("#{base_dir} is not a directory") if raise_exception
end
else
raise Exception.new("#{base_dir} does not exist.") if raise_exception
end
end
##
# Close the file we log to if it isn't closed already.
#
def shutdown
if @out.respond_to?(:close)
unless @in_shutdown
@in_shutdown = true
Log.debug("close, #{@out.inspect}")
@in_shutdown = false
end
@out.close
end
end
##
# Integration to Logging.
#
# @param [String] tag The type of message we're logging.
# @param [Array] messages An array of messages to log.
#
def log(tag, *messages)
return unless @log_levels.include?(tag)
# Update current log
update_current_log
messages.flatten!
prefix = tag.to_s.upcase.ljust(5)
messages.each do |message|
@out.puts(log_interpolate(prefix, message))
end
@out.flush if @out.respond_to?(:flush)
end
##
# Takes the prefix (tag), text and timestamp and applies it to
# the :format trait.
#
# @param [String] prefix
# @param [String] text
# @param [Integer] time
#
def log_interpolate(prefix, text, time = timestamp)
message = class_trait[:format].dup
vars = { '%time' => time, '%prefix' => prefix, '%text' => text }
vars.each{|from, to| message.gsub!(from, to) }
message
end
##
# This uses timestamp trait or a date in the format of
# ``%Y-%m-%d %H:%M:%S``
#
# @return [String]
#
def timestamp
mask = class_trait[:timestamp]
Time.now.strftime(mask || "%Y-%m-%d %H:%M:%S")
end
##
# Is ``@out`` closed?
#
# @return [TrueClass|FalseClass]
#
def closed?
@out.respond_to?(:closed?) && @out.closed?
end
##
# Method that is called by Rack::CommonLogger when logging data to a file.
#
# @author Yorick Peterse
# @param [String] message The data that has to be logged.
#
def write(message)
log(:info, message)
end
private
##
# Checks whether current filename is still valid. If not, update the
# current log to point at the new filename.
#
def update_current_log
out = File.join(@base_dir, Time.now.strftime(@time_format))
if @out.nil? || @out.path != out
# Close old log if necessary
shutdown unless @out.nil? || closed?
# Start new log
@out = File.open(out, 'ab+')
end
end
end # RotatingInformer
end # Log
end # Ramaze
|
C++
|
UTF-8
| 1,279
| 3.8125
| 4
|
[] |
no_license
|
/*
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ? k ? BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need
to find the kth smallest frequently? How would you optimize the kthSmallest routine?
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int helper(TreeNode* root, int& k) {
if(!root) return -1;
auto x = helper(root->left, k);
if(k == 0) return x;
if(k == 1) {--k; return root->val;}
return helper(root->right, --k);
}
int kthSmallest(TreeNode* root, int k) {
if(!root) return -1;
return helper(root, k);
}
};
class Solution1 {
public:
void inorder(TreeNode* root, vector<int>& res){
if(root == NULL) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
int kthSmallest(TreeNode* root, int k) {
vector<int> res;
inorder(root, res);
return res[k-1];
}
};
|
Python
|
UTF-8
| 2,073
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
import validators
class RequestError(Exception):
pass
class Request(object):
def __init__(self, parameters=None):
if parameters is None:
self.parameters = []
else:
self.parameters = parameters
self.errors = []
self.global_errors = []
self.is_bound = False
self.post_validators = []
self.param_bag = []
def bind(self, param_bag):
self.param_bag = param_bag
self.is_valid = False
for parameter in self.parameters:
parameter.bind(self.param_bag)
self.is_bound = True
def validate(self):
self.errors = []
self.global_errors = []
for parameter in self.parameters:
try:
parameter.validate()
except validators.ValidatorError as e:
self.errors.append((parameter, e))
if len(self.errors) is 0:
self.is_valid = True
else:
self.is_valid = False
self.runPostValidators()
def runPostValidators(self):
for postvalidator in self.post_validators:
try:
postvalidator(self)
except validators.ValidatorGlobalError as e:
self.global_errors.append(e)
if len(self.global_errors):
self.is_valid = False
def getArgs(self):
if self.is_valid is False:
return None
return {param.varname: param.getValue() for param in self.parameters}
def addParam(self, parameter):
self.parameters.append(parameter)
def addPostValidator(self, postvalidator):
self.post_validators.append(postvalidator)
def getParam(self, param_varname):
'''
get a request parameter by varname
or raise RequestError
'''
for param in self.parameters:
if param.varname == param_varname:
return param
raise RequestError('Tried to use undefined request parameter <{}>'.format(param_varname))
def describe(self):
pass
|
Python
|
UTF-8
| 729
| 3.703125
| 4
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 18:48:10 2020
@author: Christopher Cheng
"""
# By setting a new variable and casting the dictionary into a list form,
# Can make a new copy of it
artists = ["monet", "picasso"]
painters = list(artists)
painters.append("van gogh")
# If list, can also use .copy() function
# This is another way that acheives the same thing
lala = ["turt","clemm"]
bobo = lala.copy()
bobo.append("plush")
# Can sort and copy at the same time via sorted(L)
# Rather than using .sort(), which changes the pointer and sorts the original
kids_age = [2,1,4]
sorted_age = sorted(kids_age)
# QC 28.4
chaos = []
order = sorted(chaos)
colors = []
colors.sort()
cards = []
deck = cards
cards = cards.sort()
|
Java
|
UTF-8
| 16,419
| 2.375
| 2
|
[] |
no_license
|
package Dc.app.Sampleboot;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
//import javax.swing.text.html.HTMLDocument.Iterator;
@Service
public class ConstantsService {
@Autowired
ConstantsRepository constantsRepository;
@Autowired
TherapeuticAreaMongoRepository therapeuticAreaMongoRepository;
@Autowired
SubTherapeuticAreaMongoRepository subTherapeuticAreaMongoRepository;
@Autowired
MedicalSchoolMongoRepository medicalSchoolMongoRepository;
@Autowired
IndustryMongoRepository industryMongoRepository;
@Autowired
LocationMongoRepository locationMongoRepository;
public CountriesResource getCountries() {
return constantsRepository.getCountries();
}
public StatesResource getStatesForCountry(String key, Country country) {
return constantsRepository.getStatesForCountry(key, country);
}
public LocationsResource getCitiesForState(String key, String state) {
List<Location> locations = locationMongoRepository.findByState(state);
LocationsResource locationsResource=new LocationsResource(locations);
return locationsResource;
}
public TherapeuticAreaResource getTherapeuticAreas(String key) {
return constantsRepository.getTherapeuticAreas(key);
}
public SubTherapeuticAreaResource getSubTherapeuticAreas(String key) {
return constantsRepository.getSubTherapeuticAreas(key);
}
public LocationsResource getLocations(String key){
return constantsRepository.getLocations(key);
}
public MedicalSchoolResource getMedicalSchools(String key) {
return constantsRepository.getMedicalSchools(key);
}
public IndustriesResource getIndustries(String key) {
return constantsRepository.getIndustries(key);
}
public DegreesResource getDegrees(String key) {
return constantsRepository.getDegrees(key);
}
public Area saveTherapeuticArea(TherapeuticArea area) {
Area newArea=therapeuticAreaMongoRepository.save(area);
return newArea;
}
public Area saveSubTherapeuticArea(SubTherapeuticArea area) {
Area newArea=subTherapeuticAreaMongoRepository.save(area);
return newArea;
}
public MedicalSchool saveMedicalSchool(MedicalSchool medicalSchool) {
MedicalSchool medicalSchool1=medicalSchoolMongoRepository.save(medicalSchool);
return medicalSchool1;
}
public Industry saveIndustry(Industry industry) {
return industryMongoRepository.save(industry);
}
public Location saveLocation(Location location){
Location location1=locationMongoRepository.save(location);
return location1;
}
public void insertTherapeuticArea(){
try
{
List<String> therapeuticAreaList = new ArrayList<String>();
therapeuticAreaList.add("Anatomy");
therapeuticAreaList.add("Anesthesiology");
therapeuticAreaList.add("Aerospace Medicine");
therapeuticAreaList.add("Biochemistry");
therapeuticAreaList.add("Biomedical Engineering");
therapeuticAreaList.add("Cardiothoracic Surgery");
therapeuticAreaList.add("Dermatology ");
therapeuticAreaList.add("Emergency Medicine");
therapeuticAreaList.add("Family Medicine");
therapeuticAreaList.add("Genetics");
therapeuticAreaList.add("Internal Medicine ");
therapeuticAreaList.add("Hospice & Palliative Medicine");
therapeuticAreaList.add("Microbiology");
therapeuticAreaList.add("Molecular Biology");
therapeuticAreaList.add("Forensic Medicine & Toxicology");
therapeuticAreaList.add("Neurology ");
therapeuticAreaList.add("Neuro Surgery");
therapeuticAreaList.add("Nuclear Medicine");
therapeuticAreaList.add("Obstetrics and Gynecology");
therapeuticAreaList.add("Occupational Medicine");
therapeuticAreaList.add("Ophthalmology");
therapeuticAreaList.add("Orthopedic Surgery");
therapeuticAreaList.add("Otorhinolaryngology, Head and Neck Surgery");
therapeuticAreaList.add("Pathology");
therapeuticAreaList.add("Pediatrics");
therapeuticAreaList.add("Pharmacology");
therapeuticAreaList.add("Pharmaceutical Mecdicine");
therapeuticAreaList.add("Physical Medicine and Rehabilitation");
therapeuticAreaList.add("Physiology");
therapeuticAreaList.add("Preventive, Community & Social Medicine");
therapeuticAreaList.add("Psychiatry");
therapeuticAreaList.add("Radiation Medicine");
therapeuticAreaList.add("Radiology");
therapeuticAreaList.add("Regenerative Medicine");
therapeuticAreaList.add("Sports Medicine");
therapeuticAreaList.add("Surgery");
therapeuticAreaList.add("Urology");
therapeuticAreaList.add("Translational Medicine");
therapeuticAreaList.add("Dentistry");
therapeuticAreaList.add("Podiatric Medicine");
therapeuticAreaList.add("Physiotherapy");
therapeuticAreaList.add("Optometry");
therapeuticAreaList.add("Audiology");
therapeuticAreaList.add("Nursing");
therapeuticAreaList.add("Hospitalist");
therapeuticAreaList.add("Immunology and cellular medicine ");
Iterator<String> itr = therapeuticAreaList.iterator();
while(itr.hasNext()){
String value = (String) itr.next();
TherapeuticArea therapeuticArea = new TherapeuticArea();
therapeuticArea.setArea(value);
therapeuticAreaMongoRepository.save(therapeuticArea);
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public void insertsubTherapeuticArea(){
try
{
List<String> subTherapeuticAreaList = new ArrayList<String>();
subTherapeuticAreaList.add("Cardiac Anesthesia");
subTherapeuticAreaList.add("Critical care");
subTherapeuticAreaList.add("Pain management");
subTherapeuticAreaList.add("Pediatric Anesthesia");
subTherapeuticAreaList.add("Neuro Anesthesia");
subTherapeuticAreaList.add("Heart Transplant");
subTherapeuticAreaList.add("Lung Transplant");
subTherapeuticAreaList.add("Structural heart Disease");
subTherapeuticAreaList.add("Pediatric");
subTherapeuticAreaList.add("Dermatopathology ");
subTherapeuticAreaList.add("Aesthetic Dermatology");
subTherapeuticAreaList.add("Derm Oncology");
subTherapeuticAreaList.add("Cutaneous Surgery");
subTherapeuticAreaList.add("Dermatological immunology");
subTherapeuticAreaList.add("Hospitalist");
subTherapeuticAreaList.add("Oncology");
subTherapeuticAreaList.add("Cardiology");
subTherapeuticAreaList.add("Gastroenterology");
subTherapeuticAreaList.add("Nephrology");
subTherapeuticAreaList.add("Pulmonary And Critical Care");
subTherapeuticAreaList.add("Rheumatology");
subTherapeuticAreaList.add("Vascular Medicine");
subTherapeuticAreaList.add("Allergy And Immunology");
subTherapeuticAreaList.add("Hepatology");
subTherapeuticAreaList.add("Endocrinologist");
subTherapeuticAreaList.add("Aesthetic medicine");
subTherapeuticAreaList.add("Geriatrics");
subTherapeuticAreaList.add("Infectious Disease");
subTherapeuticAreaList.add("Sports Medicine");
subTherapeuticAreaList.add("Neuro Oncology");
subTherapeuticAreaList.add("Autonomic Neurology");
subTherapeuticAreaList.add("Neuromuscular Neurology");
subTherapeuticAreaList.add("Headache Medicine");
subTherapeuticAreaList.add("Neurocritical Care");
subTherapeuticAreaList.add("Neural Repair And Rehabilitation");
subTherapeuticAreaList.add("Geriatric Neurology");
subTherapeuticAreaList.add("Neuroimaging");
subTherapeuticAreaList.add("Behavioral Neurology And Neuropsychiatry ");
subTherapeuticAreaList.add("Gynecology Oncology");
subTherapeuticAreaList.add("Urogynecology And Female Pelvic Medicine");
subTherapeuticAreaList.add("Reproductive Endocrinology And Infertility");
subTherapeuticAreaList.add("Minimally Invasive Gynecologist");
subTherapeuticAreaList.add("Maternal And Fetal Health");
subTherapeuticAreaList.add("Geriatric Gynecology");
subTherapeuticAreaList.add("Pediatric And Adolescent Gynecology");
subTherapeuticAreaList.add("Family Planning");
subTherapeuticAreaList.add("Retina Specialist");
subTherapeuticAreaList.add("Oculoplasty");
subTherapeuticAreaList.add("Pediatric Ophthalmology");
subTherapeuticAreaList.add("Neuropthalmology");
subTherapeuticAreaList.add("Vitreoretinal Disease Surgery");
subTherapeuticAreaList.add("Ophthalmic Pathology");
subTherapeuticAreaList.add("Corneal And External Disease");
subTherapeuticAreaList.add("Cataract And Refractive Surgery");
subTherapeuticAreaList.add("Glaucoma Surgery");
subTherapeuticAreaList.add("Uveitis And Ocular Immunology ");
subTherapeuticAreaList.add("Shoulder And Elbow");
subTherapeuticAreaList.add("Hand Surgery");
subTherapeuticAreaList.add("Hip And Knee Surgery");
subTherapeuticAreaList.add("Foot And Ankle Surgery");
subTherapeuticAreaList.add("Trauma surgery");
subTherapeuticAreaList.add("Pediatric Orthopedics");
subTherapeuticAreaList.add("Sports Medicine");
subTherapeuticAreaList.add("Spine Surgery");
subTherapeuticAreaList.add("Musculoskeletal Oncology");
subTherapeuticAreaList.add("Neuro Otology");
subTherapeuticAreaList.add("Sleep Medicine");
subTherapeuticAreaList.add("Pediatric Otolaryngiology");
subTherapeuticAreaList.add("Head And Neck Plastic Surgery");
subTherapeuticAreaList.add("General Pathology");
subTherapeuticAreaList.add("Gastrointestinal Pathology");
subTherapeuticAreaList.add("Derma Pathology");
subTherapeuticAreaList.add("Neuropathology");
subTherapeuticAreaList.add("Uropathology");
subTherapeuticAreaList.add("Thoracic pathology");
subTherapeuticAreaList.add("Cardiac Pathology");
subTherapeuticAreaList.add("Bone Pathology");
subTherapeuticAreaList.add("Neurology");
subTherapeuticAreaList.add("Gastroenterology");
subTherapeuticAreaList.add("Endocrinology");
subTherapeuticAreaList.add("Genetics");
subTherapeuticAreaList.add("Child Psychiatry");
subTherapeuticAreaList.add("Pulmonary And Critical Care");
subTherapeuticAreaList.add("Nephrology");
subTherapeuticAreaList.add("Neonatology");
subTherapeuticAreaList.add("Pediatric Oncology");
subTherapeuticAreaList.add("Cell Based Therapist ");
subTherapeuticAreaList.add("Infectious Disease ");
subTherapeuticAreaList.add("General Pharmacology");
subTherapeuticAreaList.add("Neuropharmacology");
subTherapeuticAreaList.add("Cardiacpahrmacology");
subTherapeuticAreaList.add("Gastrointestinal Pharmacology");
subTherapeuticAreaList.add("Kidney Pharmacology");
subTherapeuticAreaList.add("Psychopharmacology");
subTherapeuticAreaList.add("Clinical Pharmacology");
subTherapeuticAreaList.add("Brain Injury");
subTherapeuticAreaList.add("Pediatric PM&R");
subTherapeuticAreaList.add("Pain Medicine");
subTherapeuticAreaList.add("Sports Medicine");
subTherapeuticAreaList.add("Spinal Cord Rehabilitation");
subTherapeuticAreaList.add("Hospice And Palliative Medicine");
subTherapeuticAreaList.add("Musculoskeletal Rehabilitation");
subTherapeuticAreaList.add("Cardiac Pulmonary");
subTherapeuticAreaList.add("Gastrointestinal");
subTherapeuticAreaList.add("Kidney");
subTherapeuticAreaList.add("Blood Circulation");
subTherapeuticAreaList.add("Neurophysiology");
subTherapeuticAreaList.add("Acid Base Physiology");
subTherapeuticAreaList.add("Urophysiology");
subTherapeuticAreaList.add("Lymphatic Circulation");
subTherapeuticAreaList.add("Child And Adolescent Psychiatry ");
subTherapeuticAreaList.add("Addiction Psychiatry");
subTherapeuticAreaList.add("Forensic Psychiatry");
subTherapeuticAreaList.add("Psychosomatic Medicine");
subTherapeuticAreaList.add("Geriatric Psychiatry");
subTherapeuticAreaList.add("Sleep Medicine");
subTherapeuticAreaList.add("Pediatric Radiology");
subTherapeuticAreaList.add("Thoracic Radiology");
subTherapeuticAreaList.add("Head And Neck Radiology");
subTherapeuticAreaList.add("Neuroradiology");
subTherapeuticAreaList.add("Skeletal Radiology");
subTherapeuticAreaList.add("Interventional Radiology");
subTherapeuticAreaList.add("Ultrasonology");
subTherapeuticAreaList.add("Gastrointestinal Radiology");
subTherapeuticAreaList.add("General Surgery");
subTherapeuticAreaList.add("Cardiac Surgery");
subTherapeuticAreaList.add("Minimally Invasive Surgery");
subTherapeuticAreaList.add("Thoracic Surgery");
subTherapeuticAreaList.add("Breast Surgery");
subTherapeuticAreaList.add("Surgical Oncology");
subTherapeuticAreaList.add("Plastic Surgery");
subTherapeuticAreaList.add("Surgical Critical Care");
subTherapeuticAreaList.add("Pediatric Surgery");
subTherapeuticAreaList.add("Vascular Surgery");
subTherapeuticAreaList.add("Colorectal Surgery");
subTherapeuticAreaList.add("Uroncology");
subTherapeuticAreaList.add("Pelvic Reconstruction And Bladder Surgery");
subTherapeuticAreaList.add("Urethral Reconstruction");
subTherapeuticAreaList.add("Male Infertility");
subTherapeuticAreaList.add("Minimally Invasive Urology");
subTherapeuticAreaList.add("Pediatric Urology");
subTherapeuticAreaList.add("Pediatric Dentistry");
subTherapeuticAreaList.add("Ortho Dentistry");
subTherapeuticAreaList.add("Periodontics");
subTherapeuticAreaList.add("Maxillofacial Surgery ");
subTherapeuticAreaList.add("Aesthetic Dentistry ");
Iterator<String> itr = subTherapeuticAreaList.iterator();
while(itr.hasNext()){
String value = (String) itr.next();
SubTherapeuticArea subTherapeuticArea = new SubTherapeuticArea();
subTherapeuticArea.setArea(value);
subTherapeuticAreaMongoRepository.save(subTherapeuticArea);
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public void insertLocation(){
try{
List<Location> insertLocationList=new ArrayList<Location>();
FileInputStream file = new FileInputStream(new File("/home/kosoft-013/Downloads/eclipse/Workspace/Samplboot-master latest/cityListForIndia1.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Location loc=new Location();
Country con=new Country();
Row row = rowIterator.next();
//loc.setId("");
loc.setCity(row.getCell(0).toString());
loc.setState(row.getCell(1).toString());
con.setCountryName(row.getCell(2).toString());
con.setCountryCode(row.getCell(3).toString());
loc.setCountry(con);
insertLocationList.add(loc);
System.out.println("");
}
locationMongoRepository.save(insertLocationList);
file.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
Markdown
|
UTF-8
| 809
| 3.390625
| 3
|
[] |
no_license
|
最长连续队列
问题分类:动态规划
难度:困难
使用数据结构:unordered_map
时间复杂度: O(n)
解析:本题使用了散列的思想
```
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int ans=0;
unordered_map<int,int> m;
for(int i=0;i<nums.size();i++){
if(m.count(nums[i]))
continue;
int left=m.count(nums[i]-1)?m[nums[i]-1]:0;
int right=m.count(nums[i]+1)?m[nums[i]+1]:0;
int sum=left+right+1;
ans=max(ans,sum);
m[nums[i]]=sum;
// 只需要变换最边缘两个数对应的内容即可,无需变换整个队列的内容
m[nums[i]-left]=sum;
m[nums[i]+right]=sum;
}
return ans;
}
};
|
Java
|
UTF-8
| 13,663
| 1.640625
| 2
|
[] |
no_license
|
package technician.ifb.com.ifptecnician;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import technician.ifb.com.ifptecnician.alert.Alert;
import technician.ifb.com.ifptecnician.allurl.AllUrl;
import technician.ifb.com.ifptecnician.internet.CheckConnectivity;
import technician.ifb.com.ifptecnician.utility.SimInfo;
public class ForgotPassword extends AppCompatActivity implements View.OnClickListener{
EditText et_mobileno;
Button btn_forgot_password;
LinearLayout ll_main;
String mobile;
ProgressBar progressBar;
TextView tv_popup;
private static final String TAG = ForgotPassword.class.getSimpleName();
Alert alert=new Alert();
LinearLayout ll_sms_true,ll_sms_false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
init();
}
public void init(){
et_mobileno=findViewById(R.id.et_mobileno);
btn_forgot_password=findViewById(R.id.btn_forgot_password);
btn_forgot_password.setEnabled(false);
ll_main=findViewById(R.id.ll_main);
ll_main.setOnClickListener(this);
progressBar=findViewById(R.id.taskProcessing);
tv_popup=findViewById(R.id.tv_error_message);
ll_sms_true=findViewById(R.id.layout_sms_true);
ll_sms_false=findViewById(R.id.layout_sms_false);
et_mobileno.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (et_mobileno.getText().toString().length() == 10) {
btn_forgot_password.setEnabled(true);
btn_forgot_password.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_shape));
btn_forgot_password.setOnClickListener(ForgotPassword.this);
mobile=et_mobileno.getText().toString();
hideSoftKeyboard(ForgotPassword.this);
}
else {
btn_forgot_password.setEnabled(false);
btn_forgot_password.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_disable));
btn_forgot_password.setClickable(false);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
et_mobileno.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (et_mobileno.getText().toString().length() == 10) {
mobile=et_mobileno.getText().toString();
hideSoftKeyboard(ForgotPassword.this);
}
handled = true;
}
return handled;
}
});
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id. btn_forgot_password:
checkblank();
break;
case R.id.ll_main:
hideSoftKeyboard(ForgotPassword.this);
break;
}
}
public void checkblank(){
if (mobile.length() == 10){
getprofile();
}
}
public void getprofile(){
if (CheckConnectivity.getInstance(this).isOnline()) {
progressBar.setVisibility(View.VISIBLE);
RequestQueue queue = Volley.newRequestQueue(this);
String url = AllUrl.baseUrl+"sa-profile/getProfile/?user.Mobileno=" + mobile;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
JSONObject jsonObject=new JSONObject(response);
System.out.println("Response-->"+response);
String status=jsonObject.getString("Status");
if (status.equals("true")) {
JSONArray jsonArray = jsonObject.getJSONArray("Data");
if (jsonArray.length() == 1) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String PartnerId = obj.getString("PartnerId");
if (PartnerId.equals("")) {
alert.showDialog(ForgotPassword.this, "Error", "No valid account linked, Please Contact Administrator");
} else {
callsms("", "", mobile);
// Toast.makeText(ForgotPassword.this, "Valid user", Toast.LENGTH_SHORT).show();
}
}
}
else {
alert.showDialog(ForgotPassword.this, "Error", "Unable to Login Due to Multiple Account Detected. So Please contact your administrator");
}
}
else {
// if user is imactive show alert message
alert.showDialog(ForgotPassword.this,"Error","No valid account linked, Please Contact Administrator");;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//progressbar.setVisibility(View.GONE);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} else {
Toast.makeText(this, "No Internet connection", Toast.LENGTH_SHORT).show();
}
}
public static void hideSoftKeyboard(Activity activity) {
try {
if (activity != null) {
InputMethodManager manager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (manager != null) {
manager.hideSoftInputFromWindow(activity.findViewById(android.R.id.content).getWindowToken(), 0);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void callsms(String refno,String smstype,String Destination){
smstype="FOG";
// Destination="9674699648";
refno="1402EC721EA01EEA94F93CD4CA0A6B7A";
if (CheckConnectivity.getInstance(this).isOnline()) {
progressBar.setVisibility(View.VISIBLE);
RequestQueue queue = Volley.newRequestQueue(this);
String url =AllUrl.baseUrl+"SMS/RepeatFeedbackSMS?model.feddbacksms.RefId="+refno+"&model.feddbacksms.SMSType="+smstype+"&model.feddbacksms.Destination="+Destination+"";
System.out.println(url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
System.out.println("response--> "+response);
if (response.equals("")){
showsmsalert("false");
}
try{
JSONObject object=new JSONObject(response);
String status=object.getString("Status");
if (status.equals("true")){
showsmsalert("true");
}
else {
// showsmspopup("SMS Failed.Plesae try after some time");
showsmsalert("false");
}
}catch (Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
showsmsalert("false");
}
});
int socketTimeout = 10000; //10 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
queue.add(stringRequest);
}
else {
showsmspopup("No internet connection");
}
}
public void showsmspopup(String message){
tv_popup.setText(message);
tv_popup.setVisibility(View.VISIBLE);
Animation animation;
animation = AnimationUtils.loadAnimation(ForgotPassword.this, R.anim.slide_down);
tv_popup.startAnimation(animation);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
tv_popup.setAnimation(null);
tv_popup.setVisibility(View.GONE);
}
}, 5000);
}
public void showsmsalert(String status){
if (status.equals("true")){
ll_sms_true.setVisibility(View.VISIBLE);
ll_sms_false.setVisibility(View.GONE);
Animation animation;
animation = AnimationUtils.loadAnimation(ForgotPassword.this, R.anim.slide_down);
ll_sms_true.startAnimation(animation);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ll_sms_true.setAnimation(null);
ll_sms_true.setVisibility(View.GONE);
}
}, 5000);
}
else {
ll_sms_true.setVisibility(View.GONE);
ll_sms_false.setVisibility(View.VISIBLE);
Animation animation;
animation = AnimationUtils.loadAnimation(ForgotPassword.this, R.anim.slide_down);
ll_sms_false.startAnimation(animation);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
ll_sms_false.setAnimation(null);
ll_sms_false.setVisibility(View.GONE);
}
}, 5000);
}
}
}
|
Java
|
UTF-8
| 4,383
| 3.703125
| 4
|
[] |
no_license
|
package com.dsa.linkedlists;
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private int value;
private Node next;
private Node(int value){
this.value = value;
}
}
private Node first;
private Node last;
private int size;
public void addFirst(int item){
var node = new Node(item);
size++;
if(isEmpty())
first = last = node;
else {
node.next = first;
first = node;
}
}
public void addLast(int item){
var node = new Node(item);
size++;
if(isEmpty())
first = last = node;
else {
last.next = node;
last = node;
}
}
public void deleteFirst(){
if(!isEmpty()){
size--;
first = first.next;
}
}
public void deleteFirstGCFriendly(){
if(isEmpty()){
throw new NoSuchElementException();
} else if (first == last) {
size--;
first = last = null;
}
else {
size--;
var second = first.next;
first.next = null;
first = second;
}
}
public void deleteLast() {
if(!isEmpty()){
var current = first;
while(current != null) {
if(current.next == last){
size--;
current.next = null;
last = current;
} else {
current = current.next;
}
}
} else{
throw new NoSuchElementException();
}
}
public int indexOf (int item){
int index = 0;
var current = first;
while(current != null) {
if(current.value == item) {
return index;
} else {
current = current.next;
index++;
}
}
return -1;
}
public boolean contains (int item){
return indexOf(item) != - 1;
}
public int size() {
return size;
}
public String print() {
StringBuilder str = new StringBuilder("LinkedList - ");
if(!isEmpty()){
var current = first;
while(current != null) {
str.append(current.value + " --> ");
current = current.next;
}
}
return str.toString();
}
public int[] toArray(){
int[] arr = new int[size];
int index = 0;
if(!isEmpty()){
var current = first;
while(current!=null){
arr[index++] = current.value;
current = current.next;
}
}
return arr;
}
public void reverse(){
if(!isEmpty()) {
var firstNode = first;
var secondNode = first.next;
while(secondNode != null) {
var next = secondNode.next;
secondNode.next = firstNode;
firstNode = secondNode;
secondNode = next;
}
//setting first and last counters
last = first;
last.next = null;
first = firstNode;
}
}
public int getKthFromEnd(int k) {
if(k<0){
throw new NoSuchElementException();
} else if(k==0){
return last.value;
} else if(k>=size) {
throw new NoSuchElementException();
} else {
var firstPointer = first;
var secondPointer = first;
for(int i = 0; i < k ; i++){
secondPointer = secondPointer.next;
}
while(secondPointer != null){
if(secondPointer == last){
return firstPointer.value;
} else {
secondPointer = secondPointer.next;
firstPointer = firstPointer.next;
}
}
}
return -1;
}
private boolean isEmpty(){
return first == null;
}
}
|
Markdown
|
UTF-8
| 1,638
| 3.90625
| 4
|
[
"MIT"
] |
permissive
|
---
layout: article
title: "[Python][學習]function? method?"
key: 20180927
tags: python
---
學東西就是要越學越深入,才會知道自己以前理解的觀點是對是錯,也可以慢慢了解設計者的想法以及定義。
先看看這兩個東西的定義
`
function ——
A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body.
`
`
method —— A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self).
`
function的定義比較廣泛
***「會返回一些值,然後可以傳遞零或多個參數,而且可以用於執行主體」***
method則是基於function的定義在更嚴謹的定義其範圍
***「在類別主體內定義的函數,如果作為該類別實體的屬性使用,該方法將取得實體對像的第一個參數(通常是self)***
其實有時候會覺得這些定義文謅謅到我常常~~懷疑人生~~
不過整體上來說每個程式語言都大同小異,由上述可以理解的是method的定義更明確了,只要是在class產生的instance裡的function有帶第一個參數的,都歸類為method,就算第一個參數不是叫self,他還是會被當作self使用;而function定義比較廣,能被呼叫的通通都算。
-
參考資料
[Python里method和function的区别](https://blog.csdn.net/peachpi/article/details/6047826)
[Python Classes](https://docs.python.org/3/tutorial/classes.html#instance-objects)
|
C
|
UTF-8
| 1,887
| 3.203125
| 3
|
[] |
no_license
|
#include "unp.h" //include appropriate header file(s) for in-built socket functions
#include <time.h> //required to calculate date and time
int main(int argc, char **argv)
{
int listenfd, connfd; //socket IDs; one for the listening socket and one for the connected socket
struct sockaddr_in servaddr; //address structure to hld this server's address
char buff[MAXLINE]; //buffer to hold send data
time_t ticks; //required to calculate date and time
if (argc != 2) //verifies number of command-line args; two in this instance
{
err_quit("usage: <Program Name> <Port No.>");
}
listenfd = Socket(AF_INET, SOCK_STREAM, 0); //create socket
//Note this slightly different to the client code (uses lower case 's') as the
//error checking is wrapped inside a new function called Socket (upper case 's')
bzero(&servaddr, sizeof(servaddr)); // zero and fill in server address structure
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); //connect to any local IP address
servaddr.sin_port = htons(atoi(argv[1])); //daytime server port number
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); // connects the socket to an external interface
Listen(listenfd, LISTENQ); // changes the socket to a "passive listening" socket
for ( ; ; )
{
connfd = Accept(listenfd, (SA *) NULL, NULL); // accept the next connection request from client
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); //construct the data to return to the client
Write(connfd, buff, strlen(buff)); // write data to the client
Close(connfd);
}//end for()
}//end main()
//Note the use of upper-case letters at the start of the socket primitives names. These are wrapper functions that
//include the error checking functionality for each call. The actual socket primitives use lower case names.
|
Markdown
|
UTF-8
| 2,352
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
StreamReaderSeeker
==================
[](https://travis-ci.org/PawelStroinski/StreamReaderSeeker)
Two extension methods of `StreamReader` allowing to `GetPosition` and then to `Seek` back to that position. Furthermore, position can be fine-tuned by number of characters with help of `Position.ShiftByCharacters` method, if needed.
### Example
var fromOneToTenInArmenian = "մեկ երկու երեք չորս հինգ վեց յոթ ութ ինը տասը";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(fromOneToTenInArmenian));
var reader = new StreamReader(stream);
var buffer = new char[5];
reader.Read(buffer, 0, buffer.Length);
var positionAfterReadingFiveChars = reader.GetPosition();
var positionAfterReadingThreeChars = positionAfterReadingFiveChars.ShiftByCharacters(-2);
reader.Seek(positionAfterReadingThreeChars);
reader.Read(buffer, 0, buffer.Length);
var expected = fromOneToTenInArmenian.Substring(3, buffer.Length);
var actual = new string(buffer);
System.Diagnostics.Contracts.Contract.Assert(expected == actual);
There is also too long example in Program.cs.
### How it works
When you invoke `GetPosition`, position is stored as pair of absolute byte position (cannot be amended) and relative character position (can be amended). This character position is necessary because `StreamReader` reads data in chunks decoded to series of characters, not byte-by-byte. So position needs to reflect that.
When you `Seek` to position, this first sets stream position. This is easy. But how to set character position? Well, this is easy too. It just reads that number of characters. So you want to seek by relatively small number of characters but you can seek by infinitely large number of bytes. If you are not using `ShiftByCharacters` you don't have to worry about it, because character position returned from `GetPosition` is never bigger than `StreamReader`'s buffer what is by default not terribly large number.
It works with Unicode also when used encoding allows multiple representations of the same source string.
Don't try to use this with other TextReaders. It wouldn't work.
### Caveat
I only use it in hobby project. So test yourself before you put it into something large.
|
Python
|
UTF-8
| 3,115
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import shutil
import enum
import cv2
from common import get_filenames, read_json, write_json
class KeyStatus(enum.IntEnum):
QUIT = 113
UNDO = 117
OK = 106
FAIL = 102
REMOVE = 100
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', '--input', '-i', required=True,
help='Path to input directory')
parser.add_argument('--output_dir', '--output', '--out', '-o',
default='data/validate',
help='Path to output base directory')
parser.add_argument('--size', '-s', type=float, default=600,
help='Image preview scale')
args = parser.parse_args()
return args
def show_image(src_path, size):
img = cv2.imread(src_path, cv2.IMREAD_COLOR)
img = cv2.resize(img, (size, size))
cv2.imshow('preview', img)
while True:
key = cv2.waitKey(0)
try:
status = KeyStatus(key)
return status
except ValueError:
pass
def main(argv):
args = parse_arguments(argv)
dirname = os.path.basename(args.input_dir)
valid_dir = os.path.join(args.output_dir, dirname, 'valid')
invalid_dir = os.path.join(args.output_dir, dirname, 'invalid')
os.makedirs(valid_dir, exist_ok=True)
os.makedirs(invalid_dir, exist_ok=True)
removed_json = os.path.join(args.output_dir, dirname, '.cache.json')
names = get_filenames(args.input_dir)
valid_names = get_filenames(valid_dir)
invalid_names = get_filenames(invalid_dir)
removed_names = read_json(removed_json)
removed_names = [] if removed_names is None else removed_names
names = sorted(set(names) - set(valid_names) - set(invalid_names)
- set(removed_names))
# Instruction
sys.stdout.write(
'Key input instructions:\n'
'j: Accept current image\n'
'k: Reject current image\n'
'u: Undo recent validation\n'
'd: Exclude image \n'
'q: Quit validation\n'
)
i = 0
while i < len(names):
path = os.path.join(args.input_dir, names[i])
key = show_image(path, args.size)
if key == KeyStatus.UNDO and i > 1:
i -= 1
if os.path.exists(os.path.join(valid_dir, names[i])):
os.remove(os.path.join(valid_dir, names[i]))
elif os.path.exists(os.path.join(invalid_dir, names[i])):
os.remove(os.path.join(invalid_dir, names[i]))
else:
removed_names.pop()
elif key == KeyStatus.OK:
shutil.copyfile(path, os.path.join(valid_dir, names[i]))
i += 1
elif key == KeyStatus.FAIL:
shutil.copyfile(path, os.path.join(invalid_dir, names[i]))
i += 1
elif key == KeyStatus.REMOVE:
removed_names.append(names[i])
write_json(removed_json, removed_names)
i += 1
else:
exit()
if __name__ == '__main__':
main(sys.argv[1:])
|
Java
|
ISO-8859-13
| 2,240
| 2.8125
| 3
|
[] |
no_license
|
package ProfesorOAK;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Conexion {
private static String url= "jdbc:mysql://localhost:3306/pokedex?autoReconnect=true&useSSL=false";
private static String usuario= "root";
private static String password="36344817";
public static Connection conectar() {
Connection conexion=null;
try {
conexion= DriverManager.getConnection(url, usuario, password);
} catch (SQLException e) {
System.out.println("Ocurrio un error al conectar con la base de datos" + e.getMessage());
}
return conexion;
}
public ResultSet visualizar() {
Connection conexion=conectar();
ResultSet rs=null;
try {
PreparedStatement ps= conexion.prepareStatement("Select * from pokemon");
rs=ps.executeQuery();
} catch (Exception e) {
System.out.println("Ocurrio un error en la consulta" + e.getMessage());
}
return rs;
}
public void guardarImagen(String IdPK, String Nombre,String Tipo, String Peso, String Altura, String Habitat, String Categora,String Habilidad, String HabilidadOculta, String EvolucionaDe,String EvolucionaA, String ruta) {
Connection conexion=conectar();
String insert= "insert into pokemon (IdPK,Nombre, Tipo, Peso, Altura, Habitat, Categora, Habilidad, HabilidadOculta, EvolucionaDe, EvolucionaA, foto) values (?,?,?,?,?,?,?,?,?,?,?,?)";
FileInputStream fi= null;
PreparedStatement ps= null;
try {
File file=new File(ruta);
fi=new FileInputStream(file);
ps=conexion.prepareStatement(insert);
ps.setString(1, IdPK);
ps.setString(2, Nombre);
ps.setString(3, Tipo);
ps.setString(4, Peso);
ps.setString(5, Altura);
ps.setString(6, Habitat);
ps.setString(7, Categora);
ps.setString(8, Habilidad);
ps.setString(9, HabilidadOculta);
ps.setString(10, EvolucionaDe);
ps.setString(11, EvolucionaA);
ps.setBinaryStream(12, fi);
ps.executeUpdate();
}catch(Exception e) {
System.out.println("Error al guardar" + e.getMessage());
}
}
}
|
Java
|
UTF-8
| 623
| 2.953125
| 3
|
[] |
no_license
|
package com.example.stacktest;
/**
* 测试
*/
public class Test {
public static void main(String[] arg){
SequenceStack<Integer> stack1 = new SequenceStack<Integer>(3);
SequenceStack<Integer> stack2 = new SequenceStack<Integer>();
System.out.println(stack2.length());
stack2.push(10);
for(int x=0;x<16;x++){
stack2.push(x);
}
System.out.println("栈顶"+stack2.peek());
System.out.println(stack2.toString());
for(int x=0;x<16;x++){
System.out.print(stack2.pop()+",");
}
System.out.println();
}
}
|
C++
|
UTF-8
| 611
| 3.171875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include "stl.h"
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int res = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.size(); i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
int sum = nums[left] + nums[right] + nums[i];
if (sum > target) {
right--;
}
else if (sum < target) {
left++;
}
else {
return target;
}
res = abs(target - sum) < abs(target - res) ? sum : res;
}
}
return res;
}
};
|
Java
|
UTF-8
| 841
| 2.046875
| 2
|
[] |
no_license
|
package ru.alexgryaznov.flproject.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.alexgryaznov.flproject.dao.StopWordRepository;
import ru.alexgryaznov.flproject.domain.StopWord;
@RestController
@RequestMapping("stop-word")
public class StopWordController extends AbstractController<StopWord> {
private final StopWordRepository stopWordRepository;
@Autowired
public StopWordController(StopWordRepository stopWordRepository) {
this.stopWordRepository = stopWordRepository;
}
@Override
protected CrudRepository<StopWord, Integer> getRepository() {
return stopWordRepository;
}
}
|
Python
|
UTF-8
| 566
| 3.03125
| 3
|
[] |
no_license
|
import math, copy, re, hashlib
import itertools as it
def part_1(data):
res = 0
for i in data:
res += i
print(res)
print('END OF PART1')
return
def part_2(data):
res = 0
d = {0:1}
maxi = len(data)
i = 0
while True:
res += data[i]
try:
d[res]
break
except:
d[res] = 1
i = (i + 1) % maxi
print(res)
print('END OF PART2')
return
if __name__ == '__main__':
with open('01_input') as f:
data = f.read()
# data = data.split('\n')
data = list(map(int, data.split()))
part_1(copy.deepcopy(data))
part_2(copy.deepcopy(data))
|
Shell
|
UTF-8
| 2,477
| 3.265625
| 3
|
[] |
no_license
|
#!/bin/sh
m_files=( $(find ./${PRODUCT_NAME} -name '*.m') )
lines=0
ifs=0
unsign=0
for i in ${m_files[@]}; do
lines=$(( $lines + $(wc -l < $i) ))
ifs=$(( $ifs + $(sed -n -e '/^[ \t]*if[ \t]*(/p' $i | wc -l) ))
unsign=$(( $unsign + $(sed -n -e '/^[ \t]*\/\//p' $i | wc -l) ))
unsign=$(( $unsign + $(grep -c ^$ $i) ))
done
if_coef='<key>IfCoef</key><string>'$(bc <<<"scale=4;$ifs/($lines-$unsign)")'</string>'
commit=$(git log --pretty=format:'%H' -n 1)
commit_date='<key>CommitDate</key><string>'$(git log -n 1 --format='%cd')'</string>'
build_tags=( $(git tag | grep "$1\.*") )
from=$commit
to=$(git rev-list --max-parents=0 HEAD)
if [ ${#build_tags[@]} -gt 0 ]; then
from=$(git log ${build_tags[0]} -n 1 --format='%H')
fi
if [ ${#build_tags[@]} -gt 1 ]; then
to=$(git log ${build_tags[1]} -n 1 --format='%H')
fi
if [ $from = $to ]; then
notices[0]=$from
else
notices=( $(git log $from...$to --format='%H') )
if [ $to = $(git rev-list --max-parents=0 HEAD) ]; then
notices=(${notices[@]} $to)
fi
fi
notices_array='<key>Notices</key><array>'
for var in "${notices[@]}"
do
current_notice=$(git log --format=%B -n 1 ${var} | sed "s/\&/\&/;s/>/\>/;s/</\</;s/'/\'/g")
notices_array=$notices_array'<string>'$current_notice'</string>'
done
notices_array=$notices_array'</array>'
xml_head='<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0">'
committer_name='<key>GitUserName</key><string>'$(git config user.name)'</string>'
committer_email='<key>GitUserEmail</key><string>'$(git config user.email)'</string>'
build_time='<key>BuildTime</key><string>'$(date +"%Y-%m-%d %H:%M:%S")'</string>'
version_num='<key>VersionNumber</key><string>'$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${PROJECT_DIR}/${INFOPLIST_FILE}")'</string>'
diff=$(git status --porcelain)
if [ ${#diff} -gt 0 ]; then
isClean='<key>BranchStatus</key><string>Not clean</string>'
else
isClean='<key>BranchStatus</key><string>Clean</string>'
fi
configuration='<key>BuildConfiguration</key><string>'${CONFIGURATION}'</string>'
echo $xml_head'<dict><key>CommitHash</key><string>'$commit'</string>'$commit_date$committer_name$committer_email$build_time$version_num$isClean$configuration$if_coef$notices_array'</dict></plist>' | xmllint --format - >debugInfo.plist
cp debugInfo.plist "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/debugInfo.plist"
|
JavaScript
|
UTF-8
| 362
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import {exec} from "child_process";
/**
* @param {string} command
* @returns {Promise<void>}
*/
export default (command) => new Promise((resolve) => {
console.log(`\u001b[34m${command}\u001b[0m`)
const child = exec(command, {env: process.env});
child.stderr.on("data", data => console.error(data.toString()));
child.on("close", resolve);
});
|
Java
|
UTF-8
| 1,808
| 2.921875
| 3
|
[] |
no_license
|
package cn.edu.gduf.netserver.util;
/**
* 分页工具类
* @author hsg
* 2015/01/22
*/
public class PageUtil {
/**
* 上一页下一页
* @param totalNum
* @param currentPage
* @param pageSize
* @param type
* @return
*/
public static String getUpAndDownPage(int totalNum, int currentPage, int pageSize, int type){
int totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1; // 总页数
StringBuffer pageCode = new StringBuffer();
String up = null;
String down = null;
if (type == 0) { // 显示试卷的上下页
up = "TestPaperServlet?action=testPaperShow&page="+(currentPage-1)+"";
down = "TestPaperServlet?action=testPaperShow&page="+(currentPage+1)+"";
}else if (type == 1) { // 显示考核记录的上下页
up = "ExamServlet?action=examShow&page="+(currentPage-1)+"";
down = "ExamServlet?action=examShow&page="+(currentPage+1)+"";
}
if(currentPage == 1){
pageCode.append("<a href='#'>上一页</a>");
}else{
pageCode.append("<a href='"+up+"'>上一页</a>");
}
pageCode.append("⁄");
if(currentPage == totalPage){
pageCode.append("<a href='#'>下一页</a>");
}else{
pageCode.append("<a href='"+down+"'>下一页</a>");
}
return pageCode.toString();
}
/**
* 当前页和总页数
* @param totalNum
* @param currentPage
* @param pageSize
* @return
*/
public static String getCurrentAndTotalPage(int totalNum, int currentPage, int pageSize){
int totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1; // 总页数
StringBuffer pageCode = new StringBuffer();
pageCode.append("<span>第"+currentPage+"页");
pageCode.append(" , ");
pageCode.append("共"+totalPage+"页</span>");
return pageCode.toString();
}
}
|
Ruby
|
UTF-8
| 5,643
| 2.75
| 3
|
[] |
no_license
|
require 'active_model'
class ChildBenefitTaxCalculator
include ActiveModel::Validations
attr_reader :adjusted_net_income_calculator, :adjusted_net_income, :children_count,
:starting_children, :tax_year
NET_INCOME_THRESHOLD = 50000
TAX_COMMENCEMENT_DATE = Date.parse('7 Jan 2013')
TAX_YEARS = {
"2012" => [Date.parse("2012-04-06"), Date.parse("2013-04-05")],
"2013" => [Date.parse("2013-04-06"), Date.parse("2014-04-05")],
"2014" => [Date.parse("2014-04-06"), Date.parse("2015-04-05")],
"2015" => [Date.parse("2015-04-06"), Date.parse("2016-04-05")],
"2016" => [Date.parse("2016-04-06"), Date.parse("2017-04-05")],
}
validate :valid_child_dates
validates_inclusion_of :tax_year, in: TAX_YEARS.keys.map(&:to_i), message: "select a tax year"
validate :tax_year_contains_at_least_one_child
def initialize(params = {})
@adjusted_net_income_calculator = AdjustedNetIncomeCalculator.new(params)
@adjusted_net_income = calculate_adjusted_net_income(params[:adjusted_net_income])
@children_count = params[:children_count] ? params[:children_count].to_i : 1
@starting_children = process_starting_children(params[:starting_children])
@tax_year = params[:year].to_i
end
def self.valid_date_params?(params)
params && params[:year].present? && params[:month].present? && params[:day].present?
end
def valid_date_params?(params)
self.class.valid_date_params?(params)
end
def monday_on_or_after(date)
date + ((1 - date.wday) % 7)
end
def nothing_owed?
@adjusted_net_income < NET_INCOME_THRESHOLD || tax_estimate.abs == 0
end
def has_errors?
errors.any? || starting_children.select { |c| c.errors.any? }.any?
end
def percent_tax_charge
if @adjusted_net_income >= 60000
100
elsif (59900..59999).cover?(@adjusted_net_income)
99
else
((@adjusted_net_income - 50000) / 100.0).floor
end
end
def child_benefit_start_date
@tax_year == 2012 ? TAX_COMMENCEMENT_DATE : selected_tax_year.first
end
def child_benefit_end_date
selected_tax_year.last
end
def can_calculate?
valid? && !has_errors? && @starting_children.any?
end
def selected_tax_year
TAX_YEARS[@tax_year.to_s]
end
def can_estimate?
@total_annual_income > 0 && can_calculate?
end
def benefits_claimed_amount
all_weeks_children = {}
(child_benefit_start_date...child_benefit_end_date).each_slice(7) do |week|
monday = monday_on_or_after(week.first)
all_weeks_children[monday] = 0
@starting_children.each do |child|
all_weeks_children[monday] += 1 if eligible?(child, tax_year, monday)
end
end
# calculate total for all weeks
total = all_weeks_children.values.inject(0) do |sum, n|
sum + BigDecimal.new(weekly_sum_for_children(n).to_s)
end
total.to_f
end
def tax_estimate
(benefits_claimed_amount * (percent_tax_charge / 100.0)).floor
end
private
def process_starting_children(children)
[].tap do |ary|
@children_count.times do |n|
if children && children[n.to_s] && valid_date_params?(children[n.to_s][:start])
ary << StartingChild.new(children[n.to_s])
else
ary << StartingChild.new
end
end
end
end
def eligible?(child, tax_year, week_start_date)
eligible_for_tax_year?(child, tax_year) &&
days_include_week?(child.adjusted_start_date, child.benefits_end, week_start_date)
end
def eligible_for_tax_year?(child, tax_year)
if tax_year == 2012
!(Date.parse('1 April 2013')..Date.parse('5 April 2013')).cover?(child.start_date)
else
!(Date.parse("31 March #{tax_year + 1}")..Date.parse("5 April #{tax_year + 1}")).cover?(child.start_date)
end
end
def days_include_week?(start_date, end_date, week_start_date)
if start_date.nil?
end_date >= week_start_date
elsif end_date.nil?
start_date <= week_start_date
else
(start_date..end_date).cover?(week_start_date)
end
end
def weekly_sum_for_children(num_children)
rate = ChildBenefitRates.new(tax_year)
if num_children > 0
rate.first_child_rate + (num_children - 1) * rate.additional_child_rate
else
0
end
end
def taxable_weeks
if @tax_year == 2012
# special case for 2012-13, only weeks from 7th Jan 2013 are taxable
benefit_taxable_weeks(Date.parse("2013-01-07"), child_benefit_end_date)
else
benefit_taxable_weeks(child_benefit_start_date, child_benefit_end_date)
end
end
def benefit_taxable_weeks(start_date, end_date)
((end_date - start_date) / 7).floor
end
def calculate_adjusted_net_income(adjusted_net_income)
if @adjusted_net_income_calculator.can_calculate?
@adjusted_net_income_calculator.calculate_adjusted_net_income
elsif adjusted_net_income.present?
adjusted_net_income.gsub(/[£, -]/, '').to_i
end
end
def parse_child_date(date)
Date.new(date[:year].to_i, date[:month].to_i, date[:day].to_i)
end
def valid_child_dates
@starting_children.each(&:valid?)
end
def tax_year_contains_at_least_one_child
return unless selected_tax_year.present? && @starting_children.select(&:valid?).any?
in_tax_year = @starting_children.reject { |c| c.start_date.nil? || c.start_date > selected_tax_year.last || (c.end_date.present? && c.end_date < selected_tax_year.first) }
if in_tax_year.empty?
@starting_children.first.errors.add(:end_date, "You haven't received any Child Benefit for the tax year selected. Check your Child Benefit dates or choose a different tax year.")
end
end
end
|
Java
|
UTF-8
| 2,734
| 1.9375
| 2
|
[] |
no_license
|
package com.yc.bean;
import java.io.Serializable;
public class Message extends CommonBean implements Serializable {
private static final long serialVersionUID = -3042360926416388190L;
private Integer mid;
private String content;
private Integer mweight;
private String createtime;
private Integer fid;
private Integer did;
private Integer gid;
private Integer uid;
private Integer fromuid;
private String fromuname;
private String touname;
private String fname;
private String gname;
private String department;
public String getFromuname() {
return fromuname;
}
public void setFromuname(String fromuname) {
this.fromuname = fromuname;
}
public String getTouname() {
return touname;
}
public void setTouname(String touname) {
this.touname = touname;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Integer getFromuid() {
return fromuid;
}
public void setFromuid(Integer fromuid) {
this.fromuid = fromuid;
}
public Integer getMid() {
return mid;
}
public void setMid(Integer mid) {
this.mid = mid;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getMweight() {
return mweight;
}
public void setMweight(Integer mweight) {
this.mweight = mweight;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public Integer getFid() {
return fid;
}
public void setFid(Integer fid) {
this.fid = fid;
}
public Integer getDid() {
return did;
}
public void setDid(Integer did) {
this.did = did;
}
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
@Override
public String toString() {
return "Message [mid=" + mid + ", content=" + content + ", mweight=" + mweight + ", createtime=" + createtime
+ ", fid=" + fid + ", did=" + did + ", gid=" + gid + ", uid=" + uid + ", fromuid=" + fromuid
+ ", fromuname=" + fromuname + ", touname=" + touname + ", fname=" + fname + ", gname=" + gname
+ ", department=" + department + "]";
}
}
|
C++
|
UTF-8
| 2,155
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
// Simple example for EffectMixer. Mixers let you run multiple effects, and they
// handle concurrent rendering on multiple CPU cores.
#include "lib/effect_runner.h"
#include "lib/effect_mixer.h"
#include "lib/tinydir.h"
#include "video.h"
#include "particle_trail.h"
#include "rings.h"
int main(int argc, char **argv)
{
EffectMixer mixer;
VideoEffect video("/Users/matt//active/video/queue/");
mixer.add(&video);
EffectRunner r;
r.setEffect(&mixer);
r.setMaxFrameRate(30);
r.setLayout("../../../Active/layout/layout-60x24.json");
if (!r.parseArguments(argc, argv)) {
return 1;
}
float state = 0;
while (true) {
EffectRunner::FrameStatus frame = r.doFrame();
const float speed = 10.0f; //FAST
// const float speed = 0.001f; //SLOW
/*
// Animate the mixer's fader controls
state = fmod(state + frame.timeDelta * speed, 2 * M_PI);
for (int i = 0; i < mixer.numChannels(); i++) {
float theta = state + i * (2 * M_PI) / mixer.numChannels();
mixer.setFader(i, std::max(0.0f, sinf(theta)));
}
*/
// Animate the mixer's fader controls
///*
state = fmod(state + frame.timeDelta * speed, mixer.numChannels());
for (int i = 0; i < mixer.numChannels(); i++) {
mixer.setFader(i, 0.0);
//float remainder = state - i;
// is this state
if ( i == (int)state) {
mixer.setFader(i, 1.0);
}
/* // is next state
int nextState = (int) state;
nextState += 1;
nextState % mixer.numChannels();
if (i == nextState) {
mixer.setFader(i, 1-remainder);
}
*/
// float theta = state + i * (2 * M_PI) / mixer.numChannels();
// mixer.setFader(i, std::max(0.0f, sinf(theta)));
}
// */
// Main loops and Effects can both generate verbose debug output (-v command line option)
if (frame.debugOutput) {
fprintf(stderr, "\t[video] state = %f\n", state);
}
}
}
|
TypeScript
|
UTF-8
| 4,019
| 2.78125
| 3
|
[] |
no_license
|
import { CurrentSchedule, Variable } from '../models';
import {SoftConstraint} from '../types';
import { SchedulerContextData } from '.';
export const getVariablePicker = (pickingMethod: string, data: { schedulerContextData: SchedulerContextData }): VariablePicker => {
switch(pickingMethod) {
case 'first-unAssigned':
return new FirstUnAssigned(data);
case 'costs':
return new CostBasedVariablePicker(data);
case 'min-values':
return new MinValuesBasedVariablePicker(data);
case 'average-domain-costs':
return new AverageDomainCostsVariablePicker(data);
}
};
export abstract class VariablePicker {
variables: Variable[];
currentSchedule: CurrentSchedule;
softConstraints: SoftConstraint[];
data: { schedulerContextData: SchedulerContextData };
constructor(data: { schedulerContextData: SchedulerContextData }) {
this.data = data;
this.variables = data.schedulerContextData.variables;
this.currentSchedule = data.schedulerContextData.currentSchedule;
this.softConstraints = data.schedulerContextData.softConstraints;
};
abstract pick(): Variable;
};
export class CostBasedVariablePicker extends VariablePicker {
pick = (): Variable => {
let min = Number.MAX_SAFE_INTEGER;
let selectedVariable: Variable;
for (let variable of this.variables) {
if (!variable.hasAssignedValue()) {
let availableGroupsCount = variable.availableDomainGroups().length;
if (availableGroupsCount === 1) {
selectedVariable = variable;
break;
}
variable.updateDomainCosts(this.data);
if (variable.domain[0].cost < min) {
selectedVariable = variable;
min = variable.domain[0].cost;
}
}
}
return selectedVariable;
};
};
class MinValuesBasedVariablePicker extends VariablePicker {
pick = (): Variable => {
let min = Number.MAX_SAFE_INTEGER;
let selectedVariable: Variable;
this.variables.forEach((variable) => {
if (!variable.hasAssignedValue() && variable.availableDomainGroups().length < min) {
selectedVariable = variable;
min = variable.domain.length;
}
});
selectedVariable.updateDomainCosts(this.data);
return selectedVariable;
};
};
class AverageDomainCostsVariablePicker extends VariablePicker {
pick = (): Variable => {
let variablesMap: { values: number; variable: Variable; }[] = [];
let max = Number.MIN_SAFE_INTEGER;
let inferences = false;
let selectedVariable: Variable;
for (let variable of this.variables) {
if (!variable.hasAssignedValue()) {
let availableGroupsCount = variable.availableDomainGroups().length;
if (availableGroupsCount === 1) {
selectedVariable = variable;
inferences = true;
break;
}
variable.updateDomainCosts(this.data);
let averageDomainCosts = variable.availableDomainGroups().reduce(
(accumalator, courseGroup) => {
return accumalator + courseGroup.cost
},
0 ) / availableGroupsCount;
// let values = 0;
// variable.availableDomainGroups().forEach((group) => {
// if (group.cost <= averageDomainCosts) {
// values++;
// }
// });
// variablesMap.push({ values, variable });
if (averageDomainCosts > max) {
max = averageDomainCosts;
selectedVariable = variable;
}
}
}
// if (!inferences) {
// variablesMap.sort((a, b) => a.values - b.values);
// selectedVariable = variablesMap[0].variable;
// }
return selectedVariable;
}
};
class FirstUnAssigned extends VariablePicker {
pick = (): Variable => {
let selectedVariable: Variable;
for(let variable of this.variables) {
if(!variable.hasAssignedValue()) {
selectedVariable = variable;
break;
}
}
selectedVariable.updateDomainCosts(this.data);
return selectedVariable;
};
};
|
Python
|
UTF-8
| 305
| 2.859375
| 3
|
[] |
no_license
|
while True :
fr = open("pid_K.txt", "r")
lines = fr.readlines()
Theta = int(lines[0])
KP = int(lines[1])
KI = int(lines[2])
KD = int(lines[3])
print("Theta : %d" %Theta)
print("KP : %d" %KP)
print("KI : %d" %KI)
print("KD : %d" %KD)
print("-------------")
|
JavaScript
|
UTF-8
| 7,188
| 2.953125
| 3
|
[] |
no_license
|
// ------ updates progress bar and filter buttons
$(document).on('updateProgress', function(){
//count missions
var number_undone = $('.mission-undone .circle-mid').length
var number_wait = $('.mission-wait .circle-mid').length
var number_done = $('.mission-done .circle-mid').length
var number_total = number_undone + number_wait + number_done
//width of progress bars
$('.progress-wait').width(100*(number_done+number_wait)/number_total + '%');
$('.progress-done').width(100*number_done/number_total + '%');
//show numbers on filter buttons
$('.show-all span').text(number_total)
$('.show-undone span').text(number_undone)
$('.show-wait span').text(number_wait)
$('.show-done span').text(number_done)
})
// ----- show week missions
//appends one STATE missions assigned for this DAY to HTML
function appendMission(day, stateMissions,stateName){
// for Monday dayNumber = 0
var dayNumber=day.getUTCDay()
// index of day class
var dayIndex=$('.day').eq(dayNumber)
stateMissions.forEach(function(missionId){
//finds mission index by missionId
var missionIndex = findUserMission(missionId)
dayIndex.find('.small-mission-'+stateName).append($('<li class="circle-small"></li>'))
dayIndex.find('.mission-'+stateName).append($('<li class="circle-mid" name='+missionId+'><img src=' + userMissions[missionIndex].icon +'>'+starSvg+'<span>'+userMissions[missionIndex].points+'</li>'))
})
}
//append ALL missions assigned for this DAY to HTML
function showDay(day){
// get from database mission type assigned for this day and appends to HTML
appendMission(day, getUndoneMissions(day),'undone')
appendMission(day, getWaitMissions(day),'wait')
appendMission(day, getDoneMissions(day),'done')
}
//appends ALL missions assigned for this WEEK to HTML
$(document).on('showWeek', function (event){
//clear all missions
$('.day li').remove()
//first day of the week
var startDay=currentDate;
var startDayMonth = monthName[startDay.getMonth()]
//last day of the week
var endDay = new Date(startDay);
endDay.setDate(startDay.getDate()+6);
var endDayMonth=monthName[endDay.getMonth()]
//show DAY by DAY
for (i = 0; i < 7; i++) {
var oneDay= new Date(startDay)
oneDay.setDate(startDay.getDate()+i);
showDay(oneDay)
}
//update progress bar
$(document).trigger('updateProgress');
//update week name
if (startDayMonth==endDayMonth) {
$('.week a').text(startDay.getDate()+ ' - '+ endDay.getDate() + ' '+ endDayMonth)
} else {
$('.week a').text(startDay.getDate()+ ' ' + startDayMonth+ ' - '+ endDay.getDate() + ' '+ endDayMonth)
}
//update filter view
$(document).trigger('updateFilterView');
})
// ----- change week
//week before
$('.week span').eq(0).on('click',function(){
currentDate.setDate(currentDate.getDate()-7)
$(document).trigger('showWeek')
})
//week after
$('.week span').eq(1).on('click',function(){
currentDate.setDate(currentDate.getDate()+7)
$(document).trigger('showWeek')
})
// ----- filtering
// click event on all filter buttons
$('.show-undone').on('click',function(){showOnly(this,'undone')})
$('.show-wait').on('click',function(){showOnly(this,'wait')})
$('.show-done').on('click',function(){showOnly(this,'done')})
$('.show-all').on('click',function(){showAll(this)})
//show only type missions in details mode
function showOnly(button,type) {
//turn off day detials buttons
turnOffDayButtons()
//remember which button clicked
$('.filter button').removeClass('selected')
$(button).addClass('selected')
//first hide everything
$('.day, .day-line, .day-details ul').hide()
$('.day-details').show()
//show only days that are not empty
$('.day .mission-'+ type +' li').parents('.day').show()
$('.mission-' + type).show()
if (!kidMode()){
if ($('button.show-wait').hasClass('selected')){
$('button.acceptAll').show()
} else {
$('button.acceptAll').hide()
}
if ($('button.show-undone').hasClass('selected')){
$('button.doneAll').show()
} else {
$('button.doneAll').hide()
}
}
}
// show all missions but without details
function showAll(button) {
//turn on day details buttons
turnOnDayButtons();
//remember which button clicked
$('.filter button').removeClass('selected')
$(button).addClass('selected')
$('.day, .day-line, .day-details ul').show()
$('.day-details').hide()
$('button.acceptAll, button.doneAll').hide()
}
function turnOnDayButtons(){
//add arrow down sign
$('.day>p span').html('▼');
//turn off all actions on click (no click cumulation)
$('.day>p').off('click')
$(document).off('click','.day-line')
//turn on day details button
$('.day>p').on('click',function(){showDayDetails(this)})
$(document).on('click','.day-line',function(){showDayDetails2(this)})
}
function turnOffDayButtons(){
//turn off all actions on click
$('.day>p').off('click')
//remove arrow down sign
$('.day>p span').html('');
//remove color from day buttons
$('.day>p').removeClass('selected')
}
// show day details
function showDayDetails(dayButton){
var dayDetails = $(dayButton).parents('.day').children('.day-details')
if (dayDetails.is(":hidden")) {
//slowly show
dayDetails.slideDown('slow')
//change arrow type and background
$(dayButton).children('span').html('▲')
$(dayButton).addClass('selected')
} else {
//slowly hide
dayDetails.slideUp('slow')
//change arrow type
$(dayButton).children('span').html('▼')
$(dayButton).removeClass('selected')
}
}
//the same us above, but allows to click on line and not the button
function showDayDetails2(dayLine){
var dayDetails = $(dayLine).parents('.day').children('.day-details');
var dayButton = $(dayLine).parents('.day').find('p');
if (dayDetails.is(":hidden")) {
//slowly show
dayDetails.slideDown('slow')
//change arrow type and background
$(dayButton).children('span').html('▲')
$(dayButton).addClass('selected')
} else {
//slowly hide
dayDetails.slideUp('slow')
//change arrow type
$(dayButton).children('span').html('▼')
$(dayButton).removeClass('selected')
}
}
//clicks one more time filter button
//important becacuse filter hides days where no missions
$(document).on('updateFilterView',function(){
$('button').each(function(index){
//except of first button
if (index>0){
if ($(this).hasClass('selected')) {
$(this).trigger('click')
}
}
})
})
// ----- automatically starts after launching page
//keeps currently visible week day
var today = new Date();
today.setHours(0,0,0,0)
//go to monday
var currentDate =new Date(today);
currentDate.setDate(today.getDate()-today.getUTCDay())
//show all missions assigned for this week
$(document).trigger('showWeek')
$(document).trigger('noFilterMode')
$('.show-all').trigger('click')
|
C++
|
UTF-8
| 1,010
| 3.65625
| 4
|
[] |
no_license
|
#include"stack.h"
void stackInit(stackI *stackP, int maxSize)
{
stackElementsI *newContents;
/*Allocate memory in heap to hold the contents*/
newContents = (stackElementsI*) malloc(sizeof(stackElementsI)*maxSize);
if(newContents == NULL)
{
fprintf(stderr,"Insufficiant memory to allocate stack");
exit(1);
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1;//empty
}
void StackDestroy(stackI *stackP)
{
free(stackP->contents);
stackP->maxSize = 0;
stackP->top = -1;
}
int StackIsEmpty(stackI *stackP)
{
return stackP->top < 0;
}
int StackIsFull(stackI *stackP)
{
return stackP->top >= stackP->maxSize-1;
}
void StackPush(stackI *stackP,stackElementsI element)
{
if(StackIsFull(stackP))
{
fprintf(stderr,"Stack is full.\n");
exit(1);
}
stackP->contents[++stackP->top] = element;
}
int StackPop(stackI *stackP)
{
if(StackIsEmpty(stackP))
{
fprintf(stderr,"Stack is Empty.\n");
exit(1);
}
return stackP->contents[stackP->top--];
}
|
Python
|
UTF-8
| 170
| 3.828125
| 4
|
[] |
no_license
|
# The while loop runs as long as or while, a certain conditional is true.
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
|
Java
|
UTF-8
| 3,080
| 2.65625
| 3
|
[] |
no_license
|
package animal.editor.graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeListener;
import animal.editor.Editor;
import animal.editor.graphics.meta.FillablePrimitiveEditor;
import animal.graphics.PTGraphicObject;
import animal.graphics.PTPoint;
import animal.graphics.PTPolygon;
import animal.misc.EditPoint;
import animal.misc.EditableObject;
import animal.misc.MSMath;
/**
* Editor for a Polygon
*
* @author <a href="http://www.algoanim.info/Animal2/">Guido
* Rößling</a>
* @version 2.5 2008-06-23
*/
public class PolygonEditor extends FillablePrimitiveEditor implements
ItemListener, ActionListener, PropertyChangeListener {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = -2413776784253970663L;
public PolygonEditor() {
super();
}
public int pointsNeeded() {
return -1;
}
public boolean nextPoint(int num, Point p) {
PTPolygon pl = (PTPolygon) getCurrentObject();
pl.setNode(num - 1, new PTPoint(p));
return true;
} // nextPoint;
public int getMinDist(PTGraphicObject go, Point p) {
PTPolygon pg = (PTPolygon) go;
// if the polyline is a filled polygon and the point is inside
// there is not much of distance
if (pg.isFilled()) {
Polygon poly = pg.toPolygon();
if (poly.contains(p))
return 0;
}
Point a;
Point b = pg.getNodeAsPoint(0);
int minDist = Integer.MAX_VALUE;
int newDist;
// iterate all edges of the polyline
for (int i = 1; i < pg.getNodeCount(); i++) {
a = b;
b = pg.getNodeAsPoint(i);
if (!a.equals(b) && (newDist = MSMath.dist(p, a, b)) < minDist)
minDist = newDist;
}
return minDist;
}
public EditPoint[] getEditPoints(PTGraphicObject go) {
PTPolygon pg = (PTPolygon) go;
int pSize = pg.getNodeCount();
int size = pSize * 2 - 1;
int i;
// add change points(nodes)
EditPoint[] result = new EditPoint[size];
for (i = 0; i < pSize; i++)
result[i] = new EditPoint(i + 1, pg.getNodeAsPoint(i));
// add move points(points halfway the edges
Point a;
Point b;
b = pg.getNodeAsPoint(0);
for (i = 1; i < pSize; i++) {
a = b;
b = pg.getNodeAsPoint(i);
result[i + pSize - 1] = new EditPoint(-i, new Point((a.x + b.x) / 2,
(a.y + b.y) / 2));
}
return result;
} // getEditPoints
public EditableObject createObject() {
PTPolygon pg = new PTPolygon();
storeAttributesInto(pg);
return pg;
}
public Editor getSecondaryEditor(EditableObject go) {
PolygonEditor result = new PolygonEditor();
// important! result must be of type PolygonEditor(or casted)
// and the parameter passed must be of type PTPolygon.
// Otherwise, not all attributes are copied!
result.extractAttributesFrom(go);
return result;
}
public String getBasicType() {
return PTPolygon.POLYGON_TYPE;
}
} // PolygonEditor
|
Ruby
|
UTF-8
| 3,662
| 2.53125
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
# Copyright 2016 Matt Wrock <matt@mattwrock.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'nori'
require_relative 'powershell_output_decoder'
require_relative 'message_defragmenter'
module WinRM
module PSRP
# Class for reading powershell responses in Receive_Response messages
class ReceiveResponseReader < WSMV::ReceiveResponseReader
# Creates a new ReceiveResponseReader
# @param transport [HttpTransport] The WinRM SOAP transport
# @param logger [Logger] The logger to log diagnostic messages to
def initialize(transport, logger)
super
@output_decoder = PowershellOutputDecoder.new
end
# Reads PSRP messages sent in one or more receive response messages
# @param wsmv_message [WinRM::WSMV::Base] A wsmv message to send to endpoint
# @param wait_for_done_state whether to poll for a CommandState of Done
# @yield [Message] PSRP Message in response
# @yieldreturn [Array<Message>] All messages in response
def read_message(wsmv_message, wait_for_done_state = false)
messages = []
defragmenter = MessageDefragmenter.new
read_response(wsmv_message, wait_for_done_state) do |stream|
message = defragmenter.defragment(stream[:text])
next unless message
if block_given?
yield message
else
messages.push(message)
end
end
messages unless block_given?
end
# Reads streams and returns decoded output
# @param wsmv_message [WinRM::WSMV::Base] A wsmv message to send to endpoint
# @yieldparam [string] standard out response text
# @yieldparam [string] standard error response text
# @yieldreturn [WinRM::Output] The command output
def read_output(wsmv_message)
with_output do |output|
read_message(wsmv_message, true) do |message|
exit_code = find_exit_code(message)
output.exitcode = exit_code if exit_code
decoded_text = @output_decoder.decode(message)
next unless decoded_text
out = { stream_type(message) => decoded_text }
output << out
yield [out[:stdout], out[:stderr]] if block_given?
end
end
end
private
def stream_type(message)
type = :stdout
case message.type
when WinRM::PSRP::Message::MESSAGE_TYPES[:error_record]
type = :stderr
when WinRM::PSRP::Message::MESSAGE_TYPES[:pipeline_host_call]
type = :stderr if message.data.include?('WriteError')
when WinRM::PSRP::Message::MESSAGE_TYPES[:pipeline_state]
type = :stderr if message.parsed_data.pipeline_state == WinRM::PSRP::MessageData::PipelineState::FAILED
end
type
end
def find_exit_code(message)
parsed = message.parsed_data
return nil unless parsed.is_a?(MessageData::PipelineHostCall)
parsed.method_parameters[:i32].to_i if parsed.method_identifier == 'SetShouldExit'
end
end
end
end
|
Java
|
UTF-8
| 513
| 2.09375
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cz.fi.muni.pa165.serviceImpl;
import cz.fi.muni.pa165.api.dto.MissionDTO;
import cz.fi.muni.pa165.api.dto.RoleDTO;
/**
*
* @author Filip
*/
public class NewMain {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
RoleServiceImpl rsi = new RoleServiceImpl();
RoleDTO role = new RoleDTO();
rsi.createRole(role);
}
}
|
Python
|
UTF-8
| 107
| 3.28125
| 3
|
[] |
no_license
|
num = float(raw_input())
chocolates = 1
while num >= 2.0:
num /= 2
chocolates *= 4
print chocolates
|
SQL
|
UTF-8
| 3,270
| 3.015625
| 3
|
[
"Apache-2.0",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-unicode",
"LGPL-2.0-or-later",
"EPL-1.0",
"Classpath-exception-2.0",
"GPL-1.0-or-later",
"CC-BY-SA-3.0",
"CPL-1.0",
"LicenseRef-scancode-generic-cla",
"SAX-PD",
"EPL-2.0",
"LicenseRef-scancode-free-unknown",
"CC-PDDC",
"CDDL-1.0",
"GPL-2.0-only",
"GCC-exception-3.1",
"xpp",
"LGPL-2.1-only",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-generic-export-compliance",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"NAIST-2003",
"Apache-1.1",
"CC0-1.0",
"CDDL-1.1",
"W3C",
"MPL-1.1",
"ICU",
"WTFPL",
"LGPL-2.1-or-later",
"BSD-2-Clause"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CREATE TABLE `linkis_ps_instance_label` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`label_key` varchar(32) COLLATE utf8_bin NOT NULL COMMENT 'string key',
`label_value` varchar(255) COLLATE utf8_bin NOT NULL COMMENT 'string value',
`label_feature` varchar(16) COLLATE utf8_bin NOT NULL COMMENT 'store the feature of label, but it may be redundant',
`label_value_size` int(20) NOT NULL COMMENT 'size of key -> value map',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp',
PRIMARY KEY (`id`),
UNIQUE KEY `label_key_value` (`label_key`,`label_value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `linkis_ps_instance_label_value_relation` (
`label_value_key` varchar(255) COLLATE utf8_bin NOT NULL COMMENT 'value key',
`label_value_content` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT 'value content',
`label_id` int(20) DEFAULT NULL COMMENT 'id reference linkis_ps_instance_label -> id',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp',
UNIQUE KEY `label_value_key_label_id` (`label_value_key`,`label_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `linkis_ps_instance_label_relation` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`label_id` int(20) DEFAULT NULL COMMENT 'id reference linkis_ps_instance_label -> id',
`service_instance` varchar(64) NOT NULL COLLATE utf8_bin COMMENT 'structure like ${host|machine}:${port}',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `linkis_ps_instance_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`instance` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT 'structure like ${host|machine}:${port}',
`name` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT 'equal application name in registry',
`update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'update unix timestamp',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'create unix timestamp',
PRIMARY KEY (`id`),
UNIQUE KEY `instance` (`instance`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
|
Java
|
UTF-8
| 1,347
| 3.984375
| 4
|
[] |
no_license
|
package IO常用类库.File类的使用;
import java.io.File;
import java.util.Scanner;
/**
* @author : S K Y
* @version :0.0.1
*/
public class ListAllFileDemo {
public static void main(String[] args) {
//设置任意一个目录的路径,而后将这个目录中所有文件的信息都进行打印输出处理
//可以采用递归的方法来实现
Scanner scanner = new Scanner(System.in);
String dir = scanner.next();
File file = new File(dir);
if (!file.isDirectory()) {
System.out.println("当前输入的路径并不是一个文件夹路径");
} else {
listDir(file, 1);
}
}
/**
* 列出当前输入文件目录的所有文件列表
*
* @param file 当前的文件夹路径
* @param index 请输入1
*/
public static void listDir(File file, int index) {
File thisFile = file; //当前的文件路径
StringBuilder tab = new StringBuilder(); //间隔处理符
File[] files = thisFile.listFiles();
for (int i = 0; i < index - 1; i++) {
tab.append(" ");
}
for (File f : files) {
System.out.println(tab.toString() + f);
if (f.isDirectory()) {
listDir(f, index++);
}
}
}
}
|
C++
|
UTF-8
| 618
| 3.046875
| 3
|
[] |
no_license
|
#ifndef EASYFIND_HPP
#define EASYFIND_HPP
#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
class NotFoundException : public std::exception {
virtual const char* what() const throw() {
return "Not found";
}
};
template <template <class, class> class Container>
typename Container<int, std::allocator<int> >::iterator
easyfind(Container<int, std::allocator<int> > & cont, int num) {
typename Container<int, std::allocator<int> >::iterator it;
if ((it = std::find(cont.begin(), cont.end(), num)) != cont.end()) {
return it;
}
throw NotFoundException();
}
#endif /* EASYFIND_HPP */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.