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
|
---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 554 | 2.59375 | 3 |
[] |
no_license
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $guarded = [];
// a product belongs to one supplier (restuaraunt)
public function supplier()
{
return $this->belongsTo('App\Supplier');
}
/**
* Return collection of products by supplier
* @param integer $id is supplier_id
*/
public function productsBySupplier($id)
{
$supplier = Supplier::find($id);
$products = $supplier->products()->get();
return $products;
}
}
|
Python
|
UTF-8
| 467 | 3.90625 | 4 |
[] |
no_license
|
def grade_func():
i = 1
for i in range(0,10):
import random
rannum = random.random()
grade = rannum*100
if grade> 89 and grade < 100:
print "score {}; Your grade is A".format(grade)
elif grade > 79 and grade < 90:
print "score {}; Your grade is B".format(grade)
elif grade > 69 and grade < 80:
print "score {}; Your grade is C".format(grade)
elif grade > 59 and grade < 70:
print "score {}; Your grade is D".format(grade)
grade_func()
|
JavaScript
|
UTF-8
| 1,705 | 2.65625 | 3 |
[] |
no_license
|
const mongoose = require("mongoose");
const Vote = require("../models/vote");
const Cat = require("../models/cat");
/**
* logs a vote for a pair of cats
* updates vote statistics for the cats
*/
exports.vote = async (req, res, err) => {
const params = req.params;
const vote = new Vote({
_id: new mongoose.Types.ObjectId(),
votedForCatId: params.votedForCatId,
votedAgainstCatId: params.votedAgainstCatId,
repeatedVote: params.repeatedVote,
repetitionSelection: params.repetitionSelection
});
try {
await vote.save();
//await update cat 1
await Cat.updateOne({ _id: params.votedForCatId }, { $inc: { votedFor: 1, totalVoted: 1 }, $set: { lastVotedFor: new Date() } });
//await update cat 2
await Cat.updateOne({ _id: params.votedAgainstCatId }, { $inc: { totalVoted: 1 } });
res.status(200).json({
message: "post a vote success",
vote: vote
});
} catch (error) {
res.status(500).json({
message: "post a vote error",
error: error
});
}
}
/**
* returns voting statistics
* total votes
* total repeated votes
* voting number of same/odd cat when pair is repeated
*/
exports.getTotalVotesStats = async (req, res, err) => {
Cat.aggregate([{ $match: { totalVoted: { $gt: 0 } } }, { $project: { catApiId: 1, src: 1, total: { $divide: ["$votedFor", "$totalVoted"] } } }, { $sort: { total: -1 } }],
function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
//res.json(result);
}
});
}
|
Java
|
GB18030
| 414 | 2.9375 | 3 |
[] |
no_license
|
package days20.Singleton;
/**
* Created by Administrator on 2017/6/4.
* ģʽģʽ
* -----------ģʽ֮ʽ---------------
*/
public class SingleDemo1 {
private static SingleDemo1 sin = null;
private SingleDemo1() {
}
public static synchronized SingleDemo1 getInstance() {
if(sin==null)
sin=new SingleDemo1();
return sin;
}
}
|
Shell
|
UTF-8
| 445 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/sh -e
pkg-config --exists libudev || {
printf 'udev (or libudev-zero) is required\n'
exit 1
}
export DESTDIR="$1"
rm -rf po
sed -i 's/DocTools//' CMakeLists.txt
sed -i '/add_subdirectory(doc)/d' CMakeLists.txt
cmake -B build \
-DCMAKE_INSTALL_PREFIX=/usr \
-DCMAKE_INSTALL_LIBDIR=lib \
-DCMAKE_BUILD_TYPE=Release \
-DBUILD_TESTING=NO \
-Wno-dev -G Ninja
ninja -C build
ninja -C build install
|
Markdown
|
UTF-8
| 1,029 | 3.046875 | 3 |
[] |
no_license
|
# DoubleClickListener for Android
_______________________________________________________________
**Note: I recommend to use `android.view.GestureDetector` instead of this class. GestureDetector provides a smoother user experience.**
A simple double click listener to implement instagram-like double tap behaviour.
It works for all views implementing OnItemClickListener, for example ListViews or GridViews.
It supports both single and double clicks for the same view, the time delay is adjustable.
Usage example:
```java
GridView myGridView = (GridView)findViewById(R.id.some_id);
myGridView.setOnItemClickListener(new DoubleClickListener() {
@Override
public void onDoubleClick(AdapterView<?> parent, View v, int position, long id) {
// do something when double clicked
}
@Override
public void onSingleClick(AdapterView<?> parent, View v, int position, long id) {
// do something when single clicked
}
});
```
|
Java
|
UTF-8
| 617 | 3.515625 | 4 |
[] |
no_license
|
import java.util.*;
public class euler2
{
/**
* @param args
*/
public static void main(String[] args)
{
int x = 0;
int sum = 0;
ArrayList nums = new ArrayList();
nums.add(1);
nums.add(2);
System.out.println(nums);
int c = 0;
while (c < 4000000)
{
int a = (Integer) nums.get(x);
int b = (Integer) nums.get(x+1);
c = a + b;
nums.add(c);
x++;
}
int sum2 = 0;
for (int i = 0; i < nums.size(); i++)
{
int current = (Integer)nums.get(i);
if ( current % 2 == 0)
{
sum2 += current;
}
}
System.out.println(sum2);
}
}
|
Markdown
|
UTF-8
| 2,635 | 3.921875 | 4 |
[] |
no_license
|
# 计算机算术章节总结
## 整数乘法
1. 无符号整数乘法
- 用寄存器Q, M存储乘数和被乘数,用寄存器A存储积,加上一个一位寄存器C存储进位。注意,这里Q,M,A都是等长度的,(C,A,Q)共同组成了结果。
- 算法:
- 初始:将A,C置0,Q,M中分别放置第一个、第二个乘数。$cnt=0$
- 循环:
- 判断:
- 若Q末位为1,则$(C,A)\gets A+M$
- 若Q末位为0,则pass
- 移位:$(C,A,Q)$共同向右移一位,C用0补齐。
- $cnt\gets cnt+1$
- 当$cnt=n$时结束循环。
2. 补码乘法(布思算法)
- 用寄存器Q, M存储乘数和被乘数,用存储器A存储积。在Q的右边加上一个一位存储器$Q_{-1}$。A, Q, M等长度。(A,Q)共同组成了结果。
- 算法:
- 初始:$A, Q_{-1}$置0,Q, M中分别放置第一个、第二个乘数。cnt=0.
- 循环:
- 判断:
- 若$(Q_0,Q_{-1})=00$或$(Q_0, Q_{-1})=11$,则pass
- 若$(Q_0,Q_{-1})=10$,则$A\gets A-M$
- 若$(Q_0,Q_{-1})=01$,则$A\gets A+M$.
- 移位:$(A,Q,Q_{-1})$整体右移一位,A最高位不变。
- $cnt\gets cnt+1$.
- 当$cnt=n$时结束循环。
## 浮点数计算原理
1. 浮点表示
浮点数用以下形式表示一个数:
$$
\pm S \times B^{\pm E}
$$
用这样的数保存在一个二进制字的三个字段中。
- 符号:正或负(有效数的符号)
- 有效值S(significand): 2进制下约定第一位隐含为1。
- 指数或者阶E(exponent): 使用移码表示(表示范围$-2^{n-1}+1 \sim 2^{n-1}$)
- 指数的底B是隐含的,不需要存储,对于所有的数都相同。这里取$2$.
<img src="img/ComputerCalc/StoragePrinciple.png">
**具体分析:**
1. 移码的使用(表示指数):
<img src="img/ComputerCalc/BiasedExp.png">
移码原始值加上$2^{n-1}-1$后按无符号数转换,把原$1000$映射成$1111$,拓展了负数域。
从而,表示范围得以改为$-2^{n-1}+1 \sim 2^{n-1}$。
2. 有效值表示:
约定在二进制存储中,有效值的最左位总是$1$,从而$1$不需要存储。
**二进制浮点数存储的IEEE754标准:**
分成单精度、双精度。
2. 浮点算数
1. 浮点数加减法:
1. 检查0。这个过程中可以统一符号。
2. 对齐有效值。
3. 执行加法。考虑符号等因素,可能出现有效值上溢,进而可能导致阶值上溢。
4. 规范化结果。
|
TypeScript
|
UTF-8
| 1,136 | 2.609375 | 3 |
[] |
no_license
|
import { orderBy } from "lodash";
import { createSelector } from "reselect";
import { State } from "@client/redux";
import { UserTranslation } from "@common/types";
export enum ChronologicalOrder {
OldestFirst = "oldest-first",
NewestFirst = "newest-first"
}
export const getUserTranslations: (
state: State,
recordId: number
) => ReadonlyArray<UserTranslation> = createSelector(
state => state.userTranslations,
(state: State, recordId: number) => recordId,
(userTranslations, recordId) => userTranslations[recordId] || []
);
function selectTimestampCreated(userTranslation: UserTranslation): number {
return userTranslation.timestampCreated;
}
export const getChronologicalUserTranslations: (
state: State,
recordId: number,
order: ChronologicalOrder
) => ReadonlyArray<UserTranslation> = createSelector(
getUserTranslations,
(state: State, recordId: number, order: ChronologicalOrder) => order,
(userTranslations, order): ReadonlyArray<UserTranslation> => {
return orderBy(userTranslations, selectTimestampCreated, [
order === ChronologicalOrder.OldestFirst ? "asc" : "desc"
]);
}
);
|
C++
|
UTF-8
| 2,598 | 2.578125 | 3 |
[] |
no_license
|
#include "ChangeLogItem.h"
namespace PaymentofInternetAccess
{
ChangeLogItem::ChangeLogItem(String^ table_count, String^ change_type)
{
this->table = table_count;
this->change_type = change_type;
primary_key = gcnew Dictionary<String^, String^>();
column_name = gcnew List<String^>();
value = gcnew List<String^>();
}
void ChangeLogItem::fill_primary_key_field(String^ primary_column, String^ primary_value)
{
primary_key->Add(primary_column, primary_value);
}
void ChangeLogItem::fill_row_update(String^ column_name, String^ value)
{
this->column_name->Add(column_name);
this->value->Add(value);
}
void ChangeLogItem::applyChange()
{
String^ db = "Data Source=NIAGARA\\SQLEXPRESS;Initial Catalog=CourseProject;ApplicationIntent=ReadWrite;Integrated Security=SSPI";
SqlConnection^ connect = gcnew SqlConnection(db);
SqlCommand^ command = connect->CreateCommand();
command->Connection = connect;
String^ commandText;
if (change_type == "DELETE")
{
commandText = "DELETE FROM " + table + " WHERE ";
List<String^>^ primary_keys_check = gcnew List<String^>();
for each (String^ key in primary_key->Keys)
{
primary_keys_check->Add(key + " = " + primary_key[key]);
}
commandText += primary_keys_check[0];
for (int i = 1; i < primary_keys_check->Count; i++)
{
commandText += " AND " + primary_keys_check[i];
}
}
if (change_type == "UPDATE")
{
commandText = "UPDATE " + table + " SET ";
commandText += column_name[0] + " = " + value[0];
for (int i = 1; i < column_name->Count; i++)
{
commandText += ", " + column_name[i] + " = " + value[i];
}
commandText += " WHERE ";
List<String^>^ primary_keys_check = gcnew List<String^>();
for each (String^ key in primary_key->Keys)
{
primary_keys_check->Add(key + " = " + primary_key[key]);
}
commandText += primary_keys_check[0];
for (int i = 1; i < primary_keys_check->Count; i++)
{
commandText += " AND " + primary_keys_check[i];
}
}
if (change_type == "INSERT")
{
commandText = "INSERT INTO " + table;
commandText += "(" + column_name[0];
for (int i = 1; i < column_name->Count; i++)
{
commandText += ", " + column_name[i];
}
commandText += ") VALUES ";
commandText += "(" + value[0];
for (int i = 1; i < value->Count; i++)
{
commandText += ", " + value[i];
}
commandText += ")";
}
command->CommandText = commandText;
connect->Open();
command->ExecuteNonQuery();
connect->Close();
}
}
|
Java
|
UTF-8
| 9,929 | 1.570313 | 2 |
[] |
no_license
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.loader.plan.exec.internal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.loader.plan.exec.process.internal.AbstractRowReader;
import org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl;
import org.hibernate.loader.plan.exec.process.internal.EntityReturnReader;
import org.hibernate.loader.plan.exec.process.internal.ResultSetProcessingContextImpl;
import org.hibernate.loader.plan.exec.process.spi.EntityReferenceInitializer;
import org.hibernate.loader.plan.exec.process.spi.ReaderCollector;
import org.hibernate.loader.plan.exec.process.spi.ResultSetProcessingContext;
import org.hibernate.loader.plan.exec.process.spi.RowReader;
import org.hibernate.loader.plan.exec.query.internal.SelectStatementBuilder;
import org.hibernate.loader.plan.exec.query.spi.QueryBuildingParameters;
import org.hibernate.loader.plan.exec.spi.EntityReferenceAliases;
import org.hibernate.loader.plan.spi.EntityReturn;
import org.hibernate.loader.plan.spi.LoadPlan;
import org.hibernate.loader.plan.spi.QuerySpace;
import org.hibernate.persister.entity.Joinable;
import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.persister.entity.Queryable;
import org.jboss.logging.Logger;
/**
* Handles interpreting a LoadPlan (for loading of an entity) by:<ul>
* <li>generating the SQL query to perform</li>
* <li>creating the readers needed to read the results from the SQL's ResultSet</li>
* </ul>
*
* @author Steve Ebersole
* @author Gail Badner
*/
public class EntityLoadQueryDetails extends AbstractLoadQueryDetails {
private static final Logger log = CoreLogging.logger( EntityLoadQueryDetails.class );
private final EntityReferenceAliases entityReferenceAliases;
private final ReaderCollector readerCollector;
/**
* Constructs a EntityLoadQueryDetails object from the given inputs.
*
* @param loadPlan The load plan
* @param keyColumnNames The columns to load the entity by (the PK columns or some other unique set of columns)
* @param buildingParameters And influencers that would affect the generated SQL (mostly we are concerned with those
* that add additional joins here)
* @param factory The SessionFactory
*/
protected EntityLoadQueryDetails(
LoadPlan loadPlan,
String[] keyColumnNames,
AliasResolutionContextImpl aliasResolutionContext,
EntityReturn rootReturn,
QueryBuildingParameters buildingParameters,
SessionFactoryImplementor factory) {
super(
loadPlan,
aliasResolutionContext,
buildingParameters,
keyColumnNames,
rootReturn,
factory
);
this.entityReferenceAliases = aliasResolutionContext.generateEntityReferenceAliases(
rootReturn.getQuerySpaceUid(),
rootReturn.getEntityPersister()
);
this.readerCollector = new EntityLoaderReaderCollectorImpl(
new EntityReturnReader( rootReturn ),
new EntityReferenceInitializerImpl( rootReturn, entityReferenceAliases, true )
);
generate();
}
protected EntityLoadQueryDetails(
EntityLoadQueryDetails initialEntityLoadQueryDetails,
QueryBuildingParameters buildingParameters) {
this(
initialEntityLoadQueryDetails.getLoadPlan(),
initialEntityLoadQueryDetails.getKeyColumnNames(),
new AliasResolutionContextImpl( initialEntityLoadQueryDetails.getSessionFactory() ),
(EntityReturn) initialEntityLoadQueryDetails.getRootReturn(),
buildingParameters,
initialEntityLoadQueryDetails.getSessionFactory()
);
}
public boolean hasCollectionInitializers() {
return CollectionHelper.isNotEmpty( readerCollector.getArrayReferenceInitializers() ) ||
CollectionHelper.isNotEmpty( readerCollector.getNonArrayCollectionReferenceInitializers() );
}
private EntityReturn getRootEntityReturn() {
return (EntityReturn) getRootReturn();
}
/**
* Applies "table fragments" to the FROM-CLAUSE of the given SelectStatementBuilder for the given Loadable
*
* @param select The SELECT statement builder
*
* @see org.hibernate.persister.entity.OuterJoinLoadable#fromTableFragment(java.lang.String)
* @see org.hibernate.persister.entity.Joinable#fromJoinFragment(java.lang.String, boolean, boolean)
*/
protected void applyRootReturnTableFragments(SelectStatementBuilder select) {
final String fromTableFragment;
final String rootAlias = entityReferenceAliases.getTableAlias();
final OuterJoinLoadable outerJoinLoadable = (OuterJoinLoadable) getRootEntityReturn().getEntityPersister();
final Dialect dialect = getSessionFactory().getJdbcServices().getJdbcEnvironment().getDialect();
if ( getQueryBuildingParameters().getLockOptions() != null ) {
fromTableFragment = dialect.appendLockHint(
getQueryBuildingParameters().getLockOptions(),
outerJoinLoadable.fromTableFragment( rootAlias )
);
select.setLockOptions( getQueryBuildingParameters().getLockOptions() );
}
else if ( getQueryBuildingParameters().getLockMode() != null ) {
fromTableFragment = dialect.appendLockHint(
getQueryBuildingParameters().getLockMode(),
outerJoinLoadable.fromTableFragment( rootAlias )
);
select.setLockMode( getQueryBuildingParameters().getLockMode() );
}
else {
fromTableFragment = outerJoinLoadable.fromTableFragment( rootAlias );
}
select.appendFromClauseFragment( fromTableFragment + outerJoinLoadable.fromJoinFragment( rootAlias, true, true ) );
}
protected void applyRootReturnFilterRestrictions(SelectStatementBuilder selectStatementBuilder) {
final Queryable rootQueryable = (Queryable) getRootEntityReturn().getEntityPersister();
selectStatementBuilder.appendRestrictions(
rootQueryable.filterFragment(
entityReferenceAliases.getTableAlias(),
Collections.emptyMap()
)
);
}
protected void applyRootReturnWhereJoinRestrictions(SelectStatementBuilder selectStatementBuilder) {
final Joinable joinable = (OuterJoinLoadable) getRootEntityReturn().getEntityPersister();
selectStatementBuilder.appendRestrictions(
joinable.whereJoinFragment(
entityReferenceAliases.getTableAlias(),
true,
true
)
);
}
@Override
protected void applyRootReturnOrderByFragments(SelectStatementBuilder selectStatementBuilder) {
}
@Override
protected boolean isSubselectLoadingEnabled(FetchStats fetchStats) {
return getQueryBuildingParameters().getBatchSize() > 1 &&
fetchStats != null &&
fetchStats.hasSubselectFetches();
}
@Override
protected boolean shouldUseOptionalEntityInstance() {
return getQueryBuildingParameters().getBatchSize() < 2;
}
@Override
protected ReaderCollector getReaderCollector() {
return readerCollector;
}
@Override
protected QuerySpace getRootQuerySpace() {
return getQuerySpace( getRootEntityReturn().getQuerySpaceUid() );
}
@Override
protected String getRootTableAlias() {
return entityReferenceAliases.getTableAlias();
}
@Override
protected boolean shouldApplyRootReturnFilterBeforeKeyRestriction() {
return false;
}
protected void applyRootReturnSelectFragments(SelectStatementBuilder selectStatementBuilder) {
final OuterJoinLoadable outerJoinLoadable = (OuterJoinLoadable) getRootEntityReturn().getEntityPersister();
selectStatementBuilder.appendSelectClauseFragment(
outerJoinLoadable.selectFragment(
entityReferenceAliases.getTableAlias(),
entityReferenceAliases.getColumnAliases().getSuffix()
)
);
}
private static class EntityLoaderReaderCollectorImpl extends ReaderCollectorImpl {
private final EntityReturnReader entityReturnReader;
public EntityLoaderReaderCollectorImpl(
EntityReturnReader entityReturnReader,
EntityReferenceInitializer entityReferenceInitializer) {
this.entityReturnReader = entityReturnReader;
add( entityReferenceInitializer );
}
@Override
public RowReader buildRowReader() {
return new EntityLoaderRowReader( this );
}
@Override
public EntityReturnReader getReturnReader() {
return entityReturnReader;
}
}
private static class EntityLoaderRowReader extends AbstractRowReader {
private final EntityReturnReader rootReturnReader;
public EntityLoaderRowReader(EntityLoaderReaderCollectorImpl entityLoaderReaderCollector) {
super( entityLoaderReaderCollector );
this.rootReturnReader = entityLoaderReaderCollector.getReturnReader();
}
@Override
public Object readRow(ResultSet resultSet, ResultSetProcessingContextImpl context) throws SQLException {
final ResultSetProcessingContext.EntityReferenceProcessingState processingState =
rootReturnReader.getIdentifierResolutionContext( context );
// if the entity reference we are hydrating is a Return, it is possible that its EntityKey is
// supplied by the QueryParameter optional entity information
if ( context.shouldUseOptionalEntityInformation() && context.getQueryParameters().getOptionalId() != null ) {
final EntityKey entityKey = context.getSession().generateEntityKey(
context.getQueryParameters().getOptionalId(),
processingState.getEntityReference().getEntityPersister()
);
processingState.registerIdentifierHydratedForm( entityKey.getIdentifier() );
processingState.registerEntityKey( entityKey );
}
return super.readRow( resultSet, context );
}
@Override
protected Object readLogicalRow(ResultSet resultSet, ResultSetProcessingContextImpl context) throws SQLException {
return rootReturnReader.read( resultSet, context );
}
}
}
|
Markdown
|
UTF-8
| 954 | 2.84375 | 3 |
[] |
no_license
|
# Lexical Analysis Pipeline
## Description
Analyzes facets from EBI Biosamples to identify pairs of facets to merge. Facets are first split into
groups of facets that contain typos and those that do not. The group of facets with no typos are examined
for merge pairs using fuzzy matching followed by use of lemmatization of tokens using the WordNetLemmatizer
and morphy from NLTK. This group is then compared to the typo group to find additional merger pairs.
## Prerequisites
See `requirements.txt` for full list of modules. See http://www.nltk.org/data.html for details on installing data for NLTK.
## Usage
`python lexical_merge_analysis_pipeline.py`
See commandline args for additional parameters.
## Output
Two CSV files that contain a list of facet pairs to merge. The file "merge_confirmed.csv" contains high confidence merge pairs, while "merge_after_manual_review.csv" contains lower confidence merge pairs that require fuurther review.
|
Java
|
UTF-8
| 626 | 2.53125 | 3 |
[] |
no_license
|
/**
*
*/
package cn.edu.ecnu.heng.pinduoduo;
import java.util.Scanner;
/**
* @author Heng(LEGION)
*
* @create 2019年3月10日-下午4:13:13
*
* @detail
*/
public class Main2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
String word = in.next().toLowerCase();
String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower= upper.toLowerCase();
in.close();
for (int i = 0; i < upper.length(); i++) {
if(word.indexOf(lower.charAt(i))!=-1) {
System.out.println(lower.charAt(i));
return;
}
}
}
}
|
Python
|
UTF-8
| 17,418 | 2.59375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import numpy as np
import collections
import matplotlib.pyplot as py
import matplotlib.gridspec as gridspec
import sys
from scipy.stats.stats import pearsonr
from scipy import stats
from operator import itemgetter
class BookImporter(object):
def __init__(self, book_file, id_min=1, id_max=1, t_min=0, t_max=1, atom_min=0, atom_max=5):
'''
input arguments:
book_file
id_min - index of minimal trial to plot
id_max - index of maximal trial to plot
t_min - down edge of time period to reconstruct
t_max - upper edge of time period to reconstruct
atom_min - minimal atom to plot
atom_max - maximal atom to plot
comment:
if we want to reconstruct only one atom then atom_min should equal atom_max
'''
super(BookImporter, self).__init__()
f = open(book_file,'rb')
data, signals, atoms, epoch_s = self._read_book(f)
self.epoch_s = epoch_s
self.atoms = atoms
self.signals = signals
self.fs = data[5]['Fs']
self.ptspmV = 0.0715
self.id_min = id_min
self.id_max = id_max
self.t_min = t_min
self.t_max = t_max
self.atom_min = atom_min
self.atom_max = atom_max
# amps = self._get_atoms_peak2peak_amplitudes()
# self.draw_reconstructed_signal()
self.draw_mean_reconstructed_signal(atoms, signals)
# amps = self._get_atoms_amplitudes()
# self.amps = amps
# print(np.median(amps))
# print(amps[:10])
# self.perform_linear_regression(amps)
# t, f, E_a, sigt, signal_a, signal_reconstruction_a, alpha_mean = self.calculate_mean_map(df = 0.2, dt = 0.008, f_a = [2, 20])
# self.alpha_mean = alpha_mean
# print(pearsonr(amps,alpha_mean)) ### (Pearson’s correlation coefficient, 2-tailed p-value)
# self.perform_linear_regression(alpha_mean)
# print(np.median(alpha_mean))
# t, f, E_a,sigt, signal_a, signal_reconstruction_a = self.calculate_map(self.atoms[2],self.signals[1][1][1], df = 0.2, dt = 0.008, f_a = [2, 20])
# self.only_draw_map(t, f, E_a, sigt, signal_a, signal_reconstruction_a)
py.show()
def _get_type(self, ident, f):
'''generacja dtype dla odczytania fragmentów, odpalana od razu,
po odczytaniu identyfikatora'''
# print(ident)
if ident == 1:
com_s = np.fromfile(f, '>u4', count=1)[0]
if not com_s==0: ## comment
return np.dtype([('comment', 'S'+str(com_s))])
else:
return None
elif ident == 2: ## header
head_s = np.fromfile(f, '>u4', count=1)[0]
return None
elif ident == 3: ## www adress
www_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('www', 'S'+str(www_s))])
elif ident == 4: ## data stworzenia pliku
date_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('date', 'S'+str(date_s))])
elif ident == 5: ## info o sygnale
sig_info_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('Fs', '>f4'), ('ptspmV', '>f4'),
('chnl_cnt', '>u2')])
elif ident == 6: ## info o dekompozycji
dec_info_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('percent', '>f4'), ('maxiterations', '>u4'),
('dict_size', '>u4'), ('dict_type', '>S1')])
elif ident == 10: #dirac
return
atom_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('modulus', '>f4'), ('amplitude', '>f4'),
('t', '>f4')])
elif ident == 11: #gauss
atom_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('modulus', '>f4'), ('amplitude', '>f4'),
('t', '>f4'), ('scale', '>f4')])
elif ident == 12: #sinus
return
atom_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('modulus', '>f4'), ('amplitude', '>f4'),
('f', '>f4'), ('phase', '>f4')])
elif ident == 13: #gabor
atom_s = np.fromfile(f, '>u1', count=1)[0]
return np.dtype([('modulus', '>f4'), ('amplitude', '>f4'),
('t', '>f4'), ('scale', '>f4'),
('f', '>f4'), ('phase', '>f4')])
else:
return None
def _get_signal(self, f, epoch_nr, epoch_s):
'''uruchamiana przy odnalezieniu bloku sygnału'''
sig_s = np.fromfile(f, '>u4', count=1)[0]
chnl_nr = np.fromfile(f, '>u2', count=1)[0]
signal = np.fromfile(f, '>f4', count= epoch_s)
return chnl_nr, signal
def _get_atoms(self, f):
'''uruchamiana przy odnalezieniu bloku atomów'''
atoms = collections.defaultdict(list)
atoms_s = np.fromfile(f, '>u4', count=1)[0]
a_chnl_nr = np.fromfile(f, '>u2', count=1)[0]
ident = np.fromfile(f, '>u1', count=1)
while ident in [10, 11, 12, 13]:
atom = np.fromfile(f, self._get_type(ident[0], f), count=1)[0]
atoms[ident[0]].append(atom)
ident = np.fromfile(f, '>u1', count=1)
f.seek(f.tell()-1)
return atoms, a_chnl_nr
def _gabor(self, amplitude, position, scale, afrequency, phase):
time = np.linspace(0, self.epoch_s/self.fs, self.epoch_s)
width = scale
frequency = afrequency*2*np.pi
signal = amplitude*np.exp(-np.pi*((time-position)/width)**2)*np.cos(frequency*(time-position) + phase)
return signal
def _read_book(self, f):
try:
f = open(f, 'rb')
except Exception:
f = f
version = np.fromfile(f, 'S6', count=1)
print('version: ',version[0])
data = {} # zachowanie danych z nagłówku
ident = np.fromfile(f, 'u1', count=1)[0]
ct = self._get_type(ident, f)
signals = collections.defaultdict(list)
atoms = collections.defaultdict(list)
while ident:
if ct:
point = np.fromfile(f,ct, count=1)[0]
data[ident] = point
elif ident ==7:
data_s = np.fromfile(f, '>u4', count=1)[0]
epoch_nr = np.fromfile(f, '>u2', count=1)[0]
epoch_s = np.fromfile(f, '>u4', count=1)[0]
#print('epoch_s', epoch_s)
elif ident == 8:
chnl_nr, signal = self._get_signal(f, epoch_nr, epoch_s)
signals[epoch_nr].append([chnl_nr, signal])
elif ident == 9:
pl = f.tell()
atom, a_chnl_nr = self._get_atoms(f)
atoms[a_chnl_nr] = atom
ident = np.fromfile(f, '>u1', count=1)
if ident:
ident = ident[0]
ct = self._get_type(ident, f)
return data, signals, atoms, epoch_s
def _get_atoms_amplitudes(self):
amps = []
for trial in self.atoms.keys():
amps_temp = []
for i,atom in enumerate(self.atoms[trial][13]):
position = atom['t']/self.fs
width = atom['scale']/self.fs/2
frequency = atom['f']*self.fs/2
amplitude = atom['amplitude']
phase = atom['phase']
if self.t_min<position<self.t_max:
if self.atom_min <= i <= self.atom_max:
amps_temp.append(amplitude)
# print(amps_temp)
amps.append(max(amps_temp))
return amps
def _find_extrema(self, signal):
deriv = np.gradient(signal)
deriv[np.where(deriv < 0)] = -1
deriv[np.where(deriv > 0)] = 1
d = list(deriv)
amps = []
temp = 0
data = []
for j,i in enumerate(d):
try:
if i == d[j-1] and i == 1:
if temp == 0:
start = j-1
temp += 1
else:
if temp != 0:
data.append((start,temp))
temp = 0
except:
pass
for frag in data:
slope_start = frag[0]
slope_end = frag[0] + frag[1]
amps.append(abs(signal[slope_end] - signal[slope_start]))
return max(amps)
def _get_atoms_peak2peak_amplitudes(self):
amps = []
for trial in self.atoms.keys():
signal_reconstruction = self.reconstruct_signal_freq(self.atoms[trial])
amps.append(self._find_extrema(signal_reconstruction))
# py.figure(str(trial))
# py.plot(signal_reconstruction)
# py.show()
return amps
def draw_mean_reconstructed_signal(self, atoms, signals):
N = len(atoms.keys())
tpr = len(signals[1][0][1])
t = np.arange(0, tpr/self.fs, 1/self.fs)
for i,trial in enumerate(atoms.keys()):
signal_reconstruction = self.reconstruct_signal_freq(atoms[trial])
signal = signals[1][i][1]
try:
signal_a += signal
signal_reconstruction_a += signal_reconstruction
except Exception as a:
print(a, 'objection')
signal_a = signal
signal_reconstruction_a = signal_reconstruction
signal_a /= N
signal_reconstruction_a /= N
py.figure('Mean')
t = np.linspace(-0.5, 1, tpr)
py.plot(t,signal_reconstruction_a,color='g',label='rekonstrukcja')
py.plot(t,signal_a,color='m',label=u'sygnał')
# py.ylim(-15,20)
py.xlim(-0.5,1)
py.ylabel(u'Amplituda [$\\mu$V]')
py.xlabel(u'Czas [s]')
py.axvline(x=0,color='r')
# py.axvline(x=0.3,color='r')
py.legend()
def draw_reconstructed_signal(self):
tpr = len(self.signals[1][0][1])
# t = np.arange(-0.5, tpr/self.fs, 1/self.fs)
t = np.linspace(-0.5, 1, tpr)
for i,trial in enumerate(self.atoms.keys()):
if i in xrange(self.id_min, self.id_max+1):
signal_reconstruction = self.reconstruct_signal_freq(self.atoms[trial])
signal = self.signals[1][i][1] #- np.mean(self.signals[1][i][1][:0.5*self.fs])
# amp = np.mean(self.signals[1][i][1][0.25*self.fs:0.35*self.fs])
# amp_sig.append(amp)
py.figure('Trial '+str(i))
py.plot(t,signal_reconstruction,color='g',label='rekonstrukcja')
py.plot(t,signal,color='m',label='sygnal')
# py.axvline(x=0.3,color='r')
py.axvline(x=0,color='r')
py.ylabel(u'Amplituda [$\\mu$V]')
py.xlabel(u'Czas [s]')
py.ylim(-30,40)
py.xlim(-0.5,1)
py.legend()
def reconstruct_signal_freq(self, atoms):
reconstruction = np.zeros(self.epoch_s)
for i,atom in enumerate(atoms[13]):
position = atom['t']/self.fs
width = atom['scale']/self.fs
frequency = atom['f']*self.fs/2
amplitude = atom['amplitude']
phase = atom['phase']
# if self.t_min < position < self.t_max:
if self.atom_min <= i < self.atom_max+1:
reconstruction = reconstruction + self._gabor(amplitude, position, width, frequency, phase)
return reconstruction
def perform_linear_regression(self, amps):
y = np.linspace(1,len(amps),len(amps))
A = np.array([y, np.ones(len(amps))])
w = np.linalg.lstsq(A.T,amps)[0]
line = w[0]*y+w[1]
py.figure()
py.plot(y,line,'r-',y,amps,'o')
py.ylim(-5,22)
py.ylabel(u'Amplituda [$\\mu$V]')
py.xlabel('Realizacje')
################ rysowanie mapy
# 8 Hz < f < 12 Hz
# a > 5 µV
# s > 1.5 s
def calculate_mean_map(self,df = 0.05, dt = 1/256., f_a = [0, 64.]):
N = len(self.atoms.keys())
tpr = len(self.signals[1][0][1])
# sigt = np.arange(0, tpr/self.fs, 1/self.fs)
sigt = np.linspace(-0.5, 1, tpr)
alpha_mean = []
for nr, chnl in enumerate(self.atoms.keys()):
t, f, E, sigt_s,s_s,sr_s = self.calculate_map(self.atoms[chnl],self.signals[1][nr][1], df, dt, f_a = f_a)
alpha_recon = self._calculate_alpha_power(self.atoms[chnl],self.signals[1][nr][1], df, dt, f_a = f_a)
alpha_mean.append(sum(alpha_recon))
signal_reconstruction = self._reconstruct_signal(self.atoms[chnl])
signal = self.signals[1][nr][1]
try:
signal_a += signal
E_a += E
signal_recontruction_a += signal_reconstruction
except Exception as a:
# print(a)
signal_a = signal
E_a = E
signal_recontruction_a = signal_reconstruction
signal_a /= N
signal_recontruction_a /= N
E_a /= N
return t, f, E_a, sigt, signal_a, signal_recontruction_a,alpha_mean
def calculate_map(self,atoms,signal, df, dt, contour=0, f_a = [0, 64.]):
''' atoms - dictionary with trials/channels; for each dictionary with
atoms 4 different atom's types (10,11,12,13-Gabors)'''
tpr = len(signal)
f = np.arange(f_a[0], f_a[1], df)
t = np.arange(0, tpr/self.fs, dt)
lent = len(t)
lenf = len(f)
E = np.zeros((lent, lenf)).T
t, f = np.meshgrid(t, f)
sigt = np.arange(0, tpr/self.fs, 1/self.fs)
for atom in atoms[13]:
exp1 = np.exp(-2*(atom['scale']/self.fs)**(-2)*(t-atom['t']/self.fs)**2)
exp2 = np.exp(-2*np.pi**2 *(atom['scale']/self.fs)**2*(atom['f']*self.fs/2-f)**2)
wigners = ((atom['amplitude']/self.ptspmV)**2 * (2*np.pi)**0.5 *
atom['scale']/self.fs*exp1*exp2)
E += atom['modulus']**2 * wigners
for atom in atoms[12]:
amp = atom['modulus']**2*(atom['amplitude']/self.ptspmV)**2
E[:,int(len(f)*atom['f']/(2*np.pi))] += amp
for atom in atoms[11]:
exp1 = np.exp(-2*(atom['scale']/self.fs)**(-2)*(t-atom['t']/self.fs)**2)
exp2 = np.exp(-2*np.pi**2 *(atom['scale']/self.fs)**2*(-f)**2)
wigners = ((atom['amplitude']/self.ptspmV)**2 * (2*np.pi)**0.5 *
atom['scale']/self.fs*exp1*exp2)
E += atom['modulus']**2 * wigners
for atom in atoms[10]:
amp = atom['modulus']**2*(atom['amplitude']/self.ptspmV)**2
E[int(lent*atom['t']/tpr)] += amp
signal_reconstruction = self._reconstruct_signal(atoms)
return t, f, np.log(E), sigt, signal, signal_reconstruction
# def _calculate_alpha_power(self,atoms,signal, df, dt, contour=0, f_a = [0, 64.]):
# tpr = len(signal)
# f = np.arange(f_a[0], f_a[1], df)
# t = np.arange(0, tpr/self.fs, dt)
# lent = len(t)
# lenf = len(f)
# E = np.zeros((lent, lenf)).T
# t, f = np.meshgrid(t, f)
# sigt = np.arange(0, tpr/self.fs, 1/self.fs)
# for atom in atoms[13]:
# freq = atom['f']*self.fs/2
# amp = 2*atom['amplitude']/self.ptspmV
# scale = atom['scale']/self.fs
# position = atom['t']/self.fs
# # print(freq,position,scale)
# if 8 < freq < 12: # and position < 0.5:
# print(freq,position,scale)
# exp1 = np.exp(-2*(atom['scale']/self.fs)**(-2)*(t-atom['t']/self.fs)**2)
# exp2 = np.exp(-2*np.pi**2 *(atom['scale']/self.fs)**2*(atom['f']*self.fs/2-f)**2)
# wigners = ((atom['amplitude']/self.ptspmV)**2 * (2*np.pi)**0.5 *
# atom['scale']/self.fs*exp1*exp2)
# E += atom['modulus']**2 * wigners
# return np.mean(np.mean(E))
def _calculate_alpha_power(self,atoms,signal, df, dt, contour=0, f_a = [0, 64.]):
reconstruction = np.zeros(self.epoch_s)
for atom in atoms[13]:
amplitude = atom['amplitude']
position = atom['t']/self.fs
width = atom['scale']/self.fs
frequency = atom['f']*self.fs/2
phase = atom['phase']
if 8 < frequency < 12 and position < 0.5:
# if 13 < frequency < 30 and position < 0.5: #and amplitude > 5:
# print(frequency,position,width)
reconstruction = reconstruction + self._gabor(amplitude,position,width,frequency,phase)
return np.abs(reconstruction)**2
def only_draw_map(self, t, f, E_a, sigt, signal_a, signal_recontruction_a, contour=False):
# tp = np.linspace(-0.5, 1, 10)
fig = py.figure()
gs = gridspec.GridSpec(2,1, height_ratios=[3,1])
ax1 = fig.add_subplot(gs[0])
ax1.set_ylabel(u'Czestosc [Hz]')
ax1.set_title(sys.argv[-1])
if contour:
ax1.contour(t, f, E_a)
else:
ax1.pcolor(t, f, E_a)
# ax1.set_xticklabels(tp)
ax2 = fig.add_subplot(gs[1])
ax2.plot(sigt, signal_a, 'red')
ax2.plot(sigt, signal_recontruction_a, 'blue')
ax2.axvline(x=0,color='r')
ax2.set_ylabel(u'Amplituda [$\\mu$V]')
ax2.set_xlabel(u'Czas [s]')
ax2.set_xlim(-0.5,1)
def _reconstruct_signal(self, atoms):
reconstruction = np.zeros(self.epoch_s)
for atom in atoms[13]:
position = atom['t']/self.fs
width = atom['scale']/self.fs
frequency = atom['f']*self.fs/2
amplitude = atom['amplitude']
phase = atom['phase']
# print(amplitude)
reconstruction = reconstruction + self._gabor(amplitude,position,width,frequency,phase)
return reconstruction
if __name__ == '__main__':
# fstr = './wybrane/newMP/Cz/MMP1_compatible_group_nogo_longer_mmp.b'
# fstr = './wybrane/MMP1_compatible_ind_go_mmp.b'
# fstr = './wybrane/MMP2_compatible_ind_go_mmp.b'
# fstr = './wybrane/MMP3_compatible_ind_go_mmp.b'
# fstr = './wybrane/MMP1_compatible_ind_go_longer_mmp.b'
###### dekompozycja średnich wszystkich badanych
# fstr = './wybrane/newMP/Cz/MEANS/FILT/MMP3_MEANS_GROUP_FILT_mmp.b'
# b = BookImporter(fstr, id_min=0, id_max=10, t_min=0, t_max=1.5, atom_min=0, atom_max=0)
# ampsg = b.amps
# fstr = './wybrane/newMP/Cz/MEANS/FILT/MMP3_MEANS_INDIVIDUAL_FILT_mmp.b'
# b = BookImporter(fstr, id_min=0, id_max=10, t_min=0, t_max=1.5, atom_min=0, atom_max=0)
# ampsi = b.amps
# print(stats.ranksums(ampsg,ampsi)[1])
###### pojedyncze amplitudy + alpha
# fstr = './wybrane/newMP/Cz/MMP1_compatible_ind_nogo_longer_mmp.b'
# b = BookImporter(fstr, id_min=0, id_max=10, t_min=0, t_max=1.5, atom_min=2, atom_max=2)
# ind_comp = b.amps
# ind_c_alpha = b.alpha_mean
# fstr = './wybrane/newMP/Cz/MMP1_incompatible_ind_nogo_longer_mmp.b'
# b = BookImporter(fstr, id_min=0, id_max=10, t_min=0, t_max=1.5, atom_min=2, atom_max=2)
# ind_incomp = b.amps
# ind_inc_alpha = b.alpha_mean
# ind = ind_comp + ind_incomp
# ind_alp = ind_c_alpha + ind_inc_alpha
# fstr = './wybrane/newMP/Cz/MMP1_incompatible_group_nogo_longer_mmp.b'
# b = BookImporter(fstr, id_min=0, id_max=10, t_min=0, t_max=1.5, atom_min=1, atom_max=1)
# gr_comp = b.amps
# gr_c_alpha = b.alpha_mean
# fstr = './wybrane/newMP/Cz/MMP1_compatible_group_nogo_longer_mmp.b'
# b = BookImporter(fstr, id_min=0, id_max=10, t_min=0, t_max=1.5, atom_min=1, atom_max=1)
# gr_incomp = b.amps
# gr_inc_alpha = b.alpha_mean
# gr = gr_incomp + gr_comp
# gr_alp = gr_inc_alpha + gr_c_alpha
# # # print(pearsonr(gr_comp,gr_c_alpha))
# print(pearsonr(ind_comp,ind_c_alpha))
# print(pearsonr(ind_incomp,ind_inc_alpha))
# print(pearsonr(gr_comp,gr_c_alpha))
# print(pearsonr(gr_incomp,gr_inc_alpha))
# # print(stats.shapiro(gr)[1],stats.shapiro(ind)[1])
# print(stats.kruskal(gr,ind)[1])
#######
####### do pojedynczych - warunek go
fstr = './wybrane/newMP/Cz/MMP1_compatible_ind_go_longer_mmp.b'
b = BookImporter(fstr, id_min=0, id_max=10, t_min=0, t_max=1.5, atom_min=0, atom_max=1)
|
Markdown
|
UTF-8
| 2,865 | 2.875 | 3 |
[] |
no_license
|
# 创建用户并授权使用DRS<a name="drs_08_0012"></a>
如果您需要对您所拥有的DRS进行精细的权限管理,您可以通过[企业管理](https://support.huaweicloud.com/zh-cn/usermanual-em/em-topic_02.html)或[统一身份认证服务](https://support.huaweicloud.com/usermanual-iam/iam_01_0001.html)(Identity and Access Management,简称IAM)实现。
- 通过企业管理实现的具体操作,请您参考[项目管理](https://support.huaweicloud.com/zh-cn/usermanual-em/em-topic_02.html)。
- 通过IAM实现的具体操作,您可以:
- 根据企业的业务组织,在您的华为云帐号中,给企业中不同职能部门的员工创建IAM用户,让员工拥有唯一安全凭证,并使用DRS资源。
- 根据企业用户的职能,设置不同的访问权限,以达到用户之间的权限隔离。
- 将DRS资源委托给更专业、高效的其他华为云帐号或者云服务,这些帐号或者云服务可以根据权限进行代运维。
如果华为云帐号已经能满足您的要求,不需要创建独立的IAM用户,您可以跳过本章节,不影响您使用DRS服务的其它功能。
本章节为您介绍通过IAM对用户授权的方法,操作流程如[图1](#fig158351985619)所示。
## 前提条件<a name="section64352220313"></a>
给用户组授权之前,请您了解用户组可以添加的DRS权限,并结合实际需求进行选择,DRS支持的系统权限,请参见:[DRS系统权限](https://support.huaweicloud.com/productdesc-drs/drs_01_0201.html)。若您需要对除DRS之外的其它服务授权,IAM支持服务的所有权限请参见[权限策略](https://support.huaweicloud.com/usermanual-permissions/iam_01_0001.html)。
## 示例流程<a name="section3327121975615"></a>
**图 1** 给用户授权DRS权限流程<a name="fig158351985619"></a>

1. <a name="li1658301914563"></a>[创建用户组并授权](https://support.huaweicloud.com/usermanual-iam/iam_03_0001.html)
在IAM控制台创建用户组,并授予数据复制服务管理员权限“DRS Administrator“权限。
2. [创建用户](https://support.huaweicloud.com/usermanual-iam/iam_02_0001.html)
在IAM控制台创建用户,并将其加入[1](#li1658301914563)中创建的用户组。
3. [用户登录](https://support.huaweicloud.com/usermanual-iam/iam_01_0552.html)并验证权限
新创建的用户登录控制台,切换至授权区域验证权限,操作如下:
在“服务列表”中选择数据复制服务,进入DRS主界面,单击右上角“创建迁移任务”,尝试创建迁移任务,如果可以创建迁移任务(假设当前权限仅包含“DRS Administrator“),就表示“DRS Administrator“权限已生效。
|
JavaScript
|
UTF-8
| 2,026 | 2.8125 | 3 |
[] |
no_license
|
var camera, scene, renderer;
var geometry, material, mesh;
init();
animate();
function init() {
scene = new THREE.Scene();
group = new THREE.Group();
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, .1, 1000);
camera.position.set(0,0,100);
camera.lookAt(scene.position);
scene.add(camera);
floor_geometry = new THREE.PlaneGeometry(400, 400, 10, 10);
floor_material = new THREE.MeshLambertMaterial({
color: 0xf5bb33,
side: THREE.DoubleSide,
wireframe: true
});
floor_mesh = new THREE.Mesh(floor_geometry, floor_material);
floor_mesh.rotation.x = -0.5 * Math.PI;
floor_mesh.position.set(0, -30, 0);
scene.add(floor_mesh);
group.add(floor_mesh);
ceiling_geometry = new THREE.PlaneGeometry(400, 400, 10, 10);
ceiling_mesh = new THREE.Mesh(ceiling_geometry, floor_material);
ceiling_mesh.rotation.x = -0.5 * Math.PI;
ceiling_mesh.position.set(0, 30, 0);
scene.add(ceiling_mesh);
group.add(ceiling_mesh);
object_geometry = new THREE.IcosahedronGeometry(8,2);
object_material = new THREE.MeshLambertMaterial({
color: 0xD51A1F,
wireframe: true
});
object_mesh = new THREE.Mesh(object_geometry, object_material);
scene.add(object_mesh);
group.add(object_mesh);
geometry = new THREE.BoxGeometry(20, 20, 20 );
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh( geometry, material );
scene.add(mesh);
group.add(mesh);
// ADD LIGHTS
light = new THREE.AmbientLight(0xaaaaaa);
scene.add(light);
scene.add(group);
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
}
function animate() {
mesh.rotation.x += 0.002;
group.rotation.y += 0.004;
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
|
Java
|
UTF-8
| 5,647 | 2.078125 | 2 |
[] |
no_license
|
package org.soptorshi.service.mapper;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import org.soptorshi.domain.CommercialBudget;
import org.soptorshi.service.dto.CommercialBudgetDTO;
import org.springframework.stereotype.Component;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2021-09-05T16:56:24+0600",
comments = "version: 1.2.0.Final, compiler: javac, environment: Java 1.8.0_291 (Oracle Corporation)"
)
@Component
public class CommercialBudgetMapperImpl implements CommercialBudgetMapper {
@Override
public CommercialBudget toEntity(CommercialBudgetDTO dto) {
if ( dto == null ) {
return null;
}
CommercialBudget commercialBudget = new CommercialBudget();
commercialBudget.setId( dto.getId() );
commercialBudget.setBudgetNo( dto.getBudgetNo() );
commercialBudget.setType( dto.getType() );
commercialBudget.setCustomer( dto.getCustomer() );
commercialBudget.setBudgetDate( dto.getBudgetDate() );
commercialBudget.setCompanyName( dto.getCompanyName() );
commercialBudget.setPaymentType( dto.getPaymentType() );
commercialBudget.setTransportationType( dto.getTransportationType() );
commercialBudget.setSeaPortName( dto.getSeaPortName() );
commercialBudget.setSeaPortCost( dto.getSeaPortCost() );
commercialBudget.setAirPortName( dto.getAirPortName() );
commercialBudget.setAirPortCost( dto.getAirPortCost() );
commercialBudget.setLandPortName( dto.getLandPortName() );
commercialBudget.setLandPortCost( dto.getLandPortCost() );
commercialBudget.setInsurancePrice( dto.getInsurancePrice() );
commercialBudget.setTotalTransportationCost( dto.getTotalTransportationCost() );
commercialBudget.setTotalQuantity( dto.getTotalQuantity() );
commercialBudget.setTotalOfferedPrice( dto.getTotalOfferedPrice() );
commercialBudget.setTotalBuyingPrice( dto.getTotalBuyingPrice() );
commercialBudget.setProfitAmount( dto.getProfitAmount() );
commercialBudget.setProfitPercentage( dto.getProfitPercentage() );
commercialBudget.setBudgetStatus( dto.getBudgetStatus() );
commercialBudget.setProformaNo( dto.getProformaNo() );
commercialBudget.setCreatedBy( dto.getCreatedBy() );
commercialBudget.setCreatedOn( dto.getCreatedOn() );
commercialBudget.setUpdatedBy( dto.getUpdatedBy() );
commercialBudget.setUpdatedOn( dto.getUpdatedOn() );
return commercialBudget;
}
@Override
public CommercialBudgetDTO toDto(CommercialBudget entity) {
if ( entity == null ) {
return null;
}
CommercialBudgetDTO commercialBudgetDTO = new CommercialBudgetDTO();
commercialBudgetDTO.setId( entity.getId() );
commercialBudgetDTO.setBudgetNo( entity.getBudgetNo() );
commercialBudgetDTO.setType( entity.getType() );
commercialBudgetDTO.setCustomer( entity.getCustomer() );
commercialBudgetDTO.setBudgetDate( entity.getBudgetDate() );
commercialBudgetDTO.setCompanyName( entity.getCompanyName() );
commercialBudgetDTO.setPaymentType( entity.getPaymentType() );
commercialBudgetDTO.setTransportationType( entity.getTransportationType() );
commercialBudgetDTO.setSeaPortName( entity.getSeaPortName() );
commercialBudgetDTO.setSeaPortCost( entity.getSeaPortCost() );
commercialBudgetDTO.setAirPortName( entity.getAirPortName() );
commercialBudgetDTO.setAirPortCost( entity.getAirPortCost() );
commercialBudgetDTO.setLandPortName( entity.getLandPortName() );
commercialBudgetDTO.setLandPortCost( entity.getLandPortCost() );
commercialBudgetDTO.setInsurancePrice( entity.getInsurancePrice() );
commercialBudgetDTO.setTotalTransportationCost( entity.getTotalTransportationCost() );
commercialBudgetDTO.setTotalQuantity( entity.getTotalQuantity() );
commercialBudgetDTO.setTotalOfferedPrice( entity.getTotalOfferedPrice() );
commercialBudgetDTO.setTotalBuyingPrice( entity.getTotalBuyingPrice() );
commercialBudgetDTO.setProfitAmount( entity.getProfitAmount() );
commercialBudgetDTO.setProfitPercentage( entity.getProfitPercentage() );
commercialBudgetDTO.setBudgetStatus( entity.getBudgetStatus() );
commercialBudgetDTO.setProformaNo( entity.getProformaNo() );
commercialBudgetDTO.setCreatedBy( entity.getCreatedBy() );
commercialBudgetDTO.setCreatedOn( entity.getCreatedOn() );
commercialBudgetDTO.setUpdatedBy( entity.getUpdatedBy() );
commercialBudgetDTO.setUpdatedOn( entity.getUpdatedOn() );
return commercialBudgetDTO;
}
@Override
public List<CommercialBudget> toEntity(List<CommercialBudgetDTO> dtoList) {
if ( dtoList == null ) {
return null;
}
List<CommercialBudget> list = new ArrayList<CommercialBudget>( dtoList.size() );
for ( CommercialBudgetDTO commercialBudgetDTO : dtoList ) {
list.add( toEntity( commercialBudgetDTO ) );
}
return list;
}
@Override
public List<CommercialBudgetDTO> toDto(List<CommercialBudget> entityList) {
if ( entityList == null ) {
return null;
}
List<CommercialBudgetDTO> list = new ArrayList<CommercialBudgetDTO>( entityList.size() );
for ( CommercialBudget commercialBudget : entityList ) {
list.add( toDto( commercialBudget ) );
}
return list;
}
}
|
JavaScript
|
UTF-8
| 1,913 | 2.578125 | 3 |
[] |
no_license
|
import {
CHANGE_SHOW_TODOS_TYPE,
CHANGE_TODO_TYPE,
COLLAPSE_TODOS,
CREATE_TODO,
DELETE_TODO,
} from './actions/todos'
import { collapseTodos } from './actionCreators/todos'
const initialState = {
all: [],
active: [],
completed: [],
showTodosType: 'all',
collapseTodos: false,
}
function active(all) {
return all.filter((todo) => todo.type === 'active')
}
function completed(all) {
return all.filter((todo) => todo.type === 'completed')
}
function createTodo(state, post) {
return {
...state,
all: [post, ...state.all],
active: active([post, ...state.all]),
completed: completed([post, ...state.all]),
}
}
function changeTodoType(state, { postType, postId }) {
const oldAll = state.all
const index = oldAll.findIndex((post) => post.id == postId)
const post = oldAll[index]
const newPost = { ...post, type: postType }
const newAll = [...oldAll.slice(0, index), newPost, ...oldAll.slice(index + 1, oldAll.length)]
return {
...state,
all: newAll,
active: active(newAll),
completed: completed(newAll),
}
}
function deleteTodo(state, postId) {
const index = state.all.findIndex((post) => post.id == postId)
const newAll = [...state.all.slice(0, index), ...state.all.slice(index + 1, state.all.length)]
return {
...state,
all: newAll,
active: active(newAll),
completed: completed(newAll),
}
}
export function todosReducer(state = initialState, action) {
switch (action.type) {
case CREATE_TODO:
return createTodo(state, action.payload)
case CHANGE_TODO_TYPE:
return changeTodoType(state, action.payload)
case DELETE_TODO:
return deleteTodo(state, action.payload)
case CHANGE_SHOW_TODOS_TYPE:
return { ...state, showTodosType: action.payload }
case COLLAPSE_TODOS:
return { ...state, collapseTodos: !state.collapseTodos }
default:
return state
}
}
|
Java
|
UTF-8
| 126 | 1.632813 | 2 |
[] |
no_license
|
package com.digital.coffeeshop.constants;
public interface Constants {
boolean TRUE = true;
boolean FALSE = false;
}
|
Markdown
|
UTF-8
| 3,288 | 3.453125 | 3 |
[] |
no_license
|
- [shell中其他值得关注的知识点](#shell%e4%b8%ad%e5%85%b6%e4%bb%96%e5%80%bc%e5%be%97%e5%85%b3%e6%b3%a8%e7%9a%84%e7%9f%a5%e8%af%86%e7%82%b9)
- [1. case语句](#1-case%e8%af%ad%e5%8f%a5)
- [2. 调用shell程序的传参](#2-%e8%b0%83%e7%94%a8shell%e7%a8%8b%e5%ba%8f%e7%9a%84%e4%bc%a0%e5%8f%82)
- [3. while 循环和 case 语言和传参相结合](#3-while-%e5%be%aa%e7%8e%af%e5%92%8c-case-%e8%af%ad%e8%a8%80%e5%92%8c%e4%bc%a0%e5%8f%82%e7%9b%b8%e7%bb%93%e5%90%88)
## shell中其他值得关注的知识点
### 1. case语句
+ `shell` 中的 `case` 语句和 C 语言中的 `switch case`语句作用一样,格式有差异。
+ `shell` 中的 `case` 语句天生没有 `break`,也不需要`break`,和C语言中的`switch case`不同。`shell`中的`case`默认就是匹配上哪个执行哪个,不会说执行完了还去执行后面的其他`case`(就好像`shell`中的`case`语言默认都带了`break`)。
*示例*
```sh
#!/bin/sh
var=1
case $var in
1) echo "1" ;;
2) echo "2" ;;
esac
```
执行结果
```sh
root@book-virtual-machine:/mnt/hgfs/windows/study-notes/嵌入式/uboot移植/1.补基础之shell和makefile# ./helloworld.sh
1
```
### 2. 调用shell程序的传参
+ C 语言中可以通过`main`函数的`argc`和`argv`给程序传参
+ `shell`程序本身也可以调用时传参给他。在`shell`程序内部使用传参也是使用的一些特定符号来表示的,包括:
`$0, $1, $2...` 则依次表示传参的各个参数。
C 语言:`./a.out aa bb cc argc=4, argv[0]=./a.out, argv[1]` 是第一个有效参...
shell: `source a.sh aa bb cc $#=3`,
`$0` 是执行这个`shell`程序的解析程序的名字,`$1`是第一个有效参数的值,`$2`是第2个有效参数的值...
**注意**:`shell`中的很多语法特性和 C 语言中是相同的,也有很多是不同的。(需要多做笔记,多总结,多写代码)
<br/>
*示例*
```sh
#!/bin/sh
echo $#
echo $0
echo $1
echo $2
echo $3
```
执行结果
```sh
root@book-virtual-machine:/mnt/hgfs/windows/study-notes/嵌入式/uboot移植/1.补基础之shell和makefile# ./helloworld.sh aa bb cc
3
./helloworld.sh
aa
bb
cc
```
### 3. while 循环和 case 语言和传参相结合
+ `shell`中的`break`关键字和`c`语言中意义相同(都是跳出)但是用法不同。因为`shell`中`case`语句默认不用`break`的,因此在`shell`中`break`只用于循环跳出。所以当`while`中内嵌`case`语句时,`case`中的`break`是跳出外层的`while`循环的,不是用来跳出`case`语句的。
+ shell中的`$#`, `$1`等内置变量的值不是不可变的,而是可以被改变的,被`shift`指令改变。`shift`指令有点像左移运算符,把我们给`shell`程序的传参左移了一个移出去了,原来的`$2`变成了新的`$1`,原来的`$#`少了1个。
<br/>
*示例*
```sh
#!/bin/sh
echo $# $0 $1 $2 $3
shift
echo $# $0 $1 $2 $3
```
执行结果
```sh
root@book-virtual-machine:/mnt/hgfs/windows/study-notes/嵌入式/uboot移植/1.补基础之shell和makefile# ./helloworld.sh aa bb cc
3 ./helloworld.sh aa bb cc
2 ./helloworld.sh bb cc
```
|
C#
|
UTF-8
| 1,908 | 3.125 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
namespace Bici
{
class Program
{
static void Main(string[] args)
{
Bici bici1 = new Bici();
bici1.init("Huffy", 8, 12);
//bici1.sube();
bici1.print();
Bici bici2 = new Bici();
bici2.init("PineStar", 5, 10);
bici2.print();
Bici bici3 = new Bici();
bici3.init("Apache", 9, 13);
bici3.print();
List<Bici> bicis = new List <Bici>();
bicis.Add(bici1);
bicis.Add(bici2);
bicis.Add(bici3);
foreach(Bici b in bicis)
{
b.print();
}
Persona usuario = new Persona();
usuario.init("Felix","felixenriquelm45@gmail.com");
usuario.print();
}
}
class Persona
{
private string nombre;
private string correo;
//private List<Bici> bicis;
public void init(string n, string c)
{
nombre = n;
correo = c;
}
public void print()
{
Console.WriteLine("{0} {1}", nombre, correo);
}
}
class Bici
{
private string marca; private int current_velocity;
private int velocities;
//private Persona dueño;
public void print()
{
Console.WriteLine("Marca:{0}, Velocity:{1}", marca, current_velocity);
}
public void init(string marca, int cv, int vs)
{
this.marca = marca;
current_velocity = cv;
velocities = vs;
if (cv>vs)
{
current_velocity = vs;
}
else
{
current_velocity = cv;
}
}
}
}
|
C++
|
UTF-8
| 1,224 | 3.21875 | 3 |
[] |
no_license
|
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <fstream>
void print_usage()
{
std::cout << "usage: gen -n {file_name} -s {1eN}" << std::endl;
exit(1);
}
auto parse_size_file(const char* size)
{
if (!strstr(size, "1e")) print_usage();
auto p = atoi(&(size[2]));
return pow(10, p);
}
int main(int argc, char** argv)
{
srand(time(NULL));
if (argc < 5) {
print_usage();
}
std::string path;
size_t size = 0;
for(auto i = 1; i < argc; ++i)
{
if(strcmp(argv[i], "-n") == 0 && (i+1) < argc) {
path = argv[i+1];
} else if (strcmp(argv[i], "-s") == 0 && (i+1) < argc) {
size = parse_size_file(argv[i+1]);
}
}
if (path == "" || size == 0) print_usage();
std::cout << "Generate " << path << " file with " << size << " numbers" << std::endl;
std::ofstream file(path, std::ios::binary | std::ios::trunc);
if (!file) {
std::cerr << "can't create file" << std::endl;
exit(1);
}
while(size--)
{
int16_t num = rand() % static_cast<int16_t>(INT16_MAX);
file.write((char *)&num, sizeof(num));
}
file.close();
}
|
JavaScript
|
UTF-8
| 6,462 | 2.5625 | 3 |
[
"MIT",
"Unlicense"
] |
permissive
|
// v13
const { MessageSelectMenu: MessageMenu, MessageActionRow } = require('discord.js')
module.exports = {
name: 'filters',
category: 'filter',
description: '[Premium] 切換特效',
aliases: [],
premium: true,
run: async (bot, msg, args) => {
var { MessageMenuOption } = bot
try {
if (!bot.player.isPlaying(msg.guild.id)) { throw new Error('目前沒有正在播放的歌曲!') }
if (!msg.member.voice.channel) {
throw new Error('您尚未加入任何一個語音頻道!')
} else if (
msg.member.voice.channel && msg.guild.me.voice.channel && msg.member.voice.channel.id !== msg.guild.me.voice.channel.id
) {
throw new Error('您必須要與機器人在同一個語音頻道!')
}
const np = await bot.player.nowPlaying(msg.guild.id)
if (!await bot.isDJPerm(np)) throw new Error('沒有權限!!')
let active_filters = ["nightcore", "bass", "karaoke", "subboost", "8d", "vaporwave", "shadow", "echo", "mountain_echo", "metal"]
/*var message = await msg.channel.send(
new bot.MessageEmbed()
.setTitle("特效清單")
.setDescription(":one: nightcore\n:two: bassboost\n:three: karaoke\n:four: subboost\n:five: 8D\n:six: vaporwave\n:seven: shadow\n:eight: echo\n:nine: mountain\n:ten: metal")
.setColor("RANDOM")
.setFooter(bot.config.footer, bot.user.displayAvatarURL())
)*/
var embed =
new bot.MessageEmbed()
.setTitle("👇 可以使用下面的選單選擇音效!")
// .setDescription(":one: nightcore\n:two: bassboost\n:three: karaoke\n:four: subboost\n:five: 8D\n:six: vaporwave\n:seven: shadow\n:eight: echo\n:nine: mountain\n:ten: metal")
.setColor("RANDOM")
.setFooter(bot.config.footer, bot.user.displayAvatarURL())
const menu = new MessageMenu()
.setCustomId('filter-response')
.setPlaceholder('請選擇您想要開啟/關閉的音效! (可複選, 一次最多三個)')
.setMaxValues(3)
.setMinValues(1)
let no_option = new MessageMenuOption()
.setLabel('不用了')
.setEmoji('❌')
.setValue('no')
.setDescription('不用了謝謝 (我只是看看/上面沒有我想要的音效)')
menu.addOptions([no_option])
for (var i in active_filters) {
let i2 = Number(i) + 1
let option = new MessageMenuOption()
.setLabel("音效 " + String(i2))
.setEmoji('🎶')
.setValue(String(i2))
.setDescription(active_filters[i] + ' 音效')
menu.addOptions([option])
}
msg.channel.send({ embeds: [embed], components: [new MessageActionRow().addComponents(menu)] }).then(m => {
let collector = m.createMessageComponentCollector({ filter: menu => menu.user.id === msg.author.id, max: 1, time: 30000, errors: ['time'] })
collector.on('collect', async (menu) => {
if (menu.customId !== 'filter-response') return;
let reses = []
let no = false
menu.values.forEach(SIndex => {
if (SIndex === 'no') no = true
reses.push(active_filters[parseInt(SIndex) - 1])
})
if (no) {
// Yep, Do nothin'
} else {
reses.forEach(r => bot.commands.get(r)[msg.author.language].run(bot, msg, args))
}
try {
await menu.deferUpdate(true);
} catch (e) {
}
collector.stop()
})
collector.on('end', () => m.delete())
})
/*await message.react("❌")
await message.react("1️⃣")
await message.react("2️⃣")
await message.react("3️⃣")
await message.react("4️⃣")
await message.react("5️⃣")
await message.react("6️⃣")
await message.react("7️⃣")
await message.react("8️⃣")
await message.react️("9️⃣")
await message.react("🔟")
const collector = message.createReactionCollector((r, usr) => usr === msg.author, { time: 30000 })
collector.on("collect", async (r) => {
try {
await r.users.remove(msg.author.id).catch(e => { throw e })
} catch (e) {}
if (!bot.player.getQueue(msg.guild.id).playing) return
switch (r.emoji.name) {
case "❌":
collector.stop()
break
case "1️⃣":
bot.commands.get("nightcore")[msg.author.language].run(bot, msg, args)
break
case "2️⃣":
bot.commands.get("bass")[msg.author.language].run(bot, msg, args)
break
case "3️⃣":
bot.commands.get("karaoke")[msg.author.language].run(bot, msg, args)
break
case "4️⃣":
bot.commands.get("subboost")[msg.author.language].run(bot, msg, args)
break
case "5️⃣":
bot.commands.get("8d")[msg.author.language].run(bot, msg, args)
break
case "6️⃣":
bot.commands.get("vaporwave")[msg.author.language].run(bot, msg, args)
break
case "7️⃣":
bot.commands.get("shadow")[msg.author.language].run(bot, msg, args)
break
case "8️⃣":
bot.commands.get("echo")[msg.author.language].run(bot, msg, args)
break
case "9️⃣":
bot.commands.get("mountain_echo")[msg.author.language].run(bot, msg, args)
break
case "🔟":
bot.commands.get("metal")[msg.author.language].run(bot, msg, args)
break
}
})
collector.on("end", async () => {
try { await message.reactions.removeAll() } catch (e) {}
await message.edit(
new bot.MessageEmbed()
.setColor("FFEE07")
.setDescription("已關閉")
.setFooter(bot.user.tag, bot.user.displayAvatarURL())
)
})*/
} catch (e) {
return msg.channel.send({
embeds: [
new bot.MessageEmbed()
.setTitle('❌ 調整失敗', msg.guild.iconURL())
.setColor('FF2323')
.addField('錯誤訊息', '```' + e.toString() + '```')
.setFooter(bot.config.footer, bot.user.displayAvatarURL())
]
})
}
}
}
|
Java
|
UTF-8
| 474 | 2.109375 | 2 |
[] |
no_license
|
package com.yc.compare.bean;
import java.util.List;
/**
* Created by myflying on 2018/12/5.
*/
public class CountryWrapper {
private String name;
private List<CountryInfo> list;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<CountryInfo> getList() {
return list;
}
public void setList(List<CountryInfo> list) {
this.list = list;
}
}
|
Java
|
UTF-8
| 1,746 | 2.90625 | 3 |
[] |
no_license
|
package org.limewire.ui.swing.components;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.Timer;
/**
* This mouse listener is intended to hide the supplied component after the mouse
* has left the scope of all JComponents this this instance has been added as a
* listener to.
*/
public final class ComponentHider extends MouseAdapter {
private final JComponent component;
private final AdditionalBehavior additionalBehavior;
private final Timer hideTimer = new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (component.isVisible()) {
component.setVisible(false);
if (additionalBehavior != null) {
additionalBehavior.componentHidden();
}
}
} finally {
((Timer)e.getSource()).stop();
}
}
});
public ComponentHider(JComponent menu) {
this(menu, null);
}
public ComponentHider(JComponent menu, AdditionalBehavior additionalBehavior) {
this.component = menu;
this.additionalBehavior = additionalBehavior;
}
@Override
public void mouseEntered(MouseEvent e) {
hideTimer.stop();
}
@Override
public void mouseExited(MouseEvent e) {
hideTimer.start();
}
/**
* Callback to allow additional behavior to happen after the component has been hidden.
*/
public static interface AdditionalBehavior {
void componentHidden();
}
}
|
Python
|
UTF-8
| 881 | 3.515625 | 4 |
[] |
no_license
|
"""
almost-sorted
"""
def almost_sorted(a):
s = sorted(a)
if s == a:
print("yes")
else:
indices = [i for i in range(len(a)) if s[i] != a[i]]
if len(indices) == 2:
a[indices[0]], a[indices[1]] = a[indices[1]], a[indices[0]]
if s == a:
print("yes")
print("swap", indices[0] + 1, indices[1] + 1)
else:
print("no")
elif len(indices) > 2:
a = a[:indices[0]] + a[indices[0]:indices[-1] + 1][::-1] + a[indices[-1] + 1:]
if s == a:
print("yes")
print("reverse", indices[0] + 1, indices[-1] + 1)
else:
print("no")
else:
print("no")
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
almost_sorted(arr)
|
Python
|
UTF-8
| 9,241 | 2.96875 | 3 |
[] |
no_license
|
#main.py
#This function initialises all required aspects of the vision system and then continually processes the live video
#stream to identify hands, cards and bets. A GUI is then shown on top of the live stream.
#Imports
import imutils
import numpy as np
import cv2
from matplotlib import pyplot as plt
from card_read import *
from operator import itemgetter, attrgetter
from displayBets import *
from betprocessing import *
from boardIsolation import *
import handDetection as hdt
import time
#Start the player on $30
PlayerBalance = 30
#Configure the parameters required for the capture of screenshots from the live video feed
cap = cv2.VideoCapture(1)
cap.open(0,cv2.CAP_DSHOW);
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
#Initialise all of the initial variables
yellow_threshold = 300
a = 0
player_current = 0
dealer_current = 0
player_new = 0
dealer_new = 0
cX = []
cY = []
PlayerBalance_old = 100
this_hand = []
prev_hand = []
bet_place = 0
current_bets = [0,0,0,0,0,0,0,0,0,0,0,0,0]
new_bets = [0,0,0,0,0,0,0,0,0,0,0,0,0]
#Extract an initial screen grab so that we are able to isolate out the playing board
ret,img_read = cap.read()
cv2.imshow('Test',img_read)
cv2.waitKey(0)
image_distort_info = defineIsolation(img_read)
#This is an infinite loop which allows us to continuously capture new images from the live stream
while True:
a = a + 1
#Acquire Latest Image
# Capture from the specified camera
#Initialise these variables after 20 cycles to make sure that if cards are present they are processed
if a == 20:
HandPresent = 1
BetPresent = 1
else:
HandPresent = 0
BetPresent = 0
# Loop
# Read the frame-by-frame feed of the camera
ret,img_read = cap.read()
#Apply the isolation section to the image which has been exracted
img_read, play_area, deal_area = image_distort_info.isolateSections(img_read)
# Display livestream
cv2.imshow('Frame', img_read)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#Call the hand function and identify the location of the hand
found_hand, this_hand = hdt.handIdentifier(play_area)
deal_hand, dud = hdt.handIdentifier(deal_area)
#Determine level of movement that the hand has undergone, and if a hand is located then we need to update the
#lastest hand detection, and determine the centroid location of the tip of the hand. Then display this on the board
#as a purple dot
if found_hand == 1:
hand_move = this_hand.handMovement(prev_hand)
prev_hand = this_hand.handArea
cv2.circle(img_read,(this_hand.centroid[0], this_hand.centroid[1]),5,(200, 0, 100),-1)
else:
prev_hand = []
hand_move = 1
#If we have located a hand on the board on the board, and playing cards have been detected then we can go throough
#and update the bet processing to ensure the latest bets have been processed correctly
if (found_hand == 1) and (bet_place == 0) and (len(cX) > 0) and (len(cY) > 0) and (hand_move < 0.1):
bet_process_return = betprocessing(this_hand.centroid[0], this_hand.centroid[1], this_hand.gesture, cX, cY, current_bets, PlayerBalance, cardValue)
if PlayerBalance < 0:
#If the Player Balance is less than zero dollars then no bets would have been placed, we can update the GUI
#and return to the start of the while loop
if len(cX) > 12:
displayBets(cX,cY,card_height,current_bets,cardValue,PlayerBalance,img_read)
continue
#If the player does have money left to bet with then we will go through and update the bets on each of the cards
#update the player balance and then display these to the screen
else:
current_bets = bet_process_return[len(bet_process_return) - 2]
PlayerBalance = bet_process_return[len(bet_process_return) - 1]
PlayerBalance_old = PlayerBalance
bet_place = 1
if len(cX) > 12:
displayBets(cX,cY,card_height,current_bets,cardValue,PlayerBalance,img_read)
continue
#If we have not found a hand, but a bet is present then we can go through and update the GUI but not try to identify
#the cards present
elif ((found_hand == 0) | (hand_move > 0.1)) and bet_place == 1:
bet_place = 0
if len(cX) > 12:
displayBets(cX,cY,card_height,current_bets,cardValue,PlayerBalance,img_read)
continue
#If none of the previous if statements have been hit, but a hand or bet is present then we want to update the GUI
#but we do not want to go through and undergo card identification again
elif ((found_hand != 0) | (deal_hand != 0)) & (len(cX) > 5):
if len(cX) > 12:
displayBets(cX,cY,card_height,current_bets,cardValue,PlayerBalance,img_read)
continue
#Card Identification Function(
#Inputs: Current Image
#Function: Identifies the location of each of the cards in the image
#Outputs: [cardValue,cX,cY,card_height]
#)
#Extract out the cards which were identified as part of the identification algorithm
card_values_return = card_identification(img_read)
test_val = card_values_return[0][0]
#Check to make sure the first card returned did not have a value of 15, if it did then there has been an error
#in identifying the cards
if card_values_return[0][0] != 15:
#Extract out the card centroid location, card rank and card height from the array that was returned
cX = card_values_return[:,1]
cY = card_values_return[:,2]
cardValue = card_values_return[:,0]
card_height = card_values_return[:,3]
#Extract out the rank of the player card
if card_values_return[len(card_values_return) - 1][2] < 300:
player_new = card_values_return[len(card_values_return) - 1][0]
#Extract out the rank of the dealer card
if card_values_return[len(card_values_return) - 3][2] < 300:
dealer_new = card_values_return[len(card_values_return) -3][0]
print(len(card_values_return) -3)
#Do an if statement to determine the card values have changed for either the player or the dealer
#If the card values have changed then we will need to process the bets
if player_new == player_current:
Player_Change = 0
else:
Player_Change = 1
if dealer_new == dealer_current:
Dealer_Change = 0
else:
Dealer_Change = 1
#If a change has been made to both cards then do nothing, however if both have changed then we need to go
#through and process the bets
if (Player_Change + Dealer_Change) < 2:
cv2.waitKey(1)
elif player_new == 20 or dealer_current == 20:
cv2.waitKey(1)
elif Player_Change == 1 and Dealer_Change == 1:
#Wait briefly to make sure that the cards have stabilised and we don't mis-classify the cards
cv2.waitKey(150)
#Go through the card identification process again to make sure we have the most update to version of the
#cards
card_values_return = card_identification(img_read)
cX = card_values_return[:,1]
cY = card_values_return[:,2]
cardValue = card_values_return[:,0]
card_height = card_values_return[:,3]
player_new = card_values_return[len(card_values_return) - 1][0]
dealer_new = card_values_return[len(card_values_return) -3][0]
#Send through the new values of the player and dealer card so we can perform the relevant bet arithmetic
bet_arth_return = betarithmetic(player_new,dealer_new,current_bets,PlayerBalance)
if len(bet_arth_return) == 0:
continue
#Update the current value of the player and dealer cards to make sure that they are stored correctly for
#next time
else:
player_current = player_new
dealer_current = dealer_new
current_bets = bet_arth_return[len(bet_arth_return) - 2]
PlayerBalance = bet_arth_return[len(bet_arth_return) - 1]
#The Player's Balance only would have changed if the player won, so if so display this fact onto
#the GUI interface
if PlayerBalance != PlayerBalance_old:
cv2.putText(img_read,"Player Win",(800,240),cv2.FONT_HERSHEY_DUPLEX,0.75,(0,255,0),2)
PlayerBalance_old = PlayerBalance
cv2.waitKey(100)
#If we have found at least 12 cards then progress to display the bets
if len(cX) > 12:
displayBets(cX,cY,card_height,current_bets,cardValue,PlayerBalance,img_read)
# When done, release the capture and close windows
cap.release()
#cv2.waitKey(0)
cv2.destroyAllWindows()
|
Java
|
UTF-8
| 1,730 | 4.1875 | 4 |
[] |
no_license
|
package hw33;
/**
* Реализует структуру данных "Стэк" на основе одномерного массива.
* @author Егор
*/
public class Stack2 implements StackI{
private int n = 20;
private int[] array = new int[n];
private int length = 0;
/**
* Упорядоченно кладёт новый элемент в стэк (на вершину стэка).
* @author Егор
* @param number Число, которое является добавляемым в стэк элементом.
*/
public void push(int number) {
for (int i = n - 2; i > 0; i--)
array[i] = array[i-1];
array[0] = number;
length++;
}
/**
* Возвращает элемент, добавленный в стек последним (лежащий на вершине стэка), и удаляет этот элемент из стека.
* @author Егор
*/
public int pop() {
int temp = array[0];
for (int i = 0; i < n-1; i++)
array[i] = array[i+1];
length--;
return temp;
}
/**
* Возвращает элемент, добавленный в стек последним (лежащий на вершине стэка).
* @author Егор
*/
public int top() {
return array[0];
}
/**
* Выводит на экран все элементы стэка, начиная с вершины.
* @author Егор
*/
public void printStack() {
System.out.println("Your stack: ");
for (int i = 0; i < length; i++)
System.out.print(" " + array[i]);
System.out.println();
}
}
|
JavaScript
|
UTF-8
| 498 | 3.421875 | 3 |
[] |
no_license
|
let insertSort = function(arr) {
if (!arr) throw new Error("new error!");
let len = arr.length;
for (let i = 1; i < len; i++) {
if (arr[i] < arr[i-1]) {
let k = i - 1,
d = arr[i];
arr[i] = arr[i-1];
while(arr[k] > d) {
arr[k--] = arr[k];
}
arr[k+1] = d;
}
}
return arr;
}
let swap = function(arr, i, j) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
|
C++
|
UTF-8
| 1,768 | 3.0625 | 3 |
[] |
no_license
|
#ifndef COLOR_H
#define COLOR_H
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include "bitmap_image.hpp"
using namespace std;
// RGB struct
struct RGB {
int red;
int green;
int blue;
};
// HSV struct
struct HSV {
double hue;
double saturation;
double value;
};
RGB CreateRGB(int red, int green, int blue);
HSV CreateHSV(double hue, double saturation, double value);
RGB BitmapToRGB(rgb_t rgb_bmp);
HSV BitmapToHSV(rgb_t rgb_bmp);
rgb_t RGBToBitmap(int red, int green, int blue);
rgb_t RGBToBitmap(RGB rgb);
rgb_t HSVToBitmap(HSV hsv);
/******************************************************************************/
struct RGB ** init_RGB(int rows, int cols);
struct HSV ** init_HSV(int rows, int cols);
void populate_RGB(struct RGB ** rgb_arr, int rows, int cols);
void populate_HSV(struct HSV ** hsv_arr, int rows, int cols);
void print_RGB(struct RGB ** rgb_arr, int rows, int cols);
void print_HSV(struct HSV ** hsv_arr, int rows, int cols);
void delete_RGB(struct RGB ** rgb_arr, int rows, int cols);
void delete_HSV(struct HSV ** hsv_arr, int rows, int cols);
static double Min(double a, double b);
static double Max(double a, double b);
double GetHue(RGB rgb);
double GetHue(double red, double green, double blue);
double GetSaturation(RGB rgb);
double GetSaturation(double red, double green, double blue);
double GetValue(RGB rgb);
double GetValue(double red, double green, double blue);
HSV RGB2HSV(RGB rgb);
HSV RGB2HSV(double red, double green, double blue);
void RGB2HSV(struct RGB ** rgb_arr, struct HSV ** hsv_arr, int rows, int cols);
RGB HSV2RGB(HSV hsv);
RGB MergeRGB(RGB a, RGB b);
HSV MergeHSV(HSV a, HSV b);
#endif
|
TypeScript
|
UTF-8
| 1,565 | 2.671875 | 3 |
[] |
no_license
|
import { IAppAction } from './app-state';
import { Todo } from './todo';
export const ADD_TODO = 'ADD_TODO'
export const REMOVE_TODO = 'REMOVE_TODO'
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED'
export const START_EDIT = 'START_EDIT'
export const TODOS_RETRIEVED = 'TODOS_RETRIEVED'
export const CANCEL_EDIT = 'CANCEL_EDIT'
export const UPDATE_TODO = 'UPDATE_TODO'
export const TOGGLE_COMPLETION = 'TOGGLE_COMPLETION'
export const addTodo = (text: string): IAppAction => {
return {
type: ADD_TODO,
payload: {
newTodo: text
}
}
}
export const removeTodo = (todo: Todo): IAppAction => {
return {
type: REMOVE_TODO,
payload: {
todo: todo
}
}
}
export const clearCompleted = (): IAppAction => {
return { type: CLEAR_COMPLETED, payload: null }
}
export const startEdit = (index: number): IAppAction => {
return {
type: START_EDIT,
payload: {
index: index
}
}
}
export const todosRetrieved = (todos: Todo[]): IAppAction => {
return {
type: TODOS_RETRIEVED,
payload: {
todos: todos
}
}
}
export const cancelEdit = (index: number): IAppAction => {
return {
type: CANCEL_EDIT,
payload: {
index: index
}
}
}
export const updateTodo = (index: number, editedTitle: string): IAppAction => {
return {
type: UPDATE_TODO,
payload: {
index: index,
title: editedTitle
}
}
}
export const toggleCompletion = (index: number): IAppAction => {
return {
type: TOGGLE_COMPLETION,
payload: {
index: index
}
}
}
|
TypeScript
|
UTF-8
| 361 | 2.578125 | 3 |
[] |
no_license
|
//
import {
debounce as lodashDebounce
} from "lodash";
export function debounce(duration: number): MethodDecorator {
let decorator = function (target: object, name: string | symbol, descriptor: PropertyDescriptor): PropertyDescriptor {
descriptor.value = lodashDebounce(descriptor.value, duration);
return descriptor;
};
return decorator;
}
|
Swift
|
UTF-8
| 438 | 2.59375 | 3 |
[] |
no_license
|
//
// ToDo.swift
// ToDo
//
// Created by MacBook Air on 28.11.2019.
// Copyright © 2019 MacBook Air. All rights reserved.
//
import UIKit
class ToDo {
var name = ""
var important = false
var priority = 0
var timeForTask = 0.0
var timeLeft = 0.0
var startTimePlanning = Date()
var endTimePlanning = Date()
var doTaskButtonState = ""
var startDoTaskTime = Date()
var endDoTaskTime = Date()
}
|
Java
|
UTF-8
| 655 | 3.171875 | 3 |
[] |
no_license
|
package domain;
public class IPhone extends CellPhone {
protected String data;
static public final String BRAND = "애플",KIND="아이폰";
public void setData(String data) {
this.data=data+"이라고 문자했다.";
}
public String getData() {
return data;
}
public String toString() {
// 홍길동에게 010번호로 애플 제품 아이폰을 사용해서
// 이동가능한 상태로 안녕이라고 문자를 전송했다.
super.setPortable(true);
return String.format("%s에게 %s번호로 %s제품 %s을 사용해서 %s상태로 %s",
super.getName(),super.getPhoneNum(),BRAND,KIND,super.getMove(),data
);
}
}
|
C#
|
UTF-8
| 1,818 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
namespace Crystal.Themes.Converters;
/// <summary>
/// Converts a String into a Visibility enumeration (and back).
/// The FalseEquivalent can be declared with the "FalseEquivalent" property.
/// </summary>
[ValueConversion(typeof(string), typeof(Visibility))]
[MarkupExtensionReturnType(typeof(StringToVisibilityConverter))]
public class StringToVisibilityConverter : MarkupConverter
{
/// <summary>
/// Initialize the properties with standard values
/// </summary>
public StringToVisibilityConverter()
{
FalseEquivalent = Visibility.Collapsed;
OppositeStringValue = false;
}
/// <summary>
/// FalseEquivalent (default : Visibility.Collapsed => see Constructor)
/// </summary>
public Visibility FalseEquivalent { get; set; }
/// <summary>
/// Define whether the opposite boolean value is crucial (default : false)
/// </summary>
public bool OppositeStringValue { get; set; }
/// <inheritdoc/>
protected override object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is null or string && targetType == typeof(Visibility))
{
if (OppositeStringValue)
{
return string.IsNullOrEmpty((string?)value) ? Visibility.Visible : FalseEquivalent;
}
return string.IsNullOrEmpty((string?)value) ? FalseEquivalent : Visibility.Visible;
}
return default(Visibility);
}
/// <inheritdoc/>
protected override object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
|
Ruby
|
UTF-8
| 544 | 4.1875 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Write your code here.
def line(deli_array)
string = "The line is currently empty."
if deli_array.length > 0
string = "The line is currently: "
deli_array.each_with_index do |person, i|
string += "#{i + 1}. #{person} "
end
end
puts string.strip
end
def take_a_number(deli, name)
deli.push(name)
puts "Welcome, #{name}. You are number #{deli.length} in line."
deli
end
def now_serving(deli)
if deli.length == 0
puts "There is nobody waiting to be served!"
else
puts "Currently serving #{deli[0]}."
deli.shift
end
end
|
C++
|
UTF-8
| 754 | 2.671875 | 3 |
[] |
no_license
|
//
// Created by akira on 6/18/17.
//
#ifndef KNOWLEDGEMAP_V2_PREDMAP_H
#define KNOWLEDGEMAP_V2_PREDMAP_H
#include <unordered_map>
#include "Indiv.h"
namespace kri_map{
class PredMap{
private:
//example 2_3_4_ -> True
//map indiv_ids -> T/F
std::unordered_map<std::string, bool> map_;
public:
PredMap():map_({{}})
{
std::cout<<"PredMap: created"<<std::endl;
}
~PredMap()
{
std::cout<<"PredMap: destroyed"<<std::endl;
}
void addMapping(const std::vector<std::weak_ptr<Indiv>>& src,
const bool& t_f);
bool operator[](const std::vector<std::weak_ptr<Indiv>>&);
};
}
#endif //KNOWLEDGEMAP_V2_PREDMAP_H
|
C++
|
UTF-8
| 1,467 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "CPU_Fault.hpp"
#include "Instructions.hpp"
using namespace std;
CPU::Fault::Fault(const CPU& cpu, const string& msg)
{
stringstream ss;
ss << "CPU Fault: " << msg << '\n';
ss << "\tOpcode: ";
if (cpu._inst < NUM_INSTRUCTIONS)
{
ss << InstStrings[cpu._inst] << '\n';
}
else
{
ss << "0x" << hex << unsigned(cpu._inst) << " (Unknown)\n";
}
ss << "\tA:\t" << "0x" << hex << unsigned(cpu._regs.A) << " (" << dec << unsigned(cpu._regs.A) << ")\n";
ss << "\tI:\t" << "0x" << hex << unsigned(cpu._regs.I) << " (" << dec << unsigned(cpu._regs.I) << ")\n";
ss << "\tX:\t" << "0x" << hex << unsigned(cpu._regs.X) << " (" << dec << unsigned(cpu._regs.X) << ")\n";
ss << "\tY:\t" << "0x" << hex << unsigned(cpu._regs.Y) << " (" << dec << unsigned(cpu._regs.Y) << ")\n";
ss << "\tFP:\t" << "0x" << hex << unsigned(cpu._regs.FP) << '\n';
ss << "\tSP:\t" << "0x" << hex << unsigned(cpu._regs.SP) << '\n';
ss << "\tIP*:\t" << "0x" << hex << unsigned(cpu._regs.IP) << " (";
if (cpu._mem.Read8(cpu._regs.IP) < NUM_INSTRUCTIONS)
{
ss << InstStrings[cpu._mem.Read8(cpu._regs.IP)] << ")\n";
}
else
{
ss << "Bad Opcode)\n";
}
_what = ss.str();
}
CPU::Fault::~Fault() throw ()
{
}
const char* CPU::Fault::what() const throw ()
{
return _what.c_str();
}
|
Markdown
|
UTF-8
| 1,521 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
# Fable.Remoting
Fable.Remoting is a [RPC](https://en.wikipedia.org/wiki/Remote_procedure_call) communication layer for Fable and .NET apps featuring [Suave](https://github.com/SuaveIO/suave), [Giraffe](https://github.com/giraffe-fsharp/Giraffe), [Saturn](https://github.com/SaturnFramework/Saturn) or any [Asp.net core](https://docs.microsoft.com/en-us/aspnet/core/?view=aspnetcore-2.1) application on the server. On the client you can have either a [Fable](http://fable.io/) project or [.NET Apps](src/dotnet-client.md) like Xamarin or WPF. This library lets you think about your client-server interactions in terms of pure stateless functions by defining a shared interface that is used by both the client and server.
As the name suggests, the library is inspired by the awesomeness of [Websharper's Remoting](https://developers.websharper.com/docs/v4.x/fs/remoting) feature but it uses different approach to achieve type-safety.
### Quick Start
Use the [SAFE Stack](https://safe-stack.github.io/docs/) where Fable.Remoting is already set up and ready to go for full stack F# web development.
Learn more in-depth about Fable.Remoting from my talk at NDC Oslo 2021 where I explain and demonstrate how Fable.Remoting works and the class of problems that it solved.
<iframe width="560" height="315" src="https://www.youtube.com/embed/6bkZeR0ptqc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
Java
|
UTF-8
| 1,446 | 2.46875 | 2 |
[] |
no_license
|
package org.rb.qa.xmlmodel;
import org.rb.mm.interfaceimpl.JaxbXmlParser;
import org.rb.mm.interfaceimpl.SimpleXmlParser;
import org.rb.qa.model.KNBase;
import org.rb.mm.interfaces.IStorage;
/**
* Application scope Xml serializer/deserializer factory
* @author raitis
*/
public class XmlFactory {
public static XmlFactory take() {
return new XmlFactory();
}
public static XmlFactory use(ParserType parser){
return new XmlFactory(parser);
}
private IStorage parser = new JaxbXmlParser(KNBase.class);
private XmlFactory() {
this.parser = instantiateParser(ParserType.JaxbParser);
}
private XmlFactory(ParserType parser){
this.parser = instantiateParser(parser);
}
public IStorage getXmlParser() {
return parser;
}
public void setXmlParser(ParserType parser){
this.parser = instantiateParser(parser);
}
private IStorage instantiateParser(ParserType parser) {
IStorage xmlParser;
switch(parser){
case JaxbParser:
xmlParser= new JaxbXmlParser(KNBase.class);
break;
case SimpleParser:
xmlParser = new SimpleXmlParser(KNBase.class);
break;
default:
xmlParser= new JaxbXmlParser(KNBase.class);
}
return xmlParser;
}
}
|
Java
|
WINDOWS-1252
| 517 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
// A+ Computer Science - www.apluscompsci.com
//Name -
//Date -
//Class -
//Lab -
import static java.lang.System.*;
public class StringFirstLetterCheck
{
String wordOne, wordTwo;
public StringFirstLetterCheck()
{
}
public StringFirstLetterCheck(String one, String two)
{
}
public void setWords(String one, String two)
{
}
public boolean checkFirstLetter( )
{
return false;
}
public String toString()
{
return wordOne + " does not have the same first letter as " + wordTwo + "\n";
}
}
|
Java
|
UTF-8
| 1,348 | 1.828125 | 2 |
[] |
no_license
|
package com.ztravel.paygate.api.alipay.model;
/**
* 退款解冻结果:解冻结订单号^冻结订单号^解冻结金额^交易号^处理时间^状 态^描述码
*
* @author dingguangxian
*
*/
public class RefundUnfreezedModel {
private String unfreezeNum;
private String freezeNum;
private long unfreezeAmount;
private String traceNum;
private String transTime;
private String state;
private String msg;
public String getUnfreezeNum() {
return unfreezeNum;
}
public void setUnfreezeNum(String unfreezeNum) {
this.unfreezeNum = unfreezeNum;
}
public String getFreezeNum() {
return freezeNum;
}
public void setFreezeNum(String freezeNum) {
this.freezeNum = freezeNum;
}
public long getUnfreezeAmount() {
return unfreezeAmount;
}
public void setUnfreezeAmount(long unfreezeAmount) {
this.unfreezeAmount = unfreezeAmount;
}
public String getTraceNum() {
return traceNum;
}
public void setTraceNum(String traceNum) {
this.traceNum = traceNum;
}
public String getTransTime() {
return transTime;
}
public void setTransTime(String transTime) {
this.transTime = transTime;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
|
C#
|
UTF-8
| 1,093 | 2.953125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RespositoryDemo
{
/// <summary>
/// 所有仓库中相同逻辑实现的地方
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BaseRepository<T> : IRespository<T>
{
public virtual void Add(T item)
{
throw new NotImplementedException();
}
public virtual void Remove(T item)
{
throw new NotImplementedException();
}
public virtual void Update(T item)
{
throw new NotImplementedException();
}
public virtual T FindByID(Guid id)
{
throw new NotImplementedException();
}
public virtual IEnumerable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
throw new NotImplementedException();
}
public virtual IEnumerable<T> FindAll()
{
throw new NotImplementedException();
}
}
}
|
C#
|
UTF-8
| 1,314 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oblqo.Tasks
{
[System.AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
sealed class AccountFileStateChangeAttribute : Attribute
{
// See the attribute guidelines at
// http://go.microsoft.com/fwlink/?LinkId=85236
readonly string filePropertyName;
readonly string parentFilePropertyName;
readonly AccountFileStates newState;
// This is a positional argument
public AccountFileStateChangeAttribute(AccountFileStates newState, string filePropertyName = "File", string parentFilePropertyName = null)
{
this.filePropertyName = filePropertyName;
this.newState = newState;
this.parentFilePropertyName = parentFilePropertyName;
}
public string FilePropertyName
{
get { return filePropertyName; }
}
public string ParentFilePropertyName
{
get { return parentFilePropertyName; }
}
// This is a named argument
public AccountFileStates NewState
{
get
{
return newState;
}
}
}
}
|
Java
|
UTF-8
| 502 | 3.15625 | 3 |
[] |
no_license
|
package question10;
public class booleancontains {
public static boolean contains(String[] names, String element)
{
for (int Count = 0 ; Count< names.length ; Count++){
if(element == names[Count]){
return true;
}else return false;
}
return false;
}
public static void main(String[] args) {
String[] array2 = {"jon", "jon1", "jon2", "jon3", "jon4"};
System.out.println(contains(array2, "jon0"));
}
}
|
Rust
|
UTF-8
| 393 | 3.109375 | 3 |
[] |
no_license
|
use std::thread;
// mpsc - multi-producer, single-consumer
// https://doc.rust-lang.org/std/sync/mpsc/
use std::sync::mpsc;
pub fn run() {
// destruct a tuple
let (tx, rx) = mpsc::channel();
// unwrap the Result
thread::spawn(move || {
tx.send(42).unwrap();
});
// recv() is blocking, try_recv() is non-blocking
println!("got {}", rx.recv().unwrap());
}
|
Python
|
UTF-8
| 112 | 2.78125 | 3 |
[] |
no_license
|
class GrupModel(object):
def __init__(self, id,GrupAdi):
self.id: int = id
self.grupadi: str = GrupAdi
|
Markdown
|
UTF-8
| 6,588 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# RPZ Zones
## List all RPZ Zones
You may list collection of rpz zones using this action.
```shell
curl --include \
--header "Content-Type: application/json" \
--header "Authorization: Token token=iwwTXK54aahsosrx5JK7hkTe" \
'http://manage.rpzdb.com/api/v1/zones'
```
> The above command returns JSON structured like this:
```json
{
"zones": [
{
"id": 3,
"zone_name": "labs",
"combine": "labs.us-east.rpzdb.com",
"server_name": "us-east.rpzdb.com",
"server_ip": "54.225.70.69",
"created_at": "2013-04-05T19:29:22Z",
"updated_at": "2013-04-05T19:29:22Z",
"statements": [
{
"id": 12,
"statement": "also-notify",
"address": "8.8.8.8",
"port": 53
},
{
"id": 13,
"statement": "also-notify",
"address": "4.4.4.4",
"port": 53
}
]
},
{
"id": 82,
"zone_name": "blackhole",
"combine": "blackhole.ap-southeast.rpzdb.com",
"server_name": "ap-southeast.rpzdb.com",
"server_ip": "175.41.131.248",
"created_at": "2018-01-23T04:06:02Z",
"updated_at": "2018-01-23T04:06:02Z",
"tsig": {
"id": 32,
"keyname": "blackhole",
"algorithm": "HMAC-SHA1",
"algorithm_size": "128",
"secret": "mtIsHR3rqQKx1EfkQNIQIA=="
},
"statements": [
{
"id": 43,
"statement": "also-notify",
"address": "192.168.3.1",
"port": 53
}
]
}
]
"pages": 1
}
```
This endpoint get list of rpz zones.
### HTTP Request
`GET http://manage.rpzdb.com/api/v1/zones`
### OPTIONAL ARGUMENTS
Parameter | Description
--------- | -----------
page | Up to 20 results will be returned in a single API call per specified page. Default to 1 if not present.
## Create RPZ Zone
You may create a rpz zone using this action. It takes a JSON object containing a parameters.
```shell
curl --include \
--request POST \
--header "Content-Type: application/json" \
--header "Authorization: Token token=iwwTXK54aahsosrx5JK7hkTe" \
--data-binary "{
\"zone_name\": \"blackhole\",
\"site_ip\": [\"192.168.3.1\"],
\"feed_server\": \"ap-southeast.rpzdb.com\"
}" \
'http://manage.rpzdb.com/api/v1/zones'
```
> The above command returns JSON structured like this:
```json
{
"id": 62,
"zone_name": "blackhole",
"combine": "blackhole.ap-southeast.rpzdb.com",
"server_name": "ap-southeast.rpzdb.com",
"server_ip": "175.41.131.248",
"created_at": "2018-01-22T13:02:19Z",
"updated_at": "2018-01-22T13:02:19Z",
"tsig": {
"id": 23,
"keyname": "blackhole",
"algorithm": "HMAC-SHA1",
"algorithm_size": "128",
"secret": "KW7qFUTKrKWr+J4qJTKkEw=="
},
"statements": [
{
"id": 33,
"statement": "also-notify",
"address": "192.168.3.1",
"port": 53
}
]
}
```
This endpoint create a rpz zone.
### HTTP Request
`POST http://manage.rpzdb.com/api/v1/zones`
### REQUIRED ARGUMENTS
Parameter | Description
--------- | -----------
zone_name | Rpz zone name
site_ip | DNS server ip destination(Must be in array)
### OPTIONAL ARGUMENTS
Parameter | Description
--------- | -----------
feed_server | Blacklist provider server address
### RESPONSE PARAMETER
Parameter | Description
--------- | -----------
id | The ID of the selected zone
zone_name | Selected zone name
combine | Combined of zone name
server_name | Server name
server_ip | Server ip address
created_at | Date and time created
updated_at | Date and time updated
tsig[id] | Transaction signature id
tsig[keyname] | Transaction signature keyname
tsig[algorithm] | Transaction signature algorithm
tsig[algorithm_size] | Transaction signature size
tsig[secret] | Transaction signature secret
statement[] | Contains notify statement
## Show RPZ Zone
You may list a zone using this action.
```shell
curl --include \
--header "Authorization: Token token=iwwTXK54aahsosrx5JK7hkTe" \
'http://manage.rpzdb.com/api/v1/zones/62'
```
> The above command returns JSON structured like this:
```json
{
"id": 62,
"zone_name": "blackhole",
"combine": "blackhole.ap-southeast.rpzdb.com",
"server_name": "ap-southeast.rpzdb.com",
"server_ip": "175.41.131.248",
"created_at": "2018-01-22T13:02:19Z",
"updated_at": "2018-01-22T13:02:19Z",
"tsig": {
"id": 23,
"keyname": "blackhole",
"algorithm": "HMAC-SHA1",
"algorithm_size": "128",
"secret": "KW7qFUTKrKWr+J4qJTKkEw=="
},
"statements": [
{
"id": 33,
"statement": "also-notify",
"address": "192.168.3.1",
"port": 53
}
]
}
```
This endpoint get list of zones.
### HTTP Request
`GET http://manage.rpzdb.com/api/v1/zones/:id`
### URL PARAMETER
Parameter | Description
--------- | -----------
id | The ID of the zone to show
### RESPONSE PARAMETER
Parameter | Description
--------- | -----------
id | The ID of the selected zone
zone_name | Selected zone name
combine | Combined of zone name
server_name | Server name
server_ip | Server ip address
created_at | Date and time created
updated_at | Date and time updated
tsig[id] | Transaction signature id
tsig[keyname] | Transaction signature keyname
tsig[algorithm] | Transaction signature algorithm
tsig[algorithm_size] | Transaction signature size
tsig[secret] | Transaction signature secret
statement[] | Contains notify statement
## Delete RPZ Zone
You may delete a zone using this action.
```shell
curl --include \
--request DELETE \
--header "Content-Type: application/json" \
--header "Authorization: Token token=iwwTXK54aahsosrx5JK7hkTe" \
'http://manage.rpzdb.com/api/v1/zones/91'
```
The above command returns JSON structured like this:
```json
{
"id": 61,
"zone_name": "blackhole",
"status": "deleted"
}
```
This endpoint delete a zone.
### HTTP Request
`DELETE http://manage.rpzdb.com/api/v1/zones/:id`
### URL PARAMETER
Parameter | Description
--------- | -----------
id | The ID of the zone to delete
### RESPONSE PARAMETER
Parameter | Description
--------- | -----------
id | The ID of the deleted zone
zone_name | Deleted zone name
status | Deleted status
|
JavaScript
|
UTF-8
| 542 | 2.546875 | 3 |
[] |
no_license
|
//点击当前组件去掉其他组件焦点
function focus(e,that) {
let clickOne = e.currentTarget; // e.currentTarget 是你绑定事件的元素
let class_getmychart = document.getElementsByClassName("getmychart");
for (let i = 0 ; i < class_getmychart.length; i ++){
class_getmychart[i].classList.remove('active');
class_getmychart[i].classList.add('inactive');
}
clickOne.classList.remove('inactive');
clickOne.classList.add('active');
that.contentItem = clickOne.getAttribute('id');
}
export default {
focus
}
|
Java
|
UTF-8
| 1,839 | 2.6875 | 3 |
[] |
no_license
|
/**
*
*/
package com.sd.model;
/**
* 附件实体表
* @author elang
*
*/
public class Attachment {
/**主键*/
private int id;
/**关联业务表主键*/
private int fid;
/**附件名称*/
private String fileName;
/**附件存放路径*/
private String filePath;
/**创建时间*/
private String createTime;
/**创建者*/
private int creator;
/**
* 附件类型:0:代表头像;1代表需求;2代表合同;3代表作品;
*
* */
private int type;
public Attachment() {
super();
}
public Attachment(int id, int fid, String fileName, String filePath,
String createTime, int creator, int type) {
super();
this.id = id;
this.fid = fid;
this.fileName = fileName;
this.filePath = filePath;
this.createTime = createTime;
this.creator = creator;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getFid() {
return fid;
}
public void setFid(int fid) {
this.fid = fid;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public int getCreator() {
return creator;
}
public void setCreator(int creator) {
this.creator = creator;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "Attachment [id=" + id + ", fid=" + fid + ", fileName="
+ fileName + ", filePath=" + filePath + ", createTime="
+ createTime + ", creator=" + creator + ", type=" + type + "]";
}
}
|
Markdown
|
UTF-8
| 7,270 | 2.5625 | 3 |
[] |
no_license
|
{{roughtranslation|time=2011-01-31T20:32:00+00:00}}
「'''「嬌蠻貓娘大橫行」角色CD'''」在2010年6月9日開始由Geneon Universal Entertainment一連發售該系列的[[單曲|單曲]]。
== 概要 ==
*[[電視動畫|電視動畫]]『[[嬌蠻貓娘大橫行|嬌蠻貓娘大橫行]]』的[[角色歌曲|角色歌曲]]系列。全4片。2010年6月9日至同年6月25日發售。每次同時發售2片。
*每片有兩首歌曲和一首[[樂器|Ver.Inst]],其中一首歌曲是主題曲「はっぴぃ にゅう にゃあ」的獨唱版本,沒有參與主題曲歌唱的乙女也有獨唱版本。另一首則是角色歌曲。
== 系列一覧 ==
=== 1 芹澤文乃 ===
{{Infobox Single
| Name = 「嬌蠻貓娘大橫行」角色CD1 芹澤文乃
| Artist = 芹澤文乃([[伊藤加奈惠|伊藤加奈惠]])
| Album =
| A-side = ストライプはシマシマ
| B-side = はっぴぃ にゅう にゃあ<br />(Ver. Fumino Serizawa)
| Released = 2010年6月9日
| Format = [[單曲|單曲]]
| Recorded = 2010年<br/>{{JPN}}
| Genre = [[角色歌曲|角色歌曲]]<br />([[動畫歌曲|動畫歌曲]])
| Length =
| Label = Geneon Universal Entertainment<br/>(GNCA-0162)
| Writer = [[くまのきよみ|くまのきよみ]](作詞)<br/>あきづきかおる(作曲 #1)<br/>[[髙木隆次|髙木隆次]](作曲 #2)
| Producer =
| Certification =
| Chart position = * 65位([[ORICON|ORICON]])
| Misc =
{{Extra chronology 2
| Artist = 伊藤加奈惠
| Type = single
| Last single = [[はっぴぃ_にゅう_にゃあ/イチャラブ_Come_Home!|はっぴぃ にゅう にゃあ/イチャラブ Come Home!]]<br/>(2010年)
| This single = '''「嬌蠻貓娘大橫行」角色CD1 芹澤文乃'''<br/>(2010年)
| Next single = [[科學超電磁砲#CD|科學超電磁砲 ARCHIVES4]]<br/>(2010年)
}}}}
2010年6月9日發售。歌:芹澤文乃([[伊藤加奈惠|伊藤加奈惠]])。
# '''ストライプはシマシマ'''
#: 作詞:[[くまのきよみ|くまのきよみ]]、作曲・編曲:あきづきかおる
# '''はっぴぃ にゅう にゃあ(Ver. Fumino Serizawa)'''
#: 作詞:くまのきよみ、作曲・編曲:[[髙木隆次|髙木隆次]]
# ストライプはシマシマ(Ver.Inst)
# Monologue from Fumino
{{clear}}
=== 2 梅之森千世 ===
{{Infobox Single
| Name = 「嬌蠻貓娘大橫行」角色CD2 梅之森千世
| Artist = 梅之森千世([[井口裕香|井口裕香]])
| Album =
| A-side = オ・テ・プリ〜ズ
| B-side = はっぴぃ にゅう にゃあ<br />(Ver. Chise Umenomori)
| Released = 2010年6月9日
| Format = 單曲
| Recorded = 2010年<br/>{{JPN}}
| Genre = 角色歌曲<br />(動畫歌曲)
| Length =
| Label = Geneon Universal Entertainment<br/>(GNCA-0163)
| Writer = くまのきよみ(作詞)<br/>あきづきかおる(作曲 #1)<br/>髙木隆次(作曲 #2)
| Producer =
| Certification =
| Chart position = * 70位(ORICON)
| Misc =
{{Extra chronology 2
| Artist = 井口裕香
| Type = single
| Last single = はっぴぃ にゅう にゃあ/イチャラブ Come Home!<br/>(2010年)
| This single = '''「嬌蠻貓娘大橫行」角色CD2 梅之森千世''' <br/>(2010年)
| Next single = -
}}}}
2010年6月9日發售。歌:梅之森千世([[井口裕香|井口裕香]])。
# '''オ・テ・プリ〜ズ'''
#: 作詞:くまのきよみ、作曲・編曲:あきづきかおる
# '''はっぴぃ にゅう にゃあ(Ver. Chise Umenomori)'''
#: 作詞:くまのきよみ、作曲・編曲:髙木隆次
# オ・テ・プリ〜ズ(Ver.Inst)
# Monologue from Chise
{{clear}}
=== 3 霧谷希 ===
{{Infobox Single
| Name = 「嬌蠻貓娘大橫行」角色CD3 霧谷希
| Artist = 霧谷希([[竹達彩奈|竹達彩奈]])
| Album =
| A-side = スキだからスキ
| B-side = はっぴぃ にゅう にゃあ<br />(Ver. Nozomi Kiriya)
| Released = 2010年6月25日
| Format = 單曲
| Recorded = 2010年<br/>{{JPN}}
| Genre = 角色歌曲<br />(動畫歌曲)
| Length =
| Label = Geneon Universal Entertainment<br/>(GNCA-0164)
| Writer = くまのきよみ(作詞)<br/>髙木隆次(作曲)
| Producer =
| Certification =
| Chart position = * 82位(ORICON)
| Misc =
{{Extra chronology 2
| Artist = 竹達彩奈
| Type = single
| Last single = [[エンドレスkiss|エンドレスkiss]]<br/>(2010年)
| This single = '''「嬌蠻貓娘大橫行」角色CD3 霧谷希''' <br/>(2010年)
| Next single = [[Utauyo!!MIRACLE|Utauyo!!MIRACLE]]<br/>(2010年)
}}}}
2010年6月25日發售。歌:霧谷希([[竹達彩奈|竹達彩奈]])。
(全作詞:くまのきよみ、作曲・編曲:髙木隆次)
# '''スキだからスキ'''
# '''はっぴぃ にゅう にゃあ(Ver. Nozomi Kiriya)'''
# スキだからスキ(Ver.Inst)
# Monologue from Nozomi
{{clear}}
=== 4 都築乙女 ===
{{Infobox Single
| Name = 「嬌蠻貓娘大橫行」角色CD4 都築乙女
| Artist = 都築乙女([[佐藤聰美|佐藤聰美]])
| Album =
| A-side = 乙女ランジュ
| B-side = はっぴぃ にゅう にゃあ<br />(Ver. Otome Tsuduki)
| Released = 2010年6月25日
| Format = 單曲
| Recorded = 2010年<br/>{{JPN}}
| Genre = 角色歌曲<br />(動畫歌曲)
| Length =
| Label = Geneon Universal Entertainment<br />(GNCA-0165)
| Writer = くまのきよみ(作詞)<br/>髙木隆次(作曲)
| Producer =
| Certification =
| Chart position = * 102位(ORICON)
| Misc =
{{Extra chronology 2
| Artist = 佐藤聰美
| Type = single
| Last single = [[純純的心|ぴゅあぴゅあはーと]]<br/>(2010年)
| This single = '''「嬌蠻貓娘大橫行」角色CD4 都築乙女''' <br/>(2010年)
| Next single = [[大和撫子エデュケイション|大和撫子エデュケイション]]<br/>(2010年)
}}}}
2010年6月25日發售。歌:都築乙女([[佐藤聰美|佐藤聰美]])。
(全作詞:くまのきよみ、作曲・編曲:髙木隆次)
# '''乙女ランジュ'''
# '''はっぴぃ にゅう にゃあ(Ver. Otome Tsuduki)'''
# 乙女ランジュ(Ver.Inst)
# Monologue from Otome
{{clear}}
== 外部連結 ==
* [http://www.patisserie-straycats.com/goods_cd.html テレビアニメ『迷い猫オーバーラン!』オフィシャルサイト リリースページ]
{{DEFAULTSORT:Mayoi Neko Ōbāran characther cd}}
[[Category:2010年單曲|Category:2010年單曲]]
[[Category:動畫角色歌曲|Category:動畫角色歌曲]]
[[Category:NBC環球娛樂歌曲|Category:NBC環球娛樂歌曲]]
|
Python
|
UTF-8
| 816 | 3.375 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# url: https://pythonprogramming.net/scatter-plot-matplotlib-tutorial/
# bar charts
import matplotlib.pyplot as plt
days=list(range(1,6))
sleeping = [7,8,6,11,7]
eating = [2,3,4,3,2]
working = [7,8,7,2,2]
playing = [8,5,7,8,13]
plt.plot([],[],color='m', label='Sleeping', linewidth=5)
plt.plot([],[],color='c', label='Eating', linewidth=5)
plt.plot([],[],color='r', label='Working', linewidth=5)
plt.plot([],[],color='k', label='Playing', linewidth=5)
# maker 参数选择参考链接:https://matplotlib.org/api/markers_api.html
plt.stackplot(days, sleeping, eating, working, playing, colors=['m','c', 'r', 'k'])
plt.xlabel('x')
plt.ylabel('y')
# plt.zlabel('z')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()
# if __name__=='__main__':
|
Go
|
UTF-8
| 523 | 2.90625 | 3 |
[] |
no_license
|
package main
import "fmt"
var total_sol int
var limit uint
var board_size uint
func nqueen_bit(board_size, pos, l, r, depth uint) {
if board_size == depth {
total_sol++
return
}
var new uint
now := pos | l | r
for now < limit {
new = (now + 1) & ^now
nqueen_bit(board_size, pos|new, limit&((l|new)<<1), limit&((r|new)>>1), depth+1)
now = now | new
}
return
}
func main() {
board_size = 13
limit = (1 << (board_size)) - 1
total_sol = 0
nqueen_bit(board_size, 0, 0, 0, 0)
fmt.Println(total_sol)
}
|
C++
|
UTF-8
| 1,891 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
/**
* Pen.cpp
*
* Controller for manageing the pen (servo) up and down motion for drawing.
*
* @author Drew Sommer
* @version 1.0.1
* @license MIT (https://mit-license.org)
*/
#include "Pen.h"
#include <Arduino.h>
#include <Servo.h>
/**
* Instantiate the pen with a Servo
* @param pin The servo pin
* @param up The max angle (0-180)
* @param down The min angle (0-180)
* @param del The delay time (ms)
*/
Pen::Pen(int pin, int up, int down, int del)
: _pin(pin),
_upPos(up),
_downPos(down),
_del(del),
_cur(up){};
/**
* Attaches the Pen (call within setup())
*/
void Pen::attach() {
_servo.attach(_pin);
}
/**
* Set the servo to max angle
* @return true/false if completed
*/
bool Pen::up() {
_target = _upPos; // Set target angle
return move(); // Move to target
}
/**
* Set the servo to min angle
* @return true/false if completed
*/
bool Pen::down() {
_target = _downPos; // Set target angle
return move(); // Move to target
};
/**
* Set the low position (using a potentiometer)
* @param ro read-out
*/
int Pen::setDown(int ro) {
_downPos = ro; // Set down position
down(); // Move to down position
return getDown();
};
/**
* Move from the current angle to the target angle
* @return completed (true)
*/
bool Pen::move(){
// Our current angle is greater than our target angle. Decrement our angle
// till we match our target angle.
if(_cur > _target){
for(int i=_cur; i>=_target; i--){
_servo.write(i);
_cur = i;
delay(_del);
}
// Our current angle is less than our target angle. Increment our angle till
// we match our target angle.
} else {
for(int i=_cur; i<=_target; i++){
_servo.write(i);
_cur = i;
delay(_del);
}
}
return true;
}
|
C++
|
UHC
| 727 | 3.109375 | 3 |
[] |
no_license
|
//#include <iostream>
//
////8ܰ γȸ : Ȱ
//
//using namespace std;
//
//int GetNumberOfPeople(int floor, int room)
//{
// if (floor == 0)
// {
// return room;
// }
//
// if (floor == 1)
// {
// return room * (room + 1) * 0.5;
// }
// else {
// int result = 0;
// for (int i = 0; i < room; ++i)
// {
// result += GetNumberOfPeople(floor - 1, i + 1);
// }
// return result;
// }
//
//}
//
//int main()
//{
// cin.tie(NULL);
// cin.sync_with_stdio(false);
//
// int caseNumber;
// cin >> caseNumber;
//
// int floor,
// room;
// for (; caseNumber > 0; --caseNumber)
// {
// cin >> floor;
// cin >> room;
// cout << GetNumberOfPeople(floor, room) << "\n";
// }
//
//
//
// return 0;
//}
|
Ruby
|
UTF-8
| 445 | 3.6875 | 4 |
[] |
no_license
|
# definition of class Car
class Car
def initialize(speed, comfort)
@rating = speed * comfort
end
# Setting rating from outside is not allowed
def rating
return @rating
end
# Details of how rating is calculated are kept inside the class
end
car_1 = Car.new(4, 5)
# expected outptu:
# 20
puts car_1.rating
# access to rating raise NoMethodError of undefined method `rating='
# car_1.rating = 50
|
Java
|
UTF-8
| 1,529 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.onaple.itemizer.data.access;
import com.onaple.itemizer.Itemizer;
import com.onaple.itemizer.data.beans.ItemBean;
import com.onaple.itemizer.data.handlers.ConfigurationHandler;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
@Singleton
public class ItemDAO {
@Inject
private ConfigurationHandler configurationHandler;
/**
* Call the configuration handler to retrieve an item from an id
* @param id ID of the item
* @return Optional of the item data
*/
public Optional<ItemBean> getItem(String id) {
List<ItemBean> items = Itemizer.getConfigurationHandler().getItemList();
for(ItemBean item: items) {
if (item.getId().equals(id)) {
return Optional.of(item);
}
}
return Optional.empty();
}
public ItemBean save(ItemBean item){
List<ItemBean> items = configurationHandler.getItemList();
if(items.stream().noneMatch(itemBean -> itemBean.getId().equals(item.getId()))){
items.add(item);
Itemizer.getConfigurationHandler().saveItemConfig();
}
return item;
}
public Map<String, ItemBean> getMap(){
List<ItemBean> items = Itemizer.getConfigurationHandler().getItemList();
return items.stream().collect(Collectors.toMap(ItemBean::getId, Function.identity()));
}
}
|
Python
|
UTF-8
| 985 | 3.140625 | 3 |
[] |
no_license
|
import sys
sys.path.append('../')
from P36.main import prime_factors_multi
def totient_phi(num):
base = prime_factors_multi(num)
formula = 0 #後ほど式を入れる
for i in range(len(base)):
if formula > 0:
formula *= (base[i][0]-1) * base[i][0] ** (base[i][1]-1)
else:
formula = (base[i][0]-1) * base[i][0] ** (base[i][1]-1)
return formula
##############################修正コード###################################
#def totient_phi(num):
# for i,y in base:
# if formula > 0:
# formula *= (i-1) * i ** (y-1)
# else:
# formula = (i-1) * i ** (y-1)
# return formula
#############################修正コードPart2###############################
# import functools
# import operator
#def totient_phi(num):
# formula = list(map(lambda x: (x[0]-1) * x[0] ** (x[1]-1),base))
# result = functools.reduce(operator.mul,formula)
# return result
|
PHP
|
UTF-8
| 4,631 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
<?php
class XInputtext extends XyneoField
{
/**
*
* @var integer
*/
protected $size = 20;
/**
*
* @var integer
*/
protected $minLength = 0;
/**
*
* @var integer
*/
protected $maxLength;
/**
*
* @var string
*/
protected $placeholderText;
/**
*
* @var boolean
*/
protected $autocomplete = true;
/**
* Build field from parameters
*
* @see XyneoField::buildFromParameters()
*/
public function buildFromParameters($parameters)
{
parent::buildFromParameters($parameters);
foreach ($parameters as $key => $value) {
switch (strtoupper($key)) {
case "SIZE":
$this->setSize($value);
break;
case "MINLENGTH":
$this->setMinLength($value);
break;
case "MAXLENGTH":
$this->setMaxLength($value);
break;
case "PLACEHOLDER":
$this->setPlaceholderText($value);
break;
case "AUTOCOMPLETE":
$this->setAutocomplete($value);
break;
}
}
return $this;
}
/**
*
* @param integer $size
* @return XInputText
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
*
* @param integer $value
* @return XInputText
*/
public function setMinLength($value)
{
$this->minLength = $value;
return $this;
}
/**
*
* @param integer $value
* @return XInputText
*/
public function setMaxLength($value)
{
$this->maxLength = $value;
return $this;
}
/**
*
* @param string $value
* @return XInputText
*/
public function setPlaceholderText($value)
{
$this->placeholderText = $value;
return $this;
}
/**
*
* @param boolean $value
* @return XInputtext
*/
public function setAutocomplete($value)
{
$this->autocomplete = (boolean) $value;
return $this;
}
/**
*
* @return integer
*/
public function getSize()
{
return $this->size;
}
/**
*
* @return integer
*/
public function getMinLength()
{
return $this->minLength;
}
/**
*
* @return integer
*/
public function getMaxLength()
{
return $this->maxLength;
}
/**
*
* @return string
*/
public function getPlaceholderText()
{
return $this->placeholderText;
}
/**
*
* @return boolean
*/
public function getAutocomplete()
{
return $this->autocomplete;
}
/**
* Validate this form field
*
* @see XyneoField::validate()
*/
public function validate()
{
$isValid = true;
if ($this->maxLength && $this->validate->xIsLonger($this->getValue(), $this->maxLength)) {
$this->error = "length-is-too-long";
$isValid = false;
}
if ($this->required && $this->minLength && $this->validate->xIsShorter($this->getValue(), $this->minLength)) {
$this->error = "length-is-too-short";
$isValid = false;
}
return parent::validate() && $isValid;
}
/**
* Render field for the form
*
* @see XyneoField::renderContent()
*/
public function renderContent()
{
$ret = "";
if ($this->tooltip) {
$this->className .= " tooltip";
}
if (isset($this->prefix)) {
$ret .= $this->prefix . " ";
}
$ret .= "<input type=\"text\" name=\"" . $this->id . "\" id=\"" . $this->id . "\" size=\"" . $this->size . "\"" . ($this->maxLength ? " maxlength=\"" . $this->maxLength . "\"" : "") . ($this->className ? " class=\"" . trim($this->className) . "\"" : "") . ($this->disabled ? " disabled" : "") . ($this->readonly ? " readonly" : "") . ($this->placeholderText ? " placeholder=\"" . $this->placeholderText . "\"" : "") . (! $this->autocomplete ? " autocomplete=\"off\"" : "") . " value=\"" . htmlspecialchars($this->getValue()) . "\">" . ($this->tooltip ? " <span id=\"tt_" . $this->id . "\" class=\"tooltip\">" . $this->tooltip . "</span>" : "");
if (isset($this->suffix)) {
$ret .= " " . $this->suffix;
}
return $ret;
}
}
?>
|
Java
|
UTF-8
| 804 | 2.265625 | 2 |
[] |
no_license
|
package models;
import java.sql.Date;
public class Comments {
private int commentId;
private int userId;
private int eventId;
public int getCommentId() {
return commentId;
}
public int getUserId() {
return userId;
}
public int getEventId() {
return eventId;
}
public String getComment() {
return comment;
}
public Date getCommentDate() {
return commentDate;
}
public void setCommentId(int commentId) {
this.commentId = commentId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public void setEventId(int eventId) {
this.eventId = eventId;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setCommentDate(Date commentDate) {
this.commentDate = commentDate;
}
private String comment;
private Date commentDate;
}
|
Python
|
UTF-8
| 1,254 | 3.578125 | 4 |
[] |
no_license
|
import matplotlib.pyplot as plt
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]
first_w = 1
w = 1 # a random guess: random value
lr = 0.01 # learning rate
# our model forward pass
def forward(x):
return x * w
# Loss function
def loss(x, y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
# compute gradient
def gradient(x, y): # d_loss/d_w
return 2 * x * (x * w - y)
# Before training
print("predict (before training)", 4, forward(4))
# Training loop
w_list = list()
l_list = list()
for epoch in range(10):
for x_val, y_val in zip(x_data, y_data):
grad = gradient(x_val, y_val)
w = w - lr * grad
print("\tgrad: ", x_val, y_val, round(grad, 2))
l = loss(x_val, y_val)
w_list.append(round(w, 2))
l_list.append(round(l, 2))
print("progress:", epoch, "w=", round(w, 2), "loss=", round(l, 2))
# After training
print("predict (after training)", "4 hours", forward(4))
# epoch-w 그래프 출력
plt.plot(range(10), w_list)
plt.title('w initialized by ' + str(first_w))
plt.ylabel('w')
plt.xlabel('epoch')
plt.show()
# epoch-loss 그래프 출력
plt.plot(range(10), l_list)
plt.title('w initialized by ' + str(first_w))
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()
|
JavaScript
|
UTF-8
| 1,957 | 2.765625 | 3 |
[] |
no_license
|
var React = require('react-native');
var {
AsyncStorage
} = React;
var DEVICE_STORAGE_PREFIX = '@Quotail:';
var _parseString = function(value, type) {
if (value === null) {
return null;
}
else if (type === "object") {
return JSON.parse(value);
}
else if (type === "boolean") {
return value === "true"
}
else if (type === "number") {
return parseFloat(value);
}
else {
return value;
}
};
class LocalStorage {
constructor(){
console.log("LocalStorage construction");
}
get(key, type) {
//console.log("GETTING " + key + " " + type);
//need type to properly parse string.
return AsyncStorage.getItem(DEVICE_STORAGE_PREFIX + key)
.then(value => {
return _parseString(value, type);
});
}
set(key, value) {
//console.log(key + " " + value);
var serializedValue = typeof value === "object" ? JSON.stringify(value) : value.toString();
return AsyncStorage.setItem(DEVICE_STORAGE_PREFIX + key, serializedValue)
}
remove(key){
return AsyncStorage.removeItem(DEVICE_STORAGE_PREFIX + key);
}
multiGet(keyMaps) {
// keyMaps is an array of arrays where each subArray is of the form
// [key, keyType]. keyType is necessary to parse the string returned
// from AsyncStorage
var trueKeys = keyMaps.map((key) => {
return DEVICE_STORAGE_PREFIX + key[0];
});
return AsyncStorage.multiGet(trueKeys)
.then(rawValues => {
var values = rawValues.map(([key, value], i) => {
return [key, _parseString(value, keyMaps[i][1])];
});
return values;
});
}
multiSet(rawKvPairs) {
//need to test
var kvPairs = rawKvPairs.map(([key, value]) => {
var serializedValue = typeof value === "object" ? JSON.stringify(value) : value.toString();
return [DEVICE_STORAGE_PREFIX + key, serializedValue];
});
return AsyncStorage.multiSet(kvPairs)
}
};
module.exports = new LocalStorage();
|
JavaScript
|
UTF-8
| 6,484 | 2.796875 | 3 |
[] |
no_license
|
import React from 'react';
import { useState } from 'react';
// import styles from './UserForm.module.css/';
const UserForm = () => {
const [firstName, setFirstName ] = useState("");
const [firstError, setFirstError] = useState("");
const [lastName, setLastName ] = useState("");
const [lastError, setLastError] = useState("");
const [email, setEmail ] = useState("");
const [emailError, setEmailError ] = useState("");
const [password, setPassword ] = useState("");
const [passwordError, setPasswordError ] = useState("");
const [confirmPassword, setConfirmPassword ] = useState("");
const [confirmError, setConfirmError ] = useState("");
const [hasBeenSubmitted, setHasBeenSubmitted] = useState(false);
const handleFirst = e => {
setFirstName(e.target.value);
if(e.target.value.length < 2) {
setFirstError("First name must be at least two characters");
}else{
setFirstError("");
}
}
const handleLast = e => {
setLastName(e.target.value);
if(e.target.value.length < 2) {
setLastError("Last name must be at least two characters.");
}else{
setLastError("");
}
}
const handleEmail = e => {
setEmail(e.target.value);
if(e.target.value.length < 5){
setEmailError("Email must be at least 5 characters.");
}else{
setEmailError("");
}
}
const handlePassword = e => {
setPassword(e.target.value);
if(e.target.value.length < 8){
setPasswordError("Password must be at least 8 characters.")
}else{
setPasswordError("");
}
}
const handleConfirm = e => {
setConfirmPassword(e.target.value);
if(e.target.value.length !== password.length ){
console.log(e.target.value + " vs " + { password });
setConfirmError("Confirm password must match password. ")
}else{
setConfirmError("");
}
}
const createUser = (e) => {
e.preventDefault();
if(!passwordError && !confirmError && !firstError && !lastError && !emailError){
if(firstName && lastName && email && password && confirmPassword){
const newUser = { firstName, lastName, email, password, confirmPassword };
console.log("Welcome", newUser);
setHasBeenSubmitted( true );
}else{
if(!firstName){
setFirstError("First name is required.");
}
if(!lastName){
setLastError("Last name is required.");
}
if(!email){
setEmailError("Email is required.");
}
if(!password){
setPasswordError("Password is required");
}
if(!confirmPassword){
setConfirmError("Confirm Password is required.");
}
}
}
}
const formMessage = () => {
if( hasBeenSubmitted) {
return "Thanks for your input."
}else{
return "Please submit the form. "
}
}
return (
<div class="container">
<div className="main">
<form onSubmit={ createUser }>
{
hasBeenSubmitted ?
<h3>Thank you for submitting the form!</h3> :
<h3>Welcome, please submit the form.</h3>
}
<div className="input">
<label>First Name:</label>
<input type="text" onChange={ handleFirst } placeholder="Enter First Name" />
{
firstError ?
<p style = {{color: 'red'}}>{ firstError }</p> :
''
}
</div>
<div className="input">
<label>Last Name:</label>
<input type="text" onChange={ handleLast } placeholder="Enter Last Name"/>
{
lastError ?
<p style={{color: 'red'}}>{lastError}</p>:
''
}
</div>
<div className="input">
<label>Email Address:</label>
<input type="text" onChange={ handleEmail } placeholder="Enter Email"/>
{
emailError ?
<p style={{color: 'red'}}>{emailError}</p>:
''
}
</div>
<div className="input">
<label>Password:</label>
<input type="password" onChange={ handlePassword } placeholder="Enter Password"/>
{
passwordError ?
<p style={{color: 'red'}}>{ passwordError }</p>:
''
}
</div>
<div className="input">
<label>Confirm Password:</label>
<input type="password" onChange={ handleConfirm } placeholder="Re-Enter Password"/>
{
confirmError ?
<p style={{color: 'red'}}>{ confirmError }</p>:
''
}
</div>
<button type="submit">Submit Form</button>
</form>
</div>
<div className="results">
</div>
{
hasBeenSubmitted ?
<p>First Name: { firstName }</p> :
<p></p>
}
{
hasBeenSubmitted ?
<p>Last Name: { lastName }</p> :
<p></p>
}
{
hasBeenSubmitted ?
<p>Email: { email }</p> :
<p></p>
}
{
hasBeenSubmitted ?
<p>Password { password }</p> :
<p></p>
}
{
hasBeenSubmitted ?
<p>Confirm Password: { confirmPassword }</p> :
<p></p>
}
</div>
)
}
export default UserForm;
|
C
|
UTF-8
| 17,675 | 3.15625 | 3 |
[] |
no_license
|
//Librerias de C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
//Librerias creadas por nosotros
#include "TDAs/TDA_Mapa/hashmap.h"
#include "TDAs/TDA_Lista/list.h"
#include "Estructuras/structs.h"
#include "grafos.h"
#include "Interfaz/interfaz.h"
//Funcion para mostrar la información dentro del tipoRuta
void mostrarRuta(tipoRuta * rutaCreada)
{
printf(green"\nRuta %s\nRecorrido: ", rutaCreada->nombreRuta);
for(int k = 0; k < rutaCreada->largo; k++)
{
printf(blue"%i ", rutaCreada->arreglo[k]->posicion->identificacion);
}
printf(green"\nDistancia Total Recorrida:"blue" %.2lf\n"reset, rutaCreada->distanciaTotal);
}
//Funcion para leer la informacion del .txt y almacenar en una variable tipoCoordenadas
tipoCoordenadas * lecturaDeInformacion(char * lineaLeida, int id)
{
tipoCoordenadas * nuevaPosicion = crearTipoCoordenadas();
char * fragmento;
//Posicion X
fragmento = strtok(lineaLeida, " ");
nuevaPosicion->coordenadaX = strtol(fragmento, NULL, 10);
//Posicion Y
fragmento = strtok(NULL, "\n");
nuevaPosicion->coordenadaY = strtol(fragmento, NULL, 10);
//ID
nuevaPosicion->identificacion = id;
return nuevaPosicion;
}
//Funcion para validar que la posicion exista (Funcion 2 y 3)
tipoCoordenadas * busquedaPosicion(HashMap * mapaIdentificacion, int identificacion)
{
tipoCoordenadas * posicionBuscada = searchMap(mapaIdentificacion, &identificacion);
if(posicionBuscada == NULL)
{
printf(red"\nNo existe la entrega\n"reset);
return NULL;
}
return posicionBuscada;
}
//Funcion para verficar que en el mapa no se encuentren nombres repetidos
short nombreRepetido(HashMap * mapaRutas, char * nombreRuta)
{
tipoRuta * aux = searchMap(mapaRutas, nombreRuta);
if(aux != NULL)
{
printf(red"\nEl nombre ya se encuentra usado, use otro\n"reset);
return 0;
}
return 1;
}
void importarArchivo(HashMap * mapaIdentificacion)
{
//Se ingresa el nombre del archivo a leer
char nombreArchivo[50];
printf("\nIngrese el nombre del archivo a importar: ");
getchar();
scanf("%49[^\n]s", nombreArchivo);
//Se busca el archivo
FILE * archivo = fopen(nombreArchivo, "r");
if(archivo == NULL)
{
printf(red "\nNo se encontro el archivo!\n" reset);
return;
}
printf(green "\nSe encontro el archivo!\n" reset);
//Se ingresa la cantidad de lineas a leer
int cantLineas;
printf("\nIngrese la cantidad de lineas a leer: ");
scanf("%i", &cantLineas);
//Si se piden 0 lineas, se termina
if(cantLineas == 0)
{
printf(red "\nNo se leyo ninguna linea!\n" reset);
fclose(archivo);
return;
}
char lineaLeida[100];
int cont = 0;
//Lectura de las lineas
while(cont != cantLineas && fgets(lineaLeida, 100, archivo) != NULL)
{
tipoCoordenadas * nuevaPosicion = lecturaDeInformacion(lineaLeida, cont + 1);
insertMap(mapaIdentificacion, &nuevaPosicion->identificacion, nuevaPosicion);
cont++;
}
//Si hay menos lineas de la pedida, se indica el total leido
if(cont < cantLineas)
{
printf(blue"\nSe llego al final del archivo\n");
printf("Se leyeron unicamente %i lineas!\n"reset, cont);
}
printf(green "\nEl archivo se importo correctamente!\n" reset);
fclose(archivo);
}
void distanciaEntregas(HashMap * mapaIdentificacion)
{
int identificacion1, identificacion2;
//Se leen las dos entregas a usar
printf("\nIngrese el numero de identificacion de la entrega 1: ");
scanf("%i", &identificacion1);
tipoCoordenadas * entrega1 = busquedaPosicion(mapaIdentificacion, identificacion1);
if(entrega1 == NULL) return;
printf("\nIngrese el numero de identificacion de la entrega 2: ");
scanf("%i", &identificacion2);
tipoCoordenadas * entrega2 = busquedaPosicion(mapaIdentificacion, identificacion2);
if(entrega2 == NULL) return;
printf(green "\nSe encontraron ambas entregas\n" reset);
//Se calcula la distancia entre las dos entregas
double distanciaEntreEntregas = distanciaDosPuntos(entrega1->coordenadaX, entrega2->coordenadaX, entrega1->coordenadaY, entrega2->coordenadaY);
printf(green "\nLa distancia entre entregas es de %.2lf\n" reset, distanciaEntreEntregas);
}
void entregasCercanas(HashMap *mapaIdentificacion)
{
//PRIMERO ENCONTRAMOS TODO LO QUE VAMOS A OCUPAR, EL ENTREGAAUX SIRVE PARA RECCORER LOS PUNTOS
long long coordenadaX, coordenadaY;
printf("\nIngrese la cordenada X: ");
scanf("%lli",&coordenadaX);
printf("\nIngrese la cordenada Y: ");
scanf("%lli",&coordenadaY);
tipoCoordenadas * posicionAux = firstMap(mapaIdentificacion);
//AHORA DEFINIMOS TODO LO QUE NECESITAREMOS PARA ENCONTRAR LOS MAS CERCANOS
int arreglo[3]; //identificador
double arreglo2[3];//distancia
double distanciaEntregas;
double distanciaAux;
int cont = 0;
double maximo = 0;
int i,k;
/*
AQUI EMPIEZA LA FUNCION PARA ENCONTRAR AL MAS CERCANO
lo que pense al principio es ir encontrando los mas cercanos y guardarlos
en un arreglo, pero como pide mostrar el ID y la distancia, ocupo 2.
quizas se pueda hacer mejor, pero es una idea.
*/
while(posicionAux != NULL)
{
distanciaEntregas = distanciaDosPuntos(coordenadaX, posicionAux->coordenadaX, coordenadaY, posicionAux->coordenadaY);
if(cont != 0)
{
if(cont > 2)
{
//Recorro el arreglo distancia
for(i = 0 ; i < 3 ; i++)
{
if(maximo == arreglo2[i])
{
if(distanciaEntregas < maximo)
{
arreglo[i] = posicionAux->identificacion;
arreglo2[i] = distanciaEntregas;
//Encontrar otro maximo
maximo = 0;
for(k = 0 ; k < 3 ; k++)
if(maximo < arreglo2[k]) maximo = arreglo2[k];
break;
}
}
}
}
else
{
arreglo[cont] = posicionAux->identificacion;
arreglo2[cont] = distanciaEntregas;
if(maximo < distanciaEntregas) maximo = distanciaEntregas;
}
}
else
{
arreglo[0] = posicionAux->identificacion;
arreglo2[0] = distanciaEntregas;
maximo = distanciaEntregas;
}
distanciaAux = distanciaEntregas;
posicionAux = nextMap(mapaIdentificacion);
cont++;
}
//mostrar EL RESULTADO
printf(green"\n\nLas distancias mas cercanas a la posicion ingresada son:\n");
int largo = 3;
//Esto sirve para cuando no hay mas de 5 lugares
if(cont < 3) largo = cont;
for(i = 0 ; i < largo ; i++)
printf("\nID: %d con distancia %.2lf",arreglo[i],arreglo2[i]);
printf("\n"reset);
}
void crearRuta(HashMap * mapaIdentificacion, HashMap * mapaRutas)
{
tipoRuta* nuevaRuta = crearTipoRuta(size(mapaIdentificacion));
//Ingreso de datos
printf("\nIngrese la coordenada X: ");
scanf("%lld",&nuevaRuta->arreglo[0]->posicion->coordenadaX);
printf("\nIngrese la coordenada Y: ");
scanf("%lld",&nuevaRuta->arreglo[0]->posicion->coordenadaY);
nuevaRuta->arreglo[0]->posicion->identificacion = 0;
List* lista = get_adj_nodes(mapaIdentificacion,nuevaRuta);
tipoRuta * auxRuta = firstList(lista);
while(auxRuta != NULL)
{
//Ordenar la entregas a través de la de menor distancia, a la de mayor
int largoArreglo = 0;
auxRuta = firstList(lista);
if(auxRuta == NULL) break;
tipoRuta* orden[size(mapaIdentificacion)];
while(auxRuta != NULL){
orden[largoArreglo] = auxRuta;
auxRuta = nextList(lista);
largoArreglo++;
}
int b;
auxRuta = firstList(lista);
int c;
tipoRuta* temp;
for(b=0 ; b<largoArreglo-1 ; b++){
for(c=b ; c<largoArreglo ; c++){
if(orden[c]->arreglo[orden[b]->largo-1]->distancia < orden[b]->arreglo[orden[b]->largo-1]->distancia){
temp = orden[c];
orden[c] = orden[b];
orden[b] = temp;
}
}
}
//Muestro las entregas que puede elejir el usuario
printf(yellow"\nLista de entregas(Distancia total hasta el momento %.2lf): \n"reset, nuevaRuta->distanciaTotal);
for(b = 0 ; b < largoArreglo ; b++){
printf(blue"%d) "reset, orden[b]->arreglo[orden[b]->largo-1]->posicion->identificacion);
if(orden[b]->arreglo[orden[b]->largo-1]->posicion->identificacion < 10) printf(" ");
printf("Distancia : %.2lf",orden[b]->arreglo[orden[b]->largo-1]->distancia);
printf("\n");
}
printf("\nEl ID que elija es: ");
int opcion;
scanf("%d",&opcion);
//Busco la opcion que ingreso el usuario
auxRuta = firstList(lista);
while(auxRuta != NULL)
{
if(opcion == auxRuta->arreglo[auxRuta->largo-1]->posicion->identificacion) break;
auxRuta = nextList(lista);
}
//Si existe la entrega y no se ha usado, se almacena en el arreglo y avanza
if(auxRuta != NULL)
{
nuevaRuta = auxRuta;
lista = get_adj_nodes(mapaIdentificacion,nuevaRuta);
}
else
{
printf(red"\nNo se encuentra tal entrega\n\n"reset);
auxRuta = firstList(lista);
}
}
//Se ingresa el nombre de la ruta, verificando que no se este usando
do
{
printf("\nIngrese el nombre de la nueva ruta: ");
getchar();
scanf("%19[^\n]s",nuevaRuta->nombreRuta);
convertirEstandar(nuevaRuta->nombreRuta);
} while (nombreRepetido(mapaRutas,nuevaRuta->nombreRuta) != 1);
mostrarRuta(nuevaRuta);
insertMap(mapaRutas,nuevaRuta->nombreRuta,nuevaRuta);
}
void crearRutaAleatoria(HashMap * mapaIdentificacion, HashMap * mapaRutas)
{
//Se crea la ruta que almacenera
tipoRuta* nuevaRuta = crearTipoRuta(size(mapaIdentificacion));
//Se leen las coordenadas de la posicion inicial
printf("\nIngrese la coordenada X: ");
scanf("%lld",&nuevaRuta->arreglo[0]->posicion->coordenadaX);
printf("\nIngrese la coordenada Y: ");
scanf("%lld",&nuevaRuta->arreglo[0]->posicion->coordenadaY);
nuevaRuta->arreglo[0]->posicion->identificacion = 0;
//Se crea la primera lista de nodos adyacentes
List* lista = get_adj_nodes(mapaIdentificacion,nuevaRuta);
tipoRuta * auxRuta = firstList(lista);
while(auxRuta != NULL)
{
//Reviso que hayan posibles nodos dentro de la lista
auxRuta = firstList(lista);
if(auxRuta == NULL) break;
//Genero una posible entrega aleatoria
int opcion = rand() % size(mapaIdentificacion) + 1;
//BUSCO LA OPCION
auxRuta = firstList(lista);
while(auxRuta != NULL)
{
if(opcion == auxRuta->arreglo[auxRuta->largo-1]->posicion->identificacion) break;
auxRuta = nextList(lista);
}
//Si existe la entrega y no se ha usado, se almacena en el arreglo y avanza
if(auxRuta != NULL)
{
nuevaRuta = auxRuta;
lista = get_adj_nodes(mapaIdentificacion,nuevaRuta);
}
else auxRuta = firstList(lista);
}
//Se ingresa el nombre de la ruta, verificando que no se este usando
do
{
printf("\nIngrese el nombre de la nueva ruta: ");
getchar();
scanf("%19[^\n]s",nuevaRuta->nombreRuta);
convertirEstandar(nuevaRuta->nombreRuta);
} while (nombreRepetido(mapaRutas,nuevaRuta->nombreRuta) != 1);
mostrarRuta(nuevaRuta);
insertMap(mapaRutas,nuevaRuta->nombreRuta,nuevaRuta);
}
void mejorarRuta(HashMap * mapaRutas)
{
//Ingreso el nombre de la ruta a buscar
char nombreRuta[20];
printf("\nIngrese el nombre de la ruta: ");
getchar();
scanf("%19[^\n]s", nombreRuta);
convertirEstandar(nombreRuta);
//Si la ruta es optima, se indica que no es necesario hacerle nada
if(strcmp(nombreRuta, "Ruta optima") == 0)
{
printf(blue"\nEs la mejor ruta, no es necesario modificarla\n"reset);
return;
}
//La busco dentro del mapa
tipoRuta * aux = searchMap(mapaRutas, nombreRuta);
if(aux != NULL)
{
//Genero variables auxiliares dentro de la busqueda de posiciones en la ruta
int identificacion1, identificacion2, posicion1 = -1, posicion2 = -1;
printf(green"\nSe encontro la ruta %s\n"reset, nombreRuta);
mostrarRuta(aux);
//Se ingresa que tipo de cambio quiere hacer
char cambio[11];
printf("\nIngrese si quiere un cambio "blue"automatico"reset" o "blue"manual"reset" de posicion: ");
scanf("%10s", cambio);
if(strcmp(cambio, "automatico") == 0)
{
//Se usa la funcion rand, para generar numeros aleatorios
identificacion1 = rand() % aux->largo;
do
{
identificacion2 = rand() % aux->largo;
} while (identificacion1 == identificacion2); //Verificando que sean numeros distintos entre ellos
printf("\nSe eligieron los identificadores %i y %i\n", identificacion1, identificacion2);
}
else if(strcmp(cambio, "manual") == 0)
{
//El usuario ingresa las identificaciones a cambiar
printf("\nElija la identificacion 1: ");
scanf("%i", &identificacion1);
printf("\nElija la identificacion 2: ");
scanf("%i", &identificacion2);
}
else
{
printf(red"\nNo se hara nada\n"reset);
return;
}
//Se busca dentro del arreglo, las identificaciones que se ingresaron
for(int i = 0; i < aux->largo; i++)
{
if(aux->arreglo[i]->posicion->identificacion == identificacion1) posicion1 = i;
if(aux->arreglo[i]->posicion->identificacion == identificacion2) posicion2 = i;
if(posicion1 != -1 && posicion2 != -1) break;
}
if(posicion1 == -1 || posicion2 == -1) //Si ninguna existe termina
{
printf(red"\nNo existe alguna de las 2 entregas ingresadas\n"reset);
return;
}
cambioEntrega(aux, posicion1, posicion2); //Se cambian de posicion
double distanciaActual = aux->distanciaTotal; //Se almacena la distancia original
//Se calcula la distancia total, con las posiciones cambiadas
aux->distanciaTotal = 0;
for(int i = 0; i < aux->largo - 1; i++)
{
aux->distanciaTotal += aux->arreglo[i]->distancia = distanciaDosPuntos(aux->arreglo[i]->posicion->coordenadaX,aux->arreglo[i + 1]->posicion->coordenadaX,aux->arreglo[i]->posicion->coordenadaY,aux->arreglo[i + 1]->posicion->coordenadaY);
}
if(aux->distanciaTotal > distanciaActual) //Si la distancia nueva es peor a la original, se mantiene la ruta original
{
mostrarRuta(aux);
cambioEntrega(aux, posicion1, posicion2);
aux->distanciaTotal = distanciaActual;
printf(red"\nLa ruta actual es mejor, se mantendra\n"reset);
}
else if(aux->distanciaTotal == distanciaActual) //Si es igual, se mantiene la nueva ruta
{
mostrarRuta(aux);
printf(blue"\nLa distancia total son iguales, pero se colocara la nueva ruta\n"reset);
}
else //Si no, se mantiene la nueva ruta
{
printf(green"\nLa nueva ruta es mejor, se cambiara\n");
mostrarRuta(aux);
printf("\n");
}
}
else
{
printf(red"\nNo se ha encontrado la ruta %s\n"reset, nombreRuta);
}
}
void mostrarRutas(HashMap* mapaRutas)
{
int largo = size(mapaRutas);
tipoRuta * ruta = firstMap(mapaRutas);
tipoRuta * arregloRuta[largo];
int i = 0;
//Se ingresa la informacion a un arreglo que almacena los tipos ruta
while(ruta != NULL)
{
arregloRuta[i] = ruta;
ruta = nextMap(mapaRutas);
i++;
}
//Se ordenan de menor a mayor
for (int c = 0 ; c < largo - 1; c++)
{
for (int d = 0 ; d < largo - c - 1; d++)
{
if (arregloRuta[d]->distanciaTotal > arregloRuta[d+1]->distanciaTotal)
{
tipoRuta * swap = arregloRuta[d];
arregloRuta[d] = arregloRuta[d+1];
arregloRuta[d+1] = swap;
}
}
}
//Se muestran todas las rutas
printf(blue"\nLista de rutas creadas:\n"reset);
for(int k = 0; k < largo;k++)
{
mostrarRuta(arregloRuta[k]);
}
}
void mejorRuta(HashMap * mapaIdentificacion, HashMap * mapaRutas){
tipoRuta* nuevaRuta = crearTipoRuta(size(mapaIdentificacion)+1);
//Se inserta la primera posicion en la tipoRuta "nuevaRuta"
printf("\nIngrese la coordenada X: ");
scanf("%lld",&nuevaRuta->arreglo[0]->posicion->coordenadaX);
printf("\nIngrese la coordenada Y: ");
scanf("%lld",&nuevaRuta->arreglo[0]->posicion->coordenadaY);
nuevaRuta->arreglo[0]->posicion->identificacion = 0;
//Se crea la cola para hacer una busqueda por anchura
Queue* cola = CreateQueue();
PushBackQ(cola,nuevaRuta);
int cont = 0;
tipoRuta * eficiente;
while(get_size(cola) != 0){
//El tipoRuta n sera un auxiliar para ver los nodos adjacentes y para
//verificar si es una ruta valida para insertar al arregloRuta
tipoRuta* n= Front(cola);
if(!n) break;
PopFrontQ(cola);
List* adj = get_adj_nodes(mapaIdentificacion,n); //Obtenemos los nodos adjacentes de n
tipoRuta* aux = firstList(adj); //Esta ruta es solamente para insertarlo a la cola
//Se inserta la ruta a la cola
while(aux){
PushBackQ(cola,aux);
aux = nextList(adj);
}
//Si la ruta es valida, se inserta al arregloRuta
if(n->largo == size(mapaIdentificacion) + 1)
{
if(cont == 0) eficiente = n;
else if(eficiente->distanciaTotal > n->distanciaTotal) eficiente = n;
cont++;
}
}
//Se inserta la ruta en el mapa
printf(blue"\nSe debio hacer un total de %i combinaciones\n", cont);
strcpy(eficiente->nombreRuta,"ruta optima");
convertirEstandar(eficiente->nombreRuta);
mostrarRuta(eficiente);
insertMap(mapaRutas,eficiente->nombreRuta,eficiente);
}
void mostrarCoordenadas(HashMap * mapaIdentificacion)
{
tipoCoordenadas * aux = firstMap(mapaIdentificacion);
printf(blue"\nLista de entregas: \n");
while(aux != NULL)
{
printf(green"\nIdentificacion: %i\n", aux->identificacion);
printf("Coordenada X: %lli Coordenada Y: %lli\n"reset, aux->coordenadaX, aux->coordenadaY);
aux = nextMap(mapaIdentificacion);
}
}
|
Python
|
UTF-8
| 450 | 3.296875 | 3 |
[] |
no_license
|
"""
instructions --
- Label the axes. Don't forget that you should always include units in your axis labels. Your yy-axis label is just 'count'. Your xx-axis
label is 'petal length (cm)'. The units are essential!
- Redraw the plot constructed in the above steps using plt.draw(). Like with plt.show(), you do not need to assign this to _.
"""
# Label axes
plt.xlabel('petal length (cm)')
plt.ylabel('count')
# Show histogram
plt.draw()
plt.show()
|
PHP
|
UTF-8
| 4,136 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Controllers\Shop;
use App\Models\Menu;
use App\Models\MenuCate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class MenuController extends BaseController
{
# 菜品首页
public function index(Request $request){
/* // 得到当前登录对象
$user = Auth::user();
//得到当前对象的店铺
$shop = $user->shop;
//得到当前店铺的Id
$sID = $shop->id;
//得到当前店铺中的菜
$menus=Menu::where("shop_id",$sID)->get();//只能用这种方法调用belangsTO*/
$url=$request->query();
//收缩所有数据
$cateId = $request->get("cate_id");
$keyword = $request->get("keyword");
// 得到所有 并有分页
// $query = Menu::orderBy("id");
$query=Menu::where("shop_id",Auth::user()->shop->id);//只能用这种方法调用belangsTO
if ($keyword !==null){
$query->where("goods_name","like","%{$keyword}%");
}
if ($cateId !== null ){
$query ->where("cate_id",$cateId);
}
$menus=$query->paginate(2);
$cates=MenuCate::where("shop_id",Auth::user()->shop->id)->get();
//跳转视图
return view("shop.menu.index",compact("menus","cates","url"));
}
# 添加菜
public function add(Request $request){
// 判断提交方式
if ($request->isMethod("post")) {
// 表单验证
$this->validate($request, [
'goods_name' => "required | min:2 |unique:menu_cates",
'status' => "required |max: 1 |min:1",
'goods_price' => "required",
'description' => "required",
'tips' => "required",
]);
//2. 接收数据
$data=$request->post();
//3. 设置用户ID
$data['shop_id'] = Auth::user()->shop->id;
//dd( $data['shop_id']);
// 添加数据
Menu::create($data);
return redirect()->route("shop.menu.index")->with("success", "添加成功");
}
$cates = MenuCate::where("shop_id", Auth::user()->shop->id)->get();
return view("shop.menu.add",compact("cates"));
}
# 编辑菜
public function edit(Request $request,$id){
// 找到当前对象id
$menu = Menu::find($id);
// 判断提交方式
if ($request->isMethod("post")){
// 表单验证
$this->validate($request,[
'goods_name' => "required | min:2 |unique:menu_cates",
'status' => "required |max: 1 |min:1",
'goods_price' => "required",
'description' => "required",
'tips' => "required",
]);
//2. 接收数据
$data=$request->post();
// 数据府库
if ($menu->update($data)){
return redirect()->intended(route("shop.menu.index"))->with("success", "修改成功");
}
}
$cates = MenuCate::where("shop_id", Auth::user()->shop->id)->get();
return view("shop.menu.edit",compact("cates","menu"));
}
# 删除菜
public function del(Request $request,$id){
//找到当前对象
$menu = Menu::find($id);
//dd($cate->id);
Storage::delete($menu->img);//删除原来的图片
$menu->delete();
return redirect()->route("shop.menu.index")->with("success","删除成功");
}
# 创建 webuploader 图片上传方法
public function upload(Request $request){
//处理上传
//dd($request->file("file"));
$file=$request->file("file");
if ($file){
//上传
$url=$file->store("menu");
/// var_dump($url);
//得到真实地址 加 http的址
//$url=Storage::url($url);
$data['url']=$url;
return $data;
///var_dump($url);
}
}
}
|
Markdown
|
UTF-8
| 1,382 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
Video processing on GCP cloud function using ffmpeg
I have a website where users upload videos which are stored to cloud storage. These videos could be in any format, hence they are sometimes not compatible with certain devices. Eg: webm videos uploaded from a laptop are not compatible with mobile browsers.
We will create a Cloud Function that will process a video as soon as its uploaded to cloud storage.
https://www.encoding.com/html5-video-codec/ this article shows all audio video codecs and their compatibility with different devices. We will use MP4 video code and AAC audio codec.
Create a Cloud Function on GCP and associate it with the bucket that receives user uploaded videos. Make it trigger on event type = Finalize/Create .
Every Cloud Function comes with ffmpeg installed in it. Following is the workflow used in video_processing.py to process a video from CS using ffmpeg:
* Download video (1.webm) from CS (cloud storage) to tmp folder on CF (cloud function). tmp folder is the only folder that gives us write permissions on CF.
* process the video using ffmpeg and save results (1_processed.mp4) in tmp folder.
* upload processed video to CS.
* delete all videos from local tmp folder on CF.
* delete original raw video (1.webm) from CS.
To use video_processing.py file in CF:
```
video_obj = VideoProcessing(video_name)
video_obj.process_video()
```
|
C++
|
UTF-8
| 2,742 | 3.5 | 4 |
[] |
no_license
|
#ifndef UTILITY_SUPPORT_PROGRESSBAR_HPP
#define UTILITY_SUPPORT_PROGRESSBAR_HPP
#include <chrono>
#include <limits>
#include <string>
#include <vector>
namespace utility::support {
/**
* @brief This class displays a progress on a single line in the terminal showing rates and a bar to show progress
*/
class ProgressBar {
public:
/**
* @brief Construct a new Progress Bar object using the provided unit
*
* @param unit the unit to display
*/
ProgressBar(std::string unit = "iteration");
/**
* @brief Updates the progress bar using the new values for current and total
*
* @param current the current number of units that have been completed
* @param total the total number of units to be completed
* @param status a string to display besides the progress bar
*/
void update(const double& current, const double& total, const std::string& status = "");
/**
* @brief Updates the progress bar using the new values for current and total with types that are castable to
* double
*
* @tparam T a type that is castable to double to be used with update(double, double)
* @tparam U a type that is castable to double to be used with update(double, double)
*
* @param current the current number of units that have been completed
* @param total the total number of units to be completed
* @param status a string to display beside the progress bar
*/
template <typename T, typename U>
void update(const T& current, const U& total, const std::string& status = "") {
update(double(current), double(total), status);
}
private:
/// The previous value that was passed in for current
double previous{0};
/// The current calculated rate in units per second
double rate{std::numeric_limits<double>::quiet_NaN()};
/// The unit to display rates and progress in
std::string unit;
/// The start time for this progress bar to use when calculating rates
std::chrono::steady_clock::time_point start_time;
/// The last time the update function was called so we can rate limit updates when they are too frequent
std::chrono::steady_clock::time_point last_update;
/// The number of updates we have done in the last second so we can handle burst updates
double updates_per_second{0};
/// The characters used to make up the progress bar
std::vector<std::string> bars;
};
} // namespace utility::support
#endif // UTILITY_SUPPORT_PROGRESSBAR_HPP
|
JavaScript
|
UTF-8
| 1,205 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
// doc const aHandle = await frame.evaluateHandle(() => document.body);
beforeAll(async () => {
await page.goto(`http://localhost:${PORT}`);
})
test('all elements in this example should be available to test', async () => {
const expected = [
"heading",
"paragraph",
"light-theme",
"dark-theme",
"scoped-footer",
"theme-is-text",
];
const foundElsIds = []
for (const id of expected) {
try {
const elId = await (
await page.waitForSelector(`#${id}`, { timeout: 100 })
)
.evaluate(self => self.id);
// push all found
foundElsIds.push(elId);
} catch (err) {
throw err;
}
}
expect((foundElsIds.sort())).toEqual((expected.sort()));
});
test('proves a variable has been set before javascript loads', async () => {
await page.waitForLoadState('domcontentloaded');
// Get all css variables on html :root
const customProperties = new Map(await page.evaluate(() =>
Array.from(document.documentElement.computedStyleMap().entries(), ([key, value]) =>
key.startsWith('--') ? [key, Object.values(value[0])[0].trim()] : null ).filter(Boolean)))
expect(customProperties.get('--theme')).toBe('light')
})
|
Python
|
UTF-8
| 1,933 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
#!/opt/local/bin/python
"""
Program that shows the program on the right and its abstract syntax tree (ast) on the left.
"""
from __future__ import print_function
import sys, argparse, logging
import astviewer
from PySide import QtGui
logger = logging.getLogger(__name__)
def main():
""" Main program to test stand alone
"""
app = QtGui.QApplication(sys.argv) # to allow for Qt command line arguments
remaining_argv = app.arguments()
parser = argparse.ArgumentParser(description='Python abstract syntax tree viewer')
parser.add_argument(dest='file_name', help='Python input file', nargs='?')
parser.add_argument('-m', '--mode', dest='mode', default = 'exec',
choices = ('exec', 'eval', 'single'),
help = """The mode argument specifies what kind of code must be compiled;
it can be 'exec' if source consists of a sequence of statements,
'eval' if it consists of a single expression, or 'single' if it
consists of a single interactive statement (in the latter case,
expression statements that evaluate to something other than None
will be printed). """)
parser.add_argument('-l', '--log-level', dest='log_level', default = 'warn',
choices = ('debug', 'info', 'warn', 'error', 'critical'),
help = "Log level. Only log messages with a level higher or equal than this "
"will be printed. Default: 'warn'")
args = parser.parse_args(args = remaining_argv[1:])
astviewer.logging_basic_config(args.log_level.upper())
logger.info('Started {}'.format(astviewer.PROGRAM_NAME))
exit_code = astviewer.view(file_name = args.file_name, mode = args.mode,
width=1100, height=800)
logging.info('Done {}'.format(astviewer.PROGRAM_NAME))
sys.exit(exit_code)
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 535 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
from imlazy import import_or_install
click = import_or_install('click')
docker = import_or_install('docker')
@click.command()
def dockerlist():
"""
dockerlist
Gets a list of running docker containers and presents them.
"""
client = docker.from_env()
containers = [c.name for c in client.containers.list()]
if containers:
for c in containers:
print(c)
else:
print("No running containers were found.")
if __name__ == '__main__':
dockerlist()
|
C++
|
UTF-8
| 780 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include "PhysicalAction.h"
namespace ample::game::stateMachine::actions
{
class PhysicalApplyAngularImpAction : public PhysicalAction
{
public:
PhysicalApplyAngularImpAction(const std::string &name,
const std::vector<std::string> &bodyNames,
float impulse,
bool wake);
PhysicalApplyAngularImpAction(const filing::JsonIO &input);
float getImpulse() const noexcept;
bool getWake() const noexcept;
void setImpulse(float impulse) noexcept;
void setWake(bool wake) noexcept;
std::string dump() override;
void onActive() override;
private:
float _impulse;
bool _wake;
};
} // namespace ample::game::stateMachine::actions
|
Python
|
UTF-8
| 114 | 3.609375 | 4 |
[] |
no_license
|
#This is an exercise on practicing print formatting
today = "Today is a {}".format('HORRIBLE day')
print(today)
|
Markdown
|
UTF-8
| 4,509 | 3.3125 | 3 |
[] |
no_license
|
<!--META--
author: Sean K Smith
created: 2019-05-17T01:26:37Z
edited: 2019-05-17T01:26:37Z
title: Active Learning
subtitle: becomming a better programmer when osmosis is not enough
tags:
- learning
--END-->
Programming did not come naturally to me. In high-school I hung on to the kid nearest to me who seemed to have a good idea of what he was doing and copied his work. I knew I wanted to program (I wanted to make games) - I enjoyed the *idea* of it - but I didn't understand what it took to get good at it.
<!--BREAK-->
In college I made friends with some really talented programmers (many of whom I am still friends with to this day). I leaned on them through those years and started gaining a genuine interest for the skill during those years. Much of it continued to be daunting to me though. I felt like I was constantly behind. Barely grasping "simple" concepts like the difference between an object and a class, and the idea that a String (in Java) was an object and not a primitive (or what that difference even really meant).
I *wanted* to be a programmer but wasn't willing to put in the effort to become one. Or maybe a better way of putting it would be to say that I didn't realize what I needed to do to become a better one. It seemed to me that by going through the classes, I would just magically pick up the knowledge I needed, as if through osmosis. I'm not stupid (I think), but programming is just not simple. It's not something you can master by sitting idle through a lecture lapping up what bits of information you get from the speaker.
It wasn't until a few years later that I really learned the lesson about... learning. This game came out called Starcraft II - and I loved it. And like programming, I was *really* bad at it (at first). I loved how cold it was in how the competitive ladder measured your skill. How you could just watch as your raw skill slowly grew. This wasn't some RPG where you could just dump time in and find that you magically got better through artificially inflated statistics - you had to actively learn. That was the key, the thing that changed me. In Starcraft, if I wanted to improve I couldn't mindlessly play games - I had to engage *actively* in the learning process. I had to ask the hard question - "Why did I lose that match?"
My attitude toward learning shifted drastically. While I always loved programming, my progress was always slow. I started toying around with code more. I started picking up books and rather than just reading the pages, I really forced myself to work through the examples. My skill improved significantly (measured by my performance in interviews). The better I got, the more I loved it.
A couple of years after that I came across the book [The Practicing Mind](https://www.amazon.com/gp/product/1608680908/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1) by Thomas M. Sterner. His attitude toward learning can be summed up like this. You can try to learn to golf by going out and playing gold over and over. You will improve, but it will be slower. Instead a much faster (and more enjoyable way) to learn is by picking a particular part of your game that is weak, and focusing on that. Staying in the moment and enjoying the process of learning, rather than getting hung up on the end result. He has a lot of really great points that have honestly shifted how I view life and I can't recommend the book enough.
Since reading that book I've really focused my energy on what is both my passion and my profression - programming. I've worked with quite a few programmers now in the past decade. Many of them do the job, turn off their computer, and go home. That is a *completely reasonable thing to do*. **However**, many of them are still using old technologies, or have the same old bad habits built over decades of just getting the job done. While I'm not a great programmer, I sure am interested in continuing to get better. So, when the passion is there, I fiddle around with projects at home, I read books, and I listen to podcasts. When I'm not as interested in working on programming in my own time I focus more at work. I ask myself the questions: "Is this the best solution? What is the best practice here?" I keep a few popular programming books close at hand (The Pragmatic Programmer, Clean Code, and Effective Java) for reassurance.
Hopefully these practices will keep my skills from getting stagnant. Hopefully in my short time on this world I might approach something resembling a master. That would be pretty cool.
|
Ruby
|
UTF-8
| 780 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
# See more interesting examples in examples.rb
class MyApp
def call(env)
status_code = 200 # i.e. 'HTTP 200 OK'
headers = {}
headers["Content-Type"] = "text/plain"
lines_of_body = [
"Hi there. You're trying to retrieve the following page: ",
env['PATH_INFO'].inspect,
"\n",
"With some query string parameters: ",
env['QUERY_STRING'].inspect,
"\n", # end with a line break character. It's just prettier.
]
# Then we put it all together:
[status_code, headers, lines_of_body]
end
end
# Here Rack takes over for us. It'll listen on a socket and every time a
# request comes in it'll execute the `call` method on the instance of MyApp,
# passing in the current HTTP request in the form of a hash.
run MyApp.new
|
Markdown
|
UTF-8
| 8,119 | 2.96875 | 3 |
[] |
no_license
|
Power Cycle Script
=======================
Purpose
-------
The purpose of the Power Cycle script is to provide an automated way for
clients to power cycle VM’s.
The script is intended to be used with a scheduled job and configured to power
off and on at set times each day.
Pre-Requisites
--------------
The following are required in order for the script to work.
- A Windows 2008 R2 server or later
- PowerShell version 5 or later (visit this link for instructions:
<https://docs.microsoft.com/en-us/powershell/scripting/install/installing-windows-powershell?view=powershell-6>
)
- The server has access to the vCloud servers.
- An account with the “Organisation Administrator” role to the organisation
containing the VM’s
- The latest version of VMWare PowerCLI ensuring that the vCloud plugins are
installed.
- An SMTP server accessible from the server the script is running on
- An account on the windows server with the ability to create scheduled tasks,
execute scripts and use the SMTP server. Note this can be the same as the
service account to connect to vCloud but this isn’t a requirement.
- If the graceful shutdown option is used the VM must have VMWare tools
running on the VM.
Deployment
----------
The following section outlines deploying the script
### Download
The latest version of the script and required components can be downloaded from
<https://github.com/gtowsey/VCD>
Click on the clone or download button and download to zip
Once downloaded extract the contents to a folder.
### Encrypt Password
Right click the GenerateEncryptedPassword.ps1 file form the extracted folder and
click run with PowerShell
Once the script starts, it will ask for the user’s credentials.
IMPORTANT!!!
Note that these credentials are for the user or service account that will be
connecting to vCloud director. Note that the encrypted file can only be
de-crypted by the user that encrypts it. This is important as whatever account
encrypts the password must be used to execute the script. In the event that a
service account will be used, that service account must log in to encrypt the
password.
A new file will appear in the folder called password.txt. This is encrypted and
is used to connect to the vCloud servers.
### Update VM List
In the unzipped folder is a file called vmList.csv. This file contains the list
of VM’s that will be turned on or turned off. Update this list to contain the
VM’s that need to be power cycled.
The GracefulShutdown option dictates whether the VM should be hard powered off
(i.e. the equivalent of killing the power to the VM) or shutdown gracefully
(i.e. by issuing a shutdown command at the OS level)
IMPORTANT!!!
The script will work with only one location and one organisation at a time. If
multiple organisations are required, the folder can be copied to a new location
and the VM list and script updated to cater for this.
Ensure the file looks like this at the end of any modification
### Update Configuration Settings
Each script has a settings section that needs to be updated before the script is
run. This is located at the top of the script.
The variables that need to be updated are listed below:
| Variable | Description |
|-----------------------|----------------------------------------------------------------|
| \$username | The username of the account to connect to vCloud Director with |
| \$vCloud_server_name | The server address to connect to |
| \$vCloud_organisation | The organisation to connect to |
| \$smtprelay | The ip address or dns name of the smtp server |
| \$smtpfrom | The sender of any email addresses |
| \$smtpto | The receiver of the email address |
| \$smtpsubject | The subject of the email address |
### Testing
At this point, the script is ready to be ran.
In order to confirm all settings are working either run against a test VM in
shared cloud or alternatively perform the opposite action against a VM (if a VM
is turned off attempt to turn off, if its turned on attempt to turn on.)
If the second option is completed an email should be sent outlining that the
action cannot be performed due to the state of the VM.
### Setting up the scheduled task
Open the task scheduler and click on create task.
Click on change user to choose the account that is going to run the script. Note
this must be the account that encrypted the vCloud director credentials.
Ensure the run whether user is logged on or not and run with highest privileges
is ticked.
Click on the actions tab and click on new
In the Program/script box enter "PowerShell."
In the Add arguments (optional) box enter the value .\\powerOn.ps1 for the
powerOn scheduled task and powerOff for the power off task.
Then, in the Start in (optional) box, add the location of the folder that
contains your PowerShell script. In this example, the script is in a folder
C:\\Users\\gtowsey\\vCloud\\CustomerExamples
On the triggers page we set up the schedule of the script.
For a job configured to run at 8am Monday to Friday the below settings will
work.
Finally give the script a name and click ok.
The job can now be run either manually or will be configured at 8am each day.
Repeat the steps to configure the power off script.
If multiple organisations are required
Troubleshooting
---------------
In the event of an error the script is designed to both add to the log file
found in the script folder as well as send an email to the configured end user.
In the event that the email server is unable to be found or cannot send emails,
only the log will contain an error.
### SMTP server not found
If the smtp server is not found the logs will contain a record similar to the
below
Ensure that the smtp server is reachable from the script execution server
### Log file cannot be created
An email will be received saying “unable to create log file”
Ensure the account executing the script has write access to the folder it’s
being executed from.
### CSV cannot be imported
If the csv containing the VM’s cannot be imported an email and a log record will
be created saying “unable to import csv”
Ensure the csv exists in the folder and is in the correct csv format
### vCloud Module is not installed
If the vCloud module is not installed on the local VM an email and log record
will be created with the following error “unable to import vCloud module.”
Ensure the VMWare PowerCLI module is installed and the vCloud plugins have been
included.
### Password file missing
In the event the password file is missing an error will be returned stating
“unable to open password file”
Ensure the password.txt file exits in the folder. If it’s not found use the
GenerateEncryptedPassword.ps1 to regenerate.
### Unable to connect to vCloud Director
In the event that the vCloud server cannot be contacted, an error message will
be generated stating “organisation or credentials incorrect”
Ensure the vCloud server name is correct in the settings of the script and is
reachable from the server. Also, ensure the account provided can log in to the
vCloud server.
### Unable to find VM
In the event a VM cannot be found in the organisation. The script will continue
to action all other requests but take note of the failed VM.
In this case an email will be received similar to the below example:
To resolve ensure the VM belongs in the organisation and the user account.
### VM is not running
In the event a VM is currently turned off and the script attempts to turn the VM
of again the following error will be created.
### VMWare Tools not running
In the event the garcefulShutdown option is used the VM must have VMWare tools
running on the VM.
If tools is not running, the VM will not be shut down and the following error
will be generated.
|
Ruby
|
UTF-8
| 910 | 3.28125 | 3 |
[] |
no_license
|
latest = nil
while true
# seed
if latest.nil?
latest = '0'
end
a = latest.split("")
incrementor = a.last
carry_over = false
# deal with incrementor
if incrementor == '9'
incrementor = 'a'
elsif incrementor == 'z'
incrementor = '0'
carry_over = true
else
incrementor.next!
end
# deal with the rest
a.pop
rest = []
unless a.nil?
a.reverse.each do |char|
if char == '9' && carry_over
result = 'a'
carry_over = false
elsif char == 'z' && carry_over
result = '0'
elsif carry_over
result = char.next
carry_over = false
else
result = char
end
rest << result
end
end
if carry_over
rest << '0'
end
p latest = rest.reverse.join + incrementor
gets
end
# thoughts
=begin
changes occur when char is 9 or z
9 -> a, no carry over
z -> 0, carry over 1
=end
|
C++
|
UTF-8
| 1,648 | 3.09375 | 3 |
[] |
no_license
|
//
// Created by yuwenyong.vincent on 2019-01-13.
//
#include "net4cxx/net4cxx.h"
using namespace net4cxx;
class Person {
public:
Person() = default;
Person(std::string name, int age, std::string gender, double height)
: _name(std::move(name)), _age(age), _gender(std::move(gender)), _height(height) {
}
void display() const {
std::cout << _name << ":" << _age << ":" << _gender << ":" << _height << std::endl;
}
template<typename ArchiveT>
void serialize(ArchiveT &archive) {
archive & _name & _age & _gender & _height;
}
protected:
std::string _name;
int _age;
std::string _gender;
double _height{0.0};
};
class ArchiveTest: public Bootstrapper {
public:
using Bootstrapper::Bootstrapper;
void onRun() override {
Person p1{"testName", 21, "M", 167.5};
Person p2;
Archive<> a1;
Archive<ByteOrderNetwork> a2;
Archive<ByteOrderBigEndian> a3;
Archive<ByteOrderLittleEndian> a4;
std::cout << "Archive test start" << std::endl;
p1.display();
std::cout << "Archive Native" << std::endl;
a1 << p1;
a1 >> p2;
p2.display();
std::cout << "Archive Network" << std::endl;
a2 << p1;
a2 >> p2;
p2.display();
std::cout << "Archive BE" << std::endl;
a3 << p1;
a3 >> p2;
p2.display();
std::cout << "Archive LE" << std::endl;
a4 << p1;
a4 >> p2;
p2.display();
}
};
int main(int argc, char **argv) {
ArchiveTest app{false};
app.run(argc, argv);
return 0;
}
|
Markdown
|
UTF-8
| 8,981 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
---
layout: post
title: "记一次vpc迁移"
subtitle: "VPC , Docker network ?"
date: 2018-07-23
author: "GiraffeTree"
header-img: "img/post-bg-js-version.jpg"
tags:
- Docker
- 后端
- 日常
---
# 记一次vpc迁移
## 关键词
VPC , Docker network
## 起因
公司新买了几台服务器当海外服,都是在同一个VPC下的,但因为之前还有一台服务器运行在阿里云的经典网络下,并不在这个VPC内,所以我想把服务器都迁过来,好管理,搭建服务也比较方便.
以防万一,在预约了经典网络迁移到专有网络之前, 我详细地询问了阿里云的工作人员相关迁移事宜,包括停机时间,RDS 数据库访问,vpc迁移网络变化等等一系列问题,结果大概就是停机15分钟左右,RDS 可以正常访问,不会影响该vpc中其他的主机等,也大致看了相关的文档,了解了一下有什么风险点.
## 迁移
在确保没什么问题之后,我就预约了迁移.大概等了20分钟后,登录! 重新启动了docker server,启动web服务器,在此之前仿佛一切都很顺利.
查看日志,在运行到```Hibernate Commons Annotations```的时候突然卡着不动了,我仿佛感觉到一个不详的预兆,没过几秒程序就报错了.
```java
Caused by: java.net.UnknownHostException: xxxx-xxxx.mysql.rds.aliyuncs.com
at java.net.InetAddress.getAllByName0(InetAddress.java:1280)
at java.net.InetAddress.getAllByName(InetAddress.java:1192)
at java.net.InetAddress.getAllByName(InetAddress.java:1126)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 67 more
```
## UnknownHostException
看到 ```UnknownHostException``` 我的第一个反应就是地址写错了?但又想了想迁移之前明明运行的好好的?带着疑惑,我还是检查了RDS的地址是否正确.嗯,仔细地对照了控制台上的RDS地址,确实没错.
然后又检查了一遍 RDS 的白名单,对照了服务器的公网/内网ip,没错呀.虽然都没错,但是我发现RDS 实例还是经典网络,并不是使用 VPC 的网络.带着疑惑,我检查了一遍以后,决定将 RDS 也迁移到这个 VPC 中来.
RDS 迁移的过程很顺利,并且提示我保留了原来的经典网络地址.在迁移之后,将地址改为迁移之后的内网地址,重新打包上传了代码.重启服务! 结果仍然是 ```UnknownHostException``` .我仍然没死心,在本地准备连 RDS 迁移后的外网地址试试, 原本以为会失败,结果没想到成功了.
我越来越不明白了.
重新上传了这份代码,放到服务器上,重启服务.程序运行到一半卡住的时候,我就感觉到这次又失败了.果然一样的 ```UnknownHostException```
## 难道是域名解析的问题?
在网上搜了下 ```UnknownHostException``` ,但是没有什么结果.
想了一会儿,又测试了几次.原有的经典网络地址也没法访问,没法子,就下了个阿里云工单,问问是不是迁移时出了什么问题.
阿里云的工程师让我直接用 迁移后RDS 的ip试试, 我在服务器 ping 了RDS的地址,ping通了, 找到了这个域名的ip .然后重新改了数据库的地址,上传了代码,重启服务.
```java
Caused by: java.net.NoRouteToHostException: No route to host (Host unreachable)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 67 more
```
第一次失败!
然后我又尝试在 docker 启动容器时指定 dns 地址
```console
docker run -d --dns 8.8.8.8 -p 8000:8080 -name [容器名] -v xxx:xxx [镜像名]
```
启动之后,还是连接不上!
看来,也不是域名解析的问题.
## 折中的办法
在上面的测试中,我开始意识到容器内部的网络好像是出了什么问题.
我继续测试了宿主机(也就是这台迁移的服务器)
```console
telnet [rds地址] 3306
ping [vpc中其他主机 ip]
```
连接都成功了
接着,进入了容器的内部:
```console
docker exec -it [容器名] /bin/bash
```
继续ping了vpc中其他主机
```console
ping [vpc中其他主机 ip]
```
连接失败,外网也是如此.看来问题就出在这里了.
在网上搜了搜,docker 容器内使用宿主机网络, 看了半天好像没有什么和我的情况一样的.
为了了解地更深一点,我又大致看了看 docker 的网络管理, 默认docker 使用bridge驱动的. 我想了想,是不是这部分出了问题.于是重新启动了一个镜像.
```console
docker run --net=host -v xxx:xxx -name xxx [镜像名]
```
启动成功了,数据库也连上了,也明确了确实是```docker network bridge驱动```的问题,事情就这样解决了么?
## 尝试重置
查看了下 docker server 的版本是```1.12```,心想难道是 docker 版本过低了?
在备份了服务器的 docker 日志之后,我决定更新下 docker.
更新重启之后,然而事实还是,使用 ```docker network bridge``` 在容器内部仍然连不上宿主机的网络.(这里并没有使用```--net=host```)
在 google 上搜索了 ```docker bridge network not working```之后, 我极不情愿的使用了[StackOverFlow.com: My docker container has no internet](https://stackoverflow.com/questions/20430371/my-docker-container-has-no-internet) 中的方法 -- 重置docker网络. 一来我对这些命令并不是特别熟悉,二来重装docker之后没有成功,让我失去了对这个方法的信心
命令如下
```
pkill docker
iptables -t nat -F
ifconfig docker0 down
brctl delbr docker0
sudo systemctl start docker
```
查了点资料,具体解释如下
#### iptables
```
iptables -t nat -F
```
简单的来讲就是: 删除 nat(Network Address Translation) 中所有规则
**注 意 :** 其实 ```iptables -F -X ``` 这些命令十分危险,谨慎使用 ! 连远程主机的时候,一不小心就把自己也关在外面了,然后再也进不来了...
#### ifconfig
```
ifconfig docker0 down
```
关闭名称为 docker0 的网桥
```docker0```到底是什么呢 ? 它 docker server 在启动时,会创建一个 ```docker0``` 的网桥,默认所有的容器都通过它访问宿主机的网络
#### brctl
需要先安装```yum install bridge-utils```
```
brctl delbr docker0
```
brctl 是一个管理网桥的工具,这个命令的意思是: 删除 docker 默认的网桥
#### 重启docker
最后重新启动 docker server, 启动 web 服务容器,不幸的是, 容器内部依然无法和外部通讯.
## 最终解决
尝试了各种方法无法成功的我 , 确实有点心灰意冷.
翻着网页上的解决方案 , 翻着翻着, 开始想到这个故事的源头 -- 没错,就是 VPC .
会不会是 **VPC 的IP地址段和 docker 内部的IP地址段冲突了呢?**
查看了 VPC 的 IP 地址,又看了看 ```docker0```的ip,果然 冲突了!
问题源头找到了, 那就好办了.
修改了 ```/etc/docker/daemon.josn``` , 自定义了```docker0``` 默认 ip 段
```
"bip":"170.26.0.1/24"
```
重启了 docker server ,启动 web 服务器 , RDS 连接正常!
终于问题解决!
## 对于折中方法的思考
虽然使用 host 驱动(docker network 有 默认的bridge驱动,host驱动,overlay驱动,null驱动等)解决了上面容器中访问不了网络的问题,但是和宿主机使用了同一个网络栈,但实际没有进行 ```network namespace ```隔离,缺乏安全性,容器之间容易相互干扰.
## 反思
这次的事情也给我提了个醒,迁移之中出现问题是相对大概率的事件,一来我没有好好准备,二来对 docker 内部的原理并没有真正的了解,导致了这个问题花了我相当长的时间才解决这个问题.
说不多说,继续加油吧,毕竟还有那么多血小板等着我养呢 Σ(  ̄□ ̄||)
## 讨论
最后,对这篇文章有疑问的欢迎来 [Github: 记一次vpc迁移 ](https://github.com/giraffe-tree/giraffe-tree.github.io/issues/1) 讨论哦
## 参考
[Docker : docker 官网介绍 network bridge](https://docs.docker.com/network/bridge/)
[StackOverFlow : My docker container has no internet](https://stackoverflow.com/questions/20430371/my-docker-container-has-no-internet)
[StackOverFlow : How to change Docker IP address on Centos 7?](https://stackoverflow.com/questions/43669179/how-to-change-docker-ip-address-on-centos-7)
## 转载事宜
请在转载文章显著位置给出原文出处:
**记一次vpc迁移** https://github.com/giraffe-tree/giraffe-tree.github.io/issues/1
|
C++
|
UTF-8
| 3,451 | 2.796875 | 3 |
[] |
no_license
|
/*
* record.cpp
*
* Created on: Jun 4, 2018
* Author: mchen
*/
#include "flag.h"
#include "record.h"
#include "util.h"
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
// Public ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
Record::Record(const std::string &s_rec) : s_rec_(s_rec)
{
// std::cout << s_rec_ << std::endl;
isCtrlRec_ = false;
flag_ = 0;
s_addr_ = 0;
s_val_ = 0;
d_addr_ = 0;
d_val_ = 0;
bytesz_ = 0;
ts_ = 0;
group_mark_ = 0;
parse_record();
}
bool Record::isCtrlRecord()
{
return isCtrlRec_;
}
void Record::print_record()
{
cout << "flag:0x" << hex << (unsigned)flag_
<< " saddr:0x" << s_addr_ << " sval:" << s_val_
<< " daddr:0x" << d_addr_ << " dval:" << d_val_
<< " bytesz:" << dec << (unsigned)bytesz_ << " ts:" << ts_
<< " group mark:" << (unsigned)group_mark_ << endl;
}
// Private ----- ----- ----- ----- ----- ----- ----- ----- ----- -----
void Record::parse_record()
{
vector<string> recs;
Util::split_str(s_rec_.c_str(), '\t', recs);
// for(auto it = recs.begin(); it != recs.end(); ++it)
// cout << *it << " ";
// cout << endl;
string &flag = recs[0];
if(Flag::isCtrlMark(flag) ) { // control records, skip parsing
// cout << "Control: ";
// for(auto it = recs.begin(); it != recs.end(); ++it)
// cout << *it << " ";
// cout << endl;
isCtrlRec_ = true;
}
else { // data records
// cout << "Data: ";
// for(auto it = recs.begin(); it != recs.end(); ++it)
// cout << *it << " ";
// cout << endl;
if(Flag::isRecordMark(flag, TCG_QEMU_LD) ) {
// parse_mem_load(recs);
}
else if(Flag::isRecordMark(flag, TCG_QEMU_LD_POINTER) ||
Flag::isRecordMark(flag, TCG_QEMU_ST) ||
Flag::isRecordMark(flag, TCG_QEMU_ST_POINTER) ) {
parse_mem(recs);
}
else {
parse_non_mem(recs);
}
}
}
// Parses the memory load record. The specialty is it might contain a group mark,
// indicates it's split into 1 byte from 4-byte record.
void Record::parse_mem_load(std::vector<std::string> &recs)
{
flag_ = strtoul(recs[0].c_str(), NULL, 16);
s_addr_ = strtoul(recs[1].c_str(), NULL, 16);
s_val_ = strtoul(recs[2].c_str(), NULL, 16);
d_addr_ = strtoul(recs[4].c_str(), NULL, 16);
d_val_ = strtoul(recs[5].c_str(), NULL, 16);
bytesz_ = strtoul(recs[6].c_str(), NULL, 16) / 8;
u32 ts = strtoul(recs[8].c_str(), NULL, 10);
if(ts > 0){ // contains group mark
group_mark_ = (u8)strtoul(recs[7].c_str(), NULL, 10);
ts_ = ts;
}
else
ts_ = strtoul(recs[7].c_str(), NULL, 10);
}
void Record::parse_mem(std::vector<std::string> &recs)
{
flag_ = strtoul(recs[0].c_str(), NULL, 16);
s_addr_ = strtoul(recs[1].c_str(), NULL, 16);
s_val_ = strtoul(recs[2].c_str(), NULL, 16);
d_addr_ = strtoul(recs[4].c_str(), NULL, 16);
d_val_ = strtoul(recs[5].c_str(), NULL, 16);
bytesz_ = strtoul(recs[6].c_str(), NULL, 16) / 8;
ts_ = strtoul(recs[7].c_str(), NULL, 10);
}
void Record::parse_non_mem(std::vector<std::string> &recs)
{
flag_ = strtoul(recs[0].c_str(), NULL, 16);
s_addr_ = strtoul(recs[1].c_str(), NULL, 16);
s_val_ = strtoul(recs[2].c_str(), NULL, 16);
d_addr_ = strtoul(recs[4].c_str(), NULL, 16);
d_val_ = strtoul(recs[5].c_str(), NULL, 16);
bytesz_ = 0;
ts_ = strtoul(recs[6].c_str(), NULL, 10);
}
|
SQL
|
UTF-8
| 211 | 3.28125 | 3 |
[
"Apache-2.0"
] |
permissive
|
-- 5. Select the warehouse code and the average value of the boxes in each warehouse.
--
select warehouse,avg(value) as Average_value_of_boxes_per_warehouse from boxes group by warehouse order by warehouse asc;
|
Python
|
UTF-8
| 432 | 3.125 | 3 |
[] |
no_license
|
def find_it(seq):
my_dict = {}
num = 0
for i in seq:
my_dict[i] = 0
for i in seq:
try:
while seq[num] == i:
my_dict[i] += 1
if num <= len(seq)-1:
num += 1
else:
break
except IndexError:
pass
for i in my_dict:
if my_dict[i] % 2 != 0:
return i
|
Java
|
UTF-8
| 1,720 | 2.828125 | 3 |
[] |
no_license
|
package com.jing.imageloader.request;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* author: 陈永镜 .
* date: 2017/6/21 .
* email: jing20071201@qq.com
* <p>
* introduce:
*/
public class RequestQueue {
/**
* 阻塞式队列
* 多线程共享
* 生产效率和消费效率相差太远
* disPlayImage()
* 使用优先级队列
*/
private BlockingQueue<BitmapRequest> mReqeustQueue = new PriorityBlockingQueue<>();
/**
* 转发器的数量
*/
private int threadCount;
//线程安全的编号
private AtomicInteger i = new AtomicInteger(0);
private RequestDispatcher[] mDispatcher;
public RequestQueue(int threadCount) {
this.threadCount = threadCount;
}
/**
* 添加请求对象
*
* @param request
*/
public void addRequest(BitmapRequest request) {
//判断请求队列是否包含该请求
if (!mReqeustQueue.contains(request)) {
//给请求进行编号
request.setSerialNo(i.incrementAndGet());
mReqeustQueue.add(request);
}
}
/**
* 开始请求
*/
public void start() {
stop();
startDispatcher();
}
private void startDispatcher() {
mDispatcher = new RequestDispatcher[threadCount];
for (int i = 0; i < threadCount; i++) {
RequestDispatcher dispatcher = new RequestDispatcher(mReqeustQueue);
mDispatcher[i] = dispatcher;
mDispatcher[i].start();
}
}
/**
* 停止请求
*/
public void stop() {
}
}
|
Java
|
UTF-8
| 12,085 | 1.507813 | 2 |
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.zxing.client.android.book;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.google.zxing.client.android.HttpHelper;
import com.google.zxing.client.android.LocaleManager;
import com.google.zxing.client.android.common.executor.AsyncTaskExecInterface;
import com.google.zxing.client.android.common.executor.AsyncTaskExecManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// Referenced classes of package com.google.zxing.client.android.book:
// SearchBookContentsResult, BrowseBookListener, SearchBookContentsAdapter
public final class SearchBookContentsActivity extends Activity
{
private final class NetworkTask extends AsyncTask
{
final SearchBookContentsActivity this$0;
private void handleSearchResults(JSONObject jsonobject)
{
int j;
j = jsonobject.getInt("number_of_results");
headerView.setText((new StringBuilder(String.valueOf(getString(com.google.zxing.client.android.R.string.msg_sbc_results)))).append(" : ").append(j).toString());
if (j <= 0) goto _L2; else goto _L1
_L1:
ArrayList arraylist;
jsonobject = jsonobject.getJSONArray("search_results");
SearchBookContentsResult.setQuery(queryTextView.getText().toString());
arraylist = new ArrayList(j);
int i = 0;
_L4:
if (i >= j)
{
try
{
resultListView.setOnItemClickListener(new BrowseBookListener(SearchBookContentsActivity.this, arraylist));
resultListView.setAdapter(new SearchBookContentsAdapter(SearchBookContentsActivity.this, arraylist));
return;
}
// Misplaced declaration of an exception variable
catch (JSONObject jsonobject)
{
Log.w(SearchBookContentsActivity.TAG, "Bad JSON from book search", jsonobject);
}
break; /* Loop/switch isn't completed */
}
arraylist.add(parseResult(jsonobject.getJSONObject(i)));
i++;
if (true) goto _L4; else goto _L3
_L2:
if ("false".equals(jsonobject.optString("searchable")))
{
headerView.setText(com.google.zxing.client.android.R.string.msg_sbc_book_not_searchable);
}
resultListView.setAdapter(null);
return;
_L3:
resultListView.setAdapter(null);
headerView.setText(com.google.zxing.client.android.R.string.msg_sbc_failed);
return;
}
private SearchBookContentsResult parseResult(JSONObject jsonobject)
{
String s;
String s1;
s1 = jsonobject.getString("page_id");
s = jsonobject.getString("page_number");
if (s.length() <= 0) goto _L2; else goto _L1
_L1:
s = (new StringBuilder(String.valueOf(getString(com.google.zxing.client.android.R.string.msg_sbc_page)))).append(' ').append(s).toString();
_L7:
jsonobject = jsonobject.optString("snippet_text");
boolean flag = true;
if (jsonobject.length() <= 0) goto _L4; else goto _L3
_L3:
jsonobject = SearchBookContentsActivity.TAG_PATTERN.matcher(jsonobject).replaceAll("");
jsonobject = SearchBookContentsActivity.LT_ENTITY_PATTERN.matcher(jsonobject).replaceAll("<");
jsonobject = SearchBookContentsActivity.GT_ENTITY_PATTERN.matcher(jsonobject).replaceAll(">");
jsonobject = SearchBookContentsActivity.QUOTE_ENTITY_PATTERN.matcher(jsonobject).replaceAll("'");
jsonobject = SearchBookContentsActivity.QUOT_ENTITY_PATTERN.matcher(jsonobject).replaceAll("\"");
_L5:
return new SearchBookContentsResult(s1, s, jsonobject, flag);
_L2:
s = getString(com.google.zxing.client.android.R.string.msg_sbc_unknown_page);
continue; /* Loop/switch isn't completed */
_L4:
jsonobject = (new StringBuilder(String.valueOf('('))).append(getString(com.google.zxing.client.android.R.string.msg_sbc_snippet_unavailable)).append(')').toString();
flag = false;
goto _L5
jsonobject;
return new SearchBookContentsResult(getString(com.google.zxing.client.android.R.string.msg_sbc_no_page_returned), "", "", false);
if (true) goto _L7; else goto _L6
_L6:
}
protected volatile transient Object doInBackground(Object aobj[])
{
return doInBackground((String[])aobj);
}
protected transient JSONObject doInBackground(String as[])
{
String s = as[0];
as = as[1];
try
{
if (LocaleManager.isBookSearchUrl(as))
{
as = as.substring(as.indexOf('=') + 1);
as = (new StringBuilder("http://www.google.com/books?id=")).append(as).append("&jscmd=SearchWithinVolume2&q=").append(s).toString();
} else
{
as = (new StringBuilder("http://www.google.com/books?vid=isbn")).append(as).append("&jscmd=SearchWithinVolume2&q=").append(s).toString();
}
return new JSONObject(HttpHelper.downloadViaHttp(as, com.google.zxing.client.android.HttpHelper.ContentType.JSON).toString());
}
// Misplaced declaration of an exception variable
catch (String as[])
{
Log.w(SearchBookContentsActivity.TAG, "Error accessing book search", as);
return null;
}
// Misplaced declaration of an exception variable
catch (String as[])
{
Log.w(SearchBookContentsActivity.TAG, "Error accessing book search", as);
}
return null;
}
protected volatile void onPostExecute(Object obj)
{
onPostExecute((JSONObject)obj);
}
protected void onPostExecute(JSONObject jsonobject)
{
if (jsonobject == null)
{
headerView.setText(com.google.zxing.client.android.R.string.msg_sbc_failed);
} else
{
handleSearchResults(jsonobject);
}
queryTextView.setEnabled(true);
queryTextView.selectAll();
queryButton.setEnabled(true);
}
private NetworkTask()
{
this$0 = SearchBookContentsActivity.this;
super();
}
NetworkTask(NetworkTask networktask)
{
this();
}
}
private static final Pattern GT_ENTITY_PATTERN = Pattern.compile(">");
private static final Pattern LT_ENTITY_PATTERN = Pattern.compile("<");
private static final Pattern QUOTE_ENTITY_PATTERN = Pattern.compile("'");
private static final Pattern QUOT_ENTITY_PATTERN = Pattern.compile(""");
private static final String TAG = com/google/zxing/client/android/book/SearchBookContentsActivity.getSimpleName();
private static final Pattern TAG_PATTERN = Pattern.compile("\\<.*?\\>");
private final android.view.View.OnClickListener buttonListener = new android.view.View.OnClickListener() {
final SearchBookContentsActivity this$0;
public void onClick(View view)
{
launchSearch();
}
{
this$0 = SearchBookContentsActivity.this;
super();
}
};
private TextView headerView;
private String isbn;
private final android.view.View.OnKeyListener keyListener = new android.view.View.OnKeyListener() {
final SearchBookContentsActivity this$0;
public boolean onKey(View view, int i, KeyEvent keyevent)
{
if (i == 66 && keyevent.getAction() == 0)
{
launchSearch();
return true;
} else
{
return false;
}
}
{
this$0 = SearchBookContentsActivity.this;
super();
}
};
private NetworkTask networkTask;
private Button queryButton;
private EditText queryTextView;
private ListView resultListView;
private final AsyncTaskExecInterface taskExec = (AsyncTaskExecInterface)(new AsyncTaskExecManager()).build();
public SearchBookContentsActivity()
{
}
private void launchSearch()
{
String s = queryTextView.getText().toString();
if (s != null && s.length() > 0)
{
NetworkTask networktask = networkTask;
if (networktask != null)
{
networktask.cancel(true);
}
networkTask = new NetworkTask(null);
taskExec.execute(networkTask, new String[] {
s, isbn
});
headerView.setText(com.google.zxing.client.android.R.string.msg_sbc_searching_book);
resultListView.setAdapter(null);
queryTextView.setEnabled(false);
queryButton.setEnabled(false);
}
}
String getISBN()
{
return isbn;
}
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
CookieSyncManager.createInstance(this);
CookieManager.getInstance().removeExpiredCookie();
bundle = getIntent();
if (bundle == null || !bundle.getAction().equals("com.google.zxing.client.android.SEARCH_BOOK_CONTENTS"))
{
finish();
return;
}
isbn = bundle.getStringExtra("ISBN");
if (LocaleManager.isBookSearchUrl(isbn))
{
setTitle(getString(com.google.zxing.client.android.R.string.sbc_name));
} else
{
setTitle((new StringBuilder(String.valueOf(getString(com.google.zxing.client.android.R.string.sbc_name)))).append(": ISBN ").append(isbn).toString());
}
setContentView(com.google.zxing.client.android.R.layout.search_book_contents);
queryTextView = (EditText)findViewById(com.google.zxing.client.android.R.id.query_text_view);
bundle = bundle.getStringExtra("QUERY");
if (bundle != null && bundle.length() > 0)
{
queryTextView.setText(bundle);
}
queryTextView.setOnKeyListener(keyListener);
queryButton = (Button)findViewById(com.google.zxing.client.android.R.id.query_button);
queryButton.setOnClickListener(buttonListener);
resultListView = (ListView)findViewById(com.google.zxing.client.android.R.id.result_list_view);
headerView = (TextView)LayoutInflater.from(this).inflate(com.google.zxing.client.android.R.layout.search_book_contents_header, resultListView, false);
resultListView.addHeaderView(headerView);
}
protected void onPause()
{
NetworkTask networktask = networkTask;
if (networktask != null)
{
networktask.cancel(true);
networkTask = null;
}
super.onPause();
}
protected void onResume()
{
super.onResume();
queryTextView.selectAll();
}
}
|
Markdown
|
UTF-8
| 337 | 2.609375 | 3 |
[] |
no_license
|
## 常见数据结构
- 数组(Array)
- 链表(Linked List)
- 堆(Heap)
- 栈(Stack)
- 队列(Queue)
- 树(Tree)
- 图(Map)
- 哈希表(Hash)
## 参考文章
- [准备下次编程面试前你应该知道的数据结构](https://blog.fundebug.com/2018/08/27/code-interview-data-structure/)
- https://www.jianshu.com/p/ec783261165d
|
JavaScript
|
UTF-8
| 4,606 | 2.734375 | 3 |
[] |
no_license
|
var img;
function load() {
var currentElementId = getElementId();
var URL = window.location.href.substring(0, window.location.href.lastIndexOf('/')) + "/";
var foundElement = false;
if (currentElementId == null) {
window.location.href = URL + "index.html";
}
for (var i = 1; i <= elements.length; i++) {
var number;
if (i < 84 && i != 43 && i != 61 || (i > 88 && i < 89)) {
switch (parseInt(i.toString().length)) {
case 1:
number = "00" + i;
break;
case 2:
number = "0" + i;
break;
case 3:
number = i;
break;
default:
number = i;
console.warn("Error. parseInt(i.toString().length: " + parseInt(i.toString().length));
}
elements[i - 1][2] = "http://www.seilnacht.com/Lexikon/" + number + "pse2.JPG";
} else {
elements[i - 1][2] = "http://www.seilnacht.com/Lexikon/radioak.gif";
}
}
if (currentElementId <= elements.length) {
foundElement = true;
console.debug("Found element " + currentElementId + " " + elements[currentElementId - 1][0]);
preloadAllPictures();
drawSite(currentElementId);
}
if (!foundElement) {
console.debug("Can't find Element " + currentElementId);
document.getElementById("ueberschrift").innerHTML = "Element " + currentElementId + " kann nicht gefunden werden.";
document.getElementById("title").innerHTML = "Element " + currentElementId + " kann nicht gefunden werden.";
}
}
function getElementId() {
if (location.search == "") return null;
var queryString = location.search.substring(1);
var paare = queryString.split("&");
if (paare[0].split("=")[0] == "currentElementId") {
return paare[0].split("=")[1];
} else {
return null;
}
}
function drawSite(currentElementId) {
document.getElementById("title").innerHTML = elements[currentElementId - 1][0];
document.getElementById("ueberschrift").innerHTML = elements[currentElementId - 1][0];
document.getElementById("Ordungszahl").innerHTML = "Ordnungszahl: " + currentElementId;
document.getElementById("Masse").innerHTML = "Masse: " + elements[currentElementId - 1][1][0] + "u";
document.getElementById("Elektronegativität").innerHTML = "Elektronegativität: " + elements[currentElementId - 1][1][1];
document.getElementById("ElektronenKonfiguration").innerHTML = "Elektronenkonfiguration: " + elements[currentElementId - 1][1][2];
document.getElementById("Schmelzpunkt-Siedepunkt").innerHTML = "Schmelzpunkt/Siedepunkt: " + elements[currentElementId - 1][1][3];
document.getElementById("picture").setAttribute("src", elements[currentElementId -1][2]);
console.debug("Picture URL = " + elements[currentElementId - 1][2]);
document.getElementById("text").innerHTML = elements[currentElementId - 1][3];
document.getElementById("picture").setAttribute("alt", "Can't find picture URL: " + elements[currentElementId - 1][2]);
document.getElementById("source").innerHTML = "https://de.wikipedia.org/wiki/" + (elements[currentElementId - 1][0] == "Titan" ? elements[currentElementId - 1][0] + "_(Element)" : elements[currentElementId - 1][0]);
document.getElementById("source").setAttribute("href", "https://de.wikipedia.org/wiki/" + (elements[currentElementId - 1][0] == "Titan" ? elements[currentElementId - 1][0] + "_(Element)" : elements[currentElementId - 1][0]));
}
function preloadPicture(pictureURL) {
img = new Image();
img.src = pictureURL;
return checkPictureComplete();
}
function preloadAllPictures() {
var progressBar = document.createElement("div");
var progress = document.createElement("div");
progressBar.width = "100%";
progress.width = "0%";
document.getElementById("ueberschrift").appendChild(progressBar);
progressBar.appendChild(progress);
for(var i = 0; i < elements.length; i++) {
preloadPicture(elements[i][2]);
console.debug("Loaded " + elements[i][2]);
progress.width = elements.length / 100 * i + "%";
}
progressBar.removeChild(progress);
document.getElementById("ueberschrift").removeChild(progressBar);
}
function checkPictureComplete() {
if(img.complete == false) {
window.setTimeout(checkPictureComplete, 100);
} else {
console.debug("img.complete is " + img.complete);
return true;
}
}
|
TypeScript
|
UTF-8
| 1,096 | 3.484375 | 3 |
[
"MIT"
] |
permissive
|
class TopVotedCandidate {
orderedArray: { time: number; voteFor: number }[];
constructor(persons: number[], times: number[]) {
this.orderedArray = [];
persons.forEach((vote, index) => {
const timeOFVote = times[index];
this.orderedArray.push({ time: timeOFVote, voteFor: vote });
});
}
q(t: number): number {
const counting: { [key: number]: number } = {};
this.orderedArray.forEach((vote) => {
if (t > vote.time) {
return;
}
if (counting[vote.voteFor]) {
counting[vote.voteFor] = counting[vote.voteFor] + 1;
} else {
counting[vote.voteFor] = 1;
}
});
const entries = Object.entries<number>(counting);
let winner = ['-1', -1];
entries.forEach((kvp) => {
if (winner[1] < kvp[1]) {
winner = kvp;
}
});
return Number.parseInt(winner[0].toString(), 10);
}
}
/**
* Your TopVotedCandidate object will be instantiated and called as such:
*/
const persons = [];
const times = [];
var obj = new TopVotedCandidate(persons, times);
var param_1 = obj.q(t);
|
Java
|
UTF-8
| 1,892 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.es.singular.cover.zoo.test;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import com.es.controller.zoo.Zoo;
import com.es.singular.cover.zoo.animals.Chiken;
import com.es.singular.cover.zoo.animals.Dog;
import com.es.singular.cover.zoo.animals.DogType;
import com.es.singular.cover.zoo.animals.Parrot;
import com.es.singular.cover.zoo.exceptions.ZooNoAnimalsException;
import com.es.singular.cover.zoo.factory.AnimalType;
import com.es.singular.cover.zoo.factory.ZooFactory;
public class ZooTest {
private Dog dog = null;
private Chiken chiken = null;
private Parrot parrot = null;
private Zoo zoo = new Zoo();
@Before
public void initial() {
dog = (Dog) ZooFactory.createAnimal(AnimalType.DOG);
chiken = (Chiken) ZooFactory.createAnimal(AnimalType.CHICKEN);
parrot = (Parrot) ZooFactory.createAnimal(AnimalType.PARROT);
dog.setName("Rocky");
dog.setFavorityFood("meat");
dog.setDogType(DogType.HUNTER);
chiken.setName("Dana");
chiken.setFavorityFood("corn");
chiken.setBroiler(true);
chiken.setLengthOfWings(0.81);
parrot = (Parrot) ZooFactory.createAnimal(AnimalType.PARROT);
parrot.setName("Peter");
parrot.setFavorityFood("worms");
parrot.setLengthOfWings(0.49);
}
@Test()
public void testNoAnimalTypeCreateAnimal() {
assertEquals(parrot = (Parrot) ZooFactory.createAnimal(null),null);
}
//ShowAllAnimals test case 1: No animals in the Zoo.
@Test(expected = ZooNoAnimalsException.class)
public void testTolalCalculationForBikesWithoutDiscountSameClient() throws ZooNoAnimalsException {
preconditionsZooNoAnimals();
zoo.showAllAnimals();
}
//...
public void preconditionsZooNoAnimals() {
zoo.getAnimals().clear();
}
}
|
Shell
|
UTF-8
| 150 | 3.203125 | 3 |
[] |
no_license
|
#!/bin/bash
LOCK_FILE="lock"
if [ -f ${LOCK_FILE} ]; then
echo "ファイルが存在します"
else
echo "ファイルが存在しません"
fi
|
C
|
UTF-8
| 1,085 | 3.984375 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
struct q {
int value;
struct q *next;
};
struct q *head=NULL,*tail=NULL;
void enqueue(int val)
{
struct q *temp=(struct q*)malloc(sizeof (struct q));
temp->value=val;
temp->next=NULL;
if (head==NULL) {
head=temp;
tail=temp;
}
else {
tail->next=temp;
tail=temp;
}
printf ("%d successfully inserted\n",temp->value);
}
void dequeue()
{
if (head==NULL) {
printf ("Queue is empty\n");
return;
}
printf ("%d successfully removed\n",head->value);
head=head->next;
}
void prnt()
{
struct q *temp=head;
if (head==NULL) {
printf ("Queue is empty\n");
return;
}
printf("Values: ");
while (temp!=NULL){
printf("%d ",temp->value);
temp=temp->next;
}
printf ("\n");
}
int main ()
{
int x=1;
enqueue(x++);enqueue(x++);enqueue(x++);enqueue(x++);enqueue(x++);
prnt();
dequeue();dequeue();dequeue();
prnt();
return 0;
}
|
Swift
|
UTF-8
| 3,559 | 3.078125 | 3 |
[] |
no_license
|
//
// BaseService.swift
// GitHubRepos
//
// Created by Adrian Ghitun on 22/10/2019.
// Copyright © 2019 Adrian Ghitun. All rights reserved.
//
import Foundation
import Alamofire
/*
Exposing only what matters. Hiding the actual implementation.
Depending upon abstractions not concretions
*/
protocol BaseServiceProtocol {
func get<T: Decodable>(baseUrl: URL?, path: String, parameters: [String: String], completion: @escaping ((Swift.Result<T, Error>) -> Void))
func post<T: Decodable>(baseUrl: URL?, path: String, parameters: [String: String], completion: @escaping ((Swift.Result<T, Error>) -> Void))
}
/*
Giving the ability of having parameters with default value
*/
extension BaseServiceProtocol {
func get<T: Decodable>(baseUrl: URL? = BaseService.baseUrl, path: String, parameters: [String: String], completion: @escaping ((Swift.Result<T, Error>) -> Void)) {
get(baseUrl: baseUrl, path: path, parameters: parameters, completion: completion)
}
func post<T: Decodable>(baseUrl: URL? = BaseService.baseUrl, path: String, parameters: [String: String], completion: @escaping ((Swift.Result<T, Error>) -> Void)) {
post(baseUrl: baseUrl, path: path, parameters: parameters, completion: completion)
}
}
/*
The Base Service will use the actual Alamofire implementation
*/
class BaseService: Service {
static let shared = BaseService()
static fileprivate var baseUrl = URL(string: "https://api.github.com/")
var headers: [String: String] = [:]
/*
Setting the authorization header and using only authorized requests after it has been set.
*/
func setupAuthorization(with token: AccessToken) {
headers["Authorization"] = "token \(token.access_token)"
}
}
extension BaseService: BaseServiceProtocol {
func get<T: Decodable>(baseUrl: URL? = BaseService.baseUrl, path: String, parameters: [String: String], completion: @escaping ((Swift.Result<T, Error>) -> Void)) {
if let url = baseUrl?.appendingPathComponent(path) {
request(url: url, method: .get, parameters: parameters, headers: headers, completion: completion)
}
}
func post<T: Decodable>(baseUrl: URL? = BaseService.baseUrl, path: String, parameters: [String: String], completion: @escaping ((Swift.Result<T, Error>) -> Void)) {
if let url = baseUrl?.appendingPathComponent(path) {
request(url: url, method: .post, parameters: parameters, headers: headers, completion: completion)
}
}
}
class Service {
fileprivate init() {}
fileprivate func request<T: Decodable>(url: URL, method: HTTPMethod, parameters: [String: String], headers: [String: String] = [:], completion: @escaping ((Swift.Result<T, Error>) -> Void)) {
var headers = headers
headers["Accept"] = "application/json"
let encoding: ParameterEncoding = method == .get ? URLEncoding.default : JSONEncoding.default
Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers).responseJSON { (response) in
do {
if response.result.isSuccess, let json = response.result.value {
let data = try JSONSerialization.data(withJSONObject: json, options: [])
let obj = try JSONDecoder().decode(T.self, from: data)
completion(Swift.Result.success(obj))
}
} catch {
completion(Swift.Result.failure(ParsingError()))
}
}
}
private class ParsingError: Error {}
}
|
TypeScript
|
UTF-8
| 2,089 | 2.5625 | 3 |
[] |
no_license
|
import {inject, injectable} from "inversify";
import "reflect-metadata";
import ClientInterface from "./ClientInterface";
import CONSTANTS from "./app/config/constants";
import LoggerInterface from "./LoggerInterface";
import * as Fetch from "node-fetch";
import RetryLimitReached from "./RetryLimitReached";
@injectable()
class Client implements ClientInterface {
private maxTries: number = 3;
constructor(@inject(CONSTANTS.LOGGER) private logger: LoggerInterface) {
}
async fetch(url: string, options?: any): Promise<any> {
this.logger.debug(`Fetching ${url}`);
let currentTry = 0;
let response: Fetch.Response = new Fetch.Response();
let body: string = '';
while (currentTry < this.maxTries) {
currentTry++;
try {
response = await this.sendRequest(url, options);
body = await response.text();
if (this.isContentError(body)) {
this.logger.warn(`Server error for ${url}`);
if (currentTry >= this.maxTries) {
throw RetryLimitReached.withTriesAndUrl(this.maxTries, url);
}
this.logger.debug(`Retry ${currentTry} ${url}`);
} else {
break;
}
} catch(e) {
if (currentTry >= this.maxTries) {
throw RetryLimitReached.withTriesAndUrl(this.maxTries, url);
}
}
}
return new Fetch.Response(body, {
url: response.url,
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
}
private isContentError(body: string): boolean {
return body !== ''
&& Boolean(body.match(/(Server Error|502 Bad Gateway|video už nie je možné prehrať)/gs));
}
private sendRequest(url: string, options?: any): Promise<Fetch.Response> {
return Fetch.default(url, options);
}
}
export default Client;
|
Java
|
UTF-8
| 358 | 1.867188 | 2 |
[] |
no_license
|
package com.yhren.Dao.Interface;
import com.yhren.Dao.Bean.LeaseCapital;
import java.util.List;
public interface LeaseCapitalMapper {
int deleteByPrimaryKey(Integer capId);
int insert(LeaseCapital record);
LeaseCapital selectByPrimaryKey(Integer capId);
List<LeaseCapital> selectAll();
int updateByPrimaryKey(LeaseCapital record);
}
|
C
|
UTF-8
| 3,792 | 3.21875 | 3 |
[] |
no_license
|
#ifndef MEMBER_LIST_H_
#define MEMBER_LIST_H_
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "member.h"
#define NO_EVENTS 0
/** Type for defining the member list*/
typedef struct MemberList_t *MemberList;
/**
* memberListCreate: Allocates a new empty member list.
*
* @return
* NULL - if allocation failed.
* A new Member list in case of success.
*/
MemberList memberListCreate();
/**
* memberListDestroy: Deallocates an existing Member list.
*
* @param member_list - Target member list to be deallocated. If member list is NULL nothing will be done
*/
void memberListDestroy(MemberList member_list);
/**
* memberListCopy: Creates a copy of the member list.
*
* @param member_list - Target member list.
* @return
* NULL if a NULL was sent or a memory allocation failed.
* otherwise, a copy of the member list.
*/
MemberList memberListCopy(MemberList member_list);
/**
* memberListInsert: insert to_add member to the member list.
*
* @param member_list - Target member list.
* @param to_add - The member which to be inserted.
* @return
* false - if allocation failed or NULL argument.
* Otherwise true and the member was added.
*/
bool memberListInsert(MemberList member_list, Member to_add);
/**
* memberListContain: Checks if member with specified id is on the member list.
*
* @param member_list - Target member list.
* @param id - the id of the member.
* @return
* false if one of pointers is NULL or if there is no member in the list with the id.
* Otherwise true.
*/
bool memberListContain(MemberList member_list, int id);
/**
* memberListRemove: Removes the member with the specified id from the member list.
If there is no member with the if, nothing will happen.
*
* @param member_list - Target member list.
* @param id - the id to of the member to remove.
*
*/
void memberListRemove(MemberList member_list, int id);
/**
* getMember: Returns a member within the member list, who have the specifeid member_id .
*
* @param member_list - Target member list.
* @param member_id - the id to of the member to get.
*
* @return
* NULL if a NULL was sent or there is no member with the specifeid id in the member list.
* Otherwise return const pointer to the member
*/
const Member getMember(MemberList member_list, int member_id);
/**
* memberListAddToEventNum: add (or subtract) n from the amount of events of the member
* with the same id as member_id.
*
* @param member_list - Target member list.
* @param member_id - the id to of the member to remove.
* @param n - Target member list.
*/
void memberListAddToEventNum(MemberList member_list, int member_id, int n);
/**
* memberListUpdatePassedEvent: Subtract 1 from the amount of the events of the members in member_list1,
* for all members in member_list2
*
* @param member_list1 - Target member list to update.
* @param member_list2 - Reference list of members that will be updated.
*/
void memberListUpdatePassedEvent(MemberList member_list1, MemberList member_list2);
/**
* printMemberList: prints the name of the members in list to the open fd file.
* If NULL was sent or file is not open in read mode - nothing will happen.
*
* @param member_list - Target member list.
* @param fd - the open file to print.
*/
void printMemberList(MemberList member_list, FILE* fd);
/**
* printMembersAndEventNum: prints the name and the number of events of the members in the member list to the open fd file.
* If NULL was sent or file is not open in read mode - nothing will happen.
*
* @param member_list - Target member list.
* @param fd - the open file to print.
*/
void printMembersAndEventNum(MemberList member_list, FILE* fd);
#endif /** MEMBER_LIST_H_ */
|
C#
|
UTF-8
| 2,640 | 3.3125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Ex3.Models
{
public class FileModel : IModel
{
private IList<FlightData> DataList;
private int index;
public bool IsAlive { get; private set; }
public FileModel(string path)
{
InitData(path);
IsAlive = true;
}
public FileModel(FileModel model)
{
this.DataList = new List<FlightData>();
foreach (FlightData data in model.DataList)
{
this.DataList.Add(new FlightData(data.Lat, data.Lon, data.Throttle, data.Rudder));
}
this.index = 0;
}
/// <summary>
/// initialize all the flight data from the file to a queue
/// </summary>
/// <param name="path">the path to the file</param>
private void InitData(string path)
{
FlightData[] arr = ReadData(path);
this.DataList = new List<FlightData>();
if (arr == null)
{
return;
}
foreach (FlightData data in arr)
{
this.DataList.Add(data);
}
}
/// <summary>
/// read the data and get it as FlightData
/// </summary>
/// <param name="path">the path to the file</param>
/// <returns>the flight data as an array of FlightData</returns>
private FlightData[] ReadData(string path)
{
if (!File.Exists(path))
{
Console.WriteLine($"The File '{path}' was not found!");
return null;
}
string[] lines;
lines = File.ReadAllLines(path);
FlightData[] data = new FlightData[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
string[] split = lines[i].Split(',');
double lon = double.Parse(split[0]);
double lat = double.Parse(split[1]);
double throttle = double.Parse(split[2]);
double rudder = double.Parse(split[3]);
data[i] = new FlightData(lat, lon, throttle, rudder);
}
return data;
}
public FlightData GetNextFlightData()
{
if (this.index >= this.DataList.Count)
{
IsAlive = false;
return null;
}
int temp = this.index;
this.index++;
return this.DataList[temp];
}
}
}
|
PHP
|
UTF-8
| 220 | 2.578125 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace Sourcegr\Framework\Http\Router;
interface PredicateCompilerInterface
{
public function runPredicate($callback, RouteMatchInterface $routeMatch);
}
|
C#
|
UTF-8
| 3,808 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using Entities;
using Repositories.Contracts;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
namespace Repositories.SecurityGroupCrawler
{
public delegate void FoundUser(AzureADUser user);
public delegate void FoundGroup(AzureADGroup group);
public delegate void FoundGroupCycle(SecurityGroupCycle cycle);
public class SGCrawler
{
private readonly IGraphGroupRepository _sgRepo;
public SGCrawler(IGraphGroupRepository securityGroupRepository)
{
_sgRepo = securityGroupRepository;
}
public FoundUser FoundUserAction { private get; set; } = (_) => { };
public FoundGroup FoundGroupAction { private get; set; } = (_) => { };
public FoundGroupCycle FoundGroupCycleAction { private get; set; } = (_) => { };
// this is the number of concurrent tasks we have processing the queue
// since this involves a lot of waiting on I/O with the Graph, it's good to
// keep this number high- the runtime will manage the actual threads automatically.
private const int DegreeOfParallelism = 1024;
private ConcurrentDictionary<Guid, byte> _visitedGroups;
private readonly ConcurrentQueue<(AzureADGroup group, ImmutableList<AzureADGroup> visited)> _toVisit = new ConcurrentQueue<(AzureADGroup group, ImmutableList<AzureADGroup> visited)>();
public async Task CrawlGroup(AzureADGroup head)
{
_visitedGroups = new ConcurrentDictionary<Guid, byte>();
var visited = ImmutableList.Create(head);
FoundGroupAction(head);
EnqueueRange(ProcessChildren(await _sgRepo.GetChildrenOfGroup(head.ObjectId)).Select(x => (x, visited)));
await Task.WhenAll(Enumerable.Range(0, DegreeOfParallelism).Select(_ => ProcessQueue()));
// no sense in keeping memory allocated for this.
// the queue gets emptied naturally, but no sense in waiting if to be called again before we release this memory
// just setting it to null should be fine, but clearing it first doesn't hurt anything and helps the garbage collector out
_visitedGroups.Clear();
_visitedGroups = null;
}
private async Task ProcessQueue()
{
while (_toVisit.TryDequeue(out var pair))
{
await Visit(pair.group, pair.visited);
}
}
private async Task Visit(AzureADGroup group, ImmutableList<AzureADGroup> visited)
{
// if we've been here before, mark a cycle and return
if (CheckVisited(group, visited)) { return; }
// Try to mark that we've been here before. If it fails, it means someone beat us to it, and we should return.
if (!_visitedGroups.TryAdd(group.ObjectId, 0)) { return; }
FoundGroupAction(group);
var getChildren = _sgRepo.GetChildrenOfGroup(group.ObjectId);
visited = visited.Add(group);
EnqueueRange(ProcessChildren(await getChildren).Select(x => (x, visited)));
}
private bool CheckVisited(AzureADGroup group, ImmutableList<AzureADGroup> visited)
{
var idx = visited.IndexOf(group);
if (idx == -1) { return false; }
FoundGroupCycleAction(new SecurityGroupCycle(group, visited.RemoveRange(0, idx)));
return true;
}
private IEnumerable<AzureADGroup> ProcessChildren(IEnumerable<IAzureADObject> children)
{
foreach (var child in children)
{
switch (child)
{
case AzureADUser u:
FoundUserAction(u);
break;
case AzureADGroup g:
yield return g;
break;
default:
throw new ArgumentException("Expected either an AzureADUser or Group, got " + child.GetType().Name);
}
}
}
private void EnqueueRange(IEnumerable<(AzureADGroup group, ImmutableList<AzureADGroup> visited)> range)
{
foreach (var pair in range)
{
_toVisit.Enqueue(pair);
}
}
}
}
|
Python
|
UTF-8
| 406 | 3.09375 | 3 |
[] |
no_license
|
import numpy as np
import pandas as pd
from datetime import datetime
file = pd.read_csv("Docs/N26_Juni.csv")
balance = file["Amount (EUR)"].sum()
print(file)
print("______________________")
print("El balance del mes de ")
file['month'] = pd.DatetimeIndex(file['Date']).month
print(file['month'][0:1])
print(str(file['month'][0:1]))
month = datetime.strptime(file['month'][0:1], '%b').date()
print(month)
|
TypeScript
|
UTF-8
| 6,527 | 2.875 | 3 |
[] |
no_license
|
declare namespace org {
namespace spongepowered {
namespace api {
namespace event {
namespace server {
namespace query {
namespace QueryServerEvent {
// @ts-ignore
interface Basic extends org.spongepowered.api.event.server.query.QueryServerEvent {
/**
* Gets the MOTD to respond with.
* <p>By default, this is the server's current MOTD</p>
*/
// @ts-ignore
getMotd(): string;
/**
* Sets the MOTD to respond with.
* <p>If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setMotd(motd: string): void;
/**
* Gets the GameType to respond with.
* <p>By default, this is <code>SMP</code>.
* If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
getGameType(): string;
/**
* Sets the GameType to respond with.
* <p>If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setGameType(gameType: string): void;
/**
* Gets the map (world) to respond with.
* <p>By default, this is the current world on the server.</p>
*/
// @ts-ignore
getMap(): string;
/**
* Sets the map (world) to respond with.
* <p>If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setMap(map: string): void;
/**
* Gets the player count to respond with.
* <p>By default, this is the number of players present on the server.
* If setting the string causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
getPlayerCount(): number;
/**
* Sets the player count to respond with.
* <p>If setting the int causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setPlayerCount(playerCount: number): void;
/**
* Gets the max player count to respond with.
* <p>By default, this is the maximum number of players allowed on the
* server.</p>
*/
// @ts-ignore
getMaxPlayerCount(): number;
/**
* Sets the max player count to respond with.
* <p>If setting the int causes the message to go over the
* maximum size, the message will be automatically truncated.</p>
*/
// @ts-ignore
setMaxPlayerCount(maxPlayerCount: number): void;
/**
* Gets the address to respond with.
* <p>By default, this is the address the server is listening on.</p>
*/
// @ts-ignore
getAddress(): any;
/**
* Sets the address to respond with.
*/
// @ts-ignore
setAddress(address: any): void;
/**
* Gets the current size of the data to respond with.
* <p>This value is implementation-defined - it is only meaningful when
* compared with {@link #getMaxSize()}.</p>
*/
// @ts-ignore
getSize(): number;
/**
* Gets the maximum size of the data to respond with.
* <p>If the size of the data is greater than the returned value,
* it will be automatically truncated.
* This value is implementation-defined - it is only meaningful when
* compared with {@link #getSize()} ()}.</p>
*/
// @ts-ignore
getMaxSize(): number;
}
}
}
}
}
}
}
}
|
Ruby
|
UTF-8
| 164 | 2.953125 | 3 |
[] |
no_license
|
ages = { "Herman"=>32, "Lily"=>30, "Grandpa"=>5843, "Eddie"=>10, "Marilyn"=>22, "Spot"=>237 }
total_age = 0
ages.each do |k, v|
total_age += v
end
p total_age
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.