language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 1,823 | 2.53125 | 3 | [
"MIT"
] | permissive | using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using BirdMessenger;
using BirdMessenger.Collections;
using BirdMessenger.Infrastructure;
namespace demo3
{
class Program
{
static async Task Main(string[] args)
{
var stream = new MemoryStream(1024 * 1024 * 32);
for(var i = 0; i < 1024 * 1024 * 32; i++) {
stream.Write(Encoding.UTF8.GetBytes(BitConverter.ToString(new byte[] { (byte)i }), 0, 2));
}
//reset position
stream.Position = 0;
// remote tus service
var hostUri = new Uri(@"http://localhost:5000/files");
// build a standalone tus client instance
var tusClient = TusBuild.DefaultTusClientBuild(hostUri)
.Build();
//hook up events
tusClient.UploadProgress += printUploadProcess;
tusClient.UploadFinish += uploadFinish;
//define additional file metadata
MetadataCollection metadata = new MetadataCollection();
//create upload url
var uploadUrl = await tusClient.Create(stream.Length, metadata);
//upload file
var uploadResult = await tusClient.Upload(uploadUrl, stream, null);
}
public static void printUploadProcess(ITusClient src, ITusUploadContext context)
{
Console.WriteLine($"finished:fileUri:{context.UploadUrl}-{context.UploadedSize},total:{context.TotalSize} ");
}
public static void uploadFinish(ITusClient src, ITusUploadContext context)
{
Console.WriteLine($"uploadfinish :{context.UploadUrl.ToString()}");
}
}
} |
Markdown | UTF-8 | 1,328 | 2.875 | 3 | [
"MIT"
] | permissive | # material-colors
Java Material Design Colors (color/string)
[](https://jitpack.io/#fcannizzaro/material-colors)
## Dependence
### Gradle
```gradle
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
compile 'com.github.fcannizzaro:material-colors:0.1.0'
}
```
### Maven
```xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.fcannizzaro</groupId>
<artifactId>material-colors</artifactId>
<version>0.1.0</version>
</dependency>
</dependencies>
```
### Download JAR
[Release 0.1.0](https://github.com/fcannizzaro/material-colors/releases/tag/0.1.0)
## Usage
```java
// awt.Color
Color primary = Colors.indigo_500.asColor();
// String
String primary_dark = Colors.indigo_700.asString();
```
## Usage with [Resourcer](https://github.com/fcannizzaro/resourcer)
Use color name in xml files!
```xml
<?xml version="1.0"?>
<resources>
<color name="primary">@color/indigo_500</color>
<color name="accent" >@color/pink_accent_400</color>
</resources>
```
## Screenshot

|
JavaScript | UTF-8 | 209 | 3.078125 | 3 | [] | no_license |
avrg1 = (4+10+22+(-30)+55)/5;
avrg2 = (68+7+(-22)+9+100)/5;
avrg = (avrg1+avrg2)/2;
console.log("First average is " + avrg1)
console.log("Second average is " + avrg2)
console.log("Both averages are " + avrg) |
Java | UTF-8 | 132 | 2.0625 | 2 | [] | no_license | class Ar
{
public static void main(String arg[])
{
int a[]={1,2, 3,9};
for(Integer i:a)
{
System.out.println(i);
}
}
} |
Python | UTF-8 | 3,091 | 3.296875 | 3 | [] | no_license | """
Open and close time calculations
for ACP-sanctioned brevets
following rules described at https://rusa.org/octime_alg.html
and https://rusa.org/pages/rulesForRiders
"""
import arrow
# Note for CIS 322 Fall 2016:
# You MUST provide the following two functions
# with these signatures, so that I can write
# automated tests for grading. You must keep
# these signatures even if you don't use all the
# same arguments. Arguments are explained in the
# javadoc comments.
#
max_speed = {200: 34, 400: 32, 600:30, 1000: 28, 1300: 26}
min_speed = {200: 15, 400: 15, 600:15, 1000: 11.428, 1300:13.333}
def open_time(control_dist_km, brevet_dist_km, brevet_start_time):
"""
Args:
control_dist_km: number, the control distance in kilometers
brevet_dist_km: number, the nominal distance of the brevet
in kilometers, which must be one of 200, 300, 400, 600,
or 1000 (the only official ACP brevet distances)
brevet_start_time: An ISO 8601 format date-time string indicating
the official start time of the brevet
Returns:
An ISO 8601 format date string indicating the control open time.
This will be in the same time zone as the brevet start time.
"""
if control_dist_km == 0:
return brevet_start_time.isoformat()
elif control_dist_km < 0:
return "Invalid date"
time = 0.0
distance = 0
for bre in max_speed:
spd = max_speed.get(bre)
if (int(control_dist_km) >= bre):
time += 200/spd
distance = bre
else:
lo = control_dist_km - distance
time += (lo/spd)
break
time = round(time * 60) #convert into minutes
arw = arrow.get(brevet_start_time)
arw = arw.shift(minutes=+time)
return arw.isoformat()
def close_time(control_dist_km, brevet_dist_km, brevet_start_time):
"""
Args:
control_dist_km: number, the control distance in kilometers
brevet_dist_km: number, the nominal distance of the brevet
in kilometers, which must be one of 200, 300, 400, 600, or 1000
(the only official ACP brevet distances)
brevet_start_time: An ISO 8601 format date-time string indicating
the official start time of the brevet
Returns:
An ISO 8601 format date string indicating the control close time.
This will be in the same time zone as the brevet start time.
"""
if control_dist_km == 0:
return brevet_start_time.isoformat()
elif control_dist_km < 0:
return "Invalid date"
time = 0.0
distance = 0
for bre in min_speed:
spd = min_speed.get(bre)
if (int(control_dist_km) >= bre):
time += 200/spd
distance = bre
else:
lo = control_dist_km - distance
time += (lo/spd)
break
print("hour is ", time)
time = round(time * 60) #convert into minutes
arw = arrow.get(brevet_start_time)
arw = arw.shift(minutes=+time)
return arw.isoformat()
|
C++ | UTF-8 | 1,840 | 3 | 3 | [] | no_license | #ifndef SERVER_HPP
#define SERVER_HPP
#include <boost/asio.hpp>
#include <memory>
#include <fstream>
#include <atomic>
#include "http.hpp"
#include "cache.hpp"
#include "mutex.hpp"
/** A caching web server.
*/
class Server {
/** The io_service object used by all
* boost::asio objects.
*/
boost::asio::io_service io_service;
/** acceptor can accept connections.
*/
boost::asio::ip::tcp::acceptor acceptor;
/** The set of signals that the server will catch.
* On catching any of these signals,
* the server will gracefully exit.
*/
boost::asio::signal_set signal_set;
/** The counter for generating unique IDs.
* It is a size_t wrapped by std::atomic
* because multiple threads will be incrementing
* it simultaneously.
*/
std::atomic<size_t> id_counter;
public:
/** Item to be stored in the cache. */
struct CacheItem {
HttpMessage message;
ResponseCacheInfo info;
};
/** Type of the cache. */
typedef Cache<std::string, std::shared_ptr<CacheItem> > cache_type;
/** Type of the log.
* It is synchronized with a mutex because
* multiple threads will write to it.
*/
typedef mutex_synchronized<std::ofstream> log_type;
/** Type of the lock_guard for the log. */
typedef std::lock_guard<log_type> log_guard;
/** resolver can translate hostname and service name
* into IP address and port number.
*/
boost::asio::ip::tcp::resolver resolver;
cache_type cache; /**< The cache storing responses. */
log_type& log; /**< The message log. */
Server(uint16_t, size_t, log_type&);
Server(const Server&) = delete;
void run();
/** Return a reference to io_service. */
boost::asio::io_service& get_io_service()
{
return io_service;
}
size_t new_id();
private:
void start_accept();
void work_thread();
void finish(const boost::system::error_code&, int);
};
#endif /* SERVER_HPP */
|
C | UTF-8 | 19,800 | 2.796875 | 3 | [
"BSD-2-Clause"
] | permissive | //
// countedset.c
// GNETextSearch
//
// Created by Anthony Drendel on 11/14/15.
// Copyright © 2015 Gone East LLC. All rights reserved.
//
#include "countedset.h"
#include "GNETextSearchPrivate.h"
#include <string.h>
// ------------------------------------------------------------------------------------------
#define LEFT_HEAVY 1
#define BALANCED 0
#define RIGHT_HEAVY -1
typedef struct _tsearch_countedset_node
{
GNEInteger integer;
size_t count;
int balance;
size_t left;
size_t right;
} _tsearch_countedset_node;
typedef struct tsearch_countedset
{
_tsearch_countedset_node *nodes;
size_t count; // The number of nodes whose count > 0.
size_t nodesCapacity;
size_t insertIndex;
} tsearch_countedset;
// ------------------------------------------------------------------------------------------
_tsearch_countedset_node * _tsearch_countedset_copy_nodes(const tsearch_countedset_ptr ptr);
result _tsearch_countedset_copy_ints(const tsearch_countedset_ptr ptr, GNEInteger *integers,
const size_t integersCount);
int _tsearch_countedset_compare(const void *valuePtr1, const void *valuePtr2);
result _tsearch_countedset_add_int(const tsearch_countedset_ptr ptr,
const GNEInteger newInteger, const size_t countToAdd);
_tsearch_countedset_node * _tsearch_countedset_get_node_for_int(const tsearch_countedset_ptr ptr,
const GNEInteger integer);
size_t _tsearch_countedset_get_node_idx_for_int_insert(const tsearch_countedset_ptr ptr, const GNEInteger integer);
size_t _tsearch_countedset_get_node_and_parent_idx_for_int_insert(const tsearch_countedset_ptr ptr,
const GNEInteger integer,
size_t *outParentIndex);
int _tsearch_countedset_balance_node_at_idx(_tsearch_countedset_node *nodes, const size_t index);
void _tsearch_countedset_rotate_left(_tsearch_countedset_node *nodes, const size_t index);
void _tsearch_countedset_rotate_right(_tsearch_countedset_node *nodes, const size_t index);
result _tsearch_countedset_node_init(const tsearch_countedset_ptr ptr, const GNEInteger integer,
const size_t count, size_t *outIndex);
result _tsearch_countedset_increase_values_buf(const tsearch_countedset_ptr ptr);
// ------------------------------------------------------------------------------------------
#pragma mark - Counted Set
// ------------------------------------------------------------------------------------------
tsearch_countedset_ptr tsearch_countedset_init(void)
{
tsearch_countedset_ptr ptr = calloc(1, sizeof(tsearch_countedset));
if (ptr == NULL) { return NULL; }
size_t count = 5;
size_t size = sizeof(_tsearch_countedset_node);
_tsearch_countedset_node *nodes = calloc(count, size);
if (nodes == NULL) { tsearch_countedset_free(ptr); return NULL; }
ptr->nodes = nodes;
ptr->count = 0;
ptr->nodesCapacity = (count * size);
ptr->insertIndex = 0;
return ptr;
}
tsearch_countedset_ptr tsearch_countedset_copy(const tsearch_countedset_ptr ptr)
{
if (ptr == NULL || ptr->nodes == NULL) { return NULL; }
tsearch_countedset_ptr copyPtr = calloc(1, sizeof(tsearch_countedset));
if (copyPtr == NULL) { return NULL; }
_tsearch_countedset_node *nodes = malloc(ptr->nodesCapacity);
if (nodes == NULL) { tsearch_countedset_free(copyPtr); return NULL; }
memcpy(nodes, ptr->nodes, ptr->nodesCapacity);
copyPtr->nodes = nodes;
copyPtr->count = ptr->count;
copyPtr->nodesCapacity = ptr->nodesCapacity;
copyPtr->insertIndex = ptr->insertIndex;
return copyPtr;
}
void tsearch_countedset_free(const tsearch_countedset_ptr ptr)
{
if (ptr != NULL) {
free(ptr->nodes);
ptr->nodes = NULL;
ptr->count = 0;
ptr->nodesCapacity = 0;
ptr->insertIndex = 0;
free(ptr);
}
}
size_t tsearch_countedset_get_count(const tsearch_countedset_ptr ptr)
{
return (ptr == NULL) ? 0 : ptr->count;
}
bool tsearch_countedset_contains_int(const tsearch_countedset_ptr ptr, const GNEInteger integer)
{
_tsearch_countedset_node *nodePtr = _tsearch_countedset_get_node_for_int(ptr, integer);
return (nodePtr == NULL || nodePtr->count == 0) ? false : true;
}
size_t tsearch_countedset_get_count_for_int(const tsearch_countedset_ptr ptr, const GNEInteger integer)
{
if (ptr == NULL || ptr->nodes == NULL) { return 0; }
_tsearch_countedset_node *nodePtr = _tsearch_countedset_get_node_for_int(ptr, integer);
return (nodePtr == NULL) ? 0 : nodePtr->count;
}
result tsearch_countedset_copy_ints(const tsearch_countedset_ptr ptr, GNEInteger **outIntegers, size_t *outCount)
{
if (ptr == NULL || ptr->nodes == NULL || outIntegers == NULL || outCount == NULL) { return failure; }
size_t integersCount = ptr->count;
size_t size = sizeof(GNEInteger);
GNEInteger *integers = calloc(integersCount, size);
if (_tsearch_countedset_copy_ints(ptr, integers, integersCount) == failure) {
free(integers);
*outCount = 0;
return failure;
}
*outIntegers = integers;
*outCount = integersCount;
return success;
}
result tsearch_countedset_add_int(const tsearch_countedset_ptr ptr, const GNEInteger integer)
{
return _tsearch_countedset_add_int(ptr, integer, 1);
}
result tsearch_countedset_remove_int(const tsearch_countedset_ptr ptr, const GNEInteger integer)
{
if (ptr == NULL) { return failure; }
_tsearch_countedset_node *nodePtr = _tsearch_countedset_get_node_for_int(ptr, integer);
if (nodePtr == NULL || nodePtr->count == 0) { return success; }
nodePtr->count = 0;
ptr->count -= 1;
return success;
}
result tsearch_countedset_remove_all_ints(const tsearch_countedset_ptr ptr)
{
if (ptr == NULL) { return failure; }
size_t count = ptr->insertIndex;
for (size_t i = 0; i < count; i++) {
ptr->nodes[i].count = 0;
}
ptr->count = 0;
return success;
}
result tsearch_countedset_union(const tsearch_countedset_ptr ptr, const tsearch_countedset_ptr otherPtr)
{
if (ptr == NULL || ptr->nodes == NULL) { return failure; }
if (otherPtr == NULL || otherPtr->nodes == NULL) { return success; }
size_t otherCount = otherPtr->insertIndex;
_tsearch_countedset_node *otherNodes = otherPtr->nodes;
for (size_t i = 0; i < otherCount; i++) {
if (otherNodes[i].count == 0) { continue; }
_tsearch_countedset_node otherValue = otherNodes[i];
int result = _tsearch_countedset_add_int(ptr, otherValue.integer, otherValue.count);
if (result == failure) { return failure; }
}
return success;
}
result tsearch_countedset_intersect(const tsearch_countedset_ptr ptr, const tsearch_countedset_ptr otherPtr)
{
if (ptr == NULL || ptr->nodes == NULL) { return failure; }
if (otherPtr == NULL || otherPtr->nodes == NULL) {
return tsearch_countedset_remove_all_ints(ptr);
}
size_t actualCount = ptr->insertIndex;
// Copy all of the counted set's values so that we can iterate over them
// while modifying the set.
_tsearch_countedset_node *nodesCopy = _tsearch_countedset_copy_nodes(ptr);
if (nodesCopy == NULL) { return failure; }
for (size_t i = 0; i < actualCount; i++) {
_tsearch_countedset_node node = nodesCopy[i];
if (node.count == 0) { continue; }
_tsearch_countedset_node *nodePtr = _tsearch_countedset_get_node_for_int(otherPtr, node.integer);
if (nodePtr == NULL || nodePtr->count == 0) {
int result = tsearch_countedset_remove_int(ptr, node.integer);
if (result == failure) { free(nodesCopy); return failure; }
} else {
size_t count = tsearch_countedset_get_count_for_int(otherPtr, node.integer);
int result = _tsearch_countedset_add_int(ptr, node.integer, count);
if (result == failure) { free(nodesCopy); return failure; }
}
}
free(nodesCopy);
return success;
}
result tsearch_countedset_minus(const tsearch_countedset_ptr ptr, const tsearch_countedset_ptr otherPtr)
{
if (ptr == NULL || ptr->nodes == NULL) { return failure; }
if (otherPtr == NULL || otherPtr->nodes == NULL) { return success; }
size_t otherUsedCount = otherPtr->insertIndex;
_tsearch_countedset_node *otherNodes = otherPtr->nodes;
for (size_t i = 0; i < otherUsedCount; i++) {
_tsearch_countedset_node otherValue = otherNodes[i];
_tsearch_countedset_node *nodePtr = _tsearch_countedset_get_node_for_int(ptr, otherValue.integer);
if (nodePtr == NULL) { continue; }
if (otherValue.count >= nodePtr->count) {
int result = tsearch_countedset_remove_int(ptr, otherValue.integer);
if (result == failure) { return failure; }
} else {
nodePtr->count -= otherValue.count;
}
}
return success;
}
// ------------------------------------------------------------------------------------------
#pragma mark - Private
// ------------------------------------------------------------------------------------------
_tsearch_countedset_node * _tsearch_countedset_copy_nodes(const tsearch_countedset_ptr ptr)
{
if (ptr == NULL || ptr->nodes == NULL) { return NULL; }
size_t actualCount = ptr->insertIndex;
size_t size = sizeof(_tsearch_countedset_node);
_tsearch_countedset_node *nodesCopy = calloc(actualCount, size);
if (nodesCopy == NULL) { return failure; }
memcpy(nodesCopy, ptr->nodes, actualCount * size);
return nodesCopy;
}
result _tsearch_countedset_copy_ints(const tsearch_countedset_ptr ptr, GNEInteger *integers,
const size_t integersCount)
{
if (ptr == NULL || ptr->nodes == NULL) { return failure; }
if (integers == NULL || integersCount == 0) { return failure; }
size_t nodesCount = ptr->insertIndex;
size_t size = sizeof(_tsearch_countedset_node);
if (integersCount > nodesCount) { return failure; }
_tsearch_countedset_node *nodesCopy = _tsearch_countedset_copy_nodes(ptr);
if (nodesCopy == NULL) { return failure; }
qsort(nodesCopy, nodesCount, size, &_tsearch_countedset_compare);
// The nodes are sorted in descending order. So, all of the nodes with zero counts
// are at the end of the array. The integers count only includes nodes with
// non-zero counts.
for (size_t i = 0; i < integersCount; i++) {
_tsearch_countedset_node value = nodesCopy[i];
integers[i] = value.integer;
}
free(nodesCopy);
return success;
}
int _tsearch_countedset_compare(const void *valuePtr1, const void *valuePtr2)
{
if (valuePtr1 == NULL || valuePtr2 == NULL) { return 0; }
_tsearch_countedset_node value1 = *(_tsearch_countedset_node *)valuePtr1;
_tsearch_countedset_node value2 = *(_tsearch_countedset_node *)valuePtr2;
if (value1.count > value2.count) { return -1; }
if (value1.count < value2.count) { return 1; }
return 0;
}
result _tsearch_countedset_add_int(const tsearch_countedset_ptr ptr,
const GNEInteger newInteger,
const size_t countToAdd)
{
if (ptr == NULL || ptr->nodes == NULL) { return failure; }
if (ptr->insertIndex == 0) {
size_t index = SIZE_MAX;
int result = _tsearch_countedset_node_init(ptr, newInteger, countToAdd, &index);
if (result == failure || index == SIZE_MAX) { return failure; }
return success;
}
size_t parentIndex = SIZE_MAX;
size_t insertIndex = _tsearch_countedset_get_node_and_parent_idx_for_int_insert(ptr,
newInteger,
&parentIndex);
if (insertIndex == SIZE_MAX) { return failure; }
_tsearch_countedset_node *nodePtr = &(ptr->nodes[insertIndex]);
GNEInteger nodeInteger = nodePtr->integer;
if (nodeInteger == newInteger) {
size_t newCount = ((SIZE_MAX - nodePtr->count) >= countToAdd) ? (nodePtr->count + countToAdd) : SIZE_MAX;
nodePtr->count = newCount;
if (newCount == 1) {
ptr->count += 1;
}
return success;
}
size_t index = SIZE_MAX;
int result = _tsearch_countedset_node_init(ptr, newInteger, countToAdd, &index);
if (result == failure || index == SIZE_MAX) { return failure; }
nodePtr = &(ptr->nodes[insertIndex]); // If ptr->nodes was realloced, we need to refresh the pointer.
if (newInteger < nodeInteger) { nodePtr->left = index; }
else { nodePtr->right = index; }
_tsearch_countedset_balance_node_at_idx(ptr->nodes, parentIndex);
return success;
}
/// Returns the exact node containing the specified integer or NULL if the integer isn't
/// present in the counted set.
_tsearch_countedset_node * _tsearch_countedset_get_node_for_int(const tsearch_countedset_ptr ptr,
const GNEInteger integer)
{
if (ptr == NULL || ptr->nodes == NULL || ptr->count == 0) { return NULL; }
size_t index = _tsearch_countedset_get_node_idx_for_int_insert(ptr, integer);
if (index == SIZE_MAX) { return NULL; }
_tsearch_countedset_node *insertionNodePtr = &(ptr->nodes[index]);
return (insertionNodePtr->integer == integer) ? insertionNodePtr : NULL;
}
/// Returns the index for the node representing the specified integer or the parent node into which
/// a new node should be inserted. Returns SIZE_MAX on failure.
size_t _tsearch_countedset_get_node_idx_for_int_insert(const tsearch_countedset_ptr ptr, const GNEInteger integer)
{
return _tsearch_countedset_get_node_and_parent_idx_for_int_insert(ptr, integer, NULL);
}
size_t _tsearch_countedset_get_node_and_parent_idx_for_int_insert(const tsearch_countedset_ptr ptr,
const GNEInteger integer,
size_t *outParentIndex)
{
if (ptr == NULL || ptr->nodes == NULL || ptr->insertIndex == 0) { return SIZE_MAX; }
_tsearch_countedset_node *nodes = ptr->nodes;
size_t parentIndex = SIZE_MAX;
size_t nextIndex = 0; // Start at root
do {
if (outParentIndex != NULL) { *outParentIndex = parentIndex; }
parentIndex = nextIndex;
if (integer < nodes[parentIndex].integer) { nextIndex = nodes[parentIndex].left; }
else if (integer > nodes[parentIndex].integer) { nextIndex = nodes[parentIndex].right; }
else { return parentIndex; }
} while (nextIndex != SIZE_MAX);
return parentIndex;
}
int _tsearch_countedset_balance_node_at_idx(_tsearch_countedset_node *nodes, const size_t index)
{
if (nodes == NULL || index == SIZE_MAX) { return 0; }
int leftHeight = _tsearch_countedset_balance_node_at_idx(nodes, nodes[index].left);
int rightHeight = _tsearch_countedset_balance_node_at_idx(nodes, nodes[index].right);
int height = leftHeight - rightHeight;
if (abs(leftHeight - rightHeight) > 1) {
if (height < 0) {
_tsearch_countedset_rotate_right(nodes, index);
} else {
_tsearch_countedset_rotate_left(nodes, index);
}
height = BALANCED;
}
nodes[index].balance = height;
return abs(height) + 1;
}
void _tsearch_countedset_rotate_left(_tsearch_countedset_node *nodes, const size_t index)
{
_tsearch_countedset_node node = nodes[index];
size_t childIndex = node.left;
_tsearch_countedset_node childNode = nodes[childIndex];
size_t grandchildIndex = (childNode.balance > 0) ? childNode.left : childNode.right;
_tsearch_countedset_node grandchildNode = nodes[grandchildIndex];
if (childNode.balance > 0) {
// 8 7
// 7 ==> 2 8
// 2
nodes[index] = childNode;
nodes[index].left = grandchildIndex;
nodes[index].right = childIndex;
nodes[index].balance = BALANCED;
nodes[childIndex] = node;
nodes[childIndex].left = SIZE_MAX;
nodes[childIndex].balance = BALANCED;
} else {
// 8 7
// 2 ==> 2 8
// 7
nodes[index] = grandchildNode;
nodes[index].left = childIndex;
nodes[index].right = grandchildIndex;
nodes[index].balance = BALANCED;
nodes[grandchildIndex] = node;
nodes[grandchildIndex].left = SIZE_MAX;
nodes[grandchildIndex].balance = BALANCED;
nodes[childIndex].right = SIZE_MAX;
nodes[childIndex].balance = BALANCED;
}
}
void _tsearch_countedset_rotate_right(_tsearch_countedset_node *nodes, const size_t index)
{
_tsearch_countedset_node node = nodes[index];
size_t childIndex = node.right;
_tsearch_countedset_node childNode = nodes[childIndex];
size_t grandchildIndex = (childNode.balance > 0) ? childNode.left : childNode.right;
_tsearch_countedset_node grandchildNode = nodes[grandchildIndex];
if (childNode.balance > 0) {
// 2 7
// 8 ==> 2 8
// 7
nodes[index] = grandchildNode;
nodes[index].left = grandchildIndex;
nodes[index].right = childIndex;
nodes[index].balance = BALANCED;
nodes[grandchildIndex] = node;
nodes[grandchildIndex].left = SIZE_MAX;
nodes[grandchildIndex].right = SIZE_MAX;
nodes[grandchildIndex].balance = BALANCED;
nodes[childIndex].left = SIZE_MAX;
nodes[childIndex].balance = BALANCED;
} else {
// 2 7
// 7 ==> 2 8
// 8
nodes[index] = childNode;
nodes[index].left = childIndex;
nodes[index].right = grandchildIndex;
nodes[index].balance = BALANCED;
nodes[childIndex] = node;
nodes[childIndex].left = SIZE_MAX;
nodes[childIndex].right = SIZE_MAX;
nodes[childIndex].balance = BALANCED;
}
}
/// Returns a pointer to a new counted set node and increments the GNEIntegerCountedSet's count.
result _tsearch_countedset_node_init(const tsearch_countedset_ptr ptr, const GNEInteger integer,
const size_t count, size_t *outIndex)
{
if (outIndex == NULL) { return failure; }
if (ptr == NULL || ptr->nodes == NULL) { *outIndex = SIZE_MAX; return failure; }
if (ptr->insertIndex == SIZE_MAX - 1) { *outIndex = SIZE_MAX; return failure; }
if (_tsearch_countedset_increase_values_buf(ptr) == failure) {
*outIndex = SIZE_MAX;
return failure;
}
size_t index = ptr->insertIndex;
ptr->insertIndex += 1;
ptr->count += 1;
ptr->nodes[index].integer = integer;
ptr->nodes[index].count = count;
ptr->nodes[index].balance = BALANCED;
ptr->nodes[index].left = SIZE_MAX;
ptr->nodes[index].right = SIZE_MAX;
*outIndex = index;
return success;
}
result _tsearch_countedset_increase_values_buf(const tsearch_countedset_ptr ptr)
{
if (ptr == NULL || ptr->nodes == NULL) { return failure; }
size_t usedCount = ptr->insertIndex;
size_t capacity = ptr->nodesCapacity;
size_t emptySpaces = (capacity / sizeof(_tsearch_countedset_node)) - usedCount;
if (emptySpaces <= 2) {
size_t newCapacity = capacity * 2;
_tsearch_countedset_node *newNodes = realloc(ptr->nodes, newCapacity);
if (newNodes == NULL) { return failure; }
ptr->nodes = newNodes;
ptr->nodesCapacity = newCapacity;
}
return success;
}
|
Markdown | WINDOWS-1252 | 9,901 | 2.578125 | 3 | [] | no_license | ---
title: "Reproducible Research: Peer Assessment 1"
author: "skewdlogix"
date: "April 22, 2017"
output: html_document
keep_md: true
---
```r
knitr::opts_chunk$set(echo = TRUE)
```
### Overview
The GitHub repository was forked from https://github.com/rdpeng/RepData_PeerAssessment1 to my GitHub account and then cloned to a local repository. This template was provided in the repo as well as the dataset required for the assignment.The goal is to analyze activity data from a personal activity monitoring device. This device collects data at 5 minute intervals through out the day. The data consists of two months of data from an anonymous individual collected during the months of October and November, 2012 and include the number of steps taken in 5 minute intervals each day.
### Initial Workspace Preparation
Remove any old files and clean up workspace
```r
rm(list=ls(all=TRUE))
```
Call appropriate libraries for functions
```r
library(lubridate)
library(dplyr)
library(knitr)
library(markdown)
library(lattice)
```
Set working directory and assign it to wd
```r
setwd("C:/Documents and Settings/Stephen/Documents/GitHub/RepData_PeerAssessment1")
wd <- getwd()
```
### Unzip Files to be Analyzed
Extract list of all files in the zip file and assign to p
```r
a <- "activity.zip"
p <- unzip(file.path(wd, a))
```
### Loading and preprocessing the data
Load the data from the extracted file ensuring that the data is in the correct format for analysis
View files and examine structure
```r
activity <- read.csv(p, colClasses= c("integer","Date","integer"))
head(activity)
```
```
## steps date interval
## 1 NA 2012-10-01 0
## 2 NA 2012-10-01 5
## 3 NA 2012-10-01 10
## 4 NA 2012-10-01 15
## 5 NA 2012-10-01 20
## 6 NA 2012-10-01 25
```
```r
str(activity)
```
```
## 'data.frame': 17568 obs. of 3 variables:
## $ steps : int NA NA NA NA NA NA NA NA NA NA ...
## $ date : Date, format: "2012-10-01" "2012-10-01" ...
## $ interval: int 0 5 10 15 20 25 30 35 40 45 ...
```
### What is mean total number of steps taken per day?
For this part of the assignment, you can ignore the missing values in the dataset
#### Calculate the total number of steps taken per day
```r
total_steps <- activity %>% group_by(date) %>% summarize(steps = sum(steps, na.rm= TRUE))
head(total_steps, n= 10)
```
```
## # A tibble: 10 2
## date steps
## <date> <int>
## 1 2012-10-01 0
## 2 2012-10-02 126
## 3 2012-10-03 11352
## 4 2012-10-04 12116
## 5 2012-10-05 13294
## 6 2012-10-06 15420
## 7 2012-10-07 11015
## 8 2012-10-08 0
## 9 2012-10-09 12811
## 10 2012-10-10 9900
```
#### Create a histogram of the total number of steps taken each day
```r
hist(total_steps$steps, breaks=50, main= "Total Number of Steps Taken Each Day", xlab= "Total Steps per Day", ylab= "Number of Days", col= "red")
```

#### Calculate the mean and median of the total number of steps taken each day
The mean of the total number of steps taken per day is
```r
mean(total_steps$steps)
```
```
## [1] 9354.23
```
The median of the total number of steps taken per day is
```r
median(total_steps$steps)
```
```
## [1] 10395
```
## What is the average daily activity pattern?
#### Time-series Plot
Make a time series plot of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis)
```r
average_steps <- activity %>% group_by(interval) %>% summarize(average_steps = mean(steps, na.rm= TRUE))
head(average_steps)
```
```
## # A tibble: 6 2
## interval average_steps
## <int> <dbl>
## 1 0 1.7169811
## 2 5 0.3396226
## 3 10 0.1320755
## 4 15 0.1509434
## 5 20 0.0754717
## 6 25 2.0943396
```
```r
with(average_steps, plot(average_steps ~ interval, type="l", lwd= 1, col= "red", main= "Average Number of Steps Taken By 5 Minute Interval", ylab="Average Number of Steps Taken", xlab= "5 Minute Interval"))
```

#### 5 Minute Interval Calculations
Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps?
The 5 minute interval averaged across all days with the maximum number of steps is
```r
average_steps$interval[which.max(average_steps$average_steps)]
```
```
## [1] 835
```
## Imputing missing values
#### Calculate NAs
Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs)
The total number of NAs for each variable in the dataframe is
```r
na_count <-sapply(activity, function(y) sum(is.na(y)))
na_count
```
```
## steps date interval
## 2304 0 0
```
#### Devise a strategy for filling in all of the missing values in the dataset.
The stategy chosen is to replace each NA value with the mean of the respective interval that it belongs to. This strategy is more flexible than just using a simple mean replacement over the entire dataframe.
#### Create a new dataset that is equal to the original dataset but with the missing data filled in.
```r
activity_imputed <- activity
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
activity_imputed <- activity_imputed %>% group_by(interval) %>% mutate(steps=impute.mean(steps))
head(activity_imputed, n=10)
```
```
## Source: local data frame [10 x 3]
## Groups: interval [10]
##
## steps date interval
## <dbl> <date> <int>
## 1 1.7169811 2012-10-01 0
## 2 0.3396226 2012-10-01 5
## 3 0.1320755 2012-10-01 10
## 4 0.1509434 2012-10-01 15
## 5 0.0754717 2012-10-01 20
## 6 2.0943396 2012-10-01 25
## 7 0.5283019 2012-10-01 30
## 8 0.8679245 2012-10-01 35
## 9 0.0000000 2012-10-01 40
## 10 1.4716981 2012-10-01 45
```
Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day.
#### Create a histogram of the total number of steps taken each day
```r
total_steps_adj <- activity_imputed %>% group_by(date) %>% summarize(steps = sum(steps, na.rm= TRUE))
head(total_steps_adj, n= 10)
```
```
## # A tibble: 10 2
## date steps
## <date> <dbl>
## 1 2012-10-01 10766.19
## 2 2012-10-02 126.00
## 3 2012-10-03 11352.00
## 4 2012-10-04 12116.00
## 5 2012-10-05 13294.00
## 6 2012-10-06 15420.00
## 7 2012-10-07 11015.00
## 8 2012-10-08 10766.19
## 9 2012-10-09 12811.00
## 10 2012-10-10 9900.00
```
```r
hist(total_steps_adj$steps, breaks=50, main= "Total Number of Steps Taken Each Day (Imputed Data)", xlab= "Total Steps per Day", ylab= "Number of Days", col= "red")
```

#### Calculate the mean and median of the total number of steps taken each day
The mean of the total number of steps taken per day using imputed data is
```r
mean(total_steps_adj$steps)
```
```
## [1] 10766.19
```
The median of the total number of steps taken per day using imputed data is
```r
median(total_steps_adj$steps)
```
```
## [1] 10766.19
```
These values are slightly different than the calculated mean and median from the data with NAs.The histogram of the data becomes more symmetrical and loses its skewed shape and more closely represents a normal bell curve with both the mean and the median being the same value. The total number of daily steps increases as there are now values replacing the NAs.
## Are there differences in activity patterns between weekdays and weekends?
#### Adding Factor Variable for Weekday and Weekend
Create a new factor variable in the dataset with two levels - "weekday" and "weekend" indicating whether a given date is a weekday or weekend day.
```r
activity_imputed$DayofWeek <- ifelse(as.POSIXlt(activity_imputed$date)$wday %in% c(0,6),"weekend", "weekday")
activity_imputed$DayofWeek <- as.factor(activity_imputed$DayofWeek)
head(activity_imputed, n=10)
```
```
## Source: local data frame [10 x 4]
## Groups: interval [10]
##
## steps date interval DayofWeek
## <dbl> <date> <int> <fctr>
## 1 1.7169811 2012-10-01 0 weekday
## 2 0.3396226 2012-10-01 5 weekday
## 3 0.1320755 2012-10-01 10 weekday
## 4 0.1509434 2012-10-01 15 weekday
## 5 0.0754717 2012-10-01 20 weekday
## 6 2.0943396 2012-10-01 25 weekday
## 7 0.5283019 2012-10-01 30 weekday
## 8 0.8679245 2012-10-01 35 weekday
## 9 0.0000000 2012-10-01 40 weekday
## 10 1.4716981 2012-10-01 45 weekday
```
#### Time-series Plot Using Factors to Subset Data
Make a panel plot containing a time series plot of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis).
```r
average_steps_adj <- activity_imputed %>% group_by(interval, DayofWeek) %>% summarize(average_steps = mean(steps, na.rm= TRUE))
head(average_steps_adj)
```
```
## Source: local data frame [6 x 3]
## Groups: interval [3]
##
## interval DayofWeek average_steps
## <int> <fctr> <dbl>
## 1 0 weekday 2.25115304
## 2 0 weekend 0.21462264
## 3 5 weekday 0.44528302
## 4 5 weekend 0.04245283
## 5 10 weekday 0.17316562
## 6 10 weekend 0.01650943
```
```r
with(average_steps_adj, xyplot(average_steps ~ interval | DayofWeek, type="l", lwd= 1, layout= c(1, 2), col= "red", main= "Average Number of Steps Taken By 5 Minute Interval", ylab="Average Number of Steps Taken", xlab= "5 Minute Interval"))
```

|
Python | UTF-8 | 13,853 | 2.859375 | 3 | [] | no_license | from PIL import Image, ImageFont, ImageDraw
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale, invert
from PIL.ImageChops import multiply
from math import pi
from io import BytesIO
import json
import base64
import requests
import string
import random
from sys import argv
class ImageProcessor(object):
def __init__(self, params, logo_path, name_path, bg_path, ratio_json):
self.params = params
self.logo_path = logo_path
self.name_path = name_path
self.bg_path = bg_path
self.ratio_json = ratio_json
# Init variables
self.tmp_path = ''
self.cwidth = 100
self.cheight = 100
self.small_h = 50
self.small_w = 50
self.landh_scale = 1
self.landw_scale = 1
self.ratio = 1
self.font = None
self.canvas = None
def create_data(self):
letters = string.ascii_lowercase
rand_str = lambda l: ''.join(random.choice(letters) for i in range(l))
self.font = ImageFont.truetype('UbuntuMono-BI.ttf', 24)
self.tmp_path = f'result/{rand_str(6)}.png'
self.cwidth = self.ratio_json['cwidth']
self.cheight = self.ratio_json['cheight']
self.small_h = self.ratio_json['small_h']
self.small_w = self.ratio_json['small_w']
if self.cwidth / self.cheight > 1:
self.ratio = self.cheight / self.small_h
self.landh_scale = self.ratio / (self.cheight / self.small_h)
self.landw_scale = (self.cwidth / self.small_w) / self.ratio
else:
self.ratio = self.cwidth / self.small_w
self.landh_scale = 1
self.landw_scale = 1
# create canvas
self.canvas = Image.new('RGBA', (self.cwidth, self.cheight))
def open_font(self):
try:
with open('../application/config/print_designer.json', 'r') as f:
data = json.load(f)
for i in data:
if data[i].get('web_font'):
self.font = ImageFont.truetype(f'../fonts/prints/{data[i].get("file")}', 24)
except FileNotFoundError as e:
pass
def processed(self):
for data in self.params:
obj_prop = ImageProp(self.ratio, self.landw_scale, self.landh_scale, **data)
if obj_prop.type == 'text':
self.open_font()
self.canvas = MyImage.text(self.canvas, self.font, obj_prop)
elif obj_prop.type == 'image':
path_image = {'name': self.name_path, 'background': self.bg_path, 'logo': self.logo_path}
if path_image[obj_prop.kind] == '-':
continue
obj_img = MyImage(path_image[obj_prop.kind]).get()
if obj_prop.filter:
obj_img = MyImage.apply_filters(obj_img, obj_prop.filter, obj_prop)
# else:
# obj_img.show()
self.canvas = MyImage.add(self.canvas, obj_img, obj_prop)
self.canvas.save(self.tmp_path)
class MyImage(object):
def __init__(self, path):
path = BytesIO(requests.get(path).content) if path[:4] == 'http' else path
self.image = Image.open(path)
self.image.convert('RGBA')
def get(self):
return self.image
@staticmethod
def text(canvas, font, prop):
size = ImageDraw.Draw(canvas).textsize(prop.text, font=font) # Size area with text
background_image = Image.new('RGBA', canvas.size, (255, 255, 255, 0)) # Temporary canvas
txt = Image.new('RGBA', size, (255, 255, 255, 0)) # new transparent picture
d = ImageDraw.Draw(txt)
d.text((0, 0), prop.text, 'black', font=font) # Draw text
w = txt.rotate(prop.angle, expand=1) # Turn the text
background_image.paste(w, (prop.left, prop.top)) # Paste the text into a temporary picture
canvas = Image.alpha_composite(canvas, background_image) # Paste text into canvas
return canvas
@staticmethod
def add(canvas, img, prop):
img = img.resize((prop.width, prop.height)) # Scale image
mark = img.rotate(prop.angle, Image.BICUBIC) # Turn the image
background_image = Image.new('RGBA', canvas.size, (255, 255, 255, 0)) # Temporary canvas
background_image.paste(mark, (prop.left, prop.top)) # Paste image into a temporary canvas
# background_image.show()
canvas = Image.alpha_composite(canvas, background_image) # Paste into canvas
return canvas
@staticmethod
def apply_filters(img, filter, prop):
if filter.get('type') == 'css_hue_rotate':
img = MyImage.change_hue(img, int(filter.get('value')))
elif filter.get('type') == 'css_invert':
img = MyImage.invert_colors(img)
elif filter.get('type') == 'css_saturate':
img = MyImage.image_tint(img, filter.get('tint'))
img.convert('RGBA')
# else:
# img = MyImage.image_multiply(img)
return img
@staticmethod
def blend_images(background_image: str, foreground_image: str, alpha: float) -> Image:
"""
Function to blend two images
Parameters:
background_image (str): Path to the image that will act as the background
foreground_image (str): Path to the image that will act as the foreground
alpha(float) : Alpha value, can be used to distinguish area of intersection between two images
Returns:
Image object for further use
"""
try:
background = Image.open(background_image)
foreground = Image.open(foreground_image)
merged_image = Image.blend(background, foreground, alpha)
return merged_image
except Exception as exc:
print("Exception in overlay_with_alpha")
print(exc)
return None
@staticmethod
def overlay_images(background_image: str, foreground_image: str) -> Image:
"""
Function to merge two images without alpha
Parameters:
background_image (str): Path to the image that will act as the background
foreground_image (str): Path to the image that will act as the foreground
Returns:
Image object for further use
"""
try:
background = Image.open(background_image)
foreground = Image.open(foreground_image)
background.paste(foreground, (0, 0), foreground)
return background
except Exception as exc:
print("Exception in overlay_without_alpha")
print(exc)
return None
@staticmethod
def change_hue(image, amount: float) -> Image:
"""
Function to change hue of an image by given amount
Parameters:
image (str): Path to the image
amount (float): Hue amount
Returns:
Image object for further use
"""
# try:
# Open and ensure it is RGB, not palettised
img = image.convert('RGBA')
# Save the Alpha channel to re-apply at the end
a = img.getchannel('A')
# Convert to HSV and save the V (Lightness) channel
v = img.convert('RGB').convert('HSV').getchannel('V')
# Synthesize new Hue and Saturation channels using values from colour picker
# colpickerH, colpickerS = 10, 255
new_h = Image.new('L', img.size, (amount,))
new_s = Image.new('L', img.size, (255,))
# Recombine original V channel plus 2 synthetic ones to a 3 channel HSV image
hsv = Image.merge('HSV', (new_h, new_s, v))
# Add original Alpha layer back in
r, g, b = hsv.convert('RGB').split()
rgba = Image.merge('RGBA', (r, g, b, a))
return rgba
# except Exception as exc:
# print("Exception in change_hue")
# print(exc)
# return None
@staticmethod
def image_tint(image, tint='#ffffff'):
"""
Function to merge two images without alpha
Parameters:
image (str): Path to the image
tint (str): Hex code for the tint
Returns:
Image object for further use
"""
image = image.convert('RGBA')
image.load()
tr, tg, tb = getrgb(tint)
tl = getcolor(tint, "L") # tint color's overall luminosity
tl = 1 if not tl else tl # avoid division by zero
tl = float(tl) # compute luminosity preserving tint factors
sr, sg, sb = map(lambda tv: tv / tl, (tr, tg, tb)) # per component
# adjustments
# create look-up tables to map luminosity to adjusted tint
# (using floating-point math only to compute table)
luts = (
tuple(map(lambda lr: int(lr * sr + 0.5), range(256))) +
tuple(map(lambda lg: int(lg * sg + 0.5), range(256))) +
tuple(map(lambda lb: int(lb * sb + 0.5), range(256)))
)
lum = grayscale(image) # 8-bit luminosity version of whole image
if Image.getmodebands(image.mode) < 4:
merge_args = (image.mode, (lum, lum, lum)) # for RGB verion of grayscale
else: # include copy of image image's alpha layer
a = Image.new("L", image.size)
a.putdata(image.getdata(3))
merge_args = (image.mode, (lum, lum, lum, a)) # for RGBA verion of grayscale
luts += tuple(range(256)) # for 1:1 mapping of copied alpha values
return Image.merge(*merge_args).point(luts)
@staticmethod
def invert_colors(image) -> Image:
"""
Function to invert colors of an image
Parameters:
image (str): Path to the image
Returns:
Image object for further use
"""
try:
image = image.convert('RGBA')
r, g, b, a = image.split()
rgb_image = Image.merge('RGB', (r, g, b))
inverted_image = invert(rgb_image)
r2, g2, b2 = inverted_image.split()
final_transparent_image = Image.merge('RGBA', (r2, g2, b2, a))
image = final_transparent_image
return image
except Exception as exc:
print("Error in invert_colors")
print(exc)
return None
@staticmethod
def image_multiply(first_image: str, second_image: str) -> Image:
"""
Function to multiply two images
Parameters:
first_image (str): Path to the first image
second_image (str): Path to the second image
Returns:
Image object for further use
"""
try:
image_1 = Image.open(first_image)
image_2 = Image.open(second_image)
multiplied_image = multiply(image_1, image_2)
return multiplied_image
except Exception as exc:
print("Error in image_multiply")
print(exc)
return None
class ImageProp(object):
def __init__(self, ratio, landw_scale, landh_scale, **kwargs):
self.ratio = ratio
self.landw_scale = landw_scale
self.landh_scale = landh_scale
self.kwargs = kwargs
# init variables
self.hi_width = 100
self.hi_height = 100
self.hi_left = 0
self.hi_top = 0
self.stroke_width = 0
self.type = None
self.text = ''
self.kind = ''
self.filter = None
for i in kwargs:
setattr(self, i, kwargs[i])
self.font_size = 24 * self.ratio
self.width = int(self.hi_width * self.ratio)
self.height = int(self.hi_height * self.ratio)
self.left = int(self.hi_left * self.landw_scale * self.ratio)
self.top = int(self.hi_top * self.landh_scale * self.ratio)
self.angle = float(self.angle) * 180 / pi
def main():
params = json.loads(base64.b64decode(argv[1]))
logo_image_path = argv[2]
name_image_path = argv[3]
background_image_path = argv[4]
ratio_json = json.loads(argv[5])
processor = ImageProcessor(params, logo_image_path, name_image_path, background_image_path, ratio_json)
processor.create_data()
processor.processed()
def test():
# css_hue_rotate css_invert css_saturate
params = [
{"type": "image", "kind": "background", "logo": "template.jpg", "hi_width": 291, "hi_height": 360, "hi_left": 0,
"hi_right": 10, "hi_top": 0, "hi_bottom": 10, "angle": 0},
{"type": "image", "kind": "logo", "logo": "template.jpg", "hi_width": 291, "hi_height": 360, "hi_left": 0,
"hi_right": 10, "hi_top": 0, "hi_bottom": 10, "angle": 0},
{"type": "image", "kind": "name", "logo": "template.jpg", "hi_width": 97, "hi_height": 120, "hi_left": 97,
"hi_right": 10, "hi_top": 100, "hi_bottom": 10, "angle": 0, "filter": {"type": "css_saturate", "tint": "green"}},
# {"angle": 0, "hi_width": 145, "hi_height": 180, "type": "text", "text": "Testtext", "font": "KrinkesRegular"}
]
logo_image_path = 'https://i.ibb.co/Byptx3h/new-logo.png'
name_image_path = 'https://i.ibb.co/WnZttMH/star.png'
background_image_path = 'https://images.ua.prom.st/1184438987_w640_h640_futbolka-zhenskaya-belaya.jpg'
ratio_json = {"cwidth": 1455, "cheight": 1800, "small_w": 291, "small_h": 360}
str_param = f'{base64.b64encode(json.dumps(params).encode("utf-8")).decode()} {logo_image_path} {name_image_path} {background_image_path} \'{json.dumps(ratio_json)}\''
print(str_param)
processor = ImageProcessor(params, logo_image_path, name_image_path, background_image_path, ratio_json)
processor.create_data()
processor.processed()
if __name__ == '__main__':
if len(argv) == 1:
test()
else:
main()
|
Python | UTF-8 | 3,502 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python
import os
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
def print2(*args):
for arg in args:
print(arg, sep="\n\n", end="\n\n")
np.random.seed(112)
s0= 40 # Today's stock price
K= 40 # Strike/Exercise price
T= 0.5 # Maturity (in years)
r= 0.05 # Risk-free rate
sigma= 0.2 # Annualized volatility
barrier = 42 # Barrier level
def Call_option_price(S0, K, T, r, sigma):
"""The call_option_price function calculate the call option prices
Args:
S0 (float/int): intial stock price
K (float/int): strike price
r (float/int): risk free rate
T (float/int): term of share price
sigma (float/int): share volatility
Returns:
price (float/int): price of the option
"""
# np.random.seed(112)
n_simulation= 100 # Number of simulations and steps
n_steps= 100
dt= T/n_steps
call= np.zeros([n_simulation], dtype=float)
for j in range(0,n_simulation):
sT=S0
total=0
for i in range(0,int(n_steps)):
e = norm.rvs()
sT*= np.exp((r-0.5*sigma**2)*dt+sigma*e*np.sqrt(dt))
total+=sT
price_average = total/n_steps
call[j]=max(price_average-K, 0)
price=np.mean(call)*np.exp(-r*T)
print(f'Call price = {round(price, 3)}')
return price
Call_option_price(s0,K,T,r,sigma)
def black_schole_callprice(S, K, T, rf, sigma):
"""The black_schole_callprice function calculates the call option price
under Black Schole Merton model
Args:
S: current stock price
K: strike price
T: maturity date in years
rf: risk-free rate (continusouly compounded)
sigma: volatiity of underlying security
Returns:
callprice: call price
"""
current_time = 0
d1_numerator = np.log(S/K) + (r + sigma**2/2) * (T - current_time)
d1_denominator = sigma * np.sqrt(T - current_time)
d1 = d1_numerator / d1_denominator
d2 = d1 - d1_denominator
callprice = S*norm.cdf(d1) - (norm.cdf(d2)*K*np.exp(-r * (T - current_time)))
# print(f'Call price = {round(callprice, 3)}')
return callprice
black_schole_callprice(s0,K,T,r,sigma)
def up_and_out_call(s0,K,T,r,sigma,barrier):
"""
Returns: Call value of an up-and-out barrier option with European call
"""
n_simulation= 100 # Number of simulations and steps
n_steps= 100 # Define number of steps.
dt = T/n_steps
total=0
# simulates option price
for j in range(0,n_simulation):
sT=s0
out=False
# simulate the stock price evolution
for i in range(0,int(n_steps)):
e = norm.rvs()
sT *= np.exp((r-sigma**2/2)*dt+sigma*e*np.sqrt(dt))
# out whenever the stock price exceeds the barrier
if sT > barrier:
out=True
if out==False:
total += black_schole_callprice(s0,K,T,r,sigma)
return total/n_simulation
s0= 40 # Stock price today
K= 40 # Strike price
barrier = 42 # Barrier level
T= 0.5 # Maturity in years
r=0.05 # Risk-free rate
sigma=0.2 # Annualized volatility
n_simulation = 100 # number of simulations
result = up_and_out_call(s0,K,T,r,sigma,barrier)
print('Price for the Up-and-out Call = ', round(result,3))
|
Python | UTF-8 | 3,755 | 3.375 | 3 | [] | no_license | import requests
# ключ для доступа к сервису openweather.org
TOKEN = "2de2066e26914e2c3d870fd02592dba3"
def get_current_weather(city):
"""
Функция, возвращающая текущую погоду в городе.
"""
try:
# запрос к сайту, используя необходимые параметры
# q - название города
# units - отображение тем-ры в Цельсиях
# APPID - токен
res = requests.get("http://api.openweathermap.org/data/2.5/weather",
params={'q': city, 'units': 'metric', 'lang': 'ru', 'APPID': TOKEN})
# Результат запроса в json-формате
data = res.json()
# Шаблон вывода
info = 'Текущая погода в городе {}:\n\n' \
'- {}\n' \
'- Температура воздуха: {}°С\n' \
'- Влажность воздуха: {}%\n' \
'- Скорость ветра: {} м/с\n'.format(city, data['weather'][0]['description'].capitalize(),
data['main']['temp'], data['main']['humidity'], data['wind']['speed'])
# вытаскиваем необходимые сведения из словаря data
return info
# если возникла ошибка
except Exception as e:
print("Exception (find):", e)
return 'Ошибка запроса! Погоды для данного города не найдено!'
def get_forecast_weather(city):
"""
Функция, выводящая прогноз на несколько дней.
"""
try:
res = requests.get("http://api.openweathermap.org/data/2.5/forecast?",
params={'q': city, 'units': 'metric', 'lang': 'ru', 'APPID': TOKEN})
data = res.json()
# словари для определенного объема информации
temperatures = {} # словарь для температур
weather = {} # словарь для текстового описания погоды
# проходимся по каждой дате из списка прогнозов
for forecast in data['list']:
# дата в общепринятом виде
date = forecast['dt_txt'].split()[0]
# добавляем дату в оба словаря - значением ключей будет множество
if date not in temperatures:
temperatures[date] = set()
if date not in weather:
weather[date] = set()
# добавляем в множества информацию
temperatures[date].add(forecast['main']['temp'])
weather[date].add(forecast['weather'][0]['description'])
res = 'Прогноз погоды в городе {}:\n\n'.format(city)
# собираем ответ функции
for date in temperatures.keys():
res += '{}\n- В течение дня: {}\n- Максимальная температура: {}°С\n- Минимальная ' \
'температура: {}°С\n\n'.format('/'.join(reversed(date.split('-'))), ', '.join(weather[date]),
max(temperatures[date]), min(temperatures[date]))
except Exception as e:
# если что-то пошло не так
print("Exception (find):", e)
return 'Ошибка запроса! Погоды для данного города не найдено!'
return res
|
Java | UTF-8 | 179 | 1.546875 | 2 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | package com.cap.dao;
import com.cap.entity.RoleUser;
/**
* @author C.H
* @date 2021/6/16 16:17
*/
public interface RoleUserMapper {
int insert(RoleUser record);
} |
PHP | UTF-8 | 904 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | <?php
#
# cool, url rewrite function ;-)
#
function rewrite($url, $param) {
global $XCOW_B;
$rewrite = array();
$matches = array();
$rewrite['match'] = 0;
foreach ($XCOW_B['rewrite'] as $rewrite_key => $rewrite_value) {
if (preg_match ("/^".my_quote_forward($rewrite_key)."$/", $url, $matches)) {
$rewrite['match'] = 1;
# $rewrite['url'] = $rewrite_value['url'];
$rewrite['url'] = preg_replace ("/^(.*)\/\\\$(.*)\/(.*)$/e", "'$1/'.\$matches[$2].'/$3'", $rewrite_value['url']);
$rewrite['param'] = array();
if (is_array($rewrite_value['param'])) {
foreach ($rewrite_value['param'] as $param_key => $param_value) {
if (preg_match ("/^\\\$(.*)$/", $param_value, $param_matches)) {
$rewrite['param'][$param_key] = $matches[$param_matches[1]];
}
else {
$rewrite['param'][$param_key] = $param_value;
}
}
}
}
}
return $rewrite;
}
?>
|
C | UTF-8 | 1,114 | 2.84375 | 3 | [
"BSD-2-Clause"
] | permissive | /*******************************************************************************
*
* kit/system/util/key.c
* - inspects key events until Ctrl+D is pressed
*
* vim:ts=2:sw=2:et:tw=80:ft=c
*
* Copyright (C) 2013, Devyn Cairns
* Redistribution of this file is permitted under the terms of the simplified
* BSD license. See LICENSE for more information.
*
******************************************************************************/
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <kit/syscall.h>
#define UNUSED __attribute__((__unused__))
int main(UNUSED int argc, UNUSED char **argv)
{
keyboard_event_t event;
event.keychar = '\0';
while (!(event.ctrl_down && event.keychar == 'd'))
{
syscall_key_get(&event);
char event_info[6];
event_info[0] = event.keychar;
event_info[1] = event.pressed ? 'P' : '-';
event_info[2] = event.ctrl_down ? 'C' : '-';
event_info[3] = event.alt_down ? 'A' : '-';
event_info[4] = event.shift_down ? 'S' : '-';
event_info[5] = '\n';
syscall_twrite(sizeof(event_info), event_info);
}
return 0;
}
|
Python | UTF-8 | 1,839 | 2.5625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import cPickle
import load_data
import argparse
# WORD2INDEX_FILE_PATH = "/home/ubuntu/data/word2vec/small/word2index.pkl" # input
# JAWIKI_WAKATI_FILE_PATH = "/home/ubuntu/data/word2vec/original/jawiki-wakati.txt" # input
# INDEX_SEQUENCE_FILE_PATH = "/home/ubuntu/data/word2vec/original_with_small_vocabulary/jawiki-wakati-index-sequence.txt" # output
# test ok
def get_index(word2index, token):
return word2index[token] if token in word2index else word2index[load_data.UNKNOWN_WORD]
# test ok
def save(jawiki_wakati_file_path, word2index_file_path, index_sequence_file_path):
fout = open(index_sequence_file_path, "w")
word2index = cPickle.load(open(word2index_file_path))
for line in open(jawiki_wakati_file_path):
tokens = line.strip().split()
indices = [str(get_index(word2index, token)) for token in tokens]
seq = " ".join(indices)
fout.write("{}\n".format(seq))
def index_generator(index_sequence_file_path):
for line in open(index_sequence_file_path):
tokens = line.strip().split()
for token in tokens:
yield int(token)
if __name__ == "__main__":
# set command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--word2index_file_path", help="input: set a path to a word2index file")
parser.add_argument("--wiki_file_path", help="input: set a path to a wiki file")
parser.add_argument("--index_sequence_file_path", help="output: set a path to a index sequence file")
# parse arguments
args = parser.parse_args()
word2index_file_path = args.word2index_file_path
wiki_file_path = args.wiki_file_path
index_sequence_file_path = args.index_sequence_file_path
save(wiki_file_path, word2index_file_path, index_sequence_file_path)
|
C | UTF-8 | 1,827 | 2.921875 | 3 | [] | no_license | #include "tabelaf.h"
#include <stdio.h>
#include <string.h>
void inicializaTabela(TabelaFrequencia *Tabela){
int i; char caracter;
caracter = 'z';
for(i=0; i<MAX/2 ; i++){
Tabela->Simbolos[i].caracter = caracter;
Tabela->Simbolos[i].ocorrencia = 0;
caracter--;
}
caracter = 'Z';
for(i=i; i<MAX-1; i++){
Tabela->Simbolos[i].caracter = caracter;
Tabela->Simbolos[i].ocorrencia = 0;
caracter--;
}
Tabela->Simbolos[i].caracter = ' ';
Tabela->Simbolos[i].ocorrencia = 0;
}
int getTam(TabelaFrequencia *Tabela){
int i = MAX-1;
while ( Tabela->Simbolos[i].ocorrencia != 0 && i < MAX) {i--;}
return i+1;
}
void insere(TabelaFrequencia *Tabela, char * string){
int tamanhostring , i, indice, esq, dir;
tamanhostring = strlen(string);
for(i=0; i<tamanhostring; i++){
esq = 0; dir = MAX - 1;
do{
indice = ( esq + dir )/2 ;
if(string[i] < Tabela->Simbolos[indice].caracter)
esq = indice + 1;
else
dir = indice - 1;
}while(Tabela->Simbolos[indice].caracter != string[i]);
Tabela->Simbolos[indice].ocorrencia ++;
}
}
void ordena(TabelaFrequencia *Tabela){
int i, j, max, aux;
char str;
for(i = MAX-1; i > 0; i--){
max = i;
for(j = i-1; j >=0; j--){
if(Tabela->Simbolos[j].ocorrencia > Tabela->Simbolos[max].ocorrencia || (Tabela->Simbolos[j].ocorrencia == Tabela->Simbolos[max].ocorrencia && Tabela->Simbolos[j].caracter < Tabela->Simbolos[max].caracter)){
max = j;
}
}
if(i != max){
aux = Tabela->Simbolos[i].ocorrencia;
str = Tabela->Simbolos[i].caracter;
Tabela->Simbolos[i].ocorrencia = Tabela->Simbolos[max].ocorrencia;
Tabela->Simbolos[i].caracter = Tabela->Simbolos[max].caracter;
Tabela->Simbolos[max].ocorrencia = aux;
Tabela->Simbolos[max].caracter = str;
}
}
} |
Python | UTF-8 | 2,483 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | import redis
from random import choice
import time
import aiohttp
import asyncio
import sys
import requests
try:
from aiohttp import ClientError
except:
from aiohttp import ClientProxyConnectionError as ProxyConnectionError
class IpLib:
host='192.168.5.31'
port=6381
db=0
key='ip_t'
default_score=10
min_score=8
test_url='http://www.baidu.com'
def get_cli(self):
"""
初始化客户端
"""
cli=redis.StrictRedis(host=self.host,port=self.port,db=self.db)
return cli
def save_ip_port(self,ip_port):
"""
保存代理
"""
cli=self.get_cli()
val={ip_port:self.default_score}
cli.zadd(self.key,val,nx=True)
def decrease_ip_port(self,ip_port):
"""
检测代理有效期
"""
cli=self.get_cli()
score=cli.zscore(self.key,ip_port)
if score<self.min_score:
cli.zrem(self.key,ip_port)
else:
cli.zincrby(self.key,-1,ip_port)
def ip_count(self):
"""
检测代理总数
"""
cli=self.get_cli()
return cli.zcard(self.key)
def random(self):
"""
随机获取一个代理
"""
cli=self.get_cli()
l=list(range(self.min_score-1,self.default_score+1))
while True:
s=l.pop();
if s:
result =cli.zrangebyscore(self.key,s,s)
if len(result):
ip_port= choice(result)
# self.decrease_ip_port(ip_port)
return ip_port
else:
return None
def check_and_get(self):
"""
检验代理是否有效
"""
ip_port=self.random()
str_ip_port=ip_port
if isinstance(str_ip_port, bytes):
str_ip_port = str_ip_port.decode('utf-8')
real_proxy = 'http://' + str_ip_port
print('real_proxy:'+str_ip_port)
proxy_dict={
'http':real_proxy,
'https':real_proxy
}
try:
session=requests.Session();
response=session.get(self.test_url,proxies=proxy_dict,timeout=20)
if response.status_code in [200,302]:
return str_ip_port
except Exception as e:
print(e)
self.decrease_ip_port(ip_port)
return None
|
C# | UTF-8 | 10,506 | 2.609375 | 3 | [
"MIT"
] | permissive | using SummerBoot.Core;
using SummerBoot.Repository.Generator.Dto;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SummerBoot.Repository.Core;
namespace SummerBoot.Repository.Generator.Dialect.SqlServer
{
public class SqlServerDatabaseInfo :AbstractDatabaseInfo, IDatabaseInfo
{
private readonly IDbFactory dbFactory;
public SqlServerDatabaseInfo(IDbFactory dbFactory):base("[", "]", dbFactory.DatabaseUnit)
{
this.dbFactory = dbFactory;
}
public override GenerateDatabaseSqlResult CreateTable(DatabaseTableInfoDto tableInfo)
{
var tableName = tableInfo.Name;
var fieldInfos = tableInfo.FieldInfos;
var schemaTableName = GetSchemaTableName(tableInfo.Schema, tableName);
var body = new StringBuilder();
body.AppendLine($"CREATE TABLE {schemaTableName} (");
//主键
var keyField = "";
var hasKeyField = fieldInfos.Any(it => it.IsKey);
//数据库注释
var databaseDescriptions = new List<string>();
if (tableInfo.Description.HasText())
{
var tableDescriptionSql = CreateTableDescription(tableInfo.Schema, tableName, tableInfo.Description);
databaseDescriptions.Add(tableDescriptionSql);
}
for (int i = 0; i < fieldInfos.Count; i++)
{
var fieldInfo = fieldInfos[i];
//行末尾是否有逗号
var lastComma = "";
if (i != fieldInfos.Count - 1)
{
lastComma = ",";
}
else
{
lastComma = hasKeyField ? "," : "";
}
body.AppendLine($" {GetCreateFieldSqlByFieldInfo(fieldInfo, false)}{lastComma}");
if (fieldInfo.IsKey)
{
keyField = fieldInfo.ColumnName;
}
//添加行注释
if (fieldInfo.Description.HasText())
{
var tableFieldDescription = CreateTableFieldDescription(tableInfo.Schema, tableName, fieldInfo);
databaseDescriptions.Add(tableFieldDescription);
}
}
if (keyField.HasText())
{
body.AppendLine($" CONSTRAINT PK_{tableName} PRIMARY KEY ({keyField})");
}
body.AppendLine($")");
var result = new GenerateDatabaseSqlResult()
{
Body = body.ToString(),
Descriptions = databaseDescriptions,
FieldModifySqls = new List<string>()
};
return result;
}
/// <summary>
/// 通过字段信息生成生成表的sql
/// </summary>
/// <param name="fieldInfo"></param>
/// <returns></returns>
private string GetCreateFieldSqlByFieldInfo(DatabaseFieldInfoDto fieldInfo, bool isAlter)
{
var identityString = fieldInfo.IsAutoCreate ? "IDENTITY(1,1)" : "";
var nullableString = fieldInfo.IsNullable ? "NULL" : "NOT NULL";
var columnDataType = fieldInfo.ColumnDataType;
var primaryKeyString = fieldInfo.IsAutoCreate && fieldInfo.IsKey && isAlter ? "PRIMARY KEY" : "";
var defaultString = fieldInfo.ColumnType.IsNumberType() && !fieldInfo.IsNullable && isAlter && !fieldInfo.IsKey ? "DEFAULT 0" : "";
//string类型默认长度max,也可自定义
if (fieldInfo.ColumnDataType == "nvarchar")
{
columnDataType = fieldInfo.StringMaxLength.HasValue && fieldInfo.StringMaxLength.Value != int.MaxValue
? $"nvarchar({fieldInfo.StringMaxLength.Value})"
: $"nvarchar(max)";
}
//自定义decimal精度类型
if (fieldInfo.ColumnDataType == "decimal")
{
columnDataType =
$"decimal({fieldInfo.Precision},{fieldInfo.Scale})";
}
if (fieldInfo.SpecifiedColumnDataType.HasText())
{
columnDataType = fieldInfo.SpecifiedColumnDataType;
}
var columnName = BoxColumnName(fieldInfo.ColumnName);
var result = $"{columnName} {columnDataType}";
if (defaultString.HasText())
{
result += $" {defaultString}";
}
if (identityString.HasText())
{
result += $" {identityString}";
}
if (primaryKeyString.HasText())
{
result += $" {primaryKeyString}";
}
if (nullableString.HasText())
{
result += $" {nullableString}";
}
//var result = $"{columnName} {columnDataType} {defaultString} {identityString} {primaryKeyString} {nullableString}".MergeSpace();
return result;
}
public override string CreateTableDescription(string schema, string tableName, string description)
{
schema = GetDefaultSchema(schema);
var sql =
$"EXEC sp_addextendedproperty 'MS_Description', N'{description}', 'schema', N'{schema}', 'table', N'{tableName}'";
return sql;
}
public override string UpdateTableDescription(string schema, string tableName, string description)
{
schema = GetDefaultSchema(schema);
var sql =
$"EXEC sp_updateextendedproperty 'MS_Description', N'{description}', 'schema', N'{schema}', 'table', N'{tableName}'";
return sql;
}
public override string CreateTableField(string schema, string tableName, DatabaseFieldInfoDto fieldInfo)
{
var schemaTableName = GetSchemaTableName(schema, tableName);
var sql = $"ALTER TABLE {schemaTableName} ADD {GetCreateFieldSqlByFieldInfo(fieldInfo, true)}";
return sql;
}
public override string CreateTableFieldDescription(string schema, string tableName, DatabaseFieldInfoDto fieldInfo)
{
schema = GetDefaultSchema(schema);
var sql =
$"EXEC sp_addextendedproperty 'MS_Description', N'{fieldInfo.Description}', 'schema', N'{schema}', 'table', N'{tableName}', 'column', N'{fieldInfo.ColumnName}'";
return sql;
}
public override string UpdateTableFieldDescription(string schema, string tableName, DatabaseFieldInfoDto fieldInfo)
{
schema = GetDefaultSchema(schema);
var sql =
$"EXEC sp_updateextendedproperty 'MS_Description', N'{fieldInfo.Description}', 'schema', N'{schema}', 'table', N'{tableName}', 'column', N'{fieldInfo.ColumnName}'";
return sql;
}
public override DatabaseTableInfoDto GetTableInfoByName(string schema, string tableName)
{
schema = GetDefaultSchema(schema);
var dbConnection = dbFactory.GetDbConnection();
var sql = @"select c.name as columnName,t.name as columnDataType
,convert(bit,c.IsNullable) as isNullable
,convert(bit,case when exists(select 1 from sysobjects where xtype='PK' and parent_obj=c.id and name in (
select name from sysindexes where indid in(
select indid from sysindexkeys where id = c.id and colid=c.colid))) then 1 else 0 end)
as IsKey
,convert(bit,COLUMNPROPERTY(c.id,c.name,'IsIdentity')) as isAutoCreate
,c.Length as [占用字节]
,COLUMNPROPERTY(c.id,c.name,'PRECISION') as Precision
,isnull(COLUMNPROPERTY(c.id,c.name,'Scale'),0) as Scale
,ISNULL(CM.text,'') as [默认值]
,isnull(ETP.value,'') AS Description
from syscolumns c
inner join systypes t on c.xusertype = t.xusertype
left join sys.extended_properties ETP on ETP.major_id = c.id and ETP.minor_id = c.colid and ETP.name ='MS_Description'
left join syscomments CM on c.cdefault=CM.id
where c.id = (select t.object_id from sys.tables t join sys.schemas s on t.schema_id=s.schema_id where s.name =@schemaName and t.name =@tableName) ";
var fieldInfos = dbConnection.Query<DatabaseFieldInfoDto>(databaseUnit, sql, new { tableName, schemaName = schema }).ToList();
var tableDescriptionSql = @"select etp.value from SYS.OBJECTS c
left join sys.extended_properties ETP on ETP.major_id = c.object_id
where c.object_id =(select t.object_id from sys.tables t join sys.schemas s on t.schema_id=s.schema_id where s.name =@schemaName and t.name =@tableName) and minor_id =0";
var tableDescription = dbConnection.QueryFirstOrDefault<string>(databaseUnit, tableDescriptionSql, new { tableName, schemaName = schema });
var result = new DatabaseTableInfoDto()
{
Name = tableName,
Description = tableDescription,
FieldInfos = fieldInfos
};
return result;
}
public override string GetSchemaTableName(string schema, string tableName)
{
tableName = BoxTableName(tableName);
tableName = schema.HasText() ? schema + "." + tableName : tableName;
return tableName;
}
public override string CreatePrimaryKey(string schema, string tableName, DatabaseFieldInfoDto fieldInfo)
{
//var schemaTableName = GetSchemaTableName(schema, tableName);
//var sql =
// $"ALTER TABLE {schemaTableName} ADD CONSTRAINT {tableName}_PK PRIMARY KEY({fieldInfo.ColumnName})";
//return sql;
return "";
}
public override string GetDefaultSchema(string schema)
{
if (schema.HasText())
{
return schema;
}
var dbConnection = dbFactory.GetDbConnection();
var result = dbConnection.QueryFirstOrDefault<string>(databaseUnit, "select SCHEMA_name()");
return result;
}
}
} |
Ruby | UTF-8 | 660 | 2.53125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Kikubari
class Deploy
class Logger
def head(message)
p "*" * 80
p "* #{message}"
p "*" * 80
p ""
end
def run(message, folder = nil )
print( message, "Executing: " )
p " in folder: #{folder} " unless folder.nil?
end
def error ( message )
print( message, "Error:" )
end
def result ( message )
print( message, "Out:" )
end
def info( message )
print( message )
end
def print(message, status = "")
p "[#{DateTime.now.strftime('%Y%m%d %H:%M:%S')}] #{status} #{message}"
end
end
end
end
|
Java | UTF-8 | 13,021 | 2.359375 | 2 | [
"Apache-2.0"
] | permissive | /** See the file "LICENSE" for the full license governing this code. */
package au.org.ands.vocabs.registry.workflow.provider.backup;
import java.io.IOException;
import java.io.InputStream;
import java.lang.invoke.MethodHandles;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.org.ands.vocabs.registry.db.dao.PoolPartyServerDAO;
import au.org.ands.vocabs.registry.db.entity.PoolPartyServer;
import au.org.ands.vocabs.registry.utils.PoolPartyUtils;
import au.org.ands.vocabs.registry.utils.RegistryFileUtils;
import au.org.ands.vocabs.registry.utils.RegistryNetUtils;
import au.org.ands.vocabs.registry.workflow.tasks.TaskRunner;
import au.org.ands.vocabs.registry.workflow.tasks.TaskUtils;
import ch.qos.logback.classic.Level;
/** Backup provider for PoolParty. */
public class PoolPartyBackupProvider {
/** The logger for this class. */
private final Logger logger = LoggerFactory.getLogger(
MethodHandles.lookup().lookupClass());
/** Get all PoolParty project IDs.
* @return An ArrayList of all IDs as Strings.
*/
public final ArrayList<String> getProjectIDs() {
PoolPartyServer poolPartyServer =
PoolPartyServerDAO.getPoolPartyServerById(1);
if (poolPartyServer == null) {
logger.error("PoolParty server 1 undefined.");
return null;
}
String remoteUrl = poolPartyServer.getApiUrl();
String username = poolPartyServer.getUsername();
String password = poolPartyServer.getPassword();
logger.debug("Getting metadata from " + remoteUrl);
Client client = RegistryNetUtils.getClient();
WebTarget target = client.target(remoteUrl)
.path(PoolPartyUtils.API_PROJECTS);
HttpAuthenticationFeature feature =
HttpAuthenticationFeature.basic(username, password);
target.register(feature);
Invocation.Builder invocationBuilder =
target.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
InputStream is = response.readEntity(InputStream.class);
// Now extract the project IDs from the returned data and store
// in the ArrayList that will be returned.
JsonReader jsonReader = Json.createReader(is);
JsonArray jsonStructure = jsonReader.readArray();
ArrayList<String> pList = new ArrayList<>();
Iterator<JsonValue> iter = jsonStructure.iterator();
while (iter.hasNext()) {
JsonObject entry = (JsonObject) iter.next();
pList.add(entry.getString("id"));
}
// Tidy up I/O resources.
try {
is.close();
} catch (IOException e) {
logger.error("Exception while closing InputStream", e);
}
response.close();
return pList;
}
/** Error message returned if there is an error reading backup
* data from PoolParty. */
public static final String ERROR_READING_FROM_POOLPARTY =
"getBackupFiles got an error reading from PoolParty: ";
/** Do a backup of one PoolParty project. Return a list with the result
* of the backup.
* @param ppProjectId The PoolParty project id.
* @param outputPath The directory in which to store output files.
* of each harvested file in the results map.
* @return results HashMap representing the result of the backup.
*/
public final HashMap<String, String> getBackupFiles(
final String ppProjectId,
final String outputPath) {
HashMap<String, String> result = new HashMap<>();
PoolPartyServer poolPartyServer =
PoolPartyServerDAO.getPoolPartyServerById(1);
if (poolPartyServer == null) {
logger.error("PoolParty server 1 undefined.");
return null;
}
String remoteUrl = poolPartyServer.getApiUrl();
String username = poolPartyServer.getUsername();
String password = poolPartyServer.getPassword();
// Has to be either TriG or TriX.
// We could do this as a Toolkit property (as we used to,
// though incorrectly piggy-backing the PP harvester setting),
// but there does not yet appear to be a gain.
String format = "TriG";
List<String> exportModules = new ArrayList<>();
// The following list of export modules comes from:
// https://help.poolparty.biz/doc/developer-guide/
// basic-advanced-server-apis/poolparty-api-guide/
// general-remarks-concerning-poolparty-api/
// poolparty-project-modules
// If the list on the web page changes, change the following ...
exportModules.add("concepts");
exportModules.add("workflow");
exportModules.add("history");
exportModules.add("suggestedConcepts");
exportModules.add("void");
exportModules.add("adms");
exportModules.add("candidateConcepts");
exportModules.add("lists");
exportModules.add("deprecatedConcepts");
exportModules.add("skosnotes");
exportModules.add("linkedData");
logger.debug("Getting project from " + remoteUrl);
Client client = RegistryNetUtils.getClient();
// Tip: in case you ever need to debug the traffic to/from
// PoolParty, uncomment the following. You'll need to add an import
// for the class org.glassfish.jersey.filter.LoggingFilter.
// (NB: works with Jersey 2.22.1. For later releases, use
// LoggingFeature instead.)
// client.register(new LoggingFilter(
// java.util.logging.Logger.getGlobal(), true));
WebTarget target = client.target(remoteUrl).
path(PoolPartyUtils.API_PROJECTS);
HttpAuthenticationFeature feature =
HttpAuthenticationFeature.basic(username, password);
WebTarget thisTarget = target.register(feature)
.path(ppProjectId)
.path("export");
Invocation.Builder invocationBuilder =
thisTarget.request(MediaType.APPLICATION_XML);
// Since PoolParty API version 7.1, the parameters
// are sent in the body of a POST, in JSON format.
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("format", format);
JsonArrayBuilder jab = Json.createArrayBuilder();
for (String exportModule : exportModules) {
jab.add(exportModule);
}
job.add("modules", jab);
// API documentation now says that the prettyPrint parameter is
// required, but that seems to be incorrect. Provide a
// value anyway. We used to get the default value of false,
// and that seemed to work OK for us, so continue to specify
// false.
job.add("prettyPrint", false);
// Override the timeout values for this request.
RegistryNetUtils.setTimeouts(invocationBuilder);
Response response;
try {
// It's necessary to use job.build().toString(), not just
// job.build(), because otherwise you get extra metadata
// in the generated String, e.g.,
// {"format":{"valueType":"STRING","chars":"Turtle",
// "string":"Turtle"}, ... etc.
response = invocationBuilder.post(
Entity.json(job.build().toString()));
} catch (Exception e) {
// Can't catch SocketTimeoutException directly, but only
// the encapsulating ProcessingException. In that case,
// e.getCause() is the SocketTimeoutException.
logger.error("Exception fetching data from PoolParty; "
+ "project ID = " + ppProjectId + ": ", e);
String message;
Throwable cause = e.getCause();
if (cause != null) {
message = cause.getMessage();
} else {
message = e.getMessage();
}
logger.error(ERROR_READING_FROM_POOLPARTY
+ message);
// This is an abuse of the task status codes, because
// it is not a task.
result.put(TaskRunner.ERROR, ERROR_READING_FROM_POOLPARTY
+ message);
return result;
}
if (response.getStatus()
< Response.Status.BAD_REQUEST.getStatusCode()) {
String responseData = response.readEntity(String.class);
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);
String fileName = dateFormat.format(date) + "-backup";
String filePath = RegistryFileUtils.saveRDFToFile(
outputPath,
fileName,
format, responseData);
result.put(fileName, filePath);
} else {
logger.error("getBackupFiles got an error from PoolParty; "
+ "project ID = " + ppProjectId + "; "
+ "response code = " + response.getStatus());
// This is an abuse of the task status codes, because
// it is not a task.
result.put(TaskRunner.ERROR, "getBackupFiles got an error "
+ "from PoolParty; "
+ "response code = " + response.getStatus());
}
// Tidy up I/O resources.
response.close();
return result;
}
/** Do a backup. Update the result parameter with the result
* of the backup.
* @param pPProjectId Either the PoolParty project ID, or null for all
* projects.
* @return the complete list of the backup files.
*/
public final HashMap<String, Object> backup(final String pPProjectId) {
ArrayList<String> pList;
HashMap<String, Object> results = new HashMap<>();
if (pPProjectId == null || pPProjectId.isEmpty()) {
pList = getProjectIDs();
} else {
pList = new ArrayList<>();
pList.add(pPProjectId);
}
for (String projectId : pList) {
try {
TaskUtils.compressBackupFolder(projectId);
} catch (IOException ex) {
results.put(TaskRunner.ERROR, "Unable to compress folder"
+ " for projectId:" + projectId);
logger.error("Unable to compress folder", ex);
}
results.put(projectId, getBackupFiles(projectId,
TaskUtils.getBackupPath(projectId)));
}
return results;
}
/**
* Main method to allow running backups from the command line.
* @param args Command-line arguments.
* If the first argument is "-d", enable debugging; otherwise,
* debugging output is disabled. Then either specify one
* Poolparty project ID, or specify no additional parameters to backup
* all projects.
*/
public static void main(final String[] args) {
// The value specified as a parameter to getLogger() must be
// specific enough to cover any settings in logback.xml.
// The casting is done to enable the subsequent call to setLevel().
ch.qos.logback.classic.Logger rootLogger =
(ch.qos.logback.classic.Logger)
org.slf4j.LoggerFactory.getLogger(
"au.org.ands.vocabs");
// Put command-line arguments into an ArrayList to make them
// easier to process. (I.e., as one would use "shift" in
// Bourne shell.)
ArrayList<String> argsList = new ArrayList<>(Arrays.asList(args));
if (argsList.size() > 0 && "-d".equals(argsList.get(0))) {
rootLogger.setLevel(Level.DEBUG);
argsList.remove(0);
} else {
rootLogger.setLevel(Level.INFO);
}
switch (argsList.size()) {
case 0:
new PoolPartyBackupProvider().backup(null);
break;
case 1:
new PoolPartyBackupProvider().backup(argsList.get(0));
break;
default:
rootLogger.error("Wrong number of arguments.");
System.exit(1);
}
}
}
|
Java | UTF-8 | 942 | 2.90625 | 3 | [] | no_license | package model;
import org.json.JSONException;
import org.json.JSONObject;
public class CurrentWeatherReport{
public final String cityName;
public final Coordinates coordinates;
public final int currentTemperature;
public CurrentWeatherReport(String cityName, Coordinates coordinates, int currentTemperature) {
this.cityName = cityName;
this.coordinates = coordinates;
this.currentTemperature = currentTemperature;
}
@Override
public String toString() {
return "CurrentWeatherReport [cityName=" + cityName + ", coordinates=" + coordinates + ", currentTemperature="
+ currentTemperature + "]";
}
public JSONObject toJSON() throws JSONException {
JSONObject jsonObj = new JSONObject();
jsonObj.put("cityName", cityName);
jsonObj.put("coordinates", coordinates.toJSON());
jsonObj.put("currentTemperature", currentTemperature);
return jsonObj;
}
}
|
Go | UTF-8 | 395 | 3.25 | 3 | [] | no_license | package main
import "fmt"
// Pi this is Pi! 🐈
const Pi = 3.14
const (
// Big is huge
Big = 1 << 100
// Small is small
Small = Big >> 99
)
func needInt(x int) int { return 10*x + 1 }
func needFloat(x float64) float64 {
return x * 0.1
}
func main() {
const World = "🐈"
fmt.Println(World)
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
fmt.Println(needFloat(Big))
}
|
C | UTF-8 | 506 | 2.875 | 3 | [] | no_license | #include <unistd.h>
#include <sys/time.h>
#include "timer.h"
static double timerEndTime;
static int timerActive;
static double get_time(void) {
struct timeval time;
gettimeofday(&time, NULL);
return (double)time.tv_sec + (double)time.tv_usec * .000001;
}
void timer_start(double duration) {
timerEndTime = get_time() + duration;
timerActive = 1;
}
void timer_stop(void) {
timerActive = 0;
}
int timer_isTimeOut(void) {
return timerActive && (get_time() > timerEndTime);
} |
Python | UTF-8 | 1,075 | 3.140625 | 3 | [] | no_license | """
Exploring the spaCy NER items
"""
import spacy
article = '''
Asian shares skidded on Tuesday after a rout in tech stocks put Wall Street to the sword, while a
sharp drop in oil prices and political risks in Europe pushed the dollar to 16-month highs as investors dumped
riskier assets. MSCI’s broadest index of Asia-Pacific shares outside Japan dropped 1.7 percent to a 1-1/2
week trough, with Australian shares sinking 1.6 percent. Japan’s Nikkei dived 3.1 percent led by losses in
electric machinery makers and suppliers of Apple’s iphone parts. Sterling fell to $1.286 after three straight
sessions of losses took it to the lowest since Nov.1 as there were still considerable unresolved issues with the
European Union over Brexit, British Prime Minister Theresa May said on Monday.'''
if __name__ == "__main__":
print("Running spaCy")
spacy_nlp = spacy.load('en')
document = spacy_nlp(article)
print('Original Sentence: %s' % (article))
for element in document.ents:
print('Type: %s, Value: %s' % (element.label_, element))
|
Java | UTF-8 | 3,767 | 2.265625 | 2 | [] | no_license | package cn.meiqu.lainmonitor.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import cn.meiqu.baseproject.baseRecycle.BaseHolder;
import cn.meiqu.baseproject.baseRecycle.BaseRecycleAdapter;
import cn.meiqu.baseproject.view.RippleView;
import cn.meiqu.lainmonitor.R;
import cn.meiqu.lainmonitor.bean.AirF;
public class RecycleAirFRealAdapter extends BaseRecycleAdapter {
private Context mContent;
private ArrayList<AirF> airFs;
private OnAirClickListener onAirClickListener;
public OnAirClickListener getOnAirClickListener() {
return onAirClickListener;
}
public void setOnAirClickListener(OnAirClickListener onAirClickListener) {
this.onAirClickListener = onAirClickListener;
}
public interface OnAirClickListener {
public void onAirClick(int position, String number);
}
public RecycleAirFRealAdapter(Context mContent, ArrayList<AirF> airFs) {
this.mContent = mContent;
this.airFs = airFs;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new Holder(View.inflate(mContent, R.layout.recycle_air, null));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((Holder) holder).instanceView(position);
}
@Override
public int getItemCount() {
return airFs.size();
}
class Holder extends BaseHolder implements RippleView.OnRippleCompleteListener {
public Holder(View itemView) {
super(itemView);
itemView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
private TextView mTvAddr;
private TextView mTvName;
private RippleView mRippleStudyBoot;
private RippleView mRippleStudyOff;
private RippleView mRippleOn;
private RippleView mRippleOff;
public void assignViews() {
mTvAddr = (TextView) findViewById(R.id.tv_addr);
mTvName = (TextView) findViewById(R.id.tv_name);
mRippleStudyBoot = (RippleView) findViewById(R.id.ripple_studyBoot);
mRippleStudyOff = (RippleView) findViewById(R.id.ripple_studyOff);
mRippleOn = (RippleView) findViewById(R.id.ripple_on);
mRippleOff = (RippleView) findViewById(R.id.ripple_off);
mRippleStudyBoot.setOnRippleCompleteListener(this);
mRippleStudyOff.setOnRippleCompleteListener(this);
mRippleOn.setOnRippleCompleteListener(this);
mRippleOff.setOnRippleCompleteListener(this);
}
@Override
public void instanceView(final int position) {
AirF airF = airFs.get(position);
mTvName.setText(airF.getName() + "");
mTvAddr.setText(airF.getAddress() + "");
}
@Override
public void onComplete(RippleView v) {
if (getOnAirClickListener() != null) {
if (mRippleStudyBoot.getId() == v.getId()) {
getOnAirClickListener().onAirClick(getPosition(), "1");
} else if (mRippleStudyOff.getId() == v.getId()) {
getOnAirClickListener().onAirClick(getPosition(), "2");
} else if (mRippleOn.getId() == v.getId()) {
getOnAirClickListener().onAirClick(getPosition(), "3");
} else if (mRippleOff.getId() == v.getId()) {
getOnAirClickListener().onAirClick(getPosition(), "4");
}
}
}
}
}
|
SQL | UTF-8 | 2,730 | 3.546875 | 4 | [] | no_license | USE BD_PLPII;
/*Archivo sql de Alvaro*/
DROP PROCEDURE IF EXISTS usp_ProyectosDirigidos;
DROP PROCEDURE IF EXISTS usp_ProyectosDireccion;
DROP PROCEDURE IF EXISTS usp_ProyectosParticipas;
DROP PROCEDURE IF EXISTS usp_ProyectosParticipados;
/*PROYECTOS DIRIGIDOS*/ /*P_COD_TRABAJADOR CHAR(5)*/
delimiter $$
CREATE PROCEDURE usp_ProyectosDirigidos(P_COD_TRABAJADOR CHAR(5))
BEGIN
SELECT P.NUM_PROYECTO, FECHA_REG_PROYECTO, FECHA_ACT_PROYECTO, DEPARTAMENTO_PROYECTO, PROVINCIA_PROYECTO,
DISTRITO_PROYECTO, DIRECCION_PROYECTO, ETAPA_PROYECTO, COSTO_PROYECTO, MONTO_TOTAL_PROYECTO,
CAN_MES_TRABAJO, NUM_SOLICITUD
FROM PROYECTO P INNER JOIN DETALLE_PROYECTO DP
ON P.NUM_PROYECTO = DP.NUM_PROYECTO
WHERE DP.COD_TRABAJADOR = P_COD_TRABAJADOR AND ETAPA_PROYECTO = 'CUARTA';
end $$
delimiter ;
call usp_ProyectosDirigidos('T1010');
select * from PROYECTO;
/*PROYECTOS EN DIRECCIÓN*/
delimiter $$
CREATE PROCEDURE usp_ProyectosDireccion(P_COD_TRABAJADOR CHAR(5))
BEGIN
SELECT P.NUM_PROYECTO, FECHA_REG_PROYECTO, FECHA_ACT_PROYECTO, DEPARTAMENTO_PROYECTO, PROVINCIA_PROYECTO,
DISTRITO_PROYECTO, DIRECCION_PROYECTO, ETAPA_PROYECTO, COSTO_PROYECTO, MONTO_TOTAL_PROYECTO,
CAN_MES_TRABAJO, NUM_SOLICITUD
FROM PROYECTO P INNER JOIN DETALLE_PROYECTO DP
ON P.NUM_PROYECTO = DP.NUM_PROYECTO
WHERE DP.COD_TRABAJADOR = P_COD_TRABAJADOR AND ETAPA_PROYECTO = 'PRIMERA'
OR ETAPA_PROYECTO = 'SEGUNDA' OR ETAPA_PROYECTO = 'TERCERA';
end $$
delimiter ;
call usp_ProyectosDireccion('T1010');
/*PROYECTOS EN LOS QUE PARTICIPAS*/
delimiter $$
CREATE PROCEDURE usp_ProyectosParticipas(P_COD_TRABAJADOR CHAR(5))
BEGIN
SELECT P.NUM_PROYECTO, FECHA_REG_PROYECTO, FECHA_ACT_PROYECTO, DEPARTAMENTO_PROYECTO, PROVINCIA_PROYECTO,
DISTRITO_PROYECTO, DIRECCION_PROYECTO, ETAPA_PROYECTO, COSTO_PROYECTO, MONTO_TOTAL_PROYECTO,
CAN_MES_TRABAJO, NUM_SOLICITUD, SUELDO_MES, SUELDO_TOTAL
FROM PROYECTO P INNER JOIN DETALLE_PROYECTO DP
ON P.NUM_PROYECTO = DP.NUM_PROYECTO
WHERE DP.COD_TRABAJADOR = P_COD_TRABAJADOR AND P.ETAPA_PROYECTO = 'PRIMERA'
OR ETAPA_PROYECTO = 'SEGUNDA' OR ETAPA_PROYECTO = 'TERCERA';
end $$
delimiter ;
call usp_ProyectosParticipas('T1010');
/*PROYECTOS PARTICIPADOS*/
delimiter $$
CREATE PROCEDURE usp_ProyectosParticipados(P_COD_TRABAJADOR CHAR(5))
BEGIN
SELECT P.NUM_PROYECTO, FECHA_REG_PROYECTO, FECHA_ACT_PROYECTO, DEPARTAMENTO_PROYECTO, PROVINCIA_PROYECTO,
DISTRITO_PROYECTO, DIRECCION_PROYECTO, ETAPA_PROYECTO, COSTO_PROYECTO, MONTO_TOTAL_PROYECTO,
CAN_MES_TRABAJO, NUM_SOLICITUD, SUELDO_MES, SUELDO_TOTAL
FROM PROYECTO P INNER JOIN DETALLE_PROYECTO DP
ON P.NUM_PROYECTO = DP.NUM_PROYECTO
WHERE DP.COD_TRABAJADOR = P_COD_TRABAJADOR AND ETAPA_PROYECTO = 'CUARTA';
end $$
delimiter ;
call usp_ProyectosParticipados('T1010'); |
Markdown | UTF-8 | 1,920 | 3.125 | 3 | [] | no_license | @@ -1,19 +0,0 @@
### Github 的用途
#### 最强大的功能
- Github 最强大的功能是:协作、同步,同时包括:追溯、审核、管理
> 写代码是一件很重的任务,尤其是很多人完成一个很大的项目的时候,就十分的复杂,一群人一起来写某个项目,大家完成的时间,完成的进度都是不相同的,你写一点我写一点,甚至可能你今天写的出现了错误,影响到了我昨天写的代码,最后怎么才能将大家的代码轻松的汇总起来,又怎么在汇总所有人的代码之后发现错误等等一系列问题。这样我们就用到了GitHub这个软件。
>
> GitHub 的很强大的功能就是,你在服务器上创建一个库,一个主仓库,这里用来储存你的所有代码。如果不付费的话是所有人都可以看的,如果你不想让别人看到你的代码,可以选择付费仓库。我们创建了主仓库之后,就可以在电脑上创建分支,之后你就可以在电脑上完成自己的代码,写完之后直接同步在电脑的分支,当你认为可以上传的自己的主仓库时,就可以申请更新,当通过审核的时候,你代码就出现在了自己的主仓库中,这样全世界的程序员都可以查看你的代码。
#### 其它功能
1. 众多开源项目
- 全世界现在已经有300万的注册用户,甚至还有一些相当知名的开源项目也在其中公布代码。在GitHub上你可以看到很多计算机领域的精英所分享的自己的代码。这是GitHub的两个主要优点,适合团队协作,以及下载其他优秀者的代码。
2. 个人代码托管
- 相当于云存储
3. 个人博客
- 虽然博客网站很多,但是 Github 有它自己独特且强大的功能,用作博客纪录个人心得、经验,同时SNS功能也较便利,开以与同行交流,也是非常专业,好用。
#### test
|
Markdown | UTF-8 | 491 | 3.328125 | 3 | [
"MIT"
] | permissive | [<<< Previous question <<<](0571.md) Question ID#0572.md [>>> Next question >>>](0573.md)
---
How do you declare the return type of a function?
- [ ] A)
```php
function sum($a, $b) :int {return $a + $b;}
```
- [ ] B)
```php
function sum($a, $b) {return (int)$a + $b;}
```
- [ ] C)
```php
function sum($a, $b) => int {return $a + $b;}
```
- [ ] D) It is not possible to define a return type
<details><summary><b>Answer</b></summary>
<p>
Answer: <strong>A</strong>
</p>
</details>
|
JavaScript | UTF-8 | 348 | 2.96875 | 3 | [
"MIT"
] | permissive | /*
Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.
*/
var invert = $.invert = (thisObject, object) => {
object = object || {};
eachObject(thisObject, (item, key) => {
object[item] = key;
});
return object;
};
|
Markdown | UTF-8 | 8,247 | 2.703125 | 3 | [] | no_license | ## Amondar Security Request.
По любым вопросам образаться на e-mail - yurenery@gmail.com. <br/>
Пакет предназначен для изменения и расширения работы стандартныйх Laravel реквестов в защищенных секциях сайта.<br/>
!!! ВАЖНО!!! Для работы с Laravel начиная с версии 5.6 использовать теги - "**^2.0**"
## Для установки
```json
"repositories": [
{
"url": "https://git.attractgroup.com/amondar/SecurityRequest.git",
"type": "git"
}
]
```
```json
"amondar/security-request": "^3.0"
```
## Подключение
Подключите **SecurityRequest** трейт к своему реквесту или создайте обертку для CoreRequest, чтобы не подключать его постоянно.
Пример реквеста с использованием нашего трейта. Обратите внимание, используентся стандартный REST подход при котором на каждый конечный урл вешается один пермишн.<br/>
ВАЖНО: Для более общих пермишнов используйте мидлверы и обратитесь к документации ларавел.<br/>
Для проверок во всех функциях доступны переменные:
```php
$this->action; //Массив дейсвия.
$this->actionName; //Имя действия. Находится в ключе.
```
```php
class CategoryRequest extends FormRequest
{
use SecurityRequest;
/**
* Actions.
*
* @var array
*/
protected $actions = [
'view' => [
'methods' => [ 'GET' ],
'permission' => 'default',
],
'add' => [
'methods' => [ 'POST' ],
'permission' => 'default',
],
'edit' => [
'methods' => [ 'PUT', 'PATCH' ],
'permission' => 'default',
],
'delete' => [
'methods' => [ 'DELETE' ],
'permission' => 'default',
]
];
/**
* Rules array.
*
* @return array
*/
public function rulesArray()
{
$rules = [
'uri' => 'required|alpha_dash|unique:categories',
'is_active' => 'sometimes|boolean',
];
$this->addTranslatableFields($rules, [
'name' => [ 'required', 'string', 'min:1', 'max:255' ]
]);
return $rules;
}
public function messagesArray()
{
return [
'uri.required' => trans_db(app('translations'), 'validation-categories-uri-required', 'Uri is required field.'),
'uri.unique' => trans_db(app('translations'), 'validation-categories-uri-unique', 'Uri with this name already exists.'),
'name_*.required' => trans_db(app('translations'), 'validation-categories-name-required', 'Name is required.'),
'name_*.min' => trans_db(app('translations'), 'validation-categories-name-min', 'Name must be at least :min characters in length.', [ ':min' => 3 ]),
'name_*.max' => trans_db(app('translations'), 'validation-categories-name-max', 'Name must be maximum :max characters in length.', [ ':max' => 255 ]),
];
}
/**
* @return array
*/
protected function postActionMessages()
{
return $this->messagesArray();
}
/**
* Get action rules
*
* @return array
*/
protected function getAction()
{
return [ ];
}
/**
* Post action rules
*
* @return array
*/
protected function postAction()
{
return $this->rulesArray();
}
/**
* Put action rules
*
* @return array
*/
protected function putAction()
{
$rules = $this->rulesArray();
$category_id = $this->route('category');
$rules['uri'] = [ 'required','alpha_dash', Rule::unique('categories', 'uri')->ignore($category_id, '_id') ];
return $rules;
}
/**
* Delete action rules
*
* @return array
*/
protected function deleteAction()
{
return [];
}
}
```
Как вы моджете заметить реквест стал более читабельным.
На каждый тип запросы можно построить свой независимый массив правил и сообщений для ответа на ошибки валидации.<br/>
**ВАЖНО**: Запросы типа PUT и PATCH обрабатываются в функциях с приставкой **put** - **putAction**
## Пермишны и их возможности
Для того чтобы использовать преимущество читабельности, но опустить проверку пермишнов через Laravel Gate Facade используется имя пермишна - **default**.
Это говорит трейту, что на данном запросе не нужна проверка пермишна. Пример с пермишном:
```php
'delete' => [
'methods' => [ 'DELETE' ],
'permission' => 'change-log-delete',
],
```
Данный ключ выполнит проверку - **Auth::user()->can('change-log-delete')**. В случае, если пользователь не имеет права
выполнять запрошенное дейсвие - будет возвращен ответ **403**
## Возможности расширения
Если необходимо описать на один и тот же типа запроса, например, **PUT**, несколько запросов с разным набором правил валидации : можно воспользоваться ключем - **route**
```php
'edit' => [
'methods' => [ 'PUT', 'PATCH' ],
'route' => 'projects/*/groups/*',
'permission' => 'default',
],
'move-to' => [
'methods' => [ 'PUT', 'PATCH' ],
'route' => 'projects/*/groups/move',
'permission' => 'group-task-actions',
],
```
В данном случае трейт проведет сравнение урла в реквесте при помощи стандартной функции Laravel:
```php
$this->is('projects/*/groups/move')
```
В случае успеха данной проверки будет проверен и пермишн доступа для залогиненного юзера.<br/>
ВАЖНО: при появлении таких ключей где используется формулировка с **route** Правила именования функций для таких экшнов меняются. В данной ситуации экшны будут выглядеть так:
```php
/**
* Put method rules apply.
*/
protected function putEditAction()
{
return [];
}
/**
* Put method rules apply.
*/
protected function putMoveToAction()
{
return [];
}
```
Для ввода дополнительных правил проверки в стандартной функции Laravel - **autorise** переопределите ее и не забудьте по умолчанию вернуть ответ parent функции.
```php
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
$group_id = $this->route('group');
$user = detectUser()->user;
if (
! $this->project->isTeammates([ detectUser()->user ]) ||
($group_id && ! $this->project->groups->contains('id_task_group', $group_id)) ||
($this->actionName == 'edit' && $this->task_group_status_id == 2 && $user->cannot('group-begin')) ||
($this->actionName == 'edit' && $this->task_group_status_id == 3 && $user->cannot('group-close'))
) {
return false;
}
return parent::authorize();
}
```
По любым вопросам образаться на e-mail - yurenery@gmail.com
|
C++ | UTF-8 | 791 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <random>
#include <string>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]){
if(argc < 2){
cout << "use ./genmap mapping.txt" << endl;
return 0;
}
string outputFilename(argv[1]);
ofstream ofs(outputFilename);
vector< vector< int > > a;
for(int i = 0;i < 8; i++){
for(int j =0 ; j < 8; j++){
for(int k = 0; k < 8; k++){
std::vector<int> v;
v.push_back(i);
v.push_back(j);
v.push_back(k);
a.push_back(v);
}
}
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(a.begin(), a.end(), g);
for(int i = 0; i < a.size(); i++){
for(int j = 0; j < 3; j++){
ofs << a[i][j] << " ";
}
ofs << 0;
ofs << endl;
}
return 0;
}
|
C++ | UTF-8 | 1,541 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
//GLOBAL VARIABLES
string Menu[10] = {"Salad", "Grilled Cheese", "Tomato Soup", "Yogurt Parfait", "Bourbon", "French Fries", "Fried Chicken", "Chocolate Milkshake", "Oatmeal", "Scrambled Eggs"};
double Price[10] = {3.00, 5.00, 3.00, 4.50, 1.75, 2.00, 8.75, 2.50, 3.00, 4.50};
int Order[100];
int i = 0;
int j = 0;
//PRINTS MENU and ACCEPTS ORDER storing in Order[] Array
void PrintMenu() {
cout << "Menu: " << endl;
cout << "1. Salad" << endl;
cout << "2. Grilled Cheese" << endl;
cout << "3. Tomato Soup" << endl;
cout << "4. Yogurt Parfait" << endl;
cout << "5. Bourbon" << endl;
cout << "6. French Fries" << endl;
cout << "7. Fried Chicken" << endl;
cout << "8. Chocolate Milkshake" << endl;
cout << "9. Oatmeal" << endl;
cout << "10. Scrambled Eggs" << endl << endl;
cout << "What'll you be having then? Enter meal number(s). Type '0' when finished." << endl;
for (i = 0; i < 100; ++i) {
cin >> Order[i];
if (Order[i] == 0) {
break;
}
}
}
//PRINTS recitation of order back to user, CALCULATES total cost
void PrintChoices (int array[]) {
double totalCost = 0;
cout << "You ordered: ";
while (array[j] > 0) {
cout << Menu[array[j] - 1] << ", ";
totalCost = totalCost + Price[array[j] - 1];
++j;
}
cout << endl << "Total Cost: $" << totalCost;
}
int main () {
PrintMenu();
PrintChoices(Order);
} |
Markdown | UTF-8 | 4,727 | 2.8125 | 3 | [] | no_license | # 辟谣
[从双黄连抑制病毒这件事的发布和辟谣上看,我们应当如何向公众有效地传播科学研究结果?](https://www.zhihu.com/question/368933647/answer/993018613)
> Author: #NellNell
Last update: *21/08/2021*
Links: [[中医抗疫]] [[香油防疫]] [[科技抗疫]]
Tags: #新冠Covid-19
谢邀。
这是一个清醒度很高的提问。特别是在这一片讨伐双黄连顺带着妖魔中医的刷屏大潮下,感谢提问。
这是一个逆行的回答。我觉得目前所有关于双黄连的回答,除了抖机灵就是**毫无针对性的反驳**。什么叫毫无针对性?就是你要反驳的是**双黄莲对病毒有抑制作用。**但是这些回答反驳的都是什么?拿“抑制”做文章?质疑时间线?因为出品人以前出品的都是烂货所以这次一定没好货?用道听途说来的药物一般属性做论据?甚至截图一段电影来说“看这就是真相”的阴谋论?
连丁香医生的回答都一样,有一个算一个,没有一个值得看的回答。真的。
丁香医生的回答甚至根本**不是直接否定这一论点**,而是先讨论了一下抑制这个概念使用不规范,然后是对研究流程产生质疑,最后是从双黄连的副作用可能导致腹泻借此嘲讽了一番此操作,**这,就获得了千万赞**。
**你们点赞的时候,是觉得解气多过有理,对不对?**
**难道因为他人的“荒谬”所以针对此荒谬的一切荒谬就自动变成真理了吗?**
**这里所有的所谓“辟谣”,根本不是真正的辟谣。**
所有这些回答,都是【我觉得】这太荒谬了。再以此去寻找荒谬的证据,于是大量脑补、抖机灵、截屏、道听途说、以新的谣言遮盖旧的谣言,用一个无根据的观点去否认另一个无根据的论点。你们实质上认为泄愤比事实更重要。
那篇媒体报道的文章,事实上是无法让人做出有效的反驳的。请问媒体报道告诉你们研究团队研究过程的任何细节了吗?没有!
“实验是如何做的?如何抑制病毒,抑制是如何测量的,抑制效率如何(缩短感染时间还是减少毒性)。对不同严重程度的病人效果一样吗?在病毒感染的那一期有效?安全性如何?” —— 这是一位做药物治疗的科学家的提问,他认为在这些问题被回答以前,他既不能承认也不能否认。而我们呢?我们只是【我觉得】荒谬,于是它就【必然荒谬】。
这事本质上和社会上的“狩猎女巫”行为没有什么两样,都是【先定罪,再一人踩上一脚】。
**我绝不是为双黄莲背书,**我压根儿不知道它的药理机制,但是我也不认为中医就必然不能成为对抗病毒的一个途径。抵抗病毒的最有效途径便是提高自身免疫力,而中医、包括针灸,在提高免疫力这一方面不是没有独到之处。至于双黄连,我并没有相关的专业知识为其背书,但我也不认为其他的回答让我看到了足以驳斥其药理作用的充分论据。
不是不能辟谣,但不要以谣言代替谣言,以谎言遮盖谎言,以抖机灵反驳需要论证的观点。特别是如果你本身就是专家,更不要满嘴咒骂愤世嫉俗以此获得即刻的关注和赞扬,更要小心求证论据充分,而这正是这些医疗自媒体所缺少的。公众的掌声永远比真相更重要。这一点,跟双黄连是不是个joke没关系,是不是joke,都是如此。
---
这些所谓的“辟谣”,真正的意义,其实是其**社会学上的意义**。
它们的意义不在于揭露真相或提供答案,而在于【**促使逼近真相的诞生,以及督促大众传媒在输出科研结果时更加严谨】**。在大众围观和舆论的压力下,国内的研究人员和科学家们能够认真对待他们的科研、建立并遵守相应的流程、要用真实并详尽的数据支撑他们的结论。而媒体在传播这些结论的时候,也要加倍小心和严谨。这个驱动是好的、是有正面意义的,但这个过程也不是没有代价,就是可能会产生**新的谣言和混乱**。
这就是这场“狩猎双黄连”全部的意义了,至于说什么中医邪恶论、什么阴谋说、什么愚民这些无限引申的剧情,看都不用看,更不用细品,没啥可品的,不过是自媒体的趁机营销、以及更多的无稽之谈和恐慌。
怎么说呢?现在的情形就是,老一代的被官(x)媒(x)洗脑,年轻一代自认为有点知识的被自媒体洗脑。
如果避免被洗脑?先把你的情绪放下再说! |
Java | UTF-8 | 12,495 | 1.953125 | 2 | [] | no_license | package com.tour.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.tour.R;
import com.tour.SQLite.DBTour;
import com.tour.SQLite.TourData;
import com.tour.dao.DataJsonParser;
import com.tour.dao.HttpAsynTask;
import com.tour.encoder.PostUtil;
import com.tour.listener.HttpCallBack;
import com.tour.util.NetWorkStatus;
import com.tour.util.PublicData;
import com.tour.util.SaveDataClass;
import com.tour.util.ShowToast;
import com.tour.util.VersionUpdate;
import com.tour.view.WaitDialog;
public class TourLoginActivity extends NotTitleActivity implements HttpCallBack {
private String status = "";
NetWorkStatus networkstatus;
// private boolean NetWorkStatus = false;
private SharedPreferences user_Password;
private Button login;
private EditText editAccount, editPassword;
private String mAccount, mPassword,tip="";
// private ShowToast toast;
private HttpAsynTask httpAsynTask;
private WaitDialog dialog;// “等待”对话框
private List<HashMap<String, List<HashMap<String, String>>>> datalist = new ArrayList<HashMap<String, List<HashMap<String, String>>>>();
public Handler mHandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
init();
networkstatus=new NetWorkStatus();
PublicData.isNetWork=networkstatus.isNetWork(getApplicationContext());//检查联网情况
if(PublicData.isNetWork){
VersionUpdate updates = new VersionUpdate();//更新版本
updates.asyncUpdate(TourLoginActivity.this, true);
}
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case 0:
Toast.makeText(getApplicationContext(), tip, 1000).show();
break;
case 1:
DBTour dbTour=new DBTour(getApplicationContext());//创建数据库
try {
PublicData.isnew = datalist.get(0).get("isnew").get(0).get("isnew");//1 有返回新数据;0没有
PublicData.username = editAccount.getText().toString();
PublicData.password = editPassword.getText().toString();
PublicData.truename = datalist.get(0).get("admin_true_name").get(0).get("admin_true_name");
PublicData.uid = datalist.get(0).get("admin_id").get(0).get("admin_id");
PublicData.gid = datalist.get(0).get("admin_gid").get(0).get("admin_gid");
PublicData.islogin = datalist.get(0).get("admin_check").get(0).get("admin_check");
SaveDataClass saveDataClass=new SaveDataClass();
saveDataClass.saveAccountPassword(getApplicationContext());//保存用户账号密码
if ("1".equals(PublicData.isnew)) {
PublicData.tour_id=datalist.get(0).get("tour_id").get(0).get("tour_id");
PublicData.tour_title=datalist.get(0).get("tour_title").get(0).get("tour_title");
PublicData.tour_zip=datalist.get(0).get("tour_zip").get(0).get("tour_zip");
PublicData.tour_no=datalist.get(0).get("tour_no").get(0).get("tour_no");
PublicData.tour_date=datalist.get(0).get("tour_date").get(0).get("tour_date");
PublicData.tour_update_time=datalist.get(0).get("tour_update_time").get(0).get("tour_update_time");
PublicData.zip_url=datalist.get(0).get("url").get(0).get("url");
String last_updata_time=saveDataClass.getLastUpDataTime(getApplicationContext());
if(!last_updata_time.equals(PublicData.tour_update_time)){//有新压缩包需要更新
PublicData.isUpgrade=true;
Intent intent = new Intent();
intent.setClass(TourLoginActivity.this, RollListActivity.class);//跳转到下载压缩包页面
startActivity(intent);
}else{
PublicData.isUpgrade=false;
Intent intent=new Intent(TourLoginActivity.this,TourTabActivity.class);//直接跳转到团信息页面
startActivity(intent);
}
finish();
}else{
PublicData.isUpgrade=false;
Toast. makeText(TourLoginActivity.this, "暂没出团信息",Toast.LENGTH_LONG).show();
PublicData.tour_id=TourData.queryByUser(TourLoginActivity.this, PublicData.uid);
if(!"".equals(PublicData.tour_id)){
Intent intent=new Intent(TourLoginActivity.this,TourTabActivity.class);//直接跳转到团信息页面
startActivity(intent);
}else{
Intent intent = new Intent();
intent.setClass(TourLoginActivity.this, RollListActivity.class);//跳转到下载压缩包页面
startActivity(intent);
// Intent intent=new Intent(TourLoginActivity.this,TourTabActivity.class);
// startActivity(intent);
}
finish();
}
} catch (Exception e) {
// TODO: handle exception
tip="数据异常";
Toast.makeText(getApplicationContext(), tip, 1000).show();
}
break;
}
}
};
}
private void init() {
login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(listener);
editAccount = (EditText) findViewById(R.id.edit_login_account);
editPassword = (EditText) findViewById(R.id.edit_login_password);
editAccount.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
v.setBackgroundResource(R.drawable.login_edt_account_focus);
} else {
v.setBackgroundResource(R.drawable.login_edt_account_defaulet);
}
}
});
editPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if (hasFocus) {
v.setBackgroundResource(R.drawable.login_edt_pwd_focus);
} else {
v.setBackgroundResource(R.drawable.login_edt_pwd_defaulet);
}
}
});
// toast=new ShowToast();
// if (!PublicData.isNetWork) {//断网时
SaveDataClass saveDataClass=new SaveDataClass();
saveDataClass.getAccountPassword(TourLoginActivity.this);
if(!"".equals(PublicData.username)){
editAccount.setText(PublicData.username);
}
if(!"".equals(PublicData.password)){
editPassword.setText(PublicData.password);
}
// }
}
private OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mAccount=editAccount.getText().toString();
mPassword=editPassword.getText().toString();
PublicData.isNetWork=networkstatus.isNetWork(getApplicationContext());//检查联网情况
if (PublicData.isNetWork) {//有网
if(!"".equals(mAccount)&&!"".equals(mPassword)){
dialog=new WaitDialog(TourLoginActivity.this, android.R.style.Theme_Translucent);
dialog.show();
LoginAsyncTask loginAsyncTask=new LoginAsyncTask();
loginAsyncTask.execute();
}else{
if("".equals(mAccount)&&"".equals(mPassword)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_null_tip),Toast.LENGTH_LONG).show();
}else{
if("".equals(mAccount)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_user_tip),Toast.LENGTH_LONG).show();
}else if("".equals(mPassword)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_password_tip),Toast.LENGTH_LONG).show();
}
}
}
} else {//断网
SaveDataClass saveDataClass=new SaveDataClass();
saveDataClass.getAccountPassword(TourLoginActivity.this);//获取本地账号密码
// saveDataClass.getTourId(getApplicationContext());//获取团id
if(!"".equals(mAccount)&&!"".equals(mPassword)){
if(mAccount.equals(PublicData.username)&&mPassword.equals(PublicData.password)){
PublicData.tour_id=TourData.queryByUser(TourLoginActivity.this, PublicData.uid);
if(!"".equals(PublicData.tour_id)){
Intent intent=new Intent(TourLoginActivity.this,TourTabActivity.class);//直接跳转到团信息页面
startActivity(intent);
}else{
PublicData.isnew="0";
Intent intent = new Intent();
intent.setClass(TourLoginActivity.this, RollListActivity.class);//跳转到下载压缩包页面
startActivity(intent);
}
finish();
}else{
if(!mAccount.equals(PublicData.username)&&!mPassword.equals(PublicData.password)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_error_tip),Toast.LENGTH_LONG).show();
}else {
if(!mAccount.equals(PublicData.username)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_user_errortip),Toast.LENGTH_LONG).show();
}else if(!mPassword.equals(PublicData.password)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_password_errortip),Toast.LENGTH_LONG).show();
}
}
}
}else {
if("".equals(mAccount)&&"".equals(mPassword)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_null_tip),Toast.LENGTH_LONG).show();
}else{
if("".equals(mAccount)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_user_tip),Toast.LENGTH_LONG).show();
}else if("".equals(mPassword)){
Toast. makeText(TourLoginActivity.this, getResources().getString(R.string.login_password_tip),Toast.LENGTH_LONG).show();
}
}
}
}
}
// }
};
/**
* 登录接口
* @author wl
*
*/
class LoginAsyncTask extends AsyncTask<Object, Object, Object>{
@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
loginPost();
return null;
}
@Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (dialog != null && dialog.isShowing())
dialog.dismiss();
if(datalist.size()>0&&datalist.get(0).get("status").get(0).get("status")!=null){
if("1".equals(datalist.get(0).get("status").get(0).get("status"))){
// tip="登录成功!";
mHandler.sendEmptyMessage(1);
}else{
tip=datalist.get(0).get("tips").get(0).get("tips");
mHandler.sendEmptyMessage(0);
}
}else{
tip="网络异常!";
mHandler.sendEmptyMessage(0);
}
}
}
private void loginPost(){
String resultStr = new String("");
PostUtil pu = new PostUtil();
resultStr = pu.getData(new String[]{"act","user_login","name",mAccount,"pwd",mPassword
// ,"imei",PublicDataClass.Imei
});
// System.out.println("登录返回数据"+resultStr);
DataJsonParser jsonParser=new DataJsonParser();
try {
datalist=jsonParser.getDataList(resultStr);
// System.out.println("返回数据"+datalist);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 判断网络状态并设置网络
private boolean NetWorkStatus() {
boolean netSataus = false;
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cwjManager.getActiveNetworkInfo();
if (cwjManager.getActiveNetworkInfo() != null) {
netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
}
return netSataus;
}
@Override
public void httpCallBack(int flag, JSONObject json) {
// TODO Auto-generated method stub
if(json!=null){
Intent intent = new Intent();
intent.putExtra("NetWorkStatus", PublicData.isNetWork);
intent.setClass(TourLoginActivity.this, RollListActivity.class);
startActivity(intent);
}
}
} |
TypeScript | UTF-8 | 2,115 | 2.625 | 3 | [
"MIT"
] | permissive | import { Action } from '@ngrx/store';
import { ICard, IList } from '@boards/core/interfaces';
export enum ArchiveActionTypes {
GET_ARCHIVED_CARDS = '[ARCHIVE] Get Archived Cards',
GET_ARCHIVED_CARDS_SUCCESS = '[ARCHIVE] Get Archived Cards Success',
RESTORE_CARD = '[ARCHIVE] Restore Card',
RESTORE_CARD_SUCCESS = '[ARCHIVE] Restore Card Success',
GET_ARCHIVED_LISTS = '[ARCHIVE] Get Archived Lists',
GET_ARCHIVED_LISTS_SUCCESS = '[ARCHIVE] Get Archived Lists Success',
RESTORE_LIST = '[ARCHIVE] Restore List',
RESTORE_LIST_SUCCESS = '[ARCHIVE] Restore List Success'
}
export class GetArchivedCards implements Action {
readonly type = ArchiveActionTypes.GET_ARCHIVED_CARDS;
constructor(public payload: { boardId: string }) {}
}
export class GetArchivedCardsSuccess implements Action {
readonly type = ArchiveActionTypes.GET_ARCHIVED_CARDS_SUCCESS;
constructor(public payload: { cards: ICard[] }) {}
}
export class RestoreCard implements Action {
readonly type = ArchiveActionTypes.RESTORE_CARD;
constructor(public payload: { cardId: string }) {}
}
export class RestoreCardSuccess implements Action {
readonly type = ArchiveActionTypes.RESTORE_CARD_SUCCESS;
constructor(public payload: { card: ICard }) {}
}
export class GetArchivedLists implements Action {
readonly type = ArchiveActionTypes.GET_ARCHIVED_LISTS;
constructor(public payload: { boardId: string }) {}
}
export class GetArchivedListsSuccess implements Action {
readonly type = ArchiveActionTypes.GET_ARCHIVED_LISTS_SUCCESS;
constructor(public payload: { lists: IList[] }) {}
}
export class RestoreList implements Action {
readonly type = ArchiveActionTypes.RESTORE_LIST;
constructor(public payload: { listId: string }) {}
}
export class RestoreListSuccess implements Action {
readonly type = ArchiveActionTypes.RESTORE_LIST_SUCCESS;
constructor(public payload: { list: IList }) {}
}
export type ArchiveActionsUnion =
| GetArchivedCards
| GetArchivedCardsSuccess
| RestoreCard
| RestoreCardSuccess
| GetArchivedLists
| GetArchivedListsSuccess
| RestoreList
| RestoreListSuccess;
|
Markdown | UTF-8 | 3,242 | 2.953125 | 3 | [] | no_license | #
> 2018000模板
第四部分
27
你为什么不从黑影里走出来?你究竟长得什么样?你是不是在害怕什么?
你害怕些什么呢?
在黑影里的人后面是玻璃门。克里斯要我把门打开,他现在大多了,但是仍然面带恳求。他想知道,“我现在该怎么办?我接下来要做什么呢?”他等待我的指示。
是该行动的时候了。
我仔细研究躲在黑影里的人。他不像过去那样给我不祥的感觉,我问他,“你是谁?”
他没有回答。
“那扇门为什么不可以打开?”
他仍然没有回答。对方保持沉默,这也表示他很怯懦,他害怕的竟然是我。
“还有比躲在暗处更糟的情况是吗?这就是你不说话的原因是吗?”
他似乎意识到我要采取行动了,所以有些害怕地颤抖,想要退缩。
我在一旁等待,然后向他靠近一点。
讨厌、阴暗、邪恶的东西。我靠得更近,不是要看他,而是要看那扇玻璃门。我又停下来,双手抱肩,然后突然将手向前伸出去。
我的手似乎是勒住了他的脖子。他越挣扎,我就勒得更紧,好像捉蟒蛇一样。我愈抓愈紧,想把他拖到明亮的地方。好了,让我们看看他的真面目吧!
“爸爸!爸爸!”我听到门外传来克里斯的声音。
没错!这是我第一次听到声音,“爸爸!爸爸!”
“爸爸!爸爸!”克里斯抓住我的袖子,“爸爸!醒醒!爸爸!”
他在我身旁哭着,“爸爸!醒醒!不要这样!”
“克里斯,没事!”
“爸爸!醒醒!”
“我醒了。”透过薄薄的晨曦,我看出是他的脸。我们在户外的一棵树底下,旁边有一辆摩托车,我想是在俄勒冈州的某地吧。
“没关系!只是做了一场恶梦。”
他还是一直哭,我静静地陪了他一会儿。
我说:“没事的。”但是他还是不肯停下来,他害怕极了。
我也是一样。
“你梦到什么?”
“我想看一个人的脸。”
“你一直叫着要把我给杀了。”
“不是,不是你。”
“谁呢?那是谁呢?”
“梦里的人。”
“是谁呢?”
“我也无法确定。”
克里斯不哭了,但是他还是在发抖,可能是因为天气很冷。“你看到他的脸了吗?”
“看到了。”
“他长什么样子?”
“在我大喊的时候,我看到的是自己的脸……那只是一个恶梦。”我告诉他,他在发抖,应该回睡袋去。
他回去了,说道:“天气好冷。”
“是啊!”从晨光中,我看到我们呼出的气变成了水蒸气。他爬进睡袋里。
这时,我只看到自己吐的气。
我睡不着。
我梦到的人根本就不是我。
是斐德洛。
他醒过来了。
心灵分裂与自己对立……我……我就是在黑影当中的人,我就是那个可厌的人……
我就知道,他一定会回来的……
现在的问题就是要先做准备……
从树下望向天空,看起来是那样的灰暗,那样的绝望。
可怜的克里斯。
|
Markdown | UTF-8 | 10,394 | 3.1875 | 3 | [
"MIT"
] | permissive | # 编程思想 定义过滤的方式解耦
本文将会很少涉及 dotnet 的知识,主要讲用定义过滤的方式解除过程业务的耦合。在一些业务上,可以从业务层面或逻辑层面明显分为几层,每一层之前的数据相互依赖或处理顺序相互依赖,但逻辑都独立。此时如果将业务处理放在过程处理里面,将会让过程处理耦合具体业务。而定义过滤的方式为让过程逻辑只是搭建框架为主,具体业务通过注入过滤的形式加入到处理
<!--more-->
<!-- CreateTime:2020/3/8 8:29:53 -->
假设我有某个业务需要处理,这个业务分为两个大步骤,分别是 F1 步骤和 F2 步骤。而 F1 里面自然有 F1 步骤的业务,同理 F2 也一样。而我的业务上对于数据处理的过程要求比较高,在过程处理上面的逻辑相对复杂,而如果将 F1 的业务和 F2 的业务放进来,大概的逻辑会是这样
```csharp
// 复杂的过程处理代码
// 通用的过程处理业务代码
// F1 业务需要处理的代码
// 其他诡异的逻辑业务代码
// 过程处理的业务代码
// F2 业务需要处理的代码
// 其他处理代码
```
总体看起来逻辑将会比较复杂,同时耦合度也将会比较高
读到这里的小伙伴是否有一个疑问,在什么时候就能定义出过程处理的逻辑,而其中的 F1 业务和 F2 业务是如何能定义出哪些代码是属于哪个步骤
用一个比较具体的例子说明
我需要在 WPF 中处理一个视频文件,视频文件的处理包含了视频文件本身的专业逻辑,也就是如何解码视频文件,如何将视频文件拼接为一张张图片。而处理视频文件包含了业务上的事情,业务上的事情包含以下三个部分
1. 打开视频文件之前需要看看这个视频文件的编码格式,如果不清真就提示用户(判断格式)
2. 每一个视频转出来的图片,在拿到数据之前需要做一点点优化,如在数据上添加一个水印(添加水印)
3. 从图片数据转图片完成之后,需要随机拿出一些图片给用户预览(提供预览)
而如果将上面的业务逻辑混合到整个视频处理逻辑上,大概会是这个样子
1. 打开视频文件,分批加入到内存
1. 判断格式(业务第一个步骤)
1. 解码拿到 HEAD 数据
1. 加载声音
1. 获取视频分辨率,创建空白数据
1. 杂七杂八的专业处理逻辑
1. 按照一秒30张图片组合出视频处理,将视频一秒拆为 30 张图片
1. 以下为视频的每一张图片处理逻辑
1. 解析出视频中的图片
1. 添加水印(业务第二个步骤)
1. 将图片做一些优化
1. 奇特的图片处理
1. 保存图片到文件
1. 提供预览(业务第三个步骤)
1. 压缩处理的所有图片
1. 我也编不出的业务逻辑
大概来说,其实上面的逻辑可以分为三个大部分,第一个部分就是算法部分,或者说专业逻辑代码。这部分主要就是如何解码视频,如何将视频转图片以及优化图片等逻辑。这些逻辑基本都是很通用的,同时这部分逻辑也应该做到很独立。业务上使用只是调用方法传入参数而已,不应该将具体代码写入到耦合某个业务里面
第二个部分就是定义处理的过程,其实上面的逻辑应该可以分为以下过程
1. 从文件加载到内存
1. 解码视频
1. 从视频转图片
1. 处理图片
1. 保存处理逻辑
这里面大部分步骤都是几乎做到通用的,也就是在这些步骤上只是填充专业逻辑。这部分逻辑适合创建一个 NuGet 库存放,这样在多个项目之间都能共用。但是现在的问题来了,我的业务逻辑分散在三个过程里面
1. 文件打开后
1. 图片处理时
1. 图片处理完成
而其中 文件打开后 这个过程在此业务中只用一次。而后面两个过程将会根据具体视频执行多次
这里的业务逻辑就是第三个部分。这里的逻辑划分其实和代码执行顺序没有直接关系,而是根据代码逻辑的层次划分。进一步说,其实第一部分专业逻辑和第二部分定义处理的过程这两个部分不是紧密的关系。假设咱有很多不同的专业逻辑,如针对不同的视频采用不同的处理方式,但是这些处理方式之前的处理过程是差不多的,也就是第二个部分定义处理的过程部分可以独立出来,根据具体功能填写具体的专业逻辑。也就是从层次上,第二部分属于框架层面,但如果我将第三部分业务逻辑放在了整个处理逻辑里面,那么此时的功能就都无法独立
是否可以让第三部分业务逻辑分离?其实从上面说的内容,连第一部分都可以分离。假设将第二部分框架层面的部分作为框架使用,那么框架就是独立的,但是框架没有任何具体的功能。此时通过在框架各个部分填补专业逻辑可以让第一部分和第二部分联合作出实际的功能
但是想要完成功能还需要有业务的存在,此时的业务就不能写入到库的代码中。这里的库指的是如 NuGet 一样的代码库,或者说是通用代码里面,通用代码不含各个产品的具体业务
既然在第二部分已经可以定义出框架了,那么可以在框架里面应用过滤的方式进行解耦。在框架里面可以定义逻辑处理的顺序,在关键的处理里面开放注入接口。如在视频文件打开之后,此时添加一个可以注入的点,可以让业务层注入业务逻辑
而此时注入的部分的建议是注入一个接口,在框架里面定义了过程用到传入的数据,在某些处理的过程里面可以让开发者注入具体的实现类,通过接口进行约束和获取数据进行处理的方式,就是本文说的定义过滤的方式解耦
例如有简化的逻辑,我的框架的定义如下
```csharp
interface IFooHandler
{
void AddF1Filter(IF1Filter filter);
void AddF2Filter(IF2Filter filter);
}
```
框架里面提供了添加两个不同的业务过滤的方法,而这两个不同的业务过滤将会在整个过程的不同步骤进行调用,同时也使用两个不同的接口限定了具体的业务逻辑的注入的类的实现方式。这个方法的优点在于,可以将业务的逻辑放在具体的业务上做,而框架和库的部分只是做通用的处理逻辑。换句话说是将不通用的代码作为接口的方式提出,而在业务层进行注入,注入的方式就是调用框架给出的方法传入对应的接口实现。如上面代码,框架在两个步骤里面给出了两个可以注入的方法,通过调用框架的这两个方法传入具体实现就能做到在框架处理的过程调用注入的业务
而对比将所有逻辑都写在一起的优势在于降低耦合,原先的业务逻辑可以分散写,同时还能访问上下文更多信息。而现在只能通过约束的接口,如上面代码的 IF1Filter 定义,此时将可以让业务逻辑不影响到框架里面的逻辑,换句话是框架里面只需要了解接口的内容而不需要了解具体业务
而这个过滤的方式可以在框架里面各个地方提供,甚至框架可以通过判断有注入实际业务和没有注入的行为,如有注入业务时采用业务特殊方法替换原有的逻辑,如下面代码定义
```csharp
public void SetF1Filter(IF1Filter filter)
{
Filter = filter;
}
private IF1Filter Filter { get; set; } = DefaultFilter;
private static readonly IF1Filter DefaultFilter = new F1Filter();
```
如果用户没有注入实际的逻辑,那么将会使用 DefaultFilter 的逻辑,如果用户注入了,那么将使用用户的逻辑
对于部分业务处理,如上面说到的在文件打开之后的处理,此时的处理不应该限定只有一个,于是如上面代码定义,可以让用户调用方法多次,之后进行每个用户传入的业务处理
```csharp
private static void HandleFoo(IFooHandler fooHandler)
{
fooHandler.AddF1Filter(new F1Filter());
fooHandler.AddF1Filter(new F1Filter());
fooHandler.AddF1Filter(new F1Filter());
}
```
如上面代码可以让框架在 F1 步骤处理三次,虽然上面代码都是传入一样的类创建
而如果将整个注入好了逻辑的框架作为一个实例存放,在软件中的不同业务使用,此时也许会遇到某些业务需要添加一点功能,而某些业务不需要的情况,如下面代码的 fooHandle 是已经注入好了业务逻辑的实例,但是此时我需要在某个业务里面对他的处理过程进行一点更改
```csharp
var fooHandle = new FooHandler();
HandleFoo(fooHandle);
```
此时的修改如果依然对 fooHandle 进行注入不加任何逻辑,那么此时将会影响到其他使用的业务,这里在 C# 里面可以采用 using 的方法,大概的写法如下
```csharp
var f1Filter = new F1Filter();
using (f1Filter)
{
fooHandle.AddF1Filter(f1Filter);
// 其他业务
}
```
在本次处理完成 F1Filter 和业务之后,将会调用 f1Filter 的释放代码,在释放代码里面可以反过来调用 fooHandle 的移除添加方法
大概实现逻辑请看我的[代码](https://github.com/lindexi/lindexi_gd/tree/c8f9fa3cfcaa513c9535f36cd7deaca78d630f93/JearbechichayFuchayfawkowilem) 这里面只是简单定义
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="知识共享许可协议" style="border-width:0" src="https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png" /></a><br />本作品采用<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a>进行许可。欢迎转载、使用、重新发布,但务必保留文章署名[林德熙](http://blog.csdn.net/lindexi_gd)(包含链接:http://blog.csdn.net/lindexi_gd ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我[联系](mailto:lindexi_gd@163.com)。
|
Java | UTF-8 | 263 | 2.40625 | 2 | [] | no_license | package ar.fiuba.tdd.tp.exceptions;
public abstract class ConnectionException extends Exception {
private String msg;
public ConnectionException(String msg) {
this.msg = msg;
}
public String getMsg() {
return this.msg;
}
}
|
Markdown | UTF-8 | 1,297 | 2.59375 | 3 | [] | no_license | ---
book:
author: Frank Herbert
cover_image: dune-messiah.jpg
cover_image_url: https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1533872326l/106._SY160_.jpg
goodreads: '106'
isbn10: 0441172695
isbn13: '9780441172696'
pages: '331'
publication_year: '1987'
series: Dune Chronicles
series_position: '2'
slug: dune-messiah
title: Dune Messiah
plan:
date_added: '2018-07-09'
review:
date_read: 2018-08-04
date_started: 2018-08-04
did_not_finish: false
rating: 2
---
Dune Messiah was very much not my kind of book, and for different reasons than I disliked **Dune**. While my criticism regarding Good vs Evil characters from the first volume isn't relevant to the second one, *Frank Herbert*'s narration style of showing the thoughts of just about everybody felt like a giant "tell, don't show". I felt like the story just crawled along. Everything was overthought and overexplained, none of the characters were likeable in any way, and very little actually happened. I felt that the large time gap ("I don't want to be the messiah and cause a jihad" - 12 years later, guess what) took also part in my disbelief at the fact that there was nothing an emperor could do to at least mitigate the issues he suffered from. Ehh, I probably won't go on with the series.
|
JavaScript | UTF-8 | 503 | 2.546875 | 3 | [] | no_license | var {isRealStr} = require('./validation');
var expect = require('expect');
describe('isRealStr', () => {
it('should reject non-string values', () => {
var res = isRealStr(1111)
expect(res).toBe(false)
})
it('should reject string with only spacess', () => {
var res = isRealStr(' ')
expect(res).toBe(false)
})
it('should allow string with non-space characters', () => {
var res = isRealStr('naveen')
expect(res).toBe(true)
})
}) |
Java | UTF-8 | 426 | 2.328125 | 2 | [] | no_license | package com.epam.ag.model;
/**
* @author by Govorov Andrey.
*/
public class VehicleException extends RuntimeException {
public VehicleException() {
super();
}
public VehicleException(String message) {
super(message);
}
public VehicleException(String message, Throwable cause) {
super(message, cause);
}
public VehicleException(Throwable cause) {
super(cause);
}
}
|
Markdown | UTF-8 | 1,621 | 2.828125 | 3 | [] | no_license | # AndroidGame-BasicApp
Osnovna aplikacija za izradu igre u Android Studiu
**1. Kreiranje početnog ekrana (UI)** <br/>
*Izgled* određen u activity_main.xml koji sadrži jedan TexView i Button i koristi background.png. Orijentacija ekrana landscape.<br/>
*Funkcijonalnost* određena u MainActivity.java gdje je ulaz u igru metodom OnCreate. SetContentView koji generira UI iz layouta activity_main.xml igračima igre na zaslon.<br/>
Gumb Igraj <br/>
referenca na gumb iz layouta (findViewById) <br/>
osluškivanje kada ce netko kliknuti gumb (SetOnClickListener) <br/>
implementacija interfacea View.OnClickListener i metode OnClick </br>
Intent klasa omogućuje prijelaz između dvije aktivnosti (ovdje iz MainActivity u GameActivity) <br/>
**2.Igra** <br/>
*Izgled* <br/>
Za izgleda ekrana (View) nije korišten layout kao za UI već dinamički iscrtan pogled koji se koristi u GameActivity.java kao instanca objekta BAView iz klase BAVIew.java.<br/>
BAVwiev u metodi run koristi metode obnovi (podatke igrača), crtaj (slike) , kontrole (zasutavljanje rada dretve-koliko brzo se slika na ekranu obnavlja u minuti).Petlja igre (Game Loop) ,određena varijablom igraj, istovremeno manipulira sa ponašanjem igrača i ostalim sistemskim zahtjevima, jer smo implementirali Runnable interface kreirajući novu dretvu,
android.view.SurfaceView klasa omogućuje iscrtavanje slika, teksta, linija ali i ponašanje igrača. <br/>
*Funkcionalnost* (dinamičko iscrtavanje viewa) određeno je u GameActivity.java. <br/>
Sve activity označene su u AndroidManifest.xml datoteci , gdje je pogled namješten na full screen.
|
Python | UTF-8 | 836 | 3.28125 | 3 | [
"MIT"
] | permissive | __all__=['IsEmail','ListedEmail']
__author__='Clavin(Martin)Adyezik - Adyezik@gmail.com'
__doc__="""
EmailChecker:
Simple Module with two function .
Check if an E-mail is valid or check for list of E-mails
"""
__name__='EmailChecker'
def IsEmail(x):
"""x must be a string
Return True if x is a Valid E-mail"""
if len(x)<=6:
return False
if not'@'in x:
return False
if x.count('@')!=1:
return False
if x.startswith('.')or x.endswith('.'):
return False
local_part=x[:x.find('@')]
if len(local_part)>=65:
return False
domain=x[x.find('@'):]
if not'.'in domain:
return False
return True
def ListedEmail(x):
"""x must be a list of strings
return E-mail : boolean value"""
for i in x:
return (x,': ',IsEmail(x))
|
Java | UTF-8 | 1,078 | 3.9375 | 4 | [
"Apache-2.0"
] | permissive | package main;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntBinaryOperator;
public class Main {
/**
* 主入口
*
* @param args 参数列表
*/
public static void main(String[] args) {
// 创建AtomicInteger对象
AtomicInteger value = new AtomicInteger(2);
// 返回当前值再使用自定义运算方式更新当前值
int result = value.getAndAccumulate(3, new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left * right;
}
});
// 输出结果
System.out.println("运算结果:" + result);
// 先使用自定义运算方式更新当前值再返回当前值
result = value.accumulateAndGet(2, new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left * right;
}
});
// 输出结果
System.out.println("运算结果:" + result);
}
} |
C# | UTF-8 | 1,278 | 2.765625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MVCASPWeb.IO
{
class IOPath
{
public static string getAbsPathOfResource(string resource)
{
string outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
string debugPath = Path.Combine(outPutDirectory, @"..\..\" + resource);
string localPath = new Uri(debugPath).LocalPath;
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(
Path.GetFullPath(Path.Combine(currentDir, @"..\..\" + resource)));
Directory.GetCurrentDirectory();
string absolutePath = @"C:\\Users\\loctv.TOSHIBA-TSDV\\documents\\visual studio 2013\\Projects\\MVCASPWeb\\MVCASPWeb\\custom shape.bmp";
int relativePathStartIndex = absolutePath.IndexOf("MVCASPWeb");
string relativePath = absolutePath.Substring(relativePathStartIndex);
return localPath;
}
private static string Combine(string outPutDirectory, string p)
{
throw new NotImplementedException();
}
}
}
|
JavaScript | UTF-8 | 1,809 | 2.546875 | 3 | [] | no_license | const { gql} = require('apollo-server-express');
const typeDefs = gql`
type Course {
id: ID!
title: String!
description: String!
teacher: Teacher
rating: Int
comments: [Comment]
}
type Teacher {
id: ID!
name: String!
nationality: String!
gender: Gender
courses: [Course]
}
enum Gender {
MALE
FEMALY
}
type Comment {
id: ID!
name: String!
body: String!
}
type Query{
courses: [Course]
teachers: [Teacher]
course(id: Int): Course
teacher(id: Int): Teacher
}
`
const resolvers = {
Query: {
courses() {
return[
{
id: 1,
title: "Curso 1",
description: "Esta es una descripcion",
rating:8,
},
{
id: 2,
title: "Curso 2",
description: "Esta es una descripcion",
rating:8,
},
{
id: 3,
title: "Curso 3",
description: "Esta es una descripcion",
rating:8,
}
]
},
teachers() {
return [
{id:1, name: 'Julio', nationality: 'Ecuatoriana'},
{id:2, name: 'John', nationality: 'Ecuatoriana'},
{id:3, name: 'Jane', nationality: 'Ecuatoriana'}
]
}
},
Course: {
teacher(){
return {
id: 1,
name: 'Camilo'
}
}
}
}
module.exports = {typeDefs, resolvers };
|
PHP | UTF-8 | 3,599 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
/**
* YAWIK
*
* @filesource
* @license MIT
* @copyright 2013 - 2016 Cross Solution <http://cross-solution.de>
*/
/** */
namespace Core\Form;
use Zend\Form\Element;
/**
* A wizard style form container.
*
* Holds instances of form containers which each represent a "tab" of an wizard.
*
* @author Mathias Gelhausen <gelhausen@cross-solution.de>
* @since 0.22
*/
class WizardContainer extends Container implements HeadscriptProviderInterface, \IteratorAggregate
{
/**
* Headscripts.
*
* @var array
*/
protected $scripts = [
//'/assets/twitter-bootstrap-wizard/jquery.bootstrap.wizard.js',
];
public function setHeadscripts(array $scripts)
{
$this->scripts = $scripts;
return $this;
}
public function getHeadscripts()
{
return $this->scripts;
}
/**
* Sets a form container.
*
* Either pass in an object of type \Core\Form\Container or provide a $spec array.
* Only instances of \Core\Form\Container which have a label are allowed.
*
* @see \Core\Form\Container::setForm
*
* @param string $key
* @param array|string|\Core\Form\Container $spec
* @param bool $enabled
*
* @return self
* @throws \InvalidArgumentException
*/
public function setForm($key, $spec, $enabled = true)
{
if (is_object($spec)) {
if (!$spec instanceof Container) {
throw new \InvalidArgumentException('Tab container must be of the type \Core\Form\Container');
}
if (!$spec->getLabel()) {
throw new \InvalidArgumentException('Container instances must have a label.');
}
}
if (is_array($spec)) {
if (!isset($spec['type'])) {
$spec['type'] = 'Core/Container';
}
/*
* For convenience, forms may be specified outside the options array.
* But in order to be passed through to the form element manager,
* we must move it to the options.
*/
if (!isset($spec['options']['forms']) && isset($spec['forms'])) {
$spec['options']['forms'] = $spec['forms'];
unset($spec['forms']);
}
}
return parent::setForm($key, $spec, $enabled);
}
/**
* Gets a specific formular.
*
* This formular will be created upon the first retrievement.
* If created, the formular gets passed the formular parameters set in this container.
*
* @see Container::getForm
*
* @param string $key
* @param bool $asInstance if false, the specification array is returned.
*
* @return Container|null|\Zend\Form\FormInterface|array
* @throws \UnexpectedValueException
*/
public function getForm($key, $asInstance = true)
{
$form = parent::getForm($key, $asInstance);
/*
* We must check here, if a lazy loaded top level form is an
* instance of Container.
*/
if ($asInstance && false === strpos($key, '.') && (!$form instanceof Container || !$form->getLabel())) {
throw new \UnexpectedValueException(sprintf(
'The registered form with key "%s" is not an instance of \Core\Form\Container or does not have a label.',
$key
));
}
return $form;
}
}
|
Java | UTF-8 | 2,391 | 1.96875 | 2 | [] | no_license | package pnc.mesadmin.entity.common;
import java.util.Date;
//请检单信息表
public class QCheckMaInfo {
private Integer Ruid;
private String Guid;
private String QCheckMaCode;
private String QCheckMaType;
private String Status;
private String FinalResult; //出库确认结果 00#合格 01#不合格
private String StockMaCode;
private String Creator;
private Date CreateTime;
private String LastModifyMan;
private Date LastModifyTime;
private String Remark;
public Integer getRuid() {
return Ruid;
}
public void setRuid(Integer ruid) {
Ruid = ruid;
}
public String getGuid() {
return Guid;
}
public void setGuid(String guid) {
Guid = guid;
}
public String getQCheckMaCode() {
return QCheckMaCode;
}
public void setQCheckMaCode(String QCheckMaCode) {
this.QCheckMaCode = QCheckMaCode;
}
public String getQCheckMaType() {
return QCheckMaType;
}
public void setQCheckMaType(String QCheckMaType) {
this.QCheckMaType = QCheckMaType;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getFinalResult() {
return FinalResult;
}
public void setFinalResult(String finalResult) {
FinalResult = finalResult;
}
public String getStockMaCode() {
return StockMaCode;
}
public void setStockMaCode(String stockMaCode) {
StockMaCode = stockMaCode;
}
public String getCreator() {
return Creator;
}
public void setCreator(String creator) {
Creator = creator;
}
public Date getCreateTime() {
return CreateTime;
}
public void setCreateTime(Date createTime) {
CreateTime = createTime;
}
public String getLastModifyMan() {
return LastModifyMan;
}
public void setLastModifyMan(String lastModifyMan) {
LastModifyMan = lastModifyMan;
}
public Date getLastModifyTime() {
return LastModifyTime;
}
public void setLastModifyTime(Date lastModifyTime) {
LastModifyTime = lastModifyTime;
}
public String getRemark() {
return Remark;
}
public void setRemark(String remark) {
Remark = remark;
}
}
|
C# | UTF-8 | 440 | 2.546875 | 3 | [
"MIT"
] | permissive | namespace Shop.Data.BusinessModels
{
public class Address
{
public Address(string city, string street, string streetNumber = null)
{
this.City = city;
this.Street = street;
this.StreetNumber = streetNumber;
}
public string City { get; set; }
public string Street { get; set; }
public string StreetNumber { get; set; }
}
}
|
C# | UTF-8 | 15,080 | 2.921875 | 3 | [
"MIT"
] | permissive | using NHulk.DynamicCache;
using System.Collections.Generic;
using System.Data;
namespace NHulk
{
public static class DbConnectionByInstanceExtension
{
#region NormalQuery_ByInstance
/// <summary>
/// 通过多个实例查询满足条件的数据
/// </summary>
/// <typeparam name="T">需要返回数据的类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="values">映射到SQL语句的实例数组</param>
/// <returns>T类型集合</returns>
public static IEnumerable<T> QueryByInstances<T>(this IDbConnection connection, string commandText, object[] values)
{
List<T> resultCollection = new List<T>();
SqlDelegate<T>.GetReaderInstance instance_func = null;
SqlDelegate<T>.GetCommandByInstance command_func = SqlDynamicCache.GetInstanceCommandDelegate<T>(commandText, values[0]);
int i_length = values.Length;
IDbCommand command = connection.CreateCommand();
IDataReader reader = null;
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open(); }
for (int i = 0; i < i_length; i += 1)
{
command_func(ref command, values[i]);
reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess | CommandBehavior.SingleResult);
CloseFlag = false;
if (instance_func == null)
{
instance_func = SqlDynamicCache.GetReaderDelegate<T>(reader, commandText);
}
while (reader.Read())
{
T tNode = instance_func(reader);
resultCollection.Add(tNode);
}
while (reader.NextResult()) { }
reader.Dispose();
reader = null;
}
return resultCollection;
}
finally
{
if (reader != null)
{
if (!reader.IsClosed)
{
try { command.Cancel(); }
catch { }
}
reader.Dispose();
}
if (CloseFlag) connection.Close();
command?.Dispose();
}
}
/// <summary>
/// 通过实例,查询数据
/// </summary>
/// <typeparam name="T">需要返回数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="value">映射到SQL语句的实例</param>
/// <returns>T类型数据集合</returns>
public static IEnumerable<T> QueryByInstance<T>(this IDbConnection connection, string commandText, object value)
{
//Stopwatch watch = new Stopwatch();
List<T> resultCollection = null;
IDataReader reader = null;
SqlDelegate<T>.GetReaderInstance instance_func = null;
SqlDelegate<T>.GetCommandByInstance command_func = SqlDynamicCache.GetInstanceCommandDelegate<T>(commandText, value);
IDbCommand command = connection.CreateCommand();
command_func(ref command, value);
bool CloseFlag =( connection.State == ConnectionState.Closed );
try
{
if (CloseFlag){ connection.Open();}
reader = command.ExecuteReader(CommandBehavior.CloseConnection| CommandBehavior.SequentialAccess | CommandBehavior.SingleResult);
CloseFlag = false;
instance_func = SqlDynamicCache.GetReaderDelegate<T>(reader, commandText);
resultCollection = new List<T>(reader.FieldCount);
while (reader.Read())
{
//watch.Restart();
//T t = instance_func(reader);
//watch.Stop();
// System.Console.WriteLine("执行Reader缓存:" + watch.Elapsed);
resultCollection.Add(instance_func(reader));
}
while (reader.NextResul }
reader.Dispose();
reader = null;
return resultCollection;
}
finally
{
if (reader != null)
{
if (!reader.IsClosed)
{
try { command.Cancel(); }
catch{}
}
reader.Dispose();
}
if (CloseFlag) connection.Close();
command?.Dispose();
}
}
/// <summary>
/// 通过实例,查询一条数据
/// </summary>
/// <typeparam name="T">需要返回数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="value">映射到SQL语句的实例</param>
/// <returns>T类型数据</returns>
public static T SingleByInstance<T>(this IDbConnection connection, string commandText, object value) where T : class
{
T node = null;
SqlDelegate<T>.GetReaderInstance instance_func = null;
SqlDelegate<T>.GetCommandByInstance command_func = SqlDynamicCache.GetInstanceCommandDelegate<T>(commandText, value);
IDbCommand command = connection.CreateCommand();
command_func(ref command, value);
IDataReader reader = null;
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open(); }
reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess | CommandBehavior.SingleResult);
CloseFlag = false;
instance_func = SqlDynamicCache.GetReaderDelegate<T>(reader, commandText);
while (reader.Read())
{
node = instance_func(reader);
reader.Dispose();
reader = null;
return node;
}
return null;
}
finally
{
if (reader != null)
{
if (!reader.IsClosed)
{
try { command.Cancel(); }
catch { }
}
reader.Dispose();
}
if (CloseFlag) connection.Close();
command?.Dispose();
}
}
#endregion
#region ExecuteNonQuery_ByInstance
/// <summary>
/// 通过ExecuteNonQuery方式来操作数据
/// </summary>
/// <typeparam name="T">实例数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="values">映射到SQL语句的实例数组</param>
/// <returns>返回操作失误的实例数据集合</returns>
public static List<T> ExecuteNonQueryByInstances<T>(this IDbConnection connection, string commandText, T[] values)
{
List<T> ResultList = new List<T>();
SqlDelegate<T>.GetGenericCommand command_func = SqlDynamicCache.GetCommandGenericDelegate(commandText, values[0]);
int i_length = values.Length;
IDbCommand command = connection.CreateCommand();
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open(); }
for (int i = 0; i < i_length; i += 1)
{
command_func(ref command, values[i]);
int tempResult = command.ExecuteNonQuery();
if (tempResult == 0)
{
ResultList.Add(values[i]);
}
}
return ResultList;
}
finally
{
connection.Close();
command?.Dispose();
}
}
/// <summary>
/// 通过ExecuteNonQuery方式来操作数据
/// </summary>
/// <typeparam name="T">实例数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="value">映射到SQL语句的实例</param>
/// <returns>返回影响的行数</returns>
public static int ExecuteNonQueryByInstance<T>(this IDbConnection connection, string commandText, T value)
{
SqlDelegate<T>.GetGenericCommand command_func = SqlDynamicCache.GetCommandGenericDelegate(commandText, value);
IDbCommand command = connection.CreateCommand();
command_func(ref command , value);
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open();}
return command.ExecuteNonQuery();
}
finally
{
connection.Close();
command?.Dispose();
}
}
#endregion
#region ExecuteScalar_ByInstance
/// <summary>
/// 通过ExecuteScalar方式来操作数据
/// </summary>
/// <typeparam name="T">实例数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="values">映射到SQL语句的实例数组</param>
/// <returns>返回结果集</returns>
public static List<object> ExecuteScalarByInstances<T>(this IDbConnection connection, string commandText, T[] values)
{
List<object> ResultList = new List<object>();
SqlDelegate<T>.GetGenericCommand command_func = SqlDynamicCache.GetCommandGenericDelegate(commandText, values[0]);
IDbCommand command = connection.CreateCommand();
int i_length = values.Length;
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open(); }
for (int i = 0; i < i_length; i += 1)
{
command_func(ref command, values[i]);
ResultList.Add(command.ExecuteScalar());
}
return ResultList;
}
finally
{
connection.Close();
command?.Dispose();
}
}
/// <summary>
/// 通过ExecuteScalar方式来操作数据
/// </summary>
/// <typeparam name="T">实例数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="values">映射到SQL语句的实例</param>
/// <returns>返回结果</returns>
public static object ExecuteScalarByInstance<T>(this IDbConnection connection, string commandText, T value)
{
SqlDelegate<T>.GetGenericCommand command_func = SqlDynamicCache.GetCommandGenericDelegate(commandText, value);
IDbCommand command = connection.CreateCommand();
command_func(ref command, value);
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open();}
return command.ExecuteScalar();
}
finally
{
connection.Close();
command?.Dispose();
}
}
/// <summary>
/// 通过ExecuteScalar方式来操作数据
/// </summary>
/// <typeparam name="R">结果的类型</typeparam>
/// <typeparam name="T">实例数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="values">映射到SQL语句的实例数组</param>
/// <returns>返回结果集</returns>
public static List<R> ExecuteScalarByInstances<R, T>(this IDbConnection connection, string commandText, T[] values)
{
List<R> ResultList = new List<R>();
SqlDelegate<T>.GetGenericCommand command_func = SqlDynamicCache.GetCommandGenericDelegate(commandText, values[0]);
IDbCommand command = connection.CreateCommand();
int i_length = values.Length;
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open(); }
for (int i = 0; i < i_length; i += 1)
{
command_func(ref command, values[i]);
ResultList.Add((R)(command.ExecuteScalar()));
command.Dispose();
}
return ResultList;
}
finally
{
connection.Close();
command?.Dispose();
}
}
/// <summary>
/// 通过ExecuteScalar方式来操作数据
/// </summary>
/// <typeparam name="R">结果的类型</typeparam>
/// <typeparam name="T">实例数据类型</typeparam>
/// <param name="connection">对IDbConnection扩展</param>
/// <param name="commandText">SQL语句</param>
/// <param name="values">映射到SQL语句的实例</param>
/// <returns>返回结果</returns>
public static R ExecuteScalarByInstance<R, T>(this IDbConnection connection, string commandText, T value)
{
SqlDelegate<T>.GetGenericCommand command_func = SqlDynamicCache.GetCommandGenericDelegate(commandText, value);
IDbCommand command = connection.CreateCommand();
command_func(ref command, value);
bool CloseFlag = (connection.State == ConnectionState.Closed);
try
{
if (CloseFlag) { connection.Open(); }
return (R)command.ExecuteScalar();
}
finally
{
connection.Close();
command?.Dispose();
}
}
#endregion
}
}
|
C | UTF-8 | 11,376 | 2.609375 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "roi.h"
#define DEBUG 0
#if 1
// エンディアンの変換
unsigned short htons (unsigned short n)
{
unsigned short h;
unsigned char* c = (unsigned char*)&n;
((unsigned char*)&h)[0] = c[1];
((unsigned char*)&h)[1] = c[0];
return h;
}
// エンディアンの変換
unsigned short ntohs (unsigned short n)
{
unsigned short h;
unsigned char* c = (unsigned char*)&n;
((unsigned char*)&h)[0] = c[1];
((unsigned char*)&h)[1] = c[0];
return h;
}
#endif
/**
* @brief 掃除の開始
* @param buff コマンドバッファ
* @retval コマンドのサイズ
*/
int roi_set_clean (unsigned char* buff)
{
buff[0] = ROICMD_CLEAN;
return 1;
}
/**
* @brief ROIのモニタ開始
* @param buff コマンドバッファ
* @retval コマンドのサイズ
*/
int roi_set_start (unsigned char* buff)
{
buff[0] = ROICMD_START;
return 1;
}
/**
* @brief ボーレートの設定
*/
int roi_set_baud (unsigned char* buff, int baud)
{
buff[0] = ROICMD_BAUD;
buff[1] = 10;
return 2;
}
/**
* @brief ROIの操作開始
*/
int roi_set_control (unsigned char* buff)
{
buff[0] = ROICMD_CONTROL;
return 1;
}
/**
* @brief safeモードへ移行
* @param buff コマンドバッファ
* @retval コマンドのサイズ
*/
int roi_set_safe (char* buff)
{
buff[0] = ROICMD_SAFE;
return 1;
}
/**
* @brief 電源のON/OFF
*/
int roi_set_power (char* buff)
{
buff[0] = ROICMD_POWER;
return 1;
}
/**
* @brief DRIVEコマンド
*/
int roi_set_drive (char* buff, short v, short r)
{
char* vel;
char* rad;
vel = (char*)&v;
rad = (char*)&r;
// CAUTION: endian
buff[0] = ROICMD_DRIVE;
buff[1] = vel[1];
buff[2] = vel[0];
buff[3] = rad[1];
buff[4] = rad[0];
return 5;
}
/**
* @brief DRIVEコマンド
*/
int roi_get_drive (ubyte_t* buff, short* pos_vel, short* radius)
{
char* vel;
char* rad;
vel = (char*)pos_vel;
rad = (char*)radius;
// CAUTION: endian
vel[1] = buff[1];
vel[0] = buff[2];
rad[1] = buff[3];
rad[0] = buff[4];
return 0;
}
/**
* @brief MOTORSコマンド
*/
int roi_get_motors (ubyte_t* buff, int* side_brush, int* vacuum, int* main_brush)
{
*main_brush = (buff[1] >> 2) & 0x01;
*vacuum = (buff[1] >> 1) & 0x01;
*side_brush = buff[1] & 0x01;
return 0;
}
/**
* @brief SERVOコマンド
*/
int roi_get_servo (char* buff, short* pwm_ref)
{
char* pwm;
pwm = (char*)pwm_ref;
// CAUTION: endian
pwm[1] = buff[1];
pwm[0] = buff[2];
return 0;
}
/**
*@brief LEDの操作
*/
int roi_set_leds (char* buff, unsigned char leds, unsigned char power_color, unsigned char power_intensity)
{
buff[0] = ROICMD_LEDS;
buff[1] = leds;
buff[2] = power_color;
buff[3] = power_intensity;
return 4;
}
/**
* @brief STREAMコマンドの設定
*/
int roi_set_stream (char* buff, int id)
{
buff[0] = ROICMD_STREAM;
buff[1] = 1;
buff[2] = id;
return 3;
}
/**
* @brief streamのヘッダを設定する
* @param buff stream用バッファ
* @param data 入力データ
*/
int roi_set_stream_response_header (char* buff, unsigned char data)
{
if (data==19) {
buff[0] = data;
return 0;
}
return -1;
}
/**
* @brief streamのヘッダを設定する
* @param buff stream用バッファ
* @param c 入力データ
*/
int roi_set_stream_response_size (char *buff, unsigned char c)
{
buff[1] = c;
return 0;
}
/**
* @brief streamのサイズを取得する
* @param buff stream用バッファ
*/
int roi_get_stream_response_size (char* buff)
{
if (buff[0] != 19) {
return 0;
}
return ((unsigned char *)buff)[1];
}
/**
* @brief streamのデータを設定する
* @param buff stream用バッファ
*/
int roi_set_stream_response_data (char *buff, unsigned int no, char data)
{
if (no >= roi_get_stream_response_size (buff)) {
return -1;
}
buff[2+no] = data;
return 0;
}
/**
* @brief streamのチェックサムを確認する
* @param buff stream用バッファ
*/
int roi_check_stream_response (char *buff)
{
return 0;
}
/**
* @brief streamから左バンパセンサを取得する
* @param buff stream用バッファ
* @retval 1 バンパーON
* @retval 0 バンパーOFF
*/
int roi_get_stream_response_bump_r (char* buff)
{
if (buff[2] == 0) {
return roi_get_sensor_response_bump_r (&buff[3]);
}
if (buff[2] == 6) {
return roi_get_sensor_response_bump_r (&buff[3]);
}
return 0;
}
/**
* @brief streamから左バンパセンサを取得する
* @param buff stream用バッファ
* @retval 1 バンパーON
* @retval 0 バンパーOFF
*/
int roi_get_stream_response_bump_l (char* buff)
{
if (buff[2] == 0) {
return roi_get_sensor_response_bump_l (&buff[3]);
}
if (buff[2] == 6) {
return roi_get_sensor_response_bump_l (&buff[3]);
}
return 0;
}
/**
* @brief 右側バンパーセンサの値を取得する
*/
int roi_get_sensor_response_bump_r (char* buff)
{
return buff[0] & 0x01;
}
/**
* @brief 左側バンパーセンサの値を取得する
*/
int roi_get_sensor_response_bump_l (char* buff)
{
return buff[0] & 0x02;
}
char* scan_octave (char* arg, int* octave)
{
char* p;
p = arg + 1;
// 長さの処理
if (isdigit(*p)) {
*octave = atoi (p);
#if DEBUG
fprintf (stderr, "octave=%d\n", *octave);
fflush (stderr);
#endif
while (isdigit(*p)) {
#if DEBUG
fprintf (stderr, "*p=%c\n", *p);
fflush (stderr);
#endif
p++;
}
}
return p;
}
char* scan_rest (char* arg, int* length)
{
char* p;
p = arg + 1;
// 長さの処理
if (isdigit(*p)) {
*length = atoi (p);
while (isdigit(*p)) {
#if DEBUG
fprintf (stderr, "*p=%c\n", *p);
fflush (stderr);
#endif
p++;
}
}
return p;
}
/**
* 音符ひとかたまりを解析して情報を得る
*/
char* scan_note (char* arg, int* note, int* length)
{
int notes[12] = {'C', 'X', 'D', 'X', 'E', 'F', 'X', 'G', 'X', 'A', 'X', 'B'};
char* p;
int i;
*length = 16;
// 音符の処理
p = arg;
#if DEBUG
fprintf (stderr, "note=%c\n", *p);
fflush (stderr);
#endif
for (i=0; i<12; i++) {
if (*p==notes[i]) {
*note = i;
break;
}
}
// 半音の処理
p++;
if (*p=='#' || *p=='+') {
(*note)++;
p++;
}
else if (*p=='-') {
(*note)--;
p++;
}
// 長さの処理
if (isdigit(*p)) {
*length = atoi (p);
#if DEBUG
fprintf (stderr, "length=%d\n", *length);
fflush (stderr);
#endif
while (isdigit(*p)) {
#if DEBUG
fprintf (stderr, "*p=%c\n", *p);
fflush (stderr);
#endif
p++;
}
}
return p;
}
/**
* @brief 曲の登録
* @param buff コマンドバッファ
* @param args 楽譜データ
* @retval コマンドのサイズ
*
* O4 - オクターブ設定
* C4 - 四分音符
* C# - ドのシャープ
*/
int roi_song (unsigned char* buff, unsigned char no, char* args)
{
int note, octave = 4;
int numb = 0;
int length;
char* p;
#if DEBUG
fprintf (stderr, "args = %s\n", args);
fflush (stderr);
#endif
buff[0] = ROICMD_SONG;
buff[1] = no;
for (p=args; *p!='\0'; ) {
if (*p=='>') {
octave ++;
p++;
}
if (*p=='<') {
octave --;
p++;
}
// 音符文字の判定
if (*p=='O') {
p = scan_octave (p, &octave);
}
if (*p=='R') {
p = scan_rest (p, &length);
buff[3+2*numb+0] = 0;
buff[3+2*numb+1] = length;
numb ++;
}
if (*p=='C' || *p=='D' || *p=='E' || *p=='F' || *p=='G' || *p=='A' || *p=='B') {
p = scan_note (p, ¬e, &length);
buff[3+2*numb+0] = note + (octave + 1)*12;
buff[3+2*numb+1] = length;
numb ++;
}
}
buff[2] = numb;
#if DEBUG
fprintf (stderr, "com = %d, no = %d, numb = %d\n", (int)buff[0], (int)buff[1], (int)buff[2]);
fflush (stderr);
#endif
return (3+numb*2);
}
#if 1
int
roi_song2 (char* buff)
{
buff[0] = ROICMD_SONG;
buff[1] = 1;
buff[2] = 12;
// ド
buff[3] = 60;
buff[4] = 16;
// レ
buff[5] = 62;
buff[6] = 16;
// ミ
buff[7] = 64;
buff[8] = 64;
// レ
buff[9] = 62;
buff[10] = 16;
// ド
buff[11] = 60;
buff[12] = 16;
// ??
buff[13] = 31;
buff[14] = 32;
// ド
buff[15] = 60;
buff[16] = 16;
// レ
buff[17] = 62;
buff[18] = 16;
// ミ
buff[19] = 64;
buff[20] = 16;
// レ
buff[21] = 62;
buff[22] = 16;
// ド
buff[23] = 60;
buff[24] = 16;
// レ
buff[25] = 62;
buff[26] = 64;
return 27;
#endif
buff[0] = ROICMD_SONG;
buff[1] = 1;
buff[2] = 5;
// レ D4
buff[3] = 74;
buff[4] = 32;
// ミ E4
buff[5] = 76;
buff[6] = 32;
// ド C4
buff[7] = 72;
buff[8] = 32;
// ド C3
buff[9] = 60;
buff[10] = 32;
// ソ G3
buff[11] = 67;
buff[12] = 64;
return 13;
}
int roi_set_play (unsigned char* buff, unsigned char no)
{
buff[0] = ROICMD_PLAY;
buff[1] = no;
return 2;
}
int roi_set_sensor (char* buff, unsigned char packet_id)
{
buff[0] = ROICMD_SENSORS;
buff[1] = packet_id;
return 2;
}
int roi_set_query_list (char* buff, unsigned char numb, unsigned char packet_id_list[])
{
int i;
buff[0] = ROICMD_QUERY_LIST;
buff[1] = numb;
for (i=0; i<numb; i++) {
buff[i+2] = packet_id_list[i];
}
return 2+numb;
}
int roi_get_query_list_response_size (unsigned char numb, unsigned char packet_id_list[])
{
return 2+numb;
}
int roi_set_query_list_response (char buff, unsigned char numb, unsigned char packet_id_list[])
{
return 2+numb;
}
int roi_set_motors (char* buff, int main_brush, int vacuum, int side_brush)
{
buff[0] = ROICMD_MOTORS;
buff[1] = 0;
if (main_brush) {
buff[1] |= 0x04;
}
if (vacuum) {
buff[1] |= 0x02;
}
if (side_brush) {
buff[1] |= 0x01;
}
return 2;
}
typedef struct {
char buff[100];
} rot_song_t;
#if 0
/**
* 文字列での曲の登録
*
* C4 - ドの四分音符
* D4E4C4C3G3
*/
roi_song_str (char *buff, char *mml)
{
char *p;
song_cursor = song_buff;
// 一文字ずつ処理
while (*p != '\0') {
if (isspace (*p)) continue;
if (is_note (*p)) {
// [A-G] 音符
if (isalpha (*p)) {
// ド
if (*p == 'A') {
*song_cursor = 72;
song_cursor++;
p++;
len = strtoi (p);
}
}
}
}
}
#endif
|
Python | UTF-8 | 239 | 3.859375 | 4 | [] | no_license | animals = ['dog', 'cat', 'cow']
print(animals)
print(type(animals))
print(animals[0])
print(animals[1:2])
animals.append('pig')
print(animals)
animals.insert(1, 'bird')
print(animals)
print(len(animals))
del animals[0]
print(animals) |
Java | UTF-8 | 549 | 2.1875 | 2 | [] | no_license | package by.trepam.karotki.news.service.impl;
import java.util.ArrayList;
import by.trepam.karotki.news.controller.CommandName;
import by.trepam.karotki.news.service.HelpService;
import by.trepam.karotki.news.service.exception.ServiceException;
public class HelpServiceImpl implements HelpService {
public ArrayList<String> getCommands() throws ServiceException{
ArrayList<String> list=new ArrayList<String>();
for (int i=0;i<CommandName.values().length;i++){
list.add(CommandName.values()[i].getDescritpion());
}
return list;
}
}
|
JavaScript | UTF-8 | 1,060 | 4.46875 | 4 | [] | no_license | /*
Ejecutar una tarea asíncrona usando promesas.
var promise = new Promise(callback);
parametros para callback:
resolve: función a ser ejecutada cuando la promesa se resuelva
reject: función a ser ejecutada cuando la promesa ses resuelva
*/
var tareaAsincrona = function(condicion) {
var promesa = new Promise( function(resolve, reject) {
setTimeout(function() {
console.log("Proceso asincrono terminado");
if (condicion)
resolve();
else
reject();
}, 1300);
});
return promesa;
}
/*
var promesa = tareaAsincrona();
promesa.then(
function() { console.log('Todo ok!'); }, // cumplida
function() { console.error('Todo mal!'); } // rechazada
);
*/
tareaAsincrona().then(
function() { console.log('Todo ok!'); }, // cumplida
function() { console.error('Todo mal!'); } // rechazada
);
tareaAsincrona(true).then(
function() { console.log('Todo ok!'); }, // cumplida
function() { console.error('Todo mal!'); } // rechazada
);
|
C | UTF-8 | 542 | 3.53125 | 4 | [] | no_license | #include <stdio.h>
#define TRUE 1
#define FALSE 0
typedef int Bool;
Bool logical_and(Bool a, Bool b);
Bool logical_or(Bool a, Bool b);
Bool logical_not(Bool a);
void print_bool(Bool b);
int main(){
Bool a = TRUE;
Bool b = FALSE;
print_bool(logical_and(a, b));
print_bool(logical_or(a, b));
return 0;
}
Bool logical_and(Bool a, Bool b){
return (a&&b);
}
Bool logical_or(Bool a, Bool b)
{
return (a||b);
}
Bool logical_not(Bool a)
{
return (!a);
}
void print_bool(Bool b)
{
printf("%s\n", (b ? "TRUE" : "FALSE"));
}
|
Swift | UTF-8 | 3,504 | 2.78125 | 3 | [
"MIT"
] | permissive | //
// TagsVisibilityManager.swift
// SoundFontsFramework
//
// Created by Brad Howes on 20/01/2022.
// Copyright © 2022 Brad Howes. All rights reserved.
//
import UIKit
/**
Controls visibility of the tags table view.
*/
struct TagsVisibilityManager {
private let tagsBottomConstraint: NSLayoutConstraint
private let tagsViewHeightConstraint: NSLayoutConstraint
private let fontsView: UIView
private let containerView: UIView
private let tagsTableViewController: TagsTableViewController
private let infoBar: AnyInfoBar
private let maxTagsViewHeightConstraint: CGFloat
/**
Construct new instance
- parameter tagsBottomConstraint: constraint that controls where the tags view bottom resides
- parameter tagsViewHeightConstrain: constraint that controls the height of the tags view
- parameter fontsView: the view showing the fonts
- parameter containerView: the container view that shows the fonts and tags
- parameter tagsTableViewController: the view controller for the tags table
- parameter infoBar: the InfoBar that holds the button used to show/hide the tags table
*/
init(tagsBottonConstraint: NSLayoutConstraint, tagsViewHeightConstrain: NSLayoutConstraint, fontsView: UIView,
containerView: UIView, tagsTableViewController: TagsTableViewController, infoBar: AnyInfoBar) {
self.tagsBottomConstraint = tagsBottonConstraint
self.tagsViewHeightConstraint = tagsViewHeightConstrain
self.fontsView = fontsView
self.containerView = containerView
self.tagsTableViewController = tagsTableViewController
self.infoBar = infoBar
self.maxTagsViewHeightConstraint = tagsViewHeightConstraint.constant
infoBar.addEventClosure(.showTags, self.toggleShowTags)
}
/// True when the tags view is visible
var showingTags: Bool { tagsBottomConstraint.constant == 0.0 }
/**
Hide the tags table view
*/
func hideTags() {
guard showingTags else { return }
infoBar.resetButtonState(.showTags)
tagsViewHeightConstraint.constant = maxTagsViewHeightConstraint
tagsBottomConstraint.constant = tagsViewHeightConstraint.constant + 8
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 0.25, delay: 0.0,
options: [.allowUserInteraction, .curveEaseOut],
animations: self.containerView.layoutIfNeeded,
completion: nil
)
}
}
private extension TagsVisibilityManager {
/**
Toggle the visibility of the tags table
- parameter sender: the object that sent the request
*/
func toggleShowTags(_ sender: AnyObject) {
let button = sender as? UIButton
if tagsBottomConstraint.constant == 0.0 {
hideTags()
} else {
button?.tintColor = .systemOrange
showTags()
}
}
/**
Show the tags table view
*/
func showTags() {
guard !showingTags else { return }
let maxHeight = fontsView.frame.height - 8
let midHeight = maxHeight / 2.0
let minHeight = CGFloat(120.0)
var bestHeight = midHeight
if bestHeight > maxHeight { bestHeight = maxHeight }
if bestHeight < minHeight { bestHeight = maxHeight }
tagsViewHeightConstraint.constant = bestHeight
tagsBottomConstraint.constant = 0.0
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 0.25,
delay: 0.0,
options: [.allowUserInteraction, .curveEaseIn],
animations: {
self.containerView.layoutIfNeeded()
self.tagsTableViewController.scrollToActiveRow()
}, completion: { _ in })
}
}
|
Markdown | UTF-8 | 875 | 3.296875 | 3 | [] | no_license | # To-doist.github.io
# Project Link: https://amk1999.github.io/To-doist.github.io/
## Table of Contents
1. [General Info](#general-info)
2. [Technologies](#technologies)
3. [Use](#Use)
### General Info:
***
This Website page is the general task manager named as the to-do list this web pade contains following components.
1. header with the image and date inside.
2. list in which we can add the new task.
3. text area in wich you have to type to add the tasks.
### Technologies:
***
For making this website I used following Technologies(Languages)
1. HTML5
2. css3
3. JavaScript
### Use:
***
The main benefits of to-do lists
You'll see both the forest and the trees (with the right system in place) You'll set your priorities more easily. You can measure progress more easily (what gets done) You'll free your brain and get more mental bandwidth (memory improvement)
|
Java | UTF-8 | 832 | 2.28125 | 2 | [] | no_license | package com.example.administrator.appctct.Entity;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Student {
@SerializedName("id")
@Expose
private String id;
@SerializedName("fullname")
@Expose
private String fullname;
@SerializedName("account")
@Expose
private String account;
@SerializedName("password")
@Expose
private String password;
@SerializedName("avatar")
@Expose
private String avatar;
public String getId() {
return id;
}
public String getAccount() {
return account;
}
public String getAvatar() {
return avatar;
}
public String getFullname() {
return fullname;
}
public String getPassword() {
return password;
}
}
|
Shell | UTF-8 | 508 | 3.140625 | 3 | [] | no_license | #!/bin/bash
#To run this you have to have root privileges
#This aims to use the tool Petbox to automate honey pot setups.
#Log in to your Linux machine as an admin user. Open a terminal window and download pentbox with the command:
#Fetch the tool
#save and run in root folder
eval "cd /home/andrew/Downloads"
eval "wget http://downloads.sourceforge.net/project/pentbox18realised/pentbox-1.8.tar.gz"
eval "tar xvfz pentbox-1.8.tar.gz"
eval "cd /home/andrew/Downloads/pentbox-1.8 && sudo ./pentbox.rb"
|
Markdown | UTF-8 | 6,785 | 3.375 | 3 | [] | no_license | 六五
他很腼腆,没再说什么,就这样沉默着。渐渐地,她开始感到不安。
“我的生活并不美满。”她说。
“嗯,”他应付着,他并不想听这种话。
“我觉得不会有人真正爱我的。”她说。
他并不回答。
“你是否也这样想,”她缓缓地说,“你是否以为我只需要肉体的爱?不,不是,我需要你精神上陪伴我。”
“我知道你这样,我知道你并不只要求肉体上的东西。可我要你把你的精神——那金色的光芒给予我,那就是你,你并不懂,把它给我吧。”
沉默了一会她回答道:
“我怎么能这样呢?你并不爱我呀!你只要达到你的目的。你并不想为我做什么,却只要我为你做。这太不公平了!”
他尽了最大的努力来维持这种对话并强迫她在精神上投降。
“两回事,”他说,“这是两回事。我会以另一种方式为你尽义务,不是通过你,而是通过另一种方式。不过,我想我们可以不通过我们自身而结合在一起——因为我们在一起所以我们才在一起,如同这就是一种现象,并不是我们要通过自己的努力才能维持的东西。”
“不,”她思忖着说,“你是个自我中心者。你从来就没什么热情,你从来没有对我释放出火花来。你只需要你自己,真的,只想你自己的事。你需要我,仅仅在这个意义上,要我为你服务。”
可她这番话只能让他关上自己的心扉。
“怎么个说法并没关系。我们之间存在还是不存在那种东西呢?”
“你根本就不爱我。”她叫道。
“我爱,”他气愤地说,“可我要——”他的心又一次看到了她眼中溢满的泉水一样的金光,那光芒就象从什么窗口射出来的一样。在这个人情淡漠的世界上,他要她跟他在一起。可是,告诉她这些干什么呢?跟她交谈干什么?这想法是难以言表的。让她起什么誓只能毁了她。这想法是一只天堂之鸟,永远也不会进窝,它一定要自己飞向爱情不可。
“我一直觉得我会得到爱情,可你却让我失望了。你不爱我,这你知道的。你不想对我尽义务。你只需要你自己。”
一听她又重复那句“你不想对我尽义务”,他就觉得血管里涌过一股怒火。他心中再也没有什么天堂鸟了。
“不,”他生气地说,“我不想为你尽义务,因为没什么义务可尽。你什么义务也不需要我尽,什么也没有,甚至你自己也不需要我尽义务,这是你的女性特点。我不会为你的女性自我贡献任何东西,它不过是一块破布做成的玩具。”
“哈!”她嘲弄地笑道,“你就是这样看我的吗?你还无礼地说你爱我!”
她气愤地站起来要回家。
“你需要的是虚无缥缈的未知世界。”她转过身冲着他朦胧的身影说,“我知道你的话是什么意思了,谢谢。你想让我成为你的什么所属品,不批评你,不在你面前为我自己伸张什么。你要我仅仅成为你的什么东西!不,谢谢!如果你需要那个,倒是有不少女人可以给予你。有不少女人会躺下让你从她们身上迈过去——去吧,去找她们,只要需要,就去找她们吧。”
“不,”他恼火地脱口而出:“我要你放弃你自信武断的意志,放弃你那可怕的固执脾气,我要的就是这个。我要你相信自己,从而能够解脱自己。”
“解脱?”她调侃道,“我完全可以轻易地解脱自己。倒是你自己不能做到自我解脱,你固守着自我,似乎那是你唯一的财富。你是主日学校的教师,一个牧师。”
她话中的真理令他木然。
“我并不是说让你以狄奥尼索斯狂热的方式解脱自己,”他说,“我知道你可以那样做。可我憎恶狂热,无论是狄奥尼索斯式的还是其它形式的。那象是在重复一些毫无意义的东西。我希望你不要在乎自我,不要在乎你的自我,别再固执了,高高兴兴、自信些、超然些。”
“谁固执了?”她嘲讽道,“是谁一直在固执从事?不是我!”
她的话语中透着嘲弄与苛薄,让他无言以对。
“我知道,”他说,“我们双方都很固执,可我们都错了。
我们又没有取得一致。”
他们坐在岸边的树影下,沉默着。夜色淡淡的笼罩着他们,他们都沉浸在月夜中。
渐渐地,他们都平静了下来。她试探着把手搭在他的肩上。他们的手默默地握在一起。
“你真爱我吗?”她问。
他笑了。
“我说那是你的口号。”他逗趣说。
“是吗!”她十分有趣地说。
“你的固执——你的口号——‘一个布朗温,一个布朗温’——那是战斗的口号。你的口号就是‘你爱我吗?恶棍,要么屈服,要么去死。’”
“不嘛,”她恳求道,“才不是那个样子呢。不是那样。但我应该知道你是否爱我,难道我不应该吗?”
“嗯,或着了解,否则就算了。”
“那么你爱吗?”
“是的,我爱。我爱你,而且我知道这是不可改变的。这是不会改变的了,还有什么可说的?”
她半喜半疑地沉默了一会儿。
“真的么?”她说着偎近他。
“真的,现在就做吧,接受这爱吧。结束它。”
她离他更近了。
“结束什么?”他喃言道。
“结束烦恼。”他说。
她贴近他。他拥抱着她,温柔地吻她。多么自由自在啊,仅仅拥抱她、温柔地吻她。仅仅同她静静地在一起,不要任何思想、任何欲望和任何意志,仅仅同她安谧相处,处在一片宁馨的气氛中,但又不是睡眠,而是愉悦。满足于愉悦,不要什么欲望,不要固执,这就是天堂:同处于幸福的安谧中。
她依偎在他怀中,他温柔地吻她,吻她的头发,她的脸,她的耳朵,温柔,轻巧地,就象早晨落下的露珠儿。可这耳边热乎乎的呼气却令她不安,点燃了旧的毁灭火焰。她依偎着他,而他则能够感觉到自己的血液象水银一样在变动着。
“我们会平静下来的,对吗?”他说。
“是的,”她似乎顺从地说。
说完她又偎在他的怀中。
可不一会儿她就抽出身子,开始凝视他。
“我得回家了。”她说。
“非要走吗?太遗憾了。”他说。
她转向他,仰起头来等他吻自己。
|
PHP | UTF-8 | 1,070 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Bling\Opencart;
class Manufacturer extends \Bling\Opencart\Base {
public function get_all() {
$sql = "SELECT manufacturer_id, `name` FROM `" . DB_PREFIX . "manufacturer` ";
$result = $this->db->query($sql);
return $result->rows;
}
public function insert($manufacturer) {
$sql = "INSERT INTO " . DB_PREFIX . "manufacturer SET name = '" . $this->db->escape($manufacturer) . "', sort_order = '0'";
$this->db->query($sql);
$manufacturer_id = $this->db->getLastId();
$this->db->query("INSERT INTO " . DB_PREFIX . "manufacturer_to_store SET manufacturer_id = '" . (int)$manufacturer_id . "', store_id = 0");
// define url amigavel
$keyword = $this->url->str2url($manufacturer['name']);
$keyword = $this->check_keyword($keyword, $manufacturer_id, 'm');
if ($keyword) {
$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'manufacturer_id=" . (int)$manufacturer_id . "', keyword = '" . $this->db->escape($keyword) . "'");
}
$this->cache->delete('manufacturer');
return $manufacturer_id;
}
}
?> |
C# | UTF-8 | 323 | 3.0625 | 3 | [] | no_license | abstract class AbstractClass<T>
{
bool update()
{
Connection.Update<T>(this as T);
}
}
class Entity : AbstractClass<Entity>
{
}
class Connection
{
public static void Update<T>(T obj)
{
someMethod<T>()
}
}
|
Python | UTF-8 | 1,587 | 4.6875 | 5 | [] | no_license | #Tip: use Thonny for cool debugging
##Basic log
print("🚨 Learning Python 🚨")
##Using new line /n
#print("print('what to print')\nTest\nTest\nTest")
##Calling input
#print("Hello " + input("What is your name?"))
##Ex: Write a program that prints the number of characters in a user's name. You might need to Google for a function that calculates the length of a string.
#print(len(input("What is your name?")))
##Variables
#name = input("What is your name?")
#print(name)
##Ex: Write a program that switches the values stored in the variables a and b.
# # 🚨 Don't change the code below 👇
# a = input("a: ")
# b = input("b: ")
# # 🚨 Don't change the code above 👆
# ####################################
# #Write your code below this line 👇
# c = a
# a = b
# b = c
# #Write your code above this line 👆
# ####################################
# # 🚨 Don't change the code below 👇
# print("a: " + a)
# print("b: " + b)
## Ex: Band Name Generator
#1. Create a greeting for your program.
print("Hi there! Wellcome to the band name generator!")
#2. Ask the user for the city that they grew up in.
city_name = input("What is the city you grew up in?\n")
print(city_name)
#3. Ask the user for the name of a pet.
pet_name = input("What is the name of your pet?\n")
print(pet_name)
#4. Combine the name of their city and pet and show them their band name.
print("New Band Name: " + city_name + " " + pet_name + ". This name rocks!")
#5. Make sure the input cursor shows on a new line, see the example at:
# https://band-name-generator-end.appbrewery.repl.run/ |
Go | UTF-8 | 1,511 | 3.0625 | 3 | [] | no_license | package downloader
import(
"net/http"
"io/ioutil"
"fmt"
)
const (
retryNum = 2
retryWait = 1
)
type Downloader struct {
ID string
}
type Result struct {
Data []byte
ContentType string
}
func New() (downloader *Downloader, err error) {
downloaderID := autoID()
downloader = &Downloader{ID:downloaderID}
return
}
func (this *Downloader) Request(u string) (result Result, err error) {
var resp *http.Response
downloadSuccess := false
for i := 0; i < retryNum; i++ {
resp, err = this.download(u)
if err == nil {
downloadSuccess = true
break
}
}
if !downloadSuccess {
return
}
defer resp.Body.Close()
statusCode := resp.StatusCode
if statusCode != 200 {
err = fmt.Errorf("get url:%s error, response statusCode not 200", u)
return
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
err = fmt.Errorf("get url:%s error, content IO read error", u)
return
}
result.Data = b
result.ContentType = http.DetectContentType(b)
return
}
func (this *Downloader) download(u string) (resp *http.Response, err error) {
client := &http.Client{}
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return
}
req.Header.Add("User-Agent", `Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko`)
resp, err = client.Do(req)
if err != nil {
return
}
return
} |
Markdown | UTF-8 | 4,594 | 2.65625 | 3 | [] | no_license | ---
title: Combobox Component
---
<link rel="stylesheet" href="/css/tailwind-components.css">
<script setup>
import { ref } from "vue"
import { Icon } from "@iconify/vue"
import ApiReference from "../../src/components/ApiReference.vue"
import metadata from "../../src/gallery/metadata.json"
import { useMetadata } from '@servicestack/vue'
const { setMetadata } = useMetadata()
setMetadata(metadata)
const strings = ref()
const objects = ref()
const pairs = ref([])
</script>
<Breadcrumbs class="not-prose my-4" home-href="/vue/">
<Breadcrumb href="/vue/gallery/">gallery</Breadcrumb>
<Breadcrumb>Combobox</Breadcrumb>
</Breadcrumbs>
The `Combobox` component provides an Autocomplete Input optimized for searching a List of string values, Key Value Pairs or Object Dictionary, e.g:
```ts
<div class="grid grid-cols-12 gap-6">
<Combobox id="Strings" class="col-span-4" v-model="strings" :values="['Alpha','Bravo','Charlie']" />
<Combobox id="Object" class="col-span-4" v-model="objects" :options="{ A:'Alpha', B:'Bravo', C:'Charlie' }" />
<Combobox id="Pairs" class="col-span-4" v-model="pairs" label="Multiple from Pairs" multiple
:entries="[{key:'A',value:'Alpha'}, {key:'B',value:'Bravo'}, {key:'C',value:'Charlie'}]" />
</div>
```
<div class="not-prose grid grid-cols-12 gap-6">
<Combobox id="Strings" class="col-span-4" v-model="strings" :values="['Alpha','Bravo','Charlie']" />
<Combobox id="Object" class="col-span-4" v-model="objects" :options="{ A:'Alpha', B:'Bravo', C:'Charlie' }" />
<Combobox id="Pairs" class="col-span-4" v-model="pairs" label="Multiple from Pairs" multiple
:entries="[{key:'A',value:'Alpha'}, {key:'B',value:'Bravo'}, {key:'C',value:'Charlie'}]" />
</div>
Which supports populating both a single string value or multiple strings in an Array with **multiple** property.
<ApiReference component="Combobox">Auto Forms</ApiReference>
Combobox components can also be used in [Auto Form Components](/vue/gallery/autoform) on `string` or string collection properties
with the `[Input(Type="combobox")]` [declarative UI Attribute](/locode/declarative#ui-metadata-attributes) on C# Request DTOs, e.g:
```csharp
public class ComboBoxExamples : IReturn<ComboBoxExamples>, IPost
{
[Input(Type="combobox", Options = "{ allowableValues:['Alpha','Bravo','Charlie'] }")]
public string? SingleClientValues { get; set; }
[Input(Type="combobox", Options = "{ allowableValues:['Alpha','Bravo','Charlie'] }", Multiple = true)]
public List<string>? MultipleClientValues { get; set; }
[Input(Type="combobox", EvalAllowableValues = "['Alpha','Bravo','Charlie']")]
public string? SingleServerValues { get; set; }
[Input(Type="combobox", EvalAllowableValues = "AppData.AlphaValues", Multiple = true)]
public List<string>? MultipleServerValues { get; set; }
[Input(Type="combobox", EvalAllowableEntries = "{ A:'Alpha', B:'Bravo', C:'Charlie' }")]
public string? SingleServerEntries { get; set; }
[Input(Type="combobox", EvalAllowableEntries = "AppData.AlphaDictionary", Multiple = true)]
public List<string>? MultipleServerEntries { get; set; }
}
```
Which can then be rendered with:
```html
<AutoForm type="ComboBoxExamples" />
```
<AutoForm type="ComboBoxExamples" class="not-prose mb-4" />
**Combobox Options**
Each property shows a different way of populating the Combobox's optional values, they can be populated from a JavaScript
Object literal using `Options` or on the server with a [#Script Expression](https://sharpscript.net) where they can be
populated from a static list or from a C# class as seen in the examples referencing `AppData` properties:
```csharp
public class AppData
{
public List<string> AlphaValues { get; set; }
public Dictionary<string, string> AlphaDictionary { get; set; }
public List<KeyValuePair<string, string>> AlphaKeyValuePairs { get; set; }
}
```
Which are populated on in the AppHost on Startup with:
```csharp
ScriptContext.Args[nameof(AppData)] = new AppData
{
AlphaValues = new() {
"Alpha", "Bravo", "Charlie"
},
AlphaDictionary = new()
{
["A"] = "Alpha",
["B"] = "Bravo",
["C"] = "Charlie",
},
AlphaKeyValuePairs = new()
{
new("A","Alpha"),
new("B","Bravo"),
new("C","Charlie"),
},
};
```
Which can alternatively be populated from a dynamic source like an RDBMS table.
As C# Dictionaries have an undetermined sort order, you can use a `List<KeyValuePair<string, string>>` instead when you need to
display an ordered list of Key/Value pairs. |
C++ | UTF-8 | 2,712 | 2.609375 | 3 | [] | no_license |
#include <iostream>
#include <visualization.h>
#include <Eigen/Dense>
#include <dV_spring_particle_particle_dq.h>
#include <d2V_spring_particle_particle_dq2.h>
#include <forward_euler.h>
#include <backward_euler.h>
#include <symplectic_euler.h>
#include <runge_kutta.h>
//igl
#include <igl/readOBJ.h>
//simulation parameters
Eigen::VectorXd q;
Eigen::VectorXd q_dot;
double mass = 1.0;
double stiffness = 100.0;
double dt = 1e-2;
int integrator_type = 2;
bool simulate(igl::opengl::glfw::Viewer & viewer) {
//take a time step
auto force = [](Eigen::VectorXd &f, Eigen::VectorXd &q, Eigen::VectorXd &qdot) { dV_spring_particle_particle_dq(f, q, stiffness); f *= -1; };
auto stiff = [](Eigen::MatrixXd &k, Eigen::VectorXd &q, Eigen::VectorXd &qdot) { d2V_spring_particle_particle_dq2(k, q, stiffness); k *= -1; };
switch(integrator_type) {
case 0:
forward_euler(q,q_dot, dt, mass, force);
break;
case 1:
backward_euler(q,q_dot, dt, mass, force, stiff);
break;
case 2:
symplectic_euler(q,q_dot, dt, mass, force);
break;
case 3:
runge_kutta(q, q_dot, dt, mass, force);
break;
};
//update mesh positions
Visualize::rigid_transform_1d(0, q(0));
Visualize::scale_x(1, q(0));
return false;
}
int main(int argc, char **argv) {
std::cout<<"Start A1 \n";
//check argument for integrator type
if(argc > 1) {
if(argv[1] == std::string("be")) { integrator_type = 1; }
if(argv[1] == std::string("se")) { integrator_type = 2; }
if(argv[1] == std::string("rk")) { integrator_type = 3; }
}
//Load data for animations
Eigen::MatrixXd V_cow, V_spring;
Eigen::MatrixXi F_cow, F_spring;
igl::readOBJ("D:/github/CSC417-physics-based-animation-master/CSC417-Assignment/-CSC417-Assignment/Assignment1/data/spot.obj", V_cow, F_cow);
igl::readOBJ("D:/github/CSC417-physics-based-animation-master/CSC417-Assignment/-CSC417-Assignment/Assignment1/data/spring.obj", V_spring, F_spring);
//setup simulation variables
q.resize(1);
q_dot.resize(1);
q_dot(0) = 0;
q(0) = 1;
//setup libigl viewer and activate
Visualize::setup(q, q_dot);
Visualize::viewer().callback_post_draw = &simulate;
Visualize::add_object_to_scene(V_cow, F_cow, Eigen::RowVector3d(244,165,130)/255.);
Visualize::add_object_to_scene(V_spring, F_spring, Eigen::RowVector3d(200,200,200)/255.);
Visualize::viewer().launch();
//how am I going to organize memory
//seperate q and q Dot arrays (extra stuff to pass around) <-- this is easier to deal with
return 0;
} |
Markdown | UTF-8 | 2,456 | 3.5625 | 4 | [] | no_license | ---
layout: post
title: "紧张"
date: 2015-07-20 22:22:44 +0800
comments: true
categories: 感触
---
每个人都会犯错,很多时候我们讨厌自己犯错,但是更多是讨厌自己犯错后的处理方式,因为很多时候我们选择了逃避。<!--more-->
虽然我一直很讨厌自己,但是现在我开始接受自己了。即使我以前犯过很多错误,现在也会犯很多错,
>To raise self-esteem and that is to cope as opposed as avoid.
在中考考语文的时候,我紧张得手都在抖。每一次参加篮球比赛,我都紧张得双手双脚僵硬。每一次的考试,我都会紧张。所以我有很多遗憾,是因为每一次的紧张,都让自己无法表现得好点,中考没考上养正,篮球比赛虽然我们拿到了冠军,但是自己并没有发挥作用,充满遗憾。
但从现在回顾过去的25年,因为这些紧张和错误,我变成了我。我还是会紧张,但是我已经知道了我会紧张,我还是会犯错,但是我已经知道了我会犯错。虽然我还是害怕紧张,害怕犯错,但是我开始选择了面对这些。
明天考科目三,我有点紧张,但从一开始我就知道自己会紧张了。所以从一开始我就很认真的学,很认真的复习。教练说要练车,我就请假练,我知道这样会耽误工作。但是更知道,如果我不努力的练习,那么考试的时候我紧张起来,可能无法通过考试。既然知道自己会紧张,那么就让自己紧张吧,然后让自己准备在紧张中考试。
在过去的25年里,我不知道别人是怎么看我的,但是我觉得自己有很多问题。所以我才尝试得去了解自己,看了很多心理学的书,心灵鸡汤。但是对我影响最深刻的是一句话“我并不孤独”,不会只有我才这样子。每个人都会紧张的,而不是只有我紧张。每个人都会犯错,而不是只有我会犯错的。所以当我遇到紧张我应该怎么办?我犯错了应该怎么办?以前我选择了逃避,骗自己不会紧张,骗自己不会犯错。
但是25年过去了,我开始选择面对了。既然会紧张,那么就接受紧张,然后更加努力的练习,让紧张也无法影响自己。犯错,那么就面对错误,改正它,无法改正的就尽量弥补。
我开始接受自己。因为我就是我。
>Give yourself the permission to be human.
|
Java | UTF-8 | 525 | 1.828125 | 2 | [] | no_license | // Generated by dagger.internal.codegen.ComponentProcessor (https://google.github.io/dagger).
package com.kotlin.goods.data.repository;
import dagger.internal.Factory;
public final class CategoryRepository_Factory implements Factory<CategoryRepository> {
private static final CategoryRepository_Factory INSTANCE = new CategoryRepository_Factory();
@Override
public CategoryRepository get() {
return new CategoryRepository();
}
public static Factory<CategoryRepository> create() {
return INSTANCE;
}
}
|
TypeScript | UTF-8 | 716 | 2.96875 | 3 | [] | no_license | import * as React from 'react';
export interface Dimensions {
width: number;
height: number;
}
export type ViewPortType = 'mobile' | 'desktop';
export interface ViewPort {
dimensions: Dimensions;
type: ViewPortType;
}
export const windowDimensions = (window: Window): Dimensions => ({
width: window.innerWidth,
height: window.innerHeight,
});
export const viewportType = (dimensions: Dimensions): ViewPortType =>
dimensions.width < 480 ? 'mobile' : 'desktop';
export const viewPort = (dimensions: Dimensions): ViewPort => ({
dimensions,
type: viewportType(dimensions),
});
export const ViewPortContext = React.createContext<ViewPort>(
viewPort({
height: 768,
width: 1024,
}),
);
|
C++ | UTF-8 | 3,784 | 3.140625 | 3 | [] | no_license | #ifndef __OPENGL_EXPERIMENTS_TRANSFORMATIONS__
#define __OPENGL_EXPERIMENTS_TRANSFORMATIONS__
#include <cmath>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
/* In this file, we hand construct the transformation matrices.
* Since the aim of this project is to learn the fundamentals of
* 3D graphics, I am creating these matrices by scratch.
*/
class Transformations
{
public:
static glm::mat4 PerspectiveProjection(
float fov_degrees, // field of view in degrees
float ar, // aspect ratio (width/height) of frustum
float d_near,
float d_far)
{
/**
* |
* *|
* * |
* * |
* y+ | * |
* ^ | |
* | * | |
* o-->z- | |
* * | |
* | |
* | * |
* near * |
* * |
* *|
* |
* far
*
*
* y+
* ^
* |
* +-----------|------------+
* | | |
* | | |
* height | +--------------> x+
* | |
* | |
* +------------------------+
* width
*
*
*/
// TODO: Implement on your own
return glm::perspective(glm::radians(fov_degrees), ar, d_near, d_far);
};
static glm::mat4 OrthographicProjection(
float left,
float right,
float top,
float bottom,
float near,
float far)
{
const float& x_min = left;
const float& x_max = right;
const float& y_min = bottom;
const float& y_max = top;
const float& z_min = far;
const float& z_max = near;
glm::mat4 ortho;
ortho[0][0] = 2.0f/(x_max-x_min);
ortho[1][0] = 0.0f;
ortho[2][0] = 0.0f;
ortho[3][0] = (-2.0f*x_min) / (x_max - x_min) - 1.0f;
ortho[0][1] = 0.0f;
ortho[1][1] = 2.0f/(y_max-y_min);
ortho[2][1] = 0.0f;
ortho[3][1] = (-2.0f*y_min) / (y_max - y_min) - 1.0f;
ortho[0][2] = 0.0f;
ortho[1][2] = 0.0f;
ortho[2][2] = 2.0f/(z_max-z_min);
ortho[3][2] = (-2.0f*z_min) / (z_max - z_min) - 1.0f;
ortho[0][3] = 0.0f;
ortho[1][3] = 0.0f;
ortho[2][3] = 0.0f;
ortho[3][3] = 1.0f;
return ortho;
}
private:
static void PrintMatrix_(const glm::mat4& mat, const std::string& msg)
{
std::cout << msg << std::endl;
std::cout << mat[0][0] << "," << mat[1][0] << "," << mat[2][0] << "," << mat[3][0] << std::endl;
std::cout << mat[0][1] << "," << mat[1][1] << "," << mat[2][1] << "," << mat[3][1] << std::endl;
std::cout << mat[0][2] << "," << mat[1][2] << "," << mat[2][2] << "," << mat[3][2] << std::endl;
std::cout << mat[0][3] << "," << mat[1][3] << "," << mat[2][3] << "," << mat[3][3] << std::endl;
}
};
#endif
|
Java | UTF-8 | 7,085 | 3.65625 | 4 | [
"MIT"
] | permissive | package tictactoe;
import java.util.Scanner;
public class Main {
public static Scanner scanner = new Scanner(System.in);
public static String[][] gameBoard = {
{" ", " ", " "},
{" ", " ", " "},
{" ", " ", " "}
};
public static State currentState = State.X_TURN;
public static boolean isRunning = true;
public static void main(String[] args) {
printGameBoard();
while (isRunning) {
gameRuns(currentState);
}
}
enum State {
X_TURN, O_TURN, HAS_WINNER, DRAW
}
public static void gameRuns(State state) {
switch (state) {
case X_TURN:
getNextMove();
printGameBoard();
checkStateOfBoard();
if (currentState != State.HAS_WINNER && currentState != State.DRAW) {
currentState = State.O_TURN;
}
break;
case O_TURN:
getNextMove();
printGameBoard();
checkStateOfBoard();
if (currentState != State.HAS_WINNER && currentState != State.DRAW) {
currentState = State.X_TURN;
}
break;
case HAS_WINNER:
if (xWins) {
System.out.println("X wins");
} else {
System.out.println("O wins");
}
isRunning = false;
break;
case DRAW:
System.out.println("Draw");
isRunning = false;
break;
}
}
public static void getNextMove() {
boolean hasPlayedValidMove = false;
while (!hasPlayedValidMove) {
System.out.println("Enter the coordinates:");
String[] moveInput = scanner.nextLine().trim().split(" ");
if (moveInput[0].length() > 1 || moveInput[1].length() > 1) {
printNeedsNumbers();
continue;
}
int coord1, coord2;
try {
coord1 = Integer.parseInt(moveInput[0]);
coord2 = Integer.parseInt(moveInput[1]);
}
catch (NumberFormatException nfe) {
printNeedsNumbers();
continue;
}
if (coord1 > 3 || coord2 > 3) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
}
int coord1Index = 0;
if (coord1 == 1) {
coord1Index = 0;
}
if (coord1 == 2) {
coord1Index = 1;
}
if (coord1 == 3) {
coord1Index = 2;
}
int coord2Index = 0;
if (coord2 == 1) {
coord2Index = 2;
}
if (coord2 == 2) {
coord2Index = 1;
}
if (coord2 == 3) {
coord2Index = 0;
}
if (gameBoard[coord2Index][coord1Index].equals(" ") && currentState == State.X_TURN) {
gameBoard[coord2Index][coord1Index] = "X";
hasPlayedValidMove = true;
} else if (gameBoard[coord2Index][coord1Index].equals(" ") && currentState == State.O_TURN) {
gameBoard[coord2Index][coord1Index] = "O";
hasPlayedValidMove = true;
} else {
System.out.println("This cell is occupied! Choose another one!");
}
}
}
public static void checkStateOfBoard() {
checkForLines();
if (xWins) {
currentState = State.HAS_WINNER;
} else if (oWins) {
currentState = State.HAS_WINNER;
} else if (!checkForEmptySpaces()) {
currentState = State.DRAW;
}
}
public static boolean xWins = false;
public static boolean oWins = false;
public static void checkForLines() {
// Horizontal Case
for (int rowIndex = 0; rowIndex < 3; rowIndex++) {
if (gameBoard[rowIndex][0].equals(gameBoard[rowIndex][1]) && gameBoard[rowIndex][0].equals(gameBoard[rowIndex][2])) {
if (checkForXLine(rowIndex, 0)) {
xWins = true;
}
if (checkForOLine(rowIndex, 0)) {
oWins = true;
}
}
}
// Vertical Case
for (int columnIndex = 0; columnIndex < 3; columnIndex++) {
if (gameBoard[0][columnIndex].equals(gameBoard[1][columnIndex]) && gameBoard[0][columnIndex].equals(gameBoard[2][columnIndex])) {
if (checkForXLine(0, columnIndex)) {
xWins = true;
}
if (checkForOLine(0, columnIndex)) {
oWins = true;
}
}
}
// Main Diagonal Case
if (gameBoard[0][0].equals(gameBoard[1][1]) && gameBoard[0][0].equals(gameBoard[2][2])) {
if (checkForXLine(0, 0)) {
xWins = true;
}
if (checkForOLine(0, 0)) {
oWins = true;
}
}
// Anti Diagonal Case
if (gameBoard[2][0].equals(gameBoard[1][1]) && gameBoard[2][0].equals(gameBoard[0][2])) {
if (checkForXLine(2, 0)) {
xWins = true;
}
if (checkForOLine(2, 0)) {
oWins = true;
}
}
}
public static boolean xLine = false;
public static boolean oLine = false;
public static boolean checkForXLine(int rowIndex, int columnIndex) {
if (gameBoard[rowIndex][columnIndex].equals("X")) {
xLine = true;
}
return xLine;
}
public static boolean checkForOLine(int rowIndex, int columnIndex) {
if (gameBoard[rowIndex][columnIndex].equals("O")) {
oLine = true;
}
return oLine;
}
public static boolean checkForEmptySpaces() {
boolean hasEmptySpaces = false;
int spaceCounter = 0;
for (int rowIndex = 0; rowIndex < 3; rowIndex++) {
for (int columnIndex = 0; columnIndex < 3; columnIndex++) {
if (gameBoard[rowIndex][columnIndex].equals(" ")) {
spaceCounter += 1;
}
}
}
if (spaceCounter > 0) {
hasEmptySpaces = true;
}
return hasEmptySpaces;
}
public static void printGameBoard() {
System.out.println("---------");
for (String[] arrays : gameBoard) {
System.out.print("| ");
for (int index = 0; index < 3; index++) {
System.out.print(arrays[index] + " ");
}
System.out.print("|");
System.out.println();
}
System.out.println("---------");
}
public static void printNeedsNumbers() {
System.out.println("You should enter numbers!");
}
}
|
Markdown | UTF-8 | 1,480 | 3.328125 | 3 | [] | no_license | object Main extends Application {
val t = new Array(3, 5)
}
```scala
java.lang.VerifyError: (class: , method: <init> signature: ()V) Bad t
ield/putstatic
at RequestResult$$.<init>(<console>:3)
at RequestResult$$.<clinit>(<console>)
at RequestResult$$result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source
at sun.reflect.DelegatingMethodAccessorImpl...
```
The problem here is that the type of the Array (inferencer assigns Array[Nothing]), is different from what the constructor returns (Array[Array[Nothing]]). Actually, this is a serious type soundness problem: one can give whatever type he wants to Array, and call an unrelated (in the number of dimensions) constructor: `new Array[Array[Double]](5, 5, 5)`. Here we are typing the expression as a 2-dimensional array of Doubles, but create a 3-dimensioanl array.
In other words: the return type of an array constructor is not always the type of the array, but rather it is Array[Array[...Array[a]..]] with as many nested Arrays as the number of dimensions it takes. I think this is a case where type constraints /a la/ C# would help.
One solution is to make these constructors private and provide factory methods in `object Array`:
```scala
def make[a](d1: Int): Array[a] = new Array[a](d1, d2)
def make[a](d1: Int, d2: Int): Array[Array[a]] = new Array[Array[a]](d1, d2)
...
```
|
PHP | UTF-8 | 838 | 2.71875 | 3 | [] | no_license | <?php
namespace Indielab\AutoScout24;
use Curl\Curl;
class Client
{
public $cuid;
public $member;
const API_URL = 'https://www.autoscout24.ch/api/hci/v3/json/';
public function __construct($cuid, $member)
{
$this->cuid = $cuid;
$this->member = $member;
}
public function endpointResponse($name, array $args = [])
{
$curl = new Curl();
$curl->get(self::API_URL . $name, array_merge($args, ['cuid' => $this->cuid, 'member' => $this->member]));
if (!$curl->error) {
return $this->decodeResponse($curl->response);
}
throw new Exception("Invalid API Request: " . $curl->error_message);
}
public function decodeResponse($response)
{
return json_decode($response, true);
}
}
|
SQL | UTF-8 | 569 | 2.84375 | 3 | [] | no_license |
DROP PROCEDURE IF EXISTS PPOSITIONMOT;
DELIMITER |
CREATE PROCEDURE PPOSITIONMOT (IN VPOSITION INT, IN VTITRE BOOLEAN, IN VID_MOT INT, VID_ENTITE INT, IN VID_POS_TAG INT, IN VID_ARTICLE INT,IN VID_SYNONYME INT,IN VID_WIKI INT)
BEGIN
INSERT INTO POSITION_MOT (ID_POSITION, POSITION,TITRE,ID_MOT,ID_ENTITE,ID_POS_TAG,ID_ARTICLE,ID_SYNONYME,ID_WIKI)
VALUES (NULL, VPOSITION,VTITRE,VID_MOT,VID_ENTITE,VID_POS_TAG,VID_ARTICLE,VID_SYNONYME,VID_WIKI);
END|
DELIMITER ;
CALL PPOSITIONMOT(1,TRUE,1,1,1,1,1,1);
CALL PPOSITIONMOT(2,FALSE,2,1,1,1,1,1);
|
Java | UTF-8 | 4,324 | 2.390625 | 2 | [
"Apache-2.0"
] | permissive | package com.tyz.bluetoothstudy;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
/**
* Created by Administrator on 2017/4/4.
*/
public class ClientThread implements Runnable {
final String TAG = "ClientThread";
BluetoothAdapter mBtAdapter;
BluetoothDevice mDevice;
Handler mUiHandler;
Handler writeHandler;
BluetoothSocket mBtClientSocket;
OutputStream mClientOutputStream;
InputStream mClientInputStream;
BufferedReader reader;
BtConnnectStatusListener mBtConnnectStatusListener;
public void SetConnectBack(BtConnnectStatusListener BtConnnectStatusListener) {
this.mBtConnnectStatusListener = BtConnnectStatusListener;
}
public ClientThread(BluetoothAdapter mBtAdapter, BluetoothDevice device, Handler handler) {
this.mBtAdapter = mBtAdapter;
this.mDevice = device;
this.mUiHandler = handler;
BluetoothSocket tmpSocket = null;
try {
tmpSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(Params.UUID));
} catch (IOException e) {
e.printStackTrace();
}
mBtClientSocket = tmpSocket;
}
@Override
public void run() {
Log.e(TAG, "----------------- do client thread run()");
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
try {
try {
// Connect the mDevice through the mBtClientSocket. This will block
// until it succeeds or throws an exception
mBtClientSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the mBtClientSocket and get mClientOutputStream
try {
mBtClientSocket.close();
mBtConnnectStatusListener.onConnectFailed(mDevice);
return;
} catch (IOException closeException) {
}
mBtConnnectStatusListener.onConnectFailed(mDevice);
return;
}
mBtConnnectStatusListener.onConnectSuccess(mDevice);
connectReader();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "-------------- exception");
}
}
private void connectReader() throws IOException {
mClientOutputStream = mBtClientSocket.getOutputStream();
mClientInputStream = mBtClientSocket.getInputStream();
//reader = new BufferedReader(new InputStreamReader(mBtClientSocket.getInputStream(), "utf-8"));
new Thread(new Runnable() {
@Override
public void run() {
Log.e(TAG, "-----------do client read run()");
byte[] buffer = new byte[1024];
int len;
String content;
try {
while ((len = mClientInputStream.read(buffer)) != -1) {
content = new String(buffer, 0, len);
Message message = new Message();
message.what = Params.MSG_CLIENT_REV_NEW;
message.obj = content;
mUiHandler.sendMessage(message);
Log.e(TAG, "------------- client read data mClientInputStream while ,send msg ui" + content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void write(String data) {
// data = data+"\r\n";
try {
mClientOutputStream.write(data.getBytes("utf-8"));
Log.e(TAG, "---------- write data ok " + data);
} catch (IOException e) {
e.printStackTrace();
}
}
public interface BtConnnectStatusListener {
void onConnectSuccess(BluetoothDevice device);
void onConnectFailed(BluetoothDevice device);
void onConnecting(BluetoothDevice device);
}
}
|
SQL | UTF-8 | 1,254 | 3.609375 | 4 | [] | no_license | CREATE PROC Stage.usp_LocationUpdate
AS
INSERT INTO [Core].[Location]
([Code]
,[Name]
,LocalName
,[BusinessKey]
,[LocationType_ID]
,[ParentLocation_ID]
)
select Src.Location, Src.Location, Src.Location
,Src.Location
, (SELECT LocationType_ID FROM Core.LocationType LT
WHERE LT.Name = Src.LocationType
OR LT.Code = Src.LocationType
OR CAST(LT.LocationType_ID as varchar(255)) = Src.LocationType
) As LocationType_ID
, (SELECT Location_ID FROM Core.Location L
WHERE L.Name = Src.ParentLocation
OR L.Code = Src.ParentLocation
OR CAST(L.ParentLocation_ID as varchar(255)) = Src.ParentLocation
) As ParentLocation_ID
from Stage.Location Src
where not exists (select 1 from core.Location lExist
where lExist.name = src.Location
OR lExist.Code = src.Location
OR CAST( lExist.Location_ID as varchar(255)) = src.Location
)
UPDATE Core.Location
SET Geog = Src.Geog
FROM Core.Location L
INNER JOIN Stage.Location Src
ON L.Name = Src.Location
OR L.Code = Src.Location
OR CAST( L.Location_ID as varchar(255)) = Src.Location |
Java | UTF-8 | 2,832 | 2.46875 | 2 | [] | no_license | package com.moviesmustsee.dtos;
import com.moviesmustsee.documents.Movie;
import com.moviesmustsee.documents.MovieLinks;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
@NotNull
@NotEmpty
public class MovieOutputDto extends MovieMinimumOutputDto {
private String[] genre;
private String region;
private String artMovement;
private String language;
private int runtime;
private String color;
private String sound;
private MovieLinks movieLinks;
public MovieOutputDto(){
// Empty for framework
}
public MovieOutputDto(String id, String[] name, LocalDate releaseDate,
String artMovement, String[] genre, String storyline,
String[] director, String country, String language,
int durationInMin, String color, String sound,MovieLinks movieLinks,String poster) {
super(id, name, releaseDate,storyline,country,director,poster);
this.genre = genre;
this.artMovement=artMovement;
this.language = language;
this.runtime = durationInMin;
this.color = color;
this.sound = sound;
this.movieLinks = movieLinks;
}
public MovieOutputDto(Movie movie){
this(movie.getId(),movie.getName(),movie.getReleaseDate(),movie.getArtMovement(),movie.getGenre(),
movie.getStoryline(),movie.getDirector(),movie.getCountry(),movie.getLanguage(),
movie.getRuntime(),movie.getColor(),movie.getSound(),movie.getMovieLinks(),movie.getPoster());
}
public void setRegion(String region) {
this.region = region;
}
public void setRuntime(int runtime) {
this.runtime = runtime;
}
public void setMovieLinks(MovieLinks movieLinks) {
this.movieLinks = movieLinks;
}
public void setGenre(String[] genre) {
this.genre = genre;
}
public void setArtMovement(String artMovement) {
this.artMovement = artMovement;
}
public void setLanguage(String language) {
this.language = language;
}
public void setColor(String color) {
this.color = color;
}
public void setSound(String sound) {
this.sound = sound;
}
public String[] getGenre() {
return genre;
}
public String getArtMovement() {
return artMovement;
}
public String getLanguage() {
return language;
}
public String getColor() {
return color;
}
public String getSound() {
return sound;
}
public String getRegion() {
return region;
}
public int getRuntime() {
return runtime;
}
public MovieLinks getMovieLinks() {
return movieLinks;
}
} |
Shell | UTF-8 | 143 | 3.3125 | 3 | [] | no_license | echo " enter num1"
read a
echo " enter num2"
read b
if [ $a -gt $b ]
then
echo "$a is greater than $b"
else
echo " $b is larger than $a "
fi
|
Markdown | UTF-8 | 4,370 | 3.28125 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: "Swift. 정리하기 26"
subtitle: "Swift Language Reference-Types"
date: 2018-04-15 09:00:00
author: "MinJun"
header-img: "img/tags/Swift-bg.jpg"
comments: true
tags: [Swift]
---
## Reference
[Types](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/doc/uid/TP40014097-CH31-ID445)<br>
---
## Types
스위프트에는 두가지 종류의 타입이 있습니다: 이름이 있는 타입(named types) 과 복합 타입(compound types) 이름이 있는 타입은 정의될때 특정 이름을 부여할수 있는 타입입니다. 이름이 있는 타입은 클레스, 구조체, 열거형, 프로토콜을 포함합니다.예를들어 유저가 정의한 클레스 인스턴스는 `MyClass`로 네이밍된것은 `MyClass` 타입을 가집니다.
Swift 표준 라이브러리는 사용자가 정의한 이름이 있는 타입 외에도 배열, 딕셔너리 및 옵셔널 값을 나타내는 타입을 포함하여 일반적으로 많이 사용되는 많은 타입을 정의합니다.
일반적으로 숫자, 문자 및 문자열을 나타내는 타입과 같이 일반적으로 다른 언어에서 기본 또는 기본으로 간주되는 데이터 타입은 구조체를 사용하여 Swift 표준 라이브러리에서 정의되고 구현된 실제로 명명된 타입입니다. 왜냐하면 이름이 있는 타입이기 때문에, [확장(Extension)](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html#//apple_ref/doc/uid/TP40014097-CH24-ID151) 과 [확장 선언(Extension Declaration)](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-ID378) 에서 논의된 확장 선언을 사용하여 필요에 맞게 행동을 확장할수 있습니다.
`복합 타입(compound type)`는 이름이 없고, Swift언어 자체에서 정의됩니다. 거기에는 두가지 복합 유형이 있습니다 : 함수 타입(function types) 와 튜플 타입(tuple types)이 있습니다. 복합 타입은 이름이 있는 타입과 복합타입이 포함될수 있습니다. 예를들어 튜플 타입 `(Int, (Int, Int))`는 두개의 요소를 포함합니다 : 첫번째는 이름이 있는 Int 타입 그리고 두번째는 다른 `(Int, Int) `복합 타입 입니다.
이름이 있는 타입과(named type) 복합 타입(compound type)을 괄호로 묶을수 있습니다. 그러나 하나의 타입에 괄호를 추가해도 아무런 효과가 없습니다 예를들어 `(Int)` 는 `Int`와 같습니다.
이 장에서는 Swift언어 자체에 정의된 타입에 대해 설명하고 Swift의 타입유추 동작에 대해서 설명합니다.
---
## Optional Type
Swift 언어는 후위표기(postfix) `?`를 Optional<Wrapped> 정의된 이름이 있는 타입의 구문으로 정의합니다. 다음 두 선언은 동일합니다.
```swift
var optionalInteger: Int?
var optionalInteger: Optional<Int>
```
Optional Type 인스턴스에 값이 포함되어 있는 경우 `!`접미사 연산자를 사용하여 해당 값에 접근할수 있습니다.
```swift
optionalInteger = 42
optionalInteger! // 42
```
더 자세한 내용은 [Optional](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330)을 참조하세요
---
## Implicitly Unwrapped Optional Type
암시적 언랩핑(Implicitly Unwrapped)은 해당 타입을 포함을하는 선언의 의미를 변경하기 때문에 튜플 타입 또는 제네릭 타입의 중첩된 옵셔널 타입(딕셔너리 또는 배열 요소 타입)은 암시적으로 언랩핑된것으로 표시할수 없습니다.
```swift
let tupleOfImplicitlyUnwrappedElements: (Int!, Int!) // Error
let implicitlyUnwrappedTuple: (Int, Int)! // OK
let arrayOfImplicitlyUnwrappedElements: [Int!] // Error
let implicitlyUnwrappedArray: [Int]! // OK
```
더 자세한건 [Implicity Unwrapped Optionals](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID334)을 참조해주세요
---
|
C# | UTF-8 | 1,563 | 3.375 | 3 | [
"MIT"
] | permissive | using System.Linq;
namespace ProjectEuler
{
public class S315 : ISolution
{
private static readonly int[,] Overlap = new int[10, 10]
{
{ 6,2,4,4,3,4,5,4,6,5},
{ 2,2,1,2,2,1,1,2,2,2},
{ 4,1,5,4,2,3,4,2,5,4},
{ 4,2,4,5,3,4,4,3,5,5},
{ 3,2,2,3,4,3,3,3,4,4},
{ 4,1,3,4,3,5,5,3,5,5},
{ 5,1,4,4,3,5,6,3,6,5},
{ 4,2,2,3,3,3,3,4,4,4},
{ 6,2,5,5,4,5,6,4,7,6},
{ 5,2,4,5,4,5,5,4,6,6},
};
public string GetAnswer()
{
int count = 0;
const int MAX = 20000000;
var primes = Utils.GenPrimes(MAX).Where(p => p > MAX / 2).ToArray();
foreach (var p in primes)
{
if (p != 0)
{
count += GetCount((int)p);
}
}
return count.ToString();
}
private static int GetCount(int p)
{
int count = 0;
while (p >= 10)
{
int sum = Utils.DigitSum(p);
count += GetCount(p, sum);
p = sum;
}
return count * 2;
}
private static int GetCount(int num1, int num2)
{
int count = 0;
while (num1 > 0 && num2 > 0)
{
count += Overlap[num1 % 10, num2 % 10];
num1 /= 10;
num2 /= 10;
}
return count;
}
}
}
|
Python | UTF-8 | 330 | 3.796875 | 4 | [
"MIT"
] | permissive | print('{:=^100}'.format(' DESAFIO 23-A '))
n = str(input('\nDigite um númeoro de 0 a 9999: '))
n = '{:0>4}'.format(n[:4])
unidade = n[3]
dezena = n[2]
centena = n[1]
milhar = n[0]
print('\nUnidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}\n'.format(unidade, dezena, centena, milhar))
print('{:=^100}'.format(' FIM DESAFIO 23-A ')) |
C++ | UTF-8 | 1,143 | 2.96875 | 3 | [] | no_license | #include<stdio.h>
int main() {
int i, a=0;
float w, h, m1=0, m2=0, m3=0, m4=0, m5=0, mh=0, p=0;
for(int k=0; k<55; k++) {
if(k==0 || k==11 || k==22 || k==33 || k==44) printf("\n\n\t\tTime %d\n", k/11+1);
printf("\nDigite, nesta ordem, a idade, o peso e a altura do jogador: ");
scanf("%d %f %f", &i, &w, &h);
if(i<18) a++;
if(w>80) p++;
switch(k/11) {
case 0:
m1+=i;
break;
case 1:
m2+=i;
break;
case 2:
m3+=i;
break;
case 3:
m4+=i;
break;
default:
m5+=i;
}
mh+=h;
}
printf("\n\t\tResultados\n");
printf("\nQuantidade de jogadores com menos de 18 anos: %d",a);
printf("\nMedia da idade dos jogadores do time 1: %.2f",m1/11);
printf("\nMedia da idade dos jogadores do time 2: %.2f",m2/11);
printf("\nMedia da idade dos jogadores do time 3: %.2f",m3/11);
printf("\nMedia da idade dos jogadores do time 4: %.2f",m4/11);
printf("\nMedia da idade dos jogadores do time 5: %.2f",m5/11);
printf("\nMedia da altura de todos os jogadores: %.2f",mh/55);
printf("\nPorcentagem de jogadores com mais de 80kg: %.2f",p*100/55);
}
|
PHP | UTF-8 | 3,124 | 2.671875 | 3 | [
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace Drupal\core_search_facets;
use Drupal\Core\Database\Query\Condition;
use Drupal\search\SearchQuery;
/**
* Extension of the SearchQuery class.
*/
class FacetsQuery extends SearchQuery {
/**
* Stores joined tables.
*
* @var array
*/
protected $joinedTables = [];
/**
* Adds the facet join, but only does so once.
*
* @param array $query_info
* An associative array of query information.
* @param string $table_alias
* The alias of the table being joined.
*/
public function addFacetJoin(array $query_info, $table_alias) {
if (isset($query_info['joins'][$table_alias])) {
if (!isset($this->joinedTables[$table_alias])) {
$this->joinedTables[$table_alias] = TRUE;
$join_info = $query_info['joins'][$table_alias];
$this->join($join_info['table'], $join_info['alias'], $join_info['condition']);
}
}
}
/**
* Adds the facet field, ensures the alias is "value".
*
* @param array $query_info
* An associative array of query information.
*
* @return FacetsQuery
* An instance of this class.
*/
public function addFacetField(array $query_info) {
foreach ($query_info['fields'] as $field_info) {
$this->addField($field_info['table_alias'], $field_info['field'], 'value');
}
return $this;
}
/**
* Executes a facet query.
*/
public function execute() {
$this->parseSearchExpression();
// Adds OR conditions.
if (!empty($this->words)) {
$or = new Condition('OR');
foreach ($this->words as $word) {
$or->condition('i.word', $word);
}
$this->condition($or);
}
// Build query for keyword normalization.
$this->join('search_total', 't', 'i.word = t.word');
$this
->condition('i.type', $this->type)
->groupBy('i.langcode')
->groupBy('value')
->groupBy('i.type')
->groupBy('i.sid')
->having('COUNT(*) >= :matches', [':matches' => $this->matches]);
// For complex search queries, add the LIKE conditions.
/*if (!$this->simple) {
$this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type');
$this->condition($this->conditions);
}*/
// Add conditions to query.
$this->join('search_dataset', 'd', 'i.sid = d.sid AND i.type = d.type AND i.langcode = d.langcode');
$this->condition($this->conditions);
// Add tag and useful metadata.
$this
->addTag('search_' . $this->type)
->addMetaData('normalize', $this->normalize);
// Adds subquery to group the results in the r table.
$subquery = \Drupal::database()->select($this->query, 'r')
->fields('r', ['value'])
->groupBy('r.value');
// Adds COUNT() expression to get facet counts.
$subquery->addExpression('COUNT(r.value)', 'count');
$subquery->orderBy('count', 'DESC');
// Executes the subquery.
return $subquery->execute();
}
/**
* Returns the search expression.
*
* @return string
* The search expression.
*/
public function getSearchExpression() {
return $this->searchExpression;
}
}
|
Java | UTF-8 | 1,340 | 2.25 | 2 | [] | no_license | package com.fyf.student.controller;
import com.fyf.student.entity.User;
import com.fyf.student.model.ResultModel;
import com.fyf.student.service.ILocationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author fuyufan
* @date 2020/11/26 10:21
*/
@Slf4j
@RestController
@RequestMapping("/test")
@Api("接口")
public class LocationController extends BaseController{
@Autowired
private ILocationService service;
@PostMapping("/add")
@ApiOperation("新增用户")
public String addUser(@RequestBody User user) {
return "新增成功";
}
@GetMapping("/find")
@ApiOperation("查找用户")
public ResultModel findById(@RequestParam("id") Long id) {
if(service.getById(id) != null){
System.out.println(service.getById(id).toString());}
return success(service.getById(id));
}
@PutMapping("/update")
@ApiOperation("更新用户")
public boolean update(@RequestBody User user) {
return true;
}
@DeleteMapping("/delete/{id}")
@ApiOperation("删除用户")
public boolean delete(@PathVariable("id") int id) {
return true;
}
}
|
Shell | UTF-8 | 1,759 | 4.03125 | 4 | [
"MIT"
] | permissive | #!/usr/bin/bash
####################################################################
### This script assembles RNAseq reads into contigs and scaffolds #
# To run this script you must have SPAdes installed. #
####################################################################
### This chunk checks for whether the assembly data directory exists
# and creates it if it doesn't. This directory is necessary for the
# trimming step in the code below.
if [ -d "data/raw/assembly/" ]
then
echo "Assembly folder already exists, continuing..."
echo
else
echo "Assembly folder doesn't exist, creating and continuing..."
echo
mkdir data/raw/assembly
fi
### This chunk creates a temporary directory for use by SPAdes during assembly
# and saves it in the $TEMP variable. The if statement exits the script with
# an error if the temp directory has not been successfully created.
TEMP=$(mktemp -d)
if [ $? -ne 0 ]
then
echo "can't create $TEMP ... exit"
exit 1
fi
### This chunk iterates over a list of treatment groups contained in the
# data/process/samples.tsv file and assembles their respective short
# read sequence files using SPAdes in RNA mode with a maximum RAM limit
# of 900GB with 32 threads which are then stored in separate directories
# within data/raw/assembly/. The last line deletes the $TEMP directory
# created above.
for treatment in $(awk '{ print $2 }' data/process/samples.tsv); do
mkdir data/raw/assembly/"$treatment"
spades.py --rna -o data/raw/assembly/"$treatment"/ -1 data/raw/trimmed/"$treatment"_forward_paired.fastq -2 data/raw/trimmed/"$treatment"_reverse_paired.fastq -s data/raw/trimmed/"$treatment"_unpaired.fastq -t 32 -m 180 --tmp-dir $TEMP
done
rm -rf $TEMP
|
C# | UTF-8 | 590 | 3.046875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace ClassMetotDemo
{
class CustomerManager
{
public void Add(Customer customer)
{
Console.WriteLine(customer.Name+ " " + customer.LastName + " " + "Adlı Müşteri Eklendi");
}
public void Guncelle(string MusteriAdi, string MusteriSoyadi)
{
Console.WriteLine(MusteriAdi + " " + MusteriSoyadi + " " + "Adlı Müşteri güncellendi");
}
public void Delete(Customer customer)
{
Console.WriteLine(customer.Name + " " + customer.LastName + " " + "Adlı Müşteri Silindi");
}
}
}
|
Java | UTF-8 | 1,320 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | package denominator;
import java.io.Closeable;
import java.io.IOException;
import javax.inject.Inject;
/**
* represents the connection between a {@link DNSApi} interface and the {@link Provider} that
* implements it.
*/
public class DNSApiManager implements Closeable {
private final Provider provider;
private final DNSApi api;
private final CheckConnection checkConnection;
private final Closeable closer;
@Inject
DNSApiManager(Provider provider, DNSApi api, CheckConnection checkConnection, Closeable closer) {
this.provider = provider;
this.api = api;
this.checkConnection = checkConnection;
this.closer = closer;
}
/**
* the currently configured {@link DNSApi}
*/
public DNSApi api() {
return api;
}
/**
* Get the provider associated with this instance
*/
public Provider provider() {
return provider;
}
/**
* Returns true, if api commands are likely to succeed.
*
* @see CheckConnection
*/
public boolean checkConnection() {
return checkConnection.ok();
}
/**
* closes resources associated with the connections, such as thread pools or open files.
*/
@Override
public void close() throws IOException {
closer.close();
}
@Override
public String toString() {
return provider.toString();
}
}
|
Java | UTF-8 | 278 | 2.265625 | 2 | [] | no_license | package Messages;
import java.io.Serializable;
public class Knock implements Serializable {
public int responsePort;
public byte[] bytes;
public Knock(int responsePort, byte[] bytes){
this.responsePort = responsePort;
this.bytes = bytes;
}
}
|
C++ | UHC | 328 | 2.71875 | 3 | [] | no_license | /* پ ƿ Լ */
#ifndef GOMOKU_UTIL_H
#define GOMOKU_UTIL_H
#include <vector>
#include <sstream>
using namespace std;
class Util {
public:
// input ڸ ū Լ.
vector<string> getTokens(string input, char delimiter);
};
#endif // !GOMOKU_UTIL_H |
Java | UTF-8 | 678 | 2.203125 | 2 | [] | no_license | package com.meca.trade.to;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class GraphDataGenerator extends FileReportGenerator {
@Override
public void writeLog(String log) {
writer.print(Constants.GRAPH_DATA_JSON_START_STRING);
writer.print(log);
writer.print(Constants.GRAPH_DATA_JSON_END_STRING);
writer.println(Constants.GRAPH_DATA_JSON_SEPARATOR_STRING);
}
@Override
public void initializeLogger(String name) {
super.initializeLogger(name);
writer.println("[");
}
@Override
public void finalizeLogger() {
writer.println("]");
super.finalizeLogger();
}
}
|
Swift | UTF-8 | 7,037 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | import UIKit
import DifferenceKit
final class RandomViewController: UIViewController {
private typealias Section = ArraySection<RandomModel, RandomModel>
@IBOutlet private weak var collectionView: UICollectionView!
private var data = [Section]()
private var dataInput: [Section] {
get { return data }
set {
let changeset = StagedChangeset(source: data, target: newValue)
collectionView.reload(using: changeset) { data in
self.data = data
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Random"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Random", style: .plain, target: self, action: #selector(refresh))
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(cellType: RandomPlainCell.self)
collectionView.register(viewType: RandomLabelView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader)
}
@objc private func refresh() {
let defaultSourceSectionCount = 20
let defaultSourceElementCount = 20
func randomSection() -> ArraySection<RandomModel, RandomModel> {
let elements = (0..<defaultSourceElementCount).map { _ in RandomModel() }
return ArraySection(model: RandomModel(), elements: elements)
}
guard !data.isEmpty else {
dataInput = (0..<defaultSourceSectionCount).map { _ in randomSection() }
return
}
let source = data
var target = source
let sourceSectionCount = source.count
let deleteSectionCount = Int.random(in: 0..<sourceSectionCount / 4)
let deletedSourceSectionCount = sourceSectionCount - deleteSectionCount
let updateSectionCount = Int.random(in: 0..<deletedSourceSectionCount / 4)
let moveSectionCount = Int.random(in: 0..<deletedSourceSectionCount / 4)
let minInsertCount = defaultSourceSectionCount > sourceSectionCount ? deleteSectionCount : 0
let insertSectionCount = Int.random(in: minInsertCount..<sourceSectionCount / 4)
let targetSectionCount = deletedSourceSectionCount + insertSectionCount
let deleteSectionIndices = (0..<deleteSectionCount).map { i in Int.random(in: 0..<sourceSectionCount - i) }
let updateSectionIndices = (0..<updateSectionCount).map { _ in Int.random(in: 0..<deletedSourceSectionCount) }
let moveSectionIndexPairs = (0..<moveSectionCount).map { _ in (source: Int.random(in: 0..<deletedSourceSectionCount), target: Int.random(in: 0..<deletedSourceSectionCount)) }
let insertSectionIndices = (0..<insertSectionCount).map { i in Int.random(in: 0..<deletedSourceSectionCount + i) }
for index in deleteSectionIndices {
target.remove(at: index)
}
for index in target.indices {
let sourceCount = target[index].elements.count
let deleteCount = Int.random(in: 0..<sourceCount / 4)
let deletedSourceCount = sourceCount - deleteCount
let updateCount = Int.random(in: 0..<deletedSourceCount / 4)
let moveCount = Int.random(in: 0..<deletedSourceCount / 4)
let insertCount = Int.random(in: 0..<sourceCount / 4)
let deleteIndices = (0..<deleteCount).map { i in Int.random(in: 0..<sourceCount - i) }
let updateIndices = (0..<updateCount).map { _ in Int.random(in: 0..<deletedSourceCount) }
let moveIndexPairs = (0..<moveCount).map { _ in (source: Int.random(in: 0..<deletedSourceCount), target: Int.random(in: 0..<deletedSourceCount)) }
let insertIndices = (0..<insertCount).map { i in Int.random(in: 0..<deletedSourceCount + i) }
for elementIndex in deleteIndices {
target[index].elements.remove(at: elementIndex)
}
for elementIndex in updateIndices {
target[index].elements[elementIndex].isUpdated.toggle()
}
for pair in moveIndexPairs {
target[index].elements.swapAt(pair.source, pair.target)
}
for elementIndex in insertIndices {
target[index].elements.insert(RandomModel(), at: elementIndex)
}
}
for index in updateSectionIndices {
target[index].model.isUpdated.toggle()
}
for pair in moveSectionIndexPairs {
target.swapAt(pair.source, pair.target)
}
for index in insertSectionIndices {
target.insert(randomSection(), at: index)
}
let elementMoveAcrossSectionCount = Int.random(in: 0..<targetSectionCount * 2)
for _ in (0..<elementMoveAcrossSectionCount) {
func randomIndexPath() -> IndexPath {
let sectionIndex = Int.random(in: 0..<targetSectionCount)
let elementIndex = Int.random(in: 0..<target[sectionIndex].elements.count)
return IndexPath(item: elementIndex, section: sectionIndex)
}
let sourceIndexPath = randomIndexPath()
let targetIndexPath = randomIndexPath()
target[sourceIndexPath.section].elements[sourceIndexPath.item] = target[targetIndexPath.section].elements[targetIndexPath.item]
target[targetIndexPath.section].elements[targetIndexPath.item] = target[sourceIndexPath.section].elements[sourceIndexPath.item]
}
dataInput = target
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refresh()
}
}
extension RandomViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data[section].elements.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: RandomPlainCell = collectionView.dequeueReusableCell(for: indexPath)
let model = data[indexPath.section].elements[indexPath.item]
cell.contentView.backgroundColor = model.isUpdated ? .cyan : .orange
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard kind == UICollectionView.elementKindSectionHeader else {
return UICollectionReusableView()
}
let model = data[indexPath.section].model
let view: RandomLabelView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, for: indexPath)
view.label.text = "Section ID: \(model.id)"
view.label.textColor = model.isUpdated ? .red : .darkText
return view
}
}
|
C# | UTF-8 | 1,103 | 2.84375 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using LitJson;
public class LocalFile {
public void SaveLocalFile(string path, string fileName, object obj) {
string fpath = System.IO.Path.Combine(path, fileName);
//將myPlayer轉換成json格式的字串
string saveString = JsonMapper.ToJson(obj);
//將字串saveString存到硬碟中
StreamWriter file = new StreamWriter(fpath);
file.Write(saveString);
file.Close();
}
public JsonData LoadLocalFile(string path, string fileName) {
string fpath = System.IO.Path.Combine(path, fileName);
Debug.Log("path:" + fpath);
if (!File.Exists(fpath)) {
return null;
}
//讀取json檔案並轉存成文字格式
StreamReader file = new StreamReader(fpath);
string loadJson = file.ReadToEnd();
file.Close();
//新增一個物件類型為playerState的變數 loadData
JsonData loadData = JsonMapper.ToObject(loadJson);
return loadData;
}
}
|
JavaScript | UTF-8 | 398 | 2.96875 | 3 | [] | no_license | $(document).ready(function(){
//focus and blur
$("input").focus(function(){
$(this).css('background','pink');
});
$("input").blur(function(){
$(this).css('background','');
});
$("input").keydown(function(){
$('#output').text('You are typing...');
});
$("input").keyup(function(){
$('#output').text('Resume typing...');
});
}); |
Ruby | UTF-8 | 845 | 3.828125 | 4 | [] | no_license | require 'pry'
$side_dishes = {"Carrots": 1.75, "Mystery Yogurt": 1.00, "Beef Jerky": 0.50}
class SideDish
attr_accessor :name, :price
def initialize(name, price)
@name = name
@price = price
$side_dishes[@name.to_sym] = price
end
# def add
# puts "What menu item would you like to add?"
# name = gets.strip
# puts "How much does that item cost?"
# price = gets.to_f
# @side_dish[name] = price
# end
end
# side_1 = SideDish.new("Carrots", 1.75)
# side_2 = SideDish.new("Mystery Yougurt", 1.00)
# side_3 = SideDish.new("Beef Jerky", 0.50)
# class SideDish
# def initialize
# @side_dish = {"Beef Jerky": 0.50, "Mystery Yogurt": 1.00, "Carrots": 1.75}
# end
#
# def self.dishes
# puts @side_dish
# end
#
# end
# side_1 = SideDish.new
# side_2 = SideDish.new
# side_3 = SideDish.new
|
Java | UTF-8 | 3,067 | 2.4375 | 2 | [] | no_license |
package Levels.Three;
import Levels.BasicLevel;
import java.awt.Point;
public class Level_33 extends BasicLevel{
public Level_33() {
BackGroundColor = "Black";
Time = "300" ;
type = "GreenAndTrees" ; // if OrangeAndMushroom then red treen
pos = new Point(10 , 12);
BackGroundImage = "Clouds" ;
attribute = "Ground" ;
LevelLength = 5500 ;
this.AddStone(0, 13, 2, 16);
this.AddTree(18, 10, 5, 23);
this.AddTree(22, 7, 8, 28);
this.AddTree(30, 13, 2, 33);
this.AddTree(36, 12, 3, 43);
this.AddEnemyMushroom(25, 6);
this.AddCoin(31, 12);
this.AddCoin(32, 12);
this.AddCoin(37, 6);
this.AddCoin(42, 6, 1, 45);
this.AddTree(43, 9, 15, 47);
this.AddTree(46, 11, 4, 56);
this.AddTree(47, 7, 4, 53);
this.AddTree(55, 3, 15, 59);
this.AddCoin(56, 2, 1, 58);
this.AddQuestionMarkWithMushroom(49, 3);
this.AddEnemyTurtlePatrol(47, 6 , 5);
this.AddEnemyTurtlePatrol(46, 10 , 9);
this.AddTree(65, 7, 6, 68);
this.AddTree(69, 7, 6, 72);
this.AddTree(73, 7, 6, 76);
this.AddTree(77, 4, 9, 80);
this.AddTree(65, 13, 2, 81);
this.AddCoin(66, 6);
this.AddCoin(70, 6);
this.AddCoin(74, 6);
this.AddCoin(78, 3);
this.AddCoin(81, 5);
this.AddCoin(88, 5);
this.AddCoin(90, 5);
this.AddEnemyTurtlePatrol(65, 11, 15);
this.AddTree(84, 11, 4, 88);
this.AddTree(97, 9, 6, 100);
this.AddTree(104, 5, 15, 108);
this.AddTree(108, 7, 15, 111);
this.AddTree(107, 11, 15, 111);
this.AddTree(116, 12, 10, 119);
this.AddTree(119, 10, 10, 131);
this.AddFlyingTurtlePatrol(114, 2, 4);
this.AddEnemyTurtlePatrol(119, 9, 11);
this.AddEnemyTurtlePatrol(119, 9, 11);
this.AddCoin(105, 4, 1, 107);
this.AddCoin(109, 6);
this.AddCoin(108, 10);
this.AddChocolate(151, 12);
this.AddCheckPointsFlag(151, 3);
this.AddCastle(154, 2, "big");
this.AddStone(144, 13, 2, 170);
this.AddCastle(0, 8, "small");
this.AddCheckPoints(159, 12, 34, new Point(6,6));
this.AddBalenceLift(81 ,6 , 7);
this.AddLift_LeftRight(29, 4, 5);
this.AddLift_LeftRight(32, 8, 6);
this.AddLiftFall(60, 6);
this.AddLift_LeftRight(92, 9, 6);
this.AddLift_LeftRight(96, 5, 6);
this.AddLift_LeftRight(101, 11, 6);
this.AddLift_LeftRight(129, 6, 6);
this.AddBalenceLift(136 ,5 , 4);
}
}
|
Java | UTF-8 | 1,411 | 2.421875 | 2 | [] | no_license | package com.dyn.springbootdemo.entity;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "t_user", schema = "test", catalog = "")
public class TUserDO {
private int pkUid;
private String fName;
private String fPassword;
@Id()
@Column(name = "pk_uid", nullable = false)
public int getPkUid() {
return pkUid;
}
public void setPkUid(int pkUid) {
this.pkUid = pkUid;
}
@Basic
@Column(name = "f_name", nullable = true, length = 255)
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
@Basic
@Column(name = "f_password", nullable = true, length = 255)
public String getfPassword() {
return fPassword;
}
public void setfPassword(String fPassword) {
this.fPassword = fPassword;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TUserDO tUserDO = (TUserDO) o;
return pkUid == tUserDO.pkUid &&
Objects.equals(fName, tUserDO.fName) &&
Objects.equals(fPassword, tUserDO.fPassword);
}
@Override
public int hashCode() {
return Objects.hash(pkUid, fName, fPassword);
}
}
|
C++ | UTF-8 | 668 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minSteps(string s, string t) {
int alp1[210], alp2[210];
memset(alp1, 0, sizeof(alp1));
memset(alp2, 0, sizeof(alp2));
for (auto ch : s) alp1[ch]++;
for (auto ch : t) alp2[ch]++;
int sum = 0;
bool vis[210];
memset(vis, 0, sizeof(vis));
for (auto ch : s) {
if (!vis[ch] && (alp1[ch] - alp2[ch]) > 0) {
sum += alp1[ch] - alp2[ch];
vis[ch] = 1;
}
}
return sum;
}
};
int main(int argc, char const *argv[]) {
/* code */
return 0;
}
|
Python | UTF-8 | 1,548 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/env python3
import requests
import ujson as json
import re
import time
PUSHSHIFT_REDDIT_URL = "http://api.pushshift.io/reddit"
def fetchObjects(**kwargs):
# Default params values
params = {"sort_type": "created_utc", "sort": "asc", "size": 10}
for key, value in kwargs.items():
params[key] = value
print(params)
type = "comment"
if 'type' in kwargs and kwargs['type'].lower() == "submission":
type = "submission"
r = requests.get(PUSHSHIFT_REDDIT_URL + "/" + type + "/search/", params=params)
if r.status_code == 200:
response = json.loads(r.text)
data = response['data']
sorted_data_by__id = sorted(data, key=lambda x: int(x['id'], 36))
return sorted_data_by__id
def process(**kwargs):
max_created_utc = 1446686449
max_id = 0
file = open("data.json", "w")
while 1:
nothing_processed = True
objects = fetchObjects(**kwargs, after=max_created_utc)
if objects is not None:
for obj in objects:
id = int(obj['id'], 36)
if id > max_id:
nothing_processed = False
created_utc = obj['created_utc']
max_id = id
if created_utc > max_created_utc: max_created_utc = created_utc
print(json.dumps(obj, sort_keys=True, ensure_ascii=True), file=file)
if nothing_processed: return
max_created_utc -= 1
process(subreddit="securityanalysis", type="comment") |
C# | UTF-8 | 3,343 | 2.703125 | 3 | [] | no_license | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Calculator.Infrastructure;
using System.Linq;
namespace UnitTestProject
{
[TestClass]
public class ShuntingYardPostfixNotationTest
{
[TestMethod]
public void TestMethod1()
{
var lexemList = new List<Lexem>() {
new Lexem(5),
new Lexem(OperationEnum.Addition),
new Lexem(7)
};
var calc = new ShuntingYardCalculator();
var postfNotList = calc.TranslateToPostfixNotation(lexemList).ToArray();
Assert.IsTrue(!postfNotList[0].IsOperation);
Assert.IsTrue(!postfNotList[1].IsOperation);
Assert.IsTrue(postfNotList[2].IsOperation);
}
[TestMethod]
public void TestMethod2()
{
// 7 - 2 * 3
var lexemList = new List<Lexem>() {
new Lexem(7),
new Lexem(OperationEnum.Subtraction),
new Lexem(2),
new Lexem(OperationEnum.Multiplication),
new Lexem(3),
};
var calc = new ShuntingYardCalculator();
var postfNotList = calc.TranslateToPostfixNotation(lexemList).ToArray();
var strexpr = string.Join(" ", postfNotList.Select(x => x.ToString()));
Assert.AreEqual("7 2 3 * -", strexpr);
}
[TestMethod]
public void TestMethod3()
{
// 7 - 2 * 3 + 1 + 1 * 1 + 2 / 1;
var lexemList = new List<Lexem>() {
new Lexem(7),
new Lexem(OperationEnum.Subtraction),
new Lexem(2),
new Lexem(OperationEnum.Multiplication),
new Lexem(3),
new Lexem(OperationEnum.Addition),
new Lexem(1),
new Lexem(OperationEnum.Addition),
new Lexem(1),
new Lexem(OperationEnum.Multiplication),
new Lexem(1),
new Lexem(OperationEnum.Addition),
new Lexem(2),
new Lexem(OperationEnum.Division),
new Lexem(1),
};
var calc = new ShuntingYardCalculator();
var postfNotList = calc.TranslateToPostfixNotation(lexemList).ToArray();
var strexpr = string.Join(" ", postfNotList.Select(x => x.ToString()));
Assert.AreEqual("7 2 3 * - 1 + 1 1 * + 2 1 / +", strexpr);
}
[TestMethod]
public void TestMethod4()
{
var expression = "2 + 10 / 2 * 3 / 1 / 1 - 3 * 5";
var la = new LexemParser();
var lexems = la.Parse(expression).ToArray();
var calc = new ShuntingYardCalculator();
var postfNotList = calc.TranslateToPostfixNotation(lexems).ToArray();
var strexpr = string.Join(" ", postfNotList.Select(x => x.ToString()));
Assert.AreEqual("2 10 2 / 3 * 1 / 1 / + 3 5 * -", strexpr);
}
[TestMethod]
public void TestMethod5()
{
var expression = "2 + 10 / 2 * 1";
var la = new LexemParser();
var lexems = la.Parse(expression).ToArray();
var calc = new ShuntingYardCalculator();
var postfNotList = calc.TranslateToPostfixNotation(lexems).ToArray();
var strexpr = string.Join(" ", postfNotList.Select(x => x.ToString()));
Assert.AreEqual("2 10 2 / 1 * +", strexpr);
}
}
}
|
Ruby | UTF-8 | 510 | 2.84375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require_relative '../lib/account_challenge'
require 'csv'
if ARGV.length < 2
puts "Invalid number of arguments! Please review and try again."
else
accounts_file = File.open(ARGV[0])
transaction_file = File.open(ARGV[1])
@account_engine = AccountChallenge.new
@account_engine.read_account_input(accounts_file.read)
@account_engine.read_transaction_input(transaction_file.read)
accounts_file.close
transaction_file.close
@account_engine.print_balances
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.