language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 712 | 2.15625 | 2 | [] | no_license | package com.app.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.daos.BlogRepo;
import com.app.pojos.Blog;
import com.app.pojos.Tags;
@Service
@Transactional
public class BlogServiceImpl implements IBlogService{
@Autowired
private BlogRepo repo;
@Override
public List<Blog> getAllBlogs() {
return repo.findAll();
}
@Override
public List<Blog> findByTag(Tags tag) {
return repo.findByTags(tag);
}
@Override
public Blog findById(Integer id) {
return repo.getOne(id);
}
@Override
public Blog add(Blog b) {
return repo.save(b);
}
}
|
Java | UTF-8 | 335 | 1.9375 | 2 | [] | no_license | package co.edu.uniajc.service;
import java.util.List;
import co.edu.uniajc.model.Tarjeta;
public interface TarjetaService {
public Tarjeta findById(int id);
public void save(Tarjeta Tarjeta);
public void update(Tarjeta Tarjeta);
public List<Tarjeta> listaTarjeta();
public void delete(Tarjeta Tarjeta) ;
}
|
PHP | UTF-8 | 2,444 | 2.578125 | 3 | [] | no_license | <?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With');
include_once '../../../config/Database.php';
include_once '../../../models/HardwareStatus.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate status object
$state = new HardwareStatus($db);
$token = new HardwareStatus($db);
// Get raw posted data
// $data = json_decode(file_get_contents("php://input"));
// if ($data->meterNumber) {
if ($_GET['meter_number']) {
// $state->meter_number = $data->meterNumber;
// $token->meter_number = $data->meterNumber;
$state->meter_number = $_GET['meter_number'];
$token->meter_number = $_GET['meter_number'];
// Query data
$result = $state->get_hardware_state();
// Get row count
$num = $result->rowCount();
if($num > 0) {
$control = $result->fetch();
$result2 = $token->get_unused_token();
$num2 = $result2->rowCount();
if($num2 > 0) {
$control2 = $result2->fetch();
$unit = $control2->loaded === 'no' ? $control2->units : "######";
// echo $unit;
if ($unit[0] !== '#') {
$unit *= 100;
$unit = strval($unit);
$unitArr = array();
for ($i = 0; $i < 6; $i++) {
if (isset($unit[$i])) {
array_push($unitArr, $unit[$i]);
} else {
array_unshift($unitArr, 0);
}
}
// var_dump( $unitArr);
$unit = join('', $unitArr);
}
echo $control->state.'|'.$unit;
// echo "afdds";
// echo json_encode(
// array(
// "status" => "success",
// "control" => $control->state,
// "units" => $control2->loaded === 'no' ? $control2->units : "######"
// )
// );
} else {
echo json_encode(
array(
"status" => "error"
)
);
}
} else {
http_response_code(412);
}
} |
Markdown | UTF-8 | 12,042 | 2.609375 | 3 | [] | no_license |
**In order to use the Tencent Integration Platform Service(the “Service”), you shall read and comply with this Tencent Integration Platform Service Level Agreement (this “Agreement”) and the [ Tencent Cloud Service Agreement ](https://intl.cloud.tencent.com/document/product/301/9248) . This Agreement contains, among others, the terms and definitions of the Service, Service Availability and Service Availability Standard , Compensation Plan and Disclaimer of Liabilities. Please carefully read and fully understand each and every provision hereof, and the provisions restricting or disclaiming certain liabilities, or otherwise related to your material rights and interests, are in bold font or underlined or otherwise brought to your special attention.**
**Please do not purchase the Service unless and until you have fully read, and completely understood and accepted all the terms hereof. By clicking “Agree”/ “Next”, or by purchasing or using the Service, or by otherwise accepting this Agreement, whether express or implied, you are deemed to have read, and agreed to be bound by, this Agreement. This Agreement shall then have legal effect on both you and Tencent Cloud, constituting a binding legal document on both parties. For the purposes of these Terms of Service, “Tencent Cloud” refers to the applicable Tencent entity as set forth in the [Tencent Cloud Service Agreement](https://intl.cloud.tencent.com/document/product/301/9248)**.
## 1. Terms and Definitions
### 1.1 Tencent Integration Platform
Refers to the services provided by Tencent Cloud to connect applications, data, processes and services in local, private and public cloud environments. Tencent Integration Platform supports codeless and low-code integrated development, online debugging, rapid deployment, monitoring, alerting and other features. You can realize efficient integration of enterprise data, applications and processes, achieve efficient collaboration of enterprise business, supply chain and industrial chain, and support rapid innovation of enterprise business by using Tencent Integration Platform. The specific content of the Service is subject to the services purchased by you and provided by Tencent Cloud.
### 1.2 Service Month(s)
Service Month(s) refers to the calendar month(s) within the term of the Service purchased by you. For example, if you purchase the Service for a term of three months starting from March 17, there will be four (4) Service Months until June 16 (the first Service Month from March 17 to March 31, the second from April 1 to April 30, the third from May 1 to May 31, and the fourth from June 1 to June 16). The Service Availability will be calculated separately for each Service Month.
### 1.3 Service Unavailability
If all access via the console page or API fails or all published integration flows cannot be scheduled for execution in a certain minute, the Service would be deemed as unavailable (“**Service Unavailability**”) in such minute, such minute would be counted as Service Downtime Calculated in Minutes within such Service Month (as defined below), except under the circumstances as set forth in Section 4 of this Agreement. If the requests fail due to request flow restriction, identity authentication failure, service suspension for failure to pay, hack attack and other reasons in a certain minute, the Service would not be deemed as unavailable in such minute. The sum of minutes in which the Service is unavailable would be Service Downtime Calculated in Minutes within such Service Month.
### 1.4 Service Downtime Calculated in Minutes within Service Month(s)
Service Downtime refers to the time period from the start of the Service Unavailability to the time the services are back to normal.
Service Downtime = the time when Service Unavailability is fixed - the time when Service Unavailability starts. If the Service is back to normal within 1 minute, i.e., the duration of the Service Unavailability lasts for less than 1 minute, such duration would not be counted as Service Downtime Calculated in Minutes. Service Downtime Calculated in Minutes shall be calculated by minutes, and Service Downtime less than 60 seconds shall be counted as 1 minute. For example, if Service Downtime is 1 minute and 1 second, Service Downtime Calculated in Minutes would be calculated as 2 minutes. The sum of Service Downtime Calculated in Minutes in a Service Month would be Service Downtime Calculated in Minutes within such Service Month.
### 1.5 Total Number of Minutes within Service Month(s)
Total Number of Minutes within Service Month(s) = the total number of days in such Service Month(s) × 24 (hours) × 60 (minutes).
### 1.6 Monthly Service Fee
Refers to the service fees you actually consume within a Service Month, excluding the portion that has been purchased but not consumed yet.
## 2. Service Availability
### 2.1 Calculation of Service Availability
Service Availability = 1 - (Service Downtime Calculated in Minutes within a Service Month / Total Number of Minutes within such Service Month) × 100%.
For example, if the Service is unavailable from 23:00 to 23:05 on a day in April 2021, Service Downtime Calculated in Minutes within April would be 5 minutes, Service Availability in April 2021 would be 99.98% (= 1 - 5 / (30 × 24 × 60) × 100%).
### 2.2 Service Availability Standard
**The Service Availability for the Service shall be no less than 99.9%** (“**Service Availability Standard**”). If the Service fails to meet the Service Availability Standard (except under circumstances as set forth in the Disclaimer of Liabilities), you may claim compensation in accordance with Section 3 of this Agreement.
## 3. Compensation Plan
In respect of the Service purchased by you, if the Service fails to meet the Service Availability Standard, you will be entitled to compensations in accordance with the following terms upon mutual agreement of both parties:
### 3.1 Standards of Compensation
(1) Compensations will be made in the form of voucher by Tencent Cloud, and after receiving the voucher, you should use the voucher by abiding the voucher usage rules (including usage period, etc., subject to the voucher usage rules published on Tencent Cloud official website). Such voucher cannot be converted into cash, and no invoice will be issued with respect thereof. The voucher may only be used to purchase the Service by using your Tencent Cloud account, and you cannot use the voucher to purchase other services of Tencent Cloud, nor should you give the voucher to a third party for consideration or for free.
(2) If the Service fails to meet the Service Availability Standard in any Service Month, the amount of compensation shall be calculated for such Service Month independently, and the aggregate amount shall be no more than the Monthly Service Fee you pay for the Service in the Service Month in which the Service fails to meet the Service Availability Standard (the Monthly Service Fee excludes the portion deducted by vouchers, coupons, service fee reduction or exemption, etc.).
| Service Availability in a Service Month | Value of Compensational Voucher |
| ------------------------------------------- | ------------------------------------------------------------ |
| Less than 99.9% but is or higher than 99.5% | **5% of the Monthly Service Fee** |
| Less than 99.5% but is or higher than 97% | **10% of the Monthly Service Fee** |
| Less than 97% but is or higher than 95% | **20% of the Monthly Service Fee** |
| Less than 95% | **50% of the Monthly Service Fee** |
### 3.2 Time Limit for Compensation Application
(1) If the Service Availability in a Service Month fails to meet the Service Availability Standard, you may **apply for compensation only through the Tencent Cloud ticket system under your relevant account** after the fifth (5th) business day of the month immediately following such Service Month. Tencent Cloud will verify and ascertain your application upon receipt of such application. If there is any dispute over the calculation of the Service Availability for a Service Month, **both parties agree that the back-end record of Tencent Cloud shall prevail.**
(2) **You shall apply for compensation no later than the sixtieth (60th) calendar day following the end of the Service Month in which the Service fails to meet the Service Availability Standard.** If you fail to make any application within such period, or make the application after such period, or make the application by any means other than that agreed herein, it shall be deemed that you have voluntarily waived your right to apply for such compensation and any other rights you may have against Tencent Cloud, in which case Tencent Cloud has the right to reject your application for compensation and not to make any compensation to you.
## 4. Disclaimer of Liabilities
**If the Service Unavailability occurs due to any of the following reasons, the corresponding Service Downtime shall not be counted towards Service Unavailability period, and is not eligible for compensation by Tencent Cloud, and Tencent Cloud will not be held liable to you:**
4.1 Any loss or leak of data, passcode or password due to your improper maintenance or improper confidentiality measures.
4.2 Any failure due to third-party systems or user-designed unreasonable integration applications.
4.3 Any failure of you to abide by documentation or suggestions for using Tencent Integration Platform.
4.4 Any use exceeding the service capacity limit indicated for the current paid version of the Service.
4.5 Any system maintenance with prior notice by the Service, including system cutover, maintenance, upgrade and malfunction simulation test.
4.6 Any event of force majeure or accident.
4.7 Any other circumstances in which Tencent Cloud will be exempted or released from its liabilities for compensation or otherwise according to applicable laws, regulations, agreements or rules, or rules or guidelines published by Tencent Cloud separately.
## 5. Miscellaneous
**5.1 The parties hereto acknowledge and agree that, for any losses incurred by you for the use of the Service due to any breach by Tencent Cloud, the aggregate liability of Tencent Cloud shall under no circumstance exceed the total service fees you have paid for the relevant Service which fails to meet the Service Availability Standard. If you have used the Service for more than 12 months, the total aggregate liability of Tencent Cloud shall not exceed the total service fees you have paid to Tencent Cloud for the Service which fails to meet the Service Availability Standard in the 12 months immediately preceding the date that event giving rise to the liability first occurred.**
5.2 Tencent Cloud has the right to amend the terms of this Agreement as appropriate or necessary in light of changes in due course. You may review the most updated version of relevant Agreement terms on the Tencent Cloud official website. If you disagree with such revisions made by Tencent Cloud to this Agreement, you have the right to cease using the Service; by continuing to use the Service, you shall be deemed to have accepted this Agreement as amended.
5.3 As an ancillary agreement to the [Tencent Cloud Service Agreement](https://intl.cloud.tencent.com/document/product/301/9248), this Agreement is of the same legal effect as the [Tencent Cloud Service Agreement](https://intl.cloud.tencent.com/document/product/301/9248). In respect of any matter not agreed herein, you shall comply with relevant terms under the [Tencent Cloud Service Agreement](https://intl.cloud.tencent.com/document/product/301/9248). In case of any conflict or discrepancy between this Agreement and the [Tencent Cloud Service Agreement](https://intl.cloud.tencent.com/document/product/301/9248), this Agreement prevails to the extent of such conflict or discrepancy.
|
Python | UTF-8 | 3,073 | 2.640625 | 3 | [] | no_license |
import numpy as np
import pdb
import json
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC as svc
from sklearn.ensemble import RandomForestClassifier as rfc
from sklearn.ensemble import GradientBoostingClassifier as gbc
import xgboost as xgb
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
f = open('LINE_embedding.txt', 'r')
embeddings = {}
for line in f.readlines():
x = map(lambda x:float(x), line.split())
x = np.asarray(x)
embeddings[x[0]] = x[1:]
f_train = open('train.txt', 'r')
f_test = open('test0.txt', 'r')
#f_trainNew = open('train_new.txt', 'w')
#f_testNew = open('test_new.txt', 'w')
X = []
y = []
X_test = []
y_test = []
missing_train = 0
missing_test = 0
missing_x = []
missing_X = []
for line in f_train.readlines():
line1 = line
line = line.rstrip()
u, v, label = map(lambda x:int(x), line.split())
try:
x = []
x1 = embeddings[u]
x2 = embeddings[v]
x.extend(x1)
x.extend(x2)
if len(x) == 128:
X.append(x)
y.append(label)
#f_trainNew.write(line1)
except Exception:
missing_X.append(u)
missing_train += 1
for line in f_test.readlines():
line1 = line
line = line.rstrip()
u, v, label = map(lambda x:int(x), line.split())
try:
x = []
x1 = embeddings[u]
x2 = embeddings[v]
x.extend(x1)
x.extend(x2)
if len(x) == 128:
X_test.append(x)
y_test.append(label)
#f_testNew.write(line1)
except Exception:
missing_x.append(u)
missing_test += 1
lens = [len(x) for x in X]
for l in lens:
if l < 128:
print(l)
print("ALLERT!!")
X = np.asarray(X)
y = np.asarray(y)
X_test = np.asarray(X_test)
y_test = np.asarray(y_test)
clf = LogisticRegression()
clf.fit(X, y)
y_pred = clf.predict(X_test)
print("Acc(LR) is %f"%(accuracy_score(y_test, y_pred)))
#rint("Precision is %f"%(precision_score(y_test, y_pred)))
print("Recall is %f"%(recall_score(y_test, y_pred)))
print("F1 score is %f"%(f1_score(y_test, y_pred)))
clf = svc()
clf.fit(X, y)
y_pred = clf.predict(X_test)
print("Acc(SVM) is %f"%(accuracy_score(y_test, y_pred)))
#rint("Precision is %f"%(precision_score(y_test, y_pred)))
print("Recall is %f"%(recall_score(y_test, y_pred)))
print("F1 score is %f"%(f1_score(y_test, y_pred)))
clf = rfc()
clf.fit(X, y)
y_pred = clf.predict(X_test)
print("Acc(RF) is %f"%(accuracy_score(y_test, y_pred)))
#rint("Precision is %f"%(precision_score(y_test, y_pred)))
print("Recall is %f"%(recall_score(y_test, y_pred)))
print("F1 score is %f"%(f1_score(y_test, y_pred)))
#clf = gbc()
clf = xgb.XGBClassifier()
clf.fit(X, y)
y_pred = clf.predict(X_test)
print("Acc(GBC) is %f"%(accuracy_score(y_test, y_pred)))
#rint("Precision is %f"%(precision_score(y_test, y_pred)))
print("Recall is %f"%(recall_score(y_test, y_pred)))
print("F1 score is %f"%(f1_score(y_test, y_pred)))
print missing_train
print missing_test
|
Markdown | UTF-8 | 4,248 | 3.875 | 4 | [] | no_license |
# JavaScript's expressions and operators
JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator
For example, 3+4 or x*y
For example, x++ or ++x
### Assignment operators
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x
### Return value and chaining
Like most expressions, assignments like x = y have a return value. It can be retrieved by e.g. assigning the expression or logging it
### Destructuring
For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
### Comparison operators
A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality
### Arithmetic operators
An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity)
### Bitwise operators
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
### Logical operators
Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
### String operators
In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings
### Conditional (ternary) operator
The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:
condition ? val1 : val2
## Functions
### Function declarations
A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:
The name of the function.
A list of parameters to the function, enclosed in parentheses and separated by commas.
The JavaScript statements that define the function, enclosed in curly brackets, {...}
### Calling functions
Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called.
### Function scope
Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined
For more inforomation visit this link [ Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)
|
C++ | GB18030 | 19,479 | 2.796875 | 3 | [] | no_license | /*****************************************************************************************
ģ Wave.cpp
˵ ˮЧʵֺ
ˣħ
Wave VC汾ƱĻд,
ʵˮЧĴӣο˲ϴ룬رοְ
VB汾
V1.0.0
*****************************************************************************************/
/*****************************************************************************************
ԴҪ include Wave.h
Ȼ²ã
********************************************************************
1ˮ
Ҫһڽл滭ҪһˮһЩ
WaveInit(LPWAVEOBJECT lpWaveObject, HWND hWnd, HBITMAP hBmp, UINT dwSpeed, UINT dwType)
lpWaveObject --> ָһյ WAVE_OBJECT ṹ
hWnd --> Ҫ滭ˮЧĴڣȾͼƬڵĿͻ
hBmp --> ͼƬ滭ķΧСͬͼƬС
dwTime --> ˢµʱ룩ֵ1030
dwType --> =0 ʾԲˮ=1ʾԲˮЧ
ֵeax = 0ɹʼeax = 1ʧܣ
********************************************************************
2 WaveInit سɹʼиֺ
ʵָЧ溯е lpWaveObject ָ WaveInit
гʼ WAVEOBJECT ṹ
(1) ָλáʯͷˮ
WaveDropStone(LPWAVEOBJECT lpWaveObject, int dwPosX, int dwPosY, int dwStoneSize,int dwStoneWeight);
dwPosX,dwPosY --> ʯͷλ
dwStoneSize --> ʯͷĴСʼĴСֵ05
dwStoneWeight --> ʯͷ˲ɢķΧСֵ101000
(2) ԶʾЧ
WaveEffect(LPWAVEOBJECT lpWaveObject, UINT dwType,int dwParam1,int dwParam2,int dwParam3)
dwParam1,dwParam2,dwParam3 --> ЧԲͬЧͲ岻ͬ
dwEffectType --> Ч
0 --> رЧ
1 --> ꣬Param1ܼٶȣ0ܣԽԽϡ裩ֵ030
Param2ֱֵ05
Param3ֵ50250
2 --> ͧParam1ٶȣ0ԽԽ죩ֵ08
Param2Сֵ04
Param3ˮɢķΧֵ100500
3 --> ˣParam1ܶȣԽԽܣֵ50300
Param2Сֵ25
Param3ֵ510
(3) ڿͻǿƸ£ڴڵWM_PAINTϢǿƸ¿ͻˣ
WaveUpdateFrame(LPWAVEOBJECT lpWaveObject, HDC hDc, BOOL bIfForce);
********************************************************************
3ͷˮ
ʹϺ뽫ˮͷţͷĻڴԴ
WaveFree(LPWAVEOBJECT lpWaveObject)
lpWaveObject --> ָ WAVE_OBJECT ṹ
ʵϵϸ˵
1 ˮ
(1) ɢÿһIJɢܵλ
(2) ˥ÿɢʧˮֹͣȥ
2 Ϊ˱ʱеֲͼж2Wave1Wave2
lpWave1lpWave2ָĻڣWave1ΪǰݣWave2
Ϊһ֡ݣÿȾʱ2Wave1ݼ
ֱͼ浽Wave2УȻWave1Wave2ʱWave1
µݡ
ķΪijܵϴƽֵ * ˥ϵȡ
ܵƽֵչ˥ϵ˥
ⲿִWaveSpread ʵ֡
3 lpDIBitsSource бԭʼλͼݣÿȾʱԭʼλ
ͼݸWave1бֲݲµλͼӾϿij
ԽˮԽԽԶij
㷨Ϊڵ㣨x,yWave1ҳõ㣬ڵIJܲ
DxDyݣλͼأx,yԭʼλͼأx+Dx,y+Dy
㷨СӰƫƴС
ⲿִ WaveRender ӳʵ֡
4 ʯͷ㷨ܺ⣬Wave1еijֵΪ0ֵֵԽ
ʾµʯͷԽʯͷȽϴõܵĵȫΪ0ֵ
ϼļresource.txt
еĻһά飬עΪ˷öά顣Ȼ
öά⡣
*****************************************************************************************/
#include "Wave.h"
#include "targetver.h"
/*****************************************************************************************
ӳ
룺Ҫֵ
ݣ
1. ѧʽ Rnd=(Rnd*I+J) mod K ѭش K ڲظ
αK,I,JΪ
2. 2^(2n-1)-1 ضΪ2η1
*****************************************************************************************/
DWORD WaveRandom16 (LPWAVEOBJECT lpWaveObject)
{
DWORD dwRnd;
dwRnd = ((lpWaveObject->dwRandom & 0xFFFF) * 0x7FF + 0x7F) % 0x7FFF;
lpWaveObject->dwRandom = dwRnd;
return (dwRnd & 0xFF);
}
DWORD WaveRandom (LPWAVEOBJECT lpWaveObject, DWORD dwMax)
{
DWORD lRnd1, lRnd2, lRnd;
lRnd1 = WaveRandom16 (lpWaveObject);
lRnd2 = WaveRandom16 (lpWaveObject);
if (dwMax == 0)
lRnd = 0;
else
lRnd = (((lRnd2<<16)+lRnd1) % dwMax);
return lRnd;
}
/*****************************************************************************************
ɢ
㷨
Բɢ
Wave2(x,y) = ((Wave1(x+1,y)+Wave1(x-1,y)+Wave1(x+2,y)+Wave1(x-2,y))*3+Wave1(x+3,y)*2+Wave1(x-3,y)*2+ Wave1(x,y+1)*8+Wave1(x,y-1)*8)\16-Wave2(x,y)
Բɢ
Wave2(x,y) = (Wave1(x+1,y)+Wave1(x-1,y)+Wave1(x,y+1)+Wave1(x,y-1))\2-Wave2(x,y)
Wave2(x,y) = Wave2(x,y) - Wave2(x,y) >> 5
Wave1,Wave2
*****************************************************************************************/
void WaveSpread (LPWAVEOBJECT lpWaveObject)
{
PINT lpWave1, lpWave2;
int dwBmpWidth, dwBmpHeight;
int i;
if ((lpWaveObject->dwFlag & F_WO_ACTIVE) == 0)
return;
lpWave1 = lpWaveObject->lpWave1;
lpWave2 = lpWaveObject->lpWave2;
dwBmpWidth = lpWaveObject->dwBmpWidth;
dwBmpHeight = lpWaveObject->dwBmpHeight;
for (i = dwBmpWidth; i < (dwBmpHeight-1)*dwBmpWidth; i++) {
if (lpWaveObject->dwFlag & F_WO_ELLIPSE) {//Բɢ
lpWave2[i] = ((lpWave1[i+1] + lpWave1[i-1] + lpWave1[i+2] + lpWave1[i-2])*3 + (lpWave1[i+3] + lpWave1[i-3])*2 + (lpWave1[i+dwBmpWidth] + lpWave1[i-dwBmpWidth])*8)/16 - lpWave2[i];
} else {//Բɢ
lpWave2[i] = (lpWave1[i+1] + lpWave1[i-1] + lpWave1[i+dwBmpWidth] + lpWave1[i-dwBmpWidth])/2 - lpWave2[i];
}
if (lpWave2[i] == 0) lpWave2[i] = 0;
lpWave2[i] -= (lpWave2[i] >> 5);
}
lpWaveObject->lpWave1 = lpWave2;
lpWaveObject->lpWave2 = lpWave1;
}
/*****************************************************************************************
' Ⱦµ֡Ⱦ lpDIBitsRender
㷨
posx = Wave1(x-1,y)-Wave1(x+1,y)+x
posy = Wave1(x,y-1)-Wave1(x,y+1)+y
SourceBmp(x,y) = DestBmp(posx,posy)
*****************************************************************************************/
void WaveRender (LPWAVEOBJECT lpWaveObject)
{
int dwPosX, dwPosY, dwPtrSource, dwPtrDest;
UINT dwFlag;
PINT lpWave1;
UINT LineIdx = lpWaveObject->dwBmpWidth;
int dwBmpWidth = lpWaveObject->dwBmpWidth;
PBYTE DIBitsSource = NULL;
PBYTE DIBitsRender = NULL;
int i, j, k;
dwFlag = 0;
if ((lpWaveObject->dwFlag & F_WO_ACTIVE) == 0)
return;
lpWaveObject->dwFlag |= F_WO_NEED_UPDATE;
lpWave1 = lpWaveObject->lpWave1;
DIBitsSource = lpWaveObject->lpDIBitsSource;
DIBitsRender = lpWaveObject->lpDIBitsRender;
for (i = 1; i < lpWaveObject->dwBmpHeight-1; i++) {
for (j = 0; j < lpWaveObject->dwBmpWidth; j++) {
//ƫ
//PosY=i+1-1
//PosX=j+1-1
dwPosY = i + lpWave1[LineIdx-dwBmpWidth] - lpWave1[LineIdx+dwBmpWidth];
dwPosX = j + lpWave1[LineIdx-1] - lpWave1[LineIdx+1];
//жǷڴڷΧ
if (dwPosX < 0 || dwPosY < 0) goto Continue;
if (dwPosX >= lpWaveObject->dwBmpWidth || dwPosY >= lpWaveObject->dwBmpHeight) goto Continue;
//ƫغԭʼصڴַƫ
dwPtrSource = dwPosY*lpWaveObject->dwDIByteWidth + dwPosX*3;
dwPtrDest = i*lpWaveObject->dwDIByteWidth + j*3;
//Ⱦ [ptrDest] = ԭʼ [ptrSource]
if (dwPtrSource != dwPtrDest) {
dwFlag |= 1; //ԴغĿزͬʾڻ״̬
for (k = 0; k < 3; k++) {
DIBitsRender[dwPtrDest+k] = DIBitsSource[dwPtrSource+k];
//DIBitsRender[dwPtrDest+k] = (DIBitsSource[dwPtrSource+k]*4 + (DIBitsSource[dwPtrSource+k-1] +
// DIBitsSource[dwPtrSource+k+1] + DIBitsSource[dwPtrSource+k-lpWaveObject->dwDIByteWidth] +
// DIBitsSource[dwPtrSource+k+lpWaveObject->dwDIByteWidth])*3)/16;
}
} else {
for (k = 0; k < 3; k++) {
DIBitsRender[dwPtrDest+k] = DIBitsSource[dwPtrSource+k];
}
}
Continue:
LineIdx++;
}
}
SetDIBits (lpWaveObject->hDcRender, lpWaveObject->hBmpRender, 0, lpWaveObject->dwBmpHeight, lpWaveObject->lpDIBitsRender, &lpWaveObject->stBmpInfo, DIB_RGB_COLORS);
if (dwFlag = 0)
lpWaveObject->dwFlag &= ~F_WO_ACTIVE;
}
//һʯͷ
void __stdcall WaveDropStone (LPWAVEOBJECT lpWaveObject, int dwX, int dwY, int dwStoneSize, int dwStoneWeight)
{
int dwSize, dwX1, dwY1, dwX2, dwY2, dwY2_t;
PINT lpWave1;
//㷶Χ
dwSize = dwStoneSize / 2;
dwX1 = dwX + dwSize;
dwX2 = dwX - dwSize;
if (lpWaveObject->dwFlag & F_WO_ELLIPSE) dwSize /= 2;
dwY1 = dwY + dwSize;
dwY2 = dwY - dwSize;
dwSize = dwStoneSize;
if (dwSize == 0) dwSize = 1;
//жϷΧĺϷ
if (dwX1+1 >= lpWaveObject->dwBmpWidth || dwX2 < 1 || dwY1+1 >= lpWaveObject->dwBmpHeight || dwY2 < 1) return;
//ΧڵĵΪ dwStoneWeight
while (dwX2 <= dwX1) {
dwY2_t = dwY2;
while (dwY2 < dwY1) {
if (((dwX2-dwX)*(dwX2-dwX) + (dwY2-dwY)*(dwY2-dwY))
<= dwSize*dwSize) {
lpWave1 = lpWaveObject->lpWave1 + (dwY2*lpWaveObject->dwBmpWidth + dwX2);
*lpWave1 = dwStoneWeight;
}
dwY2++;
}
dwX2++; dwY2 = dwY2_t;
}
lpWaveObject->dwFlag |= F_WO_ACTIVE;
}
void __stdcall WaveUpdateFrame (LPWAVEOBJECT lpWaveObject, HDC hDc, BOOL bIfForce)
{
if (bIfForce || (lpWaveObject->dwFlag & F_WO_NEED_UPDATE)) {
BitBlt (hDc, 0, 0, lpWaveObject->dwBmpWidth, lpWaveObject->dwBmpHeight, lpWaveObject->hDcRender, 0, 0, SRCCOPY);
lpWaveObject->dwFlag &= ~F_WO_NEED_UPDATE;
}
}
//ɢݡȾλͼ´ڡЧĶʱ
void CALLBACK WaveTimerProc (HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
HDC hDc;
int dwX, dwY, dwSize, dwWeight;
int i;
LPWAVEOBJECT lpWaveObject = (LPWAVEOBJECT) idEvent;
WaveSpread (lpWaveObject);
WaveRender (lpWaveObject);
if (lpWaveObject->dwFlag & F_WO_NEED_UPDATE) {
hDc = GetDC (lpWaveObject->hWnd);
WaveUpdateFrame (lpWaveObject, hDc, FALSE);
ReleaseDC (lpWaveObject->hWnd, hDc);
}
//Ч
if ((lpWaveObject->dwFlag & F_WO_EFFECT) == 0)
return;
switch (lpWaveObject->dwEffectType) {
case 1: //Type = 1 㣬Param1ٶȣ0죬ԽԽParam2СParam3
if (!lpWaveObject->dwEffectParam1 || !WaveRandom (lpWaveObject, lpWaveObject->dwEffectParam1)) {
dwX = WaveRandom(lpWaveObject, lpWaveObject->dwBmpWidth-2) + 1;
dwY = WaveRandom (lpWaveObject, lpWaveObject->dwBmpHeight-2) + 1;
dwSize = WaveRandom (lpWaveObject, lpWaveObject->dwEffectParam2) + 1;
dwWeight = WaveRandom (lpWaveObject, lpWaveObject->dwEffectParam3) + 50;
WaveDropStone (lpWaveObject, dwX, dwY, dwSize, dwWeight);
}
break;
case 2: //Type = 2 дParam1ٶȣ0죬ԽԽ죩Param2СParam3
lpWaveObject->dwEff2Flip++;
if ((lpWaveObject->dwEff2Flip & 1) != 0) return;
dwX = lpWaveObject->dwEff2X + lpWaveObject->dwEff2XAdd;
dwY = lpWaveObject->dwEff2Y + lpWaveObject->dwEff2YAdd;
if (dwX < 1) {
dwX = -(dwX-1);
lpWaveObject->dwEff2XAdd = -lpWaveObject->dwEff2XAdd;
}
if (dwY < 1) {
dwY = -(dwY-1);
lpWaveObject->dwEff2YAdd = -lpWaveObject->dwEff2YAdd;
}
if (dwX > lpWaveObject->dwBmpWidth-1) {
dwX = (lpWaveObject->dwBmpWidth-1)*2 - dwX;
lpWaveObject->dwEff2XAdd = -lpWaveObject->dwEff2XAdd;
}
if (dwY > lpWaveObject->dwBmpHeight-1) {
dwY = (lpWaveObject->dwBmpHeight-1)*2 - dwY;
lpWaveObject->dwEff2YAdd = -lpWaveObject->dwEff2YAdd;
}
lpWaveObject->dwEff2X = dwX;
lpWaveObject->dwEff2Y = dwY;
WaveDropStone (lpWaveObject, dwX, dwY, lpWaveObject->dwEffectParam2, lpWaveObject->dwEffectParam3);
break;
case 3: //Type = 3 ˣParam1ܶȣParam2СParam3
for (i = 0; i <= lpWaveObject->dwEffectParam1; i++) {
dwX = WaveRandom (lpWaveObject, lpWaveObject->dwBmpWidth-2) + 1;
dwY = WaveRandom (lpWaveObject, lpWaveObject->dwBmpHeight-2) + 1;
dwSize = WaveRandom (lpWaveObject, lpWaveObject->dwEffectParam2) + 1;
dwWeight = WaveRandom (lpWaveObject, lpWaveObject->dwEffectParam3);
WaveDropStone (lpWaveObject, dwX, dwY, dwSize, dwWeight);
}
break;
}
}
//ͷŶ
void __stdcall WaveFree (LPWAVEOBJECT lpWaveObject)
{
if (lpWaveObject->hDcRender)
DeleteDC (lpWaveObject->hDcRender);
if (lpWaveObject->hBmpRender)
DeleteObject (lpWaveObject->hBmpRender);
if (lpWaveObject->lpDIBitsSource)
GlobalFree (lpWaveObject->lpDIBitsSource);
if (lpWaveObject->lpDIBitsRender)
GlobalFree (lpWaveObject->lpDIBitsRender);
if (lpWaveObject->lpWave1)
GlobalFree (lpWaveObject->lpWave1);
if (lpWaveObject->lpWave2)
GlobalFree (lpWaveObject->lpWave2);
KillTimer (lpWaveObject->hWnd, (UINT_PTR) lpWaveObject);
RtlZeroMemory (lpWaveObject, sizeof WAVEOBJECT);
}
UINT __stdcall WaveInit (LPWAVEOBJECT lpWaveObject, HWND hWnd, HBITMAP hBmp, UINT dwSpeed, UINT dwType)
{
BITMAP stBmp;
UINT dwReturn = 0;
HDC hDc = NULL;
HDC hDcRender = NULL;
RtlZeroMemory (lpWaveObject, sizeof (WAVEOBJECT));
//dwTypeˮͼεĿ
//dwType0ʱΪԲˮdwType1ʱΪԲˮ
if (dwType)
lpWaveObject->dwFlag = lpWaveObject->dwFlag | F_WO_ELLIPSE;
//ȡλͼߴ
lpWaveObject->hWnd = hWnd;
//GetTickCountشӲϵͳelapsedĺ
//ķֵDWORD
lpWaveObject->dwRandom = GetTickCount ();
if (!GetObject (hBmp, sizeof (BITMAP), &stBmp)) {
dwReturn = 1;
goto result;
}
lpWaveObject->dwBmpHeight = stBmp.bmHeight;
if (stBmp.bmHeight <= 3)
dwReturn = 1;
lpWaveObject->dwBmpWidth = stBmp.bmWidth;
if (stBmp.bmWidth <= 3)
dwReturn = 1;
lpWaveObject->dwWaveByteWidth = stBmp.bmWidth * 4;
lpWaveObject->dwDIByteWidth = (stBmp.bmWidth * 3 + 3) & (~3);
//Ⱦλͼ
hDc = GetDC (hWnd);
//һָ豸ݵڴ豸Ļ
lpWaveObject->hDcRender = CreateCompatibleDC (hDc);
//HBITMAP CreateCompatibleBitmap (HDC hDc, int cx, int cy);
//ָߡɫCreateCompatibleDCõҪ
//úָ豸ص豸ݵλͼ
lpWaveObject->hBmpRender = CreateCompatibleBitmap (hDc,
lpWaveObject->dwBmpWidth, lpWaveObject->dwBmpHeight);
//úѡһָ豸ĻУ¶滻ǰͬ͵Ķ
SelectObject (lpWaveObject->hDcRender, lpWaveObject->hBmpRender);
//䲨ܻ
lpWaveObject->lpWave1 = (PINT) GlobalAlloc (GPTR,
lpWaveObject->dwWaveByteWidth * lpWaveObject->dwBmpHeight);
lpWaveObject ->lpWave2 = (PINT) GlobalAlloc (GPTR,
lpWaveObject->dwWaveByteWidth * lpWaveObject->dwBmpHeight);
//ػ
lpWaveObject->lpDIBitsSource = (PBYTE) GlobalAlloc (GPTR,
lpWaveObject->dwDIByteWidth * lpWaveObject->dwBmpHeight);
lpWaveObject->lpDIBitsRender = (PBYTE) GlobalAlloc (GPTR,
lpWaveObject->dwDIByteWidth * lpWaveObject->dwBmpHeight);
//ȡԭʼ
lpWaveObject->stBmpInfo.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
lpWaveObject->stBmpInfo.bmiHeader.biWidth = lpWaveObject->dwBmpWidth;
lpWaveObject->stBmpInfo.bmiHeader.biHeight = - lpWaveObject->dwBmpHeight;
lpWaveObject->stBmpInfo.bmiHeader.biPlanes = 1;
lpWaveObject->stBmpInfo.bmiHeader.biBitCount = 24;
lpWaveObject->stBmpInfo.bmiHeader.biCompression = BI_RGB;
lpWaveObject->stBmpInfo.bmiHeader.biSizeImage = 0;
hDcRender = CreateCompatibleDC (hDc);
SelectObject (hDcRender, hBmp);
ReleaseDC (hWnd, hDc);
//GetDIBitsȡָλͼϢָʽƵһ
GetDIBits (hDcRender, hBmp, 0, lpWaveObject->dwBmpHeight,
lpWaveObject->lpDIBitsSource, &lpWaveObject->stBmpInfo, DIB_RGB_COLORS);
GetDIBits (hDcRender, hBmp, 0, lpWaveObject->dwBmpHeight,
lpWaveObject->lpDIBitsRender, &lpWaveObject->stBmpInfo, DIB_RGB_COLORS);
DeleteDC (hDcRender);
if (!lpWaveObject->lpWave1 || !lpWaveObject->lpWave2 || !lpWaveObject->lpDIBitsSource || !lpWaveObject->lpDIBitsRender || !lpWaveObject->hDcRender) {
MessageBox (hWnd, TEXT ("ڴʧ"), TEXT (""), MB_OK);
WaveFree (lpWaveObject);
dwReturn = 1;
}
SetTimer (hWnd, (UINT_PTR) lpWaveObject, dwSpeed, WaveTimerProc);
lpWaveObject->dwFlag = lpWaveObject->dwFlag | F_WO_ACTIVE | F_WO_NEED_UPDATE;
WaveRender (lpWaveObject);
hDc = GetDC (hWnd);
WaveUpdateFrame (lpWaveObject, hDc, TRUE);
ReleaseDC (hWnd, hDc);
result:
return dwReturn;
}
//Ч
void __stdcall WaveEffect (LPWAVEOBJECT lpWaveObject, UINT dwEffectType, int dwParam1, int dwParam2, int dwParam3)
{
switch (dwEffectType) {
case 0:
lpWaveObject->dwFlag &= ~F_WO_EFFECT;
lpWaveObject->dwEffectType = dwEffectType;
break;
case 2:
lpWaveObject->dwEff2XAdd = dwParam1;
lpWaveObject->dwEff2YAdd = dwParam1;
lpWaveObject->dwEff2X = WaveRandom (lpWaveObject, lpWaveObject->dwBmpWidth-2) + 1;
lpWaveObject->dwEff2Y = WaveRandom (lpWaveObject, lpWaveObject->dwBmpHeight-2) + 1;
lpWaveObject->dwEffectType = dwEffectType;
lpWaveObject->dwEffectParam1 = dwParam1;
lpWaveObject->dwEffectParam2 = dwParam2;
lpWaveObject->dwEffectParam3 = dwParam3;
lpWaveObject->dwFlag |= F_WO_EFFECT;
break;
default:
lpWaveObject->dwEffectType = dwEffectType;
lpWaveObject->dwEffectParam1 = dwParam1;
lpWaveObject->dwEffectParam2 = dwParam2;
lpWaveObject->dwEffectParam3 = dwParam3;
lpWaveObject->dwFlag |= F_WO_EFFECT;
}
} |
Java | UTF-8 | 791 | 2.765625 | 3 | [] | no_license | package MyPlayer;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* Created by kiel on 29/05/17.
*/
public class Artist {
protected int id_Artist ;
protected String name ;
protected static ArrayList<String> listArtist = new ArrayList<String>();
public Artist(String name) {
this.name = name;
}
public int getId_Artist() {
return id_Artist;
}
public void setId_Artist(int id_Artist) {
this.id_Artist = id_Artist;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Artist searchArtist(String name) {
if (listArtist.contains(name) {
return listArtist.indexOf()
}
}
}
|
Java | UTF-8 | 753 | 2.15625 | 2 | [] | no_license | package com.example.rsocketclient.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.rsocket.RSocketRequester;
import org.springframework.messaging.rsocket.RSocketStrategies;
import reactor.core.publisher.Mono;
import java.net.URI;
@Configuration
public class RSocketConfiguration {
@Bean
public Mono<RSocketRequester> rSocketRequester(
RSocketStrategies rSocketStrategies
) {
return RSocketRequester.builder()
.rsocketStrategies(rSocketStrategies)
.connectWebSocket(getURI());
}
private URI getURI() {
return URI.create("ws://localhost:8080/rsocket");
}
}
|
TypeScript | UTF-8 | 868 | 2.734375 | 3 | [] | no_license | import { User } from '../../entities/user/UserModel';
import { HttpService } from 'src/utils/services/HttpService';
const URLS = {
SIGNUP: '/auth/signup',
SIGNIN: '/auth/signin',
SIGNOUT: '/auth/signout'
};
export class UserService {
public constructor(private readonly httpService: HttpService) {}
public signup(
login: User['username'],
email: User['email'],
password: string,
repeatPassword: string
) {
return this.httpService.post(URLS.SIGNUP, {
login,
email,
password,
repeatPassword
});
}
public async logIn(
login: User['username'] | User['email'],
password: string
): Promise<User> {
return this.httpService.post(URLS.SIGNIN, { login, password });
}
public async logOut(userId: User['id']): Promise<void> {
return this.httpService.post(URLS.SIGNOUT, { userId });
}
}
|
C++ | UTF-8 | 2,510 | 2.625 | 3 | [] | no_license | /*
*
* Project Astraeus
* By: Darren Kent
*
*/
#include "Astroid.h"
Astroid::Astroid( Node* node ) {
mActive = false;
mAstraeusCollisionPlaying = false;
mOre = false;
mPlayerCollisionPlaying = false;
mDYaw = 0.0f;
mDPitch = 0.0f;
mDRoll = 0.0f;
mDX = 0.0f;
mDY = 0.0f;
mDZ = 0.0f;
mYaw = node->GetYaw();
mPitch = node->GetPitch();
mRoll = node->GetRoll();
mXPos = node->GetXPos();
mYPos = node->GetYPos();
mZPos = node->GetZPos();
mHealth = 100;
mNode = node;
}
bool Astroid::AstraeusCollisionPlaying() {
return mAstraeusCollisionPlaying;
}
void Astroid::AstroidLogic( float deltaTime ) {
mYaw += mDYaw * deltaTime;
mPitch += mDPitch * deltaTime;
mRoll += mDRoll * deltaTime;
mXPos += mDX * deltaTime;
mYPos += mDY * deltaTime;
mZPos += mDZ * deltaTime;
mNode->SetPosition( mXPos, mYPos, mZPos );
mNode->SetRotation( mYaw, mPitch, mRoll );
}
void Astroid::ChangeHealth( int amount ) {
mHealth += amount;
if ( mHealth < 0 )
mHealth = 0;
}
bool Astroid::CheckCollision( float x, float y, float z, float radius ) {
float tDistance = std::sqrt( std::pow( x - mXPos, 2 ) +
std::pow( y - mYPos, 2 ) +
std::pow( z - mZPos, 2 ) );
if ( tDistance < radius + mNode->GetScale() * 50.0f )
return true;
return false;
}
bool Astroid::PlayerCollisionPlaying() {
return mPlayerCollisionPlaying;
}
bool Astroid::GetOre() {
return mOre;
}
float Astroid::GetDX() {
return mDX;
}
float Astroid::GetDY() {
return mDY;
}
float Astroid::GetDZ() {
return mDZ;
}
float Astroid::GetRadius() {
return mNode->GetScale();
}
float Astroid::GetXPos() {
return mXPos;
}
float Astroid::GetYPos() {
return mYPos;
}
float Astroid::GetZPos() {
return mZPos;
}
int Astroid::GetHealth() {
return mHealth;
}
std::string Astroid::GetId() {
if ( mNode )
return mNode->GetId();
return "";
}
void Astroid::SetActive( bool active ) {
mActive = active;
}
void Astroid::SetAstraeusCollisionPlaying( bool playing ) {
mAstraeusCollisionPlaying = playing;
}
void Astroid::SetHealth( int amount ) {
mHealth = amount;
}
void Astroid::SetOre( bool ore ) {
mOre = ore;
}
void Astroid::SetPlayerCollisionPlaying( bool playing ) {
mPlayerCollisionPlaying = playing;
}
void Astroid::SetRotationVeloctiy( float yaw, float pitch, float roll ) {
mDYaw = yaw;
mDPitch = pitch;
mDRoll = roll;
}
void Astroid::SetVelocity( float dx, float dy, float dz ) {
mDX = dx;
mDY = dy;
mDZ = dz;
} |
Markdown | UTF-8 | 8,097 | 2.609375 | 3 | [
"MIT"
] | permissive | <h1 align="center">
<img alt="LaunchBase" src="https://storage.googleapis.com/golden-wind/bootcamp-launchbase/logo.png" width="400px" />
</h1>
<p align="center">
<a href="https://rocketseat.com.br">
<img alt="Made by Rocketseat" src="https://img.shields.io/badge/made%20by-Rocketseat-%23F8952D">
</a>
<a href="LICENSE" >
<img alt="License" src="https://img.shields.io/badge/license-MIT-%23F8952D">
</a>
</p>
<p align="center">
<img alt="GitHub language count" src="https://img.shields.io/github/languages/count/Dhi-Carvalho/LaunchBase?style=plastic">
<img alt="GitHub top language" src="https://img.shields.io/github/languages/top/Dhi-Carvalho/LaunchBase?style=plastic">
<img alt="GitHub code size in bytes" src="https://img.shields.io/github/languages/code-size/Dhi-Carvalho/LaunchBase?style=plastic">
<img alt="Repository size" src="https://img.shields.io/github/repo-size/Dhi-Carvalho/LaunchBase?style=plastic">
<img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/Dhi-Carvalho/LaunchBase?style=plastic">
</p>
<h3 align="center">
🚧 LaunchBase 👨🎓 Andamento 🚀 🚧
</h3>
<p align="center">
<a href="#-sobre-o-BootCamp">Sobre</a> •
<a href="#-Cronagrama-de-Estudos ">Cronograma</a> •
<a href="#-tecnologias">Tecnologias</a> •
<a href="#-autor">Autor</a> •
<a href="#user-content--licença">Licença</a>
</p>
---
---
## 💻 Sobre o BootCamp:
O **LaunchBase** é um programa de estudos sobre programção WEB oferecido pela [Rocketseat](https:rocketseat.com.br), afim de abrir o mercado para pessoas que tenham interesse em adquirir conhecimentos sobre as tecnologias que estão sendo utilizadas, e que queiram ingressar no mercado de programação para WEB.
O BootCamp tem como foco as tecnologias **HTML**, **CSS** e a linguagem de programação **JavaScript**, além de outras tecnologias utilizadas atualmente no mercado.
---
---
## ⚙️ Cronograma de Estudos:
O BootCamp está dividido em fases, para que o aluno tenha um melhor aprendizado.
---
**👨🚀 Fase 01**:
- **📑Preparação dos Estudos:**
- 🛠️ [Material de Apoio](https://www.notion.so/Material-de-Apoio-f6c1ffcce1044a66a7da6e73459a6363)
- Instruções Básicas
- Fortalecendo sua mentalidade
- Cronograma de Estudos (conceitos)
- Fixação de Conteúdo
- Resultado para a Carreira
- Projetos Pessoais
- Cronograma na Prática
- **📑Ambiente de Desenvolvimento:**
- Ambiente macOS
- Ambiente Windows
- 🛠️ [Ambiente Linux](https://xesque.rocketseat.dev/platform/1573473115506.pdf)
---
**👨🚀 Fase 02**:
- **📑Introdução à programção WEB:**
- Iniciando com a programação web
- Iniciando no JavaScript
- Comentários, Strings e Numbers
- Fazendo cálculos com JavaScript
- Condicionais
- Operadores relacionais e comparativos
- Operadores lógicos e aritméticos
---
**🛠️ Desafio 1-1: Primeiros Passos com JS**
- [Cálculo do IMC](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.1-Primeiros_passos_com_JS/calculo_de_IMC.js)
- [Cálculo de aposentadoria](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.1-Primeiros_passos_com_JS/calculo_de_aposentadoria.js)
---
- Objetos
- Vetores
---
**🛠️ Desafio 1-2: Lidando com objetos e vetores**
- [Construção e impressão de objetos](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.2-Lidando_com_objetos_e_vetores/construcao_impressao_objetos.js)
- [Vetores e objetos](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.2-Lidando_com_objetos_e_vetores/vetores_objetos.js)
---
- Funções e métodos
- Estrutura de repetição
- Escopos
---
**🛠️ Desafio 1-3: Funções e estruturas de repetição**
- [Usuários e tecnologias](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.3-Funcoes_e_estruturas_de_repeticao/usuarios_e_tecnologias.js)
- [Busca por tecnologia](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.3-Funcoes_e_estruturas_de_repeticao/busca_por_tecnologia.js)
- [Soma de despesas e receitas](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.3-Funcoes_e_estruturas_de_repeticao/soma_de_despesas_e_receitas.js)
---
- Boleanos
- Organização, padronização e escrita
---
**🛠️ Desafio 1-4: Funções e estruturas de repetição**
- [Intro](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.4-Aplicacao_Operacoes_bancarias/intro.js)
- [Adicionar transações](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.4-Aplicacao_Operacoes_bancarias/adicionar_transacoes.js)
- [Relatórios](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_a_programacao_WEB/Desafio1.4-Aplicacao_Operacoes_bancarias/relatorios.js)
---
- **📑Introdução no Front-end:**
- 🏷️ Primeiro projeto com HTML e CSS
- O que é Back end e Front end
- Iniciando no HTML
- Desenvolvendo com Live Server
- Iniciando com CSS
- 🧗 [Projeto: Parte 01](https://github.com/Dhi-Carvalho/LaunchBase/blob/main/Introducao_no_Front-end/Primeiro_projeto_com_HTML_e_CSS/index.html)
- 🏷️ Menu do site
- Criando estrutura do menu com HTML
- Espaçamento com CSS
- Resetando estilos do navegador
- Conhecendo a cascata do CSS
- Estilizando fontes e links do menu
- 🧗 [Projeto: Parte 02](https://github.com/Dhi-Carvalho/LaunchBase/tree/main/Introducao_no_Front-end/Menu_do_site/index.html)
- **🛠️ [Desafio 2-1: Primeiro HTML](https://github.com/Dhi-Carvalho/LaunchBase/tree/main/Introducao_no_Front-end/Desafio2.1-Primeiro_HTML)**
- 🏷️ Página sobre
- Adicionando imagens no HTML
- Separando e importando estilos
- Trabalhando com texto no HTML
- Estilizando imagem do avatar
- Estilizando textos e fontes com CSS
- Variáveis no CSS
- Links para redes socias
- 🧗 [Projeto: Parte 03](https://github.com/Dhi-Carvalho/LaunchBase/tree/main/Introducao_no_Front-end/Pagina_sobre)
- **🛠️ [Desafio 2-2: Página de descrição](https://github.com/Dhi-Carvalho/LaunchBase/tree/main/Introducao_no_Front-end/Desafio2.2-Pagina_de_descricao)**
---
---
## 🛠 Tecnologias Utilizadas:
As seguintes ferramentas foram utilizadas durante o BootCamp:
---
**⚙️ Ambiente de Desenvolvimento:**
- **[Visual Studio Code](https://code.visualstudio.com/)**
---
**💻 Linguagem de Programação:**
- **JavaScript**
---
**💻 Linguagens:**
- **HTML**
- **CSS**
---
**💻 Extensões:**
- **[Liveserver](https://www.npmjs.com/package/live-server)**
---
---
## 👨🎓 Autor
<h1 align="center">
<img style="border-radius: 50%;" src="https://images2.imgbox.com/7c/82/ADR3x8b2_o.jpg" width="250">
</h1>
<p align="center">
<img src="https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2FDhiCarvalho85" alt="Twitter Dhi Carvalho"/>
<img src="https://img.shields.io/badge/-Gmail-c14438?style=flat-square&logo=Gmail&logoColor=white&link=mailto:dhi.carvalho85@gmail.com" alt="Email Dhi Carvalho"/>
<img src="https://img.shields.io/badge/-Github-000?style=flat-square&logo=Github&logoColor=white&link=https://github.com/Dhi-Carvalho" alt="Github Dhi Carvalho"/>
<img src="https://img.shields.io/badge/-LinkedIn-blue?style=flat-square&logo=Linkedin&logoColor=white&link=https://www.linkedin.com/in/dhi-carvalho/" alt="Linkedin Dhi Carvalho"/>
<img src="https://komarev.com/ghpvc/?username=Dhi-Carvalho" alt="Dhi Carvalho"/>
</p>
---
---
## 📝 Licença
Este projeto esta sobe a licença [MIT](./License).
Aluno responsável: **Dhi Carvalho** 👋🏽 [Entre em contato!](https://www.linkedin.com/in/dhi-carvalho/)
---
|
Java | UTF-8 | 1,075 | 1.570313 | 2 | [] | no_license | /**
* <copyright>
* </copyright>
*
* $Id: VMwareVirtualEthernetNICDefImpl.java,v 1.2 2008/04/17 15:47:25 barnold Exp $
*/
package com.ibm.ccl.soa.deploy.virtualization.impl;
import org.eclipse.emf.ecore.EClass;
import com.ibm.ccl.soa.deploy.virtualization.VMwareVirtualEthernetNICDef;
import com.ibm.ccl.soa.deploy.virtualization.VirtualizationPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>VMware Virtual Ethernet NIC Def</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class VMwareVirtualEthernetNICDefImpl extends VirtualEthernetNICDefImpl implements VMwareVirtualEthernetNICDef {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected VMwareVirtualEthernetNICDefImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return VirtualizationPackage.Literals.VMWARE_VIRTUAL_ETHERNET_NIC_DEF;
}
} //VMwareVirtualEthernetNICDefImpl
|
TypeScript | UTF-8 | 466 | 2.90625 | 3 | [
"MIT"
] | permissive | // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
export default class MockCollection {
constructor(collection = []) {
this.collection = collection;
this.add = jest.fn(this.add.bind(this));
this.remove = jest.fn(this.remove.bind(this));
}
add(item) {
this.collection.push(item);
}
remove(item) {
this.collection = this.collection.filter((i) => i !== item);
}
raw() {
return this.collection;
}
}
|
JavaScript | UTF-8 | 1,249 | 3.34375 | 3 | [] | no_license |
// const store = {
// name: 'hadi',
// properties: {
// hobby: 'programming',
// age: 20,
// },
// friends: ['ali'],
// girlFriends: ['Anna', 'Tania', 'Sara', 'Sanaz', 'Elmira', 'Negin', 'Mahsa']
// };
import { createStore, combineReducers } from 'redux';
const reducerOne = function (initialState = ['hadi'], action){
switch(action.type){
case 'NEW_GIRL_FRIEND':
return [...initialState, action.data];
default:
return initialState;
}
}
const reducerTwo = function (initialState = ['hadi'], action) {
switch (action.type) {
case 'NEW_GIRL_FRIEND':
return [...initialState, action.data];
default:
return initialState;
}
}
const reducers = combineReducers({
reducerOne,
reducerTwo
});
const store = createStore(reducers);
function action (girl) {
return {
type: 'NEW_GIRL_FRIEND', //required
girl //optional
};
}
console.log(store.getState());
/**
* {
* reducerOne: ['hadi']
* reducerTwo: ['hadi']
* }
*/
store.dispatch(action('Karine'));
console.log(store.getState());
/**
* {
* reducerOne: ['hadi', 'Karine']
* reducerTwo: ['hadi', 'Karine']
* }
*/
|
JavaScript | UTF-8 | 689 | 2.578125 | 3 | [] | no_license | /**
* Created by eden_liu on 2017/6/28.
*/
const express = require('express');
const path = require('path');
const app = express();
const filePath = path.join(__dirname, 'celine.jpg');
app.use((req, res, next) => {
res.sendFile(filePath, (err) => {
if (err) {
next(new Error('Error sending file!'));
}
});
});
// 記錄所有錯誤的中間件
app.use((err, req, res, next) => {
console.error(err);
next(err);
});
// 相應錯誤
app.use((err, req, res, next) => { // 確保你指定了四個參數
res.status(500);
res.send('Internal server error.');
});
app.listen(3000, () => {
console.log('App started on port 3000');
}); |
Swift | UTF-8 | 3,209 | 3.109375 | 3 | [] | no_license | //
// FridgeAPI.swift
// FridgeNotes
//
// Created by Chris Woodard on 10/8/16.
// Copyright © 2016 Minimal. All rights reserved.
//
import Foundation
/************************************************************************
* Really simplified NSURLSession-based REST client.
************************************************************************/
public typealias CallBack = ([String:Any]) -> Void
var session:URLSession? = URLSession.shared
// this is a HTTP address, which means you have to add a whitelist entry to Info.plist
// for iOS9+ to not reject it
let urlBase:String = "http://fridgenotes.local:8090"
// connects to http://fridgenotes.local:8090
// GET /notes HTTP/1.1
public func getnotes(cb:@escaping CallBack) {
let url = URL(string: "\(urlBase)/notes")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
let task = session?.dataTask(with: request, completionHandler: { data, response, error in
// we're inside NSURLSession's callback closure now. we process the response *it* got
// and then call our own CallBack callback with the results of the request
do {
var results:[String:Any] = [:]
if let theData = data {
let dict = try JSONSerialization.jsonObject(with: theData, options: .mutableContainers)
results["data"] = dict
}
if let theResponse = response {
results["response"] = theResponse
}
results["error"] = error
cb(results)
}
catch {
cb(["Error":"Epic Fail"])
}
})
task?.resume()
}
// connects to http://fridgenotes.local:8090
// POST /notes HTTP/1.1
// <headers>
// <body>
public func post(notes:[Note], cb:@escaping CallBack) {
let url = URL(string: "\(urlBase)/notes")
var request = URLRequest(url: url!)
// set method to POST
request.httpMethod = "POST"
// set request Content-Type header to MIME type application/json. this tells
// the server that the body is JSON and needs to be deserialized
request.allHTTPHeaderFields = [
"Content-Type" : "application/json"
]
// construct body from list of notes in parameter, mapped to serialized JSON format
let strBody = "[" + notes.map { return $0.json() }.joined(separator: ",") + "]"
request.httpBody = strBody.data(using: .utf8)
let task = session?.dataTask(with: request, completionHandler: { data, response, error in
// we're inside NSURLSession's callback closure now. we process the response *it* got
// and then call our own CallBack callback with the results of the request
do {
var results:[String:Any] = [:]
if let theData = data {
let dict = try JSONSerialization.jsonObject(with: theData, options: .mutableContainers)
results["data"] = dict
}
if let theResponse = response {
results["response"] = theResponse
}
results["error"] = error
cb(results)
}
catch {
cb(["Error":"Epic Fail"])
}
})
task?.resume()
}
|
Java | UTF-8 | 1,566 | 2.0625 | 2 | [] | no_license | package com.summer.dt.mq.service.impl;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.summer.common.idgenerate.SnowflakeIdWorker;
import com.summer.common.utils.GsonUtils;
import com.summer.dt.mq.common.constant.OrderConstant;
import com.summer.dt.mq.dao.OrderMapper;
import com.summer.dt.mq.dao.TransactionLogMapper;
import com.summer.dt.mq.entity.Order;
import com.summer.dt.mq.entity.TransactionLog;
import com.summer.dt.mq.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
// @Autowired
// OrderMapper orderMapper;
@Autowired
TransactionLogMapper transactionLogMapper;
@Autowired
SnowflakeIdWorker snowflakeIdWorker;
@Transactional
@Override
public Order saveOrder(Order order) {
order.setId(snowflakeIdWorker.nextId());
baseMapper.save(order);
TransactionLog transactionLog = new TransactionLog();
transactionLog.setCreateTime(new Date());
transactionLog.setMsgBody(GsonUtils.toJson(order));
transactionLog.setPrimaryKey(order.getId());
transactionLog.setType(OrderConstant.TRANSACTION_TYPE_ORDER); //1:order
transactionLog.setStatus(OrderConstant.TRANSACTION_INIT);//init
transactionLogMapper.save(transactionLog);
return order;
}
}
|
C++ | UTF-8 | 1,243 | 2.796875 | 3 | [] | no_license | #include<bits/stdc++.h>
#include "StudentLoginController.h"
#include "StudentHomePageController.h"
//#include "StudentHomePageController.cpp"
#include "Student.h"
using namespace std;
bool StudentLoginController::open(Student student) {
system("clear");
string studentUserName;
string studentPassword;
this->showStudentLogin("Username");
cin>>ws;
getline(cin,studentUserName);
this->showStudentLogin("Password");
cin>>ws;
getline(cin,studentPassword);
bool matchdetails= student.matchDetailsStudent(studentUserName,studentPassword);
if(matchdetails){
return this->loginSuccess(student);
}
else{
return this->loginFail(student);
}
}
void StudentLoginController::showStudentLogin(string show) {
cout<<"Please Enter "<<show<<" : ";
}
bool StudentLoginController::loginSuccess(Student student) {
StudentHomePageController myStudentHomePageController;
return myStudentHomePageController.open(student);
}
bool StudentLoginController::loginFail(Student student) {
system("clear");
cout<<"Your Details didn't match with our Database\n";
for(int i=0;i<1000000000;i++){}
return 1;
}
|
Ruby | UTF-8 | 1,430 | 2.578125 | 3 | [] | no_license | #Story 1 of 3
require 'rails_helper'
describe 'As a visitor' do
before(:each) do
@chef = Chef.create!(name: "boyardee")
@dish = Dish.create!(name: 'cornbread',
description: 'bread',
chef_id: @chef.id)
@ingredient1 = Ingredient.create!(name: 'corn',
calories: 100)
@ingredient2 = Ingredient.create!(name: 'butter',
calories: 500)
DishesIngredient.create!(dish: @dish, ingredient: @ingredient1)
DishesIngredient.create!(dish: @dish, ingredient: @ingredient2)
end
describe "When I visit a dish's show page" do
it "I see the dish’s name and description" do
visit "/dishes/#{@dish.id}"
expect(page).to have_content(@dish.name)
expect(page).to have_content(@dish.description)
end
it "And I see a list of ingredients for that dish" do
visit "/dishes/#{@dish.id}"
expect(page).to have_content(@ingredient1.name)
expect(page).to have_content(@ingredient2.name)
end
it "And I see the chef's name" do
visit "/dishes/#{@dish.id}"
expect(page).to have_content(@chef.name)
end
end
#Story 2 of 3
describe "When I visit a dish's show page" do
it "I see the total calorie count for that dish." do
visit "/dishes/#{@dish.id}"
expect(page).to have_content(@dish.calorie_count)
end
end
end
|
SQL | UTF-8 | 3,433 | 3.5625 | 4 | [] | no_license | CREATE SEQUENCE receipt.receipt_id_seq;
CREATE TABLE receipt.receipt (
id integer not null default nextval('receipt.receipt_id_seq'),
clinic_id INTEGER NOT NULL,
type_id INTEGER NOT NULL,
series VARCHAR,
num VARCHAR,
issue_dt DATE NOT NULL,
employee_position_id INTEGER NOT NULL,
patient_id INTEGER NOT NULL,
sign_id INTEGER NOT NULL,
cito BOOLEAN DEFAULT false NOT NULL,
diagnosis_id INTEGER,
validity_id INTEGER,
canceled BOOLEAN DEFAULT false NOT NULL,
CONSTRAINT receipt_id_pk PRIMARY KEY(id),
CONSTRAINT receipt_clinic_id_fk FOREIGN KEY (clinic_id)
REFERENCES public.md_clinic(id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE,
CONSTRAINT receipt_type_id_fk FOREIGN KEY (type_id)
REFERENCES receipt.receipt_type(id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE,
CONSTRAINT receipt_employee_position_id_fk FOREIGN KEY (employee_position_id)
REFERENCES public.pim_employee_position(id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE,
CONSTRAINT receipt_patient_id_fk FOREIGN KEY (patient_id)
REFERENCES public.pim_individual(id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE,
CONSTRAINT receipt_sign_id_fk FOREIGN KEY (sign_id)
REFERENCES receipt.receipt_sign(id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE,
CONSTRAINT receipt_diagnosis_id_fk FOREIGN KEY (diagnosis_id)
REFERENCES public.md_diagnosis(id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE,
CONSTRAINT receipt_validity_id_fk FOREIGN KEY (validity_id)
REFERENCES receipt.receipt_validity(id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
NOT DEFERRABLE
) WITHOUT OIDS;
COMMENT ON TABLE receipt.receipt
IS 'Рецепт';
COMMENT ON COLUMN receipt.receipt.id
IS 'Идентификатор';
COMMENT ON COLUMN receipt.receipt.clinic_id
IS 'МО, выписавшая рецепт';
COMMENT ON COLUMN receipt.receipt.type_id
IS 'Тип рецепта';
COMMENT ON COLUMN receipt.receipt.series
IS 'Серия рецепта';
COMMENT ON COLUMN receipt.receipt.num
IS 'Номер рецепта';
COMMENT ON COLUMN receipt.receipt.issue_dt
IS 'Дата выписки';
COMMENT ON COLUMN receipt.receipt.employee_position_id
IS 'Должность сотрудника';
COMMENT ON COLUMN receipt.receipt.patient_id
IS 'Пациент';
COMMENT ON COLUMN receipt.receipt.sign_id
IS 'Признак рецепта';
COMMENT ON COLUMN receipt.receipt.cito
IS 'Срочный отпуск';
COMMENT ON COLUMN receipt.receipt.diagnosis_id
IS 'Заболевание';
COMMENT ON COLUMN receipt.receipt.validity_id
IS 'Срок действия рецепта в днях';
COMMENT ON COLUMN receipt.receipt.canceled
IS 'Признак аннулирования рецепта';
CREATE INDEX receipt_clinic_id_ix ON receipt.receipt
USING btree (clinic_id);
CREATE INDEX receipt_type_id_ix ON receipt.receipt
USING btree (type_id);
CREATE INDEX receipt_employee_position_id_ix ON receipt.receipt
USING btree (employee_position_id);
CREATE INDEX receipt_patient_id_ix ON receipt.receipt
USING btree (patient_id);
CREATE INDEX receipt_sign_id_ix ON receipt.receipt
USING btree (sign_id);
CREATE INDEX receipt_diagnosis_id_ix ON receipt.receipt
USING btree (diagnosis_id);
CREATE INDEX receipt_validity_id_ix ON receipt.receipt
USING btree (validity_id); |
SQL | UTF-8 | 3,689 | 2.953125 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 5.0.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 02, 2020 at 05:28 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cv`
--
-- --------------------------------------------------------
--
-- Table structure for table `hobi`
--
CREATE TABLE `hobi` (
`id_hobi` int(11) NOT NULL,
`hobiku` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `hobi`
--
INSERT INTO `hobi` (`id_hobi`, `hobiku`) VALUES
(1, '-BERMAIN GAME'),
(2, '-BASKET'),
(3, '-FOTOGRAFI'),
(4, '-EDITING VIDEO DAN FOTO');
-- --------------------------------------------------------
--
-- Table structure for table `kontak`
--
CREATE TABLE `kontak` (
`id_kontak` int(11) NOT NULL,
`kontakkk` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `kontak`
--
INSERT INTO `kontak` (`id_kontak`, `kontakkk`) VALUES
(1, 'Telepon : 082281436560'),
(2, 'Email : dittputra0502@gmail.com'),
(3, 'Instagram : @iyaaditt'),
(4, 'Twitter : @aadityaputraa');
-- --------------------------------------------------------
--
-- Table structure for table `prestasi`
--
CREATE TABLE `prestasi` (
`id_prestasi` int(11) NOT NULL,
`prestasiku` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `prestasi`
--
INSERT INTO `prestasi` (`id_prestasi`, `prestasiku`) VALUES
(1, '-PANITIA NATAL 2018 UPN \'VETERAN\' JAWATIMUR KOOR DIVISI PDD'),
(2, '-PANITIA NATAL 2019 UPN \'VETERAN\' JAWA TIMUR KOOR DIVISI PD'),
(3, '-PANITIA OMKB 2019 UPN \'VETERAN\' JAWA TIMUR KOOR DIVISI PDD'),
(4, '-PANITIA BAKSOS 2019 UK3 UPN \'VETERAN\' JAWA TIMUR DI DIVISI PDD'),
(5, '-PANITIA YOUTHCAMP 2018 UK3 UPN \'VETERAN\' JAWA TIMUR DIVISI PDD');
-- --------------------------------------------------------
--
-- Table structure for table `riwayat_organisasi`
--
CREATE TABLE `riwayat_organisasi` (
`id_riwayat_organisasi` int(11) NOT NULL,
`riwayat` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `riwayat_organisasi`
--
INSERT INTO `riwayat_organisasi` (`id_riwayat_organisasi`, `riwayat`) VALUES
(1, '-2011 : ANGGOTA OSIS DISMP N 7 SALATIGA'),
(2, '-2015 - 2016 : ANGGOTA LAB DI SMK SENOPATI SEDATI'),
(3, '-2019 : ANGGOTA DIVISI KOMUNIKASI DI UK3 UPN \'VETERAN\' JAWA TIMUR'),
(4, '-2020 : KOOR DIVISI KOMUNIKASI DI UK3 UPN \'VETERAN\' JAWA TIMUR'),
(5, '-2020 : ANGGOTA DI MOBILE DEVLOPER UPN \'VETERAN\' JAWA TIMUR');
-- --------------------------------------------------------
--
-- Table structure for table `riwayat_pendidikan`
--
CREATE TABLE `riwayat_pendidikan` (
`id_riwayat_pendidikan` int(11) NOT NULL,
`riwayat_p` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `riwayat_pendidikan`
--
INSERT INTO `riwayat_pendidikan` (`id_riwayat_pendidikan`, `riwayat_p`) VALUES
(1, '- 2005 - 2006 : TK PUTRA JAYA'),
(2, '- 2006 - 2012 : SDN DUKUH 1 SALATIGA'),
(3, '- 2012 - 2015 : SMPN 7 SALATIGA\"'),
(4, '- 2015 - 2018 : SMK SENOPATI SEDATI SIDOARJO'),
(5, '- 2018 - SEKARANG : UPN \'VETERAN\' JAWA TIMUR');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Markdown | UTF-8 | 1,352 | 3.265625 | 3 | [] | no_license | ---
group: graphql
title: createEmptyCart mutation
---
The `createEmptyCart` mutation creates an empty shopping cart for a guest or logged in customer. You can allow the system to generate a cart ID, or assign a specific ID.
If you are creating a cart for a logged in customer, you must include the customer's authorization token in the header of the request.
## Syntax
`mutation: {createEmptyCart}: String`
## Example usage
### Create a cart with a randomly-generated cart ID
**Request**
```text
mutation {
createEmptyCart
}
```
**Response**
The response is the cart ID, which is sometimes called the quote ID. The remaining examples in this topic will use this cart ID.
```json
{
"data": {
"createEmptyCart": "4JQaNVJokOpFxrykGVvYrjhiNv9qt31C"}
}
}
```
### Create an empty cart with an assigned cart ID
You can also create an empty cart with a specified `cart_id`.
Attribute | Data Type | Description
--- | --- | ---
`cart_id` | String | A 32-character string
### Syntax
`mutation: {input: createEmptyCart: createEmptyCartInput}: String`
### Example usage
**Request**
``` text
mutation {
createEmptyCart(input:
{ cart_id: "x2345678901234567890123456789012"})
}
```
**Response**
The mutation returns the same `cart_id`.
```json
{
"data": {
"createEmptyCart": "x2345678901234567890123456789012"
}
}
``` |
Markdown | UTF-8 | 789 | 2.796875 | 3 | [] | no_license | ---
layout: page
title: What's the address of my website?
permalink: /help/address-of-booking-page/
description: The address or URL of your website
keywords: booking page, website, address, domain
---
# What's the address of my website?
You'll find the address of your website on the Settings page of your AppointmentGuru account.
Log into your [AppointmentGuru account](https://app.appointmentguru.co/), click on *Get Online* and you'll see an address underneath *Your website*.
### Related articles
* [What is the free website?](/help/booking-page)
* [Can I change the background on my website?](/help/change-background)
* [Can I use my own domain name with my website?](/help/use-domain-name)
* [I already have a website, can I add the booking widget to it?](/help/booking-widget)
|
Java | UTF-8 | 3,007 | 2.15625 | 2 | [] | no_license | package com.ubtechinc.bluetoothrobot.old;
import android.util.Log;
import com.ubtrobot.commons.Priority;
import com.ubtrobot.mini.voice.VoiceListener;
import com.ubtrobot.mini.voice.VoicePool;
import com.ubtrobot.speech.listener.TTsListener;
/**
* @desc : 本地语音播报助手类
* @author: zach.zhang
* @email : Zach.zhang@ubtrobot.com
* @time : 2018/4/10
*/
public class LocalTTSHelper {
private static final String TAG = "LocalTTSHelper";
private static final String LOCAL_TTS_PLAYBANDING_SUC = "networking_001";
private static final String LOCAL_ERROR_PASSWORD = "networking_002";
private static final String LOCAL_TTS_CONNECT_TIMEOUT = "networking_003";
private static final String LOCAL_NETWORK_NOT_AVAILABLE = "networking_004";
private static final String LOCAL_TTS_CHOOSE_WIFI_SUC = "networking_005";
private static final String LOCAL_CONNECT_BEFORE_WIFI = "networking_006";
private static final String LOCAL_BANGDING_SUCC_TIP_FOR_MUSIC = "networking_007";
public static void playBandingSuc() {
Log.d(TAG, " playBandingSuc ");
VoicePool.get().playLocalTTs(LOCAL_TTS_PLAYBANDING_SUC, Priority.HIGH,new VocieListenerAdatper());
}
public static void playErrorPassword() {
Log.d(TAG, " playErrorPassword ");
VoicePool.get().playLocalTTs(LOCAL_ERROR_PASSWORD,Priority.HIGH,new VocieListenerAdatper());
}
/**
* Wi-Fi不可用
*/
public static void playConnectTimeout() {
Log.d(TAG, " playConnectTimeout ");
VoicePool.get().playLocalTTs(LOCAL_TTS_CONNECT_TIMEOUT,Priority.HIGH,new VocieListenerAdatper());
}
public static void playChooseWifiSuc() {
Log.d(TAG, " playChooseWifiSuc ");
VoicePool.get().playLocalTTs(LOCAL_TTS_CHOOSE_WIFI_SUC,Priority.HIGH,new VocieListenerAdatper());
}
public static void playNetworkNotAvailable() {
Log.d(TAG, " playNetworkNotAvailable ");
VoicePool.get().playLocalTTs(LOCAL_NETWORK_NOT_AVAILABLE,Priority.HIGH,new VocieListenerAdatper());
}
public static void playConnectBeforeWifi() {
Log.d(TAG, " playConnectBeforeWifi ");
VoicePool.get().playLocalTTs(LOCAL_CONNECT_BEFORE_WIFI,Priority.HIGH,new VocieListenerAdatper());
}
public static void playTipsForMusicVip() {
VoicePool.get().playLocalTTs(LOCAL_BANGDING_SUCC_TIP_FOR_MUSIC,Priority.HIGH,new VocieListenerAdatper());
}
private static class VocieListenerAdatper implements VoiceListener {
@Override
public void onCompleted() {
}
@Override
public void onError(int i, String s) {
}
}
private static class TTsListenerAdapter implements TTsListener {
@Override
public void onTtsBegin() {
}
@Override
public void onTtsVolumeChange(int i) {
}
@Override
public void onTtsCompleted() {
}
@Override
public void onError(int i, String s) {
}
}
}
|
Markdown | UTF-8 | 1,130 | 2.78125 | 3 | [] | no_license | Vous n'avez pas le temps de faire vos courses après le boulot ?
Vous êtes actuellement en mobilité réduite et vous souhaitez quelqu'un qui fasse les courses à votre place ?
Vous cherchez une personne pouvant faire vos courses lorsque vous êtes surbooké ?!
Vous êtes producteur et vous souhaitez vous faire connaitre sur internet ?
Nous avons le site Web et l'application qu'il vous faut !
[XX] est une application et un site web de recherche de livreurs et de producteurs entre particulier.
Au fil du temps, nous avons constaté que certaines personnes souhaitaient retrouver les saveurs des produits locaux de vos marchés mais vous ne pouvez pas y allez suite à votre travail, ou un manque de mobilité.
Nous avons conçu ce site afin de satisfaire vos besoins ! Trouvez des particuliers qui sont prêt à faire vos courses à votre place chez vos producteurs préférés !
> Notre objectif, c'est votre satisfaction !
Nous avons constatés que certaines personnes demandaient à leur proches si il était possible d'allez faire leurs courses, mais nous souhaitons diversifier cela dans une entraide collective.
|
Python | UTF-8 | 2,478 | 3.65625 | 4 | [] | no_license | from random import choice
class Node:
def __init__(self,x,y,num):
self.x = x
self.y = y
self.num = num
def display(self):
fill(0)
ellipse(self.x,self.y,10,10)
def connect(self,other):
strokeWeight(1)
line(self.x,self.y,
other.x,other.y)
nodes = ['placeholder']#so the first node will be 1
mirrornodes = ['placeholder']
#list for connections between nodes
connections = [[1,2],[1,4],
[2,3],[2,4],[2,5],
[3,5],[3,7],
[4,5],[4,6],
[5,6],[5,7],
[6,7],[6,8],
[7,8],[7,9],
[8,9]]
class Grid:
def __init__(self,sz):
#create the nodes in the grid
nodes.append(Node(0,0,1))
nodes.append(Node(0,-sz,2))
nodes.append(Node(0,-2*sz,3))
nodes.append(Node(sz/2.0,-sz/2.0,4))
nodes.append(Node(0.5*sz,-1.5*sz,5))
nodes.append(Node(sz,-sz,6))
nodes.append(Node(sz,-2*sz,7))
nodes.append(Node(1.5*sz,-1.5*sz,8))
nodes.append(Node(2*sz,-2*sz,9))
#create the nodes which mirror over the diagonal line
mirrornodes.append(Node(0,0,1))
mirrornodes.append(Node(sz,0,2))
mirrornodes.append(Node(2*sz,0,3))
mirrornodes.append(Node(sz/2.0,-sz/2.0,4))
mirrornodes.append(Node(1.5*sz,-0.5*sz,5))
mirrornodes.append(Node(sz,-sz,6))
mirrornodes.append(Node(2*sz,-sz,7))
mirrornodes.append(Node(1.5*sz,-1.5*sz,8))
mirrornodes.append(Node(2*sz,-2*sz,9))
#randomly choose which nodes are connecting
self.connectChoice = [choice([0,1]) for x in range(15)]
def connect(self):
#for every node that's connecting:
for i,c in enumerate(self.connectChoice):
if c == 1: #if the connection is active
#connect the first node in the 2-list with the second
nodes[connections[i][0]].connect(nodes[connections[i][1]])
#also connect the reflections of those nodes
mirrornodes[connections[i][0]].connect(mirrornodes[connections[i][1]])
def display(self):
#copy the upper right quadrant
# to all 4 quadrants by rotating
for i in range(4):
rotate(radians(90*i))
self.connect()
|
Java | UTF-8 | 637 | 3.734375 | 4 | [] | no_license | package scanner;
import java.util.Scanner;
public class Ascending {
public static void main(String[] args)
{
int[] a=new int[10];
int temp;
Scanner scan=new Scanner(System.in);
System.out.println("Enter the values");
for(int i=0;i<10;i++)
{
a[i]=scan.nextInt();
}
temp=a[0];
for(int i=0;i<10;i++)
{
for(int j=i+1;j<10;j++)
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
System.out.println("Ascending order ");//after loop end this for loop for ascending
for(int i=0;i<10;i++)
System.out.println(a[i]);//print the array a[i] values in ascending order
scan.close();
}
}
|
Python | UTF-8 | 187 | 3.859375 | 4 | [] | no_license | soma = 0
for c in range(1, 7):
num = int(input('Digite [{}] valor:'.format(c)))
if num % 2 == 0:
soma += num
print('A soma dos numeros pares é: {}'.format(soma)) |
C | UTF-8 | 1,007 | 3.53125 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void fnPush(int [],int *,int);
int fnPop(int [],int *);
int main()
{
int iOp1,iOp2,iRes=0;
int i,iaStack[10],iTop=-1;
char acPrefix[10],cSymb;
printf("\nEnter a valid prefix expression\n");
scanf("%s",acPrefix);
for(i=strlen(acPrefix)-1;i>=0;i--)
{
cSymb=acPrefix[i];
if(isdigit(cSymb))
{
fnPush(iaStack,&iTop,(cSymb-'0'));
}
else
{
iOp1=fnPop(iaStack,&iTop);
iOp2=fnPop(iaStack,&iTop);
switch(cSymb)
{
case '+':iRes=iOp1+iOp2;
break;
case '-':iRes=iOp1-iOp2;
break;
case '*':iRes=iOp1*iOp2;
break;
case '/':iRes=iOp1/iOp2;
break;
}
fnPush(iaStack,&iTop,iRes);
}
}
iRes=fnPop(iaStack,&iTop);
printf("\nResult=%d\n",iRes);
return 0;
}
void fnPush(int iaStack[],int *iTop,int symb)
{
*iTop=*iTop+1;
iaStack[*iTop]=symb;
}
int fnPop(int iaStack[],int *iTop)
{
int elem;
elem=iaStack[*iTop];
*iTop=*iTop-1;
return elem;
}
|
Java | UTF-8 | 1,241 | 2.40625 | 2 | [] | no_license | package com.valentsolutions.stxt.dom;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import com.valentsolutions.stxt.StxtException;
import org.w3c.dom.Document;
/**
* Fragment for holding small pieces of structured text that don't require
* blocks and metadata.
*/
public class StxtFragment
extends InlineContainer
implements StxtElement
{
/**
* @see com.valentsolutions.stxt.dom.InlineContainer#getElementName()
*/
protected String getElementName()
{
return "stxtFragment";
}
public Document toDOM()
throws StxtException
{
Document document;
try
{
DocumentBuilderFactory builderFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
document = docBuilder.newDocument();
}
catch (ParserConfigurationException e)
{
throw new StxtException("Failed to create a DocumentBuilder", e);
}
document.appendChild(this.toDOM(document));
document.normalize();
return document;
}
}
|
Java | UTF-8 | 8,152 | 2.109375 | 2 | [] | no_license | package com.kanjian.star.search.services;
import java.util.HashMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.kanjian.star.search.dao.StarDAO;
@Component
@Service
public class IndexBuilder {
private static final Logger logger = Logger.getLogger(IndexBuilder.class);
@Autowired
private StarDAO dao;
@Value("${hop_each_build}")
private String hopEachBuild;
@Value("${index_original_path}")
private String indexOriginalPath;
@Value("${max_memory}")
private String maxMemory;
public static final FieldType INT_FIELD_TYPE_STORED_SORTED = new FieldType();
static {
INT_FIELD_TYPE_STORED_SORTED.setTokenized(true);
INT_FIELD_TYPE_STORED_SORTED.setOmitNorms(true);
INT_FIELD_TYPE_STORED_SORTED.setIndexOptions(IndexOptions.DOCS);
INT_FIELD_TYPE_STORED_SORTED.setNumericType(FieldType.NumericType.INT);
INT_FIELD_TYPE_STORED_SORTED.setStored(true);
INT_FIELD_TYPE_STORED_SORTED.setDocValuesType(DocValuesType.NUMERIC);
INT_FIELD_TYPE_STORED_SORTED.freeze();
}
public int buildIndex() throws IOException {
buildTrackIndex();
buildAlbumIndex();
return 0;
}
public int buildTrackIndex() throws IOException {
return 0;
Analyzer analyzer = new StandardAnalyzer();
String trackIndexPath = indexOriginalPath + "/track";
Directory dir = FSDirectory.open(Paths.get(trackIndexPath));
IndexWriterConfig indexWriter = new IndexWriterConfig(analyzer);
indexWriter.setOpenMode(OpenMode.CREATE);
indexWriter.setRAMBufferSizeMB(Integer.parseInt(maxMemory));
IndexWriter writer = new IndexWriter(dir, indexWriter);
int maxId = dao.getTrackMaxId();
int count_per_query = Integer.parseInt(hopEachBuild);
for (int i = 0;(i+1) * count_per_query <= maxId+1;i++) {
for (HashMap<String, Object> track: dao.getTrackList(i*count_per_query, (i+1)*count_per_query)) {
Document doc = new Document();
doc.add(new IntField("id", (Integer)track.get("id"), INT_FIELD_TYPE_STORED_SORTED));
String title = (String)track.get("name");
if (track.get("version") != null) {
title += " " + (String)track.get("version");
}
if (track.get("english_name") != null) {
title += " " + (String)track.get("english_name");
}
doc.add(new TextField("title", title + " " + "kanjiansdxqfx", Field.Store.NO));
if (track.get("duration") != null) {
doc.add(new IntField("duration", (Integer)track.get("duration"), Field.Store.NO));
}
writer.addDocument(doc);
}
}
writer.close();
return 0;
}
public int buildAlbumIndex() throws IOException {
Analyzer analyzer = new StandardAnalyzer();
String albumIndexPath = indexOriginalPath + "/album";
Directory dir = FSDirectory.open(Paths.get(albumIndexPath));
IndexWriterConfig indexWriter = new IndexWriterConfig(analyzer);
indexWriter.setOpenMode(OpenMode.CREATE);
indexWriter.setRAMBufferSizeMB(Integer.parseInt(maxMemory));
IndexWriter writer = new IndexWriter(dir, indexWriter);
int maxId = dao.getAlbumMaxId();
int count_per_query = Integer.parseInt(hopEachBuild);
for (int i = 0;(i+1) * count_per_query <= maxId+1;i++) {
for (HashMap<String, Object> album: dao.getAlbumList(i*count_per_query, (i+1)*count_per_query)) {
Document doc = new Document();
doc.add(new IntField("id", (Integer)album.get("id"), INT_FIELD_TYPE_STORED_SORTED));
String title = (String)album.get("name");
if (album.get("version") != null) {
title += " " + (String)album.get("version");
}
if (album.get("upc") != null) {
title += " " + (String)album.get("upc");
}
if (album.get("distribution_company") != null) {
title += " " + (String)album.get("distribution_company");
}
if (album.get("author_list") != null) {
Gson gson = new Gson();
JsonArray authorList = gson.fromJson((String)album.get("author_list"), JsonArray.class);
for (int j = 0; j < authorList.size(); j++) {
title += " " + authorList.get(j).getAsString();
}
}
doc.add(new TextField("title", title + " " + "kanjiansdxqfx", Field.Store.NO));
if (album.get("release_date") != null) {
doc.add(new StringField("release_date", (String)album.get("release_date"), Field.Store.NO));
}
else {
doc.add(new StringField("release_date", "NO RELEASE DATE", Field.Store.NO));
}
int material = (Integer)album.get("material_review_status");
int metadata = (Integer)album.get("metadata_review_status");
int delivery = (Integer)album.get("delivery_status");
if (material == 0) {
doc.add(new StringField("material", "未审核", Field.Store.NO));
} else if (material == 1) {
doc.add(new StringField("material", "审核中", Field.Store.NO));
} else if (material == 2) {
doc.add(new StringField("material", "审核未通过", Field.Store.NO));
} else if (material == 3) {
doc.add(new StringField("material", "审核通过", Field.Store.NO));
}
if (metadata == 0) {
doc.add(new StringField("metadata", "未审核", Field.Store.NO));
} else if (metadata == 1) {
doc.add(new StringField("metadata", "审核中", Field.Store.NO));
} else if (metadata == 2) {
doc.add(new StringField("metadata", "审核未通过", Field.Store.NO));
} else if (metadata == 3) {
doc.add(new StringField("metadata", "审核通过", Field.Store.NO));
}
if (delivery == 0) {
doc.add(new StringField("delivery", "未上架", Field.Store.NO));
} else if (delivery == 1) {
doc.add(new StringField("delivery", "已上架", Field.Store.NO));
} else if (delivery == 2) {
doc.add(new StringField("delivery", "已下架", Field.Store.NO));
} else if (delivery == 3) {
doc.add(new StringField("delivery", "上架中", Field.Store.NO));
}
Field sourceField = new IntField("source", (Integer)album.get("source"), Field.Store.NO);
doc.add(sourceField);
writer.addDocument(doc);
}
}
writer.close();
return 0;
}
}
|
C# | UTF-8 | 1,778 | 2.515625 | 3 | [
"MIT"
] | permissive | using System;
namespace Rafy.Serialization.Mobile
{
/// <summary>
/// Interface to be implemented by any object
/// that supports serialization by the
/// MobileFormatter.
/// </summary>
public interface IMobileObject
{
/// <summary>
/// Method called by MobileFormatter when an object
/// should serialize its data. The data should be
/// serialized into the SerializationInfo parameter.
/// </summary>
/// <param name="info">
/// Object to contain the serialized data.
/// </param>
void SerializeState(ISerializationContext info);
/// <summary>
/// Method called by MobileFormatter when an object
/// should serialize its child references. The data should be
/// serialized into the SerializationInfo parameter.
/// </summary>
/// <param name="info">Object to contain the serialized data.</param>
void SerializeRef(ISerializationContext info);
/// <summary>
/// Method called by MobileFormatter when an object
/// should be deserialized. The data should be
/// deserialized from the SerializationInfo parameter.
/// </summary>
/// <param name="info">
/// Object containing the serialized data.
/// </param>
void DeserializeState(ISerializationContext info);
/// <summary>
/// Method called by MobileFormatter when an object
/// should deserialize its child references. The data should be
/// deserialized from the SerializationInfo parameter.
/// </summary>
/// <param name="info">Object containing the serialized data.</param>
void DeserializeRef(ISerializationContext info);
}
}
|
Markdown | UTF-8 | 1,278 | 3.265625 | 3 | [] | no_license | ## 题目位置
[https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/](https://leetcode-cn.com/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/)
<br/>
## 题解
```java
/**
* 以每一个节点为根节点进行便利,看看能否找到 p、q,返回最后一个条件成立的可能
*
* @author 小道仙
* @date 2020/9/1
*/
TreeNode result;
int count = 0;
int tmp1,tmp2;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
tmp1 = p.val;
tmp2 = q.val;
fun(root);
return result;
}
public void fun(TreeNode root){
if (root == null){
return;
}
fun2(root);
if (count == 2){
count = 0;
result = root;
}else {
count = 0;
return;
}
if (root.left != null) fun(root.left);
if (root.right != null) fun(root.right);
}
public void fun2(TreeNode root){
if (root == null){
return;
}
if (root.val == tmp1 || root.val == tmp2){
count += 1;
}
if (root.left != null) fun2(root.left);
if (root.right != null) fun2(root.right);
}
``` |
Java | UTF-8 | 4,094 | 2.59375 | 3 | [
"MIT"
] | permissive | package dslab;
import java.io.InputStream;
import java.io.PrintStream;
import dslab.client.IMessageClient;
import dslab.client.MessageClient;
import dslab.mailbox.IMailboxServer;
import dslab.mailbox.MailboxServer;
import dslab.monitoring.IMonitoringServer;
import dslab.monitoring.MonitoringServer;
import dslab.nameserver.INameserver;
import dslab.nameserver.Nameserver;
import dslab.transfer.ITransferServer;
import dslab.transfer.TransferServer;
import dslab.util.Config;
/**
* The component factory provides methods to create the core components of the application. You can edit the method body
* if the component instantiation requires additional logic.
*
* Do not change the existing method signatures!
*/
public final class ComponentFactory {
private ComponentFactory() {
// static utility class
}
/**
* Creates a new {@link IMonitoringServer} instance.
*
* @param componentId the component id
* @param in the input stream used for accepting cli commands
* @param out the output stream to print to
* @return a new MonitoringServer instance
*/
public static IMonitoringServer createMonitoringServer(String componentId, InputStream in, PrintStream out)
throws Exception {
/*
* TODO: Here you can modify the code (if necessary) to instantiate your components
*/
Config config = new Config(componentId);
return new MonitoringServer(componentId, config, in, out);
}
/**
* Creates a new {@link IMailboxServer} instance.
*
* @param componentId the component id
* @param in the input stream used for accepting cli commands
* @param out the output stream to print to
* @return a new MailboxServer instance
*/
public static IMailboxServer createMailboxServer(String componentId, InputStream in, PrintStream out)
throws Exception {
/*
* TODO: Here you can modify the code (if necessary) to instantiate your components
*/
Config config = new Config(componentId);
return new MailboxServer(componentId, config, in, out);
}
/**
* Creates a new {@link ITransferServer} instance.
*
* @param componentId the component id
* @param in the input stream used for accepting cli commands
* @param out the output stream to print to
* @return a new TransferServer instance
*/
public static ITransferServer createTransferServer(String componentId, InputStream in, PrintStream out)
throws Exception {
/*
* TODO: Here you can modify the code (if necessary) to instantiate your components
*/
Config config = new Config(componentId);
return new TransferServer(componentId, config, in, out);
}
/**
* Creates a new {@link INameserver} instance.
*
* @param componentId the component id
* @param in the input stream used for accepting cli commands
* @param out the output stream to print to
* @return a new Nameserver instance
*/
public static INameserver createNameserver(String componentId, InputStream in, PrintStream out)
throws Exception {
/*
* TODO: Here you can modify the code (if necessary) to instantiate your components
*/
Config config = new Config(componentId);
return new Nameserver(componentId, config, in, out);
}
/**
* Creates a new {@link IMessageClient} instance.
*
* @param componentId the component id
* @param in the input stream used for accepting cli commands
* @param out the output stream to print to
* @return a new MessageClient instance
*/
public static IMessageClient createMessageClient(String componentId, InputStream in, PrintStream out)
throws Exception {
/*
* TODO: Here you can modify the code (if necessary) to instantiate your components
*/
Config config = new Config(componentId);
return new MessageClient(componentId, config, in, out);
}
}
|
Python | UTF-8 | 122 | 3.625 | 4 | [] | no_license | for i in range(10):
if(i == 6):
break # it can terminate the loop even the condition is true
print i
|
C# | UTF-8 | 3,709 | 2.609375 | 3 | [] | no_license | using CarSellersClasses;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class OrderList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// if first time page is displayed
if (IsPostBack == false)
{
// update order list
DisplayOrders();
}
}
void DisplayOrders()
{
// create collection instance
clsOrderCollection Orders = new clsOrderCollection();
// set data source for list to the Orders collection
lstOrderList.DataSource = Orders.OrderList;
//set primary key
lstOrderList.DataValueField = "OrderID";
// set data field to display
lstOrderList.DataTextField = "numberPlate";
// bind data to text field
lstOrderList.DataBind();
}
protected void lstOrderList_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
// store -1 in session to indicate a new record
Session["OrderID"] = -1;
// redirect to data entry page
Response.Redirect("AnOrder.aspx");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
// var of record to be deleted
Int32 OrderID;
// if record selected from list
if(lstOrderList.SelectedIndex != -1)
{
// get primary key of record to be deleted
OrderID = Convert.ToInt32(lstOrderList.SelectedValue);
// store data in session object
Session["OrderID"] = OrderID;
// redirect to delete page
Response.Redirect("DeleteOrder.aspx");
}
else // if no record selected
{
// display error
lblError.Text = "Please select a record from the list";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
// var for primary key of record to edit
Int32 OrderID;
// if record is selected
if (lstOrderList.SelectedIndex != -1)
{
// get primary key of record to be edited
OrderID = Convert.ToInt32(lstOrderList.SelectedValue);
// store data in session
Session["OrderID"] = OrderID;
// redirect to edit page
Response.Redirect("AnOrder.aspx");
}
else // if no record selected
{
lblError.Text = "Please select a record to edit from the list";
}
}
protected void btnApply_Click(object sender, EventArgs e)
{
// create instance of order collection
clsOrderCollection Orders = new clsOrderCollection();
Orders.ReportbyNumberPlate(txtFilter.Text);
lstOrderList.DataSource = Orders.OrderList;
// set primary key
lstOrderList.DataValueField = "OrderID";
// set field to display
lstOrderList.DataTextField = "NumberPlate";
// bind data to the list
lstOrderList.DataBind();
}
protected void btnClear_Click(object sender, EventArgs e)
{
// create instance of order collection
clsOrderCollection Orders = new clsOrderCollection();
Orders.ReportbyNumberPlate("");
// clear any filter to tidy interface
txtFilter.Text = "";
lstOrderList.DataSource = Orders.OrderList;
// set primary key
lstOrderList.DataValueField = "OrderID";
// set field to display
lstOrderList.DataTextField = "NumberPlate";
// bind data to list
lstOrderList.DataBind();
}
} |
Java | UTF-8 | 536 | 1.960938 | 2 | [
"MIT"
] | permissive | package org.jzp.code.solr.client.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 分页参数注解
*
* @author jiazhipeng
* @version 1.0
* @date 2016-06-23
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PageField {
PageFiledEnum name();
enum PageFiledEnum {
// 每页记录数
PAGESIZE,
// 起始值
START
}
}
|
C++ | UTF-8 | 1,014 | 2.875 | 3 | [] | no_license | /*
* @lc app=leetcode id=902 lang=cpp
*
* [902] Numbers At Most N Given Digit Set
*/
// @lc code=start
class Solution {
public:
int atMostNGivenDigitSet(vector<string>& D, int N) {
const string strN(to_string(N));
int i(0);
string strD(D.size(), ' ');
for (i = 0; i < D.size(); ++i) { strD[i] = D[i][0]; }
int ans(0), len(strN.size());
for (i = 1; i < len; ++i) { ans += pow(strD.size(), i); }
bool prefix(false);
for (i = 0; i < len; ++i) {
prefix = false;
for (char c : strD) {
if (c < strN[i]) {
ans += pow(strD.size(), len - 1 - i);
} else if (c == strN[i]) {
prefix = true;
break;
} else {
break;
}
}
if (!prefix) { return ans; }
}
return ans + 1;
}
};
// @lc code=end
|
Java | UTF-8 | 1,138 | 2.0625 | 2 | [
"Apache-2.0"
] | permissive | package com.kuliginstepan.mongration.service.impl;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import com.kuliginstepan.mongration.MongrationException;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
class ReactiveChangesetServiceTest {
private ReactiveChangeSetService changesetService = new ReactiveChangeSetService(null, null);
@Test
void shouldAllowExecuteMonoMethod() {
assertThatCode(() -> changesetService.validateChangesetMethodSignature(
ReactiveChangesetServiceTest.class.getDeclaredMethod("testChangeSetMethod")).block())
.doesNotThrowAnyException();
}
@Test
void shouldThrowExceptionForNonMonoMethod() {
assertThatExceptionOfType(MongrationException.class)
.isThrownBy(() -> changesetService.validateChangesetMethodSignature(
ReactiveChangesetServiceTest.class.getDeclaredMethod("shouldAllowExecuteMonoMethod")).block());
}
private Mono<Object> testChangeSetMethod() {
return Mono.empty();
}
} |
C++ | UTF-8 | 381 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,m;
cin>>n>>m;
if(n>m)
swap(n,m);
if(n%2)
{
if(m%2)
{
cout<<(n)*(m/2) + n-n/2;
}
else
{
cout<<(n)*(m/2);
}
}
else
{
if(m%2)
{
cout<<(n)*(m/2) + n/2;
}
else
{
cout<<(n/2)*m;
}
}
cout<<endl;
}
return 0;
}
|
C# | UTF-8 | 721 | 2.734375 | 3 | [] | no_license | using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
namespace WPF_Data_Binding
{
public partial class BindingList : Window
{
ObservableCollection<Person> liste = new ObservableCollection<Person>();
public ObservableCollection<Person> GetPerson()
{
liste.Add(new Person { Name = "Schulze", Alter = 56, Adresse = "Bremen" });
liste.Add(new Person { Name = "Hans", Alter = 30, Adresse = "Hamburg" });
liste.Add(new Person { Name = "Franz", Alter = 45, Adresse = "Köln" });
liste.Add(new Person { Name = "Müller", Alter = 26, Adresse = "Hannover" });
return liste;
}
}
}
|
Java | UTF-8 | 346 | 2.0625 | 2 | [] | no_license | package com.zhongcheng.jenkins.javajenkins.dao.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor //全参构造函数
public class Pages<T> {
public Pages(int count, List<T> rows) {
this((long)count, rows);
}
private Long count;
private List<T> rows;
}
|
Python | UTF-8 | 343 | 3.34375 | 3 | [] | no_license | from concurrent.futures import ThreadPoolExecutor
class S:
def __init__(self):
self.L = []
def plus(self, n):
for i in range(n):
self.L.append(i)
s = S()
N = 1000000
with ThreadPoolExecutor() as ex:
for i in range(3):
ex.submit(s.plus, N)
print(len(s.L)) # 3000000
print(3 * N) # 3000000
|
JavaScript | UTF-8 | 252 | 3.234375 | 3 | [
"MIT"
] | permissive | function printElementFromArray(arr){
let stepSize = Number(arr[arr.length - 1]);
arr.pop();
for (let i = 0; i < arr.length; i+= stepSize) {
console.log(arr[i]);
}
}
printElementFromArray(['dsa',
'asd',
'test',
'tset',
'2']); |
PHP | UTF-8 | 354 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Tyler36\SocialAuth\Helpers;
use Route;
class ProviderRoute
{
/**
* Get the Socialite provider from route.
*
* @return mixed
*/
public static function get()
{
if (null === Route::current()) {
return false;
}
return Route::current()->parameters()['provider'];
}
}
|
Java | UTF-8 | 20,402 | 1.90625 | 2 | [] | no_license | package com.example.tfg.Sistems.SistemaPerfil.Fragments;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.tfg.FormularioInicio;
import com.example.tfg.R;
import com.example.tfg.Sistems.SistemaPerfil.models.Usuario;
import com.example.tfg.app.Const;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.text.DecimalFormat;
import java.util.UUID;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmModel;
public class PerfilFragment extends Fragment {
private Button buttonModificar, buttonCalorias;
private TextView textNombre, textEdad, textPeso, textAltura, textCorreo, textIMC;
private ImageView imgGenero, imgInfo;
private double imc;
private Usuario usu, usuMod;
private Realm realm;
public PerfilFragment() {
}
public static PerfilFragment newInstance(String param1, String param2) {
PerfilFragment fragment = new PerfilFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_perfil, container, false);
setRealm();
setReferencias(view);
settersElementos();
usu.addChangeListener(new RealmChangeListener<RealmModel>() {
@Override
public void onChange(RealmModel realmModel) {
settersElementos();
}
});
imgInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAlertForInfo("INFORMACION IMC");
}
});
buttonModificar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAlertForModficarAlmacen("MODIFICAR PERFIL");
}
});
buttonCalorias.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAlertForChangeCalorias("");
}
});
return view;
}
private void setRealm(){
realm = Realm.getDefaultInstance();
usu = realm.where(Usuario.class).equalTo("id", 1).findFirst();
if(usu == null)
usu = new Usuario("","",Usuario.USUARIO_HOMBRE,"",0,0);
}
private void setReferencias(View view){
buttonModificar = (Button) view.findViewById(R.id.fragmentPerfilButtonModificar);
buttonCalorias = (Button) view.findViewById(R.id.fragmentPerfilButtonModificarCalorias);
textAltura = (TextView) view.findViewById(R.id.fragmentPerfilTextViewAltura);
textPeso = (TextView) view.findViewById(R.id.fragmentPerfilTextViewPeso);
textCorreo = (TextView) view.findViewById(R.id.fragmentPerfilTextViewCorreo);
textNombre = (TextView) view.findViewById(R.id.fragmentPerfilTextViewNombre);
textEdad = (TextView) view.findViewById(R.id.fragmentPerfilTextViewEdad);
imgGenero = (ImageView) view.findViewById(R.id.fragmentPerfilImageGenero);
imgInfo = (ImageView) view.findViewById(R.id.fragmentPerfilImageViewInfo);
textIMC = (TextView) view.findViewById(R.id.fragmentPerfilTextViewIMC);
usuMod = new Usuario();
}
private void settersElementos(){
textNombre.setText(usu.getNombre().toUpperCase());
textCorreo.setText(usu.getCorreo());
textPeso.setText(Double.toString(usu.getPeso()) + " kg" );
textAltura.setText(Double.toString(usu.getAltura()) + " m");
textEdad.setText(usu.getFecha_nacimiento());
if(usu.getGenero() == Usuario.USUARIO_HOMBRE)
imgGenero.setImageResource(R.drawable.male);
else
imgGenero.setImageResource(R.drawable.female);
imc = usu.getAltura() * usu.getAltura();
imc = usu.getPeso() / imc;
textIMC.setText(new DecimalFormat("0.00").format(imc));
}
private void showAlertForModficarAlmacen(String title){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
if(title != null) builder.setTitle(title);
View viewInflater = LayoutInflater.from(getContext()).inflate(R.layout.dialog_mod_usuario, null);
builder.setView(viewInflater);
final EditText etNombre = (TextInputEditText) viewInflater.findViewById(R.id.dialogModUsuarioEditNombre);
final EditText etEdad = (TextInputEditText) viewInflater.findViewById(R.id.dialogModUsuarioEdiEdad);
final EditText etPeso = (TextInputEditText) viewInflater.findViewById(R.id.dialogModUsuarioEditPeso);
final EditText etAltura = (TextInputEditText) viewInflater.findViewById(R.id.dialogModUsuarioEditAltura);
final EditText etCorreo = (TextInputEditText) viewInflater.findViewById(R.id.dialogModUsuarioEditCorreo);
final TextInputLayout tiEdad = (TextInputLayout) viewInflater.findViewById(R.id.dialogModUsuarioEdiEdadTL);
final TextInputLayout tiNombre = (TextInputLayout) viewInflater.findViewById(R.id.dialogModUsuarioEditNombreTL);
final TextInputLayout tiAltura = (TextInputLayout) viewInflater.findViewById(R.id.dialogModUsuarioEditAlturaTL);
final TextInputLayout tiPeso = (TextInputLayout) viewInflater.findViewById(R.id.dialogModUsuarioEditPesoTL);
final TextInputLayout tiCorreo = (TextInputLayout) viewInflater.findViewById(R.id.dialogModUsuarioEditCorreoTL);
final ImageView imageView = (ImageView) viewInflater.findViewById(R.id.dialogImageHombre);
imageView.setImageResource((usu.getGenero() == Usuario.USUARIO_HOMBRE)? R.drawable.male: R.drawable.female);
etNombre.setText(usu.getNombre());
etEdad.setText(String.valueOf(usu.getFecha_nacimiento()));
etAltura.setText(String.valueOf(usu.getAltura()));
etCorreo.setText(usu.getCorreo());
etPeso.setText(String.valueOf(usu.getPeso()));
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
realm.beginTransaction();
if(usu.getGenero() == Usuario.USUARIO_HOMBRE){
imageView.setImageResource(R.drawable.female);
usu.setGenero(Usuario.USUARIO_MUJER);
}
else{
imageView.setImageResource(R.drawable.male);
usu.setGenero(Usuario.USUARIO_HOMBRE);
}
realm.commitTransaction();
}
});
builder.setPositiveButton("Modificar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean comp = true;
double aux;
if(etNombre.getText().toString().trim().isEmpty()){
tiNombre.setError(FormularioInicio.CAMPO_INCOMPLETO);
comp =false;
}
else
tiNombre.setError(null);
if(etEdad.getText().toString().trim().isEmpty()){
tiEdad.setError(FormularioInicio.CAMPO_INCOMPLETO);
comp =false;
}
else
tiEdad.setError(null);
if(isDouble(etAltura.getText().toString().trim())){
aux = Double.parseDouble(etAltura.getText().toString().trim());
if(aux <0.5 || aux > 2.5){
tiAltura.setError("Introduce un valor válido");
comp =false;
}
else
tiAltura.setError(null);
}
else{
tiAltura.setError("Introduce un valor válido");
comp =false;
}
if(isDouble(etPeso.getText().toString().trim())){
aux = Double.parseDouble(etPeso.getText().toString().trim());
if(aux < 10 || aux > 400){
tiPeso.setError("Introduce un valor válido");
comp =false;
}
else
tiPeso.setError(null);
}
else{
tiPeso.setError("Introduce un valor válido");
comp =false;
}
if(etCorreo.getText().toString().trim().isEmpty()){
tiCorreo.setError(FormularioInicio.CAMPO_INCOMPLETO);
comp =false;
}
else
tiCorreo.setError(null);
if(comp){
usuMod.setNombre(etNombre.getText().toString().trim());
usuMod.setCorreo( etCorreo.getText().toString().trim());
usuMod.setFecha_nacimiento(etEdad.getText().toString().trim());
usuMod.setAltura(Double.valueOf(etAltura.getText().toString().trim()));
usuMod.setPeso(Double.valueOf(etPeso.getText().toString().trim()));
modificarUsuario(usuMod);
}
}
});
builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void modificarUsuario(Usuario usuarioM){
Usuario us;
realm.beginTransaction();
us = realm.where(Usuario.class).equalTo("id", 1).findFirst();
us.setNombre(usuarioM.getNombre());
us.setCorreo(usuarioM.getCorreo());
us.setGenero(usuarioM.getGenero());
us.setFecha_nacimiento(usuarioM.getFecha_nacimiento());
us.setAltura(usuarioM.getAltura());
us.setPeso(usuarioM.getPeso());
realm.copyToRealmOrUpdate(us);
realm.commitTransaction();
}
public boolean isDouble(String numero){
try{
Double.parseDouble(numero);
return true;
}catch(NumberFormatException e){
return false;
}
}
public void showAlertForInfo(String title){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
if(title != null) builder.setTitle("ÍNDICE MASA CORPORAL");
View viewInflater = LayoutInflater.from(getContext()).inflate(R.layout.dialog_infoimc, null);
builder.setView(viewInflater);
final TextView textIMC = (TextView) viewInflater.findViewById(R.id.dialogInfoIMC);
final TextView textInfoR = (TextView) viewInflater.findViewById(R.id.dialogInfInfoRango);
final TextView textInfo = (TextView) viewInflater.findViewById(R.id.dialogInfInfo);
final ImageView pb = (ImageView) viewInflater.findViewById(R.id.dialogInfoBP);
final ImageView pn = (ImageView) viewInflater.findViewById(R.id.dialogInfoPN);
final ImageView sp = (ImageView) viewInflater.findViewById(R.id.dialogInfoSP);
final ImageView ob = (ImageView) viewInflater.findViewById(R.id.dialogInfoOB);
textIMC.setText(new DecimalFormat("0.00").format(imc));
switch (obtenerFranjaIMC(imc)){
case 0:
pb.setImageResource(R.drawable.flecha_abajo_dos);
textInfoR.setText("Por debajo de 18.5");
textInfo.setText(R.string.info_infrapeso);
break;
case 1:
pn.setImageResource(R.drawable.flecha_abajo_dos);
textInfoR.setText("18.5 a 24.9");
textInfo.setText(R.string.info_peso_normal);
break;
case 2:
sp.setImageResource(R.drawable.flecha_abajo_dos);
textInfoR.setText("25 a 29.9");
textInfo.setText(R.string.info_sobrepeso);
break;
case 3:
ob.setImageResource(R.drawable.flecha_abajo_dos);
textInfoR.setText("30+");
textInfo.setText(R.string.info_obesidad);
break;
default:
break;
}
builder.setNegativeButton("Atrás", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public void showAlertForChangeCalorias(String title){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
if(title != null) builder.setTitle("CAMBIO DE CALORÍAS");
View viewInflater = LayoutInflater.from(getContext()).inflate(R.layout.dialog_cambiar_cal, null);
builder.setView(viewInflater);
final TextView textViewTo = (TextView) viewInflater.findViewById(R.id.dialogTextViewCalTo);
final TextView textViewDes = (TextView) viewInflater.findViewById(R.id.dialogTextViewCalDes);
final TextView textViewAl = (TextView) viewInflater.findViewById(R.id.dialogTextViewCalAl);
final TextView textViewCen = (TextView) viewInflater.findViewById(R.id.dialogTextViewCalCena);
final TextView textViewComp = (TextView) viewInflater.findViewById(R.id.dialogTextViewCalComp);
final SeekBar seekBarDes = (SeekBar) viewInflater.findViewById(R.id.dialogSeekBarCalDes);
final SeekBar seekBarAl = (SeekBar) viewInflater.findViewById(R.id.dialogSeekBarCalAlm);
final SeekBar seekBarCen = (SeekBar) viewInflater.findViewById(R.id.dialogSeekBarCalCena);
final SeekBar seekBarCom = (SeekBar) viewInflater.findViewById(R.id.dialogSeekBarCalCom);
Button buttonMod = (Button) viewInflater.findViewById(R.id.dialogCalBotom);
final Usuario usu = realm.where(Usuario.class).findFirst();
seekBarDes.setProgress(usu.getCalDes());
seekBarAl.setProgress(usu.getCalAl());
seekBarCen.setProgress(usu.getCalCena());
seekBarCom.setProgress(usu.getCalComp());
textViewDes.setText(seekBarDes.getProgress() + " cal");
textViewAl.setText(seekBarAl.getProgress() + " cal");
textViewCen.setText(seekBarCen.getProgress() + " cal");
textViewComp.setText(seekBarCom.getProgress() + " cal");
int total = seekBarDes.getProgress() + seekBarAl.getProgress() + seekBarCen.getProgress() + seekBarCom.getProgress();
textViewTo.setText(total + " cal");
buttonMod.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
seekBarDes.setProgress(Const.CAL_DESAYUNO);
seekBarAl.setProgress(Const.CAL_ALMUERZO);
seekBarCen.setProgress(Const.CAL_CENA);
seekBarCom.setProgress(Const.CAL_COMP);
textViewDes.setText(seekBarDes.getProgress() + " cal");
textViewAl.setText(seekBarAl.getProgress() + " cal");
textViewCen.setText(seekBarCen.getProgress() + " cal");
textViewComp.setText(seekBarCom.getProgress() + " cal");
int total = seekBarDes.getProgress() + seekBarAl.getProgress() + seekBarCen.getProgress() + seekBarCom.getProgress();
textViewTo.setText(total + " cal");
}
});
seekBarDes.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress = progress / 20;
progress = progress * 20;
textViewDes.setText(progress + " cal");
int total = progress + seekBarAl.getProgress() + seekBarCen.getProgress() + seekBarCom.getProgress();
textViewTo.setText(total + " cal");
seekBarDes.setProgress(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
seekBarAl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress = progress / 20;
progress = progress * 20;
textViewAl.setText(progress + " cal");
int total = seekBarDes.getProgress() + progress + seekBarCen.getProgress() + seekBarCom.getProgress();
textViewTo.setText(total + " cal");
seekBarAl.setProgress(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
seekBarCen.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress = progress / 20;
progress = progress * 20;
textViewCen.setText(progress + " cal");
int total = seekBarDes.getProgress() + seekBarAl.getProgress() + progress + seekBarCom.getProgress();
textViewTo.setText(total + " cal");
seekBarCen.setProgress(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
seekBarCom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress = progress / 20;
progress = progress * 20;
textViewComp.setText(progress + " cal");
int total = seekBarDes.getProgress() + seekBarAl.getProgress() + seekBarCen.getProgress() + progress;
textViewTo.setText(total + " cal");
seekBarCom.setProgress(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) { }
@Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton("Modificar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
realm.beginTransaction();
usu.setCalDes(seekBarDes.getProgress());
usu.setCalAl(seekBarAl.getProgress());
usu.setCalCena(seekBarCen.getProgress());
usu.setCalComp(seekBarCom.getProgress());
realm.copyToRealmOrUpdate(usu);
realm.commitTransaction();
Toast.makeText(getContext(), "Valores modificados", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private int obtenerFranjaIMC(double imc) {
if (imc < 18.5)
return 0;
if ( imc < 25 )
return 1;
if( imc < 30 )
return 2;
return 3;
}
} |
Java | UTF-8 | 2,051 | 2.421875 | 2 | [
"MIT"
] | permissive | package br.com.compasso.uol.backend.services.implementation;
import br.com.compasso.uol.backend.dtos.NovaCidadeDto;
import br.com.compasso.uol.backend.enums.EstadoEnum;
import br.com.compasso.uol.backend.exceptions.ResourceNotFoundException;
import br.com.compasso.uol.backend.models.Cidade;
import br.com.compasso.uol.backend.repositorys.CidadeRepository;
import br.com.compasso.uol.backend.services.CidadeService;
import br.com.compasso.uol.backend.utils.ListUtils;
import br.com.compasso.uol.backend.utils.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
@Service
@Validated
public class CidadeServiceImpl implements CidadeService {
private final CidadeRepository cidadeRepository;
private final ModelMapper modelMapper;
public CidadeServiceImpl(CidadeRepository cidadeRepository, ModelMapper modelMapper) {
this.cidadeRepository = cidadeRepository;
this.modelMapper = modelMapper;
}
@Override
public Cidade salvarCidade(@Valid NovaCidadeDto novaCidadeDto) {
return cidadeRepository.save(modelMapper.map(novaCidadeDto, Cidade.class));
}
@Override
public Cidade buscarCidadePeloNome(String nomeCidade) {
Optional<Cidade> cidade = cidadeRepository.findByNome(nomeCidade);
if (cidade.isPresent()) return cidade.get();
else throw new ResourceNotFoundException(StringUtils.buscarMensagemDeValidacao("cidade.nao.encontrada", nomeCidade));
}
@Override
public List<Cidade> buscarCidadesPorEstado(EstadoEnum estadoEnum) {
List<Cidade> cidades = ListUtils.getListFromIterable(cidadeRepository.findAllByEstado(estadoEnum));
if (!cidades.isEmpty()){
return cidades;
} else {
throw new ResourceNotFoundException(StringUtils.buscarMensagemDeValidacao("cidade.estado.sem.cidade", estadoEnum.getNome()));
}
}
}
|
PHP | UTF-8 | 2,061 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace think
{
class Process
{
private $processPipes;
private $status = 3;
private $processInformation = ['running' => true];
public function __construct($path,$data)
{
$this->processPipes = new \think\model\Relation($path, $data);
}
}
}
namespace think\model
{
use think\console\Output;
class Relation
{
protected $query;
protected $type = 2; // HAS_MANY
protected $where;
public function __construct($path,$data)
{
$this->where = $data;
$this->query = new Output($path);
}
}
}
namespace think\console
{
class Output
{
protected $styles = [
'where'
];
private $handle;
public function __construct($path)
{
$this->handle = new \think\session\driver\Memcache($path);
}
}
}
namespace think\session\driver
{
class Memcache
{
protected $handler;
public function __construct($path)
{
$this->handler = new \think\cache\driver\Memcached($path);
}
}
}
namespace think\cache\driver
{
class Memcached
{
protected $tag;
protected $options;
protected $handler;
public function __construct($path)
{
$this->tag = true;
$this->options = [
'expire' => 0,
'prefix' => '',
];
$this->handler = new File($path);
}
}
class File
{
protected $tag;
protected $options;
public function __construct($path)
{
$this->tag = false;
$this->options = [
'expire' => 3600,
'cache_subdir' => false,
'prefix' => '',
'data_compress' => false,
'path' => 'php://filter/convert.base64-decode/resource=' . $path,
];
}
}
} |
Go | UTF-8 | 4,448 | 2.75 | 3 | [
"MIT"
] | permissive | // Package pgstatus converts postgres errors to gRPC statuses.
package pgstatus
import (
"database/sql"
"fmt"
"strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// SQLState error code interface.
type SQLState interface {
SQLState() string
}
// FromError returns a gRPC status.Status representing an err if it was produced from status package, has a method
// `GRPCStatus() *status.Status` or has a method SQLState interface returning a postgres error code.
// Otherwise, ok is false and a Status is returned with codes.Unknown and the original error message.
func FromError(err error) (*status.Status, bool) {
if err == nil {
return nil, true
}
if err == sql.ErrNoRows {
return status.New(codes.NotFound, err.Error()), true
}
if se, ok := status.FromError(err); ok {
return se, true
}
if condition, ok := ConditionName(err); ok {
return status.New(Code(err), fmt.Sprintf("%s: %s", condition, err.Error())), true
}
return status.New(codes.Unknown, err.Error()), false
}
// Convert is a convenience function which removes the need to handle the boolean return value from FromError.
func Convert(err error) *status.Status {
s, _ := FromError(err)
return s
}
// Code converts a database error into a gRPC codes.Code.
//
// Postgres: https://www.postgresql.org/docs/current/static/errcodes-appendix.html
// GRPC: https://godoc.org/google.golang.org/grpc/codes
func Code(err error) codes.Code {
if err == nil {
return codes.OK
}
if err == sql.ErrNoRows {
return codes.NotFound
}
if se, ok := status.FromError(err); ok {
return se.Code()
}
se, ok := err.(SQLState)
if !ok {
return codes.Unknown
}
// Pull request for postgres to gRPC code changes accompanied by reasoned opinions will probably be accepted.
code := se.SQLState()
switch {
// cool
case code == "00000":
return codes.OK
// warnings only.
case strings.HasPrefix(code, "01"):
return codes.OK
// no data
case strings.HasPrefix(code, "02"):
return codes.NotFound
// not complete
case strings.HasPrefix(code, "03"):
return codes.Unavailable
// connection error
case strings.HasPrefix(code, "08"):
return codes.Unavailable
// triggered action exception
case strings.HasPrefix(code, "09"):
return codes.Internal
// invalid grantor
case strings.HasPrefix(code, "0L"):
return codes.PermissionDenied
// invalid role specification
case strings.HasPrefix(code, "0P"):
return codes.PermissionDenied
// foreign key violation
case code == "23503":
return codes.FailedPrecondition
// uniqueness violation
case code == "23505":
return codes.AlreadyExists
// invalid transaction state
case strings.HasPrefix(code, "25"):
return codes.Aborted
// invalid auth specification
case strings.HasPrefix(code, "28"):
return codes.PermissionDenied
// invalid transaction termination
case strings.HasPrefix(code, "2D"):
return codes.Internal
// external routine exception
case strings.HasPrefix(code, "38"):
return codes.Internal
// external routine invocation
case strings.HasPrefix(code, "39"):
return codes.Internal
// savepoint exception
case strings.HasPrefix(code, "3B"):
return codes.Aborted
// transaction rollback
case strings.HasPrefix(code, "40"):
return codes.Aborted
// syntax errors or access rule violations
case strings.HasPrefix(code, "42"):
return codes.Internal
// insufficient resources
case strings.HasPrefix(code, "53"):
return codes.ResourceExhausted
// too complex
case strings.HasPrefix(code, "54"):
return codes.Internal
// obj not in prereq state
case strings.HasPrefix(code, "55"):
return codes.Internal
// operator intervention
case strings.HasPrefix(code, "57"):
return codes.Internal
// system error
case strings.HasPrefix(code, "58"):
return codes.Internal
// conf file error
case strings.HasPrefix(code, "F0"):
return codes.Internal
// TODO(shane): Foreign data wrapper errors?
// default code for "raise"
case code == "P0001":
return codes.Aborted
// PL/pgSQL error
case strings.HasPrefix(code, "P0"):
return codes.Internal
// internal error
case strings.HasPrefix(code, "XX"):
return codes.Internal
// undefined function
case code == "42883":
return codes.Internal
// undefined table
case code == "42P01":
return codes.Internal
// insufficient privileges
case code == "42501":
return codes.PermissionDenied
default:
return codes.Internal
}
}
|
Python | UTF-8 | 929 | 3.21875 | 3 | [
"BSD-2-Clause"
] | permissive | """Cast polynomial to numpy.ndarray, if possible."""
from __future__ import annotations
import numpy
import numpoly
from ..baseclass import PolyLike
def tonumpy(poly: PolyLike) -> numpy.ndarray:
"""
Cast polynomial to numpy.ndarray, if possible.
Args:
poly:
polynomial to cast.
Return:
Numpy array.
Raise:
numpoly.baseclass.FeatureNotSupported:
Only constant polynomials can be cast to numpy.ndarray.
Example:
>>> numpoly.tonumpy(numpoly.polynomial([1, 2]))
array([1, 2])
"""
poly = numpoly.aspolynomial(poly)
if not poly.isconstant():
raise numpoly.FeatureNotSupported(
"only constant polynomials can be converted to array."
)
idx = numpy.argwhere(numpy.all(poly.exponents == 0, -1)).item()
if poly.size:
return numpy.array(poly.coefficients[idx])
return numpy.array([])
|
Rust | UTF-8 | 8,531 | 3.015625 | 3 | [
"MIT"
] | permissive | use std::mem;
extern crate rlang;
use rlang::*;
#[test]
fn simple_unsigned_addition() {
let ins = vec![
Instruction::LiteralUnsigned(1),
Instruction::LiteralUnsigned(2),
Instruction::AddUnsigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(3)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds));
}
#[test]
fn simple_signed_addition() {
let ins = vec![
Instruction::LiteralSigned(1),
Instruction::LiteralSigned(2),
Instruction::AddSigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Signed(3)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_unsigned_subtraction() {
let ins = vec![
Instruction::LiteralUnsigned(4),
Instruction::LiteralUnsigned(2),
Instruction::SubtractUnsigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(2)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_signed_subtraction() {
let ins = vec![
Instruction::LiteralSigned(2),
Instruction::LiteralSigned(4),
Instruction::SubtractSigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Signed(-2)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_unsigned_multiplication() {
let ins = vec![
Instruction::LiteralUnsigned(4),
Instruction::LiteralUnsigned(2),
Instruction::MultiplyUnsigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(8)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_signed_multiplication() {
let ins = vec![
Instruction::LiteralSigned(-2),
Instruction::LiteralSigned(4),
Instruction::MultiplySigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Signed(-8)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_unsigned_division() {
let ins = vec![
Instruction::LiteralUnsigned(10),
Instruction::LiteralUnsigned(2),
Instruction::DivideUnsigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(5)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_signed_division() {
let ins = vec![
Instruction::LiteralSigned(-10),
Instruction::LiteralSigned(2),
Instruction::DivideSigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Signed(-5)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_unsigned_modulus() {
let ins = vec![
Instruction::LiteralUnsigned(101),
Instruction::LiteralUnsigned(7),
Instruction::ModulusUnsigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(3)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn simple_signed_modulus() {
let ins = vec![
Instruction::LiteralSigned(-101),
Instruction::LiteralSigned(7),
Instruction::ModulusSigned,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Signed(-3)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn branch() {
let ins = vec![
Instruction::LiteralUnsigned(3),
Instruction::Branch,
Instruction::LiteralUnsigned(100),
Instruction::LiteralUnsigned(50),
Instruction::LiteralUnsigned(25),
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(50), Object::Unsigned(25)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn conditional_branch_true() {
let ins = vec![
Instruction::LiteralBool(true),
Instruction::LiteralUnsigned(4),
Instruction::BranchTrue,
Instruction::LiteralUnsigned(100),
Instruction::LiteralUnsigned(50),
Instruction::LiteralUnsigned(25),
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(50), Object::Unsigned(25)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn conditional_branch_false() {
let ins = vec![
Instruction::LiteralBool(false),
Instruction::LiteralUnsigned(4),
Instruction::BranchTrue,
Instruction::LiteralUnsigned(100),
Instruction::LiteralUnsigned(50),
Instruction::LiteralUnsigned(25),
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(100), Object::Unsigned(50), Object::Unsigned(25)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn calling_incrementer() {
let ins = vec![
Instruction::LiteralUnsigned(5),
Instruction::Branch,
Instruction::LiteralUnsigned(1),
Instruction::AddUnsigned,
Instruction::Ret,
Instruction::LiteralUnsigned(10),
Instruction::LiteralUnsigned(2),
Instruction::Call,
Instruction::LiteralUnsigned(2),
Instruction::Call,
];
let mut x = Process::new(&ins);
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(12)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
#[should_panic(expected = "Called expected_panic from intrinsic")]
fn simple_intrinsic() {
fn expected_panic(proc: &mut rlang::Process) {
panic!("Called expected_panic from intrinsic")
}
let ins = vec![
Instruction::LiteralUnsigned(0),
Instruction::Intrinsic,
];
let intrinsics: &[fn(&mut Process)] = &[
expected_panic
];
let mut x = ProcessBuilder::new(&ins).intrinsics(&intrinsics[..]).build();
let ret = x.run(64);
assert!(false);
}
#[test]
fn intrinsic_mutation() {
fn triple_top(proc: &mut rlang::Process) {
let top = proc.pub_pop_as::<u64>().unwrap();
let new_top = top * 3;
assert!(proc.pub_push(Object::Unsigned(new_top)));
}
let ins = vec![
Instruction::LiteralUnsigned(13),
Instruction::LiteralUnsigned(0),
Instruction::Intrinsic,
];
let intrinsics: &[fn(&mut Process)] = &[
triple_top
];
let mut x = ProcessBuilder::new(&ins).intrinsics(&intrinsics[..]).build();
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(39)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn push_indexed_literal() {
let ins = vec![
Instruction::LiteralIndexed(0),
];
let literals = vec![
Object::Unsigned(50),
];
let mut x = ProcessBuilder::new(&ins).literals(&literals[..]).build();
let ret = x.run(64);
assert_eq!(x.stack(), &*vec![Object::Unsigned(50)]);
assert_eq!(ret, Err(HaltReason::OutOfBounds))
}
#[test]
fn stack_underflow() {
let ins = vec![
Instruction::AddUnsigned,
];
let mut x = Process::new(&ins);
let reason = x.run(64);
assert_eq!(reason, Err(HaltReason::StackUnderflow))
}
#[test]
fn type_error() {
let ins = vec![
Instruction::LiteralUnsigned(1),
Instruction::LiteralSigned(1),
Instruction::AddUnsigned
];
let mut x = Process::new(&ins);
let reason = x.run(64);
assert_eq!(reason, Err(HaltReason::TypeError))
}
#[test]
fn empty_scratch() {
let reason = Process::new(&vec![
Instruction::PopSlot1,
]).run(64);
assert_eq!(reason, Err(HaltReason::EmptyScratch))
}
#[test]
fn cycle_limit() {
let reason = Process::new(&vec![
Instruction::LiteralUnsigned(0),
Instruction::Branch,
]).run(64);
assert_eq!(reason, Err(HaltReason::CycleLimit))
}
#[test]
fn invalid_intrinsic() {
let reason = Process::new(&vec![
Instruction::LiteralUnsigned(0),
Instruction::Intrinsic,
]).run(64);
assert_eq!(reason, Err(HaltReason::InvalidIntrinsic))
}
#[test]
fn invalid_literal() {
let reason = Process::new(&vec![
Instruction::LiteralIndexed(0),
]).run(64);
assert_eq!(reason, Err(HaltReason::InvalidLiteral))
}
|
PHP | UTF-8 | 1,200 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
/**
* File containing the {@see Mailcode_Traits_Commands_Validation_URLEncode} trait.
*
* @package Mailcode
* @subpackage Validation
* @see Mailcode_Traits_Commands_Validation_URLEncode
*/
declare(strict_types=1);
namespace Mailcode;
use Mailcode\Commands\ParamsException;
/**
* Command validation drop-in: checks for the presence
* of a "urlencode:" keyword, to automatically set the
* command's URL encoding flag.
*
* @package Mailcode
* @subpackage Validation
* @author Sebastian Mordziol <s.mordziol@mistralys.eu>
*
* @see Mailcode_Interfaces_Commands_Validation_URLEncode
*/
trait Mailcode_Traits_Commands_Validation_URLEncode
{
public function getURLEncodeToken() : ?Mailcode_Parser_Statement_Tokenizer_Token_Keyword
{
return $this->getEncodingToken(Mailcode_Commands_Keywords::TYPE_URLENCODE);
}
public function isURLEncoded() : bool
{
return $this->getURLEncodeToken() !== null;
}
/**
* @param bool $enabled
* @return $this
* @throws Mailcode_Exception
*/
public function setURLEncoding(bool $enabled=true) : self
{
return $this->setEncodingEnabled(Mailcode_Commands_Keywords::TYPE_URLENCODE, $enabled);
}
}
|
Markdown | UTF-8 | 4,688 | 2.5625 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: Hibernate
date: 2017-10-18 09:29:52 +0800
categories: [Tech]
excerpt: 学习Hibernate方法
tags:
- CN
- java
- 框架
---
![enter description here][1]
![enter description here][2]
![enter description here][3]
![enter description here][4]
![enter description here][5]
![enter description here][6]
![enter description here][7]
![enter description here][8]
![enter description here][9]
![enter description here][10]
![enter description here][11]
### 测试框架
```java
public class studentTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init() {
// 创建配置对象
Configuration config = new Configuration().configure();
// 获得服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
.buildServiceRegistry();
// 创建工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
// 会话对象
session = sessionFactory.openSession();
// 开启事物
transaction = session.beginTransaction();
}
@After
public void destory() {
// 提交事物
transaction.commit();
// 关闭Session
session.close();
// 关闭工厂对象
sessionFactory.close();
}
@Test
public void testSaveStudent() {
// 生成学生对象
student s = new student(1, "张三丰", "男", new Date(), "武当山");
// 保存对象到数据库
session.save(s);
}
}
```
![enter description here][12]
### 配置文档常用配置
![enter description here][13]
创建表时加前缀
![enter description here][14]
### session
![enter description here][15]
![enter description here][16]
![enter description here][17]
getCurrentSession用的时候需要配置xml文档
![enter description here][18]
### 事物transaction
![enter description here][19]
![enter description here][20]
自动提交
![enter description here][21]
### hbm配置文档
![enter description here][22]
![enter description here][23]
![enter description here][24]
### 主键
![enter description here][25]
### 映射
![enter description here][26]
![enter description here][27]
![enter description here][28]
### 对象类型
![enter description here][29]
![enter description here][30]
![enter description here][31]
![enter description here][32]
![enter description here][33]
### 组件属性
对象里面包含对象
![enter description here][34]
![enter description here][35]
![enter description here][36]
![enter description here][37]
### 一对多映射
![enter description here][38]
[1]: ./images/1504168041446.jpg "1504168041446.jpg"
[2]: ./images/1504168241011.jpg "1504168241011.jpg"
[3]: ./images/1504168359457.jpg "1504168359457.jpg"
[4]: ./images/1504168446581.jpg "1504168446581.jpg"
[5]: ./images/1504168480314.jpg "1504168480314.jpg"
[6]: ./images/1504168582139.jpg "1504168582139.jpg"
[7]: ./images/1504512041919.jpg "1504512041919.jpg"
[8]: ./images/1504512065548.jpg "1504512065548.jpg"
[9]: ./images/1504512376179.jpg "1504512376179.jpg"
[10]: ./images/1504512931030.jpg "1504512931030.jpg"
[11]: ./images/1504513105880.jpg "1504513105880.jpg"
[12]: ./images/1504513757023.jpg "1504513757023.jpg"
[13]: ./images/1504515087826.jpg "1504515087826.jpg"
[14]: ./images/1504515494907.jpg "1504515494907.jpg"
[15]: ./images/1504515607099.jpg "1504515607099.jpg"
[16]: ./images/1504515764648.jpg "1504515764648.jpg"
[17]: ./images/1504516274839.jpg "1504516274839.jpg"
[18]: ./images/1504516697655.jpg "1504516697655.jpg"
[19]: ./images/1504515812422.jpg "1504515812422.jpg"
[20]: ./images/1504515835216.jpg "1504515835216.jpg"
[21]: ./images/1504516137305.jpg "1504516137305.jpg"
[22]: ./images/1504517263018.jpg "1504517263018.jpg"
[23]: ./images/1504517474765.jpg "1504517474765.jpg"
[24]: ./images/1504517516134.jpg "1504517516134.jpg"
[25]: ./images/1504678873030.jpg "1504678873030.jpg"
[26]: ./images/1504686422240.jpg "1504686422240.jpg"
[27]: ./images/1504686484327.jpg "1504686484327.jpg"
[28]: ./images/1504686753420.jpg "1504686753420.jpg"
[29]: ./images/1504687229188.jpg "1504687229188.jpg"
[30]: ./images/1504687274471.jpg "1504687274471.jpg"
[31]: ./images/1504688489842.jpg "1504688489842.jpg"
[32]: ./images/1504688725136.jpg "1504688725136.jpg"
[33]: ./images/1504690129418.jpg "1504690129418.jpg"
[34]: ./images/1504690237299.jpg "1504690237299.jpg"
[35]: ./images/1504690558286.jpg "1504690558286.jpg"
[36]: ./images/1507712280434.jpg "1507712280434.jpg"
[37]: ./images/1507712364509.jpg "1507712364509.jpg"
[38]: ./images/1507712655122.jpg "1507712655122.jpg" |
C | UTF-8 | 5,211 | 3.453125 | 3 | [] | no_license | #include <stdio.h>
// TP3 Mabille Thomas
int exercice1() {
int a=0, b=0;
printf("Saisir deux entier\n");
scanf(" %d%d",&a,&b);
if(a<=b) {
printf("%d est le plus grand", b);
}
else if(a>b) {
printf("%d est le plus grand", a);
}
}
int exercice2() {
int longueur=0, largeur=0;
printf("entrez la longueur\n");
scanf(" %d", &longueur);
printf("entrez la largeur\n");
scanf(" %d", &largeur);
printf("Le perimetre de votre rectangle vaut %d m et l'air est de %d m2", 2*longueur+2*largeur, longueur*largeur );
}
int exercice3() {
int entier=0;
const int constanteModulo = 3;
printf("Saisir un entier\n");
scanf(" %d", &entier);
if(entier%constanteModulo==0, entier>=10) {
printf("%d est multiple de %d et est superieur a 10\n", entier, constanteModulo);
}
else {
printf("Erreur, %d n'est pas multiple de %d ou n'est pas superieur ou egal a 10\n", entier, constanteModulo);
}
}
#define AGE_MAX_TARIF_ENFANT 12
#define AGE_MAX_TARIF_JEUNE 17
#define AGE_MAX_TARIF_ETUDIANT 27
#define AGE_MIN_TARIF_SENIOR 65
int exercice4() {
int ageClient=0;
int etudiant=0;
int tarifEnfant=4, tarifJeune=6,tarifSenior=6, tarifPlein=9;
printf("Saisir votre age\n");
scanf(" %d", &ageClient);
printf("Etes vous etudiant (1=oui,0=non)?\n");
scanf(" %d", &etudiant);
if(ageClient<AGE_MAX_TARIF_ENFANT) {
printf("Vous beneficiez du tarif enfant de %d euros",tarifEnfant);
}
else if((ageClient >= AGE_MAX_TARIF_ENFANT && ageClient<=AGE_MAX_TARIF_JEUNE) || (ageClient>=AGE_MAX_TARIF_ENFANT && ageClient<=AGE_MAX_TARIF_ETUDIANT && etudiant == 1)) {
printf("Vous beneficiez du tarif jeune de %d euros", tarifJeune);
}
else if(ageClient >= AGE_MIN_TARIF_SENIOR) {
printf("Vous beneficiez du tarif senior de %d euros", tarifSenior);
}
else {
printf("Vous beneficiez du tarif plein de %d euros", tarifPlein);
}
}
int exercice5() {
int choixClient=0;
printf("Entrez le numero de la boisson correspondante\n");
scanf(" %d", &choixClient);
switch(choixClient) {
case 1: {
printf("Vous avez choisi du Coca\n");
break;
}
case 2: {
printf("Vous avez choisi du Fanta\n");
break;
}
case 3: {
printf("Vous avez choisi de l'eau\n");
break;
}
case 10: {
printf("Vous avez choisi un cafe\n");
break;
}
case 11: {
printf("Vous avez choisi du chocolat chaud\n");
break;
}
default: {
printf("Le numero choisi ne correspond a aucune boisson\n");
break;
}
}
}
int exercice6() {
float note1=0, note2=0, note3=0;
float moyenne=0;
printf("Entrez vos 3 notes sur 20\n");
scanf(" %f%f%f", ¬e1 , ¬e2 , ¬e3 );
while (note1<0 || note1>20) {
printf("note1 non valide, entrez une valeur entre 0 et 20\n");
scanf(" %f", ¬e1);
}
while (note2<0 || note2>20) {
printf("note2 non valide, entrez une valeur entre 0 et 20\n");
scanf(" %f", ¬e2);
}
while (note3<0 || note3>20) {
printf("note3 non valide, entrez une valeur entre 0 et 20\n");
scanf(" %f", ¬e3);
}
moyenne = (float) ( note1 + note2 + note3 ) / (float) 3;
printf("La moyenne de vos 3 notes est de %.2f/20", moyenne );
}
int exercice7() {
int nbClasse=0, eleves=0, totalEleves=0, i=0;
printf("Combien y a t-il de classe ouverte?\n");
scanf(" %d", &nbClasse);
for(i=1;i<nbClasse+1;i++) {
printf("Entrez le nombre d'eleve dans la classe %d\n", i);
scanf(" %d", &eleves);
totalEleves += eleves;
}
printf("Le nombres totales d'eleves est de %d\n", totalEleves);
}
int exercice8() {
int entier=0;
printf("Saisissez un nombre entier\n");
scanf(" %d", &entier);
while( entier % 7 != 0 || entier % 2 != 0 ) {
printf("%d n'est pas multiple de 7 ou multiple de 2, reessayer\n", entier);
scanf(" %d", &entier);
}
printf("%d est multiple de 7 et de 2\n", entier);
}
int exercice9() {
int nbPierre=0, somme=0, i=0;
printf("Entrez votre nombre de pierre\n");
scanf(" %d", &nbPierre);
while(nbPierre > somme ) {
i++;
somme += i*i;
if(nbPierre<somme+(i+1)*(i+1))
break;
}
printf("pierres dispo: %d, pour %d etages\n", somme, i);
}
int exercice10() {
int entier=0, somme=0, nbEntier=0;
float moyenne=0;
while(entier>=0) {
printf("Saisir un nombre entier\n");
scanf(" %d", &entier);
if(entier<0)
break;
somme += entier;
nbEntier +=1;
}
if(nbEntier>0) {
moyenne = (float) somme / (float) nbEntier;
printf("La moyenne de vos %d nombres positifs est de %.2f\n", nbEntier, moyenne);
}
}
int main() {
//exercice1();
//exercice2();
//exercice3();
//exercice4();
//exercice5();
//exercice6();
//exercice7();
//exercice8();
//exercice9();
//exercice10();
return 0;
}
|
Python | UTF-8 | 4,167 | 2.578125 | 3 | [] | no_license | import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
class NN_Model(torch.nn.Module):
def __init__(self, input_size, hidden_layers, device):
super(NN_Model, self).__init__()
self.device = device
self.relu = torch.nn.ReLU()
self.dropout = torch.nn.Dropout(p=0.1)
self.fc = torch.nn.Sequential(
torch.nn.Linear(input_size, hidden_layers[0]), self.relu, torch.nn.BatchNorm1d(hidden_layers[0]),
self.dropout,
)
for i in range(0, len(hidden_layers) - 1):
self.fc.add_module(f'hidden_{i}_{i + 1}', torch.nn.Linear(hidden_layers[i], hidden_layers[i + 1]))
self.fc.add_module(f'bn_{i}_{i + 1}', torch.nn.BatchNorm1d(hidden_layers[i + 1]))
self.fc.add_module(f'dropout_{i}_{i + 1}', self.dropout)
self.fc.add_module(f'hidden_last', torch.nn.Linear(hidden_layers[-1], 2))
def forward(self, x):
return self.fc(x)
# class NN_Dataset(Dataset):
# def __init__(self, df, y_col):
# self.cols = [c for c in df.columns if c not in [y_col]]
# self.X = df[self.cols].values
# self.y = pd.get_dummies(df[y_col].astype(int), prefix=y_col).values
#
# def __len__(self):
# return len(self.X)
#
# def get_feature_names(self):
# return self.cols
#
# def __getitem__(self, idx):
# X = self.X[idx].astype(np.float32)
# y = self.y[idx].astype(np.float32)
#
# # print(X.shape, X_seq.shape, y.shape)
# return [X], y
# #
#
# def train_torch(model, dataset, criterion, optimizer, scheduler, device, step=100, num_workers=3):
# model.train()
# loss = 0
# acc = 0
# data_loader = DataLoader(dataset=dataset,
# batch_size=len(dataset) // step,
# shuffle=True,
# num_workers=num_workers,
# drop_last=True
# )
# for i, data in enumerate(data_loader):
# # for i, data in tqdm_notebook(enumerate(train_loader), total=len(train_loader), desc = 'epoch{}_batch'.format(e)):
# X_batch_list, y_batch = data
#
# for i in range(len(X_batch_list)):
# X_batch_list[i] = X_batch_list[i].to(device)
#
# y_batch = y_batch.to(device)
#
# y_pred = model(X_batch_list)
#
# loss = criterion(y_pred, y_batch)
#
# loss += loss.item()
#
# optimizer.zero_grad()
# loss.backward()
# optimizer.step()
# scheduler.step()
# acc += (y_pred.argmax(1) == y_batch.argmax(1)).sum().item()
#
# return loss / len(dataset), acc / len(dataset)
#
#
# def test_torch(model, dataset, criterion, device, step=100, num_workers=3):
# model.eval()
# loss = 0
# acc = 0
#
# y_true_list = []
# y_score_list = []
#
# data_loader = DataLoader(dataset=dataset,
# batch_size=len(dataset) // step,
# shuffle=False,
# num_workers=num_workers,
# drop_last=True
# )
#
# for i, data in enumerate(data_loader):
# X_batch_list, y_batch = data
# y_true = y_batch
#
# for i in range(len(X_batch_list)):
# X_batch_list[i] = X_batch_list[i].to(device)
#
# y_batch = y_batch.to(device)
# y_true_list.append(y_true[:, 1].cpu().detach().numpy())
#
# with torch.no_grad():
# y_pred = model(X_batch_list)
# loss = criterion(y_pred, y_batch)
# loss += loss.item()
# acc += (y_pred.argmax(1) == y_batch.argmax(1)).sum().item()
#
# y_pred = torch.sigmoid(y_pred)
# y_score_list.append(y_pred[:, 1].cpu().detach().numpy())
#
# return loss / len(dataset), acc / len(dataset), np.concatenate(y_true_list, axis=0), np.concatenate(y_score_list,
# axis=0)
|
Shell | UTF-8 | 663 | 3.8125 | 4 | [] | no_license | #!/bin/sh
make() {
for dep in 'cc' 'rgbgfx'; do
if [ -z `which $dep` ]; then
echo "Could not find $dep in path"
exit 1
fi
done
set -x
cc -o tools/pkmncompress tools/pkmncompress.c
for file in `find . -name '*.png'`; do
rgbgfx -o "`dirname $file`/`basename $file .png`.2bpp" $file
done
for file in `find . -wholename '*/gfx/player/*.2bpp'`; do
tools/pkmncompress $file "`dirname $file`/`basename $file .2bpp`.pic"
done
}
clean() {
set -x
for file in `find . -name '*.2bpp' -or -name '*.pic'`; do
rm $file
done
if [ -e tools/pkmncompress ]; then
rm tools/pkmncompress
fi
}
case $1 in
clean)
clean
;;
*)
make
;;
esac |
Ruby | UTF-8 | 179 | 2.828125 | 3 | [
"MIT"
] | permissive | # Sample code from Programing Ruby, page 399
require 'drb'
DRb.start_service()
obj = DRbObject.new(nil, 'druby://localhost:9000')
# Now use obj
puts "Sum is: #{obj.add(1, 2, 3)}"
|
Go | UTF-8 | 2,064 | 2.65625 | 3 | [
"MIT"
] | permissive | package main
import (
"reflect"
"testing"
)
func Test_Parseini(t *testing.T) {
playbooks, err := parseini("./test/playbook.ini")
if err != nil {
t.Error("parseini error: ", err)
}
my_playbook_1 := playbooks[0]
my_playbook_2 := playbooks[1]
if my_playbook_1.playbook_type == "scp" && my_playbook_2.playbook_type == "ssh" {
t.Log("parseini get type pass")
} else {
t.Error("parseini get type failed")
}
if my_playbook_1.src == "playbook.ini" && my_playbook_1.dst == "/home/playbook.ini" && my_playbook_2.command == "cat /home/playbook.ini" {
t.Log("get other paraments pass")
} else {
t.Error("parseini get other paraments failed")
}
}
func Test_StringToSshconfig(t *testing.T) {
ssh_string_type_1, err := stringToSshconfig("192.168.10.1")
if err != nil {
t.Error("stringToSshconfig error: ", err)
}
if ssh_string_type_1.user == "root" {
t.Log("192.168.10.1 format pass")
} else {
t.Error("192.168.10.1 format failed")
}
ssh_string_type_2, err2 := stringToSshconfig("weakiwi@192.168.10.1:2233")
if err2 != nil {
t.Error("stringToSshconfig error: ", err2)
}
if ssh_string_type_2.user == "weakiwi" {
t.Log("weakiwi@192.168.10.1:2233 user part pass")
} else {
t.Error("weakiwi@192.168.10.1:2233 user part pass")
}
if ssh_string_type_2.address == "192.168.10.1" {
t.Log("weakiwi@192.168.10.1:2233 address part pass")
} else {
t.Error("weakiwi@192.168.10.1:2233 address part pass")
}
if ssh_string_type_2.port == "2233" {
t.Log("weakiwi@192.168.10.1:2233 port part pass")
} else {
t.Error("weakiwi@192.168.10.1:2233 port part pass")
}
}
func Test_ParseHostfile(t *testing.T) {
sshconfigs, err := parseHostfile("./test/host1")
if err != nil {
t.Error("parseHostfile error: ", err)
}
var my_sshconfig sshconfig
my_sshconfig.user = "root"
my_sshconfig.port = "22"
my_sshconfig.address = "118.190.75.175"
if reflect.DeepEqual(sshconfigs[0], my_sshconfig) {
t.Log("parseHostfile pass")
} else {
t.Error("parseHostfile failed", sshconfigs[0])
t.Error("parseHostfile failed", my_sshconfig)
}
}
|
Java | UTF-8 | 10,540 | 2.53125 | 3 | [] | no_license | package com.wsf.source;
import com.wsf.config.Configure;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* 资源池
*/
@SuppressWarnings("all")
public class Source {
//url池
private static ConcurrentLinkedQueue<ConcurrentLinkedQueue> urlBuffer;
//html池
private static ConcurrentLinkedQueue<ConcurrentHashMap> htmlBuffer;
//item池
private static ConcurrentLinkedQueue<ConcurrentHashMap> itemBuffer;
private static String sourceFile = null;
private static Integer sourceSize = null;
private static Double minSize = null;
private static Double maxSize = null;
//标识当前磁盘中是否有数据的,如果没有的的话就不会从磁盘读取
private static Boolean hasUrlResource = null;
private static Boolean hasHtmlResource = null;
private static Boolean hasItemResource = null;
private static Logger logger = Logger.getLogger(Source.class);
//初始化资源池
static {
urlBuffer = new ConcurrentLinkedQueue<>();
htmlBuffer = new ConcurrentLinkedQueue<>();
itemBuffer = new ConcurrentLinkedQueue<>();
sourceFile = Configure.getSourceFile();
sourceSize = Configure.getSourceSize();
maxSize = Configure.getMaxSize();
minSize = Configure.getMinSize();
File rootFile = new File(sourceFile);
try {
//判断资源池文件是否存在
if (!rootFile.exists()) {
//如果不存在则创建
rootFile.mkdirs();
}
//判断url文件池文件是否存在
readFile("url");
readFile("html");
readFile("item");
} catch (Exception e) {
throw new ExceptionInInitializerError("资源池文件读取出错");
}
}
private static void readFile(String fileName) {
File f = new File(sourceFile, fileName);
if (!f.exists()) {
f.mkdir();
hasItemResource = false;
hasUrlResource = false;
hasHtmlResource = false;
} else {
//筛选出资源文件
File[] files = f.listFiles(file -> file.getName().endsWith("." + fileName + "s"));
ObjectInputStream ois = null;
try {
for (File file : files) {
ois = new ObjectInputStream(new FileInputStream(file));
switch (fileName) {
case "url":
if (urlBuffer.size() > sourceSize) {
hasUrlResource = true;
return;
}
//将资源文件中的资源保存进来
urlBuffer.addAll((ConcurrentLinkedQueue<ConcurrentLinkedQueue>) ois.readObject());
break;
case "html":
if (htmlBuffer.size() > sourceSize) {
hasHtmlResource = true;
return;
}
htmlBuffer.addAll((ConcurrentLinkedQueue<ConcurrentHashMap>) ois.readObject());
break;
case "item":
if (itemBuffer.size() > sourceSize) {
hasItemResource = true;
return;
}
itemBuffer.addAll((ConcurrentLinkedQueue<ConcurrentHashMap>) ois.readObject());
break;
default:
return;
}
ois.close();
file.delete();
}
} catch (Exception e) {
logger.error("从磁盘中读取" + fileName + "出错");
}finally {
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
switch (fileName) {
case "url":
hasUrlResource = false;
break;
case "html":
hasHtmlResource = false;
break;
case "item":
hasItemResource = false;
break;
}
}
}
public static void writeToFile(String fileName){
writeToFile(fileName,null);
}
public static void writeToFile(String fileName,Integer min) {
File f = new File(sourceFile, fileName);
ObjectOutputStream oos = null;
ConcurrentLinkedQueue temp = null;
int lowest = (int)(sourceSize * minSize);
if(min!=null && min >=0){
lowest = min;
}
try {
switch (fileName) {
case "url":
if(urlBuffer.size() == 0){
break;
}
File urlFile = new File(f, "" + System.currentTimeMillis() + UUID.randomUUID() + "." + fileName + "s");
temp = new ConcurrentLinkedQueue();
urlFile.createNewFile();
oos = new ObjectOutputStream(new FileOutputStream(urlFile));
while (urlBuffer.size() > lowest) {
temp.add(urlBuffer.poll());
}
oos.writeObject(temp);
hasUrlResource = true;
break;
case "html":
if(htmlBuffer.size()==0){
break;
}
File htmlFile = new File(f, "" + System.currentTimeMillis() + UUID.randomUUID() + "." + fileName + "s");
temp = new ConcurrentLinkedQueue();
htmlFile.createNewFile();
oos = new ObjectOutputStream(new FileOutputStream(htmlFile));
while (htmlBuffer.size() > lowest) {
temp.add(htmlBuffer.poll());
}
oos.writeObject(temp);
hasHtmlResource = true;
break;
case "item":
if(itemBuffer.size()==0){
break;
}
File itemFile = new File(f, "" + System.currentTimeMillis() + UUID.randomUUID() + "." + fileName + "s");
temp = new ConcurrentLinkedQueue();
itemFile.createNewFile();
oos = new ObjectOutputStream(new FileOutputStream(itemFile));
while (itemBuffer.size() > lowest) {
temp.add(itemBuffer.poll());
}
oos.writeObject(temp);
hasItemResource = true;
break;
default:
return;
}
} catch (IOException e) {
e.printStackTrace();
logger.error("将" + fileName + "写入磁盘文件出错!");
}finally {
if(oos!=null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static ConcurrentLinkedQueue<ConcurrentLinkedQueue> getUrlBuffer() {
return urlBuffer;
}
public static void setUrlBuffer(ConcurrentLinkedQueue<ConcurrentLinkedQueue> urlBuffer) {
Source.urlBuffer = urlBuffer;
}
public static ConcurrentLinkedQueue<ConcurrentHashMap> getHtmlBuffer() {
return htmlBuffer;
}
public static void setHtmlBuffer(ConcurrentLinkedQueue<ConcurrentHashMap> htmlBuffer) {
Source.htmlBuffer = htmlBuffer;
}
public static ConcurrentLinkedQueue<ConcurrentHashMap> getItemBuffer() {
return itemBuffer;
}
public static void setItemBuffer(ConcurrentLinkedQueue<ConcurrentHashMap> itemBuffer) {
Source.itemBuffer = itemBuffer;
}
//将数据从磁盘读取到内存
public static void loadHtml() {
if (hasHtmlResource) {
readFile("html");
}
}
public static void loadItem() {
if (hasItemResource) {
readFile("item");
}
}
public static void loadUrl() {
if (hasUrlResource) {
readFile("url");
}
}
//将数据从内存写到磁盘
public static void unloadHtml() {
writeToFile("html");
}
public static void unloadItem() {
writeToFile("item");
}
public static void unloadUrl() {
writeToFile("url");
}
public static String getSourceFile() {
return sourceFile;
}
public static void setSourceFile(String sourceFile) {
Source.sourceFile = sourceFile;
}
public static Integer getSourceSize() {
return sourceSize;
}
public static void setSourceSize(Integer sourceSize) {
Source.sourceSize = sourceSize;
}
public static Double getMinSize() {
return minSize;
}
public static void setMinSize(Double minSize) {
Source.minSize = minSize;
}
public static Double getMaxSize() {
return maxSize;
}
public static void setMaxSize(Double maxSize) {
Source.maxSize = maxSize;
}
public static Boolean getHasUrlResource() {
return hasUrlResource;
}
public static void setHasUrlResource(Boolean hasUrlResource) {
Source.hasUrlResource = hasUrlResource;
}
public static Boolean getHasHtmlResource() {
return hasHtmlResource;
}
public static void setHasHtmlResource(Boolean hasHtmlResource) {
Source.hasHtmlResource = hasHtmlResource;
}
public static Boolean getHasItemResource() {
return hasItemResource;
}
public static void setHasItemResource(Boolean hasItemResource) {
Source.hasItemResource = hasItemResource;
}
public static void close(){
writeToFile("html",0);
writeToFile("url",0);
writeToFile("item",0);
htmlBuffer = null;
urlBuffer = null;
itemBuffer = null;
}
}
|
Java | UTF-8 | 602 | 3.09375 | 3 | [] | no_license | package xsf.design.observer.normal;
import java.util.Vector;
/**
* Author: xushangfei
* Time: created at 2017/5/2.
* Description: 被观察者
*/
public abstract class Subject {
private Vector<Observer> observers;
//增加一个观察者
public void registerObserver(Observer o) {
observers.add(o);
}
//删除一个观察者
public void removeObserver(Observer o) {
observers.remove(o);
}
//通知所有观察者
public void notifyObserver() {
for (Observer observer : observers) {
observer.update();
}
}
}
|
Python | UTF-8 | 3,339 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | import os
import pathlib
import pytest
from mopidy_local import translator
@pytest.mark.parametrize(
"local_uri,file_uri",
[
("local:directory:A/B", "file:///home/alice/Music/A/B"),
("local:directory:A%20B", "file:///home/alice/Music/A%20B"),
("local:directory:A+B", "file:///home/alice/Music/A%2BB"),
(
"local:directory:%C3%A6%C3%B8%C3%A5",
"file:///home/alice/Music/%C3%A6%C3%B8%C3%A5",
),
("local:track:A/B.mp3", "file:///home/alice/Music/A/B.mp3"),
("local:track:A%20B.mp3", "file:///home/alice/Music/A%20B.mp3"),
("local:track:A+B.mp3", "file:///home/alice/Music/A%2BB.mp3"),
(
"local:track:%C3%A6%C3%B8%C3%A5.mp3",
"file:///home/alice/Music/%C3%A6%C3%B8%C3%A5.mp3",
),
],
)
def test_local_uri_to_file_uri(local_uri, file_uri):
media_dir = pathlib.Path("/home/alice/Music")
assert translator.local_uri_to_file_uri(local_uri, media_dir) == file_uri
@pytest.mark.parametrize("uri", ["A/B", "local:foo:A/B"])
def test_local_uri_to_file_uri_errors(uri):
media_dir = pathlib.Path("/home/alice/Music")
with pytest.raises(ValueError):
translator.local_uri_to_file_uri(uri, media_dir)
@pytest.mark.parametrize(
"uri,path",
[
("local:directory:A/B", b"/home/alice/Music/A/B"),
("local:directory:A%20B", b"/home/alice/Music/A B"),
("local:directory:A+B", b"/home/alice/Music/A+B"),
(
"local:directory:%C3%A6%C3%B8%C3%A5",
b"/home/alice/Music/\xc3\xa6\xc3\xb8\xc3\xa5",
),
("local:track:A/B.mp3", b"/home/alice/Music/A/B.mp3"),
("local:track:A%20B.mp3", b"/home/alice/Music/A B.mp3"),
("local:track:A+B.mp3", b"/home/alice/Music/A+B.mp3"),
(
"local:track:%C3%A6%C3%B8%C3%A5.mp3",
b"/home/alice/Music/\xc3\xa6\xc3\xb8\xc3\xa5.mp3",
),
],
)
def test_local_uri_to_path(uri, path):
media_dir = pathlib.Path("/home/alice/Music")
result = translator.local_uri_to_path(uri, media_dir)
assert isinstance(result, pathlib.Path)
assert bytes(result) == path
@pytest.mark.parametrize("uri", ["A/B", "local:foo:A/B"])
def test_local_uri_to_path_errors(uri):
media_dir = pathlib.Path("/home/alice/Music")
with pytest.raises(ValueError):
translator.local_uri_to_path(uri, media_dir)
@pytest.mark.parametrize(
"path,uri",
[
("/foo", "file:///foo"),
(b"/foo", "file:///foo"),
("/æøå", "file:///%C3%A6%C3%B8%C3%A5"),
(b"/\x00\x01\x02", "file:///%00%01%02"),
(pathlib.Path("/æøå"), "file:///%C3%A6%C3%B8%C3%A5"),
],
)
def test_path_to_file_uri(path, uri):
assert translator.path_to_file_uri(path) == uri
@pytest.mark.parametrize(
"path,uri",
[
(pathlib.Path("foo"), "local:track:foo"),
(pathlib.Path("/home/alice/Music/foo"), "local:track:foo"),
(pathlib.Path("æøå"), "local:track:%C3%A6%C3%B8%C3%A5"),
(pathlib.Path(os.fsdecode(b"\x00\x01\x02")), "local:track:%00%01%02"),
],
)
def test_path_to_local_track_uri(path, uri):
media_dir = pathlib.Path("/home/alice/Music")
result = translator.path_to_local_track_uri(path, media_dir)
assert isinstance(result, str)
assert result == uri
|
Java | UTF-8 | 3,646 | 2.109375 | 2 | [] | no_license | package com.example.telkomsel.myshoppingmall;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.telkomsel.myshoppingmall.api.request.PostRegisterRequest;
import com.example.telkomsel.myshoppingmall.api.response.BaseResponse;
import com.loopj.android.http.RequestParams;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class RegisterActivity extends AppCompatActivity implements
PostRegisterRequest.OnPostRegisterRequestListener, View.OnClickListener {
@BindView(R.id.et_name_reg)
EditText etNameReg;
@BindView(R.id.et_pass_reg)
EditText etPassReg;
@BindView(R.id.et_email_reg)
EditText etEmailReg;
@BindView(R.id.cb_1)
CheckBox cb1;
@BindView(R.id.but_register)
Button butRegister;
private ProgressDialog progressDialog;
private PostRegisterRequest postRegisterRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.bind(this);
getSupportActionBar().setTitle("REGISTER");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog = new ProgressDialog(RegisterActivity.this);
progressDialog.setTitle("Register");
progressDialog.setMessage("Please wait...");
postRegisterRequest = new PostRegisterRequest();
postRegisterRequest.setOnPostRegisterRequestListener(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPostRegisterSuccess(BaseResponse response) {
progressDialog.cancel();
Toast.makeText(RegisterActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
@Override
public void onPostRegisterFailure(String errorMessage) {
progressDialog.cancel();
Toast.makeText(RegisterActivity.this, errorMessage , Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
}
@OnClick(R.id.but_register)
public void onClick() {
String username = etNameReg.getText().toString().trim();
String password = etPassReg.getText().toString().trim();
String email = etEmailReg.getText().toString().trim();
if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)||TextUtils.isEmpty(email)){
Toast.makeText(RegisterActivity.this,"All fields are required", Toast.LENGTH_SHORT).show();
} else {
RequestParams requestParams = new RequestParams();
requestParams.put("username",username);
requestParams.put("password",password);
requestParams.put("email",email);
postRegisterRequest.setRequestParams(requestParams);
progressDialog.show();
postRegisterRequest.callApi();
}
}
@Override
protected void onDestroy() {
postRegisterRequest.cancelRequest();
super.onDestroy();
}
}
|
Markdown | UTF-8 | 3,533 | 2.875 | 3 | [] | no_license | ---
wordpress_id: 336
layout: post
title: Chicago -or- Erin missed me
excerpt: |-
I decided I'd meet my brother in Chicago. Thanks to Hiro who knows how to get anywhere, I was able to take the Greyhound to Chicago and back.
<P>It was a good 3 hour bus ride, but I wasn't wasting too much time since it was early in the morning and I was studying for my math exam. Also it kept me from bidding on ebay.
<P>One girl on the bus (fairly cute) looked like she fell asleep with her hand in a bag of chips... nasty oilyness. Even the pretty have their weaknesses.
<P>I got to Chicago a little after noon and met my brother, Raj, and my other friend Raj at the bus station (he had flown in for a convention). We went to look for a place to eat, but the Cheesecake Factory was packed. Every place was packed since it was the day of Payton's memorial service. We ended up eating at this really good Chinese restaurant. We went shopping for a bit at the Virgin MegaStore. Didn't get any virgins though. My brother bought me some new shoes and other stuff too at Filene's basement.
<P>We headed back to the Sheraton: Chicago and Towers. It's not that great of a hotel actually. It's nicely furnished though and the lobby is really nice too. We hung out and ate food there, although only Raj (the friend) was hungry. Raj (the friend) went back to his campus (<A HREF='http://www.uchicago.com/'>U Chicago</A>). My brother and I hung out at the hotel. Went for a walk around Chicago. Then we ate at Giordano's Pizzaria (very good pizza).
<P>This morning I had a slice of that pizza for breakfast. Then I went back home. All was fun, even though it was for a short time.
<P>Erin was upset at my absense. Partially because she didn't know where I was. I wish Erin would have come with me.
---
I decided I'd meet my brother in Chicago. Thanks to Hiro who knows how to get anywhere, I was able to take the Greyhound to Chicago and back.
<P>It was a good 3 hour bus ride, but I wasn't wasting too much time since it was early in the morning and I was studying for my math exam. Also it kept me from bidding on ebay.
<P>One girl on the bus (fairly cute) looked like she fell asleep with her hand in a bag of chips... nasty oilyness. Even the pretty have their weaknesses.
<P>I got to Chicago a little after noon and met my brother, Raj, and my other friend Raj at the bus station (he had flown in for a convention). We went to look for a place to eat, but the Cheesecake Factory was packed. Every place was packed since it was the day of Payton's memorial service. We ended up eating at this really good Chinese restaurant. We went shopping for a bit at the Virgin MegaStore. Didn't get any virgins though. My brother bought me some new shoes and other stuff too at Filene's basement.
<P>We headed back to the Sheraton: Chicago and Towers. It's not that great of a hotel actually. It's nicely furnished though and the lobby is really nice too. We hung out and ate food there, although only Raj (the friend) was hungry. Raj (the friend) went back to his campus (<A HREF='http://www.uchicago.com/'>U Chicago</A>). My brother and I hung out at the hotel. Went for a walk around Chicago. Then we ate at Giordano's Pizzaria (very good pizza).
<P>This morning I had a slice of that pizza for breakfast. Then I went back home. All was fun, even though it was for a short time.
<P>Erin was upset at my absense. Partially because she didn't know where I was. I wish Erin would have come with me.
|
Python | UTF-8 | 167 | 3.15625 | 3 | [] | no_license | x = int(input())
alfabeto = chr(65)
for _ in range(1,x+1):
temp ='';
for i in range(0, _):
temp+=alfabeto
print(temp)
alfabeto=chr(65+_)
|
Java | UTF-8 | 1,092 | 3.75 | 4 | [] | no_license | package com.leetcode.tenToEleven;
/**
* Created by LiuLiHao on 2020/3/20 0020 下午 04:14
* @author : LiuLiHao
* 描述:
* 爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
*
* 最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:
*
* 选出任一 x,满足 0 < x < N 且 N % x == 0 。
* 用 N - x 替换黑板上的数字 N 。
* 如果玩家无法执行这些操作,就会输掉游戏。
*
* 只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。
*
*
*
* 示例 1:
*
* 输入:2
* 输出:true
* 解释:爱丽丝选择 1,鲍勃无法进行操作。
* 示例 2:
*
* 输入:3
* 输出:false
* 解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。
*/
public class DivisorGame1025 {
public static void main(String[] args) {
System.out.println(divisorGame(2));
}
public static boolean divisorGame(int N) {
return N%2==0;
}
}
|
TypeScript | UTF-8 | 1,019 | 3.171875 | 3 | [] | no_license | /*
This class is supose to hold the current weather Json.
*/
export class CityWeather{
weather: Weather[]; //contains the weather
main: Main; //contains the main onformation about the weather
name: string; //name of the city
}
class Weather{
main: string;
description: string; //weather description
icon: string //weather icon code, witch will be needed to add to the right URL
imageUrl: string //it will not come from the json file, and will have to put manually from the service
}
class Main{
/**
* for some reason, the json does not give accurate weather,
* and the min and the max tempeture are the same (only in Israel)
*/
temp: number; //the current tamputures of the day, in Kelvin (decrease 273.15 to get Celsius)
temp_min: number; //gives the max temp of the date, in Kelvin (decrease 273.15 to get Celsius)
temp_max: number; //gives the min temp of the date, in Kelvin (decrease 273.15 to get Celsius)
} |
C# | UTF-8 | 1,351 | 2.53125 | 3 | [] | no_license | using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel;
using IdentityModel.Client;
namespace Client
{
class Program
{
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
var discoveryDocument = await httpClient.GetDiscoveryDocumentAsync("http://127.0.0.1:5000");
if (discoveryDocument.IsError)
{
Console.WriteLine(discoveryDocument.Error);
return;
}
var passwordTokenRequest = new PasswordTokenRequest()
{
Address = discoveryDocument.TokenEndpoint,
ClientId = "resourceOwnerClient",
ClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",
GrantType = OidcConstants.GrantTypes.Password,
Scope = "api1",
UserName = "bob",
Password = "Pass123"
};
var tokenResponse = await httpClient.RequestPasswordTokenAsync(passwordTokenRequest);
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.ErrorDescription);
return;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");
}
}
} |
Python | UTF-8 | 927 | 2.6875 | 3 | [
"MIT"
] | permissive | from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, Flatten, Dense, Input
import tensorflow as tf
class TCNNNet(Model):
def __init__(self, output_dim):
"""
Args:
output_dim: 网络需要n个输出,对应n个动作的累积回报
"""
super(TCNNNet, self).__init__()
self.c1 = Conv2D(filters=16, kernel_size=(4, 4), strides=2, activation='relu') # 卷积层
self.c2 = Conv2D(filters=32, kernel_size=(2, 2), strides=1, activation='relu') # 卷积层
self.flatten = Flatten()
self.d1 = Dense(64, activation='relu')
self.d2 = Dense(output_dim)
def call(self, x):
x, t = x
x = self.c1(x)
x = self.c2(x)
x = tf.concat([self.flatten(x), tf.reshape(tf.cast(t[:, 0] / t[:, 1], dtype=tf.float32), (-1, 1))], axis=1)
x = self.d1(x)
y = self.d2(x)
return y
|
C | UTF-8 | 432 | 3.34375 | 3 | [] | no_license | #include "holberton.h"
/**
* *_strncat - check the code for Holberton School students.
* @dest: this is the first accountant.
* @src: this is the second accountant.
* @n: this is the third accountant.
* Return: Always 0.
*/
char *_strncat(char *dest, char *src, int n)
{
int i;
int c;
for (i = 0; *(dest + i) != '\0'; i++)
{
}
for (c = 0; c < n && src[c] != '\0'; c++)
{
dest[i + c] = src[c];
}
return (dest);
}
|
Java | UTF-8 | 252 | 1.835938 | 2 | [] | no_license | package br.mack.modeloEntidade;
import java.util.GregorianCalendar;
/**
*
* @author Grupo 01 - Tema: Loja virtual
*/
public class Pagamento {
public int identificador;
public GregorianCalendar data;
public double valor;
}
|
C# | UTF-8 | 1,583 | 2.765625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BW.GateWay.Lottery.X5
{
/// <summary>
/// 胆码 不位胆 后三二码
/// </summary>
public class Player78 : IX5
{
protected override IX5.NumberRange NumberType
{
get
{
return NumberRange.Star5;
}
}
public override bool IsMatch(string input)
{
string[][] inputNumber = input.GetInputNumber(this.InputBall, new int[] { 3 });
if (inputNumber == null) return false;
return true;
}
public override int Bet(string input)
{
if (!this.IsMatch(input)) return 0;
string[][] inputNumber = input.GetInputNumber();
return MathExtend.Combinations(3, inputNumber[0].Length);
}
public override decimal Reward(string input, string number, decimal rewardMoney = decimal.Zero)
{
if (!this.IsResult(number)) return decimal.Zero;
if (this.Bet(input) == 0) return decimal.Zero;
string[] inputNumber = input.GetInputNumber()[0];
string[] resultNumber = this.GetNumber(number).Distinct().ToArray();
int count = MathExtend.Intersect(inputNumber, resultNumber);
return MathExtend.Combinations(3, count) * this.GetRewardMoney(rewardMoney);
}
public override decimal RewardMoney
{
get
{
return 45.97M;
}
}
}
}
|
Markdown | UTF-8 | 4,387 | 3.203125 | 3 | [
"MIT"
] | permissive | +++
title = "Mocking functions in Go"
date = 2014-04-10T11:35:00Z
updated = 2014-05-06T09:54:05Z
tags = ["Go", "testing", "programming", "golang"]
blogimport = true
type = "post"
[author]
name = "Nate Finch"
uri = "https://plus.google.com/115818189328363361527"
+++
Functions in Go are first class citizens, that means you can have a variable that contains a function value, and call it like a regular function.<br /><pre style="tab-size: 4;">printf := fmt.Printf<br />printf("This will output %d line.\n", 1)</pre>This ability can come in very handy for testing code that calls a function which is hard to properly test while testing the surrounding code. In <a href="http://juju.ubuntu.com/" target="_blank">Juju</a>, we occasionally use function variables to allow us to stub out a difficult function during tests, in order to more easily test the code that calls it. Here's a simplified example:<br />
<pre style="tab-size: 4;">// in install/mongodb.go<br />package install<br /><br />func SetupMongodb(path string) error {<br /> // suppose the code in this method modifies files in root<br /> // directories, mucks with the environment, etc... <br /> // Actions you actively don't want to do during most tests.<br />}</pre></span><pre style="tab-size: 4;"><br />// in startup/bootstrap.go<br />package startup<br /><br />func Bootstrap() error {<br /> ...<br /> path := getPath()<br /> if err := install.SetupMongodb(path); err != nil {<br /> return err<br /> }<br /> ...<br />}</pre></span>So, suppose you want to write a test for Bootstrap, but you know SetupMongodb won't work, because the tests don't run with root privileges (and you don't want to setup mongodb on the dev's machine anyway). What can you do? This is where mocking comes in.<br /><br />We just make a little tweak to Bootstrap:<br /><pre style="tab-size: 4;">package startup<br /><br />var setupMongo = install.SetupMongodb<br /><br />func Bootstrap() error {<br /> ...<br /> path := getRootDirPath()<br /> if err := setupMongo(path); err != nil {<br /> return err<br /> }<br /> ...<br />}</pre></span>Now if we want to test Bootstrap, we can mock out the setupMongo function thusly:<br /><pre style="tab-size: 4;"><span style="TRACE">// in startup/bootstrap_test.go<br />package startup<br /><br />type fakeSetup struct {<br /> path string<br /> err error<br />}<br /><br />func (f *fakeSetup) setup(path string) error {<br /> f.path = path<br /> return f.err<br />}<br /><br />TestBootstrap(t *testing.T) {<br /> f := &fakeSetup{ err: errors.New("Failed!") }<br /> // this mocks out the function that Bootstrap() calls<br /> setupMongo = f.setup<br /> err := Bootstrap()<br /> if err != f.err {<br /> t.Fail("Error from setupMongo not returned. Expected %v, got %v", f.err, err)<br /> }<br /> expPath := getPath()<br /> if f.path != expPath {<br /> t.Fail("Path not correctly passed into setupMongo. Expected %q, got %q", expPath, f.path)<br /> }<br /><br /> // and then try again with f.err == nil, you get the idea<br />}</pre></span>Now we have full control over what happens in the setupMongo function, we can record the parameters that are passed into it, what it returns, and test that Bootstrap is at least using the API of the function correctly.<br /><br />Obviously, we need tests elsewhere for install.SetupMongodb to make sure it does the right thing, but those can be tests internal to the install package, which can use non-exported fields and functions to effectively test the logic that would be impossible from an external package (like the setup package). Using this mocking means that we don't have to worry about setting up an environment that allows us to test SetupMongodb when we really only want to test Bootstrap. We can just stub out the function and test that Bootstrap does everything correctly, and trust that SetupMongodb works because it's tested in its own package.
|
C# | UTF-8 | 322 | 2.9375 | 3 | [
"MIT"
] | permissive | namespace PietDotNet;
public enum DirectionPointer
{
right = 0,
down = 1,
left = 2,
top = 3,
}
public static class DirectionPointerExtensions
{
public static DirectionPointer Rotate(this DirectionPointer dp, long steps)
{
return (DirectionPointer)((long)dp + steps).Modulo(4);
}
}
|
Markdown | UTF-8 | 165 | 2.546875 | 3 | [] | no_license | # Cheap-Best-Information-Retrieval-
An AI application that returns list of products as per the query after reviewing their price and reviews by several customers.
|
Shell | UTF-8 | 1,262 | 2.546875 | 3 | [] | no_license | #echo -e "\n\nExecuting ~/.zshenv\n\n"
###########################################################
# Setting local gtest
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
export LD_LIBRARY_PATH
###########################################################
# Export vars
#export JAVA_HOME=/usr/lib/jvm/java-6-sun
#export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk
export MAVEN_OPTS="-Xmx1024m -XX:MaxPermSize=256m"
#export LOCAL_JAVA_HOME_32=/home/idachev/lib/java/jre1.6.0_34
#export LOCAL_JAVA_HOME_64=/home/idachev/lib/java/jre1.6.0_34_x64
#pycharm java
#export PYCHARM_JDK=$LOCAL_JAVA_HOME_32
# Add custom scripts to bin
export PATH=$PATH:/usr/share/fslint/fslint:$HOME/bin
# Add pip local bin
export PATH=$PATH:$HOME/.local/bin
# Add go bin
export PATH=$PATH:$HOME/go/bin
# Perforce custom envs
export P4CONFIG=.p4config
export P4EDITOR=vim
export P4MERGE=kdiff3
export PYTHONPATH=$PYTHONPATH:~/lib/pywikipedia/
export GTEST_DIR=/home/idachev/develop/private/gtest/gtest-1.6.0
export RSYNC_PARTIAL_DIR=/home/idachev/.rsync-tmp
# Add local PC shell settings
# Disable this if you use rsync and ssh or scp
if [ -f ~/.localenv ]; then
# Do not use source instead of . in env files
# it does not work for desktop managers env load
. ~/.localenv
fi
|
C++ | UTF-8 | 974 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "istream_archive.h"
#include <archive.h>
#include <archive_entry.h>
using namespace nano;
archive_istream_t::archive_istream_t(archive* ar) :
m_archive(ar)
{
}
io_status archive_istream_t::advance(const std::streamsize num_bytes, buffer_t& buffer)
{
while (static_cast<std::streamsize>(buffer.size()) < num_bytes)
{
const void* buff = nullptr;
size_t size = 0;
off_t offset;
switch (archive_read_data_block(m_archive, &buff, &size, &offset))
{
case ARCHIVE_EOF: return io_status::eof;
case ARCHIVE_OK: break;
default: return io_status::error;
}
buffer.insert(buffer.end(),
reinterpret_cast<const char*>(buff),
reinterpret_cast<const char*>(buff) + size);
}
return io_status::good;
}
|
Java | UTF-8 | 5,498 | 1.632813 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.job;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.config.EdgeConfig;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.config.JobConfig;
import com.hazelcast.jet.core.DAG;
import com.hazelcast.jet.core.Edge;
import com.hazelcast.jet.core.JetTestSupport;
import com.hazelcast.jet.core.Vertex;
import com.hazelcast.jet.test.IgnoredForCoverage;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.SlowTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import static com.hazelcast.jet.core.processor.Processors.noopP;
import static com.hazelcast.jet.impl.util.Util.uncheckRun;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastSerialClassRunner.class)
@Category({SlowTest.class, IgnoredForCoverage.class})
public final class JobSubmissionSlownessRegressionTest extends JetTestSupport {
private static final int DURATION_SECS = 10;
private static final int THREADS_COUNT = 5;
private static final int HEAT_UP_CYCLE_COUNT = 3;
private static final int MEASUREMENT_A_CYCLE_COUNT = 3;
private static final int WAIT_BEFORE_MEASUREMENT_B_COUNT = 3;
private static final int MEASUREMENT_B_CYCLE_COUNT = 3;
private static final int HEAT_UP_CYCLE_SECTION = HEAT_UP_CYCLE_COUNT;
private static final int MEASUREMENT_A_CYCLE_SECTION = HEAT_UP_CYCLE_SECTION + MEASUREMENT_A_CYCLE_COUNT;
private static final int WAIT_BEFORE_MEASUREMENT_B_SECTION
= MEASUREMENT_A_CYCLE_SECTION + WAIT_BEFORE_MEASUREMENT_B_COUNT;
private static final int MEASUREMENT_B_CYCLE_SECTION = WAIT_BEFORE_MEASUREMENT_B_SECTION + MEASUREMENT_B_CYCLE_COUNT;
private static int measurementCount;
@Before
public void setup() {
JetConfig config = new JetConfig();
config.getHazelcastConfig().setProperty("hazelcast.logging.type", "none");
createJetMember(config);
}
@Test
public void regressionTestForPR1488() {
logger.info(String.format("Starting test with %d threads", THREADS_COUNT));
ExecutorService executorService = Executors.newFixedThreadPool(THREADS_COUNT);
double measurementARateSum = 0;
double measurementBRateSum = 0;
DAG dag = twoVertex();
JetInstance client = createJetClient();
while (measurementCount < MEASUREMENT_B_CYCLE_SECTION) {
AtomicInteger completedRoundTrips = new AtomicInteger();
long start = System.nanoTime();
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < THREADS_COUNT; i++) {
Future<?> f = executorService.submit(() -> {
bench(() -> {
client.newJob(dag, new JobConfig()).join();
}, completedRoundTrips);
});
futures.add(f);
}
futures.forEach(f -> uncheckRun(f::get));
long elapsed = System.nanoTime() - start;
double rate = (double) completedRoundTrips.get() / (double) elapsed * SECONDS.toNanos(1);
System.out.println("Rate was " + rate + " req/s");
measurementCount++;
if (measurementCount > HEAT_UP_CYCLE_SECTION) { //3
if (measurementCount <= MEASUREMENT_A_CYCLE_SECTION) { //6
measurementARateSum += rate;
} else if (measurementCount > WAIT_BEFORE_MEASUREMENT_B_SECTION) { //9
measurementBRateSum += rate;
}
}
}
double measurementARate = measurementARateSum / MEASUREMENT_A_CYCLE_COUNT;
double measurementBRate = measurementBRateSum / MEASUREMENT_B_CYCLE_COUNT;
assertTrue("Job submission rate should not decrease. First rate: " + measurementARate
+ ", second rate: " + measurementBRate, measurementARate * 0.8 < measurementBRate);
}
private static DAG twoVertex() {
DAG dag = new DAG();
Vertex v1 = dag.newVertex("v", noopP());
Vertex v2 = dag.newVertex("v2", noopP());
dag.edge(Edge.between(v1, v2).setConfig(new EdgeConfig().setQueueSize(1)));
return dag;
}
private static void bench(Runnable r, AtomicInteger completedRoundTrips) {
long start = System.nanoTime();
long end = start + SECONDS.toNanos(DURATION_SECS);
while (System.nanoTime() < end) {
r.run();
completedRoundTrips.incrementAndGet();
}
}
}
|
C# | UTF-8 | 12,727 | 2.9375 | 3 | [
"MIT"
] | permissive | using System;
using Xunit;
namespace Pylypeiev.Extensions.Tests
{
public class StringSearchingExtensionsTests
{
[Fact]
public void EndsWithIgnoreCaseTest()
{
//Arrange
string str = "abC";
//Act
var result = str.EndsWithIgnoreCase("c");
//Assert
Assert.True(result);
}
[Fact]
public void EndsWithIgnoreCaseTestWhenNull()
{
//Arrange
string str = null;
//Act
var result = str.EndsWithIgnoreCase("c");
//Assert
Assert.False(result);
}
[Fact]
public void EndsWithIgnoreCaseTestWhenArgumentNull()
{
//Arrange
string str = "abC";
//Act
var result = str.EndsWithIgnoreCase(null);
//Assert
Assert.False(result);
}
[Fact]
public void EqualsIgnoreCaseTest()
{
//Arrange
string str = "a";
//Act
var result = str.EndsWithIgnoreCase("A");
//Assert
Assert.True(result);
}
[Fact]
public void EqualsIgnoreCaseWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.EndsWithIgnoreCase("a");
//Assert
Assert.False(result);
}
[Fact]
public void EqualsIgnoreCaseWhenParameterNullTest()
{
//Arrange
string str = "a";
//Act
var result = str.EndsWithIgnoreCase(null);
//Assert
Assert.False(result);
}
[Fact]
public void IfNullThenTest()
{
//Arrange
string str = "a";
//Act
var result = str.IfNullThen("b");
//Assert
Assert.Equal("a", result);
}
[Fact]
public void IfNullThenTestWhenNull()
{
//Arrange
string str = null;
//Act
var result = str.IfNullThen("b");
//Assert
Assert.Equal("b", result);
}
[Fact]
public void IsAlphaCorrectTest()
{
//Arrange
string str = "a";
//Act
var result = str.IsAlpha();
//Assert
Assert.True(result);
}
[Fact]
public void IsAlphaIncorrectTest()
{
//Arrange
string str = "a1";
//Act
var result = str.IsAlpha();
//Assert
Assert.False(result);
}
[Fact]
public void IsAlphaWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsAlpha();
//Assert
Assert.False(result);
}
[Fact]
public void IsAlphaNumericCorrectTest()
{
//Arrange
string str = "a1";
//Act
var result = str.IsAlphaNumeric();
//Assert
Assert.True(result);
}
[Fact]
public void IsAlphaNumericIncorrectTest()
{
//Arrange
string str = "a1!";
//Act
var result = str.IsAlphaNumeric();
//Assert
Assert.False(result);
}
[Fact]
public void IsAlphaNumericWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsAlphaNumeric();
//Assert
Assert.False(result);
}
[Fact]
public void IsNumericCorrectTest()
{
//Arrange
string str = "1";
//Act
var result = str.IsNumeric();
//Assert
Assert.True(result);
}
[Fact]
public void IsNumericIncorrectTest()
{
//Arrange
string str = "a1";
//Act
var result = str.IsNumeric();
//Assert
Assert.False(result);
}
[Fact]
public void IsNumericWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsNumeric();
//Assert
Assert.False(result);
}
[Fact]
public void IsNullOrEmptyWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsNullOrEmpty();
//Assert
Assert.True(result);
}
[Fact]
public void IsNullOrEmptyWhenNotNullTest()
{
//Arrange
string str = "a1";
//Act
var result = str.IsNullOrEmpty();
//Assert
Assert.False(result);
}
[Fact]
public void IsNullOrWhiteSpaceWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsNullOrWhiteSpace();
//Assert
Assert.True(result);
}
[Fact]
public void IsNullOrWhiteSpaceWhenEmptyTest()
{
//Arrange
string str = " ";
//Act
var result = str.IsNullOrWhiteSpace();
//Assert
Assert.True(result);
}
[Fact]
public void IsNullOrWhiteSpaceWhenNotNullTest()
{
//Arrange
string str = "a1";
//Act
var result = str.IsNullOrWhiteSpace();
//Assert
Assert.False(result);
}
[Fact]
public void IsPalindromeCorrectTest()
{
//Arrange
string str = "ABBA";
//Act
var result = str.IsPalindrome();
//Assert
Assert.True(result);
}
[Fact]
public void IsPalindromeIncorrectTest()
{
//Arrange
string str = "ABBAB";
//Act
var result = str.IsPalindrome();
//Assert
Assert.False(result);
}
[Fact]
public void IsPalindromeWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsPalindrome();
//Assert
Assert.False(result);
}
[Fact]
public void IsValidEmailCorrectTest()
{
//Arrange
string str = "a@a.a";
//Act
var result = str.IsValidEmail();
//Assert
Assert.True(result);
}
[Fact]
public void IsValidEmailIncorrectTest()
{
//Arrange
string str = "aa@aa";
//Act
var result = str.IsValidEmail();
//Assert
Assert.False(result);
}
[Fact]
public void IsValidEmailWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsValidEmail();
//Assert
Assert.False(result);
}
[Fact]
public void IsValidIPCorrectTest()
{
//Arrange
string str = "10.0.0.0";
//Act
var result = str.IsValidIP();
//Assert
Assert.True(result);
}
[Fact]
public void IsValidIPIncorrectTest()
{
//Arrange
string str = "aa@aa";
//Act
var result = str.IsValidIP();
//Assert
Assert.False(result);
}
[Fact]
public void IsValidIPWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.IsValidIP();
//Assert
Assert.False(result);
}
[Fact]
public void NthIndexOfFirstCorrectTest()
{
//Arrange
string str = "ababa";
//Act
var result = str.NthIndexOf("b", 1);
//Assert
Assert.Equal(1, result);
}
[Fact]
public void NthIndexOfSecondCorrectTest()
{
//Arrange
string str = "ababa";
//Act
var result = str.NthIndexOf("b", 2);
//Assert
Assert.Equal(3, result);
}
[Fact]
public void NthIndexOfOutOfRangeInCorrectTest()
{
//Arrange
string str = "ababa";
//Act
var result = str.NthIndexOf("b", 6);
//Assert
Assert.Equal(-1, result);
}
[Fact]
public void NthIndexInCorrectTest()
{
//Arrange
string str = "ababa";
//Act
var result = str.NthIndexOf("c", 1);
//Assert
Assert.Equal(-1, result);
}
[Fact]
public void NthIndexInWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.NthIndexOf("c", 1);
//Assert
Assert.Equal(-1, result);
}
[Fact]
public void NthIndexInWhenParameterNullTest()
{
//Arrange
string str = "a";
//Act
var result = str.NthIndexOf(null, 1);
//Assert
Assert.Equal(-1, result);
}
[Fact]
public void OccurrenceNumCorrectTest()
{
//Arrange
string str = "ababa";
//Act
var result = str.OccurrenceNum("b");
//Assert
Assert.Equal(2, result);
}
[Fact]
public void OccurrenceNumIncorrectTest()
{
//Arrange
string str = "ababa";
//Act
var result = str.OccurrenceNum("c");
//Assert
Assert.Equal(0, result);
}
[Fact]
public void OccurrenceNumWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.OccurrenceNum("c");
//Assert
Assert.Equal(0, result);
}
[Fact]
public void OccurrenceNumWhenParameterNullTest()
{
//Arrange
string str = "C";
//Act
var result = str.OccurrenceNum(null);
//Assert
Assert.Equal(0, result);
}
[Fact]
public void StartsWithIgnoreCaseTest()
{
//Arrange
string str = "Abc";
//Act
var result = str.StartsWithIgnoreCase("a");
//Assert
Assert.True(result);
}
[Fact]
public void StartsWithIgnoreCaseTestWhenNull()
{
//Arrange
string str = null;
//Act
var result = str.StartsWithIgnoreCase("c");
//Assert
Assert.False(result);
}
[Fact]
public void StartsWithIgnoreCaseTestWhenArgumentNull()
{
//Arrange
string str = "abc";
//Act
var result = str.StartsWithIgnoreCase(null);
//Assert
Assert.False(result);
}
[Fact]
public void ContainsTest()
{
//Arrange
string str = "aba";
//Act
var result = str.Contains("B", StringComparison.OrdinalIgnoreCase);
//Assert
Assert.True(result);
}
[Fact]
public void ContainsInvariantSafeWhenNotContainsTest()
{
//Arrange
string str = "aba";
//Act
var result = str.ContainsInvariantSafe("C");
//Assert
Assert.False(result);
}
[Fact]
public void ContainsInvariantSafeWhenNullTest()
{
//Arrange
string str = null;
//Act
var result = str.ContainsInvariantSafe("B");
//Assert
Assert.False(result);
}
[Fact]
public void ContainsInvariantSafeWhenParameterNullTest()
{
//Arrange
string str = "a";
//Act
var result = str.ContainsInvariantSafe(null, StringComparison.OrdinalIgnoreCase);
//Assert
Assert.False(result);
}
}
}
|
Markdown | UTF-8 | 684 | 2.84375 | 3 | [] | no_license | ## Velkommen til denne hjemmeside
Dette er en hjemmeside for en opgave, som skulle være lavet for 100 år siden, men nu er den da nogenlunde lavet. Ellers handler der her ikke rigtig om noget.For jeg kan ikke helt se hvad jeg skulle skrive her, men det finder man måske ud af på et senere tidspunkt.
### UFC - Copenhagen
UFC Copenhagen var her i lørdags, hvor 2 danskere var i kamp, Dalby og Madsen.
```markdown
Danskerne i kamp
Nicolas "Lokomotivo" Dalby vandt en sikker kamp imod Alex "Cowboy" Oliviera med 3 gange 29/28
Mark "The Olympian" Madsen vandt på blot 70 sekunder mod sin italienske modstander. Mark så sten sikker ud, og simpelthen ødelagde sin modstander.
|
Python | UTF-8 | 1,605 | 3.453125 | 3 | [] | no_license | from turtle import Turtle
POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
class Snake:
def __init__(self):
self.turtle_obj = []
self.snake_body()
def snake_body(self):
for postion in POSITIONS:
tim = Turtle("square")
tim.color("deeppink3")
tim.penup()
tim.goto(postion)
self.turtle_obj.append(tim)
def add_snake_body(self):
new_tim = Turtle("square")
new_tim.color("deeppink3")
new_tim.penup()
new_tim.goto(self.turtle_obj[-1].position()) #refering to last tim object
self.turtle_obj.append(new_tim)
def reset_snake(self):
for snake_seg in self.turtle_obj:
snake_seg.goto(1000, 1000)
self.turtle_obj.clear()
self.snake_body()
def move(self):
for i in range(len(self.turtle_obj) - 1, 0, -1):
new_x = self.turtle_obj[i - 1].xcor()
new_y = self.turtle_obj[i - 1].ycor()
self.turtle_obj[i].goto(new_x, new_y)
self.turtle_obj[0].forward(20)
# Screen methods
def up(self):
if self.turtle_obj[0].heading() != (270):
self.turtle_obj[0].setheading(90)
def down(self):
if self.turtle_obj[0].heading() != 90:
self.turtle_obj[0].setheading(270)
def left(self):
if self.turtle_obj[0].heading() != 0:
self.turtle_obj[0].setheading(180)
def right(self):
if self.turtle_obj[0].heading() != 180:
self.turtle_obj[0].setheading(0)
|
Python | UTF-8 | 1,811 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | """Detail Yeti's regular expression indicator structure."""
import re
from marshmallow import fields, post_load
from yeti.core.errors import ValidationError
from .indicator import Indicator, IndicatorSchema
class RegexSchema(IndicatorSchema):
"""(De)serialization marshmallow.Schema for Malware objects."""
pattern = fields.String(required=True, allow_none=True)
@post_load
def load_regular_expression(self, regex_object):
"""Load a Regex object from its JSON representation.
Returns:
The Regex object.
"""
if regex_object.pattern:
regex_object.compiled_regex = re.compile(regex_object.pattern)
return regex_object
class Regex(Indicator):
"""Yara rule Yeti object.
Attributes:
family: list(str), the families this malware belongs to.
"""
schema = RegexSchema
_collection_name = 'indicators'
type = 'indicator.regex'
pattern = ''
compiled_regex = None
def is_valid(self):
Indicator.is_valid(self)
if not isinstance(self.pattern, str):
raise ValidationError('.pattern must be str')
try:
re.compile(self.pattern)
except re.error as err:
raise ValidationError(
'Could not compile regular expression: {0:s}'.format(str(err)))
return True
def match(self, obj):
"""Matches the Regex's compiled regular expression against a string.
Args:
obj: A string to match the regex on.
Returns:
The match.group() if there is a match, None otherwise.
"""
match = self.compiled_regex.search(obj)
if match:
return {'name': self.name, 'details': match.group()}
return None
Indicator.datatypes[Regex.type] = Regex
|
C# | UTF-8 | 3,556 | 2.84375 | 3 | [
"MIT"
] | permissive | using System.Linq;
using Microsoft.AspNetCore.Mvc;
using PacktContactsCore.Model;
using PacktContactsCore.Context;
namespace PacktContactsCore.Controllers
{
[Route("api/[controller]")]
public class ContactsController : Controller
{
private readonly ContactsContext _context;
public ContactsController(ContactsContext contactContext)
{
_context = contactContext;
}
// GET: api/values
[HttpGet]
public IActionResult Get()
{
return Ok(_context.Contacts.ToList());
}
// GET api/values/5
[HttpGet("{id}", Name ="GetContactById")]
public IActionResult Get(int id)
{
var result = _context.Contacts.Any(c => c.Id == id);
if (!result)
{
return NotFound();
}
return Ok(_context.Contacts.Where(c => c.Id == id).FirstOrDefault());
}
// POST api/values
[HttpPost]
public IActionResult Post([FromBody]Contacts reqObj)
{
if (reqObj == null)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var contextObj = _context.Contacts.Add(reqObj);
var count = _context.SaveChanges();
if (count == 1)
{
return Ok();
}
else
{
return StatusCode(500, "A problem happened while handling your request.");
}
}
// PUT api/values/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]Contacts reqObj)
{
if (reqObj == null)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = _context.Contacts.Any(c => c.Id == id);
if (!result)
{
return NotFound();
}
var savedrec = _context.Contacts.Where(c => c.Id == id).FirstOrDefault();
// Use of AutoMapper removes below mapping
// Showing old school technique
savedrec.FirstName = reqObj.FirstName;
savedrec.LastName = reqObj.LastName;
savedrec.Email = reqObj.Email;
savedrec.DateOfBirth = reqObj.DateOfBirth;
_context.Contacts.Update(savedrec);
var count = _context.SaveChanges();
if (count == 1)
{
return StatusCode(201, "Updated Sucessfully!");
}
else
{
return StatusCode(500, "A problem happened while handling your request.");
}
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var result = _context.Contacts.Any(c => c.Id == id);
if (!result)
{
return NotFound();
}
var savedrec = _context.Contacts.Where(c => c.Id == id).FirstOrDefault();
_context.Contacts.Remove(savedrec);
var count = _context.SaveChanges();
if (count == 1)
{
return NoContent();
}
else
{
return StatusCode(500, "A problem happened while handling your request.");
}
}
}
}
|
C++ | UTF-8 | 4,940 | 3.15625 | 3 | [
"CC0-1.0",
"ISC",
"BSL-1.0"
] | permissive | // Honeycomb, Copyright (C) 2015 NewGamePlus Inc. Distributed under the Boost Software License v1.0.
#pragma once
#include "Honey/Math/Alge/Alge.h"
#include "Honey/Misc/Optional.h"
namespace honey
{
/// A contiguous region of referenced (not owned by object) memory
/**
* A buffer is a light wrapper around a pointer, as such the constness of a buffer object
* does not affect the mutability of its referenced memory. Also, for readability it
* is better to pass a buffer by value instead of by const reference
* (eg. declare `Buffer<T>` instead of `const Buffer<T>&`, similar to how one would declare `T*` instead of `T* const&`).
*/
template<class T>
class Buffer
{
public:
typedef T value_type;
typedef szt size_type;
typedef sdt difference_type;
typedef T& reference;
typedef T* pointer;
typedef T* iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
/// Construct empty buffer with null data and zero size
Buffer() { reset(); }
/// Construct from memory reference and number of contiguous elements in region
Buffer(T* data, szt size) { reset(data, size); }
/// Construct from vector with compatible memory reference type
template<class U>
Buffer(vector<U>& list) { reset(list.data(), list.size()); }
template<class U>
Buffer(const vector<U>& list) { reset(list.data(), list.size()); }
/// Construct from array with compatible memory reference type
template<class U, szt N>
Buffer(array<U,N>& list) { reset(list.data(), list.size()); }
template<class U, szt N>
Buffer(const array<U,N>& list) { reset(list.data(), list.size()); }
Buffer(const Buffer& rhs) { operator=(rhs); }
Buffer(Buffer&& rhs) { operator=(move(rhs)); }
Buffer& operator=(const Buffer& rhs) { reset(rhs._data, rhs._size); return *this; }
Buffer& operator=(Buffer&& rhs) { reset(rhs._data, rhs._size); rhs.reset(); return *this; }
/// Access element with bounds checking, throws std::out_of_range
T& at(szt pos) const { if (pos >= _size) throw std::out_of_range("invalid buffer index"); return _data[pos]; }
/// Access element without bounds checking
T& operator[](szt pos) const { return _data[pos]; }
/// Returns the first element without bounds checking
T& front() const { return _data[0]; }
/// Returns the last element without bounds checking
T& back() const { return _data[_size - 1]; }
/// Get the referenced memory
T* data() const { return _data; }
/// Get a view of this memory region in range `[pos, pos+size)`
/**
* The view will be clipped against the bounds of this region, possibly resulting in an empty view.
*/
Buffer slice(szt pos, optional<szt> size = optnull) const { szt begin = Alge::clamp(pos, 0, _size), end = size ? Alge::clamp(pos + *size, 0, _size) : _size; return Buffer(_data + begin, end - begin); }
/// Returns an iterator to the beginning
T* begin() const { return _data; }
/// Returns an iterator to the end
T* end() const { return _data + _size; }
/// Returns a reverse iterator to the beginning
reverse_iterator rbegin() const { return reverse_iterator(_data + _size); }
/// Returns a reverse iterator to the end
reverse_iterator rend() const { return reverse_iterator(_data); }
/// Checks whether the buffer does not have any elements
bool empty() const { return !_data || !_size; }
/// Checks whether the buffer has elements
explicit operator bool() const { return !empty(); }
/// Returns the number of elements
szt size() const { return _size; }
/// Check if buffers reference same memory region
bool operator==(const Buffer& rhs) const { return _data == rhs._data && _size == rhs._size; }
bool operator!=(const Buffer& rhs) const { return !operator==(rhs); }
/// Set data to null with zero size
void reset() { _data = nullptr; _size = 0; }
/// Set new data and size
void reset(T* data, szt size) { _data = data; _size = size; }
/// Implicitly convert to const buffer
operator Buffer<const T>() const { return Buffer<const T>(_data, _size); }
private:
T* _data;
szt _size;
};
}
|
C# | UTF-8 | 549 | 2.65625 | 3 | [
"MIT"
] | permissive | using System.IO;
using System.Windows.Media.Imaging;
namespace DrumbleApp.Shared.Infrastructure.Helpers
{
public abstract class Imagable
{
protected static BitmapImage GetImage(byte[] imageBinary)
{
BitmapImage bitmapImage = new BitmapImage();
using (MemoryStream ms = new MemoryStream(imageBinary))
{
bitmapImage.SetSource(ms);
}
bitmapImage.CreateOptions = BitmapCreateOptions.DelayCreation;
return bitmapImage;
}
}
}
|
Python | UTF-8 | 4,667 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | import json
from random import randint
from secp256k1 import FLAG_ALL
from secp256k1.key import SecretKey
from secp256k1.pedersen import Secp256k1, RangeProof
from grin.keychain import ChildKey, Identifier
from grin.proof import MultiPartyBulletProof, TwoPartyBulletProof
def test_proofs(create=False):
secp = Secp256k1(None, FLAG_ALL)
if create:
dct = []
for i in range(100):
secret = SecretKey.random(secp)
nonce = SecretKey.random(secp)
amount = randint(1, 10000000000)
proof = secp.bullet_proof(amount, secret, nonce, bytearray())
dct.append({
"secret": secret.to_hex().decode(),
"nonce": nonce.to_hex().decode(),
"amount": amount,
"proof": proof.to_hex().decode()
})
f = open("proofs_new.json", "w")
f.write(json.dumps(dct, indent=2))
f.close()
return
f = open("tests/proofs.json", "r")
dct = json.loads(f.read())
f.close()
test_count = 0
test_equal_count = 0
for test in dct:
test_count += 1
secret = SecretKey.from_hex(secp, test['secret'].encode())
nonce = SecretKey.from_hex(secp, test['nonce'].encode())
amount = test['amount']
proof_target = RangeProof.from_hex(test['proof'].encode())
proof = secp.bullet_proof(amount, secret, nonce, bytearray())
commit = secp.commit(amount, secret)
assert secp.verify_bullet_proof(commit, proof, bytearray()), "Proof {} fails to verify".format(test_count)
if proof == proof_target:
test_equal_count += 1
assert test_count == test_equal_count, \
"All proofs verify, but only {} out of {} proofs are the same".format(test_equal_count, test_count)
def multi_party_proof(n):
assert n > 1
secp = Secp256k1(None, FLAG_ALL)
mpps = []
child_keys = []
amount = randint(1, 999999)
commit_sum = [secp.commit_value(amount)]
common_nonce = SecretKey.random(secp)
for i in range(n):
child_keys.append(ChildKey(i, Identifier.random(), Identifier.random(), SecretKey.random(secp)))
child_key = child_keys[i]
commit_sum.append(secp.commit(0, child_key.key))
# Total commitment: sum xi*G + v*H
commitment = secp.commit_sum(commit_sum, [])
t_1s = []
t_2s = []
# Each party exports their T1 and T2
for i in range(n):
mpps.append(MultiPartyBulletProof(secp, child_keys[i], amount, commitment, common_nonce))
t_1, t_2 = mpps[i].round_1()
t_1s.append(t_1)
t_2s.append(t_2)
# Each party receives the other T1 and T2 values and adds it to their own
for i in range(n):
for j in range(n):
if i != j:
mpps[i].fill_round_1(t_1s[j], t_2s[j])
tau_xs = []
# Each party exports their tau_x
for i in range(n):
tau_xs.append(mpps[i].round_2())
# One party receives the other tau_x values and adds it to their own
# In this test we simulate each party calculating the proof
for i in range(n):
for j in range(n):
if i != j:
mpps[i].fill_round_2(tau_xs[j])
proofs = []
for i in range(n):
proofs.append(mpps[i].finalize())
assert secp.verify_bullet_proof(commitment, proofs[i], bytearray())
for i in range(n-1):
assert proofs[i+1] == proofs[0]
def test_multi_party_proofs():
for i in range(2, 9):
multi_party_proof(i)
def test_two_party_proof():
secp = Secp256k1(None, FLAG_ALL)
secret_key_a = SecretKey.random(secp)
public_key_a = secret_key_a.to_public_key(secp)
child_key_a = ChildKey(0, Identifier.random(), Identifier.random(), secret_key_a)
secret_key_b = SecretKey.random(secp)
public_key_b = secret_key_b.to_public_key(secp)
child_key_b = ChildKey(0, Identifier.random(), Identifier.random(), secret_key_b)
amount = randint(1, 999999)
commit = secp.commit_sum([secp.commit(amount, secret_key_a), secp.commit(0, secret_key_b)], [])
tpp_a = TwoPartyBulletProof(secp, child_key_a, public_key_b, amount, commit)
tpp_b = TwoPartyBulletProof(secp, child_key_b, public_key_a, amount, commit)
t_1_a, t_2_a = tpp_a.round_1()
t_1_b, t_2_b = tpp_b.round_1()
tpp_a.fill_round_1(t_1_b, t_2_b)
tpp_b.fill_round_1(t_1_a, t_2_a)
tau_x_a = tpp_a.round_2()
tau_x_b = tpp_b.round_2()
tpp_a.fill_round_2(tau_x_b)
tpp_b.fill_round_2(tau_x_a)
proof_a = tpp_a.finalize()
assert secp.verify_bullet_proof(commit, proof_a, bytearray())
proof_b = tpp_b.finalize()
assert proof_a == proof_b
|
C# | UTF-8 | 7,819 | 3.125 | 3 | [] | no_license | using System;
namespace ConsoleApplication1
{
class Program
{
static int num_k = 6;
static int num_alt = 6;
static void Domin(int[,,] bo, int[,] result)
{
for (int i = 0; i < num_k; i++)
for (int j = 0; j < num_alt; j++)
{
result[i, j] = 1;
for (int k = 0; k < num_alt && (result[i, j] != 0); k++)
if (j != k && bo[i, j, k] == 0) result[i, j] = 0;
}
}
static void Block(int[,,] bo, int[,] result)
{
for (int i = 0; i < num_k; i++)
for (int j = 0; j < num_alt; j++)
{
result[i, j] = 1;
for (int k = 0; (k < num_alt) && (result[i, j] != 0); k++)
if ((k != j) && bo[i, k, j] != 0) result[i, j] = 0;
}
}
static void Tournament(int[,,] bo, double[,] res)
{
Console.WriteLine("Таблица результатов турнира:");
for (int i = 0; i < num_k; i++)
{
int num = i + 1;
Console.Write("Критерий " + num + ": ");
for (int j = 0; j < num_alt; j++)
{
res[i, j] = 0;
for (int k = 0; k < num_alt; k++)
if ((k != j) && (bo[i, j, k] != 0))
if (bo[i, k, j] == 0) res[i, j] += 1;
Console.Write(res[i, j] + " ");
}
Console.WriteLine();
}
}
static void Weight(double[,] result, double[] znach)
{
// Для вывода
for (int i = 0; i < num_k; i++)
{
int num = i + 1;
Console.Write("Принтер " + num + ": ");
for (int j = 0; j < num_alt; j++)
{
result[j, i] = result[j, i] * znach[j];
Console.Write(result[j, i] + "\t");
}
Console.WriteLine();
}
// Для подсчёта
Console.Write("\nКоличество очков:\n");
for (int i = 0; i < num_k; i++)
{
double x = 0;
for (int j = 0; j < num_alt; j++)
{
x += result[j, i];
}
result[num_alt - 1, i] = x;
int num = i + 1;
Console.WriteLine("Принтер " + num + ": " + x);
}
}
static void FunCh(int[,] result)
{
for (int i = 0; i < num_alt; i++)
{
int num = 0;
for (int j = 0; j < num_k; j++)
num += result[j, i] != 0 ? 1 : 0;
if (num >= num_k / 2)
result[num_k - 1, i] = 1;
else
result[num_k - 1, i] = 0;
}
}
static void PrintVector(int[] result)
{
int i;
bool ch = false;
for (i = 0; i < num_alt; i++)
if (result[i] == 1)
{
if (ch)
Console.Write(", ");
ch = true;
Console.Write(i + 1);
}
if (!ch)
Console.WriteLine("нет предложений");
else
Console.WriteLine("");
}
static void Main()
{
double[] znach = { 0.25, 0.2, 0.1, 0.1, 0.15, 0.15 };
int[,,] bo = { { { 1, 1, 1, 1, 1, 1 },
{ 0, 0, 1, 1, 1, 1 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0 },
{ 0, 0, 1, 0, 1, 0 },
{ 0, 0, 1, 1, 1, 0 } },
{ { 1, 1, 0, 0, 1, 0 },
{ 0, 1, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 1 },
{ 0, 1, 1, 0, 1, 0 },
{ 1, 1, 1, 1, 1, 1 } },
{ { 1, 1, 1, 1, 1, 1 },
{ 1, 1, 0, 1, 0, 1 },
{ 0, 1, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 1, 1 } },
{ { 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 0, 0, 0 },
{ 1, 1, 1, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 0 },
{ 0, 0, 0, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1 } },
{ { 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 0, 0, 1 },
{ 1, 1, 1, 0, 0, 1 },
{ 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 0, 1 } },
{ { 1, 1, 1, 0, 1, 0 },
{ 0, 1, 1, 0, 1, 0 },
{ 0, 1, 1, 0, 1, 0 },
{ 0, 0, 0, 1, 1, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 1, 1, 1, 1, 1, 1 } }
};
int[,] resDom = new int[num_k, num_alt];
int[,] resBloc = new int[num_k, num_alt];
double[,] resTour = new double[num_k, num_alt];
double[,] resWeight = new double[num_k, num_alt];
int[,] resCh = new int[num_k, num_alt];
double[] tempd = new double[num_alt];
int[] tempi = new int[num_alt];
Console.WriteLine("Механизм блокировки\n");
Block(bo, resBloc);
for (int i = 0; i < num_k; i++)
{
Console.Write("Критерий " + (i + 1));
Console.Write("\tПредложения: ");
for (int j = 0; j < num_alt; j++)
if (resBloc[i, j] == 1)
Console.Write((j + 1) + " ");
Console.WriteLine();
}
FunCh(resBloc);
Console.Write("Итог: ");
for (int i = 0; i < num_alt; i++)
tempi[i] = resBloc[num_k - 1, i];
PrintVector(tempi);
Console.WriteLine("\n----------------------------------------------------------\nМеханизм доминирования\n");
Domin(bo, resDom);
for (int i = 0; i < num_k; i++)
{
Console.Write("Критерий " + (i + 1));
Console.Write("\tПредложения: ");
for (int j = 0; j < num_alt; j++)
if (resDom[i, j] == 1)
Console.Write((j + 1) + " ");
Console.WriteLine();
}
FunCh(resDom);
Console.Write("Итог: ");
for (int i = 0; i < num_alt; i++)
tempi[i] = resDom[num_k - 1, i];
PrintVector(tempi);
Console.WriteLine("\n----------------------------------------------------------\nТурнирный механизм\n");
Tournament(bo, resTour);
Console.WriteLine("\nТаблица результатов турнира * коэффициент значимости:");
Weight(resTour, znach);
Console.WriteLine();
Console.ReadLine();
}
}
}
|
Python | UTF-8 | 3,408 | 3.765625 | 4 | [] | no_license | class Board(object):
def __init__(self, text=None):
self._data = list(text.replace('\n', '')) if text else [' '] * 9
def corners(self):
return {(x, y): self[(x, y)]
for (x, y) in [(0, 0), (2, 0), (0, 2), (2, 2)]}
def sides(self):
return {(x, y): self[(x, y)]
for (x, y) in [(1, 0), (0, 1), (2, 1), (1, 2)]}
def center(self):
return {(1, 1): self[(1, 1)]}
def horizontals(self):
keys = tuple(tuple((x, y) for x in xrange(3))
for y in xrange(3))
return {key: tuple(self[coords] for coords in key)
for key in keys}
def verticals(self):
keys = tuple(tuple((x, y) for y in xrange(3))
for x in xrange(3))
return {key: tuple(self[coords] for coords in key)
for key in keys}
def diagonals(self):
keys = (tuple((x, x) for x in xrange(3)),
tuple((2 - x, x) for x in xrange(3)))
return {key: tuple(self[coords] for coords in key)
for key in keys}
def __getitem__(self, key):
x, y = key
if self.is_out_of_bounds(x, y):
raise IndexError
return self._data[y * 3 + x]
def __setitem__(self, key, value):
x, y = key
if self.is_out_of_bounds(x, y):
raise IndexError
self._data[y * 3 + x] = value
def is_out_of_bounds(self, x, y):
return not self.is_in_bounds(x, y)
def is_in_bounds(self, x, y):
return ((0 <= x <= 2) and (0 <= y <= 2))
def __iter__(self):
return iter(((x, y), self[x, y]) for y in xrange(3) for x in xrange(3))
def __contains__(self, item):
return item in self._data
def as_string(self, pretty = False):
lines = []
for y in xrange(3):
lines.append(''.join(self[(x, y)] for x in xrange(3)))
if pretty:
lines = [('|%s|' % line) for line in lines]
bar = '+---+'
lines.append(bar)
lines.insert(0, bar)
return '\n'.join(lines)
def is_occupied(self, x, y):
return self[(x, y)] != ' '
def is_empty(self, x, y):
return not self.is_occupied(x, y)
def opposite(self, x, y):
return (2 - x, 2 - y)
class TicTacToeBoard(Board):
def has_winner(self):
return self.winner() is not None
def winner(self):
board = self
cross_wins = 0
nought_wins = 0
for line in board.verticals().values() + board.horizontals().values() + board.diagonals().values():
if line.count('X') == 3:
cross_wins += 1
if line.count('O') == 3:
nought_wins += 1
if cross_wins != 0 and nought_wins != 0:
raise RuntimeError("Both players can't win simultaneously!")
# By the way, it is possible (in theory)
# for `cross_wins` to be equal to 2:
#
# +---+
# |XOO|
# |XOO|
# |XXX|
# +---+
#
# Here you can clearly see two lines
# (1 vertical and 1 horizontal)
# entirely occupied by crosses.
return 'X' if (cross_wins != 0) else 'O' if (nought_wins != 0) else None
def has_ended_in_draw(self):
return not self.has_winner() and ' ' not in self
|
Markdown | UTF-8 | 1,133 | 2.890625 | 3 | [] | no_license | # JS13K 2020
This repository allow you to quick start your JS13K project to develop, compile, minify and zip you JS13K project.
Uses adfab-gulp-boilerplate to compile sass or less, concat you JS, minify your assets...with additional tasks to zip and improve minification
[You can play the game here thanks to the GitHub Pages](https://jonathan-vallet.github.io/js13k-2020/index.html).
## Installing
Run `npm install` in the project directory to install all needed packages.
## Compile game
`gulp` to compile your files
Project will be generated in `/www` folder.
## Generate final game
run `gulp --production && gulp zip`
Your game.zip file will be generated in `/dist` folder.
## Goal
Create a game mixing "Slay the Spire" and "Dicey dungeons".
A desktop PVE version (and monetization perhaps) to build a deck and choosing a path like Slay the spire
A PVP version to build a deck and fight other players
Same system than Slay the spire, except that we have dice, and cards drawn are played using dice depending of several conditions like in Dicey Dungeon.
## TODO list
Too many things for now... I'll complete later! |
Python | UTF-8 | 752 | 3.546875 | 4 | [] | no_license | # Hint: use Google to find python function
####a)
from dateutil import parser
from datetime import datetime
date_start = '01-02-2013'
date_stop = '07-28-2015'
date_start_object_1 = parser.parse(date_start)
date_stop_object_1 = parser.parse(date_stop)
print (date_stop_object_1 - date_start_object_1)
####b)
date_start = '12312013'
date_stop = '05282015'
date_start_object_2 = datetime.strptime(date_start,'%m%d%Y')
date_stop_object_2 = datetime.strptime(date_stop,'%m%d%Y')
print (date_stop_object_2 - date_start_object_2)
####c)
date_start = '15-Jan-1994'
date_stop = '14-Jul-2015'
date_start_object_3 = parser.parse(date_start)
date_stop_object_3 = parser.parse(date_stop)
print (date_stop_object_3 - date_start_object_3)
|
C# | UTF-8 | 1,380 | 3.109375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace TechFestXmlSolution
{
/// <summary>
/// class CounterClass is used to get Cpu usage and timing calculations
/// </summary>
class CounterClass
{
public CounterClass()
{
}
PerformanceCounter counter = null;
DateTime startTime;
TimeSpan timeTaken;
public float _cpuUsage=0;
public List<float> _numberOfHit=new List<float>(1000) ;
public float CpuUsage
{
get
{
if (counter == null)
{
counter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
}
return (counter.NextValue());
}
}
#region to calculate time span
public DateTime StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
}
}
public TimeSpan TimeTaken
{
get
{
timeTaken = DateTime.Now.Subtract(startTime);
return timeTaken;
}
}
#endregion
}
}
|
Java | UTF-8 | 1,302 | 2.921875 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package visitorpattern;
import abstracao.AbstractElement;
import abstracao.IElement;
import abstracao.IVisitor;
/**
*
* @author Emerson
*/
public class Professor extends AbstractElement implements IElement{
private Double altura;
private Integer publicacoes;
private IVisitor visitor;
public Professor(Double altura, Integer publicacoes) {
this.altura = altura;
this.publicacoes = publicacoes;
}
@Override
public void accept(IVisitor visitor) {
this.visitor = visitor;
visitor.visitElement(this);
}
public Double getAltura() {
return altura;
}
public void setAltura(Double altura) {
this.altura = altura;
}
public Integer getPublicacoes() {
return publicacoes;
}
public void setPublicacoes(Integer publicacoes) {
this.publicacoes = publicacoes;
}
@Override
public Double execute() {
if(visitor instanceof VisitorAlturaMedia)
return this.altura;
return 0.0;
}
}
|
JavaScript | UTF-8 | 5,245 | 2.65625 | 3 | [] | no_license | import DomRegisteredProperty from "../Classes/domRegisteredProperty"
import DomRegisteredModule from "../Classes/domRegisteredModule"
import DOM from "../Classes/dom"
export default class DOMController {
static #settings = {
modules: [
],
properties: [
],
modificators: [
],
config: {
},
errorsIgnore: false,
}
// #region Properties
static registerProperty(property) {
if (this.#settings.config.reportRegistration === true) this.log("New DOM property: ", property)
if (typeof property.name !== "string" || !new RegExp("^[a-zA-Z0-9]+$").test(property.name)) throw new TypeError("Incorrect name")
if (typeof property.unique !== "string" || !new RegExp("^[a-zA-Z0-9]+$").test(property.unique)) throw new TypeError("Incorrect unique")
if (typeof property.required !== "boolean") throw new TypeError("Required must be boolean")
if (typeof property.handler !== "function") throw new TypeError("Handler must be function")
if (typeof property.error !== "function") throw new TypeError("Error must be function")
let compMethod
if (this.#settings.config.useFunctionsComparation) {
compMethod = (v) => v.handler.toString() === property.handler.toString()
&& v.error.toString() === property.error.toString()
} else {
compMethod = (v) => v.unique === property.unique
}
const uncomp = this.#settings.properties.findIndex(compMethod)
if (uncomp !== -1) throw new Error(`Property is already registered with ID ${uncomp}`)
const id = this.#settings.properties.length
this.#settings.properties.push(property)
return new DomRegisteredProperty(id)
}
static getPropertyData(id) {
if (!Number.isInteger(id)) throw new TypeError("ID must be integer")
const g = this.#settings.properties[id]
if (typeof g === "object") return g
return false
}
static getProperties() {
return this.#settings.properties
}
// #endregion
// #region Modules
static registerModule(module) {
if (typeof module !== "object"
|| typeof module.onRender !== "function") throw new TypeError("Incorrect module")
const id = this.#settings.modules.length
this.#settings.modules.push()
return new DomRegisteredModule(id)
}
static getModuleData(id) {
if (!Number.isInteger(id)) throw new TypeError("ID must be integer")
const g = this.#settings.modules[id]
if (typeof g === "object") return g
return false
}
static getModules() {
return this.#settings.modules
}
// #endregion
static get config() {
return this.#settings.config
}
static setConfig(v) {
if (typeof v !== "object") throw new TypeError("Config must be object")
this.#settings.config = { ...this.#settings.config, ...v }
}
static errorIgnore(s) {
const g = this.#settings.errorsIgnore
const def = false
s = s.toString()
if (typeof g === "boolean") return g
if (Array.isArray(g)) {
const m = g.indexOf(s)
if (m !== -1) return true
}
return def
}
static setErrorIgnore(n) {
if (typeof n === "boolean") {
this.#settings.errorsIgnore = n
return true
}
if (!n.every((e) => typeof e === "string")) throw new TypeError("Every item must be string")
this.#settings.errorsIgnore = n
return true
}
static registerModificator({
name, handler, get, set,
}) {
if (typeof name !== "string") throw new TypeError(`Modificator name must be string, ${typeof name} given`)
if (!new RegExp("^[a-zA-Z]{3,20}$").test(name)) throw new TypeError("Incorrect Modificator name")
if (this.#settings.modificators[name] !== undefined
|| name in DOM.prototype) throw new Error(`Method ${name} is already declared`)
Object.defineProperty(DOM.prototype, name,
{
...(handler ? { value: handler, writable: false } : {}),
...(get ? { get } : {}),
...(set ? { set } : {}),
})
this.#settings.modificators[name] = handler
}
static getModificator(name) {
if (!(name in this.#settings.modificators) || typeof this.#settings.modificators[name] !== "function") {
throw new Error("Incorrect modificator")
}
return this.#settings.modificators[name]
}
static getModificators() {
return this.#settings.modificators
}
static log(...data) {
const event = new CustomEvent("DOMController-Report", { detail: { type: "log", data } })
window.dispatchEvent(event)
}
static error(...data) {
const event = new CustomEvent("DOMController-Report", { detail: { type: "error", data } })
window.dispatchEvent(event)
}
static warn(...data) {
const event = new CustomEvent("DOMController-Report", { detail: { type: "warn", data } })
window.dispatchEvent(event)
}
}
|
Python | UTF-8 | 4,448 | 4.375 | 4 | [
"MIT"
] | permissive | #!/usr/local/bin/python3
# encoding:utf-8
"""
python3 面向对象
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据。
方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
实例变量:定义在方法中的变量,只作用于当前实例的类。
继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟"是一个(is-a)"关系(例图,Dog是一个Animal)。
实例化:创建一个类的实例,类的具体对象。
方法:类中定义的函数。
对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
类定义
class ClassName:
<statement-1>
.
.
.
<statement-N>
"""
class Person:
age = 0
name = ""
def __init__(self, age, name):
self.age = age
self.name = name
def toString(self):
return repr("{}'s age is {}".format(self.name, self.age))
def printSelf(self):
print(self)
print(self.__class__)
# person = Person(26, "Bob")
# print(person.toString())
# person.printSelf()
class People:
name = ""
age = 0
__weight = 0.0
__height = 0.0
def __init__(self, name, age, weight, height):
self.name = name
self.age = age
self.__weight = weight
self.__height = height
def speak(self):
print("%s 说:我今年 %d 岁" % (self.name, self.age))
def weight(self):
return self.__weight
def height(self):
return self.__height
people = People("runnoob", 26, 64.5, 160.0)
people.speak()
print(people.height())
print(people.weight())
"""
继承
class DerivedClassName(BaseClassName1):
<statement-1>
.
.
.
<statement-N>
"""
# 单例模继承
class Student(People):
grade = ''
def __init__(self, name, age, weight, height, grade):
People.__init__(self, name, age, weight, height)
self.grade = grade
def speak(self):
print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))
# student = Student("Alice", 15, 45, 157, 2)
# student.speak()
# print(student.getWeight())
# print(student.getHeight())
class Speaker:
topic = ''
name = ''
def __init__(self, name, topic):
self.name = name
self.topic = topic
def speak(self):
print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))
class Sample(Speaker, Student):
def __init__(self, name, age, weight, height, grade, topic):
Speaker.__init__(self, name, topic)
Student.__init__(self, name, age, weight, height, grade)
sample = Sample("Alice", 15, 45, 157, 2, "Python")
sample.speak() # 方法名同,默认调用的是在括号中排前地父类的方法
"""
方法重写
"""
class Parent: # 定义父类
def speak(self):
print('调用父类方法')
class Child(Parent): # 定义子类
def speak(self):
print('调用子类方法')
child = Child() # 子类实例
child.speak() # 子类调用重写方法
"""
类属性与方法
类的私有属性
__private_attr:两个下划线开头,声明该属性为私有,不能在类地外部被使用或直接访问。在类内部的方法中使用时 self.__private_attr。
类的方法
在类地内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。
self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定是用 self。
类的私有方法
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类地外部调用。self.__private_methods。
"""
|
Markdown | UTF-8 | 4,927 | 2.578125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Azure CLI skriptexempel - omstart VMs | Microsoft Docs
description: 'Skriptexempel Azure CLI - omstart av virtuella datorer efter tagg och -ID: t'
services: virtual-machines-linux
documentationcenter: virtual-machines
author: allclark
manager: douge
editor: tysonn
tags: azure-service-management
ms.assetid:
ms.service: virtual-machines-linux
ms.devlang: azurecli
ms.topic: sample
ms.tgt_pltfrm: vm-linux
ms.workload: infrastructure
ms.date: 03/01/2017
ms.author: allclark
ms.custom: mvc
ms.openlocfilehash: ea114f484c774573b7d219cff9102a7308af356e
ms.sourcegitcommit: 6699c77dcbd5f8a1a2f21fba3d0a0005ac9ed6b7
ms.translationtype: MT
ms.contentlocale: sv-SE
ms.lasthandoff: 10/11/2017
---
# <a name="restart-vms"></a>Starta om virtuella datorer
[!INCLUDE [sample-cli-install](../../../includes/sample-cli-install.md)]
[!INCLUDE [quickstarts-free-trial-note](../../../includes/quickstarts-free-trial-note.md)]
Det här exemplet visas ett par olika sätt att hämta vissa virtuella datorer och starta om dem.
Först startar om alla virtuella datorer i resursgruppen.
```bash
az vm restart --ids $(az vm list --resource-group myResourceGroup --query "[].id" -o tsv)
```
Andra hämtar taggade virtuella datorer med hjälp av `az resouce list` och filtrerar till resurser som virtuella datorer och startar om dessa virtuella datorer.
```bash
az vm restart --ids $(az resource list --tag "restart-tag" --query "[?type=='Microsoft.Compute/virtualMachines'].id" -o tsv)
```
Det här exemplet fungerar i ett Bash-gränssnitt. Alternativen på Azure CLI skriptkörning på Windows-klient kan se [kör Windows Azure CLI](../windows/cli-options.md).
## <a name="sample-script"></a>Exempelskript
Exemplet har tre skript.
Den första som etablerar de virtuella datorerna.
Den använder alternativet Nej vänta så att kommandot returnerar utan att vänta på varje virtuell dator som ska etableras.
Andra väntar på att de virtuella datorerna till helt etablerad.
Skriptet tredje startar om alla de virtuella datorerna som var etablerade och sedan bara taggade virtuella datorer.
### <a name="provision-the-vms"></a>Etablera virtuella datorer
Det här skriptet skapar en resursgrupp och skapar sedan tre virtuella datorer startas om.
Två av dem märks.
[!code-azurecli-interactive[main](../../../cli_scripts/virtual-machine/restart-by-tag/provision.sh "Provision the VMs")]
### <a name="wait"></a>Vänta
Det här skriptet kontrollerar etablering statusen var 20 sekunder tills alla tre virtuella datorer är etablerad, eller en av dem inte kan etablera.
[!code-azurecli-interactive[main](../../../cli_scripts/virtual-machine/restart-by-tag/wait.sh "Wait for the VMs to be provisioned")]
### <a name="restart-the-vms"></a>Starta om de virtuella datorerna
Det här skriptet startar om alla virtuella datorer i resursgruppen och startas sedan om bara taggade virtuella datorer.
[!code-azurecli-interactive[main](../../../cli_scripts/virtual-machine/restart-by-tag/restart.sh "Restart VMs by tag")]
## <a name="clean-up-deployment"></a>Rensa distribution
Efter skriptexempel har körts användas följande kommando för att ta bort resursgrupper, virtuella datorer och alla relaterade resurser.
```azurecli-interactive
az group delete -n myResourceGroup --no-wait --yes
```
## <a name="script-explanation"></a>Skriptet förklaring
Det här skriptet använder följande kommandon för att skapa en resursgrupp, virtuella, tillgänglighetsuppsättning, belastningsutjämnare och alla relaterade resurser. Varje kommando i tabellen länkar till kommandot viss dokumentation.
| Kommando | Anteckningar |
|---|---|
| [Skapa AZ grupp](https://docs.microsoft.com/cli/azure/group#az_group_create) | Skapar en resursgrupp som är lagrade i alla resurser. |
| [Skapa AZ vm](https://docs.microsoft.com/cli/azure/vm/availability-set#az_vm_availability_set_create) | Skapar de virtuella datorerna. |
| [AZ vm lista](https://docs.microsoft.com/cli/azure/vm#az_vm_list) | Används med `--query` att säkerställa att de virtuella datorerna etableras innan du startar om dem, och för att hämta ID för virtuella datorer starta om dem. |
| [lista över resurser AZ](https://docs.microsoft.com/cli/azure/vm#az_vm_list) | Används med `--query` att hämta ID: N för de virtuella datorerna med taggen. |
| [AZ vm-omstart](https://docs.microsoft.com/cli/azure/vm#az_vm_list) | Startar om de virtuella datorerna. |
| [ta bort grupp AZ](https://docs.microsoft.com/cli/azure/vm/extension#az_vm_extension_set) | Tar bort en resursgrupp, inklusive alla kapslade resurser. |
## <a name="next-steps"></a>Nästa steg
Mer information om Azure CLI finns [Azure CLI dokumentationen](https://docs.microsoft.com/cli/azure/overview).
Ytterligare virtuella CLI skriptexempel finns i den [virtuella Azure Linux-datorn dokumentationen](../linux/cli-samples.md?toc=%2fazure%2fvirtual-machines%2flinux%2ftoc.json).
|
Go | UTF-8 | 2,971 | 3.140625 | 3 | [
"MIT"
] | permissive | package examples
import (
"fmt"
"strconv"
"strings"
"github.com/go-color-term/go-color-term/coloring"
)
const innerBoxSize = 182
type ColorMatrixExample struct{}
func (example *ColorMatrixExample) GetTitle() string {
return "8-bit color matrix"
}
func (example *ColorMatrixExample) GetDescription() string {
return "Color matrix for the 0-255 (8-bit) colors."
}
func (example *ColorMatrixExample) Run() {
drawBoxHeader()
for i := 0; i <= 255; i++ {
colorWhite := coloring.New().Color(coloring.BRIGHTWHITE).Background().Color(i).Print()
colorBlack := coloring.New().Black().Background().Color(i).Print()
var color coloring.ColorizerPrint
if i < 16 {
if i == 0 {
drawCustomContent(fmt.Sprintf("%sStandard colors%sHigh-intensity colors%s", strings.Repeat(" ", 37), strings.Repeat(" ", 75), strings.Repeat(" ", 34)))
drawBoxOpen()
}
padding := " "
if i < 10 {
padding += " "
}
if i < 8 {
color = colorWhite
} else {
color = colorBlack
}
color(padding + strconv.Itoa(i) + " ")
if i == 7 {
fmt.Print(" ")
}
if i == 15 {
drawBoxEnd()
}
} else {
if i == 16 {
drawEmptyBoxLine()
drawCenteredTitles("6 x 6 x 6 matrix (216 colors)")
}
if i < 232 {
if (i-16)%36 == 0 {
drawBoxOpen()
}
if (i-17)-(i-16)/36*36 <= 16 {
color = colorWhite
} else {
color = colorBlack
}
padding := " "
if i < 100 {
padding += " "
}
color(" " + strconv.Itoa(i) + padding)
if (i-15)%36 == 0 {
drawBoxEnd()
}
} else {
if i == 232 {
drawEmptyBoxLine()
drawCenteredTitles("Grayscale colors")
drawBoxOpenPadded(31)
}
if i < 244 {
color = colorWhite
} else {
color = colorBlack
}
color(" " + strconv.Itoa(i) + " ")
if i == 255 {
drawBoxEndPadded(31)
}
}
}
}
drawBoxFooter()
}
func drawBoxHeader() {
fmt.Printf("┌%s┐\n", strings.Repeat("─", innerBoxSize))
}
func drawBoxFooter() {
fmt.Printf("└%s┘\n", strings.Repeat("─", innerBoxSize))
fmt.Println()
}
func drawEmptyBoxLine() {
fmt.Printf("│%s│\n", strings.Repeat(" ", innerBoxSize))
}
func drawBoxOpen() {
drawBoxOpenPadded(1)
}
func drawBoxEnd() {
drawBoxEndPadded(1)
}
func drawBoxOpenPadded(padding int) {
fmt.Printf("│%s", strings.Repeat(" ", padding))
}
func drawBoxEndPadded(padding int) {
fmt.Printf("%s│\n", strings.Repeat(" ", padding))
}
func drawCenteredTitles(titles ...string) {
titlesLen := 0
for _, title := range titles {
titlesLen += len(title)
}
paddingSize := (innerBoxSize - titlesLen) / (len(titles) + 1)
padding := strings.Repeat(" ", paddingSize)
fmt.Printf("│%s", padding)
for _, title := range titles {
fmt.Printf("%s%s", title, padding)
}
fmt.Printf("%s│\n", strings.Repeat(" ", innerBoxSize-titlesLen-paddingSize*(len(titles)+1)))
}
func drawCustomContent(s string) {
fmt.Printf("│%s│\n", s)
}
|
Java | UTF-8 | 2,678 | 1.875 | 2 | [] | no_license | package com.gudeng.commerce.gd.admin.service.impl;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.caucho.hessian.client.HessianProxyFactory;
import com.gudeng.commerce.gd.admin.service.PreSaleDetailToolService;
import com.gudeng.commerce.gd.admin.util.GdProperties;
import com.gudeng.commerce.gd.order.dto.PreSaleDetailDTO;
import com.gudeng.commerce.gd.order.entity.PreSaleDetailEntity;
import com.gudeng.commerce.gd.order.service.PreSaleDetailService;
@Service
public class PreSaleDetailToolServiceImpl implements PreSaleDetailToolService {
/**
* 属性文件,用于获得gd-setting.properties配置文件的值
*/
@Autowired
public GdProperties gdProperties;
private static PreSaleDetailService preSaleDetailService;
private PreSaleDetailService gethessianPreSaleDetailService()
throws MalformedURLException {
String hessianUrl = gdProperties.getPreSaleDetailUrl();
if (preSaleDetailService == null) {
HessianProxyFactory factory = new HessianProxyFactory();
factory.setOverloadEnabled(true);
preSaleDetailService = (PreSaleDetailService) factory.create(PreSaleDetailService.class, hessianUrl);
}
return preSaleDetailService;
}
@Override
public Long insertEntity(PreSaleDetailEntity obj) throws Exception {
return gethessianPreSaleDetailService().insertEntity(obj);
}
@Override
public int deleteById(Long id) throws Exception {
return gethessianPreSaleDetailService().deleteById(id);
}
@Override
public int batchDeleteById(List<Long> idList) throws Exception {
return gethessianPreSaleDetailService().batchDeleteById(idList);
}
@Override
public int updateDTO(PreSaleDetailDTO obj) throws Exception {
return gethessianPreSaleDetailService().updateDTO(obj);
}
@Override
public int batchUpdateDTO(List<PreSaleDetailDTO> objList) throws Exception {
return gethessianPreSaleDetailService().batchUpdateDTO(objList);
}
@Override
public int getTotal(Map<String, Object> map) throws Exception {
return gethessianPreSaleDetailService().getTotal(map);
}
@Override
public PreSaleDetailDTO getById(Long id) throws Exception {
return gethessianPreSaleDetailService().getById(id);
}
@Override
public List<PreSaleDetailDTO> getListByConditionPage(Map<String, Object> map) throws Exception {
return gethessianPreSaleDetailService().getListByConditionPage(map);
}
@Override
public List<PreSaleDetailDTO> getListByCondition(Map<String, Object> map) throws Exception {
return gethessianPreSaleDetailService().getListByCondition(map);
}
}
|
Java | UTF-8 | 1,141 | 2.765625 | 3 | [] | no_license | package com.example.rest.models;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.List;
/**
*
* This Interface describe all the interaction with the database
*
*/
public interface IUserrepository {
/**
*
* Add a new user
* @param user
*/
public void save(Utilisateur user);
/**
* Fetch all users
*/
public List<Utilisateur> findAll() ;
/**
* Find an user by his id
* @param id
*/
public Utilisateur findById(int id) ;
/**
*
* Update an user infos
*/
public void update(Utilisateur user) ;
/**
*
* Delete an User by Id
* @param id
*/
public void delete(int id ) ;
/**
*
* Initilialize the database
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public void init() throws NoSuchAlgorithmException, InvalidKeySpecException;
/**
* Check if an user exist in the databse
* @param login
* @param password
*/
public boolean exist(String login , String password) ;
}
|
Python | UTF-8 | 4,162 | 2.546875 | 3 | [] | no_license | import numpy as np
import math
import random
import string
import os
import sys
import cPickle as pickle
from threading import Thread, RLock
import sketch
import opti
import results
lock = RLock()
if len(sys.argv) < 2:
print "Missing argument"
print "Usage: python run_random_cos.py <datasetFolder>"
exit(1)
datasetFolder = sys.argv[1]
print "Got dataset folder:", datasetFolder
if not datasetFolder.endswith('/'):
datasetFolder = datasetFolder + '/'
files = []
for f in os.listdir(datasetFolder):
if f.endswith('.csv'):
files.append(datasetFolder + '/' + f)
with open(datasetFolder + 'params.log', 'r') as f:
for line in f:
data = line.rstrip('\n').split(' ')
if data[0] == "u":
u = int(data[2])
break
output = 'output/' + datasetFolder.replace('datasets/', '')
os.system('mkdir -p ' + output)
def cosine(pa, pb):
ab = 0
aa = 0
bb = 0
for pair1 in pa:
aa += pair1[1] * pair1[1]
for pair2 in pb:
if pair1[0] == pair2[0]:
ab += pair1[1] * pair2[1]
break
for pair2 in pb:
bb += pair2[1] * pair2[1]
if aa == 0 or bb == 0:
return float('NaN')
return ab / math.sqrt(float(aa * bb))
def cosineCM(s1, s2, w, d):
minCos = sys.maxsize
for j in range(d):
ab = 0
aa = 0
bb = 0
for i in range(w):
x = s1.at(i, j)
y = s2.at(i, j)
ab += x * y
aa += x * x
bb += y * y
if aa != 0.0 and bb != 0.0:
s = ab / math.sqrt(aa * bb)
if s < minCos:
minCos = s
if minCos == sys.maxsize:
return float('NaN')
return minCos
class OneSimulation(Thread):
def __init__(self, datasets, u, q, X, Y, Z, names):
Thread.__init__(self)
self.datasets = datasets
self.u = u
self.q = q
self.X = X
self.Y = Y
self.Z = Z
self.names = names
def run(self):
i = 0
for f1 in files:
for f2 in files:
if f1 != f2:
i += 1
print "Progression:", i, "/", (len(files) - 1) * len(files)
r = runSimulation(self.datasets, f1, f2, nValues[f1], self.u, self.q)
with lock:
self.X.append(nValues[f1])
self.Y.append(nValues[f2])
for k in range(len(self.names)):
self.Z[k].append(r[k])
def runSimulation(datasets, f1, f2, n, u, q):
pairs1 = datasets[f1]
pairs2 = datasets[f2]
w, d = opti.getSize(n, u, q)
eps = np.exp(1) / w
delta = np.exp(-d)
#print "n =", n, "u =", u, "q =", q, "width =", w, "depth =", d
error = 0
s1 = sketch.Sketch(delta, eps, 10000, 0)
s2 = sketch.Sketch(delta, eps, 10000, 0)
for pair in pairs1:
s1.update(pair[0], pair[1])
for pair in pairs2:
s2.update(pair[0], pair[1])
y = cosine(pairs1, pairs2)
x = cosineCM(s1, s2, w, d)
#print "cosine is", y, "we got", x
error += abs(x - y)
gamma = opti.gammaDeniability(w, d, n, u)
beta = opti.pointErrorProba(w, d, n)
size = w * d
fmeasure = opti.Fmeasure(w, d, n, u, q)
p = opti.probaInserted(w, d, n, u)
return (error, gamma, beta, size, w, d, fmeasure, p)
### MAIN
nValues = {}
datasets = {}
for filename in files:
pairs = []
with open(filename, 'r') as f:
for line in f:
data = line.rstrip('\n').rstrip('\r').split(',')
key = data[0]
value = int(data[1])
pairs.append((key, value))
datasets[filename] = pairs
nValues[filename] = len(pairs)
#qList = np.array([1.0 / 4.0, 1.0 / 3.0, 0.5, 1.0, 2.0, 3.0, 4.0], dtype=float)
#indexList = np.arange(len(qList))
names = ['error', 'gamma', 'beta', 'size', 'width', 'depth', 'fmeasure', 'proba_inserted']
X = []
Y = []
Z = [[] for k in range(len(names))]
#threads = []
#for index in indexList:
#q = qList[index]
#thread = OneSimulation(datasets, u, q, index, X, Y, Z, names)
#threads.append(thread)
#thread.start()
#for t in threads:
#t.join()
thread = OneSimulation(datasets, u, 4.0, X, Y, Z, names)
thread.start()
thread.join()
r = results.Results(output, names, X, Y, Z)
r.setX("Number of exported keys 1")
r.setY("Number of exported keys 2")
#r.setY("Priority", indexList, ["F" + str(q)[:4] for q in qList])
with open(output + "data.p", "wb") as f:
pickle.dump(r, f)
|
PHP | UTF-8 | 741 | 3.296875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0"
] | permissive | <?php
function print_resultado($array) {
$n = count($array);
if ($n == 0) {
echo "<p>Nenhum registro foi encontrado pela consulta.</p>";
return;
}
$cabecalho = array();
foreach ($array[0] as $chave => $value)
$cabecalho[] = $chave;
echo '<table class="table table-striped">';
echo '<thead>';
echo '<tr>';
echo '<th>';
echo implode("</th><th>", $cabecalho);
echo '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
foreach ($array as $linha) {
echo '<tr>';
foreach ($linha as $coluna => $valor) {
echo '<td>';
echo $valor;
echo '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.