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
| 3,559 | 1.976563 | 2 |
[] |
no_license
|
package com.example.notuygulamam.Fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.notuygulamam.Adapters.Friend_Req_Adapter;
import com.example.notuygulamam.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
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 java.util.ArrayList;
import java.util.List;
public class BildirimFragment extends Fragment {
View view;
FirebaseAuth auth;
FirebaseUser firebaseUser;
String userId;
FirebaseDatabase firebaseDatabase;
DatabaseReference reference;
List<String> friend_req_key_list;
RecyclerView friend_req_recy;
Friend_Req_Adapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_bildirim, container, false);
tanimla();
istekler();
return view;
}
public void tanimla() {
auth = FirebaseAuth.getInstance();
firebaseUser = auth.getCurrentUser();
userId = firebaseUser.getUid();
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference().child("Arkadaslik_Istek");
friend_req_key_list = new ArrayList<>();
friend_req_recy = (RecyclerView) view.findViewById(R.id.friend_req_recy);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
friend_req_recy.setLayoutManager(layoutManager);
adapter = new Friend_Req_Adapter(friend_req_key_list, getActivity(), getContext());
friend_req_recy.setAdapter(adapter);
}
public void istekler() {
reference.child(userId).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Log.i("istekler", dataSnapshot.getKey());
String kontrol = dataSnapshot.child("tip").getValue().toString();
if (kontrol.equals("alındı")) {
friend_req_key_list.add(dataSnapshot.getKey()); //kullanıcı keylerini arrayde tutuyourum.
adapter.notifyDataSetChanged();
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
friend_req_key_list.remove(dataSnapshot.getKey());
adapter.notifyDataSetChanged();
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
|
SQL
|
UTF-8
| 1,565 | 4.03125 | 4 |
[] |
no_license
|
-- Bài 1
-- Hiển thị tất cả thông tin khách hàng (câu a)
select *
from KHACHHANG;
select *
from sanpham;
-- Hiển thị 3 khách hàng đầu tiên( câu b )
select maKhachHang,HovaTen,email,dienThoai
from khachhang limit 3;
-- Hiển thị tất cả thông tin sản phẩm (câu c)
select maSanPham,tenSP, CONCAT(soLuong*donGia) as 'Tổng tiền tồn kho'
from sanpham;
-- Yêu cầu câu d
select CONCAT(HovaTen, ' ',Ten) as 'Ho va Ten ',maKhachHang,diaChi
from khachhang
where Ten like 'H%';
-- Yêu cầu câu e
select *
from khachhang
where diaChi like 'Đà Nẵng%';
-- Yêu cầu f
select * from sanpham
where soLuong between 100 and 500 ;
-- Yêu cầu g
select *
from hoadon
where ngayMuaHang like '2016%';
-- Yê cầu h
select * from hoadon
where maKhachHang like '321%';
-- Bài 2
-- Câu a
select *from khachhang;
-- Câu b
select *
from sanpham;
select Max(donGia) as 'Đơn giá cao nhất'
from sanpham;
-- Câu c
select min(soLuong) as 'Số lượng sản phẩm thấp nhất'
from sanpham;
-- Câu d
select sum(soLuong) as 'Tổng số sản phẩm'
from sanpham;
-- Câu e
select
*from hoadon
where ngayMuaHang like '2016-12%' and trangThai like 'chuaThanhToan%' ;
-- Câu f
select maHoaDon,soLuong as'Sản phẩm được mua'
from hoadonchitiet;
-- Câu g
select maHoaDon,soLuong as'Sản phẩm được mua'
from hoadonchitiet
where soLuong >=5;
-- Câu h
select *from hoadon;
select maHoaDon,ngayMuaHang,maKhachHang
from hoadon
ORDER BY ngayMuaHang DESC;
|
C++
|
UTF-8
| 3,935 | 3.046875 | 3 |
[] |
no_license
|
/**
* @file src/program/game/Entity.hpp
* @author Adam 'Adanos' Gąsior
* Used library: SFML
*/
#pragma once
#include <SFML/Graphics.hpp>
namespace rr
{
class Item;
class Entity : public sf::Drawable
{
public: enum Species
{
NONE,
CHEST,
DOOR,
ITEM,
N_P_C,
PLAYER,
STAIRS
};
////////////////////////////////////////////////////////////////////////
/// \brief Virtual destructor.
////////////////////////////////////////////////////////////////////////
virtual ~Entity() {}
////////////////////////////////////////////////////////////////////////
/// \brief Virtual constructor: cloning
////////////////////////////////////////////////////////////////////////
virtual Entity* clone() const = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Sets the entity's position in relation to the actual
/// coordinate system.
////////////////////////////////////////////////////////////////////////
virtual void setGridPosition(sf::Vector2i pos) = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Returns the entity's position in relation to the actual
/// coordinate system.
////////////////////////////////////////////////////////////////////////
virtual sf::Vector2i getGridPosition() const = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Sets the entity's position in relation to the grid.
////////////////////////////////////////////////////////////////////////
virtual void setPosition(sf::Vector2f pos) = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Returns the entity's position in relation to the grid.
////////////////////////////////////////////////////////////////////////
virtual sf::Vector2f getPosition() const = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Returns the entity's bound box.
////////////////////////////////////////////////////////////////////////
virtual sf::FloatRect getBounds() const = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Tells if this entity collides with another one.
////////////////////////////////////////////////////////////////////////
virtual bool collides(Entity*) const = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Reads the entity from file.
////////////////////////////////////////////////////////////////////////
virtual std::ifstream& operator<< (std::ifstream&) = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Writes the entity to file.
////////////////////////////////////////////////////////////////////////
virtual std::ofstream& operator>> (std::ofstream&) = 0;
////////////////////////////////////////////////////////////////////////
/// \brief Returns the species of the entity.
////////////////////////////////////////////////////////////////////////
virtual Species getSpecies() const = 0;
private: ////////////////////////////////////////////////////////////////////////
/// \brief Initializes the object.
////////////////////////////////////////////////////////////////////////
virtual void initialize() = 0;
};
}
|
C++
|
UTF-8
| 2,527 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
// Copyright (c) 2019-2020 OuterC - Nomango
#pragma once
#include "json_value.h"
namespace oc
{
namespace __json_detail
{
template <typename _BasicJsonTy>
struct json_value_getter
{
using string_type = typename _BasicJsonTy::string_type;
using char_type = typename _BasicJsonTy::char_type;
using integer_type = typename _BasicJsonTy::integer_type;
using float_type = typename _BasicJsonTy::float_type;
using boolean_type = typename _BasicJsonTy::boolean_type;
using array_type = typename _BasicJsonTy::array_type;
using object_type = typename _BasicJsonTy::object_type;
static inline void assign(const _BasicJsonTy& json, object_type& value)
{
if (!json.is_object()) throw json_type_error("json value type must be object");
value = *json.value_.data.object;
}
static inline void assign(const _BasicJsonTy& json, array_type& value)
{
if (!json.is_array()) throw json_type_error("json value type must be array");
value = *json.value_.data.vector;
}
static inline void assign(const _BasicJsonTy& json, string_type& value)
{
if (!json.is_string()) throw json_type_error("json value type must be string");
value = *json.value_.data.string;
}
static inline void assign(const _BasicJsonTy& json, boolean_type& value)
{
if (!json.is_boolean()) throw json_type_error("json value type must be boolean");
value = json.value_.data.boolean;
}
static inline void assign(const _BasicJsonTy& json, integer_type& value)
{
if (!json.is_integer()) throw json_type_error("json value type must be integer");
value = json.value_.data.number_integer;
}
template <
typename _IntegerTy,
typename std::enable_if<std::is_integral<_IntegerTy>::value, int>::type = 0>
static inline void assign(const _BasicJsonTy& json, _IntegerTy& value)
{
if (!json.is_integer()) throw json_type_error("json value type must be integer");
value = static_cast<_IntegerTy>(json.value_.data.number_integer);
}
static inline void assign(const _BasicJsonTy& json, float_type& value)
{
if (!json.is_float()) throw json_type_error("json value type must be float");
value = json.value_.data.number_float;
}
template <
typename _FloatingTy,
typename std::enable_if<std::is_floating_point<_FloatingTy>::value, int>::type = 0>
static inline void assign(const _BasicJsonTy& json, _FloatingTy& value)
{
if (!json.is_float()) throw json_type_error("json value type must be float");
value = static_cast<_FloatingTy>(json.value_.data.number_float);
}
};
} // namespace __json_detail
} // namespace oc
|
C#
|
UTF-8
| 931 | 3.015625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace VsPlayer
{
class CommandExcute
{
public static string executeCmd(string[] Commands)
{
Process process = new Process
{
StartInfo = { FileName = "cmd.exe", UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true }
};
process.Start();
foreach (string cmd in Commands)
process.StandardInput.WriteLine(cmd);
process.StandardInput.WriteLine("exit");
process.WaitForExit();
string str = process.StandardOutput.ReadToEnd();
process.Close();
return str;
}
public static string executeCmd(string Command)
{
return executeCmd(new string[] { Command });
}
}
}
|
Markdown
|
UTF-8
| 1,159 | 2.875 | 3 |
[] |
no_license
|
# 见面之后的感想 - 雷霄骅(leixiaohua1020)的专栏 - CSDN博客
2014年12月18日 13:54:51[雷霄骅](https://me.csdn.net/leixiaohua1020)阅读数:5635
好久没写非技术文字,见面之后的感想,记录几句。
这件事从头至尾都是一个不可思议故事,以至于让我自己都有些稀里糊涂。而如今它却迅速迎来一个非常寻常的结尾。尽管很多人都说“不忘初心”,但是实际上实践起来却很不容易。当人们长时间经历过不同的生活环境之后,已经不太容易有相同的思维方式。而空间上距离的遥远更是无法逾越的障碍。
不可思议的故事确实很难发生,更多的还是平凡的故事。
我也想过有可能是这样的结尾,毕竟时间和空间都是一把利刃。但是尽管如此,我还是决定等待一下,想要在见面的时候,看看你有什么变化。
而如今在经过一阵沉重的阴郁之后也感觉轻松了很多,也更加“接地气”一些,看来今后还是应该从身边找爱情。
不管怎样还是要祝福你,希望你在国外能够过上幸福的生活。
|
C
|
UTF-8
| 2,939 | 2.6875 | 3 |
[] |
no_license
|
#include<pic.h>
//LCD PIN Connection
#define rs RE0
#define rw RE1
#define en RE2
//Signal1 LED
#define S1G RB0
#define S1Y RB1
#define S1R RB2
//Signal2 LED
#define S2G RB3
#define S2Y RB4
#define S2R RB5
//Signal3 LED
#define S3G RB6
#define S3Y RB7
#define S3R RC0
//Signal4 LED
#define S4G RC1
#define S4Y RC2
#define S4R RC3
unsigned int j,g=0,o=10,a,b;
//Delay function
void del(unsigned int y)
{
while(y--);
}
//Function to send LCD Command
/*
RS - Register select
0-Instruction Input
1-Data Input
R/W - Read/Write (R/W)
0-Write to LCD
1-Read from LCD
Enable (E)-Allows access to the display through R/W and RS lines
*/
void lcd_command(unsigned char com)
{
PORTD=com;
rs=0;
rw=0;
en=1;
del(125);
en=0;
}
//Function to send LCD Data
void lcd_data(unsigned char dat)
{
PORTD=dat;
rs=1;
rw=0;
en=1;
del(125);
en=0;
}
void lcd_init()
{
lcd_command(0X38);//8-bit mode
lcd_command(0X06);//entry mode
lcd_command(0X0c);//display on and cursor off
lcd_command(0X01);//clear display
}
void lcd_disply(const unsigned char *da)
{
unsigned int i;
for(i=0;da[i]!=0;i++)
{
del(1000);
lcd_data(da[i]);
}
}
void delay1()
{
for(j=0;j<110;j++)
{
TMR1L=0X2B;//dec val = 43, LSB
TMR1H=0XCF;//dec val = 207, MSB
T1CKPS0=1;
T1CKPS1=1;//1:8 prescalar value
TMR1CS=0;//external clk
TMR1ON=1;
while(TMR1IF==0);
TMR1IF=0;
TMR1ON=0;
g=g+1;
if(g==10)
{
g=0;
a=o/10;
b=o%10;
o=o-1;
lcd_command(0X85);
lcd_data(a+0X30);
lcd_data(b+0X30);
}
}
o=10;
}
void delay2()
{
for(j=0;j<110;j++)
{
TMR1L=0X2B;
TMR1H=0XCF;
T1CKPS0=1;
T1CKPS1=1;
TMR1CS=0;
TMR1ON=1;
while(TMR1IF==0);
TMR1IF=0;
TMR1ON=0;
g=g+1;
if(g==10)
{
g=0;
a=o/10;
b=o%10;
o=o-1;
lcd_command(0X8d);
lcd_data(a+0X30);
lcd_data(b+0X30);
}
}
o=10;
}
void delay3()
{
for(j=0;j<110;j++)
{
TMR1L=0X2B;
TMR1H=0XCF;
T1CKPS0=1;
T1CKPS1=1;
TMR1CS=0;
TMR1ON=1;
while(TMR1IF==0);
TMR1IF=0;
TMR1ON=0;
g=g+1;
if(g==10)
{
g=0;
a=o/10;
b=o%10;
o=o-1;
lcd_command(0Xc5);
lcd_data(a+0X30);
lcd_data(b+0X30);
}
}
o=10;
}
void delay4()
{
for(j=0;j<110;j++)
{
TMR1L=0X2B;
TMR1H=0XCF;
T1CKPS0=1;
T1CKPS1=1;
TMR1CS=0;
TMR1ON=1;
while(TMR1IF==0);
TMR1IF=0;
TMR1ON=0;
g=g+1;
if(g==10)
{
g=0;
a=o/10;
b=o%10;
o=o-1;
lcd_command(0Xcd);
lcd_data(a+0X30);
lcd_data(b+0X30);
}
}
o=10;
}
void delay5()
{
for(j=0;j<30;j++)
{
TMR1L=0X2B;
TMR1H=0XCF;
T1CKPS0=1;
T1CKPS1=1;
TMR1CS=0;
TMR1ON=1;
while(TMR1IF==0);
TMR1IF=0;
TMR1ON=0;
}
}
/* MAIN function*/
void main()
{
ADCON1=0X06;
TRISE=0X00;
TRISD=0X00;
PORTE=PORTD=0X00;
TRISB=0X00;
PORTB=0X00;
TRISC=0X00;
PORTC=0X00;
lcd_init();
lcd_command(0X80);
lcd_disply("SIG1: SIG2: ");
lcd_command(0XC0);
lcd_disply("SIG3: SIG4: ");
while(1)
{
S1G=1;
S2R=S3R=S4R=1;
delay1();
S1G=0;S1Y=1;
delay5();
S1Y=0;
S2G=1;S2R=0;
S1R=S3R=S4R=1;
delay2();
S2G=0;S2Y=1;
delay5();
S2Y=0;
S3G=1;S3R=0;
S1R=S2R=S4R=1;
delay3();
S3G=0;S3Y=1;
delay5();
S3Y=0;
S4G=1;S4R=0;
S1R=S3R=S2R=1;
delay4();
S4G=0;S4Y=1;
delay5();
S4Y=0;
}
}
|
JavaScript
|
UTF-8
| 896 | 2.609375 | 3 |
[] |
no_license
|
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
http.createServer(function (req, res) {
var uri = url.parse(req.url).pathname;
console.log(uri);
ext = path.extname(uri);
if (ext == '') {
uri += '.html';
}
filePath = './public' + uri
console.log('Incoming request to ' + req.url);
console.log('Incoming request resolved to ' + filePath);
if (req.url === '/favicon.ico') {
return res.end();
}
fs.readFile(filePath, function (err, data) {
if (err) throw err;
console.log('ext is ' + ext);
if (ext == '.css') {
res.writeHead(200, {'Content-Type': 'text/css'});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
}
res.write(data);
res.end();
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
|
C
|
UTF-8
| 293 | 3.28125 | 3 |
[] |
no_license
|
#include "get_next_line.h"
int main()
{
int fd;
int i;
char *line;
fd = open("text.txt", O_RDONLY);
i = 0;
while((i = get_next_line(fd, &line)) > 0)
{
printf("i = %d |%s|\n", i, line);
free(line);
}
if (line)
{
printf("i = %d |%s|\n", i, line);
free(line);
}
return 0;
}
|
C++
|
UTF-8
| 3,281 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
//------------------------------------------------------------------------------------------------
// File: animatedmeshcontroller.h
//
// Desc:
//
// Copyright (c) 2007-2008 Unseen Studios. All rights reserved.
//------------------------------------------------------------------------------------------------
#ifndef __ANIMATEDMESHCONTROLLER_H__
#define __ANIMATEDMESHCONTROLLER_H__
struct UnseenSkeletalAnimation;
struct D3DXMATRIX;
struct GameFileDataSkinnedMesh;
struct IDirect3DDevice9;
typedef struct IDirect3DDevice9 *LPDIRECT3DDEVICE9;
class IsometricCamera;
/**
* This class is used to manage animations
*/
class AnimatedMeshController {
/**
* Stores information about an animation's state
*/
struct AnimationState
{
UnseenSkeletalAnimation* animation;
double time;
float speed;
};
public:
/**
* Initializes this class
*/
AnimatedMeshController();
/**
* Initializes this controller to handle animations for the given skinned mesh
*/
// TODO: why isn't this const?
bool create(GameFileDataSkinnedMesh* skinnedMesh);
/**
* Frees memory used by this class
*/
void destroy();
/**
* Determines whether or not this animation controller is valid
*/
bool isInitialized() const;
/**
* Updates this mesh controller
*/
void advance(const D3DXMATRIX* rootMatrix, double currentFrameTime, double timeSinceLastUpdate);
/**
* Sets the mesh's bone matrices into the device using the camera
*/
void setBoneMatrices(LPDIRECT3DDEVICE9 d3dDevice, IsometricCamera* camera);
/**
* Sets the base animation. The base animation loops, and should be something
* like idling, walking, running or sleeping.
*/
// todo: why not const?
void changeBaseAnimation(UnseenSkeletalAnimation* animation, float speed);
/**
* Sets the base animation to be at a given time index with 0 speed. Usually this is only invoked for death.
*/
void changeBasePose(UnseenSkeletalAnimation* animation, float posePercent);
/**
* Executes a specific action animation. This is intended to be used for things
* like attacking, spells, emotes, etc.
*/
void runAnimationOnce(UnseenSkeletalAnimation* animation, float speed);
/**
*
*/
const D3DXMATRIX* getBoneMatrix(size_t boneIndex);
protected:
/**
* Resets this class
*/
void zero();
protected:
/// The mesh that this animation controller manages
GameFileDataSkinnedMesh* mySkinnedMesh;
/// The set of matrices used to position this mesh
D3DXMATRIX* myFrameMatrices;
/// The current base animations
AnimationState myPrimaryBaseAnimationState;
AnimationState mySecondaryBaseAnimationState;
/// The primary weight defines the amount of weight placed on the
/// primary animation. The secondary animation has 1.0 - this value
/// as its weight. During each advance(), this value is pushed
/// toward 1.0 so that the secondary animation always goes away.
float myPrimaryBaseAnimationWeight;
/// The action animation weight. This is 1.0 while the action
/// animation is running, then drops off to 0.0 when it finishes.
float myActionAnimationWeight;
/// This animation gets full priority to run a single time
AnimationState myActionAnimationState;
};
#endif
|
PHP
|
UTF-8
| 2,494 | 2.796875 | 3 |
[] |
no_license
|
<?php
namespace App\Jobs;
use App\Route;
class SendApiRequest extends Job
{
protected $route;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Route $route)
{
$this->route = $route;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// Fetch locations from model
$origin = $this->route->locations()->where('category', 'origin')->first();
$destination = $this->route->locations()->where('category', 'destination')->first();
$waypoints = $this->route->locations()->where('category', 'waypoint')->get();
// Build query for access google maps api
$url = 'https://maps.googleapis.com/maps/api/directions/json?';
$query = [
'key' => 'AIzaSyBzBmtwh4MhdeMXchQUnau1t3WTRYp69yY',
'origin' => $origin->lat . ',' . $origin->lng,
'destination' => $destination->lat . ',' . $destination->lng,
];
$url .= urldecode(http_build_query($query));
// add query when there is waypoint
if ($waypoints->count() > 0) {
$waypoint_str = '&waypoints=optimize:true';
foreach ($waypoints as $waypoint) {
$waypoint_str .= '|' . $waypoint->lat . ',' . $waypoint->lng;
}
$url .= $waypoint_str;
}
// Call api via cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
if ($output === FALSE) {
$this->route->update([
'status' => Route::STATUS_FAIL
]);
return false;
}
$info = curl_getinfo($ch);
$http_result = $info ['http_code'];
curl_close($ch);
// Update model with response
$json = json_decode($output, true);
$legs = $json['routes'][0]['legs'];
// Sum up distance and time for each legs
$distance = 0;
$time = 0;
foreach($legs as $leg) {
$distance += $leg['distance']['value'];
$time += $leg['duration']['value'];
}
$this->route->update([
'distance' => $distance,
'time' => $time,
'status' => Route::STATUS_SUCCESS
]);
return true;
}
}
|
Markdown
|
UTF-8
| 429 | 2.765625 | 3 |
[] |
no_license
|
# Float
A **Float** \(Floating Point\) data type represents a numerical value, which contain a decimal point.
**Floats** have a very large range, at the cost of some precision.
They are mostly used for very large and very small numbers where _relative accuracy_ is needed.
For more in-depth information on floating point numbers:
[Floating Point Numbers](https://floating-point-gui.de/formats/fp/) on floating-point-gui.de
|
Shell
|
UTF-8
| 624 | 3.671875 | 4 |
[] |
no_license
|
imgs_file='imgs.list' #存储着图片src的文件
imgs_dir='./img' #用于保存下载图片的路经
exist_file='exist.list' #用于保存之前已经下载过的标题
mkdir $imgs_dir
cat $imgs_file | while read line
do
if [[ "$line" =~ "#" ]];then
{
line=`echo $line | sed 's/\ //g' | sed 's/\[/(/g' | sed 's/\]/)/g'`
flag=`grep "$line" $exist_file`
if [[ "$flag" == "" ]];then
lock="false"
echo $line >> $exist_file
echo "不存在 $line"
wait
else
lock="true"
echo "存在 $line"
fi
}
else
if [[ "$lock" == "false" ]];then
{
wget $line -P "$imgs_dir" -t 1
}&
fi
fi
done
|
C#
|
UTF-8
| 754 | 2.71875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Einfall.Editor
{
// An ending list and a possibility to work out containing varaibles would be nice
public class FunctionMetaData
{
int _startingLineNumber;
string _name;
public string Name
{
get { return _name; }
}
public int StartLine
{
get { return _startingLineNumber; }
}
public FunctionMetaData(int line, string name)
{
_startingLineNumber = line;
_name = name;
}
public override string ToString()
{
return _name;
}
}
}
|
Swift
|
UTF-8
| 2,667 | 2.59375 | 3 |
[] |
no_license
|
//
// LoginTextField.swift
// PlantTree
//
// Created by Admin on 27/04/2017.
// Copyright © 2017 greenworld. All rights reserved.
//
import UIKit
//@IBDesignable
class LoginTextField : UITextField {
//Initializers
private let iconView = UIImageView()
private let iconBox = UIView()
private let lineLayer = CALayer()
@IBInspectable
private var lineWidth : CGFloat = 2
private var _iconName = ""
@IBInspectable
var iconName: String {
get {
return self._iconName
}
set {
self._iconName = newValue
iconView.image = UIImage(named: self._iconName)
}
}
override var placeholder: String? {
get {
return super.attributedPlaceholder?.string
}
set {
let font = UIFont(name: "Helvetica", size: 18)!
let fontColor = DesignerColors.text_light_gray
let attributedPlaceholderText =
NSMutableAttributedString(
string: newValue ?? "",
attributes: [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: fontColor]
)
self.attributedPlaceholder = attributedPlaceholderText
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUi()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupUi()
}
func setupUi() {
self.iconBox.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
self.iconBox.addSubview(self.iconView)
self.iconView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
self.leftView = self.iconBox
self.leftViewMode = .always
self.layer.addSublayer(self.lineLayer)
self.backgroundColor = .clear
self.textColor = UIColor.white
self.drawBottomLine()
self.placeholder = super.placeholder
}
// Helper functions
private func drawBottomLine() {
self.lineLayer.frame = CGRect(x: 0, y: self.frame.size.height - self.lineWidth, width: self.frame.size.width, height: self.lineWidth)
self.lineLayer.backgroundColor = UIColor.white.cgColor
}
// Overrides
override func layoutSubviews() {
super.layoutSubviews()
self.drawBottomLine()
}
// Interface
func setImage(img: UIImage?) {
self.iconView.image = img
}
func setPlaceholderText(text: String) {
}
}
|
Java
|
UTF-8
| 5,800 | 3.140625 | 3 |
[] |
no_license
|
package hr.fer.zemris.java.hw02;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class ComplexNumberTest {
static ComplexNumber c1 = new ComplexNumber(1, 1); // 1+i
static ComplexNumber c2 = new ComplexNumber(-2.1, 1); // -2.1 + i
static ComplexNumber c3 = new ComplexNumber(-3, -2.21); // -3-2.21i
static ComplexNumber c4 = new ComplexNumber(1, -2); // 1 - 2i
static final double DIFFERENCE = 10E-7;
@Test
void testComplexNumber() {
ComplexNumber z = new ComplexNumber(5, 10);
assertEquals(5, z.getReal());
assertEquals(10, z.getImaginary());
}
@Test
void testFromReal() {
ComplexNumber c = ComplexNumber.fromReal(3);
assertEquals(new ComplexNumber(3, 0), c);
}
@Test
void testFromImaginary() {
ComplexNumber c = ComplexNumber.fromImaginary(-3);
assertEquals(new ComplexNumber(0, -3), c);
}
@Test
void testFromMagnitudeAndAngle() {
ComplexNumber c = ComplexNumber.fromMagnitudeAndAngle(Math.sqrt(2), Math.PI/4);
assertEquals(c1, c);
}
@Test
void testFromMagnitudeAndAngleNegativeMagnitude() {
try {
ComplexNumber.fromMagnitudeAndAngle(-2, Math.PI/4);
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testParse1() {
assertEquals(new ComplexNumber(1, 1), ComplexNumber.parse("1+i"));
}
@Test
void testParse2() {
assertEquals(new ComplexNumber(-3, -2.21), ComplexNumber.parse("-3 - 2.21i"));
}
@Test
void testParse3() {
assertEquals(new ComplexNumber(0, -1), ComplexNumber.parse("-i"));
}
@Test
void testParse4() {
assertEquals(new ComplexNumber(3.23, 0), ComplexNumber.parse("+3.23"));
}
@Test
void testParse5() {
assertEquals(new ComplexNumber(3.23, 0), ComplexNumber.parse("+3.23 + 0i"));
}
@Test
void testParseNull() {
try {
ComplexNumber.parse(null);
fail("Must fail");
} catch(NullPointerException exc) {
assertTrue(true);
}
}
@Test
void testParseFail1() {
try {
ComplexNumber.parse("-2+-3i");
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testParseFail2() {
try {
ComplexNumber.parse("++2-3i");
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testParseFail3() {
try {
ComplexNumber.parse("-2-+3i");
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testParseFail4() {
try {
ComplexNumber.parse("-2--3i");
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testParseFail5() {
try {
ComplexNumber.parse("-2-i3");
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testParseFailWithoutI() {
try {
ComplexNumber.parse("-2-3");
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testParseFailUnsupported() {
try {
ComplexNumber.parse("-2-f3fs");
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testGetReal() {
assertEquals(-2.1, c2.getReal());
}
@Test
void testGetImaginary() {
assertEquals(1, c1.getImaginary());
}
@Test
void testGetMagnitude() {
assertEquals(Math.sqrt(2), c1.getMagnitude());
}
@Test
void testGetAngleFirstQuandrant() {
assertEquals(Math.PI/4, c1.getAngle());
}
@Test
void testGetAngleSecondQuandrant() {
assertTrue((2.697173444 - c2.getAngle()) < DIFFERENCE);
}
@Test
void testGetAngleThirdQuandrant() {
assertTrue((3.776505676 - c3.getAngle()) < DIFFERENCE);
}
@Test
void testGetAngleFourthQuandrant() {
assertTrue((5.176036589 - c4.getAngle()) < DIFFERENCE);
}
@Test
void testAdd() {
assertEquals(new ComplexNumber(-1.1, 2), c1.add(c2));
}
@Test
void testAddNull() {
try {
c1.add(null);
fail("Must fail");
} catch(NullPointerException exc) {
assertTrue(true);
}
}
@Test
void testSub() {
assertEquals(new ComplexNumber(0.9, 3.21), c2.sub(c3));
}
@Test
void testSubNull() {
try {
c1.sub(null);
fail("Must fail");
} catch(NullPointerException exc) {
assertTrue(true);
}
}
@Test
void testMul() {
assertEquals(new ComplexNumber(3, -1), c1.mul(c4));
}
@Test
void testAddMul() {
try {
c1.mul(null);
fail("Must fail");
} catch(NullPointerException exc) {
assertTrue(true);
}
}
@Test
void testDiv() {
assertEquals(new ComplexNumber(-0.2, 0.6), c1.div(c4));
}
@Test
void testDivWithZero() {
ComplexNumber c = new ComplexNumber(0, 0);
ComplexNumber z = c1.div(c);
assertTrue(Double.isNaN(z.getReal()));
assertTrue(Double.isNaN(z.getImaginary()));
}
@Test
void testAddDiv() {
try {
c1.div(null);
fail("Must fail");
} catch(NullPointerException exc) {
assertTrue(true);
}
}
@Test
void testPower() {
assertEquals(new ComplexNumber(-11, 2), c4.power(3));
}
@Test
void testPowerWithZero() {
assertEquals(new ComplexNumber(1, 0), c4.power(0));
}
@Test
void testPowerLowerBound() {
try {
c1.power(-1);
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testRoot() {
ComplexNumber root1 = new ComplexNumber(1.0986841, 0.4550899);
ComplexNumber root2 = new ComplexNumber(-1.0986841, -0.4550899);
assertEquals(root1, c1.root(2)[0]);
assertEquals(root2, c1.root(2)[1]);
}
@Test
void testRootLowerBound() {
try {
c1.root(0);
fail("Must fail");
} catch(IllegalArgumentException exc) {
assertTrue(true);
}
}
@Test
void testEquals() {
ComplexNumber z = new ComplexNumber(1.000000001, -2.000000001);
ComplexNumber w = new ComplexNumber(1.000000002, -2.000000002);
assertEquals(z, w);
}
}
|
JavaScript
|
UTF-8
| 1,021 | 2.53125 | 3 |
[] |
no_license
|
import React, {
createContext,
useContext,
useState,
useMemo,
useCallback,
} from "react";
const themes = {
light: {
type: "light",
fontColor: "#2b2c38",
background: "#fff",
},
dark: {
type: "dark",
fontColor: "#dcdcdc",
background: "#2b2c38",
},
};
const ThemeContext = createContext({});
export default function ThemeProvider({ children }) {
const [theme, setTheme] = useState(themes.light);
// useCallback will return a memoized version of the callback that only changes if one of the inputs has changed.
const toggleTheme = useCallback(() => {
setTheme(theme === themes.dark ? themes.light : themes.dark);
}, [theme]);
// useMemo will only recompute the memoized value when one of the deps has changed.
const themeAPI = useMemo(() => {
return { theme, toggleTheme };
}, [theme, toggleTheme]);
return (
<ThemeContext.Provider value={themeAPI}>{children}</ThemeContext.Provider>
);
}
export const useTheme = () => useContext(ThemeContext);
|
Java
|
UTF-8
| 1,027 | 2.21875 | 2 |
[] |
no_license
|
// Generated by Dagger (https://dagger.dev).
package com.hs.weatherforecast.domain.usecase;
import com.hs.weatherforecast.repo.CurrentWeatherRepository;
import dagger.internal.Factory;
import javax.inject.Provider;
@SuppressWarnings({
"unchecked",
"rawtypes"
})
public final class CurrentWeatherUseCase_Factory implements Factory<CurrentWeatherUseCase> {
private final Provider<CurrentWeatherRepository> repositoryProvider;
public CurrentWeatherUseCase_Factory(Provider<CurrentWeatherRepository> repositoryProvider) {
this.repositoryProvider = repositoryProvider;
}
@Override
public CurrentWeatherUseCase get() {
return newInstance(repositoryProvider.get());
}
public static CurrentWeatherUseCase_Factory create(
Provider<CurrentWeatherRepository> repositoryProvider) {
return new CurrentWeatherUseCase_Factory(repositoryProvider);
}
public static CurrentWeatherUseCase newInstance(CurrentWeatherRepository repository) {
return new CurrentWeatherUseCase(repository);
}
}
|
Markdown
|
UTF-8
| 12,670 | 3.46875 | 3 |
[] |
no_license
|
preprocess:
replace "IMAGE: ([^;\n]+);?(.*)" -> "<center><img src=\"/circle-tree-system/intro/\\1.svg\" \\2 /></center>"
replace "<!--a*-->" -> ""
---
layout: post
title: Introducing the Circle-Tree System
comments: True
---
If you want to follow along on paper, you'll want some colored pencils. Like at least 5 colors, not including a pencil to draw links.
# Circtrees
In any case, we'll call the diagrams we're interested in "circtrees."[^1] Circtrees can be constructed in one of three ways.
## 1. Dots
A dot of any color is a circtree. Here are some examples[^2]:
IMAGE: vars
<!--end excerpt-->
## 2. Bubbles
A circtree that's placed in a bubble is still a circtree. Note that you multiple bubbles around a circtree, since each time you bubble it, it's still a circtree.
IMAGE: lambdas
(For now, the light coloration inside the circles is a little confusing; it'll make for nicer diagrams later. For now, just ignore the filling and focus on the bubble boundary.)
## 3. Links
A circtree that is linked to another circtree is a circtree.
IMAGE: apps
The links can overall form a tree-like structure, for example:
IMAGE: tree
You might have to flip the circtree upside down to see the tree, but it's there[^3].
## And that's all
Those are the only ways to create circtrees! It's a fairly simple system, but we can see that it's an incredibly useful one.
# Redraws
A redraw is a way to take a circtree and get another circtree. The intuition behind a redraw is that if we can redraw two circtrees into the same circtree, they are "equivalent" in some sense.
# The Recolor Redraw
A recolor is a way to change up the colors on a diagram. To understand the steps, we first need to define a bit of terminology: "contained".
## What does "Contained" mean?
Contained is a relationship between dots and bubbles of the same color. It doesn't make sense to say if a tree is contained in a bubble or if a dot is contained in a tree.
The basic intuition behind containment is that bubbles are kinda like fences that keep dots (let's call them sheep[^4]) of the same color in. So if you have:
IMAGE: red-inside-red; height="200"
then the red dot ("sheep") is contained inside the red bubble ("fence").
However, if you have:
IMAGE: red-inside-blue; height="200"
then the red sheep can escape because it can travel through a blue fence to the outside world. So we call this dot "free".
We say that a dot is "contained" by the first fence that it runs into if it tries to escape.
Now let's look at a more complicated example:
IMAGE: contained-threedots; height="200"
With the green dot, if we move outward, we hit the inner green bubble. Therefore the green dot is contained in the inner green bubble. The red dot can "move through" the green fence, but it can't get out of the red one immediately outside, so it is contained in the red fence.
Finally, the blue dot can go through both fences to freedom! That means that the blue dot is free.
<mark>Important note: When we talk about containment, we talk about where dots <i>could move</i> under the restriction that they can't move through bubbles of the same color, not where dots <i>do move</i>. Dots don't actually move through bubbles of different colors (i.e., moving a dot through a bubble isn't an allowable redraw in general); it's just a thought experiment to motivate this definition. </mark>
Here's another example:
IMAGE: contained-outside; height="200"
If we look at the dot on the left, it's clear that it's stuck in the bubble on the left. However, the dot on the right is free because it isn't in a bubble at all!
And finally one last example:
IMAGE: contained-two-same-color; height="200"
OK, so this one's a little more complicated. If we look at the dot on the left, if it wanted to escape it would have to go through *two* red fences. So which one is the one it's contained in? Well, the definition says that it's always the first fence that blocks it, so it's contained in the smaller bubble. The red dot on the right, however, is contained in the larger bubble because that's the first (and only) fence that would block *it*.
## Problems for Contained
For each of the given circtrees, go through every dot and figure out if it is contained in a bubble or if it is free. If it is contained in a bubble, identify the bubble.
IMAGE: contained-exercises; height="600"
## What is recoloring?
It's probably best to think of recoloring as a puzzle. You're shown a circtree, for example:
IMAGE: recolor-example; height="400"
And then you're given a bubble (for example, the larger green one) and told to change it to a color of your choice. You are allowed to change the color of any of the dots.
The one rule is that which bubble dots belong to should not be changed. However, actually just randomly picking colors for each dot until you find an arrangement that works takes a long time, so we instead have a few shortcut rules that lead to a process for recoloring rather than just a definition.
### 1. Contained Dots
Let's say we just change the color of the green bubble to yellow;
IMAGE: recolor-example-didnt-change-contained
Why doesn't it work? Well, we can see that the green dots on the left and in the purple bubble are free whereas before they were contained in our bubble. What this tells us is that we need to change the colors of the dots that are contained in our bubble. So what happens when we change the colors of other dots?
IMAGE: recolor-example-changed-contained-in-other
Here the issue is that the dot on the right goes from being contained in the small green bubble to being contained in the large formerly-green one. So, we need to change the colors of *only* the dots contained in our bubble.
IMAGE: recolor-example-correct-to-yellow
OK, so that one worked! This leads us to the first derived rule: <mark>Dots contained in the given bubble must have their colors changed in the same way as the bubble. Other dots' colors are unchanged.</mark>
### 2. Locally Free Dots
So can we in general recolor a bubble and all the dots it contains to any color? Well, let's try a different color, say red:
IMAGE: recolor-example-capture-locally-free
OK, so that one didn't work. Why? See the red dot on the far left? It was contained in the large red bubble and got captured by our recolored bubble. So, is the rule that we aren't allowed to pick colors of dots within the bubble that we are recoloring? Well, let's try changing the color to blue:
IMAGE: recolor-example-correct-to-blue
If you look at each dot before and after, you can in fact verify that this transformation works! What is the difference between this and the last one? Well, in this case the blue dot doesn't get captured because it was already contained by the smaller blue bubble.
So we know that the problem only pops up when there are dots of our desired color that aren't contained by a bubble smaller than our target bubble. This leads us to the concept of a locally free dot: a dot that can escape the bubble we are considering. The fence-sheep intuition for this is that if we don't want to repaint our fence in such a way that sheep that could escape it before (locally free dots) aren't captured.
Using this definition, we have the second derived rule: <mark>The new color cannot be the color of any dots that are locally free to the given bubble.</mark>
### 3. Capturing Bubbles
But this isn't the only restriction: for example, there are no purple locally free dots, but this recoloring is still invalid:
IMAGE: recolor-captured-by-bubble
Why is this a problem? Well, the dot on the right of the originally purple bubble was contained in the target bubble before but got captured by the smaller purple bubble. We call any bubble that physically surrounds a dot that is contained in our target bubble a "capturing bubble".
The fence-sheep intuition for this one is that we don't want to repaint any sheep to a color that means that they get captured by a smaller fence. We want to make sure that they stay blocked first by the fence we're currently repainting.
This definition leads us to the final rule: <mark>The new color cannot be the color of any capturing bubbles.</mark>
### How to Recolor
OK, so there's a lot of advice on how *not* to recolor, but how do we ensure that recoloring is a success? Well, as it turns out, if we follow the three rules I listed above, we will never break the same-contained-status rule. Given this, there's a simple strategy for recoloring:
> 1. Write down a list of colors for locally free dots
> 2. Write down a list of colors of capturing bubbles.
> 3. Find a color not on either of those lists.
> 4. Recolor the bubble and all dots it contains to the selected color
Of course, you can bypass steps 2 and 3 by just selecting a color that's not on the diagram already. While this always theoretically works, in practice you run out of marker colors (or colors that can easily be distinguished), so I recommend following steps 2 and 3 if your diagram has a lot of colors already.
## Exercises for Recoloring
For each image, determine whether or not the transformation is a valid recoloring.
IMAGE: recolor-questions
# The Bubble Burst Redraw
Bubble bursting is the second basic redraw. A bubble burst can only be done when there is a link with a bubble on the left.
A bubble burst consists of "bursting" the bubble on the left by removing it and replacing all the dots it contains with the circtree from the right. Similar to redraw, we need to make sure that any locally free variables on the right aren't captured.
IMAGE: burst1
For example, in the circtree above we can see that the red bubble is burst and the red dot is being replaced by the green dot. This is a valid recolor because the green dot is free both before and after the burst.
However, this burst is *not* valid:
IMAGE: burst-invalid1
This is because the blue dot goes from being locally free to being captured.
## Examples
The circtree on the right of the link doesn't have to be a dot, it can be anything. For example, it can be a bubble:
IMAGE: burst2
Or even a tree:
IMAGE: burst3
## Multiple Step Redrawing
Generally, we want to burst bubbles. Bursting bubbles is basically the point of the circle-tree system. But sometimes colors can get in the way, as in the previous example. So what should we do? Recolor!
For example, we can burst the above bubble as follows:
IMAGE: reduce1
## What is Bubble Bursting?
I mentioned above that Bubble Bursting is the point of the Circle-Tree system. Why is this? Well, bubble bursting is useful because it allows us to treat bubbles as templates that we can plug any circtree into. For example, let's say we have a common pattern, like so:
IMAGE: pattern-impl
Through the bubble burst mechanism, each diagram can be restated:
IMAGE: pattern-abs
And we can see that there is a common element, a circtree that represents a *pattern*:
IMAGE: pattern; height="200"
In this view of circtrees, bubbles represent a template, and linking a template to a value represent the "filling in" of the template with that value. You can actually fill in the template by bubble bursting.
# Bubble Creation
Bubble creation is the final basic redraw. A bubble creation can be done on any circtree. Basically, we take a circtree and link a dot on the right. Then we draw a bubble around it.
IMAGE: create1
The one rule of bubble creation is that it isn't allowed to capture any free variables. So, this isn't valid:
IMAGE: create-invalid
The basic idea behind bubble creation is that a bubble creation around a bubble can be undone by a burst:
IMAGE: create-burst
So, really, the only reason to ever use this is if you want to show that two circtrees that represent the same template are in fact the same. This is generally a last step when showing that two circtrees are equivalent.
# And that's the system!
Yeah, that's it. Pretty simple, huh? OK, maybe it's not that simple. But when you compare it to what it's capable of, it starts looking pretty simple...
# Until next time...
Play around with this for a while, it really only makes sense when you have some experience manipulating the circtrees.
[^1]: You can probably guess where that name came from
[^2]: I choose to draw pretty big dots, but if you're doing this by hand, you'll probably want to use smaller ones for ease of drawing.
[^3]: CS people generally draw trees upside down. I guess because most of us have at best a passing familiarity with the biological equivalent.
[^4]: If you don't like sheep, then you can mentally substitute cows or pigs. But not chickens. They'd just fly over the fence.
|
Python
|
UTF-8
| 1,618 | 2.921875 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
from xlrd import open_workbook
import re
class Plot(object):
"""Used to plot."""
def __init__(self,dpi=100):
self.dpi=dpi
def plot_from_memorry(self, vars, labels=None, xylabel=None):
"""The first element of vars is independent variable."""
length=len(vars)-1
vars=np.array(vars)
x=vars[0]
fig=plt.figure(dpi=self.dpi)
if labels!=None:
for i in range(length):
plt.loglog(x,vars[i+1],label=labels[i],lw=2)
else:
for i in range(length):
plt.loglog(x,vars[i+1],lw=2)
if xylabel!=None:
plt.xlabel=xylabel[0]
plt.ylabel=xylabel[1]
plt.show()
def plot_from_file(self, filename, dtype, vars_number,labels=None,xylabels=None):
"""The order is the same as it in vars."""
if dtype=='excel':
workshop=open_workbook(filename)
sheet=workshop.sheet_by_index(0)
vars=[]
for i in range(vars_number):
store=sheet.col(i)
for j in range(len(store)):
store[j]=store[j].value
vars.append(store)
self.plot_from_memorry(vars,labels,xylabels)
elif dtype=='txt':
file=open(filename)
store=file.readline()
store=re.sub(r'\D',' ',store).split()
length=vars_number
vars=[[] for i in range(length)]
for i in range(length):
vars[i].append(store[i])
while True:
store=file.readline()
if not store:
break
store=re.sub(r'\D',' ',store).split()
for i in range(length):
vars[i].append(store[i])
self.plot_from_memorry(vars,labels,xylabels)
else:
raise ValueError('The value of dtype is invalid.')
|
C++
|
UTF-8
| 4,089 | 2.8125 | 3 |
[] |
no_license
|
#pragma once
#include <json/value.hxx>
#include <json/string.hxx>
#include <istream>
#include <ostream>
#include <fstream>
#include <string>
#include <vector>
namespace podreader
{
namespace json
{
namespace detail
{
template <typename T, typename Enable = STL enable_if_t<STL is_fundamental_v<T> or STL is_same_v<T, cstring>>>
auto read_v(std::istream& is, value& val)
{
T t;
is >> t;
if (auto ptr = dynamic_cast<value_impl<T>*>(&val))
{
ptr->members = t;
}
}
template <>
auto read_v<bool>(std::istream& is, value& val)
{
std::string s;
unsigned char c;
is >> c;
is.unget();
std::getline(is, s, ',');
if (auto ptr = dynamic_cast<value_impl<bool>*>(&val))
{
ptr->members = (s == "true");
}
}
template <>
auto read_v<cstring>(std::istream& is, value& val)
{
std::string s;
unsigned char c;
is >> c;
std::getline(is, s, '"');
return s;
}
}
template <typename T, typename Enable = typename std::enable_if<std::is_aggregate<T>::value and std::is_class<T>::value>::type>
class jsonreader
{
public:
static constexpr const meta::type_data& type = typeof(T);
private:
std::istream &stream;
value *result;
inline static std::vector<std::string *> strs;
bool set;
public:
explicit jsonreader(std::istream &stream)
: stream(stream),
result(new value_impl<T>()),
set(false)
{}
~jsonreader()
{
delete result;
}
private:
jsonreader(const jsonreader<T>& other) = delete;
void evaluate_raw(value &val)
{
using namespace detail;
if (val.type_of() == typeof(bool))
{
read_v<bool>(stream, val);
}
else if (val.type_of() == typeof(char))
{
read_v<char>(stream, val);
}
else if (val.type_of() == typeof(signed char))
{
read_v<signed char>(stream, val);
}
else if (val.type_of() == typeof(unsigned char))
{
read_v<unsigned char>(stream, val);
}
else if (val.type_of() == typeof(short))
{
read_v<short>(stream, val);
}
else if (val.type_of() == typeof(unsigned short))
{
read_v<unsigned short>(stream, val);
}
else if (val.type_of() == typeof(int))
{
read_v<int>(stream, val);
}
else if (val.type_of() == typeof(unsigned int))
{
read_v<unsigned int>(stream, val);
}
else if (val.type_of() == typeof(long))
{
read_v<long>(stream, val);
}
else if (val.type_of() == typeof(unsigned long))
{
read_v<unsigned long>(stream, val);
}
else if (val.type_of() == typeof(long long))
{
read_v<long long>(stream, val);
}
else if (val.type_of() == typeof(unsigned long long))
{
read_v<unsigned long long>(stream, val);
}
else if (val.type_of() == typeof(float))
{
read_v<float>(stream, val);
}
else if (val.type_of() == typeof(double))
{
read_v<double>(stream, val);
}
else if (val.type_of() == typeof(long double))
{
read_v<long double>(stream, val);
}
else if (val.type_of() == typeof(cstring))
{
const std::size_t index = strs.size();
strs.push_back(new std::string(read_v<cstring>(stream, val)));
const std::string& str = *strs[index];
auto &c_str = dynamic_cast<value_impl<const char *>&>(val[0]);
auto &len = dynamic_cast<value_impl<std::size_t>&>(val[1]);
c_str.members = str.c_str();
len.members = str.length();
}
}
void evaluate_intern(value &val)
{
if (!val.type_of().is_struct || val.type_of() == typeof(cstring)) evaluate_raw(val);
else
{
const type_data& typeinfo = val.type_of();
for (std::size_t n = 0; n < typeinfo.num_members; ++n)
{
std::string s;
std::getline(stream, s, ':');
evaluate_intern(val[n]);
}
}
}
public:
void evaluate()
{
evaluate_intern(*result);
set = true;
}
T result_of() noexcept
{
if (!set) evaluate();
T res = *result;
return res;
}
};
}
}
|
JavaScript
|
UTF-8
| 680 | 2.625 | 3 |
[] |
no_license
|
(function( window ) {
'use strict';
angular
.module( 'utils.localstorage', [])
.factory( 'localstorage', localstorage );
function localstorage() {
var services = {
get : get,
set : set,
remove : remove
};
return services;
function get( key ) {
return localStorage.getItem( key );
}
function set( key, value ) {
var str = Array.isArray( value ) ? JSON.stringify( value ) : value;
if(localStorage.key( key )) {
localStorage.removeItem( key );
}
localStorage.setItem( key, str );
}
function remove( key ) {
localStorage.removeItem( key );
}
}
})( window );
|
C++
|
UTF-8
| 1,148 | 3.921875 | 4 |
[] |
no_license
|
#include<iostream>
#define MAX 100
using namespace std;
class stack{
private:
int top;
public:
int a[MAX];
stack(){
top = -1;
}
int pop();
bool push(int x);
bool isEmpty();
bool isFull();
};
bool stack :: push(int x){
if(top >= MAX - 1){
cout << "Stack overflow" << endl;
return false;
}
else{
cout<<"inserted " << x << endl;
a[++top] = x;
}
return true;
}
int stack :: pop(){
if(isEmpty()) {
cout<<"stack empty"<<endl;
return -1;
}
else{
return a[top--];
}
}
bool stack :: isEmpty(){
if(top == -1){
cout << "stack empty" << endl;
return true;
}
return false;
}
bool stack :: isFull(){
if(top >= MAX){
cout<<"stack full" << endl;
return true;
}
return false;
}
int main(){
stack s;
s.push(10);
s.push(100);
s.push(3);
cout<<"POP :" << s.pop() << endl;
cout<<"POP :" << s.pop() << endl;
cout<<"POP :" << s.pop() << endl;
cout<<"POP :" << s.pop() << endl;
return 0;
}
|
PHP
|
UTF-8
| 641 | 3 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace AbstractFactory\Repository;
use AbstractFactory\Contract\DbRecordInterface;
use AbstractFactory\Entity\User;
class MySqlRecord extends BaseMySqlRepository
implements DbRecordInterface
{
public function add(User $user)
{
echo 'Добавляем в mysql пользователя $user.' . PHP_EOL;
}
public function delete(User $user)
{
echo 'Удаляем в mysql пользователя $user.' . PHP_EOL;
}
public function update(User $user)
{
echo 'Обновляем в mysql пользователя $user.' . PHP_EOL;
}
}
|
Java
|
UTF-8
| 1,091 | 1.539063 | 2 |
[] |
no_license
|
package com.entities;
import com.entities.Activite;
import com.entities.ResponsableMarketing;
import javax.annotation.Generated;
import javax.persistence.metamodel.ListAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-08-14T13:06:50")
@StaticMetamodel(Filiale.class)
public class Filiale_ {
public static volatile SingularAttribute<Filiale, String> nomFiliale;
public static volatile SingularAttribute<Filiale, String> ville;
public static volatile SingularAttribute<Filiale, Integer> idFiliale;
public static volatile ListAttribute<Filiale, ResponsableMarketing> ListUtilisateurPGH;
public static volatile SingularAttribute<Filiale, String> adresse;
public static volatile ListAttribute<Filiale, Activite> ListActivite;
public static volatile SingularAttribute<Filiale, String> telephone;
public static volatile SingularAttribute<Filiale, String> email;
public static volatile SingularAttribute<Filiale, String> pays;
}
|
Java
|
UTF-8
| 1,125 | 2.21875 | 2 |
[] |
no_license
|
package com.cinema.Domain;
import java.sql.Date;
public class Ticket {
private long id_ticket;
private long id_showtime;
private long id_seat;
private long id_user;
private long id_type;
private Date date;
public long getId_ticket() {
return id_ticket;
}
public void setId_ticket(long id_ticket) {
this.id_ticket = id_ticket;
}
public long getId_showtime() {
return id_showtime;
}
public void setId_showtime(long id_showtime) {
this.id_showtime = id_showtime;
}
public long getId_seat() {
return id_seat;
}
public void setId_seat(long id_seat) {
this.id_seat = id_seat;
}
public long getId_user() {
return id_user;
}
public void setId_user(long id_user) {
this.id_user = id_user;
}
public long getId_type() {
return id_type;
}
public void setId_type(long id_type) {
this.id_type = id_type;
}
public Date getDate() {
return date;
}
public void setDate(java.sql.Date date) {
this.date = date;
}
}
|
Java
|
UTF-8
| 1,069 | 2.71875 | 3 |
[] |
no_license
|
package attributes;
import java.util.Map;
/**
* Created by msg on 2016/11/23.
*/
public class PropertyEffect {
private final String name;
private final Map<Integer, Integer> attributes;
public PropertyEffect(String name, Map<Integer, Integer> attributes) {
this.name = name;
this.attributes = attributes;
}
public String getName() {
return name;
}
Map<Integer, Integer> getAttributes() {
return attributes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PropertyEffect that = (PropertyEffect) o;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public String toString() {
return "PropertyEffect{" +
"name='" + name + '\'' +
", attributes=" + attributes +
'}';
}
}
|
Java
|
UTF-8
| 763 | 3.28125 | 3 |
[] |
no_license
|
/*
* Gson tutorial: http://zetcode.com/java/gson/
* Java Gson read list
*
*/
package com.zetcode.e06;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class GsonReadList {
public static void main(String[] args) throws IOException {
Gson gson = new GsonBuilder().create();
try (Reader reader = new FileReader("resources/items.json")) {
List<Item> items = gson.fromJson(reader,
new TypeToken<List<Item>>(){}.getType());
items.forEach(System.out::println);
}
}
}
|
JavaScript
|
UTF-8
| 5,111 | 2.734375 | 3 |
[] |
no_license
|
/* jshint expr: true, node: true */
/* global describe, it, beforeEach, before */
"use strict";
var assert = require("should");
var BallView = require("../scripts/view/ballView.js");
var BallDOMMock = require("./mocks/ballDOMMock.js");
var FrameView = require("../scripts/view/frameView.js");
var FrameDOMMock = require("./mocks/frameDOMMock.js");
var _ = require('lodash');
BallDOMMock.mock(BallView);
FrameDOMMock.mock(FrameView);
describe('kata-bowling-game', function(){
describe('BallView', function(){
it("should create a new ball with a dom mock", function(){
var ball = new BallView("anyId");
ball.dom.should.be.an.instanceOf(BallDOMMock);
});
describe('#modified()', function(){
it("should do nothing if the value did not change", function() {
var passed = false;
var ball = new BallView("anyID");
ball.modified(function(){
passed = true;
});
passed.should.be.true;
});
it("should call the observers with the method #ballModification() and the argument should be itself", function() {
var reciver = {
passed:null,
ballModification:function(obj){
this.passed = obj;
}
};
var ball = new BallView("anyID", reciver);
ball.setValue('2');
ball.modified();
reciver.passed.should.be.equal(ball);
});
it("should throw exception when value is not numeric", function(){
var ball = new BallView("anyID");
ball.setValue('asfd');
(function try1(){
ball.modified();
}).should.throw(/UserException: /);
ball.setValue('asfd4');
(function try2(){
ball.modified();
}).should.throw(/UserException: /);
ball.setValue('4asd');
(function try3(){
ball.modified();
}).should.throw(/UserException: /);
ball.setValue(' ');
(function try4(){
ball.modified();
}).should.throw(/UserException: /);
});
it("should throw exception when value is out of range", function(){
var ball = new BallView("anyID");
ball.setValue('-1');
(function try1(){
ball.modified();
}).should.throw(/UserException: /);
ball.setValue('-1012');
(function try2(){
ball.modified();
}).should.throw(/UserException: /);
ball.setValue('11');
(function try3(){
ball.modified();
}).should.throw(/UserException: /);
ball.setValue('1235');
(function try1(){
ball.modified();
}).should.throw(/UserException: /);
});
});
});
describe('FrameView', function(){
it("should create a new frame view with dom mock objects", function(){
var frame = new FrameView("frame-0");
frame.round.should.be.equal(0);
frame.fst.should.be.an.instanceOf(BallView);
frame.snd.should.be.an.instanceOf(BallView);
frame.fst.dom.should.be.an.instanceOf(BallDOMMock);
frame.snd.dom.should.be.an.instanceOf(BallDOMMock);
frame.points.should.be.an.instanceOf(FrameDOMMock.PointsDOMMock);
});
describe('#ballModification()', function(){
it("should enable the second ball when the first one is less than 10", function(){
var frame = new FrameView("frame-0");
frame.snd.disable();
frame.fst.setValue(4);
frame.ballModification(frame.fst);
frame.snd.enabled().should.be.true;
});
it("should disable the second ball when the first one is 10", function(){
var frame = new FrameView("frame-0");
frame.fst.setValue(10);
frame.ballModification(frame.fst);
frame.snd.enabled().should.be.false;
});
it("should call the observer with the method #frameModificated() and the argument should be itself when the first shoot is 10", function () {
var reciver = {
passed:null,
times:0,
frameModificated:function(obj){
this.times += 1;
this.passed = obj;
}
};
var frame = new FrameView("frame-0", reciver);
frame.fst.setValue(10);
frame.ballModification(frame.fst);
reciver.passed.should.be.equal(frame);
reciver.times.should.be.equal(1);
});
it("should call the observer with the method #frameModificated() and the argument should be itself when the first shoot is less than 10 and the sencond one was done", function () {
var reciver = {
passed:null,
times:0,
frameModificated:function(obj){
this.times += 1;
this.passed = obj;
}
};
var frame = new FrameView("frame-0", reciver);
frame.fst.setValue(5);
frame.ballModification(frame.fst);
frame.snd.setValue(2);
frame.ballModification(frame.snd);
reciver.passed.should.be.equal(frame);
reciver.times.should.be.equal(1);
});
it("should NOT call the observer with the method #frameModificated() the first shoot is less than 10", function () {
var reciver = {
passed:null,
times:0,
frameModificated:function(obj){
this.times += 1;
this.passed = obj;
}
};
var frame = new FrameView("frame-0", reciver);
frame.fst.setValue(3);
frame.ballModification(frame.fst);
(reciver.passed === null).should.be.true;
reciver.times.should.be.equal(0);
});
});
});
});
|
Java
|
UTF-8
| 196 | 1.875 | 2 |
[] |
no_license
|
package edu.eci.arsw.alexandria.model.Paint;
import lombok.Data;
@Data
public class Circle extends Figure{
private float radius;
private float startAngle;
private float endAngle;
}
|
Java
|
UTF-8
| 1,534 | 2.21875 | 2 |
[] |
no_license
|
package es.studium.LoginServlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import es.studium.modelo.Libro;
/**
* Servlet implementation class HazAlgo
*/
public class MuestraLibro extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MuestraLibro()
{
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
try
{
HttpSession session = request.getSession(false);
synchronized(session)
{
Libro libro = new Libro();
List <Libro> libros = libro.listarLibro();
session.setAttribute("libros", libros);
response.sendRedirect("./vistas/listLibro.jsp");
}
}catch(Exception E){
System.out.println(E.getMessage());
}
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// TODO Auto-generated method stub
doPost(request, response);
}
}
|
Python
|
UTF-8
| 2,683 | 2.953125 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 23:14:55 2021
@author: EI11560
"""
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import nltk
import string
import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
#%matplotlib inline
# data set
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
# Method for remove unwanted thinks
def remove_pattern(input_txt, pattern):
r = re.findall(pattern, input_txt)
for i in r:
input_txt = re.sub(i, '', input_txt)
return input_txt
com = train.append(test, ignore_index=True)
com['tidy_tweet'] = np.vectorize(remove_pattern)(com['tweet'], "@[\w]*")
# Remove special characters, numbers, punctuation
com['tidy_tweet'] = com['tidy_tweet'].str.replace("[^a-zA-Z#]", " " )
# Removing short words
com['tidy_tweet'] = com['tidy_tweet'].apply(lambda x: ' '.join([w for w in x.split() if len(w)>3]))
tokenized_tweet = com['tidy_tweet'].apply(lambda x: x.split())
print(com.head())
# import nltk
#from nltk.stem.porter import *
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
tokenized_tweet = tokenized_tweet.apply(lambda x: [stemmer.stem(i) for i in x])
from sklearn.feature_extraction.text import CountVectorizer
bow_vectorizer = CountVectorizer(max_df=0.90, min_df=2, max_features=1000, stop_words='english')
bow = bow_vectorizer.fit_transform(com['tidy_tweet'])
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(max_df=0.90, min_df=2, max_features=1000, stop_words='english')
tfidf = tfidf_vectorizer.fit_transform(com['tidy_tweet'])
# we’ll build with the bag-of-words dataframe
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
train_bow = bow[:31962, :]
test_bow = bow[31962:, :]
xtrain_bow, xvalid_bow, ytrain, yvalid = train_test_split(train_bow, train['label'], random_state=42, test_size=0.3)
lreg = LogisticRegression()
lreg.fit(xtrain_bow, ytrain)
prediction = lreg.predict_proba(xvalid_bow)
prediction_int = prediction[:,1] >= 0.3
prediction_int = prediction_int.astype(np.int)
#printing
print (f1_score(yvalid, prediction_int))
train_tfidf = tfidf[:31962, :]
test_tfidf = tfidf[31962:, :]
xtrain_tfidf = train_tfidf[ytrain.index]
xvalid_tfidf = train_tfidf[yvalid.index]
lreg.fit(xtrain_tfidf, ytrain)
prediction = lreg.predict_proba(xvalid_tfidf)
prediction_int = prediction[:, 1] >= 0.3
prediction_int = prediction_int.astype(np.int)
|
Java
|
UTF-8
| 2,275 | 2.109375 | 2 |
[] |
no_license
|
package net.mcreator.nkquest.potion;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraft.util.ResourceLocation;
import net.minecraft.potion.PotionType;
import net.minecraft.potion.PotionEffect;
import net.minecraft.potion.Potion;
import net.minecraft.item.ItemStack;
import net.minecraft.init.Items;
import net.mcreator.nkquest.ElementsNkquest;
import java.util.List;
import java.util.ArrayList;
@ElementsNkquest.ModElement.Tag
public class PotionPowerUpPotionOfFire extends ElementsNkquest.ModElement {
@GameRegistry.ObjectHolder("nkquest:poweruppotionoffire")
public static final Potion potion = null;
@GameRegistry.ObjectHolder("nkquest:poweruppotionoffire")
public static final PotionType potionType = null;
public PotionPowerUpPotionOfFire(ElementsNkquest instance) {
super(instance, 483);
}
@Override
public void initElements() {
elements.potions.add(() -> new PotionCustom());
}
@Override
public void init(FMLInitializationEvent event) {
ForgeRegistries.POTION_TYPES.register(new PotionTypeCustom());
}
public static class PotionTypeCustom extends PotionType {
public PotionTypeCustom() {
super(new PotionEffect[]{new PotionEffect(potion, 3600)});
setRegistryName("poweruppotionoffire");
}
}
public static class PotionCustom extends Potion {
private final ResourceLocation potionIcon;
public PotionCustom() {
super(false, -1012440);
setBeneficial();
setRegistryName("poweruppotionoffire");
setPotionName("effect.poweruppotionoffire");
potionIcon = new ResourceLocation("nkquest:textures/mob_effect/poweruppotionoffire.png");
}
@Override
public boolean isInstant() {
return true;
}
@Override
public List<ItemStack> getCurativeItems() {
List<ItemStack> ret = new ArrayList<>();
ret.add(new ItemStack(Items.MILK_BUCKET, (int) (1)));
return ret;
}
@Override
public boolean shouldRenderInvText(PotionEffect effect) {
return false;
}
@Override
public boolean shouldRenderHUD(PotionEffect effect) {
return false;
}
@Override
public boolean isReady(int duration, int amplifier) {
return true;
}
}
}
|
Java
|
UTF-8
| 1,747 | 1.992188 | 2 |
[] |
no_license
|
package com.myroom.application;
import com.myroom.activity.CreateRoomActivity;
import com.myroom.adapter.CurrencyAdapter;
import com.myroom.adapter.GuestInRoomAdapter;
import com.myroom.adapter.PaymentHistoryAdapter;
import com.myroom.adapter.RoomAdapter;
import com.myroom.adapter.RoomInformationAdapter;
import com.myroom.adapter.UtilityInRoomAdapter;
import com.myroom.fragment.CreateBillFragment;
import com.myroom.fragment.GuestInRoomFragment;
import com.myroom.fragment.SendMessageFragment;
import com.myroom.service.ICurrencyService;
import com.myroom.service.IGuestService;
import com.myroom.service.IMessageService;
import com.myroom.service.IPaymentService;
import com.myroom.service.IRoomService;
import com.myroom.service.IUtilityService;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {ServiceModule.class})
public interface ServiceComponent {
void inject(UtilityInRoomAdapter utilityInRoomAdapter);
void inject(GuestInRoomAdapter guestInRoomAdapter);
void inject(CreateRoomActivity createRoomActivity);
void inject(RoomAdapter roomAdapter);
void inject(CurrencyAdapter currencyAdapter);
void inject(CreateBillFragment createBillFragment);
void inject(SendMessageFragment sendMessageFragment);
void inject(GuestInRoomFragment guestInRoomFragment);
void inject(RoomInformationAdapter roomInformationAdapter);
void inject(IRoomService roomService);
void inject(PaymentHistoryAdapter paymentHistoryAdapter);
IRoomService getRoomService();
ICurrencyService getCurrencyService();
IGuestService getGuestService();
IMessageService getMessageService();
IUtilityService getUtilityService();
IPaymentService getPaymentService();
}
|
Java
|
UTF-8
| 3,644 | 1.789063 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.hover.stax.actions;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import com.hover.sdk.actions.HoverAction;
import com.hover.stax.R;
import com.hover.stax.databinding.StaxSpinnerItemWithLogoBinding;
import com.hover.stax.utils.UIHelper;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.util.List;
import timber.log.Timber;
import static com.hover.stax.utils.Constants.size55;
public class ActionDropdownAdapter extends ArrayAdapter<HoverAction> {
private final List<HoverAction> actions;
public ActionDropdownAdapter(@NonNull List<HoverAction> actions, @NonNull Context context) {
super(context, 0, actions);
this.actions = actions;
}
@NonNull
@Override
public View getView(int position, @Nullable View view, @NonNull ViewGroup parent) {
HoverAction a = actions.get(position);
ViewHolder holder;
if (view == null) {
StaxSpinnerItemWithLogoBinding binding = StaxSpinnerItemWithLogoBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
view = binding.getRoot();
holder = new ViewHolder(binding);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.setAction(a, getContext().getString(R.string.root_url));
return view;
}
private static class ViewHolder implements Target {
TextView id;
ImageView logo;
AppCompatTextView channelText;
StaxSpinnerItemWithLogoBinding binding;
private ViewHolder(StaxSpinnerItemWithLogoBinding binding) {
this.binding = binding;
logo = binding.serviceItemImageId;
channelText = binding.serviceItemNameId;
id = binding.serviceItemId;
}
@SuppressLint("SetTextI18n")
private void setAction(HoverAction action, String baseUrl) {
id.setText(Integer.toString(action.id));
channelText.setText(action.toString());
UIHelper.loadPicasso(baseUrl + action.to_institution_logo, size55, this);
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
RoundedBitmapDrawable d = RoundedBitmapDrawableFactory.create(id.getContext().getResources(), bitmap);
d.setCircular(true);
logo.setImageDrawable(d);
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
Timber.e(e.getLocalizedMessage());
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
@Override
public int getCount() {
return actions.size();
}
@Override
public long getItemId(int position) {
return position;
}
@Nullable
@Override
public HoverAction getItem(int position) {
return actions.isEmpty() ? null : actions.get(position);
}
@Override
public int getItemViewType(int position) {
return position;
}
}
|
Python
|
UTF-8
| 13,243 | 3.0625 | 3 |
[] |
no_license
|
'''
-----------------------Authors-------------------------
Nayanika Ghosh - 4191 4976
Disha Nayar - 6199 1035
-------------------------------------------------------
'''
import pickle
import numpy as np
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor
from sklearn.utils import shuffle
from sklearn.model_selection import KFold
from sklearn import metrics
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import confusion_matrix
from sklearn.neural_network import MLPClassifier
class Classifier():
'''
This class implements 3 functions for classifiers
Each function has one classifier model defined.
'''
def __init__(self):
'''
Load the tiktac_final and tiktak_single data files
Call each of the models with the two datasets
'''
self.final_path = "datasets-part1/tictac_final.txt"
self.single_path = 'datasets-part1/tictac_single.txt'
self.data_final = np.loadtxt(self.final_path)
self.data_single = np.loadtxt(self.single_path)
# randomly shuffle the data
self.data_final = shuffle(self.data_final)
self.data_single = shuffle(self.data_single)
# call functions for Final dataset
self.linear_SVM(self.data_final, 2, "Final boards classification dataset")
self.kNearest(self.data_final, 2, "Final boards classification dataset")
self.MLP(self.data_final, 2, "Final boards classification dataset")
# call functions for Intermediate - single label
self.linear_SVM(self.data_single, 9, "Intermediate boards optimal play (single label)")
self.kNearest(self.data_single, 9, "Intermediate boards optimal play (single label)")
self.MLP(self.data_single, 9, "Intermediate boards optimal play (single label)")
def linear_SVM(self, data, num_labels, str):
'''
This function implements linear svm
It applies k-fold cross validation with k = 10
:param data: input dataset
:param num_labels: number of values that output label can take
:param str: name of the dataset, used in printing
:return: None
'''
features = data[:,:9]
labels = data[:,9:]
kf = KFold(n_splits=10)
kf.get_n_splits(features)
total_accuracy = 0.0
con_matrix = np.zeros((num_labels, num_labels))
for train_index, test_index in kf.split(features):
X_train, X_test = features[train_index], features[test_index]
y_train, y_test = labels[train_index], labels[test_index]
svm_model = SVC(kernel='linear')
svm_model.fit(X_train, y_train.ravel())
y_pred = svm_model.predict(X_test)
acc = metrics.accuracy_score(y_pred, y_test)
total_accuracy += acc
con_matrix += confusion_matrix(y_test, y_pred)
cm_normalized = con_matrix.astype('float') / con_matrix.sum(axis=1)[:, np.newaxis]
print('Accuracy of Linear SVM on ', str, ' is ', total_accuracy/10)
np.set_printoptions(precision=2)
print('Confusion Matrix of Linear SVM on ', str, ' is \n', cm_normalized, '\n\n')
def kNearest(self, data, num_labels, str):
'''
This function implements K nearest neighbours model
It applies k-fold cross validation with k = 10
number of neighbors = 9
:param data: input dataset
:param num_labels: number of values that output label can take
:param str: name of the dataset, used in printing
:return: None
'''
features = data[:, :9]
labels = data[:, 9:]
kf = KFold(n_splits=10)
kf.get_n_splits(features)
total_accuracy = 0.0
con_matrix = np.zeros((num_labels, num_labels))
for train_index, test_index in kf.split(features):
X_train, X_test = features[train_index], features[test_index]
y_train, y_test = labels[train_index], labels[test_index]
knn_model = KNeighborsClassifier(n_neighbors=9)
knn_model.fit(X_train, y_train.ravel())
y_pred = knn_model.predict(X_test)
acc = metrics.accuracy_score(y_pred, y_test)
total_accuracy += acc
con_matrix += confusion_matrix(y_test, y_pred)
cm_normalized = con_matrix.astype('float') / con_matrix.sum(axis=1)[:, np.newaxis]
print('Accuracy of k-Nearest Classifier on ', str, ' is ', total_accuracy / 10)
np.set_printoptions(precision=2)
print('Confusion Matrix of k-Nearest Classifier on ', str, ' is \n', cm_normalized, '\n\n')
def MLP(self, data, num_labels, str):
'''
This function implements the MLP model
It applies k-fold cross validation with k = 10
:param data: input dataset
:param num_labels: number of values that output label can take
:param str: name of the dataset, used in printing
:return: None
'''
features = data[:, :9]
labels = data[:, 9:]
kf = KFold(n_splits=10)
kf.get_n_splits(features)
total_accuracy = 0.0
con_matrix = np.zeros((num_labels, num_labels))
for train_index, test_index in kf.split(features):
X_train, X_test = features[train_index], features[test_index]
y_train, y_test = labels[train_index], labels[test_index]
mlp_model = MLPClassifier(solver='adam', activation='relu', hidden_layer_sizes=(200,100,40),
random_state=1, max_iter=500).fit(X_train, y_train.ravel())
y_pred = mlp_model.predict(X_test)
acc3 = metrics.accuracy_score(y_pred, y_test)
total_accuracy += acc3
con_matrix += confusion_matrix(y_test, y_pred)
cm_normalized = con_matrix.astype('float') / con_matrix.sum(axis=1)[:, np.newaxis]
print('Accuracy of MLP Classifier on ', str, ' is ', total_accuracy / 10)
np.set_printoptions(precision=2)
print('Confusion Matrix of MLP Classifier on ', str, ' is \n', cm_normalized, '\n\n')
class Regressor():
'''
This class implements 3 functions for regressors
Each function has one regressor model defined.
'''
def __init__(self):
'''
Load the tiktac_multi data files
Call each of the models with the two datasets
'''
self.multi_path = 'datasets-part1/tictac_multi.txt'
self.data_multi = np.loadtxt(self.multi_path)
# randomly shuffle the data
self.data_multi = shuffle(self.data_multi)
# call functions for Intermediate - multi label
self.linear_regressor()
self.kNearest()
self.MLP()
def linear_regressor(self):
'''
This function implements a linear regressor model
The weigths are calculated using normal equation
w0 to w8 define the weigths
It applies k-fold cross validation with k = 10
:return: None
'''
X = self.data_multi[:, :9]
y = self.data_multi[:, 9:]
y0 = y[:, :1]
y1 = y[:, 1:2]
y2 = y[:, 2:3]
y3 = y[:, 3:4]
y4 = y[:, 4:5]
y5 = y[:, 5:6]
y6 = y[:, 6:7]
y7 = y[:, 7:8]
y8 = y[:, 8:]
x_shape = X.shape
x_bias = np.ones((x_shape[0], 1))
features = np.append(x_bias, X, axis=1)
kf = KFold(n_splits=10)
total_accuracy = 0.0
for train_index, test_index in kf.split(features):
X_train, X_test = features[train_index], features[test_index]
# Calculate (X^TX)^-1X^T
M1 = np.dot(np.transpose(X_train), X_train)
M2 = np.dot(np.linalg.inv(M1), np.transpose(X_train))
# train on y0
y0_train, y0_test = y0[train_index], y0[test_index]
w0 = np.dot(M2, y0_train)
y0_pred = np.dot(X_test, w0)
# train on y1
y1_train, y1_test = y1[train_index], y1[test_index]
w1 = np.dot(M2, y1_train)
y1_pred = np.dot(X_test, w1)
# train on y2
y2_train, y2_test = y2[train_index], y2[test_index]
w2 = np.dot(M2, y2_train)
y2_pred = np.dot(X_test, w2)
# train on y3
y3_train, y3_test = y3[train_index], y3[test_index]
w3 = np.dot(M2, y3_train)
y3_pred = np.dot(X_test, w3)
# train on y4
y4_train, y4_test = y4[train_index], y4[test_index]
w4 = np.dot(M2, y4_train)
y4_pred = np.dot(X_test, w4)
# train on y5
y5_train, y5_test = y5[train_index], y5[test_index]
w5 = np.dot(M2, y5_train)
y5_pred = np.dot(X_test, w5)
# train on y6
y6_train, y6_test = y6[train_index], y6[test_index]
w6 = np.dot(M2, y6_train)
y6_pred = np.dot(X_test, w6)
# train on y7
y7_train, y7_test = y7[train_index], y7[test_index]
w7 = np.dot(M2, y7_train)
y7_pred = np.dot(X_test, w7)
# train on y8
y8_train, y8_test = y8[train_index], y8[test_index]
w8 = np.dot(M2, y8_train)
y8_pred = np.dot(X_test, w8)
# stack all the vectors together to get y_predicted
y_pred = np.column_stack((y0_pred, y1_pred, y2_pred, y3_pred, y4_pred,
y5_pred, y6_pred, y7_pred, y8_pred))
y_test = np.column_stack((y0_test, y1_test, y2_test, y3_test, y4_test,
y5_test, y6_test, y7_test, y8_test))
b = np.zeros_like(y_pred)
b[np.arange(len(y_pred)), y_pred.argmax(1)] = 1
y_pred_updated = b
acc = 0.0
for i in range(len(y_pred_updated)):
acc = acc + metrics.accuracy_score(y_test[i], y_pred_updated[i])
acc_vec = acc / len(y_pred_updated)
total_accuracy += acc_vec
with open("LRWeights.txt", "w") as f:
f.write("\n".join(" ".join(map(str, x)) for x
in (w0.T, w1.T, w2.T, w3.T, w4.T, w5.T, w6.T, w7.T, w8.T)))
print('Accuracy of Linear Regressor on Intermediate boards optimal play '
'(multi label): is ', total_accuracy/10, '\n')
def kNearest(self):
'''
This function implements K nearest regressor
It applies k-fold cross validation with k = 10
number of neighbors = 9
:return: None
'''
features = self.data_multi[:, :9]
labels = self.data_multi[:, 9:]
kf = KFold(n_splits=10)
kf.get_n_splits(features)
total_accuracy = 0.0
for train_index, test_index in kf.split(features):
X_train, X_test = features[train_index], features[test_index]
y_train, y_test = labels[train_index], labels[test_index]
knn_reg_model = KNeighborsRegressor(n_neighbors=9)
knn_reg_model.fit(X_train, y_train)
y_pred = knn_reg_model.predict(X_test)
y_pred_updated = np.where(y_pred > 0.5, 1, 0)
acc = 0.0
for i in range(len(y_pred_updated)):
acc = acc + metrics.accuracy_score(y_test[i], y_pred_updated[i])
acc_vec = acc / len(y_pred_updated)
total_accuracy += acc_vec
knnWeights = open('knnWeights', 'wb')
pickle.dump(knn_reg_model, knnWeights)
print('Accuracy of k-Nearest Regressor on Intermediate boards optimal '
'play (multi label): is ', total_accuracy / 10, '\n')
def MLP(self):
'''
This function implements a mlp regressor
It applies k-fold cross validation with k = 10
:return: None
'''
features = self.data_multi[:, :9]
labels = self.data_multi[:, 9:]
kf = KFold(n_splits=10)
kf.get_n_splits(features)
total_accuracy = 0.0
for train_index, test_index in kf.split(features):
X_train, X_test = features[train_index], features[test_index]
y_train, y_test = labels[train_index], labels[test_index]
mlp_reg_model = MLPRegressor(solver='adam', activation='relu', hidden_layer_sizes=(200, 100, 40),
random_state=1, max_iter=500).fit(X_train, y_train)
y_pred = mlp_reg_model.predict(X_test)
y_pred_updated = np.where(y_pred > 0.5, 1, 0)
acc = 0.0
for i in range(len(y_pred_updated)):
acc = acc + metrics.accuracy_score(y_test[i], y_pred_updated[i])
acc_vec = acc / len(y_pred_updated)
total_accuracy += acc_vec
# save the model
MLPWeights = open('MLPWeights', 'wb')
pickle.dump(mlp_reg_model, MLPWeights)
print('Accuracy of MLP Regressor on Intermediate boards optimal play '
'(multi label): is ', total_accuracy / 10)
if __name__ == "__main__":
print('Output for Classifiers \n')
classifier = Classifier()
print('Output for Regresors \n')
regressor = Regressor()
|
C++
|
UTF-8
| 3,913 | 3.84375 | 4 |
[] |
no_license
|
#pragma once
#include <iostream>
using namespace std;
template <typename T>
struct node {
T value;
node* left;
node* right;
};
template <typename T>
class BinarySearchTreeTemplate
{
public:
BinarySearchTreeTemplate();
~BinarySearchTreeTemplate();
//public-facing methods
void insertType(T value);
void printTree();
void terminateTree();
bool searchTree(T searchVal);
protected:
//internal methods for modifying the tree
void insertType(node<T>** tree, T value);
void printTree(node<T>* tree);
void terminateTree(node<T>* tree);
bool searchTree(node<T>* tree, T searchVal);
node<int>* root;
T currentType; //for checking input type is same as the Tree's current type
};
//.ccp file bits; the actual implementation
template <typename T>
BinarySearchTreeTemplate<T>::BinarySearchTreeTemplate() {
root = nullptr;
}
template <typename T>
BinarySearchTreeTemplate<T>::~BinarySearchTreeTemplate() {
terminateTree(root);
}
//public-facing methods, essentially just wrapper methods which mean root isn't exposed to external classes
template <typename T>
void BinarySearchTreeTemplate<T>::insertType(T value) {
insertType(&root, value);
}
template <typename T>
void BinarySearchTreeTemplate<T>::printTree() {
printTree(root);
}
template <typename T>
void BinarySearchTreeTemplate<T>::terminateTree() {
terminateTree(root);
root = nullptr; //null the root node!
}
template <typename T>
bool BinarySearchTreeTemplate<T>::searchTree(T searchVal) {
return searchTree(root, searchVal);
}
//internal methods for modifying the tree
template <typename T>
void BinarySearchTreeTemplate<T>::insertType(node<T>** tree, T value) {
//if the node is empty, stick the number in there
node<int>* treePtr = *tree; //for convenience
if (treePtr == nullptr) {
node<int>* newNode = new node<int>();
*tree = newNode;
newNode->value = value;
newNode->left = nullptr;
newNode->right = nullptr;
return;
}
else { //else, check if it's higher or lower then go into that node
if (treePtr->value == value) { //ignore duplicate entries
return;
}
else if (treePtr->value > value) {
insertType(&(treePtr->left), value);
}
else {
insertType(&(treePtr->right), value);
}
}
}
template <typename T>
void BinarySearchTreeTemplate<T>::printTree(node<T>* tree) {
//safety check if it's null
if (tree == nullptr) {
return;
}
//go as far left as possible
if (tree->left != nullptr) {
printTree(tree->left);
}
//then print out the node's value
cout << tree->value << " ";
//then go right if possible
if (tree->right != nullptr) {
printTree(tree->right);
}
return;
}
template <typename T>
void BinarySearchTreeTemplate<T>::terminateTree(node<T>* tree) {
//safety check if it's null
if (tree == nullptr) {
return;
}
//go left if possible
if (tree->left != nullptr) {
terminateTree(tree->left);
}
//else go right if possible
if (tree->right != nullptr) {
terminateTree(tree->right);
}
//then delete the node itself
delete tree;
return;
}
template <typename T>
bool BinarySearchTreeTemplate<T>::searchTree(node<T>* tree, T searchVal) {
//safety check if the root is null
if (tree == nullptr) {
return false;
}
//if it matches, we're done
else if (tree->value == searchVal) {
return true;
}
//else, check if the node exists and if the searched value is lower than the current node (if it is, go left)
else if (
tree->left != nullptr && //if left isn't null AND
searchVal < tree->value && //if the searched for value is less than the current node's value AND
searchTree(tree->left, searchVal) //the search down the left-side node returns true theeeeen
) {
return true; //we're in business, return true to the search above
}
//eeeelse, it has to be greater on the right side
else if (tree->right != nullptr && searchTree(tree->right, searchVal)) {
return true;
}
return false;
}
|
C++
|
UTF-8
| 1,904 | 2.90625 | 3 |
[] |
no_license
|
#pragma once
#include <iostream>
#include <memory>
#include <utility>
#include <vector>
struct Vector;
class Matrix {
public:
Matrix() = default;
Matrix(int size, int size2 = 0); explicit
Matrix(const Matrix& mat);
Matrix(Matrix&& mat);
Matrix(double* table, const std::pair<int, int> size);
std::pair<int, int> getSize() const;
double& operator()(int x, int y);
double operator()(int x, int y) const;
Matrix& operator=(const Matrix& mat);
Matrix& operator=(Matrix&& mat);
Matrix& operator+=(Matrix& mat);
Matrix& operator*= (double mul);
friend std::ostream& operator<< (std::ostream& os, const Matrix& mat);
friend Matrix& operator/ (Matrix& mat, double scalar);
friend Matrix& operator+ (Matrix& mat, double scalar);
friend std::shared_ptr<Matrix> operator+ (Matrix& mat, Matrix& tab);
friend std::unique_ptr<Matrix> operator* (Matrix& mat, Matrix& mat1);
std::unique_ptr<Vector> multiply (Matrix& mat, Vector& vec);
void abs();
protected:
size_t sizeH, sizeW;
std::vector<std::vector<double>> tab;
};
struct Vector {
Vector() = default;
Vector(size_t size);
Vector(double* data, const size_t size);
Vector(const Vector& vec);
Vector(std::unique_ptr<Vector> vec);
Vector& operator=(Vector& vec);
Vector& operator=(std::unique_ptr<Vector> vec);
Vector& operator+=(Vector& mat);
Vector& operator*=(double scalar);
friend std::unique_ptr<Vector> operator*(Vector& vec, Matrix& mat);
friend std::unique_ptr<Vector> operator+ (Vector& a, Vector& b);
friend std::ostream& operator<< (std::ostream& os, const Vector& vec);
friend std::unique_ptr<Matrix> vecAndvecTMultiplication(Vector& a);
double& operator()(int);
double operator()(int) const;
void fullFill(double value);
std::vector<double> tab;
};
double determinantMat2(Matrix& mat);
void transposeMat2(Matrix& mat);
void inverseMat2(Matrix& mat);
|
PHP
|
UTF-8
| 3,176 | 3.046875 | 3 |
[] |
no_license
|
<?php
// Dossier dans lequel iront les images
$uploadDir = 'images/';
if (isset($_POST['Send']))
{
for($i=0; $i<count($_FILES['fichier']['name']); $i++) //boucle pour chaque fichier
{
if ($_FILES['fichier']['size'][$i] < 1000000) // Validation de la taille en octets
{
if (isset($_FILES['fichier']['type'][$i])) //Validation de la présence d'un fichier
{
if (in_array($_FILES['fichier']['type'][$i], array('image/gif', 'image/png', 'image/jpg', 'image/jpeg'))) // Validation du format de fichier
{
$uploadFile = $uploadDir . 'image' . uniqid() . '.' . pathinfo($_FILES['fichier']['name'][$i], PATHINFO_EXTENSION); //préparation du nommage du fichier et du chemin d'acces
$ok = move_uploaded_file($_FILES['fichier']['tmp_name'][$i], $uploadFile); //Déplacement du ficher depuis le fichier temp jusqu'au repertoire final
} else
{
$typeError = "Mauvais type de fichier";
}
}
}else
{
$sizeError = "Taille de fichier trop importante";
}
}
}
/**
* Deleting files
*/
if (isset($_GET["d"]))
{
unlink('images/' . $_GET["d"]);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<center style="padding-top: 300px">
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fichier[]" multiple="multiple" />
<input type="submit" name="Send" value="Send" />
<br><br>
<?php if (isset($typeError)){echo '<h1 style="color: red;">' . $typeError . '</h1>';}
if (isset($sizeError)){echo '<h1 style="color: red;">' . $sizeError . '</h1>';}
if (isset($ok)){echo '<h1 style="color: green;">Fichier(s) uploadé(s) !</h1>';}
?>
</form>
</center>
<br>
<hr><br>
<div class="container">
<div class="row justify-content-around">
<?php
$it = new FilesystemIterator('images/');
foreach ($it as $fileinfo)
{
?>
<div class="col-2">
<img src="images/<?= $fileinfo->getFilename()?>" alt="htr" class="img-thumbnail">
<center><a href="index.php?d=<?= $fileinfo->getFilename()?>"><button>Delete</button></a></center>
</div>
<?php } ?>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
|
Java
|
UTF-8
| 502 | 1.90625 | 2 |
[] |
no_license
|
package jinhetech.oracle.generation.entity.service;
import java.util.List;
import java.util.Map;
import jinhetech.oracle.generation.entity.entity.Table;
public interface DaoService {
/**
* 生成Dao层信息
* @param moduleMap 当前模块Map
* @param daoMap 当前Dao配置Map
* @param tableList
* @return
* @throws Exception
*/
public boolean generateDao(Map<String, Object> moduleMap,Map<String,Object> entityMap,List<Table> tableList) throws Exception;
}
|
Java
|
UTF-8
| 4,393 | 1.96875 | 2 |
[] |
no_license
|
package com.valfom.skydiving.altimeter;
import android.app.Activity;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ListView;
public class AltimeterListActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private AltimeterSimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
String[] fromColumns = { AltimeterDB.KEY_TRACKS_DATE };
int[] toViews = { R.id.tvTime };
adapter = new AltimeterSimpleCursorAdapter(this, R.layout.list_row,
null, fromColumns, toViews, 0);
setListAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked) {
SharedPreferences sharedPreferences = getSharedPreferences(AltimeterActivity.PREF_FILE_NAME, Activity.MODE_PRIVATE);
boolean logging = sharedPreferences.getBoolean("logging", false);
if (logging) {
int trackId = sharedPreferences.getInt("trackId", 0);
if (id == trackId) getListView().setItemChecked(position, false);
}
}
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_row_delete:
long[] checkedItems = getListView().getCheckedItemIds();
for (long id : checkedItems) {
Uri uri = Uri.parse(AltimeterContentProvider.CONTENT_URI_TRACKS + "/" + id);
getContentResolver().delete(uri, null, null);
}
mode.finish();
return true;
default:
return false;
}
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_list_row_selection, menu);
return true;
}
public void onDestroyActionMode(ActionMode mode) {}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
});
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, AltimeterContentProvider.CONTENT_URI_TRACKS,
null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent info = new Intent(AltimeterListActivity.this, AltimeterInfoActivity.class);
info.putExtra("trackId", id);
startActivity(info);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_list, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_settings:
Intent settings = new Intent(AltimeterListActivity.this, AltimeterPreferenceActivity.class);
startActivity(settings);
return true;
default:
return super.onMenuItemSelected(featureId, item);
}
}
}
|
Markdown
|
UTF-8
| 7,227 | 2.671875 | 3 |
[] |
no_license
|
p8105\_hw2\_kxg2002.Rmd
================
Katie
10/9/2019
## Load in the trash wheel data
``` r
trash_wheel_data =
read_excel(
path = "./Data/Trash-Wheel-Collection-Totals-8-6-19.xlsx",
range = "A2:N408") %>%
janitor::clean_names() %>%
select(-homes_powered) %>%
drop_na(dumpster) %>%
mutate(sports_balls = as.integer(sports_balls))
```
## Read and clean 2017 and 2018 precip data
``` r
precip_data_2017 =
read_excel(
path = "./Data/Trash-Wheel-Collection-Totals-8-6-19.xlsx",
sheet = 6,
range = "A2:B14") %>%
janitor::clean_names() %>%
drop_na(total) %>%
mutate(year = "2017")
precip_data_2018 =
read_excel(
path = "./Data/Trash-Wheel-Collection-Totals-8-6-19.xlsx",
sheet = 5,
range = "A2:B14") %>%
janitor::clean_names() %>%
drop_na(total) %>%
mutate(year = "2018")
```
## Combine precip data sets
``` r
precip_data =
full_join(precip_data_2017, precip_data_2018) %>%
mutate(month = month.name[month])
```
## Joining, by = c("month", "total", "year")
## Write about the data
Looking at the two datasets from 2017 and 2018, we can see that there
was a substantial amount of precipitation for both years in May and
July. However, there were also differences. For example, in 2018 there
was a large amount of precipitation in September compared to 2017, where
there was not a lot of precipitation. There were 12 observations in the
2017 precipiation data, 12 observations in the 2018 precipitation data,
and 344 observations from the trash wheel data. Key variables in the
precipitation data included month, total, year. Key variables in the
trash wheel data included dumpster, month, year, date, weight\_tons,
volume\_cubic\_yards, plastic\_bottles, polystyrene, cigarette\_butts,
glass\_bottles, grocery\_bags, chip\_bags, sports\_balls. The total
precipitation in 2018 was 70.33, and the median number of sports balls
found in dumpsters in 2017 were 8.
## Load, read, and clean data in pols-month.csv
``` r
polls_data =
read.csv("./Data/fivethirtyeight_datasets/pols-month.csv") %>%
janitor::clean_names() %>%
separate(col = mon, into = c("year", "month", "day"), sep = "-") %>%
mutate(year = as.integer(year), month = as.integer(month), day = as.integer(day)) %>%
mutate(month = month.abb[month]) %>%
select(year, month, day, prez_gop, prez_dem, everything()) %>%
pivot_longer(
prez_gop:prez_dem,
names_to = "president",
values_to = "status"
) %>%
select(year, month, president, everything(), -day, -status)
```
## Load, read, and clean data in snp.csv
``` r
snp_data =
read.csv("./Data/fivethirtyeight_datasets/snp.csv") %>%
janitor::clean_names() %>%
separate(col = date, into = c("month", "day", "year"), sep = "/") %>%
mutate(year = as.integer(year), month = as.integer(month)) %>%
mutate(month = month.abb[month]) %>%
select(year, month, close, -day)
```
## Load, read, and clean data in unemployment.csv
``` r
unemployment_data =
read_csv("./Data/fivethirtyeight_datasets/unemployment.csv") %>%
mutate(Year = as.integer(Year)) %>%
pivot_longer(
Jan:Dec,
names_to = "month",
values_to = "unemployment") %>%
janitor::clean_names()
```
## Parsed with column specification:
## cols(
## Year = col_double(),
## Jan = col_double(),
## Feb = col_double(),
## Mar = col_double(),
## Apr = col_double(),
## May = col_double(),
## Jun = col_double(),
## Jul = col_double(),
## Aug = col_double(),
## Sep = col_double(),
## Oct = col_double(),
## Nov = col_double(),
## Dec = col_double()
## )
## Merge data sets
``` r
join_polls_and_snp =
left_join(polls_data, snp_data)
```
## Joining, by = c("year", "month")
``` r
all_joined_datasets =
left_join(join_polls_and_snp, unemployment_data)
```
## Joining, by = c("year", "month")
## Write about the data
The polls data set contained information on the number and breakdown of
current and past serving Democratic and Republican public officials,
specifically governors, senators, and representatives. It also included
the party representation of the President. The dimensions of the data
set were 1644, 9, the names of key variables included year, month,
president, gov\_gop, sen\_gop, rep\_gop, gov\_dem, sen\_dem, rep\_dem,
and the range of years listed were between 1947, 2015.
The snp data set contained information on the closing values of the S\&P
stock index on the date listed. The dimensions of the data set were 787,
3, the names of key variables included year, month, close, and the range
of years listed were between 1950, 2015.
The unemployment data set contained information on the percentage of
unemployment in the corresponding month and year. The dimensions of the
data set were 816, 3, the names of key variables included year, month,
unemployment, and the range of years listed were between 1948, 2015.
The resulting combined dataset of all three contained information on the
number of Democratic and Republican public officials and the offices
they held during a specific month and year, the closing values of the
S\&P stock index during that time frame, and the percentage of
unemployment that month and year.
## Load and tidy Popular\_Baby\_Names.csv
``` r
baby_names =
read_csv("./Data/Popular_Baby_Names.csv") %>%
janitor::clean_names() %>%
mutate(gender = str_to_lower(gender),
ethnicity = str_to_lower(ethnicity),
childs_first_name = str_to_lower(childs_first_name),
ethnicity = recode(ethnicity,
"asian and paci" = "asian and pacific islander",
"black non hisp" = "black non hispanic",
"white non hisp" = "white non hispanic")) %>%
distinct(year_of_birth, gender, ethnicity, childs_first_name, .keep_all= TRUE)
```
## Parsed with column specification:
## cols(
## `Year of Birth` = col_double(),
## Gender = col_character(),
## Ethnicity = col_character(),
## `Child's First Name` = col_character(),
## Count = col_double(),
## Rank = col_double()
## )
## Create a table to show the rank in popularity of the name Olivia over the years
``` r
olivia_table =
filter(baby_names, childs_first_name == "olivia") %>%
select(-gender, -childs_first_name, -count) %>%
pivot_wider(
names_from = year_of_birth,
values_from = rank)
```
## Create a table to show the most popular name among male children over time
``` r
most_popular_boy_names =
filter(baby_names, gender == "male", rank == "1") %>%
select(-gender, -count, -rank) %>%
pivot_wider(
names_from = year_of_birth,
values_from = childs_first_name)
```
## Make a scatter plot
``` r
scatter_plot =
filter(baby_names, gender == "male", ethnicity == "white non hispanic", year_of_birth == "2016") %>%
ggplot(aes(x = rank, y = count)) +
geom_point()
```
Quick note: I tried to add color to geom\_point by doing (aes(color =
name)), but for some reason it wouldn’t graph anything… is it just
because the dataset is so large or is it because it won’t run?
|
Rust
|
UTF-8
| 10,153 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
//! Integration tests for the GDLK Wasm API
#![deny(clippy::all)]
// Needed for the macro
#![allow(clippy::bool_assert_comparison)]
use gdlk_wasm::{
compile, HardwareSpec, LangValue, ProgramSpec, SourceElement, Span,
};
use maplit::hashmap;
use std::collections::HashMap;
use wasm_bindgen_test::wasm_bindgen_test;
/// Checks each portion of the given machine's state, and compares each field
/// to the corresponding expected value.
macro_rules! assert_machine_state {
(
$machine:expr,
program_counter = $program_counter:expr,
cycle_count = $cycle_count:expr,
terminated = $terminated:expr,
successful = $successful:expr,
input = $input:expr,
output = $output:expr,
registers = $registers:expr,
stacks = $stacks:expr,
error = $error:expr
$(,)?
) => {{
let m = &$machine;
assert_eq!(m.program_counter(), $program_counter, "program counter");
assert_eq!(m.cycle_count(), $cycle_count, "cycle count");
assert_eq!(m.terminated(), $terminated, "terminated");
assert_eq!(m.successful(), $successful, "successful");
assert_eq!(m.input(), $input as &[LangValue], "input");
assert_eq!(m.output(), $output as &[LangValue], "output");
assert_eq!(
m.wasm_registers()
.into_serde::<HashMap<String, LangValue>>()
.unwrap(),
$registers,
"registers"
);
assert_eq!(
m.wasm_stacks()
.into_serde::<HashMap<String, Vec<LangValue>>>()
.unwrap(),
$stacks,
"stacks"
);
assert_eq!(m.wasm_error(), $error, "error");
}};
}
#[wasm_bindgen_test]
fn test_compile_success() {
let result = compile(
&HardwareSpec {
num_registers: 1,
num_stacks: 2,
max_stack_length: 10,
},
&ProgramSpec::new(vec![1], vec![1]),
"
READ RX0
WRITE RX0
",
);
let compile_success = result.unwrap();
let instructions = compile_success.instructions();
assert_eq!(
instructions.into_serde::<Vec<SourceElement>>().unwrap(),
vec![
SourceElement {
text: "TODO".into(),
span: Span {
offset: 9,
length: 8,
start_line: 2,
start_col: 9,
end_line: 2,
end_col: 17
}
},
SourceElement {
text: "TODO".into(),
span: Span {
offset: 26,
length: 9,
start_line: 3,
start_col: 9,
end_line: 3,
end_col: 18
}
}
]
);
let machine = compile_success.machine();
// Test initial state
assert_machine_state!(
machine,
program_counter = 0,
cycle_count = 0,
terminated = false,
successful = false,
input = &[1],
output = &[],
registers = hashmap! {
"RLI".into() => 1,
"RS0".into() => 0,
"RS1".into() => 0,
"RX0".into() => 0,
},
stacks = hashmap! {
"S0".into() => vec![],
"S1".into() => vec![],
},
error = None
);
}
#[wasm_bindgen_test]
fn test_compile_errors() {
let result = compile(
&HardwareSpec::default(),
&ProgramSpec::default(),
"
READ RX1
PUSH 3 S0
",
);
let errors = result.unwrap_err();
assert_eq!(
errors.into_serde::<Vec<SourceElement>>().unwrap(),
vec![
SourceElement {
text:
"Validation error at 2:14: Invalid reference to register `RX1`"
.into(),
span: Span {
offset: 14,
length: 3,
start_line: 2,
start_col: 14,
end_line: 2,
end_col: 17,
}
},
SourceElement {
text: "Validation error at 3:16: Invalid reference to stack `S0`"
.into(),
span: Span {
offset: 33,
length: 2,
start_line: 3,
start_col: 16,
end_line: 3,
end_col: 18,
}
}
]
);
}
#[allow(clippy::cognitive_complexity)]
#[wasm_bindgen_test]
fn test_execute() {
let result = compile(
&HardwareSpec {
num_registers: 1,
num_stacks: 1,
max_stack_length: 10,
},
&ProgramSpec::new(vec![1, 2, 3], vec![1, 2, 3]),
"
START:
JEZ RLI END
READ RX0
PUSH RX0 S0
POP S0 RX0
WRITE RX0
JMP START
END:
",
);
let mut machine = result.unwrap().machine();
// Test initial state
assert_machine_state!(
machine,
program_counter = 0,
cycle_count = 0,
terminated = false,
successful = false,
input = &[1, 2, 3],
output = &[],
registers = hashmap! {
"RLI".into() => 3,
"RS0".into() => 0,
"RX0".into() => 0,
},
stacks = hashmap! {
"S0".into() => vec![],
},
error = None
);
// JEZ
assert!(machine.wasm_execute_next());
assert_machine_state!(
machine,
program_counter = 1,
cycle_count = 1,
terminated = false,
successful = false,
input = &[1, 2, 3],
output = &[],
registers = hashmap! {
"RLI".into() => 3,
"RS0".into() => 0,
"RX0".into() => 0,
},
stacks = hashmap! {
"S0".into() => vec![],
},
error = None
);
// READ
assert!(machine.wasm_execute_next());
assert_machine_state!(
machine,
program_counter = 2,
cycle_count = 2,
terminated = false,
successful = false,
input = &[2, 3],
output = &[],
registers = hashmap! {
"RLI".into() => 2,
"RS0".into() => 0,
"RX0".into() => 1,
},
stacks = hashmap! {
"S0".into() => vec![],
},
error = None
);
// PUSH
assert!(machine.wasm_execute_next());
assert_machine_state!(
machine,
program_counter = 3,
cycle_count = 3,
terminated = false,
successful = false,
input = &[2, 3],
output = &[],
registers = hashmap! {
"RLI".into() => 2,
"RS0".into() => 1,
"RX0".into() => 1,
},
stacks = hashmap! {
"S0".into() => vec![1],
},
error = None
);
// POP
assert!(machine.wasm_execute_next());
assert_machine_state!(
machine,
program_counter = 4,
cycle_count = 4,
terminated = false,
successful = false,
input = &[2, 3],
output = &[],
registers = hashmap! {
"RLI".into() => 2,
"RS0".into() => 0,
"RX0".into() => 1,
},
stacks = hashmap! {
"S0".into() => vec![],
},
error = None
);
// WRITE
assert!(machine.wasm_execute_next());
assert_machine_state!(
machine,
program_counter = 5,
cycle_count = 5,
terminated = false,
successful = false,
input = &[2, 3],
output = &[1],
registers = hashmap! {
"RLI".into() => 2,
"RS0".into() => 0,
"RX0".into() => 1,
},
stacks = hashmap! {
"S0".into() => vec![],
},
error = None
);
// JMP
assert!(machine.wasm_execute_next());
assert_machine_state!(
machine,
program_counter = 0,
cycle_count = 6,
terminated = false,
successful = false,
input = &[2, 3],
output = &[1],
registers = hashmap! {
"RLI".into() => 2,
"RS0".into() => 0,
"RX0".into() => 1,
},
stacks = hashmap! {
"S0".into() => vec![],
},
error = None
);
// Execute the rest of the program
while !machine.terminated() {
assert!(machine.wasm_execute_next());
}
// Check final state
assert_machine_state!(
machine,
program_counter = 6,
cycle_count = 19,
terminated = true,
successful = true,
input = &[],
output = &[1, 2, 3],
registers = hashmap! {
"RLI".into() => 0,
"RS0".into() => 0,
"RX0".into() => 3,
},
stacks = hashmap! {
"S0".into() => vec![],
},
error = None
);
}
#[wasm_bindgen_test]
fn test_runtime_error() {
let result = compile(
&HardwareSpec::default(),
&ProgramSpec::default(),
"READ RX0",
);
let mut machine = result.unwrap().machine();
assert!(machine.wasm_execute_next());
assert_machine_state!(
machine,
program_counter = 0,
cycle_count = 1,
terminated = true,
successful = false,
input = &[],
output = &[],
registers = hashmap! {
"RLI".into() => 0,
"RX0".into() => 0,
},
stacks = hashmap! {},
error = Some(SourceElement {
text: "Runtime error at 1:1: Read attempted on empty input".into(),
span: Span {
offset: 0,
length: 8,
start_line: 1,
start_col: 1,
end_line: 1,
end_col: 9
}
})
);
}
|
C
|
UTF-8
| 498 | 2.765625 | 3 |
[] |
no_license
|
#include <avr/io.h>
#include <avr/interrupt.h>
int main (void)
{
// set pin 6/PB1/OC0B to be output
// set pin 5/PB0/OC0A to be output
DDRB = (1 << DDB1) | (1 << DDB0);
// Toggle OC0B on compare match with OCR0B.
// Toggle OC0A on compare match with OCR0A.
TCCR0A = (1 << COM0B0) | (1 << COM0A0);
// CTC mode.
TCCR0A |= (1 << WGM01);
// Prescaler: 256
TCCR0B = (1 << CS02);
// 20ms period
OCR0A = ((F_CPU / 1000) * 20 / 256) / 2;
while (1) {
}
return 0;
}
|
Java
|
UTF-8
| 642 | 2.734375 | 3 |
[] |
no_license
|
package com.example.nozes;
public class Meeting {
private String titulo, data, hora;
public Meeting(String titulo, String data, String hora){
this.titulo = titulo;
this.data = data;
this.hora = hora;
}
public String getTitle() {
return titulo;
}
public void setTitle(String titulo) {
this.titulo = titulo;
}
public String getDate() {
return data;
}
public void setDate(String data) {
this.data = data;
}
public String getHour() {
return hora;
}
public void setHour(String hora) {
this.hora = hora;
}
}
|
PHP
|
UTF-8
| 1,796 | 3 | 3 |
[] |
no_license
|
<?php
/**
* User: ms
* Date: 14.09.15
* Time: 21:24
*/
namespace Mvg\Parser\Html;
use Mvg\Parser\AbstractParser;
/**
* Class NewsTicker
* @package Mvg\Parser\Html
*/
class NewsTicker extends AbstractParser {
/**
* @var array
*/
protected $interferences = array();
/**
* @param $response
*/
public function __construct($response) {
parent::__construct($response);
$this->parse();
}
protected function parse() {
$jsonString = str_replace('//OK', '', $this->getHtmlResponse());
$array = json_decode($jsonString);
$payload = null;
//Find the interesting part
foreach ($array as $item) {
if (is_array($item)) {
$payload = $item;
break;
}
}
if (null === $payload) {
throw new \Exception('unable to parse payload from ' . $jsonString);
}
//Remove the Javastuff
foreach ($payload as $key => $item) {
if (preg_match('/de.swm.mvglive.gwt.client.newsticker.NewstickerItem/', $item)) {
unset($payload[$key]);
}
if (preg_match('/java.util.ArrayList/', $item)) {
unset($payload[$key]);
}
}
if (0 != (count($payload) % 2)) {
throw new \Exception('Item count is odd! ' . $jsonString);
}
$object = new \stdClass();
foreach ($payload as $key => $item) {
if (0 == ($key % 2)) {
$object = new \stdClass();
$object->lines = $item;
//get Lines with problems
$stringToAnalyze = trim(str_replace('Linie(n)', '', $item));
$linesString = explode(':', $stringToAnalyze)[0];
$object->affectedLines = explode(',', $linesString);
array_walk($object->affectedLines, function (&$item) {
$item = trim($item);
});
} else {
$object->messages = $item;
$this->interferences[] = $object;
}
}
}
public function getInterferences() {
return $this->interferences;
}
}
|
C#
|
UTF-8
| 7,524 | 2.796875 | 3 |
[] |
no_license
|
using Analytics.Modeling.ModelingExceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Analytics.Modeling.ModelingRules
{
class EnterOperation : BasicOperation
{
public EnterOperation(ModelingModel model) : base(model)//Пустой для функции check
{
}
private EnterOperation(string name, int numberOfOccupiedPoints, ModelingModel model) :
base(model)
{
parameters = new string[2];
parameters[0] = name;
parameters[1] = numberOfOccupiedPoints.ToString();
}
private EnterOperation(string name, ModelingModel model) : base(model)
{
parameters = new string[1];
parameters[0] = name;
}
public override Operation check(string rule)
{
string[] words = rule.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (words.Length > 0 && words[0] == "ENTER")
{
string[] param = words[1].Split(new char[] { ',' }, StringSplitOptions.
RemoveEmptyEntries);
if(param.Count() == 2)
{
return new EnterOperation(param[0], int.Parse(param[1]), model);
}
if (param.Count() == 1)
{
return new EnterOperation(words[1], model);
}
if (param.Count() > 2)
{
throw new IncorrectFormatOperation("Incorrect format modeling operation"+
"enter");
}
}
//Для случая наличия метки
if (words.Length > 1 && words[1] == "ENTER")
{
Lable lable = new Lable(model.getState().newRules.Count, words[0]);//создание метки
model.getState().lables.Add(lable);
string[] param = words[2].Split(new char[] { ',' }, StringSplitOptions.
RemoveEmptyEntries);
if (param.Count() == 2)
{
return new EnterOperation(param[0], int.Parse(param[1]), model);
}
if (param.Count() == 1)
{
return new EnterOperation(words[2], model);
}
if (param.Count() > 2)
{
throw new IncorrectFormatOperation("Incorrect format modeling operation"+
"enter");
}
}
return null;
}
public override void processing()
{
//поиск устройства по имени
for (int n = 0; n < model.getState().storages.Count; n++)
{
if (model.getState().storages.ElementAt(n).Get_name() == parameters[0])
{
//проверка на занятость
//если свободно
if (parameters.Count() == 2 && model.getState().storages.ElementAt(n).
checkEmptyPlaces(int.Parse(parameters[1])) == true)
{
model.getState().storages.ElementAt(n).enterStorage(int.
Parse(parameters[1]));
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).my_place++;//передвинул по программе дальше
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).sparePlace = 0;
return;
}
if (parameters.Count() == 1 && model.getState().storages.ElementAt(n).
checkEmptyPlaces(1) == true)
{
model.getState().storages.ElementAt(n).enterStorage(1);
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).my_place++;//передвинул по программе дальше
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).sparePlace = 0;
return;
}
//проверка, возможно, использовался режим both у операции Transfer
//и у транзакта есть запасное место перехода, для случая занятости основного
//(основной-в данном случае операция enter)
if(model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).sparePlace != 0)
{
//Убрал один переход из метки, что по ней был переход, так как транзакт не смог
//войти, а значит переход не должен быть зафиксирован
for (int i = 0; i < model.getState().lables.Count; i++)
{
if (model.getState().lables.ElementAt(i).get_my_plase() == model.getState().
tranzakts.ElementAt(model.getState().idProcessingTranzact).my_place)
{
model.getState().lables.ElementAt(i).decrementEntriesNumber();
}
}
//Переместил транзакт на запасное место
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).my_place =
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).sparePlace;
//Обнулил запасное место
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).sparePlace = 0;
return;
}
//иначе заносим в очередь, внутри устройства и блокируем перемещение
model.getState().storages.ElementAt(n).id_tranzaktions_in_device_queue.Add(
model.getState().tranzakts.ElementAt(model.getState().
idProcessingTranzact).get_my_id());
model.getState().tranzakts.ElementAt(model.getState().idProcessingTranzact).
blocked = true;
break;
}
}
}
public override Operation clone()
{
if (parameters.Count() == 1)
{
return new EnterOperation(parameters[0], model);
}
if (parameters.Count() == 2)
{
return new EnterOperation(parameters[0], int.Parse(parameters[1]), model);
}
throw new IncorrectFormatOperation("Incorrect format modeling operation"+
"enter");
}
}
}
|
Java
|
UHC
| 1,245 | 2.671875 | 3 |
[] |
no_license
|
package com.example.simplelistactivity;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SimpleList2Activity extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_list2);
// TODO Auto-generated method stub
ListView listView = (ListView)findViewById(R.id.simple_list2_listView);
ArrayList<HashMap<String, String>> hashMapList1 = new ArrayList<HashMap<String, String>>(2);
for(int i=0 ; i<10 ; i++){
HashMap<String, String> map = new HashMap<String, String>();
map.put("line1", "ù° "+i+"");
map.put("line2", "ι° "+i+"");
hashMapList1.add(map);
}
String[] from = {"line1", "line2"};
int[] to = {android.R.id.text1, android.R.id.text2};
SimpleAdapter simpleAdapter2 = new SimpleAdapter(this, hashMapList1, android.R.layout.simple_list_item_2, from, to);
listView.setAdapter(simpleAdapter2);
}
}
|
Java
|
UTF-8
| 2,542 | 2.421875 | 2 |
[] |
no_license
|
import java.io.*;
import java.util.*;
import javax.servlet.*;
import java.sql.*;
import java.util.*;
import javax.servlet.http.*;
public class DonateCloth extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
PrintWriter out = response.getWriter();
response.setContentType("text/html");
Connection con=null;
Statement st=null;
Statement st1=null;
ResultSet rs=null;
try
{
String name=request.getParameter("name");
String email=request.getParameter("email");
String mobile=request.getParameter("mobile");
String item=request.getParameter("item");
String village=request.getParameter("vill");
String post=request.getParameter("post");
String pincode=request.getParameter("pin");
String ps=request.getParameter("ps");
String city1=request.getParameter("city");
String city=city1.toUpperCase();
String dist=request.getParameter("dist");
String state=request.getParameter("state");
String date_and_time=request.getParameter("date");
String message=request.getParameter("message");
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");
st=con.createStatement();
rs=st.executeQuery("insert into donatecloth values('"+name+"','"+email+"','"+mobile+"','"+item+"','"+village+"','"+post+"','"+pincode+"','"+ps+"','"+city+"','"+dist+"','"+state+"','"+date_and_time+"','"+message+"')");
boolean a=rs.next();
if(a){
out.println("<script>alert(\"Thank You For Your Donation\");\n" +
" window.location=\"donatecloth.html\";\n" +
"</script>");
//request.getRequestDispatcher("signup.html").include(request, response);
}
else{
out.println("<script>alert(\"Unable to submit details! Please try again\");\n" +
" window.location=\"donatecloth.html\";\n" +
"</script>");
}
}
catch (Exception e){
out.println("<script>alert(\"Something went wrong!\");\n" +
" window.location=\"donatecloth.html\";\n" +
"</script>");
}
}
}
|
JavaScript
|
UTF-8
| 1,126 | 2.75 | 3 |
[] |
no_license
|
import React, { useEffect, useState } from "react";
import axios from "axios";
import LocationCard from "./LocationCard.js";
export default function LocationsList() {
const [locationList, setLocationList] = useState([]);
const [error, setError] = useState();
useEffect(() => {
//request to api
axios.get("https://rickandmortyapi.com/api/location/")
.then( response => {
//console.log(response.data.results);
//setter function stores response in locationList
setLocationList(response.data.results);
})
.catch(error => {
setError(error.response.message);
})
}, []);
return (
<section className="list grid-view">
{locationList.map(location => (
/*img = character.img */
<LocationCard key = {location.id} name = {location.name} dimension = {location.dimension}
residents = {location.residents.length} />))}
</section>
);
}
|
Python
|
UTF-8
| 648 | 3.203125 | 3 |
[] |
no_license
|
def DFS(graph, root):
visit = []
stack = [root]
while stack:
node = stack.pop()
if node not in visit:
visit.append(node)
stack.extend(graph[node])
return visit
T = int(input())
for _ in range(T):
N = int(input())
plist = list(map(int, input().split()))
graph = {}
for key in range(1, N+1):
graph[key] = set()
for node in range(1, N+1):
graph[node].add(plist[node-1])
count = 0
visited = []
for node in range(1, N+1):
if node not in visited:
visited.extend(DFS(graph, node))
count += 1
print(count)
|
Java
|
UTF-8
| 345 | 2.15625 | 2 |
[] |
no_license
|
package Ljc.JFramework;
public class TimeOutException extends CoreException {
/**
*
*/
private static final long serialVersionUID = 1L;
public TimeOutException() {
super();
}
public TimeOutException(String message) {
super(message);
}
public TimeOutException(String message, Exception inner) {
super(message, inner);
}
}
|
C
|
UTF-8
| 677 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
#include <string.h>
#define LEN_TEST 8
extern int init_randombytes();
extern void cleanup_randombytes();
extern void randombytes(unsigned char* dest, long long int length);
void print_buffer(unsigned char* randomness)
{
int i;
for(i = 0; i < LEN_TEST-1; i++)
{
printf("%02X ", randomness[i]);
}
printf("%02X\n", randomness[LEN_TEST-1]);
}
int main(int argc, char** argv)
{
unsigned char randomness[LEN_TEST];
int retval = init_randombytes();
memset(randomness, 0, LEN_TEST);
print_buffer(randomness);
randombytes(randomness, LEN_TEST);
print_buffer(randomness);
cleanup_randombytes();
return 0;
}
|
SQL
|
UHC
| 615 | 2.859375 | 3 |
[] |
no_license
|
DROP VIEW USRBM.VW_PC_CROSS;
/* Formatted on 2017-03-18 11:00:30 (QP5 v5.136.908.31019) */
CREATE OR REPLACE FORCE VIEW USRBM.VW_PC_CROSS
(
STND_YEAR,
SELL,
TMS,
DAY_ORD,
RACE_NO
)
AS
SELECT stnd_year,
DECODE (SUM (sell_cd), 2, 'â', 4, '', 'â') sell,
tms,
day_ord,
race_no
FROM TBJI_PC_PAYOFFS
WHERE meet_cd = '001' --AND day_ord = '1' AND tms = '12'
AND pool_cd = '001' AND sell_cd <> '01'
GROUP BY stnd_year,
tms,
day_ord,
race_no;
|
PHP
|
UTF-8
| 4,614 | 3.3125 | 3 |
[] |
no_license
|
<?php
class ExponentialGenerator {
public static function generate($start, $end, $ratio) {
$res = array();
if ($ratio <= 1.0) {
return $res;
}
while ($start <= $end) {
$next = (int) ($start * $ratio);
if ($next == $start) {
$next++;
}
$res[] = array($start, $next);
$start = $next;
}
return $res;
}
}
class Histogram {
private $binMap;
private $min;
private $max;
private $size;
private $total;
private function validateBins($bins) {
if (count($bins) == 0) {
return TRUE;
}
$f = $bins[0][0];
foreach ($bins as $b) {
if ($b[0] < $f || $b[0] >= $b[1]) {
return FALSE;
}
$f = $b[1];
}
return TRUE;
}
public function __construct($bins = array()) {
$this->binMap = array();
if ($this->validateBins($bins)) {
foreach ($bins as $b) {
$this->binMap[] = array($b[0], $b[1], 0);
}
} else {
print("WARNING: Bins invalid, histogram will not be built.");
}
$this->min = 0;
$this->max = 0;
$this->size = 0;
$this->total = 0;
}
public function add($key, $count = 1) {
$l = count($this->binMap);
for ($i = 0; $i < $l; $i++) {
if ($this->binMap[$i][0] <= $key && $key < $this->binMap[$i][1]) {
$this->binMap[$i][2] += $count;
if ($this->size == 0) {
$this->min = $key;
$this->max = $key;
} else {
if ($key < $this->min) {
$this->min = $key;
} else if ($key > $this->max) {
$this->max = $key;
}
}
$this->size += $count;
$this->total += $count * $key;
return TRUE;
}
}
return FALSE;
}
public function addHisto($h) {
$l = count($this->binMap);
if ($l != count($h->binMap)) {
return FALSE;
}
for ($i = 0; $i < $l; $i++) {
if ($this->binMap[$i][0] != $h->binMap[$i][0]
|| $this->binMap[$i][1] != $h->binMap[$i][1]) {
return FALSE;
}
}
if ($h->size > 0) {
for ($i = 0; $i < $l; $i++) {
$this->binMap[$i][2] += $h->binMap[$i][2];
}
$this->size += $h->size;
$this->total += $h->total;
if ($this->size == 0 || $h->min < $this->min) {
$this->min = $h->min;
}
if ($this->size == 0 || $h->max > $this->max) {
$this->max = $h->max;
}
}
return TRUE;
}
public function isSubset($h) {
$l = count($this->binMap);
if ($l != count($h->binMap)) {
return FALSE;
}
for ($i = 0; $i < $l; $i++) {
if ($this->binMap[$i][0] != $h->binMap[$i][0]
|| $this->binMap[$i][1] != $h->binMap[$i][1]) {
return FALSE;
}
}
if ($h->size > 0) {
for ($i = 0; $i < $l; $i++) {
if ($h->binMap[$i][2] > $this->binMap[$i][2]) {
return FALSE;
}
}
}
return TRUE;
}
public function getMin() {
return $this->min;
}
public function getMax() {
return $this->max;
}
public function getAvg() {
return $this->total / $this->size;
}
public function getSize() {
return $this->size;
}
public function getStr($name, $printZero = FALSE) {
$res = "{$name} histogram:\n";
$l = count($this->binMap);
for ($i = 0; $i < $l; $i++) {
if ($printZero || $this->binMap[$i][2] > 0) {
$res .= " [{$this->binMap[$i][0]}, {$this->binMap[$i][1]}] = {$this->binMap[$i][2]}\n";
}
}
if ($this->size > 0) {
$res .= "\n";
$res .= "Max = {$this->max}\n";
$res .= "Min = {$this->min}\n";
$res .= "Avg = {$this->getAvg()}\n";
}
$res .= "\n";
return $res;
}
public function printHisto($name, $printZero = FALSE) {
print($this->getStr($name, $printZero));
}
public function getBins() {
// TO BE WRITTEN
}
}
?>
|
TypeScript
|
UTF-8
| 1,234 | 2.734375 | 3 |
[] |
no_license
|
/*
Copyright (C) Michael Fatemi - All Rights Reserved.
Unauthorized copying of this file via any medium is strictly prohibited.
Proprietary and confidential.
Written by Michael Fatemi <myfatemi04@gmail.com>, February 2021.
*/
import hyphenate from '../lib/hyphenate';
export type Theme = {
// The classname for the theme to go under
name: string;
/** A dictionary of variables and their values */
colors: {
textPrimary: string;
textSecondary: string;
textDisabled: string;
textError: string;
textWarn: string;
bgPrimary: string;
bgSecondary: string;
bgElevated: string;
white: string;
};
};
function createStyleTag() {
const tag = document.createElement('style');
tag.setAttribute('type', 'text/css');
tag.setAttribute('data-styled', 'true');
const head = document.getElementsByTagName('head')[0];
head.appendChild(tag);
return tag;
}
const injectedThemes = new Set<string>();
export default function injectTheme(theme: Theme) {
if (!injectedThemes.has(theme.name)) {
const tag = createStyleTag();
let css = `.theme-${theme.name}{`;
for (let [name, value] of Object.entries(theme.colors)) {
css += `--${hyphenate(name)}:${value};`;
}
css += '}';
tag.innerHTML = css;
injectedThemes.add(theme.name);
}
}
|
Go
|
UTF-8
| 526 | 3.34375 | 3 |
[] |
no_license
|
package strand
// ToRNA will transcribe given DNA strain to its corresponding RNA strain
func ToRNA(dna string) string {
// Assuming the DNA sequence consist of nucleotide in bytes
dnaSeq := []byte(dna)
rnaSeq := make([]byte, len(dnaSeq))
// The mapping of DNA nucleotide to RNA nucleotide
rnaMapping := map[uint8]uint8{
'G': 'C',
'C': 'G',
'T': 'A',
'A': 'U',
}
// Transcribing RNA from given DNA sequence
for index, value := range dnaSeq {
rnaSeq[index] = rnaMapping[value]
}
return string(rnaSeq)
}
|
SQL
|
UTF-8
| 7,092 | 2.8125 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Jul 30, 2019 at 04:37 AM
-- Server version: 5.7.26
-- PHP Version: 7.3.7
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `rest_api`
--
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`enable` tinyint(1) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`, `enable`, `created_at`, `updated_at`, `deleted_at`) VALUES
(2, 'adsds', 1, '2019-07-28 11:54:46', '2019-07-30 02:53:47', '2019-07-30 02:53:47'),
(3, 'learning', 1, '2019-07-28 11:55:17', '2019-07-28 11:55:17', NULL),
(4, 'learning', 1, '2019-07-28 12:00:42', '2019-07-28 12:00:42', NULL),
(5, 'learning', 1, '2019-07-28 12:02:27', '2019-07-30 02:54:14', '2019-07-30 02:54:14'),
(6, 'learning', 1, '2019-07-28 12:03:08', '2019-07-28 12:03:08', NULL),
(7, 'learning', 1, '2019-07-28 12:03:17', '2019-07-28 12:03:17', NULL),
(8, 'learning', 1, '2019-07-28 12:04:21', '2019-07-28 12:04:21', NULL),
(9, 'learning', 1, '2019-07-28 12:04:23', '2019-07-28 12:04:23', NULL),
(10, 'learning', 0, '2019-07-28 12:04:36', '2019-07-29 03:01:39', NULL),
(11, 'learning', 1, '2019-07-28 12:04:37', '2019-07-28 12:04:37', NULL),
(12, 'belajar', 1, '2019-07-28 13:42:50', '2019-07-28 13:42:50', NULL),
(13, 'aye', 0, '2019-07-29 02:59:39', '2019-07-29 03:01:07', NULL),
(14, 'belajar', 1, '2019-07-30 03:28:31', '2019-07-30 03:32:42', '2019-07-30 03:32:42'),
(15, 'belajar', 1, '2019-07-30 03:33:45', '2019-07-30 03:39:42', '2019-07-30 03:39:42'),
(16, 'belajar', 1, '2019-07-30 03:39:29', '2019-07-30 03:39:29', NULL),
(17, 'belajar', 1, '2019-07-30 04:26:11', '2019-07-30 04:26:11', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `category_products`
--
CREATE TABLE `category_products` (
`id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `category_products`
--
INSERT INTO `category_products` (`id`, `product_id`, `category_id`, `created_at`, `updated_at`) VALUES
(3, 4, 3, '2019-07-29 03:11:56', '2019-07-29 03:14:30'),
(4, 7, 14, '2019-07-30 03:31:50', '2019-07-30 03:31:50'),
(7, 9, 17, '2019-07-30 04:26:30', '2019-07-30 04:26:30'),
(8, 9, 17, '2019-07-30 04:27:41', '2019-07-30 04:27:41');
-- --------------------------------------------------------
--
-- Table structure for table `images`
--
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`file` varchar(255) NOT NULL,
`enable` tinyint(1) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `images`
--
INSERT INTO `images` (`id`, `name`, `file`, `enable`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'images.jpg', './images/images.jpg.png', 1, '2019-07-28 22:43:22', '2019-07-30 03:04:54', NULL),
(2, 'batik.jpg', './images/batik.jpg.png', 1, '2019-07-29 03:16:05', '2019-07-29 03:16:05', NULL),
(3, 'DESAIN BANNER 1 HUT RI 74.psd', './images/DESAIN BANNER 1 HUT RI 74.psd.png', 1, '2019-07-30 03:41:10', '2019-07-30 03:41:49', '2019-07-30 03:41:49'),
(4, 'DESAIN BANNER 1 HUT RI 74.psd', './images/DESAIN BANNER 1 HUT RI 74.psd.png', 1, '2019-07-30 04:26:44', '2019-07-30 04:36:41', '2019-07-30 04:36:41');
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`description` varchar(255) NOT NULL,
`enable` tinyint(1) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `name`, `description`, `enable`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'adsds', 'aassss', 1, '2019-07-28 12:13:59', '2019-07-30 04:24:56', '2019-07-30 04:24:56'),
(2, 'buku', 'buku adalah', 1, '2019-07-28 13:41:57', '2019-07-28 13:41:57', NULL),
(3, 'buku', '', 1, '2019-07-28 14:34:04', '2019-07-28 14:34:04', NULL),
(4, 'uyea', 'huy', 1, '2019-07-29 02:48:58', '2019-07-30 04:23:18', '2019-07-30 04:23:18'),
(5, 'u', 'u', 1, '2019-07-29 03:03:35', '2019-07-30 03:01:50', NULL),
(6, 'uyea', 'huy', 1, '2019-07-29 03:04:58', '2019-07-29 03:04:58', NULL),
(7, 'uyea', 'huy', 1, '2019-07-29 03:09:28', '2019-07-29 03:09:28', NULL),
(8, 'p', 'p', 1, '2019-07-30 03:40:14', '2019-07-30 03:40:28', '2019-07-30 03:40:28'),
(9, 'p', 'p', 1, '2019-07-30 04:26:19', '2019-07-30 04:26:19', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `product_images`
--
CREATE TABLE `product_images` (
`id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`image_id` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `category_products`
--
ALTER TABLE `category_products`
ADD PRIMARY KEY (`id`),
ADD KEY `product_idx` (`product_id`),
ADD KEY `category_idx` (`category_id`);
--
-- Indexes for table `images`
--
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `product_images`
--
ALTER TABLE `product_images`
ADD PRIMARY KEY (`id`),
ADD KEY `product_idx` (`product_id`),
ADD KEY `image_idx` (`image_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- AUTO_INCREMENT for table `category_products`
--
ALTER TABLE `category_products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `images`
--
ALTER TABLE `images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `product_images`
--
ALTER TABLE `product_images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
|
Java
|
UTF-8
| 920 | 4.28125 | 4 |
[] |
no_license
|
/*
* File: Ch4Ex13.java
* ------------------
* This program reads in a series of integers from the user, until the
* sentinel is entered. Then it displays the largest number and the
* second largest entered.
*/
import acm.program.*;
public class Ch4Ex13 extends ConsoleProgram {
/* Variable to store the sentinel value */
private static final int SENTINEL = 0;
public void run() {
println("This program prompts you for a series of numbers, and");
println("then displays the largest, and second largest ones entered.");
println("Enter '0' to terminate the program.");
int max = 0;
int second_max = 0;
while (true) {
int input = readInt(" ? ");
if (input == SENTINEL) break;
if (input > max) {
max = input;
} else if (input > second_max) {
second_max = input;
}
}
println("The largest value is " + max);
println("The second largest is " + second_max);
}
}
|
C++
|
UTF-8
| 715 | 2.890625 | 3 |
[] |
no_license
|
#pragma once
#include <random>
#include <vector>
#include <algorithm>
using namespace std;
int Randrange(int b) {
static random_device r;
static mt19937 gen(r());
return gen() % b;
}
int Randrange(int a, int b) {
return Randrange(b) + a;
}
int Randchoice(const vector<int> &nums, const vector<double> &probs) {
vector<double> newProbs;
double sum = 0;
for (int i: nums) {
sum += probs[i];
newProbs.push_back(probs[i]);
}
newProbs[0] /= sum;
for (size_t i = 1; i < newProbs.size(); ++i) {
newProbs[i] = newProbs[i] / sum + newProbs[i - 1];
}
double choice = (double)rand() / RAND_MAX;
size_t i = lower_bound(newProbs.begin(), newProbs.end(), choice) - newProbs.begin();
return nums[i];
}
|
Java
|
UTF-8
| 2,227 | 2.015625 | 2 |
[] |
no_license
|
package com.how2java.tmall.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.how2java.tmall.mapper.OrderItemMapper;
import com.how2java.tmall.pojo.Order;
import com.how2java.tmall.pojo.OrderItem;
import com.how2java.tmall.pojo.OrderItemExample;
import com.how2java.tmall.pojo.Product;
import com.how2java.tmall.pojo.User;
import com.how2java.tmall.service.OrderItemService;
import com.how2java.tmall.service.ProductService;
@Service
public class OrderItemServiceimpl implements OrderItemService {
@Autowired
OrderItemMapper orderitemmapper;
OrderItemExample orderitemexample = new OrderItemExample();
//用到的service
@Autowired
ProductService productservice;
public List<OrderItem> getallorderitembyproduct(Product product){
orderitemexample.clear();
OrderItemExample.Criteria cri3 = orderitemexample.createCriteria();
cri3.andPidEqualTo(product.getId());
List<OrderItem> tempitem = orderitemmapper.selectByExample(orderitemexample);
return tempitem;
}
public List<OrderItem> getallorderitembyorder(Order order){
orderitemexample.clear();
OrderItemExample.Criteria cri3 = orderitemexample.createCriteria();
cri3.andOidEqualTo(order.getId());
List<OrderItem> tempitem = orderitemmapper.selectByExample(orderitemexample);
for(OrderItem oi : tempitem) {
oi.setProduct(productservice.getproduct(oi.getPid()));
}
return tempitem;
}
public List<OrderItem> getallcartitembyuser(User user){
orderitemexample.clear();
orderitemexample.createCriteria().andUidEqualTo(user.getId()).andOidIsNull();
List<OrderItem> tempitem = orderitemmapper.selectByExample(orderitemexample);
for(OrderItem oi : tempitem) {
oi.setProduct(productservice.getproduct(oi.getPid()));
}
return tempitem;
}
public void updateitem(OrderItem record){
orderitemmapper.updateByPrimaryKey(record);
}
public void additem(OrderItem record){
orderitemmapper.insert(record);
}
public OrderItem getitem(int id){
OrderItem tempitem = orderitemmapper.selectByPrimaryKey(id);
tempitem.setProduct(productservice.getproduct(tempitem.getPid()));
return tempitem;
}
}
|
Python
|
UTF-8
| 1,018 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
import os
from flask import Flask, request
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text)
email = db.Column(db.Text)
username = db.Column(db.Text)
def __init__(self, name, email, username):
self.name = name
self.email = email
self.username = username
db.create_all()
@app.route('/')
def index():
return "For the demo, navigate to the endpoint /"
@app.route('/signup')
def signup():
name = request.args.get('name')
email = request.args.get('email')
username = request.args.get('username')
new_user = User(name, email, username)
db.session.add(new_user)
return name + " was successfully added to the database!"
if __name__ == "__main__":
app.run(debug=True, use_reloader=True)
|
C
|
UTF-8
| 813 | 2.921875 | 3 |
[] |
no_license
|
/*
Solves the board using brute force.
returns :
*/
#define SOLUTION 0
#define PARTIAL_SOLN 1
#define NO_SOLN 2
int brute_force(cell_t* board) {
// Construct list of spots to fill up.
int lst_unfilled_idxs[BOARD_SIZE]; // Unnecessarily large, but that's okay.
int iter_lui; // iterator for lst_unfilled_indices
int n_unfilled;
iter_lui = 0;
int iter_board;
for(iter_board = 1; iter_board< BOARD_SIZE; ++iter_board) { // The 0th position is always null.
if( board[iter_board].value == 0 ) {
lst_unfilled_idxs[iter_lui] = iter_board;
++iter_lui;
}
}
n_unfilled = iter_lui;
// Now, to do iteration.
// To do this, maintain a lst_(cell_node_t*)
cell_node_t* lst_cellnodes[BOARD_SIZE];
int fl_bfcont = 1;
int idx_lst_idxs = 0;
/*
In any iteration,
*/
while (fl_bfcont) {
}
}
|
Python
|
UTF-8
| 881 | 4.125 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
def binary_search(my_list, key):
#Search key in my_list[start... end - 1].
start = 0
end = len(my_list)
while start < end:
mid = (start + end)//2
if my_list[mid] > key:
end = mid
elif my_list[mid] < key:
start = mid + 1
else:
return mid
return -1
#Вариант без пользовательского ввода в консоли
my_list1 = [2, 4, 6, 7, 9, 23]
key1 = 6
print(binary_search(my_list1, key1))
my_list = input('Enter the sorted list of numbers: ')
my_list = my_list.split()
my_list = [int(x) for x in my_list]
key = int(input('The number to search for: '))
index = binary_search(my_list, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
|
C++
|
UTF-8
| 469 | 3.453125 | 3 |
[] |
no_license
|
// Dynamic Programming
// Set 1 Overlapping sub-problems
// Fibonacci numbers
// solution 1: Top down
#define MAX 100
vector<int> v(MAX, 0);
int fib(int n) {
if(v[n] == 0) {
if(n <= 1) {
v[n] = 1;
}
else {
v[n] = fib(n-1) +fib(n-2);
}
}
return v[n];
}
// solution 2: Bottom up
int fib(int n) {
if(n <= 1) {
return 1;
}
vector<int> v(n+1, 0);
v[0] = v[1] = 1;
for(int i = 2; i <= n;i++) {
v[i] = v[i-1] + v[i-2];
}
return v[n];
}
|
PHP
|
UTF-8
| 1,937 | 2.75 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AppVersionController extends Controller
{
/**
* This index method is use for check app version in adroid and ios both
* If version is not latest than send update app message
* If platform is not android or ios than it gives invalid platform error
*/
public function index(Request $request) {
$validator = \Validator::make($request->all(), [
'app_version' => 'required',
'platform' => 'required|in:android,ios'
]);
if ($validator->fails()) {
return $this->error("error", implode(',',$validator->messages()->all()), 500);
}
if ($request->get('platform') == "android") {
if (config()->get('constants.ANDROID_MIN_REQUIRED_VERSION') > $request->get('app_version')) {
return response()->json([
'status' => 'error',
'message' => 'Please update app'
], 500);
} else {
return response()->json([
'status' => 'success',
'message' => 'success'
], 200);
}
} else if ($request->get('platform') == "ios") {
if (config()->get('constants.IOS_MIN_REQUIRED_VERSION') > $request->get('app_version')) {
return response()->json([
'status' => 'error',
'message' => 'Please update app'
], 500);
} else {
return response()->json([
'status' => 'success',
'message' => 'success'
], 200);
}
} else {
return response()->json([
'status' => 'error',
'message' => 'Invalid platform'
], 500);
}
}
}
|
C++
|
UTF-8
| 661 | 3.140625 | 3 |
[] |
no_license
|
#include "Polynomial.h"
Polynomial::Polynomial()
{
}
Polynomial::Polynomial(int key, int a0, int a1, int a2, int a3, int a4, int x)
:key(key),x(x)
{
a[0] = a0;
a[1] = a1;
a[2] = a2;
a[3] = a3;
a[4] = a4;
}
Polynomial::~Polynomial()
{
}
int* Polynomial::getCoefficient()
{
return a;
}
int Polynomial::getX()
{
return x;
}
int Polynomial::getKey()
{
return key;
}
int Polynomial::Value()
{
return a[0] + a[1]*x + a[2]*x*x + a[3]*x*x*x + a[4]*x*x*x*x;
}
void Polynomial::setKey(int key) {
this->key = key;
}
int Polynomial::overflowAddr()
{
return ofAddress;
}
void Polynomial::setOverflowAddr(int address)
{
this->ofAddress = address;
}
|
Markdown
|
UTF-8
| 3,584 | 2.65625 | 3 |
[] |
no_license
|
###### Mad in craft
# The psychologist who pretended to be insane
##### Susannah Cahalan grippingly explores an influential—but unreliable—experiment

> Jan 9th 2020
The Great Pretender: The Undercover Mission that Changed our Understanding of Madness. By Susannah Cahalan. Grand Central; 400 pages; $28. Canongate; £16.99.
IN 1973 DAVID ROSENHAN, an American psychologist, published a paper entitled “On Being Sane in Insane Places”. He had recruited seven volunteers to join him in feigning mental illness, to expose what he called the “undoubtedly counter-therapeutic” culture of his country’s psychiatric hospitals. The readiness with which the group’s sham symptoms were taken for the real thing seemed to show that even highly trained professionals could not accurately differentiate between the sick and the well.
For at least a decade, a crusade against traditional psychiatry had been gathering pace. In common with the period’s civil-rights campaigners, the leaders of this movement disputed the power of institutions and their prescriptions about society’s norms. Rosenhan’s findings played a crucial part in reinforcing the charges of sceptics who believed that mainstream psychiatric practice was crudely repressive. Indeed, they sparked debate about the very definition of mental illness.
In “The Great Pretender” Susannah Cahalan provides a vivid account of Rosenhan’s “undercover mission”. Her interest in him began with her own experience of being misdiagnosed with schizoaffective disorder, when in fact she had an autoimmune disease—as documented in her memoir “Brain on Fire” (2012). In her new book she recalls her delighted recognition as she read Rosenhan’s attack on the hubris that can blight psychiatry. Looking more closely at the man and his work seemed a way to sharpen her sense of the flaws in the profession’s diagnostic systems. Yet as she examined his notes and tried to track down his seven fellow “pseudopatients”, she began to have doubts about his methods.
Rosenhan (who died in 2012) was a gifted teacher, combining twinkly charisma with a flair for memorable anecdotes. But although he achieved academic eminence, holding chairs in both psychology and law at Stanford University, even his admirers acknowledged that he was slippery and given to drama. This was useful when he was trying to pass himself off as an ill man in need of psychiatric treatment. As Ms Cahalan reveals, however, his less enthusiastic colleagues thought he was “shady” and “avoided work like the plague”. His most severe critic, Robert Spitzer of Columbia University, bemoaned the sheer seductiveness of Rosenhan’s writings, opening a takedown with the remark that “Some foods taste delicious but leave a bad aftertaste.”
“The Great Pretender” is a sobering exercise in revisionism. It is also an impressive feat of investigative journalism—tenaciously conducted, appealingly written (despite the odd purple patch) and, when it focuses on Rosenhan’s story, as compelling as a detective novel. In the end Rosenhan emerges as an unpalatable symptom of a wider academic malaise.
Many of psychology’s most famous experiments have recently been discredited or devalued, the author notes. Immense significance has been attached to Stanley Milgram’s shock tests and Philip Zimbardo’s Stanford prison experiment, yet later re-runs have failed to reproduce their findings. As Ms Cahalan laments, the feverish reports on the undermining of such theories are a gift to people who would like to discredit science itself. ■
|
Shell
|
UTF-8
| 2,292 | 3.875 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
#set -e
#set -o pipefail
# trap any script errors and exit
trap "trapError" ERR
SUDO=
trapError() {
echo
echo " ^ Received error ^"
exit 1
}
createArchImg(){
#sudo apt-get install -y gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf libasound2-dev
#sudo apt-get -y update
#sudo apt-get -f -y --force-yes dist-upgrade
#sudo apt-get install -y libgssapi-krb5-2 libkrb5-3 libidn11
#sudo ./arch-bootstrap.sh archlinux
./arch-bootstrap_downloadonly.sh -a armv7h -r "http://eu.mirror.archlinuxarm.org/" archlinux
}
downloadToolchain(){
#wget http://archlinuxarm.org/builder/xtools/x-tools7h.tar.xz
#tar xf x-tools7h.tar.xz
#rm x-tools7h.tar.xz
if [ "$(ls -A ~/rpi2_toolchain)" ]; then
echo "Using cached RPI2 toolchain"
else
wget http://ci.openframeworks.cc/rpi2_toolchain.tar.bz2
tar xjf rpi2_toolchain.tar.bz2 -C ~/
rm rpi2_toolchain.tar.bz2
fi
}
downloadFirmware(){
wget https://github.com/raspberrypi/firmware/archive/master.zip -O firmware.zip
unzip firmware.zip
${SUDO} cp -r firmware-master/opt archlinux/
rm -r firmware-master
rm firmware.zip
}
relativeSoftLinks(){
rel_link=$1
escaped_rel_link=$2
for link in $(ls -la | grep "\-> /" | sed "s/.* \([^ ]*\) \-> \/\(.*\)/\1->\/\2/g"); do
lib=$(echo $link | sed "s/\(.*\)\->\(.*\)/\1/g");
link=$(echo $link | sed "s/\(.*\)\->\(.*\)/\2/g");
${SUDO} rm $lib
${SUDO} ln -s ${rel_link}/${link} $lib
done
for f in *; do
error_lib=$(grep " \/lib/" $f > /dev/null 2>&1; echo $?)
error_usr=$(grep " \/usr/" $f > /dev/null 2>&1; echo $?)
if [ $error_lib -eq 0 ] || [ $error_usr -eq 0 ]; then
${SUDO} sed -i "s/ \/lib/ $escaped_rel_link\/lib/g" $f
${SUDO} sed -i "s/ \/usr/ $escaped_rel_link\/usr/g" $f
fi
done
}
ROOT=$( cd "$(dirname "$0")" ; pwd -P )
echo $ROOT
cd $ROOT
createArchImg
downloadToolchain
downloadFirmware
cd $ROOT/archlinux/usr/lib
relativeSoftLinks "../.." "..\/.."
#cd $ROOT/archlinux/usr/lib/arm-unknown-linux-gnueabihf
#relativeSoftLinks "../../.." "..\/..\/.."
#cd $ROOT/raspbian/usr/lib/gcc/arm-unknown-linux-gnueabihf/5.3
#relativeSoftLinks "../../../.." "..\/..\/..\/.."
|
C
|
UTF-8
| 48,812 | 3.15625 | 3 |
[] |
no_license
|
/*
* ledSegment.c
*
* Created on: Dec 29, 2017
* Author: Sterna
*
* This file handles segmentation of LEDs. A segment is a strip with a certain number of LEDs
* The segment can be treated like a single strip, just smaller. It can be faded, put on loops, perform a pre-programmed pattern etc
* A segment may only span a single real strip. (i.e. a segment cannot begin on strip1 and end on strip2)
*
* A segment is created by initing it. The information needed is basically a range in a strip (say strip1, pixel 30 to 50).
* It will return a number, used to reference to this strip. Using this number, various things can be programmed per strip.
* Segment numbers are counted from 0.
*
* A segment has two settings, working in unison: fade and pulse. If one is not given (it does not have a segment number), that one is ignored
* The pulse (if given) will always supersede the fade.
* Pulse:
* A pulse is defined as a number of LEDs at max power, surrounded by a number of LEDs before and after with decreasing intensity, from max to min, per colour
* The pulse has an LED propagation speed. It consists of the number of cycles between each update, and the number of pixels the pulse shall move
* Pulse supports three modes: bounce and loop.
* In Loop mode, the pulse starts over from the first (or last) LED in the segment
* In Loop_end mode, the pulse behaves the same as in Loop mode, but the whole pulse will disappear before re-appearing
* In Bounce mode, the pulse will travel to the end of the segment, and then back to beginning, and then back to the end and loop like that
* Cycles defines the number of loop/bounce cycles. A complete bounce (first->last->first) is considered to be two cycles
* A pulse can start at a specified LED and have a specified direction. This direction will change in bounce mode, but persist in loop mode.
* Fade:
* A fade is defined as a max and min value per colour, between which the whole segment will fade in a certain time.
* Fade supports two modes: bounce and loop.
* In Loop mode, the intensity goes only in one direction, jumping immediately to the other extreme when done
* In Bounce mode, the intensity goes back and forth between min and max
* Loop_end mode is not really supported for fade, and will do the same thing as Loop mode
* Fade can also have the colToFrom-flag. This is used when wanting to fade between two different colours. Min is the from colour, and Max is the To colour
* In bounce mode, the fade is back an forth between the two colours
*
* Note on some animation tricks
* - Fill a segment with a pulse:
* Init a segment with a pulse and no fade. Use LOOP_END mode and 1 cycle
* - Use only pulse on a segment:
* Set max of all colours of fade=0
*
*
* New mode: Glitter mode. Runs instead of a pulse. Will be painted on a fade, without any regard to the fade setting.
* Instead of a wandering pulse, it will light up a number of LEDs in random places in the whole strip, each specified cycle.
*
* Glitter has a couple of main settings different from the standard settings to use:
* - RGBmax (set by pulse RGBMax). This describes the end colour for the glitter points. Glitter points always start from RGB=000;
* - Number of persistent glitter points (set by pulse ledsMaxPower). These are the number of saved glitter points.
* - Number of glitter points to be updated at the time (set by pulse pixelsPerIteration). These are the number of glitter points being faded from 0 to max. This is called the "glitter subset"
* - (This means that the total number of glitter points are ledsMaxPower+ledsFadeBefore)
* - Glitter fade time (set by pixelTime in ms). The time it will take for all fade LEDs (that is, all persistant LEDs) to reach max. It is also the cycle time.
* This means that each glitter subset will take pixelTime*pixelsPerIteration/ledsMaxpower
* pixelTime should be a multiple of LEDSEG_UPDATE_PERIOD_TIME
* Apart from these, the following settings are also used:
* - Mode. Sets which mode we're using (like before)
* - Start dir. (Will be added later. Set by startDir). The direction to start with
* - Number of cycles (set by cycles). One cycle is defined as when all ledsMaxPower have been lit.
* - GlobalSetting. Same as before
* The other settings are not used and can be omitted.
*
*
* Glitter can use the following modes. All modes light up points according to the settings until it reaches max. The mode then decides what happens:
* Loop: At max, it puts all those points out and restarts from 0.
* Loop_end: At max, it stops, persisting all lit points.
* Loop_persist (new mode): At max, it adds new LEDs every cycle, replacing the oldest ones.
* Bounce (implemented because it seems annoying): Like normal bounce, but works with adding/removing LEDs as the direction.
*
*
* Glitter - each cycle (with info needed)
* Count down cyclesToPulseMove. If trigger cycle:
* Update fade colour. If fade is done (>=RGBMax), reset colour state, add new
* Start in the ringbuffer from the currentLed (which is index0+pixelsPerIteration). Set all LEDs from this index until end of ringbuffer to maxRGB
*
*
*/
#include "ledSegment.h"
#include "stdlib.h"
#include "advancedAnimations.h"
//-----------Internal variables--------//
//Contains all information for all virtual LED segments
static ledSegment_t segments[LEDSEG_MAX_SEGMENTS];
//The number of initialized segments
static uint8_t currentNofSegments=0;
//---------------Internal functions------------//
static void fadeCalcColour(uint8_t seg);
static uint8_t pulseCalcColourPerLed(ledSegmentState_t* st,uint16_t led, colour_t col);
static void pulseCalcAndSet(uint8_t seg);
static bool checkCycleCounter(uint32_t* cycle);
static bool checkCycleCounterU16(uint16_t* cycle);
static bool checkSyncReadyFade(uint8_t syncGrp, uint8_t seg);
static bool checkFadeNotWaitingForSyncAll(uint8_t syncGrp);
static void resetSyncDoneGroup(uint8_t syncGrp);
static bool ledIsWithinSeg(uint8_t seg, uint16_t led);
static bool isExcludedFromAll(uint8_t seg);
/*
* Inits an LED segment
* Will return a value larger than LEDSEG_MAX_SEGMENTS if there is no more room for segments or any other error
* Note that it's possible to register a segment over another segment. There are no checks for this
*/
uint8_t ledSegInitSegment(uint8_t strip, uint16_t start, uint16_t stop, bool invertPulse, bool excludeFromAll, ledSegmentPulseSetting_t* pulse, ledSegmentFadeSetting_t* fade)
{
if(currentNofSegments>=LEDSEG_MAX_SEGMENTS || start>stop)
{
return (LEDSEG_MAX_SEGMENTS+1);
}
if(!apa102IsValidPixel(strip,start) || !apa102IsValidPixel(strip,stop))
{
return (LEDSEG_MAX_SEGMENTS+1);
}
//Make it slighly faster to write code for
ledSegment_t* sg=&segments[currentNofSegments];
//Load settings into state
sg->strip=strip;
sg->start=start;
sg->stop=stop;
sg->invertPulse=invertPulse;
sg->excludeFromAll=excludeFromAll;
currentNofSegments++;
if(!ledSegSetFade(currentNofSegments-1,fade))
{
sg->state.fadeActive=false;
}
if(!ledSegSetPulse(currentNofSegments-1,pulse))
{
sg->state.pulseActive=false;
}
return (currentNofSegments-1);
}
/*
* Get the state and all info for a specific led segment
* seg is the number of the segment (given from initSegment)
* state is where the state will be copied (you will not have access to the internal state variable)
* Returns false if the segment does not exist
*/
bool ledSegGetState(uint8_t seg, ledSegment_t* state)
{
if(ledSegExists(seg))
{
memcpy(state,&segments[seg],sizeof(ledSegment_t));
return true;
}
return false;
}
/*
* Returns true if a led segment exists. Includes LEDSEG_ALL
*/
bool ledSegExists(uint8_t seg)
{
if(seg<currentNofSegments || seg==LEDSEG_ALL)
{
return true;
}
return false;
}
/*
* Returns true if a led segment exists.
*/
bool ledSegExistsNotAll(uint8_t seg)
{
if(seg<currentNofSegments)
{
return true;
}
return false;
}
/*
* Setup the fade for a segment
* seg is the segment given by the init function
* fs is a pointer to the wanted setting
* Will reset the current fade cycle
*/
bool ledSegSetFade(uint8_t seg, ledSegmentFadeSetting_t* fs)
{
if(!ledSegExists(seg) || fs==NULL)
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetFade(i,fs);
}
}
return true;
}
//Create some temp variables that are easier to use
ledSegment_t* sg;
sg=&(segments[seg]);
ledSegmentState_t* st;
st=&(sg->state);
ledSegmentFadeSetting_t* fd;
fd=&(sg->state.confFade);
//Copy new setting into state
memcpy(fd,fs,sizeof(ledSegmentFadeSetting_t));
//Setup fade parameters
uint16_t periodMultiplier=1;
bool makeItSlower=false;
//The total number update periods we have to achieve the fade time Todo: consider adding a limit if a fade is very small (such as less than 10 steps)
uint32_t master_steps=0;
const uint8_t largestError=50;
do
{
makeItSlower=false;
master_steps=fs->fadeTime/(LEDSEG_UPDATE_PERIOD_TIME*periodMultiplier);
//Calculate number of steps needed to increase the colour per update period. If any value is too small, we need to go to a slower period
uint8_t r_diff= abs(fs->r_max-fs->r_min);
uint8_t g_diff= abs(fs->g_max-fs->g_min);
uint8_t b_diff= abs(fs->b_max-fs->b_min);
st->r_rate = r_diff/master_steps;
if(r_diff!=0 && (st->r_rate<1 || ((r_diff%master_steps)>largestError)))
{
makeItSlower=true;
}
st->g_rate = g_diff/master_steps;
if(g_diff!=0 && (st->g_rate<1 || ((g_diff%master_steps)>largestError)))
{
makeItSlower=true;
}
st->b_rate = b_diff/master_steps;
if(b_diff!=0 && (st->b_rate<1 || ((b_diff%master_steps)>largestError)))
{
makeItSlower=true;
}
if(makeItSlower)
{
periodMultiplier++;
}
}
while(makeItSlower);
fd->fadePeriodMultiplier = periodMultiplier;
st->cyclesToFadeChange = periodMultiplier;
//If the start dir is down, start from max
if(fs->startDir ==-1)
{
st->r=fs->r_max;
st->g=fs->g_max;
st->b=fs->b_max;
}
else
{
st->r=fs->r_min;
st->g=fs->g_min;
st->b=fs->b_min;
}
st->fadeDir = fs->startDir;
//Check if user wants a very large number of cycles. If so, mark this as run indefinitely
if(fs->cycles==0 || (UINT32_MAX/fs->cycles)<master_steps)
{
st->confFade.cycles=0;
}
else
{
st->confFade.cycles=fs->cycles;//*master_steps; //Each cycle shall be one half cycle (min->max)
}
st->fadeCycle=st->confFade.cycles;
//If the global setting is not used (set to 0) the default global will be loaded dynamically from the current global
if(fd->globalSetting == 0)
{
//fd->globalSetting = APA_MAX_GLOBAL_SETTING+1;
}
st->fadeActive = true;
st->fadeState=LEDSEG_FADE_NOT_DONE;
return true;
}
/*
* Setup a pulse for an LED segment
* Will reset the current pulse cycle
*/
bool ledSegSetPulse(uint8_t seg, ledSegmentPulseSetting_t* ps)
{
if(!ledSegExists(seg) || ps==NULL)
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetPulse(i,ps);
}
}
return true;
}
//Create some temp variables that are easier to use
ledSegment_t* sg;
sg=&(segments[seg]);
ledSegmentState_t* st;
st=&(sg->state);
ledSegmentPulseSetting_t* pu;
pu=&(sg->state.confPulse);
//Copy new setting into state
memcpy(pu,ps,sizeof(ledSegmentPulseSetting_t));
st->pulseCycle=ps->cycles;
st->pulseActive = true;
if(ledSegisGlitterMode(pu->mode))
{
//Allocate memory for the ring buffer.
free(st->glitterActiveLeds); //Remove old buffer
st->glitterActiveLeds = (uint16_t*)calloc(pu->ledsMaxPower+pu->pixelsPerIteration,sizeof(uint16_t)); //Allocate new buffer
st->currentLed=0; //currentLed is used as index in the ringbuffer.
//For glitter mode, pixelTime setting is the total time for fade of all the glitter pixels together.
//Therefore, we calculate the number of LEDSEG_UPDATE_PERIOD_TIME-cycles is needed for each glitter subsegment
//(GCC will probably optimize this)
uint32_t pixelTimeTemp=0;
pixelTimeTemp=pu->pixelTime/LEDSEG_UPDATE_PERIOD_TIME; //Total number of update periods for all glitter points (until the whole cycle is done)
pixelTimeTemp=pixelTimeTemp*pu->pixelsPerIteration/pu->ledsMaxPower; //The time it will take for each cycle to fade completely from 0 to max
if(pixelTimeTemp==0)
{
pixelTimeTemp=1;
}
pu->pixelTime=pixelTimeTemp;
st->cyclesToPulseMove=1; //So that we get LEDs from the beginning
}
else
{
//Allows to start index from the back
while(pu->startLed<0)
{
pu->startLed=pu->startLed+sg->stop-sg->start+2;
}
if(sg->invertPulse)
{
pu->startLed = sg->stop-pu->startLed+1;
pu->startDir *= -1;
}
else
{
pu->startLed = sg->start + pu->startLed-1;
}
if(pu->startLed>sg->stop)
{
pu->startLed=sg->stop;
}
else if(pu->startLed < sg->start)
{
pu->startLed=sg->start;
}
st->currentLed = pu->startLed;
st->cyclesToPulseMove = pu->pixelTime;
}
st->pulseDir=pu->startDir;
//If the global setting is not used (set to 0) the default global will be loaded dynamically from the current global
if(pu->globalSetting == 0)
{
//pu->globalSetting = APA_MAX_GLOBAL_SETTING+1;
}
st->pulseDone=false;
st->pulseActive=true;
return true;
}
/*
* Sets the fade colour to 0
*/
bool ledSegClearFade(uint8_t seg)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegClearFade(i);
}
}
return true;
}
ledSegment_t st;
ledSegGetState(seg,&st);
st.state.confFade.r_min=0;
st.state.confFade.r_max=0;
st.state.confFade.g_min=0;
st.state.confFade.g_max=0;
st.state.confFade.b_min=0;
st.state.confFade.b_max=0;
return ledSegSetFade(seg,&(st.state.confFade));
}
/*
* Sets the pulse colour to 0
*/
bool ledSegClearPulse(uint8_t seg)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegClearPulse(i);
}
}
return true;
}
ledSegment_t st;
ledSegGetState(seg,&st);
st.state.confPulse.r_max=0;
st.state.confPulse.g_max=0;
st.state.confPulse.b_max=0;
return ledSegSetPulse(seg,&(st.state.confPulse));
}
/*
* Sets the mode for a pulse
* Will take effect immediately
*/
bool ledSegSetFadeMode(uint8_t seg, ledSegmentMode_t mode)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetFadeMode(i,mode);
}
}
return true;
}
segments[seg].state.confFade.mode=mode;
return true;
}
/*
* Sets the mode for a pulse
* Will take effect immediately
*/
bool ledSegSetPulseMode(uint8_t seg, ledSegmentMode_t mode)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetPulseMode(i,mode);
}
}
return true;
}
segments[seg].state.confPulse.mode=mode;
return true;
}
/*
* Sets a single LED within a segment to a colour
* The LED is counted from the first LED in the segment (if LED=1, the start will be set)
* If the LED is out of bounds for the strip, the function will return false
* Will be overriden by any fade or pulse setting
*/
bool ledSegSetLed(uint8_t seg, uint16_t led, uint8_t r, uint8_t g, uint8_t b)
{
return ledSegSetLedWithGlobal(seg,led,r,g,b,0);
}
/*
* Sets a single LED within a segment to a colour, including the global setting
* The LED is counted from the first LED in the segment (if LED=1, the first LED will be set)
* If the LED is out of bounds for the strip, the function will return false
* Will be overriden by any fade or pulse setting
*/
bool ledSegSetLedWithGlobal(uint8_t seg, uint16_t led, uint8_t r, uint8_t g, uint8_t b,uint8_t global)
{
if(!ledIsWithinSeg(seg,led))
{
return false;
}
uint16_t tmp=0;
if(segments[seg].invertPulse)
{
tmp=segments[seg].stop-led+1;
}
else
{
tmp=segments[seg].start+led-1;
}
apa102SetPixelWithGlobal(segments[seg].strip,tmp,r,g,b,global,true);
return true;
}
/*
* Sets a range of LEDs within a segment to the same colour
* Start and stop are counted from the first LED in the segment (if LED=1, the first LED will be set)
* If the LED is out of bounds for the strip, the function will return false
* Will be overriden by any fade or pulse setting
*/
bool ledSegSetRange(uint8_t seg, uint16_t start, uint16_t stop,uint8_t r,uint8_t g,uint8_t b)
{
return ledSegSetRangeWithGlobal(seg,start,stop,r,g,b,0);
}
/*
* Sets a range of LEDs within a segment to the same colour, including the global setting
* Start and stop are counted from the first LED in the segment (if LED=1, the first LED will be set)
* If the LED is out of bounds for the strip, the function will return false
* Will be overriden by any fade or pulse setting
*/
bool ledSegSetRangeWithGlobal(uint8_t seg, uint16_t start, uint16_t stop,uint8_t r,uint8_t g,uint8_t b,uint8_t global)
{
if(start>stop || !ledIsWithinSeg(seg,start) || !ledIsWithinSeg(seg,stop))
{
return false;
}
apa102FillRange(segments[seg].strip,segments[seg].start+start-1,segments[seg].start+stop-1,r,g,b,global);
return true;
}
/*
* Sets the pulse active state to a new value. Useful for pausing an animation
*/
bool ledSegSetPulseActiveState(uint8_t seg, bool state)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetPulseActiveState(i,state);
}
}
return true;
}
segments[seg].state.pulseActive=state;
return true;
}
/*
* Gets the status of a pulse animation
*/
bool ledSegGetPulseActiveState(uint8_t seg)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i) && !ledSegGetPulseActiveState(i))
{
return false;
}
}
return true;
}
return segments[seg].state.pulseActive;
}
/*
* Sets the fade active state to a new value. Useful for pausing an animation
*/
bool ledSegSetFadeActiveState(uint8_t seg, bool state)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetFadeActiveState(i,state);
}
}
return true;
}
segments[seg].state.fadeActive=state;
return true;
}
/*
* Gets the status os a fade animation
*/
bool ledSegGetFadeActiveState(uint8_t seg)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i) && !ledSegGetFadeActiveState(i))
{
return false;
}
}
return true;
}
return segments[seg].state.fadeActive;
}
/*
* Returns true if the set fade animation is done
*/
bool ledSegGetFadeDone(uint8_t seg)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i) && !ledSegGetFadeDone(i))
{
return false;
}
}
return true;
}
return (segments[seg].state.fadeState==LEDSEG_FADE_DONE);
}
/*
* Returns true if the set fade animation switch is done
* If LEDSEG_ALL is given, it will only report true if all segments are done
*/
bool ledSegGetFadeSwitchDone(uint8_t seg)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i) && !ledSegGetFadeSwitchDone(i))
{
return false;
}
}
return true;
}
return (!segments[seg].state.switchMode);
}
/*
* Returns the sync group a segment is part of (will return 0 if not part of any sync group)
*/
uint8_t ledSegGetSyncGroup(uint8_t seg)
{
if(!ledSegExistsNotAll(seg))
{
return 0;
}
return segments[seg].state.confFade.syncGroup;
}
/*
* Checks if all fades within
* If the segment is not part of any sync group (if it's ==0) it's considered done
*/
bool ledSegGetSyncGroupDone(uint8_t syncGrp)
{
if(!syncGrp)
{
return true;
}
ledSegmentState_t* st;
for(uint8_t i=0;i<currentNofSegments;i++)
{
st=&(segments[i].state);
if(st->confFade.syncGroup == syncGrp && st->fadeState !=LEDSEG_FADE_DONE)
{
return false;
}
}
return true;
}
/*
* Returns true if the set pulse animation is done
*/
bool ledSegGetPulseDone(uint8_t seg)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i) && !ledSegGetPulseDone(i))
{
return false;
}
}
return true;
}
return segments[seg].state.pulseDone;
}
/*
* The the pulse speed by setting the pixel time and the pixelsPerIteration
* If value is 0, the existing value is used
* This will take effect immediately
*/
bool ledSegSetPulseSpeed(uint8_t seg, uint16_t time, uint16_t ppi)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetPulseSpeed(i,time,ppi);
}
}
return true;
}
if(time)
{
segments[seg].state.confPulse.pixelTime=time;
}
if(ppi)
{
segments[seg].state.confPulse.pixelsPerIteration=ppi;
}
return true;
}
/*
* Restart the fade, pulse or both. All other settings are retained
*/
bool ledSegRestart(uint8_t seg, bool restartFade, bool restartPulse)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegRestart(i,restartFade,restartPulse);
}
}
return true;
}
ledSegmentState_t* st=&segments[seg].state;
if(restartFade)
{
if(st->confFade.startDir == 1)
{
st->r = st->confFade.r_min;
st->g = st->confFade.g_min;
st->b = st->confFade.b_min;
st->fadeDir = 1;
}
else
{
st->r = st->confFade.r_max;
st->g = st->confFade.g_max;
st->b = st->confFade.b_max;
st->fadeDir = -1;
}
st->fadeState=LEDSEG_FADE_NOT_DONE;
st->fadeCycle=st->confFade.cycles;
st->fadeActive=true;
}
if(restartPulse)
{
st->pulseDir = st->confPulse.startDir;
st->currentLed = st->confPulse.startLed;
st->pulseCycle=st->confPulse.cycles;
if(ledSegisGlitterMode(st->confPulse.mode))
{
//Todo: Add handling for bounce
st->currentLed=st->confPulse.startLed;
}
st->pulseUpdatedCycle=false;
st->pulseActive=true;
st->pulseDone=false;
}
return true;
}
/*
* Sets a new global setting for the current segment
* Setting global to 0 will use the set default in the library
*/
bool ledSegSetGlobal(uint8_t seg, uint8_t fadeGlobal, uint8_t pulseGlobal)
{
if(!ledSegExists(seg))
{
return false;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetGlobal(i,fadeGlobal,pulseGlobal);
}
}
return true;
}
segments[seg].state.confFade.globalSetting=fadeGlobal;
segments[seg].state.confPulse.globalSetting=pulseGlobal;
return true;
}
/*
* Sets up a mode where you switch from one mode to another (soft fade between the two fade colours)
* st is the fade setting to fade TO (this just loads the correct colour)
* switchAtMax indicates of the modeChange-animation shall end on min or max
*/
void ledSegSetModeChange(ledSegmentFadeSetting_t* fs, uint8_t seg, bool switchAtMax)
{
if(!ledSegExists(seg))
{
return;
}
if(seg==LEDSEG_ALL)
{
for(uint8_t i=0;i<currentNofSegments;i++)
{
if(!isExcludedFromAll(i))
{
ledSegSetModeChange(fs,i,switchAtMax);
}
}
return;
}
//Get the colour of the current state to know what to move from
ledSegmentState_t* st = &(segments[seg].state);
ledSegmentFadeSetting_t fsTmp;
memcpy(&fsTmp,fs,sizeof(ledSegmentFadeSetting_t));
//At this point, we know the entire setting that we're going to go TO.
//Now we save the settings needed:
st->savedCycles = fs->cycles;
st->switchMode=true;
st->savedDir = fs->startDir;
//We will fade from min to max, with dir up. We therefore save the min value and assign that to the current state.
if(switchAtMax)
{
st->savedR =fs->r_min;
st->savedG =fs->g_min;
st->savedB =fs->b_min;
fsTmp.r_min = st->r;
fsTmp.g_min = st->g;
fsTmp.b_min = st->b;
fsTmp.startDir=1;
}
else //we will fade from max to min, with dir down.
{
st->savedR =fs->r_max;
st->savedG =fs->g_max;
st->savedB =fs->b_max;
fsTmp.r_max = st->r;
fsTmp.g_max = st->g;
fsTmp.b_max = st->b;
fsTmp.startDir=-1;
}
//Cycles shall always be 1, so we know when we are done
fsTmp.cycles=1;
ledSegSetFade(seg,&fsTmp);
}
/*
* Tells if a mode is a glitter mode
*/
bool ledSegisGlitterMode(ledSegmentMode_t mode)
{
if(mode>=LEDSEG_MODE_GLITTER_LOOP && mode<=LEDSEG_MODE_GLITTER_BOUNCE)
{
return true;
}
else
{
return false;
}
}
/*
* Returns the total length of a led segment
*/
uint16_t ledSegGetLen(uint8_t seg)
{
if(!ledSegExistsNotAll(seg))
{
return 0; //A non-exisiting ledSeg has the length of 0
}
return segments[seg].stop-segments[seg].start+1;
}
/*
* The great big update function. This should be run as often as possible (not from interrupts!)
* It keeps its own time gate, and will from time to time create a heavy load
*
* It uses the following scheme:
* The whole LED-system (all strips) is updated every LEDSEG_UPDATE_PERIOD_TIME.
* It has several calculations cycles per period (configurable in ledSegment.h). Each of these iterations, a calculation is performed
* Each calculation cycle will calculate a fraction of the total number of segments and load this into the big pixel array
* Note: no calculations are done while the strips are updating (the DMA is running).
* Otherwise, we would need to keep two copies of the whole pixel map, costing about 3kB of additional RAM
*
* Add an option in fadeSetting or a state in fadeState.
* The fade state or conf will need to remember some parts of the fade setting (the min colours, that it's fade, and the number of cycles)
* Set up the fade as normal, but create that special setting that allows fade between two colours and one cycle.
* Once fadeDone is true, switch the fade to the fade that's it supposed to be and switch to that
*
*/
void ledSegRunIteration()
{
static uint32_t nextCallTime=0;
static uint8_t calcCycle=0;
static uint8_t currentSeg=0;
//Temporary variables
uint8_t stopSegment=0;
uint16_t start=0;
uint16_t stop=0;
uint8_t strip=0;
ledSegmentState_t* st;
//These two are to measure the time the calculation takes
volatile uint32_t startVal=0;
volatile uint32_t timeTaken=0;
if(systemTime>nextCallTime && !apa102DMABusy(APA_ALL_STRIPS))
{
calcCycle++;
nextCallTime=systemTime+LEDSEG_UPDATE_PERIOD_TIME/LEDSEG_CALCULATION_CYCLES;
//Calculate the number of segments to calculate this cycle (always try to calculate one segment, even though it doesn't exist)
stopSegment=currentSeg+currentNofSegments/LEDSEG_CALCULATION_CYCLES+1;
//Calculate all active segments for this cycle
while(ledSegExists(currentSeg) && currentSeg<stopSegment)
{
startVal=microSeconds();
//Extract useful variables from the state
st=&(segments[currentSeg].state);
start=segments[currentSeg].start;
stop=segments[currentSeg].stop;
strip=segments[currentSeg].strip;
//Calculate and write fill colour to internal buffer
if(st->fadeActive)
{
if(checkCycleCounterU16(&st->cyclesToFadeChange))
{
fadeCalcColour(currentSeg);
st->cyclesToFadeChange = st->confFade.fadePeriodMultiplier;
}
//It will most likely take longer time to calculate which LEDs should not be filled,
//rather than just filling them and overwriting them. Writing a single pixel with force does not take very long time
apa102FillRange(strip,start,stop,st->r,st->g,st->b,st->confFade.globalSetting);
}
//Calculate and write pulse to internal LED buffer. Will overwrite the fade colour
if(st->pulseActive)
{
pulseCalcAndSet(currentSeg);
}
timeTaken=microSeconds()-startVal;
currentSeg++;
}
//Update calculation cycle and check if we should update the physical strip
if(calcCycle>=LEDSEG_CALCULATION_CYCLES)
{
//Update LEDs and restart calc cycle
apa102UpdateStrip(APA_ALL_STRIPS);
calcCycle=0;
currentSeg=0;
}
}
}
//-------------Internal functions------------------------//
/*
* Calculate the colour of a led faded in a pulse
* led is the led within the pulse, counted from currentLed (the first LED with a colour).
* led is indexed from reality (meaning currentLed has value 1, and that the lowest value is 1)
*/
static uint8_t pulseCalcColourPerLed(ledSegmentState_t* st,uint16_t led, colour_t col)
{
typedef enum
{
PULSE_BEFORE=0,
PULSE_MAX,
PULSE_AFTER
}pulsePart_t;
ledSegmentPulseSetting_t* ps;
ps=&(st->confPulse);
RGB_t RGBMaxTmp;
if(ps->colourSeqNum)
{
uint8_t tmp=1;
if(ps->colourSeqLoops)
{
tmp=ps->colourSeqLoops;
}
uint16_t ledsPerColour=(ps->ledsFadeBefore+ps->ledsMaxPower+ps->ledsFadeAfter)/(tmp*ps->colourSeqNum);
//If the pulse is shorter than PRIDE_COL_NOF_COLOURS, this will not work well
if(ledsPerColour<1)
{
ledsPerColour=1;
}
uint16_t colIndex=((led-1)/ledsPerColour)%ps->colourSeqNum;
RGBMaxTmp=animGetColourFromSequence(ps->colourSeqPtr,colIndex,255);//animGetColourPride((prideCols_t)colIndex,255);
}
else
{
RGBMaxTmp.r=ps->r_max;
RGBMaxTmp.g=ps->g_max;
RGBMaxTmp.b=ps->b_max;
}
uint8_t tmpCol=0;
uint8_t tmpMax=0;
uint8_t tmpMin=0;
pulsePart_t part=PULSE_BEFORE;
if(led<=ps->ledsFadeBefore)
{
part=PULSE_BEFORE;
}
else if(led<=(ps->ledsFadeBefore+ps->ledsMaxPower))
{
part=PULSE_MAX;
}
else
{
part=PULSE_AFTER;
}
switch(col)
{
case COL_RED:
// tmpMax=ps->r_max;
tmpMax=RGBMaxTmp.r;
tmpMin=st->r;
break;
case COL_GREEN:
// tmpMax=ps->g_max;
tmpMax=RGBMaxTmp.g;
tmpMin=st->g;
break;
case COL_BLUE:
// tmpMax=ps->b_max;
tmpMax=RGBMaxTmp.b;
tmpMin=st->b;
break;
}
switch(part)
{
case PULSE_MAX:
tmpCol=tmpMax;
break;
case PULSE_BEFORE:
tmpCol=tmpMin+(led)*(tmpMax-tmpMin)/ps->ledsFadeBefore;
break;
case PULSE_AFTER:
tmpCol=tmpMax-(led-ps->ledsFadeBefore-ps->ledsMaxPower-1)*(tmpMax-tmpMin)/ps->ledsFadeAfter;
break;
}
return tmpCol;
}
/*
* Calculate and set the LEDs for a pulse
*/
static void pulseCalcAndSet(uint8_t seg)
{
uint16_t start=0;
uint16_t stop=0;
uint8_t strip=0;
ledSegmentPulseSetting_t* ps;
ledSegmentState_t* st;
int8_t tmpDir=1;
uint16_t pulseLength=0;
uint8_t tmpR=0;
uint8_t tmpG=0;
uint8_t tmpB=0;
volatile uint8_t tmpSeg=seg;
if(!ledSegExists(seg))
{
return;
}
//Extract useful information
st=&(segments[seg].state);
ps=&(st->confPulse);
start=segments[seg].start;
stop=segments[seg].stop;
strip=segments[seg].strip;
pulseLength=ps->ledsFadeAfter+ps->ledsFadeBefore+ps->ledsMaxPower;
uint16_t glitterTotal=ps->ledsMaxPower+ps->pixelsPerIteration;
bool glitterJustGenerated=false;
//Move LED and update direction
//Check if it's time to move a pixel
if(checkCycleCounterU16(&st->cyclesToPulseMove) && !st->pulseDone)
{
if(ps->mode == LEDSEG_MODE_LOOP_END || st->pulseUpdatedCycle)
{
if((st->currentLed>=start) && (st->currentLed<=stop) && utilValueWillOverflow(st->currentLed,ps->pixelsPerIteration*st->pulseDir,start,stop))
{
if(checkCycleCounter(&st->pulseCycle))
{
st->pulseUpdatedCycle=true;
}
}
st->currentLed =st->currentLed+ps->pixelsPerIteration*st->pulseDir;
int32_t tmpLed= st->currentLed;
if(st->pulseDir==1 && (tmpLed>=(pulseLength+stop)))
{
if(st->pulseUpdatedCycle)
{
st->pulseDone = true;
st->pulseActive = false;
st->pulseUpdatedCycle=false;
}
else
{
st->currentLed = start;
}
}
else if(st->pulseDir==-1 && (tmpLed<=(int32_t)(start-pulseLength)))
{
if(st->pulseUpdatedCycle)
{
st->pulseDone = true;
st->pulseActive = false;
st->pulseUpdatedCycle=false;
}
else
{
st->currentLed = stop;
}
}
}
else if(ps->mode == LEDSEG_MODE_BOUNCE)
{
st->currentLed = utilBounceValue(st->currentLed,ps->pixelsPerIteration*st->pulseDir,start,stop,&tmpDir);
if(st->pulseDir!=tmpDir)
{
if(checkCycleCounter(&st->pulseCycle))
{
st->pulseUpdatedCycle=true;
}
else
{
st->pulseDir=tmpDir;
}
}
}
else if(ps->mode == LEDSEG_MODE_LOOP)
{
if(utilValueWillOverflow(st->currentLed,ps->pixelsPerIteration*st->pulseDir,start,stop))
{
if(checkCycleCounter(&st->pulseCycle))
{
st->pulseUpdatedCycle=true;
}
}
if(!st->pulseUpdatedCycle)
{
st->currentLed = utilLoopValue(st->currentLed,ps->pixelsPerIteration*st->pulseDir,start,stop);
}
}
else if(ledSegisGlitterMode(ps->mode))
{
//If fade is not active, make sure to clear all LEDs (which is what the fade would have done)
if(!st->fadeActive)
{
for(uint16_t i=0;i<glitterTotal;i++)
{
ledSegSetLedWithGlobal(seg,st->glitterActiveLeds[i],0,0,0,ps->globalSetting);
}
}
//For glitter mode, we will generate new LEDs now
//Here, we also check what we need to do based on mode.
if(st->currentLed>=glitterTotal)
{
if(ps->mode==LEDSEG_MODE_GLITTER_LOOP)
{
memset(st->glitterActiveLeds,0,glitterTotal*sizeof(uint16_t));
st->currentLed=0;
}
}
//This will handle LEDSEG_MODE_GLITTER_LOOP_END (and also other unforeseen things)
if(st->currentLed<glitterTotal)
{
for(uint16_t i=0;i<ps->pixelsPerIteration;i++)
{
//Todo: This method might generate LEDs that are already lit. To avoid this, we would need to look through the entire buffer for each new LED. Sorting might help here. Don't this unless really needed.
//Generate a random LED
if(st->pulseDir==-1)
{
st->glitterActiveLeds[st->currentLed]=0; //Clear the current LED if direction is down
}
else
{
st->glitterActiveLeds[st->currentLed]=utilRandRange(stop-start)+1; //We will skip LED 0 in the segment
}
if(st->pulseDir==-1 && st->currentLed==0)
{
st->currentLed=1;
}
st->currentLed+=st->pulseDir;
if(st->currentLed>=glitterTotal)
{
st->pulseUpdatedCycle=true;
//In loop_persist, we will restart the ring buffer from 0
if(ps->mode == LEDSEG_MODE_GLITTER_LOOP_PERSIST)
{
st->currentLed=0;
}
else if(ps->mode==LEDSEG_MODE_GLITTER_BOUNCE)
{
st->currentLed=glitterTotal-1;
st->pulseDir=-1;
break;
}
else //For LEDSEG_MODE_GLITTER_LOOP and LOOP_END
{
st->currentLed=glitterTotal;
break;
}
}
else if(st->currentLed==0 && ps->mode==LEDSEG_MODE_GLITTER_BOUNCE)
{
st->pulseUpdatedCycle=true;
st->pulseDir=1;
}
}
glitterJustGenerated=true;
}
}
else
{
//Invalid mode, fail silently
return;
}
st->cyclesToPulseMove = ps->pixelTime;
}//End of Cycles to move
//Glitter mode:
if(ledSegisGlitterMode(ps->mode))
{
//Load the current index of the ring buffer
uint16_t currentIndex=st->currentLed;
if((ps->mode == LEDSEG_MODE_GLITTER_LOOP || ps->mode == LEDSEG_MODE_GLITTER_LOOP_END) && currentIndex==glitterTotal)
{
currentIndex--;
}
//Calculate how many leds per colout for rainbowMode
uint16_t ledsPerCol=0;
if(ps->colourSeqNum)
{
uint8_t tmp=1;
if(ps->colourSeqLoops)
{
tmp=ps->colourSeqLoops;
}
ledsPerCol=(stop-start)/(ps->colourSeqNum*tmp);
}
//Handles the LED fading (the newest LEDs) for all modes. If no fading is going on (because we're done), currentIndex==glitterTotal.
if(currentIndex<glitterTotal)
{
//Todo: Check general buffer indexing to see if we miss/use the same LED multiple times, etc
//Go through the ring buffer in reverse, setting all fade LEDs to the proper colour
for(uint16_t i=0;i<ps->pixelsPerIteration;i++)
{
//Get which LED it is (updating the ring buffer)
if(currentIndex>0)
{
currentIndex--;
}
else
{
currentIndex=glitterTotal-1;
}
uint16_t ledIndex=st->glitterActiveLeds[currentIndex];
RGB_t RGBMaxTmp;
if(ps->colourSeqNum)
{
uint16_t colIndex=((ledIndex-1)/ledsPerCol)%ps->colourSeqNum;
RGBMaxTmp=animGetColourFromSequence(ps->colourSeqPtr,colIndex,255);
}
else
{
RGBMaxTmp.r=ps->r_max;
RGBMaxTmp.g=ps->g_max;
RGBMaxTmp.b=ps->b_max;
}
//Only reset the colour if new LEDs were just generated
if(glitterJustGenerated)
{
if(ps->mode == LEDSEG_MODE_GLITTER_BOUNCE && st->pulseDir==-1)
{
st->glitterR=RGBMaxTmp.r;
st->glitterG=RGBMaxTmp.g;
st->glitterB=RGBMaxTmp.b;
}
else
{
//Reset fade colour to 0, to start a new fade cycle
st->glitterR=0;//st->r;
st->glitterG=0;//st->g;
st->glitterB=0;//st->b;
}
}
//Update colour
//Todo: Make sure we can fade to and from st->rgb (might require quite a bit of code and possibly syncing to get right...)
st->glitterR=utilIncWithDir(st->glitterR,st->pulseDir,RGBMaxTmp.r/ps->pixelTime,0,RGBMaxTmp.r);
st->glitterG=utilIncWithDir(st->glitterG,st->pulseDir,RGBMaxTmp.g/ps->pixelTime,0,RGBMaxTmp.g);
st->glitterB=utilIncWithDir(st->glitterB,st->pulseDir,RGBMaxTmp.b/ps->pixelTime,0,RGBMaxTmp.b);
ledSegSetLedWithGlobal(seg,ledIndex,st->glitterR,st->glitterG,st->glitterB,ps->globalSetting);
//Check if colour is reached
if( (st->pulseDir==1 && st->glitterR == RGBMaxTmp.r && st->glitterG == RGBMaxTmp.g && st->glitterB == RGBMaxTmp.b) ||
(st->pulseDir==-1 && st->glitterR == 0 && st->glitterG == 0 && st->glitterB == 0) )
{
//If colour is reached, check if we have just generated all LEDs and update cycle if needed.
if(st->pulseUpdatedCycle)
{
st->pulseUpdatedCycle=false;
if(checkCycleCounter(&st->pulseCycle))
{
st->currentLed=glitterTotal;
st->pulseDone=true;
}
}
}
}
}
//Traverse the buffer in reverse from the point stopped to light up the rest of the LEDs fully (This will always run as long as the glitter pulse is active)
for(uint16_t i=0;i<ps->ledsMaxPower;i++)
{
if(currentIndex>0)
{
currentIndex--;
}
else
{
currentIndex=glitterTotal-1;
}
//Get which LED it is
uint16_t ledIndex=st->glitterActiveLeds[currentIndex];
//An LED with number 0 indicates that this is something we have not handled yet
if(ledIndex==0)
{
break;
}
//Generate maxColour for LED
RGB_t RGBMaxTmp;
if(ps->colourSeqNum)
{
uint16_t colIndex=((ledIndex-1)/ledsPerCol)%ps->colourSeqNum;
RGBMaxTmp=animGetColourFromSequence(ps->colourSeqPtr,colIndex,255);
}
else
{
RGBMaxTmp.r=ps->r_max;
RGBMaxTmp.g=ps->g_max;
RGBMaxTmp.b=ps->b_max;
}
ledSegSetLedWithGlobal(seg,ledIndex,RGBMaxTmp.r,RGBMaxTmp.g,RGBMaxTmp.b,ps->globalSetting);
}
}
else //Not glitter mode
{
if(st->pulseActive)
{
//Set colour for all LEDs in pulse
for(uint16_t i=0;i<pulseLength;i++)
{
//Generate where the LED shall be
int16_t tmpLedNum=0;
if(ps->mode == LEDSEG_MODE_LOOP_END || st->pulseUpdatedCycle)
{
tmpLedNum = st->currentLed+i*st->pulseDir*-1;
}
else if(ps->mode == LEDSEG_MODE_BOUNCE)
{
tmpLedNum=utilBounceValue(st->currentLed,i*st->pulseDir*-1,start,stop,NULL);
}
else if(ps->mode == LEDSEG_MODE_LOOP)
{
tmpLedNum=utilLoopValue(st->currentLed,i*st->pulseDir*-1,start,stop);
}
else
{
//Invalid mode, fail silently
return;
}
//Calculate colours and write LED
if(tmpLedNum>=start && tmpLedNum<=stop)
{
tmpR=pulseCalcColourPerLed(st,i+1,COL_RED);
tmpG=pulseCalcColourPerLed(st,i+1,COL_GREEN);
tmpB=pulseCalcColourPerLed(st,i+1,COL_BLUE);
apa102SetPixelWithGlobal(strip,tmpLedNum,tmpR,tmpG,tmpB,ps->globalSetting,true);
}
}
}
}
}
/*
* Takes a cycle counter and checks if it's done. Returns true if the cycles are completed
*/
static bool checkCycleCounter(uint32_t* cycle)
{
uint32_t tmp=0;
tmp=*cycle;
if(!tmp)
{
return false;
}
tmp--;
if(!tmp)
{
return true;
}
*cycle=tmp;
return false;
}
/*
* Takes a cycle counter and checks if it's done. Returns true if the cycles are completed
*/
static bool checkCycleCounterU16(uint16_t* cycle)
{
uint16_t tmp=0;
tmp=*cycle;
if(!tmp)
{
return false;
}
tmp--;
if(!tmp)
{
return true;
}
*cycle=tmp;
return false;
}
static bool segSyncReleaseFade[LEDSEG_MAX_SEGMENTS];
/*
* Calculates the colour to set for the fade part of this segment
* This colour is applied to all parts of the LED fade segment
*/
static void fadeCalcColour(uint8_t seg)
{
volatile uint8_t segTmp=seg;
ledSegmentState_t* st;
ledSegmentFadeSetting_t* conf;
if(!ledSegExists(seg))
{
return;
}
st=&(segments[seg].state);
conf=&(st->confFade);
bool redReversed=false;
bool blueReversed=false;
bool greenReversed=false;
if(st->fadeActive)
{
//Check if the direction of any colour is reveresed
if(conf->r_min>conf->r_max)
{
redReversed=true;
}
if(conf->g_min>conf->g_max)
{
greenReversed=true;
}
if(conf->b_min>conf->b_max)
{
blueReversed=true;
}
if(redReversed)
{
st->r=utilIncWithDir(st->r,st->fadeDir*-1,st->r_rate,conf->r_max,conf->r_min);
}
else
{
st->r=utilIncWithDir(st->r,st->fadeDir,st->r_rate,conf->r_min,conf->r_max);
}
if(greenReversed)
{
st->g=utilIncWithDir(st->g,st->fadeDir*-1,st->g_rate,conf->g_max,conf->g_min);
}
else
{
st->g=utilIncWithDir(st->g,st->fadeDir,st->g_rate,conf->g_min,conf->g_max);
}
if(blueReversed)
{
st->b=utilIncWithDir(st->b,st->fadeDir*-1,st->b_rate,conf->b_max,conf->b_min);
}
else
{
st->b=utilIncWithDir(st->b,st->fadeDir,st->b_rate,conf->b_min,conf->b_max);
}
//Check if we have reached an end (regardless of mode)
bool bAtMin=false;
bool bAtMax=false;
bool gAtMin=false;
bool gAtMax=false;
bool rAtMin=false;
bool rAtMax=false;
bool allReached=false;
//Check if each colour has reached its end
if((blueReversed && st->b<=conf->b_max) || (!blueReversed && st->b>=conf->b_max))
{
bAtMax=true;
}
else if((blueReversed && st->b>=conf->b_min) || (!blueReversed && st->b<=conf->b_min))
{
bAtMin=true;
}
if((greenReversed && st->g<=conf->g_max) || (!greenReversed && st->g>=conf->g_max))
{
gAtMax=true;
}
else if((greenReversed && st->g>=conf->g_min) || (!greenReversed && st->g<=conf->g_min))
{
gAtMin=true;
}
if((redReversed && st->r<=conf->r_max) || (!redReversed && st->r>=conf->r_max))
{
rAtMax=true;
}
else if((redReversed && st->r>=conf->r_min) || (!redReversed && st->r<=conf->r_min))
{
rAtMin=true;
}
if((bAtMin || bAtMax) && (gAtMin || gAtMax) && (rAtMin || rAtMax))
{
allReached=true;
}
if(allReached)
{
/*
* Om den är i syncgrp, måste den vänta tills alla i samma syncgrp är klara innan den går vidare
* NÄR ett segment hamnar här och alla är klara, kan vi gå vidare.
* När vi går vidare måste resten av syncgruppen veta att vi blev klara och ska gå vidare.
*
* state 1: sync not done (vi kör som vanligt och går till sin extrem
* state 2: extreme reached, this seg ready for sync
* state 3: all reached and synced.
* state 4: sync done for this seg
* state 5: sync done for all, move to state 1
*/
volatile ledSegmentFadeState_t syncState=LEDSEG_FADE_NOT_DONE;
if(conf->syncGroup)
{
//We enter here and we have not marked this as ready. Mark it as ready and continue to loop the fade to its own max
if(st->fadeState==LEDSEG_FADE_NOT_DONE)
{
st->fadeState=LEDSEG_FADE_WAITING_FOR_SYNC;
}
if(checkSyncReadyFade(conf->syncGroup,seg))
{
segSyncReleaseFade[conf->syncGroup]=true;
}
//Check: Have all reached and are we at the lowest seg in the group?
//If so, we can release all segs in this group
}
/*
* Sync system (fade)
* Register syncs:
* Add the sync number to the fade setting.
* Send this setting to a segment
*
* During run
* When this segment has allReached and is about to clear the last cycle, mark as waitingForSync.
* Check if all segments with this sync number are waitingForSync.
* If yes, end cycle and continue
* If no, run one more cycle and check again.
*/
if(!conf->syncGroup || (conf->syncGroup && segSyncReleaseFade[conf->syncGroup]))
{
//Check if the fade is done. if so, mark this fade as done. Otherwise, update what is do be done at an extreme
if(st->fadeCycle && checkCycleCounter(&st->fadeCycle))
{
//Perform switch, if needed to. Otherwise, we're done
if(st->switchMode)
{
st->switchMode=false;
if(conf->startDir==1) //We are at max
{
//Restore min
conf->r_min = st->savedR;
conf->g_min = st->savedG;
conf->b_min = st->savedB;
}
else //We are at min
{
//Restore max
conf->r_max = st->savedR;
conf->g_max = st->savedG;
conf->b_max = st->savedB;
}
if(conf->mode == LEDSEG_MODE_LOOP || conf->mode == LEDSEG_MODE_LOOP_END)
{
conf->startDir = st->savedDir;
}
else if(conf->mode == LEDSEG_MODE_BOUNCE)
{
conf->startDir = st->fadeDir*-1;
}
conf->cycles = st->savedCycles;
ledSegSetFade(seg,conf);
}
else
{
st->fadeState=LEDSEG_FADE_DONE;
}
}
else
{
switch (conf->mode)
{
case LEDSEG_MODE_BOUNCE:
{
st->fadeDir*=-1;
break;
}
//Loop and Loop_end works the same
case LEDSEG_MODE_LOOP:
case LEDSEG_MODE_LOOP_END:
{
if(st->fadeDir == -1)
{
st->r=conf->r_max;
st->g=conf->g_max;
st->b=conf->b_max;
}
else if(st->fadeDir == 1)
{
st->r=conf->r_min;
st->g=conf->g_min;
st->b=conf->b_min;
}
break;
}
default:
{
//For any other mode, do nothing
break;
}
}
st->fadeState=LEDSEG_FADE_NOT_DONE;
}
//Check if ALL segments in the group have finished syncing. If so, reset all of them to NOT_FINISHED (except if they're done)
if(segSyncReleaseFade[conf->syncGroup] && checkFadeNotWaitingForSyncAll(conf->syncGroup))
{
segSyncReleaseFade[conf->syncGroup]=false;
}
}
} //End of allReached
}
}
/*
* Checks if all the fade animations in the same sync group are ready for sync
* If syncgroup=0 (not part of any sync group), it is by definition synced with itself
* Note: FADE_DONE is treated as FADE_SYNC_DONE
*/
static bool checkSyncReadyFade(uint8_t syncGrp, uint8_t seg)
{
if(!syncGrp)
{
return true;
}
bool allState=true;
uint8_t firstFound=255;
ledSegmentState_t* st;
for(uint8_t i=0;i<currentNofSegments;i++)
{
st=&(segments[i].state);
if(st->confFade.syncGroup == syncGrp)
{
if(firstFound==255)
{
firstFound=i;
}
if(st->fadeState != LEDSEG_FADE_WAITING_FOR_SYNC)
{
allState=false;
}
}
}
return (allState && (firstFound==seg));
}
/*
* Returns true if all none of the fades in a sync group are not in Waiting_for_sync
* This is used to detect if they have already synced
*/
static bool checkFadeNotWaitingForSyncAll(uint8_t syncGrp)
{
if(!syncGrp)
{
return true;
}
bool allState=true;
ledSegmentState_t* st;
for(uint8_t i=0;i<currentNofSegments;i++)
{
st=&(segments[i].state);
if(st->confFade.syncGroup == syncGrp && st->fadeState==LEDSEG_FADE_WAITING_FOR_SYNC)
{
allState=false;
}
}
return allState;
}
/*
* This will reset all segments to LEDSEG_FADE_NOT_DONE
*/
static void resetSyncDoneGroup(uint8_t syncGrp)
{
ledSegmentState_t* st;
for(uint8_t seg=0;seg<currentNofSegments;seg++)
{
st=&(segments[seg].state);
if(st->confFade.syncGroup == syncGrp && st->fadeState!=LEDSEG_FADE_DONE)
{
st->fadeState=LEDSEG_FADE_NOT_DONE;
}
}
}
/*
* Returns true if the LED exists within the segment and if the segment exists (Not valid for LEDSEG_ALL)
*/
static bool ledIsWithinSeg(uint8_t seg, uint16_t led)
{
if(!ledSegExistsNotAll(seg))
{
return false;
}
if(led==0 || led>(segments[seg].stop-segments[seg].start+1))
{
return false;
}
return true;
}
/*
* Returns true if a segment is configured to be excluded from a call with LEDSEG_ALL
* LEDSEG_ALL and a non-existing segment are considered to be excluded
*/
static bool isExcludedFromAll(uint8_t seg)
{
if(!ledSegExistsNotAll(seg))
{
return true;
}
return segments[seg].excludeFromAll;
}
|
C
|
UTF-8
| 314 | 3.25 | 3 |
[] |
no_license
|
#include "player_heal.h"
#include <stdio.h>
int player_heal(int *nowHP,int healHP,int MaxHP){
if(*nowHP+healHP<MaxHP){
*nowHP += healHP;
printf("HPを%d回復した!\n",healHP);
}
else{
*nowHP = MaxHP;
printf("HPが満タンになった!\n");
}
return 0;
}
|
C
|
UTF-8
| 279 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
#include <message_def.h>
MSG_CODE get_my_message(void) {
return HELLO_YOU;
}
int main() {
printf(gm(JUST_SAY_HI));
printf("\n");
printf(gm(HELLO_WORLD));
printf("\n");
printf(gm(get_my_message()));
printf("\n");
return 0;
}
|
C++
|
UTF-8
| 4,421 | 2.734375 | 3 |
[] |
no_license
|
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include <cmath>
#include <random>
#include <chrono>
#include <vector>
#include <map>
using namespace std;
struct TEXT{
public:
std::map<int, string> menu;
TEXT(){
this->menu[1] = "Sortowanie przez proste wstawianie\n";
this->menu[2] = "Sortowanie przez wstawianie polowkowe\n";
this->menu[3] = "Sortowanie przez proste wybieranie\n";
this->menu[4] = "Sortowanie babelkowe\n";
this->menu[5] = "Sortowanie mieszane\n";
this->menu[6] = "Sortowanie metoda Shella\n";
this->menu[7] = "Sortowanie stogowe\n";
this->menu[8] = "Sortowanie szybkie metoda rekurencyjna\n";
this->menu[9] = "Zamknij program\n";
}
};
vector <int> randomVector(int sizeTab, int beginRange, int endRange);
int* randomTabInt(int sizeTab, int beginRange, int endRange);
void zad1(int * tab, int sizeTab);
void zad2(int *tab, int sizeTab);
void zad3(int *tab, int sizeTab);
void zad4(int *tab, int sizeTab);
void zad5(int *tab, int sizeTab);
void zad6(int *tab, int sizeTab);
void zad7(int * tab, int size);
void zad8(int *a, int n);
void przesiewanie(int * tab, int p, int q);
void sortuj(int *a, int q, int p);
void zad1(int *tab, int sizeTab){
int j=0, k=0;
for(int i = 1; i <sizeTab; i++){
k = tab[i];
j = i -1;
while(j>=0 && k < tab[j]){
tab[j+1] = tab[j];
--j;
}
tab[j+1] = k;
}
}
void zad2(int *tab, int sizeTab){
int i, j, q, p, m, k;
for (i=1;i<sizeTab;i++) {
k = tab[i];
q = 0;
p = i-1;
while (q<=p) {
m = (q+p)/2;
if (k < tab[m]) {
p = m-1;
} else {
q = m+1;
}
}
for (j=i-1; j>=q; j--) {
tab[j+1] = tab[j];
}
tab[q] = k;
}
}
void zad3(int *tab, int sizeTab){
int i, j, z, k;
//Point k;
for (i=0; i<=sizeTab-1; i++) {
z = i;
k = tab[i];
for (j=i+1; j<sizeTab; j++) {
if (tab[j] < k) {
z=j;
k=tab[j];
}
}
tab[z]=tab[i];
tab[i]=k;
}
}
void zad4(int *tab, int sizeTab){
int i,j,x;
for(i=1; i<sizeTab; i++){
for(j=sizeTab; j>=i; j--){
if(tab[j-1] > tab[j]){
swap(tab[j-1], tab[j]);
}
}
}
}
void zad5(int *tab, int sizeTab){
int j,k,q,p,x, obj;
q=0;
p=sizeTab;
k=sizeTab;
do {
for (j=p; j>=q; j--) {
if (tab[j-1] > tab[j]) {
obj=tab[j-1];
tab[j-1]=tab[j];
tab[j]=obj;
k=j;
}
}
q = k+1;//+1
for (j=q; j<=p; j++) {
if (tab[j-1] > tab[j]) {
obj = tab[j-1];
tab[j-1] = tab[j];
tab[j] = obj;
k=j;
}
}
p = k-1;//-1;//-1
} while (q < p);
}
void zad6(int *tab, int sizeTab){
const int t = 4;
int i, j, k, s, x;
int h[4] = {1,3,7,15};//9,5,3,1};
for(int m=0; m<t; m++) { // <=
k = h[m]; // k=9
s = -k; // s = -9 //-k
//stapsize = s
//s<=N-1
for (i = k; i < sizeTab; i++) {// 10 ->12 //s-> k
x = tab[i]; //x =tab[9]
j = i-k; //j = 9-9 = 0
if (s==0) {
s = -k;
s = s+1;
tab[s] = x;
}
while (x < tab[j] && j>=0) { //tab[0]
tab[j+k]=tab[j]; //tab[9] = tab[0]
j = j-k;// j = -9
}
tab[j+k] = x; //tab[0] = tab[9]
}
}
}
void przesiewanie(int *tab, int p, int q){
int i, j, x;
i = q;
j = 2*i;
x = tab[i];
while (j < p){
if(j<p){
if(tab[j] < tab[j+1])
j += 1;
if(x >= tab[j])
goto stop;
tab[i] = tab[j];
i = j;
j = 2*i;
}
}
stop: tab[i] = x;
}
void zad7(int *tab, int size){
int q, p, x;
q = size/2;
p = size-1;
while (q>0){
q -= 1;
przesiewanie(tab, p, q);
};
while (p>0){
x = tab[0];
tab[0] = tab[p];
tab[p] = x;
p -= 1;
przesiewanie(tab, p, q);
};
}
void sortuj(int *tab, int q, int p) {
int i, j, x, w;
i = q;
j = p;
x = tab[(q+p)/2];
while (i <= j){
while (tab[i] < x) {
++i;
}
while (x < tab[j]) {
--j;
}
if (i <= j) {
w = tab[i];
tab[i] = tab[j];
tab[j] = w;
++i;
--j;
}
}
if (q < j) {
sortuj(tab, q, j);
}
if (i < p) {
sortuj(tab, i, p);
}
}
void zad8(int *a, int n) {
sortuj (a, 0, n-1);
}
int* randomTabInt(int sizeTab, int beginRange, int endRange){
int* tab = new int[sizeTab];
std::default_random_engine random_generator(std::chrono::steady_clock::now().time_since_epoch().count());
std::uniform_int_distribution<int> distribution(beginRange, endRange);
for(int i=0; i< sizeTab; i++){
tab[i] = distribution(random_generator);
}
return tab;
}
|
TypeScript
|
UTF-8
| 9,226 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2020-2023 SenX S.A.S.
*
* 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.
*/
/**
* Parsing result of // @command parameter in the beginning of the WarpScript
*/
export interface specialCommentCommands {
endpoint?: string;
timeunit?: string;
localmacrosubstitution?: boolean;
displayPreviewOpt?: string;
listOfMacroInclusion?: string[];
listOfMacroInclusionRange?: any[];
theme?: string;
}
/**
* Little class to store statement and its offset in the text
*/
export class wsStatement {
public statement: string;
public offset: number;
constructor(statement: string, offset: number) {
this.statement = statement;
this.offset = offset;
}
}
export class WarpScriptParser {
/**
* Look for a statement position in the recursive tree of macros markers.
*
* @param macroPositions the table of macro positions (output of parseWarpScriptMacros)
* @param offset the absolute position of the start of statement you are looking for
* @param numberOfMacros the expected number of macros
*/
public static findMacrosBeforePosition(macroPositions: any, offset: number, numberOfMacros: number): any[] {
for (let idx = 0; idx < macroPositions.length; idx++) {
if (macroPositions[idx] instanceof wsStatement && (macroPositions[idx] as wsStatement).offset == offset) {
//found the statement. need to return previous macros as ranges
let pidx = idx - 1;
let c = 0;
let startEndList: any[] = [];
while (pidx >= 0 && c < numberOfMacros) {
if (macroPositions[pidx] instanceof wsStatement) {
break;
} else {
if (typeof (macroPositions[pidx]) !== 'number') {
startEndList.push([macroPositions[pidx][0], macroPositions[pidx][macroPositions[pidx].length - 1]]);
c++;
}
}
pidx--;
}
return startEndList;
} else if (typeof (macroPositions[idx]) === 'number') {
// console.log("not in this block")
} else {
let r = this.findMacrosBeforePosition(macroPositions[idx], offset, numberOfMacros);
if (null !== r) {
return r;
}
}
}
return null;
}
/**
* Unlike parseWarpScriptMacros, this function return a very simple list of statements (as strings), ignoring comments.
* [ '"HELLO"' '"WORLD"' '+' '2' '2' '*' ]
*
* When called with withPosition true, it returns a list of list than include start and end position of the statement:
* [ [ '"HELLO"' 4 11 ] [ '"WORLD"' 22 29 ] ]
*/
public static parseWarpScriptStatements(ws: String, withPosition = false): any[] {
let i: number = 0;
let result: any[] = [];
while (i < ws.length - 1) { //often test 2 characters
if (ws.charAt(i) == '<' && ws.charAt(i + 1) == '\'') { //start of a multiline, look for end
// console.log(i, 'start of multiline');
let lines: string[] = ws.substring(i, ws.length).split('\n');
let lc = 0;
while (lc < lines.length && lines[lc].trim() != '\'>') {
i += lines[lc].length + 1;
lc++;
}
i += lines[lc].length + 1;
// console.log(i, 'end of multiline');
}
if (ws.charAt(i) == '/' && ws.charAt(i + 1) == '*') { //start one multiline comment, seek for end of comment
// console.log(i, 'start of multiline comment');
i++;
while (i < ws.length - 1 && !(ws.charAt(i) == '*' && ws.charAt(i + 1) == '/')) {
i++;
}
i += 2;
// console.log(i, 'end of multiline comment');
}
if (ws.charAt(i) == '/' && ws.charAt(i + 1) == '/') { //start single line comment, seek for end of line
// console.log(i, 'start of a comment');
i++;
while (i < ws.length - 1 && (ws.charAt(i) != '\n')) {
i++;
}
// console.log(i, 'end of a comment');
}
if (ws.charAt(i) == '\'') { //start of string, seek for end
// console.log(i, 'start of string');
let start = i;
i++;
while (i < ws.length && ws.charAt(i) != '\'' && ws.charAt(i) != '\n') {
i++;
}
i++;
result.push(ws.substring(start, i).replace('\r', ''));
// console.log(i, 'end of string');
}
if (ws.charAt(i) == '"') { //start of string, seek for end
// console.log(i, 'start of string');
let start = i;
i++;
while (i < ws.length && ws.charAt(i) != '"' && ws.charAt(i) != '\n') {
i++;
}
// console.log(i, 'end of string');
i++;
result.push(ws.substring(start, i).replace('\r', ''));
}
if (ws.charAt(i) == '<' && ws.charAt(i + 1) == '%') { //start of a macro.
// console.log(i, 'start of macro');
result.push('<%');
i += 2;
}
if (ws.charAt(i) == '%' && ws.charAt(i + 1) == '>') { //end of a macro.
// console.log(i, 'end of macro');
result.push('%>');
i += 2;
}
if (ws.charAt(i) != ' ' && ws.charAt(i) != '\n') {
let start = i;
while (i < ws.length && ws.charAt(i) != ' ' && ws.charAt(i) != '\n') {
i++;
}
if (withPosition) {
result.push([ws.substring(start, i).replace('\r', ''), start, i]);
} else {
result.push(ws.substring(start, i).replace('\r', ''));
}
}
i++;
}
return result;
}
public static extractSpecialComments(executedWarpScript: string): specialCommentCommands {
let result: specialCommentCommands = {};
let warpscriptlines = executedWarpScript.split('\n');
result.listOfMacroInclusion = [];
result.listOfMacroInclusionRange = [];
for (let l = 0; l < warpscriptlines.length; l++) {
let currentline = warpscriptlines[l];
if (currentline.startsWith('//')) {
//find and extract // @paramname parameters
let extraparamsPattern = /\/\/\s*@(\w*)\s*(.*)$/g;
let lineonMatch: RegExpMatchArray | null;
let re = RegExp(extraparamsPattern);
while (lineonMatch = re.exec(currentline.replace('\r', ''))) { //think about windows... \r\n in mc2 files !
let parametername = lineonMatch[1];
let parametervalue = lineonMatch[2];
switch (parametername) {
case 'endpoint': // // @endpoint http://mywarp10server/api/v0/exec
result.endpoint = parametervalue; // overrides the Warp10URL configuration
break;
case 'localmacrosubstitution':
result.localmacrosubstitution = ('true' === parametervalue.trim().toLowerCase()); // overrides the substitutionWithLocalMacros
break;
case 'timeunit':
if (['us', 'ms', 'ns'].indexOf(parametervalue.trim()) > -1) {
result.timeunit = parametervalue.trim();
}
break;
case 'preview':
switch (parametervalue.toLowerCase().substring(0, 4)) {
case 'none':
result.displayPreviewOpt = 'X';
break;
case 'gts':
result.displayPreviewOpt = 'G';
break;
case 'imag':
result.displayPreviewOpt = 'I';
break;
case 'json':
result.displayPreviewOpt = 'J';
break;
case 'disc':
result.displayPreviewOpt = 'D';
break;
default:
result.displayPreviewOpt = '';
break;
}
break;
case 'include':
let p = parametervalue.trim();
if (p.startsWith('macro:')) {
p = p.substring(6).trim();
result.listOfMacroInclusion.push(p);
let r = {startLineNumber: l, startColumn: 3, endLineNumber: l, endColumn: currentline.trim().length};
result.listOfMacroInclusionRange.push(r);
}
break;
case 'theme':
result.theme = parametervalue.trim().toLowerCase();
break;
default:
break;
}
}
} else {
if (currentline.trim().length > 0) {
break; //no more comments at the beginning of the file
}
}
}
return result;
}
public static IsWsLitteralString(s: String): boolean {
// up to MemoryWarpScriptStack, a valid string is:
return (s.length >= 2 && ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith('\'') && s.endsWith('\''))));
}
}
|
JavaScript
|
UTF-8
| 1,144 | 2.953125 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
import CharacterSelector from '../components/CharacterSelector.js';
import CharacterDetail from '../components/CharacterDetail.js';
class StarWarsContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
characters: [],
selectedCharacter: null
};
this.handleCharacterSelected = this.handleCharacterSelected.bind(this);
}
componentDidMount() {
const url = 'https://swapi.co/api/people'
fetch(url)
.then((res) => {
return res.json();
})
.then((characters) => {
this.setState({
characters: characters.results
});
})
}
handleCharacterSelected(index) {
console.log(index);
const selectedCharacter = this.state.characters[index];
this.setState({
selectedCharacter: selectedCharacter
});
}
render() {
return(
<div className="star-wars-container">
<CharacterSelector characters={this.state.characters}
onCharacterSelected = {this.handleCharacterSelected}/>
<CharacterDetail selectedCharacter={this.state.selectedCharacter}/>
</div>
)
}
};
export default StarWarsContainer;
|
Markdown
|
UTF-8
| 2,912 | 3.703125 | 4 |
[] |
no_license
|
# Command-line-interpreter
Implementation of a shell (command-line interpreter).
Like traditional UNIX shells, the shell program will also be a user level process , that will
rely heavily on the operating system's services.
The shell do the following:
* Receive commands from the user.
* Interpret the commands, and use the operating system to help starting up programs and processes requested by the user.
* Manage process execution (e.g. run processes in the background, suspend them, etc.), using the operating system's services.
## Shell description
The shell works like a real command interpreter.
It means that the shell supports executing commands without waiting for the process to terminate.
In addition , the shell supports the waiting option , using the waitpid call.
The shell also has "cd" feature that allows the user to change the current working directory.
## Job control description
I used a linked list, where each node is a struct job in order to store a list of all running/suspended jobs.
```
typedef struct job{
char *cmd; /* the whole command line as typed by the user, including input/output redirection and pipes */
int idx; /* index of current job (starting from 1) */
pid_t pgid; /* process group id of the job*/
int status; /* status of the job */
struct termios *tmodes; /* saved terminal modes */
struct job *next; /* next job in chain */
} job;
```
### Job control feautres
* Receive a cmd (command line), initialize job fields (to NULLs, 0s etc.), and allocate memory for the new job and its fields
* free all memory allocate for the job, include the job struct itself.
* Receive a job list and an index, and return the job that has the given index.
* update the status of jobs running in the background
* Adding jobs to the list, and printing them
* Running jobs in the foreground
* Runing jobs in the background
## Examples
```
$>test1&
Start of test1
$>test2&
Start of test2
$>test3&
Start of test3
$>jobs
[1] Running ./test1&
[2] Running ./test2&
[3] Running ./test3&
$>End of test3
End of test2
End of test1
quit
```
Run in the foreground
```
$> test1
Start of test1
^Z
$> jobs
[1] Suspended test1
$> fg 1
End of test1
[1] Done test1
$>quit
```
Run in the background
```
$> test1
Start of test1
^Z
$> test2
Start of test2
^Z
$> test3
Start of test3
^Z
$> jobs
[1] Suspended test1
[2] Suspended test2
[3] Suspended test3
$> fg 3
End of test3
[3] Done test3
$> jobs
[1] Suspended test1
[2] Suspended test2
$> bg 2
$> End of test2
fg 1
End of test1
[1] Done test1
$>jobs
[2] Done test2
$>jobs
$> quit
```
|
C++
|
UTF-8
| 6,766 | 2.546875 | 3 |
[] |
no_license
|
#include "firstfollow.h"
//functions for checking wheather the look ahead token is in first of any non terminal
//First of definition
vector<Symbol> Firstfollow::firstOfDefinition()
{
vector<Symbol> fOfConstDef = firstOfConstDef();
vector<Symbol> fOfVariDef = firstOfVariDef();
vector<Symbol> fOfProcDef = firstOfProcDef();
vector<Symbol> fOfDefSet = fOfConstDef + fOfVariDef + fOfProcDef;
return fOfDefSet;
}
//First of constantDefinition
vector<Symbol> Firstfollow::firstOfConstDef()
{
vector<Symbol> fOfContDef;
fOfContDef.push_back(CONST);
return fOfContDef;
}
//First of variableDefinition
vector<Symbol> Firstfollow::firstOfVariDef()
{
vector<Symbol> fOfVariDef;
fOfVariDef.push_back(INT);
fOfVariDef.push_back(BOOL);
return fOfVariDef;
}
//First of procedureDefinition
vector<Symbol> Firstfollow::firstOfProcDef()
{
vector<Symbol> fOfProcDef;
fOfProcDef.push_back(PROC);
return fOfProcDef;
}
//First of variableList
vector<Symbol> Firstfollow::firstOfVariList()
{
vector<Symbol> fOfVariList;
fOfVariList.push_back(ID);
return fOfVariList;
}
//First of statementPart
vector<Symbol> Firstfollow::firstOfStatePart()
{
}
//First of statement
vector<Symbol> Firstfollow::firstOfStatement()
{
vector<Symbol> fOfEmptySt = firstOfEmptySt();
vector<Symbol> fOfReadSt = firstOfReadSt();
vector<Symbol> fOfWriteSt = firstOfWriteSt();
vector<Symbol> fOfAssignSt = firstOfAssignSt();
vector<Symbol> fOfProcSt = firstOfProcSt();
vector<Symbol> fOfIfSt = firstOfIfSt();
vector<Symbol> fOfDoSt = firstOfDoSt();
return fOfEmptySt + fOfReadSt + fOfWriteSt + fOfAssignSt + fOfProcSt + fOfIfSt + fOfDoSt ;
}
//First of emptyStatement
vector<Symbol> Firstfollow::firstOfEmptySt()
{
vector<Symbol> fOfEmptySt;
fOfEmptySt.push_back(SKIP);
return fOfEmptySt;
}
//First of readStatement
vector<Symbol> Firstfollow::firstOfReadSt()
{
vector<Symbol> fOfReadSt;
fOfReadSt.push_back(READ);
return fOfReadSt;
}
//First of writeStatement
vector<Symbol> Firstfollow::firstOfWriteSt()
{
vector<Symbol> fOfWriteSt;
fOfWriteSt.push_back(WRITE);
return fOfWriteSt;
}
//First of procedureStatement
vector<Symbol> Firstfollow::firstOfProcSt()
{
vector<Symbol> fOfProcSt;
fOfProcSt.push_back(CALL);
return fOfProcSt;
}
//First of assignmentStatement
vector<Symbol> Firstfollow::firstOfAssignSt()
{
vector<Symbol> inVAList = firstOfVAList();
return inVAList;
}
//First of variableAccessList
vector<Symbol> Firstfollow::firstOfIfSt()
{
vector<Symbol> fOfIfSt;
fOfIfSt.push_back(IF);
return fOfIfSt;
}
//First of doStatement
vector<Symbol> Firstfollow::firstOfDoSt()
{
vector<Symbol> fOfDoSt;
fOfDoSt.push_back(DO);
return fOfDoSt;
}
//First of variableAccessList
vector<Symbol> Firstfollow::firstOfVAList()
{
vector<Symbol> fOfVaList;
fOfVaList.push_back(ID);
return fOfVaList;
}
//First of indexSelector
vector<Symbol> Firstfollow::firstOfIndexSel()
{
vector<Symbol> fOfIndSel;
fOfIndSel.push_back(LEFTBRACKET);
return fOfIndSel;
}
//First of primaryOperator
vector<Symbol> Firstfollow::firstOfPrimOp()
{
vector<Symbol> fOfPrimOp;
fOfPrimOp.push_back(AND);
fOfPrimOp.push_back(OR);
return fOfPrimOp;
}
//First of term
vector<Symbol> Firstfollow::firstOfTerm()
{
vector<Symbol> inFactor = firstOfFactor();
return inFactor;
}
//First of factor
vector<Symbol> Firstfollow::firstOfFactor()
{
vector<Symbol> fOfName;
fOfName.push_back(ID);
vector<Symbol> fOfLeftp;
fOfLeftp.push_back(LEFTP);
vector<Symbol> fOfConst = firstOfConstant();
vector<Symbol> fOfTilt;
fOfTilt.push_back(NOT);
return fOfName + fOfConst + fOfLeftp + fOfTilt;
}
//First of constant
vector<Symbol> Firstfollow::firstOfConstant()
{
vector<Symbol> fOfConst;
fOfConst.push_back(ID);
fOfConst.push_back(NUMERAL);
fOfConst.push_back(TRUE);
fOfConst.push_back(FALSE);
return fOfConst;
}
//First of relationalOperator
vector<Symbol> Firstfollow::firstOfRelOp()
{
vector<Symbol> fOfRelOp;
fOfRelOp.push_back(LESST);
fOfRelOp.push_back(EQUAL);
fOfRelOp.push_back(GREATERT);
fOfRelOp.push_back(LTE);
fOfRelOp.push_back(GTE);
return fOfRelOp;
}
//First of multiplyingOperator
vector<Symbol> Firstfollow::firstOfMultOp()
{
vector<Symbol> fOfMultOp;
fOfMultOp.push_back(TIMES);
fOfMultOp.push_back(DIV);
fOfMultOp.push_back(MOD);
return fOfMultOp;
}
//First of addingOperator
vector<Symbol> Firstfollow::firstOfAddOp()
{
vector<Symbol> fOfAddOp;
fOfAddOp.push_back(PLUS);
fOfAddOp.push_back(MINUS);
return fOfAddOp;
}
//First if expressionList
vector<Symbol> Firstfollow::firstOfExpList()
{
vector<Symbol> fOfExpList;
fOfExpList.push_back(MINUS);
vector<Symbol> fOfTerm = firstOfTerm();
return fOfExpList + fOfTerm;
}
//First if guardedCommandList
vector<Symbol> Firstfollow::firstOfGCList()
{
vector<Symbol> fOfExpList;
fOfExpList.push_back(MINUS);
vector<Symbol> fOfTerm = firstOfTerm();
return fOfExpList + fOfTerm;
}
//follow//functions for checking wheather the look ahead token is in follow of any non terminal
//follow of definitionPart
vector<Symbol> Firstfollow::followOfDefPart()
{
vector<Symbol> fOfStatement = firstOfStatement();
vector<Symbol> fOfEnd;
fOfEnd.push_back(END);
return fOfEnd + fOfStatement ;
}
//follow of statementPart
vector<Symbol> Firstfollow::followOfStatePart()
{
vector<Symbol> folOfGc = followOfGuardedCommand();
vector<Symbol> fOfEnd;
fOfEnd.push_back(END);
return folOfGc + fOfEnd ;
}
//follow of guardedCommand
vector<Symbol> Firstfollow::followOfGuardedCommand()
{
vector<Symbol> folOfGc;
folOfGc.push_back(FI);
folOfGc.push_back(OD);
folOfGc.push_back(GC1);
return folOfGc;
}
//follow of variableAccessList
vector<Symbol> Firstfollow::followOfVaList()
{
vector<Symbol> folOfVaList;
folOfVaList.push_back(ASSIGN);
return folOfVaList;
}
//follow of expressoion
vector<Symbol> Firstfollow::followOfExpression()
{
vector<Symbol> folOfExpression;
folOfExpression.push_back(GC2);
folOfExpression.push_back(RIGHTP);
folOfExpression.push_back(RIGHTBRACKET);
return folOfExpression;
}
// union operation for 2 vectors. Each vector is set of symbols
//+ operator overloading for vector
vector<Symbol> operator+(vector<Symbol> set1, vector<Symbol> set2)
{
vector<Symbol> mergedSet;
mergedSet.reserve(set1.size() + set2.size());
mergedSet.insert(mergedSet.end(), set1.begin(), set1.end());
mergedSet.insert(mergedSet.end(), set2.begin(), set2.end());
return mergedSet;
}
//// minus operation for a vectors(which is set of symbols) and a symbol
//+ operator overloading for vector
vector<Symbol> operator-(vector<Symbol> set, Symbol sym)
{
for(int i = 0; i < set.size(); i++)
{
if (sym == set.at(i))
set.at(i) = NONAME;
}
return set;
}
|
Java
|
UTF-8
| 5,908 | 2.609375 | 3 |
[] |
no_license
|
package choi.security.keystroke.data;
import android.util.Log;
import java.util.ArrayList;
import choi.security.keystroke.util.Converter;
/**
* Created by Nate on 2017-10-17.
*/
public class FeatureManage {
private String username;
private long inputtime; //currentTimeMillis
private String day;
private String time;
private ArrayList<ArrayList<Double>> key;
private ArrayList<ArrayList<Double>> size;
private ArrayList<ArrayList<Double>> acc;
private ArrayList<Double> lacc;
private ArrayList<Double> gyr;
private ArrayList<Double> ugyr;
private ArrayList<ArrayList<Double>> all;
public FeatureManage(){
}
public FeatureManage(DataManage dm, setManage setting){ //추후 세팅값만 전달받아서 DB에서 sliding window 크기만큼 불러와서 dm에 저장하고 특징 추출하도록 변경 필요
username = dm.getUsername();
key = extractKeyFeature(dm.getkeyTime(), setting.getPinCount());
size = extractSizeFeature(dm.getkeySize(), setting.getPinCount());
acc = extractAccFeature(dm.getAcc(), setting.getPinCount());
all = addAllfeatures(key, size);
Log.e("FeatureManage", "allFeature size: " + all.size());
}
public void setUsername(String name){
username = name;
}
public void setKey(String input){
ArrayList<Double> temp = new ArrayList<Double>();
temp = Converter.convertStringtoArrayListDouble(input);
key.add(temp);
}
public void setSize(String input){
ArrayList<Double> temp = new ArrayList<Double>();
temp = Converter.convertStringtoArrayListDouble(input);
size.add(temp);
}
private ArrayList<ArrayList<Double>> addAllfeatures(ArrayList<ArrayList<Double>> key, ArrayList<ArrayList<Double>> size){
ArrayList<ArrayList<Double>> output = new ArrayList<ArrayList<Double>>();
//각 특징별로 모두 동일한 사이즈(윈도우 사이즈 크기)인지 확인하기 추가 필요
for (int i = 0; i < key.size(); i++){
ArrayList<Double> temp = new ArrayList<Double>();
for (int j = 0; j < key.get(i).size(); j++){
temp.add(key.get(i).get(j));
}
for (int j = 0; j < size.get(i).size(); j++){
temp.add(size.get(i).get(j));
}
output.add(temp);
}
return output;
}
public ArrayList<ArrayList<Double>> getAll(){
return all;
}
private ArrayList<ArrayList<Double>> extractKeyFeature(ArrayList<ArrayList<String>> keyTime, int pinCount){
ArrayList<ArrayList<Double>> output = new ArrayList<ArrayList<Double>>();
if (keyTime.size() == pinCount){
for (int i = 0; i < keyTime.size(); i++){
ArrayList<Double> temp = new ArrayList<Double>();
for (int j = 0; j < keyTime.get(i).size(); j+= 2){
temp.add(Double.valueOf(keyTime.get(i).get(j+1)) - Double.valueOf(keyTime.get(i).get(j))); // DU 특징
}
for (int j = 1; j < keyTime.get(i).size()-1; j+= 2){
temp.add(Double.valueOf(keyTime.get(i).get(j+1)) - Double.valueOf(keyTime.get(i).get(j))); // UD 특징
}
for (int j = 1; j < keyTime.get(i).size()-1; j+= 2){
temp.add(Double.valueOf(keyTime.get(i).get(j+2)) - Double.valueOf(keyTime.get(i).get(j))); // UU 특징 // 추가 부분
}
for (int j = 0; j < keyTime.get(i).size()-2; j+= 2){
temp.add(Double.valueOf(keyTime.get(i).get(j+2)) - Double.valueOf(keyTime.get(i).get(j))); // DD 특징 // 추가 부분
}
output.add(temp);
}
}
else{
Log.e("FeatureManage", "extractKeyFeature Error - size");
}
return output;
}
private ArrayList<ArrayList<Double>> extractAccFeature(ArrayList<ArrayList<ArrayList<String>>> acc, int pinCount){
ArrayList<ArrayList<Double>> output = new ArrayList<ArrayList<Double>>();
return output;
}
// size 특징 추출
private ArrayList<ArrayList<Double>> extractSizeFeature(ArrayList<ArrayList<String>> keySize, int pinCount){
ArrayList<ArrayList<Double>> output = new ArrayList<ArrayList<Double>>();
if (keySize.size() == pinCount){
for (int i = 0; i < keySize.size(); i++){
ArrayList<Double> temp = new ArrayList<Double>();
for (int j = 0; j < keySize.get(i).size(); j++)
temp.add(Double.valueOf(keySize.get(i).get(j))); // rawdata 그대로 사용
output.add(temp);
}
}
else{
Log.e("FeatureManage", "extractSizeFeature Error - size");
}
return output;
}
// xy 특징 추출
private ArrayList<ArrayList<Double>> extractXYFeature(ArrayList<ArrayList<String>> keyXY, int pinCount){
ArrayList<ArrayList<Double>> output = new ArrayList<ArrayList<Double>>();
if (keyXY.size() == pinCount){
for (int i = 0; i < keyXY.size(); i++){
ArrayList<Double> temp = new ArrayList<Double>();
for (int j = 0; j < keyXY.get(i).size(); j++)
temp.add(Double.valueOf(keyXY.get(i).get(j))); // rawdata 그대로 사용
output.add(temp);
}
}
else{
Log.e("FeatureManage", "extractSizeFeature Error - size");
}
return output;
}
public String getUsername(){
return username;
}
public ArrayList<ArrayList<Double>> getKeyTimeFeautre(){
return key;
}
public ArrayList<ArrayList<Double>> getSizeFeature(){
return size;
}
}
|
Java
|
UTF-8
| 4,512 | 3.5625 | 4 |
[] |
no_license
|
import org.junit.Test;
import org.mockito.InOrder;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class SomeObjectTest {
@Test
public void testMultipleTimes() {
List mockedList = mock(List.class);
mockedList.add("once");
mockedList.add("twice");
mockedList.add("twice");
mockedList.add("three times");
mockedList.add("three times");
mockedList.add("three times");
//following two verifications work exactly the same - times(1) is used by default
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");
//exact number of invocations verification
verify(mockedList, times(2)).add("twice");
verify(mockedList, times(3)).add("three times");
//verification using never(). never() is an alias to times(0)
verify(mockedList, never()).add("never happened");
//verification using atLeast()/atMost()
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("three times");
verify(mockedList, atMost(5)).add("three times");
}
@Test(expected = RuntimeException.class)
public void testThrowingExceptions() {
List mockedList = mock(List.class);
//throwing exceptions
doThrow(new RuntimeException()).when(mockedList).clear();
//following throws RuntimeException:
mockedList.clear();
}
@Test
public void testOrderOnOneMock() {
// A. Single mock whose methods must be invoked in a particular order
List singleMock = mock(List.class);
//using a single mock
singleMock.add("was added first");
singleMock.add("was added second");
//create an inOrder verifier for a single mock
InOrder inOrder = inOrder(singleMock);
//following will make sure that add is first called with "was added first, then with "was added second"
inOrder.verify(singleMock).add("was added first");
inOrder.verify(singleMock).add("was added second");
}
@Test
public void testOrderOnMultipleMocks() {
// B. Multiple mocks that must be used in a particular order
List firstMock = mock(List.class);
List secondMock = mock(List.class);
//using mocks
firstMock.add("was called first");
secondMock.add("was called second");
firstMock.add("was called 1.5");
//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(secondMock, firstMock);
//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).add("was called first");
inOrder.verify(firstMock).add("was called 1.5");
inOrder.verify(secondMock).add("was called second");
}
@Test
public void testMockReturnsMultipleReturnsInOrder() {
SomeObject mock = mock(SomeObject.class);
when(mock.someMethod("arg"))
.thenReturn("foo")
.thenReturn("bar");
assertEquals(mock.someMethod("arg"), "foo");
assertEquals(mock.someMethod("arg"), "bar");
}
@Test(expected = RuntimeException.class)
public void testExceptionsAndRegularReturns() {
SomeObject mock = mock(SomeObject.class);
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");
//First call: throws runtime exception:
mock.someMethod("some arg");
//Second call: prints "foo"
System.out.println(mock.someMethod("some arg"));
//Any consecutive call: prints "foo" as well (last stubbing wins).
System.out.println(mock.someMethod("some arg"));
}
@Test
public void testSpyingOnRealObjects() {
List list = new LinkedList();
List spy = spy(list);
//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);
//using the spy calls *real* methods
spy.add("one");
spy.add("two");
//prints "one" - the first element of a list
System.out.println(spy.get(0));
//size() method was stubbed - 100 is printed
System.out.println(spy.size());
//optionally, you can verify
verify(spy).add("one");
verify(spy).add("two");
}
}
|
TypeScript
|
UTF-8
| 1,994 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
import { Point } from './point';
/**
* Provides the utilities for getting element's metrics.
*/
export declare class ElementRect {
private element;
/**
* Returns the width of the current element.
*/
width: number;
/**
* Returns the height of the current element.
*/
height: number;
/**
* Returns the size (the biggest side) of the current element.
*/
size: number;
/**
* Initializes a new instance of the `ElementRect` class with the specified `element`.
*/
constructor(element: HTMLElement);
/**
* Returns the center coordinates of the current element.
*/
readonly center: Point;
/**
* Returns the size of the current element and its position relative to the viewport.
*/
readonly boundingRect: ClientRect;
/**
* Calculates euclidean distance between two points.
* @param point1 - Start point
* @param point2 - End point
* @returns Distance between two points.
*/
static euclideanDistance(point1: Point, point2: Point): number;
/**
* Calculates the distance between given point and farthest corner of the current element.
* @param The point object containing x and y coordinates.
* @returns Distance from a point to the container's farthest corner.
*/
distanceToFarthestCorner({x, y}: Point): number;
/**
* Determines if the specified point is contained within this element.
* @param {(Event|Object)} ev - The object containing coordinates of the point.
* @param {Number} ev.x - The `x` coordinate of the point.
* @param {Number} ev.y - The `y` coordinate of the point.
* @param {Number} ev.clientX - The `x` coordinate of the point.
* @param {Number} ev.clientY - The `y` coordinate of the point.
* @returns {Boolean} Returns `true` if the `x` and `y` coordinates of point is a point inside this element's rectangle, otherwise `false`.
*/
contains(ev: any): boolean;
}
|
Java
|
UTF-8
| 609 | 1.859375 | 2 |
[] |
no_license
|
package com.chinaredstar.jc.crawler.biz.service.impl;
import com.chinaredstar.jc.crawler.biz.result.UserResult;
import com.chinaredstar.jc.crawler.biz.service.IUserService;
import com.chinaredstar.jc.crawler.dao.mapper.UserMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by lenovo on 2017/10/30.
*/
@Service
public class UserServiceImpl implements IUserService {
@Resource
private UserMapper userMapper;
@Override
public List<UserResult> selectAllUser() {
return userMapper.selectAllUser();
}
}
|
JavaScript
|
UTF-8
| 3,127 | 2.734375 | 3 |
[] |
no_license
|
const toggleWidgets = {
title: "Widgets",
html: ` <div id=widgetListContainer>
</div>
<div id=footerContainer>
<button class=widgetSettingsBtn id=applyWidgetToggleBtn>Show Changes</button>
</div>`,
css: true,
openScript: function () {
// Send Ajax request to server for widget names
$.ajax({
url: "/app/widgetnames",
success: function (widgetNames) {
// Get current toggle state of all widgets
$.ajax({
url: "/widgets/toggle",
success: function(settingsObj) {
// Parse data
widgetNames = widgetNames.split(",");
// Loop through widgets
for (let i = 0; i < widgetNames.length; i++) {
// Determine widget toggle state
var widgetStatus = settingsObj[widgetNames[i]] != undefined ? settingsObj[widgetNames[i]] : true;
var checkedStr = widgetStatus ? "checked" : "";
// Format widget name for presentation
let widgetName = widgetNames[i][0].toUpperCase() + widgetNames[i].slice(1);
// Create slider
document.getElementById("widgetListContainer").innerHTML += `<div class="widgetOptionContainer">
<label class="switch">
<input type="checkbox" id="` + widgetNames[i] + `Checkbox"` + checkedStr + `>
<span class="slider round"></span>
</label>
<p class="widgetTitle">` + widgetName + `</p>
</div>`;
}
},
error: function(err) {
console.error("Could not get widget settings object");
console.error(err);
}
});
},
error: function (err) {
console.error(err);
}
});
document.getElementById("applyWidgetToggleBtn").addEventListener("click", function() {
location.reload();
});
},
prepareScript: function () {
// Click event when clicking checkbox
document.addEventListener("click", function(e) {
const idCheck = new RegExp("(.+)(Checkbox)");
const matchOut = e.target.id.match(idCheck);
if (matchOut !== null) {
// When click on slider, toggle widget
$.ajax({
type: "POST",
url: "/widgets/toggle",
data: matchOut[1],
error: function () {
console.error("Could not toggle widget");
}
});
}
});
}
};
var event = new CustomEvent('settingReady', {detail: "toggleWidgets"});
window.dispatchEvent(event);
|
Markdown
|
UTF-8
| 357 | 2.765625 | 3 |
[] |
no_license
|
# Capital One Summit Challenge
An application that gets information from Instagram's API about a certain tag and displays info about the number of posts, the users who used the tag, and whether or not the post was positive or negative.
Built to accomplish Capital One's challenge, not meant to be something that is extremely useful or even valuable at all
|
Shell
|
UTF-8
| 1,730 | 2.953125 | 3 |
[] |
no_license
|
export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ "
export CLICOLOR=1
export LSCOLORS=ExFxBxDxCxegedabagacad
alias ls='ls -GFhl'
_complete_hosts () {
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
host_list=`{
for c in /etc/ssh_config /etc/ssh/ssh_config ~/.ssh/config
do [ -r $c ] && sed -n -e 's/^Host[[:space:]]//p' -e 's/^[[:space:]]*HostName[[:space:]]//p' $c
done
for k in /etc/ssh_known_hosts /etc/ssh/ssh_known_hosts ~/.ssh/known_hosts
do [ -r $k ] && egrep -v '^[#\[]' $k|cut -f 1 -d ' '|sed -e 's/[,:].*//g'
done
sed -n -e 's/^[0-9][0-9\.]*//p' /etc/hosts; }|tr ' ' '\n'|grep -v '*'`
COMPREPLY=( $(compgen -W "${host_list}" -- $cur))
return 0
}
complete -F _complete_hosts ssh
# Git auto complet
if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi
|
Swift
|
UTF-8
| 695 | 3.59375 | 4 |
[] |
no_license
|
import Foundation
enum Transaction:Error {
case inactiveUseAccount
case WithdrawalError
}
class Bank {
var initial = 500
var my_bal = 1000
var active:Bool = false
func CheckData(withdrawal:Int)throws {
if !active {
throw Transaction.inactiveUseAccount
}
if my_bal <= initial || withdrawal >= my_bal {
throw Transaction.WithdrawalError
}
else {
print("Active account")
print("Withrawal amount is \(withdrawal)")
print("Total balance is \(my_bal-withdrawal)")
}
}
}
var b1 = Bank()
do{
try b1.CheckData(withdrawal: 300)
}
catch let m {
print(m)
}
|
SQL
|
UTF-8
| 1,717 | 2.875 | 3 |
[] |
no_license
|
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
ALTER TABLE IF EXISTS ONLY public.py_trade_tourism_and_investment_programme_absorption_perc DROP CONSTRAINT IF EXISTS pk_py_trade_tourism_and_investment_programme_absorption_perc;
DROP TABLE IF EXISTS public.py_trade_tourism_and_investment_programme_absorption_perc;
SET default_tablespace = '';
SET default_with_oids = false;
CREATE TABLE IF NOT EXISTS public.py_trade_tourism_and_investment_programme_absorption_perc (
geo_level TEXT,
geo_code TEXT,
geo_version NUMERIC,
parent_level TEXT,
parent_code TEXT,
variable_2 TEXT,
variable_1 TEXT,
value NUMERIC,
name TEXT
);
ALTER TABLE ONLY public.py_trade_tourism_and_investment_programme_absorption_perc ADD CONSTRAINT pk_py_trade_tourism_and_investment_programme_absorption_perc PRIMARY KEY (geo_level, geo_code, geo_version, parent_level, parent_code, variable_2, variable_1, value, name);
INSERT INTO public.py_trade_tourism_and_investment_programme_absorption_perc VALUES
('level1','KE_1_001',2009,'country','KE','Absorption','Administration Unit',34.7,'Mombasa'),
('level1','KE_1_001',2009,'country','KE','Absorption','Trade Development',2.5,'Mombasa'),
('level1','KE_1_001',2009,'country','KE','Absorption','Development of Tourism',0,'Mombasa'),
('level1','KE_1_001',2009,'country','KE','Absorption','Investment Promotion and Products Headquarters',0,'Mombasa'),
('level1','KE_1_001',2009,'country','KE','Absorption','Ease of Doing Business-Headquarters',0,'Mombasa') ON CONFLICT DO NOTHING;
|
Python
|
UTF-8
| 1,068 | 2.609375 | 3 |
[] |
no_license
|
"""Business level operations on customers."""
from bizwiz.common.session_filter import get_session_filter
from bizwiz.customers.models import Customer
def get_session_filtered_customers(session):
"""Return customers optionally filtered by currently active session."""
session_filter = get_session_filter(session)
filtered_project = session_filter.project
filtered_customer_group = session_filter.customer_group
if filtered_customer_group:
queryset = Customer.objects.filter(customergroup=filtered_customer_group)
elif filtered_project:
queryset = Customer.objects.filter(customergroup__project=filtered_project)
else:
queryset = Customer.objects.all()
return queryset
def apply_session_filter(session, customer):
"""If session filter is set, add customer to curently active customer group."""
session_filter = get_session_filter(session)
customer_group = session_filter.customer_group
if customer_group:
customer_group.customers.add(customer)
return True
return False
|
C#
|
UTF-8
| 1,563 | 3.015625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cslab3gui
{
public partial class Form1 : Form
{
Matrix matrixA = new Matrix();
Matrix matrixB = new Matrix();
Matrix matrixD = new Matrix();
public Form1()
{
InitializeComponent();
}
private void Save_Click(object sender, EventArgs e)
{
try
{
matrixA.SetElement(Int32.Parse(textBox1.Text));
matrixB.SetElement(Int32.Parse(textBox2.Text));
NumElement.Text = $"Number of Element A( {matrixA.CurrentRow+1}, {matrixA.CurrentColumn+1})" +
$" Number of Element B({ matrixB.CurrentRow + 1}, { matrixB.CurrentColumn + 1})";
}
catch(Exception exc) { MessageBox.Show(exc.Message); }
}
private void display_TextChanged(object sender, EventArgs e)
{
}
private void Show_Click(object sender, EventArgs e)
{
matrixD = 3 * matrixB * matrixA + (matrixB - matrixA);
display.Text = "A:\n"+matrixA.ToString()+"\nB:\n"+matrixB.ToString()+"\nD:\n"+matrixD.ToString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
|
Python
|
UTF-8
| 1,222 | 3.53125 | 4 |
[] |
no_license
|
import numpy as np
import xarray as xr
import pandas as pd
from matplotlib import pyplot as plt
def to_farenheit(val):
'''
Convert value in degrees Kelvin to Farenheit
'''
return((val - 273.15)*(9/5)+32)
def get_cdd_hdd(dataset):
'''
Calculate HDD and CDD given temperature
Parameters:
-----------
dataset: xr.DataArray
temperature dataset T(lat, lon, time)
Return:
-------
temp_far: xr.DataArray
dataset with new entries for HDD and CDD
'''
# Convert temperatures to farenheit
temp_far = dataset.apply(to_farenheit)
# Calculate CDD
temp_far['cdd'] = 65 - temp_far['t2m']
temp_far['cdd'] = temp_far['cdd'].where(temp_far['cdd']>0, 0)
temp_far['cdd'] = temp_far['cdd'].sum(dim = 'time')
# Calculate HDD
temp_far['hdd'] = temp_far['t2m'] - 65
temp_far['hdd'] = temp_far['hdd'].where(temp_far['hdd']>0, 0)
temp_far['hdd'] = temp_far['hdd'].sum(dim = 'time')
return(temp_far)
if __name__ == "__main__":
# Open temperature data
data_2018 = xr.open_dataset('T2_2018_MEAN.nc')
data_2018 = get_cdd_hdd(data_2018)
# write out HDD/CDD data to a netCDF
data_2018.to_netcdf('hdd_cdd_data.nc')
|
Java
|
UTF-8
| 5,428 | 2.1875 | 2 |
[] |
no_license
|
package example.com.mydbmv;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* <pre>
* author :YangXiaoMeng
* e-mail :xmyang3@gc.omron.com
* time :2018/09/07
* desc :DouBanMovie
* version:1.0
* </pre>
*/
public class MainActivity extends AppCompatActivity {
ArrayList<MovieInfo> movieList = new ArrayList<>();
RecyclerView recyclerView;
MovieAdapter mMovieAdapter;
List<InTheater.SubjectsBean> myMovieList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rv_main_movies);
MovieRepo movieRepo = new MovieRepo(getApplicationContext());
movieList = movieRepo.getSaveInfoList();
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
if (isNetworkOk()) {
Toast.makeText(this, "net is ok", Toast.LENGTH_SHORT).show();
requestNetwork();
mMovieAdapter = new MovieAdapter(this, movieList);
recyclerView.setAdapter(mMovieAdapter);
mMovieAdapter.setOnItemClickListener(new MovieAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
}
});
} else if ((movieList.size() != 0)) {
mMovieAdapter = new MovieAdapter(this, movieList);
recyclerView.setAdapter(mMovieAdapter);
mMovieAdapter.setOnItemClickListener(new MovieAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
}
});
Toast.makeText(this, "get data without network", Toast.LENGTH_SHORT).show();
} else {
mMovieAdapter = new MovieAdapter(this, movieList);
recyclerView.setAdapter(mMovieAdapter);
Toast.makeText(this, "can not get data", Toast.LENGTH_SHORT).show();
}
}
public boolean isNetworkOk() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
public void requestNetwork() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.douban.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<InTheater> inTheaterCall = service.getInTheaters(0, 34);
inTheaterCall.enqueue(new Callback<InTheater>() {
@Override
public void onResponse(@NonNull Call<InTheater> call, @NonNull Response<InTheater> response) {
InTheater inTheater = response.body();
assert inTheater != null;
myMovieList = inTheater.getSubjects();
MovieRepo movieRepo = new MovieRepo(getApplicationContext());
MovieInfo movieInfo = new MovieInfo();
if (movieList == null || movieList.size() == 0) {
for (int i = 0; i < 34; i++) {
movieInfo.setId(myMovieList.get(i).getId());
movieInfo.setYear(myMovieList.get(i).getYear());
movieInfo.setRating(String.valueOf(myMovieList.get(i).getRating().getAverage()));
movieInfo.setTitle(myMovieList.get(i).getTitle());
movieInfo.setVideo_url(myMovieList.get(i).getAlt());
movieInfo.setImage_url(myMovieList.get(i).getImages().getSmall());
movieRepo.insertData(movieInfo);
}
} else {
for (int j = 0; j < 34; j++) {
movieInfo.setYear(myMovieList.get(j).getYear());
movieInfo.setTitle(myMovieList.get(j).getTitle());
movieInfo.setRating(String.valueOf(myMovieList.get(j).getRating().getAverage()));
movieInfo.setImage_url(myMovieList.get(j).getImages().getSmall());
movieInfo.setVideo_url(myMovieList.get(j).getAlt());
movieInfo.setId(myMovieList.get(j).getId());
movieRepo.update(movieInfo, myMovieList.get(j).getId());
}
}
movieList = movieRepo.getSaveInfoList();
mMovieAdapter.update(movieList);
}
@Override
public void onFailure(@NonNull Call<InTheater> call, @NonNull Throwable t) {
}
});
}
}
|
Java
|
UTF-8
| 5,806 | 1.828125 | 2 |
[] |
no_license
|
package com.gabriellcosta.mymapsapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import com.gabriellcosta.mymapsapp.FavoriteDialog.DialogItemClick;
import com.gabriellcosta.mymapsapp.data.FavoriteDAO;
import com.gabriellcosta.mymapsapp.data.FavoriteDAOImpl;
import com.gabriellcosta.mymapsapp.data.FavoritePlaceVO;
import com.gabriellcosta.mymapsapp.data.FavoritePlacesDBHelper;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
import com.google.android.gms.location.places.ui.PlaceAutocomplete.IntentBuilder;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, DialogItemClick {
private static final String TAG = "MainActivity";
private static final String POSITION_KEY = "POSITION_KEY";
private static final int RC_PLACES_AUTOCOMPLETE = 231;
private MarkerOptions marker;
private LatLng position;
private GoogleMapsManager googleMapsManagerImpl;
private FavoriteDAO dao;
private View imageButton;
private PreferenceManager preferenceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_main_map);
mapFragment.getMapAsync(this);
imageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
googleMapsManagerImpl.moveToMarker();
}
});
preferenceManager = new PreferenceManager(this);
dao = new FavoriteDAOImpl(new FavoritePlacesDBHelper(this));
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(POSITION_KEY, googleMapsManagerImpl.getMarker().getPosition());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(POSITION_KEY)) {
position = savedInstanceState.getParcelable(POSITION_KEY);
}
}
@Override
protected void onDestroy() {
dao.close();
super.onDestroy();
}
@Override
public void onMapReady(final GoogleMap googleMap) {
Log.v(TAG, "Map Ready to be used");
initMark();
googleMapsManagerImpl = new GoogleMapsManagerImpl(googleMap, marker);
googleMapsManagerImpl.update();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final boolean result;
final int itemId = item.getItemId();
if (itemId == R.id.menu_search) {
startPlaceAutoComplete();
result = true;
} else if (itemId == R.id.menu_add_favorite) {
LatLng position = googleMapsManagerImpl.getMarker().getPosition();
FavoritePlaceVO favoritePlaceVO = new FavoritePlaceVO(0, getTitle().toString(),
position.latitude, position.longitude);
dao.insert(favoritePlaceVO);
result = true;
} else if (itemId == R.id.menu_fav){
List<FavoritePlaceVO> fetch = dao.fetch();
new FavoriteDialog().showDialog(this, fetch, this);
result = false;
} else {
result = false;
}
return result;
}
private void startPlaceAutoComplete() {
try {
final Intent intentBuilder = new IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(this);
startActivityForResult(intentBuilder, RC_PLACES_AUTOCOMPLETE);
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {
Log.e(TAG, e.getMessage(), e);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == RC_PLACES_AUTOCOMPLETE) {
final Place place = PlaceAutocomplete.getPlace(this, data);
Log.i(TAG, "Place: " + place.getName());
googleMapsManagerImpl.update(place.getLatLng());
setTitle(place.getName());
}
}
@Override
protected void onPause() {
super.onPause();
preferenceManager.saveLocation(googleMapsManagerImpl.getMarker().getPosition());
}
private void initMark() {
final double lat, lng;
if (position != null) {
lat = position.latitude;
lng = position.longitude;
} else {
LatLng location = preferenceManager.getLocation();
lat = location.latitude;
lng = location.longitude;
}
marker = MarkerFactory.createSimpleMarker(lat, lng);
}
private void initViews() {
imageButton = findViewById(R.id.imb_main_map);
}
@Override
public void dialogItemChoosed(FavoritePlaceVO item) {
googleMapsManagerImpl.update(new LatLng(item.getLatitute(), item.getLongitude()));
}
@Override
public void deletedItemChoosed(FavoritePlaceVO item) {
dao.delete(item.getId());
}
}
|
Python
|
UTF-8
| 429 | 3.609375 | 4 |
[] |
no_license
|
kapsel = []
print('Tänk att du ska gräva ned en tidskapsel som ska hittas om 500 år! Vad skulle du fylla den med?')
while len(kapsel) < 5:
print('Vad vill du lägga till i kapseln?')
nySak = input('> ')
kapsel.append(nySak)
print()
print('----- 500 år senare ------')
print('I ett bygge av ett 700-våningshus hittar man en kapsel...')
print('I kapseln finns:')
for sak in kapsel:
print('- %s' % (sak))
|
Java
|
UTF-8
| 472 | 1.828125 | 2 |
[] |
no_license
|
private Result setLength(long lobID, long length) {
ResultMetaData meta = updateLobLength.getParametersMetaData();
Object[] params = new Object[meta.getColumnCount()];
params[UPDATE_LENGTH.LOB_LENGTH] = ValuePool.getLong(length);
params[UPDATE_LENGTH.LOB_ID] = ValuePool.getLong(lobID);
Result result = sysLobSession.executeCompiledStatement(updateLobLength,
params, 0);
return result;
}
|
Python
|
UTF-8
| 253 | 2.859375 | 3 |
[] |
no_license
|
c=()
d=()
a0=int(input())
a1=int(input())
b0=int(input())
b1=int(input())
h=sqrt((a0-b0)^2 + (a1-b1)^2)
c0=b0
c1=b1-(((h*h)-(b0-c0)*(b0-c0))**0.5)
c1=int(c1)
d0=a0
d1=c1
c=(c0,c1)
d=(d0,d1)
H=format(h,'.2f')
print(c)
print(d)
print(H)
|
Python
|
UTF-8
| 2,883 | 3.078125 | 3 |
[] |
no_license
|
import pygame, sys
from all_levels.Minesweeper.constant import X_DIMENSION, Y_DIMENSION, TOPBAR_RATIO, CLOCK_BORDER, CLOCK_SPACING, WHITE, BLACK
def initScreenAndGameClock():
# initialize pygame
pygame.init()
# initialize the fonts
try:
pygame.font.init()
except:
sys.exit()
# create a game clock
gameClock = pygame.time.Clock()
# create a screen
screen = pygame.display.set_mode((X_DIMENSION, Y_DIMENSION))
return [screen, gameClock]
def timeToString(timeInSeconds):
if timeInSeconds < 0:
timeInSeconds = 0
timeInSeconds = int(timeInSeconds)
seconds = timeInSeconds % 60
if seconds < 10:
seconds = "0" + str(seconds)
else:
seconds = str(seconds)
minutes = str(timeInSeconds // 60)
return minutes + ":" + seconds
def drawClock(screen, timeInSeconds):
width = (X_DIMENSION // CLOCK_SPACING) - (CLOCK_BORDER * 2)
height = (Y_DIMENSION // TOPBAR_RATIO) - (CLOCK_BORDER * 2)
x = X_DIMENSION - width - CLOCK_BORDER
y = 0 + CLOCK_BORDER
# background
pygame.draw.rect(screen, (255,255,255), pygame.Rect((x , y), (width, height)))
# numbers
afont = pygame.font.SysFont("Helvetica", 60, bold=False)
textObject = afont.render(timeToString(timeInSeconds), True, BLACK)
screen.blit(textObject, (x + 50, 2 * y - 10))
def drawKeysLeft(screen, numKeysLeft):
width = (X_DIMENSION // CLOCK_SPACING) - (CLOCK_BORDER * 2)
height = (Y_DIMENSION // TOPBAR_RATIO) - (CLOCK_BORDER * 2)
x = CLOCK_BORDER + width
y = 0 + CLOCK_BORDER
afont = pygame.font.SysFont("Helvetica", 30, bold=False)
textObject = afont.render("Keys to collect: " + str(numKeysLeft), True, (0,0,0))
screen.blit(textObject, (x + 25, 2 * y + 10))
def drawBackButton(screen):
width = (X_DIMENSION // CLOCK_SPACING) - (CLOCK_BORDER * 2)
height = (Y_DIMENSION // TOPBAR_RATIO) - (CLOCK_BORDER * 2)
x = CLOCK_BORDER
y = 0 + CLOCK_BORDER
# background
pygame.draw.rect(screen, (125, 0, 255), pygame.Rect((x , y), (width, height)))
# font for back
afont = pygame.font.SysFont("Helvetica", 60, bold=False)
textObject = afont.render("back", True, (255,255,255))
screen.blit(textObject, (x + 25, 2 * y - 10))
def drawTopBar(screen, timeInSeconds, includeClock=True, includeBackButton=True, includeKeysLeft=False, keys=5):
pygame.draw.rect(screen, (0, 204, 204), pygame.Rect(
(0, 0), (X_DIMENSION, Y_DIMENSION / TOPBAR_RATIO)))
if includeBackButton:
drawBackButton(screen)
if includeClock:
drawClock(screen, timeInSeconds)
if includeKeysLeft:
drawKeysLeft(screen, keys)
# size of the rest of the screen below the topbar
return [X_DIMENSION, Y_DIMENSION - (Y_DIMENSION / TOPBAR_RATIO)]
def hashRect(rect):
return hash(str(rect.x) + "|" + str(rect.y))
|
TypeScript
|
UTF-8
| 1,242 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
namespace Question {
export interface Input {
readonly id: string;
readonly type: 'images' | 'text' | 'checkbox';
readonly options: Options;
}
export interface ImagesOptions {
readonly required: boolean;
readonly hint?: string;
readonly images: Array<{
readonly id: string;
readonly url: string;
/// Will also be used for aria-label
readonly title: string;
readonly alt: string;
}>;
}
export interface CheckboxOptions {
readonly required: boolean;
readonly label: string;
readonly defaultValue: boolean;
readonly hint?: string;
readonly checkedHint?: string;
readonly uncheckedHint?: string;
}
export interface TextOptions {
readonly kind: 'text' | 'textfield' | 'email';
readonly label?: string;
readonly placeholder?: string;
readonly hint?: string;
readonly minimumCharacters?: number;
readonly maximumCharacters?: number;
readonly autoCapitalize?: 'characters' | 'words' | 'sentences';
}
export type Options = ImagesOptions | TextOptions | CheckboxOptions;
}
interface Question {
readonly title?: string;
readonly inputs: Array<Question.Input[] | Question.Input>;
}
export default Question;
|
Java
|
UTF-8
| 1,607 | 3.96875 | 4 |
[] |
no_license
|
public class Triangle{
//Instance variables
private Point v1;
private Point v2;
private Point v3;
//Constructor to make a triangle given points
public Triangle(Point A, Point B, Point C){
v1 = new Point(A.getX(), A.getY());
v2 = new Point(B.getX(), B.getY());
v3 = new Point(C.getX(), C.getY());
}
//Constructor to make a triangle given doubles
public Triangle(double x1, double y1, double x2, double y2, double x3, double y3){
v1 = new Point(x1, y1);
v2 = new Point(x2, y2);
v3 = new Point(x3, y3);
}
//Getting the perimeter of the Triangle
public double getPerimeter(){
return v1.distanceTo(v2) + v1.distanceTo(v3) + v2.distanceTo(v3);
}
//Getting vertex
public Point getVertex(int index){
if (index < 0 || index > 2){
System.out.println("Please enter a number between 0 to 2 inclusive.");
return null;
}
if (index == 0){
return new Point(this.v1.getX(), this.v1.getY());
}
if (index == 1){
return new Point(this.v2.getX(), this.v2.getY());
}
return new Point(this.v3.getX(), this.v3.getY());
}
public void setVertex(int idx, Point p){
if (idx < 0 || idx > 2){
System.out.println("Please enter a number between 0 to 2 inclusive.");
}
if (idx == 0){
this.v1 = new Point(p.getX(), p.getY());
}if (idx == 1){
this.v2 = new Point(p.getX(), p.getY());
}
if (idx == 2){
this.v3 = new Point(p.getX(), p.getY());
}
}
//toString triangle
public String toString(){
return "Triangle: A" + this.v1 + ", B" + this.v2 + ", C" + this.v3;
}
}
|
Java
|
UTF-8
| 2,396 | 2.8125 | 3 |
[] |
no_license
|
package MCADatabase;
//Imports use for various methods in the program
import java.sql.*;
import java.util.logging.*;
import javax.swing.table.DefaultTableModel;
import java.text.*;
import java.util.Locale;
import javax.swing.event.*;
public class sqlDriver {
//This method is called multiple times throughout the program. It ensures that the database and the table exists.
//If they do not exist then this code creates them with no rows
public static Connection connectDatabase() throws SQLException {
Connection con;
Statement st = null;
String url = "jdbc:mysql://localhost:3306";
String user = "root";
String password = "";
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
st.executeUpdate("CREATE DATABASE IF NOT EXISTS CricketDatabase");
st.executeUpdate("CREATE TABLE IF NOT EXISTS CricketDatabase.pupils("
+ "ID int(11) NOT NULL AUTO_INCREMENT,"
+ "Name text,"
+ "Age int(11) DEFAULT NULL,"
+ "DOB date DEFAULT NULL,"
+ "Gender text,"
+ "Email text,"
+ "Phone text,"
+ "Emergency text,"
+ "Hand text,"
+ "SessDate date DEFAULT NULL,"
+ "SessTime text DEFAULT NULL,"
+ "SessInfo text,"
+ "Exp text,"
+ "Medical text,"
+ "Pay text,"
+ "PaySess int(11) DEFAULT NULL,"
+ "PRIMARY KEY (ID)"
+ ")");
st.executeUpdate("CREATE TABLE IF NOT EXISTS CricketDatabase.login("
+ " Username text,"
+ " Passcode text"
+ ")");
st.executeUpdate("CREATE TABLE IF NOT EXISTS CricketDatabase.forms("
+ " Name text,"
+ " Form text"
+ ")");
st.executeUpdate("CREATE TABLE IF NOT EXISTS CricketDatabase.forgot("
+ " State text,"
+ " Question text,"
+ " Answer text"
+ ")");
st.executeUpdate("CREATE TABLE IF NOT EXISTS CricketDatabase.documents("
+ " Name text,"
+ " FileName text,"
+ " FilePath text"
+ ")");
return con;
}
}
|
Python
|
UTF-8
| 13,405 | 2.609375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
================================================
main_process_lma_data
================================================
This program reads LMA raw data and plots several features such as sources
position, histograms, etc.
"""
# Author: fvj
# License: BSD 3 clause
import datetime
import argparse
import atexit
import numpy as np
from pyrad.io import read_lightning, write_histogram
from pyrad.graph import plot_histogram, plot_pos, _plot_time_range
print(__doc__)
def main():
"""
"""
# parse the arguments
parser = argparse.ArgumentParser(
description='Entry to Pyrad processing framework')
# positional arguments
parser.add_argument(
'days', nargs='+', type=str,
help='Dates to process. Format YYYYMMDD')
# keyword arguments
parser.add_argument(
'--basepath', type=str,
default='/store/msrad/lightning/LMA/Santis/',
help='name of folder containing the LMA lightning data')
parser.add_argument(
'--nsources_min', type=int, default=10,
help='Minimum number of sources to consider the LMA flash valid')
args = parser.parse_args()
print("====== LMA data processing started: %s" %
datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
atexit.register(_print_end_msg,
"====== LMA data processing finished: ")
day_vec = []
for day in args.days:
day_vec.append(datetime.datetime.strptime(day, '%Y%m%d'))
flashnr = np.asarray([], dtype=int)
# time_data = np.asarray([], dtype=datetime.datetime)
# time_in_flash = np.asarray([], dtype=float)
lat = np.asarray([], dtype=float)
lon = np.asarray([], dtype=float)
alt = np.asarray([], dtype=float)
dBm = np.asarray([], dtype=float)
# define histogram bin edges
bin_edges_alt = np.arange(-50., 14150., 100.)
bin_edges_dBm = np.arange(-17., 47., 1.)
flash_cnt = 0
for day in day_vec:
day_str = day.strftime('%y%m%d')
fname = args.basepath+day_str+'.txt'
print('Reading LMA data file '+fname)
(flashnr_aux, _, _, lat_aux, lon_aux,
alt_aux, dBm_aux) = read_lightning(fname)
# Filter data with less than nsources_min sources
unique_flashnr = np.unique(flashnr_aux, return_index=False)
ind = []
for flash in unique_flashnr:
ind_flash = np.where(flashnr_aux == flash)[0]
if ind_flash.size < args.nsources_min:
continue
ind.extend(ind_flash)
flashnr_aux = flashnr_aux[ind]
lat_aux = lat_aux[ind]
lon_aux = lon_aux[ind]
alt_aux = alt_aux[ind]
dBm_aux = dBm_aux[ind]
# get first flash
_, unique_ind = np.unique(flashnr_aux, return_index=True)
lat_first = lat_aux[unique_ind]
lon_first = lon_aux[unique_ind]
alt_first = alt_aux[unique_ind]
dBm_first = dBm_aux[unique_ind]
print('N sources: '+str(flashnr_aux.size))
print('Min alt: '+str(alt_aux.min()))
print('Max alt: '+str(alt_aux.max()))
print('Min power: '+str(dBm_aux.min()))
print('Max power: '+str(dBm_aux.max()))
print('N flashes: '+str(alt_first.size))
# put data in global list
flashnr = np.append(flashnr, flashnr_aux+flash_cnt)
flash_cnt += flashnr_aux.max()
# time_data = np.append(time_data, time_data_aux)
# time_in_flash = np.append(time_in_flash, time_in_flash_aux)
lat = np.append(lat, lat_aux)
lon = np.append(lon, lon_aux)
alt = np.append(alt, alt_aux)
dBm = np.append(dBm, dBm_aux)
# Plot histogram altitude all sources
fname_hist = args.basepath+day_str+'_hist_alt.png'
fname_hist = plot_histogram(
bin_edges_alt, alt_aux, [fname_hist], labelx='Altitude [m MSL]',
titl=day_str+' Flash sources altitude')
print('Plotted '+' '.join(fname_hist))
# Plot histogram altitude first sources
fname_hist = args.basepath+day_str+'_hist_alt_first_source.png'
fname_hist = plot_histogram(
bin_edges_alt, alt_first, [fname_hist], labelx='Altitude [m MSL]',
titl=day_str+' Flash first source altitude')
print('Plotted '+' '.join(fname_hist))
# Plot histogram power all sources
fname_hist = args.basepath+day_str+'_hist_dBm.png'
fname_hist = plot_histogram(
bin_edges_dBm, dBm_aux, [fname_hist], labelx='Power [dBm]',
titl=day_str+' Flash sources power')
print('Plotted '+' '.join(fname_hist))
# Plot histogram power first sources
fname_hist = args.basepath+day_str+'_hist_dBm_first_source.png'
fname_hist = plot_histogram(
bin_edges_dBm, dBm_first, [fname_hist], labelx='Power [dBm]',
titl=day_str+' Flash first source power')
print('Plotted '+' '.join(fname_hist))
# plot position all sources
figfname = args.basepath+day_str+'_sources_pos_max_height_on_top.png'
figfname = plot_pos(
lat_aux, lon_aux, alt_aux, [figfname],
sort_altitude='Highest_on_top', cb_label='Source height [m MSL]',
titl=day_str+' flash sources position. Highest on top')
print('Plotted '+' '.join(figfname))
figfname = args.basepath+day_str+'_sources_pos_min_height_on_top.png'
figfname = plot_pos(
lat_aux, lon_aux, alt_aux, [figfname],
sort_altitude='Lowest_on_top', cb_label='Source height [m MSL]',
titl=day_str+' flash sources position. Lowest on top')
print('Plotted '+' '.join(figfname))
# plot position first source
figfname = (
args.basepath+day_str+'_first_source_pos_max_height_on_top.png')
figfname = plot_pos(
lat_first, lon_first, alt_first, [figfname],
sort_altitude='Highest_on_top', cb_label='Source height [m MSL]',
titl=day_str+' first flash source position. Highest on top')
print('Plotted '+' '.join(figfname))
figfname = (
args.basepath+day_str+'_first_source_pos_min_height_on_top.png')
figfname = plot_pos(
lat_first, lon_first, alt_first, [figfname],
sort_altitude='Lowest_on_top', cb_label='Source height [m MSL]',
titl=day_str+' first flash source position. Lowest on top')
print('Plotted '+' '.join(figfname))
# Plot 2D histogram all sources
H, _, _ = np.histogram2d(
alt_aux, dBm_aux, bins=[bin_edges_alt, bin_edges_dBm])
# set 0 values to blank
H = np.ma.asarray(H)
H[H == 0] = np.ma.masked
fname_hist = args.basepath+day_str+'_Santis_2Dhist_alt_dBm.png'
fname_hist = _plot_time_range(
bin_edges_alt, bin_edges_dBm, H, None, [fname_hist],
titl='LMA sources Altitude-Power histogram',
xlabel='Altitude [m MSL]', ylabel='Power [dBm]',
clabel='Occurrence',
vmin=0, vmax=None, figsize=[10, 8], dpi=72)
print('Plotted '+' '.join(fname_hist))
# Plot 2D histogram first sources
H, _, _ = np.histogram2d(
alt_first, dBm_first, bins=[bin_edges_alt, bin_edges_dBm])
# set 0 values to blank
H = np.ma.asarray(H)
H[H == 0] = np.ma.masked
fname_hist = (
args.basepath+day_str+'_Santis_2Dhist_alt_dBm_first_source.png')
fname_hist = _plot_time_range(
bin_edges_alt, bin_edges_dBm, H, None, [fname_hist],
titl='LMA first sources Altitude-Power histogram',
xlabel='Altitude [m MSL]', ylabel='Power [dBm]',
clabel='Occurrence',
vmin=0, vmax=None, figsize=[10, 8], dpi=72)
print('Plotted '+' '.join(fname_hist))
print('N sources total: '+str(alt.size))
print('Min alt: '+str(alt.min()))
print('Max alt: '+str(alt.max()))
print('Min power: '+str(dBm.min()))
print('Max power: '+str(dBm.max()))
# Get first sources
_, unique_ind = np.unique(flashnr, return_index=True)
lat_first = lat[unique_ind]
lon_first = lon[unique_ind]
alt_first = alt[unique_ind]
dBm_first = dBm[unique_ind]
# plot position all sources
figfname = args.basepath+'Santis_LMA_sources_pos_max_height_on_top.png'
figfname = plot_pos(
lat, lon, alt, [figfname], sort_altitude='Highest_on_top',
cb_label='Source height [m MSL]',
titl='Flash sources position. Highest on top')
print('Plotted '+' '.join(figfname))
figfname = args.basepath+'Santis_LMA_sources_pos_min_height_on_top.png'
figfname = plot_pos(
lat, lon, alt, [figfname], sort_altitude='Lowest_on_top',
cb_label='Source height [m MSL]',
titl='Flash sources position. Lowest on top')
print('Plotted '+' '.join(figfname))
# plot position first source
print('N flashes total: '+str(alt_first.size))
figfname = (
args.basepath+'Santis_LMA_first_source_pos_max_height_on_top.png')
figfname = plot_pos(
lat_first, lon_first, alt_first, [figfname],
sort_altitude='Highest_on_top', cb_label='Source height [m MSL]',
titl='First flash source position. Highest on top')
print('Plotted '+' '.join(figfname))
figfname = (
args.basepath+'Santis_LMA_first_source_pos_min_height_on_top.png')
figfname = plot_pos(
lat_first, lon_first, alt_first, [figfname],
sort_altitude='Lowest_on_top', cb_label='Source height [m MSL]',
titl='First flash source position. Lowest on top')
print('Plotted '+' '.join(figfname))
# Plot histogram altitude all sources
fname_hist = args.basepath+'Santis_hist_alt.png'
fname_hist = plot_histogram(
bin_edges_alt, alt, [fname_hist], labelx='Altitude [m MSL]',
titl='Flash sources altitude')
print('Plotted '+' '.join(fname_hist))
fname_hist = args.basepath+'Santis_hist_alt.csv'
hist_alt, _ = np.histogram(alt, bins=bin_edges_alt)
fname_hist = write_histogram(bin_edges_alt, hist_alt, fname_hist)
print('Written '+fname_hist)
# Plot histogram altitude first sources
fname_hist = args.basepath+'Santis_hist_alt_first_source.png'
fname_hist = plot_histogram(
bin_edges_alt, alt_first, [fname_hist], labelx='Altitude [m MSL]',
titl='Flash first source altitude')
print('Plotted '+' '.join(fname_hist))
fname_hist = args.basepath+'Santis_hist_alt_first_source.csv'
hist_alt_first, _ = np.histogram(alt_first, bins=bin_edges_alt)
fname_hist = write_histogram(bin_edges_alt, hist_alt_first, fname_hist)
print('Written '+fname_hist)
fname_hist = args.basepath+'Santis_hist_dBm.png'
fname_hist = plot_histogram(
bin_edges_dBm, dBm, [fname_hist], labelx='Power [dBm]',
titl='Flash sources power')
print('Plotted '+' '.join(fname_hist))
fname_hist = args.basepath+'Santis_hist_dBm.csv'
hist_dBm, _ = np.histogram(dBm, bins=bin_edges_dBm)
fname_hist = write_histogram(bin_edges_dBm, hist_dBm, fname_hist)
print('Written '+fname_hist)
# Plot histogram power first sources
fname_hist = args.basepath+'Santis_hist_dBm_first_source.png'
fname_hist = plot_histogram(
bin_edges_dBm, dBm_first, [fname_hist], labelx='Power [dBm]',
titl='Flash first source power')
print('Plotted '+' '.join(fname_hist))
fname_hist = args.basepath+'Santis_hist_dBm_first_source.csv'
hist_dBm_first, _ = np.histogram(dBm_first, bins=bin_edges_dBm)
fname_hist = write_histogram(bin_edges_dBm, hist_dBm_first, fname_hist)
print('Written '+fname_hist)
# Plot 2D histogram all sources
H, _, _ = np.histogram2d(alt, dBm, bins=[bin_edges_alt, bin_edges_dBm])
# set 0 values to blank
H = np.ma.asarray(H)
H[H == 0] = np.ma.masked
fname_hist = args.basepath+'Santis_2Dhist_alt_dBm.png'
fname_hist = _plot_time_range(
bin_edges_alt, bin_edges_dBm, H, None, [fname_hist],
titl='LMA sources Altitude-Power histogram',
xlabel='Altitude [m MSL]', ylabel='Power [dBm]',
clabel='Occurrence',
vmin=0, vmax=None, figsize=[10, 8], dpi=72)
print('Plotted '+' '.join(fname_hist))
# Plot 2D histogram first sources
H, _, _ = np.histogram2d(
alt_first, dBm_first, bins=[bin_edges_alt, bin_edges_dBm])
# set 0 values to blank
H = np.ma.asarray(H)
H[H == 0] = np.ma.masked
fname_hist = args.basepath+'Santis_2Dhist_alt_dBm_first_source.png'
fname_hist = _plot_time_range(
bin_edges_alt, bin_edges_dBm, H, None, [fname_hist],
titl='LMA first sources Altitude-Power histogram',
xlabel='Altitude [m MSL]', ylabel='Power [dBm]',
clabel='Occurrence',
vmin=0, vmax=None, figsize=[10, 8], dpi=72)
print('Plotted '+' '.join(fname_hist))
def _print_end_msg(text):
"""
prints end message
Parameters
----------
text : str
the text to be printed
Returns
-------
Nothing
"""
print(text + datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
# ---------------------------------------------------------
# Start main:
# ---------------------------------------------------------
if __name__ == "__main__":
main()
|
Java
|
UTF-8
| 1,155 | 2.359375 | 2 |
[] |
no_license
|
package com.refactorizando.example.springnative;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;
@RequiredArgsConstructor
public class CarHandler {
private final CarService service;
public Mono<ServerResponse> getAll(ServerRequest req) {
var all = service.findAll(Sort.by("model", "brand"));
return ok().body(BodyInserters.fromPublisher(all, Car.class));
}
public Mono<ServerResponse> getOne(ServerRequest req) {
var mono = service
.findById(Long.valueOf(req.pathVariable("id")))
.switchIfEmpty(Mono.error(() -> new ResponseStatusException(NOT_FOUND)));
return ok().body(BodyInserters.fromPublisher(mono, Car.class));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.