language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 274 | 2.0625 | 2 |
[] |
no_license
|
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DeviceInterface deviceInterface = DeviceInterface.getInstance();
deviceInterface.AddDevice();
deviceInterface.RunDevice();
}
}
|
Python
|
UTF-8
| 99 | 2.90625 | 3 |
[] |
no_license
|
N=int(input())
h=int(N/3600)
N=N-3600*h
m=int(N/60)
N=N-60*m
print('%02d:%02d:%02d'%(h,m,N))
|
Markdown
|
UTF-8
| 4,308 | 3.703125 | 4 |
[] |
no_license
|
# Geometry Function Lab
### Part 1, Rectangle
Given the following a `rectangle` object like the one below, write the following functions which accept a `rectangle` object as an argument:
* isSquare - Returns whether the rectangle is a square or not
* area - Returns the area of the rectangle
* perimeter - Returns the perimeter of the rectangle
```javascript
const rectangleA = {
length: 4,
width: 4
};
```
### Part 2, Triangle
Given the following a `triangle` object like the one below, write the following functions which accept a `triangle` object as an argument:
* isEquilateral - Returns whether the triangle is equilateral or not
* isIsosceles - Returns whether the triangle is isosceles or not
* area - Returns the area of the Triangle
* isObtuse - Returns whether the triangle is obtuse or not
```javascript
const triangleA = {
sideA: 3,
sideB: 4,
sideC: 4
};
```
# The Cash Register
Write a function called cashRegister that takes a shopping cart object. The object contains item names and prices (itemName: itemPrice). The function should return the total price of the shopping cart.
Example
```
// Input
const cartForParty = {
banana: "1.25",
handkerchief: ".99",
Tshirt: "25.01",
apple: "0.60",
nalgene: "10.34",
proteinShake: "22.36"
};
// Output
cashRegister(cartForParty)); // 60.55
# Credit Card Validation
You're starting your own credit card business. You've come up with a new way to validate credit cards with a simple function called validateCreditCard that returns true or false.
Here are the rules for a valid number:
- Number must be 16 digits, all of them must be numbers
- You must have at least two different digits represented (all of the digits cannot be the same)
- The final digit must be even
- The sum of all the digits must be greater than 16
The following credit card numbers are valid:
- `9999-9999-8888-0000`
- `6666-6666-6666-1666`
The following credit card numbers are invalid:
- `a923-3211-9c01-1112` invalid characters
- `4444-4444-4444-4444` only one type of number
- `1111-1111-1111-1110` sum less than 16
- `6666-6666-6666-6661` odd final number
## Example
```
validateCreditCard('9999-9999-8888-0000'); // Returns: true
```
*Hint*: Remove the dashed from the input string before checking if the input credit card number is valid.
*Bonus*: Return an object indicating whether the credit card is valid, and if not, what the error is
```
{ valid: true, number: 'a923-3211-9c01-1112' }
{ valid: false, number: 'a923-3211-9c01-1112', error: ‘wrong_length’ }
```
*Double Bonus*: Make your credit card scheme even more advanced! What are the rules, and what are some numbers that pass or fail? Ideas: check expiration date! Check out the Luhn Algorithm for inspiration.
# JavaScript Bank
In this homework, you'll create a basic `bank` in Javascript. The bank has many `accounts` and the following capabilities that you need to write.
#### Bank
There is only one bank. This bank has an array of accounts. The bank needs a method that will return the total sum of money in the accounts. It also needs an `addAccount` method that will enroll a new account at the bank and add it to the array of accounts. There is no need to create additional functions of the bank to delete accounts, etc.
The bank has many accounts. Accounts should be objects that all share a set of common functionality.
#### Accounts
Accounts have a current balance and owner's name. You should be able to deposit or withdraw from an account to change the balance.
There is no need to write a user interface. Make sure functions return values -- you may also have your functions `console.log()` values to help you see your code working.
You should write a basic story through a series of JavaScript commands that shows that the methods do indeed work as expected: add some accounts, show the total balance, make some deposits and withdrawals, show the new total balance.
### Tips
Don't overthink this. Shorter code is probably the answer.
## Bonus
- Ensure that the accounts cannot have negative values.
- Write a 'transfer' on the bank that allows you to transfer amounts between two accounts.
## Additional
Begin exploring the [JavaScript Koans](https://github.com/liammclennan/JavaScript-Koans). Fork, clone and start trying them.
|
Java
|
UTF-8
| 3,612 | 2.140625 | 2 |
[] |
no_license
|
package com.eastteam.myprogram.entity;
import java.util.Date;
import java.util.List;
import org.springframework.format.annotation.DateTimeFormat;
/**
* Case实体类
* @author lichlei
*
*/
public class Case extends IdEntity {
public static final String businessCode = "c";
private String title;
private Department department;
private User owner;
private Category businessType;
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
private Date eventTime;
private int guestNum;
private Spaces space;
private String spaceTip;
private String description;
private Paper paper;
private Category status;
private List<Task> tasks;
private Date createdTimestamp;
private List<VisitActivity> visitActivities;
/**默认主角**/
private List<Category> defaultCharacters;
private List<Stakeholder> statkeholders;
private List<Scheme> schemes;
/**标识用户是否已经作答**/
private boolean answered = false;
public boolean isAnswered() {
return answered;
}
public void setAnswered(boolean answered) {
this.answered = answered;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public Category getBusinessType() {
return businessType;
}
public void setBusinessType(Category businessType) {
this.businessType = businessType;
}
public Date getEventTime() {
return eventTime;
}
public void setEventTime(Date eventTime) {
this.eventTime = eventTime;
}
public int getGuestNum() {
return guestNum;
}
public void setGuestNum(int guestNum) {
this.guestNum = guestNum;
}
public Spaces getSpace() {
return space;
}
public void setSpace(Spaces space) {
this.space = space;
}
public String getSpaceTip() {
return spaceTip;
}
public void setSpaceTip(String spaceTip) {
this.spaceTip = spaceTip;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Paper getPaper() {
return paper;
}
public void setPaper(Paper paper) {
this.paper = paper;
}
public Category getStatus() {
return status;
}
public void setStatus(Category status) {
this.status = status;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public Date getCreatedTimestamp() {
return createdTimestamp;
}
public void setCreatedTimestamp(Date createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
public List<VisitActivity> getVisitActivities() {
return visitActivities;
}
public void setVisitActivities(List<VisitActivity> visitActivities) {
this.visitActivities = visitActivities;
}
public List<Category> getDefaultCharacters() {
return defaultCharacters;
}
public void setDefaultCharacters(List<Category> defaultCharacters) {
this.defaultCharacters = defaultCharacters;
}
public List<Stakeholder> getStatkeholders() {
return statkeholders;
}
public void setStatkeholders(List<Stakeholder> statkeholders) {
this.statkeholders = statkeholders;
}
public List<Scheme> getSchemes() {
return schemes;
}
public void setSchemes(List<Scheme> schemes) {
this.schemes = schemes;
}
}
|
PHP
|
UTF-8
| 1,264 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Wesnick\FdfUtility\Fields;
use Wesnick\FdfUtility\FdfWriter;
/**
* @author Wesley O. Nichols <spanishwes@gmail.com>
*/
class ButtonField extends PdfField
{
public function getEscapedValue()
{
return '('.FdfWriter::escapePdfName($this->value).')';
}
/**
* @return mixed
*/
public function getExampleValue()
{
// Pushbuttons have no value
if ($this->isPushButton()) {
return null;
}
$keys = array_keys($this->options);
return $this->options[$keys[mt_rand(0, (count($keys) - 1))]];
}
public function isNoToggleOff()
{
return $this->isRadioButton() && $this->checkBitValue(PdfField::NO_TOGGLE_OFF);
}
public function isPushButton()
{
return $this->checkBitValue(PdfField::PUSH_BUTTON);
}
public function isRadioButton()
{
return $this->checkBitValue(PdfField::RADIO_BUTTON);
}
public function isCheckBox()
{
return !$this->checkBitValue(PdfField::PUSH_BUTTON) && !$this->checkBitValue(PdfField::RADIO_BUTTON);
}
public function isInUnison()
{
return $this->checkBitValue(PdfField::IN_UNISON);
}
public function getType()
{
return 'button';
}
}
|
C++
|
UTF-8
| 1,406 | 3.046875 | 3 |
[] |
no_license
|
#include "pch.h"
#include "Reticle.h"
Reticle::Reticle()
{
mTexture.loadFromFile("img/reticle.png");
mSprite.setTexture(mTexture);
mSprite.setOrigin(mSprite.getTexture()->getSize().x*0.5, mSprite.getTexture()->getSize().y*0.5);
ShowCursor(false);
}
Reticle::~Reticle()
{
ShowCursor(true);
}
POINT * Reticle::getScreenPosition()
{
return &screenPosition;
}
aPOINT* Reticle::getPosition()
{
return &Position;
}
aPOINT* Reticle::getRelatPosition()
{
return &relatPosition;
}
std::vector<float>* Reticle::getDirection()
{
return &direction;
}
sf::Sprite* Reticle::getSprite()
{
return &mSprite;
}
void Reticle::setPosition(float x, float y)
{
Position.x = x;
Position.y = y;
}
void Reticle::setRelativePosition(float x, float y)
{
relatPosition.x = x;
relatPosition.y = y;
}
void Reticle::setScreenPosition(float x, float y)
{
screenPosition.x = x;
screenPosition.y = y;
}
void Reticle::update(aPOINT* playerPosition, aPOINT* playerRelPosition)
{
GetCursorPos(&screenPosition);
Position.x = playerPosition->x + (screenPosition.x - playerRelPosition->x);
Position.y = playerPosition->y + (screenPosition.y - playerRelPosition->y);
direction[0] = screenPosition.x - playerRelPosition->x;
direction[1] = screenPosition.y - playerRelPosition->y;
auto pathLength = sqrt(pow(direction[0], 2) + pow(direction[1], 2));
direction[0] /= pathLength;
direction[1] /= pathLength;
}
|
PHP
|
UTF-8
| 1,110 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
namespace Csus4\PgsqlCopy;
use PHPUnit\Framework\TestCase;
use SplFileObject;
use SplTempFileObject;
class PgsqlCopyTest extends TestCase
{
/**
* @var PgsqlCopyFactory
*/
protected $pgsqlCopyFactory;
protected function setUp() : void
{
$pgsqlCopy = new PgsqlCopy(new ChunkBuilder());
$this->pgsqlCopyFactory = new PgsqlCopyFactory($pgsqlCopy);
}
public function testInvoke() : void
{
$temp = new SplTempFileObject();
$temp->setFlags(SplFileObject::READ_AHEAD|SplFileObject::READ_CSV);
$temp->fputcsv(['code', 'name', 'price']);
$temp->fputcsv(['000100', 'あいうえお', '1000']);
$csvReader = $this->pgsqlCopyFactory->newCsvReader($temp, ['code', 'name', 'price']);
$this->assertInstanceOf(CsvReader::class, $csvReader);
$pgsqlCopy = $this->pgsqlCopyFactory->newInstance(new FakePdo(), 'items', $csvReader);
$this->assertInstanceOf(PgsqlCopy::class, $pgsqlCopy);
$actual = $pgsqlCopy->__invoke();
$this->assertTrue($actual);
}
}
|
JavaScript
|
UTF-8
| 2,610 | 2.546875 | 3 |
[] |
no_license
|
(function() {
$(document).ready(function()
{
var zoomChart = new Chart2D({id: 'zoomChart', width: '100%', height: '100%', style: 'Simple'});
zoomChart.setConfigFile('./zoomChart/stockConfig.xml');
zoomChart.setCSVData("./zoomChart/date.csv", ["label", "value"])
var configXML;
var htmlContent = '';
var chartShotContent;
$.get('./config.xml', function(data)
{
if( typeof data == 'string'){
configXML = $.stringToXML(data);
}
else{
configXML = data;
};
// 根据配置文件初始化
$(configXML).find('chart').each(function()
{
htmlContent += '<p class="chartTypeTitle">' + $(this).attr('title') + '</p>';
chartShotContent = ''
$(this).find('item').each(function()
{
var url = $(this).attr('demoURL');
if (typeof $(this).attr('style') != 'undefined')
url += '&style=' + $(this).attr('style');
else
url += '&style=Classic'
url += '&type=' + $(this).attr('type');
chartShotContent += '<div class="chart-shot">';
chartShotContent += '<a class="chart-link" href=' + './gallery/demo.html?url=' + url + '><img src=' + $(this).attr('imgURL') + '></a>'
chartShotContent += '<a class="chart-over" href=' + './gallery/demo.html?url='+ url + '><strong>' + $(this).attr('title') + '</strong><span>' + $(this).attr('desc') + '</span></a>'
chartShotContent += '</div>'
})
htmlContent += chartShotContent;
})
$('#centerContent').html(htmlContent);
// 添加鼠标状态与点击事件
$('div.chart-shot').each(function()
{
var link = $('a', this).last();
var title = link.find('strong').text();
// 默认隐藏
link.css('opacity', 0)
link.mouseover(function()
{
link.css('opacity', 1);
})
link.mouseout(function()
{
$(this).css('opacity', 0);
})
// 点击后弹出新窗口
link.click(function(event)
{
if (window.event)
{
window.event.returnValue = false;
window.event.cancelBubble = true;
}
else if (event)
{
event.stopPropagation();
event.preventDefault();
}
openChart(link.attr('href'), title)
return false;
})
})
})
});
var openChart = function(path, title)
{
var width = 800;
var height = 500;
var left = (screen.width) ? (screen.width - width)/2 : 0;
var top = (screen.height) ? (screen.height - height)/2 : 0;
window.open(path, title, 'scrollbars=1,resizable=1, width=' + width + ', height=' + height + ', left=' + left + ', top=' + top);
return false;
};
})()
|
PHP
|
UTF-8
| 3,219 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
namespace CodeRhapsodie\DataflowBundle\Command;
use CodeRhapsodie\DataflowBundle\Factory\ConnectionFactory;
use CodeRhapsodie\DataflowBundle\Repository\JobRepository;
use CodeRhapsodie\DataflowBundle\Repository\ScheduledDataflowRepository;
use CodeRhapsodie\DataflowBundle\SchemaProvider\DataflowSchemaProvider;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* @codeCoverageIgnore
*/
class SchemaCommand extends Command
{
protected static $defaultName = 'code-rhapsodie:dataflow:dump-schema';
public function __construct(private ConnectionFactory $connectionFactory)
{
parent::__construct();
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setDescription('Generates schema create / update SQL queries')
->setHelp('The <info>%command.name%</info> help you to generate SQL Query to create or update your database schema for this bundle')
->addOption('update', null, InputOption::VALUE_NONE, 'Dump only the update SQL queries.')
->addOption('connection', null, InputOption::VALUE_REQUIRED, 'Define the DBAL connection to use')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (null !== $input->getOption('connection')) {
$this->connectionFactory->setConnectionName($input->getOption('connection'));
}
$connection = $this->connectionFactory->getConnection();
$schemaProvider = new DataflowSchemaProvider();
$schema = $schemaProvider->createSchema();
$sqls = $schema->toSql($connection->getDatabasePlatform());
if ($input->getOption('update')) {
$sm = $connection->getSchemaManager();
$tableArray = [JobRepository::TABLE_NAME, ScheduledDataflowRepository::TABLE_NAME];
$tables = [];
foreach ($sm->listTables() as $table) {
/** @var Table $table */
if (in_array($table->getName(), $tableArray)) {
$tables[] = $table;
}
}
$namespaces = [];
if ($connection->getDatabasePlatform()->supportsSchemas()) {
$namespaces = $sm->listNamespaceNames();
}
$sequences = [];
if ($connection->getDatabasePlatform()->supportsSequences()) {
$sequences = $sm->listSequences();
}
$oldSchema = new Schema($tables, $sequences, $sm->createSchemaConfig(), $namespaces);
$sqls = $schema->getMigrateFromSql($oldSchema, $connection->getDatabasePlatform());
}
$io = new SymfonyStyle($input, $output);
$io->text('Execute these SQL Queries on your database:');
foreach ($sqls as $sql) {
$io->text($sql.';');
}
return 0;
}
}
|
Java
|
UTF-8
| 760 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
package oop.simulation;
/**
* IComponent interface (attached to a GameObject).
* Components should not contain logic either. Like GameObjects,
* they only serve to store information. One component can be
* attached to many GameObjects.
*
* @author Kevin Dai
*/
public interface IComponent
{
/**
* Determines whether multiple components of this type may
* be attached to a GameObject
* @return True if the above statement is true, false otherwise.
*/
boolean isUnique();
/**
* Contains very very simple logic run once per act()
*/
void update();
/**
* @param g GameObject that is parent
*/
void setOwner(GameObject g);
/**
* @return The owner
*/
GameObject getOwner();
}
|
Markdown
|
UTF-8
| 2,616 | 3.28125 | 3 |
[] |
no_license
|
# Single-Source Shortest Path:Dijkstra's Algorithm



**Kruskal (global approach):** At each step, choose the cheapest available edge _anywhere_ which does not violate the goal of creating a spanning tree.
**Dijkstra:** At each step, choose the edge _attached to any previously chosen vertex_ (the local aspect) which makes the _total distance from the starting vertex_ (the global aspect) as small as possible, and does not violate the goal of creating a spanning tree.
**Dijkstra**’s algorithm is used to compute the minimal distance from a node to all the other nodes in a weighted graph.
**Kruskal**’s algorithm are used to compute the minimum spanning tree.
I will a speak about how these two algorithms are different.
We’re assuming a N nodes, M edges undirected connected graph. Choosing in between them depends a lot on the values of N, M and what’s the format in which your graph is given.
**Kruskal**
Starts with a set of N trees. Each tree is comprised of a node. At each step it picks one edge that connects two different trees. This edge is the one with the minimum cost that has not yet been picked.
In order to do this you need to sort the edges and then keep track of the nodes that form each tree. For this you’ll probably want to use a _Disjoint set_ data structure.
--------------------------------
Dijkstra是解決「**單源最短路徑問題**」的算法。這個問題是說,**如何找到從某個特定的節點出發,通向其他節點的最短路徑**。
Example
把城市的路口看作圖的節點,把公路看做邊,綜合長度、擁堵程度等指標作為邊的權重,就可以通過Dijkstra算法計算出從城市一點到另一點的最短路線。
Kruskal則是解決「**最小生成樹問題**」的算法,即**在一個連通的圖里,如何去除圖里的邊,使得剩餘的邊仍能連接所有的節點,且這些邊的權重之和最小**。
Example
有一個快遞公司,每天都要開車把快遞送到城市里的不同地點,怎樣走才能不重複地經過每個節點,還能讓總時間最短呢?我們就可以用Kruskal這樣的最小生成樹算法,找到一個最小生成樹,只需要按這個路線走就行了。
|
Java
|
UTF-8
| 1,616 | 3.453125 | 3 |
[] |
no_license
|
/* Daesang Yoon - day42@pitt.edu
* Actual clothe cutter test and main run file
*/
import javax.swing.*;
import java.util.ArrayList;
import java.util.Date;
public class TestClothCutter {
static int SYNC = 500;
static int SLEEP = 30;
public static void main(String[] args) {
ArrayList<Pattern> patterns = new ArrayList<Pattern>();
patterns.add(new Pattern(2,2,1,"A")) ;
patterns.add(new Pattern(2,6,4,"B")) ;
patterns.add(new Pattern(4,2,3,"C")) ;
patterns.add(new Pattern(5,3,5,"D")) ;
int width = 30;
int height = 15;
int pixels = 30;
ClothCutter cutter = new ClothCutter(width,height,patterns) ;
cutter.optimize() ;
System.out.println( cutter.getOptimalValue() ) ;
System.out.println( cutter.getGarments()) ;
ClothGraphic cloth = new ClothGraphic(width,height,pixels) ;
JFrame frame = new JFrame("Nice Cloth Cutter") ;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
frame.getContentPane().add(cloth) ;
frame.pack() ;
//frame.setLocation(50, 50);
frame.setVisible(true) ;
sleep(SYNC) ;
for (Cut c : cutter.getOptimalCuts()) { sleep(SLEEP) ; cloth.drawCuts(c); }
sleep(SYNC) ;
for (Garment g : cutter.getGarments()) { sleep(SLEEP) ; cloth.drawGarment(g) ; }
}
public static void sleep(long milliseconds) {
Date d ;
long start, now ;
d = new Date() ;
start = d.getTime() ;
do { d = new Date() ; now = d.getTime() ; } while ( (now - start) < milliseconds ) ;
}
}
|
Java
|
UTF-8
| 839 | 2.09375 | 2 |
[] |
no_license
|
package raylsing.touchsrc;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import raylsing.widget.MyFloatAB;
public class MainActivity extends BaseActivity {
private static final String TAG = "MainActivity";
@BindView(R.id.fab) MyFloatAB fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// Intent startIntent = new Intent(this, MyService.class);
// startService(startIntent);
fab.setImageResource(R.drawable.icon_sfdog);
}
@OnClick(R.id.fab)
public void onFabClick(View v){
Log.e(TAG, "onClick: 1" );
}
}
|
C
|
UTF-8
| 364 | 3.0625 | 3 |
[] |
no_license
|
#include"header.h"
int main()
{
BinTree P;
CreateEmpty(&P);
InsertNode(&P, 11);
InsertNode(&P, 12);
InsertNode(&P, 13);
InsertNode(&P, 14);
InsertNode(&P, 15);
printf("\n InOrder : "); PrintInOrder(P);
printf("\n PreOrder : "); PrintInOrder(P);
printf("\n PostOrder : "); PrintInOrder(P);
return 0;
}
|
PHP
|
UTF-8
| 3,320 | 2.59375 | 3 |
[] |
no_license
|
<?php
if(!require('ajax_header.php'))
{
return;
}
$entityUpdateTables = [
'project' => 'projects',
'organization' => 'organizations',
'contributor' => 'contributors'
];
$entityUpdateFields = [
'project' => [
'name' => 'name',
'repo' => 'repo',
'short_desc' => 'short_description',
'description'=> 'description',
],
'organization' => [
'name' => 'name',
'short_desc' => 'short_description',
'description' => 'description',
'homepage' => 'homepage'
],
'contributor' => [
'name' => 'name',
'email' => 'email'
]
];
if(!isset($_POST['type'])
|| !isset($entityUpdateTables[$_POST['type']])
|| !isset($_POST['id']))
{
writeJsonResponse(400, "Missing or invalid parameter.");
return;
}
$entity = $_POST['type'];
$fields = $entityUpdateFields[$entity];
$updateProperties = array_filter($_POST, function ($field) use ($fields) { return isset($fields[$field]); }, ARRAY_FILTER_USE_KEY);
if(count($updateProperties) === 0)
{
writeJsonResponse(200, true);
return;
}
$updateSql = "UPDATE \"{$entityUpdateTables[$entity]}\"";
$bindings = [];
$firstAppend = true;
foreach($updateProperties as $prop => $val)
{
$placeholder = makeNamedPlaceholder($prop);
$updateSql .= $firstAppend ? ' SET ' : ', ';
$updateSql .= $fields[$prop] . ' = :' . $placeholder;
$bindings[$placeholder] = $val;
$firstAppend = false;
}
$updateSql .= " WHERE id = :id";
$bindings['id'] = $_POST['id'];
$stmt = $dbh->prepare($updateSql);
if(!$stmt->execute($bindings))
{
writeJsonResponse(500, makeDBErrorString($stmt));
return;
}
// See whether any rows were actually updated; if not, return.
if($stmt->rowCount() === 0)
{
writeJsonResponse(200, false);
return;
}
// Now email all users who watch this entity.
// A transaction is not necessary, since the entity should still be updated
// regardless of whether we can successfully notify the users.
// Get all the users to notify
$watchersStmt = getWatchersQuery($dbh, $_POST['id']);
if(!$watchersStmt->execute())
{
writeJsonResponse(500, makeDBErrorString($watchersStmt));
return;
}
// Get the full information from the entity that was updated
$getEntityStmt = $entityBaseQueries[$entity]($dbh, $_POST['id']);
if(!$getEntityStmt->execute())
{
writeJsonResponse(500, makeDBErrorString($getEntityStmt));
return;
}
$updatedEntity = $getEntityStmt->fetch(PDO::FETCH_ASSOC);
// Email all watchers
$mailHeaders = <<<EOD
From: brandon.nathan.tom@gmail.com
MIME-Version: 1.0
Content-Type: text/html; charset=iso-8859-1
EOD;
while(($watcher = $watchersStmt->fetch(PDO::FETCH_ASSOC)) !== false)
{
$safeName = htmlspecialchars($watcher['name']);
$safeEntityName = htmlspecialchars($updatedEntity['name']);
$safeEntity = htmlspecialchars($entity);
$messageBody = <<<EOD
<html>
<body>
<p>Hi, {$safeName}!</p>
<p><a href="http://70.179.164.247:{$_SERVER['SERVER_PORT']}/view_entity.php?type={$safeEntity}&id={$updatedEntity['id']}">{$safeEntityName}</a>
has been updated on BNT Project Tracker!</p>
</body>
</html>
EOD;
echo 'Emailing ' . $watcher['email'];
mail($watcher['email'], 'Notification - BNT Project Tracker', $messageBody, $mailHeaders);
}
writeJsonResponse(200, true);
return;
?>
|
Java
|
UTF-8
| 2,540 | 2.140625 | 2 |
[] |
no_license
|
package fi.academy.climateswipe.controllers;
import fi.academy.climateswipe.entities.Relations;
import fi.academy.climateswipe.entities.Users;
import fi.academy.climateswipe.repositories.RelationsRepository;
import fi.academy.climateswipe.repositories.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import javax.management.relation.Relation;
import java.net.URI;
import java.util.List;
import java.util.Optional;
@RestController
@CrossOrigin(origins= "http://localhost:3000")
@RequestMapping("/relations")
public class RelationsController {
private RelationsRepository relationsRepository;
private UsersRepository usersRepository;
@Autowired
public RelationsController(RelationsRepository relationsRepository, UsersRepository usersRepository) {
this.relationsRepository = relationsRepository;
this.usersRepository = usersRepository;
}
@GetMapping
public List<Relations> getAll() {
return relationsRepository.findAll(); }
@GetMapping("/{id}")
public Relations getOne(@PathVariable int id) { return relationsRepository.findById(id);
}
@GetMapping("user/{id}")
public List<Relations> getAllRelations(@PathVariable String id) {
Users user = usersRepository.findByUid(id);
return relationsRepository.findAllByUser(user);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteOne(@PathVariable int id) {
relationsRepository.deleteById(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
@PostMapping
public ResponseEntity<?> addRelation(@RequestBody Relations relations) {
relationsRepository.save(relations);
int id = relations.getId();
URI location = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(8080)
.path("/relations/{id}")
.buildAndExpand(id)
.toUri();
return ResponseEntity.created(location).build();
}
@PutMapping("/{id}")
public void update(@RequestBody Relations newRelations, @PathVariable int id) {
Relations relations = relationsRepository.findById(id);
relations.setChoice(newRelations.getChoice());
relationsRepository.save(relations);
}
}
|
Markdown
|
UTF-8
| 992 | 3.171875 | 3 |
[] |
no_license
|
# interactive-form-v3
Form interacting with Javascript
I create and added a span element for all the fields that are required.
That shows an example of how a correct field should look like.
I did this to give the user more information as to the way the validation fails for that specific input(if the user does not provide correct data).
This span elements will be display just under "*- required fields" at the top of the page
For the name and email fields, I programmed them to be responsive depending on the error type. For example, if the user types a number for the name, the span associated with that name will say that only letters are allowed for that input(this will happen when the user clicks the submit button). In the same matter, if the user types in the email input and forgets to type a email without the "@", for example, tomas_anotioj.com. The span associated with that email will say that email requires the "@."(this will also happen when the form button is click)
|
Rust
|
UTF-8
| 5,444 | 3.3125 | 3 |
[] |
no_license
|
extern crate nom;
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::digit1,
combinator::{all_consuming, map, map_res, opt},
multi::many0,
sequence::{separated_pair, tuple},
IResult,
};
pub fn part_ab(input: &str, day: usize) -> String {
format!(
"AOC 2015 Day {}\n Part 1: {}\n Part 2: {}\n",
day,
part_a(&input),
part_b(&input)
)
}
type Lights = [bool; 1_000_000];
type Lights2 = [usize; 1_000_000];
type Pos = (usize, usize);
#[derive(PartialEq, Debug)]
enum Instruction {
LightOn,
LightOff,
LightToggle,
}
fn parse_input(input: &str) -> Vec<(Instruction, Pos, Pos)> {
// turn on 0,0 through 999,999 would turn on (or leave on) every light.
// toggle 0,0 through 999,0 would toggle the first line of 1000 lights, turning off the ones that were on, and turning on the ones that were off.
// turn off 499,499 through 500,500 would turn off (or leave off) the middle four lights.
fn parse_line(l: &str) -> IResult<&str, (Instruction, Pos, Pos)> {
fn number(i: &str) -> IResult<&str, usize> {
map_res(digit1, |x: &str| x.parse::<usize>())(i)
}
fn pos(i: &str) -> IResult<&str, Pos> {
separated_pair(number, tag(","), number)(i)
}
let through = tag(" through ");
let turn_on = map(tag("turn on "), |_| Instruction::LightOn);
let turn_off = map(tag("turn off "), |_| Instruction::LightOff);
let toggle = map(tag("toggle "), |_| Instruction::LightToggle);
let instr = alt((turn_on, turn_off, toggle));
let newline = opt(tag("\n"));
let (input, (i, s, _, e, _)) = tuple((instr, pos, through, pos, newline))(l)?;
IResult::Ok((input, (i, s, e)))
}
match all_consuming(many0(parse_line))(input) {
Ok((_, res)) => res,
x => panic!("could not parse input {:?}", x),
}
}
pub fn part_a(i: &str) -> usize {
let lines = parse_input(&i);
let mut lights = [false; 1_000_000];
for (i, s, e) in lines {
process(&mut lights, &i, s, e);
}
count_on(&lights)
}
fn process(lights: &mut Lights, instr: &Instruction, start: Pos, end: Pos) {
let (sx, sy) = start;
let (ex, ey) = end;
for x in sx..(ex + 1) {
for y in sy..(ey + 1) {
let pos = x + y * 1_000;
let set = match instr {
Instruction::LightOn => true,
Instruction::LightOff => false,
Instruction::LightToggle => !lights[pos],
};
lights[pos] = set;
}
}
}
fn count_on(lights: &Lights) -> usize {
lights.iter().filter(|x| **x == true).count()
}
pub fn part_b(i: &str) -> usize {
let lines = parse_input(&i);
let mut lights: Lights2 = [0; 1_000_000];
for (i, s, e) in lines {
process2(&mut lights, &i, s, e);
}
lights.iter().sum()
}
fn process2(lights: &mut Lights2, instr: &Instruction, start: Pos, end: Pos) {
let (sx, sy) = start;
let (ex, ey) = end;
for x in sx..(ex + 1) {
for y in sy..(ey + 1) {
let pos = x + y * 1_000;
let set = match instr {
Instruction::LightOn => lights[pos] + 1,
Instruction::LightOff => lights[pos].checked_sub(1).unwrap_or(0),
Instruction::LightToggle => lights[pos] + 2,
};
lights[pos] = set;
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_count() {
assert_eq!(0, count_on(&[false; 1_000_000]));
assert_eq!(1_000_000, count_on(&[true; 1_000_000]));
}
#[test]
fn test_all_on() {
let mut lights: Lights = [false; 1_000_000];
assert_eq!(count_on(&lights), 0);
process(&mut lights, &Instruction::LightOn, (0, 0), (999, 999));
assert_eq!(count_on(&lights), 1_000_000);
}
#[test]
fn test_all_off() {
let mut lights: Lights = [true; 1_000_000];
assert_eq!(count_on(&lights), 1_000_000);
process(&mut lights, &Instruction::LightOff, (0, 0), (999, 999));
assert_eq!(count_on(&lights), 0);
}
#[test]
fn test_on_off() {
let mut lights: Lights = [false; 1_000_000];
process(&mut lights, &Instruction::LightOn, (0, 0), (0, 0));
assert_eq!(count_on(&lights), 1);
process(&mut lights, &Instruction::LightOn, (0, 0), (9, 9));
assert_eq!(count_on(&lights), 100);
process(&mut lights, &Instruction::LightOff, (0, 0), (8, 8));
assert_eq!(count_on(&lights), 19);
process(&mut lights, &Instruction::LightOff, (0, 0), (9, 9));
assert_eq!(count_on(&lights), 0);
}
#[test]
fn test_toggle() {
let mut lights: Lights = [false; 1_000_000];
process(&mut lights, &Instruction::LightToggle, (0, 0), (0, 0));
assert_eq!(count_on(&lights), 1);
process(&mut lights, &Instruction::LightToggle, (0, 0), (9, 9));
assert_eq!(count_on(&lights), 99);
}
#[test]
fn test_parser_single() {
assert_eq!(
parse_input("turn on 0,0 through 999,999"),
vec![(Instruction::LightOn, (0, 0), (999, 999))]
);
assert_eq!(
parse_input("turn off 0,0 through 888,888"),
vec![(Instruction::LightOff, (0, 0), (888, 888))]
);
assert_eq!(
parse_input("toggle 0,0 through 777,777"),
vec![(Instruction::LightToggle, (0, 0), (777, 777))]
);
}
#[test]
fn test_parser_multiple() {
assert_eq!(
parse_input(
"turn on 0,0 through 999,999\nturn off 0,0 through 888,888\ntoggle 0,0 through 777,777"
),
vec![
(Instruction::LightOn, (0, 0), (999, 999)),
(Instruction::LightOff, (0, 0), (888, 888)),
(Instruction::LightToggle, (0, 0), (777, 777))
]
);
}
}
|
C++
|
UTF-8
| 2,950 | 3.28125 | 3 |
[] |
no_license
|
#ifndef SYMBOLTABLE_CPP_INCLUDED
#define SYMBOLTABLE_CPP_INCLUDED
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include "SymbolTable.h"
using std::cout; using std::endl;
using std::map; using std::string;
using std::count; using std::vector;
SymbolTable& SymbolTable::operator=(const SymbolTable& rhs)
{
if (&rhs != this)
symbols = rhs.symbols;
return *this;
}
SymbolTable::SymbolTable(const SymbolTable& from)
{
*this = from;
}
SymbolTable::~SymbolTable()
{
symbols.clear();
symbols.~map();
}
// resets the scope
void SymbolTable::startSubroutine()
{
symbols.clear();
}
int SymbolTable::varCount(const string& wanted_kind) // returns number of occurrences of 'kind' inside the symbol table
{
vector<string> vect_kind;
for (SymbolTable::iterator iter = begin(); iter != end(); ++iter)
{
vect_kind.push_back( (*iter).second.kind );
}
int count_kind = count(vect_kind.begin(), vect_kind.end(), wanted_kind); // ->second.kind
return count_kind;
}
void SymbolTable::define(const string& name, const string& type, const string& kind)
{
if ( symbols.find(name) == symbols.end() )
{
Table values;
int count_kind = varCount(kind); //count(symbols.begin()->second.kind, symbols.end()->second.kind, kind);
values.entry_counter = count_kind;
values.name = name;
values.type = type;
values.kind = kind;
//++values.entry_counter;
symbols.insert(make_pair(values.name, values)); // main symbol table
}
}
string SymbolTable::kindOf(const string& name) // return the kind of entry 'name'
{
map<string, Table>::iterator find_kind = symbols.find(name);
string ret;
if (find_kind == symbols.end() )
ret = "NONE";
else
ret = find_kind->second.kind;
return ret;
}
string SymbolTable::typeOf(const string& name) // returns entry type
{
map<string, Table>::iterator find_type = symbols.find(name);
string ret;
if (find_type != symbols.end() )
ret = find_type->second.type;
else
{
string error(name + " does not have a type assigned");
throw error;
}
return ret;
}
int SymbolTable::indexOf(const string& name) // returns index number of entry
{
map<string, Table>::iterator find_index = symbols.find(name);
int ret;
if (find_index != symbols.end() )
ret = find_index->second.entry_counter;
else
{
string error(name + " does not have a type assigned");
throw error;
}
return ret;
}
SymbolTable::iterator SymbolTable::find(const string& key)
{
return symbols.find(key);
}
#endif // SYMBOLTABLE_CPP_INCLUDED
|
Java
|
UTF-8
| 494 | 2.03125 | 2 |
[] |
no_license
|
package com.nhanhv.ecommerce.repository;
import com.nhanhv.ecommerce.domain.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface RoleRepo extends JpaRepository<Role, Long> {
@Query("SELECT u FROM Role u WHERE u.name = :name")
Role findByName(@Param("name") String name);
}
|
Markdown
|
UTF-8
| 1,502 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "Wooden Sanctuary"
date: 2017-01-01
source: From the Arcane Archive
tags: [cleric, druid, ranger, witch, level2, transmutation, hb, fan]
---
**2nd-level transmutation**
**Casting Time**: 1 action
**Range**: Self
**Components**: V, S
**Duration**: Concentration, up to 1 minute
You step into a wooden object or tree large enough to fully contain your body, melding yourself and all the equipment you carry with the wood for the duration. Using your movement, you step into the wood at a point you can touch. Nothing of your presence remains visible or otherwise detectable by nonmagical senses.
While merged with the wood, you can't see what occurs outside it, and any Wisdom (Perception) checks you make to hear sounds outside it are made with disadvantage. You remain aware of the passage of time and can cast spells on yourself while merged in the wood. You can use your movement to leave the wood where you entered it, which ends the spell. You otherwise can't move.
Minor physical damage to the wood doesn't harm you, but its partial destruction or a change in its shape (to the extent that you no longer fit within it) expels you and deals 3d6 bludgeoning damage to you; the same happens if your concentration is broken while merged with the wood. The wood's complete destruction (or transmutation into a different substance) expels you and deals 25 bludgeoning damage to you. If expelled, you fall prone in an unoccupied space closest to where you first entered.
|
Python
|
UTF-8
| 1,437 | 3.3125 | 3 |
[] |
no_license
|
import numpy as np
from math import pow
def linearRegression(x, y):
a = np.vstack((x, np.ones(x.size))).T
pseudoInverse = np.linalg.inv(a.T@a)@a.T
return pseudoInverse@y
def main():
input_x = np.array(input().split(", ")).astype(float)
input_y = np.array(input().split(", ")).astype(float)
totalSize = input_x.size
# calculate coefficient
a, b = linearRegression(input_x, input_y)
print("{:.3f} {:.3f}".format(a, b))
# calculate MSSE(Minimum Sum Square Error)
sum = 0
opList = list()
for counter in range(0, totalSize):
predictRes = input_x[counter] * a + b
error = (predictRes) - input_y[counter]
tmp = pow(error, 2)
sum += tmp
opList.append([input_x[counter], predictRes, input_y[counter], error, counter])
print("{:.3f}".format(sum / totalSize))
# output
#
sortedarr = np.array(opList)
#print(sortedarr.shape)
sortedarr = sortedarr[np.argsort(sortedarr[:,0])]
row, col = sortedarr.shape
for i in range(row):
for j in range(col-1):
if j < col-2:
print("{:.3f}".format(sortedarr[i][j]), end=" ")
else :
print("{:.3f}".format(sortedarr[i][j]))
#opList.sort(key=lambda x: (x[0], x[3]))
#for element in opList:
# print("{:.3f} {:.3f} {:.3f} {:.3f}".format(*element), sep=' ')
main()
|
C#
|
UTF-8
| 7,911 | 3.15625 | 3 |
[] |
no_license
|
namespace SurprisesWithMutableStructures;
/// <summary>
/// Shows scenarios that demonstrate how using mutable structs can give unexpected results.
/// </summary>
class Program
{
static void Main(string[] args)
{
AccessACopy();
UsingArrays();
AccessStructViaGetter();
ListIndexer();
AccessReadonlyStructs();
BoxingUnboxing();
AccessStructViaInterface();
AccessStructViaReadOnlyMember();
}
private static void AccessACopy()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("StructCopy");
Counter c1 = new Counter();
// The next portion works as expected.
Console.WriteLine(c1.Increment());
Console.WriteLine(c1.Increment());
Console.WriteLine(c1.Increment());
Counter c2 = c1;
// Changing c2 does not change c1. That is pretty obvious since c2 is a copy of c1.
// All other cases throughout the rest of the code are based on the same type of process.
// It the other cases however, the fact that you will operate on a copy of some original structure
// is not quite so obvious.
Console.WriteLine(c2.Increment());
Console.WriteLine(c2.Increment());
Console.WriteLine(c1.GetCounter());
}
private static void UsingArrays()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("ArrayScenario");
Counter[] counterArray = new Counter[1];
// The next portion works as expected.
Console.WriteLine(counterArray[0].Increment());
Console.WriteLine(counterArray[0].Increment());
Console.WriteLine(counterArray[0].Increment());
// The next portion may surprise you.
Counter c1 = counterArray[0];
Console.WriteLine(c1.Increment());
Console.WriteLine(c1.Increment());
Console.WriteLine(counterArray[0].GetCounter());
}
private static void AccessStructViaGetter()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("AccessStructViaGetter");
CounterWrapper counterWrapper = new CounterWrapper();
// The next portion may surprise you.
Console.WriteLine(counterWrapper.Counter.Increment());
Console.WriteLine(counterWrapper.Counter.Increment());
Console.WriteLine(counterWrapper.Counter.Increment());
}
private static void ListIndexer()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("ListIndexer");
List<Counter> counterList = new List<Counter>() { new Counter() };
// The next portion may surprise you.
// This is the same scenario as in AccessStructViaGetter. The indexer
// of List works like a property (is in fact a parameterized property).
Console.WriteLine(counterList[0].Increment());
Console.WriteLine(counterList[0].Increment());
Console.WriteLine(counterList[0].Increment());
}
private static void AccessReadonlyStructs()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("AccessReadonlyStructs");
CounterWrapperWithReadOnlyField counterWrapper = new CounterWrapperWithReadOnlyField();
// The next portion may surprise you.
Console.WriteLine(counterWrapper.Counter.Increment());
Console.WriteLine(counterWrapper.Counter.Increment());
Console.WriteLine(counterWrapper.Counter.Increment());
}
private static void BoxingUnboxing()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("BoxingUnboxing");
Counter counter = new Counter();
Console.WriteLine(counter.Increment());
Object obj = counter;
Console.WriteLine(((Counter)obj).GetCounter());
// The next portion may surprise you.
((Counter)obj).Increment();
Console.WriteLine(((Counter)obj).GetCounter());
}
private static void AccessStructViaInterface()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("AccessStructViaInterface");
IntChanger intChanger = new IntChanger();
intChanger.Change(10);
Console.WriteLine(intChanger.GetValue());
// The next portion may surprise you.
((IChangeValue)intChanger).Change(20);
Console.WriteLine(intChanger.GetValue());
}
private static void AccessStructViaReadOnlyMember()
{
Console.WriteLine("---------------------------------");
Console.WriteLine("AccessStructViaReadOnlyMember");
CounterWrapperWithField c1 = new CounterWrapperWithField();
c1.Counter.Increment();
Console.WriteLine(c1.Counter.GetCounter());
c1.Counter.Increment();
Console.WriteLine(c1.Counter.GetCounter());
c1.Counter.Increment();
Console.WriteLine(c1.Counter.GetCounter());
// The next portion may surprise you.
CounterWrapperWithReadOnlyField c2 = new CounterWrapperWithReadOnlyField();
c2.Counter.Increment();
Console.WriteLine(c2.Counter.GetCounter());
c2.Counter.Increment();
Console.WriteLine(c2.Counter.GetCounter());
c2.Counter.Increment();
Console.WriteLine(c2.Counter.GetCounter());
}
private static void CompilerError()
{
CounterWrapperWithPublicProperty counterWrapper = new CounterWrapperWithPublicProperty();
// Uncomment the next line to see a compiler error.
// Simply accessing counterWrapper.Counter will generate a copy of Counter. That copy however
// is not accessible since you are not assigning the copy to any variable. In other words, you are
// attempting to mutate a copy of counterWrapper.Counter that is not accessible and the compiler
// realize that's very likely not what you want.
// counterWrapper.Counter.counterValue++;
// This will work fine.
CounterWithPublicField c1 = counterWrapper.Counter;
c1.CounterValue++;
}
}
public struct Counter
{
private int _counterValue;
public int Increment()
{
_counterValue++;
return _counterValue;
}
public void Reset()
{
_counterValue = 0;
}
public int GetCounter()
{
return _counterValue;
}
}
public class CounterWrapper
{
public Counter Counter { get; set; }
}
public class CounterWrapperWithField
{
public Counter Counter;
public void Reset()
{
// Note that this will not generate a compiler error although Counter is declared read-only.
// The compiler does not know that Counter.Reset mutates the Counter struct.
Counter.Reset();
// Note that the next line would generate a compiler error even if _counterValue was public
// Counter._counterValue = 100;
}
}
public class CounterWrapperWithReadOnlyField
{
public readonly Counter Counter;
public void Reset()
{
// Note that this will not generate a compiler error although Counter is declared read-only.
// The compiler does not know that Counter.Reset mutates the Counter struct.
Counter.Reset();
// Note that the next line would generate a compiler error even if _counterValue was public
// Counter._counterValue = 100;
}
}
public struct CounterWithPublicField
{
public int CounterValue;
}
public class CounterWrapperWithPublicProperty
{
public CounterWithPublicField Counter { get; set; }
}
public interface IChangeValue
{
void Change(int i);
}
public struct IntChanger : IChangeValue
{
private int _intValue;
public void Change(int i)
{
_intValue = i;
}
public int GetValue()
{
return _intValue; ;
}
}
|
PHP
|
UTF-8
| 2,235 | 3.328125 | 3 |
[] |
no_license
|
<?php
require_once 'classes.php';
//---------1 задание---------------
//Написать код, который будет использовать классы из файла classes.php
//следующим образом: создаст три экземпляра класса NewsArticle и три
//экземпляра класса CrossArtide, после чего эти объекты будут добавлены
//в объект списка статей (экземпляр класса ArticleList) с помощью метода add().
echo "<h1>1 задание</h1>";
$a1 = new NewsArticle (1, 'NewsArticle 1', 'NewsArticleNewsArticleNewsArticleNewsArticleNewsArticleNewsArticle');
$a2 = new NewsArticle (2, 'NewsArticle 2', 'NewsArticleNewsArticleNewsArticleNewsArticleNewsArticleNewsArticle');
$a3 = new NewsArticle (3, 'NewsArticle 3', 'NewsArticleNewsArticleNewsArticleNewsArticleNewsArticleNewsArticle');
$a = new ArticleList();
$a->add($a1);
$a->add($a2);
$a->add($a3);
$a->view();
// -------2 задание-----------
//Создать потомка класса Article, который будет отвечать за статьи,
//у которых есть прикреплённое изображение. Создать несколько таких
//статей и добавить в существующий список (экземпляр класса ArticleList).
echo "<h1>2 задание</h1>";
$a4 = new imageArticle(4, 'Img 4', 'imageArticleimageArticle', 'img/1.png');
$a5 = new imageArticle(5, 'Img 5', 'imageArticleimageArticle', 'img/2.png');
$a6 = new imageArticle(6, 'Img 6', 'КimageArticleimageArticle', 'img/3.png');
$a = new ArticleList();
$a->add($a4);
$a->add($a5);
$a->add($a6);
$a->view();
// -----------4 задание-----------
//Создать потомок класса ArticleList,
//который будет выводить статьи в обратном порядке,
//а не в том, в котором статьи были добавлены.
echo "<h1>4 задание</h1>";
$Reverse = new Reverse();
$Reverse->add($a1);
$Reverse->add($a2);
$Reverse->add($a3);
$Reverse->add($a4);
$Reverse->add($a5);
$Reverse->add($a6);
$Reverse->view();
|
C++
|
UTF-8
| 399 | 2.6875 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main() {
// Write your code here
int i,j,k,h=1,n,g;
cin>>n;
for(i=h;i<=n;i++)
{
for(j=h;j<=i;j++)
{
cout<<j;
}
for(g=((2*n)-2);g>((i+j)-3);g--)
{
cout<<" ";
}
for(k=i;k>=h;k--)
{
cout<<k;
}
cout<<endl;
}
return 0;
}
|
Python
|
UTF-8
| 5,205 | 2.78125 | 3 |
[] |
no_license
|
#!usr/bin/python3
from __future__ import print_function
import smbus
import time
def help():
Robot().help()
class Robot:
def __init__(self):
self.bus = smbus.SMBus(1)
self.restore_defaults()
def restore_defaults(self):
self.buzzer(0)
self.red(0)
self.green(0)
self.blue(0)
self.sleep(1)
self.motor_a(0)
self.motor_b(0)
self.speed_a(1)
self.speed_b(1)
self.motor_a_direction(1)
self.motor_b_direction(1)
self.microstepping(16)
self.power(3)
def help(self):
print("Available commands:")
print(" red(), green(), blue()")
print(" buzzer()")
print(" status()")
print(" Examples: green(1), red('on'), blue('Off')\n")
def write(self, data_byte):
self.bus.write_byte_data(0x70, 0, data_byte)
print("Byte {0} sent".format(data_byte))
def write_block(self, data_block):
self.bus.write_i2c_block_data(0x70, 0, data_block)
print("{0} sent".format(data_block))
def read(self, number_of_bytes):
vals = self.bus.read_i2c_block_data(0x70, 0x00)
return vals
def green(self, on):
try:
if on.upper() in ('OFF', 'AUS'):
on = False
else:
on = True
except:
pass
if on:
self.write(0x51)
else:
self.write(0x50)
def red(self, on):
try:
if on.upper() in ('OFF', 'AUS'):
on = False
else:
on = True
except:
pass
if on:
self.write(0x53)
else:
self.write(0x52)
def blue(self, on):
try:
if on.upper() in ('OFF', 'AUS'):
on = False
else:
on = True
except:
pass
if on:
self.write(0x55)
else:
self.write(0x54)
def buzzer(self, on):
try:
if on.upper() in ('OFF', 'AUS'):
on = False
else:
on = True
except:
pass
if on:
self.write(0x57)
else:
self.write(0x56)
def status(self):
data = self.read(5)
if data[1] == 0:
print('Green is off')
else:
print('Green is on')
if data[2] == 0:
print('Red is off')
else:
print('Red is on')
if data[3] == 0:
print('Blue is off')
else:
print('Blue is on')
if data[4] == 0:
print('Buzzer is off')
else:
print('Buzzer is on')
def enable(self, on):
if on:
self.write(0x59)
else:
self.write(0x58)
def reset(self, on):
if on:
self.write(0x61)
else:
self.write(0x60)
def sleep(self, on):
if on:
self.write(0x63)
else:
self.write(0x62)
def motor_a(self, on):
if on:
self.write(0x65)
else:
self.write(0x64)
def motor_b(self, on):
if on:
self.write(0x67)
else:
self.write(0x66)
def microstepping(self, stepsize):
if stepsize==1:
self.write(0x68)
elif stepsize==2:
self.write(0x69)
elif stepsize==4:
self.write(0x6A)
elif stepsize==16:
self.write(0x6B)
def motor_a_direction(self, direction):
if direction:
self.write(0x6C)
else:
self.write(0x6D)
def motor_b_direction(self, direction):
if direction:
self.write(0x6E)
else:
self.write(0x6F)
def speed_a(self, speed):
self.write_block([0x10, speed])
def speed_b(self, speed):
self.write_block([0x11, speed])
def power(self, power):
self.write_block([0x12, power])
def drive(self, millimeters, speed=0):
msb = abs(millimeters) // 256
lsb = abs(millimeters) % 256
if speed in [1,2,3,4,5]:
self.speed_a(speed)
self.speed_b(speed)
if millimeters>0:
self.motor_a_direction(1)
self.motor_b_direction(1)
else:
self.motor_a_direction(0)
self.motor_b_direction(0)
self.write_block([0x22, msb, lsb, msb, lsb])
def turn(self, angle, speed=0):
width = 162.0 #width in millimeters
circle = width * 3.1415
multiplier = circle / 360.0
milimeters = int(multiplier*angle)
msb = abs(milimeters) // 256
lsb = abs(milimeters) % 256
if speed in [1,2,3,4,5]:
self.speed_a(speed)
self.speed_b(speed)
self.speed_b(speed)
if angle>0:
self.motor_a_direction(0)
self.motor_b_direction(1)
else:
self.motor_a_direction(1)
self.motor_b_direction(0)
self.write_block([0x22, msb, lsb, msb, lsb])
def demo(self):
self.restore_defaults()
#flash red
self.red(1)
time.sleep(1)
self.red(0)
#flash green
self.green(1)
time.sleep(1)
self.green(0)
#flash blue
self.blue(1)
time.sleep(1)
self.blue(0)
#beep
self.buzzer(1)
time.sleep(1)
self.buzzer(0)
#increase power
self.power(6)
#drive
self.drive(100,1)
time.sleep(4)
#turn
self.turn(180,1)
time.sleep(9)
#drive
self.drive(200,3)
time.sleep(4)
#turn again
self.turn(-90,1)
time.sleep(6)
self.turn(180,4)
time.sleep(5)
#drive
self.drive(200,5)
time.sleep(2)
#turn
self.turn(-45,2)
time.sleep(3)
#beep twice
self.buzzer(1)
self.buzzer(0)
self.buzzer(1)
self.buzzer(0)
#decrease power
self.power(3)
|
TypeScript
|
UTF-8
| 11,753 | 3.109375 | 3 |
[] |
no_license
|
import { Board, BoardPosition, PenguinColor } from "../../board";
import {
Game,
getCurrentPlayer,
getCurrentPlayerColor,
MovementGame,
Player,
} from "../../state";
import { placePenguin } from "./penguinPlacement";
import { positionIsPlayable } from "./validation";
import { IllegalPlacementError, NotMovementGameError } from "../types/errors";
import { Movement, GameTree, MovementToResultingTree } from "../../game-tree";
import {
createGameTreeFromMovementGame,
gameIsMovementGame,
} from "./gameTreeCreation";
import { Result } from "true-myth";
const { ok, err } = Result;
import { Maybe } from "true-myth";
import { getFishNumberFromPosition } from "./boardCreation";
import { getReachablePositions } from "./movementChecking";
const { just, nothing } = Maybe;
/**
* Using the zig-zag strategy as outlined in Milestone 5, finds the next
* playable position on the board in the given game. Returns the position
* of the next playable tile.
*
* @param game Game to search for next available tile in zig-zag pattern
* @returns BoardPosition representing the next available position to place
* a penguin.
*/
const getNextPenguinPlacementPosition = (game: Game): Maybe<BoardPosition> => {
for (let row = 0; row < game.board.tiles.length; row++) {
for (let col = 0; col < game.board.tiles[row].length; col++) {
if (positionIsPlayable(game, { row, col })) {
return just({ row, col });
}
}
}
return nothing();
};
/**
* Using the zig-zag strategy as outlined in Milestone 5, find the next
* position for the placement of the given game's current player's
* penguin while they have penguins to place.
*
* @param game the Game state from which to place the next penguin
* @return the resulting Game state from the placement or an error
* if the penguin can't be placed
*/
const placeNextPenguin = (game: Game): Result<Game, IllegalPlacementError> => {
const maybePos = getNextPenguinPlacementPosition(game);
if (maybePos.isNothing()) {
return err(
new IllegalPlacementError(
game,
getCurrentPlayer(game),
{ row: 0, col: 0 } as BoardPosition,
"No more placements available"
)
);
}
return placePenguin(getCurrentPlayer(game), game, maybePos.unsafelyUnwrap());
};
/**
* Places all remaining unplaced penguins in given Game in the zig-zag pattern
* outlined in Milestone 5.
*
* @param game Game state to place all remaining unplaced penguins
* @returns Game with all penguins placed in playable spaces in a zig-zag pattern
*/
const placeAllPenguinsZigZag = (
game: Game
): Result<MovementGame, IllegalPlacementError | NotMovementGameError> => {
const resultGameHasPlacements = (
gameOrError: Result<Game, Error>
): boolean => {
return (
gameOrError.isOk() && !gameIsMovementGame(gameOrError.unsafelyUnwrap())
);
};
let placedPenguinGame: Result<
Game,
IllegalPlacementError | NotMovementGameError
> = ok(game);
while (resultGameHasPlacements(placedPenguinGame)) {
placedPenguinGame = placedPenguinGame.andThen((game: Game) =>
placeNextPenguin(game)
);
}
return placedPenguinGame.andThen((game: Game) => {
if (gameIsMovementGame(game)) {
return ok(game as MovementGame);
} else {
return err(
new NotMovementGameError(game, "Unable to make all placements.")
);
}
});
};
/**
* Minimax recursive search function to find the maximum possible score for the searchingPlayerIndex,
* assuming all other players will make a move to minimize the searchingPlayerIndex's score.
* This computation will be done up to a given remaining depth in the searching player's turns.
*
* @param gameTree GameTree representing the current node in tree traversal
* @param searchingPlayerColor assigned PenguinColor the player the function is maximizing for
* @param lookAheadTurnsDepth Depth remaining in tree traversal
*/
const getMinMaxScore = (
gameTree: GameTree,
searchingPlayerColor: PenguinColor,
lookAheadTurnsDepth: number
): number => {
// If current node is root node or if we've reached the desired depth, return current player score.
if (lookAheadTurnsDepth === 1 || gameTree.potentialMoves.length === 0) {
const player: Player = gameTree.gameState.players.find(
(player: Player) => player.color === searchingPlayerColor
) as Player;
return gameTree.gameState.scores.get(player.color) as number;
}
const isMaximizing: boolean =
searchingPlayerColor === getCurrentPlayerColor(gameTree.gameState);
let curLookAheadTurnsDepth: number = isMaximizing
? lookAheadTurnsDepth - 1
: lookAheadTurnsDepth;
// Get minimax scores for all child nodes of current gameTree.
const scores: Array<number> = gameTree.potentialMoves.map(
(movementToResultingTree: MovementToResultingTree) => {
let resGameTree = movementToResultingTree.resultingGameTree();
if (isTurnSkipped(gameTree, resGameTree, searchingPlayerColor)) {
curLookAheadTurnsDepth = lookAheadTurnsDepth - 1;
} else if (
getCurrentPlayerColor(resGameTree.gameState) === searchingPlayerColor &&
resGameTree.potentialMoves.length > 0 &&
curLookAheadTurnsDepth === 2
) {
const startPositionToMovementToResultingTrees = (
startPosition: BoardPosition
): number => {
if (
getReachablePositions(resGameTree.gameState, startPosition).length >
0
) {
return getFishNumberFromPosition(
resGameTree.gameState.board,
startPosition
);
}
return Number.NEGATIVE_INFINITY;
};
const positions: BoardPosition[] = resGameTree.gameState.penguinPositions.get(
searchingPlayerColor
) as BoardPosition[];
const scores_temp2: number = Math.max(
...positions.map(startPositionToMovementToResultingTrees)
);
return (
resGameTree.gameState.scores.get(searchingPlayerColor) + scores_temp2
);
}
return getMinMaxScore(
resGameTree,
searchingPlayerColor,
curLookAheadTurnsDepth
);
}
);
if (isMaximizing) {
// If the current player in the Game state is the player searching for their
// move, then find the maximum move.
return Math.max(...scores);
}
return Math.min(...scores);
};
/**
*
* @param prevGameTree previous game tree
* @param curGameTree current game tree
* @param maximizingPlayerColor color of the maximizing player
* Checks if the maximizing Player's turn was skipped while transitioning to a directly
* reachable substate in the cureent Game Tree from the game State in the previous game tree
*/
const isTurnSkipped = (
prevGameTree: GameTree,
curGameTree: GameTree,
maximizingPlayerColor: PenguinColor
): boolean => {
return (
curGameTree.gameState.players.length >= 2 &&
prevGameTree.gameState.players[1].color === maximizingPlayerColor &&
curGameTree.gameState.players[0].color !==
prevGameTree.gameState.players[1].color
);
};
/**
* Given an array of T and a function to get the numeric value of T, return
* an array containing the mininimum values of T.
*
* @param arr the array to find the minimum values of
* @param getValue a function which gets the numeric value of a T
* @return the array containing the elements of arr which have the miinimum
* numeric value.
*/
const minArray = <T>(arr: Array<T>, getValue: (el: T) => number): Array<T> => {
const values: Array<number> = arr.map((el: T) => getValue(el));
const minValue = Math.min(...values);
return arr.filter((el: T) => getValue(el) === minValue);
};
/**
* Given an array of T and a function to get the numeric value of T, return
* an array containing the maximum values of T.
*
* @param arr the array to find the maximum values of
* @param getValue a function which gets the numeric value of a T
* @return the array containing the elements of arr which have the maximum
* numeric value.
*/
const maxArray = <T>(arr: Array<T>, getValue: (el: T) => number): Array<T> => {
const values: Array<number> = arr.map((el: T) => getValue(el));
const maxValue = Math.max(...values);
return arr.filter((el: T) => getValue(el) === maxValue);
};
/**
* Given a non empty array of movements, narrow them down into a single
* movement by filtering in the order of the following criteria:
* - lowest starting row position
* - lowest starting column positionl
* - lowest ending row position
* - lowest ending column position
*
* @param movements the movements to break ties for
* @return a single movement chosen from the given array of movements
*/
const tieBreakMovements = (movements: Array<Movement>): Movement => {
// Get the movements with the lowest starting row value.
const filteredByLowestStartingRow = minArray<Movement>(
movements,
(movement: Movement) => movement.startPosition.row
);
if (filteredByLowestStartingRow.length === 1) {
return filteredByLowestStartingRow[0];
}
// Get the movements with the lowest starting column value.
const filteredByLowestStartCol = minArray<Movement>(
filteredByLowestStartingRow,
(movement: Movement) => movement.startPosition.col
);
if (filteredByLowestStartCol.length === 1) {
return filteredByLowestStartCol[0];
}
// Get the movements with the lowest ending row value.
const filteredByLowestEndRow = minArray<Movement>(
filteredByLowestStartCol,
(movement: Movement) => movement.endPosition.row
);
if (filteredByLowestEndRow.length === 1) {
return filteredByLowestEndRow[0];
}
// Get the movements with the lowest ending column value.
const filteredByLowestEndPosition = minArray<Movement>(
filteredByLowestEndRow,
(movement: Movement) => movement.endPosition.col
);
return filteredByLowestEndPosition[0];
};
/**
* Choose the next action for the current player of the given Game state using
* a minimax optimization with the given maximum depth corresponding to the
* number of that player's turns to search when optimizing.
*
* @param game the Game state to find the next action from
* @param lookAheadTurnsDepth the maximum number of turns for the current
* player to search through when optimimizing using the minimax optimization
* strategy.
*/
const chooseNextAction = (
game: MovementGame,
lookAheadTurnsDepth: number
): Maybe<Movement> => {
// Create the GameTree for the given state.
const gameTree: GameTree = createGameTreeFromMovementGame(game);
// Return false if there are no next actions for the player to make.
if (gameTree.potentialMoves.length < 1) {
return nothing();
}
// For each of the movements, find their min max.
const movementsToMinMax: Array<
[Movement, number]
> = gameTree.potentialMoves.map(
(movementToResultingTree: MovementToResultingTree) => [
movementToResultingTree.movement,
getMinMaxScore(
movementToResultingTree.resultingGameTree(),
getCurrentPlayerColor(game),
lookAheadTurnsDepth
),
]
);
// Get the movements with the greatest scores.
const maxMovements: Array<Movement> = maxArray<[Movement, number]>(
movementsToMinMax,
([, score]: [Movement, number]) => score
).map(([movement, score]: [Movement, number]) => movement);
// Tie break into a single movement
const nextMovement: Movement | false = tieBreakMovements(maxMovements);
// Return the next movement.
return just(nextMovement);
};
export {
getNextPenguinPlacementPosition,
placeNextPenguin,
placeAllPenguinsZigZag,
chooseNextAction,
getMinMaxScore,
minArray,
maxArray,
tieBreakMovements,
};
|
Java
|
UTF-8
| 860 | 2.515625 | 3 |
[] |
no_license
|
package pdm.ifpb.com.projeto_pdm.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;
public class InternetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(!verificarConexao(context)){
Toast.makeText(context, "Sem conexão com a internet!",
Toast.LENGTH_SHORT).show();
}
}
private boolean verificarConexao(Context context){
ConnectivityManager manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()){
return true;
}
return false;
}
}
|
Java
|
UTF-8
| 5,157 | 1.984375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2007 ETH Zuerich, CISD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.systemsx.cisd.openbis.generic.server.dataaccess.db;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.support.JdbcAccessor;
import org.springframework.orm.hibernate5.HibernateTemplate;
import ch.systemsx.cisd.common.logging.LogCategory;
import ch.systemsx.cisd.common.logging.LogFactory;
import ch.systemsx.cisd.common.reflection.MethodUtils;
import ch.systemsx.cisd.openbis.generic.server.dataaccess.db.deletion.EntityHistoryCreator;
import ch.systemsx.cisd.openbis.generic.shared.basic.CodeConverter;
import ch.systemsx.cisd.openbis.generic.shared.dto.AbstractTypePE;
/**
* An abstract extension of <code>HibernateAbstractDAO</code> suitable for tables that contains <i>type</i> information. <br>
*
* @author Izabela Adamczyk
*/
abstract class AbstractTypeDAO<T extends AbstractTypePE> extends AbstractGenericEntityDAO<T>
{
/**
* The <code>Logger</code> of this class.
* <p>
* This logger does not output any SQL statement. If you want to do so, you had better set an appropriate debugging level for class
* {@link JdbcAccessor}.
* </p>
*/
private final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, getClass());
public AbstractTypeDAO(final SessionFactory sessionFactory, final Class<T> entityClass, EntityHistoryCreator historyCreator)
{
super(sessionFactory, entityClass, historyCreator);
}
final T tryFindTypeByCode(final String code) throws DataAccessException
{
return tryFindTypeByCode(code, true);
}
final T tryFindTypeByCode(final String code, final boolean appendDatabaseInstance)
throws DataAccessException
{
assert code != null : "Unspecified code";
final DetachedCriteria criteria = DetachedCriteria.forClass(getEntityClass());
criteria.add(Restrictions.eq("code", CodeConverter.tryToDatabase(code)));
final List<T> list = cast(getHibernateTemplate().findByCriteria(criteria));
final T entity = tryFindEntity(list, "type");
if (operationLog.isDebugEnabled())
{
operationLog
.debug(String.format("%s(%s,%s): Entity type '%s' has been found.", MethodUtils
.getCurrentMethod().getName(), code, appendDatabaseInstance, entity));
}
return entity;
}
final List<T> tryFindTypeByCodes(final List<String> codes, final boolean appendDatabaseInstance)
throws DataAccessException
{
assert codes != null : "Unspecified codes";
List<String> dbCodes = new ArrayList<String>(codes.size());
for (String code : codes)
{
dbCodes.add(CodeConverter.tryToDatabase(code));
}
final DetachedCriteria criteria = DetachedCriteria.forClass(getEntityClass());
criteria.add(Restrictions.in("code", dbCodes));
final List<T> list = cast(getHibernateTemplate().findByCriteria(criteria));
if (operationLog.isDebugEnabled())
{
operationLog.debug(String.format("%s(): %d entity type(s) have been found.", MethodUtils
.getCurrentMethod().getName(), list.size()));
}
return list;
}
final List<T> listTypes() throws DataAccessException
{
return listTypes(true);
}
final List<T> listTypes(final boolean appendDatabaseInstance) throws DataAccessException
{
final DetachedCriteria criteria = DetachedCriteria.forClass(getEntityClass());
final List<T> list = cast(getHibernateTemplate().findByCriteria(criteria));
if (operationLog.isDebugEnabled())
{
operationLog.debug(String.format("%s(%s): %d entity type(s) have been found.",
MethodUtils.getCurrentMethod().getName(), appendDatabaseInstance, list.size()));
}
return list;
}
protected void createOrUpdateType(T type)
{
final HibernateTemplate hibernateTemplate = getHibernateTemplate();
validatePE(type);
type.setCode(CodeConverter.tryToDatabase(type.getCode()));
hibernateTemplate.saveOrUpdate(type);
hibernateTemplate.flush();
if (operationLog.isInfoEnabled())
{
operationLog.info(String.format("ADD/UPDATE: type '%s'.", type));
}
}
}
|
Python
|
UTF-8
| 4,209 | 3.046875 | 3 |
[] |
no_license
|
#import Dependencies
from splinter import Browser as Br
from bs4 import BeautifulSoup as soup
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
import datetime as dt
import requests
def scrape_all():
# Set the executable path and initialize the chrome browser in splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Br('chrome', **executable_path, headless=True)
news_title, news_paragraph = mars_news(browser)
#Run all scraping and store results in dictionary
data ={
"news_title": news_title,
"news_paragraph": news_paragraph,
"featured_image": features_image(browser),
"last_modified": dt.datetime.now(),
"hemispheres": hemispheres(browser),
"facts": mars_facts()
}
#close browser
browser.quit()
return data
def mars_news(browser):
#set URL and visit first website
url = 'https://mars.nasa.gov/news'
browser.visit(url)
#optional delay for loading page
browser.is_element_present_by_css("ul_item_list li.slide", wait_time=1)
#set BS element and search within for scraping
html = browser.html
news_soup = soup(html, 'html.parser')
# Add try/except for error handling
try:
slide_elem = news_soup.select_one('ul.item_list li.slide')
# Use the parent element to find the first <a> tag and save it as `news_title`
news_title = slide_elem.find("div", class_='content_title').get_text()
# find paragraph text
news_p = slide_elem.find("div", class_= "article_teaser_body").get_text()
except AttributeError:
return None, None
#return values
return news_title, news_p
def features_image(browser):
### FEATURED IMAGE SCRAPPING
#VISIT URL
url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars"
browser.visit(url)
base_url = "https://www.jpl.nasa.gov"
html = browser.html
list_soup = soup(html, 'html.parser')
link_list = list_soup.find_all('div', {'class': 'SearchResultCard'})[0]
img_soup = link_list.select_one('a').get('href')
full_url = base_url + img_soup
browser.visit(full_url)
html = browser.html
a_soup = soup(html, 'html.parser')
try:
# Find the relative image url
link = a_soup.find('a', {'class': 'BaseButton text-contrast-none w-full mb-5 -primary -compact inline-block'}).get('href')
except AttributeError:
return None
return link
def mars_facts():
try:
#read html table into pandas dataframe
df = pd.read_html('http://space-facts.com/mars/')[0]
except BaseException:
return None
df.columns=['Description','Mars']
df.set_index('Description',inplace=True)
df
#export scraped table to html format
return df.to_html(classes="table table-striped")
def hemispheres(browser):
# 1. Use browser to visit the URL
url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
response = requests.get(url)
#Parse the resulting html with soup
hem_soup = soup(response.text, 'html.parser')
# 2. Create a list to hold the images and titles.
hemisphere_image_urls = []
base_url = 'https://astrogeology.usgs.gov'
# 3. Write code to retrieve the image urls and titles for each hemisphere.
hem_links = [base_url + a['href'] for a in hem_soup.find_all('a', {'class': 'product-item'})]
hem_links
#initiate for loop to get links to image and title
for link in hem_links:
#find link to 'sample' jpg image and title under h2
hem_page = soup(requests.get(link).text, 'html.parser')
img_url = hem_page.find('div', {'class': 'downloads'}).find('a', text='Sample')['href']
title = hem_page.find('h2', {'class':'title'}).text
#append link and title to list as a dictionary item
hemisphere_image_urls.append(dict([('img_url', img_url),('title', title)]))
return hemisphere_image_urls
if __name__ == "__main__":
# If running as script, print scraped data
print(scrape_all())
|
Markdown
|
UTF-8
| 31,909 | 2.8125 | 3 |
[] |
no_license
|
# Laravel Passport——OAuth2 API 认证系统源码解析(下)
## 隐式授权
隐式授权类似于授权码授权,但是它只令牌将返回给客户端而不交换授权码。这种授权最常用于无法安全存储客户端凭据的 JavaScript 或移动应用程序。通过调用 `AuthServiceProvider` 中的 `enableImplicitGrant` 方法来启用这种授权:
```php
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::enableImplicitGrant();
}
```
调用上面方法开启授权后,开发者可以使用他们的客户端 ID 从应用程序请求访问令牌。接入的应用程序应该向你的应用程序的 /oauth/authorize 路由发出重定向请求,如下所示:
```php
Route::get('/redirect', function () {
$query = http_build_query([
'client_id' => 'client-id',
'redirect_uri' => 'http://example.com/callback',
'response_type' => 'token',
'scope' => '',
]);
return redirect('http://your-app.com/oauth/authorize?'.$query);
});
```
首先仍然是验证授权请求的合法性,其流程与授权码模式基本一致:
```php
public function validateAuthorizationRequest(ServerRequestInterface $request)
{
$clientId = $this->getQueryStringParameter(
'client_id',
$request,
$this->getServerParameter('PHP_AUTH_USER', $request)
);
if (is_null($clientId)) {
throw OAuthServerException::invalidRequest('client_id');
}
$client = $this->clientRepository->getClientEntity(
$clientId,
$this->getIdentifier(),
null,
false
);
if ($client instanceof ClientEntityInterface === false) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidClient();
}
$redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
$scopes = $this->validateScopes(
$this->getQueryStringParameter('scope', $request, $this->defaultScope),
is_array($client->getRedirectUri())
? $client->getRedirectUri()[0]
: $client->getRedirectUri()
);
// Finalize the requested scopes
$finalizedScopes = $this->scopeRepository->finalizeScopes(
$scopes,
$this->getIdentifier(),
$client
);
$stateParameter = $this->getQueryStringParameter('state', $request);
$authorizationRequest = new AuthorizationRequest();
$authorizationRequest->setGrantTypeId($this->getIdentifier());
$authorizationRequest->setClient($client);
$authorizationRequest->setRedirectUri($redirectUri);
$authorizationRequest->setState($stateParameter);
$authorizationRequest->setScopes($finalizedScopes);
return $authorizationRequest;
}
```
接着,当用户同意授权之后,就要直接返回 `access_token`,`League OAuth2` 直接将令牌放入 `JWT` 中发送回第三方客户端,值得注意的是依据 `OAuth2` 标准,参数都是以 `location hash` 的形式返回的,间隔符是 `#`,而不是 `?`:
```php
public function __construct(\DateInterval $accessTokenTTL, $queryDelimiter = '#')
{
$this->accessTokenTTL = $accessTokenTTL;
$this->queryDelimiter = $queryDelimiter;
}
public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
{
if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
throw new \LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
}
$finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
? is_array($authorizationRequest->getClient()->getRedirectUri())
? $authorizationRequest->getClient()->getRedirectUri()[0]
: $authorizationRequest->getClient()->getRedirectUri()
: $authorizationRequest->getRedirectUri();
// The user approved the client, redirect them back with an access token
if ($authorizationRequest->isAuthorizationApproved() === true) {
$accessToken = $this->issueAccessToken(
$this->accessTokenTTL,
$authorizationRequest->getClient(),
$authorizationRequest->getUser()->getIdentifier(),
$authorizationRequest->getScopes()
);
$response = new RedirectResponse();
$response->setRedirectUri(
$this->makeRedirectUri(
$finalRedirectUri,
[
'access_token' => (string) $accessToken->convertToJWT($this->privateKey),
'token_type' => 'Bearer',
'expires_in' => $accessToken->getExpiryDateTime()->getTimestamp() - (new \DateTime())->getTimestamp(),
'state' => $authorizationRequest->getState(),
],
$this->queryDelimiter
)
);
return $response;
}
// The user denied the client, redirect them back with an error
throw OAuthServerException::accessDenied(
'The user denied the request',
$this->makeRedirectUri(
$finalRedirectUri,
[
'state' => $authorizationRequest->getState(),
]
)
);
}
```
这个用于构建 `jwt` 的私钥就是 `oauth-private.key`,我们知道,`jwt` 一般有三个部分组成:`header`、`claim`、`sign`, 用于 `oauth2` 的 `jwt` 中 `claim` 主要构成有:
* aud 客户端 id
* jti access\_token 随机码
* iat 生成时间
* nbf 拒绝接受 jwt 时间
* exp access\_token 失效时间
* sub 用户 id
具体可以参考 : [JSON Web Token \(JWT\) draft-ietf-oauth-json-web-token-32](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32)
```php
public function convertToJWT(CryptKey $privateKey)
{
return (new Builder())
->setAudience($this->getClient()->getIdentifier())
->setId($this->getIdentifier(), true)
->setIssuedAt(time())
->setNotBefore(time())
->setExpiration($this->getExpiryDateTime()->getTimestamp())
->setSubject($this->getUserIdentifier())
->set('scopes', $this->getScopes())
->sign(new Sha256(), new Key($privateKey->getKeyPath(), $privateKey->getPassPhrase()))
->getToken();
}
public function __construct(
Encoder $encoder = null,
ClaimFactory $claimFactory = null
) {
$this->encoder = $encoder ?: new Encoder();
$this->claimFactory = $claimFactory ?: new ClaimFactory();
$this->headers = ['typ'=> 'JWT', 'alg' => 'none'];
$this->claims = [];
}
public function setAudience($audience, $replicateAsHeader = false)
{
return $this->setRegisteredClaim('aud', (string) $audience, $replicateAsHeader);
}
public function setId($id, $replicateAsHeader = false)
{
return $this->setRegisteredClaim('jti', (string) $id, $replicateAsHeader);
}
public function setIssuedAt($issuedAt, $replicateAsHeader = false)
{
return $this->setRegisteredClaim('iat', (int) $issuedAt, $replicateAsHeader);
}
public function setNotBefore($notBefore, $replicateAsHeader = false)
{
return $this->setRegisteredClaim('nbf', (int) $notBefore, $replicateAsHeader);
}
public function setExpiration($expiration, $replicateAsHeader = false)
{
return $this->setRegisteredClaim('exp', (int) $expiration, $replicateAsHeader);
}
public function setSubject($subject, $replicateAsHeader = false)
{
return $this->setRegisteredClaim('sub', (string) $subject, $replicateAsHeader);
}
public function sign(Signer $signer, $key)
{
$signer->modifyHeader($this->headers);
$this->signature = $signer->sign(
$this->getToken()->getPayload(),
$key
);
return $this;
}
public function getToken()
{
$payload = [
$this->encoder->base64UrlEncode($this->encoder->jsonEncode($this->headers)),
$this->encoder->base64UrlEncode($this->encoder->jsonEncode($this->claims))
];
if ($this->signature !== null) {
$payload[] = $this->encoder->base64UrlEncode($this->signature);
}
return new Token($this->headers, $this->claims, $this->signature, $payload);
}
```
根据 JWT 的生成方法,签名部分 `signature` 是 `header` 与 `claim` 进行 `base64` 编码后再加密的结果。
## 客户端模式
客户端凭据授权适用于机器到机器的认证。例如,你可以在通过 API 执行维护任务中使用此授权。要使用这种授权,你首先需要在 app/Http/Kernel.php 的 routeMiddleware 变量中添加新的中间件:
```php
protected $routeMiddleware = [
'client' => CheckClientCredentials::class,
];
Route::get('/user', function(Request $request) {
...
})->middleware('client');
```
接下来通过向 oauth/token 接口发出请求来获取令牌:
```php
$response = $guzzle->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'client_credentials',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'scope' => 'your-scope',
],
]);
echo json_decode((string) $response->getBody(), true);
```
客户端模式类似于授权码模式的后一部分,利用客户端 id 与客户端密码来获取 `access_token`:
```php
public function respondToAccessTokenRequest(
ServerRequestInterface $request,
ResponseTypeInterface $responseType,
\DateInterval $accessTokenTTL
) {
// Validate request
$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
// Finalize the requested scopes
$finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
// Issue and persist access token
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, null, $finalizedScopes);
// Inject access token into response type
$responseType->setAccessToken($accessToken);
return $responseType;
}
```
类似于授权码模式,`access_token` 的发放也是通过 `Bearer Token` 中存放 JWT。
## 密码模式
OAuth2 密码授权机制可以让你自己的客户端(如移动应用程序)邮箱地址或者用户名和密码获取访问令牌。如此一来你就可以安全地向自己的客户端发出访问令牌,而不需要遍历整个 OAuth2 授权代码重定向流程。
创建密码授权的客户端后,就可以通过向用户的电子邮件地址和密码向 /oauth/token 路由发出 POST 请求来获取访问令牌。而该路由已经由 Passport::routes 方法注册,因此不需要手动定义它。如果请求成功,会在服务端返回的 JSON 响应中收到一个 access\_token 和 refresh\_token:
```php
$response = $http->post('http://your-app.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'taylor@laravel.com',
'password' => 'my-password',
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
```
只要用用户名与密码来验证合法性就可以发放 `access_token` 与 `refresh_token`:
```php
public function respondToAccessTokenRequest(
ServerRequestInterface $request,
ResponseTypeInterface $responseType,
\DateInterval $accessTokenTTL
) {
// Validate request
$client = $this->validateClient($request);
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
$user = $this->validateUser($request, $client);
// Finalize the requested scopes
$finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());
// Issue and persist new tokens
$accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $finalizedScopes);
$refreshToken = $this->issueRefreshToken($accessToken);
// Inject tokens into response
$responseType->setAccessToken($accessToken);
$responseType->setRefreshToken($refreshToken);
return $responseType;
}
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
{
$username = $this->getRequestParameter('username', $request);
if (is_null($username)) {
throw OAuthServerException::invalidRequest('username');
}
$password = $this->getRequestParameter('password', $request);
if (is_null($password)) {
throw OAuthServerException::invalidRequest('password');
}
$user = $this->userRepository->getUserEntityByUserCredentials(
$username,
$password,
$this->getIdentifier(),
$client
);
if ($user instanceof UserEntityInterface === false) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidCredentials();
}
return $user;
}
```
## 路由保护
Passport 包含一个 验证保护机制 可以验证请求中传入的访问令牌。配置 api 的看守器使用 passport 驱动程序后,只需要在需要有效访问令牌的任何路由上指定 auth:api 中间件:
```php
Route::get('/user', function () {
//
})->middleware('auth:api');
```
当调用 Passport 保护下的路由时,接入的 API 应用需要将访问令牌作为 Bearer 令牌放在请求头 Authorization 中。例如,使用 Guzzle HTTP 库时:
```php
$response = $client->request('GET', '/api/user', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
],
]);
```
## auth:api 中间件
当我们已经配置完成 `Passport` 的四种模式并拿到 `access_token` 之后,我们就可以利用令牌去资源服务器获取数据了。资源服务器最常用的校验令牌的中间件就是 `auth:api`,中间件是 `auth`,`api` 是中间件的参数:
```php
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
```
这个中间件是验证登录状态的常用中间件:
```php
class Authenticate
{
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
public function handle($request, Closure $next, ...$guards)
{
$this->authenticate($guards);
return $next($request);
}
protected function authenticate(array $guards)
{
if (empty($guards)) {
return $this->auth->authenticate();
}
foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
throw new AuthenticationException('Unauthenticated.', $guards);
}
}
```
我们的参数 `api` 就是上面的 `guards`,`Auth` 是 `laravel` 自带的登录校验服务:
```php
class AuthManager implements FactoryContract
{
public function guard($name = null)
{
$name = $name ?: $this->getDefaultDriver();
return $this->guards[$name] ?? $this->guards[$name] = $this->resolve($name);
}
protected function resolve($name)
{
$config = $this->getConfig($name);
if (is_null($config)) {
throw new InvalidArgumentException("Auth guard [{$name}] is not defined.");
}
if (isset($this->customCreators[$config['driver']])) {
return $this->callCustomCreator($name, $config);
}
$driverMethod = 'create'.ucfirst($config['driver']).'Driver';
if (method_exists($this, $driverMethod)) {
return $this->{$driverMethod}($name, $config);
}
throw new InvalidArgumentException("Auth guard driver [{$name}] is not defined.");
}
}
```
文档告诉我们,若想要使用 `passport` 服务,我们的 `config/auth` 文件需要如此配置:
```php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
```
可以看出,`driver` 就是 `passport`,我们在启动 `passport` 服务的时候曾经注册过一个 `Guard`:
```php
protected function registerGuard()
{
Auth::extend('passport', function ($app, $name, array $config) {
return tap($this->makeGuard($config), function ($guard) {
$this->app->refresh('request', $guard, 'setRequest');
});
});
}
protected function makeGuard(array $config)
{
return new RequestGuard(function ($request) use ($config) {
return (new TokenGuard(
$this->app->make(ResourceServer::class),
Auth::createUserProvider($config['provider']),
$this->app->make(TokenRepository::class),
$this->app->make(ClientRepository::class),
$this->app->make('encrypter')
))->user($request);
}, $this->app['request']);
}
```
因此,`passport` 使用的就是这个 `TokenGuard`:
```php
class TokenGuard
{
public function __construct(ResourceServer $server,
UserProvider $provider,
TokenRepository $tokens,
ClientRepository $clients,
Encrypter $encrypter)
{
$this->server = $server;
$this->tokens = $tokens;
$this->clients = $clients;
$this->provider = $provider;
$this->encrypter = $encrypter;
}
public function user(Request $request)
{
if ($request->bearerToken()) {
return $this->authenticateViaBearerToken($request);
} elseif ($request->cookie(Passport::cookie())) {
return $this->authenticateViaCookie($request);
}
}
}
```
可以看到,`TokenGuard` 支持两种 `Token` 的验证:`BearerToken` 与 `cookie`。
我们首先看 `BearerToken`:
```php
public function bearerToken()
{
$header = $this->header('Authorization', '');
if (Str::startsWith($header, 'Bearer ')) {
return Str::substr($header, 7);
}
}
protected function authenticateViaBearerToken($request)
{
$psr = (new DiactorosFactory)->createRequest($request);
try {
$psr = $this->server->validateAuthenticatedRequest($psr);
$user = $this->provider->retrieveById(
$psr->getAttribute('oauth_user_id')
);
if (! $user) {
return;
}
$token = $this->tokens->find(
$psr->getAttribute('oauth_access_token_id')
);
$clientId = $psr->getAttribute('oauth_client_id');
if ($this->clients->revoked($clientId)) {
return;
}
return $token ? $user->withAccessToken($token) : null;
} catch (OAuthServerException $e) {
return Container::getInstance()->make(
ExceptionHandler::class
)->report($e);
}
}
```
首先,需要验证请求的合法性:
```php
class ResourceServer
{
public function validateAuthenticatedRequest(ServerRequestInterface $request)
{
return $this->getAuthorizationValidator()->validateAuthorization($request);
}
protected function getAuthorizationValidator()
{
if ($this->authorizationValidator instanceof AuthorizationValidatorInterface === false) {
$this->authorizationValidator = new BearerTokenValidator($this->accessTokenRepository);
}
$this->authorizationValidator->setPublicKey($this->publicKey);
return $this->authorizationValidator;
}
}
```
`BearerTokenValidator` 专门用于验证 `BearerToken` 的合法性:
```php
class BearerTokenValidator implements AuthorizationValidatorInterface
{
public function validateAuthorization(ServerRequestInterface $request)
{
if ($request->hasHeader('authorization') === false) {
throw OAuthServerException::accessDenied('Missing "Authorization" header');
}
$header = $request->getHeader('authorization');
$jwt = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header[0]));
try {
// Attempt to parse and validate the JWT
$token = (new Parser())->parse($jwt);
if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
throw OAuthServerException::accessDenied('Access token could not be verified');
}
// Ensure access token hasn't expired
$data = new ValidationData();
$data->setCurrentTime(time());
if ($token->validate($data) === false) {
throw OAuthServerException::accessDenied('Access token is invalid');
}
// Check if token has been revoked
if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) {
throw OAuthServerException::accessDenied('Access token has been revoked');
}
// Return the request with additional attributes
return $request
->withAttribute('oauth_access_token_id', $token->getClaim('jti'))
->withAttribute('oauth_client_id', $token->getClaim('aud'))
->withAttribute('oauth_user_id', $token->getClaim('sub'))
->withAttribute('oauth_scopes', $token->getClaim('scopes'));
} catch (\InvalidArgumentException $exception) {
// JWT couldn't be parsed so return the request as is
throw OAuthServerException::accessDenied($exception->getMessage());
} catch (\RuntimeException $exception) {
//JWR couldn't be parsed so return the request as is
throw OAuthServerException::accessDenied('Error while decoding to JSON');
}
}
}
```
通过 `passport` 拿到的 `access_token` 都是 `JWT` 格式的,因此首先第一步需要将 `JWT` 解析:
```php
class Parser
{
public function parse($jwt)
{
$data = $this->splitJwt($jwt);
$header = $this->parseHeader($data[0]);
$claims = $this->parseClaims($data[1]);
$signature = $this->parseSignature($header, $data[2]);
foreach ($claims as $name => $value) {
if (isset($header[$name])) {
$header[$name] = $value;
}
}
if ($signature === null) {
unset($data[2]);
}
return new Token($header, $claims, $signature, $data);
}
protected function splitJwt($jwt)
{
if (!is_string($jwt)) {
throw new InvalidArgumentException('The JWT string must have two dots');
}
$data = explode('.', $jwt);
if (count($data) != 3) {
throw new InvalidArgumentException('The JWT string must have two dots');
}
return $data;
}
protected function parseHeader($data)
{
$header = (array) $this->decoder->jsonDecode($this->decoder->base64UrlDecode($data));
if (isset($header['enc'])) {
throw new InvalidArgumentException('Encryption is not supported yet');
}
return $header;
}
protected function parseClaims($data)
{
$claims = (array) $this->decoder->jsonDecode($this->decoder->base64UrlDecode($data));
foreach ($claims as $name => &$value) {
$value = $this->claimFactory->create($name, $value);
}
return $claims;
}
protected function parseSignature(array $header, $data)
{
if ($data == '' || !isset($header['alg']) || $header['alg'] == 'none') {
return null;
}
$hash = $this->decoder->base64UrlDecode($data);
return new Signature($hash);
}
}
```
获得 `JWT` 的三个部分之后,就要验证签名部分是否合法:
```php
class Token
{
public function verify(Signer $signer, $key)
{
if ($this->signature === null) {
throw new BadMethodCallException('This token is not signed');
}
if ($this->headers['alg'] !== $signer->getAlgorithmId()) {
return false;
}
return $this->signature->verify($signer, $this->getPayload(), $key);
}
}
```
验证通过之后,就要验证 `JWT` 各个部分是否合法:
```php
$data = new ValidationData();
$data->setCurrentTime(time());
public function __construct($currentTime = null)
{
$currentTime = $currentTime ?: time();
$this->items = [
'jti' => null,
'iss' => null,
'aud' => null,
'sub' => null,
'iat' => $currentTime,
'nbf' => $currentTime,
'exp' => $currentTime
];
}
public function validate(ValidationData $data)
{
foreach ($this->getValidatableClaims() as $claim) {
if (!$claim->validate($data)) {
return false;
}
}
return true;
}
public function __construct(array $callbacks = [])
{
$this->callbacks = array_merge(
[
'iat' => [$this, 'createLesserOrEqualsTo'],
'nbf' => [$this, 'createLesserOrEqualsTo'],
'exp' => [$this, 'createGreaterOrEqualsTo'],
'iss' => [$this, 'createEqualsTo'],
'aud' => [$this, 'createEqualsTo'],
'sub' => [$this, 'createEqualsTo'],
'jti' => [$this, 'createEqualsTo']
],
$callbacks
);
}
```
我们前面说过,
* aud 客户端 id
* jti access\_token 随机码
* iat 生成时间
* nbf 拒绝接受 jwt 时间
* exp access\_token 失效时间
* sub 用户 id
因此,`JWT` 的生成时间、拒绝接受时间、失效时间就会被验证完成。
接下来,还会验证最重要的 `access_token` :
```php
if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) {
throw OAuthServerException::accessDenied('Access token has been revoked');
}
public function isAccessTokenRevoked($tokenId)
{
return $this->tokenRepository->isAccessTokenRevoked($tokenId);
}
public function isAccessTokenRevoked($id)
{
if ($token = $this->find($id)) {
return $token->revoked;
}
return true;
}
```
接下来,`TokenGuard` 就会验证 `userid`、`clientid` 与 `access_token` 的合法性:
```php
$user = $this->provider->retrieveById(
$psr->getAttribute('oauth_user_id')
);
if (! $user) {
return;
}
$token = $this->tokens->find(
$psr->getAttribute('oauth_access_token_id')
);
$clientId = $psr->getAttribute('oauth_client_id');
if ($this->clients->revoked($clientId)) {
return;
}
return $token ? $user->withAccessToken($token) : null;
```
中间件验证完成。
## 客户端模式中间件 CheckClientCredentials
我们在上面可以看到 `auth:api` 中间件不仅验证 `access_token`,还会验证 `user_id`,对于客户端模式来说,由于 `JWT` 中并没有用户信息,因此 `passport` 专门存在中间件 `CheckClientCredentials` 来做非登录状态的校验。
```php
class CheckClientCredentials
{
public function handle($request, Closure $next, ...$scopes)
{
$psr = (new DiactorosFactory)->createRequest($request);
try {
$psr = $this->server->validateAuthenticatedRequest($psr);
} catch (OAuthServerException $e) {
throw new AuthenticationException;
}
$this->validateScopes($psr, $scopes);
return $next($request);
}
}
```
## 使用 JavaScript 接入 API
在构建 API 时,如果能通过 JavaScript 应用接入自己的 API 将会给开发过程带来极大的便利。这种 API 开发方法允许你使用自己的应用程序的 API 和别人共享的 API。你的 Web 应用程序、移动应用程序、第三方应用程序以及可能在各种软件包管理器上发布的任何 SDK 都可能会使用相同的API。
通常,如果要从 JavaScript 应用程序中使用 API,则需要手动向应用程序发送访问令牌,并将其传递给应用程序。但是,Passport 有一个可以处理这个问题的中间件。将 CreateFreshApiToken 中间件添加到 web 中间件组就可以了:
```php
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
```
Passport 的这个中间件将会在你所有的对外请求中添加一个 laravel\_token cookie。该 cookie 将包含一个加密后的 JWT ,Passport 将用来验证来自 JavaScript 应用程序的 API 请求。至此,你可以在不明确传递访问令牌的情况下向应用程序的 API 发出请求
```php
axios.get('/user')
.then(response => {
console.log(response.data);
});
```
当使用上面的授权方法时,Axios 会自动带上 X-CSRF-TOKEN 请求头传递。另外,默认的 Laravel JavaScript 脚手架会让 Axios 发送 X-Requested-With 请求头:
```php
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
};
```
## CreateFreshApiToken 中间件
```php
class CreateFreshApiToken
{
public function handle($request, Closure $next, $guard = null)
{
$this->guard = $guard;
$response = $next($request);
if ($this->shouldReceiveFreshToken($request, $response)) {
$response->withCookie($this->cookieFactory->make(
$request->user($this->guard)->getKey(), $request->session()->token()
));
}
return $response;
}
public function make($userId, $csrfToken)
{
$config = $this->config->get('session');
$expiration = Carbon::now()->addMinutes($config['lifetime']);
return new Cookie(
Passport::cookie(),
$this->createToken($userId, $csrfToken, $expiration),
$expiration,
$config['path'],
$config['domain'],
$config['secure'],
true
);
}
protected function createToken($userId, $csrfToken, Carbon $expiration)
{
return JWT::encode([
'sub' => $userId,
'csrf' => $csrfToken,
'expiry' => $expiration->getTimestamp(),
], $this->encrypter->getKey());
}
protected function shouldReceiveFreshToken($request, $response)
{
return $this->requestShouldReceiveFreshToken($request) &&
$this->responseShouldReceiveFreshToken($response);
}
protected function requestShouldReceiveFreshToken($request)
{
return $request->isMethod('GET') && $request->user($this->guard);
}
protected function responseShouldReceiveFreshToken($response)
{
return $response instanceof Response && ! $this->alreadyContainsToken($response);
}
}
```
这个中间件发出的 `JWT` 令牌仍然由 `auth:api` 来负责验证,我们前面说过,`TokenGuard` 负责两种令牌的验证,一种是 `BearerToken`, 另一种就是这个 `Cookie` :
```php
public function user(Request $request)
{
if ($request->bearerToken()) {
return $this->authenticateViaBearerToken($request);
} elseif ($request->cookie(Passport::cookie())) {
return $this->authenticateViaCookie($request);
}
}
protected function authenticateViaCookie($request)
{
try {
$token = $this->decodeJwtTokenCookie($request);
} catch (Exception $e) {
return;
}
if (! $this->validCsrf($token, $request) ||
time() >= $token['expiry']) {
return;
}
if ($user = $this->provider->retrieveById($token['sub'])) {
return $user->withAccessToken(new TransientToken);
}
}
protected function decodeJwtTokenCookie($request)
{
return (array) JWT::decode(
$this->encrypter->decrypt($request->cookie(Passport::cookie())),
$this->encrypter->getKey(), ['HS256']
);
}
protected function validCsrf($token, $request)
{
return isset($token['csrf']) && hash_equals(
$token['csrf'], (string) $request->header('X-CSRF-TOKEN')
);
}
```
|
C#
|
UTF-8
| 781 | 3.375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Collections;
namespace _13集合
{
class Program
{
static void Main(string[] args)
{
IList list = new ArrayList();
list.Add("苍老师赛高!");
ArrayList arrayList = new ArrayList();
arrayList.Add(new Cat());//添加的时候做了装箱操作
arrayList.Add(new Dog());
arrayList.Add(1);
arrayList.Add("哈哈哈");
for (int i = 0; i < arrayList.Count; i++)
{
System.Console.WriteLine(arrayList[i].ToString());
}
Dog dog = (Dog)arrayList[1];//拆箱操作
}
}
class Cat
{
}
class Dog
{
}
}
|
Java
|
UTF-8
| 877 | 3.703125 | 4 |
[] |
no_license
|
import java.util.*;
class Fznak {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Deklaracija
double x, rez;
char znak;
System.out.print("Unesite realan broj x: ");
x = input.nextDouble();
do {
System.out.print("Unesite znak s, c, a, l ili e: ");
znak = input.next().charAt(0);
} while (znak != 's' && znak != 'c' && znak != 'a' && znak != 'l' && znak != 'e');
rez = 0.0;
switch (znak) {
case 's':
rez = Math.sin(x);
break;
case 'c':
rez = Math.cos(x);
break;
case 'a':
rez = Math.atan(x);
break;
case 'l':
rez = Math.log(x);
break;
case 'e':
rez = Math.exp(x);
break;
}
System.out.println("f(" + x + ", " + znak + ") = " + rez);
}
}
|
Markdown
|
UTF-8
| 3,550 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
# Topic
> 中國 AI 科技進入校園!學生上課狀況一目了然!(How China Is Using Artificial-Intelligence In Classrooms | WSJ) <br>
> This fifth grader, whom we caught dozing off in class, told us his parents punish him for low attention scores and that kind of data adds a new kind of pressure for students. <br>
> 這位小五生,被我們抓到上課打瞌睡,他告訴我們他的父母會因為專注力分數低而懲罰他,而這些數據對學生來說是一種新的壓力。 <br>
[](https://www.youtube.com/embed/JMLsHI8aV0g?rel=0&showinfo=0&cc_load_policy=0&controls=1&autoplay=1&iv_load_policy=3&playsinline=1&wmode=transparent&start=272&end=284&enablejsapi=1&origin=https://tw.voicetube.com&widgetid=1)<br>
Host: Victoria
<br>Today issue: Last week of March already! What kind of apps can help you track your attention span? Only this video tells you how crazy it would be like in real life.
There is a pop quiz for you in this episode! Just trying out something new here. Let me know what you think!
Song credit: "The Future is Now" - by MARLOE.
-----
Remember to watch the video first!!!
Here is a link for you to practice and play around with the words you've learned from Victoria’s Pron Challenge today.
Note that not all of them are on there, but the ones I think are essential!!
Join “Flash with Victoria” class:
https://quizlet.com/join/2rK5Vt3M7
Password for lessons: victoria
You will need to either go on the Quizlet website or download the Quizlet app! Enjoy!
<br>
[Host record](https://cdn.voicetube.com/tmp/everyday_records/victoria_vt_19881/3961.mp3)
<br><br>
## learning points
1. _
* dozing off [doz] (phr.) (尤指在白天)睡著了,入睡了
- Benson has been dozing off at school I wonder why maybe it's because he's been burning the midnight oil.
+ 一直在學校打盹,我想知道為什麼是因為他一直在開夜車。
* take a nap [næp] (n..) (尤指日間的)打盹,小睡
- dozing off => during the day
- Freddy likes to take a nap on that couch with the TV on for background noise.
+ 弗雷迪(Freddy)喜歡在電視打開的那張沙發上小睡,以消除背景噪音。
* burn the midnight oil [ ˋmIdˏnaIt] (n..) 午夜; 子夜
2. _
* punish [ˋpʌnIʃ] (v..) 懲罰
- When Chelsea's grades went down her parents punished her by taking away her phone for a whole month.
+ 當切爾西的成績下降時,她的父母將她的手機拿走了整整一個月,以懲罰她。
- putting your palms with a feather duster
- taking away their privilege to sit
- squares
* physical punishment [ˋfIzIkL] [ˋpʌnIʃmәnt] (n..) 體罰
- I don't believe in physical punishment.
* corporal punishment [`kɒrprәl] [ˋpʌnIʃmәnt] (n..) (尤指對孩子的)體罰
3. _
* data [ˋdetә,ˋdætә,ˋdɑtә] (n.) 資料,數據
- The data shows that we need to implement a different approach to reach our audience.
+ 數據表明,我們需要採用其他方法來吸引受眾。
4. _
* pressure [ˋprєʃZ] (n..) 壓力;困擾
- With my parents' high expectations of me, I am under a lot of pressure.
+ 父母對我的期望很高,我承受很大的壓力
* peer pressure [pIr] (n..) 同儕壓力
- When your so-called friends are pure pressuring you to do something you don't like just said no.
+ 當您所謂的朋友純粹是在向您施壓時,您要做一些自己不喜歡的事情,就是說不。
|
Java
|
UTF-8
| 1,112 | 2.328125 | 2 |
[] |
no_license
|
package com.docky.wiki.resp;
import javax.validation.constraints.NotNull;
public class UserLoginResp {
private Long id;
@NotNull(message = "用户名不能为空")
private String username;
@NotNull(message = "昵称不能为空")
private String name;
private String token;
public Long getId() {
return id;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "UserLoginResp{" +
"id=" + id +
", username='" + username + '\'' +
", name='" + name + '\'' +
", token='" + token + '\'' +
'}';
}
}
|
Shell
|
UTF-8
| 2,734 | 3.625 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
#FG Colours
color_fg_none="\e[0m"
color_fg_lightGreen="\e[38;5;47m"
color_fg_lightBlue="\e[38;5;75m"
color_fg_lightYellow="\e[38;5;229m"
color_fg_lightPink="\e[38;5;211m"
color_fg_lightPurple="\e[38;5;163m"
color_fg_red="\e[38;5;196m"
#BG Colours
color_bg_purple="\e[48;5;54m"
if [[ "$1" == "" ]]; then
echo -e "$color_fg_lightYellow Por favor, insira um termo para buscar entre as tarefas. $color_fg_none
$color_fg_lightBlue Ex:$color_fg_lightYellow$ horade$color_fg_lightGreen programar $color_fg_none"
else
if [[ "$2" == "" ]]; then
complemento="hoj"
else
complemento="$2"
fi
if [[ "${complemento}" != "hoj" ]] && [[ "${complemento}" != "ama" ]] && [[ "${complemento}" != "ont" ]] && [[ "${complemento}" != "seg" ]] && [[ "${complemento}" != "ter" ]] && [[ "${complemento}" != "qua" ]] && [[ "${complemento}" != "qui" ]] && [[ "${complemento}" != "sex" ]] && [[ "${complemento}" != "sab" ]] && [[ "${complemento}" != "dom" ]]; then
echo -e "\
$color_fg_lightYellow Por favor use três letras para epecificar o dia
$color_fg_lightBlue Opções:
$color_fg_lightGreen hoj $color_fg_lightPink #Exibe as tarefas de hoje ($(date | awk '{print $1}'))
$color_fg_lightGreen ama $color_fg_lightPink #Exibe as tarefas de amanhã ($(date -d "+1 days" | awk '{print $1}'))
$color_fg_lightGreen ont $color_fg_lightPink #Exibe as tarefas de ontem ($(date -d "-1 days" | awk '{print $1}'))
$color_fg_lightGreen seg $color_fg_lightPink #Exibe as tarefas de Segunda
$color_fg_lightGreen ter $color_fg_lightPink #Exibe as tarefas de Terça
$color_fg_lightGreen qua $color_fg_lightPink #Exibe as tarefas de Quarta
$color_fg_lightGreen qui $color_fg_lightPink #Exibe as tarefas de Quinta
$color_fg_lightGreen sex $color_fg_lightPink #Exibe as tarefas de Sexta
$color_fg_lightGreen sab $color_fg_lightPink #Exibe as tarefas de Sábado
$color_fg_lightGreen dom $color_fg_lightPink #Exibe as tarefas de Domingo
$color_fg_lightBlue Ex:$color_fg_lightYellow$ horade$color_fg_lightGreen programar qua $color_fg_none
"
else
tarefasde $complemento | awk 'FNR==1' > /tmp/.dia_buscado;
tarefasde $complemento | ag -i --nocolor "$1" > /tmp/.resultado_da_busca;
if [[ $( cat /tmp/.resultado_da_busca ) == '' ]];then
echo -e "$color_fg_lightPink Não foi possível encontrar $color_bg_purple$color_fg_lightYellow$1$color_fg_none$color_fg_lightPink entre as tarefas de $color_bg_purple$color_fg_lightYellow$complemento$color_fg_none$color_fg_lightBlue \n -tente outro termo $color_fg_none"
else
echo -e " $color_fg_lightYellow$color_bg_purple ${1^} $color_fg_none in$( cat /tmp/.dia_buscado | cut -f1 -d-)"
cat /tmp/.resultado_da_busca
fi
fi
fi
|
Markdown
|
UTF-8
| 1,605 | 3.203125 | 3 |
[] |
no_license
|
# TDD Baseball Game
## 세 자리 숫자를 맞추는 야구 게임
- 세 자리 수를 입력 받아 결과를 반환한다
## 결과에 대한 반환 값은 다음의 속성을 가지는 객체로 한다
- Boolean solved
- int strikes
- int balls
## 다음의 경우 예외처리 후 게임을 종료한다
- 입력 값이 없을 경우
- 자리 수가 세 자리가 아닐 경우
- 숫자 외의 문자가 입력될 경우
- 중복된 숫자가 입력될 경우
# TDD 법칙
1. 가장 쉽게 구현할 수 있는 테스트부터 시작한다
2. 실패하는 테스트 케이스를 만든다 (Red)
3. 실패하는 테스트 케이스를 성공하도록 최소한의 소스를 수정한다 (Green)
- 필요하면 하드코딩한다.
4. 리팩토링이 필요하면 수행한다 (Refactoring)
- 중복을 제거한다 / 비슷한 중복을 완전한 중복으로 변경한다
- Extract method / Extract to local variable / Inline local variable 등 활용
5. 새로운 실패하는 테스트 케이스를 만든다
6. 1 ~ 5의 반복을 통해 구체화되는 테스트 케이스로 일반화된 소스 코듣를 작성한다
# Baseball Game 테스트 케이스 예시
1. 입력 값이 없을 경우
2. 입력 값의 자리 수가 세 자리가 아닐 경우
3. 입력 값에 숫자 외의 문자가 입력될 경우
4. 입력 값에 중복된 숫자가 입력될 경우
5. 숫자 세 개가 전부 일치하는 경우
6. 숫자 세 개가 전부 일치하지 않을 경우
7. 스트라이크만 있는 경우
8. 볼만 있는 경우
9. 볼과 스트라이크가 함께 있는 경우
|
TypeScript
|
UTF-8
| 425 | 2.703125 | 3 |
[] |
no_license
|
export interface ChessItemProps {
item: ItemType;
name: string;
dragEnd: Function;
isDisabled: boolean;
}
export interface ChessBoardProps {
isDisabled: boolean;
}
export enum FigureType {
black,
white
}
export interface ItemType {
value: string;
type: FigureType;
index: number;
}
export enum Mode {
on = 'ON',
off = 'OFF'
}
export interface DragEndEvent {
source: number;
target: number;
}
|
JavaScript
|
UTF-8
| 1,060 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
(function (window) {
'use strict';
var App = window.App || {};
var $ = window.jQuery;
function RemoteDataStore(url) {
if (!url) {
throw new Error('No remote URL supplied');
}
this.serverUrl = url;
}
RemoteDataStore.prototype.add = function (key, val) {
return $.post(this.serverUrl, val, function (serverResponse) {
console.log(serverResponse);
});
};
RemoteDataStore.prototype.getAll = function (cb) {
return $.get(this.serverUrl, function (serverResponse) {
if (cb) {
console.log(serverResponse);
cb(serverResponse);
}
});
};
RemoteDataStore.prototype.get = function (key, cb) {
return $.get(this.serverUrl + '/' + key, function (serverResponse) {
if (cb) {
console.log(serverResponse);
cb(serverResponse);
}
});
};
RemoteDataStore.prototype.remove = function (key) {
return $.ajax(this.serverUrl + '/' + key, {
type: 'DELETE'
});
};
App.RemoteDataStore = RemoteDataStore;
window.App = App;
})(window);
|
Markdown
|
UTF-8
| 2,018 | 3.875 | 4 |
[] |
no_license
|
### cellular-automata
An object oriented Cython-based Python library for making and visualizing [Cellular Automata](https://en.wikipedia.org/wiki/Cellular_automaton). It should be able to execute and plot any Wolfram (**WIP**) or 2D automaton.
[TOC]
#### Compiling
If you wish to not use the pre-built binaries and compile the code yourself, good news! It's fairly simple. All you need to do is meet the dependencies:
- Python 3.7+
- python3-dev
- cython
- [Optional for graphical plot] matplotlib
#### Usage
To get started, you'll need to import the library and instantiate the CA class. The only required parameter is the dimension of the *square* grid.
```python
>>> from ca import *
>>> c = CA(30) # Initializes a 30x30 grid.
```
With that done, you can proceed to plot the automaton.
```python
>>> plot(c)
```
That will create the file "out.pdf" which contains *up to* 10 steps from a randomly generated 30x30 board. By default, the CA rule is [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
<br />
Of course, Conway's Game of Life may not be the only thing you want to plot, so you'll want to modify the rules. In order to do so, you need to inherit from the base CA class and overwrite the `rule()` method.
```python
from ca import *
class T(CA):
# This function is ran for each cell in the grid and expects the
# new value for the cell to be returned
def rule(self, x, y):
s = self[x, y] # Gets the current value from the cell at (x, y) on the grid
if (s > 0): s -= 1
return s # Updates such cell by returning a new value
c = T(30, values=5) # Creates a 30x30 grid with random values ranging from 0 to 4
plot(c)
```
If you run the above example, you'll get something that looks like this

<br />
For more examples to help you understand the parameters and how they work, check the examples folder. You may also check the description of methods and classes with the `help()` function.
```python
>>> import ca
>>> help(ca)
```
|
Java
|
UTF-8
| 973 | 2.203125 | 2 |
[] |
no_license
|
package com.yaoyao.android.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yaoyao.android.model.DaoMaster;
import org.greenrobot.greendao.database.Database;
/**
* @author:yaoyao
* @email :229847401@qq.com
* @date :2017/6/15
* @desc :
*/
public class CommonDBHelper extends DaoMaster.OpenHelper{
public CommonDBHelper(Context context, String name) {
super(context, name);
}
public CommonDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onCreate(Database db) {
super.onCreate(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
}
}
|
Swift
|
UTF-8
| 660 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
import Foundation
public struct GetNewsResponseModel: Decodable {
let id: Int
let title, text, header: String
let userID: Int
let deletedAt: String?
let createdAt, updatedAt: String
let isNewsPrivate: Int
let author: AuthorResponseModel
enum CodingKeys: String, CodingKey {
case id, title, text, header
case userID = "user_id"
case deletedAt = "deleted_at"
case createdAt = "created_at"
case updatedAt = "updated_at"
case isNewsPrivate = "private"
case author
}
}
// MARK: - Author
struct AuthorResponseModel: Decodable {
let id: Int
let user: String
}
|
C++
|
UTF-8
| 11,161 | 2.625 | 3 |
[] |
no_license
|
#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
typedef int int_type;
// -- utility --
// C-style loop
#define FOR(x, a, b) for(int_type x = static_cast<int_type>(a); x < static_cast<int_type>(b); ++x)
// Ruby-style loop
#define TIMES(x, n) FOR(x, 0, n)
#define STEP(x, a, b, s) for(int_type x = static_cast<int_type>(a); s > 0 ? x <= static_cast<int_type>(b) : x >= static_cast<int_type>(b); x += static_cast<int_type>(s) )
#define UPTO(x, a, b) for(int_type x = static_cast<int_type>(a); x <= static_cast<int_type>(b); ++x)
#define DOWNTO(x, a, b) for(int_type x = static_cast<int_type>(a); x >= static_cast<int_type>(b); --x)
#define EACH(c, i) for(__typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define ALL(cont, it, cond, ret) \
bool ret = true; EACH(cont, it) { if(!(cond)) {ret=false;break;} }
#define ANY(cont, it, cond, ret) \
bool ret = false; EACH(cont, it) { if(cond) {ret=true;break;} }
using namespace std;
// debug
// BEGIN CUT HERE
#define DUMP(x) std::cerr << #x << " = " << to_s(x) << std::endl;
template<typename T> string to_s(const T& v);
template<> string to_s(const string& v);
template<> string to_s(const bool& v);
template<typename T> string to_s(const vector<T>& v);
template<typename T> string to_s(const list<T>& v);
template<typename T> string to_s(const set<T>& v);
template<typename F, typename S> string to_s(const pair<F,S>& v);
template<typename K, typename V> string to_s(const map<K,V>& v);
// END CUT HERE
#ifndef DUMP
#define DUMP(x)
#endif
class ConductorWalk {
public:
vector <int> getObserverRecords(vector <int> orderSeat, vector <int> orderTime, int inspectorSeat)
{
vector <int> result;
// -- main code --
int pos = 0;
int state = 0; // 0: wait, 1: serve, 2: return
list<int> rest;
int served = 0;
int sz = orderTime.size();
UPTO(t, 0, 1050000) {
FOR(k, served, sz) {
if(t == orderTime[k]) {
rest.push_back(orderSeat[k]);
}
}
if(state == 1) {
pos += 1;
if(pos == rest.front()) {
state = 2;
++served;
}
}else if(state == 2) {
pos -= 1;
if(pos == 0) {
rest.pop_front();
if(rest.empty()) {
state = 0;
}else {
state = 1;
}
}
} else {
if(!rest.empty()) {
state = 1;
}
if(sz == served) break;
}
if(pos == inspectorSeat) {
result.push_back(t);
}
DUMP(t);DUMP(pos);DUMP(state);
}
return result;
}
// BEGIN CUT HERE
void debug()
{
}
/*
// PROBLEM STATEMENT
//
The seats are enumerated from 1 to 100, and the i-th seat is located exactly i meters from the conductor's place. The seats are arranged in a straight line, so there are exactly |i-j| meters between the i-th and j-th seats.
During the trip some passengers may order a tea. The orders are described by vector <int>s orderSeat and orderTime. The i-th order comes from the passenger at the orderSeat[i]-th seat orderTime[i] seconds after the departure. The orders will be given in chronological order, which means that the (i+1)-th order will always occur later then the i-th.
The conductor can carry at most one cup at once, so to satisfy each order he must walk to the passenger's seat, give him the tea and return back to his own place. He satisfies the orders in chronological order, i.e. in exactly the same order as they are given in the input. The conductor tries to satisfy each order as soon as possible. That is, if he has already satisfied all previous orders by the moment orderTime[i], then he will start satisfying the i-th order exactly at the moment orderTime[i]. Otherwise, he will start satisfying it immediately after all the chronologically earlier orders are satisfied. The conductor walks 1 meter per second and giving tea to a passenger takes no time, so delivering tea to the i-th passenger takes 2 * i seconds.
The passenger seated at seat inspectorSeat is an inspector. Every time the conductor passes by the inspector's seat, the inspector will write down the current time in seconds in his book. Return a vector <int> containing all times written down by the inspector in increasing order.
DEFINITION
Class:ConductorWalk
Method:getObserverRecords
Parameters:vector <int>, vector <int>, int
Returns:vector <int>
Method signature:vector <int> getObserverRecords(vector <int> orderSeat, vector <int> orderTime, int inspectorSeat)
CONSTRAINTS
-orderSeat will contain between 1 and 50 elements, inclusive.
-orderTime and orderSeat will contain the same number of elements.
-Each element of orderSeat will be between 1 and 100, inclusive.
-Each element of orderTime will be between 0 and 10000, inclusive.
-Each element of orderTime will be strictly greater than the previous one.
-inspectorSeat will be between 1 and 100, inclusive.
EXAMPLES
0)
{1, 3}
{5, 105}
2
Returns: {107, 109 }
Two passengers (at seats 1 and 3) request tea during the trip. The sequence of the conductor's actions is given in the following list:
Time Event
5 Gets the first order
6 Delivers the tea to the first passenger
7 Returns back to his place
105 Gets the second order
107 Walks by inspector's seat
108 Delivers the tea to the second passenger
109 Walks by inspector's seat on the way back
111 Returns to his place
1)
{10, 20, 30}
{0, 5, 10}
1
Returns: {1, 19, 21, 59, 61, 119 }
Time Event
0 Gets order number 1
1 Walks by inspector
10 Delivers the tea to the first passenger
19 Walks by inspector
20 Order number 1 processed, starts processing order number 2
21 Walks by inspector
40 Delivers the tea to the second passenger
59 Walks by inspector
60 Order number 2 processed, starts processing order number 3
61 Walks by inspector
90 Delivers the tea to the third passenger
119 Walks by inspector
120 All orders processed
2)
{1}
{0}
1
Returns: {1 }
The inspector ordered a tea for himself.
3)
{1}
{0}
100
Returns: { }
The inspector is sitting farther away from the conductor than the one passenger who places an order. Therefore, the conductor will never walk by the inspector, and the inspector's book will be empty.
4)
{5, 5, 4, 5, 10, 5, 3, 7, 4}
{4, 18, 36, 43, 61, 78, 90, 101, 113}
4
Returns: {8, 10, 22, 24, 40, 48, 50, 65, 77, 85, 87, 105, 111, 119 }
*/
// END CUT HERE
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { int Arr0[] = {1, 3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {5, 105}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; int Arr3[] = {107, 109 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(0, Arg3, getObserverRecords(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arr0[] = {10, 20, 30}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 5, 10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 1; int Arr3[] = {1, 19, 21, 59, 61, 119 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(1, Arg3, getObserverRecords(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arr0[] = {1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 1; int Arr3[] = {1 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(2, Arg3, getObserverRecords(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arr0[] = {1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 100; int Arr3[] = { }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(3, Arg3, getObserverRecords(Arg0, Arg1, Arg2)); }
void test_case_4() { int Arr0[] = {5, 5, 4, 5, 10, 5, 3, 7, 4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {4, 18, 36, 43, 61, 78, 90, 101, 113}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 4; int Arr3[] = {8, 10, 22, 24, 40, 48, 50, 65, 77, 85, 87, 105, 111, 119 }; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); verify_case(4, Arg3, getObserverRecords(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main(int argc, char *argv[])
{
ConductorWalk test;
if(argc == 1) {
test.run_test(-1);
}else {
std::string arg(argv[1]);
if(arg[0] != '-') {
test.run_test(arg[0] - '0');
}else {
test.debug();
}
}
return 0;
}
template<typename T> string to_s(const T& v) { ostringstream oss; oss << v; return oss.str(); }
template<> string to_s(const string& v) { ostringstream oss; oss << '"' << v << '"'; return oss.str(); }
template<> string to_s(const bool& v) { ostringstream oss; oss << ( v ? "true" : "false") ; return oss.str(); }
template<typename T> string to_s(const vector<T>& v) { ostringstream oss; oss << "["; EACH(v,i) oss << to_s(*i) << ","; oss << "]"; return oss.str(); }
template<typename T> string to_s(const list<T>& v) { ostringstream oss; oss << "("; EACH(v,i) oss << to_s(*i) << ","; oss << ")"; return oss.str(); }
template<typename T> string to_s(const set<T>& v) { ostringstream oss; oss << "{"; EACH(v,i) oss << to_s(*i) << ","; oss << "}"; return oss.str(); }
template<typename F, typename S> string to_s(const pair<F,S>& v) { ostringstream oss; oss << "<" << to_s(v.first) << " " << to_s(v.second) << ">"; return oss.str(); }
template<typename K, typename V> string to_s(const map<K,V>& v) { ostringstream oss; oss << "{"; EACH(v,i) oss << to_s(i->first) << " => " << to_s(i->second) << ","; oss << "}"; return oss.str(); }
// END CUT HERE
|
C#
|
UTF-8
| 956 | 2.890625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Game2
{
class Class1
{
protected Rectangle srcRect;
protected int frame;
protected double frameTimer, frameInterval = 100;
public Class1()
{
srcRect = new Rectangle(0, 0, Game1.tex.Width / 12, Game1.tex.Height / 2);
}
public void FrameTimer(GameTime gameTime)
{
frameTimer -= gameTime.ElapsedGameTime.TotalMilliseconds;
if (frameTimer <= 0)
{
frameTimer = frameInterval;
frame++;
srcRect.X = (frame % 12) * Game1.tex.Width/12;
}
}
public void Draw(SpriteBatch sb)
{
sb.Draw(Game1.tex, new Rectangle(100, 100, 100, 120), srcRect, Color.White);
}
}
}
|
Java
|
UTF-8
| 1,185 | 2.359375 | 2 |
[] |
no_license
|
package chromeoptions;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class example1 {
@Test
public void launch_google_chrome() { // firefoxoption, internetoption
ChromeOptions options = new ChromeOptions(); // method help to supress the notification and infobars
options.addArguments("--disable-infobars"); // we can define the size of window by window-size
options.addArguments("disable-notification");
System.setProperty("webdriver.chrome.driver",
"F:\\Software\\Selenium11-BrowserDrivers\\Selenium11-BrowserDrivers\\BrowserDrivers\\chromedriver_win32_v2_36\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver(options); // lunch browser with defined settings in option object
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("http://automationpractice.com/index.php");
//driver.quit();
}
}
|
PHP
|
UTF-8
| 3,833 | 3.078125 | 3 |
[] |
no_license
|
<?php
class User {
#### Twitter clone
private $id;
private $username;
private $hashed_password;
private $email;
static public function loadUserById(mysqli $connection, $id) {
$sql = "SELECT * FROM Users WHERE id=$id";
$result = $connection->query($sql);
if ($result == true && $result->num_rows == 1) {
$row = $result->fetch_assoc();
$loadedUser = new User();
$loadedUser->id = $row['id'];
$loadedUser->username = $row['username'];
$loadedUser->email = $row['email'];
$loadedUser->hashed_password = $row['hashed_password'];
return $loadedUser;
}return null;
}
public function savetoDB($connection) {
if ($this->id == -1) {
$sql = "INSERT INTO Users(email, username, hashed_password) "
. "VALUES ('$this->email', '$this->username', '$this->hashed_password')";
$result = $connection->query($sql);
if ($result == true) {
$this->id = $connection->insert_id;
echo "user " . $this->username . " has been created";
return true;
} else {
$sql = "SELECT * FROM Users WHERE email='$this->email'";
$result = $connection->query($sql);
if ($result->num_rows != 0) {
return true;
}
}
} else {
$sql = "UPDATE Users SET email='$this->email',"
. "username='$this->username',"
. "hashed_password='$this->hashed_password'"
. "WHERE id='$this->id'";
$result = $connection->query($sql);
if ($result == true) {
echo "user " . $this->username . ' has been modified';
return true;
}
}
}
static public function loadUserByEmail($email, mysqli $connection) {
$sql = "SELECT * FROM Users WHERE email='$email'";
$result = $connection->query($sql);
if ($result == true && $result->num_rows != 0) {
$row = $result->fetch_assoc();
$loadedUser = new User();
$loadedUser->id = $row['id'];
$loadedUser->username = $row['username'];
$loadedUser->email = $row['email'];
$loadedUser->hashed_password = $row['hashed_password'];
return $loadedUser;
}return null;
}
public function __construct() {
$this->id = -1;
$this->username = "";
$this->hashed_password = "";
$this->email = "";
}
function getId() {
return $this->id;
}
function getUsername() {
return $this->username;
}
function getHashed_password() {
return $this->hashed_password;
}
function setHashed_password($hashed_password) {
$this->hashed_password = $hashed_password;
}
function getEmail() {
return $this->email;
}
function setId($id) {
$this->id = $id;
}
function setUsername($username) {
$this->username = $username;
}
function setEmail($email) {
$this->email = $email;
}
static public function loadAllUsers(mysqli $connection){
$sql="SELECT * from Users";
$users=array();
$result=$connection->query($sql);
if($result==true&&$result->num_rows!=0){
foreach($result as $row){
$loadedUser = new User();
$loadedUser->id = $row['id'];
$loadedUser->username = $row['username'];
$loadedUser->email = $row['email'];
$loadedUser->hashed_password = $row['hashed_password'];
$users[]=$loadedUser;
}
}
return $users;
}
}
?>
|
Java
|
UTF-8
| 122 | 1.945313 | 2 |
[] |
no_license
|
package com.microservice_pokemon.data.interfaces;
public interface CustomType {
int getId();
String getName();
}
|
Python
|
UTF-8
| 324 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
#autor : Tomas E. García Fernández
#email : tomas.garcia.fisica@gmail.com
# tomas.garcia.fisica@hotmail.com
#Linkedin: www.linkedin.com/in/tomas-garcia-fisica
# Desarrollo en PROCESO
import pickle
def Cargar(name):
"""Cargar archivos"""
with open (name, "rb") as hand:
dic=pickle.load(hand)
return dic
if __name__=="__main__":
print("Ejecutado manualmente")
|
Java
|
GB18030
| 1,890 | 3.953125 | 4 |
[] |
no_license
|
package _62_uniquePath;
public class uniquePaths {
//method 1: recursion method, however, it will too long to get the result, time limit extended
public static int uniquePaths(int m, int n) {
if(m < 1 || n < 1) return 0;
if(m == 1 || n == 1) return 1;
return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}
//method 2: Ź㷨ؼ֪result[i][j] = result[i - 1][j] + result[i][j - 1]
public int uniquePaths2(int m, int n) {
int[][] result = new int[m][n];
for(int i = 0; i < n; i++){
result[0][i] = 1;
}
for(int i = 0; i < m; i++){
result[i][0] = 1;
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
result[i][j] = result[i - 1][j] + result[i][j - 1];
}
}
return result[m - 1][n - 1];
}
//method3: N = m + n - 2յղȷģ K = m - 1صҪƵIJҲȷģԿԼΪ⣬n + m - 2ѡ m - 1
public int uniquePaths3(int m, int n) {
if(m < 1 || n < 1) return 0;
if(m == 1 || n == 1) return 1;
int N = m + n - 2;
int K = m - 1;
return combination(N, K);
}
public static int combination(int N, int K){
double res = 1;
for(int i = 1; i <= K; i++){
res = res*(N - K + i)/i;
}
return (int)res;
}
public int permutation(int N, int K){
double res = 1;
for(int i = 1; i <= K; i++ ){
res = res*(N - K + i);
}
return (int)res;
}
public static void main(String[] args) {
// TODO Զɵķ
int m = 23;
int n = 12;
System.out.println(uniquePaths(m, n));
int N = 33;
int K = 22;
System.out.println(combination(N, K));
}
}
|
Java
|
UTF-8
| 589 | 3.109375 | 3 |
[] |
no_license
|
package twenty_Twenty;
import java.util.Scanner;
import java.util.TreeSet;
public class Twenty {
TreeSet<String>treeSet=new TreeSet<>();
public Twenty(String string) {
// TODO Auto-generated constructor stub
String[] tokens=string.split(" ");
for (String token : tokens) {
token=token.toLowerCase();
treeSet.add(token);
}
for (String token : treeSet) {
System.out.println(token);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
Twenty twenty=new Twenty(input.nextLine());
}
}
|
C++
|
SHIFT_JIS
| 7,141 | 3.578125 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <future>//p
#include <thread>//X[vp
#include <chrono>//Ԍvp
#include <vector>//eXgvZp
#include <algorithm>//eXgvZp
//vZpA
int calcSubA()
{
//Ԃ̂鏈̃X[v
std::this_thread::sleep_for(std::chrono::milliseconds(10));
return 1;
}
//vZpB
int calcSubB()
{
//Ԃ̂鏈̃X[v
std::this_thread::sleep_for(std::chrono::milliseconds(10));
return 2;
}
//vZpC
int calcSubC()
{
//Ԃ̂鏈̃X[v
std::this_thread::sleep_for(std::chrono::milliseconds(10));
return 3;
}
//ʏ
void testNormalCalc()
{
//ԌvJn
auto begin = std::chrono::high_resolution_clock::now();
//
int result = 0;
static const int TEST_TIMES = 100;
for (int i = 0; i < TEST_TIMES; ++i)
{
result += (calcSubA() + calcSubB() + calcSubC());
}
//ԌvI
auto end = std::chrono::high_resolution_clock::now();
auto duration = static_cast<float>(static_cast<double>(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.);
//ʕ\
printf("----------------------------------------\n");
printf("subNormalCalc: result = %d (%.6f sec)\n", result, duration);
}
//
void testAsyncCalc()
{
//ԌvJn
auto begin = std::chrono::high_resolution_clock::now();
//
int result = 0;
static const int TEST_TIMES = 100;
for (int i = 0; i < TEST_TIMES; ++i)
{
//(future)ɌʂԂŎs
std::future<int> r1 = std::async(calcSubA),
r2 = std::async(calcSubB),
r3 = std::async(calcSubC);
//.get()\bh́Å҂ČʂԂ
result += (r1.get() + r2.get() + r3.get());
}
//ԌvI
auto end = std::chrono::high_resolution_clock::now();
auto duration = static_cast<float>(static_cast<double>(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.);
//ʕ\
printf("----------------------------------------\n");
printf("subAsyncCalc: result = %d (%.6f sec)\n", result, duration);
}
//ypz
void testAsyncCalcEx()
{
//Xg쐬
static const int LIST_MAX = 10000000;
std::vector<int> list_org;
list_org.reserve(LIST_MAX);
for (int i = 0; i < LIST_MAX; ++i)
{
list_org.push_back(i);
}
//XgVbt
std::random_shuffle(list_org.begin(), list_org.end());
//̎_̃Xg\
printf("----------------------------------------\n");
printf("subAsyncCalcEx: before\n");
printf("list =");
std::for_each(list_org.begin(), list_org.begin() + 10, [](int val){printf(" %d", val); });
printf(" ... ");
std::for_each(list_org.end() - 10, list_org.end(), [](int val){printf(" %d", val); });
printf("\n");
//ʏ\[g
{
//ԌvJn
auto begin = std::chrono::high_resolution_clock::now();
//FVbtς݃XgRs[
std::vector<int> list = list_org;
//NCbN\[g
std::sort(list.begin(), list.end());
//ԌvI
auto end = std::chrono::high_resolution_clock::now();
auto duration = static_cast<float>(static_cast<double>(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.);
//ʕ\
printf("----------------------------------------\n");
printf("subAsyncCalcEx: normal-sort: result (%.6f sec):\n", duration);
printf("list =");
std::for_each(list.begin(), list.begin() + 10, [](int val){printf(" %d", val);});
printf(" ... ");
std::for_each(list.end() - 10, list.end(), [](int val){printf(" %d", val); });
printf("\n");
}
//Ń\[g
//ʂɃobt@
{
//ԌvJn
auto begin = std::chrono::high_resolution_clock::now();
//FVbtς݃XgRs[
std::vector<int> list = list_org;
const int list_size = list.size();
//4ŕNCbN\[g
std::future<void> r_a[4];
{
//ɂ́A|C^[ȊOɂAIuWFNg_nƂł
auto sort_lambda = [&list](const int index, const int list_begin, const int list_end)
{
std::vector<int>::iterator ite_begin = list.begin() + list_begin;
std::vector<int>::iterator ite_end = list.begin() + list_end;
std::sort(ite_begin, ite_end);
};
r_a[0] = std::async(sort_lambda, 0, list_size / 4 * 0, list_size / 4 * 1);
r_a[1] = std::async(sort_lambda, 1, list_size / 4 * 1, list_size / 4 * 2);
r_a[2] = std::async(sort_lambda, 2, list_size / 4 * 2, list_size / 4 * 3);
r_a[3] = std::async(sort_lambda, 3, list_size / 4 * 3, list_size);
}
//2ŕ}[W\[g
std::future<void> r_b[2];
{
//ɂ́A|C^[ȊOɂAIuWFNg_nƂł
auto merge_sort_lambda = [&r_a, &list](const int index, const int list_begin, const int list_mid, const int list_end)
{
r_a[index * 2 + 0].wait();
r_a[index * 2 + 1].wait();
std::vector<int>::iterator ite_begin = list.begin() + list_begin;
std::vector<int>::iterator ite_mid = list.begin() + list_mid;
std::vector<int>::iterator ite_end = list.begin() + list_end;
std::inplace_merge(ite_begin, ite_mid, ite_end);//̃Xg}[W\[gꍇɂ std::merge() g
};
r_b[0] = std::async(merge_sort_lambda, 0, list_size / 2 * 0, list_size / 2 * 0 + list_size / 4, list_size / 2 * 1);
r_b[1] = std::async(merge_sort_lambda, 1, list_size / 2 * 1, list_size / 2 * 1 + list_size / 4, list_size);
}
//}[W\[gij
{
r_b[0].wait();
r_b[1].wait();
std::vector<int>::iterator ite_begin = list.begin();
std::vector<int>::iterator ite_mid = list.begin() + list_size / 2;
std::vector<int>::iterator ite_end = list.end();
std::inplace_merge(ite_begin, ite_mid, ite_end);//̃Xg}[W\[gꍇɂ std::merge() g
}
//ԌvI
auto end = std::chrono::high_resolution_clock::now();
auto duration = static_cast<float>(static_cast<double>(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()) / 1000000.);
//ʕ\
printf("----------------------------------------\n");
printf("subAsyncCalcEx: async-sort: result (%.6f sec):\n", duration);
printf("list =");
std::for_each(list.begin(), list.begin() + 10, [](int val){printf(" %d", val); });
printf(" ... ");
std::for_each(list.end() - 10, list.end(), [](int val){printf(" %d", val); });
printf("\n");
}
}
//eXg
int main(const int argc, const char* argv[])
{
//ʏ
testNormalCalc();
//
testAsyncCalc();
//p
testAsyncCalcEx();
return EXIT_SUCCESS;
}
// End of file
|
Python
|
UTF-8
| 2,407 | 2.6875 | 3 |
[] |
no_license
|
import cv2 as cv
import numpy as np
import os
import Select_File
import Result
import tkinter as tk
from tkinter import filedialog
haar_cascade_face = cv.CascadeClassifier("haarcascade_frontalface_default.xml")
people = []
for i in os.listdir(r"Dataset\Training"):
people.append(i)
face_recognizer = cv.face.LBPHFaceRecognizer_create(
radius=2, neighbors=8, grid_x=8, grid_y=8
)
face_recognizer.read("face_trained.yml")
q = 1
def recognize(img_path):
global q
img = cv.imread(img_path)
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_rec = haar_cascade_face.detectMultiScale(gray_img, 1.3, 7)
for (x, y, w, h) in face_rec:
faces_region_of_interest = gray_img[x : x + w, y : y + h]
label, confidence = face_recognizer.predict(faces_region_of_interest)
print(f"Label = {people[label]} with a confidence of : {confidence}")
if confidence > 100:
cv.putText(
img,
str("Face not recognized!"),
(40, 40),
cv.FONT_HERSHEY_COMPLEX,
1.0,
(0, 255, 0),
thickness=2,
)
cv.rectangle(img, (x, y), (x + w, y + h), (65, 185, 225), thickness=2)
Result.store_result(img, q)
else:
cv.putText(
img,
str(people[label]),
(40, 40),
cv.FONT_HERSHEY_COMPLEX,
1.0,
(0, 255, 0),
thickness=2,
)
cv.rectangle(img, (x, y), (x + w, y + h), (65, 185, 225), thickness=2)
Result.store_result(img, q)
q += 1
return img
user_input = input(
"Do you want to recognize single image, Press 'y' for Yes and 'n' for No\n"
)
if user_input == "y":
img_path = Select_File.select_file()
image = recognize(img_path)
cv.imshow("Output", image)
cv.waitKey(0)
cv.destroyAllWindows()
elif user_input == "n":
DIR = r"Dataset\Validation"
people = []
for i in os.listdir(DIR):
people.append(i)
for person in people:
path = os.path.join(DIR, person)
for image in os.listdir(path):
image_path = os.path.join(path, image)
recognize(image_path)
else:
print("Wrong key pressed")
|
Python
|
UTF-8
| 389 | 3.4375 | 3 |
[] |
no_license
|
import math
ax = float(raw_input("Ax="))
ay = float(raw_input("Ay="))
bx = float(raw_input("Bx="))
by = float(raw_input("By="))
theta = math.atan2(ay, ax) - math.atan2(by, bx)
print "theta=" + str(theta)
da = math.sqrt(ax*ax + ay*ay)
db = da * math.cos(theta)
thetab = math.atan2(by, bx)
px = db * math.cos(thetab)
py = db * math.sin(thetab)
print "(" + str(px) + "," + str(py) + ")"
|
Java
|
UTF-8
| 4,984 | 1.8125 | 2 |
[] |
no_license
|
/*
* Copyright (C) 2014 Joseph Areeda <joseph.areeda at ligo.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.fullerton.ldvplugin;
import com.areeda.jaDatabaseSupport.Database;
import edu.fullerton.jspWebUtils.Page;
import edu.fullerton.jspWebUtils.PageItem;
import edu.fullerton.jspWebUtils.PageItemList;
import edu.fullerton.jspWebUtils.PageItemString;
import edu.fullerton.jspWebUtils.WebUtilException;
import edu.fullerton.ldvjutils.LdvTableException;
import edu.fullerton.ldvtables.ViewUser;
import edu.fullerton.plugindefn.CrossSpectrumDefinition;
import edu.fullerton.viewerplugin.ChanDataBuffer;
import edu.fullerton.viewerplugin.PlotProduct;
import java.io.File;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
/**
*
* @author Joseph Areeda <joseph.areeda at ligo.org>
*/
public class CrossSpectrumManager extends ExternalPlotManager implements PlotProduct
{
private File tempFile;
private final CrossSpectrumDefinition csd;
private final String nameSpace="csp";
public CrossSpectrumManager(Database db, Page vpage, ViewUser vuser)
{
super(db, vpage, vuser);
width = height = 0;
csd = new CrossSpectrumDefinition();
csd.init();
}
@Override
public ArrayList<Integer> makePlot(ArrayList<ChanDataBuffer> dbuf, boolean compact) throws WebUtilException
{
try
{
if (width > 200 && height > 100)
{
String[] geom = {String.format("%1$dx%2$d", width, height)};
paramMap.put("geom", geom);
}
csd.setFormParameters(paramMap);
String cmd = csd.getCommandLine(dbuf, paramMap);
vpage.add(cmd);
vpage.addBlankLines(2);
ArrayList<Integer> ret = new ArrayList<>();
if (runExternalProgram(cmd))
{
String txtOutput = String.format("%1$s Output:<br>%2$s", getProductName(), getStdout());
vpage.add(new PageItemString(txtOutput, false));
vpage.addBlankLines(1);
txtOutput = String.format("%1$s <br>Stderr: %2$s", getProductName(), getStderr());
vpage.add(new PageItemString(txtOutput, false));
vpage.addBlankLines(1);
tempFile = csd.getTempFile();
if (tempFile != null && tempFile.canRead())
{
String desc = "";
int imgId = importImage(tempFile, "image/png", desc);
if (imgId > 0)
{
ret.add(imgId);
}
}
}
else
{
int stat = getStatus();
String stderr = getStderr();
vpage.add(String.format("%1$s returned and error: %2$d", getProductName(), stat));
vpage.addBlankLines(1);
PageItemString ermsg = new PageItemString(stderr, false);
vpage.add(ermsg);
}
return ret;
}
catch (LdvTableException ex)
{
throw new WebUtilException("Making cross spectrum plot:", ex);
}
}
@Override
public boolean isStackable()
{
return csd.getBoolAttribute("isStackable", true);
}
@Override
public boolean needsImageDescriptor()
{
return true;
}
@Override
public String getProductName()
{
return "Cross Spectrum";
}
@Override
public PageItem getSelector(String enableKey, int nSel, String[] multDisp) throws WebUtilException
{
PageItemList ret = csd.getSelector(enableKey, nSel);
tempFile = csd.getTempFile();
return ret;
}
@Override
public boolean needsDataXfer()
{
return false;
}
@Override
public void setDispFormat(String dispFormat)
{
// ignore it
}
@Override
public void setParameters(Map<String, String[]> parameterMap)
{
paramMap = new TreeMap<>();
paramMap.putAll(parameterMap);
}
@Override
public boolean hasImages()
{
return true;
}
@Override
public boolean isPaired()
{
return true;
}
@Override
public String getNameSpace()
{
return nameSpace;
}
}
|
Java
|
UTF-8
| 3,951 | 2.390625 | 2 |
[] |
no_license
|
package com.example.vijaygarg.delagain.Adapters;
/**
* Created by vijaygarg on 03/04/18.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.vijaygarg.delagain.Model.ObjectModel;
import com.example.vijaygarg.delagain.Model.SchemeModel;
import com.example.vijaygarg.delagain.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* Created by vijaygarg on 18/03/18.
*/
public class SchemeAdapter extends RecyclerView.Adapter<SchemeAdapter.MyViewHolder> {
Context context;
ArrayList<SchemeModel>arr;
DatabaseReference firebaseDatabase;
public SchemeAdapter(Context context, ArrayList<SchemeModel> arr) {
this.context = context;
this.arr = arr;
firebaseDatabase=FirebaseDatabase.getInstance().getReference();
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.view_delete_scheme,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.title.setText(arr.get(position).getTitle());
holder.discription.setText(arr.get(position).getDescription());
holder.date.setText(formatdate(arr.get(position).getDate()));
holder.removebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
removeitem(holder,position);
}
});
}
public void removeitem(final SchemeAdapter.MyViewHolder holder, final int position ){
DatabaseReference mydr=firebaseDatabase.child("schemes");
final String stitle=arr.get(position).getTitle();
final String sdate=arr.get(position).getDate();
mydr.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
for(DataSnapshot dataSnapshot2:dataSnapshot1.getChildren()){
SchemeModel schemeModel=dataSnapshot2.getValue(SchemeModel.class);
if(schemeModel.getTitle().equals(stitle)&&schemeModel.getIs_active()&&sdate.equals(schemeModel.getDate())){
dataSnapshot2.getRef().child("is_active").setValue(false);
arr.remove(position);
}
}
}
notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public int getItemCount() {
return arr.size();
}
public String formatdate(String date){
return date.substring(0,2)+"/"+date.substring(2,4)+"/"+date.substring(4);
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView title,discription,date;
Button removebtn;
public MyViewHolder(View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
discription=itemView.findViewById(R.id.discription);
date=itemView.findViewById(R.id.date);
removebtn=itemView.findViewById(R.id.btnremove);
}
}
}
|
Java
|
UTF-8
| 294 | 3.359375 | 3 |
[] |
no_license
|
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
int a = 13;
int b = 5;
System.out.println("The product of a and b is " + product(a, b));
System.out.println("1234");
}
private static int product(int a, int b) {
return a*b;
}
}
|
C++
|
UTF-8
| 22,704 | 2.578125 | 3 |
[] |
no_license
|
//
// Created by mathis on 05/04/2021.
//
#include "../Headers/General.h"
//Constructeur
General::General(const std::string &nomfichier)
:m_estOptiChemin(false)
{
t_chargeFichier fCharge;
lecturefichier(nomfichier,fCharge);
arcs.initialisation(fCharge);
lectureFichierCapacite();
}
//Méthodes
///Méthode permettant de lire le fichier data_arcs.txt
void General::lecturefichier(const std::string &nomfichier,t_chargeFichier& fCharge) {
std::ifstream fichier (nomfichier);
int temp = 0;
if(!fichier)
throw std::runtime_error( "Impossible d'ouvrir en lecture ");
fichier >> temp ; // nombre de sommets dans le graphe
arcs.setOrdre(temp);
if(fichier.fail())
throw std::runtime_error("Probleme de lecture de l'ordre du graphe");
for(int i = 0 ; i < arcs.getOrdre(); i++)
{
t_chargeSommets tempSommet;
fichier >> tempSommet.num ;
fichier >> tempSommet.nom ;
fichier >> tempSommet.altitude;
if(fichier.fail())
throw std::runtime_error("Probleme lecture pour les sommets");
fCharge.sommets.push_back(tempSommet);
}
/// Concernant le remplissage des descentes et des Bus nécéssité de rajouter une ligne vide ///
fichier >> temp;// nombre de descentes avce les types
for (int i = 0; i < temp; ++i) {
std::pair<std::string,std::vector<int>> paireDonnee;
int donnee = 0;
fichier >> paireDonnee.first;
fichier >> donnee;
paireDonnee.second.push_back(donnee);
if(fichier.fail())
throw std::runtime_error("Probleme lecture pour les descentes");
arcs.getMatriceDuree()['D'][paireDonnee.first]=paireDonnee.second;
m_optiTrajets.push_back(std::make_pair(paireDonnee.first,false));
}
fichier >> temp;// nombre de Bus
for (int i = 0; i < temp; ++i) {
std::pair<std::string,std::vector<int>> paireDonnee;
int donnee = 0;
fichier >> paireDonnee.first;
fichier >> donnee;
paireDonnee.second.push_back(donnee);
if(fichier.fail())
throw std::runtime_error("Probleme lecture pour les Bus");
arcs.getMatriceDuree()['B'][paireDonnee.first]=paireDonnee.second;
}
m_optiTrajets.push_back(std::make_pair("BUS",true));
fichier >> temp;// nombre de remontee
for (int i = 0; i < temp; ++i) {
std::pair<std::string,std::vector<int>> paireDonnee;
int donnee;
fichier >> paireDonnee.first;
fichier >> donnee;
paireDonnee.second.push_back(donnee);
fichier >> donnee;
paireDonnee.second.push_back(donnee);
if(fichier.fail())
throw std::runtime_error("Probleme lecture pour les montees");
arcs.getMatriceDuree()['R'][paireDonnee.first]=paireDonnee.second;
m_optiTrajets.push_back(std::make_pair(paireDonnee.first,true));
}
fichier >> temp; // nombre d'arcs dans le graphe
arcs.setTaille(temp);
if ( fichier.fail() )
throw std::runtime_error("Probleme lecture taille du graphe");
for (int i = 0; i < arcs.getTaille(); ++i) {
t_chargeTrajet tempTrajet;
fichier >> tempTrajet.num;
fichier >>tempTrajet.nom;
fichier >> tempTrajet.type;
fichier >> tempTrajet.depart;
fichier >> tempTrajet.arrivee;
if(fichier.fail())
throw std::runtime_error("Probleme lecture nom d'une sommet");
fCharge.trajets.push_back(tempTrajet);
}
}
///Methode permettant de lire le fichier capacité
void General::lectureFichierCapacite() {
std::ifstream fichier ("../capacite.txt");
int taille;
if(!fichier)
throw std::runtime_error( "Impossible d'ouvrir en lecture ");
fichier >> taille;
for(int i = 0 ; i< taille ; i++)
{
std::pair <std::string, int> temp;
fichier >> temp.first;
fichier >> temp.second;
arcs.setVecteurCapacite(temp);
}
fichier.close();
}
///Methode permettant de connecter l'utilisateur au lancement de la borne
void General::connection(){
std::string pseudoInput;
print("Bonjour ! ",color_red);
std::cout << std::endl;
arcs.horaire();
std::cout <<std::endl
<<std::endl
<<"Veuillez renseigner votre ";
print("pseudo ",color_dark_green);
std::cout <<"(pas d'espace): ";
std::cin >> pseudoInput;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
bool dejaInscript = m_baseUtilisateur.pseudoExiste(pseudoInput);
if(!dejaInscript){
m_profilActif = m_baseUtilisateur.ajoutProfil(pseudoInput);
}
else
m_profilActif= m_baseUtilisateur.getProfil(pseudoInput);
//Changer les préférences des trajets optis
for(auto& elem : m_optiTrajets){
bool aEviter=false;
for(auto& elem2 : m_profilActif->getPrefTrajets()){
if(elem2 == elem.first)
aEviter=true;
}
elem.second=aEviter;
}
std::system("cls || clear");
std::cout << "Bonjour " ;
print(m_profilActif->getProfil().first,color_green);
std::cout << "!" << std::endl;
if(dejaInscript){
std::cout << "Votre compte a bien ete charge avec vos preferences! " << std::endl;
if(m_profilActif->getProfil().second){
std::cout << "Vous etes ";
print("administrateur",color_dark_red);
std::cout << " de cette borne" << std::endl;
}
}
else
std::cout << "Votre compte a bien ete cree! " << std::endl;
finProgrammeActu("Appuyez sur entree.............");
}
///Méthode principal du projet permettant d'intéragir et d'afficher les menus
void General::boucle(){
int menuActu=1;
while(menuActu!=0){
std::system("clear || cls");
afficheMenu(menuActu);
std::cout <<std::endl<< "Menu n'" ;
std::string donnee;
std::cin >> donnee;
std::system("clear || cls");
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
interactionDonnee(donnee,menuActu);
}
}
void General::finProgrammeActu(const std::string& phrase){
std::cout << std::endl;
print(phrase,color_dark_green);
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
/// Interaction menu ///
void General::interactionDonnee(const std::string &donnee, int &menuActu) {
if(donnee=="q")
menuActu=0;
else{
switch(menuActu){
case 1:
interactionDonneeMenu1(donnee,menuActu);
break;
case 2:
interactionDonneeMenu2(donnee,menuActu);
break;
case 3:
interactionDonneeMenu3(donnee,menuActu);
break;
case 4:
interactionDonneeMenu4(donnee,menuActu,true);
break;
case 5:
interactionDonneeMenu4(donnee,menuActu,false);
break;
case 6:
interactionDonneeMenu6(donnee,menuActu);
break;
case 7:
interactionDonneeMenu7(donnee,menuActu);
break;
case 11:
interactionDonneeMenu11(donnee,menuActu);
break;
case 20 :
interactionDonneeAdmin(donnee,menuActu);
break;
}
}
}
void General::interactionDonneeMenu1(const std::string& donnee, int& menuActu){
if(donnee.size()==1){
switch(donnee[0]){
case '1':
arcs.afficheInfo();
finProgrammeActu();
break;
case '2':
if(arcs.changementDuree())
finProgrammeActu();
break;
case '3':
menuActu=2;
break;
case '4':
menuActu =3;
break;
case '5':
menuActu=6;
setEstOptiChemin(false);
break;
case '6':
menuActu=7;
setEstOptiChemin(true);
break;
case '7':
menuActu=11;
break;
}
}
if((donnee=="a" || donnee=="A" ) && m_profilActif->getProfil().second){ //si admin
menuActu=20;
}
}
void General::interactionDonneeMenu2(const std::string& donnee, int& menuActu){
if(donnee.size()==1){
switch(donnee[0]){
case '0':
menuActu=1;
break;
case '1':
arcs.afficheSommets();
finProgrammeActu();
break;
case '2':
std::string numSommet;
arcs.afficheSommets(numSommet);
finProgrammeActu();
break;
}
}
}
void General::interactionDonneeMenu3(const std::string& donnee, int& menuActu){
if(donnee.size()==1){
switch(donnee[0]){
case '0':
menuActu=1;
break;
case '1':
arcs.afficheTrajets();
finProgrammeActu();
break;
case '2':
arcs.afficheTrajets('D');
finProgrammeActu();
break;
case '3':
arcs.afficheTrajets('R');
finProgrammeActu();
break;
case '4':
arcs.afficheTrajets('B');
finProgrammeActu();
break;
case '5':
std::string numTrajet;
std::cout << "Nom ou numero du trajet: ";
std::getline (std::cin,numTrajet);
arcs.afficheTrajets('T',numTrajet);
finProgrammeActu();
break;
}
}
}
void General::interactionDonneeMenu4(const std::string& donnee, int& menuActu,const bool& estDijkstra){
if(donnee.size()==1){
switch(donnee[0]){
case '0':
menuActu=6;
break;
case '1':{
int s = arcs.entreePoint("Nom ou numero du point initial: ");
std::cout << std::endl;
arcs.plusCourtChemin(estDijkstra,getEstOptiChemin(),getOptiTrajets(),s);
finProgrammeActu();
break;
}
case '2':{
int s0 = arcs.entreePoint("Nom ou numero du point initial: ");
int sF = arcs.entreePoint("Nom ou numero du point final: ");
std::cout << std::endl;
arcs.plusCourtChemin(estDijkstra,getEstOptiChemin(),getOptiTrajets(),s0,sF);
finProgrammeActu();
break;
}
}
}
}
void General::interactionDonneeMenu6(const std::string& donnee, int& menuActu){
if(donnee.size()==1){
switch(donnee[0]){
case '0':{
if(getEstOptiChemin())
menuActu=7;
else
menuActu=1;
break;
}
case '1':{
menuActu=4;
break;
}
case '2':{
menuActu=5;
break;
}
}
}
}
void General::interactionDonneeMenu11(const std::string& donnee,int& menuActu) {
if(donnee.size()==1){
switch(donnee[0]){
case '0':
menuActu=1;
break;
case '1':
arcs.interactionCapaciteFlot(m_profilActif->getProfil().second);
break;
case '2':
int s0 = arcs.entreePoint("Nom ou numero de la source: ");
int sF = arcs.entreePoint("Nom ou numero du puit: ");
arcs.algosQuatreSix(s0,sF);
break;
}
}
}
void General::interactionDonneeMenu7(const std::string& donnee, int& menuActu){
if(donnee.size()==1){
switch(donnee[0]){
case '0':
menuActu=1;
break;
case '1':
modifierOptiTrajets();
break;
case '2':
menuActu=6;
break;
}
}
}
void General::interactionDonneeAdmin(const std::string& donnee,int& menuActu){
if(donnee.size()==1){
switch(donnee[0]){
case '0':
menuActu=1;
break;
case '1':
arcs.modifCapaciteAdmin();
break;
}
}
}
/// Affichage Menu ///
void General::afficheMenu(const int& menuActu){
std::cout << "q : Quitter le programme" <<std::endl;
switch(menuActu){
case 1:
menu1();
break;
case 2:
menu2();
break;
case 3:
menu3();
break;
case 4:
menu4(true);
break;
case 5:
menu4(false);
break;
case 6:
menu6();
break;
case 7:
menu7();
break;
case 11://Menu affcihage capacité
menu11();
break;
case 20:
menuAdminAffichage();
break;
}
}
void General::menu1(){
std::cout << std::endl <<"----------------------------------" << std::endl;
print(" Domaine skiable des arcs ",color_dark_blue);
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << std::endl <<"1 : A propos du domaine skiable des Arcs" << std::endl;
std::cout << "2 : Afficher/Modifier les temps par default des trajets (4.1)" << std::endl;
std::cout << "3 : A propos des points (4.3)" << std::endl;
std::cout << "4 : A propos des trajets (4.3)" << std::endl;
std::cout << "5 : Plus courts chemins (4.4)" << std::endl;
std::cout << "6 : Plus courts chemins selon vos preferences (4.5)" << std::endl;
std::cout << "7 : A propos des flots (4.6)" << std::endl;
if(m_profilActif->getProfil().second){//Si est admin
std::cout << std::endl;
print("A : Pannel admin" ,color_dark_red);
std::cout << std::endl;
}
}
void General::menu2(){
std::cout << "0 : Retour en arriere" << std::endl;
std::cout << std::endl <<"----------------------------------" << std::endl;
print(" A propos des points ",color_dark_blue);
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << std::endl <<"1 : Afficher tous les points" << std::endl;
std::cout << "2 : Information sur 1 point" << std::endl;
}
void General::menu3(){
std::cout << "0 : Retour en arriere" << std::endl;
std::cout << std::endl <<"----------------------------------" << std::endl;
print( " A propos des trajets ",color_dark_blue);
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout <<std::endl << "1 : Afficher tous les trajets" << std::endl;
std::cout << "2 : Afficher toutes les pistes" << std::endl;
std::cout << "3 : Afficher toutes les remontees" << std::endl;
std::cout << "4 : Afficher toutes les navettes" << std::endl;
std::cout << "5 : Information sur 1 trajet" << std::endl;
}
void General::menu4(const bool& estDijkstra){
std::string phraseOpti;
if(getEstOptiChemin())
phraseOpti=" avec optimisation\n";
std::cout << "0 : Retour en arriere" << std::endl;
std::cout << std::endl <<"----------------------------------" << std::endl;
if(estDijkstra){
print( " En temps ",color_dark_blue);
std::cout << std::endl;
}
else{
print( " En nombre de trajets",color_dark_blue);
std::cout << std::endl;
}
print( phraseOpti,color_dark_blue);
std::cout << "----------------------------------" << std::endl;
std::cout << std::endl <<"1 : Tous les plus courts chemin en partant d'un point" << std::endl;
std::cout << "2 : Plus court chemin entre 2 points" << std::endl;
}
void General::menu6(){
std::string phraseOpti;
if(getEstOptiChemin())
phraseOpti=" avec optimisation \n";
std::cout << "0 : Retour en arriere" << std::endl;
std::cout << std::endl <<"----------------------------------" << std::endl;
print( " Plus court chemin " ,color_dark_blue);
std::cout << std::endl;
print( phraseOpti ,color_dark_blue);
std::cout << "----------------------------------" << std::endl;
std::cout << std::endl <<"1 : Plus court chemin en temps" << std::endl;
std::cout << "2 : Plus court chemin en nombre de trajets" << std::endl;
}
void General::menu11() {
std::cout << "0 : Retour en arriere" << std::endl;
std::cout << std::endl <<"----------------------------------" << std::endl;
print( " Etudes des flots des skieurs " ,color_dark_blue);
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << std::endl <<"1 : Afficher les capacites des trajets" << std::endl;
std::cout << "2 : Trouver le flot maximal entre 2 points" << std::endl;
}
void General::menuAdminAffichage(){
std::cout << "0 : Retour en arriere" << std::endl;
std::cout << std::endl <<"----------------------------------" << std::endl;
print( " Pannel admin " ,color_dark_red);
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << "1 : Modifier les capacites" << std::endl;
}
void General::menu7(){
std::cout << "0 : Retour en arriere" << std::endl;
std::cout << std::endl <<"----------------------------------" << std::endl;
print( " Plus court chemin optimise (4.5) " ,color_dark_blue);
std::cout << std::endl;
std::cout << "----------------------------------" << std::endl;
std::cout << std::endl <<"1 : Afficher/Modifier vos preferences a l'interet des trajets" << std::endl;
std::cout << "2 : Trouver les plus courts chemins selon vos preferences" << std::endl;
}
/// Fonction Fichier concernant la capacite ///
void General::changementValeurFichierCapacite(const std::string nomFichier) {
//ouverture en mode écriture afin d'éffacer le contenu
// on réecrit le vecteur dans le fichier
std::ofstream fichier ("../"+nomFichier+".txt");
if(!fichier)
throw std::runtime_error( "Impossible d'ouvrir en ecriture ");
fichier << arcs.getVecteurCapacite().size() <<std::endl;
for(const auto& elem : arcs.getVecteurCapacite())
fichier << elem.first << " " << elem.second << std::endl;
}
///Méthode permettant d'affcher les preferences trajets
void General::afficherOptiTrajets(){
std::cout << " --------------------------------------------------------------------------------------"<<std::endl;
std::cout << " Nom du trajet A eviter?"<<std::endl;
std::cout << " --------------------------------------------------------------------------------------"<<std::endl;
for(const auto& elem : m_optiTrajets){
Trajet temp=Trajet(elem.first);
std::cout << " ";
print(temp.returnNomType(),temp.retourneCouleurType());
std::cout <<" ";
if(elem.second)
std::cout << "Oui";
else
std::cout << "Non";
std::cout << std::endl;
}
std::cout << std::endl<<std::endl;
}
///Méthode prmettant de modifier les preferences utilisateurs
void General::modifierOptiTrajets(){
std::string donnee;
std::string parametre;
do{
std::system("cls || clear");
afficherOptiTrajets();
std::cout << "Appuyez sur \"s\" pour revenir au menu " << std::endl;
std::cout <<"Appuyez sur \"m\" pour modifier les valeurs une par une" << std::endl;
std::cout <<"Appuyez sur \"r\" pour n\'eviter que les remontees et les navettes" << std::endl;
std::cout <<"Appuyez sur \"p\" pour n\'eviter que les pistes" << std::endl<<std::endl;
std::cout << "Votre choix: ";
std::cin >> parametre;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}while(parametre!="s" && parametre!="m"&¶metre!="p" && parametre!="r");
if(parametre!="s"){
switch(parametre[0]){
case 'm':
{
for(auto& elem : m_optiTrajets){
Trajet temp= Trajet(elem.first);
do{
std::system("cls || clear");
std::cout <<"Souhaitez vous eviter: ";
print(temp.returnNomType(),temp.retourneCouleurType());
std::cout << "?" << std::endl << std::endl;
std::cout <<"Ecrire \"o\" pour \"oui\" ou \"n\" pour \"non\": ";
std::cin >> parametre;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}while(parametre!="o" && parametre!="n");
if(parametre=="o")
elem.second=true;
else
elem.second=false;
}
}
break;
case 'p':
for(auto& elem : m_optiTrajets){
Trajet temp= Trajet(elem.first);
if(temp.getGType()=='R'|| temp.getGType()=='B')
elem.second=false;
else
elem.second=true;
}
break;
case 'r':
for(auto& elem : m_optiTrajets){
Trajet temp= Trajet(elem.first);
if(temp.getGType()=='R' || temp.getGType()=='B')
elem.second=true;
else
elem.second=false;
}
break;
}
m_profilActif->prefTrajetsModification(m_optiTrajets);
m_baseUtilisateur.reecrireFichierProfil();
std::system("cls || clear");
std::cout << "Toutes vos modifications ont ete pris en compte!" << std::endl;
finProgrammeActu();
}
}
//Getters & Setters
bool General::getEstOptiChemin() const {
return m_estOptiChemin;
}
std::vector<std::pair<std::string,bool>> General::getOptiTrajets() const {
return m_optiTrajets;
}
void General::setEstOptiChemin(const bool& _valeur) {
m_estOptiChemin=_valeur;
}
|
JavaScript
|
UTF-8
| 1,527 | 2.890625 | 3 |
[] |
no_license
|
import React, { useState, useEffect } from "react";
import "./noteDetail.scss";
import 'bootstrap/dist/css/bootstrap.min.css';
//component to add new note
const UpdateNote = (props) => {
let [title, setTitle] = useState("");
let [body, setBody] = useState("");
//get notes data from localstorage, only one time.
useEffect(() => {
getNotes(props.noteId);
}, []);
const getNotes = (id) => {
if (!!localStorage.getItem('notes')) {
let data = localStorage.getItem('notes').split("\n");
//Parse each line string to an 'noteObj' Object.
//The line should be built in the following layout: 'TITLE|BODY|DATE|FOLDER' (the date is in mlseconds)
const allNotes = data.map(note => {
return {
title: note.split("|")[0],
body: note.split("|")[1],
date: note.split("|")[2],
dateStr: new Date(parseInt(note.split("|")[2])).toLocaleString(),
folder: note.split("|")[3]
}
});
//Filter only 'created' notes.
const note = allNotes.filter(item => item.date === id);
setTitle(note[0].title);
setBody(note[0].body);
}
}
// form to add new note
return (
<div className="form-row">
<div className="col-md-12 mb-3 note-card">
<div className="card">
<div className="card-body">
<h5 className="card-title">{title}</h5>
<p className="card-text">{body}</p>
</div>
</div>
</div>
</div>
);
};
export default UpdateNote;
|
C++
|
UTF-8
| 9,900 | 3.125 | 3 |
[] |
no_license
|
#include "Header.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <random>
#include <list>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
std::default_random_engine generator;
float GaussianLaw (float t)
{
return erf(t/sqrt(2))/2 - erf(-1000000000)/2;
}
float generateGaussianRandomValue()
{
std::normal_distribution<float> distribution(0.0, 1.0);
float randomValue = distribution(generator);
return randomValue;
}
float generateUniformRandomValue()
{
std::uniform_real_distribution<float> distribution(0.0, 1.0);
float randomValue = distribution(generator);
return randomValue;
}
float uniformLaw(float inf, float sup)
{
std::uniform_real_distribution<float> distribution(inf, sup);
float randomValue = distribution(generator);
return randomValue;
}
vector<float> generateGaussianRandomVector(int N)
{
vector<float> x(N);
for (int i=0; i<N; i++)
{
x[i]= generateGaussianRandomValue();
}
return x;
}
float norme2(std::vector<float> x)
{
float a=0;
for (int i=0; i<x.size(); i++)
{
a+= pow(x[i],2) ;
}
return sqrt(a);
}
float norme(std::vector<float> x, std::vector<float> y)
{//x and y must have same dimension
float a= x.size();
return std::max(norme2(x)/sqrt(a),norme2(y)/sqrt(a));
}
float BlackScholes(float S, float sigma, float t, float r, float K)
{
float d1= 1/(sigma*sqrt(t))*(log(S/K)+(r+sigma*sigma/2)*t);
float d2= 1/(sigma*sqrt(t))*(log(S/K)+(r-sigma*sigma/2)*t);
return (S*GaussianLaw(d1)-K*exp(-r*t)*GaussianLaw(d2));
}
//European call pricing with Monte-Carlo
float montecarlo(int nbpaths,float S,float sigma,float t,float r,float K)
{
float x=0;
float St;
float payoff;
for (int i=0; i<nbpaths; i++){
St= S * exp((r-sigma*sigma/2.0)*t + sigma*sqrt(t)*generateGaussianRandomValue());
payoff= exp(-r*t) * std::max(St-K,float(0.));
x += payoff;
}
float price= x/nbpaths;
return price;
}
//European call pricing with Monte-Carlo (with variance computation)
float montecarlo_call(int nbpaths, float S, float sigma, float t, float r, float K, float &sig)
{
float x=0, x2=0;
float St;
float payoff;
for (int i=0; i<nbpaths; i++){
St= S * exp((r-sigma*sigma/2.0)*t + sigma*sqrt(t)*generateGaussianRandomValue());
payoff= exp(-r*t) * std::max(St-K,float(0.));
x += payoff;
x2 += payoff*payoff;
}
float price = x/nbpaths ;
sig = x2/nbpaths - price*price;
return price;
}
//Simulation of stock-path with Monte-Carlo
void simulation_stockpath(int N, float S, float sigma, float t, float r, float M, float &ST, float &maxi, float &avg)
{
float stock[N+1];
float x= S;
stock[0]= S;
maxi= S;
for (int i=1; i<=N; i++)
{
stock[i]= stock[i-1] * exp((r-sigma*sigma/2.0)*t/N + sigma*sqrt(t/N)*generateGaussianRandomValue());
x += stock[i];
if (stock[i]>maxi)
{
maxi= stock[i];
}
}
ST= stock[N];
avg= x/(N+1);
}
//Piricing of asian call option with Monte-Carlo
float MC_asiatique(int nbpaths, int N, float S, float sigma, float t, float r, float K, float &sig)
{
float x=0, x2=0;
float payoff;
float ST, maxi, avg;
for (int i=0; i<nbpaths; i++)
{
simulation_stockpath(N,S,sigma,t,r,0,ST,maxi,avg);
payoff= exp(-r*t) * std::max(avg-K,float(0.));
x += payoff;
x2 += payoff*payoff;
}
float price= x/nbpaths;
sig= x2/nbpaths - price*price;
return price;
}
//Monte-Carlo for European Call with variance reduction technique (antithetic variables)
float MC_call_antithetique(int nbpaths, float S, float sigma, float t, float r, float K, float &sig)
{
float x=0, x1=0, x2=0, sum1=0, sum2=0, sum_cov=0;
float St_1, St_2, payoff1, payoff2;
for (int i=0; i<nbpaths; i++)
{
float Z= generateGaussianRandomValue();
St_1= S * exp((r-sigma*sigma/2.0)*t + sigma*sqrt(t)*Z);
payoff1= exp(-r*t) * std::max(St_1-K,float(0.));
St_2= S * exp((r-sigma*sigma/2.0)*t + sigma*sqrt(t)*(-Z));
payoff2= exp(-r*t) * std::max(St_2-K,float(0.));
x += 0.5*(payoff1+payoff2);
x1 += payoff1;
sum1 += payoff1*payoff1;
x2 += payoff2;
sum2 += payoff2*payoff2;
sum_cov += payoff1*payoff2;
}
float var_1= sum1/nbpaths - (x1/nbpaths)*(x1/nbpaths);
float var_2= sum2/nbpaths - (x2/nbpaths)*(x2/nbpaths);
float cov_1_2= sum_cov/nbpaths - (x1/nbpaths)*(x2/nbpaths);
sig= 0.25*(var_1 + var_2 + 2*cov_1_2);
float price= x/nbpaths;
return price;
}
//Stock-path simulation with antithetic variables technique
void simulation_stockpath_antithetique(int N, float S, float sigma, float t, float r, float &avg1, float &avg2)
{
float stock1[N], stock2[N];
float sum1= S, sum2= S;
stock1[0]= S;
stock2[0]= S;
for (int i=1; i<N; i++){
float Z= generateGaussianRandomValue();
stock1[i] = stock1[i-1] * exp((r-sigma*sigma/2.0)*t/N + sigma*sqrt(t/N)*Z);
sum1 += stock1[i];
stock2[i] = stock2[i-1] * exp((r-sigma*sigma/2.0)*t/N + sigma*sqrt(t/N)*(-Z));
sum2 += stock2[i];
}
avg1 = sum1/N;
avg2= sum2/N;
}
//Asian option pricing with Monte-Carlo with antithetic variables
float MC_asiatique_antithetique(int nbpaths, int N, float S, float sigma, float t, float r, float K, float &sig)
{
float x=0, x2=0;
float S1, S2, payoff1, payoff2;
for (int i=0; i<nbpaths; i++)
{
simulation_stockpath_antithetique(N,S,sigma,t,r,S1,S2);
payoff1= exp(-r*t) * std::max(S1-K,float(0.));
payoff2= exp(-r*t) * std::max(S2-K,float(0.));
x += 0.5*(payoff1+payoff2);
x2 += (0.5*(payoff1+payoff2))*(0.5*(payoff1+payoff2));
}
float price= x/nbpaths;
sig= x2/nbpaths - price*price;
return price;
}
//Asian call option pricing with Monte-Carlo using control variable Z=ST
float MC_asiatique_controle1(int nbpaths, int N, float S, float sigma, float t, float r, float K, float &sig)
{
float x=0, x2=0, sum_payoff=0, sum_cov=0;
float payoff, ST, maxi, avg;
/* Compute Cov(h(X),Z) by Monte-Carlo, with h(X)=payoff and Z=ST */
for (int j=0; j<1000; j++)
{
simulation_stockpath(N,S,sigma,t,r,0,ST,maxi,avg);
payoff= exp(-r*t) * std::max(avg-K,float(0.));
sum_payoff += payoff;
sum_cov += payoff*ST;
}
float cov= (sum_cov/1000) - (S*exp(r*t))*(sum_payoff/1000);
/* Compute Var(Z) with Z following a log-normal distribution (mu, s2) */
float mu= log(S) + (r-sigma*sigma/2)*t;
float s2= sigma*sigma*t;
float varZ= (exp(s2) - 1) * exp(2*mu + s2);
float c= -cov/varZ;
/* Compute price and variance of option */
for (int i=0; i<nbpaths; i++)
{
simulation_stockpath(N,S,sigma,t,r,0,ST,maxi,avg);
payoff = exp(-r*t) * std::max(avg-K,float(0.));
x += (payoff + c*(ST-S*exp(r*t)));
x2 += (payoff + c*(ST-S*exp(r*t)))*(payoff + c*(ST-S*exp(r*t)));
}
float price= x/nbpaths;
sig= x2/nbpaths - price*price;
return price;
}
//Asian call option pricing with Monte-Carlo using control variable Z=AVERAGE(S)
float MC_asiatique_controle2(int nbpaths, int N, float S, float sigma, float t, float r, float K, float &sig)
{
float x=0, x2=0, sum_esp=0, sum_payoff=0, sum_avg=0, sum_cov=0, sum_var=0;
float payoff, ST, maxi, avg;
/* Compute E(Z) */
for (int k=1; k<=N; k++)
{
sum_esp += exp(r*k*t/N);
}
float espZ= S*(1+sum_esp)/(N+1);
/* Compute cov(h(X),Z) by Monte-Carlo, with h(X)=payoff and Z=avg */
for (int j=0; j<10000 ; j++)
{
simulation_stockpath(N,S,sigma,t,r,0,ST,maxi,avg);
payoff= exp(-r*t) * std::max(avg-K,float(0.));
sum_payoff += payoff;
sum_avg += avg;
sum_cov += avg*payoff;
sum_var += avg*avg;
}
float cov= sum_cov/10000 - (sum_payoff/10000)*espZ;
float varZ= sum_var/10000 - espZ*espZ;
float c= -cov/varZ;
/* Compute price and variance of option */
for (int i=0; i<nbpaths; i++)
{
simulation_stockpath(N,S,sigma,t,r,0,ST,maxi,avg);
payoff= exp(-r*t) * std::max(avg-K,float(0.));
x += (payoff + c*(avg-espZ));
x2 += (payoff + c*(avg-espZ))*(payoff + c*(avg-espZ));
}
float price= x/nbpaths;
sig= x2/nbpaths - price*price;
return price;
}
//Asian call option pricing with Monte-Carlo using control variable Z= MAX(ST-K,0)
float MC_asiatique_controle3(int nbpaths, int N, float S, float sigma, float t, float r, float K, float &sig)
{
float x=0, x2=0, sum_payoff=0, sum_cov=0, sum_var=0;
float payoff, ST, maxi, avg, Z;
/* Calcul de cov(h(X),Z) par Monte-Carlo, avec h(X)=payoff et Z=MAX(ST-K,0) */
for (int j=0; j<100000; j++)
{
simulation_stockpath(N,S,sigma,t,r,0,ST,maxi,avg);
payoff= exp(-r*t) * std::max(avg-K,float(0.));
Z= exp(-r*t) * std::max(ST-K,float(0.));
sum_payoff += payoff;
sum_cov += Z*payoff;
sum_var += Z*Z;
}
float espZ= BlackScholes(S,sigma,t,r,K);
float varZ= (sum_var/100000) - espZ*espZ;
float cov= (sum_cov/100000) - espZ*(sum_payoff/100000);
float c= -cov/varZ;
/* Calcul du prix et de la variance de l'option asiatique */
for (int i=0; i<nbpaths; i++)
{
simulation_stockpath(N,S,sigma,t,r,0,ST,maxi,avg);
payoff= exp(-r*t) * std::max(avg-K,float(0.));
Z= exp(-r*t) * std::max(ST-K,float(0.));
x += (payoff + c*(Z-espZ));
x2 += (payoff + c*(Z-espZ))*(payoff + c*(Z-espZ));
}
float price= x/nbpaths;
sig = x2/nbpaths - price*price;
return price;
}
|
C
|
UTF-8
| 372 | 3.671875 | 4 |
[] |
no_license
|
/* FILE: Lab 3
* Factoring if/else code
* Author: Jason Ang Chia Wuen
* Last Modified: 11:50 am 19/3/2018
*/
#include <stdio.h>
int main()
{
int num;
int x;
int b = 0;
int y = 0;
printf("num =");
scanf("%i", &num);
if (num == 1)
{
x = 3;
}
else if (num == 2)
{
x = 6;
y = y + 10;
}
else
{
x = 9;
}
b = b + x;
printf("%i", num);
return 0;
}
|
Java
|
UTF-8
| 5,849 | 2.296875 | 2 |
[] |
no_license
|
/*
* Decompiled with CFR 0.145.
*/
package sun.misc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
public abstract class CharacterEncoder {
protected PrintStream pStream;
private byte[] getBytes(ByteBuffer byteBuffer) {
byte[] arrby;
byte[] arrby2 = arrby = null;
if (byteBuffer.hasArray()) {
byte[] arrby3 = byteBuffer.array();
arrby2 = arrby;
if (arrby3.length == byteBuffer.capacity()) {
arrby2 = arrby;
if (arrby3.length == byteBuffer.remaining()) {
arrby2 = arrby3;
byteBuffer.position(byteBuffer.limit());
}
}
}
arrby = arrby2;
if (arrby2 == null) {
arrby = new byte[byteBuffer.remaining()];
byteBuffer.get(arrby);
}
return arrby;
}
protected abstract int bytesPerAtom();
protected abstract int bytesPerLine();
public String encode(ByteBuffer byteBuffer) {
return this.encode(this.getBytes(byteBuffer));
}
public String encode(byte[] object) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
object = new ByteArrayInputStream((byte[])object);
try {
this.encode((InputStream)object, (OutputStream)byteArrayOutputStream);
object = byteArrayOutputStream.toString("8859_1");
return object;
}
catch (Exception exception) {
throw new Error("CharacterEncoder.encode internal error");
}
}
public void encode(InputStream inputStream, OutputStream outputStream) throws IOException {
byte[] arrby = new byte[this.bytesPerLine()];
this.encodeBufferPrefix(outputStream);
do {
block7 : {
block6 : {
int n;
if ((n = this.readFully(inputStream, arrby)) == 0) break block6;
this.encodeLinePrefix(outputStream, n);
for (int i = 0; i < n; i += this.bytesPerAtom()) {
if (this.bytesPerAtom() + i <= n) {
this.encodeAtom(outputStream, arrby, i, this.bytesPerAtom());
continue;
}
this.encodeAtom(outputStream, arrby, i, n - i);
}
if (n >= this.bytesPerLine()) break block7;
}
this.encodeBufferSuffix(outputStream);
return;
}
this.encodeLineSuffix(outputStream);
} while (true);
}
public void encode(ByteBuffer byteBuffer, OutputStream outputStream) throws IOException {
this.encode(this.getBytes(byteBuffer), outputStream);
}
public void encode(byte[] arrby, OutputStream outputStream) throws IOException {
this.encode(new ByteArrayInputStream(arrby), outputStream);
}
protected abstract void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException;
public String encodeBuffer(ByteBuffer byteBuffer) {
return this.encodeBuffer(this.getBytes(byteBuffer));
}
public String encodeBuffer(byte[] object) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
object = new ByteArrayInputStream((byte[])object);
try {
this.encodeBuffer((InputStream)object, (OutputStream)byteArrayOutputStream);
return byteArrayOutputStream.toString();
}
catch (Exception exception) {
throw new Error("CharacterEncoder.encodeBuffer internal error");
}
}
public void encodeBuffer(InputStream inputStream, OutputStream outputStream) throws IOException {
int n;
byte[] arrby = new byte[this.bytesPerLine()];
this.encodeBufferPrefix(outputStream);
while ((n = this.readFully(inputStream, arrby)) != 0) {
this.encodeLinePrefix(outputStream, n);
for (int i = 0; i < n; i += this.bytesPerAtom()) {
if (this.bytesPerAtom() + i <= n) {
this.encodeAtom(outputStream, arrby, i, this.bytesPerAtom());
continue;
}
this.encodeAtom(outputStream, arrby, i, n - i);
}
this.encodeLineSuffix(outputStream);
if (n >= this.bytesPerLine()) continue;
}
this.encodeBufferSuffix(outputStream);
}
public void encodeBuffer(ByteBuffer byteBuffer, OutputStream outputStream) throws IOException {
this.encodeBuffer(this.getBytes(byteBuffer), outputStream);
}
public void encodeBuffer(byte[] arrby, OutputStream outputStream) throws IOException {
this.encodeBuffer(new ByteArrayInputStream(arrby), outputStream);
}
protected void encodeBufferPrefix(OutputStream outputStream) throws IOException {
this.pStream = new PrintStream(outputStream);
}
protected void encodeBufferSuffix(OutputStream outputStream) throws IOException {
}
protected void encodeLinePrefix(OutputStream outputStream, int n) throws IOException {
}
protected void encodeLineSuffix(OutputStream outputStream) throws IOException {
this.pStream.println();
}
protected int readFully(InputStream inputStream, byte[] arrby) throws IOException {
for (int i = 0; i < arrby.length; ++i) {
int n = inputStream.read();
if (n == -1) {
return i;
}
arrby[i] = (byte)n;
}
return arrby.length;
}
}
|
PHP
|
UTF-8
| 2,760 | 2.671875 | 3 |
[] |
no_license
|
<?php
require_once("../../includes/database.php");
require_once("../../includes/user.php");
require_once("../../includes/helper.php");
require_once("../../includes/session.php");
$photo_ok = false;
$photo = '';
if (isset($_POST['save'])) {
$user = new User;
$file = $_FILES['photo']['name'];
if (!empty($file)) {
$type = $_FILES['photo']['type'];
$photo_ok = typeGambar($type);
$size = $_FILES['photo']['size'];
if ($photo_ok && ($size <= 2000000)) {
$photo = create_image("photo");
}
}
$user->nama = $_POST['nama'];
$user->namabelakang = $_POST['namabelakang'];
$user->photo = $photo;
$user->email = $_POST['email'];
$user->password = $_POST['password'];
$hasil = $user->create();
if ($hasil) {
$session->login($hasil);
$session->nama($user->nama);
$pesan = "Hi, " . $user->nama . " Welcome.";
$session->pesan($pesan);
redirect_ke("http://localhost/social-media/public/");
} else {
redirect_ke("http://localhost/social-media/public/pages/register.php");
}
}
?>
<?php require_once("../layouts/header.php") ?>
<?php require_once("../layouts/navbar.php") ?>
<main role="main" class="container">
<div class="row justify-content-center">
<div class="col-lg-4">
<h2 class="my-4">Register Yourself</h2>
<form action="register.php" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="nama" required>
</div>
<div class="form-group">
<label>Nama Belakang</label>
<input type="text" class="form-control" name="namabelakang" required>
</div>
<div class="form-group">
<label>Foto</label>
<input type="file" class="form-control" name="photo">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" required>
</div>
<button type="submit" class="btn btn-info mt-2" name="save">Register</button>
</form>
</div>
</div>
</main><!-- /.container -->
<?php require_once("../layouts/footer.php") ?>
|
C++
|
UTF-8
| 1,298 | 3.75 | 4 |
[] |
no_license
|
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct HtmlElement {
string name;
string text;
vector <HtmlElement> sub_elements;
const size_t indent_size = 2;
HtmlElement () { }
HtmlElement(string name, string text): name(name), text(text) {
}
string str(int indent = 0) const {
ostringstream oss;
string i(indent_size*indent, ' ');
oss<<i<<"<"<<name<<">"<<endl;
if(text.size()>0) {
oss<<string(indent_size*indent+1, ' ')<<text<<endl;
}
for (const auto &element : sub_elements) {
oss<<element.str(indent+1)<<endl;
}
oss<<i<<"</"<<name<<">"<<endl;
return oss.str();
}
};
struct HtmlBuilder {
HtmlElement root;
HtmlBuilder() { }
HtmlBuilder(string root_name) {
root.name = root_name;
}
void add_child(string child_name, string child_text) {
HtmlElement e{child_name, child_text};
root.sub_elements.emplace_back(e);
}
const string str () {return root.str().c_str();}
};
int main() {
HtmlBuilder root{"ul"};
root.add_child("li", "Hello");
root.add_child("li", "world");
cout<<root.str()<<endl;
return 0;
}
|
Java
|
UTF-8
| 8,040 | 2.3125 | 2 |
[] |
no_license
|
package com.makersfactory.marinemod.entity;
import java.util.Random;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIFollowParent;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIMate;
import net.minecraft.entity.ai.EntityAIPanic;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAITempt;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityLargeFireball;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFishFood;
import net.minecraft.item.ItemSeeds;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeModContainer;
public class EntitySeagull extends EntityAnimal {
private ChunkCoordinates spawnPosition;
public int courseChangeCooldown;
public double waypointX;
public double waypointY;
public double waypointZ;
public EntitySeagull(World par1World) {
super(par1World);
this.setSize(1.0F,1.0F);
this.tasks.addTask(0, new EntityAISwimming(this));
this.tasks.addTask(1, new EntityAIPanic(this, 1.4D));
this.tasks.addTask(2, new EntityAIMate(this, 1.0D));
this.tasks.addTask(3, new EntityAITempt(this, 1.0D, Items.fish, false));
this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1D));
this.tasks.addTask(5, new EntityAIWander(this, 1.0D));
this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F));
this.tasks.addTask(7, new EntityAILookIdle(this));
}
protected void entityInit()
{
super.entityInit();
}
public boolean isAIEnabled(){
if(this.onGround){
return true;
}else{
return false;
}
}
protected Item getDropItem(){
return this.isBurning() ? Items.cooked_fished : Items.fish;
}
protected void dropFewItems(boolean par1, int par2){
int random = this.rand.nextInt(3) + 1 + this.rand.nextInt(1 + par2);
for(int i = 0; i < random; ++i){
if(i==2){
this.dropItem(Items.feather, 2);
} else if (i==1){
this.dropItem(Items.fish, 1);
}
}
if(this.isBurning()){
this.dropItem(Items.cooked_fished, 1);
}
}
//Moves the entity based on the specified heading. Args: strafe, forward
public void moveEntityWithHeading(float p_70612_1_, float p_70612_2_)
{
if (this.isInWater())
{
this.moveFlying(p_70612_1_, p_70612_2_, 0.02F);
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.800000011920929D;
this.motionY *= 0.800000011920929D;
this.motionZ *= 0.800000011920929D;
}
else if (this.handleLavaMovement())
{
this.moveFlying(p_70612_1_, p_70612_2_, 0.02F);
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= 0.5D;
this.motionY *= 0.5D;
this.motionZ *= 0.5D;
}
else
{
float f2 = 0.91F;
if (this.onGround)
{
f2 = this.worldObj.getBlock(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.boundingBox.minY) - 1, MathHelper.floor_double(this.posZ)).slipperiness * 0.91F;
}
float f3 = 0.16277136F / (f2 * f2 * f2);
this.moveFlying(p_70612_1_, p_70612_2_, this.onGround ? 0.1F * f3 : 0.02F);
f2 = 0.91F;
if (this.onGround)
{
f2 = this.worldObj.getBlock(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.boundingBox.minY) - 1, MathHelper.floor_double(this.posZ)).slipperiness * 0.91F;
}
this.moveEntity(this.motionX, this.motionY, this.motionZ);
this.motionX *= (double)f2;
this.motionY *= (double)f2;
this.motionZ *= (double)f2;
}
this.prevLimbSwingAmount = this.limbSwingAmount;
double d1 = this.posX - this.prevPosX;
double d0 = this.posZ - this.prevPosZ;
float f4 = MathHelper.sqrt_double(d1 * d1 + d0 * d0) * 4.0F;
if (f4 > 1.0F)
{
f4 = 1.0F;
}
this.limbSwingAmount += (f4 - this.limbSwingAmount) * 0.4F;
this.limbSwing += this.limbSwingAmount;
}
//Times course changing and determines if course is traversable.
protected void updateEntityActionState()
{
double d0 = this.waypointX - this.posX;
double d1 = this.waypointY - this.posY;
double d2 = this.waypointZ - this.posZ;
double d3 = d0 * d0 + d1 * d1 + d2 * d2;
if (d3 < 1.0D || d3 > 3600.0D)
{
this.waypointX = this.posX + (double)((this.rand.nextFloat() * 2.0F - 1.0F) * 16.0F);
this.waypointY = this.posY + (double)((this.rand.nextFloat() * 2.0F - 1.0F) * 16.0F);
this.waypointZ = this.posZ + (double)((this.rand.nextFloat() * 2.0F - 1.0F) * 16.0F);
}
if (this.courseChangeCooldown-- <= 0)
{
this.courseChangeCooldown += this.rand.nextInt(5) + 2;
d3 = (double)MathHelper.sqrt_double(d3);
if (this.isCourseTraversable(this.waypointX, this.waypointY, this.waypointZ, d3))
{
this.motionX += d0 / d3 * 0.1D;
this.motionY += d1 / d3 * 0.1D;
this.motionZ += d2 / d3 * 0.1D;
}
else
{
this.waypointX = this.posX;
this.waypointY = this.posY;
this.waypointZ = this.posZ;
}
}
double d4 = 64.0D;
}
//True if the seagull has an unobstructed line of travel to the waypoint.
private boolean isCourseTraversable(double p_70790_1_, double p_70790_3_, double p_70790_5_, double p_70790_7_)
{
double d4 = (this.waypointX - this.posX) / p_70790_7_;
double d5 = (this.waypointY - this.posY) / p_70790_7_;
double d6 = (this.waypointZ - this.posZ) / p_70790_7_;
AxisAlignedBB axisalignedbb = this.boundingBox.copy();
for (int i = 1; (double)i < p_70790_7_; ++i)
{
axisalignedbb.offset(d4, d5, d6);
if (!this.worldObj.getCollidingBoundingBoxes(this, axisalignedbb).isEmpty())
{
return false;
}
}
return true;
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(4.0D);
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D);
}
@Override
public EntityAgeable createChild(EntityAgeable p_90011_1_) {
return new EntitySeagull(worldObj);
}
//Going to change sounds below.
protected String getLivingSound()
{
return "mob.chicken.say";
}
protected String getHurtSound()
{
return "mob.chicken.hurt";
}
protected String getDeathSound()
{
return "mob.chicken.hurt";
}
//Item used to breed Seagulls
public boolean isBreedingItem(ItemStack p_70877_1_)
{
return p_70877_1_ != null && p_70877_1_.getItem() instanceof ItemFishFood;
}
public int getMaxSpawnedInChunk()
{
return 10;
}
//Called when the mob is falling. Calculates and applies fall damage.
protected void fall(float p_70069_1_) {}
}
|
Java
|
UTF-8
| 1,802 | 2.515625 | 3 |
[] |
no_license
|
package com.myhealth.application.cards;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.myhealth.application.R;
import it.gmariotti.cardslib.library.internal.Card;
/**
* Created by Akatchi on 25-9-2014.
*/
public class HeartCard extends Card {
protected TextView mTitle;
protected TextView mSecondaryTitle;
private String heartrate, complaint;
/**
* Constructor with a custom inner layout
* @param context
*/
public HeartCard(Context context) {
this(context, R.layout.card_heartmeasurement);
}
/**
*
* @param context
* @param innerLayout
*/
public HeartCard(Context context, int innerLayout) {
super(context, innerLayout);
init();
}
/**
* Init
*/
private void init(){
//No Header
//Set a OnClickListener listener
// setOnClickListener(new OnCardClickListener() {
// @Override
// public void onClick(Card card, View view) {
// Toast.makeText(getContext(), "Click Listener card=", Toast.LENGTH_LONG).show();
// }
// });
}
@Override
public void setupInnerViewElements(ViewGroup parent, View view) {
//Retrieve elements
mTitle = (TextView) parent.findViewById(R.id.card_heartrate);
mSecondaryTitle = (TextView) parent.findViewById(R.id.card_klachten);
if (mTitle!=null){ mTitle.setText(heartrate); }
if (mSecondaryTitle!=null){ mSecondaryTitle.setText(complaint); }
}
public void setHeartrate(String heartrate)
{
this.heartrate = heartrate;
}
public void setComplaint(String complaint)
{
this.complaint = complaint;
}
}
|
Java
|
UTF-8
| 407 | 1.789063 | 2 |
[] |
no_license
|
package com.hua.library.dao;
import com.hua.library.entity.Tb_bookinfo;
public interface Tb_bookinfoMapper {
int deleteByPrimaryKey(Integer id);
int insert(Tb_bookinfo record);
int insertSelective(Tb_bookinfo record);
Tb_bookinfo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Tb_bookinfo record);
int updateByPrimaryKey(Tb_bookinfo record);
}
|
Java
|
UTF-8
| 5,779 | 1.9375 | 2 |
[] |
no_license
|
/*
Copyright (c) 2007, Dale Anson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ise.plugin.svn.action;
import ise.plugin.svn.gui.OutputPanel;
import ise.plugin.svn.SVNPlugin;
import ise.plugin.svn.command.BrowseRepository;
import ise.plugin.svn.data.CheckoutData;
import ise.plugin.svn.gui.DirTreeNode;
import ise.plugin.svn.io.ConsolePrintStream;
import ise.plugin.svn.library.SwingWorker;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.JTree;
import javax.swing.tree.*;
import org.gjt.sp.jedit.View;
import org.gjt.sp.jedit.jEdit;
public class BrowseRepositoryAction extends SVNAction {
private JTree tree = null;
private DirTreeNode node = null;
private CheckoutData data = null;
public BrowseRepositoryAction( View view, JTree tree, DirTreeNode node, CheckoutData data ) {
super( view, jEdit.getProperty( "ips.Browse_Repository", "Browse Repository" ) );
this.tree = tree;
this.node = node;
this.data = data;
if ( tree == null || node == null || data == null || data.getURL() == null ) {
throw new IllegalArgumentException( "neither tree, node, nor url can be null" );
}
}
public void actionPerformed( ActionEvent ae ) {
data.setOut( new ConsolePrintStream( getView() ) );
getView().getDockableWindowManager().showDockableWindow( "subversion" );
getView().getDockableWindowManager().showDockableWindow( "subversion.browser" );
final OutputPanel panel = SVNPlugin.getOutputPanel( getView() );
panel.showConsole();
Logger logger = panel.getLogger();
logger.log( Level.INFO, jEdit.getProperty( "ips.Fetching_repository_info_for", "Fetching repository info for" ) + "\n" + data.getURL() + "..." );
for ( Handler handler : logger.getHandlers() ) {
handler.flush();
}
class Runner extends SwingWorker < List<DirTreeNode>, Object> {
@Override
public List<DirTreeNode> doInBackground() {
tree.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) );
tree.setEditable( false );
try {
BrowseRepository br = new BrowseRepository( );
return node.isExternal() ? br.getRepository( node, data ) : br.getRepository( data );
}
catch ( Exception e ) {
data.getOut().printError( e.getMessage() );
}
finally {
data.getOut().close();
}
return null;
}
@Override
public boolean doCancel( boolean mayInterruptIfRunning ) {
boolean cancelled = super.cancel( mayInterruptIfRunning );
if ( cancelled ) {
data.getOut().printError( "Stopped 'Browse Repository' action." );
data.getOut().close();
}
else {
data.getOut().printError( "Unable to stop 'Browse Repository' action." );
}
return cancelled;
}
@Override
protected void done() {
if ( isCancelled() ) {
return ;
}
try {
List<DirTreeNode> children = get();
for ( DirTreeNode child : children ) {
node.add( child );
}
DefaultTreeModel model = ( DefaultTreeModel ) tree.getModel();
model.nodeStructureChanged( node );
TreePath path = new TreePath( node.getPath() );
tree.revalidate();
tree.repaint();
tree.expandPath( path );
}
catch ( Exception e ) { // NOPMD
// ignored
}
finally {
tree.setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) );
tree.setEditable( true );
tree.requestFocus();
}
}
}
Runner runner = new Runner();
panel.addWorker( "Browse Repository", runner );
runner.execute();
}
}
|
C++
|
UTF-8
| 799 | 3.703125 | 4 |
[] |
no_license
|
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::string;
string Get_User_Name()
{
string first_name;
string last_name;
cout << "Please enter your first name: "
<< "\n";
cin >> first_name;
cout << "Please enter your last name: "
<< "\n";
cin >> last_name;
string full_name = first_name + " " + last_name;
return full_name;
}
string Greet_User(string user_name)
{
return "Hello, " + user_name + "! It's a pleasure to meet you :)\n";
}
int main()
{
cout << "======= GOOD DAY!!! =======!"
<< "\n";
string user_name = Get_User_Name();
string greeting = Greet_User(user_name);
cout << "\n";
cout << greeting << "\n";
return 0;
}
|
Java
|
UTF-8
| 3,084 | 2.171875 | 2 |
[] |
no_license
|
package de.hdm.sambook.client;
import java.util.Vector;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import de.hdm.sambook.shared.LoginService;
import de.hdm.sambook.shared.LoginServiceAsync;
import de.hdm.sambook.shared.PinnwandAdministrationAsync;
import de.hdm.sambook.shared.bo.Nutzer;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Sambook implements EntryPoint {
private LoginInfo loginInfo = null;
private VerticalPanel loginPanel = new VerticalPanel();
private Label loginLabel = new Label(
"Please sign in to your Google Account to access the StockWatcher application.");
private Anchor signInLink = new Anchor("Sign In");
// Check login status using login service.
LoginServiceAsync loginService = GWT.create(LoginService.class);
@Override
public void onModuleLoad() {
//RootPanel.get("content".add(new Label("Hello, World!"));
Window.alert("jj");
loginService.login(GWT.getHostPageBaseURL() + "Sambook.html", new AsyncCallback<LoginInfo>() {
public void onFailure(Throwable error) {
error.getMessage().toString();
}
public void onSuccess(LoginInfo result) {
Window.alert("he");
loginInfo = result;
if(loginInfo.isLoggedIn()) {
loadPinnWand();
} else {
loadLogin();
}
}
});
}
/**
* Wird beim Start der Applikation nach dem login geladen.
* (Wenn User vorhanden in der DB).
*/
public void loadPinnWand() {
//Navigation Klasse reinladen
}
/**
* Methode wird aufgerufen, wenn User nicht eingeloggt.
*/
public void loadLogin() {
signInLink.setHref(loginInfo.getLoginUrl());
loginPanel.add(loginLabel);
loginPanel.add(signInLink);
loginPanel.addStyleName("login");
// Footer wird geelert fuer den LoginContainer
RootPanel.get("navi").clear();
RootPanel.get("content").clear();
// Hinzufuegen des LoginPanels in den <div> Container "content"
RootPanel.get("content").add(loginPanel);
}
}
|
Python
|
UTF-8
| 2,877 | 2.796875 | 3 |
[] |
no_license
|
#coding:utf-8
import datetime
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn.cluster import DBSCAN
'''
利用两次DBSACN对事务进行聚类
第一次初步剔除噪声,并获得最短事务耗时
第二次变换坐标后得到真正的聚类结果
'''
print 'Start reading data...'
df = pd.read_csv("D:\SubwayData\Transactions_201412_01_07_line_1_1276913.csv", usecols=[3, 4, 5, 7])
print 'Data has been read yet.'
s_time = datetime.datetime.strptime('20141205' + '160000', '%Y%m%d%H%M%S')
e_time = datetime.datetime.strptime('20141205' + '173000', '%Y%m%d%H%M%S')
star_time = datetime.datetime.strptime('20141205' + '063000', '%Y%m%d%H%M%S')
end_time = datetime.datetime.strptime('20141205' + '235900', '%Y%m%d%H%M%S')
df = df[(pd.to_datetime(df.in_time) >= star_time) & (pd.to_datetime(df.in_time) <= end_time) & (df.in_station == 23) & (
df.out_station == 14)] .loc[:, ['in_time', 'total_time']]
x = []
y = df['total_time']
for i in df['in_time']:
x.append((datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S')-star_time).seconds)
df = pd.DataFrame({ 'in_time' : x,
'total_time' : y})
X = df.values
y_pred = DBSCAN(eps = 90, min_samples = 7).fit_predict(X)
s = pd.Series(y_pred)
X = pd.DataFrame(X)
X['C'] = s
# plt.scatter(X[X.C!=-1].loc[:,0], X[X.C!=-1].loc[:,1], c=X[X.C!=-1].loc[:,'C'])
# plt.show()
n_clusters_ = len(set(y_pred))
mins = []
for i in range(n_clusters_-1):#排除分类标签-1的数据,所以实际分类数量要-1
tra_time = X[X.C==i].loc[:,1]
#mins.append(tra_time.min(0))
mins.append(min(tra_time))
min_total = min(mins)
df['new_x'] = df.in_time + (df.total_time - min_total)
df['new_y'] = 0.75 * min_total + 0.25 * df.total_time
X = df.loc[:,['new_x','new_y']].values
y_pred = DBSCAN(eps = 90, min_samples = 12).fit_predict(X)
s = pd.Series(y_pred)
df =pd.DataFrame(df.loc[:,['in_time','total_time']].values)#这一步重置DF不可省略,重置DF索引,使之为0,1,2,3.。。与s保持一致,才可以合并
df['C'] = s
df.columns = ['in_time','total_time','C']
df = df[(df.in_time>=(s_time-star_time).seconds)&(df.in_time<=(e_time-star_time).seconds)]
x = []
for i in df['in_time']:
x.append((datetime.datetime.strptime('20141205' + '063000', '%Y%m%d%H%M%S') + datetime.timedelta(seconds=int(i))).time())
df['in_time'] = x
x = df[df.C!=-1].loc[:,'in_time'].values
plt.scatter(x, df[df.C!=-1].loc[:,'total_time'], c=df[df.C!=-1].loc[:,'C'], s=10, marker='.')
plt.xlabel('Checkin time')
plt.ylabel('Travel time(s)')
plt.title('Travel time and checkin time on 2015-05-08')
plt.xticks(['16:00:00', '16:15:00', '16:30:00', '16:45:00', '17:00:00', '17:15:00', '17:30:00'])
plt.yticks([1750, 2000, 2250, 2500, 2750, 3000, 3250, 3500])
plt.show()
# plt.scatter(df.loc[:,0], df.loc[:,1], c=df.loc[:,'C'])
# plt.show()
|
Python
|
UTF-8
| 703 | 2.65625 | 3 |
[] |
no_license
|
import pymysql
class DBConnectivity:
@staticmethod
def getConnection(hostname,username,password,database):
con = pymysql.connect(host=hostname,user=username,password=password,db=database)
return con
@staticmethod
def getQueryResult(connection,query):
cursor = connection.cursor()
cursor.execute(query)
return cursor
@staticmethod
def updateDatabase(connection,query):
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
cursor.close()
@staticmethod
def closeConnection(connection):
if connection != None:
connection.close()
|
Java
|
UTF-8
| 9,453 | 2.25 | 2 |
[] |
no_license
|
package com.client;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.security.*;
import org.apache.commons.codec.Charsets;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import java.io.*;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* pdf分离签署例子
*/
public class SignerClient {
static String PreSignURL;
static String PostSignURL;
public static final String CERT = "src/main/resources/econtract.cer";
public static final String PFX = "src/main/resources/econtract.jks";
public static final String PROPERTY = "src/main/resources/key.properties";
public static final String DEST = "results/signed.pdf";
public static final String IMAGE_DEST = "src/main/resources/sign.png";
static String key_password;
public static final String SRC = "src/main/resources/test.pdf";
private String message;
//保存共享变量
private HashMap<String, Object> shareMap = new HashMap<>();
public static void readProperty(String propertyPath) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(propertyPath));
key_password = properties.getProperty("PASSWORD");
PreSignURL = properties.getProperty("presign-url");
PostSignURL = properties.getProperty("postsign-url");
} catch (IOException e) {
e.printStackTrace();
}
}
public byte[] getHash(String cert) throws IOException, CertificateException {
try {
FileInputStream fis = new FileInputStream(cert);
// We get the self-signed certificate from the client
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate[] chain = new Certificate[1];
chain[0] = factory.generateCertificate(fis);
// we create a reader and a stamper
PdfReader reader = new PdfReader(SRC);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
// we create the signature appearance
PdfSignatureAppearance sap = stamper.getSignatureAppearance();
sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
//图片
Image image = Image.getInstance(IMAGE_DEST); //使用png格式透明图片
// image.scaleAbsolute(200,200);
sap.setSignatureGraphic(image);
sap.setReason("sim签电子平台签署");
sap.setLocation("中国广州市");
sap.setVisibleSignature(new Rectangle(100, 500, 300, 700), 1, "sig");
sap.setCertificate(chain[0]);
//the time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dt = sdf.parse("2019-08-11");
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(dt);
sap.setSignDate(rightNow);
// we create the signature infrastructure
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.setReason(sap.getReason());
dic.setLocation(sap.getLocation());
dic.setContact(sap.getContact());
dic.setDate(new PdfDate(sap.getSignDate()));
sap.setCryptoDictionary(dic);
HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
sap.preClose(exc);
ExternalDigest externalDigest = new ExternalDigest() {
@Override
public MessageDigest getMessageDigest(String hashAlgorithm)
throws GeneralSecurityException {
return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
}
};
PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
InputStream data = sap.getRangeStream();
byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
System.out.println("sha256 后字节长度:"+hash.length);
System.out.println("base64 before getAuthenticatedAttributeBytes hash:\n" + new String(Base64.encode(hash), Charsets.UTF_8));
// we get OCSP and CRL for the cert
OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);
OcspClient ocspClient = new OcspClientBouncyCastle(ocspVerifier);
byte[] ocsp = null;
if (chain.length >= 2 && ocspClient != null) {
ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
}
Collection<byte[]> crlBytes = null;
byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, null, null, MakeSignature.CryptoStandard.CMS);
System.out.println("签名前字节长度:"+sh.length);
// We store the objects we'll need for post signing in a shareMap
shareMap.put("sgn", sgn);
shareMap.put("hash", hash);
shareMap.put("ocsp", ocsp);
shareMap.put("sap", sap);
shareMap.put("baos", baos);
// we write the hash that needs to be signed to the HttpResponse output
return sh;
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public byte[] Sign(byte[] hash, String pfx) throws KeyStoreException,
IOException, UnrecoverableKeyException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException, CertificateException {
byte[] data = new byte[256];
Security.addProvider(new BouncyCastleProvider());
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream input = new FileInputStream(pfx);
char[] kp = key_password.toCharArray();
ks.load(input, kp);
String alias = (String) ks.aliases().nextElement();
PrivateKey pk = (PrivateKey) ks.getKey(alias, key_password.toCharArray());
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(pk);
sig.update(hash);
data = sig.sign();
return data;
}
public void getSignedPDF(byte[] signature, String file) throws IOException, DocumentException {
// we get the objects we need for postsigning from the shareMap
PdfPKCS7 sgn = (PdfPKCS7) shareMap.get("sgn");
byte[] hash = (byte[]) shareMap.get("hash");
byte[] ocsp = (byte[]) shareMap.get("ocsp");
PdfSignatureAppearance sap = (PdfSignatureAppearance) shareMap.get("sap");
ByteArrayOutputStream os = (ByteArrayOutputStream) shareMap.get("baos");
// we read the signed bytes
// we complete the PDF signing process
sgn.setExternalDigest(signature, null, "RSA");
Collection<byte[]> crlBytes = null;
TSAClientBouncyCastle tsaClient = new TSAClientBouncyCastle("http://timestamp.gdca.com.cn/tsa", null, null);
byte[] encodedSig = sgn.getEncodedPKCS7(hash, tsaClient, ocsp, crlBytes, MakeSignature.CryptoStandard.CMS);
byte[] paddedSig = new byte[8192];
System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
PdfDictionary dic2 = new PdfDictionary();
dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
sap.close(dic2);
byte[] pdf = os.toByteArray();
FileOutputStream fos = new FileOutputStream(file);
fos.write(pdf);
fos.close();
}
public static void main(String args[]) throws IOException, DocumentException {
readProperty(PROPERTY);
SignerClient sc = new SignerClient();
// 1. get hash to be signed
byte[] hash = null;
try {
hash = sc.getHash(CERT);
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
System.out.println("base64 hash:\n" + new String(Base64.encode(hash), Charsets.UTF_8));
// 2. sign hash with private key
byte[] signature = null;
try {
signature = sc.Sign(hash, PFX);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("签名后字节长度:"+signature.length);
System.out.println("base64 signed hash:\n" + new String(Base64.encode(signature), Charsets.UTF_8));
// 3. post signed hash to get the signed PDF
sc.getSignedPDF(signature, DEST);
}
}
|
C++
|
UTF-8
| 796 | 2.8125 | 3 |
[] |
no_license
|
#ifndef Player_h //This is used when more than one header file is compiling the same header file.
#define Player_h //This is used when more than one header file is compiling the same header file.
#include "Entity.h"
#include "World.h"
#include <string>
class Player : public Entity
{
private:
int score;
int speed;
int lifes;
int respawnHealth;
public:
const void takeDamage() override;
const int getScore();
void playerMovement();
void fireBullet(int x, int y);
int getPositionX();
int getPositionY();
void update() override final;
int getSide() const override final;
Player(std::string entityName, int playerHealth, int playerDamage);
~Player();
};
#endif // Player_h //This is used when more than one header file is compiling the same header file.
|
Python
|
UTF-8
| 1,949 | 3.578125 | 4 |
[] |
no_license
|
import numpy as np
import csv
# 숫자로 주어지는 y값을 길이 vector_length인 one-hot 벡터로 변환합니다.
def convert_y_to_one_hot_vector(y, vector_length):
y_vect = np.zeros((len(y), vector_length))
for i in range(len(y)):
y_vect[i, y[i]] = 1
return y_vect
# 붓꽃 품종을 딕셔너리로 정의하여 문자열로된 라벨을 숫자값 라벨로 변환하는데 사용합니다.
Species_Dict ={'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}
# 특성(X)와 라벨(Y)를 저장하는데 사용합니다.
X = []
Y = []
# csv 파일을 열어서 한줄씩 가져옵니다.
with open('Iris.csv', newline='') as file:
reader = csv.reader(file)
try:
for i,row in enumerate(reader):
if i > 0:
# csv로부터 읽어온 데이터를 특성과 라벨로 나누어 리스트에 저장합니다.
X.append(np.array(row[1:5], dtype="float64"))
# 앞에서 정의한 딕셔너리를 이용하여 문자열 라벨을 숫자 라벨로 변환합니다.
Y.append(Species_Dict[row[-1]])
# 데이터가 저장된 리스트를 넘파이 배열로 변환합니다.
X = np.array(X)
Y = np.array(Y)
except csv.Error as e:
sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))
# {0, 1, 2} 값을 가지는 라벨을 one-hot 인코딩을하여 {0 0 1, 0 1 0, 1 0 0}로 변환합니다.
Y = convert_y_to_one_hot_vector(Y, vector_length=3)
# 데이터 셋을 무작위로 섞습니다.
s = np.arange(Y.shape[0])
np.random.seed(0)
np.random.shuffle(s)
Y = Y[s]
X = X[s]
# 학습용 데이터(X_train,Y_train)와 테스트용 데이터(X_test,Y_test)를 8:2 비율로 사용합니다.
size = len(Y)
p = int(size * 0.8)
X_train = X[0:p]
Y_train = Y[0:p]
X_test = X[p:]
Y_test = Y[p:]
# 학습용 데이터를 시험 삼아 출력해봅니다.
print(X_train[0])
print(Y_train[0])
|
Shell
|
UTF-8
| 563 | 2.859375 | 3 |
[] |
no_license
|
#!/bin/sh
sendrequired=''
outfile=translog_outfile.mail
emails="AutomatedAlertsForSearchDevelopment@careerbuilder.com"
subject="[Production Alert] Transaction log failed to create/reap"
statuscode=`curl -s -w "%{http_code}\\n" cbcassweb01/utils/create_translog?devkey=LetMeIn -o /dev/null`
if [ $statuscode != '200' ]; then
sendrequired=true
fi
if [ $sendrequired ]; then
touch $outfile
curl -s cbcassweb01/utils/create_translog?devkey=LetMeIn >> $outfile
ruby /opt/search/PagerDuty/PagerDutyModule.rb "High" "$subject" "$(cat $outfile)" "cassandraadmin@opscenter01" "text"
rm $outfile
fi
|
PHP
|
UTF-8
| 1,158 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class AddClassificationToSchoolsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('schools', function(Blueprint $table)
{
$table->string('classification', '200')->default('');
$table->string('sex', '200')->default('');
$table->string('religion', '200')->default('');
$table->string('religion_type', '200')->default('');
$table->string('extra', '200')->default('');
$table->string('preschool', '200')->default('');
$table->string('tertiary', '200')->default('');
$table->string('military', '200')->default('');
$table->string('military_level', '200')->default('');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('schools', function(Blueprint $table)
{
$table->dropColumn('classification', 'sex', 'religion', 'religion_type', 'extra', 'preschool', 'tertiary', 'military', 'military_level' );
});
}
}
|
Python
|
UTF-8
| 2,642 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
'''
Authors: James Barr, Demarcus Campbell, Tucker Simpson
'''
from scapy.all import *
import sys
'''
Returns dictionary of all levels' headers, and application data
{"frame_header":..., "arp/ip_header":, "tcp/udp_header":...,"raw_data":...}
param: None
returns: dict packet_information
'''
def get_packet(filt=None, func):
packet_information = dict()
if not filt and not func:
packet = sniff(store=1, count=1)[0]
elif filt and not func:
packet = sniff(store=1, count=1, filter=filt)
elif func and not filt:
packet = sniff(store=1, count=1, prn=func)
else:
packet = sniff(store=1, count=1, prn=func, filter=filt)
packet_information["frame_header"] = packet.getlayer(Ether)
if packet.type == 2054:
packet_information["arp_header"] = packet.getlayer(ARP)
packet_information["padding"] = packet.getlayer(Padding)
else:
if packet.type == 2048: # IPv4
packet_information["ip_header"] = packet.getlayer(IP)
if packet_information["ip_header"].proto == 6:
packet_information["tcp_header"] = packet.getlayer(TCP)
packet_information["raw_data"] = packet.getlayer(Raw)
elif packet_information["ip_header"].proto == 17:
packet_information["udp_header"] = packet.getlayer(UDP)
packet_information["raw_data"] = packet.getlayer(Raw)
elif packet_information["ip_header"].proto == 1:
packet_information["icmp_header"] = packet.getlayer(ICMP)
packet_information["raw_data"] = packet.getlayer(Raw)
else: # Packet not TCP, UDP, or ICMP
return get_packet()
elif packet.type == 34525: # IPv6
packet_information["ipv6_header"] = packet.getlayer(IPv6)
if packet_information["ipv6_header"].nh == 6:
packet_information["tcp_header"] = packet.getlayer(TCP)
packet_information["raw_data"] = packet.getlayer(Raw)
elif packet_information["ipv6_header"].nh == 17:
packet_information["udp_header"] = packet.getlayer(UDP)
packet_information["raw_data"] = packet.getlayer(Raw)
#elif packet_information["ipv6_header"].nh == 58:
# packet_information["icmp_header"] = packet.getlayer(_ICMPv6)
# packet_information["raw_data"] = packet.getlayer(Raw)
else: # Packet not TCP or UDP
get_packet()
else: # Packet not ARP or IP
return get_packet()
return packet_information
if __name__ == "__main__":
print(get_packet())
|
Java
|
UTF-8
| 146 | 2.3125 | 2 |
[] |
no_license
|
public class HaierFridge implements Fridge {
@Override
public void fridgeInfo() {
System.out.println("海尔冰箱");
}
}
|
C++
|
WINDOWS-1251
| 2,433 | 3.296875 | 3 |
[] |
no_license
|
#include <algorithm> // transform
#include <iostream> // cout
#include <string> // string
using namespace std;
//
void setVigenereKey(string &key) {
do {
cout << " :" << endl;
cin >> key;
} while (key == "");
transform(key.begin(), key.end(), key.begin(), ::toupper);
}
//
string vigenereEnc(string text, string key) {
string result = "";
if (text != "") {
for (int i = 0; i < text.length(); i++) {
result += ((char)(((text[i] + key[i % key.length()]) % 26) + 'A'));
}
}
return result;
}
// x y
// (- )
int gcd(int x, int y) {
if (y == 0)
return x;
else
return gcd(y, x % y);
}
//
void setAffineKey(int &a, int &b) {
cout << " :" << endl;
do {
cout << "a = ";
cin >> a;
} while (a <= 0);
do {
cout << "b = ";
cin >> b;
} while (b < 0);
if (gcd(a, 26) != 1) {
cout << "\n \'\' = " << a << " \'n\' = 26 "
<< " !\n";
setAffineKey(a, b);
}
}
//
string affineEnc(string text, int a, int b) {
string result = "";
for (int i = 0; i < text.length(); i++) {
result += ((char)(((a * text[i] - 'A' + b) % 26) + 'A'));
}
return result;
}
string preprocessing(string text) {
string result = "";
for (int i = 0; i < text.length(); i++) {
char currChar = toupper(text[i]);
if (isalpha(currChar)) {
result += currChar;
}
}
return result;
}
//
int main() {
setlocale(LC_ALL, "BGR"); //
string plaintext, vigenereKey;
int keyA, keyB;
cout << " : ";
getline(cin, plaintext);
setAffineKey(keyA, keyB);
setVigenereKey(vigenereKey);
cout << endl
<< vigenereEnc(affineEnc(preprocessing(plaintext), keyA, keyB), vigenereKey)
<< endl;
return 0;
}
|
Python
|
UTF-8
| 478 | 3.015625 | 3 |
[] |
no_license
|
import string
N, K = map(int, raw_input().split())
S = raw_input()
chars = [S.count(c) for c in string.ascii_lowercase]
arr = [(chars, 0)]
for i in range(1, N-K):
chars = chars[:]
chars[ord(S[i-1])-ord('a')] -= 1
chars[ord(S[i+K-1])-ord('a')] += 1
arr.append((chars, i))
arr.sort()
a = arr[0]
for i in range(1, len(arr)):
if a[0] == arr[i][0]:
if abs(a[1] - arr[i][1]) >= K:
print 'YES'
exit()
else: a = arr[i]
print 'NO'
|
Java
|
UTF-8
| 901 | 3 | 3 |
[] |
no_license
|
package PracticeFor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
public class 숫자의합 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String temp = br.readLine();
int[] tempArr = new int[temp.length()];
//Stream.of(temp.split("")).mapToInt(Integer::parseInt).toArray();
int answer = 0;
// for (int i = 0; i < tempArr.length; i++) {
// answer += tempArr[i];
// }
for (int i = 0; i < tempArr.length; i++) {
tempArr[i] = temp.charAt(i) - '0';
answer += tempArr[i];
}
System.out.println(answer);
}
}
|
C++
|
UTF-8
| 1,226 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <eosio.system/eosio.system.hpp>
#include <eosiolib/privileged.h>
using namespace eosio;
bool has_ram_managed( const name& account ) {
eosiosystem::voters_table _voters("eosio"_n, "eosio"_n.value);
auto vitr = _voters.find( account.value );
if( vitr == _voters.end() )
return true;
return eosiosystem::has_field( vitr->flags1, eosiosystem::voter_info::flags1_fields::ram_managed );
}
int64_t ram_balance_to_bytes(const asset& ram_balance) {
uint128_t new_ram_bytes = uint128_t(ram_balance.amount);
new_ram_bytes *= uint128_t(1000); //1 RAM token represents 1000 bytes of RAM
new_ram_bytes += uint128_t(49999999); //round up any value > 0.5 bytes to 1 byte
new_ram_bytes /= uint128_t(100000000); //divide by the precision of RAM token (8)
return static_cast<int64_t>(new_ram_bytes);
}
void update_account_ram_limit(const name& account, const asset& ram_balance) {
if( has_ram_managed(account) )
return;
int64_t ram_bytes, net, cpu;
get_resource_limits( account.value, &ram_bytes, &net, &cpu );
int64_t new_ram_bytes = ram_balance_to_bytes(ram_balance);
set_resource_limits( account.value, new_ram_bytes, net, cpu );
}
|
Python
|
UTF-8
| 689 | 3.484375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
class AbstractExpression(object):
def interpreter(self, context):
pass
class TerminalExpression(AbstractExpression):
def interpreter(self, context):
print "terminal",context
class NotTerminalExpression(AbstractExpression):
def interpreter(self, context):
print "non terminal",context
class Context(object):
def __init__(self):
self.name = ""
if __name__ == "__main__":
context = Context()
context.name = 'Andy'
arr_list = [NotTerminalExpression(),TerminalExpression(),TerminalExpression()]
for entry in arr_list:
entry.interpreter(context)
|
SQL
|
UTF-8
| 2,417 | 3.578125 | 4 |
[] |
no_license
|
drop table if exists oauth_users;
create table oauth_users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
active BOOLEAN
) Engine=InnoDB;
create table oauth_permissions (
id INT PRIMARY KEY AUTO_INCREMENT,
id_user VARCHAR(100) NOT NULL REFERENCES s_users(id),
user_role VARCHAR(255) NOT NULL
) Engine=InnoDB;
create table if not exists oauth_client_details (
client_id VARCHAR(255) PRIMARY KEY,
resource_ids VARCHAR(255),
client_secret VARCHAR(255),
scope VARCHAR(255),
authorized_grant_types VARCHAR(255),
web_server_redirect_uri VARCHAR(255),
authorities VARCHAR(255),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR(4096),
autoapprove VARCHAR(255)
);
create table if not exists oauth_client_token (
token_id VARCHAR(255),
token LONG VARBINARY,
authentication_id VARCHAR(255) PRIMARY KEY,
user_name VARCHAR(255),
client_id VARCHAR(255)
);
create table if not exists oauth_access_token (
token_id VARCHAR(255),
token LONG VARBINARY,
authentication_id VARCHAR(255) PRIMARY KEY,
user_name VARCHAR(255),
client_id VARCHAR(255),
authentication LONG VARBINARY,
refresh_token VARCHAR(255)
);
create table if not exists oauth_refresh_token (
token_id VARCHAR(255),
token LONG VARBINARY,
authentication LONG VARBINARY
);
create table if not exists oauth_code (
code VARCHAR(255), authentication LONG VARBINARY
);
create table if not exists oauth_approvals (
userId VARCHAR(255),
clientId VARCHAR(255),
scope VARCHAR(255),
status VARCHAR(10),
expiresAt TIMESTAMP,
lastModifiedAt TIMESTAMP default now()
);
insert into oauth_users (username, password, active)
values ('patartimotius', 'evievi123', true);
insert into oauth_permissions (id_user, user_role)
values (1, 'ROLE_SUPERVISOR');
insert into oauth_permissions (id_user, user_role)
values (1, 'ROLE_OPERATOR');
insert into oauth_client_details
(client_id, client_secret, resource_ids,
scope, authorized_grant_types, authorities) values
('clientauthcode', '123456', 'belajar', 'read,write', 'authorization_code, refresh_token', 'CLIENT');
insert into oauth_client_details
(client_id, client_secret, resource_ids,
scope, authorized_grant_types) values
('clientapp', '123456', 'belajar', 'read,write', 'password,refresh_token');
|
TypeScript
|
UTF-8
| 13,078 | 2.9375 | 3 |
[
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"CC-BY-SA-4.0",
"LGPL-2.1-or-later",
"MIT-Wu",
"ISC",
"AFL-2.1",
"Apache-2.0",
"LGPL-2.0-only",
"CC0-1.0",
"BSD-2-Clause",
"Unlicense"
] |
permissive
|
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
// tslint:disable:no-unused-expression
// tslint:disable:max-func-body-length
import * as assert from "assert";
import { Language } from "../extension.bundle";
const Contains = Language.Contains;
const IssueKind = Language.IssueKind;
suite("Language", () => {
suite("Span", () => {
suite("constructor()", () => {
function constructorTest(startIndex: number, length: number): void {
test(`with [${startIndex},${length})`, () => {
const span = new Language.Span(startIndex, length);
assert.deepStrictEqual(span.startIndex, startIndex);
assert.deepStrictEqual(span.length, length);
assert.deepStrictEqual(span.endIndex, startIndex + (length > 0 ? length - 1 : 0), "Wrong endIndex");
assert.deepStrictEqual(span.afterEndIndex, startIndex + length, "Wrong afterEndIndex");
});
}
constructorTest(-1, 3);
constructorTest(0, 3);
constructorTest(10, -3);
constructorTest(11, 0);
constructorTest(21, 3);
});
suite("contains()", () => {
suite("Contains.strict", () => {
test("With index less than startIndex", () => {
assert.deepStrictEqual(false, new Language.Span(3, 4).contains(2, Contains.strict));
});
test("With index equal to startIndex", () => {
assert(new Language.Span(3, 4).contains(3, Contains.strict));
});
test("With index between the start and end indexes", () => {
assert(new Language.Span(3, 4).contains(5, Contains.strict));
});
test("With index equal to endIndex", () => {
assert(new Language.Span(3, 4).contains(6, Contains.strict));
});
test("With index directly after end index", () => {
assert.deepStrictEqual(false, new Language.Span(3, 4).contains(7, Contains.strict));
});
});
suite("Contains.extended", () => {
test("With index less than startIndex", () => {
assert.deepStrictEqual(false, new Language.Span(3, 4).contains(2, Contains.extended));
});
test("With index equal to startIndex", () => {
assert(new Language.Span(3, 4).contains(3, Contains.extended));
});
test("With index between the start and end indexes", () => {
assert(new Language.Span(3, 4).contains(5, Contains.extended));
});
test("With index equal to endIndex", () => {
assert(new Language.Span(3, 4).contains(6, Contains.extended));
});
test("With index directly after end index", () => {
// Extended, so this should be true
assert.deepStrictEqual(true, new Language.Span(3, 4).contains(7, Contains.extended));
});
test("With index two after end index", () => {
assert.deepStrictEqual(false, new Language.Span(3, 4).contains(8, Contains.extended));
});
});
suite("Contains.enclosed", () => {
test("With index less than startIndex", () => {
assert.deepStrictEqual(false, new Language.Span(3, 4).contains(2, Contains.enclosed));
});
test("With index equal to startIndex", () => {
// With enclosed, this should be false
assert.equal(new Language.Span(3, 4).contains(3, Contains.enclosed), false);
});
test("With index between the start and end indexes", () => {
assert(new Language.Span(3, 4).contains(5, Contains.enclosed));
});
test("With index equal to endIndex", () => {
assert(new Language.Span(3, 4).contains(6, Contains.enclosed));
});
test("With index directly after end index", () => {
assert.deepStrictEqual(false, new Language.Span(3, 4).contains(7, Contains.enclosed));
});
});
});
suite("union()", () => {
test("With null", () => {
let s = new Language.Span(5, 7);
assert.deepStrictEqual(s, s.union(undefined));
});
test("With same span", () => {
let s = new Language.Span(5, 7);
assert.deepEqual(s, s.union(s));
});
test("With equal span", () => {
let s = new Language.Span(5, 7);
assert.deepEqual(s, s.union(new Language.Span(5, 7)));
});
test("With subset span", () => {
let s = new Language.Span(5, 17);
assert.deepEqual(s, s.union(new Language.Span(10, 2)));
});
});
suite("intersect()", () => {
test("With null", () => {
let s = Language.Span.fromStartAndAfterEnd(5, 7);
assert.deepStrictEqual(s.intersect(undefined), undefined);
});
test("With same span", () => {
let s = Language.Span.fromStartAndAfterEnd(5, 7);
assert.deepEqual(s, s.intersect(s));
});
test("With equal span", () => {
let s = Language.Span.fromStartAndAfterEnd(5, 7);
assert.deepEqual(s, s.intersect(new Language.Span(5, 7)));
});
test("second span to left", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(Language.Span.fromStartAndAfterEnd(0, 9)),
undefined
);
});
test("second touches the left", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(Language.Span.fromStartAndAfterEnd(0, 10)),
// Two results could be argued here: len 0 span at 10, or undefined
// We'll go with the former until sometimes finds a reason why it should
// be different
new Language.Span(10, 0)
);
});
test("second span to left and overlap", () => {
assert.deepEqual(
new Language.Span(10, 20).intersect(new Language.Span(0, 11)),
new Language.Span(10, 1)
);
});
test("second span is superset", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(Language.Span.fromStartAndAfterEnd(0, 21)),
Language.Span.fromStartAndAfterEnd(10, 20)
);
});
test("second span is subset", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(new Language.Span(11, 8)),
new Language.Span(11, 8)
);
});
test("second span is len 0 subset, touching on the left", () => {
assert.deepEqual(
new Language.Span(10, 10).intersect(new Language.Span(10, 0)),
new Language.Span(10, 0)
);
});
test("second span is len 0 subset, touching on the right", () => {
assert.deepEqual(
new Language.Span(10, 10).intersect(new Language.Span(20, 0)),
new Language.Span(20, 0)
);
});
test("second span to right and overlapping", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(new Language.Span(19, 10)),
new Language.Span(19, 1)
);
});
test("second span to right", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(new Language.Span(21, 9)),
undefined
);
});
test("length 0", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(new Language.Span(15, 0)),
new Language.Span(15, 0)
);
});
test("length 1", () => {
assert.deepEqual(
Language.Span.fromStartAndAfterEnd(10, 20).intersect(new Language.Span(15, 1)),
new Language.Span(15, 1)
);
});
});
suite("translate()", () => {
test("with 0 movement", () => {
const span = new Language.Span(1, 2);
assert.equal(span.translate(0), span);
assert.deepStrictEqual(span.translate(0), new Language.Span(1, 2));
});
test("with 1 movement", () => {
const span = new Language.Span(1, 2);
assert.notEqual(span.translate(1), new Language.Span(2, 2));
assert.deepStrictEqual(span.translate(1), new Language.Span(2, 2));
});
test("with -1 movement", () => {
const span = new Language.Span(1, 2);
assert.notEqual(span.translate(-1), new Language.Span(0, 2));
assert.deepStrictEqual(span.translate(-1), new Language.Span(0, 2));
});
});
test("toString()", () => {
assert.deepStrictEqual(new Language.Span(1, 2).toString(), "[1, 3)");
});
});
suite("Position", () => {
suite("constructor(number,number)", () => {
test("With null _line", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Position(<any>null, 3); });
});
test("With undefined _line", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Position(<any>undefined, 3); });
});
test("With negative _line", () => {
assert.throws(() => { new Language.Position(-1, 3); });
});
test("With null _column", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Position(2, <any>null); });
});
test("With undefined _column", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Position(2, <any>undefined); });
});
test("With negative _column", () => {
assert.throws(() => { new Language.Position(2, -3); });
});
test("With valid arguments", () => {
const p = new Language.Position(2, 3);
assert.deepStrictEqual(p.line, 2);
assert.deepStrictEqual(p.column, 3);
});
});
});
suite("Issue", () => {
suite("constructor(Span,string)", () => {
test("With null span", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Issue(<any>null, "error message", IssueKind.tleSyntax); });
});
test("With undefined span", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Issue(<any>undefined, "error message", IssueKind.tleSyntax); });
});
test("With null message", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Issue(new Language.Span(4, 1), <any>null, IssueKind.tleSyntax); });
});
test("With undefined message", () => {
// tslint:disable-next-line:no-any
assert.throws(() => { new Language.Issue(new Language.Span(4, 1), <any>undefined, IssueKind.tleSyntax); });
});
test("With empty message", () => {
assert.throws(() => { new Language.Issue(new Language.Span(3, 2), "", IssueKind.tleSyntax); });
});
test("With valid arguments", () => {
const issue = new Language.Issue(new Language.Span(2, 4), "error message", IssueKind.tleSyntax);
assert.deepStrictEqual(issue.span, new Language.Span(2, 4));
assert.deepStrictEqual(issue.message, "error message");
});
});
});
});
|
Java
|
UTF-8
| 305 | 2.578125 | 3 |
[] |
no_license
|
package ds.sort;
public class Pair {
int key;
int[] array;
public Pair() {
super();
}
public int[] getArray() {
return array;
}
public void setArray(int[] array) {
this.array = array;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
}
|
Java
|
UTF-8
| 1,173 | 2.421875 | 2 |
[] |
no_license
|
package cn.mxz.newpvp;
import cn.mxz.city.City;
import cn.mxz.script.Script;
import cn.mxz.user.team.Formation;
public class PracticeCaculator {
public int calc(City me, PvpFightUser pfu) {
int danId = pfu.getPlayer().getDanId();
int dan = me.getNewPvpManager().getPlayer().getDan();
return (int) Script.Pvp.getWinPointsWin(danId, dan);
}
// /**
// * 根据对手和自己的战斗力的比值, 计算修行值加成
// *
// * @param scale
// * @return
// */
// private float getAddition(float scale) {
// Collection<AdditionRewardTemplet> all = AdditionRewardTempletConfig.getAll();
// for (AdditionRewardTemplet temp : all) {
// if (contains(temp, scale)) {
// return temp.getAddition();
// }
// }
// return 0;
// }
//
// private boolean contains(AdditionRewardTemplet temp, float scale) {
// List<Integer> s = Util.Collection.getIntegers(temp.getRatio());
// int min = s.get(0);
// int max = s.get(1);
//
// return min <= scale && scale <= max;
// }
private int getShenJia(City city) {
Formation oF = city.getFormation();
int shenJia = oF.getShenJia();
return shenJia;
}
}
|
Markdown
|
UTF-8
| 13,452 | 2.9375 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
# How the Rust CI works
Rust CI ensures that the master branch of rust-lang/rust is always in a valid state.
A developer submitting a pull request to rust-lang/rust, experiences the following:
- A small subset of tests and checks are run on each commit to catch common errors.
- When the PR is ready and approved, the "bors" tool enqueues a full CI run.
- The full run either queues the specific PR or the PR is "rolled up" with other changes.
- Eventually a CI run containing the changes from the PR is performed and either passes or fails with an error the developer must address.
## Which jobs we run
The `rust-lang/rust` repository uses GitHub Actions to test [all the
platforms][platforms] we support. We currently have two kinds of jobs running
for each commit we want to merge to master:
- Dist jobs build a full release of the compiler for that platform, including
all the tools we ship through rustup; Those builds are then uploaded to the
`rust-lang-ci2` S3 bucket and are available to be locally installed with the
[rustup-toolchain-install-master] tool; The same builds are also used for
actual releases: our release process basically consists of copying those
artifacts from `rust-lang-ci2` to the production endpoint and signing them.
- Non-dist jobs run our full test suite on the platform, and the test suite of
all the tools we ship through rustup; The amount of stuff we test depends on
the platform (for example some tests are run only on Tier 1 platforms), and
some quicker platforms are grouped together on the same builder to avoid
wasting CI resources.
All the builds except those on macOS and Windows are executed inside that
platform’s custom [Docker container]. This has a lot of advantages for us:
- The build environment is consistent regardless of the changes of the
underlying image (switching from the trusty image to xenial was painless for
us).
- We can use ancient build environments to ensure maximum binary compatibility,
for example [using older CentOS releases][dist-x86_64-linux] on our Linux builders.
- We can avoid reinstalling tools (like QEMU or the Android emulator) every
time thanks to Docker image caching.
- Users can run the same tests in the same environment locally by just running
`src/ci/docker/run.sh image-name`, which is awesome to debug failures.
The docker images prefixed with `dist-` are used for building artifacts while those without that prefix run tests and checks.
We also run tests for less common architectures (mainly Tier 2 and Tier 3
platforms) in CI. Since those platforms are not x86 we either run
everything inside QEMU or just cross-compile if we don’t want to run the tests
for that platform.
These builders are running on a special pool of builders set up and maintained for us by GitHub.
Almost all build steps shell out to separate scripts. This keeps the CI fairly platform independent (i.e., we are not
overly reliant on GitHub Actions). GitHub Actions is only relied on for bootstrapping the CI process and for orchestrating
the scripts that drive the process.
[platforms]: https://doc.rust-lang.org/nightly/rustc/platform-support.html
[rustup-toolchain-install-master]: https://github.com/kennytm/rustup-toolchain-install-master
[Docker container]: https://github.com/rust-lang/rust/tree/master/src/ci/docker
[dist-x86_64-linux]: https://github.com/rust-lang/rust/blob/master/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile
## Merging PRs serially with bors
CI services usually test the last commit of a branch merged with the last
commit in master, and while that’s great to check if the feature works in
isolation it doesn’t provide any guarantee the code is going to work once it’s
merged. Breakages like these usually happen when another, incompatible PR is
merged after the build happened.
To ensure a master that works all the time we forbid manual merges: instead all
PRs have to be approved through our bot, [bors] (the software behind it is
called [homu]). All the approved PRs are put [in a queue][homu-queue] (sorted
by priority and creation date) and are automatically tested one at the time. If
all the builders are green the PR is merged, otherwise the failure is recorded
and the PR will have to be re-approved again.
Bors doesn’t interact with CI services directly, but it works by pushing the
merge commit it wants to test to a branch called `auto`, and detecting the
outcome of the build by listening for either Commit Statuses or Check Runs.
Since the merge commit is based on the latest master and only one can be tested
at the same time, when the results are green master is fast-forwarded to that
merge commit.
The `auto` branch and other branches used by bors live on a fork of rust-lang/rust:
[rust-lang-ci/rust]. This was originally done due to some security limitations in GitHub
Actions. These limitations have been addressed, but we've not yet done the work of removing
the use of the fork.
Unfortunately testing a single PR at the time, combined with our long CI (~3
hours for a full run)[^1], means we can’t merge too many PRs in a single day, and a
single failure greatly impacts our throughput for the day. The maximum number
of PRs we can merge in a day is around 8.
The large CI run times and requirement for a large builder pool is largely due to the
fact that full release artifacts are built in the `dist-` builders. This is worth it
because these release artifacts:
- allow perf testing even at a later date
- allow bisection when bugs are discovered later
- ensure release quality since if we're always releasing, we can catch problems early
Bors [runs on ecs](https://github.com/rust-lang/simpleinfra/blob/master/terraform/bors/app.tf) and uses a sqlite database running in a volume as storage.
[^1]: As of January 2023, the bottleneck are the `dist-x86_64-linux` and `dist-x86_64-linux-alt` runners because of their usage of [BOLT] and [PGO] optimization tooling.
[bors]: https://github.com/bors
[homu]: https://github.com/rust-lang/homu
[homu-queue]: https://bors.rust-lang.org/queue/rust
[rust-lang-ci/rust]: https://github.com/rust-lang-ci/rust
[BOLT]: https://github.com/facebookincubator/BOLT
[PGO]: https://en.wikipedia.org/wiki/Profile-guided_optimization
### Rollups
Some PRs don’t need the full test suite to be executed: trivial changes like
typo fixes or README improvements *shouldn’t* break the build, and testing
every single one of them for 2 to 3 hours is a big waste of time. To solve this
we do a "rollup", a PR where we merge all the trivial PRs so they can be tested
together. Rollups are created manually by a team member using the "create a rollup" button on the [bors queue]. The team member uses their
judgment to decide if a PR is risky or not, and are the best tool we have at
the moment to keep the queue in a manageable state.
[bors queue]: https://bors.rust-lang.org/queue/rust
### Try builds
Sometimes we need a working compiler build before approving a PR, usually for
[benchmarking][perf] or [checking the impact of the PR across the
ecosystem][crater]. Bors supports creating them by pushing the merge commit on
a separate branch (`try`), and they basically work the same as normal builds,
without the actual merge at the end. Any number of try builds can happen at the
same time, even if there is a normal PR in progress.
You can see the CI configuration for try builds [here](https://github.com/rust-lang/rust/blob/9d46c7a3e69966782e163877151c1f0cea8b630a/src/ci/github-actions/ci.yml#L728-L741).
[perf]: https://perf.rust-lang.org
[crater]: https://github.com/rust-lang/crater
## Which branches we test
Our builders are defined in [`src/ci/github-actions/ci.yml`].
[`src/ci/github-actions/ci.yml`]: https://github.com/rust-lang/rust/blob/master/src/ci/github-actions/ci.yml
### PR builds
All the commits pushed in a PR run a limited set of tests: a job containing a
bunch of lints plus a cross-compile check build to Windows mingw (without
producing any artifacts) and the `x86_64-gnu-llvm-##` non-dist builder (where
`##` is the *system* LLVM version we are currently testing). Those two
builders are enough to catch most of the common errors introduced in a PR, but
they don’t cover other platforms at all. Unfortunately it would take too many
resources to run the full test suite for each commit on every PR.
Additionally, if the PR changes certain tools (or certain platform-specific
parts of std to check for miri breakage), the `x86_64-gnu-tools` non-dist
builder is run.
### The `try` branch
On the main rust repo, `try` builds produce just a Linux toolchain using the
`dist-x86_64-linux` image.
### The `auto` branch
This branch is used by bors to run all the tests on a PR before merging it, so
all the builders are enabled for it. bors will repeatedly force-push on it
(every time a new commit is tested).
### The `master` branch
Since all the commits to `master` are fast-forwarded from the `auto` branch (if
they pass all the tests there) we don’t need to build or test anything. A quick
job is executed on each push to update toolstate (see the toolstate description
below).
### Other branches
Other branches are just disabled and don’t run any kind of builds, since all
the in-progress branches will eventually be tested in a PR.
## Caching
The main rust repository doesn’t use the native GitHub Actions caching tools.
All our caching is uploaded to an S3 bucket we control
(`rust-lang-ci-sccache2`), and it’s used mainly for two things:
### Docker images caching
The Docker images we use to run most of the Linux-based builders take a *long*
time to fully build. To speed up the build, we cache the exported images on the
S3 bucket (with `docker save`/`docker load`).
Since we test multiple, diverged branches (`master`, `beta` and `stable`) we
can’t rely on a single cache for the images, otherwise builds on a branch would
override the cache for the others. Instead we store the images identifying them
with a custom hash, made from the host’s Docker version and the contents of all
the Dockerfiles and related scripts.
### LLVM caching with sccache
We build some C/C++ stuff during the build and we rely on [sccache] to cache
intermediate LLVM artifacts. Sccache is a distributed ccache developed by
Mozilla, and it can use an object storage bucket as the storage backend, like
we do with our S3 bucket.
[sccache]: https://github.com/mozilla/sccache
## Custom tooling around CI
During the years we developed some custom tooling to improve our CI experience.
### Rust Log Analyzer to show the error message in PRs
The build logs for `rust-lang/rust` are huge, and it’s not practical to find
what caused the build to fail by looking at the logs. To improve the
developers’ experience we developed a bot called [Rust Log Analyzer][rla] (RLA)
that receives the build logs on failure and extracts the error message
automatically, posting it on the PR.
The bot is not hardcoded to look for error strings, but was trained with a
bunch of build failures to recognize which lines are common between builds and
which are not. While the generated snippets can be weird sometimes, the bot is
pretty good at identifying the relevant lines even if it’s an error we've never
seen before.
[rla]: https://github.com/rust-lang/rust-log-analyzer
### Toolstate to support allowed failures
The `rust-lang/rust` repo doesn’t only test the compiler on its CI, but also a
variety of tools and documentation. Some documentation is pulled in via git
submodules. If we blocked merging rustc PRs on the documentation being fixed,
we would be stuck in a chicken-and-egg problem, because the documentation's CI
would not pass since updating it would need the not-yet-merged version of
rustc to test against (and we usually require CI to be passing).
To avoid the problem, submodules are allowed to fail, and their status is
recorded in [rust-toolstate]. When a submodule breaks, a bot automatically
pings the maintainers so they know about the breakage, and it records the
failure on the toolstate repository. The release process will then ignore
broken tools on nightly, removing them from the shipped nightlies.
While tool failures are allowed most of the time, they’re automatically
forbidden a week before a release: we don’t care if tools are broken on nightly
but they must work on beta and stable, so they also need to work on nightly a
few days before we promote nightly to beta.
More information is available in the [toolstate documentation].
### GitHub Actions Templating
GitHub Actions does not natively support templating which can cause configurations to be large and difficult to change. We use YAML anchors for templating and a custom tool, [`expand-yaml-anchors`], to expand [the template] into the CI configuration that [GitHub uses][ci config].
This templating language is fairly straightforward:
- `&` indicates a template section
- `*` expands the indicated template in place
- `<<` merges yaml dictionaries
[rust-toolstate]: https://rust-lang-nursery.github.io/rust-toolstate
[toolstate documentation]: ../toolstate.md
[`expand-yaml-anchors`]: https://github.com/rust-lang/rust/tree/master/src/tools/expand-yaml-anchors
[the template]: https://github.com/rust-lang/rust/blob/736c675d2ab65bcde6554e1b73340c2dbc27c85a/src/ci/github-actions/ci.yml
[ci config]: https://github.com/rust-lang/rust/blob/master/.github/workflows/ci.yml
|
C#
|
UTF-8
| 2,565 | 3.078125 | 3 |
[] |
no_license
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace BogusConsoleApplication
{
internal class TcpServer
{
private readonly int _port;
private readonly CancellationToken _ct;
private readonly Func<TcpClient, CancellationToken, bool> _callback;
private readonly ManualResetEvent _clientConnected = new ManualResetEvent(false);
private readonly Logger _logger;
private TcpListener _listener;
private Task _listenerTask;
public TcpServer(int port, CancellationToken ct, Logger logger, Func<TcpClient, CancellationToken, bool> callback)
{
_logger = logger;
_callback = callback;
_port = port;
_ct = ct;
}
public void Initialize()
{
_listener = new TcpListener(IPAddress.Any, _port);
}
public void StartListener()
{
_listener.Start();
_listenerTask = Task.Run(() => ListenerThread());
}
public void StopListener()
{
_listener.Stop();
// this needs some help
_listenerTask.Wait();
}
private void ListenerThread()
{
while(!_ct.IsCancellationRequested)
{
_clientConnected.Reset();
_logger.Log("accepting clients");
// non-blocking
var client = _listener.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
_logger.Log("waiting for client connection or a cancellation");
var handleSet = WaitHandle.WaitAny(new WaitHandle[] { _ct.WaitHandle, _clientConnected });
_logger.Log($"WaitAny returned...{handleSet}");
}
}
private void AcceptTcpClientCallback(IAsyncResult ar)
{
if (_ct.IsCancellationRequested)
{
_logger.Log("early termination");
return;
}
// End the operation and display the received data on the console.
TcpClient client = _listener.EndAcceptTcpClient(ar);
// Process the connection here. (Add the client to a server table, read data, etc.)
_logger.Log("Client connected completed");
Task.Run(() => _callback(client, _ct));
_logger.Log("signalling complete");
// Signal the calling thread to continue.
_clientConnected.Set();
}
}
}
|
Java
|
ISO-8859-1
| 715 | 3.71875 | 4 |
[] |
no_license
|
package com.radrian.ejerciciosMiscelaneos.ejercicios;
import java.lang.Math;
import javax.swing.JOptionPane;
/**
* Ejercicio 5) Haz una aplicacin que calcule el rea de un crculo(pi*R2). El
* radio se pedir por teclado (recuerda pasar de String a double con
* Double.parseDouble). Usa la constante PI y el mtodo pow de Math.
*
* @author RAdrian
*
*/
public class Ejercicio05 {
public void calcularAreaCirculo() {
String userInputRadius = JOptionPane.showInputDialog("Para calcular el rea de un crculo, introduce el radio");
float areaCirculo = (float) (Math.PI * (Math.pow(Float.parseFloat(userInputRadius), 2)));
System.out.println("El area del crculo es " + areaCirculo);
}
}
|
C++
|
UTF-8
| 783 | 3.0625 | 3 |
[] |
no_license
|
/*Author: David Johnston
Class: CSI-281-01
Assignment: pa 2
Date Assigned: 9/5/13
Due Date: 9/12/13 - 12:30
Description: The purpose of this program is to recieve two polynomials from the user and add them together using a linkedlist backbone.
Certification of Authenticity:
I certify that this assignment is entirely my own work, with collaboration from West Hall study group*/
#ifndef HEADER_H
#define HEADER_H
#include <string>
#include "linkedList.h"
#include "term.h"
using namespace std;
void addPolynomials(LinkedList<Term>& poly1, LinkedList<Term>& poly2, LinkedList<Term>& sumPoly);
Term createTerm(const string term);
void displayPolynomial(LinkedList<Term>& listToDisplay);
string getPolynomial();
void populateLLWithPolynomial(LinkedList<Term>& aLinkedList);
#endif HEADER_H
|
Markdown
|
UTF-8
| 1,613 | 2.875 | 3 |
[] |
no_license
|
---
title: "Homeschool teachers"
date: 2022-10-01T13:57:50-08:00
description: "Home Schooling Tips for Web Success"
featured_image: "/images/Home Schooling.jpg"
tags: ["Home Schooling"]
---
Homeschool teachers
The teacher is the key to the success of homeschooling. In most
cases, the teacher is a parent or a close relative. In some cases,
parents may divide the subjects between them. Rarely, if both
parents are busy, they may hire a homeschool teacher. Whatever the
case, children need time with their parents. Parents, as a rule,
make very good teachers.
Teaching does not involve a clinical presentation of facts.
Learning has to be integrated lovingly into daily life for it to
interest the child. That is where parents come in. Grandparents
also make great teachers, especially since they have an abundance
of patience.
If you feel anxious about your skill or knowledge, relax. There
are countless homeschooling resources that are aimed at helping
you. Professional curriculum packages, support groups, online help
desks, virtual schools and library resources are all available.
When you start out, you may want to make use of the commercial
curriculum packages. Readymade software also allows you to record
and log important achievements.
Local support groups are an excellent source of help, ideas and
material. This is where you get to meet experienced homeschoolers,
who will be more than happy to offer their insight and advice.
Once you settle into the homeschooling routine, you will find
yourself tailoring the curriculum to suit your own needs.
(word count 219)
PPPPP
|
C++
|
UTF-8
| 1,633 | 3.0625 | 3 |
[] |
no_license
|
/*
*
*/
#include <string>
#include <vector>
#include <list>
#include <stack>
#include <sstream>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <queue>
#include <functional>
#include <algorithm>
#include <utility>
#include "utils.h"
using namespace std;
class DecodeWays {
public:
int numDecodings(string s)
{
// corner case
if(s.empty() || s[0] == '0')
return 0;
// return recursiveImpl(s, 0);
return dpImpl(s);
}
private:
// recursive solution runs too long
int recursiveImpl(const string& s, int start)
{
// when one decoding found, return 1
if(start >= s.size())
return 1;
if(s[start] == '0')
return 0;
int res = 0;
res += recursiveImpl(s, start + 1);
if(start + 1 < s.size()) {
if(s[start] == '1' || (s[start] == '2' && s[start + 1] <= '6')) {
res += recursiveImpl(s, start + 2);
}
}
return res;
}
int dpImpl(const string& s)
{
if(s.size() < 1 || s[0] == '0')
return 0;
int first = 1, second = 1, cur = second;
for(int i = 1; i < s.size(); ++i) {
cur = 0;
// decode with preceding char as one number
if(s[i - 1] == '1' || (s[i - 1] == '2' && s[i] <= '6'))
cur += first;
// decode current digit as single number
if(s[i] != '0')
cur += second;
first = second;
second = cur;
}
return cur;
}
};
|
Markdown
|
UTF-8
| 1,953 | 2.609375 | 3 |
[] |
no_license
|
本文将介绍 WordPress 平台自带的用户管理和登录认证功能。
## 前提条件
- 已开通 [云函数 SCF 服务](https://console.cloud.tencent.com/scf)。
- 已开通 [文件存储 CFS 服务](https://console.cloud.tencent.com/cfs)。
- (可选)准备好已备案的自定义域名,您也可以通过 Serverless 备案资源包完成备案(详情请参见 [ICP 备案](https://cloud.tencent.com/document/product/1154/50706))。
## 操作步骤
1. 登录 [Serverless 应用控制台](https://console.cloud.tencent.com/scf/list?rid=4&ns=default),在左侧导航栏选择 **Serverless 应用**,进入 Serverless 应用页面。
2. 在 Serverless 应用页面,单击**新建应用**,进入新建应用页面。

3. 在新建应用页面,创建方式选择**应用市场** ,模板选择**快速部署一个 Wordpress 框架**,单击**下一步**。
4. 根据页面提示,配置所需参数,单击**完成**,即可创建 WordPress 应用。
>?相关参数请参见 [快速部署 Wordpress 原生应用](https://cloud.tencent.com/document/product/1154/52643#.E6.8E.A7.E5.88.B6.E5.8F.B0.E9.83.A8.E7.BD.B2)。
>

5. 以管理员身份登录后台,在左侧导航栏,单击**用户** > **所有用户** ,进入所有用户页面。
>?假设已部署好的 WordPress 站点根路径是 `https://WORDPRESS.SITE`。
6. 在所有用户页面,可查看 WordPress 的用户列表,以及查看用户详情、维护用户信息、重置密码。

7. 访问站点首页 `https://WORDPRESS.SITE`,单击页面的**登录**,WordPress 默认的登录页面只支持账号密码认证方式。

|
JavaScript
|
UTF-8
| 1,389 | 2.625 | 3 |
[] |
no_license
|
import axios from "axios";
import { getRandomQuote, getRandomQuotes } from "../quotesAPI";
jest.mock("axios");
const DUMMY_QUOTES = [
{
id: 1,
author: "Anon",
quote: "Lorem ipsum....",
permalink: "http://quotes.stormconsultancy.co.uk/quotes/1",
},
{
id: 2,
author: "Anon",
quote: "Lorem ipsum....",
permalink: "http://quotes.stormconsultancy.co.uk/quotes/2",
},
{
id: 3,
author: "Anon",
quote: "Lorem ipsum....",
permalink: "http://quotes.stormconsultancy.co.uk/quotes/3",
},
{
id: 4,
author: "Anon",
quote: "Lorem ipsum....",
permalink: "http://quotes.stormconsultancy.co.uk/quotes/4",
},
{
id: 5,
author: "Anon",
quote: "Lorem ipsum....",
permalink: "http://quotes.stormconsultancy.co.uk/quotes/5",
},
];
it("returns random quote", async () => {
let randomInt = Math.floor(Math.random() * DUMMY_QUOTES.length);
axios.get.mockResolvedValue({
data: DUMMY_QUOTES[randomInt],
});
const { data } = await getRandomQuote();
let expected = DUMMY_QUOTES[randomInt];
expect(data.id).toEqual(expected.id);
});
it("returns random quotes", async () => {
axios.get.mockResolvedValue({
data: DUMMY_QUOTES[Math.floor(Math.random() * DUMMY_QUOTES.length)],
});
const data = await getRandomQuotes(5);
const expected = 5;
expect(data.length).toEqual(expected);
});
|
C++
|
UTF-8
| 375 | 3.34375 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
void towerOfHanoi(int n, char src, char helper, char dest)
{
if(n==0)
{
return;
}
towerOfHanoi(n-1,src,dest,helper);
cout<<"Moving ring "<<n<<" from "<<src<<" to "<<dest<<endl;
towerOfHanoi(n-1,helper,src,dest);
}
int main()
{
int n;
cin>>n;
towerOfHanoi(n,'A','C','B');
}
|
Java
|
UTF-8
| 509 | 3.578125 | 4 |
[] |
no_license
|
package primeNumber;
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
/*Scanner myVar= new Scanner(System.in);
System.out.print("Enter a number: ");
int num= myVar.nextInt();
*/
int num=10;
int i=2;
int count=0;
while(i<num)
{
if(num% i==0)
{
count=1;
break;
}
i++;
}
if (count==0)
{
System.out.println("Number is prime..");
}
else{
System.out.print("Not prime...");
}
}
}
|
JavaScript
|
UTF-8
| 3,887 | 3.15625 | 3 |
[] |
no_license
|
export default class Helpers {
// Parsing URL params
static getUrlParameter(name) {
const newName = String(name).replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp(`[\\?&]${newName}=([^&#]*)`);
const results = regex.exec(window.location.search);
return results === null ? false : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
// Generates array of times (as strings) for every X minutes
static getWorkingHorus(lap, start, end, lastM = false) {
const x = lap; // minutes interval
const times = []; // time array
let tt = start * 60; // start time
const ap = [' AM', ' PM']; // AM-PM
if (lastM) {
end = (end * 60) + (lap * 2);
} else {
end = (end * 60) + lap;
}
// loop to increment the time and push results in array
for (let i = 0; tt < end; i += 1) {
const hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
const mm = tt % 60; // getting minutes of the hour in 0-55 format
const seconds = `0${mm}`.slice(-2);
times[i] = ("" + ((hh===12)?12:hh%12)).slice(-2) + ':' + seconds + ap[Math.floor(hh/12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt += x;
}
return times;
}
// Returns an array with working days from today date up to lastD day
static getWorkingDays(lastD = 15) {
const currDate = new Date();
const workingDays = [];
for (let i = 0; i < lastD; i += 1) {
let dd = currDate.getDate();
let mm = currDate.getMonth() + 1;
const yyyy = currDate.getFullYear();
if (dd < 10) {
dd = '0'+dd;
}
if (mm < 10) {
mm = '0'+mm;
}
const vDate = mm+'-'+dd+'-'+yyyy;
// let nextDay = new Date(vDate);
// if( nextDay.getDay() !== 0 && nextDay.getDay() !== 6 ){
workingDays[i] = vDate;
// }
currDate.setDate(currDate.getDate() + 1);
}
return workingDays;
}
static getCurrentDate() {
const currDate = new Date();
let dd = currDate.getDate();
let mm = currDate.getMonth() + 1;
const yyyy = currDate.getFullYear();
if (dd < 10) {
dd = '0'+dd;
}
if (mm < 10) {
mm = '0'+mm;
}
return mm+'-'+dd+'-'+yyyy;
}
static decodeProvidedHours(weekHours, step = 30) {
const result = { sun: null, mon: [], tue: [], wed: [], thu: [], fri: [], sat: null };
for (const [key, value] of Object.entries(weekHours)) {
if (value !== null) {
result[key] = value.map(item => {
let auxTimes = item.split('-');
let startAux = auxTimes[0].split(':');
let start = Number(startAux[0]);
let endAux = auxTimes[1].split(':');
let end = Number(endAux[0]);
return this.getWorkingHorus(step, start, end, false);
});
result[key] = [].concat.apply([], result[key]);
}
}
return result;
}
static getCurrentHour() {
const time = new Date();
return time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
}
static convertHourTo24Format(timeStr) {
const sectionArr = timeStr.split(' ');
const section = sectionArr[1];
const hourArr = timeStr.split(':');
const hour = parseInt(hourArr[0], 10);
return section === 'AM' || hour === 12 ? hour : hour + 12;
}
static changeDateFormat(dateStr) {
return new Date(dateStr.replace(/-/g, '/'));
}
}
|
C++
|
UTF-8
| 1,292 | 2.796875 | 3 |
[] |
no_license
|
#include <Servo.h>
Servo servo;
double runningAvg = 0.0f;
enum ServoState {
ST,
WT,
FW,
};
int time;
int presTime;
int prevTime;
double sensorValue;
ServoState servoState = ST;
int timeSinceFw = 0;
int timeSinceInc= 0;
const int ledPin = 13;
void setup() {
Serial.begin(9600);
servo.attach(9);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
servo.write(90);
runningAvg = (double)analogRead(A0);
while (millis() < 5000) {
sensorValue = (double)analogRead(A0);
runningAvg = runningAvg*0.5 + sensorValue * 0.5;
}
digitalWrite(ledPin, LOW);
prevTime = millis();
}
void loop ()
{
sensorValue = (double)analogRead(A0);
presTime = millis();
time = presTime - prevTime;
prevTime = presTime;
double diff = runningAvg - sensorValue;
runningAvg = runningAvg*0.99 + sensorValue*0.01;
timeSinceInc = timeSinceInc + time;
timeSinceFw = timeSinceFw + time;
if (servoState == ST) {
servo.write(90);
if (diff > 2.0) {
servoState = WT;
timeSinceInc = 0;
}
}
if (servoState == WT) {
if (timeSinceInc > 350) {
servoState = FW;
timeSinceFw = 0;
}
}
if (servoState == FW) {
servo.write(0);
if (timeSinceFw > 100) {
servoState = ST;
}
}
delay(20);
}
|
JavaScript
|
UTF-8
| 2,046 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
var win = Ti.UI.createWindow({backgroundColor: "#222"});
var listView = Ti.UI.createListView();
var sections = [];
var fruitSection = Ti.UI.createListSection({ headerTitle: 'Fruits'});
var fruitDataSet = [
{properties: { title: 'Apple'}},
{properties: { title: 'Banana'}},
];
fruitSection.setItems(fruitDataSet);
sections.push(fruitSection);
var vegSection = Ti.UI.createListSection({ headerTitle: 'Vegetables'});
var vegDataSet = [
{properties: { title: 'Carrots'}},
{properties: { title: 'Potatoes'}},
];
vegSection.setItems(vegDataSet);
sections.push(vegSection);
listView.sections = sections;
win.add(listView);
win.open();
var fishSection = Ti.UI.createListSection({ headerTitle: 'Fish'});
var fishDataSet = [
{properties: { title: 'Cod'}},
{properties: { title: 'Haddock'}},
];
fishSection.setItems(fishDataSet);
listView.appendSection(fishSection);
//----
var win = Ti.UI.createWindow({
title: "List of Items",
backgroundColor: "#589"
});
var dataArray = [];
var db = Ti.Database.install('/sql/test','test');
var rows = db.execute('SELECT * FROM products');
if(Ti.UI.iOS) {
var listView = Ti.UI.createListView({
backgroundColor: "#035",
top: 20
});
}else {
var listView = Ti.UI.createListView({
backgroundColor: "#035"
});
}
var dataSection = Ti.UI.createListSection();
//console.log(rows.fieldByName("category"));
while(rows.isValidRow()) {
//console.log(rows.fieldByName("category"));
dataArray.push({
properties: {
title: "" + rows.fieldByName("category") + ""
}
});
/*var dataSet = [
{
properties: {
title: "" + rows.fieldByName("category") + "",
color: "#000",
font: {
fontSize: 20,
fontWeight: "bold"
},
backgroundColor: "#248"
}
}
];*/
console.log(dataArray + "------------");
//console.log(dataSet);
rows.next(); //note: used for while loop
}
console.log(dataArray);
dataSection.setItems(dataArray);
dataArray.push(dataSection);
listView.sections = dataArray;
win.add(listView);
win.open();
rows.close();
db.close();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.