branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <repo_name>chaoxiyan1225/RT-Theard<file_sep>/bsp/ls1cdev/applications/test_pwm.c
/*代码 test_pwm.c*/
/*
测试硬件 pwm, 在 finsh 中运行
*/
#include "../libraries/ls1c_public.h"
#include "../libraries/ls1c_gpio.h"
#include "../libraries/ls1c_delay.h"
#include "../libraries/ls1c_pwm.h"
// 测试硬件 pwm 产生连续的 pwm 波形
struct pwm_info_t
{
unsigned int gpio; // PWMn 所在的 gpio
unsigned int mode; // 工作模式(单脉冲、连续脉冲)
float duty; // pwm 的占空比
unsigned long period_ns; // pwm 周期(单位 ns)
};
void pwm_control(void)
{
pwm_info_t pwm_info;
pwm_info.gpio = LS1C_PWM0_GPIO06; // pwm 引脚位 gpio06
pwm_info.mode = PWM_MODE_NORMAL; // 正常模式--连续输出 pwm 波形
pwm_info.duty =0.75; // pwm 占空比
pwm_info.period_ns = 1*500*1000; // pwm 周期 0.5ms
// pwm 初始化,初始化后立即产生 pwm 波形
pwm_init(&pwm_info);
pwm_enable(&pwm_info);
return ;
}
#include <finsh.h>
FINSH_FUNCTION_EXPORT(pwm_control, pwm_control e.g.pwm_control());
MSH_CMD_EXPORT(pwm_control, pwm_control );
<file_sep>/bsp/ls1cdev/applications/test_gpio.c
/*代码 test_gpio.c*/
#include <rtthread.h>
#include <stdlib.h>
#include "../libraries/ls1c_public.h"
#include "../libraries/ls1c_gpio.h"
#include "../libraries/ls1c_delay.h"
#define led_gpio 52
#define key_gpio 85
void turn_on(void)
{
int i;
// 初始化
rt_kprintf("Init gpio! \n");
gpio_init(led_gpio, gpio_mode_output);
gpio_set(led_gpio, gpio_level_low); //指示灯开启
return ;
}
void turn_off(void)
{
int i;
// 初始化
rt_kprintf("Init gpio! \n");
gpio_init(led_gpio, gpio_mode_output);
gpio_set(led_gpio, gpio_level_high); //指示灯熄灭
return ;
}
#include <finsh.h>
FINSH_FUNCTION_EXPORT(turn_on, turn_on e.g.turn_on());
FINSH_FUNCTION_EXPORT(turn_off, turn_off e.g.turn_off());
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(turn_on, gpio output sample);
MSH_CMD_EXPORT(turn_off, gpio output sample);
| 0db39a5c32df34feb56f2de593b8944842669685 | [
"C"
] | 2 | C | chaoxiyan1225/RT-Theard | daf9b32f5710ec2814eeff7b0f20d92591941db7 | 39f9fa68cf964a97d1a205cc78857bbf9841278d |
refs/heads/main | <repo_name>KNTU-Algorithm-Design-Spring-2021/individual-project-3-ghazal-pouresfandiyar<file_sep>/Word Break/src/ir/ac/kntu/Main.java
package ir.ac.kntu;
import java.io.*;
import java.util.HashMap;
public class Main {
static HashMap<String , Boolean> DICTIONARY ;
public static void main(String[] args) {
DICTIONARY= readDictionaryFromFile();
sentenceBreak("mango");
sentenceBreak("ILOVEICECREAMANDMANGO");
sentenceBreak("IAMBATMAN");
sentenceBreak("CALLSECURITYATMIAMIAIRPORTBECAUSEITHINKABOMBISABOUTTOGOOFF");
sentenceBreak("ABORTTHEPLANMEETATTHEDARKCABIN");
sentenceBreak("LADIESANDGENTLEMENPLEASEWEARYOURMASKSEVERYWHERE");
sentenceBreak("MYGRANDMOTHERALWAYSREMINDEDMETODRIVECAREFULLYANYTIMEIAMONMYWAYTOHOME");
}
public static HashMap<String , Boolean> readDictionaryFromFile (){
HashMap<String , Boolean> DICTIONARY = new HashMap<>();
File file = new File("Dictionary.txt");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String st;
try {
while ((st = br.readLine()) != null) {
if(st.length() == 1 && !st.equals("a") && !st.equals("i")) {
DICTIONARY.put(st, false);
}else {
DICTIONARY.put(st, true);
}
}
}catch (IOException e){
e.printStackTrace();
}
return DICTIONARY;
}
public static boolean isValid(String word){
if(DICTIONARY.get(word) == null) {
return false;
} else if(DICTIONARY.get(word)) {
return true;
}
return false;
}
public static void tracingTree(String str, String result) {
int size = str.length();
for (int i = 1; i <= size; i++) {
String prefix = str.substring(0, i);
if (isValid(prefix)) {
if (i == size) {
result += prefix;
System.out.println(result);
return;
}
tracingTree(str.substring(i, size), result + prefix + " ");
}
}
}
public static void sentenceBreak(String str){
System.out.println("__________________________________________________________________________________");
tracingTree(str.toLowerCase() , "");
}
}
| 3755df577ab43de3279eaa9f47e9313a30b9d5cf | [
"Java"
] | 1 | Java | KNTU-Algorithm-Design-Spring-2021/individual-project-3-ghazal-pouresfandiyar | d731adc1f476311894f1c4c564441629549aad0c | 8562e83ec6723956fe585a379221be7bad064109 |
refs/heads/master | <file_sep>pub mod requests;
pub enum CutepawError {
ReqwestError(reqwest::Error),
APIError,
}
| b95344ed72e6e24b06ebc368ef72dfdc2d480940 | [
"Rust"
] | 1 | Rust | eoan-ermine/cutepaw | 201bfe8f0d7758b195848a894ad5c42ad2de77ff | d0ea870e494703827c57b773a59b213fc1af52ce |
refs/heads/master | <repo_name>sujanan/siddhi-doc-fetch-experimental<file_sep>/src/main/java/com/example/githubclient/HtmlContentResponse.java
package com.example.githubclient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import javax.net.ssl.HttpsURLConnection;
public class HtmlContentResponse extends ContentResponse<Document> {
HtmlContentResponse(HttpsURLConnection connection) throws IOException {
super(connection);
super.docExtractor = new DocExtractor<Document, HtmlContentResponse>(this) {
@Override
String getFirstParagraph(Document content) {
Elements pTags = content.getElementsByTag("p");
if (pTags != null) {
Element firstPTag = pTags.first();
if (firstPTag != null) {
return firstPTag.text();
}
}
return null;
}
};
}
@Override
String mediaType() {
return "html";
}
@Override
public Document getContent() throws IOException {
return Jsoup.parse(super.stream, null, "");
}
}
<file_sep>/src/main/java/com/example/githubclient/GithubContentsClient.java
package com.example.githubclient;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class GithubContentsClient {
private static final String DOMAIN = "api.github.com";
private final HttpsURLConnection connection;
public static class Builder {
private final String owner;
private final String repos;
private final StringBuilder queryParamsBuilder;
private boolean isReadme = false;
private String path = "/";
public Builder(String owner, String repos) {
this.owner = owner;
this.repos = repos;
queryParamsBuilder = new StringBuilder();
}
public Builder isReadme(boolean isReadme) {
this.isReadme = isReadme;
return this;
}
public Builder path(String path) {
if (!path.isEmpty() && path.charAt(0) != '/') {
path = '/' + path;
}
this.path = path;
return this;
}
public Builder queryParam(String key, String val) {
if (queryParamsBuilder.length() != 0) {
queryParamsBuilder.append("&");
}
queryParamsBuilder.append(key).append("=").append(val);
return this;
}
public GithubContentsClient build() throws IOException {
return new GithubContentsClient(this);
}
}
private GithubContentsClient(Builder builder) throws IOException {
StringBuilder urlBuilder = new StringBuilder()
.append("https://")
.append(DOMAIN)
.append("/repos")
.append("/").append(builder.owner)
.append("/").append(builder.repos);
if (builder.isReadme) {
urlBuilder.append("/readme");
} else {
urlBuilder.append("/contents").append(builder.path);
}
String queryParams = builder.queryParamsBuilder.toString();
if (!queryParams.isEmpty()) {
urlBuilder.append("?").append(queryParams);
}
URL url = new URL(urlBuilder.toString());
connection = (HttpsURLConnection) url.openConnection();
}
public void setHeader(String key, String val) {
connection.setRequestProperty(key, val);
}
public <T extends ContentResponse> T getContentResponse(Class<T> tClass) throws Exception {
Constructor<T> constructor = tClass.getDeclaredConstructor(HttpsURLConnection.class);
constructor.setAccessible(true);
return constructor.newInstance(connection);
}
}
<file_sep>/src/main/java/com/example/githubclient/DocExtractor.java
package com.example.githubclient;
import java.io.IOException;
public abstract class DocExtractor<E, T extends ContentResponse<E>> {
private final T response;
public DocExtractor(T response) {
this.response = response;
}
public String getFirstParagraph() throws IOException {
if (response.getStatus() != 200) {
return null;
}
return getFirstParagraph(response.getContent());
}
abstract String getFirstParagraph(E content);
}
<file_sep>/src/main/java/com/example/DocRetriever.java
package com.example;
import com.example.githubclient.GithubContentsClient;
import com.example.githubclient.HtmlContentResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import java.util.logging.Logger;
public class DocRetriever {
private static final Logger LOG = Logger.getLogger(DocRetriever.class.getName());
private static final String CREDENTIALS_PROPERTIES = "credentials.properties";
private static final String CLIENT_ID = "client_id";
private static final String CLIENT_SECRET = "client_secret";
private final String baseRepo;
private final String[] extensions;
private DocStore docStore;
public DocRetriever(String baseRepo, String[] extensions) {
this.baseRepo = baseRepo;
this.extensions = extensions;
docStore = null;
try {
docStore = new DocStore();
} catch (IOException | URISyntaxException e) {
LOG.warning("DocStore creation failed. Will depend on the remote data only.");
}
}
public void fetch() throws Exception {
if (docStore == null) {
return;
}
String httpStandardLastModified = DateTimeFormatter.RFC_1123_DATE_TIME
.withZone(ZoneOffset.UTC)
.format(docStore.lastModified().toInstant());
int i = 0;
caller:
for (; i < extensions.length; i++) {
final String extension = extensions[i];
GithubContentsClient client = new GithubContentsClient.Builder(baseRepo, extension)
.isReadme(true)
.build();
if (docStore.has(extension)) {
client.setHeader("If-Modified-Since", httpStandardLastModified);
}
HtmlContentResponse response = client.getContentResponse(HtmlContentResponse.class);
switch (response.getStatus()) {
case 304:
LOG.info(String.format("[%s] %s", extension, "Content was not modified."));
continue;
case 403:
LOG.info("Maximum request quota exceeded. Falling back to Authorized routes.");
break caller;
case 200:
String firstParagraph = response.getFirstParagraph();
if (firstParagraph == null) {
continue;
}
LOG.info(String.format("[%s] %s", extension, "Content was modified."));
docStore.add(extension, firstParagraph);
break;
default:
LOG.warning(response.getError().toString());
break;
}
}
Properties credentials = new Properties();
if (!loadCredentials(credentials)) {
return;
}
for (; i < extensions.length; i++) {
final String extension = extensions[i];
GithubContentsClient client = new GithubContentsClient.Builder(baseRepo, extension)
.isReadme(true)
.queryParam(CLIENT_ID, credentials.getProperty(CLIENT_ID))
.queryParam(CLIENT_SECRET, credentials.getProperty(CLIENT_SECRET))
.build();
if (docStore.has(extension)) {
client.setHeader("If-Modified-Since", httpStandardLastModified);
}
HtmlContentResponse response = client.getContentResponse(HtmlContentResponse.class);
switch (response.getStatus()) {
case 304:
LOG.info(String.format("[%s] %s", extension, "Content was not modified."));
continue;
case 200:
String firstParagraph = response.getFirstParagraph();
if (firstParagraph == null) {
continue;
}
LOG.info(String.format("[%s] %s", extension, "Content was modified."));
docStore.add(extension, firstParagraph);
break;
default:
LOG.warning(response.getError().toString());
break;
}
}
docStore.getUpdater().commit().updateSource();
}
private boolean loadCredentials(Properties credentials) {
URL credentialsUrl = DocRetriever.class.getClassLoader().getResource(CREDENTIALS_PROPERTIES);
if (credentialsUrl == null) {
return false;
}
Path credentialsPath;
try {
credentialsPath = Paths.get(credentialsUrl.toURI());
} catch (URISyntaxException e) {
return false;
}
try (FileInputStream stream = new FileInputStream(credentialsPath.toString())) {
credentials.load(stream);
if (credentials.getProperty(CLIENT_ID) == null || credentials.getProperty(CLIENT_SECRET) == null) {
return false;
}
} catch (IOException e) {
return false;
}
return true;
}
}
| 4ae21bdb229d834ff806cdc3000beff50a12a240 | [
"Java"
] | 4 | Java | sujanan/siddhi-doc-fetch-experimental | 33aed18ed6d22d0c77a0b4455d5fc578afbae48d | c592b401d6a9aa57c0d28bd117dc05599ccf9301 |
refs/heads/master | <repo_name>netanelgilad/angular-meteor-collectionfs-example<file_sep>/model.js
Images = new FS.Collection("images", {
stores: [
new FS.Store.GridFS("original"),
new FS.Store.GridFS("thumbnail", {
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name()).resize('112', '112', '!').stream().pipe(writeStream);
}
})
],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
if (Meteor.isServer) {
Meteor.methods({
setThumbnail: function(_id, size) {
var image = Images.findOne(_id);
var readStream = image.createReadStream('original');
var writeStream = image.createWriteStream('thumbnail');
//The following line should be avoided
writeStream.safeOn('stored', function() {
image.updatedAt(new Date(), {store: 'thumbnail'});
});
gm(readStream).crop(size.width, size.height, size.x, size.y).stream().pipe(writeStream);
}
});
}
| a06597859b17e62347f5f8c583252cabd2e3d180 | [
"JavaScript"
] | 1 | JavaScript | netanelgilad/angular-meteor-collectionfs-example | ff3052df75c55ca727db1a6e596e6c469deb3910 | 6e87b1fe2772dc96515894ea83933046cbf8de3d |
refs/heads/master | <file_sep>print("I, <NAME>, want tacos!")
print("I, Eamon Lamberty, want tacos!")
print("I, <NAME>, want tacos more than *anyone*, especially more than Eamon!")
print("I, <NAME>, want tacos!")
| d95d39e32ea67148ac4c87e1ac00d9cfb072474a | [
"Python"
] | 1 | Python | JaeLee77/tacoworld | 6be5490af03032ba9ebc22eed4b66b1deb62a563 | 6b0116a31cf5b529f1f537cca32326b2055c0ee3 |
refs/heads/main | <file_sep><?php
namespace bemusedrat\phasmophobia;
use SilverStripe\ORM\DataObject;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TextField;
class Evidence extends DataObject {
private static $db = [
'Name' => 'Varchar'
];
private static $has_one = [
'GhostPage' => GhostPage::class
];
private static $belongs_many_many = [
'Ghosts' => Ghost::class
];
//private static $default_sort = 'Name ASC';
private static $table_name = 'Evidence';
public function getCMSFields() {
$fields = FieldList::create(
TextField::create('Name')
);
return $fields;
}
}<file_sep><?php
namespace bemusedrat\phasmophobia;
use PageController;
use SilverStripe\Control\Director;
use SilverStripe\View\Requirements;
use SilverStripe\ORM\DataObject;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\CheckboxSetField;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\RequiredFields;
class GhostPageController extends PageController {
protected function init()
{
parent::init();
//Requirements::javascript("<my-module-dir>/javascript/some_file.js");
Requirements::css("vendor/bemusedrat/phasmophobia/css/phasmophobia.css");
}
private static $allowed_actions = [
'EvidenceForm',
];
// Create the frontend form to select evidence types
public function EvidenceForm() {
$EvidenceCheckBoxField = CheckboxSetField::create(
'EvidenceTypes',
'Select up to 3 evidence types to see which ghosts match.',
$this->EvidenceTypes()->map('ID', 'Title')
);
$myForm = Form::create(
$this,
'EvidenceForm',
FieldList::create(
$EvidenceCheckBoxField
),
FieldList::create(
FormAction::create('sendEvidenceForm','Update')
)
);
// Check if there's a string query in the URL and add those values array. This will enable pre-filling the form based on URL (for refreshes, link sharing, etc.)
$e1 = $this->getRequest()->getVar('e1');
$e2 = $this->getRequest()->getVar('e2');
$e3 = $this->getRequest()->getVar('e3');
$EvidenceTypes = array();
// Push each evidence type to the array
if($e3) {
array_push($EvidenceTypes, $e3);
}
if($e2) {
array_push($EvidenceTypes, $e2);
}
if($e1) {
array_push($EvidenceTypes, $e1);
} else {
$EvidenceTypes = null;
}
// Pre-fill checkboxes with query string data from constructed array (if any)
if($EvidenceTypes) {
$EvidenceCheckBoxField->setDefaultItems($EvidenceTypes);
}
return $myForm;
}
// Action taken when the "Update" button gets pushed
public function sendEvidenceForm($data, $form) {
// Check for an empty form (nothing selected) and just refresh
if(!isset($data['EvidenceTypes'])) {
return $this->redirect($this->AbsoluteLink());
}
// Redirect with an error if more than 3 options are selected
if(count($data['EvidenceTypes']) > 3) {
$form->sessionError('Too many evidence types selected! Max = 3');
return $this->redirectBack();
}
$EvidenceTypes = $data['EvidenceTypes'];
// Contstruct query string to pre-fill the form and show results
// TO-DO: Remove the trailing "&" after the last query string entry for le tidiness
$querystring = "?";
$i = 1;
foreach ($EvidenceTypes as $key => $value) {
$querystring = $querystring . 'e' . $i . '=' . $value . "&";
$i++;
}
return $this->redirect($this->AbsoluteLink(). $querystring);
}
// Function to get the ghosts associated with the selected evidence. Returns a list of ghosts.
public function getEvidencedGhosts() {
// Get evidence IDs from query string
$e1 = $this->getRequest()->getVar('e1');
$e2 = $this->getRequest()->getVar('e2');
$e3 = $this->getRequest()->getVar('e3');
// Return all ghosts if no evidence has been selected
if(!$e1) {
return Ghost::get();
}
// This feels a bit awkward but we make an array of ghosts for each evidence type
// We then use array_intersect to combine the arrays together to get only the ghosts that match ALL selected evidence types
$Ghost1 = array();
$Ghost2 = array();
$Ghost3 = array();
$Ghosts = array();
// Get all ghosts matching the first evidence type
$evidence1 = $this->EvidenceTypes()->filter('ID', $e1)->First();
$Ghost1 = $evidence1->Ghosts()->columnUnique('ID');
$GhostIDs = $Ghost1;
// Get all ghosts matching the second evidence type
if($e2) {
$evidence2 = $this->EvidenceTypes()->filter('ID', $e2)->First();
$Ghost2 = $evidence2->Ghosts()->columnUnique('ID');
// Get rid of the ghosts that don't have both types of evidence
$Ghosts1and2 = array_intersect($Ghost1, $Ghost2);
$GhostIDs = $Ghosts1and2;
}
// Get all ghosts matching the second evidence type
if($e3) {
$evidence3 = $this->EvidenceTypes()->filter('ID', $e3)->First();
$Ghost3 = $evidence3->Ghosts()->columnUnique('ID');
// Get rid of the ghosts that don't have all 3 types of evidence
$GhostIDs = array_intersect($Ghosts1and2, $Ghost3);
}
// Above we are simply working with the ghost IDs to keep things simple and hopefully speedy. Now we need to get the actual ghosts with those IDs.
if($GhostIDs) {
$Ghosts = Ghost::get()->filter('ID', $GhostIDs);
} else {
return null;
}
return $Ghosts;
}
// See if their is only one returned Ghost. This can then be highlighted on the front end as successful. Returns true or false
public function getOnlyGhost() {
$Ghosts = $this->getEvidencedGhosts();
if(!$Ghosts){return null;}
if($Ghosts->Count() == 1) {
return true;
} else {
return false;
}
}
}<file_sep># Phasmophobia Ghost Identifier
This module helps you identify ghosts in Phasmophobia (BYO database)
Install SilverStripe 4.6
composer create-project silverstripe/installer ./my-project 4.6.0
Install bootstrap theme 1.0
composer require ilateral/silverstripe-bootstrap-4 1.1.2
Install fractas/cookiepolicy
composer require fractas/cookiepolicy dev-master
Update main composer.json with bemusudRat/phasmo location
Install bemusedrat/phasmophobia
<file_sep><?php
namespace bemusedrat\phasmophobia;
use SilverStripe\Control\Controller;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DataList;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\CheckboxSetField;
class Ghost extends DataObject {
private static $db = [
'Name' => 'Varchar',
];
private static $has_one = [
'GhostPage' => GhostPage::class,
];
private static $many_many = [
'EvidenceTypes' => Evidence::class
];
//private static $default_sort = 'Name ASC';
private static $table_name = 'Ghost';
public function getCMSFields() {
$fields = FieldList::create(
TextField::create('Name'),
CheckboxSetField::create(
'EvidenceTypes',
'Evidence Types',
$this->GhostPage()->EvidenceTypes()->map('ID', 'Title')
)
);
return $fields;
}
public function getRequiredEvidence() {
// Get evidence IDs from query string
$Controller = Controller::curr();
$e1 = $Controller->getRequest()->getVar('e1');
$e2 = $Controller->getRequest()->getVar('e2');
$e3 = $Controller->getRequest()->getVar('e3');
// Do nothing if no evidence has been selected yet
if(!$e1) {
return null;
}
// Get evidence types based on query string
$evidence1 = Evidence::get()->filter('ID', $e1)->First()->ID;
if($e2) {
$evidence2 = Evidence::get()->filter('ID', $e2)->First()->ID;
}
if($e3) {
$evidence3 = Evidence::get()->filter('ID', $e3)->First()->ID;
}
// Evidence that still needs to be collected
$RequiredEvidence = array();
// The current ghosts evidence types
$Evidences = $this->EvidenceTypes();
// Check each evidence type for this ghost against what was selected in the form to see which ones match (marked 'Selected')
foreach ($Evidences as $Evidence) {
$Selected = false;
if($Evidence->ID == $evidence1) {
$Selected = true;
}
if($e2){
if($Evidence->ID == $evidence2) {
$Selected = true;
}
}
if($e3) {
if($Evidence->ID == $evidence3) {
$Selected = true;
}
}
// If the current evidence type does NOT match any of the evidence types selected, then add it to the Required list as it is still required
if(!$Selected) {
array_push($RequiredEvidence, $Evidence->ID);
}
}
// If $RequiredEvidence is empty then we return null as ALL the evidence for this ghost has been selected in the form. Nothing is still required.
if(empty($RequiredEvidence)){return null;}
// If there IS evidence still to get, then return them to the template as a list to be displayed
$RequiredEvidences = Evidence::get()->filter('ID', $RequiredEvidence);
return $RequiredEvidences;
}
}<file_sep><?php
namespace bemusedrat\phasmophobia;
use Page;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
class GhostPage extends Page {
private static $has_many = [
'Ghosts' => Ghost::class,
'EvidenceTypes' => Evidence::class
];
private static $table_name = 'GhostPage';
public function getCMSFields() {
$fields = parent::getCMSFields();
// Create GridField for Ghosts
$GhostGridField = GridField::create(
'Ghosts',
'Ghost types',
$this->Ghosts(),
GridFieldConfig_RecordEditor::create()
);
// Create GridField for Evidence
$EvidenceGridField = GridField::create(
'EvidenceTypes',
'Evidence types',
$this->EvidenceTypes(),
GridFieldConfig_RecordEditor::create()
);
// Add GridFields to $fields
$fields->addFieldToTab('Root.Ghosts', $GhostGridField);
$fields->addFieldToTab('Root.Evidence', $EvidenceGridField);
return $fields;
}
} | 3e29e3fffd1de58aab5d6de8c05beff30ef0ece3 | [
"Markdown",
"PHP"
] | 5 | PHP | BemusedRat/phasmophobia | 92fc3cdec7f62c599564ca46722ee3a8bfb1b763 | 0055d5ac2d0159b8adc3bb8522c4f2fffcf3bc68 |
refs/heads/master | <file_sep>using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Syncfusion.ListView.XForms;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
namespace ListViewXamarin
{
public class MainPageViewModel : BindableBase, INavigationAware
{
#region Fields
private ObservableCollection<ToDoItem> toDoList;
#endregion
#region Constructor
public MainPageViewModel()
{
this.GenerateSource();
ItemDraggingCommand = new DelegateCommand<ItemDraggingEventArgs>(OnItemDragging);
}
#endregion
#region Properties
public DelegateCommand<ItemDraggingEventArgs> ItemDraggingCommand { get; set; }
public ObservableCollection<ToDoItem> ToDoList
{
get
{
return toDoList;
}
set
{
this.toDoList = value;
}
}
#endregion
#region Methods
public void GenerateSource()
{
ToDoListRepository todoRepository = new ToDoListRepository();
toDoList = todoRepository.GetToDoList();
}
private void OnItemDragging(ItemDraggingEventArgs args)
{
if (args.Action == DragAction.Drop)
App.Current.MainPage.DisplayAlert("Message", "ListView item index after reordering " + args.NewIndex, "Ok");
}
#endregion
#region Prism Methods
public void OnNavigatedFrom(INavigationParameters parameters)
{
}
public void OnNavigatedTo(INavigationParameters parameters)
{
}
public void OnNavigatingTo(INavigationParameters parameters)
{
}
#endregion
}
}
<file_sep># How to retrieve the dragged item index in ViewModel command with the Prism framework in Xamarin.Forms ListView (SfListView)?
You can retrieve the drag index of [ListViewItem](https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfListView.XForms~Syncfusion.ListView.XForms.ListViewItem.html?) in ViewModel using the [Prism](https://prismlibrary.com/docs/xamarin-forms/Getting-Started.html) framework [DelegateCommand](https://prismlibrary.com/docs/commanding.html#creating-a-delegatecommand) in Xamarin.Forms [SfListView](https://help.syncfusion.com/xamarin/listview/overview?).
You can also refer the following article.
https://www.syncfusion.com/kb/11371
**XAML**
[EventToCommandBehavior](https://help.syncfusion.com/xamarin/listview/mvvm?_ga=2.48449378.576537389.1586149449-1204678185.1570168583#event-to-command) to convert the [ItemDragging](https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfListView.XForms~Syncfusion.ListView.XForms.SfListView~ItemDragging_EV.html?) event to a command and set ListView behavior.
``` xml
<syncfusion:SfListView x:Name="listView" Grid.Row="1" ItemSize="60" BackgroundColor="#FFE8E8EC" GroupHeaderSize="50" ItemsSource="{Binding ToDoList}" DragStartMode="OnHold,OnDragIndicator" SelectionMode="None">
<syncfusion:SfListView.Behaviors>
<local:EventToCommandBehavior EventName="ItemDragging" Command="{Binding ItemDraggingCommand}"/>
</syncfusion:SfListView.Behaviors>
<syncfusion:SfListView.ItemTemplate>
<DataTemplate>
<Frame HasShadow="True" BackgroundColor="White" Padding="0">
<Frame.InputTransparent>
<OnPlatform x:TypeArguments="x:Boolean" Android="True" iOS="False"/>
</Frame.InputTransparent>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<Label x:Name="textLabel" Text="{Binding Name}" FontSize="15" TextColor="#333333" VerticalOptions="Center" HorizontalOptions="Start" Margin="5,0,0,0" />
<syncfusion:DragIndicatorView Grid.Column="1" ListView="{x:Reference listView}" HorizontalOptions="Center" VerticalOptions="Center">
<Grid Padding="10, 20, 20, 20">
<Image Source="DragIndicator.png" VerticalOptions="Center" HorizontalOptions="Center" />
</Grid>
</syncfusion:DragIndicatorView>
</Grid>
</Frame>
</DataTemplate>
</syncfusion:SfListView.ItemTemplate>
</syncfusion:SfListView>
```
**C#**
Create command for the ItemDragging event with the [ItemDraggingEventArgs](https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfListView.XForms~Syncfusion.ListView.XForms.ItemDraggingEventArgs.html?) parameter. You can access the item index from [NewIndex](https://help.syncfusion.com/cr/cref_files/xamarin/Syncfusion.SfListView.XForms~Syncfusion.ListView.XForms.ItemDraggingEventArgs~NewIndex.html?) field of the **ItemDraggingEventArgs**.
``` c#
public class ViewModel
{
public DelegateCommand<ItemDraggingEventArgs> ItemDraggingCommand { get; set; }
public ViewModel()
{
ItemDraggingCommand = new DelegateCommand<ItemDraggingEventArgs>(OnItemDragging);
}
private void OnItemDragging(ItemDraggingEventArgs args)
{
if (args.Action == DragAction.Drop)
App.Current.MainPage.DisplayAlert("Message", "ListView item index after reordering " + args.NewIndex, "Ok");
}
}
```
**Output**

| 8151da26c75668c763e614cb01491d673ab38b16 | [
"Markdown",
"C#"
] | 2 | C# | SyncfusionExamples/dragged-listviewitem-index-xamarin-listview | 4c537b6ce03e40755fb6d4cc780e78703c829628 | 1342cc2715db4b41f89911f25d550d90a27244d4 |
refs/heads/master | <file_sep>import React from 'react';
import {connect} from 'react-redux';
import {
fetchCheeses
} from '../actions/cheese';
export class CheeseList extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.dispatch(fetchCheeses());
}
render() {
console.log(this.props.cheeses);
const cheeses = this.props.cheeses;
return (
<div className="cheese">
<h1> The Cheese List </h1>
{cheeses.map(function(cheese, index) {
return <li key={index}> {cheese} </li>
})}
</div>
);
}
}
const mapStateToProps = (state) => ({
cheeses: state.cheeses
});
export default connect(mapStateToProps)(CheeseList);
| b7cf4762c221e6917b96f6ccd5e71ddec6f7134c | [
"JavaScript"
] | 1 | JavaScript | simgill13/Full-Stack-Primer | 0aaa55e923299bfea1ea3ff09e5f8a5a29b57b49 | 2182cf243f05186fe34b70fa2c410cc684b59f16 |
refs/heads/master | <repo_name>austinsc/riot-data<file_sep>/src/api/featuredGames.js
import {FEATURED_GAMES} from '../Constants';
export const FeaturedGames = {
get(options = {}) {
return Object.assign({}, options, {
endpoint: 'api.pvp.net',
uri: FEATURED_GAMES
});
}
};
<file_sep>/test/index.js
//function requireAll(r) { r.keys().forEach(r); }
//requireAll(require.context('./', true, /\.test\.js$/));
require('./Api.test');<file_sep>/src/api/matchHistory.js
import {MATCH_HISTORY} from '../Constants';
export const MatchHistory = {
getBySummonerId(summonerId, options = {}) {
return Object.assign({}, options, {
id: summonerId,
uri: MATCH_HISTORY,
query: {
championIds: options.championIds instanceof Array ? options.championIds.join() : options.championIds || null,
rankedQueues: options.rankedQueues instanceof Array ? options.rankedQueues.join() : options.rankedQueues || null,
beginIndex: options.beginIndex || null,
endIndex: options.endIndex || null
}
});
}
};<file_sep>/src/api/match.js
import {MATCH} from '../Constants';
export const Match = {
get(matchId, options = {}) {
return Object.assign({}, options, {
id: matchId,
uri: MATCH,
query: {
includeTimeline: options.includeTimeline || false
}
});
}
};<file_sep>/src/cli.js
import rc from 'rc';
import optimist from 'optimist';
import Logdown from 'logdown';
import cfonts from 'cfonts';
import * as defaults from './defaults';
import RiotAccess, {print} from './riot';
var fonts = new cfonts({
'text': 'riot-data', //text to be converted
'font': 'block', //define the font face
'colors': '', //define all colors
'background': 'Black', //define the background color
'letterSpacing': 1, //define letter spacing
'space': true, //define if the output text should have empty lines on top and on the bottom
'maxLength': '9' //define how many character can be on one line
});
const argv = optimist
.usage('Run the data mining service.')
.describe('r', 'Region to mine').alias('r', 'region')
.describe('k', 'Riot API key').alias('k', 'apikey')
.describe('m', 'MongoDB connection string').alias('m', 'mongodb')
.argv;
const config = rc('riot-data', {...defaults, logger: new Logdown({prefix: 'riot-data'})}, argv);
var rito = new RiotAccess(config);
async function main() {
try{
await rito.start();
} catch(err) {
config.logger.error(err.stack || err);
}
config.logger.info('Peace out.');
process.exit(0);
}
main();<file_sep>/src/utilities.js
import _ from 'lodash';
import prettyjson from 'prettyjson';
export function isInteger(value) {
return +value === (value | 0);
}
export function isArrayOfIntegers(array) {
return _.isArray(array) && _.every(array, isInteger);
}
export function isArrayOfStrings(array) {
return _.isArray(array) && _.every(array, _.isString);
}
export function fillUri(options) {
const pattern = new RegExp('\\{(?:(\\w+):)?(\\w+)\\}', 'gi');
let result = pattern.exec(options.uri);
while(result) {
const needle = result[0];
const param = result[result.length - 1];
if(!options[param]) {
throw new Error('Param ' + param + ' was not provided');
}
if(result.length === 3) {
const type = result[1];
switch(type) {
case 'string':
if(typeof options[param] !== 'string' && !isArrayOfStrings(options[param])) {
throw new Error('Param ' + param + ' must be string or an array of strings');
}
break;
case 'int':
if(!isInteger(options[param]) && !isArrayOfIntegers(options[param])) {
throw new Error('Param ' + param + ' must be an integer or an array of integers');
}
break;
}
if(options[param] instanceof Array) {
options[param] = options[param].join();
}
}
result = pattern.exec(options.uri);
options.uri = options.uri.replace(needle, options[param]);
}
return options.uri;
}
export function print(data) {
console.log(prettyjson.render(data));
return data;
}<file_sep>/src/api/static.js
import {
STATIC_CHAMPION,
STATIC_CHAMPION_ID,
STATIC_ITEM,
STATIC_ITEM_ID,
STATIC_MASTERY,
STATIC_MASTERY_ID,
STATIC_RUNE,
STATIC_RUNE_ID,
STATIC_SUMMONER_SPELL,
STATIC_SUMMONER_SPELL_ID,
STATIC_REALM,
STATIC_VERSIONS
} from '../Constants';
export const Static = {
getChampions(options = {}) {
return Object.assign({}, options, {
uri: STATIC_CHAMPION,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
dataById: options.dataById || null,
champData: options.champData instanceof Array ? options.champData.join() : options.champData || null
}
});
},
getChampion(championId, options = {}) {
return Object.assign({}, options, {
id: championId,
uri: STATIC_CHAMPION,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
champData: options.champData instanceof Array ? options.champData.join() : options.champData || null
}
});
},
getItems(options = {}) {
return Object.assign({}, options, {
uri: STATIC_ITEM,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
itemListData: options.itemListData instanceof Array ? options.itemListData.join() : options.itemListData || null
}
});
},
getItem(itemId, options = {}) {
return Object.assign({}, options, {
id: itemId,
uri: STATIC_ITEM_ID,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
itemData: options.itemData instanceof Array ? options.itemData.join() : options.itemData || null
}
});
},
getMasteries(options = {}) {
return Object.assign({}, options, {
uri: STATIC_MASTERY,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
masteryListData: options.masteryListData instanceof Array ? options.masteryListData.join() : options.masteryListData || null
}
});
},
getMastery(masteryId, options = {}) {
return Object.assign({}, options, {
id: masteryId,
uri: STATIC_MASTERY_ID,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
masteryData: options.masteryData instanceof Array ? options.masteryData.join() : options.masteryData || null
}
});
},
getRunes(options = {}) {
return Object.assign({}, options, {
uri: STATIC_RUNE,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
runeListData: options.runeListData instanceof Array ? options.runeListData.join() : options.runeListData || null
}
});
},
getRune(runeId, options = {}) {
return Object.assign({}, options, {
id: runeId,
uri: STATIC_RUNE_ID,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
runeData: options.runeData instanceof Array ? options.runeData.join() : options.runeData || null
}
});
},
getSummonerSpells(options = {}) {
return Object.assign({}, options, {
uri: STATIC_SUMMONER_SPELL,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
spellData: options.spellData instanceof Array ? options.spellData.join() : options.spellData || null
}
});
},
getSummonerSpell(summonerSpellId, options = {}) {
return Object.assign({}, options, {
id: summonerSpellId,
uri: STATIC_SUMMONER_SPELL_ID,
static: true,
query: {
locale: options.locale || null,
version: options.version || null,
dataById: options.dataById || null,
spellData: options.spellData instanceof Array ? options.spellData.join() : options.spellData || null
}
});
},
getRealm(options = {}) {
return Object.assign({}, options, {
uri: STATIC_REALM,
static: true
});
},
getVersions(options = {}) {
return Object.assign({}, options, {
uri: STATIC_VERSIONS,
static: true
});
}
};<file_sep>/src/api/currentGame.js
import {CURRENT_GAME, PLATFORMS} from '../Constants';
export const CurrentGame = {
getBySummonerId(summonerId, options = {}) {
return Object.assign({}, options, {
endpoint: 'api.pvp.net',
uri: CURRENT_GAME,
id: summonerId,
platformId: PLATFORMS[options.region]
});
}
};<file_sep>/src/api/status.js
import {STATUS_SHARD_ID, STATUS_SHARD_LIST} from '../Constants';
export const Status = {
get(shardName, options = {}) {
return Object.assign({}, options, {
names: shardName,
uri: STATUS_SHARD_ID,
host: 'http://status.leagueoflegends.com',
useHttp: true
});
},
getAll(options = {}) {
return Object.assign({}, options, {
uri: STATUS_SHARD_LIST,
host: 'http://status.leagueoflegends.com',
useHttp: true
});
}
};<file_sep>/src/Constants.js
// API Challenge
export const API_CHALLENGE = '/{string:region}/v4.1/game/ids';
// Champion
export const CHAMPION_LIST = '/{string:region}/v1.2/champion';
export const CHAMPION_ID = '/{string:region}/v1.2/champion/{int:id}';
// Current Game
export const CURRENT_GAME = '/observer-mode/rest/consumer/getSpectatorGameInfo/{string:platformId}/{int:id}';
// Feature Games
export const FEATURED_GAMES = '/observer-mode/rest/featured';
// Game
export const RECENT_GAMES = '/{string:region}/v1.3/game/by-summoner/{int:id}/recent';
// League
export const LEAGUE_BY_SUMMONER_FULL = '/{string:region}/v2.5/league/by-summoner/{int:id}';
export const LEAGUE_BY_SUMMONER = '/{string:region}/v2.5/league/by-summoner/{int:id}/entry';
export const LEAGUE_BY_TEAM_FULL = '/{string:region}/v2.5/league/by-team/{int:id}';
export const LEAGUE_BY_TEAM = '/{string:region}/v2.5/league/by-team/{int:id}/entry';
export const CHALLENGER_LEAGUE = '/{string:region}/v2.5/league/challenger';
// Match
export const MATCH = '/{string:region}/v2.2/match/{int:id}';
// Match history
export const MATCH_HISTORY = '/{string:region}/v2.2/matchhistory/{int:id}';
// Summoner
export const SUMMONER_BY_NAME = '/{string:region}/v1.4/summoner/by-name/{string:names}';
export const SUMMONER_ID = '/{string:region}/v1.4/summoner/{int:id}';
export const SUMMONER_NAME = '/{string:region}/v1.4/summoner/{int:id}/name';
export const SUMMONER_RUNES = '/{string:region}/v1.4/summoner/{int:id}/runes';
export const SUMMONER_MASTERIES = '/{string:region}/v1.4/summoner/{int:id}/masteries';
// Stats
export const RANKED_STATS = '/{string:region}/v1.3/stats/by-summoner/{int:id}/ranked';
export const STAT_SUMMARY = '/{string:region}/v1.3/stats/by-summoner/{int:id}/summary';
// Static
export const STATIC_CHAMPION = '/static-data/{string:region}/v1.2/champion';
export const STATIC_CHAMPION_ID = '/static-data/{string:region}/v1.2/champion/{int:id}';
export const STATIC_ITEM = '/static-data/{string:region}/v1.2/item';
export const STATIC_ITEM_ID = '/static-data/{string:region}/v1.2/item/{int:id}';
export const STATIC_MASTERY = '/static-data/{string:region}/v1.2/mastery';
export const STATIC_MASTERY_ID = '/static-data/{string:region}/v1.2/mastery/{int:id}';
export const STATIC_REALM = '/static-data/{string:region}/v1.2/realm';
export const STATIC_VERSIONS = '/static-data/{string:region}/v1.2/versions';
export const STATIC_RUNE = '/static-data/{string:region}/v1.2/rune';
export const STATIC_RUNE_ID = '/static-data/{string:region}/v1.2/rune/{int:id}';
export const STATIC_SUMMONER_SPELL = '/static-data/{string:region}/v1.2/summoner-spell';
export const STATIC_SUMMONER_SPELL_ID = '/static-data/{string:region}/v1.2/summoner-spell/{int:id}';
// Status
export const STATUS_SHARD_LIST = '/shards';
export const STATUS_SHARD_ID = '/shards/{string:names}';
// Team
export const TEAM_BY_SUMMONER = '/{string:region}/v2.4/team/by-summoner/{int:id}';
export const TEAM_ID = '/{string:region}/v2.4/team/{string:id}';
export const PLATFORMS = {
br: 'BR1',
na: 'NA1',
lan: 'LA1',
las: 'LA2',
oce: 'OC1',
eune: 'EUN1',
euw: 'EUW1',
tr: 'TR1',
ru: 'RU',
kr: 'KR'
};<file_sep>/src/api/summoner.js
import {SUMMONER_ID, SUMMONER_BY_NAME, SUMMONER_NAME, SUMMONER_RUNES, SUMMONER_MASTERIES} from '../Constants';
export const Summoner = {
get(summonerIds, options = {}) {
return Object.assign({}, options, {
id: summonerIds,
uri: SUMMONER_ID
});
},
getByName(summonerNames, options = {}) {
return Object.assign({}, options, {
uri: SUMMONER_BY_NAME,
names: summonerNames instanceof Array ? summonerNames.join() : summonerNames
});
},
getName(summonerIds, options = {}) {
return Object.assign({}, options, {
id: summonerIds,
uri: SUMMONER_NAME
});
},
getRunes(summonerIds, options = {}) {
return Object.assign({}, options, {
id: summonerIds,
uri: SUMMONER_RUNES
});
},
getMasteries(summonerIds, options = {}) {
return Object.assign({}, options, {
id: summonerIds,
uri: SUMMONER_MASTERIES
});
}
}; | 3aa2cd5f70fd90a2f4dccf60569c2268bc220f30 | [
"JavaScript"
] | 11 | JavaScript | austinsc/riot-data | a8cdb1eb9681e39bd9b49a182568d17b24c8cb88 | 32a6b0577e8f36961239767a3d33e9849ac88272 |
refs/heads/main | <repo_name>aliramazon/move-website-vanilla<file_sep>/js/script.js
const headerElement = document.querySelector("#header");
const navElement = document.querySelector(".nav");
let options = {
root: null,
rootMargin: `-150px`,
threshold: 0
};
function stickyNavigation(entries) {
let ent = entries[0];
if (ent.isIntersecting === false) {
navElement.classList.add("sticky");
}
if (ent.isIntersecting === true) {
navElement.classList.remove("sticky");
}
}
const observer = new IntersectionObserver(stickyNavigation, options);
observer.observe(headerElement);
const menuIcon = document.querySelector("#menu-icon");
const closeIcon = document.querySelector("#close-icon");
const mobileNav = document.querySelector(".mobile-nav");
menuIcon.addEventListener("click", function () {
mobileNav.classList.add("mobile-nav--show");
});
closeIcon.addEventListener("click", function () {
mobileNav.classList.remove("mobile-nav--show");
});
| 77fda6cdd1db91e9c88ba41179f60ae260cd77ca | [
"JavaScript"
] | 1 | JavaScript | aliramazon/move-website-vanilla | a6aed7914f50a13d2e620b60206b6b97820ffb3a | 5f44903056288d8663192351c24b1e8bbb4599dc |
refs/heads/master | <repo_name>League-Level1-Student/level1-module2-josephredivosems<file_sep>/src/_04_tea_maker/TeaMakerRunner.java
package _04_tea_maker;
public class TeaMakerRunner {
public static void main(String[] args) {
TeaBag flavor = new TeaBag(TeaBag.GREEN);
String teaFlavor = flavor.getFlavor();
Kettle kettle = new Kettle();
kettle.boil();
Cup cup = new Cup();
cup.makeTea(flavor, kettle.getWater());
}
}
| a641d11556b367c8fea6f6a0175d7ce2bf9a93ae | [
"Java"
] | 1 | Java | League-Level1-Student/level1-module2-josephredivosems | 543d522b8e82013b32100f4413094e3f435cc3ef | 5770553367ea0f7686122a688db442a3d6be7509 |
refs/heads/main | <file_sep>function openNav() {
document.getElementById("myNav").style.width = "100%";
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
$(document).ready(function(){
var mixer = mixitup('.container');
});<file_sep># Single page portfollio landing page
| 45537c9ce3ba8118438487781bf63049d81a9ba5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ahmedsohel4u/single-page-portfollio-website | 0818c62a74b0a123055d5cd26ea1b53f1a58cea3 | e432e8288b6c20c129d64fb2a1a70287235fd97f |
refs/heads/master | <repo_name>ONESucH/angular-app-vk-api<file_sep>/src/app/shablon-user/shablon-user.pipe.ts
import {Pipe, PipeTransform} from '@angular/core';
import {ShablonUserComponent} from './shablon-user.component';
@Pipe({
name: 'shablonUser',
pure: false
})
export class ShablonUserPipe implements PipeTransform {
transform(items: any[], filter: ShablonUserComponent): any {
if (!items || !filter) {
return items;
}
console.log('items', items);
console.log('ShablonUserComponent', ShablonUserComponent);
return items.filter(item => {
return item.title.indexOf(filter.arr) !== -1;
});
}
}
<file_sep>/src/app/shablon-user/shablon-user.pipe.spec.ts
import { ShablonUserPipe } from './shablon-user.pipe';
describe('ShablonUserPipe', () => {
it('create an instance', () => {
const pipe = new ShablonUserPipe();
expect(pipe).toBeTruthy();
});
});
<file_sep>/src/app/shablon-user/shablon-user.component.ts
import {Component} from '@angular/core';
import {Http} from '@angular/http';
@Component({
selector: 'app-shablon-user',
templateUrl: './shablon-user.component.html',
styleUrls: ['./shablon-user.component.css']
})
export class ShablonUserComponent {
public tokken = '<KEY>';
public url = 'https://api.vk.com/method/users.search?q=&sort=1&offset&count=1000&city1=&country=1&fields=photo_id,verified,sex,bdate,city,country,home_town,photo_100,photo_200,photo_max,online,lists,nickname,occupation,domain,has_mobile,contacts,site,educc&access_token=' + this.tokken + '&v=5.69';
arr: any[];
constructor(private http: Http) {
}
getUsers() {
this.http.get(this.url)
.subscribe(
data => {
/* Парсим в json */
const dataJson = data.json();
/* Рендерим данные */
this.arr = dataJson.response.items;
console.log('this.arr', this.arr);
},
//error => console.log('error'),
//() => console.log('success')
)
}
}
| 2522a87a013ec283dc36048a196b3e541b4fc92a | [
"TypeScript"
] | 3 | TypeScript | ONESucH/angular-app-vk-api | 6259902c174d55d9c22db68044044fffa206a61d | 6c444e1fbc963d9b5a995a9799cffd20e809af7a |
refs/heads/master | <repo_name>mathiasnovas/tap-bpm<file_sep>/README.md
tap-bpm
=======
Tap to find the BPM of a song.
## Want to try it out?
[Check out the demo!](http://mathiasnovas.github.io/tap-bpm)
<file_sep>/js/bpm.js
jQuery(function ($) {
/**
* Assign variables.
*/
var lastClick = 0,
doc = $(document),
count = 0,
canvas = $('#canvas p');
/**
* Various calculations
*
* @type {Object}
*/
var calculate = {
/**
* Return the difference between two values.
*
* It also divides the number by 1000 to convert the output into seconds.
*
* @param {Number} now
* @param {Number} last
* @return {Number}
*/
difference: function (now, last) {
return (now - last) / 1000;
},
/**
* Return the average value of an array
*
* @param {Array} arr
* @return {Number}
*/
average: function (arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
}
/**
* Value pool for "remembering" previous BPMs
*
* @type {Object}
*/
var pool = {
array: [],
/**
* Add value to the pool.
*
* @param {Number} val
*/
add: function (val) {
pool.array.push(val);
},
/**
* Clear the pool.
*/
flush: function () {
pool.array = [];
},
/**
* Advance the array by releasing the oldest value and appending a new one.
*/
advance: function () {
pool.array.shift();
}
}
/**
* Start the BPM mapping when clicking the document or hitting a key.
*
* It will always be 0 the first time you click as two values
* are necessary to calculate the BPM.
*/
doc.on('click keydown touchstart', function () {
var timeNow = (new Date()).getTime(),
bpm = 0;
// We need at least two values to compare.
if (count > 0) {
var difference = calculate.difference(timeNow, lastClick),
rawBpm = 60 / difference;
// Advance the value pool after the 10th click.
if (count > 10) {
pool.advance();
}
pool.add(rawBpm);
// Get the average BPM.
bpm = calculate.average(pool.array).toFixed(2);
}
// Animate "Flash" effect
canvas.stop().animate({
opacity: 0.25
}, 10, function () {
canvas.animate({
opacity: 1
}, 100);
});
// Display the BPM
canvas.html(bpm);
lastClick = timeNow;
count ++;
});
});
| 938e07171e166051a808494e5711e2cec8f8a9e5 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | mathiasnovas/tap-bpm | 3d2c9e2058bc3d70ee7171f6ecf96d0257dd76c9 | 87329198ef09c754470764d917788d964af1ffbf |
refs/heads/master | <file_sep>var x;
var y;
/*기능 ; 영화 주토피아에 나오는 나무늘보 플래시 그리기
x,y : 플래시 얼굴 중심*/
function drawFlash (x,y) {
//Body;
fill(200,255,100);
noStroke();
arc(x,y+170,240,220,radians(180),radians(360) );
//Neck
fill(120,100,0);
noStroke();
quad(x-80,y,x+80,y,x+90,y+100,x-90,y+100);
arc(x,y+100,180,40,radians(0),radians(180) );
//Head
fill(255,232,203);
stroke(120,100,0);
strokeWeight(10);
ellipse(x,y,150,140);
//Eye
stroke(10);
strokeWeight(2);
fill(250);
ellipse(x-40,y-10,45,30);
ellipse(x+40,y-10,45,30);
fill(120,100,0);
noStroke();
arc(x-40,y-10,45,30,radians(180),radians(360) );
arc(x+40,y-10,45,30,radians(180),radians(360) );
fill(50);
ellipse(x-40,y-2,12,12);
ellipse(x+40,y-2,12,12);
//Nose
stroke(10);
strokeWeight(2);
line(x-15,y-45,x-20,y+30);
line(x+15,y-45,x+20,y+30);
fill(120,100,0);
noStroke();
arc( x,y+30,42,50,radians(180),radians(360) );
arc( x,y+30,42,40,radians(0),radians(180) );
//Mouth
fill(200,0,0);
noStroke();
arc( x,y+40,30,15,radians(0),radians(180) );
//Nosehole
fill(50);
ellipse(x-10,y+30,10,5);
ellipse(x+10,y+30,10,5);
//Eyebrow
fill(255,232,203);
stroke(25);
strokeWeight(4);
arc( x-20,y-30,75,30,radians(180),radians(275) );
arc( x+20,y-30,75,30,radians(265),radians(360) );
}
function setup() {
createCanvas(400,400);
background(255);
drawFlash(200,150);
}
function draw(){
} | ee1ba630e90badf3a1900884e999d409a6128ac9 | [
"JavaScript"
] | 1 | JavaScript | seojihye2/004 | 6fa6fcc32b6ec155558bcd9285123d363cfc6055 | d39f0f2a339d6c0a73c0674963466473c98bf993 |
refs/heads/master | <file_sep>using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL;
using DBHelper;
namespace BLL_Tests
{
[TestFixture]
public class BHelperTest
{
[Test]
public void TestMethod()
{
// TODO: Add your test code here
Assert.Pass("Your first passing test");
}
[Test]
public void Test_BHelper()
{
BHelper bHelper = new BHelper(null);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLL;
using DBHelper;
using DBHelper.SQLite;
namespace FileManagement
{
public partial class MainForm : Form
{
private DataSet _dataSource;
private BHelper bHelper;
//数据库是否可用
private bool dbStatus;
public MainForm()
{
InitializeComponent();
bHelper = new BHelper(new SQLiteHelper($"Data Source={tb_DbName.Text};Version=3;"));
}
#region 界面
/// <summary>
/// 显示数据
/// </summary>
private void ShowData()
{
dgvMain.DataSource = _dataSource;
}
private void TextBoxDragEnter(object sender, DragEventArgs e)
{
}
private void TextBoxDragDrop(object sender, DragEventArgs e)
{
}
#endregion
#region 数据库
/// <summary>
/// 查数据
/// </summary>
public void Query()
{
_dataSource = bHelper.Query("", "", "");
}
/// <summary>
/// 插入
/// </summary>
private void Insert()
{
bHelper.Insert("", "", "");
}
/// <summary>
/// 更新
/// </summary>
public void Update()
{
bHelper.Update("", "", "");
}
/// <summary>
/// 删除
/// </summary>
private void Delete()
{
bHelper.Delete("", "");
}
#endregion
private void Preview()
{
}
//连接按钮
private void btn_Connect_Click(object sender, EventArgs e)
{
//SQLite
InitialSQLite(tb_DbName.Text, bHelper);
}
private void InitialSQLite(string dbName, BHelper bHelper)
{
if (!string.IsNullOrEmpty(dbName))
{
if (!File.Exists(dbName))
MessageBox.Show(bHelper.InitialDataBaseAndDataTable(tb_DbName.Text));
}
else
{
MessageBox.Show("初始化数据库失败");
dbStatus = false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DBHelper;
namespace BLL
{
public class BHelper
{
private IDBHelper _dBHelper;
public IDBHelper DbHelper
{
get { return _dBHelper; }
set { _dBHelper = value; }
}
//无参构造
public BHelper()
{
}
/// <summary>
/// 实例化
/// </summary>
/// <param name="dBHelper">IDBHelper,用来初始化属性DbHelper, 为NULL时抛ArgumentNullException异常</param>
public BHelper(IDBHelper dBHelper)
{
if (dBHelper != null)
DbHelper = dBHelper;
else
throw new ArgumentNullException();
}
/// <summary>
/// 初始化数据库和数据表
/// </summary>
/// <param name="dbName">数据库名(包含绝对路径)</param>
public string InitialDataBaseAndDataTable(string dbName)
{
string message = "";
bool result = DbHelper.CreateDataBase(dbName, ref message);
if (result)
{
if (!CreateDataTable("tb_FileManagement", "", ref message))
return message;
return "OK!";
}
return message;
}
/// <summary>
/// 创建数据表
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="columns">字段名及格式描述</param>
public bool CreateDataTable(string tbName, string columns, ref string message)
{
bool result = DbHelper.CreateDataTable(tbName, columns, ref message);
//MessageBox.Show(message);
return result;
}
/// <summary>
/// 查询
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="fileds">要查询的所有字段</param>
/// <param name="condition">指定where条件(需要where)</param>
/// <returns></returns>
public DataSet Query(string tbName, string fileds, string condition)
{
string sql = $"select {fileds} from {tbName} {condition}";
return DbHelper.Query(sql);
}
/// <summary>
/// 插入
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="fileds">字段</param>
/// <param name="values">值</param>
/// <returns></returns>
public int Insert(string tbName, string fileds, string values)
{
string sql = $"insert into {tbName} ({fileds}) values({values})";
return DbHelper.ExcuteSQL(sql);
}
/// <summary>
/// 更新
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="fileds">字段及字段值</param>
/// <param name="condition">指定where条件(需要where关键字)</param>
/// <returns></returns>
public int Update(string tbName, string fileds, string condition)
{
string sql = $"update {tbName} set {fileds} {condition}";
return DbHelper.ExcuteSQL(sql);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="condition">指定where条件(不需要where关键字)</param>
/// <returns></returns>
public int Delete(string tbName, string condition)
{
if (!string.IsNullOrEmpty(condition))
{
string sql = $"delete from {tbName} where {condition}";
return DbHelper.ExcuteSQL(sql);
}
return 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBHelper
{
public interface IDBHelper
{
/// <summary>
/// 创建一个空数据库文件
/// </summary>
/// <param name="dbName">文件名称</param>
/// <returns>创建结果</returns>
bool CreateDataBase(string dbName, ref string message);
/// <summary>
/// 在指定数据库中创建数据表
/// </summary>
/// <param name="dbName">指定数据库</param>
/// <param name="tbName">数据表名</param>
/// <param name="columns">表中字段</param>
/// <returns>创建结果</returns>
bool CreateDataTable(string tbName, string columns, ref string message);
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="sql">查询语句</param>
/// <returns>DataSet</returns>
DataSet Query(string sql);
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="sql">SQL语句</param>
/// <returns>影响的记录数</returns>
int ExcuteSQL(string sql);
/// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="sqls">多条SQL语句</param>
/// <returns>是否执行成功</returns>
bool DoTransaction(string[] sqls);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace DBHelper.SQLite
{
public class SQLiteHelper : IDBHelper
{
private readonly string CONNECTIONSTRING;
public SQLiteHelper(string conStr)
{
CONNECTIONSTRING = conStr;
}
public bool CreateDataBase(string dbName, ref string message)
{
try
{
SQLiteConnection.CreateFile(dbName);
message = $"成功创建数据库文件{dbName}。";
return true;
//return $"成功创建数据库文件{dbName}。";
}
catch (Exception e)
{
message = e.ToString();
return false;
}
}
public bool CreateDataTable(string tbName, string columns, ref string message)
{
string sql = $"create table {tbName} ({columns})";
using (SQLiteConnection conn = new SQLiteConnection(CONNECTIONSTRING))
{
try
{
SQLiteCommand comm = new SQLiteCommand(sql, conn);
comm.ExecuteNonQuery();
message = $"成功创建数据表{tbName}。";
return true;
}
catch (Exception e)
{
message = e.ToString();
return false;
}
}
}
public DataSet Query(string sql)
{
using (SQLiteConnection connection = new SQLiteConnection(CONNECTIONSTRING))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SQLiteDataAdapter command = new SQLiteDataAdapter(sql, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SQLite.SQLiteException ex)
{
//throw new Exception(ex.Message);
return null;
}
return ds;
}
}
public int ExcuteSQL(string sql)
{
using (SQLiteConnection connection = new SQLiteConnection(CONNECTIONSTRING))
{
using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
connection.Close();
//throw new Exception(E.Message);
return 0;
}
}
}
}
public bool DoTransaction(string[] sqls)
{
using (SQLiteConnection conn = new SQLiteConnection(CONNECTIONSTRING))
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
SQLiteTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < sqls.Length; n++)
{
string strsql = sqls[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
return true;
}
catch (System.Data.SQLite.SQLiteException E)
{
tx.Rollback();
//throw new Exception(E.Message);
return false;
}
}
}
}
}
| 96a5913351e35956a58b256fe2787e62d9e3d753 | [
"C#"
] | 5 | C# | liang8892/FileManagement | 26d0560689ab3e1eb1225a0a7353e8bec4b6eb90 | f5f7824219ea3aa3ebbe2e2ac14ed18548524dab |
refs/heads/master | <file_sep><main class="page__main page__main--messages">
<h1 class="visually-hidden">Личные сообщения</h1>
<section class="messages tabs">
<h2 class="visually-hidden">Сообщения</h2>
<div class="messages__contacts">
<ul class="messages__contacts-list tabs__list">
<?php foreach ($user_list as $user) : ?>
<li class="messages__contacts-item<!-- messages__contacts-item--new-->">
<a class="messages__contacts-tab tabs__item<?php if ($id === $user['id']) :
?> messages__contacts-tab--active tabs__item tabs__item--active <?php
endif; ?>" href="/messages.php?id=<?=$user['id']; ?>">
<div class="messages__avatar-wrapper">
<img class="messages__avatar" src="img/<?=$user['avatar_img']; ?>" alt="Аватар пользователя">
<!--<i class="messages__indicator">2</i>-->
</div>
<div class="messages__info">
<span class="messages__contact-name">
<?=$user['name'];?>
</span>
<div class="messages__preview">
<p class="messages__preview-text">
<?=cut_string($user['content'], 18, true); ?>
</p>
<time class="messages__preview-time" datetime="<?=$user['pulished_at']; ?>">
<?=date('H:i', strtotime($user['published_at'])); ?>
</time>
</div>
</div>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="messages__chat">
<?php if ($messages) : ?>
<div class="messages__chat-wrapper">
<ul class="messages__list tabs__content tabs__content--active">
<?php foreach ($messages as $message) : ?>
<li class="messages__item<?php if ($auth_user['id'] === $message['from_user_id']) :
?> messages__item--my<?php
endif; ?>">
<div class="messages__info-wrapper">
<div class="messages__item-avatar">
<a class="messages__author-link" href="/profile.php?id=<?=$message['id']; ?>">
<img class="messages__avatar" src="img/<?=$message['avatar_img']; ?>" alt="Аватар пользователя">
</a>
</div>
<div class="messages__item-info">
<a class="messages__author" href="/profile.php?id=<?=$message['id']; ?>">
<?=$message['name']; ?>
</a>
<time class="messages__time" datetime="<?=$message['published_at']; ?>">
<?=make_datetime_relative($message['published_at']); ?>
</time>
</div>
</div>
<p class="messages__text">
<?=$message['content']; ?>
</p>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php if ($user_list) : ?>
<div class="comments">
<form class="comments__form form" action="/messages.php?<?=http_build_query(['id' => $id]); ?>" method="post">
<div class="comments__my-avatar">
<img class="comments__picture" src="img/<?=$auth_user['avatar_img']; ?>" alt="Аватар пользователя">
</div>
<div class="form__input-section<?php if ($errors) :
?> form__input-section--error<?php
endif; ?>">
<textarea class="comments__textarea form__textarea form__input" name="text"
placeholder="Ваше сообщение"><?=$content; ?></textarea>
<label class="visually-hidden">Ваше сообщение</label>
<button class="form__error-button button" type="button">!</button>
<div class="form__error-text">
<h3 class="form__error-title">Ошибка валидации</h3>
<p class="form__error-desc"><?=$errors['text']; ?></p>
</div>
</div>
<button class="comments__submit button button--green" type="submit">Отправить</button>
</form>
</div>
<?php endif; ?>
</div>
</section>
</main><file_sep><?php
if (file_exists('local_config.php')) {
require_once('local_config.php');
} else {
echo("Файл не существует");
}
$transport_username = $mailtrap_username ?? '<EMAIL>';
$transport_password = $mailtrap_password ?? '<PASSWORD>';
$localhost = $local_host ?? '127.0.0.1';
$db_user = $db_local_user ?? 'root';
$db_password = $db_local_password ?? '<PASSWORD>';
$db_session = $db_local_session ?? 'readme';
<file_sep><?php
require_once('helpers.php');
require_once('init.php');
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
} else {
$id = null;
}
if ($id) {
$check_post_id = mysqli_num_rows(mysqli_query($db_link, "SELECT id FROM posts WHERE id = $id"));
$user_id = $user['id'];
$like_exist = mysqli_num_rows(
mysqli_query(
$db_link,
"SELECT id
FROM likes
WHERE user_id = $user_id AND post_id = $id;"
)
);
if ($check_post_id && !$like_exist) {
$like = [$user['id'], $id];
$sql = "INSERT INTO likes (user_id, post_id) VALUES (?, ?);";
$stmt = db_get_prepare_stmt($db_link, $sql, $like);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
}
header("Location: " . $_SERVER["HTTP_REFERER"]);
exit();
}
<file_sep><section class="page__main page__main--popular">
<div class="container">
<h1 class="page__title page__title--popular">Популярное</h1>
</div>
<div class="popular container">
<div class="popular__filters-wrapper">
<div class="popular__sorting sorting">
<b class="popular__sorting-caption sorting__caption">Сортировка:</b>
<ul class="popular__sorting-list sorting__list">
<?php foreach ($sort_types as $sort_type) : ?>
<li class="sorting__item">
<a class="sorting__link<?php if ($sort === $sort_type['id']) :
?> sorting__link--active <?php
endif; ?>"
href="/popular.php?<?=http_build_query(array_merge($_GET, [ 'order_by' => $sort_type['id'] ])); ?>">
<span><?=$sort_type['title']; ?></span>
<svg class="sorting__icon" width="10" height="12">
<use xlink:href="#icon-sort"></use>
</svg>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="popular__filters filters">
<b class="popular__filters-caption filters__caption">Тип контента:</b>
<ul class="popular__filters-list filters__list">
<li class="popular__filters-item popular__filters-item--all filters__item filters__item--all">
<a class="filters__button filters__button--ellipse filters__button--all
<?= is_null($id)? 'filters__button--active' : '' ?>"
href="/popular.php?<?=http_build_query(array_merge($_GET, ['id' => null])); ?>">
<span>Все</span>
</a>
</li>
<?php foreach ($post_types as $types) : ?>
<li class="popular__filters-item filters__item">
<a class="filters__button filters__button--<?=$types['icon_class']; ?> button
<?php if ($id === $types['id']) :
?> filters__button--active <?php
endif; ?>"
href="/popular.php?<?=http_build_query(array_merge($_GET, [ 'id' => $types['id'] ])); ?>">
<span class="visually-hidden"><?=$types['type_name']; ?></span>
<svg class="filters__icon" width="22" height="18">
<use xlink:href="#icon-filter-<?=$types['icon_class']; ?>"></use>
</svg>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
<div class="popular__posts">
<?php foreach ($posts as $post) : ?>
<article class="popular__post post <?='post-' . $post['class']; ?>">
<header class="post__header">
<h2><a href="/post.php?id=<?=$post['id']; ?>"><?=$post['title']; ?></a></h2>
</header>
<div class="post__main">
<?php if ($post['type'] === "Цитата") : ?>
<blockquote>
<p>
<!--здесь текст-->
<?=$post['content']; ?>
</p>
<cite><?=$post['author']; ?></cite>
</blockquote>
<?php endif; ?>
<?php if ($post['type'] === "Ссылка") : ?>
<div class="post-link__wrapper">
<a class="post-link__external" href="http://<?=$post['link']; ?>" title="Перейти по ссылке">
<div class="post-link__info-wrapper">
<div class="post-link__icon-wrapper">
<img src="https://www.google.com/s2/favicons?domain=vitadental.ru" alt="Иконка">
</div>
<div class="post-link__info">
<h3><?=$post['title']; ?><!--здесь заголовок--></h3>
</div>
</div>
<span><?=$post['link']; ?><!--здесь ссылка--></span>
</a>
</div>
<?php endif; ?>
<?php if ($post['type'] === "Картинка") : ?>
<div class="post-photo__image-wrapper">
<img src="uploads/<?=$post['img']; ?>" alt="Фото от пользователя" width="360" height="240">
</div>
<?php endif; ?>
<?php if ($post['type'] === "Видео") : ?>
<div class="post-video__block">
<div class="post-video__preview">
<?=embed_youtube_cover($post['video']); ?>
<img src="" alt="Превью к видео" width="360" height="188">
</div>
<a href="post-details.html" class="post-video__play-big button">
<svg class="post-video__play-big-icon" width="14" height="14">
<use xlink:href="#icon-video-play-big"></use>
</svg>
<span class="visually-hidden">Запустить проигрыватель</span>
</a>
</div>
<?php endif; ?>
<?php if ($post['type'] === "Текст") : ?>
<?=cut_string($post['content']); ?><!--здесь текст-->
<?php endif; ?>
</div>
<footer class="post__footer">
<div class="post__author">
<a class="post__author-link" href="/profile.php?id=<?=$post['user_id']; ?>" title="Автор">
<div class="post__avatar-wrapper">
<!--укажите путь к файлу аватара-->
<img class="post__author-avatar" src="img/<?=$post['avatar']; ?>" alt="Аватар пользователя">
</div>
<div class="post__info">
<b class="post__author-name"><?=$post['name']; ?><!--здесь имя пользоателя--></b>
<time class="post__time" datetime="<?=$post['published_at']; ?>" title="<?=date("d.m.Y H:i", strtotime($post['published_at'])); ?>">
<?=make_datetime_relative($post['published_at']); ?>
</time>
</div>
</a>
</div>
<div class="post__indicators">
<div class="post__buttons">
<a class="post__indicator post__indicator--likes button" href="/like.php?id=<?=$post['id']; ?>" title="Лайк">
<svg class="post__indicator-icon" width="20" height="17">
<use xlink:href="#icon-heart"></use>
</svg>
<svg class="post__indicator-icon post__indicator-icon--like-active" width="20" height="17">
<use xlink:href="#icon-heart-active"></use>
</svg>
<span><?=$post['likes']; ?></span>
<span class="visually-hidden">количество лайков</span>
</a>
<a class="post__indicator post__indicator--comments button" href="#" title="Комментарии">
<svg class="post__indicator-icon" width="19" height="17">
<use xlink:href="#icon-comment"></use>
</svg>
<span><?=$post['comments']; ?></span>
<span class="visually-hidden">количество комментариев</span>
</a>
</div>
</div>
</footer>
</article>
<?php endforeach; ?>
</div>
<?php if ($pages_count > 1) : ?>
<div class="popular__page-links">
<a class="popular__page-link popular__page-link--prev button button--gray" href="/popular.php?<?=http_build_query(array_merge($_GET, ['page' => $current_page - 1])); ?>">Предыдущая страница</a>
<a class="popular__page-link popular__page-link--next button button--gray" href="/popular.php?<?=http_build_query(array_merge($_GET, ['page' => $current_page + 1])); ?>">Следующая страница</a>
</div>
<?php endif; ?>
</div>
</section><file_sep><?php
require_once('helpers.php');
require_once('init.php');
require_once('mail.php');
$add_form = false;
$tabs = [
[
'tab' => 'posts',
'title' => 'Посты'
],
[
'tab' => 'likes',
'title' => 'Лайки'
],
[
'tab' => 'subscriptions',
'title' => 'Подписки'
]
];
$id = 0;
$content = [];
$user_subscriptions = [];
$user_profile = [];
$subs = [];
$is_subscribe = 0;
$tab = 'posts';
if (isset($_GET['tab'])) {
$tab = filter_input(INPUT_GET, 'tab', FILTER_DEFAULT);
}
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
} else {
$id = null;
}
if ($id) {
if (mysqli_num_rows(mysqli_query($db_link, "SELECT id FROM users WHERE id = $id;"))) {
$user_profile = make_select_query(
$db_link,
"SELECT u.id, u.name, u.avatar_img, u.created_at, COUNT(DISTINCT p.id) AS posts_count,
COUNT(DISTINCT s.id) AS subs
FROM users u JOIN posts p ON u.id = p.user_id
LEFT JOIN subscriptions s ON u.id = s.to_user_id
WHERE u.id = $id
GROUP BY u.id",
true
);
$subs = make_select_query(
$db_link,
"SELECT COUNT(s.id) AS subs
FROM users u JOIN subscriptions s ON u.id = s.to_user_id
WHERE u.id = $id
GROUP BY u.id",
true
);
$user_id = $user['id'];
$is_subscribe = mysqli_num_rows(mysqli_query($db_link, "SELECT id FROM subscriptions
WHERE user_id = $user_id AND to_user_id = $id"));
switch ($tab) {
case 'likes':
$content = make_select_query(
$db_link,
"SELECT DISTINCT us.id AS user_id, us.name, us.avatar_img, pt.id AS post_id, pt.img,
tp.icon_class AS type, l.created_at
FROM users us, posts pt JOIN types tp ON pt.post_type = tp.id
JOIN likes l ON pt.id = l.post_id
WHERE (us.id, pt.id) IN (SELECT u.id, p.id
FROM likes l JOIN users u ON l.user_id = u.id
JOIN posts p ON p.id = l.post_id)
AND pt.id IN (SELECT id FROM posts WHERE user_id = $id)
ORDER BY created_at DESC;"
);
break;
case 'subscriptions':
$content = make_select_query(
$db_link,
"SELECT u.id, u.name, u.avatar_img, u.created_at, COUNT(DISTINCT p.id) AS posts_count,
COUNT(DISTINCT s.id) AS subs
FROM users u JOIN posts p ON u.id = p.user_id
LEFT JOIN subscriptions s ON u.id = s.to_user_id
WHERE u.id IN (SELECT user_id FROM subscriptions WHERE to_user_id = $id)
GROUP BY u.id;"
);
$user_subscriptions = array_column(make_select_query(
$db_link,
"SELECT to_user_id FROM subscriptions WHERE user_id = $user_id;"
), 'to_user_id');
break;
default:
$content = make_select_query(
$db_link,
"SELECT p.*, name, avatar_img AS avatar, type_name AS type, icon_class AS class,
COUNT(DISTINCT c.id) AS comments, COUNT(DISTINCT l.id) AS likes
FROM posts p
JOIN users us ON p.user_id = us.id
JOIN types tp ON p.post_type = tp.id
LEFT JOIN comments c ON p.id = c.post_id
LEFT JOIN likes l ON l.post_id = p.id
WHERE us.id = $id
GROUP BY p.id"
);
}
} else {
header("Location: /feed.php");
exit();
}
}
$tab_content = include_template('profile-' . $tab . '.php', [
'content' => filter_posts($content),
'user_subscriptions' => $user_subscriptions,
'user' => $user
]);
$page_content = include_template('profile-main.php', [
'content' => $tab_content,
'user_profile' => filter_post($user_profile),
'subs' => filter_post($subs),
'is_subscribe' => $is_subscribe,
'tab' => $tab,
'tabs' => $tabs,
'user' => $user
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'title' => 'readme: профиль',
'user' => $user,
'header_my_nav' => $header_my_nav,
'is_auth' => $is_auth,
'add_form' => $add_form
]);
print($layout_content);
<file_sep><?php
require_once('helpers.php');
require_once('default-config.php');
$is_auth = 0;
$errors = [];
$db_link = mysqli_connect($localhost, $db_user, $db_password, $db_session);
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$required_fields = ['email', 'login', 'password', 'password-repeat'];
$post = $_POST;
foreach ($required_fields as $field) {
$result = validateFilled($post[$field], $field);
if ($result) {
$errors[$field] = $result;
}
}
if (isset($post['email']) && !empty($post['email'])) {
if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'email. Неверный формат электронной почты.';
}
}
if (empty($errors)) {
$user_fields = ['login', 'password', 'email'];
$img_key = '';
$img_value = '';
$email = mysqli_real_escape_string($db_link, $post['email']);
$email_check = make_select_query($db_link, "SELECT id FROM users WHERE email = '$email'", true);
$login = mysqli_real_escape_string($db_link, $post['login']);
$login_check = make_select_query($db_link, "SELECT id FROM users WHERE name = '$login'", true);
if ($email_check) {
$errors['email'] = 'Пользователь с таким email уже зарегистрирован.';
} elseif ($login_check) {
$errors['login'] = 'Пользователь с таким логином уже зарегистрирован.';
} elseif ($post['password'] !== $post['password-repeat']) {
$errors['password'] = '<PASSWORD> не совпадают.';
$errors['password-repeat'] = 'Пароли не совпадают.';
} else {
if (!empty($_FILES['userpic-file']['name'])) {
$tmp_name = $_FILES['userpic-file']['tmp_name'];
$img_name = $_FILES['userpic-file']['name'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file_type = finfo_file($finfo, $tmp_name);
$valid_type = validateFileType($file_type, ['image/png', 'image/jpeg', 'image/gif']);
if (!$valid_type) {
move_uploaded_file($tmp_name, 'img/' . $img_name);
$post['avatar_img'] = $img_name;
$img_key = ', avatar_img';
$img_value = ', ?';
$user_fields[3] = 'avatar_img';
} else {
$errors['file'] = $valid_type;
}
}
if (empty($errors)) {
$password = password_hash($post['password'], PASSWORD_DEFAULT);
$post['password'] = $password;
$post = fillArray($post, $user_fields);
$sql = 'INSERT INTO users (name, password, email' . $img_key . ') VALUES (?, ?, ?' . $img_value . ');';
$stmt = db_get_prepare_stmt($db_link, $sql, $post);
$result = mysqli_stmt_execute($stmt);
if ($result) {
$user_id = mysqli_insert_id($db_link);
header("Location: /index.php");
} else {
print("Ошибка запроса: " . mysqli_error($db_link));
}
}
}
}
}
$page_content = include_template('reg-main.php', [
'errors' =>$errors
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'title' => 'readme: регистрация',
'is_login' => false
]);
print($layout_content);
<file_sep><?php
/**
* Создает подготовленное выражение на основе готового SQL запроса и переданных данных
*
* @param $link mysqli Ресурс соединения
* @param $sql string SQL запрос с плейсхолдерами вместо значений
* @param array $data Данные для вставки на место плейсхолдеров
*
* @return mysqli_stmt Подготовленное выражение
*/
function db_get_prepare_stmt($link, $sql, $data = [])
{
$stmt = mysqli_prepare($link, $sql);
if ($stmt === false) {
$errorMsg = 'Не удалось инициализировать подготовленное выражение: ' . mysqli_error($link);
die($errorMsg);
}
if ($data) {
$types = '';
$stmt_data = [];
foreach ($data as $value) {
$type = 's';
if (is_int($value)) {
$type = 'i';
} else {
if (is_string($value)) {
$type = 's';
} else {
if (is_double($value)) {
$type = 'd';
}
}
}
if ($type) {
$types .= $type;
$stmt_data[] = $value;
}
}
$values = array_merge([$stmt, $types], $stmt_data);
$func = 'mysqli_stmt_bind_param';
$func(...$values);
if (mysqli_errno($link) > 0) {
$errorMsg = 'Не удалось связать подготовленное выражение с параметрами: ' . mysqli_error($link);
die($errorMsg);
}
}
return $stmt;
}
/**
* Возвращает корректную форму множественного числа
* Ограничения: только для целых чисел
*
* Пример использования:
* $remaining_minutes = 5;
* echo "Я поставил таймер на {$remaining_minutes} " .
* get_noun_plural_form(
* $remaining_minutes,
* 'минута',
* 'минуты',
* 'минут'
* );
* Результат: "Я поставил таймер на 5 минут"
*
* @param int $number Число, по которому вычисляем форму множественного числа
* @param string $one Форма единственного числа: яблоко, час, минута
* @param string $two Форма множественного числа для 2, 3, 4: яблока, часа, минуты
* @param string $many Форма множественного числа для остальных чисел
*
* @return string Рассчитанная форма множественнго числа
*/
function get_noun_plural_form(int $number, string $one, string $two, string $many): string
{
$number = (int)$number;
$mod10 = $number % 10;
$mod100 = $number % 100;
switch (true) {
case ($mod100 >= 11 && $mod100 <= 20):
return $many;
case ($mod10 > 5):
return $many;
case ($mod10 === 1):
return $one;
case ($mod10 >= 2 && $mod10 <= 4):
return $two;
default:
return $many;
}
}
/**
* Подключает шаблон, передает туда данные и возвращает итоговый HTML контент
* @param string $name Путь к файлу шаблона относительно папки templates
* @param array $data Ассоциативный массив с данными для шаблона
* @return string Итоговый HTML
*/
function include_template($name, array $data = [])
{
$name = 'templates/' . $name;
$result = '';
if (!is_readable($name)) {
return $result;
}
ob_start();
extract($data);
require $name;
$result = ob_get_clean();
return $result;
}
/**
* Функция проверяет доступно ли видео по ссылке на youtube
* @param string $url ссылка на видео
*
* @return string Ошибку если валидация не прошла
*/
function check_youtube_url($url)
{
$id = extract_youtube_id($url);
set_error_handler(function () {
}, E_WARNING);
$headers = get_headers('https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=' . $id);
restore_error_handler();
if (!is_array($headers)) {
return "Видео по такой ссылке не найдено. Проверьте ссылку на видео";
}
$err_flag = strpos($headers[0], '200') ? 200 : 404;
if ($err_flag !== 200) {
return "Видео по такой ссылке не найдено. Проверьте ссылку на видео";
}
return true;
}
/**
* Возвращает код iframe для вставки youtube видео на страницу
* @param string $youtube_url Ссылка на youtube видео
* @return string
*/
function embed_youtube_video($youtube_url)
{
$res = "";
$id = extract_youtube_id($youtube_url);
if ($id) {
$src = "https://www.youtube.com/embed/" . $id;
$res = '<iframe width="760" height="400" src="' . $src . '" frameborder="0"></iframe>';
}
return $res;
}
/**
* Возвращает img-тег с обложкой видео для вставки на страницу
* @param string $youtube_url Ссылка на youtube видео
* @return string
*/
function embed_youtube_cover($youtube_url)
{
$res = "";
$id = extract_youtube_id($youtube_url);
if ($id) {
$src = sprintf("https://img.youtube.com/vi/%s/mqdefault.jpg", $id);
$res = '<img alt="youtube cover" width="320" height="120" src="' . $src . '" />';
}
return $res;
}
/**
* Извлекает из ссылки на youtube видео его уникальный ID
* @param string $youtube_url Ссылка на youtube видео
* @return array
*/
function extract_youtube_id($youtube_url)
{
$id = false;
$parts = parse_url($youtube_url);
if ($parts) {
if ($parts['path'] == '/watch') {
parse_str($parts['query'], $vars);
$id = $vars['v'] ?? null;
} else {
if ($parts['host'] == 'youtu.be') {
$id = substr($parts['path'], 1);
}
}
}
return $id;
}
/**
* @param $index
* @return false|string
*/
function generate_random_date($index)
{
$deltas = [['minutes' => 59], ['hours' => 23], ['days' => 6], ['weeks' => 4], ['months' => 11]];
$dcnt = count($deltas);
if ($index < 0) {
$index = 0;
}
if ($index >= $dcnt) {
$index = $dcnt - 1;
}
$delta = $deltas[$index];
$timeval = rand(1, current($delta));
$timename = key($delta);
$ts = strtotime("$timeval $timename ago");
$dt = date('Y-m-d H:i:s', $ts);
return $dt;
}
/**
* Функция обрезает длинну строки и возвращает итоговый HTML абзац
* @param string $string входящая строка
* @param int $length максимальная длинна строки для обрезки, по умолчанию 300 символов
* @param boolean $is_simple проверяет необходимость добавления абзаца и кнопки продолжения, по умолчанию false
* @return string итоговый HTML абзац
*/
function cut_string($string, $length = 300, $is_simple = false)
{
$words = explode(" ", $string);
$tail = '<a class="post-text__more-link" href="#">Читать далее</a>';
$result_string = '';
if (mb_strlen($string) > $length) {
$i = 0;
$current_length = -1;
$result_array = [];
do {
$current_length += mb_strlen($words[$i]) + 1;
if ($current_length < $length) {
array_push($result_array, $words[$i]);
}
$i++;
} while ($current_length < $length);
$result_string .= rtrim(implode(" ", $result_array), " .,?!:;") . '...';
$is_cut = true;
} else {
$result_string = $string;
}
if ($is_simple) {
return $result_string;
}
if ($is_cut) {
return "<p>$result_string</p> $tail";
}
return "<p>$result_string</p>";
}
/**
* Фунуция фильтрует пользовательский архив с постами заменяя HTML-теги на HTML-мнемоники
* @param array $posts массив с пользавательскими постами
* @return array массив с отфильтрованными данными или пустой архив
*/
function filter_posts($posts)
{
$new_posts = [];
if ($posts) {
foreach ($posts as $post) {
$new_post = filter_post($post);
array_push($new_posts, $new_post);
}
}
return $new_posts;
}
/**
* Функция фильтрует одиночный пост заменяя HTML-теги на HTML-мнемоники
* @param array $post массив с постом
* @return array массив с отфильтрованными данными или пустой архив
*/
function filter_post($post)
{
$new_post = [];
if ($post) {
foreach ($post as $key => $string) {
if (is_string($string)) {
$new_post[$key] = htmlspecialchars($string);
} else {
$new_post[$key] = $string;
}
}
}
return $new_post;
}
/**
* Функция добавляет дату к постам пользователей
* @param array &$posts ссылки на массив с постами пользователей
*/
function add_time_to_post(&$posts)
{
foreach ($posts as $key => &$post) {
$post['datetime'] = generate_random_date($key);
}
}
/**
* Функция преобразовывает дату в относительный формат.
* Заменяет дату на сообщение сколько времени назад произошло событие
* @param string $datetime входящая дата
* @param string $end_string окончание сообщения о времени, по умолчанию = назад
* @return string результирующая строка сообщения
*/
function make_datetime_relative($datetime, $end_string = " назад")
{
$ts_input = strtotime($datetime);
$ts_now = time();
$count_minutes = ceil(($ts_now - $ts_input) / 60);
$string = "";
$count = 0;
switch ($count_minutes) {
case $count_minutes < 60:
$count = $count_minutes;
$string = $count . get_noun_plural_form($count, " минута", " минуты", " минут");
break;
case $count_minutes < 60 * 24:
$count = ceil($count_minutes / 60);
$string = $count . get_noun_plural_form($count, " час", " часа", " часов");
break;
case $count_minutes < 60 * 24 * 7:
$count = ceil($count_minutes / 60 / 24);
$string = $count . get_noun_plural_form($count, " день", " дня", " дней");
break;
case $count_minutes < 60 * 24 * 7 * 5:
$count = ceil($count_minutes / 60 / 24 / 7);
$string = $count . get_noun_plural_form($count, " неделя", " недели", " недель");
break;
case $count_minutes < 60 * 24 * 365:
$count = ceil($count_minutes / 60 / 24 / 31);
$string = $count . get_noun_plural_form($count, " месяц", " месяца", " месяцев");
break;
default:
$count = ceil($count_minutes / 60 / 24 / 365);
$string = $count . get_noun_plural_form($count, " год", " года", " лет");
}
$string .= $end_string;
return $string;
}
/**
* Функция выполняет запрос SELECT и возвращает из базы готовый массив с запрошенными данными
* @param mysqli $db_link подключение к базе данных
* @param string $sql строка запроса на выборку данных
* @param boolean $one параметр определяет возвращаемый результат двумерный массив или просто массив с данными,
* по умолчанию false
* @return array готовый массив с данными
*/
function make_select_query($db_link, $sql, $one = false)
{
$result = mysqli_query($db_link, $sql);
if ($result) {
if ($one) {
return mysqli_fetch_assoc($result);
}
return mysqli_fetch_all($result, MYSQLI_ASSOC);
}
print("Ошибка запроса: " . mysqli_error($db_link));
}
/**
* Функция возвращает значение поля формы после отправки
* @param string $name имя поля формы
* @return string значение поля формы
*/
function getPostVal($name)
{
return filter_input(INPUT_POST, $name);
}
/**
* Функция проверяет заполнено ли поле формы
* @param string $value содержимое поля формы
* @param string $title название поля формы
* @return string сообщение об ошибке или null если поле заполнено
*/
function validateFilled($value, $title)
{
if (empty($value)) {
return $title . ". Это поле должно быть заполнено.";
}
return null;
}
/**
* Функция проверяет длину текстового поля на превышение максимального значения
* @param string $value содержимое поля формы
* @param int $max максимально допустимое значение длины поля
* @param string $title название поля формы
* @return string сообщение об ошибке или null если ошибок нет
*/
function validateFilledLength($value, $max, $title)
{
$notEmpty = validateFilled($value, $title);
if (!$notEmpty) {
$length = mb_strlen($value);
if ($length > $max) {
return "Текст не должен превышать " . $max . " знаков.";
}
return null;
}
return $notEmpty;
}
/**
* Функция проверяет правильность ссылки
* @param string $value содержимое поля формы
* @param string $title название поля формы
* @param boolean $video указатель на ссылку с Youtube, по умолчанию false
* @return string сообщение об ошибке или null если ошибок нет
*/
function validateUrl($value, $title, $video = false)
{
$notEmpty = validateFilled($value, $title);
if (!$notEmpty) {
if (!filter_var($value, FILTER_VALIDATE_URL)) {
return "Введен некорректный URL.";
} elseif (!$video && !check_youtube_url($value)) {
return "Видео не существует!";
}
return null;
}
return $notEmpty;
}
/**
* Функция возвращает тип файла
* @param string $file файл у которого проверяется тип
* @return string тип файла
*/
function getFileType($file)
{
return image_type_to_mime_type(exif_imagetype($file));
}
/**
* Функция проверки соответствия типов файла
* @param string $file_type тип файла
* @param array $available_types массив с допустимыми типами файлов
* @return string возвращает ошибку если тип файла не соответствует допустимым типам, иначе возвращает null
*/
function validateFileType($file_type, $available_types)
{
if (in_array($file_type, $available_types)) {
return null;
}
return "Неверный формат файла. Файл может быть PNG, JPEG или GIF.";
}
/**
* Функция заполнения полей поста для запроса
* @param array $post входящий массив с данными поста
* @param array $fields список полей базы данных постов
* @return array заполненный массив поста
*/
function fillArray($post, $fields)
{
$result = [];
foreach ($fields as $key => $field) {
if (isset($post[$field])) {
$result[$field] = $post[$field];
} else {
$result[$field] = null;
}
}
return $result;
}
/**
* Функция проверяет теги на соответствие формату допустимых символов
* @param array $tags входящий массив с тегами
* @return string возвращает ошибку или null если все в порядке
*/
function validate_tags($tags)
{
foreach ($tags as $key => $value) {
if (!preg_match('/^[a-zа-яё0-9_-]+$/ui', $value)) {
return "Неверный формат тегов";
}
}
return null;
}
<file_sep><?php
require_once('helpers.php');
require_once('init.php');
$add_form = false;
$posts = [];
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
$search = $_GET['query'] ?? '';
if ($search) {
$search = trim($search);
$is_tag = substr($search, 0, 1);
if ($is_tag === '#') {
$tag_name = substr($search, 1, strlen($search) - 1);
$tag_name = mysqli_real_escape_string($db_link, $tag_name);
$posts = make_select_query(
$db_link,
"SELECT p.*, name, avatar_img AS avatar, type_name AS type, icon_class AS class,
COUNT(c.id) AS comments, COUNT(l.id) AS likes
FROM posts p
JOIN users us ON p.user_id = us.id
JOIN types tp ON p.post_type = tp.id
LEFT JOIN comments c ON p.id = c.post_id
LEFT JOIN likes l ON l.post_id = p.id
WHERE p.id IN (SELECT post_id FROM posts_hashtags ph JOIN hashtags h ON ph.hash_id = h.id
WHERE hash_name = '$tag_name')
GROUP BY p.id ORDER BY published_at"
);
} else {
$sql = "SELECT p.*, name, avatar_img AS avatar, type_name AS type, icon_class AS class,
COUNT(c.id) AS comments, COUNT(l.id) AS likes
FROM posts p
JOIN users us ON p.user_id = us.id
JOIN types tp ON p.post_type = tp.id
LEFT JOIN comments c ON p.id = c.post_id
LEFT JOIN likes l ON l.post_id = p.id
WHERE MATCH(p.title, p.content) AGAINST(?)
GROUP BY p.id;";
$stmt = db_get_prepare_stmt($db_link, $sql, [$search]);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($result) {
$posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
}
}
if ($posts) {
$page = 'main';
} else {
$page = 'none';
}
} else {
$page = 'none';
}
$post_content = include_template('posts-page.php', [
'posts' => filter_posts($posts)
]);
$page_content = include_template('search-' . $page . '.php', [
'content' => $post_content,
'search' => $search
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'search' => $search,
'title' => 'readme: страница результатов поиска',
'user' => $user,
'header_my_nav' => $header_my_nav,
'is_auth' => $is_auth,
'add_form' => $add_form
]);
print($layout_content);
<file_sep><?php
require_once('helpers.php');
require_once('init.php');
require_once('mail.php');
$add_form = false;
$id = 0;
$errors = [];
$user_list = [];
$messages = [];
$content = '';
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
$user_id = $user['id'];
$user_list = make_select_query(
$db_link,
"SELECT id, name, avatar_img, content, published_at FROM users u JOIN
(SELECT user_id, content, published_at
FROM messages mes JOIN
(SELECT IF(from_user_id = $user_id, to_user_id, from_user_id) AS user_id, MAX(published_at) AS max_date
FROM messages
WHERE from_user_id = $user_id OR to_user_id = $user_id
GROUP BY user_id
) last_mes ON mes.published_at = last_mes.max_date
AND (mes.from_user_id = last_mes.user_id OR mes.to_user_id = last_mes.user_id)
) AS m ON m.user_id = id
WHERE id IN (SELECT from_user_id FROM messages WHERE to_user_id = $user_id)
OR id IN (SELECT to_user_id FROM messages WHERE from_user_id = $user_id);"
);
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$user_list_ids = array_column($user_list, 'id');
if (!in_array($id, $user_list_ids)) {
$user_list = make_select_query(
$db_link,
"SELECT id, name, avatar_img FROM users
WHERE id IN (SELECT from_user_id FROM messages WHERE to_user_id = $user_id)
OR id IN (SELECT to_user_id FROM messages WHERE from_user_id = $user_id)
OR id = $id;"
);
}
} else {
$id = $user_list[0]['id'];
}
if ($user_list) {
$messages = make_select_query(
$db_link,
"SELECT u.id, from_user_id, name, avatar_img, content, published_at
FROM users u JOIN messages m ON u.id = m.from_user_id
WHERE m.to_user_id = $id
UNION
SELECT u.id, from_user_id, name, avatar_img, content, published_at
FROM users u JOIN messages m ON u.id = m.from_user_id
WHERE m.to_user_id = $user_id AND u.id = $id
ORDER BY published_at ASC;"
);
} else {
$messages = [];
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['text'])) {
$errors['text'] = 'Это поле обязательно к заполнению';
} else {
$errors = [];
$content = trim(filter_input(INPUT_POST, 'text', FILTER_SANITIZE_STRING));
$sql = "INSERT INTO messages (content, from_user_id, to_user_id) VALUES (?, $user_id, $id);";
$stmt = db_get_prepare_stmt($db_link, $sql, [$content]);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
header("Location: messages.php?id=" . $id);
}
}
$page_content = include_template('messages-main.php', [
'user_list' => filter_posts($user_list),
'messages' => filter_posts($messages),
'content' => $content,
'errors' => $errors,
'auth_user' => $user,
'id' => $id
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'title' => 'readme: личные сообщения',
'user' => $user,
'page' => 'messages',
'header_my_nav' => $header_my_nav,
'is_auth' => $is_auth,
'add_form' => $add_form
]);
print($layout_content);
<file_sep><main class="page__main page__main--publication">
<div class="container">
<h1 class="page__title page__title--publication"><?=$post['title']; ?></h1>
<section class="post-details">
<h2 class="visually-hidden">Публикация</h2>
<div class="post-details__wrapper post-<?=$post['class']; ?>">
<div class="post-details__main-block post post--details">
<?=$content; ?>
<div class="post__indicators">
<div class="post__buttons">
<a class="post__indicator post__indicator--likes button" href="/like.php?id=<?=$post['id']; ?>" title="Лайк">
<svg class="post__indicator-icon" width="20" height="17">
<use xlink:href="#icon-heart"></use>
</svg>
<svg class="post__indicator-icon post__indicator-icon--like-active" width="20" height="17">
<use xlink:href="#icon-heart-active"></use>
</svg>
<span><?=$post['likes']; ?></span>
<span class="visually-hidden">количество лайков</span>
</a>
<a class="post__indicator post__indicator--comments button" href="#" title="Комментарии">
<svg class="post__indicator-icon" width="19" height="17">
<use xlink:href="#icon-comment"></use>
</svg>
<span><?=$post['comments']; ?></span>
<span class="visually-hidden">количество комментариев</span>
</a>
<a class="post__indicator post__indicator--repost button" href="/repost.php?id=<?=$post['id']; ?>" title="Репост">
<svg class="post__indicator-icon" width="19" height="17">
<use xlink:href="#icon-repost"></use>
</svg>
<span><?=$post['repost_count']; ?></span>
<span class="visually-hidden">количество репостов</span>
</a>
</div>
<span class="post__view"><?=$post['show_count']; ?> просмотров</span>
</div>
<ul class="post__tags">
<?php foreach ($tags as $key => $value) : ?>
<li><a href="/search.php?query=<?=urlencode('#' . $value['tag']); ?>">#<?=$value['tag']; ?></a></li>
<?php endforeach; ?>
</ul>
<div class="comments">
<form class="comments__form form" action="/post.php?<?=http_build_query(['id' => $id]); ?>" method="post">
<div class="comments__my-avatar">
<img class="comments__picture" src="img/<?=$auth_user['avatar_img']?>" alt="Аватар пользователя">
</div>
<div class="form__input-section<?php if ($errors) :
?> form__input-section--error<?php
endif; ?>">
<textarea class="comments__textarea form__textarea form__input" name="text" placeholder="Ваш комментарий"><?=$comment; ?></textarea>
<label class="visually-hidden">Ваш комментарий</label>
<button class="form__error-button button" type="button">!</button>
<div class="form__error-text">
<h3 class="form__error-title">Ошибка валидации</h3>
<p class="form__error-desc"><?=$errors['text']; ?></p>
</div>
</div>
<button class="comments__submit button button--green" type="submit">Отправить</button>
</form>
<div class="comments__list-wrapper">
<ul class="comments__list">
<?php foreach ($comments as $comment) : ?>
<li class="comments__item user">
<div class="comments__avatar">
<a class="user__avatar-link" href="/profile.php?id=<?=$comment['id']; ?>">
<img class="comments__picture" src="img/<?=$comment['avatar_img']; ?>" alt="Аватар пользователя">
</a>
</div>
<div class="comments__info">
<div class="comments__name-wrapper">
<a class="comments__user-name" href="/profile.php?id=<?=$comment['id']; ?>">
<span><?=$comment['name']; ?></span>
</a>
<time class="comments__time" datetime="<?=$comment['published_at']; ?>">
<?=make_datetime_relative($comment['published_at']); ?>
</time>
</div>
<p class="comments__text">
<?=$comment['comment']; ?>
</p>
</div>
</li>
<?php endforeach; ?>
</ul>
<?php if ($post['comments'] > 4) : ?>
<a class="comments__more-link" href="#">
<span>Показать все комментарии</span>
<sup class="comments__amount"><?=$post['comments']; ?></sup>
</a>
<?php endif; ?>
</div>
</div>
</div>
<div class="post-details__user user">
<div class="post-details__user-info user__info">
<div class="post-details__avatar user__avatar">
<a class="post-details__avatar-link user__avatar-link" href="/profile.php?id=<?=$post['user_id']; ?>">
<img class="post-details__picture user__picture" src="img/<?=$user['avatar_img']; ?>" alt="Аватар пользователя">
</a>
</div>
<div class="post-details__name-wrapper user__name-wrapper">
<a class="post-details__name user__name" href="/profile.php?id=<?=$post['user_id']; ?>">
<span><?=$user['name'];?></span>
</a>
<time class="post-details__time user__time" datetime="<?=$user['created_at']; ?>"><?=make_datetime_relative($user['created_at'], " на сайте"); ?></time>
</div>
</div>
<div class="post-details__rating user__rating">
<p class="post-details__rating-item user__rating-item user__rating-item--subscribers">
<span class="post-details__rating-amount user__rating-amount"><?=$user['subs']; ?></span>
<span class="post-details__rating-text user__rating-text">подписчиков</span>
</p>
<p class="post-details__rating-item user__rating-item user__rating-item--publications">
<span class="post-details__rating-amount user__rating-amount"><?=$user['posts']; ?></span>
<span class="post-details__rating-text user__rating-text">публикаций</span>
</p>
</div>
<div class="post-details__user-buttons user__buttons">
<?php if (!$is_subscribe) : ?>
<button class="user__button user__button--subscription button button--main" onClick='location.href="/subscribe.php?id=<?=$user['id']; ?>"' type="button">Подписаться</button>
<?php else : ?>
<button class="user__button user__button--subscription button button--quartz" onClick='location.href="/unsubscribe.php?id=<?=$user['id']; ?>"' type="button">Отписаться</button>
<?php endif; ?>
<a class="user__button user__button--writing button button--green" href="/messages.php?id=<?=$post['user_id']; ?>">Сообщение</a>
</div>
</div>
</div>
</section>
</div>
</main><file_sep><?php foreach ($posts as $post) : ?>
<article class="feed__post post post-<?=$post['class']?>">
<header class="post__header post__author">
<a class="post__author-link" href="/profile.php?id=<?=$post['user_id']; ?>" title="Автор">
<div class="post__avatar-wrapper">
<img class="post__author-avatar" src="img/<?=$post['avatar']?>" alt="Аватар пользователя" width="60" height="60">
</div>
<div class="post__info">
<b class="post__author-name"><?=$post['name']?></b>
<span class="post__time"><?=make_datetime_relative($post['published_at']); ?></span>
</div>
</a>
</header>
<div class="post__main">
<?php if ($post['type'] === 'Картинка') : ?>
<h2><a href="/post.php?id=<?=$post['id']; ?>"><?=$post['title']; ?></a></h2>
<div class="post-<?=$post['class']; ?>__image-wrapper">
<img src="uploads/<?=$post['img']; ?>" alt="Фото от пользователя" width="760" height="396">
</div>
<?php endif; ?>
<?php if ($post['type'] === 'Текст') : ?>
<h2><a href="/post.php?id=<?=$post['id']; ?>"><?=$post['title']; ?></a></h2>
<?=cut_string($post['content']); ?>
<?php endif; ?>
<?php if ($post['type'] === 'Видео') : ?>
<div class="post-video__block">
<div class="post-video__preview">
<img src="img/coast.jpg" alt="Превью к видео" width="760" height="396">
</div>
<div class="post-video__control">
<button class="post-video__play post-video__play--paused button button--video" type="button"><span class="visually-hidden">Запустить видео</span></button>
<div class="post-video__scale-wrapper">
<div class="post-video__scale">
<div class="post-video__bar">
<div class="post-video__toggle"></div>
</div>
</div>
</div>
<button class="post-video__fullscreen post-video__fullscreen--inactive button button--video" type="button"><span class="visually-hidden">Полноэкранный режим</span></button>
</div>
<button class="post-video__play-big button" type="button">
<svg class="post-video__play-big-icon" width="27" height="28">
<use xlink:href="#icon-video-play-big"></use>
</svg>
<span class="visually-hidden">Запустить проигрыватель</span>
</button>
</div>
<?php endif; ?>
<?php if ($post['type'] === 'Цитата') : ?>
<blockquote>
<p>
<?=$post['content']; ?>
</p>
<cite><?=$post['author']; ?></cite>
</blockquote>
<?php endif; ?>
<?php if ($post['type'] === 'Ссылка') : ?>
<div class="post-link__wrapper">
<a class="post-link__external" href="<?=$post['link']; ?>" title="Перейти по ссылке">
<div class="post-link__icon-wrapper">
<img src="img/logo-vita.jpg" alt="Иконка">
</div>
<div class="post-link__info">
<h3><?=$post['title']; ?></h3>
<span><?=$post['link']; ?></span>
</div>
<svg class="post-link__arrow" width="11" height="16">
<use xlink:href="#icon-arrow-right-ad"></use>
</svg>
</a>
</div>
<?php endif; ?>
</div>
<footer class="post__footer post__indicators">
<div class="post__buttons">
<a class="post__indicator post__indicator--likes button" href="/like.php?id=<?=$post['id']; ?>" title="Лайк">
<svg class="post__indicator-icon" width="20" height="17">
<use xlink:href="#icon-heart"></use>
</svg>
<svg class="post__indicator-icon post__indicator-icon--like-active" width="20" height="17">
<use xlink:href="#icon-heart-active"></use>
</svg>
<span><?=$post['likes']; ?></span>
<span class="visually-hidden">количество лайков</span>
</a>
<a class="post__indicator post__indicator--comments button" href="#" title="Комментарии">
<svg class="post__indicator-icon" width="19" height="17">
<use xlink:href="#icon-comment"></use>
</svg>
<span><?=$post['comments']; ?></span>
<span class="visually-hidden">количество комментариев</span>
</a>
<a class="post__indicator post__indicator--repost button" href="/repost.php?id=<?=$post['id']; ?>" title="Репост">
<svg class="post__indicator-icon" width="19" height="17">
<use xlink:href="#icon-repost"></use>
</svg>
<span><?=$post['repost_count']; ?></span>
<span class="visually-hidden">количество репостов</span>
</a>
</div>
</footer>
</article>
<?php endforeach; ?><file_sep><main class="page__main page__main--adding-post">
<div class="page__main-section">
<div class="container">
<h1 class="page__title page__title--adding-post">Добавить публикацию</h1>
</div>
<div class="adding-post container">
<div class="adding-post__tabs-wrapper tabs">
<div class="adding-post__tabs filters">
<ul class="adding-post__tabs-list filters__list tabs__list">
<?php foreach ($post_types as $type) : ?>
<li class="adding-post__tabs-item filters__item">
<a class="adding-post__tabs-link filters__button filters__button--<?=$type['icon_class']; ?>
<?php if ($type['id'] === $id) :
?> filters__button--active <?php
endif; ?> tabs__item tabs__itm_active button" href="/add.php?<?=http_build_query([ 'id' => $type['id'] ]); ?>">
<svg class="filters__icon" width="22" height="18">
<use xlink:href="#icon-filter-<?=$type['icon_class']; ?>"></use>
</svg>
<span><?=$type['type_name']; ?></span>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="adding-post__tab-content">
<section class="adding-post__<?=$post_types[$id - 1]['icon_class']; ?> tabs__content tabs__content--active">
<h2 class="visually-hidden">Форма добавления</h2>
<form class="adding-post__form form" action="/add.php?<?=http_build_query([ 'id' => $id ]); ?>" method="post" enctype="multipart/form-data">
<div class="form__text-inputs-wrapper">
<div class="form__text-inputs">
<div class="adding-post__input-wrapper form__input-wrapper <?php if (array_key_exists("title", $errors)) :
?> form__input-section--error <?php
endif; ?>">
<label class="adding-post__label form__label" for="heading">Заголовок <span class="form__input-required">*</span></label>
<div class="form__input-section">
<input class="adding-post__input form__input" id="heading" type="text" name="title" value="<?=getPostVal('title'); ?>" placeholder="Введите заголовок">
<button class="form__error-button button" type="button">!<span class="visually-hidden">Информация об ошибке</span></button>
<div class="form__error-text">
<h3 class="form__error-title">Ошибка!</h3>
<p class="form__error-desc"><?=$errors['title']; ?></p>
</div>
</div>
</div>
<?=$content; ?>
<div class="adding-post__input-wrapper form__input-wrapper <?php if (array_key_exists("tags", $errors)) :
?> form__input-section--error <?php
endif; ?>">
<label class="adding-post__label form__label" for="tags">Теги</label>
<div class="form__input-section">
<input class="adding-post__input form__input" id="tags" type="text" name="tags" value="<?=getPostVal('tags'); ?>" placeholder="Введите теги">
<button class="form__error-button button" type="button">!<span class="visually-hidden">Информация об ошибке</span></button>
<div class="form__error-text">
<h3 class="form__error-title">Ошибка!</h3>
<p class="form__error-desc"><?=$errors['tags']; ?></p>
</div>
</div>
</div>
</div>
<?php if (count($errors)) : ?>
<div class="form__invalid-block">
<b class="form__invalid-slogan">Пожалуйста, исправьте следующие ошибки:</b>
<?php foreach ($errors as $key => $value) : ?>
<ul class="form__invalid-list">
<li class="form__invalid-item"><?=$value; ?></li>
</ul>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php if ($post_types[$id - 1]['icon_class'] === 'photo') : ?>
<div class="adding-post__input-file-container form__input-container form__input-container--file">
<div class="adding-post__input-file-wrapper form__input-file-wrapper">
<div class="adding-post__file-zone adding-post__file-zone--photo form__file-zone dropzone">
<input class="adding-post__input-file form__input-file" id="photo" type="file" name="photo" title=" ">
<div class="form__file-zone-text">
<span>Перетащите фото сюда</span>
</div>
</div>
<button class="adding-post__input-file-button form__input-file-button form__input-file-button--photo button" type="button">
<span>Выбрать фото</span>
<svg class="adding-post__attach-icon form__attach-icon" width="10" height="20">
<use xlink:href="#icon-attach"></use>
</svg>
</button>
</div>
<div class="adding-post__file adding-post__file--photo form__file dropzone-previews">
</div>
</div>
<?php endif; ?>
<div class="adding-post__buttons">
<button class="adding-post__submit button button--main" type="submit">Опубликовать</button>
<a class="adding-post__close" href="/index.php">Закрыть</a>
</div>
</form>
</section>
</div>
</div>
</div>
</div>
</main><file_sep><?php
require_once('helpers.php');
require_once('init.php');
$add_form = false;
$sort_types = [
[
'id' => '1',
'title' => 'Популярность',
'order_by' => 'show_count'
],
[
'id' => '2',
'title' => 'Лайки',
'order_by' => 'likes'
],
[
'id' => '3',
'title' => 'Дата',
'order_by' => 'published_at'
]
];
$post_types = [];
$posts = [];
$id = 0;
$sort = 1;
$current_page = 1;
$offset = 0;
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
$post_types = make_select_query($db_link, "SELECT * FROM types;");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
} else {
$id = null;
}
if (isset($_GET['order_by'])) {
$sort = filter_input(INPUT_GET, 'order_by', FILTER_SANITIZE_NUMBER_INT);
} else {
$sort = '1';
}
if (isset($_GET['page'])) {
$current_page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT);
} else {
$current_page = '1';
}
$condition = '';
if ($id) {
$condition = "WHERE tp.id = $id";
}
$total_items = make_select_query(
$db_link,
"SELECT COUNT(p.id) AS total FROM posts p
JOIN types tp ON p.post_type = tp.id " . $condition,
true
)['total'];
$page_items = 6;
$pages_count = ceil($total_items / $page_items);
if ($current_page) {
if ($current_page > $pages_count) {
$current_page = $pages_count;
}
$offset = ($current_page - 1) * $page_items;
} else {
$current_page = '1';
$offset = '0';
}
if ($total_items) {
$posts = make_select_query(
$db_link,
"SELECT p.*, name, avatar_img AS avatar, type_name AS type, icon_class AS class,
COUNT(DISTINCT c.id) AS comments, COUNT(l.id) AS likes
FROM posts p
JOIN users us ON p.user_id = us.id
JOIN types tp ON p.post_type = tp.id
LEFT JOIN comments c ON p.id = c.post_id
LEFT JOIN likes l ON l.post_id = p.id " .
$condition .
" GROUP BY p.id ORDER BY " . $sort_types[$sort - 1]['order_by'] . " DESC LIMIT " .
$page_items . " OFFSET " . $offset
);
}
$page_content = include_template('main.php', [
'posts' => filter_posts($posts),
'pages_count' => $pages_count,
'current_page' => $current_page,
'post_types' => filter_posts($post_types),
'sort_types' => $sort_types,
'id' => $id,
'sort' => $sort
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'user' => $user,
'page' => 'popular',
'header_my_nav' => $header_my_nav,
'title' => 'readme: популярное',
'add_form' => $add_form
]);
print($layout_content);
<file_sep><main class="page__main page__main--login">
<div class="container">
<h1 class="page__title page__title--login">Вход</h1>
</div>
<section class="login container">
<h2 class="visually-hidden">Форма авторизации</h2>
<form class="login__form form" action="#" method="post">
<div class="login__input-wrapper form__input-wrapper<?php if (array_key_exists('email', $errors)) :
?> form__input-section--error<?php
endif; ?>">
<label class="login__label form__label" for="login-email">Электронная почта</label>
<div class="form__input-section">
<input class="login__input form__input" id="login-email" type="email" name="email" value="<?=getPostVal('email')?>" placeholder="Укажите эл.почту">
<button class="form__error-button button" type="button">!<span class="visually-hidden">Информация об ошибке</span></button>
<div class="form__error-text">
<h3 class="form__error-title">Ошибка!</h3>
<p class="form__error-desc"><?=$errors['email']; ?></p>
</div>
</div>
</div>
<div class="login__input-wrapper form__input-wrapper <?php if (array_key_exists('password', $errors)) :
?> form__input-section--error<?php
endif; ?>">
<label class="login__label form__label" for="login-password">Пароль</label>
<div class="form__input-section">
<input class="login__input form__input" id="login-password" type="<PASSWORD>" name="password" placeholder="<PASSWORD> <PASSWORD>">
<button class="form__error-button button button--main" type="button">!<span class="visually-hidden">Информация об ошибке</span></button>
<div class="form__error-text">
<h3 class="form__error-title">Ошибка!</h3>
<p class="form__error-desc"><?=$errors['password']?></p>
</div>
</div>
</div>
<button class="login__submit button button--main" type="submit">Отправить</button>
</form>
</section>
</main><file_sep><?php
session_start();
require_once('default-config.php');
$is_auth = 0;
if (!isset($_SESSION['user'])) {
header("Location: /index.php");
exit();
}
$is_auth = 1;
$user = $_SESSION['user'];
$header_my_nav = [
[
'page' => 'popular',
'title' => 'Популярный контент'
],
[
'page' => 'feed',
'title' => 'Моя лента'
],
[
'page' => 'messages',
'title' => 'Личные сообщения'
]
];
$db_link = mysqli_connect($localhost, $db_user, $db_password, $db_session);
date_default_timezone_set("Asia/Yekaterinburg");
<file_sep><?php
require_once('helpers.php');
require_once('init.php');
require_once('mail.php');
$add_form = true;
$user_id = $user['id'];
$id = '1';
$post_types = [];
$errors = [];
$post = [];
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
$post_types = make_select_query($db_link, "SELECT * FROM types;");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$post = $_POST;
$required_fields = ['title', 'text', 'author', 'link', 'video'];
$rules = [
'title' => function ($value) {
return validateFilled($value, 'Заголовок');
},
'text' => function ($value) {
return validateFilled($value, 'Текст');
},
'quote' => function ($value) {
return validateFilledLength($value, 70, "Цитата");
},
'author' => function ($value) {
return validateFilled($value, 'Автор');
},
'link' => function ($value) {
return validateUrl($value, 'Ссылка');
},
'video' => function ($value) {
return validateUrl($value, 'Ссылка Youtube', true);
}
];
foreach ($_POST as $key => $value) {
if (isset($rules[$key])) {
$rule = $rules[$key];
$errors[$key] = $rule($value);
}
}
if ($id === '2') {
$avalable_file_types = ['image/jpeg', 'image/gif', 'image/png'];
if (!empty($_FILES['photo']['name'])) {
$tmp_name = $_FILES['photo']['tmp_name'];
$img_name = $_FILES['photo']['name'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file_type = finfo_file($finfo, $tmp_name);
$valid_type = validateFileType($file_type, $avalable_file_types);
if (!$valid_type) {
move_uploaded_file($tmp_name, 'uploads/' . $img_name);
$post['img'] = $img_name;
} else {
$errors['file'] = $valid_type;
}
} elseif (empty($_POST['url'])) {
$errors['url'] = "Добавьте файл или введите ссылку.";
} elseif (validateUrl($_POST['url'])) {
$file_type = getFileType($_POST['url']);
$file = file_get_contents($_POST['url']);
if ($file) {
$valid_type = validateFileType($file_type, $avalable_file_types);
if (!$valid_type) {
$img_name = pathinfo($_POST['url'], PATHINFO_BASENAME);
file_put_contents('uploads/' . $img_name, $file);
$post['img'] = $img_name;
} else {
$errors['file'] = $valid_type;
}
}
}
}
$tags = [];
if (isset($post['tags']) && !empty($post['tags'])) {
$tags = explode(' ', $post['tags']);
$check_tags = validate_tags($tags);
if ($check_tags) {
$errors['tags'] = $check_tags;
}
}
$errors = array_filter($errors);
if (!count($errors)) {
if (isset($post['text'])) {
$post['content'] = $post['text'];
}
if (isset($post['quote'])) {
$post['content'] = $post['quote'];
}
$post = array_filter($post);
$post = fillArray($post, ['title', 'content', 'author', 'img', 'video', 'link']);
$sql = "INSERT INTO posts (title, content, author, img, video, link, user_id, post_type)
VALUES (?, ?, ?, ?, ?, ?, $user_id, $id);";
$stmt = db_get_prepare_stmt($db_link, $sql, $post);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
$post_id = mysqli_insert_id($db_link);
foreach ($tags as $key => $tag) {
$check_tag = make_select_query($db_link, "SELECT id FROM hashtags WHERE hash_name = '$tag'", true);
if (!$check_tag) {
$sql = "INSERT INTO hashtags (hash_name) VALUES (?);";
$insert_tag = [$tag];
$stmt = db_get_prepare_stmt($db_link, $sql, $insert_tag);
$result = mysqli_stmt_execute($stmt);
if ($result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
$tag_id = mysqli_insert_id($db_link);
}
$tag_id = $check_tag['id'];
$sql = "INSERT INTO posts_hashtags (post_id, hash_id) VALUES (?, ?);";
$insert_post_tag = [$post_id, $tag_id];
$stmt = db_get_prepare_stmt($db_link, $sql, $insert_post_tag);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
}
$subscribed_users = make_select_query(
$db_link,
"SELECT name, email FROM users WHERE id IN (SELECT user_id FROM subscriptions WHERE to_user_id = $user_id);"
);
foreach ($subscribed_users as $subscribed_user) {
$message_content = "Здравствуйте, " .
$subscribed_user['name'] .
". Пользователь " . $user['name'] .
" только что опубликовал новую запись \"" .
$post['title'] . "\" . Посмотрите её на странице пользователя: ";
$message_subject = "Новая публикация от пользователя " . $user['name'];
$message = new Swift_Message();
$message->setSubject($message_subject);
$message->setTo([$subscribed_user['email'] => $subscribed_user['name']]);
$message->setBody($message_content . '<a href="http://localhost/profile.php?id=' .
$user['id'] . '">' . $user['name'] .'</a>', 'text/html');
$message->setFrom(['<EMAIL>' => 'ReadMe']);
$send_result = $mailer->send($message);
}
header("Location: post.php?id=" . $post_id);
}
}
$add_file = "add-" . $post_types[$id - 1]['icon_class'] . ".php";
$add_content = include_template($add_file, [
'errors' => $errors
]);
$page_content = include_template('adding-post.php', [
'content' => $add_content,
'post_types' => filter_posts($post_types),
'errors' => $errors,
'id' => $id
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'user' => $user,
'header_my_nav' => $header_my_nav,
'title' => 'readme: добавление публикации',
'add_form' => $add_form
]);
print($layout_content);
<file_sep><main class="page__main page__main--profile">
<h1 class="visually-hidden">Профиль</h1>
<div class="profile profile--<?=$tab; ?>">
<div class="profile__user-wrapper">
<div class="profile__user user container">
<div class="profile__user-info user__info">
<div class="profile__avatar user__avatar">
<img class="profile__picture user__picture" src="img/<?=$user_profile['avatar_img']; ?>" alt="Аватар пользователя">
</div>
<div class="profile__name-wrapper user__name-wrapper">
<span class="profile__name user__name"><?=$user_profile['name']; ?></span>
<time class="profile__user-time user__time" datetime="<?=$user_profile['created_at']; ?>"><?=make_datetime_relative($user_profile['created_at'], ' на сайте');?></time>
</div>
</div>
<div class="profile__rating user__rating">
<p class="profile__rating-item user__rating-item user__rating-item--publications">
<span class="user__rating-amount"><?=$user_profile['posts_count']; ?></span>
<span class="profile__rating-text user__rating-text">публикаций</span>
</p>
<p class="profile__rating-item user__rating-item user__rating-item--subscribers">
<span class="user__rating-amount"><?=$user_profile['subs']; ?></span>
<span class="profile__rating-text user__rating-text">подписчиков</span>
</p>
</div>
<?php if ($user_profile['id'] !== $user['id']) : ?>
<div class="profile__user-buttons user__buttons">
<?php if (!$is_subscribe) : ?>
<button class="profile__user-button user__button user__button--subscription button button--main" onClick='location.href="/subscribe.php?id=<?=$user_profile['id']; ?>"' type="button">Подписаться</button>
<?php else : ?>
<button class="profile__user-button user__button user__button--subscription button button--quartz" onClick='location.href="/unsubscribe.php?id=<?=$user_profile['id']; ?>"' type="button">Отписаться</button>
<?php endif; ?>
<a class="profile__user-button user__button user__button--writing button button--green" href="/messages.php?id=<?=$user_profile['id']; ?>">Сообщение</a>
</div>
<?php endif; ?>
</div>
<div class="profile__tabs-wrapper tabs">
<div class="container">
<div class="profile__tabs filters">
<b class="profile__tabs-caption filters__caption">Показать:</b>
<ul class="profile__tabs-list filters__list tabs__list">
<?php foreach ($tabs as $element) : ?>
<li class="profile__tabs-item filters__item tabs__item">
<a class="profile__tabs-link filters__button <?php if ($tab === $element['tab']) :
?>filters__button--active button"<?php
else :
?> button" href="/profile.php?<?=http_build_query(array_merge($_GET, ['tab' => $element['tab']]));?>"<?php
endif; ?>><?=$element['title']; ?></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?=$content; ?>
</div>
</div>
</div>
</main><file_sep><?php
require_once('helpers.php');
require_once('init.php');
$add_form = false;
$id = 0;
$posts = [];
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
$post_types = make_select_query($db_link, "SELECT * FROM types;");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
} else {
$id = null;
}
$condition = "";
if ($id) {
$condition = "AND tp.id = $id";
}
$user_id = $user['id'];
$posts = make_select_query(
$db_link,
"SELECT p.*, name, avatar_img AS avatar, type_name AS type, icon_class AS class,
COUNT(c.id) AS comments, COUNT(l.id) AS likes
FROM posts p
JOIN users us ON p.user_id = us.id
JOIN types tp ON p.post_type = tp.id
LEFT JOIN comments c ON p.id = c.post_id
LEFT JOIN likes l ON l.post_id = p.id
WHERE p.user_id IN (SELECT to_user_id FROM subscriptions WHERE user_id = $user_id)" .
$condition .
" GROUP BY p.id;"
);
$post_content = include_template('posts-page.php', [
'posts' => filter_posts($posts)
]);
$page_content = include_template('feed-main.php', [
'content' => $post_content,
'id' => $id,
'post_types' => filter_posts($post_types)
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'title' => 'readme: моя лента',
'user' => $user,
'page' => 'feed',
'header_my_nav' => $header_my_nav,
'is_auth' => $is_auth,
'add_form' => $add_form
]);
print($layout_content);
<file_sep><?php
require_once('vendor/autoload.php');
$transport = new Swift_SmtpTransport('smtp.mailtrap.io', 2525);
$transport->setUsername($transport_username);
$transport->setPassword($transport_password);
$mailer = new Swift_Mailer($transport);
<file_sep><?php
require_once('helpers.php');
require_once('init.php');
require_once('mail.php');
$id = null;
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
}
if ($id) {
$check_id = mysqli_num_rows(mysqli_query($db_link, "SELECT id FROM users WHERE id = $id"));
if ($check_id) {
$subscription = ['0' => $user['id'], '1' => $id];
$sql = "INSERT INTO subscriptions (user_id, to_user_id) VALUES (?, ?);";
$stmt = db_get_prepare_stmt($db_link, $sql, $subscription);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
$to_user = make_select_query($db_link, "SELECT name, email FROM users WHERE id = $id;", true);
$message_content = "Здравствуйте, " . $to_user['name'] . ". На вас подписался новый пользователь " .
$user['name'] . ". Вот ссылка на его профиль: ";
$message = new Swift_Message();
$message->setSubject("У вас новый подписчик");
$message->setTo([$to_user['email'] => $to_user['name']]);
$message->setBody($message_content . '<a href="http://localhost/profile.php?id=' . $user['id'] . '">' .
$user['name'] .'</a>', 'text/html');
$message->setFrom(['<EMAIL>' => 'ReadMe']);
$result = $mailer->send($message);
}
header("Location: profile.php?id=" . $id);
}
<file_sep>/*
Вносим список типов контента для поста
*/
INSERT INTO types (type_name, icon_class) VALUES
('Текст', 'text'),
('Картинка', 'photo'),
('Ссылка', 'link'),
('Цитата', 'quote'),
('Видео', 'video');
/*
Создаем несколько пользователей
*/
INSERT INTO users
SET name = 'Владик', email = '<EMAIL>', password = '<PASSWORD>', avatar_img = 'userpic.jpg';
INSERT INTO users
SET NAME = 'Лариса', email = '<EMAIL>', password = '<PASSWORD>', avatar_img = 'userpic-larisa-small.jpg';
INSERT INTO users
SET NAME = 'Виктор', email = '<EMAIL>', password = '<PASSWORD>', avatar_img = 'userpic-mark.jpg';
/*
Добавляет пост с цитатой в список постов
*/
INSERT INTO posts (title, content, user_id, post_type, show_count)
VALUES
(
'Цитата',
'Мы в жизни любим только раз, а после ищем лишь похожих',
(SELECT id FROM users WHERE name = 'Лариса'),
(SELECT id FROM types WHERE type_name = 'Цитата'),
0
);
/*
Добавляет пост с текстом в список постов
*/
INSERT INTO posts (title, content, user_id, post_type, show_count)
VALUES
(
'Игра престолов',
'Не могу дождаться начала финального сезона своего любимого сериала!',
(SELECT id FROM users WHERE name = 'Владик'),
(SELECT id FROM types WHERE type_name = 'Текст'),
0
);
/*
Добавляет посты с фото в список постов
*/
INSERT INTO posts (title, img, user_id, post_type, show_count)
VALUES
(
'Наконец, обработал фотки!',
'rock-medium.jpg',
(SELECT id FROM users WHERE name = 'Виктор'),
(SELECT id FROM types WHERE type_name = 'Картинка'),
0
),
(
'<NAME>',
'coast-medium.jpg',
(SELECT id FROM users WHERE name = 'Лариса'),
(SELECT id FROM types WHERE type_name = 'Картинка'),
0
);
/*
Добавляет пост с ссылкой в список постов
*/
INSERT INTO posts (title, link, user_id, post_type, show_count)
VALUES
(
'Лучшие курсы',
'www.htmlacademy.ru',
(SELECT id FROM users WHERE name = 'Владик'),
(SELECT id FROM types WHERE type_name = 'Ссылка'),
0
);
/*
Добавляет комментарии к постам
*/
INSERT INTO comments (comment, user_id, post_id)
VALUES
(
'Мечты сбываются!',
(SELECT id FROM users WHERE name = 'Владик'),
(SELECT id FROM posts WHERE title = 'Моя мечта')
),
(
'Замечательное место для зимнего отдыха!',
(SELECT id FROM users WHERE name = 'Виктор'),
(SELECT id FROM posts WHERE title = 'Моя мечта')
);
/*
Получает список постов с сортировкой по популярности с именами авторов и типом контента
*/
SELECT p.*, name, type_name
FROM posts p
JOIN users us ON p.user_id = us.id
JOIN types tp ON p.post_type = tp.id
ORDER BY show_count DESC;
/*
Получает список постов для конкретного пользователя
*/
SELECT * FROM posts WHERE user_id = (SELECT id FROM users WHERE NAME = 'Владик');
/*
Получает список комментариев для поста с указанием логина пользователя
*/
SELECT comment, name
FROM comments com JOIN users us ON com.user_id = us.id;
/*
Добавляет лайк к посту
*/
INSERT INTO likes (user_id, post_id)
VALUES
(
(SELECT id FROM users WHERE name = 'Владик'),
(SELECT id FROM posts WHERE title = 'Наконец, обработал фотки!')
);
/*
Подписка на пользователя
*/
INSERT INTO subscriptions (user_id, to_user_id)
VALUES
(
(SELECT id FROM users WHERE name = 'Виктор'),
(SELECT id FROM users WHERE name = 'Лариса')
);<file_sep><div class="profile__tab-content">
<section class="profile__likes tabs__content tabs__content--active">
<h2 class="visually-hidden">Лайки</h2>
<ul class="profile__likes-list">
<?php foreach ($content as $like) : ?>
<li class="post-mini post-mini--photo post user">
<div class="post-mini__user-info user__info">
<div class="post-mini__avatar user__avatar">
<a class="user__avatar-link" href="/profile.php?id=<?=$like['user_id']; ?>">
<img class="post-mini__picture user__picture" src="img/<?=$like['avatar_img']; ?>" alt="Аватар пользователя">
</a>
</div>
<div class="post-mini__name-wrapper user__name-wrapper">
<a class="post-mini__name user__name" href="/profile.php?id=<?=$like['user_id']; ?>">
<span><?=$like['name']; ?></span>
</a>
<div class="post-mini__action">
<span class="post-mini__activity user__additional">Лайкнул вашу публикацию</span>
<time class="post-mini__time user__additional" datetime="<?=$like['created_at']; ?>"><?=make_datetime_relative($like['created_at']); ?></time>
</div>
</div>
</div>
<div class="post-mini__preview">
<a class="post-mini__link" href="/post.php?id=<?=$like['post_id']; ?>" title="Перейти на публикацию">
<?php if ($like['type'] === 'photo') : ?>
<div class="post-mini__image-wrapper">
<img class="post-mini__image" src="uploads/<?=$like['img']; ?>" width="109" height="109" alt="Превью публикации">
</div>
<span class="visually-hidden">Фото</span>
<?php endif; ?>
<?php if ($like['type'] === 'text') : ?>
<span class="visually-hidden">Текст</span>
<svg class="post-mini__preview-icon" width="20" height="21">
<use xlink:href="#icon-filter-text"></use>
</svg>
<?php endif; ?>
<?php if ($like['type'] === 'video') : ?>
<div class="post-mini__image-wrapper">
<img class="post-mini__image" src="img/coast-small.png" width="109" height="109" alt="Превью публикации">
<span class="post-mini__play-big">
<svg class="post-mini__play-big-icon" width="12" height="13">
<use xlink:href="#icon-video-play-big"></use>
</svg>
</span>
</div>
<span class="visually-hidden">Видео</span>
<?php endif; ?>
<?php if ($like['type'] === 'quote') : ?>
<span class="visually-hidden">Цитата</span>
<svg class="post-mini__preview-icon" width="21" height="20">
<use xlink:href="#icon-filter-quote"></use>
</svg>
<?php endif; ?>
<?php if ($like['type'] === 'link') : ?>
<span class="visually-hidden">Ссылка</span>
<svg class="post-mini__preview-icon" width="21" height="18">
<use xlink:href="#icon-filter-link"></use>
</svg>
<?php endif; ?>
</a>
</div>
</li>
<?php endforeach; ?>
</ul>
</section>
</div><file_sep><div class="profile__tab-content">
<section class="profile__subscriptions tabs__content tabs__content--active">
<h2 class="visually-hidden">Подписки</h2>
<ul class="profile__subscriptions-list">
<?php foreach ($content as $subscription) : ?>
<li class="post-mini post-mini--photo post user">
<div class="post-mini__user-info user__info">
<div class="post-mini__avatar user__avatar">
<a class="user__avatar-link" href="/profile.php?id=<?=$subscription['id']; ?>">
<img class="post-mini__picture user__picture" src="img/<?=$subscription['avatar_img']; ?>" alt="Аватар пользователя">
</a>
</div>
<div class="post-mini__name-wrapper user__name-wrapper">
<a class="post-mini__name user__name" href="/profile.php?id=<?=$subscription['id']; ?>">
<span><?=$subscription['name']; ?></span>
</a>
<time class="post-mini__time user__additional" datetime="<?=$subscription['created_at']; ?>"><?=make_datetime_relative($subscription['created_at'], ' на сайте');?></time>
</div>
</div>
<div class="post-mini__rating user__rating">
<p class="post-mini__rating-item user__rating-item user__rating-item--publications">
<span class="post-mini__rating-amount user__rating-amount"><?=$subscription['posts_count']; ?></span>
<span class="post-mini__rating-text user__rating-text">публикаций</span>
</p>
<p class="post-mini__rating-item user__rating-item user__rating-item--subscribers">
<span class="post-mini__rating-amount user__rating-amount"><?=$subscription['subs']; ?></span>
<span class="post-mini__rating-text user__rating-text">подписчиков</span>
</p>
</div>
<?php if ($user['id'] !== $subscription['id']) : ?>
<div class="post-mini__user-buttons user__buttons">
<?php if (!in_array($subscription['id'], $user_subscriptions)) : ?>
<button class="post-mini__user-button user__button user__button--subscription button button--main" onClick='location.href="/unsubscribe.php?id=<?=$subscription['id']; ?>"' type="button">Подписаться</button>
<?php else : ?>
<button class="post-mini__user-button user__button user__button--subscription button button--quartz" onClick='location.href="/unsubscribe.php?id=<?=$subscription['id']; ?>"' type="button">Отписаться</button>
<?php endif; ?>
</div>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</section>
</div><file_sep>CREATE DATABASE readme
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;
USE readme;
CREATE TABLE types (
id INT AUTO_INCREMENT PRIMARY KEY,
type_name VARCHAR(128) NOT NULL UNIQUE,
icon_class VARCHAR(128) NOT NULL UNIQUE
);
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(128) NOT NULL UNIQUE,
password VARCHAR(64) NOT NULL,
email VARCHAR(128) NOT NULL UNIQUE,
avatar_img VARCHAR(128),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX name_index ON users (name) USING BTREE;
CREATE INDEX email_index ON users (email) USING BTREE;
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(128) NOT NULL,
content TEXT,
author VARCHAR(128),
img VARCHAR(128),
video VARCHAR(128),
link VARCHAR(128),
show_count INT,
published_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
user_id INT NOT NULL,
post_type INT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (post_type) REFERENCES types (id)
);
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
comment TEXT,
published_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
user_id INT NOT NULL,
post_id INT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE
);
CREATE TABLE likes (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
post_id INT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE,
UNIQUE KEY unique_likes_idx (user_id, post_id)
);
CREATE TABLE subscriptions (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
to_user_id INT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (to_user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
content TEXT,
published_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
from_user_id INT NOT NULL,
to_user_id INT NOT NULL,
FOREIGN KEY (from_user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (to_user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE TABLE hashtags (
id INT AUTO_INCREMENT PRIMARY KEY,
hash_name VARCHAR(128) NOT NULL UNIQUE
);
CREATE TABLE posts_hashtags (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
hash_id INT NOT NULL,
FOREIGN KEY (post_id) REFERENCES posts (id) ON DELETE CASCADE,
FOREIGN KEY (hash_id) REFERENCES hashtags (id) ON DELETE CASCADE
);
CREATE FULLTEXT INDEX posts_ft_search ON posts(title, content);
ALTER TABLE likes
ADD created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE posts
ADD is_repost BOOLEAN DEFAULT 0,
ADD author_id INT,
ADD repost_count INT DEFAULT 0;<file_sep><?php
require_once('helpers.php');
require_once('init.php');
$add_form = false;
$id = 0;
$post = [];
$post_content = [];
$tags = [];
$comments = [];
$errors = [];
$comment = '';
$is_subscribe = 0;
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
}
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
$check_id = mysqli_num_rows(mysqli_query($db_link, "SELECT id FROM posts WHERE id = $id"));
if ($check_id === 0) {
http_response_code(404);
exit();
}
$show_count = make_select_query($db_link, "SELECT show_count FROM posts WHERE id = $id;", true)['show_count'] + 1;
$result = mysqli_query($db_link, "UPDATE posts SET show_count = $show_count WHERE id = $id;");
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
$post = make_select_query(
$db_link,
"SELECT p.*, type_name AS type, icon_class AS class, COUNT(DISTINCT c.id) AS comments, COUNT(l.id) AS likes
FROM posts p
JOIN types tp ON p.post_type = tp.id
LEFT JOIN comments c ON p.id = c.post_id
LEFT JOIN likes l ON p.id = l.post_id
GROUP BY p.id
HAVING p.id = $id;",
true
);
$post_user_id = $post['user_id'];
$post_user = make_select_query(
$db_link,
"SELECT u.*, COUNT(DISTINCT sub.id) AS subs, COUNT(p.id) AS posts
FROM users u
LEFT JOIN subscriptions sub ON u.id = sub.user_id
LEFT JOIN posts p ON u.id = p.user_id
GROUP BY u.id
HAVING u.id = $post_user_id;",
true
);
$user_id = $user['id'];
$is_subscribe = mysqli_num_rows(
mysqli_query(
$db_link,
"SELECT id FROM subscriptions WHERE user_id = $user_id AND to_user_id = $post_user_id"
)
);
$comments = make_select_query(
$db_link,
"SELECT u.id, comment, published_at, name, avatar_img
FROM comments c
JOIN users u ON c.user_id = u.id
WHERE c.post_id = $id
ORDER BY published_at DESC LIMIT 4;"
);
$tags = make_select_query(
$db_link,
"SELECT hash_name AS tag FROM hashtags h
JOIN posts_hashtags ph ON h.id = ph.hash_id
WHERE ph.post_id = $id;"
);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors['text'] = 'Это поле обязательно к заполнению';
if (!empty($_POST['text'])) {
unset($errors['text']);
}
$comment = trim(filter_input(INPUT_POST, 'text', FILTER_SANITIZE_STRING));
if (mb_strlen($comment) < 4) {
$errors['text'] = 'Слишком короткий текст';
} else {
$sql = "INSERT INTO comments (comment, user_id, post_id) VALUES (?, $user_id, $id);";
$stmt = db_get_prepare_stmt($db_link, $sql, [$comment]);
$result = mysqli_stmt_execute($stmt);
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
header("Location: profile.php?id=" . $post_user_id);
}
}
$post_file = "post-" . $post['class'] . ".php";
$post_content = include_template($post_file, [
'post' => filter_post($post)
]);
$page_content = include_template('post-main.php', [
'id' => $id,
'content' => $post_content,
'post' => filter_post($post),
'user' => filter_post($post_user),
'auth_user' => $user,
'is_subscribe' => $is_subscribe,
'comments' => filter_posts($comments),
'tags' => filter_posts($tags),
'comment' => $comment,
'errors' => $errors
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'user' => $user,
'header_my_nav' => $header_my_nav,
'title' => 'readme: публикация',
'add_form' => $add_form
]);
print($layout_content);
<file_sep><?php
require_once('helpers.php');
require_once('default-config.php');
session_start();
if (isset($_SESSION['user'])) {
header("Location: /feed.php");
exit();
}
$errors = [];
$post = [];
$user = [];
$db_link = mysqli_connect($localhost, $db_user, $db_password, $db_session);
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$post = $_POST;
$required_fields = ['login', 'password'];
foreach ($required_fields as $field) {
if (empty($post[$field])) {
$errors[$field] = 'Поле должно быть заполнено';
}
}
if (empty($errors)) {
$login = mysqli_real_escape_string($db_link, $post['login']);
$sql = "SELECT * FROM users WHERE name = '$login'";
$user = make_select_query($db_link, $sql, true);
if (empty($errors) && $user) {
if (password_verify($post['password'], $user['password'])) {
$_SESSION['user'] = $user;
} else {
$errors['password'] = '<PASSWORD>';
}
} else {
$errors['login'] = 'Неверный логин';
}
}
if (empty($errors)) {
header("Location: /feed.php");
exit();
}
}
$layout_content = include_template('layout-main.php', [
'title' => 'readme: блог, каким он должен быть',
'errors' => $errors
]);
print($layout_content);
<file_sep><?php
require_once('helpers.php');
require_once('default-config.php');
session_start();
if (isset($_SESSION['user'])) {
header("Location: /feed.php");
exit();
}
$is_auth = 0;
$errors = [];
$db_link = mysqli_connect($localhost, $db_user, $db_password, $db_session);
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$post = $_POST;
$required_fields = ['email', 'password'];
foreach ($required_fields as $field) {
if (empty($post[$field])) {
$errors[$field] = "Поле должно быть заполнено";
}
}
$user = [];
if (empty($errors)) {
$email = mysqli_real_escape_string($db_link, $post['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "Неверный формат почты";
} else {
$user = make_select_query($db_link, "SELECT * FROM users WHERE email = '$email'", true);
}
if ($user) {
if (password_verify($post['password'], $user['password'])) {
$_SESSION['user'] = $user;
} else {
$errors['password'] = '<PASSWORD>';
}
} else {
$errors['email'] = "Неверная почта";
}
}
if (empty($errors)) {
header("Location: /feed.php");
exit();
}
}
$page_content = include_template('login-main.php', [
'errors' =>$errors
]);
$layout_content = include_template('layout.php', [
'content' => $page_content,
'is_auth' => $is_auth,
'title' => 'readme: авторизация',
'is_login' => true
]);
print($layout_content);
<file_sep><?php
require_once('helpers.php');
require_once('init.php');
$post = [];
$id = null;
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
}
if ($id) {
$check_id = mysqli_num_rows(mysqli_query($db_link, "SELECT id FROM posts WHERE id = $id"));
if ($check_id) {
$post = make_select_query(
$db_link,
"SELECT title, content, author, img, video, link, user_id, post_type, is_repost, author_id, repost_count
FROM posts WHERE id = $id;",
true
);
if ($post['user_id'] === $user['id'] or $post['author_id'] === $user['id']) {
header("Location: " . $_SERVER['HTTP_REFERER']);
exit();
}
$post['is_repost'] = '1';
$post['repost_count'] = $post['repost_count'] + 1;
$post['user_id'] = $user['id'];
if (!$post['author_id']) {
$post['author_id'] = $post['user_id'];
}
$sql = "INSERT INTO posts (title, content, author, img, video, link, user_id,
post_type, is_repost, author_id, repost_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = db_get_prepare_stmt($db_link, $sql, $post);
$result = mysqli_stmt_execute($stmt);
if ($result) {
header("Location: /profile.php?id=" . $user['id']);
exit();
}
print("Ошибка запроса: " . mysqli_error($db_link));
}
}
<file_sep><?php
require_once('helpers.php');
require_once('init.php');
$id = null;
if ($db_link == false) {
print("Ошибка подключения: " . mysqli_connect_error());
die();
}
mysqli_set_charset($db_link, "utf8");
if (isset($_GET['id'])) {
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
}
if ($id) {
$user_id = $user['id'];
$check_id = mysqli_num_rows(mysqli_query($db_link, "SELECT id FROM subscriptions
WHERE user_id = $user_id AND to_user_id = $id"));
if ($check_id) {
$result = mysqli_query($db_link, "DELETE FROM subscriptions WHERE user_id = $user_id AND to_user_id = $id;");
if (!$result) {
print("Ошибка запроса: " . mysqli_error($db_link));
die();
}
}
}
header("Location: profile.php?id=" . $id);
| f4df2705ce7e98c29650919e4ffca1b0a3096b4c | [
"SQL",
"PHP"
] | 29 | PHP | htmlacademy-php/1704585-readme-12 | 5e4c8d08451ecc5de352bb9bbe96912c6fe35c52 | 33efd0d9adcdae0be22fb38f61378797541a2401 |
refs/heads/main | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Encap;
/**
*
* @author -LENOVO-
*/
public class EncapTest {
public static void main(String[] args) {
EncapDemo encap1=new EncapDemo();
encap1.setName("James");
encap1.setAge(35);
System.out.println("Name : "+encap1.getName());
System.out.println("Age : "+encap1.getAge());
EncapDemo encap2=new EncapDemo();
encap2.setName("Hannah");
encap2.setAge(17);
System.out.println("Name : "+encap2.getName());
System.out.println("Age : "+encap2.getAge());
}
}
| d907580e298ee57a1dd7fcd1bf299f343283780e | [
"Java"
] | 1 | Java | ShineDevi/Tugas3-PrkPBO-2C-20 | 1df0983538392ade1ac441828b5f4a06257c775d | 4dc0e5ea6fb862d0d0081633a5484a4a5e0de3ec |
refs/heads/master | <repo_name>gedison/openGL<file_sep>/test.cpp
#define GL_GLEXT_PROTOTYPES
#include <stdio.h>
#ifdef __APPLE__
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glut.h>
#endif
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
using namespace std;
#define VPASSES 10
#define JITTER 0.01
float cameraAngleX=0, cameraAngleY=0, cameraDistance=0;
bool mouseLeftDown=false, mouseRightDown=false, mouseMiddleDown=false;
int mouseX=0, mouseY=0;
GLfloat *myVertices=NULL;
GLfloat *myNormals=NULL;
int verticeSize=0, normalSize=0, sides=0;
GLfloat VBObuff[1253340];
struct point{
float x;
float y;
float z;
};
class vec2{
public:
vec2() : x(0), y(0) {}
vec2(const double inx, const double iny) : x(inx), y(iny) {}
vec2(const vec2& in) : x(in.x), y(in.y) {}
vec2& operator=(const vec2& in){
if(this == &in) return *this;
x = in.x;
y = in.y;
return *this;
}
double x, y;
};
class vec3{
public:
vec3() : x(0), y(0), z(0) {}
vec3(const double inx, const double iny, const double inz) : x(inx), y(iny), z(inz) {}
vec3(const vec3& in) : x(in.x), y(in.y), z(in.z) {}
vec3& operator=(const vec3& in){
if(this == &in) return *this;
x = in.x;
y = in.y;
z = in.z;
return *this;
}
double x, y, z;
};
float eye[3]={0,3.0,5.0};
//for anti-aliasing
double genRand(){
return (((double)(random()+1))/2147483649.);
}
struct point cross(const struct point& u, const struct point& v){
struct point w;
w.x = u.y*v.z - u.z*v.y;
w.y = -(u.x*v.z - u.z*v.x);
w.z = u.x*v.y - u.y*v.x;
return(w);
}
struct point unit_length(const struct point& u){
double length;
struct point v;
length = sqrt(u.x*u.x+u.y*u.y+u.z*u.z);
v.x = u.x/length;
v.y = u.y/length;
v.z = u.z/length;
return(v);
}
void viewVolume(){
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, 1.0, 0.01, 1000.0);
glMatrixMode(GL_MODELVIEW);
}
//jitter view for anti-aliasing
void jitter_view(){
glLoadIdentity();
struct point jEye, view, up, vdir, utemp, vtemp;
jEye.x = eye[0]; jEye.y = eye[1]; jEye.z = eye[2];
view.x=JITTER*genRand(); view.y=JITTER*genRand(); view.z=JITTER*genRand();
up.x=0.0; up.y=1.0; up.z=0.0;
vdir.x = view.x - jEye.x; vdir.y = view.y - jEye.y; vdir.z = view.z - jEye.z;
//up vector orthogonal to vdir, in plane of vdir and (0,1,0)
vtemp = cross(vdir, up);
utemp = cross(vtemp, vdir);
up = unit_length(utemp);
gluLookAt(jEye.x,jEye.y,jEye.z,view.x,view.y,view.z,up.x,up.y,up.z);
}
void draw(){
int view_pass;
glClear(GL_ACCUM_BUFFER_BIT);
for(view_pass=0; view_pass < VPASSES; view_pass++){
jitter_view();
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES,0,sides);
glAccum(GL_ACCUM, 1.0/(float)(VPASSES));
}
glAccum(GL_RETURN, 1.0);
glFlush();
}
//3 point lighting
void lights(){
const float diff1 = .5;
const float spec1 = .5;
const float diff2 = .2;
const float spec2 = .2;
const float diff3 = .2;
const float spec3 = .2;
float key_ambient[]={0,0,0,0};
float key_diffuse[]={diff1,diff1,diff1,0};
float key_specular[]={spec1,spec1,spec1,0};
float key_position[]={-3,4,7.5,1};
float fill_ambient[]={0,0,0,0};
float fill_diffuse[]={diff2,diff2,diff2,0};
float fill_specular[]={spec2,spec2,spec2,0};
float fill_position[]={3.5,1,6.5,1};
float back_ambient[]={0,0,0,0};
float back_diffuse[]={diff3,diff3,diff3,0};
float back_specular[]={spec3,spec3,spec3,0};
float back_position[]={0,5,-6.5,1};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,key_ambient);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,1);
glLightfv(GL_LIGHT0,GL_AMBIENT,key_ambient);
glLightfv(GL_LIGHT0,GL_DIFFUSE,key_diffuse);
glLightfv(GL_LIGHT0,GL_SPECULAR,key_specular);
glLightf(GL_LIGHT0,GL_SPOT_EXPONENT, 1.0);
glLightf(GL_LIGHT0,GL_SPOT_CUTOFF, 180.0);
glLightf(GL_LIGHT0,GL_CONSTANT_ATTENUATION, .5);
glLightf(GL_LIGHT0,GL_LINEAR_ATTENUATION, .1);
glLightf(GL_LIGHT0,GL_QUADRATIC_ATTENUATION, .01);
glLightfv(GL_LIGHT0,GL_POSITION,key_position);
glLightfv(GL_LIGHT1,GL_AMBIENT,fill_ambient);
glLightfv(GL_LIGHT1,GL_DIFFUSE,fill_diffuse);
glLightfv(GL_LIGHT1,GL_SPECULAR,fill_specular);
glLightf(GL_LIGHT1,GL_SPOT_EXPONENT, 1.0);
glLightf(GL_LIGHT1,GL_SPOT_CUTOFF, 180.0);
glLightf(GL_LIGHT1,GL_CONSTANT_ATTENUATION, .5);
glLightf(GL_LIGHT1,GL_LINEAR_ATTENUATION, .1);
glLightf(GL_LIGHT1,GL_QUADRATIC_ATTENUATION, .01);
glLightfv(GL_LIGHT1,GL_POSITION,fill_position);
glLightfv(GL_LIGHT2,GL_AMBIENT,back_ambient);
glLightfv(GL_LIGHT2,GL_DIFFUSE,back_diffuse);
glLightfv(GL_LIGHT2,GL_SPECULAR,back_specular);
glLightf(GL_LIGHT2,GL_SPOT_EXPONENT, 1.0);
glLightf(GL_LIGHT2,GL_SPOT_CUTOFF, 180.0);
glLightf(GL_LIGHT2,GL_CONSTANT_ATTENUATION, .5);
glLightf(GL_LIGHT2,GL_LINEAR_ATTENUATION, .1);
glLightf(GL_LIGHT2,GL_QUADRATIC_ATTENUATION, .01);
glLightfv(GL_LIGHT2,GL_POSITION,back_position);
}
void material(){
//make our bunny a nice shade of pink
float mat_ambient[]={.2,0,0,1};
float mat_diffuse[]={1,.2,.2,1};
float mat_specular[] = {.5,.5,.5,1};
float mat_shininess[]={1.0};
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
}
GLuint mybuf = 1;
void initOGL(int argc, char **argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_ACCUM);
glutInitWindowSize(512,512);
glutInitWindowPosition(100,50);
glutCreateWindow("test");
glClearColor(.35,.35,.35,0);
glClearAccum(0.0,0.0,0.0,0.0);
viewVolume();
jitter_view();
lights();
material();
//buffer stuff for VBO
glBindBuffer(GL_ARRAY_BUFFER, mybuf);
glBufferData(GL_ARRAY_BUFFER, sizeof(VBObuff), VBObuff, GL_STATIC_DRAW);
glVertexPointer(3, GL_FLOAT, 3*sizeof(GLfloat), NULL+0);
glNormalPointer(GL_FLOAT, 3*sizeof(GLfloat), (GLvoid*)(NULL+626670*sizeof(GLfloat)));
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
}
void keyboard(unsigned char key, int x, int y){
switch(key){
case 'q':
glDeleteBuffers(1, &mybuf);
exit(1);
default: break;
}
}
bool loadObj(string filename,
vector <vec3> &vertices,
vector <vec2> &uvs,
vector <vec3> &normals)
{
vector<unsigned int> vertexIndices, uvIndices, normalIndices;
vector<vec3> temp_vertices;
vector<vec2> temp_uvs;
vector<vec3> temp_normals;
ifstream ifs(filename.c_str());
if(!ifs){
cout << "Error opening file: " << filename << endl;
return false;
}
string lineIn;
while(ifs >> lineIn){
if(lineIn.compare("v") == 0){
vec3 vertex;
ifs >> vertex.x >> vertex.y >> vertex.z;
temp_vertices.push_back(vertex);
}
else if(lineIn.compare("vt") == 0){
vec2 uv;
ifs >> uv.x >> uv.y;
temp_uvs.push_back(uv);
}
else if(lineIn.compare("vn") == 0){
vec3 normal;
ifs >> normal.x >> normal.y >> normal.z;
temp_normals.push_back(normal);
}
//scan vertex//normal
else if(lineIn.compare("f") == 0){
unsigned int vertIndex[3], normIndex[3];
ifs >> vertIndex[0];
ifs.ignore(1,'/'); ifs.ignore(1,'/');
ifs >> normIndex[0] >> vertIndex[1];
ifs.ignore(1,'/'); ifs.ignore(1,'/');
ifs >> normIndex[1] >> vertIndex[2];
ifs.ignore(1,'/'); ifs.ignore(1,'/');
ifs >> normIndex[2];
vertexIndices.push_back(vertIndex[0]);
vertexIndices.push_back(vertIndex[1]);
vertexIndices.push_back(vertIndex[2]);
normalIndices.push_back(normIndex[0]);
normalIndices.push_back(normIndex[1]);
normalIndices.push_back(normIndex[2]);
}
}
for(unsigned int i=0; i<vertexIndices.size(); i++){
unsigned int vertexIndex = vertexIndices[i];
vec3 vertex = temp_vertices[vertexIndex-1];
vertices.push_back(vertex);
}
for(unsigned int i=0; i<uvIndices.size(); i++){
unsigned int uvIndex = uvIndices[i];
vec2 uv = temp_uvs[uvIndex-1];
uvs.push_back(uv);
}
for(unsigned int i=0; i<normalIndices.size(); i++){
unsigned int normalIndex = normalIndices[i];
vec3 normal = temp_normals[normalIndex-1];
normals.push_back(normal);
}
return 1;
}
char *read_shader_program(const char *filename)
{
FILE *fp;
char *content = NULL;
int fd, count;
fd = open(filename,O_RDONLY);
count = lseek(fd,0,SEEK_END);
close(fd);
content = (char *)calloc(1,(count+1));
fp = fopen(filename,"r");
count = fread(content,sizeof(char),count,fp);
content[count] = '\0';
fclose(fp);
return content;
}
unsigned int set_shaders(){
GLint vertCompiled, fragCompiled;
char *vs, *fs;
GLuint v, f, p;
v = glCreateShader(GL_VERTEX_SHADER);
f = glCreateShader(GL_FRAGMENT_SHADER);
vs = read_shader_program("phong.vert");
fs = read_shader_program("phong.frag");
glShaderSource(v,1,(const char **)&vs,NULL);
glShaderSource(f,1,(const char **)&fs,NULL);
free(vs);
free(fs);
glCompileShader(v);
GLint shaderCompiled;
glGetShaderiv(v, GL_COMPILE_STATUS, &shaderCompiled);
if(shaderCompiled == GL_FALSE){
cout<<"ShaderCasher.cpp"<<"loadShader(s)"<<"Shader did not compile"<<endl;
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(v, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 0){
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(v, infologLength, &charsWritten, infoLog);
string log = infoLog;
cout<<log<<endl;
}
}
glCompileShader(f);
glGetShaderiv(f, GL_COMPILE_STATUS, &shaderCompiled);
if(shaderCompiled == GL_FALSE){
cout<<"ShaderCasher.cpp"<<"loadShader(f)"<<"Shader did not compile"<<endl;
int infologLength = 0;
int charsWritten = 0;
char *infoLog;
glGetShaderiv(f, GL_INFO_LOG_LENGTH,&infologLength);
if (infologLength > 0){
infoLog = (char *)malloc(infologLength);
glGetShaderInfoLog(f, infologLength, &charsWritten, infoLog);
string log = infoLog;
cout<<log<<endl;
}
}
p = glCreateProgram();
glAttachShader(p,f);
glAttachShader(p,v);
glLinkProgram(p);
glUseProgram(p);
return(p);
}
void set_uniform_parameters(unsigned int p)
{
int location;
location = glGetUniformLocation(p,"eye_position");
glUniform3fv(location,1,eye);
}
int main(int argc, char **argv){
srandom(123456789);
string filename= "bunny.obj";
vector <vec3> vertices2;
vector <vec2> uvs2;
vector <vec3> normals2;
if(!loadObj(filename, vertices2, uvs2, normals2)){
cout << "Could not read object.\n";
return 0;
}
//fill buffer
for(unsigned int i = 0; i<vertices2.size(); i++){
VBObuff[(i*3)]=vertices2[i].x;
VBObuff[(i*3)+1]=vertices2[i].y;
VBObuff[(i*3)+2]=vertices2[i].z;
verticeSize+=3;
}
for(unsigned int i = 0; i<normals2.size(); i++){
VBObuff[verticeSize+(i*3)]=normals2[i].x;
VBObuff[verticeSize+(i*3)+1]=normals2[i].y;
VBObuff[verticeSize+(i*3)+2]=normals2[i].z;
normalSize+=3;
}sides=verticeSize/3;
initOGL(argc, argv);
//quit function
glutKeyboardFunc(keyboard);
set_shaders();
glutDisplayFunc(draw);
glutMainLoop();
return 0;
}
| 90ca5b1657c5fa2a00d861008ba785adaed7bde4 | [
"C++"
] | 1 | C++ | gedison/openGL | 65453394035454ba8249d9c17fa67ecec18d8409 | cda3c0f6f08fc088b14d1bca6335005cfacf8b62 |
refs/heads/master | <repo_name>elharony/elharony.com<file_sep>/404.php
<?php get_header(); ?>
<main class="page-404 single">
<section class="hero">
<div class="container">
<h1 class="section-title">Page Not Found</h1>
<p>Sorry, the page you were looking for doesn't exist. It might have been removed, had its name changed, or is temporarily unavailable.</p>
<a href="<?php echo get_home_url(); ?>" class="btn btn-reversed">Back to Homepage</a>
</div>
</section>
<!-- blog -->
<section class="blog">
<div class="container">
<h2 class="section-title">Helpful Articles</h2>
<div class="blog-list">
<?php
$posts = get_posts(array(
'posts_per_page' => 6,
'orderby' => 'most_recent'
));
if ( $posts ) {
foreach ( $posts as $post ) :
setup_postdata( $post );
?>
<article>
<div class="inner">
<div class="thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('medium'); ?>
</a>
</div>
<div class="content">
<h3 class="title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<div class="brief"><?php the_excerpt() ?></div>
<?php the_category(''); ?>
<ul class="date">
<li class="day"><?php the_time('j'); ?></li>
<li class="month"><?php the_time('M'); ?></li>
</ul>
</div>
</div>
</article>
<?php
endforeach;
wp_reset_postdata();
}
?>
</div>
</div>
</section>
</main>
<?php get_footer(); ?><file_sep>/index.php
<?php get_header(); ?>
<main class="page-home">
<!-- about -->
<section class="about" id="about">
<div class="container">
<h1 class="section-title">
<NAME>
<span class="watermark">Hey, it's me</span>
</h1>
<div class="intro flex-container">
<div class="info">
<div class="details">
<p>
<strong>Frontend Lead</strong> @ <a href="https://www.webkeyz.com/">webkeyz</a> 🇪🇬
</p>
<p>
<strong>Web Development Mentor</strong> @ <a href="https://openclassrooms.com">OpenClassrooms</a> 🇫🇷
</p>
<p>
I <a href="/blog/">write articles</a>, build online products like; <a href="https://imeicheck.co" target="_blank">IMEICheck.co</a>, <a href="https://iphoneimeicheck.info" target="_blank">iPhoneIMEICheck.info</a>, <a href="https://emojicopypaste.co/" target="_blank">EmojiCopyPaste.co</a>, <a href="https://findfb.id/" target="_blank">FindFB.id</a>, and more!
</p>
</div>
<a href="https://www.elharony.com/Yahya-Elharony--Resume.pdf" class="btn btn-reversed">Download Resume</a>
<a href="/contact" class="btn">Let's Work Together</a>
</div>
<div class="empty">
<p>I used to put my picture here. <br>But I don't like it anymore, <br>Any ideas? <a href="/contact">Let me know</a></p>
</div>
</div>
</div>
</section>
<!-- blog -->
<section class="blog">
<div class="container">
<h2 class="section-title">Blog</h2>
<div class="blog-list">
<?php
$posts_args = array(
'post_type' => 'Post',
'post_status' => 'publish',
'orderby' => 'date',
'posts_per_page' => 6
);
// Custom query.
$posts = new WP_Query( $posts_args );
// Check that we have query results.
if ( $posts->have_posts() ) {
// Start looping over the query results.
while ( $posts->have_posts() ) {
$posts->the_post();
?>
<article>
<div class="inner">
<div class="thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('medium_large'); ?>
</a>
</div>
<div class="content">
<h3 class="title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<div class="brief"><?php the_excerpt() ?></div>
<?php the_category(''); ?>
<ul class="date">
<li class="day"><?php the_time('j'); ?></li>
<li class="month"><?php the_time('M'); ?></li>
</ul>
</div>
</div>
</article>
<?php
}
} else {
echo "<h4>Sorry, no posts available.</h4>";
}
// Restore original post data.
wp_reset_postdata();
?>
</div>
<a href="/blog/" class="btn">Show All</a>
</div>
</section>
<!-- Testimonials -->
<section class="testimonials" id="testimonials">
<div class="container">
<h2 class="section-title">Testimonials</h2>
<div class="testimonials-list">
<?php
$args = array(
'post_type' => 'testimonials',
'post_status' => 'publish',
'orderby' => 'rand',
'posts_per_page' => -1
);
$testimonials = new WP_Query( $args );
if( $testimonials->have_posts() ) :
while( $testimonials->have_posts() ) :
$testimonials->the_post();
?>
<div class="testimonial">
<div class="inner">
<div class="info">
<span class="client"><?php the_field('client'); ?></span>,
<span class="company"><?php the_field('job_title'); ?></span>
</div>
<div class="review">
<?php the_content(); ?>
</div>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
else :
echo "<h4>Sorry, no testimonials available.</h4>";
endif;
?>
</div>
</div>
</section>
</main>
<?php get_footer(); ?><file_sep>/functions.php
<?php
/*
* Theme Support
*/
add_theme_support("post-thumbnails");
/*
* add_styles
*/
function add_styles() {
wp_enqueue_style("main-css", get_template_directory_uri() . "/css/main.css");
}
function add_scripts() {
// wp_enqueue_script("jquery");
wp_enqueue_script("main-script", get_template_directory_uri() . "/js/app.js", array(), "", true);
// // Conditional Scripts [ Web Compatibility ]
// wp_enqueue_script("html5shiv", get_template_directory_uri() . "/js/html5shiv.min.js");
// wp_script_add_data("html5shiv", "conditional", "lt IE 9");
// wp_enqueue_script("respond", get_template_directory_uri() . "/js/respond.min.js");
// wp_script_add_data("respond", "conditional", "lt IE 9");
}
/*
* Menu
*
* Let our theme support WP menus and give them unique names
*
*/
function add_custom_menu() {
register_nav_menus(array(
"header" => "Main Navbar"
));
}
function display_menu() {
wp_nav_menu(array(
"theme-location" => "header",
"menu_class" => "menu-links",
"container" => false,
"depth" => 2,
));
}
/*
* custom_post_type_testimonials
*
* Create new Custom Page for the "Testimonials"
*
* @params: NO
* @return: NO
*/
function custom_post_type_testimonials() {
// Labels
$labels = array(
'name' => "Testimonials",
'singular_name' => "testimonials",
'menu_name' => 'Testimonials',
'add_new' => "Add Testimonial",
'add_new_item' => "Add New Testimonial",
'edit_item' => "Edit Testimonial",
'new_item' => "New Testimonial",
'view_item' => "View Testimonial",
'all_items' => "View all",
'search_items' => __("Search Testimonials"),
'not_found' => __("No Testimonials Found"),
'not_found_in_trash' => __("No Testimonials Found in Trash"),
'parent_item_colon' => ''
);
// Register post type
register_post_type('testimonials' , array(
'labels' => $labels,
'public' => true,
'has_archive' => false,
'menu_icon' => 'dashicons-book',
'rewrite' => false,
'supports' => array('title', 'editor', 'thumbnail')
) );
}
/*
* custom_post_type_clients
*
* Create new Custom Post Type for the "Clients"
*
* @params: NO
* @return: NO
*/
function custom_post_type_clients() {
// Labels
$labels = array(
'name' => "Clients",
'singular_name' => "clients",
'menu_name' => 'Clients',
'add_new' => "Add Client",
'add_new_item' => "Add New Client",
'edit_item' => "Edit Client",
'new_item' => "New Client",
'view_item' => "View Client",
'all_items' => "View all",
'search_items' => __("Search Clients"),
'not_found' => __("No Clients Found"),
'not_found_in_trash' => __("No Clients Found in Trash"),
'parent_item_colon' => ''
);
// Register post type
register_post_type('clients' , array(
'labels' => $labels,
'public' => true,
'has_archive' => false,
'menu_icon' => 'dashicons-groups',
'rewrite' => false,
'supports' => array('title', 'thumbnail')
) );
}
/*
* Limit the excerpt length
* Change the style of the read more; The default is […]
*/
function change_excerpt_length($length) {
return 30;
}
function change_excerpt_more($more) {
return " ...";
}
add_filter("excerpt_length", "change_excerpt_length");
add_filter("excerpt_more", "change_excerpt_more");
/*
* Hooks
*/
add_action("wp_enqueue_scripts", "add_styles");
add_action("wp_enqueue_scripts", "add_scripts");
add_action("init", "add_custom_menu");
add_action( 'init', 'custom_post_type_testimonials', 0 );
add_action( 'init', 'custom_post_type_clients', 0 );
add_filter("excerpt_length", "change_excerpt_length");
?><file_sep>/js/app.js
/*
* Responsive Menu
*/
const openMenuIcon = document.querySelector(".open-menu");
const closeMenuIcon = document.querySelector(".close-menu");
const menu = document.querySelector(".menu-links");
function openMenu() {
menu.style.left = 0;
openMenuIcon.style.display = "none";
closeMenuIcon.style.display = "block";
}
function closeMenu() {
menu.style.left = "-100%";
closeMenuIcon.style.display = "none";
openMenuIcon.style.display = "block";
}
openMenuIcon.addEventListener("click", () => {
openMenu();
})
closeMenuIcon.addEventListener("click", () => {
closeMenu();
})
// Hide menu after clicking on a link
const menuLinks = document.querySelectorAll(".menu-item");
for(let i = 0; i < menuLinks.length; i++) {
menuLinks[i].addEventListener('click', function () {
closeMenu();
})
}
// /*
// * Automatic Scrolling
// */
// const autoScrollingOn = document.querySelector(".auto-scrolling-on");
// const autoScrollingOff = document.querySelector(".auto-scrolling-off");
// const moreSection = document.querySelector(".related-articles");
// // Interval
// let autoScrolling;
// // On/Off Switches
// autoScrollingOn.addEventListener("click", () => {
// // Start Scrolling
// autoScrollOn();
// // Hide me
// autoScrollingOn.classList.replace("show", "hide");
// // Show the other Switch
// autoScrollingOff.classList.replace("hide", "show");
// });
// autoScrollingOff.addEventListener("click", () => {
// // Start Scrolling
// autoScrollOff();
// // Hide me
// autoScrollingOff.classList.replace("show", "hide");
// // Show the other Switch
// autoScrollingOn.classList.replace("hide", "show");
// });
// // Auto Scrolling [ON]
// function autoScrollOn() {
// let scrollTop = window.scrollY;
// autoScrolling = setInterval( () => {
// scrollTop += 1;
// window.scrollTo({
// top: scrollTop,
// behavior: "smooth"
// })
// // Stop Scrolling if reaches the end of article
// if(scrollTop > moreSection.offsetTop) {
// clearInterval(autoScrolling);
// }
// }, 100);
// }
// // Auto Scrolling [OFF]
// function autoScrollOff() {
// clearInterval(autoScrolling);
// }<file_sep>/footer.php
<footer>
<div class="container">
<div class="footer-content">
<p class="copyrights">Elharony © <?php echo date("Y"); ?></p>
<ul class="contact-links">
<li>
<a href="https://github.com/elharony" title="<NAME> on Github">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 0h-14c-2.761 0-5 2.239-5 5v14c0 2.761 2.239 5 5 5h14c2.762 0 5-2.239 5-5v-14c0-2.761-2.238-5-5-5zm-4.466 19.59c-.405.078-.534-.171-.534-.384v-2.195c0-.747-.262-1.233-.55-1.481 1.782-.198 3.654-.875 3.654-3.947 0-.874-.312-1.588-.823-2.147.082-.202.356-1.016-.079-2.117 0 0-.671-.215-2.198.82-.64-.18-1.324-.267-2.004-.271-.68.003-1.364.091-2.003.269-1.528-1.035-2.2-.82-2.2-.82-.434 1.102-.16 1.915-.077 2.118-.512.56-.824 1.273-.824 2.147 0 3.064 1.867 3.751 3.645 3.954-.229.2-.436.552-.508 1.07-.457.204-1.614.557-2.328-.666 0 0-.423-.768-1.227-.825 0 0-.78-.01-.055.487 0 0 .525.246.889 1.17 0 0 .463 1.428 2.688.944v1.489c0 .211-.129.459-.528.385-3.18-1.057-5.472-4.056-5.472-7.59 0-4.419 3.582-8 8-8s8 3.581 8 8c0 3.533-2.289 6.531-5.466 7.59z"/></svg>
</a>
<a href="https://www.linkedin.com/in/elharony/" title="<NAME> on LinkedIn">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 0h-14c-2.761 0-5 2.239-5 5v14c0 2.761 2.239 5 5 5h14c2.762 0 5-2.239 5-5v-14c0-2.761-2.238-5-5-5zm-11 19h-3v-11h3v11zm-1.5-12.268c-.966 0-1.75-.79-1.75-1.764s.784-1.764 1.75-1.764 1.75.79 1.75 1.764-.783 1.764-1.75 1.764zm13.5 12.268h-3v-5.604c0-3.368-4-3.113-4 0v5.604h-3v-11h3v1.765c1.396-2.586 7-2.777 7 2.476v6.759z"/></svg>
</a>
<a href="https://www.youtube.com/channel/UCcWSbBe_s-T_gZRnqFbtyIA" title="<NAME> on YouTube">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M10 9.333l5.333 2.662-5.333 2.672v-5.334zm14-4.333v14c0 2.761-2.238 5-5 5h-14c-2.761 0-5-2.239-5-5v-14c0-2.761 2.239-5 5-5h14c2.762 0 5 2.239 5 5zm-4 7c-.02-4.123-.323-5.7-2.923-5.877-2.403-.164-7.754-.163-10.153 0-2.598.177-2.904 1.747-2.924 5.877.02 4.123.323 5.7 2.923 5.877 2.399.163 7.75.164 10.153 0 2.598-.177 2.904-1.747 2.924-5.877z"/></svg>
</a>
<!-- <a href="https://www.facebook.com/elharony" title="<NAME> on Facebook"><i class="fab fa-facebook fa-fw"></i></a> -->
<!-- <a href="https://twitter.com/Yahya_Elharony" title="<NAME> on Twitter"><i class="fab fa-twitter fa-fw"></i></a> -->
<!-- <a href="https://stackoverflow.com/users/5560399/elharony" title="<NAME> on StackOverflow"><i class="fab fa-stack-overflow fa-fw"></i></a> -->
<!-- <a href="https://medium.com/@elharony" title="<NAME> on Medium"><i class="fab fa-medium fa-fw"></i></a> -->
</li>
</ul>
</div>
</div>
</footer>
<?php wp_footer(); ?>
<!-- Tidio Livechat -->
<!-- <script src="//code.tidio.co/p3rqljn7k0thhq4wbagbtttf2upb98pf.js"></script> -->
</body>
</html><file_sep>/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-128258295-1"></script>
<script>
// Don't count the Development Traffic!
var host = window.location.hostname;
if(host != "localhost")
{
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-128258295-1');
}
</script>
<meta charset="<?php bloginfo("charset"); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- SEO Essentials -->
<title>
<?php is_front_page() ? bloginfo("name") : wp_title("»", true, "right")?>
</title>
<?php
if(is_front_page()) {
?>
<meta name="description" content="<?php bloginfo('description'); ?>">
<!-- Favicon -->
<link rel="icon" type="image/png" sizes="32x32" href="<?php echo get_template_directory_uri(); ?>/img/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="<?php echo get_template_directory_uri(); ?>/img/favicon/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo get_template_directory_uri(); ?>/img/favicon/favicon-16x16.png">
<!-- Social Media Sharing Details -->
<meta property="og:title" content="<?php bloginfo("name"); ?>"/>
<meta property="og:description" content="<?php bloginfo('description'); ?>"/>
<meta property="og:url" content="https://www.elharony.com"/>
<meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/img/Yahya-Elharony-Social-Media-Post-Image.jpg"/>
<?php
}
?>
<?php wp_head(); ?>
</head>
<body>
<header>
<div class="container">
<nav>
<a href="<?php bloginfo("url"); ?>" class="logo">
<img src="<?php echo get_template_directory_uri(); ?>/img/logo.jpg" alt="Yahya Elharony - Logo" width="165" height="50">
</a>
<div class="toggle-menu">
<span class="open-menu">
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 294.843 294.843" style="enable-background:new 0 0 294.843 294.843;" xml:space="preserve">
<g><path d="M147.421,0C66.133,0,0,66.133,0,147.421c0,40.968,17.259,80.425,47.351,108.255c2.433,2.25,6.229,2.101,8.479-0.331 c2.25-2.434,2.102-6.229-0.332-8.479C27.854,221.3,12,185.054,12,147.421C12,72.75,72.75,12,147.421,12 s135.421,60.75,135.421,135.421s-60.75,135.421-135.421,135.421c-3.313,0-6,2.687-6,6s2.687,6,6,6 c81.289,0,147.421-66.133,147.421-147.421S228.71,0,147.421,0z"/><path d="M84.185,90.185h126.473c3.313,0,6-2.687,6-6s-2.687-6-6-6H84.185c-3.313,0-6,2.687-6,6S80.872,90.185,84.185,90.185z"/><path d="M84.185,153.421h126.473c3.313,0,6-2.687,6-6s-2.687-6-6-6H84.185c-3.313,0-6,2.687-6,6S80.872,153.421,84.185,153.421z"/><path d="M216.658,210.658c0-3.313-2.687-6-6-6H84.185c-3.313,0-6,2.687-6,6s2.687,6,6,6h126.473 C213.971,216.658,216.658,213.971,216.658,210.658z"/></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g><g></g>
</svg>
</span>
<span class="close-menu">
<svg enable-background="new 0 0 40 40" id="Слой_1" version="1.1" viewBox="0 0 40 40" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g><path d="M28.1,26.8c0.4,0.4,0.4,1,0,1.4c-0.2,0.2-0.5,0.3-0.7,0.3s-0.5-0.1-0.7-0.3l-6.8-6.8l-6.8,6.8c-0.2,0.2-0.5,0.3-0.7,0.3 s-0.5-0.1-0.7-0.3c-0.4-0.4-0.4-1,0-1.4l6.8-6.8l-6.8-6.8c-0.4-0.4-0.4-1,0-1.4c0.4-0.4,1-0.4,1.4,0l6.8,6.8l6.8-6.8 c0.4-0.4,1-0.4,1.4,0c0.4,0.4,0.4,1,0,1.4L21.3,20L28.1,26.8z"/></g><g><path d="M19.9,40c-11,0-20-9-20-20s9-20,20-20c4.5,0,8.7,1.5,12.3,4.2c0.4,0.3,0.5,1,0.2,1.4c-0.3,0.4-1,0.5-1.4,0.2 c-3.2-2.5-7-3.8-11-3.8c-9.9,0-18,8.1-18,18s8.1,18,18,18s18-8.1,18-18c0-3.2-0.9-6.4-2.5-9.2c-0.3-0.5-0.1-1.1,0.3-1.4 c0.5-0.3,1.1-0.1,1.4,0.3c1.8,3.1,2.8,6.6,2.8,10.2C39.9,31,30.9,40,19.9,40z"/></g>
</svg>
</span>
</div>
<?php display_menu() ?>
<!-- <a class="kofi-button" target="_blank" rel="noopener noreferrer" href="https://ko-fi.com/elharony" aria-label="Buy me a coffee!" title="Buy me a coffee!"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWEAAADkCAYAAABJ9ZUIAAABG2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4KPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS41LjAiPgogPHJkZjpSREYgeG1sbnM6cmRmPS<KEY>" alt="Kofi" class="kofi"></a> -->
</nav>
</div>
</header><file_sep>/single.php
<?php get_header(); ?>
<?php
// Retrieve Data
the_post();
?>
<main class="single-article">
<section class="hero">
<div class="container">
<div class="flex-container">
<ul class="article-date">
<li class="day"><?php the_time('j'); ?></li>
<li class="month"><?php the_time('F'); ?></li>
</ul>
<div class="article-meta">
<h1 class="title"><?php the_title(); ?></h1>
<span class="category"><?php the_category(' - '); ?></span>
</div>
</div>
<!-- <ul class="article-info">
<li>Published On: <time><?php the_time('F j, Y'); ?></time></li>
<li>In: <?php the_category(' - '); ?></li>
</ul> -->
</div>
</section>
<!-- <div class="article-controls">
<div class="container">
<div class="reading-mode">
<button class="auto-scrolling-on show btn" title="Start Reading Mode"><i class="fas fa-book-open fa-fw"></i></button>
<button class="auto-scrolling-off hide btn" title="Back to Normal"><i class="fas fa-eye fa-fw"></i></button>
</div>
</div>
</div> -->
<article class="article-body">
<div class="container">
<?php the_content(); ?>
</div>
</article>
<section class="comments">
<div class="container">
<?php
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
?>
</div>
</section>
<?php
//for use in the loop, list 5 post titles related to first tag on current post
$categories = get_the_category($post->ID);
if ($categories) {
$first_category = $categories[0]->term_id;
$args=array (
'category__in' => array($first_category),
'post__not_in' => array($post->ID),
'posts_per_page'=>6,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
?>
<!-- Related Articles -->
<section class="related-articles blog">
<div class="container">
<h3 class="section-title">Related Articles</h3>
<div class="blog-list">
<?php
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<!-- Related Post -->
<article>
<div class="inner">
<div class="thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('medium_large'); ?>
</a>
</div>
<div class="content">
<h3 class="title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<div class="brief"><?php the_excerpt() ?></div>
<?php the_category(''); ?>
<ul class="date">
<li class="day"><?php the_time('j'); ?></li>
<li class="month"><?php the_time('M'); ?></li>
</ul>
</div>
</div>
</article>
<?php
}
?>
</div>
</div>
</section>
<?php
} else {
}
wp_reset_query();
}
?>
</main>
<?php get_footer(); ?><file_sep>/README.md
# Elharony | A Personal Blog
Portfolio Website Theme built from Scratch using WordPress CMS
> **It is still a beta version!**
<file_sep>/page-blog.php
<?php
get_header(); ?>
<main class="archive single">
<section class="hero">
<div class="container">
<h1 class="section-title">Blog</h1>
</div>
</section>
<!-- blog -->
<section class="blog">
<div class="container">
<div class="blog-list">
<?php
$posts_args = array(
'posts_per_page' => 20,
'orderby' => 'most_recent'
);
$the_posts = new WP_Query( $posts_args );
if ( have_posts() ) {
while ( $the_posts->have_posts() ) {
$the_posts->the_post();
?>
<article>
<div class="inner">
<div class="thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('medium_large'); ?>
</a>
</div>
<div class="content">
<h3 class="title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<div class="brief"><?php the_excerpt() ?></div>
<?php the_category(''); ?>
<ul class="date">
<li class="day"><?php the_time('j'); ?></li>
<li class="month"><?php the_time('M'); ?></li>
</ul>
</div>
</div>
</article>
<?php
} // end while
} else {
echo "Sorry, There is no posts";
} // end if
wp_reset_postdata();
?>
</div>
</div>
</section>
</main>
<?php
get_footer();<file_sep>/category.php
<?php
get_header(); ?>
<main class="archive single">
<section class="hero">
<div class="container">
<h1 class="section-title">"<?php echo single_cat_title( '', false ); ?>" Articles</h1>
</div>
</section>
<section class="blog">
<div class="container">
<div class="blog-list">
<?php if ( have_posts() ) : ?>
<?php
// Start the Loop.
while ( have_posts() ) :
the_post();
// Get Categories as Links
$categories = get_the_category();
$separator = ' - ';
$output = '';
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
$output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
?>
<article>
<div class="inner">
<div class="thumbnail">
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('medium_large'); ?>
</a>
</div>
<div class="content">
<h3 class="title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<div class="brief"><?php the_excerpt() ?></div>
<?php the_category(''); ?>
<ul class="date">
<li class="day"><?php the_time('j'); ?></li>
<li class="month"><?php the_time('M'); ?></li>
</ul>
</div>
</div>
</article>
<?php
} // end categories condition
endwhile;
else :
// If no content, include the "No posts found" template.
echo "<h4>Sorry, no posts available.</h4>";
endif;
?>
</div>
</div>
</section>
</main>
<?php
get_footer();<file_sep>/page-contact.php
<?php
get_header(); ?>
<main class="page-contact single">
<section class="hero">
<div class="container">
<h1 class="section-title">Reach me out</h1>
</div>
</section>
<section class="contact-form">
<div class="container">
<?php echo do_shortcode('[ninja_form id=3]'); ?>
</div>
</section>
</main>
<?php
get_footer(); | 9c785112d87be4ee4b73da2210dc04d26c2679e8 | [
"JavaScript",
"Markdown",
"PHP"
] | 11 | PHP | elharony/elharony.com | 2e665458743f6c481eb6ba6f456ef157be90a8a7 | 9a7e8b529f4f9a277dcfc1591b92b6c02e3812b4 |
refs/heads/master | <repo_name>rioderelfte/colorizer<file_sep>/Library/colorizer.sh
####
# Copyright (c) 2012, <NAME> <<EMAIL>>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
####
source "${COLORIZE_SH_SOURCE_DIR:-$( cd "$( dirname "${BASH_SOURCE:-${0}}" )" && pwd )}/Compatibility/compatibility.sh"
# Escape codes
COLORIZER_START="\033["
COLORIZER_END="m"
# Default colors
COLORIZER_blue="0;34"
COLORIZER_green="0;32"
COLORIZER_cyan="0;36"
COLORIZER_red="0;31"
COLORIZER_purple="0;35"
COLORIZER_yellow="0;33"
COLORIZER_gray="1;30"
COLORIZER_light_blue="1;34"
COLORIZER_light_green="1;32"
COLORIZER_light_cyan="1;36"
COLORIZER_light_red="1;31"
COLORIZER_light_purple="1;35"
COLORIZER_light_yellow="1;33"
COLORIZER_light_gray="0;37"
# Somewhat special colors
COLORIZER_black="0;30"
COLORIZER_white="1;37"
COLORIZER_none="0"
##
# Add escape sequences to defined color codes
#
# Must never be called outside of this script, as it only is allowed to be
# called once
#
# It's only a function to allow local variables
##
COLORIZER_add_escape_sequences() {
local color
for color in blue green cyan red purple yellow gray; do
eval "COLORIZER_${color}=\"\${COLORIZER_START}\${COLORIZER_${color}}\${COLORIZER_END}\""
eval "COLORIZER_light_${color}=\"\${COLORIZER_START}\${COLORIZER_light_${color}}\${COLORIZER_END}\""
done
for color in black white none; do
eval "COLORIZER_${color}=\"\${COLORIZER_START}\${COLORIZER_${color}}\${COLORIZER_END}\""
done
}
##
# Parse the input and return the ansi code output processed output
##
COLORIZER_process_input() {
local processed="${*}"
local pseudoTag=""
local stack
ARRAY_define "stack"
local result=""
result="${processed%%<*}"
if [ "${result}" != "" ] && [ "${result}" != "${processed}" ]; then
# Cut outer content, which has been processed already
processed="<${processed#*<}"
fi
while [ "${processed#*<}" != "${processed}" ]; do
# Isolate first tag in stream
pseudoTag="${processed#*<}"
pseudoTag="${pseudoTag%%>*}"
# Push/Pop tag to/from stack
if [ "${pseudoTag:0:1}" != "/" ]; then
ARRAY_push "stack" "${pseudoTag}"
else
if [ "${pseudoTag:1}" != "$(ARRAY_peek "stack")" ]; then
echo "Mismatching colorize tag nesting at <$(ARRAY_peek "stack")>...<${pseudoTag}>"
exit 42
fi
ARRAY_pop "stack" >/dev/null
fi
# Apply ansi formatting
pseudoTag="${pseudoTag/-/_}"
if [ "${pseudoTag:0:1}" != "/" ]; then
# Opening Tag
eval "result=\"\${result}\${COLORIZER_${pseudoTag}}\""
else
# Closing Tag
if [ "$(ARRAY_count "stack")" -eq 0 ]; then
result="${result}${COLORIZER_none}"
else
eval "result=\"\${result}\${COLORIZER_$(ARRAY_peek "stack")}\""
fi
fi
# Cut processed portion from stream
processed="${processed#*>}"
# Update result with next content part
result="${result}${processed%%<*}"
done
if [ "$(ARRAY_count "stack")" -ne 0 ]; then
echo "Could not find closing tag for <$(ARRAY_peek "stack")>"
exit 42
fi
result="${result//</<}"
result="${result//>/>}"
echo "${result}"
}
##
# Parse a given colorize string and output the correctly escaped ansi-code
# formatted string for it.
#
# This function is the only public API method to this utillity
#
# echo -e is used for output.
#
# The -n option may be specified, which will behave exactly like echo -n, aka
# omitting the newline.
#
# @option -n omit the newline
# @param [string,...]
##
colorize() {
local OPTIND=1
local newline_option=""
local option=""
while getopts ":n" option; do
case "${option}" in
n) newline_option="SET";;
\?) echo "Invalid option (-${OPTARG}) given to colorize"; exit 42;;
esac
done
shift $((OPTIND-1))
local processed_message="$(COLORIZER_process_input "${@}")"
if [ "${newline_option}" = "SET" ]; then
echo -en "${processed_message}"
else
echo -e "${processed_message}"
fi
}
# Allow alternate spelling
alias colourise=colorize
# Initialize the color codes
COLORIZER_add_escape_sequences
<file_sep>/README.md
# Colorizer - A bash library for XML-like ansi coloring
**Colorizer** allows the easy usage of ANSI color coded output in shell scripts
using an XML-like syntax
## Usage and Examples
Simply call the `colorize` function instead of using `echo` supplying an
XML-like color definition
colorize "Hey <red>attention</red>! the before seen is <light-red>red</light-red>"
**Colorizer** automatically injects the ANSI colorcodes needed to output the
given string in the correct color.
Nested tags are possible as well:
colorize "<green>This is a <yellow>yellow colored</yellow> string inside a green one</green>"
Due to the XML-like nature of the used definition language `<` (less than) and
`>` (greater than) characters can no longer be used inside the provided string.
You need to escape them using their usual XML entity representation:
colorize "<cyan>1</cyan> < <purple>2</purple>"
**Colorizer** used the `echo -e` command to output the formatted information.
Therefore a newline is automatically echoed at the end of the string. If you do
not want to output this newline just supply the `-n` option to `colorize`. In
this case `echo -en` is used for output to suppress the newline:
colorize -n "<blue>Question:</blue> Do you think this library rocks? [Y/n]"
Mismatched tags as well as missing start or end tags will be detected. In this
case an error message indicating the problem will be echoed back as well as an
exit with errorcode *42* will be issued.
### Aliases
As *colorize* and *colourise* is differently spelled in american and british
english an alias is defined for the `colorize` function. Therefore you may
substitute it with the `colourise` command without thinking about it.
## Loading the Library
Before you can use the library you need to load it into your bash script.
A simple call to the `source` function will enable you to do this:
source "folder/to/Colorizer/Library/colorizer.sh"
After that the `colorize` function is available and works as expected.
If your shell does neither set `$BASH_SOURCE` nor `$0` in the sourced file, you
have to manually define the variable `COLORIZE_SH_SOURCE_DIR` to the directory
containing the `colorize.sh` file.
## Available Color-Tags
Currently all *16* default ANSI terminal colors are supported. Maybe support
for the extended 256 colors modern terminals are capable of displaying will be
added in the future.
Currently the following tags are supported:
<table>
<tr>
<th>Color Tag</th><th>Generated ANSI Code</th>
</tr>
<tr>
<td><<b>red</b>>…</red></td><td>\033[0;31m</td>
</tr>
<tr>
<td><<b>green</b>>…</green></td><td>\033[0;32m</td>
</tr>
<tr>
<td><<b>yellow</b>>…</yellow></td><td>\033[0;33m</td>
</tr>
<tr>
<td><<b>blue</b>>…</blue></td><td>\033[0;34m</td>
</tr>
<tr>
<td><<b>purple</b>>…</purple></td><td>\033[0;35m</td>
</tr>
<tr>
<td><<b>cyan</b>>…</cyan></td><td>\033[0;36m</td>
</tr>
<tr>
<td><<b>light-red</b>>…</light-red></td><td>\033[1;31m</td>
</tr>
<tr>
<td><<b>light-green</b>>…</light-green></td><td>\033[1;32m</td>
</tr>
<tr>
<td><<b>light-yellow</b>>…</light-yellow></td><td>\033[1;33m</td>
</tr>
<tr>
<td><<b>light-blue</b>>…</light-blue></td><td>\033[1;34m</td>
</tr>
<tr>
<td><<b>light-purple</b>>…</light-purple></td><td>\033[1;35m</td>
</tr>
<tr>
<td><<b>light-cyan</b>>…</light-cyan></td><td>\033[1;36m</td>
</tr>
<tr>
<td><<b>gray</b>>…</gray></td><td>\033[1;30m</td>
</tr>
<tr>
<td><<b>light-gray</b>>…</light-gray></td><td>\033[0;37m</td>
</tr>
<tr>
<td><<b>white</b>>…</white></td><td>\033[1;37m</td>
</tr>
<tr>
<td><<b>black</b>>…</black></td><td>\033[0;30m</td>
</tr>
<tr>
<td><<b>none</b>>…</none></td><td>\033[0m</td>
</tr>
<tr>
</table>
## Limitations
Currently this library has only been tested with the
[Bash](http://www.gnu.org/software/bash/) (>3.x),
[ZSH](http://zsh.sourceforge.net/) shell (>5.x) and
[busybox](http://www.busybox.net/) ash. The code should run in every POSIX
compatible shell as well, but I didn't have the time to test those yet.
**Colorizer** uses a lot of quite sophisticated variable expansion features, to
do all the XML-tag extraction and parsing using only shell builtins to provide
a fast and nice user experience. Therefore making the library compatible
with less powerful shells may be a difficult task. However a compatibility
layer exists, which may allow implementation of complex tasks for different shells.
Background color setting is currently not supported. I simply don't have real
demand for that in most of my scripts. If you want this feature just drop me
a line, maybe with an example how the syntax for this could look. I will see
what I can do then. :)
## How you can help
If you have got some time and are using currently untested shells, I would love
some feedback about the compatibility of this library with your environment.
If you are interested in porting this library over to another shell
environment, any pull request with compatibility updates will be great. Error
output and information about your shell may help me as well.
| 5bff1820d8757b2e60e8f7d6410612f2ad648f5c | [
"Markdown",
"Shell"
] | 2 | Shell | rioderelfte/colorizer | 71dfbf4e47b979ea8a4ba986c65212974f651e55 | 9a9794fe2745b895b1748fe618b50e3d534fd662 |
refs/heads/master | <repo_name>rukowen/Hotel-Management_MINF10-HCM<file_sep>/HotelManagement/src/business/Reservation.java
package business;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import connect.sqlite.ConnectData;
import connect.sqlite.SQLItem;
import connect.sqlite.SQLSupport;
public class Reservation implements IReservation{
int resID;
int customerID;
Date resDate;
Date resLeaveDate;
double preTotalCost;
int numberOfAdult;
int numberOfChild;
int resStatus;
ConnectData conn;
public Reservation(){
}
public Reservation(int resID){
try {
this.resID = resID;
String sql = "select * from Reservation where resID = " + resID;
conn = new ConnectData();
conn.connect();
ResultSet rs = conn.ExcuteQuery(sql);
while(rs.next()){
this.resID = resID;
this.customerID = rs.getInt("customerID");
this.resDate = rs.getDate("resDate");
this.resLeaveDate = rs.getDate("resLeaveDate");
this.preTotalCost = rs.getDouble("preTotalCost");
this.numberOfAdult = rs.getInt("numberOfAdult");
this.numberOfChild = rs.getInt("numberOfChild");
this.resStatus = rs.getInt("resStatus");
}
conn.dispose();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getResID() {
return resID;
}
public void setResID(int resID) {
this.resID = resID;
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public Date getResDate() {
return resDate;
}
public void setResDate(Date resDate) {
this.resDate = resDate;
}
public Date getResLeaveDate() {
return resLeaveDate;
}
public void setResLeaveDate(Date resLeaveDate) {
this.resLeaveDate = resLeaveDate;
}
public double getPreTotalCost() {
return preTotalCost;
}
public void setPreTotalCost(double preTotalCost) {
this.preTotalCost = preTotalCost;
}
public int getNumberOfAdult() {
return numberOfAdult;
}
public void setNumberOfAdult(int numberOfAdult) {
this.numberOfAdult = numberOfAdult;
}
public int getNumberOfChild() {
return numberOfChild;
}
public void setNumberOfChild(int numberOfChild) {
this.numberOfChild = numberOfChild;
}
public int getResStatus() {
return resStatus;
}
public void setResStatus(int resStatus) {
this.resStatus = resStatus;
}
public Reservation(int resID, int customerID, Date resDate, Date resLeaveDate, double preTotalCost, int numberOfAdult, int numberOfChild, int resStatus){
this.resID = resID;
this.customerID = customerID;
this.resDate = resDate;
this.resLeaveDate = resLeaveDate;
this.preTotalCost = preTotalCost;
this.numberOfAdult = numberOfAdult;
this.numberOfChild = numberOfChild;
this.resStatus = resStatus;
}
public Reservation(int customerID, Date resDate, Date resLeaveDate, double preTotalCost, int numberOfAdult, int numberOfChild, int resStatus){
this.customerID = customerID;
this.resDate = resDate;
this.resLeaveDate = resLeaveDate;
this.preTotalCost = preTotalCost;
this.numberOfAdult = numberOfAdult;
this.numberOfChild = numberOfChild;
this.resStatus = resStatus;
}
@Override
public int addReservation() {
// TODO Auto-generated method stub
ArrayList<SQLItem> items = new ArrayList<SQLItem>();
items.add(new SQLItem(1, "resID", null));
items.add(new SQLItem(1, "customerID", customerID));
items.add(new SQLItem(1, "resDate", resDate));
items.add(new SQLItem(1, "resLeaveDate", resLeaveDate));
items.add(new SQLItem(1, "preTotalCost", preTotalCost));
items.add(new SQLItem(1, "numberOfAdult", numberOfAdult));
items.add(new SQLItem(1, "numberOfChild", numberOfChild));
items.add(new SQLItem(1, "resStatus", resStatus));
String sql = SQLSupport.prepareAddSql("Reservation", items);
System.out.println(sql);
conn = new ConnectData();
conn.connect();
int reID = conn.queryExcuteUpdateGenerateKey(sql);
try {
conn.dispose();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return reID;
}
@Override
public boolean updateReservation() {
// TODO Auto-generated method stub
return false;
}
//update status: 0: reserved. 1: occupied. 2: complete. 3: cancel
@Override
public boolean cancelReservation() {
// TODO Auto-generated method stub
String sql = "UPDATE Reservation set resStatus = 3 where resID = " + resID;
conn = new ConnectData();
conn.connect();
boolean isOk = conn.queryExcuteUpdate(sql);
return isOk;
}
@Override
public boolean addServices() {
// TODO Auto-generated method stub
return false;
}
@Override
public double getPreAmount() {
// TODO Auto-generated method stub
return 0;
}
public static ResultSet searchReservation(){
return null;
}
public static boolean cancelReservation(int resID){
String sql = "UPDATE Reservation set resStatus = 3 where resID = " + resID;
ConnectData conn = new ConnectData();
conn.connect();
boolean isOk = conn.queryExcuteUpdate(sql);
return isOk;
}
}
<file_sep>/HotelManagement/src/business/ReservationDetailService.java
package business;
import java.sql.SQLException;
import connect.sqlite.ConnectData;
public class ReservationDetailService {
int resDetailServiceID;
int resDetailID;
int serviceID;
int qtyOfService;
ConnectData conn;
public ReservationDetailService(){
}
public ReservationDetailService(int resDetailID, int serviceID, int qtyOfService){
this.resDetailID = resDetailID;
this.serviceID = serviceID;
this.qtyOfService = qtyOfService;
}
public int addReservationServiceDetail(){
conn = new ConnectData();
conn.connect();
String sql ="insert into RoomStatus values(null, "+ resDetailID + ", " + serviceID + ", " + qtyOfService +")";
int reID = conn.queryExcuteUpdateGenerateKey(sql);
this.resDetailServiceID = reID;
try {
conn.dispose();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return reID;
}
}
<file_sep>/HotelManagement/src/Movie.java
// From book: 'Refactoring' by <NAME>
// This is the original code before refactoring begins
public class Movie {
private static final int CHILDRENS = 2;
private static final int NEWRELEASE = 1;
private static final int REGULAR = 0;
private String _title;
private int _priceCode;
private Movie(String title, int priceCode) {
_title = title;
_priceCode = priceCode;
}
public int getPriceCode() {
return _priceCode;
}
public void setPriceCode(int arg) {
_priceCode = arg;
}
public String getTitle() {
return _title;
}
double charge(int daysRented) {
double result = 0;
switch (_priceCode) {
case REGULAR:
result += 2;
if (daysRented > 2)
result += (daysRented - 2) * 1.5;
break;
case NEWRELEASE:
result += daysRented * 3;
break;
case CHILDRENS:
result += 1.5;
if (daysRented > 3)
result += (daysRented - 3) * 1.5;
break;
}
return result;
}
public static Movie createChildrenMovie(String title) {
return new Movie(title, CHILDRENS);
}
public static Movie createRegularMovie(String title) {
return new Movie(title, REGULAR);
}
public static Movie createNewReleaseMovie(String title) {
return new Movie(title, NEWRELEASE);
}
public int getRenterPoints(int daysRented) {
if ((getPriceCode() == Movie.NEWRELEASE) && daysRented > 1) return 2;
else return 1;
}
}
| eb443ca5780f43271658b320cdd5671d9397c0d0 | [
"Java"
] | 3 | Java | rukowen/Hotel-Management_MINF10-HCM | df60384ae4fb09d03da88dc31b846c9c841dd743 | 46a416808a9582e6223a33cc77f751f2f9e19b10 |
refs/heads/main | <repo_name>mpochopien/detect-page-visit<file_sep>/index.php
<?php
//To capture visit include this code in
require_once "func/func.php";
captureVisit();
?>
<!-- Rest of the page content -->
Hello world<file_sep>/func/func.php
<?php
require(dirname(__DIR__) . '/vendor/autoload.php');
use Sinergi\BrowserDetector;
ini_set('display_errors', 0);
function captureVisit()
{
$browser = new BrowserDetector\Browser();
$os = new BrowserDetector\Os();
$device = new BrowserDetector\Device();
$ipAddress = $_SERVER['REMOTE_ADDR'];
$log =
"[" . date("Y-m-d H:i:s") . "] " .
"Browser - " . $browser->getName() . " " . $browser->getVersion() . " | " .
"OS - " . $os->getName() . " | " .
"Device - " . $device->getName() . " | " .
$ipAddress . PHP_EOL;
$logFile = fopen(dirname(__DIR__) . "/func/visitLog.txt", "a") or die();
fwrite($logFile, $log);
fclose($logFile);
}<file_sep>/README.md
# detect-page-visit
# Instalation:
1. You have to have composer installed on your OS to install dependecies. Then, execute: `composer install` in main directory.
2. Replace `index.php` with your page content.
3. Remeber to connect page content to function - see `index.php`.
All logs will be stored in `func` folder, in text file. Text file format:
`[date_and_time] Browser - browser_version | OS - system_name | Device - device_type | ip_address` | 1cdab00a008e83cafda1e2150834136b50886f58 | [
"Markdown",
"PHP"
] | 3 | PHP | mpochopien/detect-page-visit | 170aa12155cea1c01004083f43b022fb6887eef7 | cf22a6f7fc69f07ef368fbd149c0b12e2201d994 |
refs/heads/master | <repo_name>omshiv2415/test-bank<file_sep>/app/models/employee.rb
class Employee < ActiveRecord::Base
validates :fullname, presence: true
validates :address, presence: true
validates :phone, presence: true
validates :employeeRole, presence: true
validates :email, presence: true
validates :branch, presence: true
end
<file_sep>/app/controllers/accounts_controller.rb
class AccountsController < ApplicationController
before_action :set_account, only: [:show, :edit, :update, :destroy]
# GET /accounts
# GET /accounts.json
def index
if current_user.try(:admin?)
@accounts = Account.order(:name).paginate(page: params[:page], per_page: 15)
elsif
@accounts = current_user.accounts.order(:name).paginate(page: params[:page], per_page: 2)
end
end
# GET /accounts/1
# GET /accounts/1.json
def show
@transactions = Transaction.all.where(:user_id => @account.id).order(created_at: :desc)
.paginate(page: params[:page], per_page: 15)
end
# GET /accounts/new
def new
@account = Account.new
@find = User.all
@set_user_account = @find.where(:verify => false)
@get_branch = Branch.all
end
# GET /accounts/1/edit
def edit
@get_branch = Branch.all
@get_account = Account.all
end
# POST /accounts
# POST /accounts.json
def create
@account = Account.new(account_params)
respond_to do |format|
if @account.save
format.html { redirect_to @account, notice: 'Account was successfully created.' }
format.json { render :show, status: :created, location: @account }
else
format.html { render :new }
format.json { render json: @account.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /accounts/1
# PATCH/PUT /accounts/1.json
def update
respond_to do |format|
if @account.update(account_params)
format.html { redirect_to @account, notice: 'Account was successfully updated.' }
format.json { render :show, status: :ok, location: @account }
else
format.html { render :edit }
format.json { render json: @account.errors, status: :unprocessable_entity }
end
end
end
# DELETE /accounts/1
# DELETE /accounts/1.json
def destroy
@account.destroy
respond_to do |format|
format.html { redirect_to accounts_url, notice: 'Account was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_account
@account = Account.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def account_params
params.require(:account).permit(:customer_id, :user_id, :accountType, :balance, :overdraft,
:branchName, :address, :dob, :email, :postcode, :gender, :name, :phone, transactions_attributes:
[:transType, :method, :description, :amount, :account_id, :employee_id, :t_balance, :total_balance])
end
end
<file_sep>/app/models/transaction.rb
class Transaction < ActiveRecord::Base
belongs_to :user
belongs_to :account
accepts_nested_attributes_for :account, :user
validates :amount, :numericality => {:greater_than => 0}
validates :transType, presence: true, length: {minimum:1, maximum:50}
validates :description, presence: true ,length: {minimum:1, maximum:50}
validates :amount, presence: true, length: {minimum:1, maximum:15}
validates :account_id, presence: true ,length: {minimum:1, maximum:8}
before_save :transaction_update
#after_save :debit
private
def transaction_update
if self.transType == 'Transfer'
debit = Account.find(user_id)
self.total_balance = debit.balance
self.t_balance = self.total_balance - self.amount
self.total_balance = self.t_balance
debit.balance = self.total_balance
debit.save
elsif self.transType == 'Deposit'
credit = Account.find(user_id)
self.total_balance = credit.balance
self.t_balance = self.total_balance + self.amount
self.total_balance = self.t_balance
credit.balance = self.total_balance
credit.save
end
end
searchable do
text :transType, :method, :description, :amount, :account_id, :employee_id, :t_balance, :total_balance
string :transType
string :method
string :description
float :amount
integer :account_id
integer :employee_id
integer :user_id, :multiple => true
end
end
<file_sep>/app/models/branch.rb
class Branch < ActiveRecord::Base
has_many :accounts
has_many :users
has_many :employees
accepts_nested_attributes_for :accounts, :users, :employees
validates :branchName, presence: true
validates :branchLocation, presence: true
validates :branchPostcode, presence: true
end
<file_sep>/app/models/account.rb
class Account < ActiveRecord::Base
has_many :transactions
belongs_to :user
belongs_to :branch
accepts_nested_attributes_for :transactions, :user
validates :customer_id, presence: true, length:{minimum:8}
validates :accountType, presence: true, length: {minimum:1, maximum:15}
validates :balance, presence: true, length: {minimum:1, maximum:15}
validates :overdraft, presence: true,length: {minimum:1, maximum:8}
validates :address, presence: true, length: {minimum:1, maximum:115}
validates :dob, presence: true
#validates :email, presence: true
validates :postcode, presence: true, length: {minimum:7, maximum:7}
validates :gender, presence: true
validates :name, presence: true, length: {minimum:1, maximum:70}
validates :phone, presence: true, length: {minimum:1, maximum:11}
before_save :user_setup
after_save :verify_user_account
private
def user_setup
if self.id.blank?
self.id = self.email
#self.user_id = self.email
end
end
private
def verify_user_account
if created_at == updated_at
userobject = User.find(self.email)
userobject.verify = "true"# setting up user verify column to true
userobject.save
end
end
end
<file_sep>/app/views/transactions/index.json.jbuilder
json.array!(@transactions) do |transaction|
json.extract! transaction, :id, :transType, :method, :description, :amount, :account_id, :employee_id, :total_balance, :t_balance
json.url transaction_url(transaction, format: :json)
end
<file_sep>/app/views/branches/show.json.jbuilder
json.extract! @branch, :id, :branchName, :branchLocation, :branchPostcode, :created_at, :updated_at
<file_sep>/app/views/transactions/show.json.jbuilder
json.extract! @transaction, :id, :transType, :method, :description, :amount, :account_id,
:employee_id, :created_at, :updated_at, :total_balance, :t_balance
<file_sep>/db/migrate/20160206150856_add_column_to_transactions.rb
class AddColumnToTransactions < ActiveRecord::Migration
def change
add_column :transactions, :t_balance, :float
add_column :transactions, :total_balance, :float
end
end
<file_sep>/app/views/accounts/index.json.jbuilder
json.array!(@accounts) do |account|
json.extract! account, :id, :customer_id, :accountType, :balance, :overdraft, :branch, :address, :dob, :email, :postcode, :gender, :name, :phone
json.url account_url(account, format: :json)
end
<file_sep>/README.rdoc
== README
1. View Application Online
https://abcbankmsc.herokuapp.com
3. Setup Guide Instruction to run this project.
1. Download the project file form GitHub or clone the repository
<EMAIL>:omshiv2415/ABC-Bank-Ruby-on-Rails-.git
2. Type the following command in you console but make sure you are in project directory
Command – bundle install -- without production (please type the command don’t do copy paste)
3. Type the following command for data migration (create database)
Command – rake db:migrate
4. Run Rails server to view this project in production.
Command – rails server –b 0.0.0.0
---------------------------------------------------------------------------------
* Ruby version
ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]
Rails 4.2.5
* System dependencies
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5'
# Use sqlite3 as the database for Active Record
gem 'devise'
gem 'twitter-bootstrap-rails'
gem 'devise-bootstrap-views'
gem 'protected_attributes'
gem 'will_paginate', '3.0.7'
gem 'bootstrap-will_paginate', '0.0.10'
gem 'bootstrap-sass', '~> 3.3.5'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
gem 'sqlite3'
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
gem "rails-erd"
gem 'railroady'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
group :production do
gem 'pg'
gem 'rails_12factor'
end
* Configuration
1 Download the application
or
2 Clone the git
* Database creation
* Database initialization
* How to run the test suite
* Services (job queues, cache servers, search engines, etc.)
* Deployment instructions
* ...
Please feel free to use a different markup language if you do not plan to run
<tt>rake doc:app</tt>.
== README
This is test application of ruby on rails
Important command
* rvm reinstall ruby-2.2.1
* rake db:migrate
* rails server -b 0.0.0
* rake routes
* rails generate scaffold Article title:string description:text
* rails generate migration create_users
* git commit -m "type message to commit"
* git add -A
* rails new project name
* cd "change directory" and cd .. go to back directory
* heroku keys:add
* heroku create
* heroku login
* bundle install --without production
* cat ~/.ssh/id_rsa.pub "getting public key"
* git config --global user.email "<EMAIL>"
* git config --global user.name "omshiv2415"
* git checkout -f
* git config
* rails g bootstrap:install
// drop talble
go to rails console
ActiveRecord::Migration.drop_table(:users)
// setup git directory
git init
git add -A
git commit -m "new project created"
git checkout -f
git status
1. get the key by typing command inside command line
cat ~/.ssh/id_rsa.pub
2. add shh key to github account inside setting
copy the key and paste in settings SSH key
3. create new repository on github account
git init
git add README.md
git commit -m "first commit"
git remote add origin <EMAIL>:omshiv2415/exercise_ruby.git
git push -u origin master
git checkout -b create-users
rails generate migration create_users
//add
// Deploy ruby application to heroku
1 open gemfile inside your project
move gem 'sqlite3' to group :development, :test do
2. create new grup
group :production do
gem 'pg'
gem 'rails_12factor'
end
3. bundle install --without production
4. install nitrous environment toolbelt
wget -qO- https://toolbelt.heroku.com/install-ubuntu.sh | sh
5. heroku login
enter email and password
6. heroku create
7. heroku keys:add
8. git push heroku master
9. heroku run rake db:migrate
10. Deploy changes
cd
11. heroku apps:rename msc-abc-bank
git add -A
git commit -am "make it better"
git push heroku master
This README would normally document whatever steps are necessary to get the
application up and running.
Things you may want to cover:
* Ruby version
* System dependencies
* Configuration
* Database creation
* Database initialization
* How to run the test suite
* Services (job queues, cache servers, search engines, etc.)
* Deployment instructions
* ...
* rails destroy scaffold Comment
Please feel free to use a different markup language if you do not plan to run
<tt>rake doc:app</tt>.
rails generate migration add_user_id_to_articles
| c0aaca0bebb4e02a769fc20b3ad68e1b064985fc | [
"RDoc",
"Ruby"
] | 11 | Ruby | omshiv2415/test-bank | 346ab1cf54aef7b5d0c0debc87936f9eb5b5676f | 140306b9a0b2146a7b93432322b00239fe350236 |
refs/heads/master | <repo_name>Triuman/TriumansGreatAnalyzer<file_sep>/Triuman's Great Analyzer.js
/*
- How many pips can I earn on a pair with these settings?
Input:
symbol,
take_profit_waiting_time,
stop_loss_spread_count,
take_profit_spread_count
Output:
pip count
- With what settings I can earn most on a pair?
Input:
symbol
Output:
take_profit_waiting_time,
stop_loss_spread_count,
take_profit_spread_count
- Show time/profit chart of a pair
Input:
symbol
Output:
graph showing 24 hours with their profits
*/
var ClosingReasons = {
PROGRAM: 0,
TAKE_PROFIT: 1,
STOP_LOSS: 2
};
function HowMuchCanIEarn(symbol, take_profit_waiting_time, stop_loss_spread_count, take_profit_spread_count, start_time, end_time) {
var pips_to_earn = 0;
for (var d in DATA) {
if (DATA[d].symbol != symbol)
continue;
for (var p in DATA[d].positions) {
position = DATA[d].positions[p];
if(start_time && end_time){
var position_time = parseDateToTime(position.open_date);
if (compare_times(start_time, position_time) == -1 || compare_times(end_time, position_time) == 1) {
continue;
}
}
var pip_to_earn = 0;
//If position was never positive and it was closed by stoploss, we assume stoploss will be hit for these settings.
if (position.max_min_profits.length == 1 && position.closing_reason == ClosingReasons.STOP_LOSS) {
pip_to_earn = -Math.ceil(stop_loss_spread_count * DATA[d].spread); //We cannot lose half pip.
continue;
}
for (var m in position.max_min_profits) {
var max_price = position.max_min_profits[m];
if (max_price.price_difference_as_spread > 0) {
//see if we can close the order and take our profit with either tp or take_profit_waiting_time
if (max_price.price_difference_as_spread >= take_profit_spread_count) {
pip_to_earn = Math.ceil(take_profit_spread_count * DATA[d].spread); //We cannot earn half pip.
break;
} else if (max_price.start_time <= take_profit_waiting_time && max_price.end_time >= take_profit_waiting_time) {
pip_to_earn = Math.ceil(max_price.price_difference_as_spread * DATA[d].spread);
pip_to_earn = pip_to_earn < 1 ? 1 : pip_to_earn; //we will earn at least 1 pip.
break;
}else if(max_price.start_time > take_profit_waiting_time){
pip_to_earn = Math.ceil((take_profit_waiting_time / max_price.start_time) * max_price.price_difference_as_spread * DATA[d].spread);
pip_to_earn = pip_to_earn < 1 ? 1 : pip_to_earn; //we will earn at least 1 pip.
break;
}else if(max_price.end_time < take_profit_waiting_time){
pip_to_earn = Math.ceil(((max_price.start_time-(take_profit_waiting_time-max_price.end_time)) / max_price.start_time) * max_price.price_difference_as_spread * DATA[d].spread);
pip_to_earn = pip_to_earn < 1 ? 1 : pip_to_earn; //we will earn at least 1 pip.
break;
}
} else {
//see if price hits our sl
if (-max_price.price_difference_as_spread >= stop_loss_spread_count) {
pip_to_earn = -Math.ceil(stop_loss_spread_count * DATA[d].spread); //We cannot lose half pip.
break;
}
}
}
if (pip_to_earn == 0) {
//if we couldnt determine pip to earn yet, the given stop loss or take profit might be bigger than positions'. So we check if position ended negative or positive. Then select the lowest tp or sl.
if (position.profit > 0) {
pip_to_earn = Math.min(take_profit_spread_count, DATA[d].take_profit_spread_count) * DATA[d].spread;
} else {
pip_to_earn = -Math.min(stop_loss_spread_count, DATA[d].stop_loss_spread_count) * DATA[d].spread;
}
}
pips_to_earn += pip_to_earn;
}
}
return pips_to_earn;
}
function GetSettingsForMaximumProfit(symbol) {
var settings_for_maximum_profit = {
take_profit_waiting_time: 0,
stop_loss_spread_count: 0,
take_profit_spread_count: 0,
profit: 0
};
var settings_for_minimum_profit = {
take_profit_waiting_time: 0,
stop_loss_spread_count: 0,
take_profit_spread_count: 0,
profit: 0
};
var totalProfit = 0; //We sum all the possible profits
var MaxProfitWaitingTime = 100000; //ms
var MaxProfitWaitingTimeStepSize = 1000; //ms
var MaxTakeProfitSpreadCount = 10;
var MaxStopLossSpreadCount = 10;
var Spread = GetSpread(symbol);
if (Spread == 0) {
console.log(symbol + " could not found in DATA.");
return { settings_for_maximum_profit, settings_for_minimum_profit, totalProfit };
}
var currentProfitWaitingTime = MaxProfitWaitingTime;
var maxProfit = 0;
var minProfit = 0;
for (var p = 0; p < MaxProfitWaitingTime / MaxProfitWaitingTimeStepSize; p++) {
var currentTakeProfitSpreadCount = MaxTakeProfitSpreadCount;
for (var t = 0; t < MaxTakeProfitSpreadCount * Spread; t++) {
var currentStopLossSpreadCount = MaxStopLossSpreadCount;
for (var s = 0; s < MaxStopLossSpreadCount * Spread; s++) {
var currentProfit = HowMuchCanIEarn(symbol, currentProfitWaitingTime, currentStopLossSpreadCount, currentTakeProfitSpreadCount);
totalProfit += currentProfit;
if (currentProfit >= maxProfit) {
settings_for_maximum_profit.take_profit_waiting_time = currentProfitWaitingTime;
settings_for_maximum_profit.take_profit_spread_count = currentTakeProfitSpreadCount;
settings_for_maximum_profit.stop_loss_spread_count = currentStopLossSpreadCount;
settings_for_maximum_profit.profit = currentProfit;
maxProfit = currentProfit;
}
if (currentProfit <= minProfit) {
settings_for_minimum_profit.take_profit_waiting_time = currentProfitWaitingTime;
settings_for_minimum_profit.take_profit_spread_count = currentTakeProfitSpreadCount;
settings_for_minimum_profit.stop_loss_spread_count = currentStopLossSpreadCount;
settings_for_minimum_profit.profit = currentProfit;
minProfit = currentProfit;
}
currentStopLossSpreadCount -= 1 / Spread;
}
currentTakeProfitSpreadCount -= 1 / Spread;
}
currentProfitWaitingTime -= MaxProfitWaitingTimeStepSize;
}
return { settings_for_maximum_profit, settings_for_minimum_profit, totalProfit };
}
function GetSpread(symbol) {
for (var d in DATA)
if (DATA[d].symbol == symbol)
return DATA[d].spread;
return 0;
}
function GetBestSettingsClick() {
var selectSymbol = document.getElementById("selectSymbol");
var symbol = selectSymbol.options[selectSymbol.selectedIndex].value;
var max_settings = GetSettingsForMaximumProfit(symbol);
var divResult = document.getElementById("divResult");
divResult.innerHTML = "";
divResult.innerHTML += "<div style='margin-top:20px;'>Best settings for " + symbol + "</div>";
var best_settings_string = "<div>";
best_settings_string += "<div>Take Profit Waiting Time: " + max_settings.settings_for_maximum_profit.take_profit_waiting_time + "</div>";
best_settings_string += "<div>Take Profit Spread Count: " + max_settings.settings_for_maximum_profit.take_profit_spread_count + "</div>";
best_settings_string += "<div>Stop Loss Spread Count: " + max_settings.settings_for_maximum_profit.stop_loss_spread_count + "</div>";
best_settings_string += "<div>Your Profit in Pips: " + max_settings.settings_for_maximum_profit.profit + "</div>";
best_settings_string += "</div>";
divResult.innerHTML += best_settings_string;
divResult.innerHTML += "<div style='margin-top:20px;'>Worst settings for " + symbol + "</div>";
var worst_settings_string = "<div>";
worst_settings_string += "<div>Take Profit Waiting Time: " + max_settings.settings_for_minimum_profit.take_profit_waiting_time + "</div>";
worst_settings_string += "<div>Take Profit Spread Count: " + max_settings.settings_for_minimum_profit.take_profit_spread_count + "</div>";
worst_settings_string += "<div>Stop Loss Spread Count: " + max_settings.settings_for_minimum_profit.stop_loss_spread_count + "</div>";
worst_settings_string += "<div>Your Profit in Pips: " + max_settings.settings_for_minimum_profit.profit + "</div>";
worst_settings_string += "</div>";
divResult.innerHTML += worst_settings_string;
divResult.innerHTML += "<div style='margin-top:20px;'>Total profit of all settings: " + max_settings.totalProfit + "</div>";
document.getElementById("txtProfitWaitingTime").value=max_settings.settings_for_maximum_profit.take_profit_waiting_time;
document.getElementById("txtTakeProfitSpreadCount").value=max_settings.settings_for_maximum_profit.take_profit_spread_count;
document.getElementById("txtStopLossSpreadCount").value=max_settings.settings_for_maximum_profit.stop_loss_spread_count;
}
function compare_times(time1, time2) {
var time1value = time1.hour * 60 + time1.minute;
var time2value = time2.hour * 60 + time2.minute;
if (time1value > time2value)
return -1;
if (time1value < time2value)
return 1;
if (time1value == time2value)
return 0;
}
function parseDateToTime(datetime) {
var timearray = datetime.split(" ")[1].split(":");
return {
hour: parseInt(timearray[0]),
minute: parseInt(timearray[1])
};
}
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(initChart);
var googleChart;
function initChart() {
googleChart = new google.visualization.LineChart(document.getElementById('curve_chart'));
}
function ShowProfitByHour(symbol, take_profit_waiting_time, stop_loss_spread_count, take_profit_spread_count) {
var selectSymbol = document.getElementById("selectSymbol");
var symbol = selectSymbol.options[selectSymbol.selectedIndex].value;
take_profit_waiting_time= parseInt(document.getElementById("txtProfitWaitingTime").value);
take_profit_spread_count= parseFloat(document.getElementById("txtTakeProfitSpreadCount").value);
stop_loss_spread_count= parseFloat(document.getElementById("txtStopLossSpreadCount").value);
var time_profit_array = [['Time', 'Profit']];
for (var h = 0; h < 24; h++) {
var start_time = { hour: h, minute: 0 };
var end_time = { hour: h, minute: 59 };
var profit = HowMuchCanIEarn(symbol, take_profit_waiting_time, stop_loss_spread_count, take_profit_spread_count, start_time, end_time);
time_profit_array.push([h + ":00", profit]);
}
var data = google.visualization.arrayToDataTable(time_profit_array);
var options = {
title: 'Profit by Hour ' + symbol,
curveType: 'none',
legend: { position: 'bottom' }
};
googleChart.draw(data, options);
}<file_sep>/data.js
var DATA = [
{
"symbol": "EURUSD",
"spread": 2,
"point": 0.0001,
"lot_size": 1,
"take_profit_waiting_time": 1000,
"stop_loss_spread_count": 10,
"take_profit_spread_count": 10,
"min_distance_to_real_price_as_spread": 1,
"max_distance_to_real_price_as_spread": 3,
"tick_delay": 30000,
"max_buy_position_count": 1,
"max_sell_position_count": 1,
"positions": [
{
type: 1,
open_date: "11.2.1242 17:42:45",
close_date: "11.2.1242 18:11:44",
closing_reason: 0,
open_price: 1.2232,
close_price: 1.3244,
average_price: 1.3432,
profit: -243,
swap: 0,
commission: 0,
max_min_profits: [{price_difference_as_spread:-5, start_time:233, end_time:893},{price_difference_as_spread:1, start_time:233, end_time:893}, {price_difference_as_spread:-7,start_time:233, end_time:893}],
average_positive_profit_duration: 3000,
average_negative_profit_duration: 12000
}
]
},
{
"symbol": "EURUSD",
"spread": 2,
"point": 0.0001,
"lot_size": 1,
"take_profit_waiting_time": 1000,
"stop_loss_spread_count": 10,
"take_profit_spread_count": 10,
"min_distance_to_real_price_as_spread": 1,
"max_distance_to_real_price_as_spread": 3,
"tick_delay": 30000,
"max_buy_position_count": 1,
"max_sell_position_count": 1,
"positions": [
{
type: 1,
open_date: "11.2.1242 8:34:23",
close_date: "11.2.1242 8:40:33",
closing_reason: 0,
open_price: 1.2232,
close_price: 1.3244,
average_price: 1.3432,
profit: 243,
swap: 0,
commission: 0,
max_min_profits: [{price_difference_as_spread:-5, start_time:233, end_time:893},{price_difference_as_spread:1, start_time:233, end_time:893}, {price_difference_as_spread:-4,start_time:233, end_time:893},{price_difference_as_spread:10, start_time:233, end_time:893}],
average_positive_profit_duration: 3000,
average_negative_profit_duration: 12000
}
]
},
{
"symbol": "EURUSD",
"spread": 2,
"point": 0.0001,
"lot_size": 1,
"take_profit_waiting_time": 1000,
"stop_loss_spread_count": 10,
"take_profit_spread_count": 10,
"min_distance_to_real_price_as_spread": 1,
"max_distance_to_real_price_as_spread": 3,
"tick_delay": 30000,
"max_buy_position_count": 1,
"max_sell_position_count": 1,
"positions": [
{
type: 1,
open_date: "11.2.1242 23:14:53",
close_date: "11.2.1242 23:26:21",
closing_reason: 0,
open_price: 1.2232,
close_price: 1.3244,
average_price: 1.3432,
profit: 243,
swap: 0,
commission: 0,
max_min_profits: [{price_difference_as_spread:-2, start_time:233, end_time:893},{price_difference_as_spread:8, start_time:233, end_time:893}, {price_difference_as_spread:-3,start_time:233, end_time:893},{price_difference_as_spread:10, start_time:233, end_time:893}],
average_positive_profit_duration: 3000,
average_negative_profit_duration: 12000
}
]
}
]; | ddbae0e8354330595e1c69974d3d34031b4fb6e7 | [
"JavaScript"
] | 2 | JavaScript | Triuman/TriumansGreatAnalyzer | 875755c86dc9f4df341a73d21ef1414729f0c73c | a626c695272fa0e3bdf705e32f066a56d7371269 |
refs/heads/master | <repo_name>BenjaminTheDeveloper/3280Assignment02<file_sep>/CS3280A2/CS3280_A2/Assignment02/Program.cs
//<NAME>
// CS 3280
// Assignment 02
// 6/8/20
using System;
using System.Collections.Generic;
using System.Linq;
namespace Assignment02
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\t\t\tName Organizer");
var fullNames = new List<string>(); // The (first and last) name of each entered person.
var sortChoice = "";
var reversedNames = new List<string>();
var incomplete = true;
string currentNameInput = "";
Console.WriteLine("Enter 5 People's first and last names EX: <NAME>");
insertNames(fullNames, currentNameInput);
//Sort the names by first or last
sortByUserChoice(incomplete,sortChoice,fullNames,reversedNames);
Console.WriteLine("Thank you for using my program!");
Console.ReadKey();
}
#region
public static void insertNames(List<string> fullNames, string currentNameInput)
{
for (int i = 0; i < 5; i++)
{
Console.Write("Name " + (i + 1) + ": ");
currentNameInput = Console.ReadLine();
//Logic to check if name is used
if (fullNames.Contains(currentNameInput))
{
Console.WriteLine("Please enter a new name");
--i;
}
else
{
fullNames.Add(currentNameInput);
}
}
}
#endregion
#region
public static void sortByUserChoice(bool incomplete, string sortChoice, List<string> fullNames, List<string> reversedNames)
{
const string choiceFirst = "first";
const string choiceLast = "last";
while (incomplete)
{
Console.Write("Would you like to sort these names by first or last names? ");
sortChoice = Console.ReadLine();
if (sortChoice.Equals(choiceFirst))
{
fullNames.Sort();
foreach (string name in fullNames)
{
Console.WriteLine(name);
}
incomplete = false;
}
else if (sortChoice.Equals(choiceLast))
{
foreach (string name in fullNames)
{
var lastName = name.Split(' ').Last();
var firstName = name.Split(' ').First();
reversedNames.Add(lastName + ", " + firstName);
}
incomplete = false;
reversedNames.Sort();
foreach (string name in reversedNames)
{
Console.WriteLine(name);
}
}
else
{
Console.WriteLine("Please enter a valid order type.");
}
}
}
#endregion
}
}
<file_sep>/README.md
Written By <NAME>
# Assignment 02
Description:
This assignment was designed to organize 5 full names by first or last name.
# Variables
var fullNames = new List<string>(); // The (first and last) name of each entered person.
string currentNameInput; // used for the current input name
var sortChoice = ""; //Stores whether the user wants to sort by first or last name.
var reversedNames = new List<string>(); // This list holds the fullName list with last names first.
var incomplete = true; //Runs the while loop until it is complete(!incomplete)
# Code
This program utilizes if, else, and while conditions.
The while loop was written to stop errors from happening when a user enters their sort choice.
# Methods
1)
public static void insertNames(List<string> fullNames, string currentNameInput);
Description: This method allows the user to enter 5 names while adding them to the fullNames List.
Using the currentNameInput variable, it holds each name entered by the user one at a time before placing it into the fullNames List.
2)
public static void sortByUserChoice(bool incomplete, string sortChoice, List<string> fullNames, List<string> reversedNames);
Description: This method prompts the user for a choice. Once the user is prompted the method uses the choice to determine how it will organize the names. It uses the reverseNames to store last names if the user chooses to order by last. Otherwise it will use fullNames to order them by first names.
# Usage
1) The Name Organizer will prompt you for five names. (Make sure to not repeat a name, it will catch this.)
2) Once you complete entering names, it will then ask if you want first names or last names organized.
3) Once you choose your sort type (first or last) you can see the results in alphabetic order.
| f36ba8f6864a83eba88281de32ffd19b17587f41 | [
"Markdown",
"C#"
] | 2 | C# | BenjaminTheDeveloper/3280Assignment02 | 9a2ba80ded1be61e0400e9def08e3f6fc057c103 | 2ceac13b5b3d018bcaf25b6b0ca089edd84bd32e |
refs/heads/master | <file_sep>import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import models
# import cv2
import sys
import numpy as np
import time
import math
mode = "LeNet"
def set_mode(new_mode):
global mode
mode = new_mode
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def replace_layers(model, i, indexes, layers):
if i in indexes:
return layers[indexes.index(i)]
return model[i]
def prune_vgg16_conv_layer(model, layer_index, filter_index, use_cuda=False):
global mode
# replace batchnormal layer
if mode == "MobileNet":
model = replace_bn_layers(model, layer_index, filter_index)
_, conv = list(model.features._modules.items())[layer_index]
next_conv = None
offset = 1
while layer_index + offset < len(model.features._modules.items()):
res = list(model.features._modules.items())[layer_index + offset]
if isinstance(res[1], torch.nn.modules.conv.Conv2d):
next_name, next_conv = res
break
offset = offset + 1
new_conv = \
torch.nn.Conv2d(in_channels=conv.in_channels, \
out_channels=conv.out_channels - 1,
kernel_size=conv.kernel_size, \
stride=conv.stride,
padding=conv.padding,
dilation=conv.dilation,
groups=conv.groups,
bias=(conv.bias is not None))
old_weights = conv.weight.data.cpu().numpy()
new_weights = new_conv.weight.data.cpu().numpy()
new_weights[: filter_index, :, :, :] = old_weights[: filter_index, :, :, :]
new_weights[filter_index:, :, :, :] = old_weights[filter_index + 1:, :, :, :]
new_conv.weight.data = torch.from_numpy(new_weights)
if use_cuda:
new_conv.weight.data = new_conv.weight.data.cuda()
bias_numpy = conv.bias.data.cpu().numpy()
bias = np.zeros(shape=(bias_numpy.shape[0] - 1), dtype=np.float32)
bias[:filter_index] = bias_numpy[:filter_index]
bias[filter_index:] = bias_numpy[filter_index + 1:]
new_conv.bias.data = torch.from_numpy(bias)
if use_cuda:
new_conv.bias.data = new_conv.bias.data.cuda()
if not next_conv is None:
next_new_conv = \
torch.nn.Conv2d(in_channels=next_conv.in_channels - 1, \
out_channels=next_conv.out_channels, \
kernel_size=next_conv.kernel_size, \
stride=next_conv.stride,
padding=next_conv.padding,
dilation=next_conv.dilation,
groups=next_conv.groups,
bias=(next_conv.bias is not None))
old_weights = next_conv.weight.data.cpu().numpy()
new_weights = next_new_conv.weight.data.cpu().numpy()
new_weights[:, : filter_index, :, :] = old_weights[:, : filter_index, :, :]
new_weights[:, filter_index:, :, :] = old_weights[:, filter_index + 1:, :, :]
next_new_conv.weight.data = torch.from_numpy(new_weights)
if use_cuda:
next_new_conv.weight.data = next_new_conv.weight.data.cuda()
next_new_conv.bias.data = next_conv.bias.data
if not next_conv is None:
features = torch.nn.Sequential(
*(replace_layers(model.features, i, [layer_index, layer_index + offset], \
[new_conv, next_new_conv]) for i, _ in enumerate(model.features)))
del model.features
del conv
model.features = features
else:
# Prunning the last conv layer. This affects the first linear layer of the classifier.
model.features = torch.nn.Sequential(
*(replace_layers(model.features, i, [layer_index], \
[new_conv]) for i, _ in enumerate(model.features)))
layer_index = 0
old_linear_layer = None
for _, module in model.classifier._modules.items():
if isinstance(module, torch.nn.Linear):
old_linear_layer = module
break
layer_index = layer_index + 1
if old_linear_layer is None:
raise BaseException("No linear laye found in classifier")
params_per_input_channel = old_linear_layer.in_features // conv.out_channels
new_linear_layer = \
torch.nn.Linear(old_linear_layer.in_features - params_per_input_channel,
old_linear_layer.out_features)
old_weights = old_linear_layer.weight.data.cpu().numpy()
new_weights = new_linear_layer.weight.data.cpu().numpy()
new_weights[:, : filter_index * params_per_input_channel] = \
old_weights[:, : filter_index * params_per_input_channel]
new_weights[:, filter_index * params_per_input_channel:] = \
old_weights[:, (filter_index + 1) * params_per_input_channel:]
new_linear_layer.bias.data = old_linear_layer.bias.data
new_linear_layer.weight.data = torch.from_numpy(new_weights)
if use_cuda:
new_linear_layer.weight.data = new_linear_layer.weight.data.cuda()
classifier = torch.nn.Sequential(
*(replace_layers(model.classifier, i, [layer_index], \
[new_linear_layer]) for i, _ in enumerate(model.classifier)))
del model.classifier
del next_conv
del conv
model.classifier = classifier
return model
def replace_bn_layers(model, layer_index, filter_index):
del_num = 1
_, current_layer = list(model.features._modules.items())[layer_index+1]
new_num_features = current_layer.num_features - del_num
new_bn = nn.BatchNorm2d(
num_features=new_num_features,
eps=current_layer.eps,
momentum=current_layer.momentum,
affine=current_layer.affine,
track_running_stats=current_layer.track_running_stats
)
# bias
new_bn.bias.data[:filter_index] = current_layer.bias.data[:filter_index]
new_bn.bias.data[filter_index:] = current_layer.bias.data[filter_index+1:]
# weight
new_bn.weight.data[:filter_index] = current_layer.weight.data[:filter_index]
new_bn.weight.data[filter_index:] = current_layer.weight.data[filter_index+1:]
# find old layer's position
seq, index = find_seq_index(model, current_layer)
seq[index] = new_bn
return model
def find_seq(model):
seqs = []
for module in model.modules():
if isinstance(module, torch.nn.modules.Sequential):
seqs.append(module)
return seqs
def find_seq_index(model, layer):
sequence = None
index = None
for seq in model.modules():
if isinstance(seq, nn.Sequential):
if layer in seq:
sequence = seq
for i in range(len(seq)):
if layer is seq[i]:
index = i
return sequence, index
def find_layers(model):
layers = []
for module in model.modules():
if isinstance(module, torch.nn.modules.Conv2d) or isinstance(module, torch.nn.modules.Linear):
layers.append(module)
return layers
def del_cov_filter(old_conv_layer, filter_index, is_first=True):
if old_conv_layer is None:
raise BaseException("No Conv layer found in classifier")
# delete filter number is 1
del_num = 1
old_weights = old_conv_layer.weight.data.cpu()
# create new_conv_layer
if is_first:
new_conv_layer = torch.nn.Conv2d(in_channels=(old_conv_layer.in_channels - del_num) if old_conv_layer.groups > 1 else old_conv_layer.in_channels,
out_channels=old_conv_layer.out_channels - del_num,
kernel_size=old_conv_layer.kernel_size,
stride=old_conv_layer.stride,
padding=old_conv_layer.padding,
dilation=old_conv_layer.dilation,
groups=(old_conv_layer.groups - del_num) if old_conv_layer.groups > 1 else old_conv_layer.groups,
bias=(old_conv_layer.bias is not None))
# depth-wise conv layer
new_conv_layer.weight.data[:filter_index] = old_weights[:filter_index]
new_conv_layer.weight.data[filter_index:] = old_weights[filter_index + 1:]
else:
new_conv_layer = torch.nn.Conv2d(in_channels=old_conv_layer.in_channels - del_num,
out_channels=old_conv_layer.out_channels,
kernel_size=old_conv_layer.kernel_size,
stride=old_conv_layer.stride,
padding=old_conv_layer.padding,
dilation=old_conv_layer.dilation,
groups=(old_conv_layer.groups - del_num) if old_conv_layer.groups > 1 else old_conv_layer.groups,
bias=(old_conv_layer.bias is not None))
# copy new weights to new_conv_layer
new_conv_layer.weight.data[:, :filter_index] = old_weights[:, :filter_index]
new_conv_layer.weight.data[:, filter_index:] = old_weights[:, filter_index + 1:]
return new_conv_layer
def del_linear_filter(old_linear_layer, filter_index):
# delete filter number is 1
del_num = 1
new_linear_layer = torch.nn.Linear(old_linear_layer.in_features - del_num,
old_linear_layer.out_features)
new_linear_layer.weight.data[:, :filter_index] = old_linear_layer.weight.data[:, :filter_index]
new_linear_layer.weight.data[:, filter_index:] = old_linear_layer.weight.data[:, filter_index + 1:]
return new_linear_layer
def prune_mbnet_layer(model, layer_index, filter_index):
# find layers
layers = find_layers(model)
# convert layer index into correct format
layer_index = layer_index * 2
old_layer = layers[layer_index]
old_layer2 = None
old_layer3 = None
# first
new_layer = del_cov_filter(old_layer, filter_index, is_first=True)
if layer_index < len(layers) - 2:
# select next two layers which are needed to adapt to new size.
old_layer2 = layers[layer_index + 1]
old_layer3 = layers[layer_index + 2]
new_layer2 = del_cov_filter(old_layer2, filter_index, is_first=True)
# third
new_layer3 = del_cov_filter(old_layer3, filter_index, is_first=False)
old_layers = [old_layer, old_layer2, old_layer3]
new_layers = [new_layer, new_layer2, new_layer3]
else:
# second fc
old_layer2 = layers[layer_index + 1]
new_layer2 = del_linear_filter(old_layer2, filter_index)
old_layers = [old_layer]
new_layers = [new_layer]
model.fc = new_layer2
# then replace old layers by new layers
for old, new in zip(old_layers, new_layers):
seq, i = find_seq_index(model, old)
seq[i] = new
del old_layer
del old_layer2
del old_layer3
return model
if __name__ == '__main__':
model = models.vgg16(pretrained=True)
model.train()
t0 = time.time()
model = prune_vgg16_conv_layer(model, 28, 10)
print("The prunning took", time.time() - t0)
<file_sep>from torch.utils.data import DataLoader, Dataset
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import os
#######################
class Data(Dataset):
def __init__(self, x, y, num_channels=8, width=20, Mode='2D'):
self.x = np.load(x)
self.y = np.load(y)
# normalize
self.Mode = Mode
if Mode == '2D':
self.x = self.x.transpose((0, 2, 1))
self.x = self.x.reshape((-1, num_channels, 1, width))
self.x = self.x.astype(np.float32)
self.x = (self.x - np.mean(self.x)) / np.std(self.x)
if Mode == 'S+C':
self.x = self.x.astype(np.float32)
self.x = (self.x - np.mean(self.x)) / np.std(self.x)
if Mode == 'C+S':
self.x = self.x.transpose((0, 2, 1))
self.x = self.x.astype(np.float32)
self.x = (self.x - np.mean(self.x)) / np.std(self.x)
self.y = self.y
self.y = self.y.astype(np.long)
self.y = self.y.reshape((-1))
self.y = self.y - 1
def __len__(self):
return len(self.x)
def __getitem__(self, index):
# load image as ndarray type (Height * Width * Channels)
# be carefull for converting dtype to np.uint8 [Unsigned integer (0 to 255)]
# in this example, i don't use ToTensor() method of torchvision.transforms
# so you can convert numpy ndarray shape to tensor in PyTorch (H, W, C) --> (C, H, W)
if self.Mode == '2D':
x = self.x[index, :, :, :]
if self.Mode == 'S+C' or self.Mode == 'C+S':
x = self.x[index, :, :]
y = self.y[index]
return x, y
class DataSet(Dataset):
def __init__(self, path_to_x, path_to_y):
self.x = np.load(path_to_x)
self.y = np.load(path_to_y)
self.x = self.x.astype(np.float32)
self.y = self.y.astype(np.long)
def __len__(self):
return len(self.x)
def __getitem__(self, index):
x = self.x[index]
y = self.y[index]
return x, y
class DataSetNP(Dataset):
def __init__(self, x_np, y_np):
self.x = x_np
self.y = y_np
self.x = self.x.astype(np.float32)
self.y = self.y.astype(np.long)
def __len__(self):
return len(self.x)
def __getitem__(self, index):
x = self.x[index]
y = self.y[index]
return x, y
class Config:
def __init__(self, path_x=None, path_y=None, input_width=20, input_height=1, channel=8, num_classes=6,
batch_size=16, num_epochs=20, learning_rate=0.001, shuffle=True):
self.input_width = input_width
self.input_height = input_height
self.channel = channel
self.batch_size = batch_size
self.num_epochs = num_epochs
self.learning_rate = learning_rate
self.path_to_x = path_x
self.path_to_y = path_y
self.num_classes = num_classes
self.dataset = Data(self.path_to_x, self.path_to_y, num_channels=channel, width=input_width)
self.shuffle = shuffle
def data_loader(self):
train_loader = DataLoader(self.dataset, batch_size=self.batch_size, shuffle=self.shuffle)
return train_loader
def generate_data_loader(batch_size, dataset='MNIST', is_main=True):
# if dataset == 'MNIST':
# transform = transforms.Compose([
# transforms.ToTensor(),
# transforms.Normalize((0.1307,), (0.3081,)),
# ])
# if is_main:
# root_dir = '../data'
# else:
# root_dir = '../../data'
# trainset = torchvision.datasets.MNIST(root=root_dir, train=True,
# download=True, transform=transform)
# trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
# shuffle=True, num_workers=0)
# testset = torchvision.datasets.MNIST(root=root_dir, train=False,
# download=True, transform=transform)
# testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
# shuffle=False, num_workers=0)
if dataset == 'MNIST':
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,)),
])
if is_main:
root_dir = '../data'
else:
root_dir = '../../data'
trainset = torchvision.datasets.MNIST(root=root_dir, train=True,
download=True, transform=transform)
testset = torchvision.datasets.MNIST(root=root_dir, train=False,
download=True, transform=transform)
# selecting classes
train_idx = torch.tensor([True if i in [0, 1, 2, 3, 4] else False for i in trainset.targets])
trainset.data = trainset.data[train_idx]
trainset.targets = trainset.targets[train_idx]
test_idx = torch.tensor([True if i in [0, 1, 2, 3, 4] else False for i in testset.targets])
testset.data = testset.data[test_idx]
testset.targets = testset.targets[test_idx]
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=0)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
shuffle=False, num_workers=0)
elif dataset == 'CIFAR10':
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
if is_main:
root_dir = '../data'
else:
root_dir = '../../data'
trainset = torchvision.datasets.CIFAR10(root=root_dir, train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=0)
testset = torchvision.datasets.CIFAR10(root=root_dir, train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
shuffle=False, num_workers=0)
elif dataset == 'EMG':
# path_to_x_train = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data/train_X.npy"
# path_to_y_train = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data/train_y.npy"
# path_to_x_test = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data/test_X.npy"
# path_to_y_test = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data/test_y.npy"
# path_to_x_train = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_w100/train_X.npy"
# path_to_y_train = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_w100/train_y.npy"
# path_to_x_test = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_w100/test_X.npy"
# path_to_y_test = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_w100/test_y.npy"
path_to_x_train = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_part/train_X.npy"
path_to_y_train = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_part/train_y.npy"
path_to_x_test = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_part/test_X.npy"
path_to_y_test = "/Users/zber/ProgramDev/data_process_jupyter/EMG/data_gen/npy_data_part/test_y.npy"
trainset = DataSet(path_to_x_train, path_to_y_train)
testset = DataSet(path_to_x_test, path_to_y_test)
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
testloader = DataLoader(testset, batch_size=batch_size, shuffle=True)
elif dataset == 'Har':
# path_to_x_train = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy/train_X.npy'
# path_to_y_train = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy/train_y.npy'
# path_to_x_test = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy/test_X.npy'
# path_to_y_test = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy/test_y.npy'
path_to_x_train = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_shuffle/train_X.npy'
path_to_y_train = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_shuffle/train_y.npy'
path_to_x_test = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_shuffle/test_X.npy'
path_to_y_test = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_shuffle/test_y.npy'
# path_to_x_train = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_part/train_X.npy'
# path_to_y_train = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_part/train_y.npy'
# path_to_x_test = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_part/test_X.npy'
# path_to_y_test = '/Users/zber/ProgramDev/data_process_jupyter/Har/data_gen/data_npy_part/test_y.npy'
trainset = DataSet(path_to_x_train, path_to_y_train)
testset = DataSet(path_to_x_test, path_to_y_test)
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
testloader = DataLoader(testset, batch_size=batch_size, shuffle=True)
elif dataset == 'myHealth':
path_to_x_test = "/Users/zber/ProgramDev/data_process_jupyter/MyHealth/gen_data/data_npy/test_X.npy"
path_to_y_test = "/Users/zber/ProgramDev/data_process_jupyter/MyHealth/gen_data/data_npy/test_y.npy"
path_to_x_train = "/Users/zber/ProgramDev/data_process_jupyter/MyHealth/gen_data/data_npy/train_X.npy"
path_to_y_train = "/Users/zber/ProgramDev/data_process_jupyter/MyHealth/gen_data/data_npy/train_y.npy"
trainset = DataSet(path_to_x_train, path_to_y_train)
testset = DataSet(path_to_x_test, path_to_y_test)
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
testloader = DataLoader(testset, batch_size=batch_size, shuffle=True)
elif dataset == 'FinDroid':
path_to_x_test = "/Users/zber/ProgramDev/data_process_jupyter/Finger/data_gen/test_X.npy"
path_to_y_test = "/Users/zber/ProgramDev/data_process_jupyter/Finger/data_gen/test_y.npy"
path_to_x_train = "/Users/zber/ProgramDev/data_process_jupyter/Finger/data_gen/train_X.npy"
path_to_y_train = "/Users/zber/ProgramDev/data_process_jupyter/Finger/data_gen/train_y.npy"
trainset = DataSet(path_to_x_train, path_to_y_train)
testset = DataSet(path_to_x_test, path_to_y_test)
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
testloader = DataLoader(testset, batch_size=batch_size, shuffle=True)
elif dataset == 'HUA':
root = "/Users/zber/ProgramDev/pytorch-pruning/data/HUA/acc_ppg2_gyro"
path_to_x_test = os.path.join(root, 'test_X.npy')
path_to_y_test = os.path.join(root, 'test_y.npy')
path_to_x_train = os.path.join(root, 'train_X.npy')
path_to_y_train = os.path.join(root, 'train_y.npy')
trainset = DataSet(path_to_x_train, path_to_y_train)
testset = DataSet(path_to_x_test, path_to_y_test)
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
testloader = DataLoader(testset, batch_size=batch_size, shuffle=True)
elif dataset == 'Fin_Sitting':
path_to_x_train = "/Users/zber/ProgramDev/data_process_jupyter/Finger/sitting/x_train.npy"
path_to_y_train = "/Users/zber/ProgramDev/data_process_jupyter/Finger/sitting/y_train.npy"
path_to_x_test = "/Users/zber/ProgramDev/data_process_jupyter/Finger/sitting/x_test.npy"
path_to_y_test = "/Users/zber/ProgramDev/data_process_jupyter/Finger/sitting/y_test.npy"
trainset = DataSet(path_to_x_train, path_to_y_train)
testset = DataSet(path_to_x_test, path_to_y_test)
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
testloader = DataLoader(testset, batch_size=batch_size, shuffle=True)
elif dataset == 'Fin_SitRun':
path_to_x_train = "/Users/zber/ProgramDev/data_process_jupyter/Finger/running/x_train.npy"
path_to_y_train = "/Users/zber/ProgramDev/data_process_jupyter/Finger/running/y_train.npy"
path_to_x_test = "/Users/zber/ProgramDev/data_process_jupyter/Finger/running/x_test.npy"
path_to_y_test = "/Users/zber/ProgramDev/data_process_jupyter/Finger/running/y_test.npy"
trainset = DataSet(path_to_x_train, path_to_y_train)
testset = DataSet(path_to_x_test, path_to_y_test)
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
testloader = DataLoader(testset, batch_size=batch_size, shuffle=True)
return trainloader, testloader
<file_sep>import torch.nn as nn
import torch.nn.functional as F
'''VGG11/13/16/19 in Pytorch.'''
import torch
from torchsummary import summary
from ptflops import get_model_complexity_info
class LeNet5_GROW_P(nn.Module):
def __init__(self, out1=2, out2=5, fc1=10):
super(LeNet5_GROW_P, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, out1, kernel_size=5, stride=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(2),
nn.Conv2d(out1, out2, kernel_size=5, stride=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(2)
)
self.classifier = nn.Sequential(
nn.Linear(out2 * 16, fc1),
nn.ReLU(inplace=True),
nn.Linear(fc1, 10),
)
def forward(self, x):
x = self.features(x)
out1 = x.view(x.size(0), -1)
x = self.classifier(out1)
out2 = F.softmax(x, dim=1)
return out2
class LeNet5(nn.Module):
def __init__(self, in_channel, out1_channel, out2_channel, fc, out_classes, kernel_size, flatten_factor, padding=0):
super(LeNet5, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(in_channel, out1_channel, kernel_size=(1, kernel_size), stride=1, padding=padding),
# nn.BatchNorm2d(out1_channel),
nn.ReLU(inplace=True),
nn.MaxPool2d((1, 2)),
nn.Conv2d(out1_channel, out2_channel, kernel_size=(1, kernel_size), stride=1, padding=padding),
# nn.BatchNorm2d(out2_channel),
nn.ReLU(inplace=True),
nn.MaxPool2d((1, 2)),
)
self.classifier = nn.Sequential(
nn.Linear(flatten_factor * out2_channel, fc),
nn.ReLU(inplace=True),
nn.Linear(fc, out_classes),
)
def forward(self, x):
x = self.features(x)
out1 = x.view(x.size(0), -1)
x = self.classifier(out1)
out2 = F.softmax(x, dim=1)
return out2
class NetS(nn.Module):
def __init__(self, in_channel=9, out1_channel=32, out2_channel=64, out3_channel=128, out4_channel=256,
out_classes=10, avg_factor=13, kernel_size=14):
super(NetS, self).__init__()
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, (1, kernel_size), stride, 0, bias=False),
# nn.BatchNorm2d(oup),
nn.ReLU(inplace=True)
)
def conv_dw(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, inp, (1, kernel_size), stride, 0, groups=inp, bias=False),
# nn.BatchNorm2d(inp),
nn.ReLU(inplace=True),
nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
# nn.BatchNorm2d(oup),
nn.ReLU(inplace=True),
)
self.model = nn.Sequential(
conv_bn(in_channel, out1_channel, (1, 2)),
conv_dw(out1_channel, out2_channel, (1, 1)),
conv_dw(out2_channel, out3_channel, (1, 2)),
conv_dw(out3_channel, out4_channel, (1, 2)),
nn.AvgPool2d((1, avg_factor)),
)
self.fc = nn.Linear(out4_channel, out_classes)
def forward(self, x):
x = self.model(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
cfg = {
'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG11_10': [8, 'M', 16, 'M', 32, 32, 'M', 64, 64, 'M', 64, 64, 'M'],
'VGG11_25': [16, 'M', 32, 'M', 64, 64, 'M', 128, 128, 'M', 128, 128, 'M'],
'VGG11_25_1': [16, 'M', 32, 'M', 64, 64, 'M', 128, 128, 'M', 256, 256, 'M'],
'VGG11_25_2': [16, 'M', 32, 'M', 128, 128, 'M', 128, 128, 'M', 256, 256, 'M'],
'VGG11_40': [25, 'M', 51, 'M', 102, 102, 'M', 204, 204, 'M', 204, 204, 'M'],
'VGG11_50': [32, 'M', 64, 'M', 128, 128, 'M', 256, 256, 'M', 256, 256, 'M'],
'VGG11_60': [38, 'M', 76, 'M', 153, 153, 'M', 307, 307, 'M', 307, 307, 'M'],
'VGG11_70': [44, 'M', 89, 'M', 179, 179, 'M', 358, 358, 'M', 358, 358, 'M'],
'VGG11_s1': [63, 'M', 44, 'M', 51, 51, 'M', 86, 86, 'M', 86, 86, 'M'],
'VGG11_bn_s1': [17, 'M', 30, 'M', 52, 52, 'M', 86, 86, 'M', 86, 86, 'M'],
'seed': [6, 'M', 12, 'M', 25, 25, 'M', 50, 50, 'M', 50, 50, 'M'],
'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}
class VGG(nn.Module):
def __init__(self, vgg_name):
super(VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
# self.classifier = nn.Sequential(nn.Linear(512, 10))
self.classifier = nn.Sequential(nn.Linear(cfg[vgg_name][-2], 10))
def forward(self, x):
out = self.features(x)
out1 = out.view(out.size(0), -1)
out = self.classifier(out1)
return out
def _make_layers(self, cfg):
layers = []
in_channels = 3
for x in cfg:
if x == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
nn.ReLU(inplace=True)]
in_channels = x
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
return nn.Sequential(*layers)
class VGG_BN(nn.Module):
def __init__(self, vgg_name):
super(VGG_BN, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
# self.classifier = nn.Sequential(nn.Linear(512, 10))
self.classifier = nn.Sequential(nn.Linear(cfg[vgg_name][-2], 10))
def forward(self, x):
out = self.features(x)
out1 = out.view(out.size(0), -1)
out = self.classifier(out1)
return out
def _make_layers(self, cfg):
layers = []
in_channels = 3
for x in cfg:
if x == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
nn.BatchNorm2d(x),
nn.ReLU(inplace=True)]
in_channels = x
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
return nn.Sequential(*layers)
if __name__ == "__main__":
net = VGG('VGG11_25_2')
summary = summary(net, (3, 34, 34))
# macs, params = get_model_complexity_info(net, (3, 34, 34), as_strings=True,
# print_per_layer_stat=True, verbose=True)
# print('{:<30} {:<8}'.format('Computational complexity: ', macs))
# print('{:<30} {:<8}'.format('Number of parameters: ', params))
#
# print('abcd')
| c9952ebf1a2b50c18c4cb951d9559890a93f0693 | [
"Python"
] | 3 | Python | Zber5/pytorch-pruning | 9b59936c5ee99c5bdb0b2d9f9e66cc78ac53e802 | e1a362384cde2f0fb41deed2d69bb6501e3b5523 |
refs/heads/master | <file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
import Dashboard from '@/components/views/Dashboard'
import ProductMenu from '@/components/views/pages/ProductMenu'
import Men from '@/components/views/pages/Men'
import Women from '@/components/views/pages/Women'
import Kid from '@/components/views/pages/Kid'
import Sale from '@/components/views/pages/Sale'
import Product from '@/components/views/pages/Product'
import Cart from '@/components/views/pages/cart'
import Order from '@/components/views/pages/Order'
import Checkout from '@/components/views/pages/Checkout'
import Home from '@/components/views/pages/Home'
import Login from '@/components/back/pages/Login'
import BackDashboard from '@/components/back/Dashboard'
import Products from '@/components/back/pages/Products'
import Orders from '@/components/back/pages/Orders'
import Coupon from '@/components/back/pages/Coupon'
import CustomerOrder from '@/components/back/pages/CustomerOrder'
import CustomerCheckout from '@/components/back/pages/CustomerCheckout'
Vue.use(VueRouter)
export default new VueRouter({
routes: [{
path: '*',
redirect: '/Home'
}, {
path: '/',
name: 'Dashboard',
component: Dashboard,
children: [{
path: 'productmenu',
name: 'productmenu',
component: ProductMenu
}, {
path: 'productmenu/men',
name: 'Men',
component: Men
}, {
path: 'productmenu/women',
name: 'Women',
component: Women
}, {
path: 'productmenu/kid',
name: 'Kid',
component: Kid
}, {
path: 'productmenu/sale',
name: 'Sale',
component: Sale
}, {
path: 'product/:productId',
name: 'product',
component: Product
}, {
path: 'cart',
name: 'cart',
component: Cart
}, {
path: 'order',
name: 'order',
component: Order
}, {
path: 'checkout/:orderId',
name: 'checkout',
component: Checkout
}, {
path: 'Home',
name: 'Home',
component: Home
}]
}, {
path: '/login',
name: 'Login',
component: Login
}, {
path: '/admin',
name: 'BackDashboard',
component: BackDashboard,
meta: { requiresAuth: true },
children: [{
path: 'products',
name: 'Products',
component: Products,
meta: { requiresAuth: true }
}, {
path: 'orders',
name: 'Orders',
component: Orders,
meta: { requiresAuth: true }
}, {
path: 'coupon',
name: 'Coupon',
component: Coupon,
meta: { requiresAuth: true }
}]
}, {
path: '/',
name: 'BackDashboard',
component: BackDashboard,
children: [{
path: 'customer_order',
name: 'CustomerOrder',
component: CustomerOrder
}, {
path: 'customer_checkout/:orderId',
name: 'CustomerCheckout',
component: CustomerCheckout
}]
}]
})
<file_sep>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import './bus'
import Vue from 'vue'
import App from './App'
import 'bootstrap'
import router from './router'
import axios from 'axios'
import VueAxios from 'vue-axios'
import Loading from 'vue-loading-overlay'
import 'vue-loading-overlay/dist/vue-loading.css'
import currencyFilter from './filters/currency'
import VeeValidate from 'vee-validate'
import zhTWValidte from 'vee-validate/dist/locale/zh_TW'
import timestampFormat from './filters/timestampFormat'
Vue.use(VueAxios, axios)
Vue.config.productionTip = false
Vue.component('Loading', Loading)
Vue.filter('currency', currencyFilter)
Vue.filter('timeFormat', timestampFormat)
Vue.use(VeeValidate)
VeeValidate.Validator.localize('zh_TW', zhTWValidte)
axios.defaults.withCredentials = true
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>',
router
})
router.beforeEach((to, from, next) => { // Navigation Guards
// console.log('to', to, 'from', from, 'next', next);
if (to.meta.requiresAuth) { // 要到達的頁面(to),如果有requiresAuth,會被Guards擋住
console.log('這裡需要驗證')
const api = `${process.env.APIPATH}/api/user/check`
axios.post(api).then((response) => {
console.log(response.data)
if (response.data.success) {
next()
} else {
next({ path: '/login' })
}
})
} else { // 要達到的頁面(to),如果沒有requiresAuth,直接next().
next()
}
})
<file_sep># Vue-SimpleDress
## [Demo](https://johnnyli326.github.io/Vue-SimpleDress/dist/#/Home)
## Development tool
Vitual Studio Code
## Language
1. Vue.js
## Features
1. The entire project is created with Vue. There are some features:
(1). Use ajax to get, put or post data to back-end database.
(2). This shopping website includes: view(customer side) and admin(administrater side).
1). VIEW:
(1). Home page
(2). Products List : which got from back-end database.
(3). Cart : add product to cart
(4). Ordering : check the products and fill out the form about customer's information.
(5). Responsive Web Design : this project is designed with RWD.
2). ADMIN:
(1). Manage products: release/remove products.
(2). Order list: we can know the latest ordering condition.
(3). Coupon: Add/remove coupon.
(4). Shopping/Ordering Simulation.
| 49c2e0745cf045523935c331d72ac55586375458 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | cariskao/Vue-SimpleDress | 045633ad5bd327a274d94b9d51e84a55938158a7 | 6a1e9a588b02a7279d9249837ef62c1df1c3be5a |
refs/heads/main | <file_sep>from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from . import models
# Create your views here.
def articleslist(request):
articles=models.Article.objects.all().order_by("date")
args={'articles':articles}
return render(request,'articles/articlelist.html',context=args)
<file_sep>#Wblog Webapp by Python 3,8 Django Framework
This is a experımental project being developed on GateHub with the powerful Django framework in Python 3.8. In this project we are going to develop a weblog to publısh news.
| 1d13de687509cd49dca59c8cbae8e4d5e59341f3 | [
"Markdown",
"Python"
] | 2 | Python | mohammadbtc100/DjangoWeblog | a5138c3cb8dde7790e20c1fdc17ee21792f2663a | a6507bc198030dd7471f86f9726e8cb30dbf6e47 |
refs/heads/main | <file_sep>package xyz.realraec;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class MainFrame extends JFrame {
public MainFrame(String url) throws IOException {
this.setSize(1300, 665);
this.setMinimumSize(new Dimension(860, 435));
this.setLocationRelativeTo(null);
//this.setLocation(100, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Document
Document inputDocument = initDocument(url);
// Title
initTitle(inputDocument);
// Buttons and text
initLeft(inputDocument);
// Card and search
initRight(inputDocument);
// Menu bar
initMenuBar();
this.setVisible(true);
}
public Document initDocument(String url) throws IOException {
return Jsoup.connect(url).get();
}
public void initTitle(Document inputDocument) {
String titleRaw = inputDocument.title();
this.setTitle(titleRaw.substring(0, titleRaw.lastIndexOf(" - ")));
}
public void initLeft(Document inputDocument) {
// Check and reset to make the previous page disappear if there is one
BorderLayout layout = (BorderLayout)this.getContentPane().getLayout();
if (layout.getLayoutComponent(BorderLayout.CENTER) != null) {
this.getContentPane().remove(layout.getLayoutComponent(BorderLayout.CENTER));
}
LeftPanel leftPanel = new LeftPanel(this, inputDocument);
this.getContentPane().add(leftPanel, BorderLayout.CENTER);
}
public void initRight(Document inputDocument) {
// Check and reset to make the previous page disappear if there is one
BorderLayout layout = (BorderLayout)this.getContentPane().getLayout();
if (layout.getLayoutComponent(BorderLayout.EAST) != null) {
this.getContentPane().remove(layout.getLayoutComponent(BorderLayout.EAST));
}
RightPanel rightPanel = new RightPanel(this, inputDocument);
this.getContentPane().add(rightPanel, BorderLayout.EAST);
}
private void initMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenuItem godsListItem = new JMenuItem("God voicelines");
godsListItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performSearch("https://smite.fandom.com/wiki/God_voicelines");
}
});
JMenuItem skinsListItem = new JMenuItem("Skin voicelines");
skinsListItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performSearch("https://smite.fandom.com/wiki/Skin_voicelines");
}
});
JMenuItem announcerPacksItem = new JMenuItem("Announcer packs");
announcerPacksItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performSearch("https://smite.fandom.com/wiki/Announcer_packs");
}
});
JMenu listsMenu = new JMenu("Lists");
listsMenu.add(godsListItem);
listsMenu.add(skinsListItem);
listsMenu.add(announcerPacksItem);
JMenuItem explorerItem = new JMenuItem("Explorer");
JMenuItem favoritesItem = new JMenuItem("Favorites");
favoritesItem.setEnabled(false);
JMenu singlesMenu = new JMenu("Viewer");
singlesMenu.add(explorerItem);
singlesMenu.add(favoritesItem);
menuBar.add(listsMenu);
menuBar.add(singlesMenu);
this.setJMenuBar(menuBar);
}
public void performSearch(String userInput) {
int code;
try {
URL possibleUrl = new URL(userInput);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) possibleUrl
.openConnection();
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.connect();
code = httpsURLConnection.getResponseCode();
} catch (IOException ignored) {
return;
}
//System.out.println(code);
if (code == 200) {
try {
Document newDocument = this.initDocument(userInput);
System.out.println("Fetching " + userInput);
this.initTitle(newDocument);
this.initLeft(newDocument);
this.initRight(newDocument);
this.getContentPane().revalidate();
} catch (IOException ioException) {
ioException.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Make sure you've entered a valid link or name.");
}
}
}
<file_sep>package xyz.realraec;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
public class VoicelineBundle {
String name;
JButton button;
JComponent firstSection;
JComponent secondSection;
JComponent thirdSection;
public VoicelineBundle() {
}
public VoicelineBundle(JButton button, JComponent firstSection,
JComponent secondSection, JComponent thirdSection) {
this.button = button;
this.firstSection = firstSection;
this.secondSection = secondSection;
this.thirdSection = thirdSection;
this.name = button.getText();
}
public void setButton(JButton button) {
this.button = button;
this.name = button.getText();
}
public void setFirstSection(JComponent firstSection) {
this.firstSection = firstSection;
}
public void setSecondSection(JComponent secondSection) {
this.secondSection = secondSection;
}
public void setThirdSection(JComponent thirdSection) {
this.thirdSection = thirdSection;
}
@Override
public String toString() {
return "VoicelineBundle{" +
"name='" + name + '\'' +
", lowerTitle=" + ((firstSection !=null) ?((JLabel) firstSection).getText() : "null") +
", middleTitle=" + ((secondSection !=null) ? ((JLabel) secondSection).getText() : "null") +
", upperTitle=" + ((thirdSection !=null) ? ((JLabel) thirdSection).getText() : "null") +
'}';
}
}
<file_sep># voicelines
Short applet that lets you play .OGG files from a wiki, while fetching the text associated with those
Uses an external library for HTML parsing
Allows you to search for a webpage directly
Handles links and words, recreates a URL in either case and checks if it the kind of URL that is expected, and if the server doesn't return an error
Creates a new button for each voiceline, and giving it its text
You can navigate through the list of buttons via the table of content to be found on the left-hand side
Clicking on an item on the left will reposition the scrollbar of the center area, effectively bringing you to the section you clicked on

Menu items that are lists that have all the gods/skins/AP to allow you to navigate your way through them all
Those lists do not load only once all the buttons are done loading, but update with each newly created button

Distinguishes between when an audio file is available (button enabled) and when it isn't (button disabled)
Useful when the text has been contributed, but not the audio file

Allows you to filter the buttons and display only those that contain the input you provide

<file_sep>package xyz.realraec;
import java.io.IOException;
import org.jsoup.helper.Validate;
public class VGSMain {
public static void main(String[] args) throws IOException {
String url = "";
/*
Either with jSoup
Validate.isTrue(args.length == 1, "Supply URL to fetch.");
url = args[0];
or without
assert args.length == 1;
url = args[0];
*/
//url = "https://smite.gamepedia.com/Baron_Samedi_voicelines";
//url = "https://smite.gamepedia.com/Fafnir_voicelines";
//url = "https://smite.gamepedia.com/Cu_Chulainn_voicelines";
//url = "https://smite.gamepedia.com/Kukulkan_voicelines";
//url = "https://smite.gamepedia.com/Ymir_voicelines";
//url = "https://smite.gamepedia.com/Stellar_Demise_Baron_Samedi_voicelines";
//url = "https://smite.gamepedia.com/Cu_Chulainn_voicelines";
//url = "https://smite.gamepedia.com/Demonic_Pact_Anubis_voicelines";
//url = "https://smite.gamepedia.com/Hel_voicelines";
//url = "https://smite.gamepedia.com/Sylvanus_voicelines";
//url = "https://smite.gamepedia.com/Cthulhu_voicelines";
//url = "https://smite.gamepedia.com/Geb_voicelines";
//url = "https://smite.gamepedia.com/Aggro_Announcer_pack";
//url = "https://smite.gamepedia.com/Announcer_Packs";
//url = "https://smite.gamepedia.com/God_voicelines";
//url = "https://smite.gamepedia.com/Skin_voicelines";
//url = "https://smite.gamepedia.com/Ma_Ch%C3%A9rie_Arachne_voicelines";
//url = "https://smite.gamepedia.com/Unbreakable_Anhur_voicelines";
//url = "https://smite.gamepedia.com/Winds_of_Change_Kukulkan_voicelines";
//url = "https://smite.gamepedia.com/King_Arthur_voicelines";
//url = "https://smite.gamepedia.com/Chang'e_voicelines";
//url = "https://smite.gamepedia.com/Divine_Dragon_Bellona_voicelines";
url = "https://smite.gamepedia.com/Ra%27merica_voicelines";
System.out.println("Fetching " + url);
// Frame
new MainFrame(url);
}
}
| 9bdc6c61d564a1a937fcf7d07d8c31e85165e8b3 | [
"Markdown",
"Java"
] | 4 | Java | realraec/voicelines | 1b19006c97aa8d10df2e6ed43232f212ed8c7186 | 90f92d8470d47245ae2e4f2895ff0b1f992acf97 |
refs/heads/main | <repo_name>1fallxbamba/PMS_backend<file_sep>/api/core/administrator/deleteemployee.php
<?php
include '../../config/controller.php';
$_employeeID = isset($_GET['code']) ? $_GET['code'] : die(json_encode(array('ERROR' => 'No Employee Code provided')));
// Get the posted data
$_data = file_get_contents("php://input");
$newClientData = json_decode($_data);
$woman = new AdministratorController();
$woman->deleteEmployee($_employeeID);
<file_sep>/api/core/secretary/newproject.php
<?php
include '../../config/controller.php';
// Get the posted data
$_data = file_get_contents("php://input");
$_projectData = json_decode($_data);
$woman = new SecretaryController();
$woman->addProject($_projectData);
<file_sep>/api/core/shared/authenticate.php
<?php
include '../../config/controller.php';
$_data = file_get_contents("php://input");
$_credentials = json_decode($_data);
$pmsUser = new PMSController();
$pmsUser->authenticate($_credentials);
<file_sep>/api/config/controller.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: *');
/**
* PMS Controller v1.0, @author : 1fallxbamba
*/
require_once __DIR__ . '/vendor/autoload.php';
class PMSController
{
protected static $_db;
public function __construct()
{
$client = new \MongoDB\Client('mongodb://localhost:27017');
self::$_db = $client->pms;
}
public function authenticate($credentials)
{
$_collection = self::$_db->employees;
try {
$result = $_collection->findOne(['login' => $credentials->login]);
if ($result == null) {
self::notify("err", "UDNE", "User Does Not Exist : the given login does not exist.");
} else {
if (password_verify($credentials->passwd, $result['shadow'])) {
self::notify("s", "USA", "User Successfully Authenticated", array(
'id' => $result['_id'],
'profile' => $result['profile'],
'nom' => $result['nom'],
'prenom' => $result['prenom'],
'email' => $result['email']
));
} else {
self::notify("err", "WPWD", "Wrong Password : The entered password is incorrect.");
}
}
} catch (Exception $e) {
self::notify("uerr", "UNEX", $e->getMessage());
}
}
public function fetchEmployeeInfo($employeeID)
{
$_collection = self::$_db->employees;
try {
$result = $_collection->findOne(
['_id' => new MongoDB\BSON\ObjectId($employeeID)],
['projection' => [
'name' => 1,
'fName' => 1,
'tel' => 1,
'email' => 1,
'profile' => 1
]]
);
if ($result == null) {
self::notify("err", "ENF", "Employee Not Found : the given id may be inexistant.");
} else {
self::notify("s", "EDF", "Employee Data Found", $result);
}
} catch (Exception $e) {
self::notify("uerr", "UNEX", $e->getMessage());
}
}
public function fetchProjects()
{
$_collection = self::$_db->projects;
try {
$result = $_collection->find();
if ($result == null) {
self::notify("err", "NPF", "No Projects Found.");
} else {
$res = array();
foreach ($result as $document) {
array_push($res, $document);
}
self::notify("s", "PF", "Projects Found", $res);
}
} catch (Exception $e) {
self::notify("uerr", "UNEX", $e->getMessage());
}
}
public function fetchProject($projectID)
{
$_collection = self::$_db->projects;
try {
$result = $_collection->findOne(['_id' => new MongoDB\BSON\ObjectId($projectID)]);
self::notify("s", "PDF", "Project Data Found", $result);
} catch (Exception $e) {
self::notify("uerr", "UNEX", $e->getMessage());
}
}
public function searchProject($projectName)
{
$_collection = self::$_db->projects;
try {
$result = $_collection->findOne(['name' => $projectName]);
if ($result == null) {
self::notify("err", "NPF", "No Project Found for the given name");
} else {
self::notify("s", "PDF", "Project Data Found", $result);
}
} catch (Exception $e) {
self::notify("uerr", "UNEX", $e->getMessage());
}
}
public function updateProject($projectID, $newData)
{
$_collection = self::$_db->projects;
try {
$_collection->updateOne(
['_id' => new MongoDB\BSON\ObjectId($projectID)],
['$set' => $newData]
);
self::notify("s", "PSU", "Project Successfully Updated");
} catch (Exception $e) {
self::notify("uerr", "UNEX", $e);
}
}
public static function notify($type, $code, $message, $data = null)
{
if ($type == 'uerr') {
echo json_encode(array('RESPONSE' => 'Unexpected-Error', 'CODE' => $code, 'DESCRIPTION' => $message));
} elseif ($type == 'err') {
echo json_encode(array('RESPONSE' => 'Request-Error', 'CODE' => $code, 'DESCRIPTION' => $message));
} else {
if ($data == null) {
echo json_encode(array('RESPONSE' => 'Success', 'CODE' => $code, 'MESSAGE' => $message));
} else {
echo json_encode(array('RESPONSE' => 'Success', 'CODE' => $code, 'MESSAGE' => $message, 'DATA' => $data));
}
}
}
}
class SecretaryController extends PMSController
{
private $_collection;
public function addProject($projectData)
{
$this->_collection = parent::$_db->projects;
try {
$this->_collection->insertOne($projectData);
parent::notify("s", "PSA", "Project Successfully Added");
} catch (Exception $e) {
parent::notify("uerr", "UNEX", $e->getMessage());
}
}
public function addClient($clientData)
{
$this->_collection = parent::$_db->clients;
try {
$this->_collection->insertOne($clientData);
parent::notify("s", "CSA", "Client Successfully Added");
} catch (Exception $e) {
parent::notify("uerr", "UNEX", $e->getMessage());
}
}
public function updateClient($clientID, $newData)
{
$this->_collection = parent::$_db->clients;
try {
$this->_collection->updateOne(
['_id' => new MongoDB\BSON\ObjectId($clientID)],
['$set' => $newData]
);
parent::notify("s", "CSU", "Client Successfully Updated");
} catch (Exception $e) {
parent::notify("uerr", "UNEX", $e);
}
}
}
class AdministratorController extends PMSController
{
private $_collection;
public function __construct()
{
parent::__construct();
$this->_collection = parent::$_db->employees;
}
public function addEmployee($employeeData)
{
try {
$this->_collection->insertOne($employeeData);
parent::notify("s", "ESA", "Employee Successfully Added");
} catch (Exception $e) {
parent::notify("uerr", "UNEX", $e->getMessage());
}
}
public function updateEmployee($employeeID, $newData)
{
try {
$this->_collection->updateOne(
['_id' => new MongoDB\BSON\ObjectId($employeeID)],
['$set' => $newData]
);
parent::notify("s", "USU", "User Successfully Updated");
} catch (Exception $e) {
parent::notify("uerr", "UNEX", $e);
}
}
public function deleteEmployee($employeeID)
{
try {
$this->_collection->deleteOne(['_id' => new MongoDB\BSON\ObjectId($employeeID)]);
parent::notify("s", "USD", "User Successfully Deleted");
} catch (Exception $e) {
parent::notify("uerr", "UNEX", $e);
}
}
}
<file_sep>/api/core/shared/updateproject.php
<?php
include '../../config/controller.php';
$_projectID = isset($_GET['code']) ? $_GET['code'] : die(json_encode(array('ERROR' => 'No Project Code provided')));
$_data = file_get_contents("php://input");
$newProjectData = json_decode($_data);
$pmsUser = new PMSController();
$pmsUser->updateProject($_projectID, $newProjectData);
<file_sep>/api/core/shared/project.php
<?php
include '../../config/controller.php';
$_projectID = isset($_GET['code']) ? $_GET['code'] : die(json_encode(array('ERROR' => 'No Project Code provided')));
$pmsUser = new PMSController();
$pmsUser->fetchProject($_projectID);
<file_sep>/api/config/tt.php
<?php
require_once __DIR__ .'/vendor/autoload.php';
$client = new \MongoDB\Client('mongodb://localhost:27017');
$db = $client->test;
$col = $db->first;
// $result = $col->insertOne([ 'firstName' => 'Ibou', 'lastName' => 'Ndiaye', 'phones' => json_encode(array('SN' => 788888888, 'TN' => 3324557765)) ]);
// echo "Inserted object with id ". $result->getInsertedId();
$result = $col->find([]);
$res = array();
foreach ($result as $document) {
// print_r($document['firstName']);
array_push($res, $document);
}
echo json_encode($res);
<file_sep>/api/core/administrator/newemployee.php
<?php
include '../../config/controller.php';
// Get the posted data
$_data = file_get_contents("php://input");
$_employeeData = json_decode($_data);
$_employeeData->shadow = password_hash($_employeeData->shadow, PASSWORD_DEFAULT);
$admin = new AdministratorController();
$admin->addEmployee($_employeeData);
<file_sep>/api/core/secretary/updateclient.php
<?php
include '../../config/controller.php';
$_clientID = isset($_GET['code']) ? $_GET['code'] : die(json_encode(array('ERROR' => 'No Client Code provided')));
// Get the posted data
$_data = file_get_contents("php://input");
$newClientData = json_decode($_data);
$woman = new SecretaryController();
$woman->updateClient($_clientID, $newClientData);
<file_sep>/api/core/shared/projects.php
<?php
include '../../config/controller.php';
$pmsUser = new PMSController();
$pmsUser->fetchProjects();
<file_sep>/api/core/shared/employeeinfo.php
<?php
include '../../config/controller.php';
$_employeeID = isset($_GET['code']) ? $_GET['code'] : die(json_encode(array('ERROR' => 'No Employee Code provided')));
$pmsUser = new PMSController();
$pmsUser->fetchEmployeeInfo($_employeeID);
<file_sep>/api/core/secretary/newclient.php
<?php
include '../../config/controller.php';
// Get the posted data
$_data = file_get_contents("php://input");
$_clientData = json_decode($_data);
$woman = new SecretaryController();
$woman->addClient($_clientData);
| 505358ba9ca48da7c53b576be0e164295766bfa7 | [
"PHP"
] | 12 | PHP | 1fallxbamba/PMS_backend | 56688af8b1a67b7515fc950dbf1ebf85b926702e | a1abef9103874131cde2b41c2fa54bef61976ad1 |
refs/heads/master | <file_sep>function getUserInfo() {
console.log("getuserinfo");
var mysupersuit = new Gh3.User("mysupersuit"),
userInfos = $("#user");
mysupersuit.fetch(function (err, resUser) {
if (err) {
throw "ouch..."
}
console.log(mysupersuit, resUser);
_.each(_.keys(resUser), function(prop) {
userInfos.append(
$('<li>').append(prop+" : "+resUser[prop])
);
});
});
}
function getRepo() {
console.log("get repo");
var mysupersuit = new Gh3.User("mysupersuit");
var myRepos = new Gh3.Repositories(mysupersuit);
myRepos.fetch({page:1, per_page:5, direction : "desc"},"next",
function (err, res) {
if (err) {
throw "ouch...";
}
console.log("Repositories ", myRepos);
});
}
function userSearch() {
console.log("user search");
Gh3.Search.users({
q: '+language:Python+location:Ireland',
sort: 'followers',
}, {per_page: 1}, function (err,users) {
if (err) {throw 'ouch...'}
//console.log(users);
var user = users[0];
console.log(user);
var userRepo = new Gh3.Repositories(user);
userRepo.fetch({page:1,per_page:1,direction : "desc"},"next",function(err, res) {
if (err) {
throw "ouch..."
}
var repo = res.repositories[0];
console.log(repo);
});
// _.each(users, function(user) {
// $("#user").append(
// $('<li/>').append(
// $('<a/>')
// .attr('href', user.html_url)
// .text(user.login)
// )
// );
// })
});
}
// seems good (except first one)
// for each repo impact vs churn per top collaborator?
//visualisation for each repo?
// then best coders/ see what langauge are most popular among the "best" coders
Gh3.Search.repos({
q: 'size:>=100000',
sort: 'forks',
order: 'desc'
}, {per_page: 50}, function(err, repos) {
console.log(repos);
});
<file_sep># githubAPI
Merge pull #1 interrogates api and returns a list of python developers in Ireland sorted by followers.
| 56d7ded382dc2926a623b069e2f2b620777c5fd4 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | MySupersuit/githubAPI | 9df179899430aaa1f62821c313ff7004e9d2acf7 | f457a6a717f59265a8cec1c8295bc62d1369f5e5 |
refs/heads/master | <repo_name>correasebastian/webpack-beginner-guide<file_sep>/src/app.js
// src/app.js
if (module.hot) {
module.hot.accept()
}
import './styles.scss'
import {groupBy} from 'lodash/collection'
const people = [{
manager: 'Jen',
name: 'Bob'
}, {
manager: 'Jen',
name: 'Sue'
}, {
manager: 'Bob',
name: 'Shirley'
}, {
manager: 'Bob',
name: 'Terrence'
}]
const managerGroups = groupBy(people, 'manager')
const root = document.querySelector('#root')
root.innerHTML = `<pre>${JSON.stringify(managerGroups, null, 2)}</pre>`
const routes = {
dashboard: () => {
System.import('./dashboard').then((dashboard) => {
dashboard.draw()
}).catch((err) => {
console.log("Chunk loading failed")
})
}
}
// demo async loading with a timeout
setTimeout(routes.dashboard, 2000) | ff375a13eeaecedb6b8924872541ce2f450cc55b | [
"JavaScript"
] | 1 | JavaScript | correasebastian/webpack-beginner-guide | 1254a4054df46da8177070649509ef7f64d22cf6 | a7e47b01dce515977d0ca318f94af6adc13d7dd4 |
refs/heads/master | <repo_name>codeesh/sql-crowdfunding-lab-v-000<file_sep>/lib/insert.sql
INSERT INTO projects VALUES (1,'Send Me to Mars','Travel','5000000000','March 1 ,2016', 'March 28,2017');
INSERT INTO projects VALUES (2,'Replace My broken iron','Personal','20','March 1 ,2016', 'March 2,2016');
INSERT INTO projects VALUES (3,'Emergency surgery for dog','Animal Care','6500','March 1 ,2016', 'March 8,2016');
INSERT INTO projects VALUES (4,'Vacation to Hawaii','Travel','6000','March 1 ,2016', 'March 20,2016');
INSERT INTO projects VALUES (5,'Rehome dog/cats','Animal care','15000','March 1 ,2016', 'April 28,2016');
INSERT INTO projects VALUES (6,'Send Me to Mars','Travel','5000000000','March 1 ,2016', 'March 28,2016');
INSERT INTO projects VALUES (7,'Send Me to Mars','Travel','5000000000','March 1 ,2016', 'March 28,2016');
INSERT INTO projects VALUES (8,'Send Me to Mars','Travel','5000000000','March 1 ,2016', 'March 28,2016');
INSERT INTO projects VALUES (9,'Send Me to Mars','Travel','5000000000','March 1 ,2016', 'March 28,2016');
INSERT INTO projects VALUES (10,'Send Me to Mars','Travel','5000000000','March 1 ,2016', 'March 28,2016');
INSERT INTO users VALUES (1,'John',18);
INSERT INTO users VALUES (2,'Joe',35);
INSERT INTO users VALUES (3,'Sabrina',20);
INSERT INTO users VALUES (4,'Samantha',25);
INSERT INTO users VALUES (5,'Dave',48);
INSERT INTO users VALUES (6,'Jim',65);
INSERT INTO users VALUES (7,'Holly',30);
INSERT INTO users VALUES (8,'Tim',40);
INSERT INTO users VALUES (9,'JOHN',20);
INSERT INTO users VALUES (10,'JOHN',20);
INSERT INTO users VALUES (11,'JOHN',20);
INSERT INTO users VALUES (12,'JOHN',20);
INSERT INTO users VALUES (13,'JOHN',20);
INSERT INTO users VALUES (14,'JOHN',20);
INSERT INTO users VALUES (15,'JOHN',20);
INSERT INTO users VALUES (16,'JOHN',20);
INSERT INTO users VALUES (17,'JOHN',20);
INSERT INTO users VALUES (18,'JOHN',20);
INSERT INTO users VALUES (19,'JOHN',20);
INSERT INTO users VALUES (20,'JOHN',20);
INSERT INTO pledges VALUES (1,10,'John',1);
INSERT INTO pledges VALUES (2,50,'Joe',5);
INSERT INTO pledges VALUES (3,1000,'Sabrina',5);
INSERT INTO pledges VALUES (4,20,'Samantha',4);
INSERT INTO pledges VALUES (5,5,'Dave',6);
INSERT INTO pledges VALUES (6,5,'Jim',7);
INSERT INTO pledges VALUES (7,5000,'Holly',1);
INSERT INTO pledges VALUES (8,25,'Tim',2);
INSERT INTO pledges VALUES (9,5,'JOHN',2);
INSERT INTO pledges VALUES (10,90,'JOHN',3);
INSERT INTO pledges VALUES (11,10,'JOHN',5);
INSERT INTO pledges VALUES (12,20,'JOHN',6);
INSERT INTO pledges VALUES (13,1000,'JOHN',4);
INSERT INTO pledges VALUES (14,100,'JOHN',4);
INSERT INTO pledges VALUES (15,900,'JOHN',9);
INSERT INTO pledges VALUES (16,50,'JOHN',10);
INSERT INTO pledges VALUES (17,25,'JOHN',10);
INSERT INTO pledges VALUES (18,900,'JOHN',4);
INSERT INTO pledges VALUES (19,2000,'JOHN',4);
INSERT INTO pledges VALUES (20,50,'JOHN',5);
INSERT INTO pledges VALUES (21,30,'John',6);
INSERT INTO pledges VALUES (22,40,'Joe',7);
INSERT INTO pledges VALUES (23,90,'Sabrina',8);
INSERT INTO pledges VALUES (24,4000,'Samantha',2);
INSERT INTO pledges VALUES (25,50,'Dave',7);
INSERT INTO pledges VALUES (26,20,'Jim',7);
INSERT INTO pledges VALUES (27,35,'Holly',6);
INSERT INTO pledges VALUES (28,500,'Tim',4);
INSERT INTO pledges VALUES (29,50,'JOHN',3);
INSERT INTO pledges VALUES (30,400,'JOHN',5);
<file_sep>/lib/sql_queries.rb
# Write your sql queries in this file in the appropriate method like the example below:
#
# def select_category_from_projects
# "SELECT category FROM projects;"
# end
# Make sure each ruby method returns a string containing a valid SQL statement.
def selects_the_titles_of_all_projects_and_their_pledge_amounts
"SELECT Title, SUM(amount)
from pledges
INNER JOIN projects
ON projects.Id = pledges.Project_id
GROUP BY title;"
end
def selects_the_user_name_age_and_pledge_amount_for_all_pledges
"SELECT Name,Age, SUM(amount)
FROM users
INNER JOIN pledges
ON users.Id = pledges.User_id
GROUP BY name;
"
end
def selects_the_titles_of_all_projects_that_have_met_their_funding_goal
"SELECT Title , projects.Funding_goal - SUM(amount)
from pledges
JOIN projects
ON projects.Id = pledges.Project_id
GROUP BY title
HAVING SUM(pledges.Amount) >= projects.Funding_goal ;"
end
def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_amount
"SELECT Name, SUM(amount)
FROM pledges
INNER JOIN users
ON users.Id = pledges.User_id
GROUP BY name
ORDER BY SUM(amount) ASC ;"
end
def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category
"SELECT category,amount
FROM projects
INNER JOIN pledges
ON projects.Id = pledges.Project_id
GROUP BY pledges.Id
HAVING projects.Category = 'music';"
end
def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_book_category
"SELECT category,SUM(amount)
FROM projects
INNER JOIN pledges
ON projects.Id = pledges.Project_id
GROUP BY category
HAVING projects.Category = 'books';"
end
| 147fc1b14a1fb6e5c48e5e15943fc6a3857a13de | [
"SQL",
"Ruby"
] | 2 | SQL | codeesh/sql-crowdfunding-lab-v-000 | 1563ad6c32244f62db9c91fc6e07ad807f608e43 | ddf914314798401ac438149d470e08a98d1a2208 |
refs/heads/master | <repo_name>lordrex34/commons-annotation-config<file_sep>/src/main/java/com/github/lordrex34/config/converter/ArrayConfigConverter.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.converter;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.regex.Pattern;
public class ArrayConfigConverter implements IConfigConverter
{
@Override
public Object convertFromString(Field field, Class<?> type, String value)
{
final Class<?> componentType = type.getComponentType();
if (value.isEmpty())
{
return Array.newInstance(componentType, 0);
}
final String[] splitted = Pattern.compile(getElementDelimiter(), Pattern.LITERAL).split(value);
final Object array = Array.newInstance(componentType, splitted.length);
for (int i = 0; i < splitted.length; i++)
{
Array.set(array, i, getElementConverter().convertFromString(field, componentType, splitted[i]));
}
// Commented out, so arrays can retain their order, and tests won't fail.
// I merely don't see any reason why on earth should a String array be sorted.
// if (Comparable.class.isAssignableFrom(componentType))
// {
// Arrays.sort((Comparable[]) array);
// }
return array;
}
@Override
public String convertToString(Field field, Class<?> type, Object obj)
{
final Class<?> componentType = type.getComponentType();
if (obj == null)
{
return "";
}
final int length = Array.getLength(obj);
if (length < 1)
{
return "";
}
// Commented out, so arrays can retain their order, and tests won't fail.
// I merely don't see any reason why on earth should a String array be sorted.
// if (Comparable.class.isAssignableFrom(componentType))
// {
// Arrays.sort((Comparable[]) obj);
// }
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
if (i > 0)
{
sb.append(getElementDelimiter());
}
sb.append(getElementConverter().convertToString(field, componentType, Array.get(obj, i)));
}
return sb.toString();
}
protected String getElementDelimiter()
{
return ",";
}
protected IConfigConverter getElementConverter()
{
return MainConfigConverter.getInstance();
}
private static final class SingletonHolder
{
static final ArrayConfigConverter INSTANCE = new ArrayConfigConverter();
}
public static ArrayConfigConverter getInstance()
{
return SingletonHolder.INSTANCE;
}
}
<file_sep>/src/test/java/com/github/lordrex34/config/AbstractConfigTest.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.junit.Before;
import com.github.lordrex34.config.annotation.ConfigClass;
import com.github.lordrex34.config.util.ConfigPropertyRegistry;
import com.github.lordrex34.reflection.util.ClassPathUtil;
/**
* @author lord_rex
*/
public abstract class AbstractConfigTest
{
protected ConfigManager _configManager;
@Before
public void before() throws IOException, IllegalArgumentException, IllegalAccessException, InstantiationException
{
clearAll(ITestConfigMarker.class.getPackage().getName());
_configManager = new ConfigManager();
_configManager.load(ITestConfigMarker.class.getPackage().getName());
}
protected void reload() throws IllegalAccessException, IOException, InstantiationException
{
_configManager.reload(ITestConfigMarker.class.getPackage().getName());
}
/**
* Clears everything from the manager. Clears also the values of the fields. Usable only for tests.
* @param packageName the package where configuration related classes are stored
* @throws IOException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws SecurityException
*/
static void clearAll(String packageName) throws SecurityException, IllegalArgumentException, IllegalAccessException, IOException
{
for (Class<?> configClass : ClassPathUtil.getAllClassesAnnotatedWith(ClassLoader.getSystemClassLoader(), packageName, ConfigClass.class))
{
for (Field field : configClass.getDeclaredFields())
{
if (!Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()))
{
// Skip inappropriate fields.
continue;
}
// private field support
final boolean wasAccessible = field.isAccessible(); /*field.canAccess(null);*/
try
{
if (!wasAccessible)
{
field.setAccessible(true);
}
final Class<?> type = field.getType();
if ((type == Boolean.class) || (type == Boolean.TYPE))
{
field.setBoolean(null, false);
}
else if ((type == Long.class) || (type == Long.TYPE))
{
field.setLong(null, 0);
}
else if ((type == Integer.class) || (type == Integer.TYPE))
{
field.setInt(null, 0);
}
else if ((type == Short.class) || (type == Short.TYPE))
{
field.setShort(null, (short) 0);
}
else if ((type == Byte.class) || (type == Byte.TYPE))
{
field.setByte(null, (byte) 0);
}
else if ((type == Double.class) || (type == Double.TYPE))
{
field.setDouble(null, 0);
}
else if ((type == Float.class) || (type == Float.TYPE))
{
field.setFloat(null, 0);
}
else
{
field.set(null, null);
}
}
finally
{
// restore field's visibility to the original
field.setAccessible(wasAccessible);
}
}
}
ConfigPropertyRegistry.clearAll();
}
}
<file_sep>/src/main/java/com/github/lordrex34/config/converter/MainConfigConverter.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.converter;
import java.io.File;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import com.github.lordrex34.config.lang.FieldParser;
public class MainConfigConverter implements IConfigConverter
{
@Override
public Object convertFromString(Field field, Class<?> type, String value)
{
if (type.isArray())
{
return getArrayConverter().convertFromString(field, type, value);
}
if (type == List.class)
{
return getListConverter().convertFromString(field, type, value);
}
if (type == Set.class)
{
return getSetConverter().convertFromString(field, type, value);
}
if (type == Path.class)
{
return getPathConverter().convertFromString(field, type, value);
}
if (type == File.class)
{
return getFileConverter().convertFromString(field, type, value);
}
if (type == Pattern.class)
{
return getPatternConverter().convertFromString(field, type, value);
}
if (type == Duration.class)
{
return getDurationConverter().convertFromString(field, type, value);
}
return FieldParser.get(type, value);
}
@Override
public String convertToString(Field field, Class<?> type, Object obj)
{
if (type.isArray())
{
return getArrayConverter().convertToString(field, type, obj);
}
if (type == List.class)
{
return getListConverter().convertToString(field, type, obj);
}
if (type == Set.class)
{
return getSetConverter().convertToString(field, type, obj);
}
if (type == Path.class)
{
return getPathConverter().convertToString(field, type, obj);
}
if (type == File.class)
{
return getFileConverter().convertToString(field, type, obj);
}
if (type == Pattern.class)
{
return getPatternConverter().convertToString(field, type, obj);
}
if (type == Duration.class)
{
return getDurationConverter().convertToString(field, type, obj);
}
if (obj == null)
{
return "";
}
return obj.toString();
}
protected IConfigConverter getArrayConverter()
{
return ArrayConfigConverter.getInstance();
}
protected IConfigConverter getListConverter()
{
return ListConfigConverter.getInstance();
}
protected IConfigConverter getSetConverter()
{
return SetConfigConverter.getInstance();
}
protected IConfigConverter getPathConverter()
{
return PathConfigConverter.getInstance();
}
protected IConfigConverter getFileConverter()
{
return FileConfigConverter.getInstance();
}
protected IConfigConverter getPatternConverter()
{
return PatternConfigConverter.getInstance();
}
protected IConfigConverter getDurationConverter()
{
return DurationConfigConverter.getInstance();
}
private static final class SingletonHolder
{
static final MainConfigConverter INSTANCE = new MainConfigConverter();
}
public static MainConfigConverter getInstance()
{
return SingletonHolder.INSTANCE;
}
}
<file_sep>/src/main/java/com/github/lordrex34/config/lang/ConfigProperties.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.lang;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import com.github.lordrex34.config.util.TimeUtil;
/**
* A simple properties loader designed for <b>{@link String} based</b> key-value based property loading.
* @author Noctarius (original idea, basic concept)
* @author NB4L1 (re-designed concept)
* @author savormix (re-designed java 8 concept)
* @author NosBit (the getters)
*/
public class ConfigProperties implements Serializable
{
private static final long serialVersionUID = -6418707730244047405L;
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigProperties.class);
public static final ConfigProperties EMPTY = new ConfigProperties(Collections.emptyMap());
private final Map<String, String> _map;
private String _loggingPrefix = getClass().getSimpleName();
// ===================================================================================
// Default constructors
public ConfigProperties(Map<String, String> map)
{
_map = map;
}
public ConfigProperties()
{
this(new HashMap<>());
}
// ===================================================================================
// Special Constructors
public ConfigProperties(Path path) throws IOException
{
this();
_loggingPrefix = path.toString();
load(path);
}
public ConfigProperties(File file) throws IOException
{
this();
_loggingPrefix = file.toString();
load(file);
}
public ConfigProperties(String name) throws IOException
{
this();
_loggingPrefix = name;
load(name);
}
public ConfigProperties(Node node)
{
this();
load(node);
}
public ConfigProperties(Properties properties)
{
this();
load(properties);
}
public ConfigProperties(ConfigProperties properties)
{
this();
load(properties);
}
// ===================================================================================
// Loaders
public void load(Path path) throws IOException
{
final Properties prop = new Properties();
try (InputStream in = Files.newInputStream(path))
{
prop.load(in);
}
load(prop);
}
public void load(File file) throws IOException
{
load(file.toPath());
}
public void load(String name) throws IOException
{
load(Paths.get(name));
}
public void load(Node node)
{
final NamedNodeMap attrs = node.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
final Node attr = attrs.item(i);
setProperty(attr.getNodeName(), attr.getNodeValue());
}
}
public void load(Properties properties)
{
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
setProperty(entry.getKey(), entry.getValue());
}
}
public void load(ConfigProperties properties)
{
for (Map.Entry<String, String> entry : properties.entrySet())
{
setProperty(entry.getKey(), entry.getValue());
}
}
// ===================================================================================
// Wrapped map functions
public String setProperty(String key, String value)
{
return _map.put(key, value);
}
public String setProperty(Object key, Object value)
{
return _map.put(String.valueOf(key), String.valueOf(value));
}
public void clear()
{
_map.clear();
}
public int size()
{
return _map.size();
}
public boolean containsKey(String key)
{
return _map.containsKey(key);
}
public Set<Entry<String, String>> entrySet()
{
return Collections.unmodifiableSet(_map.entrySet());
}
// ===================================================================================
// getProperty
public String getProperty(String key)
{
final String value = _map.get(key);
return value != null ? value.trim() : null;
}
public String getProperty(String key, String defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
return value;
}
// ===================================================================================
// Parsers
public boolean getBoolean(String key, boolean defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
if (value.equalsIgnoreCase("true"))
{
return true;
}
else if (value.equalsIgnoreCase("false"))
{
return false;
}
else
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be \"boolean\" using default value: {}", _loggingPrefix, key, value, defaultValue);
return defaultValue;
}
}
public byte getByte(String key, byte defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
try
{
return Byte.parseByte(value);
}
catch (NumberFormatException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be \"byte\" using default value: {}", _loggingPrefix, key, value, defaultValue);
return defaultValue;
}
}
public short getShort(String key, short defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
try
{
return Short.parseShort(value);
}
catch (NumberFormatException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be \"short\" using default value: {}", _loggingPrefix, key, value, defaultValue);
return defaultValue;
}
}
public int getInt(String key, int defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
try
{
return Integer.parseInt(value);
}
catch (NumberFormatException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be \"int\" using default value: {}", _loggingPrefix, key, value, defaultValue);
return defaultValue;
}
}
public long getLong(String key, long defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
try
{
return Long.parseLong(value);
}
catch (NumberFormatException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be \"long\" using default value: {}", _loggingPrefix, key, value, defaultValue);
return defaultValue;
}
}
public float getFloat(String key, float defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
try
{
return Float.parseFloat(value);
}
catch (NumberFormatException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be \"float\" using default value: {}", _loggingPrefix, key, value, defaultValue);
return defaultValue;
}
}
public double getDouble(String key, double defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
try
{
return Double.parseDouble(value);
}
catch (NumberFormatException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be \"double\" using default value: {}", _loggingPrefix, key, value, defaultValue);
return defaultValue;
}
}
public String getString(String key, String defaultValue)
{
return getProperty(key, defaultValue);
}
public <T extends Enum<T>> T getEnum(String key, Class<T> clazz, T defaultValue)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValue);
return defaultValue;
}
try
{
return Enum.valueOf(clazz, value);
}
catch (IllegalArgumentException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be enum value of \"{}\" using default value: {}", _loggingPrefix, key, value, clazz.getSimpleName(), defaultValue);
return defaultValue;
}
}
public Duration getDuration(String durationPattern, String defaultValue)
{
return getDuration(durationPattern, defaultValue, null);
}
public Duration getDuration(String durationPattern, String defaultValue, Duration defaultDuration)
{
final String value = getString(durationPattern, defaultValue);
try
{
return TimeUtil.parseDuration(value);
}
catch (IllegalStateException e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {] should be time patttern using default value: {}", _loggingPrefix, durationPattern, value, defaultValue);
}
return defaultDuration;
}
public int[] getIntArray(String key, String separator, int... defaultValues)
{
final String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValues);
return defaultValues;
}
try
{
final String[] data = value.trim().split(separator);
int[] result = new int[data.length];
for (int i = 0; i < data.length; i++)
{
result[i] = Integer.decode(data[i].trim());
}
return result;
}
catch (Exception e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be array using default value: {}", _loggingPrefix, key, value, defaultValues);
return defaultValues;
}
}
@SafeVarargs
public final <T extends Enum<T>> T[] getEnumArray(String key, String separator, Class<T> clazz, T... defaultValues)
{
final String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValues);
return defaultValues;
}
try
{
final String[] data = value.trim().split(separator);
@SuppressWarnings("unchecked")
final T[] result = (T[]) Array.newInstance(clazz, data.length);
for (int i = 0; i < data.length; i++)
{
result[i] = Enum.valueOf(clazz, data[i]);
}
return result;
}
catch (Exception e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be array using default value: {}", _loggingPrefix, key, value, defaultValues);
return defaultValues;
}
}
@SafeVarargs
public final <T extends Enum<T>> List<T> getEnumList(String key, String separator, Class<T> clazz, T... defaultValues)
{
String value = getProperty(key);
if (value == null)
{
LOGGER.warn("[{}] missing property for key: {} using default value: {}", _loggingPrefix, key, defaultValues);
return Arrays.asList(defaultValues);
}
try
{
final String[] data = value.trim().split(separator);
final List<T> result = new ArrayList<>(data.length);
for (String element : data)
{
result.add(Enum.valueOf(clazz, element));
}
return result;
}
catch (Exception e)
{
LOGGER.warn("[{}] Invalid value specified for key: {} specified value: {} should be array using default value: {}", _loggingPrefix, key, value, defaultValues);
return Arrays.asList(defaultValues);
}
}
// ===================================================================================
// Utilities
/**
* Gets the result of two properties parser, where second is the override which overwrites the content of the first, if necessary.
* @param properties the original properties file
* @param override the override properties that overwrites original settings
* @return properties of the two properties parser
*/
public static Properties propertiesOf(ConfigProperties properties, ConfigProperties override)
{
final Properties result = new Properties();
//@formatter:off
Stream.concat(properties.entrySet().stream(), override.entrySet().stream())
.forEach(e -> result.setProperty(String.valueOf(e.getKey()), String.valueOf(e.getValue())));
//@formatter:on
return result;
}
/**
* Same as {@link #propertiesOf(ConfigProperties, ConfigProperties)}, but it returns {@link ConfigProperties}.
* @param properties the original properties file
* @param override the override properties that overwrites original settings
* @return properties of the two properties parser
*/
public static ConfigProperties of(ConfigProperties properties, ConfigProperties override)
{
return new ConfigProperties(propertiesOf(properties, override));
}
}
<file_sep>/src/main/java/com/github/lordrex34/config/supplier/DefaultConfigSupplier.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.supplier;
import java.lang.reflect.Field;
import com.github.lordrex34.config.annotation.ConfigField;
import com.github.lordrex34.config.component.ConfigComponents;
import com.github.lordrex34.config.converter.IConfigConverter;
import com.github.lordrex34.config.lang.ConfigProperties;
import com.github.lordrex34.config.lang.FieldParser.FieldParserException;
/**
* This is the configuration value supplier used by {@link ConfigField} annotation by default.
* @author lord_rex
*/
public class DefaultConfigSupplier implements IConfigValueSupplier<Object>
{
@Override
public Object supply(Class<?> clazz, Field field, ConfigField configField, ConfigProperties properties, boolean generating)
{
final String propertyKey = configField.name();
final String propertyValue = configField.value();
final String configProperty = getProperty(clazz, field, propertyKey, propertyValue, properties);
final IConfigConverter converter = ConfigComponents.get(configField.converter());
try
{
final Object value = converter.convertFromString(field, field.getType(), configProperty);
return generating ? converter.convertToString(field, field.getType(), value) : value;
}
catch (FieldParserException e)
{
throw new FieldParserException("Property '" + propertyKey + "' has incorrect syntax! Please check!");
}
}
/**
* This method provides property value
* <ul>
* <li>using environment variable with syntax: <code>(clazz.getSimpleName() + "_" + field.getName()).toUpperCase()</code></li>
* <li>using system variable with syntax: <code>(clazz.getSimpleName() + "." + field.getName()</code></li>
* <li>"override.properties"</li>
* <li><config name>.properties</li>
* </ul>
* @param clazz
* @param field
* @param propertyKey
* @param propertyValue
* @param properties
* @return the value either environment variable, system property or value specified by the properties files
*/
private String getProperty(Class<?> clazz, Field field, String propertyKey, String propertyValue, ConfigProperties properties)
{
String configProperty = System.getenv((clazz.getSimpleName() + "_" + field.getName()).toUpperCase());
if (configProperty == null)
{
configProperty = System.getProperty(clazz.getSimpleName() + "." + field.getName());
if (configProperty == null)
{
configProperty = properties.getProperty(propertyKey, propertyValue);
}
}
return configProperty;
}
}
<file_sep>/src/test/java/com/github/lordrex34/config/TestConfig.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.github.lordrex34.config.annotation.ConfigClass;
import com.github.lordrex34.config.annotation.ConfigField;
import com.github.lordrex34.config.annotation.ConfigGroupBeginning;
import com.github.lordrex34.config.annotation.ConfigGroupEnding;
import java.io.IOException;
/**
* @author lord_rex
*/
public class TestConfig extends AbstractConfigTest
{
@Test
public void test()
{
assertNotEquals(_configManager.getConfigRegistrySize(), 0);
assertTrue(ConfigTest.TEST_BOOLEAN);
assertEquals(ConfigTest.TEST_STRING, ConfigTest.TEST_STRING_VALUE);
}
@Test
public void testReload() throws IllegalAccessException, IOException, InstantiationException
{
assertNotEquals(_configManager.getConfigRegistrySize(), 0);
assertTrue(ConfigTest.TEST_BOOLEAN);
assertEquals(ConfigTest.TEST_STRING, ConfigTest.TEST_STRING_VALUE);
reload();
assertNotEquals(_configManager.getConfigRegistrySize(), 0);
assertTrue(ConfigTest.TEST_BOOLEAN);
assertEquals(ConfigTest.TEST_STRING, ConfigTest.TEST_STRING_VALUE);
}
@ConfigClass(fileName = "test")
public static class ConfigTest
{
@ConfigGroupBeginning(name = "Booleans")
@ConfigField(name = "TestBoolean", value = "true")
@ConfigGroupEnding(name = "Booleans")
public static boolean TEST_BOOLEAN;
@ConfigGroupBeginning(name = "Numbers")
@ConfigField(name = "TestByte", value = "120")
public static byte TEST_BYTE;
@ConfigField(name = "TestShort", value = "9870")
public static short TEST_SHORT;
@ConfigField(name = "TestInt", value = "129834")
public static int TEST_INT;
@ConfigField(name = "TestLong", value = "712983235535234")
public static long TEST_LONG;
@ConfigField(name = "TestFloat", value = "1234.")
public static float TEST_FLOAT;
@ConfigGroupEnding(name = "Numbers")
@ConfigField(name = "TestDouble", value = "1234.14")
public static double TEST_DOUBLE;
public static final String TEST_STRING_VALUE = "Any string is good here.";
@ConfigGroupBeginning(name = "Strings")
@ConfigField(name = "TestString", value = TEST_STRING_VALUE)
@ConfigGroupEnding(name = "Strings")
public static String TEST_STRING;
@ConfigGroupBeginning(name = "Enums")
@ConfigField(name = "TestEnum", value = "TEST_1")
@ConfigGroupEnding(name = "Enums")
public static EnumForConfig TEST_ENUM;
}
}
<file_sep>/build.gradle
plugins {
id "com.github.unafraid.gradle.git-repo-plugin" version "2.0.4"
}
apply plugin: "com.github.unafraid.gradle.git-repo-plugin"
apply plugin: "eclipse"
apply plugin: "java"
apply plugin: "maven"
apply plugin: "maven-publish"
apply plugin: "signing"
apply plugin: "findbugs"
sourceCompatibility = JavaVersion.VERSION_1_8
gitPublishConfig {
org = "lordrex34"
repo = "commons-annotation-config"
branch = "releases"
}
group = "com.github.lordrex34.config"
version = "1.0.7"
repositories {
mavenCentral()
}
dependencies {
compile(group: "com.github.lordrex34.reflection", name: "commons-reflection-utils", version: "1.0.2")
testCompile(group: 'junit', name: 'junit', version: '4.12')
testRuntime(group: "org.apache.logging.log4j", name: "log4j-slf4j-impl", version: "2.9.1")
testRuntime(group: "org.apache.logging.log4j", name: "log4j-core", version: "2.9.1")
}
test {
environment "ENVTEST_VALUE", "Environment Test."
}
findbugs {
findbugsTest.enabled = false
}
tasks.withType(FindBugs) {
reports {
xml.enabled false
html.enabled true
}
excludeFilter = file("excludeFilter.xml")
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
tasks.withType(Javadoc) {
options.addStringOption("Xdoclint:none", "-quiet")
}
task javadocJar(type: Jar) {
classifier = "javadoc"
from javadoc
}
task sourcesJar(type: Jar) {
classifier = "sources"
from sourceSets.main.allSource
}
artifacts {
archives javadocJar, sourcesJar
}
signing {
required { gradle.taskGraph.hasTask("uploadArchives") }
sign configurations.archives
}
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
artifact sourcesJar
}
}
repositories {
maven {
url "file://${gitPublishConfig.home}/${gitPublishConfig.org}/${gitPublishConfig.repo}/releases"
}
}
}
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2") {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots") {
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
}
pom.project {
name project.name
packaging "jar"
description "An annotation based configuration API for static fields."
url "https://github.com/lordrex34/commons-annotation-config"
scm {
connection "scm:git:<EMAIL>:lordrex34/commons-annotation-config.git"
developerConnection "scm:git:<EMAIL>:lordrex34/commons-annotation-config.git"
url "<EMAIL>:lordrex34/commons-annotation-config.git"
}
licenses {
license {
name "MIT License"
url "https://opensource.org/licenses/MIT"
distribution "repo"
}
}
developers {
developer {
id "lordrex34"
name "<NAME>"
email "<EMAIL>"
organization "RaveN Network"
organizationUrl "https://github.com/lordrex34"
roles {
role "developer"
}
}
}
}
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = "4.7"
}
def getRepositoryUsername() {
return hasProperty("ossrhUsername") ? ossrhUsername : ""
}
def getRepositoryPassword() {
return hasProperty("ossrhPassword") ? ossrhPassword : ""
}
<file_sep>/src/main/java/com/github/lordrex34/config/model/ConfigFieldInfo.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.model;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Objects;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.lordrex34.config.annotation.ConfigField;
import com.github.lordrex34.config.annotation.ConfigGroupBeginning;
import com.github.lordrex34.config.annotation.ConfigGroupEnding;
import com.github.lordrex34.config.component.ConfigComponents;
import com.github.lordrex34.config.context.ConfigFieldLoadingContext;
import com.github.lordrex34.config.lang.ConfigProperties;
import com.github.lordrex34.config.supplier.IConfigValueSupplier;
import com.github.lordrex34.config.util.ConfigPropertyRegistry;
/**
* @author NB4L1 (original concept)
* @author lord_rex
*/
public final class ConfigFieldInfo
{
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigFieldInfo.class);
/**
* The class that is being scanned.
*/
private final Class<?> _clazz;
/**
* The field that contains {@link ConfigField} annotation.
*/
private final Field _field;
/**
* The configuration field information annotation.
*/
private final ConfigField _configField;
/**
* Group beginning marker annotation.
*/
private final ConfigGroupBeginning _beginningGroup;
/**
* Group ending marker annotation.
*/
private final ConfigGroupEnding _endingGroup;
/**
* Constructs a new information container class for the field.
* @param clazz the class that is being scanned
* @param field the field that contains {@link ConfigField} annotation
*/
public ConfigFieldInfo(Class<?> clazz, Field field)
{
_clazz = clazz;
_field = field;
_configField = _field.getDeclaredAnnotation(ConfigField.class);
_beginningGroup = _field.getDeclaredAnnotation(ConfigGroupBeginning.class);
_endingGroup = _field.getDeclaredAnnotation(ConfigGroupEnding.class);
}
/**
* Gets the field that is being wrapped by this class.
* @return the field
*/
public Field getField()
{
return _field;
}
/**
* Loads and configures the field with its proper values.
* @param fieldLoadingContext the context of the actual loading
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void load(ConfigFieldLoadingContext fieldLoadingContext) throws IllegalArgumentException, IllegalAccessException, InstantiationException
{
// Skip constants.
if (Modifier.isStatic(_field.getModifiers()) && Modifier.isFinal(_field.getModifiers()))
{
return;
}
// Fail inappropriate fields.
if (!Modifier.isStatic(_field.getModifiers()))
{
throw new IllegalArgumentException("Field '" + _field.getName() + "' in class '" + _clazz.getName() + "' is non-static. Please fix it!");
}
// If field is just a comment holder, then do not try to load it.
if (_configField.onlyComment())
{
return;
}
final Path configPath = fieldLoadingContext.getConfigPath();
final ConfigProperties properties = fieldLoadingContext.getProperties();
final Boolean isReloading = fieldLoadingContext.isReloading();
Objects.requireNonNull(configPath, "ConfigPath is null in the loading context!");
Objects.requireNonNull(properties, "Properties is null in the loading context!");
Objects.requireNonNull(isReloading, "isReloading boolean is null in the loading context!");
final String propertyKey = _configField.name();
ConfigPropertyRegistry.add(_clazz.getPackage().getName(), configPath, propertyKey);
if (!_configField.reloadable() && isReloading)
{
LOGGER.debug("Property '{}' retained with its previous value!", propertyKey);
return;
}
// private field support
final boolean wasAccessible = _field.isAccessible(); /*_field.canAccess(null);*/
try
{
if (!wasAccessible)
{
_field.setAccessible(true);
}
final IConfigValueSupplier<?> supplier = ConfigComponents.get(_configField.valueSupplier());
final Object value = supplier.supply(_clazz, _field, _configField, properties, false);
_field.set(null, value);
ConfigComponents.get(_configField.postLoadHook()).load(properties);
}
finally
{
// restore field's visibility to the original
_field.setAccessible(wasAccessible);
}
}
/**
* Prints the necessary field information into a {@link StringBuilder}.
* @param out the {@link StringBuilder} that receives the output
*/
public void print(StringBuilder out) throws IllegalAccessException, InstantiationException
{
if (_beginningGroup != null)
{
out.append("########################################").append(System.lineSeparator());
out.append("## Section BEGIN: ").append(_beginningGroup.name()).append(System.lineSeparator());
for (String line : _beginningGroup.comment())
{
out.append("# ").append(line).append(System.lineSeparator());
}
out.append(System.lineSeparator());
}
for (String line : _configField.comment())
{
out.append("# ").append(line).append(System.lineSeparator());
}
if (!_configField.onlyComment())
{
out.append("# Default: ").append(_configField.value()).append(System.lineSeparator());
if (_field.getType().isEnum())
{
out.append("# Available: ").append(Arrays.stream(_field.getType().getEnumConstants()).map(String::valueOf).collect(Collectors.joining("|"))).append(System.lineSeparator());
}
else if (_field.getType().isArray())
{
final Class<?> fieldComponentType = _field.getType().getComponentType();
if (fieldComponentType.isEnum())
{
@SuppressWarnings("unchecked")
final EnumSet<?> collection = EnumSet.allOf(fieldComponentType.asSubclass(Enum.class));
out.append("# Available: ").append(collection.toString().replace("[", "").replace("]", "").replace(" ", "")).append(System.lineSeparator());
}
}
final IConfigValueSupplier<?> supplier = ConfigComponents.get(_configField.valueSupplier());
final Object value = supplier.supply(_clazz, _field, _configField, new ConfigProperties(), true);
out.append(_configField.name()).append(" = ").append(value).append(System.lineSeparator());
out.append(System.lineSeparator());
}
if (_endingGroup != null)
{
for (String line : _endingGroup.comment())
{
out.append("# ").append(line).append(System.lineSeparator());
}
out.append("## Section END: ").append(_endingGroup.name()).append(System.lineSeparator());
out.append("########################################").append(System.lineSeparator());
out.append(System.lineSeparator());
}
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = (prime * result) + ((_clazz == null) ? 0 : _clazz.hashCode());
result = (prime * result) + ((_field == null) ? 0 : _field.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof ConfigFieldInfo))
{
return false;
}
ConfigFieldInfo other = (ConfigFieldInfo) obj;
if (_clazz == null)
{
if (other._clazz != null)
{
return false;
}
}
else if (!_clazz.equals(other._clazz))
{
return false;
}
if (_field == null)
{
if (other._field != null)
{
return false;
}
}
else if (!_field.equals(other._field))
{
return false;
}
return true;
}
}
<file_sep>/src/main/java/com/github/lordrex34/config/lang/FieldParser.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.lang;
import java.lang.reflect.Array;
/**
* This class's purpose is eventually to parse fields.
* @author NB4L1
*/
public final class FieldParser
{
@SuppressWarnings(
{
"unchecked",
"rawtypes"
})
public static Object get(Class<?> type, String value)
{
if ((type == Boolean.class) || (type == Boolean.TYPE))
{
return FieldParser.getBoolean(value);
}
else if ((type == Long.class) || (type == Long.TYPE))
{
return FieldParser.getLong(value);
}
else if ((type == Integer.class) || (type == Integer.TYPE))
{
return FieldParser.getInteger(value);
}
else if ((type == Short.class) || (type == Short.TYPE))
{
return FieldParser.getShort(value);
}
else if ((type == Byte.class) || (type == Byte.TYPE))
{
return FieldParser.getByte(value);
}
else if ((type == Double.class) || (type == Double.TYPE))
{
return FieldParser.getDouble(value);
}
else if ((type == Float.class) || (type == Float.TYPE))
{
return FieldParser.getFloat(value);
}
else if (type == String.class)
{
return FieldParser.getString(value);
}
else if (type.isEnum())
{
return FieldParser.getEnum((Class<? extends Enum>) type, value);
}
else
{
throw new FieldParserException("Not covered type: " + type + "!");
}
}
public static boolean getBoolean(String value)
{
if (value == null)
{
throw new FieldParserException(Boolean.class);
}
try
{
return Boolean.parseBoolean(value);
}
catch (RuntimeException e)
{
throw new FieldParserException(Boolean.class, value, e);
}
}
public static byte getByte(String value)
{
if (value == null)
{
throw new FieldParserException(Byte.class);
}
try
{
return Byte.decode(value);
}
catch (RuntimeException e)
{
throw new FieldParserException(Byte.class, value, e);
}
}
public static short getShort(String value)
{
if (value == null)
{
throw new FieldParserException(Short.class);
}
try
{
return Short.decode(value);
}
catch (RuntimeException e)
{
throw new FieldParserException(Short.class, value, e);
}
}
public static int getInteger(String value)
{
if (value == null)
{
throw new FieldParserException(Integer.class);
}
try
{
return Integer.decode(value);
}
catch (RuntimeException e)
{
throw new FieldParserException(Integer.class, value, e);
}
}
public static long getLong(String value)
{
if (value == null)
{
throw new FieldParserException(Long.class);
}
try
{
return Long.decode(value);
}
catch (RuntimeException e)
{
throw new FieldParserException(Long.class, value, e);
}
}
public static float getFloat(String value)
{
if (value == null)
{
throw new FieldParserException(Float.class);
}
try
{
return Float.parseFloat(value);
}
catch (RuntimeException e)
{
throw new FieldParserException(Float.class, value, e);
}
}
public static double getDouble(String value)
{
if (value == null)
{
throw new FieldParserException(Double.class);
}
try
{
return Double.parseDouble(value);
}
catch (RuntimeException e)
{
throw new FieldParserException(Double.class, value, e);
}
}
public static String getString(String value)
{
if (value == null)
{
throw new FieldParserException(String.class);
}
return String.valueOf(value);
}
public static <T extends Enum<T>> T getEnum(Class<T> enumClass, String value)
{
if (value == null)
{
throw new FieldParserException(enumClass);
}
try
{
return Enum.valueOf(enumClass, value);
}
catch (RuntimeException e)
{
throw new FieldParserException(enumClass, value, e);
}
}
public static Object getArray(Class<?> componentClass, String value, String regex)
{
final String[] values = value.split(regex);
final Object array = Array.newInstance(componentClass, values.length);
for (int i = 0; i < values.length; i++)
{
Array.set(array, i, get(componentClass, values[i]));
}
return array;
}
public static final class FieldParserException extends RuntimeException
{
private static final long serialVersionUID = 1839324679891385619L;
public FieldParserException()
{
super();
}
public FieldParserException(String message)
{
super(message);
}
public FieldParserException(Class<?> requiredType)
{
super(requiredType + " value required, but not specified!");
}
public FieldParserException(Class<?> requiredType, String value, RuntimeException cause)
{
super(requiredType + " value required, but found: '" + value + "'!", cause);
}
}
}
<file_sep>/src/main/java/com/github/lordrex34/config/util/ConfigPropertyRegistry.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.util;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A reload supporting registry used to check duplicated properties.
* @author lord_rex
*/
public final class ConfigPropertyRegistry
{
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPropertyRegistry.class);
/** Properties registry, that is used for misplaced configuration indication. */
private static final Map<String, Map<Path, Set<String>>> PROPERTIES = new TreeMap<>();
private ConfigPropertyRegistry()
{
// utility class
}
/**
* Registers a configuration property into this manager.
* @param packageName the package where configuration related classes are stored
* @param configFile path of the configuration file
* @param propertyKey the property key to be registered into {@code PROPERTIES_REGISTRY}
*/
public static void add(String packageName, Path configFile, String propertyKey)
{
PROPERTIES.computeIfAbsent(packageName, k -> new HashMap<>()).putIfAbsent(configFile, new TreeSet<>());
PROPERTIES.values().forEach(map ->
{
map.entrySet().forEach(entry ->
{
final Path entryConfigFile = entry.getKey();
final Set<String> entryProperties = entry.getValue();
if (!entryConfigFile.equals(configFile) && entryProperties.contains(propertyKey))
{
LOGGER.warn("Property key '{}' is already defined in config file '{}', so now '{}' overwrites that! Please fix this!", propertyKey, entryConfigFile, configFile);
}
});
});
PROPERTIES.get(packageName).get(configFile).add(propertyKey);
}
/**
* Clears registered properties that are bound to the specific package.
* @param packageName the package where configuration related classes are stored
*/
public static void clear(String packageName)
{
final Map<Path, Set<String>> registry = PROPERTIES.get(packageName);
if (registry != null)
{
registry.clear();
}
}
/**
* Clears all the entries from the registry.
*/
public static void clearAll()
{
PROPERTIES.clear();
}
}
<file_sep>/README.md
[](https://www.codacy.com/app/l2junity/commons-annotation-config?utm_source=github.com&utm_medium=referral&utm_content=lordrex34/commons-annotation-config&utm_campaign=Badge_Grade)
[](https://circleci.com/gh/lordrex34/commons-annotation-config)
<file_sep>/src/test/java/com/github/lordrex34/config/TestConfigOverride.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Before;
import org.junit.Test;
import com.github.lordrex34.config.annotation.ConfigClass;
import com.github.lordrex34.config.annotation.ConfigField;
/**
* @author lord_rex
*/
public class TestConfigOverride extends AbstractConfigTest
{
private static final int OVERRIDDEN_INT = 300;
private static final int OVERRIDDEN_INT_ALT = 333;
private static final String OVERRIDDEN_STRING = "My overridden string. :)";
private static final String OVERRIDDEN_STRING_ALT = "My alternative overridden string. :)";
private boolean _alternative;
@Override
@Before
public void before() throws IOException, IllegalArgumentException, IllegalAccessException, InstantiationException
{
clearAll(ITestConfigMarker.class.getPackage().getName());
_configManager = new ConfigManager(this::overrideInputStream);
_configManager.load(ITestConfigMarker.class.getPackage().getName());
}
private InputStream overrideInputStream()
{
final StringBuffer buffer = new StringBuffer();
buffer.append("TestOverrideInt = ").append(_alternative ? OVERRIDDEN_INT_ALT : OVERRIDDEN_INT).append(System.lineSeparator());
buffer.append("TestOverrideString = ").append(_alternative ? OVERRIDDEN_STRING_ALT : OVERRIDDEN_STRING).append(System.lineSeparator());
return new ByteArrayInputStream(buffer.toString().getBytes());
}
@Test
public void test()
{
assertNotEquals(_configManager.getConfigRegistrySize(), 0);
assertNotEquals(_configManager.getOverriddenProperties().size(), 0);
assertThat(ConfigOverrideTest.TEST_OVERRIDE_INT, is(OVERRIDDEN_INT));
assertThat(ConfigOverrideTest.TEST_OVERRIDE_STRING, is(OVERRIDDEN_STRING));
}
@Test
public void testReload() throws IllegalAccessException, IOException, InstantiationException
{
assertNotEquals(_configManager.getConfigRegistrySize(), 0);
assertNotEquals(_configManager.getOverriddenProperties().size(), 0);
assertThat(ConfigOverrideTest.TEST_OVERRIDE_INT, is(OVERRIDDEN_INT));
assertThat(ConfigOverrideTest.TEST_OVERRIDE_STRING, is(OVERRIDDEN_STRING));
_configManager.reload(ITestConfigMarker.class.getPackage().getName());
assertNotEquals(_configManager.getConfigRegistrySize(), 0);
assertNotEquals(_configManager.getOverriddenProperties().size(), 0);
assertThat(ConfigOverrideTest.TEST_OVERRIDE_INT, is(OVERRIDDEN_INT));
assertThat(ConfigOverrideTest.TEST_OVERRIDE_STRING, is(OVERRIDDEN_STRING));
_alternative = true;
_configManager.reload(ITestConfigMarker.class.getPackage().getName());
assertNotEquals(_configManager.getConfigRegistrySize(), 0);
assertNotEquals(_configManager.getOverriddenProperties().size(), 0);
assertThat(ConfigOverrideTest.TEST_OVERRIDE_INT, is(OVERRIDDEN_INT_ALT));
assertThat(ConfigOverrideTest.TEST_OVERRIDE_STRING, is(OVERRIDDEN_STRING_ALT));
}
@ConfigClass(fileName = "override_test")
public static class ConfigOverrideTest
{
@ConfigField(name = "TestOverrideInt", value = "1")
public static int TEST_OVERRIDE_INT;
@ConfigField(name = "TestOverrideString", value = "These configuration will be overridden.")
public static String TEST_OVERRIDE_STRING;
}
}
<file_sep>/src/main/java/com/github/lordrex34/config/supplier/IConfigValueSupplier.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.supplier;
import java.lang.reflect.Field;
import com.github.lordrex34.config.annotation.ConfigField;
import com.github.lordrex34.config.component.IConfigComponent;
import com.github.lordrex34.config.lang.ConfigProperties;
/**
* Configuration value supplier interface.
* @author lord_rex
* @param <T> the type that is being supplied
*/
@FunctionalInterface
public interface IConfigValueSupplier<T> extends IConfigComponent
{
/**
* Supplies a value to the field that is being configured.
* @param clazz the {@link Class} that is being configured.
* @param field the {@link Field} that is being configured.
* @param configField the {@link ConfigField} that is being processed
* @param properties mixture of normal and overridden properties
* @param generating true if configuration is being generated
* @return the supplied value
* @throws InstantiationException
* @throws IllegalAccessException
*/
T supply(Class<?> clazz, Field field, ConfigField configField, ConfigProperties properties, boolean generating) throws InstantiationException, IllegalAccessException;
}
<file_sep>/src/main/java/com/github/lordrex34/config/component/ConfigComponents.java
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.lordrex34.config.component;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import com.github.lordrex34.config.exception.ConfigComponentLoadingException;
/**
* A registry to avoid creating the same component thousand times.
* @author lord_rex
*/
public final class ConfigComponents
{
/** The registry. */
private static final Map<String, IConfigComponent> COMPONENTS = new HashMap<>();
private ConfigComponents()
{
// utility class
}
/**
* Gets the component from the registry. If it is not present, then it gets registered automatically.
* @param <T> any implementation of {@link IConfigComponent}
* @param componentClass the class contained by the information holder annotation
* @return component
*/
@SuppressWarnings("unchecked")
public static <T extends IConfigComponent> T get(Class<T> componentClass)
{
return (T) COMPONENTS.computeIfAbsent(componentClass.getName(), k ->
{
try
{
final Constructor<T> constructor = componentClass.getDeclaredConstructor();
constructor.setAccessible(true); // constructor.trySetAccessible();
return constructor.newInstance();
}
catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
{
throw new ConfigComponentLoadingException("Component couldn't be loaded, please check!", e);
}
});
}
}
| e2e48206096ddc0dc114374214061b0641d833e7 | [
"Markdown",
"Java",
"Gradle"
] | 14 | Java | lordrex34/commons-annotation-config | 8059edbd7460d1e4279d9529fcfe1d7c5d430986 | f89048a6a02e5dc46123c4677114a7c9e7afcab7 |
refs/heads/master | <repo_name>liyu158163/TouchbarPiano<file_sep>/PianoThing/AppDelegate.swift
//
// AppDelegate.swift
// PianoThing
//
// Created by <NAME> on 1/1/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
<file_sep>/PianoThing/ViewController.swift
//
// ViewController.swift
// PianoThing
//
// Created by <NAME> on 1/1/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Cocoa
import AVFoundation
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
var x = 2;
var sound: AVAudioPlayer?
@IBAction func Play(_ sender: Any) {
x += 1;
blah(x : x);
}
func blah(x : Int){
print(x);
}
@IBAction func PlayT(_ sender: Any) {
//let path = Bundle.main.path(forResource: "/Users/Felix/Music/Bouncepad.wav", ofType:nil)!
let path = "/Users/Felix/Music/Bouncepad.wav"
let url = URL(fileURLWithPath: path)
do {
sound = try AVAudioPlayer(contentsOf: url)
sound?.play()
} catch {
// couldn't load file :(
}
}
@IBAction func PlayT2(_ sender: Any) {
x -= 2;
blah(x : x);
}
}
| 00df6160bb8b64e14c523efe0d3e183370ea871b | [
"Swift"
] | 2 | Swift | liyu158163/TouchbarPiano | 0623884370aa9d744298f23eee1a8afa92be9d8b | 5e0990945dcb2df0a2751159f022f6fb791ef7e8 |
refs/heads/master | <file_sep>Rosalila STG Engine
===================
rosalilastudio.com
github.com/rosalila/stg
Build instructions using Code::Blocks:
1. Install the dependencies
---------------------------
* apt-get install libsdl1.2-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev
* yum install SDL-devel SDL_mixer-devel SDL_image-devel SDL_ttf-devel freeglut-devel
2. Link the libraries
---------------------
In Code::Blocks: "Linker settings" -> "Other linker options"
Add the following:
* lGL
* lglut
* lGLU
* lSDL
* lSDL_image
* lSDL_ttf
* lSDL_mixer
* lsmpeg
4. Clone the Rosalila Engine
----------------------------
* Create a folder named Rosalila/
* Clone the Rosalila Engine (https://github.com/Rosalila/engine) code inside.
5. Tell the compiler to look for the Rosalila Engine
----------------------------------------------------
In Code::Blocks: "Search directories" -> "Compiler"
Add the following:
* Rosalila
6. Add a game assets
--------------------
Download a complete game assets and put it in your root directory.
You should add the following
* chars/
* stages/
* menu/
* misc/
* config.xml
7. Celebrate
------------
Well done, <NAME>.
<file_sep>#ifndef DIALOGUE_H
#define DIALOGUE_H
#include "TinyXml/tinyxml.h"
#include "RosalilaGraphics/RosalilaGraphics.h"
#include "RosalilaSound/RosalilaSound.h"
#include "RosalilaInputs/RosalilaInputs.h"
class Dialogue
{
private:
RosalilaGraphics* painter;
Sound* sonido;
Receiver*receiver;
std::string text;
int iterator;
int duration;
Image*image;
public:
Dialogue(RosalilaGraphics* painter,Sound* sonido,Receiver*receiver,std::string text,Image*image);
std::string getText();
void render(int x,int y);
void logic();
bool destroyFlag();
~Dialogue();
};
#endif
<file_sep>#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
//SDL
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_mixer.h"
#include <string>
#include "RosalilaInputs/RosalilaInputs.h"
#include "RosalilaGraphics/RosalilaGraphics.h"
#include "RosalilaSound/RosalilaSound.h"
#include "STGMenu/STGMenu.h"
#include "RosalilaUtility/RosalilaUtility.h"
#include "STGUtility/STGUtility.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGB);
clearLog();
//Creadas abierto
setReceiver(new Receiver());
RosalilaGraphics*painter=new RosalilaGraphics();
painter->video(painter);
//painter->update.start();
//painter->fps.start();
Sound*sonido = new Sound();
Menu* menu=new Menu(painter,getReceiver(),sonido,(char*)"menu/main_menu.svg");
menu->playMusic();
menu->loopMenu();
return 0;
}
<file_sep>#include "Hitbox.h"
Hitbox::Hitbox(int x,int y,int width,int height,float angle)
{
this->x=x;
this->y=y;
this->width=width;
this->height=height;
this->angle=angle;
}
Hitbox::Hitbox()
{
this->x=0;
this->y=0;
this->width=0;
this->height=0;
this->angle=0;
}
int Hitbox::getX()
{
return x;
}
int Hitbox::getY()
{
return y;
}
int Hitbox::getWidth()
{
return width;
}
int Hitbox::getHeight()
{
return height;
}
float Hitbox::getAngle()
{
return angle;
}
void Hitbox::setX(int x)
{
this->x=x;
}
void Hitbox::setY(int y)
{
this->y=y;
}
void Hitbox::setWidth(int width)
{
this->width=width;
}
void Hitbox::setHeight(int height)
{
this->height=height;
}
void Hitbox::setAngle(float angle)
{
this->angle=angle;
}
void Hitbox::setValues(int x,int y, int width, int height,float angle)
{
this->x=x;
this->y=y;
this->width=width;
this->height=height;
this->angle=angle;
}
bool Hitbox::collides(Hitbox hitbox_param)
{
return hitboxCollision(this->getX(),this->getY(),this->getWidth(),this->getHeight(),this->getAngle(),
hitbox_param.getX(),hitbox_param.getY(),hitbox_param.getWidth(),hitbox_param.getHeight(),hitbox_param.getAngle())
|| hitboxCollision(hitbox_param.getX(),hitbox_param.getY(),hitbox_param.getWidth(),hitbox_param.getHeight(),hitbox_param.getAngle(),
this->getX(),this->getY(),this->getWidth(),this->getHeight(),this->getAngle());
}
bool Hitbox::collides(Hitbox hitbox_param,int hitbox_x,int hitbox_y,int hitbox_angle)
{
hitbox_param.setX(hitbox_param.getX()+hitbox_x);
hitbox_param.setY(hitbox_param.getY()+hitbox_y);
hitbox_param.setAngle(hitbox_param.getAngle()+hitbox_angle);
return hitboxCollision(this->getX(),this->getY(),this->getWidth(),this->getHeight(),this->getAngle(),
hitbox_param.getX(),hitbox_param.getY(),hitbox_param.getWidth(),hitbox_param.getHeight(),hitbox_param.getAngle())
|| hitboxCollision(hitbox_param.getX(),hitbox_param.getY(),hitbox_param.getWidth(),hitbox_param.getHeight(),hitbox_param.getAngle(),
this->getX(),this->getY(),this->getWidth(),this->getHeight(),this->getAngle());
}
Hitbox Hitbox::getPlacedHitbox(Point p,float a)
{
Hitbox hitbox = *this;
Point rotated=rotateAroundPoint(Point(hitbox.getX(),hitbox.getY()),
Point(p.x,p.y),
a+hitbox.getAngle());
hitbox.setX(rotated.x);
hitbox.setY(rotated.y);
hitbox.setAngle(a+hitbox.getAngle());
return hitbox;
}
<file_sep>#ifndef STGUTILITY_H
#define STGUTILITY_H
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;
#define PI 3.14159265
#include "RosalilaInputs/RosalilaInputs.h"
bool getIterateSlowdownFlag();
bool isSlowPressed();
bool isSlowEnabled();
bool isSlowActive();
void slowExtraControl();
void setReceiver(Receiver*receiver_param);
Receiver* getReceiver();
void disableSlow();
void enableSlow();
double getSlowdown();
#endif
<file_sep>#ifndef LAYER_H
#define LAYER_H
#include "TinyXml/tinyxml.h"
#include "RosalilaGraphics/RosalilaGraphics.h"
#include "RosalilaSound/RosalilaSound.h"
#include "RosalilaInputs/RosalilaInputs.h"
class Layer
{
public:
std::vector <Image*> textures;
std::vector <int> textures_size_x;
std::vector <int> textures_size_y;
//External logic
int frame_duration,depth_effect_x,depth_effect_y,alignment_x,alignment_y;
int separation_x;
//Internal logic
int current_frame,time_elapsed;
Layer(vector<Image*> textures,vector <int> textures_size_x,vector <int> textures_size_y,int frame_duration,int depth_effect_x,int depth_effect_y,int alignment_x,int alignment_y,int separation_x)
{
this->textures=textures;
this->textures_size_x=textures_size_x;
this->textures_size_y=textures_size_y;
this->frame_duration=frame_duration;
this->depth_effect_x=depth_effect_x;
this->depth_effect_y=depth_effect_y;
this->current_frame=0;
this->time_elapsed=0;
this->alignment_x=alignment_x;
this->alignment_y=alignment_y;
this->separation_x=separation_x;
}
~Layer()
{
writeLogLine("Deleting layer.");
for(;!textures.empty();)
{
Image*image=textures.back();
textures.pop_back();
delete image;
}
}
};
#endif
<file_sep>#include "STGUtility.h"
int iterate_slowdown_flag=0;
int current_slowdown_iteration=0;
bool slow_enabled=false;
Receiver* receiver = new Receiver();
bool getIterateSlowdownFlag()
{
return !isSlowActive() || iterate_slowdown_flag;
}
void slowExtraControl()
{
//slow extra control
if(isSlowActive())
{
iterate_slowdown_flag=false;
current_slowdown_iteration++;
if(current_slowdown_iteration>=3)
{
current_slowdown_iteration=0;
iterate_slowdown_flag=true;
}
}
}
void setReceiver(Receiver*receiver_param)
{
receiver=receiver;
}
Receiver* getReceiver()
{
return receiver;
}
bool isSlowPressed()
{
return receiver->IsKeyDownn(SDLK_x) || receiver->IsJoyDown(5,0);
}
void disableSlow()
{
slow_enabled=false;
}
void enableSlow()
{
slow_enabled=true;
}
bool isSlowEnabled()
{
return slow_enabled;
}
bool isSlowActive()
{
return isSlowEnabled() && isSlowPressed();
}
double getSlowdown()
{
int slowdown = 1.0;
if(isSlowPressed() && isSlowEnabled())
slowdown = 3.0;
return slowdown;
}
| 6f26f3bfea63412ff871883c6e8ad4308e31fa91 | [
"Markdown",
"C++"
] | 7 | Markdown | Turupawn/STGD | ba8c2bfd84776515f42bdf3ca4bb1323d57bef25 | 6820abfc8a535ef0cc36dee2ad671134c2f93d7a |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 14:36:14 2020
TP1
@author: gtchi
"""
def mesImpots(revenu):
"""montant des impots d'une personne"""
try:
revenu=int(revenu)
taxes={9964:0, 17555:14, 46260:30, 82565:41, -1:45}
tot=0
for tranche in taxes:
if revenu-tranche>0 and revenu>revenu-tranche:
revenu-=tranche
tot+=tranche*(taxes[tranche]/100)
else:
tot+=revenu*(taxes[tranche]/100)
return round(tot,2)
except Exception as error:
print(error)
return 'NaN'
revenu = input('Quels sont vaut revenu ? :')
print('Vous payerez %s € d\'impot cette annee' %(mesImpots(revenu)))
<file_sep>"""
TP1
Author: <NAME>
"""
def isBissextile(year):
""" return true if the year is bissextile."""
return (year%4==0 and year%100!=0) or year%400==0
def numberOfDay(month, year):
""" take two variables (month, year) and return the number of day."""
if not (0<month<=12):
raise Exception("Mois non valide")
if month in [1,3,5,7,8,10,12]:
return 31
elif month in [4,6,9,11]:
return 30
else:
if isBissextile(year):
return 29
else:
return 28
def isValidDate(date):
""" take a "DD/MM/YYYY" return true if it's a valid date."""
try:
[day,month,year] = date.split('/')
day=int(day)
month=int(month)
year=int(year)
return 0<day<=numberOfDay(month, year)
except Exception as error:
print(error)
return False
date = input('entrer une date (JJ/MM/AAAA) : ')
if isValidDate(date):
print('date valide')
else:
print('date non valide')
<file_sep># CS-DEV-1
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 15:06:06 2020
TP1
@author: gtchi
"""
def multiplication(A,B):
"""multiplication de matrice"""
try:
if len(A)!=len(B[0]):
raise Exception("Les matrices ne peuvent pas etre multiplié")
C=[[0 for i in range(len(A[0]))] for i in range(len(B))]
for i in range(len(C)):
for j in range(len(C[0])):
for k in range(len(B)):
C[i][j]+=A[i][k]*B[k][j]
return C
except Exception as error:
print(error)
return 'Error'
def printMatrix(A):
for (i,ligne) in enumerate(A):
for (i,coeff) in enumerate(ligne):
print(coeff,end=' ')
print('\n')
A=[[1,0,1],
[0,1,0],
[1,0,1]]
B=[[5,6,8],
[6,9,6],
[3,7,6]]
print(multiplication(A,B))
printMatrix(multiplication(A,B)) | 2c9b8f0e3eaf7d2a9c709746fa2ff92fc8a5e4e5 | [
"Markdown",
"Python"
] | 4 | Python | Gtchik/CS-DEV-1 | bf54d98c3145a5cb74b65e12f33c1b94ec67663f | c1900b6d69c08e3f2abe012c182197719bfce7dc |
refs/heads/master | <repo_name>Krompi/pi-speedtest<file_sep>/www/index.php
<?php
/**
* Created by PhpStorm.
* User: kromp
* Date: 10.05.2018
* Time: 14:56
*/
include('getData.php');
// PDO-Verbindung
$dbh = new PDO('mysql:host=localhost;dbname=speedtest', "speedtest", "speedy");
$classData = new getData(25);
$kategorie = substr(basename($_SERVER["REQUEST_URI"]), 0, strpos(basename($_SERVER["REQUEST_URI"]), "."));
if ( $kategorie == "day" && strtotime($_GET["date"]) ) {
$start = date("Y-m-d", strtotime($_GET["date"]))." 00:00:00";
$ende = date("Y-m-d", strtotime($_GET["date"]))." 23:59:59";
include('day.html');
} else {
$table = $classData->getDays();
include('index.html');
}
<file_sep>/www/getData.php
<?php
/**
* Created by PhpStorm.
* User: kromp
* Date: 12.05.2018
* Time: 21:40
*/
class getData
{
function __construct($maxDSL)
{
$this->maxDSL = $maxDSL;
$this->colors = [
"rgba( 62, 255, 0, .5 )",
"rgba(232, 227, 11, .6 )",
"rgba(255, 189, 1, .6 )",
"rgba(232, 113, 11, .7 )",
"rgba(255, 40, 12, .8 )"
];
}
public function getRecent() {
$sql = "SELECT * FROM results ORDER BY time DESC LIMIT 1";
$result = $this->fetchData($sql);
return number_format((double)current($result)["down"], 2, ",", "");
}
public function getAverage() {
$sql = "SELECT AVG(down) AS down, time FROM results ORDER BY time DESC LIMIT 1";
$result = $this->fetchData($sql, ["down"]);
return number_format((double)current($result)["down"], 2, ",", "");
}
public function getDays() {
$sql = "SELECT time, AVG(down) as down
FROM results
GROUP BY YEAR(time), MONTH(time), DAY(time)
ORDER BY YEAR(time) DESC, MONTH(time) DESC, DAY(time) DESC";
return $this->fetchData($sql, ["down", "date", "date_Ymd", "percentage", "color"]);
}
public function getLastValues($count = 10) {
$sql = "SELECT * FROM results ORDER BY time DESC LIMIT ".(int)$count;
return $this->fetchData($sql);
}
public function getValues($start, $ende) {
$whereItems = [];
if ( strtotime($start) ) $whereItems[] = "time>='".$start."'";
if ( strtotime($ende) ) $whereItems[] = "time<='".$ende."'";
if ( count($whereItems) > 0 ) {
$where = "WHERE ".implode(" AND ", $whereItems);
}
$sql = "SELECT * FROM results
".$where."";
return $this->fetchData($sql);
}
public function getValuesJson($start, $ende) {
return $this->convertJson($this->getValues($start, $ende));
}
public function getLastValuesJson($count = 10) {
return $this->convertJson($this->getLastValues($count, "ms"));
}
public function fetchData($sql, $fields = ["time_ms", "down"]) {
global $dbh;
$result = [];
$i = 0;
foreach ( $dbh->query( $sql ) as $row ) {
foreach ( $fields as $field ) {
if ( $field == "db" ) $result[$i][$field] = $row["time"];
if ( $field == "time_ms" ) $result[$i][$field] = date("U", strtotime($row["time"]))*1000;
if ( $field == "time_s" ) $result[$i][$field] = date("U", strtotime($row["time"]));
if ( $field == "date" ) $result[$i][$field] = date("d.m.Y", strtotime($row["time"]));
if ( $field == "date_Ymd" ) $result[$i][$field] = date("Y-m-d", strtotime($row["time"]));
if ( $field == "down" ) $result[$i][$field] = number_format((double) $row["down"], 2, ",", "");
if ( $field == "percentage" ) $result[$i][$field] = number_format((double)$row["down"]*100/$this->maxDSL, 2, ",", "");
if ( $field == "color" ) {
if ( $row["down"]/$this->maxDSL >= 0.9 ) {
$result[$i][$field] = $this->colors[0];
} elseif ( $row["down"]/$this->maxDSL >= 0.8 ) {
$result[$i][$field] = $this->colors[1];
} elseif ( $row["down"]/$this->maxDSL >= 0.6 ) {
$result[$i][$field] = $this->colors[2];
} elseif ( $row["down"]/$this->maxDSL >= 0.4 ) {
$result[$i][$field] = $this->colors[3];
} else {
$result[$i][$field] = $this->colors[4];
}
};
}
$i++;
}
return $result;
}
function convertJson($array) {
$result = [];
foreach ( $array as $item ) {
$buffer = [];
foreach ($item as $value) {
$buffer[] = (double) $value;
}
$result[] = $buffer;
}
return json_encode($result);
}
}<file_sep>/bin/backup_pi.sh
#!/bin/bash
# Quelle: https://raspberry.tips/raspberrypi-einsteiger/raspberry-pi-datensicherung-erstellen/
# VARIABLEN - HIER EDITIEREN
BACKUP_PFAD="/misc/nas/image"
BACKUP_ANZAHL="5"
BACKUP_NAME="RaspberryPiBackup"
DIENSTE_START_STOP="service mysql"
# ENDE VARIABLEN
# Stoppe Dienste vor Backup
${DIENSTE_START_STOP} stop
# Backup mit Hilfe von dd erstellen und im angegebenen Pfad speichern
dd if=/dev/mmcblk0 of=${BACKUP_PFAD}/${BACKUP_NAME}-$(date +%Y%m%d-%H%M%S).img bs=1MB
# Starte Dienste nach Backup
${START_SERVICES} start
# Alte Sicherungen die nach X neuen Sicherungen entfernen
pushd ${BACKUP_PFAD}; ls -tr ${BACKUP_PFAD}/${BACKUP_NAME}* | head -n -${BACKUP_ANZAHL} | xargs rm; popd<file_sep>/bin/speedtest-cli-db.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
import subprocess
import datetime
# Daten holen
speedtest = subprocess.Popen(["/usr/bin/speedtest", "--simple"],
stdout=subprocess.PIPE,
universal_newlines=True
)
# Daten verarbeiten
input_lines = []
for line in speedtest.stdout:
input_lines.append(line)
ping_key,ping_val,ping_unit = input_lines[0].split(" ")
download_key,download_val,download_unit = input_lines[1].split(" ")
upload_key,upload_val,upload_unit = input_lines[2].split(" ")
dt_log = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
# Datenbank-Verbindung öffnen
db = MySQLdb.connect(host="localhost",
user="speedtest",
passwd="<PASSWORD>",
db="speedtest")
cur = db.cursor()
# Daten einfügen
cur.execute("INSERT INTO results (time, ping, down, up) VALUES (%s, %s, %s, %s)", (dt_log, ping_val, download_val, upload_val))
# Datenbank-Verbindung schließen
cur.close()
db.commit()
db.close()
<file_sep>/graph.php
<?php
/**
* Created by PhpStorm.
* User: kromp
* Date: 07.05.2018
* Time: 16:48
*/
// PDO-Verbindung
$dbh = new PDO('mysql:host=localhost;dbname=speedtest', "speedtest", "speedy");
// Variablen setzen
$results = [];
$parameter = explode("-", substr(basename($_SERVER["REQUEST_URI"]), 0, strpos(basename($_SERVER["REQUEST_URI"]), ".")) );
$parPrecision = $parameter[1];
$parPeriod = $parameter[2];
$sqlGroup = "";
$sqlWhere = "";
$sqlOrder = "";
if ( $parPrecision == "tag" ) {
$sql = "SELECT YEAR(time) AS year, MONTH(time) AS month, DAY(time) AS day, AVG(down) AS down_avg, MIN(down) AS down_min, MAX(down) AS down_max
FROM results";
$sqlGroup = " GROUP BY YEAR(time), MONTH(time), DAY(time)";
$sqlOrder = " ORDER BY year, month, day";
} elseif ( $parPrecision == "stunde" ) {
$sql = "SELECT YEAR(time) AS year, MONTH(time) AS month, DAY(time) AS day, HOUR(time) AS hour, AVG(down) AS down_avg, MIN(down) AS down_min, MAX(down) AS down_max
FROM results ";
$sqlGroup = " GROUP BY YEAR(time), MONTH(time), DAY(time), HOUR(time)";
$sqlOrder = " ORDER BY year, month, day, hour";
}
if ( $parPeriod == "heute" ) {
$sqlWhere .= " WHERE YEAR(time)='".date("Y")."' AND MONTH(time)='".date("m")."' AND DAY(time)='".date("d")."'";
}
$sql = $sql.$sqlWhere.$sqlGroup.$sqlOrder;
foreach ( $dbh->query( $sql ) as $row ) {
// Variablen setzen
$buffer = [];
$xaxis = "Date.UTC(".$row["year"].", ".$row["month"].", ".$row["day"].", ".$row["hour"].")";
// Durchschnitt
$buffer["average"] = [
$xaxis,
number_format($row["down_avg"], 2)
];
$results["averages"][] = "[".implode(",", $buffer["average"])."]";
// Bereich
$buffer["ranges"] = [
$xaxis,
number_format($row["down_min"], 2),
number_format($row["down_max"], 2)
];
$results["ranges"][] = "[".implode(",", $buffer["ranges"])."]";
}
// Graph-Variablen setzen
$ranges = implode(",\n", $results["ranges"]);
$averages = implode(",\n", $results["averages"]);<file_sep>/sql/examples.sql
SELECT
YEAR(time), MONTH(time), DAY(time),
AVG(down) AS avg_down, MAX(down) AS max_down, MIN(down) AS min_down
FROM results GROUP BY YEAR(time), MONTH(time), DAY(time);
<file_sep>/README.md
# pi-speedtest
## Graph-Beispiele:
* https://www.highcharts.com/demo/arearange-line
* https://www.highcharts.com/demo/dynamic-master-detail
* (Klick im Graph: http://jsfiddle.net/FhF3A/3/)
## Kalender-Darstellungen
* http://freefrontend.com/css-calendars/
* https://codepen.io/AlxCrmr/pen/ybgwQG
* https://codepen.io/xmark/pen/WQaXdv
* https://1stwebdesigner.com/calendar-ui-layout-css/
* https://codepen.io/ciprianionescu/pen/JYPwwL
| 13b98ee7366dd35b3e8c761a30066ed55aca384c | [
"SQL",
"Markdown",
"Python",
"PHP",
"Shell"
] | 7 | PHP | Krompi/pi-speedtest | 2d1c5af5b3f38c58dff4d686b01d3e942b9192da | d08b638778eb47798d3059d9eca5e084183cf076 |
refs/heads/master | <repo_name>herodesigner/weather-site<file_sep>/main.js
const api = {
key: '<KEY>',
baseurl: 'http://api.openweathermap.org/data/2.5/',
}
const searchbox = document.querySelector('.search-box');
const button = document.querySelector('.btn');
const error = document.querySelector('.error');
button.addEventListener('click', ()=> {
const location = searchbox.value;
fetch(`${api.baseurl}weather?q=${location}&units=metric&APPID=${api.key}`)
.then(weather=>{
return weather.json();
})
.then(displayData)
.catch (()=> {
error.textContent = "Please enter a valid city"
});
error.textContent = '';
})
function displayData (weather) {
const city = document.querySelector('.city');
city.innerText = `${weather.name}, ${weather.sys.country}`;
const today = new Date();
const date = document.querySelector('.date');
date.innerHTML = dateFunction(today);
const temp = document.querySelector('.temp');
temp.innerHTML = `${Math.round(weather.main.temp)}` + '˚C'
const weatherIcon = document.querySelector('.icon');
weatherIcon.src = `https://openweathermap.org/img/wn/${weather.weather[0]["icon"]}@2x.png`;
const description = document.querySelector('.description');
description.innerHTML = `${weather.weather[0].main}`;
const tempRange = document.querySelector('.hi-low');
tempRange.innerHTML = `${Math.round(weather.main.temp_min)}˚C / ${Math.round(weather.main.temp_max)}˚C`;
// document.body.style.backgroundImage = `https://source.unsplash.com/1600x900/?' + ${weather.name} + '`
}
function dateFunction (today) {
let months = ['Jan','Feb','Mar','Apr','May','June','July',
'Aug','Sep','Oct','Nov','Dec'];
let days = ['Sunday','Monday','Tuesday','Wednesday','Thursday',
'Friday','Saturday',];
let day = days[today.getDay()];
let date = today.getDate();
let month = months[today.getMonth()];
let year = today.getFullYear();
return `${day}, ${date} ${month} ${year}`
} | 811773d2decf76119f0aff1b3d892d0f2b0d626c | [
"JavaScript"
] | 1 | JavaScript | herodesigner/weather-site | 5fa3a267d37c89d66b497b216649aa25bd37de14 | c017580f6557c0390e085ba25d27698ecc7fe6d0 |
refs/heads/master | <file_sep># Plant-Disease-Identification
Graduation Project for identifying plant diseases
Run the notebook Plant_Disease_Identification.ipynb for a demo of the project. Everything was done in Google Colab.
<file_sep>import os
import numpy as np
import pprint
import cv2 as cv
import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
from flask import Flask
import json
from flask_restful import reqparse, abort, Api, Resource
from flaskext.mysql import MySQL
import urllib
dicty = {0:'blight' ,
1:'greening',
2: 'healthy',
3:'measles',
4: 'mildew',
5: 'mold',
6: 'rot',
7:'rust',
8:'scorch',
9:'spot',
10:'virus'}
app = Flask(__name__)
api = Api(app)
mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'plantid_user'
app.config['MYSQL_DATABASE_PASSWORD'] = '<PASSWORD>'
app.config['MYSQL_DATABASE_DB'] = 'plantid'
app.config['MYSQL_DATABASE_HOST'] = '10.36.48.64'
mysql.init_app(app)
conn = mysql.connect()
cursor = conn.cursor()
#Error handling
def CheckExtension(s):
index = s.rfind('.')
return s[index+1:]
class check(Resource):
def get(self):
cursor.execute("SELECT id,path_web FROM disease_job WHERE status=0")
all_data = cursor.fetchall()
if len(all_data) > 0:
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = tf.keras.models.model_from_json(loaded_model_json)
model.load_weights("weights.h5")
for data in all_data:
path = urllib.request.urlopen( "http://plantid.sabanciuniv.edu/"+data[1])
ext = CheckExtension(data[1])
try:
img = plt.imread(path,format=ext)#format check, error handling
finally:
return json.dumps({"Image could not be read!"}),404
img = np.resize(img,(256,256,3))
img = np.expand_dims(img,axis=0)
pred = np.argmax(model.predict(img))
print(dicty[pred])
query = "UPDATE disease_job SET result='"+dicty[pred]+"',status=2 WHERE id="+str(data[0])
print(query)
cursor.execute(query)
return json.dumps({"Operation successfully completed!"}),200
else:
return json.dumps({"No data is fetched!"}),400
api.add_resource(check,"/identify_disease")
app.run(debug=False)
<file_sep>import os
import numpy as np
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.vis_utils import plot_model
'''
from google.colab import drive
drive.mount('/content/drive')
#Github access
!pip install -q xlrd
!git clone https://github.com/keremyldrr/Plant-Disease-Identification.git
# Files from the cloned git repository.
!ls Plant-Disease-Identification/12CLASS/train
!ls Plant-Disease-Identification/12CLASS/test
'''
#Train Data Generator with Data Augmentation(Flips, Normalizations, etc.), Train/Validation = 0.8/0.2
train_gen = ImageDataGenerator(featurewise_center=True, samplewise_center=True,
featurewise_std_normalization=True,
samplewise_std_normalization=True,
zca_whitening=False, zca_epsilon=1e-06,
rotation_range=0,
width_shift_range=0.0,
height_shift_range=0.0,
brightness_range=None,
shear_range=0.0,
zoom_range=0.0, channel_shift_range=0.0, fill_mode='nearest', cval=0.0, horizontal_flip=True,
vertical_flip=True, rescale=None, preprocessing_function=None, data_format=None,validation_split=None, dtype=None)
#Preprocessing function
#random_rotation(x, 45)
#Train Data Generator with Data Augmentation(Flips, Normalizations, etc.), Train/Validation = 0.8/0.2
validation_gen = ImageDataGenerator(featurewise_center=True, samplewise_center=True,
featurewise_std_normalization=True,
samplewise_std_normalization=True,
zca_whitening=False, zca_epsilon=1e-06,
rotation_range=0,
width_shift_range=0.0,
height_shift_range=0.0,
brightness_range=None,
shear_range=0.0,
zoom_range=0.0, channel_shift_range=0.0, fill_mode='nearest', cval=0.0, horizontal_flip=True,
vertical_flip=True, rescale=None, preprocessing_function=None, data_format=None,validation_split=None, dtype=None)
#Preprocessing function
#random_rotation(x, 45)
#Test Data Generator
test_gen = ImageDataGenerator(featurewise_center=True, samplewise_center=True,
featurewise_std_normalization=True,
samplewise_std_normalization=True,
zca_whitening=False, zca_epsilon=1e-06,
rotation_range=0,
width_shift_range=0.0,
height_shift_range=0.0,
brightness_range=None,
shear_range=0.0,
zoom_range=0.0, channel_shift_range=0.0, fill_mode='nearest', cval=0.0, horizontal_flip=True,
vertical_flip=True, rescale=None, preprocessing_function=None, data_format=None,validation_split=None, dtype=None)
"""#12 CLASS DATA"""
#For 12 class
image_data = train_gen.flow_from_directory("/cta/users/barissevilmis/workfolder/Plant-Disease-Identification/train", shuffle = True, target_size = (224, 224), class_mode = 'binary')
#print(image_data)
validation_data = validation_gen.flow_from_directory("/cta/users/barissevilmis/workfolder/Plant-Disease-Identification/validation", shuffle = True, target_size = (224, 224), class_mode = 'binary')
#print(validation_data)
test_data = test_gen.flow_from_directory("/cta/users/barissevilmis/workfolder/Plant-Disease-Identification/test", shuffle = False, target_size = (224, 224), class_mode = 'binary')
#print(test_data)
"""#12 CLASS ONLY LAST THREE LAYERS TRAINABLE"""
#For 12 classes -> training_12_2.cpkt
#Load pretrained(imagenet) VGG-16 model, leave out FC and Softmax layers
vgg16 = tf.keras.applications.VGG16(include_top = False, weights = 'imagenet', pooling = 'max')
#Only make last three layer trainable
for i in range(17):
vgg16.layers[i].trainable = False
model = tf.keras.models.Sequential()
model.add(vgg16)
model.add(tf.keras.layers.Dense(12 ,activation = 'softmax'))
#See the model summary
#vgg16.summary()
model.summary()
#12 Classes: CASE 2
checkpoint_path = "/cta/users/barissevilmis/workfolder/weights"
checkpoint_dir = os.path.dirname(checkpoint_path)
# Create checkpoint callback
cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,
monitor='val_loss',
save_weights_only=True,
save_best_only=True,
verbose = 1)
csv_logger = tf.keras.callbacks.CSVLogger("training.log")
"""#COMPILE THE MODEL"""
model.compile(
optimizer=tf.train.AdamOptimizer(learning_rate=1e-3, ),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['acc']
)
#Load pretrained weights
#model.load_weights(checkpoint_path)
print("Training has started!!")
#SKIP this block, if you only want to evaluate the results
#Fit generator
model.fit_generator(
image_data,
epochs=10,
steps_per_epoch=200,
validation_data = validation_data,
callbacks = [cp_callback, csv_logger],
verbose = 1
)
print("Training has ended!!")
"""#TEST"""
#Evaluate performance over test data
model.load_weights(checkpoint_path)
loss,acc = model.evaluate_generator(test_data)
print("Loss(Test Data)", loss)
print("Accuracy(Test Data)", acc)
#See class probabilities
pred = model.predict_generator(test_data)
print("Test has ended!!!")
| 0015d6af5cc2fd0ee51dfb61090bb588e6935968 | [
"Markdown",
"Python"
] | 3 | Markdown | keremyldrr/Plant-Disease-Identification | 562cb3de97e730b0b280e82a04f5c72334a19811 | f5d91ba01846d83968913a9bc7227538d01bb81c |
refs/heads/main | <file_sep>
CREATE TABLE ae_dt1(
docid bigint(20) NOT NULL,
field1 varchar(255) DEFAULT NULL,
field10 varchar(255) DEFAULT NULL,
field11 varchar(255) DEFAULT NULL,
field12 varchar(255) DEFAULT NULL,
field13 varchar(255) DEFAULT NULL,
field2 varchar(255) DEFAULT NULL,
field3 datetime DEFAULT NULL,
field4 varchar(255) DEFAULT NULL,
field5 varchar(255) DEFAULT NULL,
field6 varchar(255) DEFAULT NULL,
field7 varchar(255) DEFAULT NULL,
field8 varchar(255) DEFAULT NULL,
field9 varchar(255) DEFAULT NULL,
iscom bigint(20) DEFAULT NULL,
numobjects bigint(20) DEFAULT NULL,
process_dt datetime DEFAULT NULL,
receipt_dt datetime DEFAULT NULL,
PRIMARY KEY ( docid )
);
--ENGINE=InnoDB DEFAULT CHARSET=latin1;
<file_sep>package com.org.queue.app.dto;
import lombok.Builder;
import lombok.Getter;
import java.util.Date;
@Getter
@Builder
public class IncompleteQueueDto {
int docId;
String userName;
String sentTo;
Date received;
Date processed;
String faxId;
String lot;
String loanId;
}
<file_sep>package com.org.queue.app;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class QueuedApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>package com.org.queue.app.repository;
import com.org.queue.app.model.AEData;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public interface AEDataRepository extends CrudRepository<AEData,Integer> {
public List<AEData> findAll();
/*
SELECT FIELD4,FIELD8,receipt_dt,process_dt,docid,field6,field7, field1 from ae_dt1
Where receipt_dt> SYSDATE()-30 and (( field4 ='FAXIN' and FIELD8 ='OPERATIONSSUPPORTFAX')
OR (field4 = 'CUST CORR' and field8 = 'CUST CORRESPONDENCE')) order by docid;
*/
@Query(
value = " select * from ae_dt1 " +
" where receipt_dt> sysdate - 30 and (( field4 ='FAXIN' and FIELD8 ='OPERATIONSSUPPORTFAX') " +
" OR (field4 = 'CUST CORR' and field8 = 'CUST CORRESPONDENCE')) order by docid",
nativeQuery = true
)
public List<AEData> getIncompleteQueue() ;
/* @Query("select a from Article a where a.creationDateTime <= :creationDateTime")
List<AppExtender> findAllWithCreationDateTimeBefore(
@Param("creationDateTime") Date creationDateTime);*/
}
<file_sep>package com.org.queue.app.exception;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
//@RestController
public class MyErrorController implements ErrorController {
private static final String PATH = "/error";
// @RequestMapping(value = PATH )
public String myerror(HttpServletRequest request ) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
Integer statusCode = Integer.valueOf(status.toString());
/* if(statusCode == HttpStatus.NOT_FOUND.value()) {
return "error-404";
}
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "error-500";
}*/
}
return "Something went wrong error:"+status;
//return "<center><h1>Something went wrong</h1></center>";
}
@Override
public String getErrorPath() {
return PATH;
}
}<file_sep>package com.org.queue.app;
import com.org.queue.app.model.AEData;
import com.org.queue.app.repository.AEDataRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@DataJpaTest
public class JpaDataTest {
@Autowired
private AEDataRepository repository;
@Test
public void whenFindByPublicationDate_thenArticles1And2Returned() {
// List<AppExtender> result = repository.findAllWithCreationDateTimeBefore(
// new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00"));
Optional<AEData> result = repository.findById(1);
assertTrue(result.isPresent());
assertEquals(1, result.get().getId());
assertTrue("",result.stream()
.map(AEData::getId)
.allMatch(id -> Arrays.asList(1).contains(id)));
}
@Test
public void whenQueryIncomplete_thenCorrectDataReturned() {
// List<AppExtender> result = repository.findAllWithCreationDateTimeBefore(
// new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00"));
List<AEData> result = repository.getIncompleteQueue();
assertFalse(result.isEmpty());
}
@Test
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
List<String> list = Arrays.asList("A","B","C","D");
Optional<String> result = list.stream().findAny();
assertTrue(result.isPresent());
//assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
}
}
<file_sep>package com.org.queue.app.service;
import com.org.queue.app.dto.IncompleteQueueDto;
import com.org.queue.app.model.AEData;
import com.org.queue.app.repository.AEDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class AEDataService {
@Autowired
private AEDataRepository repository;
public List<IncompleteQueueDto> incompleteQueue(){
// List<AEData> aeDataList = repository.findAll();
List<AEData> aeDataList = repository.getIncompleteQueue();
return aeDataList.stream().map(aeData->IncompleteQueueDto.builder()
.docId(aeData.getId())
.userName(aeData.getField4())
.sentTo(aeData.getField8())
.received(aeData.getReceiptDt())
.processed(aeData.getProcessDt())
.faxId(aeData.getField6())
.lot(aeData.getField7())
.loanId(aeData.getField1())
.build()).collect(Collectors.toList());
}
}
<file_sep>
insert into ae_dt1 (
docid,
field1,
field2,
field3,
field4,
field5,
field6,
field7,
field8,
field9,
field10,
field11,
field12,
field13,
iscom,
numobjects ,
process_dt,
receipt_dt
) values (
14542844,
2,
'REPOSSESSION',
'2021-06-10',
'ECOBEL',
null,
null,
null,
null,
null,
null,
null,
null,
4542845,
2,
0,
'2021-07-11',
'2021-08-31'
);
insert into ae_dt1 (
docid,
field1,
field2,
field3,
field4,
field5,
field6,
field7,
field8,
field9,
field10,
field11,
field12,
field13,
iscom,
numobjects ,
process_dt,
receipt_dt
) values (
14542845,
2,
'REPOSSESSION',
'2021-06-10',
'ECOBEL',
null,
null,
null,
null,
null,
null,
null,
null,
4542845,
2,
0,
'2021-07-11',
'2021-07-10'
);
insert into ae_dt1 (
docid,
field1,
field2,
field3,
field4,
field5,
field6,
field7,
field8,
field9,
field10,
field11,
field12,
field13,
iscom,
numobjects ,
process_dt,
receipt_dt
) values (
14542846,
3,
'REPOSSESSION',
'2021-06-10',
'FAXIN',
null,
null,
null,
'OPERATIONSSUPPORTFAX',
null,
null,
null,
null,
4542845,
2,
0,
'2021-07-11',
'2021-08-31'
);
insert into ae_dt1 (
docid,
field1,
field2,
field3,
field4,
field5,
field6,
field7,
field8,
field9,
field10,
field11,
field12,
field13,
iscom,
numobjects ,
process_dt,
receipt_dt
) values (
14542850,
4,
'REPOSSESSION',
'2021-06-10',
'<NAME>',
null,
null,
null,
'CUST CORRESPONDENCE',
null,
null,
null,
null,
4542845,
2,
0,
'2021-07-11',
'2021-08-31'
);
insert into ae_dt1 (
docid,
field1,
field2,
field3,
field4,
field5,
field6,
field7,
field8,
field9,
field10,
field11,
field12,
field13,
iscom,
numobjects ,
process_dt,
receipt_dt
) values (
14542849,
4,
'REPOSSESSION',
'2021-06-10',
'<NAME>',
null,
null,
null,
'CUST CORRESPONDENCE',
null,
null,
null,
null,
4542845,
2,
0,
'2021-07-11',
'2021-08-31'
);
insert into ae_dt1 (
docid,
field1,
field2,
field3,
field4,
field5,
field6,
field7,
field8,
field9,
field10,
field11,
field12,
field13,
iscom,
numobjects ,
process_dt,
receipt_dt
) values (
14542852,
4,
'REPOSSESSION',
'2021-06-10',
'<NAME>',
null,
null,
null,
'CUST CORRESPONDENCE',
null,
null,
null,
null,
4542845,
2,
0,
'2021-07-11',
'2021-08-31'
); | 17b0170cb15d7f769f602ff048c2850bb956fa6b | [
"Java",
"SQL"
] | 8 | SQL | hardip-s/queues | 73e7338ff2e8fcc35fbb13be6a48aeecd7ada593 | fb45b19cfe5814ab5ec6ed08db245a9ad6077219 |
refs/heads/master | <file_sep>Ext.define('ChatApp.store.UsersLocal', {
extend: 'Ext.data.Store',
requires:[
'Ext.data.proxy.LocalStorage',
'ChatApp.model.User'
],
config: {
model: 'ChatApp.model.User',
storeId: 'usersLocalStore',
autoLoad: true,
proxy: {
type: "localstorage",
id: 'storage_users'
}
}
});
<file_sep>Ext.define('ChatApp.model.Message', {
extend: 'Ext.data.Model',
config: {
idProperty: 'id',
fields: [
{ name: 'id', type: 'auto' },
{ name: 'content', type: 'string' },
{ name: 'sender', type: 'string' },
{ name: 'receiver', type: 'string' },
{ name: 'isSeen', type: 'boolean', defaultValue: false },
{
name: 'timestamp',
type: 'date',
convert: function(value, record) {
if (value) {
return Date.parse(value);
} else {
return new Date();
}
}
}
]
}
});
<file_sep>Ext.define('ChatApp.controller.configuration.User', {
extend: 'Ext.app.Controller',
config: {
refs: {
mainTabPanel: 'mainTabPanel',
configurationUserForm: 'configurationUserForm',
saveButton: '#saveButton'
},
control: {
saveButton: {
tap: 'onSaveTap',
}
}
},
/*
* Controller startup code
*/
launch: function() {
this.callParent();
// Get local users store, find current user
var usersStore = Ext.data.StoreManager.lookup('usersLocalStore');
usersStore.clearFilter();
var userRecord = usersStore.findRecord('isCurrentUser', true);
usersStore.filter('isCurrentUser', false);
if (userRecord) {
// Copy user info to form
var form = this.getConfigurationUserForm().setRecord(userRecord);
// Make sure the server still knows about this username
var curentName = userRecord.get('name');
if (curentName && curentName !== '') {
this.setUserName(curentName, false);
}
}
},
/*
* Event listeners
*/
onSaveTap: function(sender) {
var formValues = this.getConfigurationUserForm().getValues();
if (formValues['name'] !== '') {
this.setUserName(formValues['name'], true);
}
},
/*
* Creates username on server, or not... who cares
*/
setUserName: function(name, showAlert) {
// Clean username
name = name.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
name = name.substring(0, 32);
// Clear old isCurrentUser values on all users
var usersStore = Ext.data.StoreManager.lookup('usersLocalStore');
Ext.each(usersStore.getData().all, function(foundUser) {
foundUser.set('isCurrentUser', false);
});
// Save name in global variable
ChatApp.app.currentUser = name;
Ext.Ajax.request({
url: 'http://luminisjschallenge.herokuapp.com/',
method: 'POST',
params: {
name: name
},
scope: this,
success: function(response) {
// Make user happy
if (showAlert) {
Ext.Msg.alert('Success!', 'The username was created on the server and will be used in future chats', Ext.emptyFn);
}
this.startApplication();
},
failure: function(response) {
// Tell user we're gonna try
if (showAlert) {
Ext.Msg.alert('Uhh?', 'The username seems to exist, but we\'ll claim it for future chats', Ext.emptyFn);
}
this.startApplication();
}
});
},
startApplication: function() {
ChatApp.app.startPolling();
this.getMainTabPanel().setActiveItem(1);
}
});<file_sep>Ext.define('ChatApp.store.MessagesLocal', {
extend: 'Ext.data.Store',
requires:[
'Ext.data.proxy.LocalStorage',
'ChatApp.model.Message'
],
config: {
model: 'ChatApp.model.Message',
storeId: 'messagesLocalStore',
autoLoad: true,
proxy: {
type: "localstorage",
id: 'storage_messages'
},
sorters: [
{
property: 'timestamp',
direction: 'ASC'
}
]
}
});
<file_sep>Ext.define('ChatApp.view.contacts.List', {
extend: 'Ext.List',
xtype: 'contacstList',
requires:[
'Ext.dataview.List',
'ChatApp.model.User',
'ChatApp.store.UsersLocal'
],
config: {
title: 'All contacts',
scrollToTopOnRefresh: false,
itemTpl: '<div class="contact">{name}</div>',
listeners: {
painted: function(component, eOpts) {
this.reloadData();
var deselectTask = Ext.create('Ext.util.DelayedTask', function() {
this.deselectAll();
}, this);
deselectTask.delay(500);
}
}
},
reloadData: function() {
// Get the global users store
var usersStore = Ext.data.StoreManager.lookup('usersLocalStore');
// Set up a new filter that shows only remote users, not the current user
usersStore.clearFilter();
usersStore.filter('isCurrentUser', false);
this.setStore(usersStore);
}
});
<file_sep>Ext.define('ChatApp.view.configuration.User', {
extend: 'Ext.form.Panel',
xtype: 'configurationUserForm',
requires: [
'Ext.form.FieldSet',
'Ext.field.Email',
],
config: {
title: 'User info',
items: [
{
xtype: 'fieldset',
title: 'Personal Info',
instructions: 'Please enter your information above.',
defaults: {
labelWidth: '35%'
},
items: [
{
xtype : 'textfield',
name : 'name',
label : 'Name',
placeHolder : '<NAME>',
autoCapitalize: true,
required : true,
clearIcon : true
}
]
},
{
xtype: 'button',
id: 'saveButton',
text: 'Set user'
}
]
}
});
<file_sep>Ext.define('ChatApp.view.chats.List', {
extend: 'Ext.List',
xtype: 'chatsList',
requires:[
'Ext.dataview.List',
'ChatApp.model.User',
'ChatApp.store.UsersLocal',
'ChatApp.store.MessagesLocal'
],
config: {
title: 'Chats',
scrollToTopOnRefresh: false,
itemTpl: '<div class="contact">{name}</div><div class="contactcount">{newmessages}</div>',
listeners: {
painted: function(component, eOpts) {
this.reloadData();
var deselectTask = Ext.create('Ext.util.DelayedTask', function() {
this.deselectAll();
}, this);
deselectTask.delay(500);
}
}
},
reloadData: function() {
var usersStore = Ext.data.StoreManager.lookup('usersLocalStore');
var messagesStore = Ext.data.StoreManager.lookup('messagesLocalStore');
usersStore.clearFilter();
messagesStore.clearFilter();
// Set up a filter that shows only users that have messages to the current user or from the current user
usersStore.filter(Ext.create('Ext.util.Filter', {
filterFn: function(record) {
var matchedIndex = messagesStore.findBy(function(msgRecord, id) {
return ((msgRecord.get('sender') == ChatApp.app.currentUser && msgRecord.get('receiver') == record.get('name')) || (msgRecord.get('sender') == record.get('name') && msgRecord.get('receiver') == ChatApp.app.currentUser));
})
return matchedIndex >= 0;
}
}));
this.setStore(usersStore);
}
});<file_sep>Ext.define('ChatApp.controller.contacts.List', {
extend: 'Ext.app.Controller',
config: {
refs: {
mainTabPanel: 'mainTabPanel',
contactsList: 'contacstList',
chatsMainNavigation: 'chatsMainNavigation'
},
control: {
contactsList: {
itemtap: 'onListItemTap'
}
}
},
/*
* Event listeners
*/
onListItemTap: function(dataview, index, target, record, e, options) {
// Set current chat user
ChatApp.app.currentChatWith = record.get('name');
// Pop all old chats
this.getChatsMainNavigation().pop(this.getChatsMainNavigation().getItems().length);
// Switch to the chat tab
this.getMainTabPanel().setActiveItem(2);
// Reset the navigation stack before pushing a new view
this.getChatsMainNavigation().push({
xtype: 'chatWindow'
});
}
});<file_sep>Ext.define('ChatApp.view.chats.ChatsMain', {
extend: 'Ext.NavigationView',
xtype: 'chatsMainNavigation',
config: {
tab: {
id: 'chatsTab',
title: 'Chats',
iconCls: 'iconChats',
action: 'chatsTab',
iconCls: 'icnChat'
},
items: [
{
xtype: 'chatsList',
}
]
}
});
<file_sep>Ext.define('ChatApp.view.chats.ChatWindow', {
extend: 'Ext.Container',
xtype: 'chatWindow',
// Set by the parent window, should contain User model
currentStore: null,
requires:[
'Ext.dataview.List',
'ChatApp.store.MessagesLocal'
],
config: {
title: 'Chat',
layout: 'vbox',
items: [
{
xtype: 'list',
id: 'chatMessagesList',
flex : 1,
disableSelection: true,
scrollToTopOnRefresh: false,
itemTpl: new Ext.XTemplate(
'<tpl if="sender !== ChatApp.app.currentUser">',
' <img class="odd" src="http://www.gravatar.com/avatar/{gravatar}?s=28&d=mm" />',
' <p class="triangle-right left"><span class="nickname">{sender}:</span> {content}</p>',
'</tpl>',
'<tpl if="sender === ChatApp.app.currentUser">',
' <p class="triangle-right right"><span class="nickname">{sender}:</span> {content}</p>',
' <img class="even" src="http://www.gravatar.com/avatar/{gravatar}?s=28&d=mm" />',
'</tpl>'
),
listeners: {
painted: function(component, options) {
this.getParent().reloadData();
}
}
},
{
xtype: 'toolbar',
docked: 'bottom',
ui: 'light',
layout: 'hbox',
items: [
{
xtype: 'textfield',
id: 'chatInputField',
placeHolder: '',
flex: 1
}
]
}
]
},
initialize: function() {
this.callParent(arguments);
// Set window title
this.setTitle('Chat - ' + ChatApp.app.currentChatWith);
// Listen for new message events events so we can scroll down
Ext.Viewport.on({
scope: this,
newMessageEvent: function() {
this.getComponent('chatMessagesList').getScrollable().getScroller().scrollToEnd();
}
});
},
destroy: function() {
// No current chat user anymore
ChatApp.app.currentChatWith = null;
this.callParent(arguments);
},
reloadData: function() {
// Get store
this.currentStore = Ext.data.StoreManager.lookup('messagesLocalStore');
this.currentStore.clearFilter();
this.currentStore.filter(Ext.create('Ext.util.Filter', {
scope: this,
filterFn: function(record) {
return (record.get('sender') == ChatApp.app.currentUser && record.get('receiver') == ChatApp.app.currentChatWith) || (record.get('sender') == ChatApp.app.currentChatWith && record.get('receiver') == ChatApp.app.currentUser);
}
}));
this.getComponent('chatMessagesList').setStore(this.currentStore);
// Set all messages to 'seen'
this.currentStore.each(function(message) {
message.set('isSeen', true);
})
// Scroll down
var scrollTask = Ext.create('Ext.util.DelayedTask', function() {
this.getComponent('chatMessagesList').getScrollable().getScroller().scrollToEnd();
}, this);
scrollTask.delay(250);
}
}); | 9fdf47279f5b7dddc63253c8a9c4e65c88236274 | [
"JavaScript"
] | 10 | JavaScript | sailei1/ChatApp | 0be457eee8546401a3473238c99274b83ede9302 | 5385aef8d25943fcae39b5ffefcc2c2cd3e8a79b |
refs/heads/master | <file_sep><?php
require_once('../../php/connect.php');
$sql="insert into platos values('','".$_POST['descripcion']."', ".$_POST['cantidad'].", '".$_POST['porcion']."', ".$_POST['kcal'].", '".$_POST['hora']."')";
mysqli_query($dbc,$sql) or die("<script>alert('Ocurrio un error'); window.location='../platos.php'</script>");
header("location: ../platos.php");
?>
<file_sep><?php
include("../../php/connect.php");
if (isset($_POST['guardar_prov'])) {
$prov = $_POST['nombre_prov'];
$query = "INSERT INTO proveedores(proveedor, telefono, direccion) VALUES ('$prov', '".$_POST['tel']."', '".$_POST['direccion']."')";
$result = mysqli_query($dbc, $query);
if (!$result) {
die("Query failed");
} else {
header("Location: ../proveedores.php");
}
$_SESSION['message'] = 'Proveedor guardado correctamente';
$_SESSION['message_type'] = 'info';
}
?>
<file_sep><?php
require_once("../../php/connect.php");
$sql="insert into detalleventa values(".$_GET['id'].", ".$_POST['producto'].", ".$_POST['cantidad'].")";
mysqli_query($dbc,$sql);
$sql="select stock from productos where productoid=".$_POST['producto'];
$rs=mysqli_query($dbc,$sql);
$stock=mysqli_fetch_array($rs);
$cant=$stock['stock']-$_POST['cantidad'];
$sql="update productos set stock=".$cant." where productoid=".$_POST['producto'];
mysqli_query($dbc,$sql);
header("location: ../editar_venta.php?id=".$_GET['id']);
?>
<file_sep><?php
include("../php/connect.php");
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = "SELECT * FROM visitas WHERE visitaid = '$id'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_array($result);
}
}
if (isset($_POST['update'])) {
$id = $_GET['id'];
$pacienteid=$_POST['pacienteid'];
$peso=$_POST['pesoPaciente'];
$altura=$_POST['alturaPaciente'];
$cintura=$_POST['cinturaPaciente'];
$cadera=$_POST['caderaPaciente'];
$presionA=$_POST['presionAltaPaciente'];
$presionB=$_POST['presionBajaPaciente'];
$imc=$_POST['imcPaciente'];
$icc=$_POST['iccPaciente'];
$temperatura=$_POST['temperaturaPaciente'];
$nota=$_POST['nota'];
$query = "UPDATE visitas SET pacienteid='".$pacienteid."', nota='".$nota."'
, peso='".$peso."', altura='".$altura."', cintura='".$cintura."', cadera='".$cadera."',
presiona='".$presionA."', presionb='".$presionB."', IMC='".$imc."',
ICC='".$icc."', temperatura='".$temperatura."'
WHERE visitaid = '$id'";
mysqli_query($dbc, $query) or die("No actualizo ".mysqli_error($dbc));
echo "<script language='javascript'>
alert('Visita Actualizada')
window.location.href='newNotaPacientePage.php'
</script>";
$_SESSION['message'] = 'Task updated succesfully';
$_SESSION['message_type'] = 'success';
}
?>
<!DOCTYPE html>
<html lang="en">
<?php include("../pacientes/security.php") ?>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Nutricen- Editar Paciente</title>
<!-- Custom fonts for this template-->
<link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Custom styles for this template-->
<link href="../css/table/bootstrap.min.css" rel="stylesheet">
<link href="../css/sb-admin-2.css" rel="stylesheet">
<link href="../css/table/bootstrap-select.min.css" rel="stylesheet" type="text/css">
<link href="../css/table/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css">
<link href="../css/table/buttons.bootstrap4.min.css" rel="stylesheet" type="text/css">
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fab fa-nutritionix"></i>
</div>
<div class="sidebar-brand-text mx-3">Nutricen</div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Pages Collapse Menu -->
<?php if ($_SESSION['tipo']=="administrador"){
echo '
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
<i class="fas fa-users-cog"></i>
<span>Administrar Usuarios</span>
</a>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Usuarios</h6>
<a class="collapse-item" href="../usuarios/agregar_usuario.php"> <i class="fa fa-plus"></i> Nuevo Usuario</a>
<a class="collapse-item" href="../usuarios/eliminar.php"> <i class="fa fa-trash"></i> Eliminar Usuario</a>
</div>
</div>
</li>
';
}
?>
<!-- Nav Item - Utilities Collapse Menu -->
<?php if($_SESSION['tipo']=="administrador" || $_SESSION['tipo']=="doctor" || $_SESSION['tipo']=="secretario"){
echo '<hr class="sidebar-divider">
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapseUtilities" aria-expanded="true" aria-controls="collapseUtilities">
<i class="fas fa-user-friends"></i>
<span>Administrar Pacientes</span>
</a>
<div id="collapseUtilities" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Pacientes:</h6>
<a class="collapse-item" href="../pacientes/newPacientePage.php"> <i class="fa fa-plus"></i> Nuevo Paciente</a>
<a class="collapse-item" href="../pacientes/listaPacientesPage.php"> <i class="fa fa-list-ul"></i> Lista de Pacientes</a>
</div>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapseVisitors" aria-expanded="true" aria-controls="collapseUtilities">
<i class="far fa-sticky-note"></i>
<span>Notas de Visita</span>
</a>
<div id="collapseVisitors" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Pacientes:</h6>
<a class="collapse-item" href="../notasPaciente/newNotaPacientePage.php"> <i class="fa fa-plus"></i> Nueva Nota Paciente</a>
<a class="collapse-item" href="../notasPaciente/listaNotaPacientePage.php"> <i class="fa fa-list-ul"></i> Historial Notas</a>
</div>
</div>
</li>';
}
?>
<!-- Nav Item - Utilities Collapse Menu -->
<?php if($_SESSION['tipo']=="administrador" || $_SESSION['tipo']=="doctor"){
echo '
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapsePages" aria-expanded="true" aria-controls="collapsePages">
<i class="fas fa-calendar-check"></i>
<span>Administrar Menús</span>
</a>
<div id="collapsePages" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Menús:</h6>
<a class="collapse-item" href="../menus/menus.php"><i class="fas fa-utensils"></i> Menús</a>
<a class="collapse-item" href="../platos/platos.php"><i class="fas fa-fish"></i> Platos</a>
</div>
</div>
</li>';
}
?>
<?php if($_SESSION['tipo']=="administrador" || $_SESSION['tipo']=="vendedor")
{
echo '
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapseSells" aria-expanded="true" aria-controls="collapseSells">
<i class="fas fa-store"></i>
<span>Ventas</span>
</a>
<div id="collapseSells" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Ventas:</h6>
<a class="collapse-item" href="../productos/productos.php"><i class="fas fa-shopping-basket"></i> Productos</a>
<a class="collapse-item" href="../notas/notas.php"><i class="fas fa-shopping-cart"></i> Notas de venta</a>
<a class="collapse-item" href="../compras/compras.php"><i class="fas fa-shopping-cart"></i> Notas de compra</a>
<a class="collapse-item" href="../proveedores/proveedores.php"><i class="fas fa-users-cog"></i> Proveedores</a>
<a class="collapse-item" href="../estantes/estantes.php"><i class="fas fa-bars"></i> Estantes</a>
<a class="collapse-item" href="../repisas/repisas.php"><i class="fas fa-align-center"></i> Repisas</a>
</div>
</div>
</li>';
}
?>
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="rounded-circle border-0" id="sidebarToggle"></button>
</div>
</ul>
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Nav Item - User Information -->
<li class="nav-item dropdown no-arrow">
<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span
class="mr-2 d-none d-lg-inline text-gray-600 small"><?php echo $_SESSION['usr']; ?></span>
<i class="fa fa-user"></i>
</a>
<!-- Dropdown - User Information -->
<div class="dropdown-menu dropdown-menu-right shadow animated--grow-in"
aria-labelledby="userDropdown">
<a class="dropdown-item" href="../menu.php">
<i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i>
Inicio
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="../php/logout.php" data-toggle="modal"
data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Salir
</a>
</div>
</li>
</ul>
</nav>
<!-- End of Topbar -->
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Editar Paciente</h1>
<div class="row">
<div class="col">
<div class="card card-body">
<form action="editVisitaPage.php?id=<?php echo $id ?>" method="post">
<div class="form-group">
<div class="row">
<div class="col">
<label>Nombre y Apellido Paterno del Paciente</label>
<select name="pacienteid" class="selectpicker" data-live-search="true"
required>
<?php
require_once("../php/connect.php");
$query = "SELECT pacienteid id, nombre, apellidop
FROM pacientes";
$rs = mysqli_query($dbc, $query);
while ($rows = mysqli_fetch_array($rs)) {
$query_paciente ="SELECT pacienteid, nombre, apellidop, apellidom FROM pacientes WHERE pacienteid='".$row['pacienteid']."'";
$rs_paciente = mysqli_query($dbc, $query_paciente);
while ($rows_paciente = mysqli_fetch_array($rs_paciente)) { ?>
<option value="<?php echo $rows_paciente['pacienteid'] ?>" selected>
<?php echo $rows_paciente['nombre'] ?> <?php echo $rows_paciente['apellidop']?>
</option>
<?php } ?>
<option value="<?php echo $rows['id'] ?>">
<?php echo $rows['nombre'] ?> <?php echo $rows['apellidop']?>
</option>
<?php } ?>
</select>
</div>
</div>
<hr>
<div class="row">
<div class="col">
<input type="number" class="form-control peso" name="pesoPaciente"
id="peso" placeholder="Peso del Paciente (Kg)"
value="<?php echo $row['peso'] ?>" required>
</div>
<div class="col">
<input type="number" class="form-control talla" name="alturaPaciente"
id="talla" placeholder="Altura (Mts)"
value="<?php echo $row['altura'] ?>" required>
</div>
</div>
<hr>
<div class="row">
<div class="col">
<input type="number" class="form-control" name="cinturaPaciente"
id="cintura"
placeholder="cintura (a nivel de la última costilla flotante)"
value="<?php echo $row['cintura'] ?>" required>
</div>
</div>
<hr>
<div class="row">
<div class="col">
<input type="number" class="form-control" name="caderaPaciente"
id="cadera" placeholder="cadera (a nivel de los glúteos)"
value="<?php echo $row['cadera'] ?>" required>
</div>
</div>
<hr>
<div class="row">
<div class="col">
<input type="number" class="form-control" name="presionAltaPaciente"
placeholder="Presión Alta" value="<?php echo $row['presiona'] ?>"
required>
</div>
<div class="col">
<input type="number" class="form-control" name="presionBajaPaciente"
placeholder="Presión Baja" value="<?php echo $row['presionb'] ?>"
required>
</div>
</div>
<hr>
<div class="row">
<div class="col text-center">
<h5>IMC</h5>
<input type="number" class="form-control imcInput" name="imcPaciente"
id="imcInput" value="<?php echo $row['IMC'] ?>" readonly required>
Kg/m2
<br>
<a class="btn btn-primary text-white" data-toggle="modal"
data-target="#imcModal">
Ver Tabla IMC
</a>
</div>
<div class="col text-center">
<h5>ICC</h5>
<input type="number" class="form-control iccInput" name="iccPaciente"
id="iccInput" value="<?php echo $row['ICC'] ?>" readonly required>
cm
<br>
<a class="btn btn-primary text-white" data-toggle="modal"
data-target="#iccModal">
Ver Tabla ICC
</a>
</div>
</div>
<hr>
<div class="row">
<div class="col">
<input type="number" class="form-control" name="temperaturaPaciente"
placeholder="Temperatura °C"
value="<?php echo $row['temperatura'] ?>" required>
</div>
</div>
<hr>
<div class="row">
<div class="col">
<textarea class="form-control" name="nota"
placeholder="Nota del Paciente"
required><?php echo $row['nota'] ?></textarea>
</div>
</div>
<hr>
<div class="form-group row">
<div class="col-sm-12">
<input type="submit" class="btn btn-primary btn-user btn-block"
value="Actualizar Visita" name="update">
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col">
<div class="card card-body">
<table class="table table-bordered" id="tablePacientes">
<thead>
<tr>
<th>Num. Visita</th>
<th>Fecha</th>
<th>Nombre y Apellido Paciente</th>
<th>IMC</th>
<th>ICC</th>
<th>Temperatura</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
require_once("../php/connect.php");
$query = "SELECT * FROM visitas";
$rs = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($rs)) { ?>
<tr>
<td><?php echo $row['visitaid'] ?></td>
<td><?php echo $row['fecha'] ?></td>
<td><?php
require_once("../php/connect.php");
$query_nombre = "SELECT nombre, apellidop, apellidom FROM pacientes WHERE pacienteid='".$row['pacienteid']."'";
$rsx = mysqli_query($dbc, $query_nombre);
while ($rows = mysqli_fetch_array($rsx)){
echo "<p>".$rows['nombre']." ".$rows['apellidop']." ".$rows['apellidom']."</p>";
}
?></td>
<td><?php echo $row['IMC']?></td>
<td><?php echo $row['ICC'] ?></td>
<td><?php echo $row['temperatura'] ?></td>
<td><a href="editVisitaPage.php?id=<?php echo $row['visitaid'] ?>"
class="btn btn-warning">
<i class="fas fa-marker"></i></a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer bg-white">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © ISEI07B 2019</span>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">¿Desea cerrar la sesión?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancelar</button>
<a class="btn btn-primary" href="../../php/logout.php">Cerrar Sesión</a>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="imcModal" tabindex="-1" role="dialog" aria-labelledby="imcModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="imcModalLabel">Tabla de Indice de Masa Corporal</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img src="../img/IMC.jpeg" class="img-fluid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="iccModal" tabindex="-1" role="dialog" aria-labelledby="iccModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="iccModalLabel">Tabla de Indice de Cintura - Cadera</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img src="../img/ICC.jpeg" class="img-fluid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="../js/jquery-3.3.1.min.js"></script>
<script src="../js/table/jquery.dataTables.min.js"></script>
<script src="../js/table/dataTables.bootstrap4.min.js"></script>
<script src="../js/table/dataTables.buttons.min.js"></script>
<script src="../js/table/buttons.bootstrap4.min.js"></script>
<script src="../js/table/jszip.min.js"></script>
<script src="../js/table/pdfmake.min.js"></script>
<script src="../js/table/buttons.html5.min.js"></script>
<script src="../js/table/buttons.print.min.js"></script>
<script src="../js/table/vfs_fonts.js"></script>
<script src="../js/table/bootstrap-select.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="../js/sb-admin-2.js"></script>
<script>
$(document).ready(function() {
$('#tablePacientes').DataTable({
dom: 'Bfrtip',
buttons: [
'excel', 'pdf'
]
});
});
</script>
<script>
$(function() {
$('#peso, #talla').keyup(function() {
var value1 = parseFloat($('#peso').val()) || 0;
var value2 = parseFloat($('#talla').val()) || 0;
$('#imcInput').val(value1 / (value2) ** 2);
});
});
</script>
<script>
$(function() {
$('#cintura, #cadera').keyup(function() {
var value1 = parseFloat($('#cintura').val()) || 0;
var value2 = parseFloat($('#cadera').val()) || 0;
$('#iccInput').val(value1 / value2);
});
});
</script>
</body>
</html>
<file_sep><?php
$id=$_GET['id'];
$sql="delete from usuarios where usuarioid=".$id;
require_once("../../php/connect.php");
mysqli_query($dbc,$sql) or die("<script> alert('".mysqli_error($dbc)."'); window.location.href='../../menu.php'; </script>");
header("location:../eliminar.php");
?>
<file_sep><?php
include("../../php/connect.php");
$sql ="update productos set producto='".$_POST['producto']."', repisaid=".$_POST['repisa'].", precio=".$_POST['precio'].",
stock=".$_POST['stock']." where productoid=".$_GET['id'];
mysqli_query($dbc, $sql);
header("location: ../productos.php");
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Servidor: localhost
-- Tiempo de generación: 02-04-2019 a las 06:48:23
-- Versión del servidor: 10.1.38-MariaDB
-- Versión de PHP: 7.3.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `nutriologodb`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `comidas`
--
CREATE TABLE `comidas` (
`platoid` int(11) DEFAULT NULL,
`menuid` int(11) DEFAULT NULL,
`dia` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `compras`
--
CREATE TABLE `compras` (
`compraid` int(11) NOT NULL,
`proveedorid` int(11) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`estado` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `compras`
--
INSERT INTO `compras` (`compraid`, `proveedorid`, `fecha`, `estado`) VALUES
(10, 2, '2019-04-01', 'abierta');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `detallecompra`
--
CREATE TABLE `detallecompra` (
`compraid` int(11) DEFAULT NULL,
`productoid` int(11) DEFAULT NULL,
`cantidad` double DEFAULT NULL,
`precio` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `detallecompra`
--
INSERT INTO `detallecompra` (`compraid`, `productoid`, `cantidad`, `precio`) VALUES
(10, 3, 20, 400);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `detalleventa`
--
CREATE TABLE `detalleventa` (
`ventaid` int(11) DEFAULT NULL,
`productoid` int(11) DEFAULT NULL,
`cantidad` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `detalleventa`
--
INSERT INTO `detalleventa` (`ventaid`, `productoid`, `cantidad`) VALUES
(6, 1, 1),
(6, 2, 3),
(6, 3, 1),
(10, 4, 1),
(9, 2, 2),
(9, 1, 1),
(13, 4, 1);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `estantes`
--
CREATE TABLE `estantes` (
`estanteid` int(11) NOT NULL,
`estante` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `estantes`
--
INSERT INTO `estantes` (`estanteid`, `estante`) VALUES
(1, 'Suplementos Alimenticios'),
(2, 'Fibras'),
(3, 'Galletas'),
(4, 'Malteadas'),
(5, 'Vitaminas'),
(6, 'Llaveros '),
(7, 'ProteÃnas'),
(8, 'El del rincón');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `menu`
--
CREATE TABLE `menu` (
`menuid` int(11) NOT NULL,
`descripcion` varchar(250) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `pacientes`
--
CREATE TABLE `pacientes` (
`pacienteid` int(11) NOT NULL,
`nombre` varchar(30) NOT NULL,
`apellidop` varchar(30) NOT NULL,
`apellidom` varchar(30) NOT NULL,
`fechanac` date NOT NULL,
`edocivil` varchar(15) NOT NULL,
`genero` varchar(15) DEFAULT NULL,
`domicilio` varchar(240) DEFAULT NULL,
`telefono` varchar(15) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`ocupacion` varchar(50) DEFAULT NULL,
`fechaalta` date DEFAULT NULL,
`curp` varchar(50) DEFAULT NULL,
`perinatales` varchar(250) DEFAULT NULL,
`heredados` varchar(250) DEFAULT NULL,
`npatologicos` varchar(250) DEFAULT NULL,
`patologicos` varchar(250) DEFAULT NULL,
`ginecoobst` varchar(250) DEFAULT NULL,
`celular` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `platos`
--
CREATE TABLE `platos` (
`platoid` int(11) NOT NULL,
`descripcion` varchar(250) DEFAULT NULL,
`cantidad` double DEFAULT NULL,
`porcion` varchar(30) DEFAULT NULL,
`kcal` double DEFAULT NULL,
`hora` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `productos`
--
CREATE TABLE `productos` (
`productoid` int(11) NOT NULL,
`repisaid` int(11) DEFAULT NULL,
`producto` varchar(30) DEFAULT NULL,
`precio` double DEFAULT NULL,
`stock` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `productos`
--
INSERT INTO `productos` (`productoid`, `repisaid`, `producto`, `precio`, `stock`) VALUES
(1, 2, 'Suplemento', 300, 56),
(2, 2, 'Malteada', 900, 5),
(3, 3, 'Fibra', 500, 20),
(4, 5, 'Llavero chido', 70, 5),
(5, 6, 'ProteÃna', 150, 7);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `proveedores`
--
CREATE TABLE `proveedores` (
`proveedorid` int(11) NOT NULL,
`proveedor` varchar(30) DEFAULT NULL,
`direccion` varchar(200) DEFAULT NULL,
`telefono` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `proveedores`
--
INSERT INTO `proveedores` (`proveedorid`, `proveedor`, `direccion`, `telefono`) VALUES
(2, 'Naturistas SA', 'Rodrigo rincón 802-54', '4492124586'),
(7, 'Doc Inc', 'Rojo 134, Vistas del Sol', '4492730860');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `repisas`
--
CREATE TABLE `repisas` (
`repisaid` int(11) NOT NULL,
`estanteid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `repisas`
--
INSERT INTO `repisas` (`repisaid`, `estanteid`) VALUES
(2, 1),
(3, 2),
(4, 5),
(5, 6),
(6, 7),
(7, 8);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `roles`
--
CREATE TABLE `roles` (
`rolid` int(11) NOT NULL,
`rol` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `roles`
--
INSERT INTO `roles` (`rolid`, `rol`) VALUES
(1, 'administrador'),
(2, 'secretario'),
(3, 'doctor'),
(4, 'vendedor');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuarios`
--
CREATE TABLE `usuarios` (
`usuarioid` int(11) NOT NULL,
`rolid` int(11) DEFAULT NULL,
`nombre` varchar(50) DEFAULT NULL,
`passwd` varchar(256) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `usuarios`
--
INSERT INTO `usuarios` (`usuarioid`, `rolid`, `nombre`, `passwd`) VALUES
(1, 1, 'admin', '<PASSWORD>'),
(2, 3, 'doc', '<PASSWORD> <KEY>'),
(3, 2, 'secre', 'd74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1'),
(4, 4, 'ventas', 'd74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1'),
(5, 1, 'jimena', 'd74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `ventas`
--
CREATE TABLE `ventas` (
`ventaid` int(11) NOT NULL,
`fecha` date DEFAULT NULL,
`estado` varchar(30) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `ventas`
--
INSERT INTO `ventas` (`ventaid`, `fecha`, `estado`) VALUES
(6, '2019-03-31', 'cerrada'),
(9, '2019-04-01', 'cerrada'),
(10, '2019-04-01', 'abierta'),
(13, '2019-04-01', 'cerrada');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `visitas`
--
CREATE TABLE `visitas` (
`visitaid` int(11) NOT NULL,
`pacienteid` int(11) DEFAULT NULL,
`fecha` date DEFAULT NULL,
`nota` varchar(250) DEFAULT NULL,
`peso` double DEFAULT NULL,
`altura` double DEFAULT NULL,
`cintura` double DEFAULT NULL,
`cadera` double DEFAULT NULL,
`presiona` int(11) DEFAULT NULL,
`presionb` int(11) DEFAULT NULL,
`IMC` double DEFAULT NULL,
`ICC` double DEFAULT NULL,
`temperatura` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `comidas`
--
ALTER TABLE `comidas`
ADD KEY `fk_com_pla` (`platoid`),
ADD KEY `fk_com_men` (`menuid`);
--
-- Indices de la tabla `compras`
--
ALTER TABLE `compras`
ADD PRIMARY KEY (`compraid`),
ADD KEY `fk_comp_proov` (`proveedorid`);
--
-- Indices de la tabla `detallecompra`
--
ALTER TABLE `detallecompra`
ADD KEY `productoid` (`productoid`),
ADD KEY `fk_det_com` (`compraid`);
--
-- Indices de la tabla `detalleventa`
--
ALTER TABLE `detalleventa`
ADD KEY `productoid` (`productoid`),
ADD KEY `fk_det_vent` (`ventaid`);
--
-- Indices de la tabla `estantes`
--
ALTER TABLE `estantes`
ADD PRIMARY KEY (`estanteid`);
--
-- Indices de la tabla `menu`
--
ALTER TABLE `menu`
ADD PRIMARY KEY (`menuid`);
--
-- Indices de la tabla `pacientes`
--
ALTER TABLE `pacientes`
ADD PRIMARY KEY (`pacienteid`),
ADD UNIQUE KEY `curp` (`curp`);
--
-- Indices de la tabla `platos`
--
ALTER TABLE `platos`
ADD PRIMARY KEY (`platoid`);
--
-- Indices de la tabla `productos`
--
ALTER TABLE `productos`
ADD PRIMARY KEY (`productoid`),
ADD KEY `fk_prod_repis` (`repisaid`);
--
-- Indices de la tabla `proveedores`
--
ALTER TABLE `proveedores`
ADD PRIMARY KEY (`proveedorid`);
--
-- Indices de la tabla `repisas`
--
ALTER TABLE `repisas`
ADD PRIMARY KEY (`repisaid`),
ADD KEY `fk_rep_estan` (`estanteid`);
--
-- Indices de la tabla `roles`
--
ALTER TABLE `roles`
ADD PRIMARY KEY (`rolid`);
--
-- Indices de la tabla `usuarios`
--
ALTER TABLE `usuarios`
ADD PRIMARY KEY (`usuarioid`),
ADD UNIQUE KEY `nombre` (`nombre`),
ADD KEY `fk_usu_rol` (`rolid`);
--
-- Indices de la tabla `ventas`
--
ALTER TABLE `ventas`
ADD PRIMARY KEY (`ventaid`);
--
-- Indices de la tabla `visitas`
--
ALTER TABLE `visitas`
ADD PRIMARY KEY (`visitaid`),
ADD KEY `fk_vis_pac` (`pacienteid`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `compras`
--
ALTER TABLE `compras`
MODIFY `compraid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT de la tabla `estantes`
--
ALTER TABLE `estantes`
MODIFY `estanteid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT de la tabla `menu`
--
ALTER TABLE `menu`
MODIFY `menuid` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `pacientes`
--
ALTER TABLE `pacientes`
MODIFY `pacienteid` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `platos`
--
ALTER TABLE `platos`
MODIFY `platoid` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `productos`
--
ALTER TABLE `productos`
MODIFY `productoid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de la tabla `proveedores`
--
ALTER TABLE `proveedores`
MODIFY `proveedorid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT de la tabla `repisas`
--
ALTER TABLE `repisas`
MODIFY `repisaid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT de la tabla `roles`
--
ALTER TABLE `roles`
MODIFY `rolid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT de la tabla `usuarios`
--
ALTER TABLE `usuarios`
MODIFY `usuarioid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de la tabla `ventas`
--
ALTER TABLE `ventas`
MODIFY `ventaid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT de la tabla `visitas`
--
ALTER TABLE `visitas`
MODIFY `visitaid` int(11) NOT NULL AUTO_INCREMENT;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `comidas`
--
ALTER TABLE `comidas`
ADD CONSTRAINT `fk_com_men` FOREIGN KEY (`menuid`) REFERENCES `menu` (`menuid`),
ADD CONSTRAINT `fk_com_pla` FOREIGN KEY (`platoid`) REFERENCES `platos` (`platoid`);
--
-- Filtros para la tabla `compras`
--
ALTER TABLE `compras`
ADD CONSTRAINT `fk_comp_proov` FOREIGN KEY (`proveedorid`) REFERENCES `proveedores` (`proveedorid`);
--
-- Filtros para la tabla `detallecompra`
--
ALTER TABLE `detallecompra`
ADD CONSTRAINT `detallecompra_ibfk_2` FOREIGN KEY (`productoid`) REFERENCES `productos` (`productoid`),
ADD CONSTRAINT `fk_det_com` FOREIGN KEY (`compraid`) REFERENCES `compras` (`compraid`);
--
-- Filtros para la tabla `detalleventa`
--
ALTER TABLE `detalleventa`
ADD CONSTRAINT `detalleventa_ibfk_2` FOREIGN KEY (`productoid`) REFERENCES `productos` (`productoid`),
ADD CONSTRAINT `fk_det_vent` FOREIGN KEY (`ventaid`) REFERENCES `ventas` (`ventaid`);
--
-- Filtros para la tabla `productos`
--
ALTER TABLE `productos`
ADD CONSTRAINT `fk_prod_repis` FOREIGN KEY (`repisaid`) REFERENCES `repisas` (`repisaid`);
--
-- Filtros para la tabla `repisas`
--
ALTER TABLE `repisas`
ADD CONSTRAINT `fk_rep_estan` FOREIGN KEY (`estanteid`) REFERENCES `estantes` (`estanteid`);
--
-- Filtros para la tabla `usuarios`
--
ALTER TABLE `usuarios`
ADD CONSTRAINT `fk_usu_rol` FOREIGN KEY (`rolid`) REFERENCES `roles` (`rolid`);
--
-- Filtros para la tabla `visitas`
--
ALTER TABLE `visitas`
ADD CONSTRAINT `fk_vis_pac` FOREIGN KEY (`pacienteid`) REFERENCES `pacientes` (`pacienteid`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
require_once '../../php/connect.php';
$sql="delete from detallecompra where compraid=".$_GET['id'];
mysqli_query($dbc,$sql);
$sql="delete from compras where compraid=".$_GET['id'];
mysqli_query($dbc,$sql);
header("Location:../compras.php");
?>
<file_sep><?php
require_once("../../php/connect.php");
$sql="insert into ventas(fecha, estado) values (date(sysdate()), 'abierta')";
$result = mysqli_query($dbc, $sql) or die ("<script>Ocurrió un error; window.location.href='../notas.php';</script>");
echo $sql;
header("location: ../notas.php");
?>
<file_sep><?php
require_once '../../php/connect.php';
$sql="update ventas set estado='cerrada' where ventaid=".$_GET['id'];
echo $sql;
mysqli_query($dbc,$sql);
header("location: ../notas.php");
?>
<file_sep><?php
require_once '../../php/connect.php';
$sql="update compras set fecha='".$_POST['fecha']."' where compraid=".$_GET['id'];
mysqli_query($dbc,$sql);
header("location:../editar_compra.php?id=".$_GET['id']);
?>
<file_sep><?php
require_once '../../php/connect.php';
if (isset ($_POST['proveedor']))
{
$prov=$_POST['proveedor'];
$sql="insert into compras(proveedorid, fecha, estado) values(".$prov.", date(sysdate()), 'abierta')";
mysqli_query($dbc,$sql) or die ("<script>Ocurrió un error; window.location.href='../compras.php';</script>");
header("Location: ../compras.php");
}
else
{
header("Location: ../compras.php");
}
?>
<file_sep><?php
require_once("../../php/connect.php");
$id=$_GET['id'];
$sql="delete from detalleventa where ventaid=".$id;
mysqli_query($dbc, $sql) or die ("<script>Ocurrió un error; window.location.href='../notas.php';</script>");
$sql="delete from ventas where ventaid=".$id;
mysqli_query($dbc, $sql) or die ("<script>Ocurrió un error; window.location.href='../notas.php';</script>");
header("location: ../notas.php");
?>
<file_sep><?php
$usr= $_POST['usuario'];
$pass=$_POST['pass'];
$sql = "select u.nombre as usuario, r.rol as rol from usuarios u, roles r where nombre='".$usr."' and passwd='".hash("sha256",$pass)."' and r.rolid=u.rolid;";
require_once("connect.php");
$rs = mysqli_query($dbc,$sql) or die("Error: ".mysqli_error($dbc));
$registro=mysqli_fetch_array($rs);
$row=mysqli_num_rows($rs);
if($row>0)
{
session_start();
$_SESSION['input']="###";
$_SESSION['tipo']=$registro['rol'];
$_SESSION['usr']=$registro['usuario'];
header("location:../menu.php");
}
else
{
header("location:invalid_user.php");
}
?>
<file_sep><?php
require('../fpdf/fpdf.php');
require_once("../php/connect.php");
$query="select date_format(fecha, '%d-%m-%Y') fecha from ventas where ventaid=".$_GET['id'];
$frs=mysqli_query($dbc,$query);
$fecha=mysqli_fetch_array($frs);
$sql="select * from detalleventa where ventaid=".$_GET['id'];
$res=mysqli_query($dbc,$sql);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->SetXY(10,10);
$pdf->Image('../img/logo.jpg' , 10 ,10, 20 , 20,'JPG');
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(170,10,utf8_decode('Nota De Remisión 000'.$_GET['id']));
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->SetFont('Arial','B',12);
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(40,10,'Fecha: '.$fecha['fecha']);
$pdf->SetFont('Arial','B',11);
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(50,10,"Producto");
$pdf->Cell(50,10,"Cantidad");
$pdf->Cell(50,10,"Precio Unitario");
$pdf->Cell(50,10,"Monto");
$pdf->SetFont('Arial','B',10);
$tot=0;
while ($row = mysqli_fetch_array($res)) {
$sel="select precio, producto from productos where productoid=".$row['productoid'];
$rs=mysqli_query($dbc,$sel);
$producto=mysqli_fetch_array($rs);
$tot=$tot+$producto['precio']*$row['cantidad'];
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(50,10,$producto['producto'],1);
$pdf->Cell(50,10,$row['cantidad'],1);
$pdf->Cell(50,10,"$".$producto['precio'],1);
$pdf->Cell(40,10,"$".$producto['precio']*$row['cantidad'],1);
}
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->SetX(147);
$pdf->Cell(40,10,"Total:");
$pdf->SetX(160);
$pdf->Cell(40,10,"$".$tot,1);
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(100,10,"*Los precios incluyen IVA del 16%.");
$pdf->Output();
?>
<file_sep><?php
require_once '../../php/connect.php';
$query="update productos set stock=stock-".$_GET['cant']." where productoid=".$_GET['id'];
mysqli_query($dbc,$query);
// echo $sql;
$sql="delete from detallecompra where productoid=".$_GET['id']." and compraid=".$_GET['compra'];
mysqli_query($dbc, $sql);
header("location: ../editar_compra.php?id=".$_GET['compra']);
?>
<file_sep><?php
include("../../php/connect.php");
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = "DELETE FROM proveedores WHERE proveedorid = '$id'";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo ("<script>alert('Error: el proveedor tiene compras asociadas');window.location.href='../proveedores.php'</script>");
// header("Location: ../proveedores.php");
}else {
header("Location: ../proveedores.php");
}
$_SESSION['message'] = 'Proveedor eliminado satisfactoriamente';
$_SESSION['message_type'] = 'danger';
}
?>
<file_sep><?php
$sql="update menu set descripcion='".$_POST['descripcion']."' where menuid=".$_GET['id'];
require_once '../../php/connect.php';
mysqli_query($dbc, $sql) or die("<script>alert('Ocurrio un error');window.location='../menus.php'</script>");
header("location: ../edit_menu.php?id=".$_GET['id']);
?>
<file_sep><?php
$id=$_GET['id'];
$sql="delete from repisas where repisaid=".$id;
include("../../php/connect.php");
$result = mysqli_query($dbc, $sql) or die ("<script>Ocurrió un error; window.location.href='../repisas.php';</script>");
header("location: ../repisas.php");
?>
<file_sep><!DOCTYPE html>
<html lang="en">
<?php include("php/security.php") ?>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Nutricen- Usuarios</title>
<!-- Custom fonts for this template-->
<link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<!-- Custom styles for this template-->
<link href="../css/sb-admin-2.css" rel="stylesheet">
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center justify-content-center" href="../menu.php">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fab fa-nutritionix"></i>
</div>
<div class="sidebar-brand-text mx-3">Nutricen</div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Pages Collapse Menu -->
<?php if ($_SESSION['tipo']=="administrador"){
echo '
<li class="nav-item">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
<i class="fas fa-users-cog"></i>
<span>Administrar Usuarios</span>
</a>
<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Usuarios</h6>
<a class="collapse-item" href="../usuarios/agregar_usuario.php"> <i class="fa fa-plus"></i> Nuevo Usuario</a>
<a class="collapse-item" href="../usuarios/eliminar.php"> <i class="fa fa-trash"></i> Eliminar Usuario</a>
</div>
</div>
</li>
';
}
?>
<!-- Nav Item - Utilities Collapse Menu -->
<?php if($_SESSION['tipo']=="administrador" || $_SESSION['tipo']=="doctor" || $_SESSION['tipo']=="secretario"){
echo '<hr class="sidebar-divider">
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapseUtilities" aria-expanded="true" aria-controls="collapseUtilities">
<i class="fas fa-user-friends"></i>
<span>Administrar Pacientes</span>
</a>
<div id="collapseUtilities" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Pacientes:</h6>
<a class="collapse-item" href="../pacientes/newPacientePage.php"> <i class="fa fa-plus"></i> Nuevo Paciente</a>
<a class="collapse-item" href="../pacientes/listaPacientesPage.php"> <i class="fa fa-list-ul"></i> Lista de Pacientes</a>
</div>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapseVisitors" aria-expanded="true" aria-controls="collapseUtilities">
<i class="far fa-sticky-note"></i>
<span>Notas de Visita</span>
</a>
<div id="collapseVisitors" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Pacientes:</h6>
<a class="collapse-item" href="../notasPaciente/newNotaPacientePage.php"> <i class="fa fa-plus"></i> Nueva Nota Paciente</a>
<a class="collapse-item" href="../notasPaciente/listaNotaPacientePage.php"> <i class="fa fa-list-ul"></i> Historial Notas</a>
</div>
</div>
</li>';
}
?>
<!-- Nav Item - Utilities Collapse Menu -->
<?php if($_SESSION['tipo']=="administrador" || $_SESSION['tipo']=="doctor"){
echo '
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapsePages" aria-expanded="true" aria-controls="collapsePages">
<i class="fas fa-calendar-check"></i>
<span>Administrar Menús</span>
</a>
<div id="collapsePages" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Menús:</h6>
<a class="collapse-item" href="../menus/menus.php"><i class="fas fa-utensils"></i> Menús</a>
<a class="collapse-item" href="../platos/platos.php"><i class="fas fa-fish"></i> Platos</a>
</div>
</div>
</li>';
}
?>
<?php if($_SESSION['tipo']=="administrador" || $_SESSION['tipo']=="vendedor")
{
echo '
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="collapse" data-target="#collapseSells" aria-expanded="true" aria-controls="collapseSells">
<i class="fas fa-store"></i>
<span>Ventas</span>
</a>
<div id="collapseSells" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Ventas:</h6>
<a class="collapse-item" href="../productos/productos.php"><i class="fas fa-shopping-basket"></i> Productos</a>
<a class="collapse-item" href="../notas/notas.php"><i class="fas fa-shopping-cart"></i> Notas de venta</a>
<a class="collapse-item" href="../compras/compras.php"><i class="fas fa-shopping-cart"></i> Notas de compra</a>
<a class="collapse-item" href="../proveedores/proveedores.php"><i class="fas fa-users-cog"></i> Proveedores</a>
<a class="collapse-item" href="../estantes/estantes.php"><i class="fas fa-bars"></i> Estantes</a>
<a class="collapse-item" href="../repisas/repisas.php"><i class="fas fa-align-center"></i> Repisas</a>
</div>
</div>
</li>';
}
?>
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="rounded-circle border-0" id="sidebarToggle"></button>
</div>
</ul>
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
<!-- Topbar Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Nav Item - User Information -->
<li class="nav-item dropdown no-arrow">
<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="mr-2 d-none d-lg-inline text-gray-600 small"><?php echo $_SESSION['usr']; ?></span>
<i class="fa fa-user"></i>
</a>
<!-- Dropdown - User Information -->
<div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
<a class="dropdown-item" href="../menu.php">
<i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i>
Inicio
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="../php/logout.php" data-toggle="modal" data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Salir
</a>
</div>
</li>
</ul>
</nav>
<!-- End of Topbar -->
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Ingrese los datos</h1>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8 mb-3 mb-sm-0">
<table class="table table-bordered">
<thead>
<tr>
<td>Id</td><td>Nombre De Usuario</td><td>Tipo</td><td>Contraseña</td><td></td>
</tr>
</thead>
<tbody>
<?php
$select="select u.nombre nombre, u.usuarioid id, u.passwd <PASSWORD>, r.rol rol from usuarios u, roles r where r.rolid=u.rolid";
require_once("../php/connect.php");
$rs = mysqli_query($dbc,$select) or die("Error: ".mysqli_error($dbc));
while ($row=mysqli_fetch_array($rs, MYSQLI_BOTH ))
{
echo '<tr><td>'.$row["id"].'</td><td>'.$row["nombre"].'</td><td>'.$row["rol"].'</td><td>$Crypted=$'.$row["pass"].'</td><td><a href="php/eliminar.php?id='.$row['id'].'"><i class="fa fa-trash"></i></a></td></tr>';
}
?>
</tbody>
</table>
</div>
<div class="col-sm-2"></div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer bg-white">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © ISEI07B 2019</span>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">¿Desea cerrar la sesión?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancelar</button>
<a class="btn btn-primary" href="../php/logout.php">Cerrar Sesión</a>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="../js/sb-admin-2.js"></script>
</body>
</html>
<file_sep><?php
require_once("../php/connect.php");
$nom=$_POST['nombre'];
$apellidop=$_POST['apellidop'];
$apellidom=$_POST['apellidom'];
$fechanac=$_POST['fechanac'];
$edocivil=$_POST['edocivil'];
$genero=$_POST['genero'];
$domicilio=$_POST['domicilio'];
$tel=$_POST['tel'];
$email=$_POST['email'];
$ocupacion=$_POST['ocupacion'];
$curp=$_POST['curp'];
$perinatales=$_POST['perinatales'];
$heredados=$_POST['heredados'];
$npatologicos=$_POST['npatologicos'];
$patologicos=$_POST['patologicos'];
$ginecoobst=$_POST['ginecoobst'];
$celular=$_POST['celular'];
$fechaalta=strftime( "%Y-%m-%d", time() );
$sql="insert into pacientes(nombre,apellidop,apellidom,fechanac,edocivil,genero,domicilio,telefono,email,ocupacion,
fechaalta,curp,perinatales,heredados,npatologicos,patologicos,ginecoobst,celular)
values('".$nom."', '".$apellidop."', '".$apellidom."','".$fechanac."','".$edocivil."',
'".$genero."','".$domicilio."','".$tel."','".$email."','".$ocupacion."','".$fechaalta."',
'".$curp."','".$perinatales."','".$heredados."','".$npatologicos."','".$patologicos."',
'".$ginecoobst."','".$celular."' )";
mysqli_query($dbc,$sql) or die('<script>alert("El usuario ya existe"); window.location.href="nofunciona.php";</script>');
header("Location: newPacientePage.php");
?>
<file_sep><?php
require_once("../../php/connect.php");
$usr=$_POST['usuario'];
$pass=$_POST['pass'];
$rol=$_POST['tipo'];
$sql="insert into usuarios(nombre,rolid,passwd) values('".$usr."', ".$rol.", '".hash("sha256",$pass)."')";
mysqli_query($dbc,$sql) or die('<script>alert("El usuario ya existe"); window.location.href="../agregar_usuario.php";</script>');
header("Location: ../../menu.php");
?>
<file_sep><?php
require_once("../php/connect.php");
$fecha_visita=date('Y-m-d', strtotime($_POST['fecha_visita']));
$pacienteid=$_POST['pacienteid'];
$peso=$_POST['pesoPaciente'];
$altura=$_POST['alturaPaciente'];
$cintura=$_POST['cinturaPaciente'];
$cadera=$_POST['caderaPaciente'];
$presionA=$_POST['presionAltaPaciente'];
$presionB=$_POST['presionBajaPaciente'];
$imc=$_POST['imcPaciente'];
$icc=$_POST['iccPaciente'];
$temperatura=$_POST['temperaturaPaciente'];
$nota=$_POST['nota'];
if($pacienteid == "noPaciente"){
echo "<script language='javascript'>
alert('Porfavor selecciona un Paciente')
window.location.href='newNotaPacientePage.php'
</script>";
}
else{
if($peso == 0 || $altura == 0 || $cintura == 0 || $cadera == 0 || $presionA == 0 || $presionB == 0 || $temperatura == 0){
echo "<script language='javascript'>
alert('No puedes poner como valor de 0 a alguno de los siguientes tributos: peso, altura, cintura, cadera, presion Alta, presion Baja, temperatura. Verifica los Datos.')
window.location.href='newNotaPacientePage.php'
</script>";
}
else{
$sql="insert into visitas(pacienteid,fecha,nota,peso,altura,cintura,cadera,presiona,presionb,IMC,ICC,temperatura)
values('".$pacienteid."', '".$fecha_visita."', '".$nota."','".$peso."','".$altura."',
'".$cintura."','".$cadera."','".$presionA."','".$presionB."','".$imc."','".$icc."',
'".$temperatura."')";
mysqli_query($dbc,$sql) or die('<script>alert("'.$sql.'"); window.location.href="nofunciona.php";</script>');
header("Location: newNotaPacientePage.php");
}
}
?>
<file_sep><?php
require_once '../../php/connect.php';
$sql="insert into menu values('', '".$_POST['descripcion']."')";
mysqli_query($dbc,$sql) or die ("<script>alert('Ocurrio un error'); window.location='../menus.php'</script>");
header("location: ../menus.php");
?>
<file_sep><?php
$estante=$_POST['estante'];
$sql="insert into repisas(estanteid) values(".$estante.")";
include("../../php/connect.php");
$result = mysqli_query($dbc, $sql) or die ("<script>Ocurrió un error; window.location.href='../repisas.php';</script>");
header("location: ../repisas.php");
?>
<file_sep><?php
require_once '../../php/connect.php';
$sql="update compras set estado='cerrada' where compraid=".$_GET['id'];
mysqli_query($dbc,$sql);
header("Location: ../compras.php");
?>
<file_sep><?php
$repisa= $_POST['repisa'];
$producto=$_POST['producto'];
$precio=$_POST['precio'];
$sql="insert into productos(repisaid, producto, precio) values (".$repisa.", '".$producto."', ".$precio.")";
include("../../php/connect.php");
$result = mysqli_query($dbc, $sql) or die("<script> alert('Ocurrió un error'); window.location.href='../productos.php';</script>");
header("location: ../productos.php");
?>
<file_sep><?php
require_once("../../php/connect.php");
$sql="update ventas set fecha='".$_POST['fecha']."' where ventaid=".$_GET['id'];
mysqli_query($dbc,$sql);
echo $sql;
header("location: ../editar_venta.php?id=".$_GET['id']);
?>
<file_sep><?php
include("../../php/connect.php");
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = "DELETE FROM estantes WHERE estanteid = '$id'";
$result = mysqli_query($dbc, $query);
if (!$result) {
die('query failed');
}else {
header("Location: ../estantes.php");
}
$_SESSION['message'] = 'Proveedor eliminado satisfactoriamente';
$_SESSION['message_type'] = 'danger';
}
?><file_sep><?php
require('../fpdf/fpdf.php');
require_once("../php/connect.php");
$query="select * from pacientes where pacienteid=".$_GET['id'];
$frs=mysqli_query($dbc,$query);
$paciente=mysqli_fetch_array($frs);
$sql="select * from visitas where pacienteid=".$_GET['id']." order by fecha desc";
$res=mysqli_query($dbc,$sql);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->SetXY(10,10);
$pdf->Image('../img/logo.jpg' , 10 ,10, 20 , 20,'JPG');
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(170,10,utf8_decode('Paciente: 000'.$_GET['id']));
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->SetFont('Arial','B',12);
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(40,10,'Nombre: '.$paciente['nombre']." ".$paciente['apellidop']." ".$paciente['apellidom']);
$y= $pdf->GetY();
$pdf->SetY($y+4);
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(40,10,'Tel/Cel: '.$paciente['telefono']." / ".$paciente['celular']);
$y= $pdf->GetY();
$pdf->SetY($y+4);
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(40,10,'CURP: '.$paciente['curp']);
$pdf->SetFont('Arial','B',11);
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(40,10,"Fecha");
$pdf->Cell(40,10,"Peso");
$pdf->Cell(40,10,"ICC");
$pdf->Cell(40,10,"IMC");
$pdf->Cell(40,10,utf8_decode("Presión Arterial"));
$pdf->SetFont('Arial','B',10);
$tot=0;
while ($visita = mysqli_fetch_array($res)) {
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(40,10,$visita['fecha'],1);
$pdf->Cell(40,10,$visita['peso'],1);
$pdf->Cell(40,10,$visita['ICC'],1);
$pdf->Cell(40,10,$visita['IMC'],1);
$pdf->Cell(35,10,$visita['presiona']." / ".$visita['presionb'],1);
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(40,10,"Nota de visita: ".$visita['nota']);
}
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(100,10,utf8_decode("_________________________________________________________________________________________________"));
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(100,10,utf8_decode("Antecedentes Perinatales: ".$paciente['perinatales']));
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(100,10,utf8_decode("Antecedentes Heredados: ".$paciente['heredados']));
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(100,10,utf8_decode("Antecedentes No Patológicos: ".$paciente['npatologicos']));
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(100,10,utf8_decode("Antecedentes Patológicos: ".$paciente['npatologicos']));
if($paciente['genero']=="mujer")
{
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(100,10,utf8_decode("Antecedentes Gineco-Obstréticos: ".$paciente['npatologicos']));
}
$pdf->Output();
?>
<file_sep><?php
require_once '../../php/connect.php';
$query="update productos set stock=stock+".$_GET['cant']." where productoid=".$_GET['id'];
mysqli_query($dbc,$query);
$sql="delete from detalleventa where ventaid=".$_GET['venta']." and productoid=".$_GET['id'];
mysqli_query($dbc,$sql);
header("location: ../editar_venta.php?id=".$_GET['venta']);
?>
<file_sep><?php
require('../fpdf/fpdf.php');
require_once("../php/connect.php");
$query="select date_format(fecha, '%d-%m-%Y') fecha, p.proveedor, p.telefono, p.direccion from compras c inner join proveedores p using(proveedorid) where compraid=".$_GET['id'];
$frs=mysqli_query($dbc,$query);
$datos=mysqli_fetch_array($frs);
$sql="select * from detallecompra where compraid=".$_GET['id'];
$res=mysqli_query($dbc,$sql);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->SetXY(10,10);
$pdf->Image('../img/logo.jpg' , 10 ,10, 20 , 20,'JPG');
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(170,10,utf8_decode('Nota De Compra 000'.$_GET['id']));
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->SetFont('Arial','B',12);
$X=$pdf->GetX();
$pdf->SetX($X+30);
$pdf->Cell(40,10,'Fecha: '.$datos['fecha']);
$X=$pdf->GetX();
$pdf->SetX($X+40);
$pdf->Cell(40,10,'Proveedor: '.$datos['proveedor']);
$y= $pdf->GetY();
$pdf->SetY($y+4);
$X=$pdf->GetX();
$pdf->SetX($X+110);
$pdf->SetFont('Arial','B',9);
$pdf->Cell(40,10,utf8_decode($datos['direccion']));
$y= $pdf->GetY();
$pdf->SetY($y+4);
$X=$pdf->GetX();
$pdf->SetX($X+110);
$pdf->Cell(40,10,utf8_decode($datos['telefono']));
$pdf->SetFont('Arial','B',11);
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(50,10,"Producto");
$pdf->Cell(50,10,"Cantidad");
$pdf->Cell(50,10,"Precio Unitario");
$pdf->Cell(50,10,"Monto");
$pdf->SetFont('Arial','B',10);
$tot=0;
while ($row = mysqli_fetch_array($res)) {
$sel="select p.producto, d.precio from productos p inner join detallecompra d where d.compraid=".$_GET['id']." and p.productoid=".$row['productoid'];
$rs=mysqli_query($dbc,$sel);
$producto=mysqli_fetch_array($rs);
$tot=$tot+$producto['precio']*$row['cantidad'];
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Cell(50,10,$producto['producto'],1);
$pdf->Cell(50,10,$row['cantidad'],1);
$pdf->Cell(50,10,"$".$producto['precio'],1);
$pdf->Cell(40,10,"$".$producto['precio']*$row['cantidad'],1);
}
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->SetX(147);
$pdf->Cell(40,10,"Total:");
$pdf->SetX(160);
$pdf->Cell(40,10,"$".$tot,1);
$y= $pdf->GetY();
$pdf->SetY($y+10);
$pdf->Output();
?>
<file_sep><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "nutriologodb";
$dbc = mysqli_connect($servername, $username, $password, $dbname);
if (!$dbc) {
die("Conexion fallida: " . mysqli_connect_error());
};
?>
<file_sep><?php
require_once '../../php/connect.php';
$sql="update productos set stock = stock +".$_POST['cantidad']." where productoid=".$_POST['producto'];
mysqli_query($dbc,$sql);
$sql="insert into detallecompra values(".$_GET['id'].", ".$_POST['producto'].",
".$_POST['cantidad'].", ".$_POST['precio'].")";
mysqli_query($dbc,$sql);
header("location: ../editar_compra.php?id=".$_GET['id']);
?>
<file_sep><?php
require_once '../../php/connect.php';
$sql="insert into comidas values(".$_POST['plato'].", ".$_GET['id'].", '".$_POST['dia']."')";
mysqli_query($dbc, $sql) or die("<script>alert('Ocurrio un error');window.location='../menus.php'</script>");
header("location: ../edit_menu.php?id=".$_GET['id']);
?>
<file_sep><?php
$sql="delete from comidas where platoid=".$_GET['id']." and menuid=".$_GET['menu'];
require_once '../../php/connect.php';
mysqli_query($dbc, $sql) or die("<script>alert('Ocurrio un error');window.location='../menus.php'</script>");
header("location: ../edit_menu.php?id=".$_GET['menu']."");
?>
| bbbbe1f23726d34947c3667cc841927afd9f2d48 | [
"SQL",
"PHP"
] | 36 | PHP | crismatters/nutriologo | 4197cc201d07857d2a10854d0d5cb782d138b07d | f2618349e490b4ac8ff0e5262a834c61a1d0ab16 |
refs/heads/main | <file_sep>//
// ViewController.swift
// Mommas Babies
//
// Created by <NAME> on 5/25/21.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
if let imageToPlayVideo = ARReferenceImage.referenceImages(inGroupNamed: "Baby Pictures", bundle: Bundle.main) {
configuration.detectionImages = imageToPlayVideo
configuration.maximumNumberOfTrackedImages = 2 // MAYBE SHOULD DO MAX = 1??????
}
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
// MARK: - ARSCNViewDelegate
fileprivate func playCorrespondingVideo(_ videoNode: SKVideoNode, _ plane: SCNPlane) {
videoNode.play()
let videoScene = SKScene(size: CGSize(width: 480, height: 360))
plane.firstMaterial?.diffuse.contents = UIColor(white: 0, alpha: 0.5)
plane.firstMaterial?.diffuse.contents = videoScene
videoNode.position = CGPoint(x: videoScene.size.width / 2, y: videoScene.size.height / 2)
videoNode.yScale = 1.0
videoNode.xScale = -1.0 // YEEHAW
videoScene.addChild(videoNode)
print("Found baby picture")
}
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
if let imageAnchor = anchor as? ARImageAnchor {
let plane = SCNPlane(width: imageAnchor.referenceImage.physicalSize.width, height: imageAnchor.referenceImage.physicalSize.height * 2) //HELLO ( * 2)
// plane.firstMaterial?.diffuse.contents = videoScene
let planeNode = SCNNode(geometry: plane)
planeNode.eulerAngles.x = -Float.pi / 2
node.addChildNode(planeNode)
switch imageAnchor.referenceImage.name {
case "Briar Ducks 1":
let videoNode = SKVideoNode(fileNamed: "Briar Ducks 1.mp4")
playCorrespondingVideo(videoNode, plane)
case "Little Mermaid Ride":
let videoNode = SKVideoNode(fileNamed: "Little Mermaid Ride.mp4")
playCorrespondingVideo(videoNode, plane)
case "Big Monkey":
let videoNode = SKVideoNode(fileNamed: "Big Monkey.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Safari Ride":
let videoNode = SKVideoNode(fileNamed: "Briar Safari Ride.mp4")
playCorrespondingVideo(videoNode, plane)
case "Braxton Laughing":
let videoNode = SKVideoNode(fileNamed: "Braxton Laughing.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Break Toy Car":
let videoNode = SKVideoNode(fileNamed: "Briar Break Toy Car.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Dinosaur Ride 2":
let videoNode = SKVideoNode(fileNamed: "Briar Dinosaur Ride 2.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Dinosaur Ride Dance 1":
let videoNode = SKVideoNode(fileNamed: "Briar Dinosaur Ride Dance 1.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Dinosaur Ride":
let videoNode = SKVideoNode(fileNamed: "Briar Dinosaur Ride.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Drive Car":
let videoNode = SKVideoNode(fileNamed: "Briar Drive Car.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Ducks 2":
let videoNode = SKVideoNode(fileNamed: "Briar Ducks 2.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Fish Tank":
let videoNode = SKVideoNode(fileNamed: "Briar Fish Tank.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Hotel Room":
let videoNode = SKVideoNode(fileNamed: "Briar Hotel Room.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Parade":
let videoNode = SKVideoNode(fileNamed: "Briar Parade.mp4")
playCorrespondingVideo(videoNode, plane)
case "Flutter":
let videoNode = SKVideoNode(fileNamed: "Flutter.mp4")
playCorrespondingVideo(videoNode, plane)
case "Frozen Play":
let videoNode = SKVideoNode(fileNamed: "Frozen Play.mp4") //test
playCorrespondingVideo(videoNode, plane)
case "Giraffe_":
let videoNode = SKVideoNode(fileNamed: "Giraffe_.mp4")
playCorrespondingVideo(videoNode, plane)
case "Jennifer Feed Bird":
let videoNode = SKVideoNode(fileNamed: "Jennifer Feed Bird.mp4")
playCorrespondingVideo(videoNode, plane)
case "Lilly Beast Dinner":
let videoNode = SKVideoNode(fileNamed: "Lilly Beast Dinner.mp4")
playCorrespondingVideo(videoNode, plane)
case "Lilly Painting Cup":
let videoNode = SKVideoNode(fileNamed: "Lilly Painting Cup.mp4")
playCorrespondingVideo(videoNode, plane)
case "Lilly_Briar Bubbles":
let videoNode = SKVideoNode(fileNamed: "Lilly_Briar Bubbles.mp4")
playCorrespondingVideo(videoNode, plane)
case "Safair Rhinoceros":
let videoNode = SKVideoNode(fileNamed: "Safair Rhinoceros.mp4")
playCorrespondingVideo(videoNode, plane)
case "Sleepy Briar 2":
let videoNode = SKVideoNode(fileNamed: "Sleepy Briar 2.mp4")
playCorrespondingVideo(videoNode, plane)
case "Weird 1":
let videoNode = SKVideoNode(fileNamed: "Weird 1.mp4")
playCorrespondingVideo(videoNode, plane)
case "Weird 2":
let videoNode = SKVideoNode(fileNamed: "Weird 2.mp4")
playCorrespondingVideo(videoNode, plane)
case "Briar Sleepy":
let videoNode = SKVideoNode(fileNamed: "Briar Sleepy.mp4")
playCorrespondingVideo(videoNode, plane)
default:
print("No Video, Something is fucked!")
}
// if imageAnchor.referenceImage.name == "Briar Ducks 1" {
// let videoNode = SKVideoNode(fileNamed: "Briar Ducks 1.mp4")
// playCorrespondingVideo(videoNode, plane)
// }
//
// if imageAnchor.referenceImage.name == "Little Mermaid Ride" {
// let videoNode = SKVideoNode(fileNamed: "Little Mermaid Ride.mp4")
// playCorrespondingVideo(videoNode, plane)
// }
//
}
return node
}
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
| f2690179863c17734a327a566c837ecce9b0ab8b | [
"Swift"
] | 1 | Swift | einmanjr/Mommas-Babies | 9b23ca7b7f9e1cab4108d6e82e53cf3a65af8c89 | 0c1907b4df70e34303998df327d0c4dc8d729f0b |
refs/heads/master | <repo_name>sri252/learning-github<file_sep>/fifo.cpp
#include<iostream>
using namespace std;
int main(){
int p=5,r=3;
int allot[5][3],max[5][3],avail[3],need[5][3];
int i,j,k;
cout<<"Allocation";
for(i=0;i<p;i++){
for(j=0;j<r;j++){
cin>>allot[i][j];
}
}
cout<<"max";
for(i=0;i<p;i++){
for(j=0;j<r;j++){
cin>>max[i][j];
}
}
cout<<"Available";
for(i=0;i<r;i++){
cin>>avail[i];
}
cout<<"need";
for(i=0;i<p;i++){
for(j=0;j<r;j++){
need[i][j] = max[i][j] - allot[i][j];
}
}
for(i=0;i<p;i++){
cout<<" \n"
for(j=0;j<r;j++){
cout<<" "<<need[i][j];
}
}
int safestate[p]={0};
int finish[p]={0};
int found=0;
int count=0;
while(count < p){
found=0;
for(i=0;i<p;i++){
if(finish[i] == 0){
for(j=0;j<r;j++){
if( need[i][j] > avail[j] ){
break;
}
}
if(j == r){
for(k=0;k<r;k++){
avail[k] = avail[k] + allot[i][k];
}
finish[i]=1;
found=1;
safestate[count++]=i;
}
}
}
if(found == 0){
cout<<"No safe sate";
}
}
cout<<"safe State";
for(i=0;i<p;i++){
cout<<" "<<safestate[i];
}
return 0;
}
| 94aca8b1e7d75485184b736cf17f3d9b17db06b4 | [
"C++"
] | 1 | C++ | sri252/learning-github | f1e0ab430f6ec87041f6769e9c8b4b5c12062371 | e2867e16b956f68cb2d62b9dfbf520fac0662f8f |
refs/heads/master | <file_sep>const CustomError = require("../extensions/custom-error");
const chainMaker = {
mainArr: [],
train: '',
addLink(value) {
this.mainArr.push(value);
return this
},
removeLink(position) {
if (position > 0 && position < this.mainArr.length ) {
this.mainArr.splice(position - 1, 1);
} else {
this.mainArr = [];
this.train = '';
throw new Error()
}
return this
},
reverseChain() {
this.mainArr.reverse();
return this
},
finishChain() {
for (let i = 0; i < this.mainArr.length; i++) {
if (i == this.mainArr.length - 1) {
this.train += `( ${this.mainArr[i]} )`;
break;
}
this.train += `( ${this.mainArr[i]} )~~`
}
this.mainArr = [];
let result = this.train;
this.train = '';
return result
}
};
module.exports = chainMaker;
<file_sep>const CustomError = require("../extensions/custom-error");
const MODERN_ACTIVITY= 15;
const HALF_LIFE_PERIOD= 5730;
module.exports = function dateSample(age) {
if (typeof(age) == 'string' && typeof(age) !== 'number') {
age = Number(age);
if (isFinite(age) === false || age > 15 || age <= 0) {
return false
}
let activity = (MODERN_ACTIVITY / age);
let k = (0.693/HALF_LIFE_PERIOD);
let result = (Math.log(activity))/k;
result = result.toFixed(0);
console.log(result);
return result
} else {
return false
}
throw new CustomError('Not implemented');
// remove line with error and write your code here
};
<file_sep>const CustomError = require("../extensions/custom-error");
module.exports = function calculateHanoi(n, t) {
let turns_value = Math.pow(2, n) - 1;
let time_value = turns_value / (t/Math.pow(60, 2));
time_value = Number(Math.floor(time_value));
let result = {
turns: turns_value,
seconds: time_value
};
return result
};<file_sep>const CustomError = require("../extensions/custom-error");
module.exports = function transform(arr) {
let change = arr.slice();
for (let i = 0; i < change.length; i++) {
switch (change[i]) {
case '--discard-next': if (i === change.length - 1) {change.splice(i, 1); i--; break;};
change.splice(i, 2, 'discard', 'discard');
break;
case '--discard-prev': if (i === 0) {change.splice(i, 1); i--; break;};
change.splice(i-1, 2, 'discard', 'discard');
break;
case '--double-next': if (i === change.length - 1) {change.splice(i, 1); i--; break;};
change[i] = change[i + 1];
break;
case '--double-prev': if (i === 0) {change.splice(i, 1); i--; break;};
change[i] = change[i - 1];
case 'discard': break;
}
}
for (let y = 0; y < change.length; y++) {
if (change[y] == 'discard') {
change.splice(y, 1);
--y;
}
}
return change
};
<file_sep>const CustomError = require("../extensions/custom-error");
module.exports = function createDreamTeam(arr) {
let result = [];
if (typeof(arr) !== 'object' || arr == null) {
return false
}
for (let i = 0; i < arr.length; i++) {
if (typeof(arr[i]) !== 'string') continue;
arr[i] = arr[i].replace(/\s/g, '');
if (/[A-Z]/gi.test(arr[i][0]) == true) {
result.push(arr[i][0])
}
}
result = result.sort(function (a, b) {
return a.localeCompare(b);
}).join('');
return result.toUpperCase()
};
| e51472dba3bb1709532644fa803fe0fbe5c88bf9 | [
"JavaScript"
] | 5 | JavaScript | Goodbish/basic-js | 4b1dcb5b0936de6a19e9849ac4bc4e941d68a332 | 1d2d54ea9263069a7419ff4813351087ed99acc1 |
refs/heads/master | <repo_name>defconcepts/PerfKitExplorer<file_sep>/client/externs.js
/**
* @copyright Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @fileoverview Externs for Closure compiler.
*
* This allows us to use Angular and other things that should not be compiled,
* while avoiding a bunch of warnings about undefined variables.
*
* @externs
* @author <EMAIL> (<NAME>)
*/
angular.$httpBackend = function() {};
angular.$httpBackend.prototype.whenGET = function(a) {};
angular.$httpBackend.prototype.whenPOST = function(a) {};
angular.$httpBackend.prototype.passThrough = function() {};
angular.$httpBackend.prototype.respond = function(a) {};
CodeMirror.prototype.setValue = function(a) {};
function history() {}
history.pushState = function(a, b, c) {};
var CURRENT_USER_ADMIN = null;
var CURRENT_USER_EMAIL = null;
<file_sep>/client/components/error/error_model.js
/**
* @copyright Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @fileoverview ErrorModel contains information on errors exposed to the user.
* @author <EMAIL> (<NAME>)
*/
goog.provide('p3rf.perfkit.explorer.components.error.ErrorModel');
goog.provide('p3rf.perfkit.explorer.components.error.ErrorTypes');
goog.scope(function() {
const components = p3rf.perfkit.explorer.components;
/**
* Static type for Error levels.
*/
components.error.ErrorTypes = function() {};
const ErrorTypes = components.error.ErrorTypes;
/** @export @type {!string} */
ErrorTypes.WARNING = 'WARNING';
/** @export @type {!string} */
ErrorTypes.SUCCESS = 'SUCCESS';
/** @export @type {!string} */
ErrorTypes.INFO = 'INFO';
/** @export @type {!string} */
ErrorTypes.DANGER = 'DANGER';
/**
* Lists the error types by severity.
* @export @type {Array.<!string>}
*/
ErrorTypes.All = [
ErrorTypes.DANGER, ErrorTypes.WARNING, ErrorTypes.INFO, ErrorTypes.SUCCESS];
/**
* @param {!string} errorType A string describing the type of alert. See
* ErrorTypes.All for a list of acceptable values.
* @param {!string} text The text to display for the error.
* @param {?string=} opt_errorId An optional ID for the error. Errors with
* an ID are replaced with another error with the same ID is added.
* @export
* @constructor
*/
components.error.ErrorModel = function(
errorType, text, opt_errorId) {
/**
* @type {!string} A string representing the type of error. See
* components.error.ErrorTypes for supported values.
* @export
*/
this.errorType = errorType || ErrorTypes.ERROR;
/**
* @type {!string} The text to display.
* @export
*/
this.text = text || '';
/**
* @type {!string|number} The unique ID, if provided, for the error.
* @export
*/
this.errorId = '';
if (goog.isDef(opt_errorId)) {
this.errorId = opt_errorId;
}
};
}); // goog.scope
<file_sep>/client/components/dashboard/dashboard-directive_test.js
/**
* @copyright Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @fileoverview Tests for ConfigDirective, which encapsulates the global config
* settings.
* @author <EMAIL> (<NAME>)
*/
goog.require('p3rf.perfkit.explorer.components.dashboard.DashboardDirective');
describe('dashboardDirective', function() {
var scope, $compile;
const explorer = p3rf.perfkit.explorer;
beforeEach(module('explorer'));
beforeEach(module('p3rf.perfkit.explorer.templates'));
beforeEach(inject(function(_$rootScope_, _$compile_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
}));
describe('compilation', function() {
it('should succeed as a standalone element.', function() {
function compile() {
$compile('<dashboard />')(scope);
}
expect(compile).not.toThrow();
});
});
});
| 2bbd88ba821dbbec2332d854670ab61ec94df1ed | [
"JavaScript"
] | 3 | JavaScript | defconcepts/PerfKitExplorer | 20959a85b8fc2eae37a01e658dee86b3ccbac173 | 283802db5479358ddf68bc2be668f8b0bbc5c039 |
refs/heads/main | <repo_name>demireleren877/School_Project<file_sep>/School_Project/DataAccesLayer/DbServices/Concrete/ProductDal.cs
using Microsoft.EntityFrameworkCore;
using School_Project.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace School_Project.DataAccesLayer
{
public class ProductDal : IProductDal
{
public void Add(Product entity)
{
using (Context c = new Context())
{
var added = c.Entry(entity);
added.State = EntityState.Added;
c.SaveChanges();
}
}
public Product Get(int id)
{
using (Context c = new Context())
{
return c.Set<Product>().FirstOrDefault(p => p.ID == id);
}
}
public List<Product> GetList()
{
using (Context c = new Context())
{
var list = c.Products.ToList();
return list;
}
}
public void Remove(Product entity)
{
using (Context c = new Context())
{
var removed = c.Remove(entity);
removed.State = EntityState.Deleted;
c.SaveChanges();
}
}
public void Update(Product entity)
{
using (Context c = new Context())
{
var updated = c.Update(entity);
updated.State = EntityState.Modified;
c.SaveChanges();
}
}
}
}
<file_sep>/School_Project/Controllers/ProductsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using School_Project.DataAccesLayer;
using School_Project.Entity;
namespace School_Project.Controllers
{
public class ProductsController : Controller
{
//private readonly Context _productDal;
private IProductDal _productDal;
public ProductsController(IProductDal productDal)
{
_productDal = productDal;
}
[HttpGet]
public IActionResult Index()
{
var productlist = _productDal.GetList();
return View(productlist);
}
[HttpGet]
public IActionResult Details(int id)
{
var product = _productDal.Get(id);
return View(product);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
_productDal.Add(product);
return RedirectToAction(nameof(Index));
}
return View(product);
}
[HttpGet]
public IActionResult Edit(int id)
{
var product = _productDal.Get(id);
return View(product);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(int id, Product product)
{
if (ModelState.IsValid)
{
_productDal.Update(product);
return RedirectToAction(nameof(Index));
}
return View(product);
}
public IActionResult Delete(int id)
{
var product = _productDal.Get(id);
_productDal.Remove(product);
return RedirectToAction(nameof(Index));
}
private bool ProductExists(int id)
{
return _productDal.Get(id) != null;
}
}
}
<file_sep>/School_Project/DataAccesLayer/DbServices/Abstract/IProductDal.cs
using School_Project.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace School_Project.DataAccesLayer
{
public interface IProductDal:IGenericRepository<Product>
{
}
}
<file_sep>/School_Project/DataAccesLayer/Entity/Product.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace School_Project.Entity
{
public class Product
{
[Key]
public int ID { get; set; }
public string Barkod { get; set; }
public string ModelKod { get; set; }
public string Marka { get; set; }
[DefaultValue("3015")]
public string Kategori { get; set; }
public string ParaBirimi { get; set; }
public string ÜrünAd { get; set; }
public string Acıklama { get; set; }
public string PiyasaFiyat { get; set; }
public string TrendyolFiyat { get; set; }
public string StokAdedi { get; set; }
public string StokKodu { get; set; }
public string KDVOranı { get; set; }
public string Desi { get; set; }
public string GörselLink { get; set; }
public string SevkiyatSüresi { get; set; }
public string WebColor { get; set; }
public string AraçMarka { get; set; }
public string AraçModel { get; set; }
}
}
<file_sep>/School_Project/Migrations/20210413225116_sp1.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace School_Project.Migrations
{
public partial class sp1 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Barkod = table.Column<string>(type: "nvarchar(max)", nullable: true),
ModelKod = table.Column<string>(type: "nvarchar(max)", nullable: true),
Marka = table.Column<string>(type: "nvarchar(max)", nullable: true),
Kategori = table.Column<string>(type: "nvarchar(max)", nullable: true),
ParaBirimi = table.Column<string>(type: "nvarchar(max)", nullable: true),
ÜrünAd = table.Column<string>(type: "nvarchar(max)", nullable: true),
Acıklama = table.Column<string>(type: "nvarchar(max)", nullable: true),
PiyasaFiyat = table.Column<string>(type: "nvarchar(max)", nullable: true),
TrendyolFiyat = table.Column<string>(type: "nvarchar(max)", nullable: true),
StokAdedi = table.Column<string>(type: "nvarchar(max)", nullable: true),
StokKodu = table.Column<string>(type: "nvarchar(max)", nullable: true),
KDVOranı = table.Column<string>(type: "nvarchar(max)", nullable: true),
Desi = table.Column<string>(type: "nvarchar(max)", nullable: true),
GörselLink = table.Column<string>(type: "nvarchar(max)", nullable: true),
SevkiyatSüresi = table.Column<string>(type: "nvarchar(max)", nullable: true),
WebColor = table.Column<string>(type: "nvarchar(max)", nullable: true),
AraçMarka = table.Column<string>(type: "nvarchar(max)", nullable: true),
AraçModel = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.ID);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Products");
}
}
}
<file_sep>/School_Project/DataAccesLayer/DbServices/IGenericRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace School_Project.DataAccesLayer
{
public interface IGenericRepository<T> where T: class, new()
{
void Add(T entity);
void Update(T entity);
void Remove(T entity);
List<T> GetList();
T Get(int id);
}
}
| 332801d9926296408500d062ba643d5364743726 | [
"C#"
] | 6 | C# | demireleren877/School_Project | c492a48934576794886567e25c50cab2c746177c | 67a5f9becaaf8dbeae675dd1aea1e41206e132bf |
refs/heads/master | <file_sep>#pragma once
#include <iostream> //for cin/cout
#include <cmath> // for math stuff
#include <conio.h> // for _getch()
#include <vector>
#include <fstream> //for file I/O
#include "Vehicle.h"
#include <string>
#include "utilityFunctions.h"
//#include "matlabFunctions.h"
#include "generateVehicle.h"
std::vector<std::vector<double> > simulation1(Vehicle testVehicle, double _dt, double _rho = 1);
std::vector<std::vector<double> > simulation3(Vehicle testVehicle, double _dt, double _rho);
std::vector<std::vector<double> > simulation4(Vehicle testVehicle, double _dt, double _rho, double _timeToFullThrottle = .2);
void functionalityDemonstration();
<file_sep>#include "Vehicle.h"
/*NOTE: Using 2001 Subaru legacy outback wagon, LL bean eddition for testing
Cd = .32
A = 23.4 ft^2 = 2.1739 m^2
mass = 3715 lbs = 1685.1 kg
Gear Ratios:
1st 2.785
2nd 1.545
3rd 1.000
4th 0.697
Rev 2.272
Diff 4.11
Tires: 225/60R16 98H SL
wheelRadius = 0.33782 m
*/
double Vehicle::transEff = .7;
Vehicle::Vehicle() {}
//constructor for sim 1
Vehicle::Vehicle(double _mass, double _Cdrag, double _fDrive)
{
mass = _mass;
Cdrag = _Cdrag;
fDrive = _fDrive;
Crr = 30 * Cdrag;
frontArea = 2; // Used for simulation 1 where the .5 coefficient must be neutralized.
simulationFlag = 1;
}
//constructor for sim 2
Vehicle::Vehicle(double _mass, double _Cdrag, double _fDrive, double _frontalArea)
{
mass = _mass;
Cdrag = _Cdrag;
fDrive = _fDrive;
frontArea = _frontalArea;
Crr = 30 * Cdrag;
simulationFlag = 2;
}
//constructor for sim 3
Vehicle::Vehicle(double _mass, double _Cdrag, double _fDrive, double _frontalArea, double _fBrake)
{
mass = _mass;
Cdrag = _Cdrag;
fDrive = _fDrive;
frontArea = _frontalArea;
fBrake = _fBrake;
Crr = 30 * Cdrag;
simulationFlag = 3;
}
//constructor for sim 4
Vehicle::Vehicle(double _mass, double _Cdrag, double _frontalArea, std::vector<double> _gearRatios, double _diffRatio, double _wheelRadius,
std::vector<double> _revMap, std::vector<double> _torqueMap)
{
mass = _mass;
Cdrag = _Cdrag;
frontArea = _frontalArea;
Crr = 30 * Cdrag;
diffRatio = _diffRatio;
wheelRadius = _wheelRadius;
gearRatios = _gearRatios;
revMap = _revMap;
torqueMap = _torqueMap;
currGear = 1;
simulationFlag = 4;
peakTorqueIndex = findPeakTorque();
}
//Honestly not 100% sure what this does.
Vehicle::~Vehicle() {}
//Returns the next velocity after dt time has passed, based on current velocity
double Vehicle::velocity(double _currVelocity, double dt, double *rho, double throttle)
{
double acceleration;
currVelocity = _currVelocity;
if (throttle == -1)
acceleration = accel(rho);
else
acceleration = accel(rho, throttle);
return currVelocity + dt * acceleration;
}
double Vehicle::brake(double _currVelocity, double dt, double *rho)
{
double acceleration;
currVelocity = _currVelocity;
acceleration = deccel(rho);
return currVelocity + dt * acceleration;
}
//calculates the acceleartion based on the sum of the forces on the car and the mass
double Vehicle::accel(double *rho, double throttle)
{
double fSum;
if (throttle == -1)
fSum = fDrive + fDrag(rho) + Frr();
else
{
fSum = engineDriveForce(throttle) + fDrag(rho) + Frr();
shift();
}
return fSum / mass;
}
//calculates the force on the vehicle due to braking
double Vehicle::deccel(double *rho)
{
double fSum;
fSum = -fBrake + fDrag(rho) + Frr();
return fSum / mass;
}
//calculates the aerodynamic drag forces
double Vehicle::fDrag(double *rho)
{
return -0.5 * Cdrag * frontArea * (*rho) * std::pow(currVelocity, 2);
}
//calculates the rolling resistances
double Vehicle::Frr()
{
return -Crr * currVelocity;
}
//calculates the drive force based on throttle and torque
double Vehicle::engineDriveForce(double throttle)
{
return getTorque(throttle) * throttle * gearRatios[currGear-1] * diffRatio * transEff / wheelRadius;;
}
//figures out if the car should shift or not.
void Vehicle::shift()
{
double currentRPM, upshiftedRPM;
currentRPM = pubGetRPM();
//will do nothing if the current gear is equal to the number of gears in the gearbox
if (currGear >= gearRatios.size())
return;
//calculates the rpm value at the current speed if the gear were increased to the next gear
upshiftedRPM = currVelocity / wheelRadius *(60 / (2 * M_PI)) * gearRatios[currGear] * diffRatio;
if ((currentRPM - upshiftedRPM) / 2 >= (revMap[peakTorqueIndex] - upshiftedRPM))
{
++currGear;
if (currGear == 2)
std::cout << "Shifted to 2nd gear at " << currentRPM << " rpm." << std::endl;
else if (currGear == 3)
std::cout << "Shifted to 3rd gear at " << currentRPM << " rpm." << std::endl;
else
std::cout << "Shifted to " << currGear << "th gear at " << currentRPM << " rpm." << std::endl;
}
}
//calculates the current rpm based on current velocity and gear ratio.
double Vehicle::pubGetRPM()
{
double rpm;
rpm = currVelocity / wheelRadius *(60 / (2 * M_PI)) * gearRatios[currGear-1] * diffRatio;
if (rpm < 3000 && currGear == 1)
rpm = 3000;
if (rpm > revMap.back())
rpm = revMap.back();
return rpm;
}
//calculates torque based on current rpm and throttle position
double Vehicle::getTorque(double throttle)
{
double currRPM, currTorque;
int i = 0;
currRPM = pubGetRPM();
// does a linear search on the rpm vector in the torque to get the position of the current rpm on the torque curve
do
++i;
while (currRPM < revMap[i]);
//linear interpolation of current rpm on the torque curve
currTorque = torqueMap[i - 1] + (currRPM - revMap[i - 1])*(torqueMap[i] - torqueMap[i - 1]) / (revMap[i] - revMap[i - 1]);
return currTorque;
}
//finds the rpm value where peak torque is generated on the torque curve
int Vehicle::findPeakTorque()
{
int i = 0;
do
++i;
while (torqueMap[i] > torqueMap[i-1]);
return i - 1;
}
<file_sep>#pragma once
#include <cmath>
#include <iostream>
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
class Vehicle
{
public:
// Constructors
Vehicle();
Vehicle(double _mass, double _Cdrag, double _fDrive); //constructor for simulation 1
Vehicle(double _mass, double _Cdrag, double _fDrive, double _frontalArea); //constructor for simulation 2
Vehicle(double _mass, double _Cdrag, double _fDrive, double _frontalArea, double _fBrake); //constructor for simulation 3
Vehicle(double _mass, double _Cdrag, double _frontalArea,std::vector<double> _gearRatio, // constructor for simulation 4
double _diffRatios, double wheelRadius,std::vector<double> _revMap, std::vector<double> _torqueMap);
//public member functions
double velocity(double _currVelocity, double dt, double *rho, double throttle = -1);
double brake(double _currVelocity, double dt, double *rho);
double engineDriveForce(double throttle);
double getTorque(double throttle);
double pubGetRPM();
~Vehicle();
//public member variables
int simulationFlag;
private:
//Member private functions
double accel(double *rho, double throttle = -1);
double deccel(double *rho);
void shift(); //shifts if rpm range is ideal
double fDrag(double *rho); //returns the drag forces ascociated with air resistance
double Frr(); //returns the resistance ascociated with rolling
int findPeakTorque();
//Member private properties
double mass;
double Cdrag;
double Crr;
double currVelocity;
double frontArea;
double fDrive;
double fBrake;
std::vector<double> gearRatios;
std::vector<double> revMap;
std::vector<double> torqueMap;
double diffRatio;
double wheelRadius;
int currGear;
int peakTorqueIndex;
static double transEff;
};
<file_sep>#include "main.h"
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
const double msToMph(2.2368);
int main()
{
std::vector<std::vector<double> > test1Data, test2Data, test3Data, test4Data, testData;
std::vector<double> time, vel, gearRatios= { 2.785, 1.545, 1, .697 };
std::string fileName;
double rho, dt, timeToFullThrottle;
int simulationFlag;
char yesNo;
Vehicle simulationVehicle;
//gearRatios.assign(ratioValues, ratioValues + sizeof(ratioValues) / sizeof(double));
//prompts user to chose a simulation and then prompts them for each required input.
do
{
std::cout << "Which simulation would you like to run? (1, 2, 3, 4)" << std::endl;
simulationFlag = util::getSanitizedInput<int>(1,4);
std::cout << std::endl;
if (simulationFlag == 99)
{
functionalityDemonstration();
std::cout << "Demonstration simulations complete, press any key to quit";
_getch();
return 0;
}
std::cout << std::endl << "Enter time step (dt): ";
dt = util::getSanitizedInput<double>();
std::cout << std::endl;
if (simulationFlag != 1)
{
std::cout << std::endl << "Enter air density rho (kg/m^3): ";
rho = util::getSanitizedInput<double>();
}
//creates a test vehicle based on simulation value entered
simulationVehicle = generateVehicle(simulationFlag);
//based on the simulation value entered, runs the corrisponding simulation
switch (simulationFlag)
{
case 1:
testData = simulation1(simulationVehicle, dt);
break;
case 2:
testData = simulation1(simulationVehicle, dt, rho);
break;
case 3:
testData = simulation3(simulationVehicle, dt, rho);
break;
case 4:
std::cout << std::endl << "Enter time to full throttle: ";
timeToFullThrottle = util::getSanitizedInput<double>();
std::cout << std::endl;
testData = simulation4(simulationVehicle, dt, rho, timeToFullThrottle);
break;
}
//promps user if they want to save the simulation data
if (util::yesNo("Write results to file?"))
{
std::cout << std::endl << "Enter name of data file: ";
fileName = util::getSanitizedInput<std::string>();
util::outputData(testData, fileName);
}
} while (util::yesNo("Run another simulation?")); //loop back through code and run another simulation.
std::cout << "Simulations complete, press any key to quit";
_getch();
return 0;
}
std::vector<std::vector<double> > simulation1(Vehicle testVehicle, double _dt, double _rho)
{
std::vector<std::vector<double> > data;
std::vector<double> time, vel;
double zeroToSixtyTime(0);
//Sets initial time and velocity.
time.push_back(0);
vel.push_back(0);
std::cout << "-------------------------------Simulation 1 and 2-------------------------------" << std::endl;
do
{
vel.push_back(testVehicle.velocity(vel.back(), _dt, &_rho));
time.push_back(time.back() + _dt);
if (vel.back() * msToMph >= 60 && zeroToSixtyTime == 0)
zeroToSixtyTime = time.back();
} while ((vel.back() - vel.rbegin()[1])/_dt > .0001); // keep calculating velocity until the acceleration is less than .0001 (essentially at max velocity)
std::cout << "Your maximum velocity was " << vel.back() << " m/s (" << vel.back() * msToMph << " mph)\n";
std::cout << "Time to reach maximum velocity: " << time.back() << "seconds." << std::endl;
std::cout << "0 - 60 time: " << zeroToSixtyTime << " seconds." << std::endl;
std::cout << "--------------------------------------------------------------------------------" << std::endl << std::endl;
data.push_back(time);
data.push_back(vel);
return data;
}
std::vector<std::vector<double> > simulation3(Vehicle testVehicle, double _dt, double _rho)
{
std::vector<std::vector<double> > data;
std::vector<double> time, vel;
double maxSpeed, timeMaxSpeed, zeroToSixtyTime(0);
//Sets initial time and velocity.
time.push_back(0);
vel.push_back(0);
std::cout << "----------------------------------Simulation 3----------------------------------" << std::endl;
do
{
vel.push_back(testVehicle.velocity(vel.back(), _dt, &_rho));
time.push_back(time.back() + _dt);
if (vel.back() * msToMph >= 60 && zeroToSixtyTime == 0)
zeroToSixtyTime = time.back();
} while ((vel.back() - vel.rbegin()[1]) / _dt > .0001); // keep calculating velocity until the acceleration is less than .0001 (essentially at max velocity)
maxSpeed = vel.back();
timeMaxSpeed = time.back();
do
{
vel.push_back(testVehicle.brake(vel.back(), _dt, &_rho));
time.push_back(time.back() + _dt);
} while (vel.back() > 0);
if (vel.back() < 0)
vel.back() = 0;
std::cout << "Your maximum velocity was " << maxSpeed << " m/s (" << maxSpeed * msToMph << " mph)\n";
std::cout << "Time to reach maximum velocity: " << time.back() << "seconds." << std::endl;
std::cout << "Time to come to a complete stop: " << time.back() - timeMaxSpeed << "seconds." << std::endl;
std::cout << "0 - 60 time: " << zeroToSixtyTime << " seconds." << std::endl;
std::cout << "--------------------------------------------------------------------------------" << std::endl << std::endl;
data.push_back(time);
data.push_back(vel);
return data;
}
std::vector<std::vector<double> > simulation4(Vehicle testVehicle, double _dt, double _rho, double _timeToFullThrottle)
{
std::vector<std::vector<double> > data;
std::vector<double> time, vel, rpm, force, torque;
double maxSpeed, timeMaxSpeed, throttle(0), zeroToSixtyTime(0);
const double timeToFullThrottle = _timeToFullThrottle;
//Sets initial values
time.push_back(_dt);
vel.push_back(0);
rpm.push_back(0);
force.push_back(0);
torque.push_back(0);
std::cout << "----------------------------------Simulation 4----------------------------------" << std::endl;
do
{
throttle = time.back()/timeToFullThrottle;
vel.push_back(testVehicle.velocity(vel.back(), _dt, &_rho, throttle));
time.push_back(time.back() + _dt);
if (vel.back() * msToMph >= 60 && zeroToSixtyTime == 0)
zeroToSixtyTime = time.back();
rpm.push_back(testVehicle.pubGetRPM());
force.push_back(testVehicle.engineDriveForce(throttle));
torque.push_back(testVehicle.getTorque(throttle));
} while (time.back() < timeToFullThrottle);
do
{
vel.push_back(testVehicle.velocity(vel.back(), _dt, &_rho, throttle));
time.push_back(time.back() + _dt);
if (vel.back() * msToMph >= 60 && zeroToSixtyTime == 0)
zeroToSixtyTime = time.back();
rpm.push_back(testVehicle.pubGetRPM());
force.push_back(testVehicle.engineDriveForce(throttle));
torque.push_back(testVehicle.getTorque(throttle));
} while ((vel.back() - vel.rbegin()[1]) / _dt > .1); // keep calculating velocity until the acceleration is less than .01 (essentially at max velocity)
std::cout << std::endl << "Your maximum velocity was " << vel.back() << " m/s (" << vel.back() * msToMph << " mph)" << std::endl;
std::cout << "Time to reach maximum throttle position: " << timeToFullThrottle << " seconds." << std::endl;
std::cout << "Time to reach maximum velocity: " << time.back() << " seconds." << std::endl;
std::cout << "0 - 60 time: " << zeroToSixtyTime << " seconds." << std::endl;
std::cout << "--------------------------------------------------------------------------------" << std::endl << std::endl;
data.push_back(time);
data.push_back(vel);
data.push_back(rpm);
data.push_back(force);
data.push_back(torque);
return data;
}
void functionalityDemonstration()
{
/*NOTE: Using 2001 Subaru legacy outback wagon, LL bean eddition for default simulation
Cd = .32
A = 23.4 ft^2 = 2.1739 m^2
mass = 3715 lbs = 1685.1 kg
Drive force ~ 1500 N
Braking force ~ 7700 N
Gear Ratios:
1st 2.785
2nd 1.545
3rd 1.000
4th 0.697
Rev 2.272
Diff 4.11
Tires: 225/60R16 98H SL
wheelRadius = 0.33782 m
RPM = { 1200, 1600, 2000, 2400, 2800, 3200, 3600, 4000, 4400, 4800, 5200, 5600, 6000, 6400, 6800 };
torque = { 240 , 250 , 260 , 270 , 280 , 290 , 300 , 305 , 310 , 305 , 295 , 285 , 280 , 270 , 260 };
*/
std::vector<std::vector<double> > test1Data, test2Data, test3Data, test4Data;
std::vector<double> revMap = { 1200, 1600, 2000, 2400, 2800, 3200, 3600, 4000, 4400, 4800, 5200, 5600, 6000, 6400, 6800 };
std::vector<double> torqueMap = { 240, 250, 260, 270, 280, 290, 300, 305, 310, 305, 295, 285, 280, 270, 260 };
std::vector<double> gearRatios = { 2.785, 1.545, 1, .697 };
double rho(1.2041), dt(.001), mass(1685.1), Cdrag(.32), driveForce(1700), frontArea(2.1739), brakingForce(7700), diffRatio(4.11), wheelRadius(.33782);
//create vehicle objects for each simulation
Vehicle SubaruSim1(mass, Cdrag, driveForce);
Vehicle SubaruSim2(mass, Cdrag, driveForce, frontArea);
Vehicle SubaruSim3(mass, Cdrag, driveForce, frontArea, brakingForce);
Vehicle SubaruSim4(mass, Cdrag, frontArea, gearRatios, diffRatio, wheelRadius, revMap, torqueMap);
//Run simulations
test1Data = simulation1(SubaruSim1, dt);
test2Data = simulation1(SubaruSim2, dt, rho);
test3Data = simulation3(SubaruSim3, dt, rho);
test4Data = simulation4(SubaruSim4, dt, rho);
//Output data for matlab
util::outputData(test1Data, "simulation_1_example_data");
util::outputData(test2Data, "simulation_2_example_data");
util::outputData(test3Data, "simulation_3_example_data");
util::outputData(test4Data, "simulation_4_example_data");
}
<file_sep>#include "utilityFunctions.h"
namespace util
{
//simple yes/no
bool yesNo(std::string promptText)
{
char inputChar;
std::cout << std::endl << promptText << " (Y/N) : ";
inputChar = util::getSanitizedInput<char>();
while ((inputChar != 'Y' && inputChar != 'N') && (inputChar != 'y' && inputChar != 'n'))
{
std::cout << "Try again. Enter 'Y' for yes, and 'N' for no.\nEnter 'Y' or 'N' : ";
inputChar = util::getSanitizedInput<char>();
}
if (inputChar == 'Y' || inputChar == 'y')
return true;
else
return false;
}
}<file_sep>#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <climits>
typedef enum {
NUMERIC,
NON_NUMERIC
} datatype_e;
namespace util
{
bool yesNo(std::string promptText);
//outputs a data matrix to the user's documents folder as a .dat file with the given filename
template<typename T, typename A>
void outputData(std::vector<std::vector<T, A> > const& vec, std::string _fileName)
{
std::ofstream outfile;
std::string filePath = getenv("USERPROFILE");
filePath += "\\Documents\\" + _fileName + ".dat";
// open file in write mode, overwriting if file exists.
//Note: this could lead to loss of data and should be dealt with.
outfile.open(filePath.c_str(), std::ios::out | std::ios::trunc);
if (outfile.is_open())
{
std::cout << "Writing to file:" << std::endl;
// write each line to the output file as column vectors
// this is clunky, since it assumes that no vector has fewer elements than the first
for (int i = 0; i < vec[0].size(); ++i)
{
for (int j = 0; j < vec.size(); ++j)
{
outfile << vec[j][i];
if (j < vec.size() - 1)
outfile << ',';
}
outfile << std::endl;
}
outfile << std::endl;
outfile.close();
}//if (outfile.is_open())
std::cout << "Sucsess writing data to:" << std::endl << filePath << std::endl << std::endl;
}
//gets input from cin and will loop until the input is of the specified type, rejecting invalid inputs.
template <typename T>
T getSanitizedInput()
{
T terminalInput;
bool failedInput = true;
do
{
std::cin >> terminalInput;
//checks if the stream encountered a fatal error (ie. a char was entered)
if (std::cin.fail())
std::cin.clear(); // clears the error
// clear out any additional input from the stream until the end of the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// if the ignore cleared out more than one character, assume that bad data was passed to the input stream
if (std::cin.gcount() > 1)
std::cout << "Error: invalid data entered." << std::endl << "Re-enter value as (" << typeid(T).name() << "): ";
else
failedInput = false;
} while (failedInput);
return terminalInput;
}
template <typename T>
T getSanitizedInput(double lBound, double uBound)
{
T terminalInput;
bool failedInput = true;
do
{
std::cin >> terminalInput;
//checks if the stream encountered a fatal error (ie. a char was entered)
if (std::cin.fail())
std::cin.clear(); // clears the error
// clear out any additional input from the stream until the end of the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// if the ignore cleared out more than one character, assume that bad data was passed to the input stream
if (std::cin.gcount() > 1)
std::cout << "Error: invalid data entered." << std::endl << "Re-enter value as (" << typeid(T).name() << "): ";
else
{
if (terminalInput <= uBound && terminalInput >= lBound)
failedInput = false;
else
std::cout << "Error: data entered outside of given bounds." << std::endl << "Re-enter a value between ( " << lBound << " , " << uBound << " ): ";
}
} while (failedInput);
return terminalInput;
}
} // end of the util:: namespace
<file_sep>#include "generateVehicle.h"
// prompts user for inputs for all vehicle parameters based on the chosen simulation and returns a vehicle object with the input parameters.
Vehicle generateVehicle(int simulationFlag)
{
//Variable declarations
int loopCount;
double mass, Cdrag, frontArea, diffRatio, wheelRadius, valueHold, maxRpm, driveForce, brakingForce;
std::vector<double> gearRatios, revMap, torqueMap;
Vehicle returnVehicle;
std::cout << std::endl << "--------------------------Enter data for simulation " << simulationFlag << "---------------------------" << std::endl;
std::cout << std::endl << "Enter mass of Vehicle (kg): ";
mass = util::getSanitizedInput<double>();
std::cout << std::endl << "Enter Cd: ";
Cdrag =util::getSanitizedInput<double>();
//Prompts user for a drive force unless simulation 4 was selected
if (simulationFlag != 4)
{
std::cout << std::endl << "Enter drive force (N): ";
driveForce = util::getSanitizedInput<double>();
}
//Vehicle creation is complete if simulation 1 was selected. Returns vehicle.
if (simulationFlag == 1)
{
std::cout << std::endl << "Created vehicle for simulation " << simulationFlag << ". Press any key to continue" << std::endl << std::endl;
_getch();
return Vehicle(mass, Cdrag, driveForce);
}
std::cout << std::endl << "Enter front area (m^2): ";
frontArea = util::getSanitizedInput<double>();
//Vehicle creation is complete if simulation 2 was selected. Returns vehicle.
if (simulationFlag == 2)
{
std::cout << std::endl << "Created vehicle for simulation " << simulationFlag << ". Press any key to continue" << std::endl << std::endl;
_getch();
return Vehicle(mass, Cdrag, driveForce, frontArea);
}
//Vehicle creation is complete if simulation 3 was selected once a braking force is input. Returns vehicle.
if (simulationFlag == 3)
{
std::cout << std::endl << "Enter braking force (N): ";
brakingForce = util::getSanitizedInput<double>();
std::cout << std::endl << "Created vehicle for simulation " << simulationFlag << ". Press any key to continue" << std::endl << std::endl;
_getch();
return Vehicle(mass, Cdrag, driveForce,frontArea,brakingForce);
}
std::cout << std::endl << "Enter wheel radius (m): ";
wheelRadius = util::getSanitizedInput<double>();
std::cout << std::endl << "Enter differential ratio: ";
diffRatio = util::getSanitizedInput<double>();
//Prompts user if they want to use default transmission values
//Default transmission values are from a 2001 subaru outback H6
if (util::yesNo("Use default values for transmission?"))
{
gearRatios = { 2.785, 1.545, 1, .697 };
std::cout << std::endl;
std::cout << "--Default Gear Ratios--" << std::endl << std::endl;
std::cout << " Gear | Ratio" << std::endl;
std::cout << "_____________" << std::endl;
for (int i = 0; i < gearRatios.size(); ++i)
{
std::cout << std::setprecision(4);
switch (i)
{
case 0:
std::cout << " 1st | " << gearRatios[i] << std::endl;
break;
case 1:
std::cout << " 2nd | " << gearRatios[i] << std::endl;
break;
case 2:
std::cout << " 3rd | " << gearRatios[i] << std::endl;
break;
default:
std::cout << " " << i+1 << "th | " << gearRatios[i] << std::endl;
break;
}
}
}
else
{
std::cout << "Enter number of gears: ";
loopCount = util::getSanitizedInput<int>();
gearRatios.resize(loopCount);
//Prompts user to enter
for (int i = 0; i < loopCount; ++i)
{
std::cout << "Enter gear ratio for gear " << (i + 1) << ": ";
if (i == 0)
valueHold = util::getSanitizedInput<double>();
else
{
//This doesn't quite work. It should make sure that the user enters in a smaller gear ratio than the one before it.
do
valueHold = util::getSanitizedInput<double>();
while (valueHold >= gearRatios[i-1]);
}
gearRatios[i] = valueHold;
}
} //if (util::yesNo("Use default values for transmission?"))
//Prompts user if they want to use the default torque table
//Default torque and RPM values are from a 2001 subaru outback H6
if (util::yesNo("Use default values for torque curve?"))
{
revMap = { 1200, 1600, 2000, 2400, 2800, 3200, 3600, 4000, 4400, 4800, 5200, 5600, 6000, 6400, 6800 };
torqueMap = { 240, 250, 260, 270, 280, 290, 300, 305, 310, 305, 295, 285, 280, 270, 260 };
std::cout << std::endl;
std::cout << "-Default Torque Table--" << std::endl << std::endl;
std::cout << " # | RPM | Tq " << std::endl;
std::cout << "___________________" << std::endl;
std::cout << std::left;
//Prints out the formatted default torque table to the console
for (int i = 0; i < revMap.size(); ++i)
{
std::cout << std::setw(3) << i + 1 << "| " << std::setw(5) << revMap[i] << "| " << std::setw(5) << torqueMap[i] << std::endl;
}
std::cout << "___________________" << std::endl << std::endl;
}
else
{
std::cout << std::endl << "Enter maximum RPM as an integer: ";
maxRpm = util::getSanitizedInput<double>();
std::cout << std::endl << "-----Torque table input-----" << std::endl;
std::cout << "Enter RPM values in ascending order, Torques in N-m" << std::endl << std::endl;
loopCount = 1;
do
{
std::cout << "Entry #: " << loopCount << std::endl;
std::cout << "RPM(" << loopCount << ") = ";
//Prompts user for RPM and torque values until the entered RPM excedes the maximum RPM value.
if (revMap.size() > 0)
{
do
valueHold = util::getSanitizedInput<double>();
while (valueHold <= revMap.back());
}
else
valueHold = util::getSanitizedInput<double>();
revMap.push_back(valueHold);
std::cout << "Torque(" << loopCount << ") = ";
torqueMap.push_back(util::getSanitizedInput<double>());
std::cout << std::endl;
++loopCount;
} while (revMap.back() < maxRpm);
}
std::cout << std::endl << "Created vehicle for simulation " << simulationFlag <<". Press any key to continue" << std::endl << std::endl;
_getch();
return Vehicle(mass, Cdrag, frontArea, gearRatios, diffRatio, wheelRadius, revMap, torqueMap);
}
| 8ecc10c006c6a623e68639a62bca705d82192d13 | [
"C++"
] | 7 | C++ | cmjscott/NumotFinal | 6724f7f1b874e1191694b41f5849011e138cbb23 | d609986911206b332088b741df367398f436765d |
refs/heads/master | <repo_name>danielkim107/myshop<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
firebase: {
apiKey: "AIzaSyDALew2HvGPQ99Y4DPFlN0Y0h3PaSAUr3s",
authDomain: "myshop-ab3ac.firebaseapp.com",
databaseURL: "https://myshop-ab3ac.firebaseio.com",
projectId: "myshop-ab3ac",
storageBucket: "myshop-ab3ac.appspot.com",
messagingSenderId: "1080580665260",
appId: "1:1080580665260:web:65ecdf8b8931ce3cb85409",
measurementId: "G-VCT605R01N"
}
};
| 7319930c6b85e8b28e96313ae4e4e14b17402e75 | [
"TypeScript"
] | 1 | TypeScript | danielkim107/myshop | 4cf4fb62c62ff239f01af1b15b6aed8b77e94152 | e6b326546e913eeef24b3ec5ccd7bc1164e36e42 |
refs/heads/master | <repo_name>zichy/phutaba<file_sep>/static/js/hidethreads.js
/* requires jquery: jQuery.noConflict() */
/* called when loading a board-page: read list of hidden threads from the cookie and hide them */
function hideThreads(bid, $j) {
hidThreads = $j.cookie('hidden_' + bid);
if (hidThreads != null)
hidThreads = JSON.parse(hidThreads);
if (hidThreads == null)
return;
for (i = 0; i < hidThreads.length; i++) {
thread = $j('thread_' + hidThreads[i]);
if (thread == null)
continue;
$j("#thread_" + hidThreads[i]).hide();
$j("#thread_" + hidThreads[i]).after(getHiddenHTML(hidThreads[i], bid));
}
}
/* adds the thread id to the cookie */
function addHideThread(tid, bid, $j) {
hidThreads = $j.cookie('hidden_' + bid);
if (hidThreads != null)
hidThreads = JSON.parse(hidThreads);
if (hidThreads == null)
hidThreads = [];
for (i = 0; i < hidThreads.length; i++)
if (hidThreads[i] == tid)
return;
hidThreads[hidThreads.length] = tid;
$j.cookie('hidden_' + bid, JSON.stringify(hidThreads), { expires: 7 });
}
/* deletes a thread id from the cookie */
function removeHideThread(tid, bid, $j) {
hidThreads = $j.cookie('hidden_' + bid);
if (hidThreads == null)
return;
hidThreads = JSON.parse(hidThreads);
for (i = 0; i < hidThreads.length; i++)
if (hidThreads[i] == tid) {
hidThreads.splice(i, 1);
i--;
}
$j.cookie('hidden_' + bid, JSON.stringify(hidThreads), { expires: 7 });
}
/* hides a single thread from the board page and adds HTML to display it again */
function hideThread(tid, bid, $j) {
hidThreads = $j.cookie('hidden_' + bid);
if (hidThreads != null) {
hidThreads = JSON.parse(hidThreads);
for (i = 0; i < hidThreads.length; i++)
if (hidThreads[i] == tid)
return;
}
$j("#thread_" + tid).hide();
$j("#thread_" + tid).after(getHiddenHTML(tid, bid));
addHideThread(tid, bid, $j);
};
/* displays the thread again after it was hidden */
function showThread(tid, bid, $j) {
$j('.show_' + tid).hide();
$j('.show_' + tid).remove();
$j("#thread_" + tid).show();
removeHideThread(tid, bid, $j);
};
/* create HTML for diplaying a hidden thread */
function getHiddenHTML(tid, bid) {
return '<div class="show_' + tid + ' togglethread">'
+ '<a class="hide" onclick="showThread(\'' + tid + '\', \'' + bid + '\', $j);">'
+ '<img src="/img/icons/show.png" width="16" height="16" alt="Thread ' + tid + ' einblenden" />'
+ ' <strong>Thread ' + tid + '</strong> einblenden</a></div>';
};
| 53b17cefcaa0846ac58068ff0588e597c1116e78 | [
"JavaScript"
] | 1 | JavaScript | zichy/phutaba | 260b4b98bf1796a5eaee65956a741cefbdae360d | 4b785e783da071aa9a5a132cd712b43b43075465 |
refs/heads/master | <repo_name>allisonhorst/Harry-Potter-aggression<file_sep>/harry_potter_aggression.R
#----------------
# Load packages
#----------------
library(RCurl)
library(dplyr)
library(tidyr)
library(stringr)
library(ggplot2)
library(grid)
library(Cairo)
#-------------------
# Helper functions
#-------------------
# Nice clean, stripped-down theme
theme_clean <- function(base_size=12, base_family="Source Sans Pro Light") {
ret <- theme_bw(base_size, base_family) +
theme(panel.background = element_rect(fill="#ffffff", colour=NA),
axis.title.x=element_text(vjust=-0.2), axis.title.y=element_text(vjust=1.5),
title=element_text(vjust=1.2, family="Source Sans Pro Semibold"),
panel.border = element_blank(), axis.line=element_blank(),
panel.grid=element_blank(), axis.ticks=element_blank(),
legend.position="bottom",
axis.title=element_text(size=rel(0.8), family="Source Sans Pro Semibold"),
strip.text=element_text(size=rel(1), family="Source Sans Pro Semibold"),
strip.background=element_rect(fill="#ffffff", colour=NA),
panel.margin.y=unit(1.5, "lines"))
ret
}
# Append spaces to labels to fake right margin/padding
add.spaces <- function(x) {
return(as.character(paste0(x, " ")))
}
# Select all the text for a specific book
get_chunk <- function(x) {
# The book name passes as a number, not text...
book.name <- nice.books[x]
filter(full.text, book==book.name)$text
}
# Count the number of times a name appears in a vector of text
count.name <- function(x, regex) {
grepl(regex, x)
}
# Make the book names from the scraped full text match the aggression data
clean.book.names <- function(x) {
ret <- gsub("sorcerers", "sorcerer's", tolower(sub("Harry Potter and ", "", x)))
ret
}
#------------
# Load data
#------------
# URL to the fantastic data
data.url <- "https://docs.google.com/spreadsheets/d/1heSMqYzYnL5bS0xiZ2waReUMLKIxHce5MMsQxzhgaA8/export?format=csv&gid=384008866"
# Book names
nice.books <- c("The Sorcerer's Stone", "The Chamber of Secrets",
"The Prisoner of Azkaban", "The Goblet of Fire",
"The Order of the Phoenix", "The Half-Blood Prince",
"The Deathly Hallows")
# Load and rearrange the data
hp <- read.csv(textConnection(getURL(data.url)), as.is=TRUE) %>%
select(1:13) %>% # Only get the first 13 columns
select(-c(g_e_m_n, evil, creature, tot)) %>% # Get rid of other columns
gather(book, aggressions, -c(Name, abb)) %>%
mutate(book = factor(book, levels=levels(book), labels=nice.books, ordered=TRUE),
book.rev = factor(book, levels=rev(levels(book)), ordered=TRUE))
# Load and clean full text from Harry Potter books
full.text <- read.csv("hp-corpus/hp-full.csv", stringsAsFactors=FALSE) %>%
mutate(text = tolower(text),
book = factor(clean.book.names(book),
levels=tolower(levels(hp$book)),
labels=levels(hp$book),
ordered=TRUE)) %>%
filter(text != "") %>% filter(text != "\n")
# Load search strings
searches <- read.csv("names_with_regex.csv", stringsAsFactors=FALSE) %>%
select(-c(abb, search))
# Calculate book length
num.paragraphs <- full.text %>% group_by(book) %>% summarize(paragraphs = n())
# Count all instances of each search string in each book (takes a while)
mentions <- hp %>%
left_join(searches, by="Name") %>%
rowwise() %>%
summarize(mentions = sum(sapply(get_chunk(book), FUN=count.name, regex=regex)),
Name = Name, book = book) %>%
mutate(book = factor(book, labels=nice.books, ordered=TRUE))
# Combine all the fancy new data
hp.full <- hp %>%
left_join(num.paragraphs, by="book") %>%
left_join(mentions, by=c("Name", "book")) %>%
mutate(agg.per.mention = ifelse(mentions == 0, 0, aggressions / mentions),
mentions.per.p = mentions / paragraphs,
agg.weighted = aggressions / mentions.per.p) %>%
filter(agg.per.mention < 1.1) %>%
filter(mentions > 10)
write.csv(select(hp.full, -book.rev),
file="harry_potter_aggression_full.csv", row.names=FALSE)
#------------
# Plot data
#------------
# Find most aggressive characters
hp.full %>% group_by(Name) %>% summarize(Aggressions = sum(aggressions)) %>%
arrange(desc(Aggressions)) %>% head(5) -> most.aggressive
# Rearrange data for plotting
plot.data <- hp.full %>%
filter(Name %in% most.aggressive$Name) %>%
mutate(Name = factor(Name, levels=most.aggressive$Name, ordered=TRUE),
Name.rev = factor(Name, levels=rev(levels(Name)),
labels=add.spaces(rev(levels(Name))), ordered=TRUE)) %>%
group_by(Name.rev, book.rev) %>%
summarize(aggr = sum(aggressions))
# Plot top 5
ggplot(plot.data, aes(x=book.rev, y=aggr, fill=Name.rev)) +
geom_bar(stat="identity", position="dodge") +
geom_hline(yintercept=seq(10, 50, by=10), colour="#ffffff", size=0.25) +
coord_flip() +
labs(x=NULL, y="Instances of aggression",
title="Most aggressive characters in the Harry Potter series") +
scale_fill_manual(values=c("#915944", "#9BAB9C", "#692521", "#CAAA17", "#B51616"),
guide=guide_legend(reverse=TRUE), name="") +
theme_clean() + theme(legend.key.size = unit(0.5, "lines")) -> nice.plot
# Save plot
ggsave(nice.plot, filename="images/top_5.png", width=7, height=5, units="in")
ggsave(nice.plot, filename="images/top_5.pdf", width=7, height=5, units="in",
device=cairo_pdf)
# Plot the characters that are most likely to be aggressive when mentioned
plot.data <- hp.full %>%
group_by(Name) %>%
summarize(aggr = mean(agg.per.mention)) %>%
arrange(desc(aggr)) %>% head(15) %>%
mutate(Name = factor(Name, levels=Name, ordered=TRUE),
Name.rev = factor(Name, level=rev(levels(Name)), ordered=TRUE)) %>%
select(-Name)
# Get the data from the original top 5 aggressive characters
original.plot <- hp.full %>%
filter(Name %in% most.aggressive$Name) %>%
mutate(Name = factor(Name, levels=most.aggressive$Name, ordered=TRUE),
Name.rev = factor(Name, levels=rev(levels(Name)),
labels=add.spaces(rev(levels(Name))), ordered=TRUE)) %>%
group_by(Name.rev) %>%
summarize(aggr = mean(agg.per.mention))
# Combine the two sets of data
combined.plot.data <- rbind(plot.data, original.plot)
# Plot!
ggplot(combined.plot.data, aes(x=Name.rev, y=aggr)) +
geom_bar(stat="identity", position="dodge") +
geom_hline(yintercept=seq(0.1, 0.5, by=0.1), colour="#ffffff", size=0.25) +
geom_vline(xintercept=15.5, colour="red", size=1) +
labs(x=NULL, y="Probability of being aggressive when mentioned") +
coord_flip() + theme_clean() -> full.plot
# Save plot
ggsave(full.plot, filename="images/adjusted.png", width=7, height=5, units="in")
ggsave(full.plot, filename="images/adjusted.pdf", width=7, height=5, units="in",
device=cairo_pdf)
<file_sep>/example_change.Rmd
---
title: "Untitled"
author: "<NAME>"
date: "10/6/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tidyverse)
```
YAY!
Yahoo!!! It's Wednesday!
HAHAHAHAA
<file_sep>/README.md
# Harry Potter Aggression Data
Someone collected [a fantastic dataset](https://docs.google.com/spreadsheets/d/1heSMqYzYnL5bS0xiZ2waReUMLKIxHce5MMsQxzhgaA8/edit#gid=1825799110) of all the instances where characters in the Harry Potter books acted aggressively, resulting in lots of interesting data visualizations. For instance, it appears that Harry is quite a sociopath, with more aggressive actions than any other character:

However, this does not account for the actual time the characters appear in the books. Harry is the subject of the series and the whole narrative centers around him, so it's logical that he would have the most aggressive actions.
We can adjust for "screen time" by counting the number of mentions each character gets in the series. I downloaded the [full text of the Harry Potter series](http://www.readfreeonline.net/Author/J._K._Rowling/Index.html) and did a crude search to find the number of paragraphs each character was mentioned in each book ([raw data](https://github.com/andrewheiss/Harry-Potter-aggression/blob/master/harry_potter_aggression_full.csv)). With this data on mentions, we can calculate the proportion of aggressive actions per mention in the books.
Using this data, the top 5 from before are far less aggressive. More obviously bad characters like boggarts, the basilisk, Nagini, and random death eaters are the most aggressive:

<file_sep>/hp_download.py
#!/usr/bin/env python3
# --------------
# Load modules
# --------------
from bs4 import BeautifulSoup
from collections import defaultdict
from random import choice
from time import sleep
import urllib.request
import csv
import logging
# --------------------------------
# Scraping and parsing functions
# --------------------------------
def get_url(url):
user_agents = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.25',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36'
]
agent = choice(user_agents)
wait = choice(range(10, 17))
response = urllib.request.Request(url, headers={'User-Agent': agent})
handler = urllib.request.urlopen(response).read()
sleep(wait)
return(handler)
def parse_chapter(url):
print("Parsing {0}".format(url))
try:
soup = BeautifulSoup(get_url(url))
except:
logging.warning("Error with {0}".format(url))
print("Error. Moving on.")
return(None)
content_section = soup.select('.ContentCss')
content_clean = [x.text.replace('\u3000', '') for x in content_section][0]
content = {}
content['content'] = content_clean.split('\n')
content['url'] = url
split_url = url.split('/')[-1].replace('.html', '').split('_')
content['book'] = ' '.join(split_url[0:-1])
content['chapter'] = split_url[-1]
return(content)
def convert_to_long(chapter):
long_results = defaultdict(dict)
entry_num = -1
for x in chapter['content']:
entry_num += 1
long_results[entry_num]['book'] = chapter['book']
long_results[entry_num]['chapter'] = chapter['chapter']
long_results[entry_num]['paragraph'] = entry_num + 1
long_results[entry_num]['text'] = x
return(long_results)
# --------------------------------
# Build a list of URLs to scrape
# --------------------------------
url_base = 'http://www.readfreeonline.net/OnlineBooks/'
specific_books = ['Harry_Potter_and_the_Sorcerers_Stone/Harry_Potter_and_the_Sorcerers_Stone_CHAPTER.html',
'Harry_Potter_and_The_Chamber_Of_Secrets/Harry_Potter_and_The_Chamber_Of_Secrets_CHAPTER.html',
'Harry_Potter_and_the_Prisoner_of_Azkaban/Harry_Potter_and_the_Prisoner_of_Azkaban_CHAPTER.html',
'Harry_Potter_and_the_Goblet_of_Fire/Harry_Potter_and_the_Goblet_of_Fire_CHAPTER.html',
'Harry_Potter_and_the_Order_of_the_Phoenix/Harry_Potter_and_the_Order_of_the_Phoenix_CHAPTER.html',
'Harry_Potter_and_the_Half-Blood_Prince/Harry_Potter_and_the_Half-Blood_Prince_CHAPTER.html',
'Harry_Potter_and_the_Deathly_Hallows/Harry_Potter_and_the_Deathly_Hallows_CHAPTER.html']
chapters = [17, 19, 22, 37, 38, 30, 37]
urls_to_parse = []
for i in range(0, len(specific_books)):
for j in range(1, chapters[i]+1):
final_url = url_base + specific_books[i].replace('CHAPTER', str(j))
urls_to_parse.append(final_url)
print(urls_to_parse.index('http://www.readfreeonline.net/OnlineBooks/Harry_Potter_and_the_Prisoner_of_Azkaban/Harry_Potter_and_the_Prisoner_of_Azkaban_20.html'))
# ---------------------------------------
# Scrape all those URLs and save to CSV
# ---------------------------------------
# # Set up log
# logging.basicConfig(filename='errors.log', filemode='w', level=logging.DEBUG,
# format='%(levelname)s %(asctime)s: %(message)s')
# logging.captureWarnings(True)
# csv_started = False
# fieldnames = ['book', 'chapter', 'paragraph', 'text']
# for url in urls_to_parse[0:2]:
# contents = convert_to_long(parse_chapter(url))
# for key, value in contents.items():
# w = csv.DictWriter(open('hp.csv', 'a'), fieldnames)
# if csv_started is False:
# w.writeheader()
# csv_started = True
# w.writerow(value)
| d2532237f5f1294edb91b7a41184e31d76052f4d | [
"Markdown",
"Python",
"R",
"RMarkdown"
] | 4 | R | allisonhorst/Harry-Potter-aggression | bf158a45052719be6f3a8bdf22d5797e167b3410 | e87b85e9f247a09390c946171d87333b68d3cc82 |
refs/heads/master | <file_sep>from sklearn.model_selection import train_test_split
from project.utils.TextExtractor import TextExtractor
from sklearn import metrics
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from time import sleep as slp
if int(input('0 to use save or 1 to extract')):
#extract text from dataset
textExtractor = TextExtractor(negativeText ='../dataset/neg', positiveText='../dataset/pos')
posText, negText = textExtractor.extractFromDataSet()
#bag of words preprocessed
allWords = list(textExtractor.dic.keys())
if int(input('0 to dont save extract or 1 to save')):
with open('saveparamssvm.txt', 'wb') as fp:
pickle.dump([allWords, posText, negText], fp)
else:
with open('saveparamssvm.txt', 'rb') as fp:
allWords, posText, negText = pickle.load(fp)
#All text and vectorizer
allText = posText+negText
vectorizer = TfidfVectorizer(vocabulary=allWords)
print(len(vectorizer.vocabulary))
slp(30)
#Vector of freq all text + tags (indexed)
X = vectorizer.fit_transform(allText)
y = ['positive' for i in range(len(posText))] + ['negative' for i in range(len(negText))]
#Training split 80/20
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0,test_size=0.2)
import pandas as pd
import numpy as np
# print(vectorizer.get_feature_names())
# print(X_train.todense())
#print(pd.DataFrame(X_train.toarray(),
#olumns=vectorizer.get_feature_n ames(),
#index=['doc1','doc2','doc3']))
#params
params = {'C':[1.0],
'kernel': ['linear', 'poly', 'rbf', 'sigmoid'],
#'gamma': [10^-7, 10]
'degree': [i for i in range(2,4)]
}
clf = GridSearchCV(SVC(random_state=0),param_grid= params, cv = 3)
clf.fit(X_train, y_train)
# print(clf.best_estimator_)
# print(clf.best_params_)
# preds = clf.predict(X_test)
# score = metrics.accuracy_score(y_test, preds)
# print(metrics.f1_score(y_test,preds,average='macro',pos_label="positive"))
# print(metrics.accuracy_score(y_test, preds))<file_sep>from sklearn.model_selection import train_test_split, RandomizedSearchCV
from project.utils.TextExtractor import TextExtractor
from sklearn import metrics
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
if int(input('0 to use save or 1 to extract')):
#extract text from dataset
textExtractor = TextExtractor(negativeText ='../dataset/neg', positiveText='../dataset/pos')
posText, negText = textExtractor.extractFromDataSet()
#bag of words preprocessed
allWords = list(textExtractor.dic.keys())
if int(input('0 to dont save extract or 1 to save')):
with open('saveparamsensemble.txt', 'wb') as fp:
pickle.dump([allWords, posText, negText], fp)
else:
with open('saveparamsensemble.txt', 'rb') as fp:
allWords, posText, negText = pickle.load(fp)
#All text and vectorizer
allText = posText+negText
vectorizer = TfidfVectorizer(vocabulary=allWords)
#Vector of freq all text + tags (indexed)
X = vectorizer.fit_transform(allText)
y = ['positive' for i in range(len(posText))] + ['negative' for i in range(len(negText))]
#Training split 80/20
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0,test_size=0.2)
random_grid = {
'max_features': [i for i in range(1,11)],
'min_samples_split':[i for i in range(2,50)],
'min_samples_leaf': [i for i in range(1,11)],
}
def randomSearchEnsemble(numberAttempts):
random_grid = {
'max_features': [i for i in range(1, 11)],
'min_samples_split': [i for i in range(2, 50)],
'min_samples_leaf': [i for i in range(1, 11)],
}
bestClf = RandomizedSearchCV(RandomForestClassifier(random_state=0),n_iter=10,param_distributions=random_grid, cv=5, n_jobs=-1,random_state=0)
bestClf.fit(X_train, y_train)
preds = bestClf.predict(X_test)
accuracy = metrics.accuracy_score(y_test, preds)
f1score = metrics.f1_score(y_test, preds, average='macro', pos_label="positive")
l = ["Initial State\nF1-score = %f\nAccuracy = %f\n\n"%(f1score,accuracy)]
for i in range(numberAttempts):
clfAttempt = RandomizedSearchCV(RandomForestClassifier(random_state=0, n_estimators=100),param_distributions=random_grid, cv=5)
clfAttempt.fit(X_train, y_train)
preds = clfAttempt.predict(X_test)
accuracyAttempt = metrics.accuracy_score(y_test, preds)
f1scoreAttempt = metrics.f1_score(y_test, preds, average='macro', pos_label="positive")
if f1scoreAttempt > f1score:
bestClf,f1score,accuracy = clfAttempt,f1scoreAttempt,accuracyAttempt
l.append("Good Attempt\nF1-score = %f\nAccuracy = %f\n\n"%(f1score,accuracy))
else:
l.append("Bad Attempt")
for i in l:
print(i)
print(bestClf.cv_results_)
print(bestClf.best_params_)
print(bestClf.best_estimator_)
return bestClf
randomSearchEnsemble(100)
# clf = RandomForestClassifier(n_estimators=10)
# clf.fit(X_train, y_train)
# preds = clf.predict(X_test)
# score = metrics.accuracy_score(y_test, preds)
# print(metrics.f1_score(y_test,preds,average='macro',pos_label="positive"))
# print(metrics.accuracy_score(y_test, preds))<file_sep>from sklearn.model_selection import train_test_split
from project.utils.TextExtractor import TextExtractor
#Split data into train and test sets
from sklearn import metrics
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.tree import DecisionTreeClassifier
from sklearn.externals.six import StringIO
from IPython.display import Image
from sklearn.tree import export_graphviz
import pydotplus
if int(input('0 to use save or 1 to extract')):
#extract text from dataset
textExtractor = TextExtractor(negativeText ='../dataset/neg', positiveText='../dataset/pos')
posText, negText = textExtractor.extractFromDataSet()
#bag of words preprocessed
allWords = list(textExtractor.dic.keys())
if int(input('0 to dont save extract or 1 to save')):
with open('saveparamsdecisiontree.txt', 'wb') as fp:
pickle.dump([allWords, posText, negText], fp)
else:
with open('saveparamsdecisiontree.txt', 'rb') as fp:
allWords, posText, negText = pickle.load(fp)
#All text and vectorizer
allText = posText+negText
vectorizer = TfidfVectorizer(vocabulary=allWords)
#KNN
#Vector of freq all text + tags (indexed)
X = vectorizer.fit_transform(allText)
y = ['positive' for i in range(len(posText))] + ['negative' for i in range(len(negText))]
#Training split 80/20
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0,test_size=0.2)
#Tunning
from sklearn.model_selection import GridSearchCV
tree_param = {'min_samples_split':[i for i in range(2,50)],
'min_samples_leaf': [i*0.1 for i in range(1,6)],
'max_features': [i*0.1 for i in range(1,11)]}
#Decision Tree
clf = GridSearchCV(DecisionTreeClassifier(random_state=0), tree_param, cv = 3, n_jobs=8)
clf = clf.fit(X_train, y_train)
preds = clf.predict(X_test)
score = metrics.accuracy_score(y_test, preds)
print(metrics.f1_score(y_test,preds,average='macro',pos_label="positive"))
print(metrics.accuracy_score(y_test, preds))
# dot_data = StringIO()
# export_graphviz(clf, out_file=dot_data,
# filled=True, rounded=True,
# special_characters=True)
# graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
# Image(graph.create_png())
print(clf.best_estimator_)
print(clf.best_params_)
print(clf.cv_results_)<file_sep>from sklearn.model_selection import train_test_split
from project.utils.TextExtractor import TextExtractor
from sklearn import metrics
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
if int(input('0 to use save or 1 to extract')):
#extract text from dataset
textExtractor = TextExtractor(negativeText ='../dataset/neg', positiveText='../dataset/pos')
posText, negText = textExtractor.extractFromDataSet()
#bag of words preprocessed
allWords = list(textExtractor.dic.keys())
if int(input('0 to dont save extract or 1 to save')):
with open('saveparamsneuralnetwork.txt', 'wb') as fp:
pickle.dump([allWords, posText, negText], fp)
else:
with open('saveparamsneuralnetwork.txt', 'rb') as fp:
allWords, posText, negText = pickle.load(fp)
#All text and vectorizer
allText = posText+negText
vectorizer = TfidfVectorizer(vocabulary=allWords)
#Vector of freq all text + tags (indexed)
X = vectorizer.fit_transform(allText)
y = ['positive' for i in range(len(posText))] + ['negative' for i in range(len(negText))]
#Training split 80/20
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0,test_size=0.2)
clfnw = MLPClassifier(activation='tanh', alpha=1e-07, batch_size='auto',
beta_1=0.9, beta_2=0.999, early_stopping=True,
epsilon=1e-08, hidden_layer_sizes=(1,100),
learning_rate='constant', learning_rate_init=0.001,
max_iter=500, momentum=0.8, n_iter_no_change=10,
nesterovs_momentum=True, power_t=0.5, random_state=1,
shuffle=True, solver='sgd', tol=0.0001,
validation_fraction=0.1, verbose=False, warm_start=False)
print("PRE TUNNING")
clfnw.fit(X_train,y_train)
preds = clfnw.predict(X_test)
print(metrics.accuracy_score(y_test, preds))
#Tunning
from sklearn.model_selection import GridSearchCV
parameter_space = {
# 'alpha': 1e-07,
'hidden_layer_sizes': [eval('('+str(i)+',)') for i in range(1,101)],
'momentum': [0.8],
'max_iter': [500],
'activation': ['tanh'],
'solver': ['sgd'],
'validation_fraction': [0.1],
# 'alpha': [0.0001, 0.05],
'learning_rate': ['constant','adaptive'],
'early_stopping': [True]
}
clf = RandomizedSearchCV(MLPClassifier(), parameter_space,n_iter= 100,random_state=0, n_jobs=-1, cv=3)
clf.fit(X_train, y_train)
print('Best parameters found:\n', clf.best_params_)
# All results
means = clf.cv_results_['mean_test_score']
stds = clf.cv_results_['std_test_score']
for mean, std, params in zip(means, stds, clf.cv_results_['params']):
print("%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params))
preds = clf.predict(X_test)
print("POS TUNNING")
print(metrics.f1_score(y_test,preds,average='macro',pos_label="positive"))
print(metrics.accuracy_score(y_test, preds))
print(clf.best_estimator_)
print(clf.best_params_)
print(clf.cv_results_)<file_sep>import re
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords
def prePreprocess(string):
#Remove Characters
result = list(map(lambda i: re.sub('[^A-Za-z0]+', ' ', i), [string]))
#Token
result = list(map(lambda i: word_tokenize(i), result))
# StopWords
result = [[i for i in sentences if i not in stopwords.words('english')] for sentences in result]
#Lemm
lemmatizer = WordNetLemmatizer()
result = list(map(lambda i: list(map(lambda j: lemmatizer.lemmatize(j),i)),result))
#Stemm
#stemmer = SnowballStemmer('english')
#result = list(map(lambda i: list(map(lambda j: stemmer.stem(j), i)), result))
return result[0]<file_sep>import os
from project.utils.PreProcess import prePreprocess
class TextExtractor:
def __init__(self, negativeText = '../dataset/competition_SA/neg', positiveText = '../dataset/competition_SA/pos'):
self.negativeText = negativeText
self.positiveText = positiveText
self.dic = {}
def extractFromDataSet (self):
return (self.positiveExtract(),self.negativeExtract())
def negativeExtract(self):
negativeList = []
for fileName in os.listdir(self.negativeText):
arq = open(self.negativeText+ '/' + fileName, 'r')
text = arq.read()
list = prePreprocess(text)
negativeList.append(text)
for i in list:
try:
self.dic[i]
except:
self.dic[i] = ''
arq.close()
return negativeList
def positiveExtract(self):
positiveList = []
for fileName in os.listdir(self.positiveText):
arq = open(self.positiveText + '/' + fileName, 'r')
text = arq.read()
list = prePreprocess(text)
positiveList.append(text)
for i in list:
try:
self.dic[i]
except:
self.dic[i] = ''
arq.close()
return positiveList
def extractTestText(self, pos = '../dataset/testSet/pos', neg = '../dataset/testSet/neg'):
testText = []
for fileName in os.listdir(pos):
arq = open(pos + '/' + fileName, 'r')
testText.append((prePreprocess(arq.read()),'P'))
arq.close()
for fileName in os.listdir(neg):
arq = open(neg + '/' + fileName, 'r')
testText.append((prePreprocess(arq.read()),'N'))
arq.close()
return testText
def extractNewText(self, set = '../dataset/testSet/newSet'):
testText = []
for fileName in os.listdir(set):
arq = open(set + '/' + fileName, 'r')
testText.append((prePreprocess(arq.read()),''))
arq.close()
return testText
def extractTextFromDataset(self):
return (self.negativeTextExtract(), self.positiveTextExtract())
def negativeTextExtract(self):
negativeList = []
for fileName in os.listdir(self.negativeText):
arq = open(self.negativeText+ '/' + fileName, 'r')
negativeList.append(arq.read())
arq.close()
return negativeList
def positiveTextExtract(self):
positiveList = []
for fileName in os.listdir(self.positiveText):
arq = open(self.positiveText + '/' + fileName, 'r')
positiveList.append(arq.read())
arq.close()
return positiveList
#text = TextExtractor()
#testList = text.extractTestText()
#for i in testList:
# print(i)
<file_sep>def createFrequencyList(self, document):
lenAllWords = len(self.train.allWords)
listTemp = [0] * lenAllWords
listAllWords = list(self.train.allWords.keys())
tempDict = {i[1]: i[0] for i in list(enumerate(listAllWords))}
# for i in range(lenAllWords):
# listTemp[i] = document.count(listAllWords[i])
for i in document:
try:
tempDict[i]
listTemp[tempDict[i]] += 1
except:
pass
return listTemp<file_sep>from project.utils.TextExtractor import TextExtractor
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.model_selection import train_test_split
from sklearn import metrics
import matplotlib.pyplot as plt
import pickle
if int(input('0 to use save or 1 to extract')):
#extract text from dataset
textExtractor = TextExtractor(negativeText ='../dataset/neg', positiveText='../dataset/pos')
posText, negText = textExtractor.extractFromDataSet()
#bag of words preprocessed
allWords = list(textExtractor.dic.keys())
if int(input('0 to dont save extract or 1 to save')):
with open('saveparmsknn.txt', 'wb') as fp:
pickle.dump([allWords, posText, negText], fp)
else:
with open('saveparmsknn.txt', 'rb') as fp:
allWords, posText, negText = pickle.load(fp)
#All text and vectorizer
allText = posText+negText
vectorizer = CountVectorizer(vocabulary=allWords)
#KNN
#Vector of freq all text + tags (indexed)
X = vectorizer.fit_transform(allText)
y = ['positive' for i in range(len(posText))] + ['negative' for i in range(len(negText))]
#Training split 80/20
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0,test_size=0.2)
#Train
# k_range = range(1,30)
# scores_f1 = {}
# scoresf1_list = []
#
# scores_Accuracy = {}
# scoresAccuracy_list = []
grid_params = {
'n_neighbors': [i for i in range(1,30)],
'weights': ['distance'],
'metric': ['euclidean', 'manhattan', 'minkowski']
}
knn = GridSearchCV(KNeighborsClassifier(), grid_params, cv=3)
knn.fit(X_train,y_train)
preds = knn.predict(X_test)
print(metrics.f1_score(y_test,preds,average='macro',pos_label="positive"))
print(metrics.accuracy_score(y_test, preds))
# for k in k_range:
# knn = KNeighborsClassifier(n_neighbors=k)
# knn.fit(X_train,y_train)
# y_pred = knn.predict(X_test)
#
# scores_Accuracy[k] = metrics.accuracy_score(y_test, y_pred)
# scoresAccuracy_list.append((metrics.accuracy_score(y_test, y_pred)))
#
# scores_f1[k] = metrics.f1_score(y_test,y_pred,average='macro',pos_label="positive")
# scoresf1_list.append((metrics.f1_score(y_test, y_pred, average='micro', pos_label="positive")))
# print("Max F1 is %.2f for K = %d"%(max(list(scores_f1.values())), max(scores_f1, key = scores_f1.get)))
# plt.plot(k_range, scoresf1_list)
# plt.xlabel('Values for K for KNN')
# plt.ylabel('Testing F1-Score')
# plt.show()
#
# print("Max Accuracy is %.2f for K = %d"%(max(list(scores_Accuracy.values())), max(scores_Accuracy, key = scores_Accuracy.get)))
# plt.plot(k_range, scoresAccuracy_list)
# plt.xlabel('Values for K for KNN')
# plt.ylabel('Testing Accuracy')
# plt.show()
#
# def predictText(knn, vectorizer, string):
# return knn.predict((vectorizer.transform([string])))
#
# print(predictText(neigh,vectorizer,'got mail works alot better than it deserves'))<file_sep>from sklearn.model_selection import train_test_split
from project.utils.TextExtractor import TextExtractor
#Split data into train and test sets
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
if int(input('0 to use save or 1 to extract')):
#extract text from dataset
textExtractor = TextExtractor(negativeText ='../dataset/neg', positiveText='../dataset/pos')
posText, negText = textExtractor.extractFromDataSet()
#bag of words preprocessed
allWords = list(textExtractor.dic.keys())
if int(input('0 to dont save extract or 1 to save')):
with open('saveparmsnaivebayes.txt', 'wb') as fp:
pickle.dump([allWords, posText, negText], fp)
else:
with open('saveparmsnaivebayes.txt', 'rb') as fp:
allWords, posText, negText = pickle.load(fp)
#print(len(posText))
#All text and vectorizer
allText = posText+negText
vectorizer = TfidfVectorizer(vocabulary=allWords)
#print(posText)
#KNN
#Vector of freq all text + tags (indexed)
X = vectorizer.fit_transform(allText)
y = ['positive' for i in range(len(posText))] + ['negative' for i in range(len(negText))]
#Training split 80/20
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0,test_size=0.2)
clfrNB = MultinomialNB(alpha = 0.1)
clfrNB.fit(X_train, y_train)
preds = clfrNB.predict(X_test)
score = metrics.accuracy_score(y_test, preds)
#print(clfrNB.predict(vectorizer.transform(['i', 'hate', 'all'])))
for i in clfrNB.predict(vectorizer.transform(['This is the best film'])):
print(vectorizer.transform(['This is the best film']))
print(i)
# print(metrics.f1_score(y_test,preds,average='macro',pos_label="positive"))
# print(metrics.accuracy_score(y_test, preds)) | 1c1cc3c74430b0f8380a383a3d45e227338e76ce | [
"Python"
] | 9 | Python | MatheusRDG/pattern_recognition_project | cf8ad553a4f4a61f18b173dab1d654d29e65c128 | a6f1d23a725926c846409244242887077116f4f6 |
refs/heads/master | <file_sep>module.exports = {
openweather: {
apikey: "YOUR_API_KEY_HERE"
}
};
<file_sep># React Weather
This project demonstrates using [ReactJS](https://facebook.github.io/react/) and [Redux](http://redux.js.org/) to fetch 5 day forecast data from [Open Weather API](http://openweathermap.org/forecast5)
### Libraries used
* [ReactJS](https://facebook.github.io/react/)
* Pattern - [Redux](http://redux.js.org/)
* Fetching Data -[Axios](https://github.com/mzabriskie/axios)
* Promises - [Redux Promises](https://github.com/acdlite/redux-promise)
* Maps - [React Google Maps](https://github.com/tomchentw/react-google-maps)
* ES6 Style JavaScript
* Graphing - [Sparklines](https://github.com/borisyankov/react-sparklines)
* Base Template - [Simple starter package for Redux with React and Babel support](<EMAIL>:StephenGrider/ReduxSimpleStarter.git)
### Signup with Open Weather
Go to open weather and signup. You will need your api key.
[http://openweathermap.org/forecast5](http://openweathermap.org/forecast5)
###Run this project###
Download or clone this project from github.
```
> npm install
> npm start
```
### What does it look like?
 | 50d2e0bb3683b310729979e8ec1597068d0252af | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | shaynemeyer/redux-weather | 8a34a7c757351feec0aa10f4e659ee9cb4df5540 | 248c5d1af931f928b0fb5945ff296806187393ab |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
var DB = require('../models/db.js');
/* GET home page. */
var db = new DB();
router.get('/login', function(req, res, next) {
console.log('login');
});
router.post('/addUser', function(req, res, next){
var insertSql = 'insert into user set ?';
var user = req.body;
console.log(user);
db.insert(insertSql, user, function(result){
res.json(result);
})
});
router.post('/login', function(req, res, next){
var selectSql = 'select * from user where name=? and password = ?';
var user = [];
user.push(req.body.name);
user.push(req.body.password);
db.findByCondition(selectSql, user,function(result){
res.json(result);
})
});
module.exports = router;
<file_sep># nodejs_tv_web
nodejs + express + mysql
the web is about website ended
the front is use angular + bootstrap + gulp
the front project name is front_tv_web
<file_sep>/**
* Created by Htmler on 2016/8/8.
*/
var express = require('express');
var router = express.Router();
var DB = require('../models/db.js');
var db = new DB();
router.get('/sort', function(req, res, next){
res.send('连接成功');
});
//获取视频分类
router.post('/sort', function(req, res, next){
var values = [];
var data = req.body();
var currentPageNum = (data.size-1) * data.currentPage;
var lastPageNum = data.size * data.currentPage;
values.push(data.type);
values.push(data.tip);
values.push(data.area);
values.push(data.releaseDate);
values.push(currentPageNum);
values.push(lastPageNum);
var sortPage = 'select * from movie where type = ? OR tip = ? OR area = ? OR releaseDate = ? ORDER BY id LIMIT ?, ?';
db.findByCondition(sortPage, values, function(result){
res.json(result);
});
});
module.exports = router;
| 3121fb93a4ff688fd0fd0651bfc3d8ec497912ef | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Lincoln-xzc/nodejs_tv_web | bbf5fd11f458b63213bb8b6f80f68d869825d0b1 | e755d9fcc2df1c71e5f9d943ae27c0eab9d0979d |
refs/heads/master | <file_sep>print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# this line is just a comment
print "Is it true that 3 +2 < 5 - 7?"
# another comment here
print 3 + 2 < 5 - 7
# below is a math problem which should equal 5
print "What is 3.2 + 2.7?", 3.2 + 2.7
print "What is 5 - 7?", 5 - 7
# explained below
print "Oh, that's why it's False."
# do you want more?
print "How about some more."
# you tell me...
print "Is it greater?", 5 > -2
print "is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
<file_sep>class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
#not sure if you got my review request. I put the @chrisklaiber in the description in the git program installed on my computer
# before I committed and synced it. I will try to put it again in the description below once I make this change. Thx.
<file_sep>py-the-hard-way
===============
| fa78f61c86a0b841e6da5165ffe6663e4fff7ac3 | [
"Markdown",
"Python"
] | 3 | Python | ryanklaiber/py-the-hard-way | 8fbc269a2f032c27cca7b452f87a720f7d470a77 | 9729d39549f66e675c292a8411b25ff2251ac83e |
refs/heads/main | <repo_name>arimemedi/parfemiapp<file_sep>/src/main/java/com/fon/parfemi/service/GradService.java
package com.fon.parfemi.service;
import java.util.List;
import com.fon.parfemi.domain.Grad;
public interface GradService {
public Grad saveGrad(Grad grad);
public List<Grad> getAllGrads();
public Grad deleteGrad(Grad grad);
public Grad updateGrad(Grad grad);
public void deleteGradById(Long gradId);
}
<file_sep>/src/main/java/com/fon/parfemi/rest/GradRestController.java
package com.fon.parfemi.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fon.parfemi.domain.Grad;
import com.fon.parfemi.service.GradService;
@RestController
@RequestMapping("/gradovi")
public class GradRestController {
@Autowired
private GradService gradService;
@GetMapping
public List<Grad> getAllGradovi(){
return gradService.getAllGrads();
}
@PostMapping
public Grad saveGrad(@RequestBody Grad grad) {
return gradService.saveGrad(grad);
}
@PutMapping
public Grad updateGrad(@RequestBody Grad grad) {
return gradService.updateGrad(grad);
}
@DeleteMapping
public Grad deleteGrad(@RequestBody Grad grad) {
return gradService.deleteGrad(grad);
}
@DeleteMapping("/{gradId}")
public void deleteGradById(@PathVariable Long gradId) {
gradService.deleteGradById(gradId);
}
}
<file_sep>/src/main/java/com/fon/parfemi/service/impl/GradServiceImpl.java
package com.fon.parfemi.service.impl;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fon.parfemi.domain.Grad;
import com.fon.parfemi.repository.GradRepository;
import com.fon.parfemi.service.GradService;
@Service
public class GradServiceImpl implements GradService {
@Autowired
private GradRepository gradRepository;
@Override
public Grad saveGrad(Grad grad) {
List<Grad> list = new LinkedList<>();
gradRepository.findAll().forEach(list::add);
boolean exists = list.stream().anyMatch((it) -> it.getNazivGrada().equals(grad.getNazivGrada()));
if(!exists)
return gradRepository.save(grad);
else
return grad;
}
@Override
public List<Grad> getAllGrads() {
List<Grad> list=new LinkedList<>();
gradRepository.findAll().forEach(list::add);
return list;
}
@Override
public Grad deleteGrad(Grad grad) {
List<Grad> list=new LinkedList<>();
gradRepository.findAll().forEach(list::add);
boolean exists=list.stream().anyMatch((it) -> it.getNazivGrada().equals(grad.getNazivGrada()));
if(exists) {
gradRepository.delete(grad);
return grad;
}
return null;
}
@Override
public Grad updateGrad(Grad grad) {
List<Grad> list=new LinkedList<>();
gradRepository.findAll().forEach(list::add);
boolean exists=list.stream().anyMatch((it) -> it.getNazivGrada().equals(grad.getNazivGrada()));
if(exists) {
gradRepository.save(grad);
return grad;
}
return null;
}
@Override
public void deleteGradById(Long gradId) {
gradRepository.deleteById(gradId);
}
}
<file_sep>/src/main/java/com/fon/parfemi/domain/Parfem.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fon.parfemi.domain;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author PC
*/
public class Parfem{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "parfemid")
private Long parfemId;
@Column(name = "nazivparfema")
private String naziv;
@Column(name = "mililitraza")
private int mililitraza;
@Column(name = "cena")
private Long cena;
public Parfem() {
}
public Parfem(Long parfemId, String naziv, int mililitraza, Long cena) {
this.parfemId = parfemId;
this.naziv = naziv;
this.mililitraza = mililitraza;
this.cena = cena;
}
public Long getParfemId() {
return parfemId;
}
public void setParfemId(Long parfemId) {
this.parfemId = parfemId;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public int getMililitraza() {
return mililitraza;
}
public void setMililitraza(int mililitraza) {
this.mililitraza = mililitraza;
}
public Long getCena() {
return cena;
}
public void setCena(Long cena) {
this.cena = cena;
}
@Override
public String toString() {
return naziv + " " + mililitraza + "ml";
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Parfem other = (Parfem) obj;
if (this.parfemId != other.parfemId) {
return false;
}
return true;
}
}
<file_sep>/src/main/resources/application.properties
server.port=9090
spring.jpa.hibernate.ddl-auto=none
spring.jpa.database=MYSQL
spring.datasource.platform=mysql
spring.jpa.show-sql=true
spring.datasource.url=jdbc:mysql://localhost:3306/prodavnicaparfema
spring.datasource.username=hbstudent
spring.datasource.password=<PASSWORD>
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.generate-ddl=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.datasource.initialization-mode=never
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp<file_sep>/src/main/java/com/fon/parfemi/rest/KlijentRestController.java
package com.fon.parfemi.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fon.parfemi.domain.Klijent;
import com.fon.parfemi.service.KlijentService;
@RestController
@RequestMapping("/klijenti")
public class KlijentRestController {
@Autowired
KlijentService klijentService;
@GetMapping
public List<Klijent> getAllKlijenti(){
return klijentService.getAllKlijents();
}
@PostMapping
public Klijent saveKlijent(@RequestBody Klijent klijent) {
return klijentService.saveKlijent(klijent);
}
@PutMapping
public Klijent updateKlijent(@RequestBody Klijent klijent) {
return klijentService.updateKlijent(klijent);
}
@DeleteMapping
public Klijent deleteKlijent(@RequestBody Klijent klijent) {
return klijentService.deleteKlijent(klijent);
}
@DeleteMapping("/{klijentId}")
public void deleteKlijentById(@PathVariable Long klijentId) {
klijentService.deleteKlijentById(klijentId);
}
}
| 62b231b667a70289b9b07e61b3c9337198783f0d | [
"Java",
"INI"
] | 6 | Java | arimemedi/parfemiapp | 601b0d680660d1020a5319f57d966bf01e11b122 | 33a7cdab2a0f167850956983896e9e723cc2b764 |
refs/heads/master | <repo_name>jessharrison83/React-Insta-Clone<file_sep>/instagram/src/components/CommentSection/CommentSection.js
import React, { Component } from "react";
import Comment from "./Comment.js";
import PropTypes from "prop-types";
import moment from "moment";
import styled from "styled-components";
const Time = styled.div`
margin-left: 10px;
color: silver;
`;
const AddComment = styled.input`
padding: 10px 0px;
border: none;
border-top: 1px solid silver;
color: silver;
margin-top: 10px;
width: 95%;
font-size: 16px;
margin-left: 10px;
`;
class CommentSection extends Component {
constructor(props) {
super();
this.state = {
comments: props.comments,
input: ""
};
}
submitHandler = event => {
const newComment = {
username: `${localStorage.getItem("username")}`,
text: this.state.input,
timestamp: moment()
};
if (event.key === "Enter") {
this.setState({
comments: [...this.state.comments, newComment],
input: ""
});
event.target.value = "";
}
};
changeHandler = event => {
const value = event.target.value;
this.setState({
input: value
});
};
onFocus = event => {
event.target.value = "";
};
onBlur = event => {
event.target.value = "Add a comment...";
};
render() {
return (
<>
{this.state.comments.map(comment => {
return (
<Comment
key={Math.random()}
commentUser={comment.username}
comment={comment.text}
/>
);
})}{" "}
<Time> {moment(this.props.time).fromNow()} </Time>{" "}
<AddComment
className="add-comment"
type="text"
defaultValue="Add a comment..."
onChange={this.changeHandler}
onFocus={this.onFocus}
onKeyDown={this.submitHandler}
onBlur={this.onBlur}
/>{" "}
</>
);
}
}
CommentSection.propTypes = {
comments: PropTypes.arrayOf(
PropTypes.shape({
username: PropTypes.string,
text: PropTypes.string
})
).isRequired
};
export default CommentSection;
<file_sep>/instagram/src/components/PostContainer/PostContainer.js
import React, { Component } from "react";
import CommentSection from "../CommentSection/CommentSection.js";
import Post from "../Post/Post.js";
import styled from "styled-components";
const Card = styled.div`
width: 600px;
margin: 0 auto;
border: 1px solid whitesmoke;
margin-bottom: 40px;
border-radius: 3px;
`;
class PostContainer extends Component {
constructor(props) {
super();
this.state = {
thumbnailUrl: props.thumbnail,
username: props.username,
imageUrl: props.imageUrl,
likes: props.likes
};
}
likeClickHandler = event => {
event.preventDefault();
const likes = event.target;
if (likes.classList.contains("far")) {
likes.classList.remove("far");
likes.classList.add("fas");
this.setState({ likes: this.state.likes + 1 });
} else {
likes.classList.remove("fas");
likes.classList.add("far");
this.setState({ likes: this.state.likes - 1 });
}
};
commentClickHandler = event => {
event.preventDefault();
document.querySelector(".add-comment").focus();
};
render() {
return (
<Card>
<Post
thumbnail={this.state.thumbnailUrl}
username={this.state.username}
imageUrl={this.state.imageUrl}
likes={this.state.likes}
likeClickHandler={this.likeClickHandler}
commentClickHandler={this.commentClickHandler}
/>
<CommentSection comments={this.props.comments} time={this.props.time} />
</Card>
);
}
}
export default PostContainer;
<file_sep>/instagram/src/components/CommentSection/Comment.js
import React from "react";
import styled from "styled-components";
const CommentContainer = styled.div`
display: flex;
margin-left: 10px;
margin-bottom: 2px;
margin-top: 0px;
padding: 0px;
`;
const User = styled.p`
font-weight: bold;
margin-right: 5px;
`;
const Comment = props => {
return (
<CommentContainer>
<User>{props.commentUser}</User>
<p>{props.comment}</p>
</CommentContainer>
);
};
export default Comment;
<file_sep>/instagram/src/components/SearchBar/SearchBar.js
import React, { Component } from "react";
import "./SearchBar.css";
import styled from "styled-components";
import img from "./search-img.png";
const SearchBarContainer = styled.div`
display: flex;
justify-content: space-between;
max-width: 800px;
margin: 0 auto;
padding-top: 20px;
margin-bottom: 60px;
`;
const LogoName = styled.div`
font-family: "Grand Hotel", cursive;
font-size: 24px;
padding-left: 10px;
`;
const Logo = styled.div`
display: flex;
`;
const LogoImg = styled.div`
border-right: 1px solid black;
padding-left: 0px;
height: 28px;
padding-right: 10px;
`;
const InstaLogo = styled.i`
font-size: 28px;
`;
const Search = styled.input`
padding-right: 25px;
padding-left: 30px;
text-align: center;
border: 1px solid #f5f5f5;
font-size: 13px;
color: silver;
background-image: url(${img});
background-repeat: no-repeat;
background-position-x: 30%;
background-position-y: center;
`;
const Icon = styled.i`
font-size: 24px;
padding-right: 8px;
padding-left: 8px;
cursor: pointer;
`;
class SearchBar extends Component {
constructor() {
super();
this.state = {
input: ""
};
}
onFocus = event => {
event.target.value = "";
event.target.classList.add("no-background");
};
onBlur = event => {
event.target.value = "Search";
event.target.classList.remove("no-background");
};
render() {
return (
<SearchBarContainer>
<Logo>
<LogoImg>
<InstaLogo className="fab fa-instagram" />
</LogoImg>{" "}
<LogoName> Instagram </LogoName>{" "}
</Logo>{" "}
<Search
type="search"
defaultValue="Search"
onFocus={this.onFocus}
onBlur={this.onBlur}
onChange={this.props.searchInputHandler}
onKeyDown={this.props.searchHandler}
/>{" "}
<div>
<Icon className="far fa-compass" />
<Icon className="far fa-heart" />
<Icon className="far fa-user" />
<Icon
className="fas fa-sign-out-alt"
onClick={this.props.logoutHandler}
/>{" "}
</div>{" "}
</SearchBarContainer>
);
}
}
export default SearchBar;
| 5f847516cdb5c6886147d57f94f6cc09cf659444 | [
"JavaScript"
] | 4 | JavaScript | jessharrison83/React-Insta-Clone | cd1c41ad9c03de7c672b26467e0387ced7ae17c2 | 2a4e16c54e77a2a72164dfca403cd8425308e365 |
refs/heads/master | <repo_name>jan-glx/castyt<file_sep>/simulation.py
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("white")
n = 5
kMact = np.random.exponential(size=(n, n))
kMdeg = np.random.exponential(size=(n, n))
kact = np.random.exponential(size=(n, n))
kdeg = np.random.exponential(size=(n, n))
kact0 = np.random.exponential(size=n)
kdeg0 = np.random.exponential(size=n)
epsilon = 1E-2
n_epsilon = 500
n_simulations = 10
n_interventions = 10
df = pd.DataFrame()
for k in range(n_interventions):
if k == 0:
ci = 1
elif k <= n:
ci = np.ones(n)
ci[k-1] = 3
else:
ci = 1 + np.random.exponential(size=n)
for j in range(n_simulations):
c0 = np.random.exponential(size=n)
c = c0
for i in np.arange(0, n_epsilon):
c += (-c*kdeg0 + kact0 + np.sum(kact/(1+kMact/(c/ci)), axis=1) - c*np.sum(kdeg/(1+kMact/(c/ci)), axis=1))*epsilon
c = np.maximum(c, 1E-4)
df = df.append(pd.DataFrame({"intervention": k, 'entity': np.arange(n), 'concentration': c, 'simulation_id': j}))
f, ax = plt.subplots(figsize=(7, 7))
ax.set(yscale="log")
sns.tsplot(data=df, time="intervention", unit="simulation_id",
condition="entity", value="concentration", err_style="unit_traces")
plt.show()
| 3fd8ef94aaa5fa88b6f44be61171973a1c342747 | [
"Python"
] | 1 | Python | jan-glx/castyt | 5707c8769dcea64cfcf5713d4e3a21f25ad95cf9 | 11b92ab2386946526bafa4c89307eaabc0f0c126 |
refs/heads/master | <repo_name>kuptservol/CraftyCorrelations<file_sep>/service/concreteService/src/test/java/ru/test/SpearmansRankCorrelationTest.java
package ru.test;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;
import org.apache.commons.math3.stat.inference.TestUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.Random;
/**
* Created by SKuptsov on 08.10.2015.
*/
public class SpearmansRankCorrelationTest{
@Test
public void testDifferentSizesCorrelationSameLine(){
int size = 100000;
int coef = 1000;
double[] xArray = new double[size];
double[] yArray = new double[size];
Random random = new Random();
for(int i = 0; i<size;i++ )
{
xArray[i] = random.nextDouble();
yArray[i] = xArray[i]*coef;
}
double correlation = new SpearmansCorrelation().correlation(xArray, yArray);
Assert.assertEquals(correlation, 1.0, 0.0);
}
@Test
public void testDifferentSizesCorrelationDiffLine(){
int size = 100000;
int coef = 1000;
double[] xArray = new double[size];
double[] yArray = new double[size];
Random random = new Random();
for(int i = 0; i<size;i++ )
{
xArray[i] = random.nextDouble();
yArray[i] = xArray[i]*coef*random.nextInt();
}
double correlation = new SpearmansCorrelation().correlation(xArray, yArray);
Assert.assertNotEquals(correlation, 1.0, 0.0);
System.out.println(correlation*100+"%");
}
@Test
/**
* Выборки разного кол-ва точек
*/
public void testDifferentNumberOfPointsCorrelationDiffLine(){
int size1 = 100000;
int size2 = 100;
double[] xArray = new double[size1];
double[] yArray = new double[size2];
Random random = new Random();
for(int i = 0; i<size1;i++ )
{
xArray[i] = random.nextDouble();
}
for(int i = 0; i<size2;i++ )
{
yArray[i] = random.nextDouble();
}
}
}
<file_sep>/build.gradle
apply plugin: 'java'
version = '1.0'
apply plugin: 'idea'
idea {
project {
jdkName = '1.7'
languageLevel = '1.7'
}
}
subprojects {
apply plugin: 'idea'
idea {
module {
downloadJavadoc = true
downloadSources = true
}
}
}
ext.sourceEncoding = 'UTF-8'
ext.compatibility = 1.7
allprojects{
//common configuration
repositories {
mavenCentral()
}
configurations.all {
// check for updates every build test
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
apply plugin: 'java'
sourceCompatibility = compatibility
compileJava.options.encoding = sourceEncoding
compileTestJava.options.encoding = sourceEncoding
configurations {
providedCompile
providedRuntime
providedRuntime.extendsFrom providedCompile
}
sourceSets {
main {
compileClasspath += configurations.providedCompile
runtimeClasspath += configurations.providedRuntime
}
test {
compileClasspath += configurations.providedCompile
runtimeClasspath += configurations.providedRuntime
}
}
}<file_sep>/service/concreteService/build.gradle
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'org.apache.commons:commons-math3:3.0'
testCompile 'org.apache.commons:commons-math3:3.0'
}<file_sep>/settings.gradle
rootProject.name = 'CraftyCorrelations'
include 'service'
include "service:concreteService"
| 207bcddc8f87bf2f51584db109c5e915ef8631ce | [
"Java",
"Gradle"
] | 4 | Java | kuptservol/CraftyCorrelations | e3bc0d913adfc832136e5a2d3e50e1692dc3dab3 | d637d52d926aeb00b1c55ac5483c86d8bcfb06d0 |
refs/heads/master | <repo_name>wljing/web<file_sep>/server/index.js
const fs = require('fs')
const path = require('path')
const express = require('express')
const app = express()
const Util = require('./Util')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
app.use(bodyParser.urlencoded({extended:false}))
app.use(cookieParser())
app.use(session({
secret: 'asdasdasdasd',
resave: true,
saveUninitialized: true,
key: 'sid',
cookie: {
maxAge: 3600 * 1000 * 2,
httpOnly: true,
}
}))
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:5000")
// res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "X-Requested-With")
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS")
res.header("Access-Control-Allow-Credentials", true)
res.header("Content-Type", "application/json;charset=utf-8")
next();
})
app.get('/build.js', function(req, res){
res.sendFile(path.join(__dirname, '../dist/build.js'))
})
app.use('/static', express.static(path.join(__dirname,'../src/static'), {
maxAge: 1000 * 60 * 60
}))
app.get('/', async function (req, res) {
// if(req.session && req.session['userinfo']){
// //更新 session
// let user = await require('./api/userInfo.js').fun(req.session['userid'])
// if(user != false){
// req.session['userinfo'] = JSON.stringify(user)
// }
// }
fs.readFile(path.resolve(__dirname,'../dist/index.html'),'utf-8', (err, data) => {
res.set('Content-Type', 'text/html');
if(err)
res.send(err)
else
res.send(data)
})
})
app.get('/su', function(req, res){
//session userinfo
if(req.session['userinfo']){
res.send(req.session['userinfo'])
}else{
res.send(JSON.stringify('UNLOGIN'))
}
})
app.get('/g', function(req, res){
res.send('no create')
})
app.get('/cancel', function(req, res){
req.session.destroy()
res.send('SUCCESS')
})
app.post('/api', function(req , res){
//根据url 找到所需api方法调用 并将参数作为对象传入
let body = req.body
if(!('m' in body)){
res.send(JSON.stringify({'type':'ERROR_PARAMS'}))
return
}
let apiPath = path.join(__dirname, './api/' + body.m + '.js')
fs.exists(apiPath, async exists => {
if(exists){
api = require(apiPath)
let data = await api.fun(body)
let dataObj = JSON.parse(data)
if((body.m === 'register' || body.m === 'login') && dataObj.type == 'SUCCESS'){
req.session['userid'] = dataObj['userid']
//如果是登录或者注册 把用户信息放在session
let userInfo = await require('./api/userInfo.js').fun(dataObj['userid'])
userInfo = JSON.parse(userInfo)
if(userInfo.type == 'SUCCESS'){
req.session['userinfo'] = JSON.stringify(userInfo.data)
}
}
res.send(data)
}else{
res.status(404)
res.end(JSON.stringify({'type': 'ERROR_FILE_NO'}))
}
})
})
app.get('*', function(req, res){
res.redirect(302 ,'http://localhost:1314')
})
app.listen(1314, () => {
})
<file_sep>/server/api/register.js
/*
**注册接口
**@url /api
**@method POST
**Content-Type application/x-www-urlencode
**@param m = register
**@param user = 用户名
**@param nickname = 昵称
**@param password = 密码
**@return JSON
**@return type
*/
const mysql = require('mysql')
const DBini = require('../DataBase.ini')
const db = DBini.db
const pool = mysql.createPool({
host: db.host,
user: db.user,
password: <PASSWORD>,
database: db.database,
port: db.port
})
let link = async function (){
//链接数据库
return new Promise((resolve, reject) => {
pool.getConnection( (err,conn) => {
if(err){
reject(err)
}
resolve(conn)
})
})
}
let isExist = async function(connect, user){
return new Promise( (resolve, reject) =>{
let sql = 'select id from user where user_id =?'
connect.query(sql,[user], (err, result) => {
if(err){
reject(err)
}
else if(Object.keys(result).length === 0){
resolve(connect)
}else{
reject('exist')
}
})
})
}
let insert = async function(connect, user, nickname, password){
//插入数据
return new Promise( (resolve, reject) => {
let sql = `insert into user values(default,?,null ,?, default, ?,default)`
connect.query(sql,[user,nickname,password], (err, result) => {
connect.release()
if(err){
reject(err)
}else{
// res.userid = result['insertId']
resolve(result['insertId'])
}
})
})
}
const userReg = /^[1-9a-zA-Z]{1}[0-9a-zA-Z]{5,9}$/ //6-10位字母数字
const nicknameReg = /([\u4e00-\u9fa5]|[0-9a-zA-Z_%@|、.,\[\]\\]){4,10}/ //4-10位
exports.fun = async function(arg){
let res = {}
if(!('user' in arg) || !('nickname' in arg)|| !('password' in arg)){
//参数形式错误
res.type = 'ERROR_PARAMS_NUM'
return JSON.stringify(res)
}
user = arg.user
nickname = arg.nickname
password = <PASSWORD>
if(!userReg.test(user) || !nicknameReg.test(nickname)){
//参数值错误
res.type = 'ERROR_PARAMS_VALUE'
return JSON.stringify(res)
}
//连接数据库
await link()
.then(data => {
return isExist(data, user)
}, err => {
res.type = 'ERROR_DB_CONNECT'
throw err
})
.then(data => {
return insert(data, user, nickname, password)
}, err => {
if(err == 'exist'){
res.type = 'ERROR_PARAMS_EXIST'
}else{
res.type = 'ERROR_DB_QUERY'
throw err
}
})
.then(data => {
res.userid = data
res.type = 'SUCCESS'
}, err => {
res.type = 'ERROR_DB_QUERY'
throw err
})
return JSON.stringify(res)
}<file_sep>/src/js/stars.js
const Stars = {}
Stars.init = function (n) {
let moon = document.createElement('div')
moon.classList.add('moon')
document.body.appendChild(moon)
let comet = document.createElement('div')
comet.classList.add('star', 'comet')
comet.style.zIndex = 10
document.body.appendChild(comet)
for (let i = 0; i < n; i++) {
let div = document.createElement('div');
div.style.zIndex = 10
div.className = i % 20 == 0 ? 'star star--big' : i % 9 == 0 ? 'star star--medium' : 'star';
div.setAttribute('style', 'top:' + Math.round(Math.random() * 960) + 'px;left:' + Math.round(Math.random() * 1920) + 'px;animation-duration:' + (Math.round(Math.random() * 3000) + 3000) + 'ms;animation-delay:' + Math.round(Math.random() * 3000) + 'ms;');
document.body.appendChild(div);
}
};
Stars.clear = function (){
let stars = document.querySelectorAll('.star')
let moon = document.querySelectorAll('.moon')
document.body.removeChild(moon[0])
for(let i = 0; i < stars.length; i++){
document.body.removeChild(stars[i])
}
}
export default Stars<file_sep>/src/js/const.js
const CONST = {}
CONST.baseUrl = 'http://localhost:1314/'
export default CONST<file_sep>/src/store/actions.js
import type from './type'
export default {
setLoginState ({ commit }, flag) {
commit(type.SET_LOGIN_STATE, flag)
},
toggleLoginBox ({ commit }) {
commit(type.TOGGLE_LOGIN_BOX)
},
setUserInfo({commit}, data){
commit(type.SET_USERINFO, data)
}
}<file_sep>/src/main.js
import Vue from 'vue'
import App from './comp/App.vue'
import Vuex from 'vuex'
import store from './store/index'
import 'vue2-animate/dist/vue2-animate.min.css'
import elementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import './static/css/base.css'
import './static/css/stars.css'
Vue.use(Vuex)
Vue.use(elementUI)
new Vue({
el: '#app',
store,
render: c => c(App)
})<file_sep>/server/api/userInfo.js
/*
** 用户信息接口
**@param userid = 用户id
**@return JSON 用户信息
*/
const mysql = require('mysql')
const DBini = require('../DataBase.ini')
const db = DBini.db
const pool = mysql.createPool({
host: db.host,
user: db.user,
password: <PASSWORD>,
database: db.database,
port: db.port
})
var link = async function(){
return new Promise( (resolve, rejects) =>{
pool.getConnection( (err, conn) => {
if(err){
rejects(err)
}
resolve(conn)
})
})
}
var getUserInfo = async function (connect, id){
let query = "select sex,nick_name,created_time,icon from user where id = ?"
return new Promise((resolve, reject) => {
connect.release()
connect.query(query, [id], (err, result) => {
if(err){
reject(err)
}else{
resolve(result)
}
})
})
}
exports.fun = async function(id){
let res = {};
await link()
.then(data => {
return getUserInfo(data, id)
}, err => {
res.type = 'ERROR_DB_CONNECT'
throw err
})
.then(data => {
res.data = data
res.type = 'SUCCESS'
}, err => {
res.type = 'ERROR_DB_QUERY'
throw err
})
return JSON.stringify(res);
}<file_sep>/README.md
# web
coder 的自我实现
<file_sep>/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import mutations from './mutations'
import getters from './getter'
import common_head from './modules/common_head'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
loginState: false,
userInfo: {
user: '',
sex: '',
nickname: '',
icon: '',
createdTime: '',
},
isShowLoginBox: false,
bgColor: '#000000'
},
actions,
mutations,
getters,
modules: {
common_head
}
})
<file_sep>/src/js/bgCool.js
import $ from 'jquery'
class bgCool{
constructor(options){
window.bgCool = this
this.model = 'img'
if(options == 'undefined')
return
if('el' in options){
this.el = $(options['el'])
}else{
console.error('no el')
}
this.width = parseInt($(this.el).css('width'))
this.height = parseInt($(this.el).css('height'))
this.imgUrl = this.el.css('background-image')
this.outerView1 = null
this.outerView2 = null
this.bgColor = this.el.css('background-color')
this.bgSize = this.el.css('background-size')
}
split(distance = 100, during = 300, timeFun = 'linear', callback){
if(this.model === 'color'){
if(callback != undefined && typeof callback == 'function' )
callback.call()
return
}
distance = distance > 100 ? 100 : distance
distance = distance < 0 ? 0 : distance
if(!this.el)
return
let el = this.el
el.css('background-image', 'url("")')
let outerView1 = $('<div id="bgCool-outerView1"></div>')
let outerView2 = $('<div id="bgCool-outerView2"></div>')
this.outerView1 = outerView1
this.outerView2 = outerView2
outerView1.css({
'width': this.width + 'px',
'height': this.height / 2 + 'px',
'z-index': el.css('z-index') - 1,
'background-image': this.imgUrl,
'background-size': this.bgSize,
'position': 'absolute',
'top': '0',
'left': '0',
'background-repeat': 'no-repeat'
})
outerView2.css({
'width': this.width + 'px',
'height': this.height / 2 + 'px',
'z-index': el.css('z-index') - 1,
'background-image': this.imgUrl,
'background-size': this.bgSize,
'background-position-y': '-' + this.height / 2 + 'px',
'position': 'absolute',
'top': this.height / 2 + 'px',
'left': '0',
'background-repeat': 'no-repeat'
})
el.append(outerView1)
el.append(outerView2)
outerView1.animate({
'top': parseInt(outerView1.css('top')) - this.height * 100 / 2 / distance + 'px'
}, during, timeFun)
outerView2.animate({
'top': parseInt(outerView2.css('top')) + this.height * 100 / 2 / distance + 'px'
}, during, timeFun, () => {
outerView1.remove()
outerView2.remove()
if(callback != undefined && typeof callback == 'function' )
callback.call()
})
}
merge(during = 300, timeFun = 'linear', callback){
if(this.model === 'color'){
if(callback != undefined && typeof callback == 'function'){
callback.call()
}
return
}
this.el.append(this.outerView1)
this.el.append(this.outerView2)
this.outerView1.animate({
'top': '0'
},during, timeFun)
this.outerView2.animate({
'top': this.height / 2 + 'px'
},during, timeFun, () => {
if(callback != undefined && typeof callback == 'function'){
callback.call()
}
this.outerView1.remove()
this.outerView2.remove()
this.el.css({
'background-image': this.imgUrl,
// 'background-color': this.bgColor
})
})
}
colorIdea(){
this.model = 'color'
}
imgIdea(){
this.model = 'img'
}
}
export default bgCool
<file_sep>/server/api/login.js
/*
**登录接口
**@url /api
**@method POST
**Content-Type application/x-www-urlencode
**@param m = 模块名
**@param user = 用户名
**@param password = 密码
**@return JSON 用户信息
*/
const mysql = require('mysql')
const DBini = require('../DataBase.ini')
const db = DBini.db
const pool = mysql.createPool({
host: db.host,
user: db.user,
password: <PASSWORD>,
database: db.database,
port: db.port
})
async function link(){
return new Promise( (resolve, rejects) =>{
pool.getConnection( (err, conn) => {
if(err){
// res.type = 'ERROR_DB_CONNECT'
rejects(err)
}
resolve(conn)
})
})
}
async function getUser(connect, user){
return new Promise( (resolve, rejects) => {
let sql = 'select * from user where user_id =?'
connect.query(sql,[user], (err
, result)=>{
connect.release()
if(err){
rejects(err)
}
if(result.length === 0){
rejects('0')
}
resolve(result[0])
})
})
}
exports.fun = async function(arg){
let res = {}
if(!('user' in arg) || !('password' in arg)){
res.type = 'ERROR_PARAMS_NUM'
return JSON.stringify(res)
}
let user = arg.user
let password = <PASSWORD>
let userInfo = await link()
.then(data => {
return getUser(data, user)
}, err => {
res.type = 'ERROR_DB_CONNECT'
throw err
})
.then(data => data, err => {
if(err == '0'){
res.type = 'ERROR_USER_OR_PWD'
}else{
res.type = 'ERROR_DB_QUERY'
throw err
}
})
if(userInfo && userInfo['password'] == password){
res.type = 'SUCCESS'
res.userid = userInfo['id']
}else{
res.type = 'ERROR_USER_OR_PWD'
}
return JSON.stringify(res)
}
| 3a2bb9730c06c19cbc784ebf7ac129c9852b64d7 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | wljing/web | b071f0c2c4abf5bb9fe21d33ed8fecea4fe2db1e | 1bdaac0d31da4cea9df63e277f148a4afbf7f2d3 |
refs/heads/master | <file_sep>
window.onload = function() {
// slider
const selectorImages = "data-img-slide";
const selectorMobileImages = "data-mobile-img-slide";
const selectorSlides = "data-slide";
const selectorButtons = "data-direction";
let activeIndex = 0;
const images = document.querySelectorAll("[" + selectorImages + "]");
const imagesMobile = document.querySelectorAll("[" + selectorMobileImages + "]");
const descriptions = document.querySelectorAll("[" + selectorSlides + "]");
const buttons = document.querySelectorAll("[" + selectorButtons + "]");
const setVisibility = (element, selector) => {
if (parseInt(element.getAttribute(selector)) !== activeIndex)
element.classList.add("hidden");
else
element.classList.remove("hidden");
};
const showSlider = () => {
if(images.length === descriptions.length && imagesMobile.length === descriptions.length){
images.forEach(element => {
setVisibility(element, selectorImages);
});
imagesMobile.forEach(element => {
setVisibility(element, selectorMobileImages);
});
descriptions.forEach(element => {
setVisibility(element, selectorSlides);
});
}
else{
console.error("Error: The slider images and the slider descriptions must be the same quantity.");
}
};
buttons.forEach(element => {
element.addEventListener("click", function (event){
let direction = event.target.getAttribute(selectorButtons);
switch(direction){
case "left":
activeIndex--;
if(activeIndex < 0) activeIndex += descriptions.length;
activeIndex = activeIndex % descriptions.length;
break;
case "right":
activeIndex++;
activeIndex = activeIndex % descriptions.length;
break;
default:
console.error("Error: The slider direction must be 'left' or 'right'.");
break;
}
showSlider();
});
});
showSlider();
// slider
// menu mobile
const selectorToggleMenu = "data-menu";
const toggleMenu = document.querySelectorAll("[" + selectorToggleMenu + "]");
toggleMenu.forEach(element => {
element.addEventListener("click", function (event){
let parent = event.target.parentNode;
parent.classList.toggle("open");
});
});
// menu mobile
}
| 2458270bf08fc095ab44903bd99f6485c8ee6845 | [
"JavaScript"
] | 1 | JavaScript | leugiim/room-homepage-master | 7fc3fb8e4b714298eef21ea64c162f541b401d35 | becceb87bd4b0012ce4297f1480d2aae0e87e5f6 |
refs/heads/master | <file_sep>const data = require("../../db/planets.js");
const Croupier = function (cards) {
this.deck = this.discardRubbishCards(cards);
}
Croupier.prototype.playCard = function (planet) {
// returns a subset of the fields needed for playing
return {
pl_name : planet.pl_name,
pl_radj : planet.pl_radj,
pl_orbsmax : planet.pl_orbsmax,
pl_orbper : planet.pl_orbper,
st_teff : planet.st_teff,
pl_pnum : planet.pl_pnum,
pl_bmassj: planet.pl_bmassj
};
};
Croupier.prototype.cardIsGood = function (planet) {
return planet.pl_radj !== null && // radius as multiple of Jupiter
planet.pl_bmassj !== null && // best-guess mass relative to jupiter
planet.pl_orbsmax !== null && // max distance from star in AU
planet.pl_orbper !== null && // orbital period, days
planet.st_teff != null && // blackbody color temperature (gives a hint as to colour)
planet.pl_pnum != null; // number of planets
};
Croupier.prototype.discardRubbishCards = function (cards) {
// gets rid of cards where some of the fields are missing
// about 10% of cards are suitable
return cards.filter( (card) => {
return this.cardIsGood(card);
}).map((planet) => {
// return JUST the playing fields
return this.playCard(planet);
});
};
Croupier.prototype.deal = function(number_per_player=1) {
// given deck and number of cards per player,
// return flat array of 2*number_per_player cards
let validCards = this.shuffle(this.deck);
let result = validCards.slice(0, number_per_player * 2);
return result;
};
Croupier.prototype.shuffle = function (myArray) {
// Fisher-Yates shuffle
// shuffles array in place
// got pseudocode from
function getRandomInt(max) {
// ger random integer in range [0,max]
return Math.floor(Math.random() * Math.floor(max));
};
let n = myArray.length;
for (let i = n-1; i > 0; i -= 1) {
let j = getRandomInt(i);
let temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
};
return myArray;
};
// quick (unexported) check to see that the shuffling works
// it's not possible to test this with a unit test as the
// results are random. run this module in node to check this.
let croupier = new Croupier(data);
croupier.deal().forEach( (planet) => {
console.log(`"${planet.pl_name}" Dist:${planet.pl_orbsmax} OrbDays:${planet.pl_orbper} Rad:${planet.pl_radj}, Mass:${planet.pl_bmassj}`);
});
module.exports = Croupier;
<file_sep>const PubSub = require('../helpers/pub_sub.js');
const CardView = require('./card_view.js');
const CardGridView = function (container){
this.container = container;
this.currentMatchCards = [];
};
CardGridView.prototype.bindEvents = function () {
PubSub.subscribe('Deck:drawn-cards', (event) => {
PubSub.signForDelivery(this,event);
this.clearGrid();
this.renderCards(event.detail,1);
this.currentMatchCards = event.detail;
});
PubSub.subscribe('Game:reveal-both-cards', (event) => {
// reveal both cards
PubSub.signForDelivery(this,event);
this.clearGrid();
this.revealCards(this.currentMatchCards);
});
PubSub.subscribe('Game:current-player-turn', (event) => {
// we know who is next up. If it's player1,
// hide player2 card, otherwise show both.
PubSub.signForDelivery(this,event);
const new_player = event.detail; // 1 or 2
this.clearGrid();
PubSub.publish("Game:message", `Over to player ${new_player}`);
this.renderCards(this.currentMatchCards, new_player);
});
};
CardGridView.prototype.clearGrid = function () {
this.container.innerHTML = '';
};
CardGridView.prototype.revealCards = function (cards) {
// show both cards
cards.forEach((card, index, array) => {
const cardItem = this.createCardItem(card, index+1);
this.container.appendChild(cardItem);
});
};
CardGridView.prototype.renderCards = function (cards, currentPlayer) {
cards.forEach((card, index, array) => {
const cardItem = this.createCardItem(card, index+1);
// if card index (1=left,2=right) doesn't match current player
// then mark card to be hidden
if (index+1 != currentPlayer) {
cardItem.classList.add("back");
}
this.container.appendChild(cardItem);
});
};
CardGridView.prototype.createCardItem = function (card, playerNumber) {
const cardView = new CardView(this.container,playerNumber);
const cardItem = cardView.renderCardDetails(card, playerNumber);
return cardItem;
};
module.exports = CardGridView;
<file_sep>const PubSub = require('../helpers/pub_sub.js');
const GameWinnerView = function (element){
this.element = element
};
GameWinnerView.prototype.bindEvents = function () {
PubSub.subscribe('Game:game-winner-determined', (event) => {
this.renderModal(event.detail);
});
// this.element.addEventListener("click", (event) => {
// this.element.style.visibility = 'hidden';
// })
}
GameWinnerView.prototype.renderModal = function (winnerPhrase) {
this.element.innerHTML = '';
this.element.style.visibility = 'visible';
const gameWinnerContent = document.createElement('div');
gameWinnerContent.className = 'game-winner-content';
const body = document.createElement('div');
body.className = 'gameWinnerBody';
winnerLine = document.createElement('p');
winnerLine.className = 'winnerLine';
winnerLine.textContent = winnerPhrase;
body.appendChild(winnerLine);
gameWinnerContent.appendChild(body)
this.element.appendChild(gameWinnerContent);
};
module.exports = GameWinnerView;
<file_sep>const PubSub = require('../helpers/pub_sub.js');
const StartGameButtonView = function (element) {
this.element = element;
};
StartGameButtonView.prototype.bindEvents = function () {
this.element.addEventListener("click", (event) => {
this.element.hidden = 'true'
PubSub.publish("StartButton:start-game",{});
});
};
module.exports = StartGameButtonView;
<file_sep>const express = require('express');
const Croupier = require("./croupier");
const PlanetRouter = function (collection) {
const router = express.Router();
console.log("Making router");
// mvp - pass back 1 card per player
router.get('/', (req, res) => {
croupier = new Croupier(collection);
res.json(croupier.deal(2));
});
router.get('/deal/:number', (req, res) => {
croupier = new Croupier(collection);
var count_per_player = parseInt(req.params.number);
res.json(croupier.deal(count_per_player));
});
return router;
}
module.exports = PlanetRouter;
<file_sep>const PubSub = require("./helpers/pub_sub");
const Game = require('./models/game.js');
const CardsGridView = require('./views/cards_grid_view.js');
const WinnerView =require("./views/winner_view.js");
const HandCounterView = require("./views/hand_counter_view.js");
const NextMatchButtonView = require("./views/next_match_button_view.js");
const StartGameButtonView = require("./views/start_game_button_view.js");
const RulesButtonView = require("./views/rules_button_view.js");
const RulesView = require("./views/rules_view.js");
const MessageView = require("./views/message_view.js");
const GameWinnerView = require("./views/game_winner_view.js");
document.addEventListener('DOMContentLoaded', () => {
console.log("DOM has loaded")
const game = new Game();
game.bindEvents();
game.populateDeck();
/* Card deck and scores */
const cardsGridView = new CardsGridView(document.querySelector('#card-grid-container'));
cardsGridView.bindEvents();
const winnerView = new WinnerView(document.querySelector("#winner-container"));
winnerView.bindEvents();
const player1HandCounterView = new HandCounterView(
document.querySelector("#player1"),
1
);
player1HandCounterView.bindEvents();
const player2HandCounterView = new HandCounterView(
document.querySelector("#player2"),
2
);
player2HandCounterView.bindEvents();
/* main button bar **/
const nextMatchButtonView = new NextMatchButtonView(
document.querySelector('#next-match')
);
nextMatchButtonView.bindEvents();
const startGameButtonView = new StartGameButtonView(
document.querySelector("#start-game")
);
startGameButtonView.bindEvents();
/** Rules button and modal */
const rulesButtonView = new RulesButtonView(
document.querySelector('#rules-button')
);
rulesButtonView.bindEvents();
const rulesView = new RulesView(
document.querySelector('#rules-modal-container')
);
rulesView.bindEvents();
/* Message View */
const messageView = new MessageView(
document.querySelector('.message-bar-message')
);
messageView.bindEvents();
/* say hello */
PubSub.publish("Game:message", "Welcome to Planet Wars!");
const gameWinnerView = new GameWinnerView(
document.querySelector('#winner-modal-container')
);
gameWinnerView.bindEvents();
});
<file_sep>const PubSub = require('../helpers/pub_sub.js');
const NextMatchButtonView = function (element) {
this.element = element;
};
NextMatchButtonView.prototype.bindEvents = function () {
this.element.addEventListener("click", (event) => {
PubSub.publish("NextMatchButton:start-next-match",{});
});
PubSub.subscribe('NextMatchButton:start-next-match', () => {
this.element.hidden = true;
})
PubSub.subscribe('Game:reveal-both-cards', () => {
this.element.hidden = false;
})
};
module.exports = NextMatchButtonView;
<file_sep>const PubSub = require('../helpers/pub_sub.js');
const RulesButtonView = function (element){
this.element = element
};
RulesButtonView.prototype.bindEvents = function () {
this.element.addEventListener("click", (event) => {
PubSub.publish("Rules:show-rules",{});
});
};
module.exports = RulesButtonView;
<file_sep>const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const PlanetRouter = require('./helpers/create_router.js');
const data = require('../db/planets.js');
const publicPath = path.join(__dirname, '../../client/public');
app.use('/', express.static(publicPath));
app.use(bodyParser.json());
const port = process.env.PORT || 3000
const planetRouter = new PlanetRouter(data);
app.use('/api/exoplanets', planetRouter);
app.listen(port, function () {
console.log(`Started server on port ${port}`);
});
<file_sep>const PubSub = require('../helpers/pub_sub.js');
const MessageView = function (container) {
this.container = container;
};
MessageView.prototype.bindEvents = function () {
PubSub.subscribe("Game:message", (event) => {
const message = event.detail;
this.container.innerHTML = message;
});
};
module.exports = MessageView;
<file_sep>const assert = require('assert');
const Deck = require('../deck.js');
describe('Deck', function () {
let deck;
let cardDeck;
beforeEach(function () {
deck = new Deck();
cardDeck = [1,2,3,4,5,6,7,8,9,10];
});
it('should split a deck', function () {
const expected = [[1,2,3,4,5],[6,7,8,9,10]];
assert.deepStrictEqual(deck.splitDeck(cardDeck), expected );
});
it('should pop a card from each deck', function () {
const expected = [5,10];
assert.deepStrictEqual(deck.popCardsForPlayers(deck.splitDeck(cardDeck)), expected);
});
// it('should check the .length feature works', function (){
// const expected = 10;
// assert.strictEqual(cardDeck.length, expected);
// })
//
// it('should get an array of hand sizes', function (){
// const expected = [5, 5];
// const splitDeck = deck.splitDeck(cardDeck);
// assert.deepStrictEqual(deck.getHandSizes(splitDeck), expected);
// });
});
<file_sep># javascript_nasa_top_trumps
##Purpose
This app is designed as an educational game aimed at a primary audience of students aged 12-16 to increase their knowledge of exoplanets and their properties.
The app can also be utilised by teachers as a learning tool for their students. Anyone with an interest in furthering their education of exoplanets could also use this app.
##The Game
This app simulates a game of Top Trumps using Exoplanet data.
###Game Rules
##Requirements
Please follow the instructions below to run this app:
- git clone this repository into a folder of your choice.
- in terminal type "npm install"
- type "npm run build"
- type "npm run server:dev"
- in the browser go to 'localhost:3000'
You should now be able to run the app.
##Brief
Browser Game
Create a browser game based on an existing card or dice game. Model and test the game logic and then display it in the browser for a user to interact with.
Write your own MVP with some specific goals to be achieved based on the game you choose to model.
You might use persistence to keep track of the state of the game or track scores/wins. Other extended features will depend on the game you choose.
##Our MVP
- the app will have access to data
- the app will display two cards with data
- the app will compare two cards on one data field
- the app will declare a winner
##Extensions
- the app can hold a hand of cards for each player
- the app can track the hands as matches are played
- the app declares a winner for each match
- the app declares a winner for the overall game
| e7599a63cc44c3fb62302fee95bb13866cf033e5 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | stevefaeembra/javascript_nasa_top_trumps | d6c04d502bbd415d73bfce80a900dd4d70d314d5 | 5989714ede129820e92c3ac7d3fe537bc5939af2 |
refs/heads/master | <repo_name>MohamedAE/OpenGL-Particles<file_sep>/Elmekki_particle_space.c
/* File: Elmekki_particle.c
Author: <NAME>
Date: 06-03-2017
Topic: CST 8234 Assignment 3
To generate a particle system: a computer graphic technique to
simulate fuzzy objects.
Purpose: Design, code, and test a simple implementation of linked lists.
Use multiple files in a program.
Use of a Makefile.
Notes: "Warp speed"
A simulation of flying through space, stars whizzing by.
*/
/* -----------------------------------------------------------------------------
INCLUDES
----------------------------------------------------------------------------- */
#include "Elmekki_particle.h"
/*------------------------------------------------------------------------------
FUNCTIONS
----------------------------------------------------------------------------- */
/*------------------------------------------------------------------------------
Function : particle_init
Purpose : initialize the properties of a single particle_init
Input : pointer to the particle structure to be initialized
Output : returns -1 on error, 0 on success
------------------------------------------------------------------------------*/
int particle_init(struct particle *p) {
/* Initialize colour (white) */
p->col.r = p->col.g = p->col.b = 1.0;
/* Initialize aplha with a low value */
p->col.a = 0.01;
/* Initialize position to 0,0 */
p->pos.x = p->pos.y = p->pos.z = 0.0;
/* Initialize random direction vector; x */
p->dir.x = random_number(-10, 10);
/* Generate a new value if initial value is too low */
while (p->dir.x > -1 && p->dir.x < 1) {
p->dir.x = random_number(-10, 10);
}
/* Initialize random direction vector; y */
p->dir.y = random_number(-10, 10);
/* Generate a new value if initial value is too low */
while (p->dir.y > -1 && p->dir.y < 1) {
p->dir.y = random_number(-10, 10);
}
/* Initialize speed vector */
p->spd.x = p->spd.y = 0.01;
/* Initialize lifespan and size */
p->lifespan = 100;
p->size = 0.1;
return 0;
}
/*------------------------------------------------------------------------------
Function : particle_add
Purpose : add a particle to the dynamic particle linked list
Input : struct particle *head; head of the particle lists
Output : returns -1 on error, 0 on success
Notes : calls particle_init()
------------------------------------------------------------------------------*/
int particle_add(struct particle **head) {
particle_t *newNode;
if ((newNode = (particle_t *) malloc(sizeof(particle_t))) == NULL) {
return -1;
}
particle_init(newNode);
newNode->next = *head;
*head = newNode;
return 0;
}
/*------------------------------------------------------------------------------
Function : particle_remove
Purpose : remove a specific particle from the dynamic particle linked
list
Input : pointer to the particle to remove
Output : returns -1 on error, 0 on success
Notes : particle can be situated in any place in the list
usually deleted because lifespan ran out
------------------------------------------------------------------------------*/
int particle_remove(struct particle *p) {
particle_t *part = p;
particle_t *remove;
if (p->next == NULL) return -1;
remove = part->next;
part->next = remove->next;
free(remove);
return 0;
}
/*------------------------------------------------------------------------------
Function : particle_destroy
Purpose : free memory used by the dynamic particle linked list
Input : struct **head; head of the particle linked list
Output : returns -1 on error, the number of particles destroyed on
success
Notes : removes all particles from the list
calls particle_remove() on each
------------------------------------------------------------------------------*/
int particle_destroy(struct particle **head) {
particle_t *remove;
int count = 0;
if (*head == NULL) return -1;
while (*head != NULL) {
remove = *head;
*head = remove->next;
particle_remove(remove);
count++;
}
return count;
}
/*------------------------------------------------------------------------------
Function : particle_update
Purpose : update the particle's properties to be renedered in the next
frame
Input : struct particle **head; head of the particle linked list
Output : returns -1 on error, 0 on success
Notes : GO NUTS!!!!
------------------------------------------------------------------------------*/
int particle_update(struct particle **head) {
particle_t *curr = *head;
if (curr == NULL) return -1;
while (curr != NULL) {
curr->col.a += 0.01;
/* Update x position */
curr->pos.x += (curr->spd.x * curr->dir.x);
/* If particle passes window boundaries, reinitialize */
if (curr->pos.x > 300 || curr->pos.x < -300) {
particle_init(curr);
}
/* Update y position */
curr->pos.y += (curr->spd.y * curr->dir.y);
/* If particle passes window boundaries, reinitialize */
if (curr->pos.y > 300 || curr->pos.y < -300) {
particle_init(curr);
}
/* Update speed */
curr->spd.x += 0.01;
curr->spd.y += 0.01;
/* Increase size */
curr->size += 0.05;
/* Particles are recycled when they reach the boundary, making lifespan
arbitrary (no need to check if lifespan is 0).
*/
curr = curr->next;
}
return 0;
}
/*------------------------------------------------------------------------------
Function : random_number
Purpose : generate and return a random number
Input : boundaries within witch a number is calculated
Output : returns a random number within given boundaries
------------------------------------------------------------------------------*/
int random_number(int min, int max) {
return (min + rand() % (max - min + 1));
}
<file_sep>/README.md
# OpenGL-Particles
Small demos of particle effects using OpenGL, written in C.
Implemented using a linked list.
Demonstrations are viewable as Gifs or on YouTube.
Space demo
https://youtu.be/VWJw_uOv0eg
Fountain demo
https://youtu.be/JCS8m2QAhH4
<file_sep>/Elmekki_particle.h
/* File: Elmekki_particles.h
Author: <NAME>
Date: 06-03-2017
Topic: CST 8234 Assignment 3
To generate a particle system: a computer graphic technique to
simulate fuzzy objects.
Purpose: Design, code, and test a simple implementation of linked lists.
Use multiple files in a program.
Use of a Makefile.
Notes:
*/
/* -----------------------------------------------------------------------------
INCLUDES
----------------------------------------------------------------------------- */
#include <stdlib.h>
/* -----------------------------------------------------------------------------
DEFINES
----------------------------------------------------------------------------- */
#define DFLT_INIT_NUM_PARTICLES 50
#define DELTA_LIFESPAN 1
/* -----------------------------------------------------------------------------
STRUCT DECLARATIONS
------------------------------------------------------------------------------*/
struct vector {
float x, y, z;
};
typedef struct vector Point3D_t;
typedef struct vector Vector3D_t;
typedef struct colour {
float r, g, b, a;
} colour4_t;
typedef struct particle {
colour4_t col;
Point3D_t pos;
Vector3D_t dir;
Vector3D_t spd;
int lifespan;
float size;
struct particle* next;
} particle_t;
/*------------------------------------------------------------------------------
FUNCTION PROTOTYPES
------------------------------------------------------------------------------*/
int particle_init(struct particle *p);
int particle_add(struct particle **head);
int particle_remove(struct particle *p);
int particle_destroy(struct particle **head);
int particle_update(struct particle **head);
int particle_destroy_recur(struct particle *part);
int random_number(int min, int max); | d4836c8cb991c68051b73572477305379bb1c456 | [
"Markdown",
"C"
] | 3 | C | MohamedAE/OpenGL-Particles | f548d50f0769c98bc24ef27849a7d2833fa77fb6 | 25242e50e12dd8c4a85a13e3c194a172cc72c147 |
refs/heads/master | <file_sep>package io.github.jython234.jpacketlib.types;
/**
* Created by atzei on 2/21/2016.
*/
public class Constant {
private String name;
private ConstantType type;
private Object value;
public Constant(String name, ConstantType type, Object value) {
this.name = name;
this.type = type;
this.value = value;
}
public String getName() {
return name;
}
public ConstantType getType() {
return type;
}
public Object getValue() {
return value;
}
}
<file_sep>package io.github.jython234.jpacketlib.types;
/**
* Represents different types of fields.
*/
public enum FieldType {
BYTE("byte", byte.class, 1),
BOOL("bool", boolean.class, 1),
SHORT("int16", short.class, 2),
USHORT("uint16", int.class, 2),
INTEGER("int32", int.class, 4),
UINTEGER("uint32", long.class, 4),
LONG("int64", long.class, 8),
FLOAT("float", float.class, 4),
DOUBLE("double", double.class, 8),
INT24("int24", int.class, 3),
UINT24("uint24", int.class, 3),
STRING("str", String.class, 2), //Length here specifies how many bytes to read to get the string length
BYTES("bytes", byte[].class, -1);
private String type;
private Class asClass;
private int len;
FieldType(String type, Class asClass, int len) {
this.type = type;
this.asClass = asClass;
this.len = len;
}
public void setLength(int len) {
this.len = len;
}
public int getLength() {
return len;
}
public static FieldType parseType(String string) {
if(string.equals("int16")) {
return FieldType.valueOf("SHORT");
} else if(string.equals("uint16")) {
return FieldType.valueOf("USHORT");
} else if(string.equals("int32")) {
return FieldType.valueOf("INTEGER");
} else if(string.equals("uint32")) {
return FieldType.valueOf("UINTEGER");
} else if(string.equals("int64")) {
return FieldType.valueOf("LONG");
} else if(string.equals("str")) {
return FieldType.valueOf("STRING");
} else {
return FieldType.valueOf(string.toUpperCase());
}
}
public Class getAsClass() {
return asClass;
}
@Override
public String toString() {
return type;
}
}
<file_sep>package io.github.jython234.jpacketlib;
import io.github.jython234.jpacketlib.packet.PacketDefinition;
import io.github.jython234.jpacketlib.types.Constant;
import io.github.jython234.jpacketlib.types.ConstantType;
import io.github.jython234.jpacketlib.types.FieldType;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class that loads and parses packet definitions. (.NPD)
*/
public class DefinitionParser {
public static Protocol parseDocument(File file) {
Protocol protocol = null;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
Element root = doc.getDocumentElement();
root.normalize();
protocol = new Protocol(root.getAttribute("name"), Integer.parseInt(root.getAttribute("version")));
//TODO: Check Exceptions
NodeList packets = doc.getElementsByTagName("packet");
for(int i = 0; i < packets.getLength(); i++) {
Element element = (Element) packets.item(i);
element.normalize();
String pkName = element.getAttribute("name");
int pid = Integer.parseInt(element.getElementsByTagName("pid").item(0).getTextContent(), 16);
int length = Integer.parseInt(element.getElementsByTagName("length").item(0).getTextContent());
if(length < -1) throw new ParseException("Packet Length must be positive or -1");
Map<String, FieldType> fieldMap = new HashMap<>();
List<String> order = new ArrayList<>();
NodeList fields = element.getElementsByTagName("field");
for(int i2 = 0; i2 < fields.getLength(); i2++) {
Element field = (Element) fields.item(i2);
field.normalize();
String fieldName = field.getAttribute("name");
String fieldType = field.getAttribute("type");
order.add(i2, fieldName);
if(fieldType.equals(FieldType.BYTES.toString())) {
if(!field.hasAttribute("length")) throw new ParseException("Length not specified for fieldType \"bytes\"");
FieldType f = FieldType.BYTES;
f.setLength(Integer.parseInt(field.getAttribute("length")));
fieldMap.put(fieldName, f);
continue;
}
if(fieldType.equals(FieldType.STRING.toString()) && field.hasAttribute("length_type")) {
FieldType f = FieldType.STRING;
f.setLength(Integer.parseInt(field.getAttribute("count_length")));
fieldMap.put(fieldName, f);
continue;
}
fieldMap.put(fieldName, FieldType.parseType(fieldType));
}
protocol.addPacketDef(new PacketDefinition(pid, pkName, length, fieldMap, order));
}
NodeList constants = doc.getElementsByTagName("const");
for(int i = 0; i < constants.getLength(); i++) {
Element element = (Element) constants.item(i);
String name = element.getAttribute("name");
ConstantType type = ConstantType.valueOf(element.getAttribute("type"));
String value = element.getAttribute("value");
Constant c;
try {
switch (type) {
case INTEGER:
c = new Constant(name, type, Integer.parseInt(value));
break;
case DECIMAL:
c = new Constant(name, type, Double.parseDouble(value));
break;
default:
c = new Constant(name, type, value);
}
protocol.addConstant(c);
} catch (NumberFormatException e) {
throw new ParseException("Value of constant \""+name+"\" must match type: \""+type+"\"");
}
}
} catch (Exception e) {
throw new ParseException(e);
}
return protocol;
}
}
<file_sep>package io.github.jython234.jpacketlib.packet;
import io.github.jython234.jpacketlib.types.FieldType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Represents a packet in a protocol with fields.
*/
public class PacketDefinition {
private final int ID;
private final String name;
private final int length;
private List<String> order;
private Map<String, FieldType> fields;
public PacketDefinition(int id, String name, int length, Map<String, FieldType> fields, List<String> order) {
this.name = name;
this.length = length;
this.fields = fields;
this.order = order;
this.ID = id;
}
public PacketDefinition(int id, String name) {
this.name = name;
this.length = -1;
this.fields = new HashMap<String, FieldType>();
this.order = new ArrayList<>();
this.ID = id;
}
public FieldType getFieldType(String name) {
return fields.get(name);
}
public List<String> getOrderOfFields() {
return order;
}
public boolean hasField(String name) {
return fields.containsKey(name);
}
public int getID() {
return ID;
}
public String getName() {
return name;
}
public int getLength() {
return length;
}
}
| 82e95207a2eac6a877c8fd4df8e3a3cc60388440 | [
"Java"
] | 4 | Java | alejzeis/JPacketLib | 7ded65af8d4e4c3f01298aa3f4ad9badc63f8b98 | fa2b8054fc023c652c27a34345508a94f934ca46 |
refs/heads/master | <file_sep>/*
Navicat Premium Data Transfer
Source Server : node
Source Server Type : MySQL
Source Server Version : 50727
Source Host : localhost:3306
Source Schema : qq
Target Server Type : MySQL
Target Server Version : 50727
File Encoding : 65001
Date: 24/03/2020 10:56:13
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for message
-- ----------------------------
DROP TABLE IF EXISTS `message`;
CREATE TABLE `message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`avatar` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
`time` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`message` longtext CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`roomid` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 153 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of message
-- ----------------------------
INSERT INTO `message` VALUES (141, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/21.jpg', '2019/11/4 下午5:35:09', '007在2号房', '2');
INSERT INTO `message` VALUES (142, '008', 'https://ui.aiyichuan.com/fhcloud/testavatar/28.jpg', '2019/11/4 下午5:36:16', '008在2号房间', '2');
INSERT INTO `message` VALUES (143, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2019/11/5 上午10:38:50', '11.5', '2');
INSERT INTO `message` VALUES (144, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020/3/13 上午10:13:04', 'gfdgfdgfd', '1');
INSERT INTO `message` VALUES (145, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020/3/13 上午10:13:07', 'gdfgfdg', '1');
INSERT INTO `message` VALUES (146, '3', 'https://ui.aiyichuan.com/fhcloud/testavatar/8.jpg', '2020/3/13 上午10:22:49', 'fuck', '1');
INSERT INTO `message` VALUES (147, '3', 'https://ui.aiyichuan.com/fhcloud/testavatar/8.jpg', '2020/3/13 上午10:22:53', 'mother fucker', '1');
INSERT INTO `message` VALUES (148, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020/3/13 上午10:23:08', '......', '1');
INSERT INTO `message` VALUES (149, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020/3/13 上午10:23:12', '1233', '1');
INSERT INTO `message` VALUES (150, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020/3/13 上午10:23:13', '1231', '1');
INSERT INTO `message` VALUES (151, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020/3/13 上午10:23:13', '321', '1');
INSERT INTO `message` VALUES (152, '007', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020/3/13 上午10:23:14', '32132', '1');
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/*
Navicat Premium Data Transfer
Source Server : node
Source Server Type : MySQL
Source Server Version : 50727
Source Host : localhost:3306
Source Schema : qq
Target Server Type : MySQL
Target Server Version : 50727
File Encoding : 65001
Date: 24/03/2020 10:56:26
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for rooms
-- ----------------------------
DROP TABLE IF EXISTS `rooms`;
CREATE TABLE `rooms` (
`id` int(11) NOT NULL,
`name` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
`icon` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of rooms
-- ----------------------------
INSERT INTO `rooms` VALUES (1, 'Room1', 'https://cdn.guaiwola.com/img/wuzeiniang.12004873.gif?imageView2/3/w/88/h/88');
INSERT INTO `rooms` VALUES (2, 'Room2', 'https://cdn.guaiwola.com/GroupAvatar/5db81d6808458d6e95094648_1572596492343?imageView2/3/w/96/h/96');
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/*
Navicat Premium Data Transfer
Source Server : node
Source Server Type : MySQL
Source Server Version : 50727
Source Host : localhost:3306
Source Schema : qq
Target Server Type : MySQL
Target Server Version : 50727
File Encoding : 65001
Date: 24/03/2020 10:56:20
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for rank
-- ----------------------------
DROP TABLE IF EXISTS `rank`;
CREATE TABLE `rank` (
`type` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '类型',
`date` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '更新时间',
`type_id` int(11) NOT NULL COMMENT '分类id',
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 17 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of rank
-- ----------------------------
INSERT INTO `rank` VALUES ('欧美榜', '更新时间:2020-03-12', 3, 1);
INSERT INTO `rank` VALUES ('流行指数榜', '更新时间:2020-03-13', 4, 2);
INSERT INTO `rank` VALUES ('内地榜', '更新时间:2019-10-17', 5, 3);
INSERT INTO `rank` VALUES ('韩国榜', '更新时间:2020-03-12', 16, 4);
INSERT INTO `rank` VALUES ('日本榜', '更新时间:2020-03-12', 17, 5);
INSERT INTO `rank` VALUES ('热歌榜', '更新时间:2020-03-12', 26, 6);
INSERT INTO `rank` VALUES ('新歌榜', '更新时间:2020-03-13', 27, 7);
INSERT INTO `rank` VALUES ('网络歌曲榜', '更新时间:2019-07-25', 28, 8);
INSERT INTO `rank` VALUES ('影视金曲榜', '更新时间:2019-07-25', 29, 9);
INSERT INTO `rank` VALUES ('', '', 36, 10);
INSERT INTO `rank` VALUES ('腾讯音乐人原创榜', '更新时间:2020-03-11', 52, 11);
INSERT INTO `rank` VALUES ('电音榜', '更新时间:2019-09-05', 57, 12);
INSERT INTO `rank` VALUES ('说唱榜', '更新时间:2020-03-12', 58, 13);
INSERT INTO `rank` VALUES ('香港地区榜', '更新时间:2020-03-12', 59, 14);
INSERT INTO `rank` VALUES ('抖音排行榜', '更新时间:2020-03-12', 60, 15);
INSERT INTO `rank` VALUES ('台湾地区榜', '更新时间:2020-03-12', 61, 16);
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/*
Navicat Premium Data Transfer
Source Server : node
Source Server Type : MySQL
Source Server Version : 50727
Source Host : localhost:3306
Source Schema : qq
Target Server Type : MySQL
Target Server Version : 50727
File Encoding : 65001
Date: 24/03/2020 10:56:31
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
`password` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
`avatar` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
`time` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`token` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
`limit` text CHARACTER SET utf8 COLLATE utf8_bin NULL,
`roomid` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 40 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (35, '007', '000', 'https://ui.aiyichuan.com/fhcloud/testavatar/4.jpg', '2020-3-13 10:13:38', '8da2710bd3a9df067a95098479728a0b', 'a78e1e3a6988ff558628f5ad2bd26297', 0);
INSERT INTO `user` VALUES (36, '008', '000', 'https://ui.aiyichuan.com/fhcloud/testavatar/28.jpg', '2019-11-4 5:36:07 PM', 'da60817d8c40a3b7b5a5daeb273c9c3a', '7bfce0c50d9cc4551e6b4ef552c4ccda', 0);
INSERT INTO `user` VALUES (37, '111', '111', 'https://ui.aiyichuan.com/fhcloud/testavatar/21.jpg', '2019-11-11 5:31:37 PM', 'f2f004857b65836382b55b857a25ebc7', 'e931d9335eb8ae0bada75ae22308d273', 1);
INSERT INTO `user` VALUES (38, '3', '33', 'https://ui.aiyichuan.com/fhcloud/testavatar/8.jpg', '2020-3-13 10:22:36', '4b225e740f90fca0123265618e405e64', '25c0c0b7dddec9fb058331f7b06825e4', 1);
INSERT INTO `user` VALUES (39, NULL, NULL, NULL, '1584066913', '7ecfb3bf076a6a9635f975fe96ac97fd', '7ecfb3bf076a6a9635f975fe96ac97fd', NULL);
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/*
Navicat Premium Data Transfer
Source Server : node
Source Server Type : MySQL
Source Server Version : 50727
Source Host : localhost:3306
Source Schema : qq
Target Server Type : MySQL
Target Server Version : 50727
File Encoding : 65001
Date: 24/03/2020 10:56:04
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for list
-- ----------------------------
DROP TABLE IF EXISTS `list`;
CREATE TABLE `list` (
`songname` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '歌曲名称',
`type_id` int(11) NOT NULL COMMENT '分类id',
`singer` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT '歌手名字',
`rank` int(255) NOT NULL COMMENT '排名顺序'
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of list
-- ----------------------------
INSERT INTO `list` VALUES ('情深深雨濛濛', 28, '杨胖雨', 3);
INSERT INTO `list` VALUES ('我走后', 28, '小咪', 4);
INSERT INTO `list` VALUES ('余情未了', 28, '魏新雨', 5);
INSERT INTO `list` VALUES ('多年以后', 28, '大欢', 6);
INSERT INTO `list` VALUES ('孤独', 28, '是你大哥阿', 7);
INSERT INTO `list` VALUES ('那女孩对我说 (完整版)', 28, 'Uu', 8);
INSERT INTO `list` VALUES ('Batte Forte凤舞九天 (DJ弹鼓版)', 28, '承利', 9);
INSERT INTO `list` VALUES ('天下有情人 (国语版)', 28, '童珺', 10);
INSERT INTO `list` VALUES ('把孤独当作晚餐', 28, 'MC画词戏子', 11);
INSERT INTO `list` VALUES ('云水谣', 28, 'en', 12);
INSERT INTO `list` VALUES ('迷人的危险', 28, '馅儿/neko', 13);
INSERT INTO `list` VALUES ('归去来兮', 28, '曼殊', 14);
INSERT INTO `list` VALUES ('纵歌万里游', 28, '叶洛洛· “我为家乡写情诗”主题曲', 15);
INSERT INTO `list` VALUES ('一百万个可能', 28, '艾辰', 16);
INSERT INTO `list` VALUES ('17岁', 28, '梦涵', 17);
INSERT INTO `list` VALUES ('从前的我快乐过', 28, '蒋雪儿', 18);
INSERT INTO `list` VALUES ('撕夜', 28, '王恰恰', 19);
INSERT INTO `list` VALUES ('十一', 28, '穆哲熙', 21);
INSERT INTO `list` VALUES ('拜拜', 28, '浙音4811', 20);
INSERT INTO `list` VALUES ('归寻', 28, '等什么君', 22);
INSERT INTO `list` VALUES ('只要你还需要我', 28, '小曼', 23);
INSERT INTO `list` VALUES ('酒空人醒', 28, '李冠霖', 25);
INSERT INTO `list` VALUES ('野花香', 28, '莫斯满/老猫', 24);
INSERT INTO `list` VALUES ('超级英雄狂想曲', 28, '龚十一', 26);
INSERT INTO `list` VALUES ('洪荒之力 (抖音热播)', 28, '8先生/李仕伟', 27);
INSERT INTO `list` VALUES ('一世薄凉', 28, '海来阿木', 28);
INSERT INTO `list` VALUES ('琵琶语', 28, '糯米Nomi', 29);
INSERT INTO `list` VALUES ('时间', 28, '贺一航', 30);
INSERT INTO `list` VALUES ('心如止水 (女声完整版)', 28, '喻言家', 31);
INSERT INTO `list` VALUES ('相遇那么美', 28, '魏新雨', 32);
INSERT INTO `list` VALUES ('成全', 28, '蓝心羽', 33);
INSERT INTO `list` VALUES ('直觉 (女版)', 28, '王珂珂', 34);
INSERT INTO `list` VALUES ('四块五 (DJ咚鼓版)', 28, '浪子康/豪大大', 35);
INSERT INTO `list` VALUES ('我愿意平凡的陪在你身旁 (DjYaha)', 28, '王七七', 36);
INSERT INTO `list` VALUES ('该不会忘了吧', 28, '马晓晨', 37);
INSERT INTO `list` VALUES ('戏影', 28, '彭十六', 38);
INSERT INTO `list` VALUES ('【温宁】赤子', 28, '于斌', 39);
INSERT INTO `list` VALUES ('停摆 (女版)', 28, '小曼', 40);
INSERT INTO `list` VALUES ('黎明前的黑暗', 28, '孟颖', 41);
INSERT INTO `list` VALUES ('我曾 (Cover 隔壁老樊)', 28, '馅儿', 42);
INSERT INTO `list` VALUES ('选择失忆 (DJ咚鼓版)', 28, '季彦霖', 43);
INSERT INTO `list` VALUES ('画者', 28, '鱼香婆婆', 44);
INSERT INTO `list` VALUES ('最寂寞的寂寞', 28, '金南玲', 47);
INSERT INTO `list` VALUES ('爱过了也伤过了', 28, '苏谭谭', 45);
INSERT INTO `list` VALUES ('过期的誓言', 28, '小二哥', 46);
INSERT INTO `list` VALUES ('柒月', 28, '排骨教主', 49);
INSERT INTO `list` VALUES ('人间城', 28, '王贰浪', 48);
INSERT INTO `list` VALUES ('绝不会放过', 28, '徐聪', 50);
INSERT INTO `list` VALUES ('哥们永远', 28, 'Mr.丁/大壮', 52);
INSERT INTO `list` VALUES ('Read All About It (Original Mix)', 28, '泽亦龙', 51);
INSERT INTO `list` VALUES ('通透', 28, '陈亦云', 53);
INSERT INTO `list` VALUES ('波妞和宗介 (抖音版)', 28, '精彩苏刚/陈丙', 54);
INSERT INTO `list` VALUES ('广寒宫', 28, '丸子呦', 55);
INSERT INTO `list` VALUES ('大暑', 28, '音阙诗听/李佳思', 57);
INSERT INTO `list` VALUES ('唯你之光', 28, 'Vk/汐音社', 56);
INSERT INTO `list` VALUES ('错的结果', 28, '唐古', 58);
INSERT INTO `list` VALUES ('天蓬大元帅', 28, '小倩', 59);
INSERT INTO `list` VALUES ('圈住你', 28, '一口甜', 61);
INSERT INTO `list` VALUES ('去终南', 28, '半阳', 60);
INSERT INTO `list` VALUES ('向前走', 28, '龙梅子· 电影《陌上有信》推广曲', 62);
INSERT INTO `list` VALUES ('安暖相伴', 28, '金艾娜/望海高歌', 63);
INSERT INTO `list` VALUES ('其实我们都有故事', 28, '樊少华', 64);
INSERT INTO `list` VALUES ('假如', 28, '伊林', 65);
INSERT INTO `list` VALUES ('不让(盗墓笔记·重启)', 28, '五音Jw/陆深', 67);
INSERT INTO `list` VALUES ('我终究还是爱你的', 28, '魏新雨', 66);
INSERT INTO `list` VALUES ('以爱之名', 28, '麓七· “以爱之名”活动主题曲', 68);
INSERT INTO `list` VALUES ('你笑起来真好看 (正版授权)', 28, '叶嘉', 69);
INSERT INTO `list` VALUES ('回家的路', 28, '大欢', 70);
INSERT INTO `list` VALUES ('恋爱脑少女', 28, '赵露思· 《天雷一部之春花秋月》电视剧片头曲', 71);
INSERT INTO `list` VALUES ('红尘情痴', 28, '王琪', 72);
INSERT INTO `list` VALUES ('假装快乐', 28, '曲肖冰', 73);
INSERT INTO `list` VALUES ('愿', 28, '艾辰', 74);
INSERT INTO `list` VALUES ('画师', 28, '夏婉安', 75);
INSERT INTO `list` VALUES ('三杯酒', 28, '陈雅森', 76);
INSERT INTO `list` VALUES ('我叫安琪拉', 28, '向熙', 77);
INSERT INTO `list` VALUES ('Sweet But Psycho(车载4)', 28, '7妹/琦妹儿', 78);
INSERT INTO `list` VALUES ('别知己', 28, '海来阿木', 79);
INSERT INTO `list` VALUES ('爱情总会败给时间', 28, '贺一航', 80);
INSERT INTO `list` VALUES ('洪荒之力 + 黎明前的黑暗 (DJ阿超 Remix)', 28, 'DJ阿超', 81);
INSERT INTO `list` VALUES ('抱歉,不懂我的人', 28, '鱼大仙儿', 83);
INSERT INTO `list` VALUES ('一去不回来', 28, '张冬玲', 84);
INSERT INTO `list` VALUES ('把孤独当作晚餐', 28, 'MC画词戏子', 82);
INSERT INTO `list` VALUES ('我就喜欢宅在家', 28, '叶洛洛/妖蝠', 85);
INSERT INTO `list` VALUES ('晚安 (DJ弹鼓版)', 28, '浪子康/豪大大', 86);
INSERT INTO `list` VALUES ('洪荒之力电摇 (抖音版)', 28, 'DJ奶小深/DJ蒋先生/普先森', 87);
INSERT INTO `list` VALUES ('情侣之间', 28, '蒋家驹(蒋蒋)', 88);
INSERT INTO `list` VALUES ('旧人', 28, '安苏羽', 89);
INSERT INTO `list` VALUES ('Coming Home (改版)', 28, '新旭', 90);
INSERT INTO `list` VALUES ('光明', 28, '张茜', 91);
INSERT INTO `list` VALUES ('相思灯', 28, '林维', 92);
INSERT INTO `list` VALUES ('i don\'t wanna see u anymore 2019', 28, 'NINEONE #', 93);
INSERT INTO `list` VALUES ('天黑了(Cause夜、萤火虫和你)', 28, '夏婉安', 94);
INSERT INTO `list` VALUES ('鳌拜鳌拜鳌拜拜 (Original Mix)', 28, '南辞/唐总', 95);
INSERT INTO `list` VALUES ('来自天堂的魔鬼', 28, '杨又歌', 96);
INSERT INTO `list` VALUES ('不错过', 28, '夏婉安', 97);
INSERT INTO `list` VALUES ('悠殇叹', 28, '阿悠悠', 98);
INSERT INTO `list` VALUES ('醉仙美', 28, '徐聪', 99);
INSERT INTO `list` VALUES ('解忧', 29, '张靓颖· 《宸汐缘》电视剧女主情感主题曲', 3);
INSERT INTO `list` VALUES ('当你孤单你会想起谁', 29, '刘宪华 (Henry)· 《一条狗的使命2》电影中国区推广曲', 4);
INSERT INTO `list` VALUES ('无愧', 29, 'R1SE· 《上海堡垒》电影片尾主题曲', 5);
INSERT INTO `list` VALUES ('Another Day', 29, '먼데이 키즈 (Monday Kiz)/펀치 (PUNCH)· 《德鲁纳酒店》韩剧插曲', 6);
INSERT INTO `list` VALUES ('今夜我属于爱情', 29, '张学友/Beyoncé· 《狮子王》全球唯一国际版主题曲', 7);
INSERT INTO `list` VALUES ('今后我与自己流浪', 29, '张碧晨· 《哪吒之魔童降世》电影片尾曲', 8);
INSERT INTO `list` VALUES ('是缘', 29, '杨宗纬· 《宸汐缘》电视剧片头主题曲', 9);
INSERT INTO `list` VALUES ('鸟语林', 29, '双笙· 《宸汐缘》电视剧插曲', 11);
INSERT INTO `list` VALUES ('【魏无羡】曲尽陈情', 29, '肖战', 10);
INSERT INTO `list` VALUES ('相信你的人', 29, '陈奕迅· 《银河补习班》电影推广曲', 12);
INSERT INTO `list` VALUES ('耿', 29, '汪苏泷· 《最好的我们》电影毕业季主题曲', 13);
INSERT INTO `list` VALUES ('如果当时', 29, '胡夏· 《上海堡垒》电影推广曲', 14);
INSERT INTO `list` VALUES ('나의 어깨에 기대어요 (Lean on me)', 29, '10cm (십센치)· 《德鲁纳酒店》韩剧插曲', 15);
INSERT INTO `list` VALUES ('银河里最像的人', 29, '邓超· 《银河补习班》电影主题曲', 17);
INSERT INTO `list` VALUES ('清平乐', 29, '火箭少女101紫宁· 《长安十二时辰》电视剧主题推广曲', 16);
INSERT INTO `list` VALUES ('【蓝忘机】不忘', 29, '王一博', 19);
INSERT INTO `list` VALUES ('【主题曲】无羁(合唱版)', 29, '肖战/王一博', 18);
INSERT INTO `list` VALUES ('我只喜欢你', 29, '胡夏· 《我只喜欢你》影视剧主题曲', 20);
INSERT INTO `list` VALUES ('天空之外', 29, '弦子· 《陪你到世界之巅》电视剧片尾曲', 22);
INSERT INTO `list` VALUES ('哪吒', 29, 'GAI/大痒痒· 《哪吒之魔童降世》电影主题曲', 21);
INSERT INTO `list` VALUES ('【主题曲】无羁( 周笔畅 特别版 )', 29, '周笔畅', 23);
INSERT INTO `list` VALUES ('WOW', 29, 'MAMAMOO (마마무)· 《请输入搜索词:WWW》韩剧插曲', 25);
INSERT INTO `list` VALUES ('时光尽头', 29, '娜扎· 《归还世界给你》电视剧沈忆恩人物曲', 24);
INSERT INTO `list` VALUES ('Fall in Luv', 29, '刘宪华 (Henry)· 《新入史官具海玲》韩剧插曲', 26);
INSERT INTO `list` VALUES ('Can You Feel the Love Tonight', 29, 'Beyoncé/<NAME>/<NAME>/Seth Rogen· 《狮子王》电影插曲', 27);
INSERT INTO `list` VALUES ('课间进行曲', 29, '阿肆· 《少年派》电视剧插曲', 28);
INSERT INTO `list` VALUES ('路过人间', 29, '郁可唯· 《我们与恶的距离》电视剧插曲', 30);
INSERT INTO `list` VALUES ('云上的傻瓜', 29, '陆虎· 《宸汐缘》电视剧插曲', 29);
INSERT INTO `list` VALUES ('最燃的冒险', 29, '王一博· 《陪你到世界之巅》电视剧主题曲', 31);
INSERT INTO `list` VALUES ('谢谢你走在我前面', 29, '梁咏琪· 《小Q》电影主题曲', 32);
INSERT INTO `list` VALUES ('短歌行', 29, '萨顶顶· 《长安十二时辰》主题推广曲', 33);
INSERT INTO `list` VALUES ('长安诀', 29, '汪苏泷· 《长安十二时辰》电视剧主题推广曲', 35);
INSERT INTO `list` VALUES ('我比从前想你了', 29, '毕书尽· 《我们不能是朋友》电视剧片尾曲', 34);
INSERT INTO `list` VALUES ('【温宁】赤子', 29, '于斌', 36);
INSERT INTO `list` VALUES ('兄弟不怀疑', 29, '刘德华/古天乐· 《扫毒2》主题曲', 37);
INSERT INTO `list` VALUES ('打破沉默', 29, '杨紫/任贤齐/欧阳靖· 《沉默的证人》电影主题曲', 38);
INSERT INTO `list` VALUES ('都是夜归人', 29, '阿云嘎/郑云龙· 《深夜食堂》电影片尾曲', 39);
INSERT INTO `list` VALUES ('没资格难过', 29, '张信哲· 《跳舞吧!大象》电影片尾曲', 40);
INSERT INTO `list` VALUES ('未完成的瞬间', 29, '李宏毅· 《天雷一部之春花秋月》电视剧片尾曲', 41);
INSERT INTO `list` VALUES ('【插曲】意难平', 29, '银临', 42);
INSERT INTO `list` VALUES ('【温情】疏林如有诉', 29, '高秋梓', 43);
INSERT INTO `list` VALUES ('小至', 29, '郁可唯/李治廷· 《白发》电视剧主题曲', 44);
INSERT INTO `list` VALUES ('【主题曲】无羁(肖战 独唱版)', 29, '肖战', 45);
INSERT INTO `list` VALUES ('追寻年少的光', 29, '林宥嘉/郁可唯· 《流淌的美好时光》电视剧主题曲', 47);
INSERT INTO `list` VALUES ('【蓝曦臣】不由', 29, '刘海宽', 46);
INSERT INTO `list` VALUES ('心锁', 29, '金润吉· 《白发》电视剧插曲', 48);
INSERT INTO `list` VALUES ('若雪', 29, '李治廷· 《白发》电视剧片尾曲', 49);
INSERT INTO `list` VALUES ('小情书', 29, '范世錡· 《追球》电视剧齐景浩角色曲', 50);
INSERT INTO `list` VALUES ('Spirit (From Disney\'s \"The Lion King\")', 29, 'Beyoncé', 51);
INSERT INTO `list` VALUES ('恋爱脑少女', 29, '赵露思· 《天雷一部之春花秋月》电视剧片头曲', 52);
INSERT INTO `list` VALUES ('I Know You Know', 29, '李治廷· 《我的真朋友》电视剧主题曲', 53);
INSERT INTO `list` VALUES ('海の幽霊 (海之幽灵)', 29, '米津玄師 (よねづ けんし)· 《海兽之子》动画电影主题曲', 54);
INSERT INTO `list` VALUES ('Forward Motion (From The Original Motion Picture “Late Night”|Explicit)', 29, 'Daya', 56);
INSERT INTO `list` VALUES ('追光的你 (男生版)', 29, '范世錡/黄圣池/朱元冰/李汶翰/李希侃· 《追球》电视剧主题曲', 55);
INSERT INTO `list` VALUES ('一双翅膀', 29, '鞠婧祎· 《请赐我一双翅膀》电视剧片尾曲', 57);
INSERT INTO `list` VALUES ('秣马', 29, '阿云嘎· 《九州缥缈录》电视剧主题曲', 58);
INSERT INTO `list` VALUES ('R.1.S.E', 29, 'R1SE· 《黑衣人:全球追缉》电影中国区主题推广曲', 59);
INSERT INTO `list` VALUES ('失物招领', 29, '郭一凡· 《动物管理局》网络剧告白版插曲', 60);
INSERT INTO `list` VALUES ('忘忧', 29, '张雪迎· 《白发》电视剧片尾曲', 61);
INSERT INTO `list` VALUES ('Taste', 29, 'Sonny Rey· 《带着爸爸去留学》电视剧插曲', 63);
INSERT INTO `list` VALUES ('【主题曲】无羁(王一博 独唱版)', 29, '王一博', 64);
INSERT INTO `list` VALUES ('Can You Hear', 29, '谭嘉仪· 《白色强人》电视剧插曲', 62);
INSERT INTO `list` VALUES ('Circle of Life/Nants\' Ingonyama', 29, 'Lindiwe Mkhize/Lebo M.· 《狮子王》电影插曲', 65);
INSERT INTO `list` VALUES ('真夏の夜の匂いがする (仲夏夜的气息)', 29, 'あいみょん· 《天国餐馆》日剧主题曲', 66);
INSERT INTO `list` VALUES ('Never let you go', 29, '萨吉· 《我只喜欢你》电视剧片尾曲', 67);
INSERT INTO `list` VALUES ('你', 29, '印子月· 《暗恋·橘生淮南》网剧主题曲', 68);
INSERT INTO `list` VALUES ('最好的我们', 29, '陈飞宇· 《最好的我们》电影同名主题曲', 69);
INSERT INTO `list` VALUES ('逆风', 29, '毛不易· 《筑梦情缘》电视剧男主情感主题曲', 70);
INSERT INTO `list` VALUES ('黑马', 29, '于文文· 《我的真朋友》电视剧插曲', 71);
INSERT INTO `list` VALUES ('生如狂澜', 29, '侯明昊/成毅/张博宇· 《怒海潜沙&秦岭神树》电视剧片尾曲', 72);
INSERT INTO `list` VALUES ('我们很好', 29, '林俊杰· 《少年的你》电影主题曲', 73);
INSERT INTO `list` VALUES ('一首情歌的时间', 29, '印子月· 《致我们暖暖的小时光》网络剧插曲', 74);
INSERT INTO `list` VALUES ('清平乐', 29, '刘珂矣· 《长安十二时辰》电视剧主题推广曲特别版', 75);
INSERT INTO `list` VALUES ('Speechless (Full)', 29, 'Naomi Scott· 《阿拉丁》电影插曲', 76);
INSERT INTO `list` VALUES ('拙慕', 29, '周深· 《爵迹临界天下》网络剧插曲', 77);
INSERT INTO `list` VALUES ('无妨', 29, '孙楠· 《破冰行动》电视剧主题曲', 78);
INSERT INTO `list` VALUES ('彼时', 29, '张碧晨· 《我的真朋友》电视剧插曲', 79);
INSERT INTO `list` VALUES ('向前走', 29, '龙梅子· 电影《陌上有信》推广曲', 80);
INSERT INTO `list` VALUES ('如果', 29, '弦子· 《我心深触》电视剧主题曲', 81);
INSERT INTO `list` VALUES ('<NAME>', 29, '<NAME>/<NAME>/JD McCrary/<NAME>· 《狮子王》电影插曲', 83);
INSERT INTO `list` VALUES ('조금 더 외로워지겠지 (会更加孤独的)', 29, '김나영 (金娜英)· 《请输入搜索词:WWW》韩剧插曲', 84);
INSERT INTO `list` VALUES ('红尘微烫', 29, '陆翊· 《白发》电视剧插曲', 82);
INSERT INTO `list` VALUES ('藏不住的心跳', 29, '朱主爱· 《我只喜欢你》影视剧片头曲', 85);
INSERT INTO `list` VALUES ('无念', 29, '张靓颖· 《筑梦情缘》电视剧女主情感主题曲', 87);
INSERT INTO `list` VALUES ('最好的故事', 29, '毕书尽· 《我的真朋友》电视剧插曲', 86);
INSERT INTO `list` VALUES ('在你身边', 29, '胡莎莎· 《请赐我一双翅膀》电视剧插曲', 88);
INSERT INTO `list` VALUES ('昨日少年', 29, '摩登兄弟· 《企鹅公路》电影少年版中文主题曲', 89);
INSERT INTO `list` VALUES ('最相爱的朋友', 29, '马栗· 《我只喜欢你》影视剧插曲', 90);
INSERT INTO `list` VALUES ('青春大满贯', 29, '胡夏· 《奋斗吧,少年!》电视剧片尾曲', 92);
INSERT INTO `list` VALUES ('退让', 29, '曾昱嘉· 《我们不能是朋友》电视剧片头曲', 91);
INSERT INTO `list` VALUES ('まちがいさがし (寻找错误)', 29, '菅田将暉 (すだ まさき)· 《完美世界》日剧片尾曲', 94);
INSERT INTO `list` VALUES ('TV에서 보는 그대 모습은 (在电视里看到的你的样子)', 29, '이다희 (李多喜)· 《请输入搜索词:WWW》韩剧插曲', 93);
INSERT INTO `list` VALUES ('我要飞翔', 29, '炎亚纶· 《请赐我一双翅膀》电视剧片头曲', 95);
INSERT INTO `list` VALUES ('My girl', 29, '<NAME>· 《带着爸爸去留学》电视剧插曲', 96);
INSERT INTO `list` VALUES ('I Just Can\'t Wait to Be King', 29, '<NAME>/<NAME>/<NAME>· 《狮子王》电影插曲', 97);
INSERT INTO `list` VALUES ('归还世界给你', 29, '王铮亮· 《归还世界给你》电视剧片尾曲', 98);
INSERT INTO `list` VALUES ('The Lion Sleeps Tonight (Full Version)', 29, '<NAME>/<NAME>· 《狮子王》电影插曲', 99);
INSERT INTO `list` VALUES ('On Fire (Explicit)', 57, 'Yultron/박재범 (朴宰范)', 4);
INSERT INTO `list` VALUES ('Lost Soul', 57, '<NAME>', 6);
INSERT INTO `list` VALUES ('We Can Get High (RetroVision Remix)', 57, 'Galantis/Yellow Claw', 5);
INSERT INTO `list` VALUES ('Retrograde', 57, 'Hardwell', 7);
INSERT INTO `list` VALUES ('Take Me Back To London', 57, '<NAME>/Stormzy/Jaykae/Aitch', 3);
INSERT INTO `list` VALUES ('Kylie', 57, '<NAME>/Dastic', 8);
INSERT INTO `list` VALUES ('Let Us Love', 57, 'Topic/Vigiland/Christopher', 9);
INSERT INTO `list` VALUES ('Midnight Hour', 57, 'Skrillex/Boys Noize/Ty Dolla $ign', 10);
INSERT INTO `list` VALUES ('Never Be Alone (feat. Aloe Blacc)', 57, '<NAME>/Aloe Blacc', 11);
INSERT INTO `list` VALUES ('Apart', 57, 'Mako', 12);
INSERT INTO `list` VALUES ('Pica (Cat Dealers Remix)', 57, 'Deorro/<NAME>/<NAME>', 13);
INSERT INTO `list` VALUES ('<NAME>', 57, 'Yellow Claw/Saweetie/INNA/<NAME>', 14);
INSERT INTO `list` VALUES ('Say Goodbye', 57, 'Yultron/Sik-K/식케이 (Sik-K)/pH-1', 15);
INSERT INTO `list` VALUES ('On My Way (Da Tweekaz Remix)', 57, '<NAME>/Sabrina Carpenter/Farruko', 16);
INSERT INTO `list` VALUES ('Monster (<NAME> Remix)', 57, 'LUM!X/Gabry Ponte', 17);
INSERT INTO `list` VALUES ('Drowning (feat. Sorana)', 57, 'Franklin/Sorana/Digital Farm Animals', 18);
INSERT INTO `list` VALUES ('Body First (董子龙&齐奕同 remix)', 57, '张靓颖', 19);
INSERT INTO `list` VALUES ('Day Or Night', 57, '<NAME>', 20);
INSERT INTO `list` VALUES ('Summer Lover feat. Devin & <NAME> (CID Remix)', 57, '<NAME>/Devin/<NAME>', 21);
INSERT INTO `list` VALUES ('Heaven (David Guetta & MORTEN Remix|Extended Version)', 57, 'Avicii', 25);
INSERT INTO `list` VALUES ('More Of Your Love', 57, '<NAME>/Reggio', 22);
INSERT INTO `list` VALUES ('Come Back Down (Original Mix)', 57, 'Mediks', 23);
INSERT INTO `list` VALUES ('Thing For You (David Guetta Remix|Explicit)', 57, '<NAME>/<NAME>', 24);
INSERT INTO `list` VALUES ('Illusion (feat. KARRA)', 57, 'NERVO/Firebeatz/Karra', 26);
INSERT INTO `list` VALUES ('Cool', 57, 'Viva La Panda/Ess Bogale', 27);
INSERT INTO `list` VALUES ('One Thing Right (feat. Kane Brown)', 57, 'Marshmello/Kane Brown', 28);
INSERT INTO `list` VALUES ('Papillon-Postlude of The Rookies 巴比龙 (BOYTOY remix)', 57, '王嘉尔· 《素人特工》电影片尾曲', 29);
INSERT INTO `list` VALUES ('Tell Me Why', 57, 'Alok/Harrison', 30);
INSERT INTO `list` VALUES ('Acordeão', 57, 'Tiësto/Moska', 31);
INSERT INTO `list` VALUES ('Post Malone (feat. RANI) (GATTÜSO Remix)', 57, '<NAME>/Rani', 32);
INSERT INTO `list` VALUES ('Rave (Explicit)', 57, '<NAME>/Showtek/MAKJ/<NAME>', 33);
INSERT INTO `list` VALUES ('OMG (MOTi Remix)', 57, 'Gryffin/<NAME>', 34);
INSERT INTO `list` VALUES ('Untamable', 57, 'Wildstylez/Sound Rush/Ruby Prophet', 35);
INSERT INTO `list` VALUES ('I Care (Intro)', 57, 'ILLENIUM', 36);
INSERT INTO `list` VALUES ('Sorry', 57, 'Blaze U', 37);
INSERT INTO `list` VALUES ('Punching in the Dark', 57, 'Hellberg/<NAME>', 38);
INSERT INTO `list` VALUES ('On One (Explicit)', 57, 'Hasho', 39);
INSERT INTO `list` VALUES ('808', 57, '张靓颖· 心电感应808 英文版', 40);
INSERT INTO `list` VALUES ('Need You', 57, 'Faustix', 41);
INSERT INTO `list` VALUES ('방콕 (Bangkok) (Prod. By Francis)', 57, '소유 (昭宥)/Francis (프란시스)', 42);
INSERT INTO `list` VALUES ('Movin\' Too Fast', 57, '<NAME>', 43);
INSERT INTO `list` VALUES ('LONELY NIGHTS (Jo<NAME> Remix)', 57, '<NAME>/Lil Yachty', 44);
INSERT INTO `list` VALUES ('Long Time', 57, 'Radiology/AXYS/Revealed Recordings', 45);
INSERT INTO `list` VALUES ('All For You', 57, 'RYNX/Kiesza', 46);
INSERT INTO `list` VALUES ('Other Side (feat. <NAME>)', 57, 'BlasterJaxx/<NAME>', 47);
INSERT INTO `list` VALUES ('This Is The End', 57, 'Gammer/<NAME>', 48);
INSERT INTO `list` VALUES ('GO OFF(Nuthin\' 2 It) (Explicit)', 57, '<NAME>', 49);
INSERT INTO `list` VALUES ('野狼disco', 5, '宝石Gem', 4);
INSERT INTO `list` VALUES ('病态', 5, '薛之谦', 5);
INSERT INTO `list` VALUES ('笑场', 5, '薛之谦', 6);
INSERT INTO `list` VALUES ('你和我都没有错', 5, '都智文', 7);
INSERT INTO `list` VALUES ('胡同少年志', 5, '周深/国道· EDIQ国风音乐连载专辑《国道》', 8);
INSERT INTO `list` VALUES ('一生有你', 5, 'ONER· 《一生有你》电影同名推广曲', 9);
INSERT INTO `list` VALUES ('Promise To You', 5, '汪苏泷· 《我不能恋爱的女朋友》电视剧插曲', 10);
INSERT INTO `list` VALUES ('我和我的祖国', 5, '华语群星· 《我和我的祖国》电影全民版片尾曲', 11);
INSERT INTO `list` VALUES ('野望', 5, '李宇春/Click#15· 《双子杀手》电影主题曲', 12);
INSERT INTO `list` VALUES ('这么久没见', 5, '薛之谦', 13);
INSERT INTO `list` VALUES ('你应该很快乐', 5, '虎二', 15);
INSERT INTO `list` VALUES ('风华', 5, '简弘亦· 《明月照我心》网络剧片头曲', 14);
INSERT INTO `list` VALUES ('还好我们再遇见', 5, '苏诗丁· 《十年三月三十日》电视剧插曲', 16);
INSERT INTO `list` VALUES ('我和我的祖国(青春唱响曲)', 5, '欧豪/周冬雨/朱一龙/刘昊然/陈飞宇', 18);
INSERT INTO `list` VALUES ('不成诗', 5, '双笙', 17);
INSERT INTO `list` VALUES ('Ain\'t Got No Love', 5, '王俊凯', 19);
INSERT INTO `list` VALUES ('何妨年少', 5, '郑云龙· 《厨神小当家》动画片主题曲', 20);
INSERT INTO `list` VALUES ('Banjitino', 5, '卡姆/陆政廷Lil Jet', 21);
INSERT INTO `list` VALUES ('彩虹弧线', 5, '许魏洲', 22);
INSERT INTO `list` VALUES ('我的中国心', 5, '肖战', 23);
INSERT INTO `list` VALUES ('海', 5, '王子异', 24);
INSERT INTO `list` VALUES ('暑假', 5, '好妹妹', 25);
INSERT INTO `list` VALUES ('远在咫尺的爱', 5, '房东的猫· 《彩虹的重力》电视剧主题曲', 26);
INSERT INTO `list` VALUES ('幸福第一站', 5, '庄心妍', 27);
INSERT INTO `list` VALUES ('西子吟', 5, '胡66', 28);
INSERT INTO `list` VALUES ('失态 (Misbehave)', 5, '余佳运', 29);
INSERT INTO `list` VALUES ('碰碰', 5, '周奇', 30);
INSERT INTO `list` VALUES ('如斟', 5, 'Mukyo木西', 31);
INSERT INTO `list` VALUES ('星途', 5, '张靓颖· EXEED星途LX专属主题曲', 32);
INSERT INTO `list` VALUES ('Do You Want More', 5, '黄旭', 33);
INSERT INTO `list` VALUES ('原来我', 5, '刘惜君· 《十年三月三十日》电视剧片尾曲', 34);
INSERT INTO `list` VALUES ('没有说完的故事', 5, '周深· 《美食大冒险之英雄烩》动画电影片尾曲', 35);
INSERT INTO `list` VALUES ('我和我的祖国 (全民合唱版)', 5, '廖昌永/张艺兴/火箭少女101段奥娟/张远/连淮伟/焦迈奇/全民K歌用户', 36);
INSERT INTO `list` VALUES ('我不好', 5, '张艺兴', 37);
INSERT INTO `list` VALUES ('常客', 5, '秦昊· 《常客》秦昊摄影集主题曲', 38);
INSERT INTO `list` VALUES ('相遇的可能', 5, '马伊琍· 《在远方》电视剧插曲', 39);
INSERT INTO `list` VALUES ('\"她\"', 5, '杨和苏KeyNG', 42);
INSERT INTO `list` VALUES ('亲爱的你 去了何方', 5, '陈硕子', 40);
INSERT INTO `list` VALUES ('卸任', 5, '谢宇伦', 41);
INSERT INTO `list` VALUES ('念殊途', 5, '河图/阿杰729· 伶伦人物曲', 43);
INSERT INTO `list` VALUES ('南方北方', 5, '康树龙', 44);
INSERT INTO `list` VALUES ('时间的脉络', 5, '王铮亮· 《十年三月三十日》电视剧主题曲', 45);
INSERT INTO `list` VALUES ('红色高跟鞋', 5, '隔壁老樊', 46);
INSERT INTO `list` VALUES ('自省', 5, '何玄· 《十年三月三十日》电视剧插曲', 47);
INSERT INTO `list` VALUES ('初见雪', 5, '方逸伦/凌美仕· 《明月照我心》网络剧片尾曲', 48);
INSERT INTO `list` VALUES ('复乐园', 5, '二珂', 49);
INSERT INTO `list` VALUES ('徐竹隐', 5, '贰婶/歪歪· 八音掌竹-严辞人物曲', 50);
INSERT INTO `list` VALUES ('循', 5, '双笙', 51);
INSERT INTO `list` VALUES ('就当从没遇见你', 5, '小沈阳', 52);
INSERT INTO `list` VALUES ('祖国', 5, '南征北战NZBZ· 共青团中央宣传部联合出品', 53);
INSERT INTO `list` VALUES ('太多', 5, '简弘亦', 55);
INSERT INTO `list` VALUES ('木梓姑娘', 5, '虎二', 54);
INSERT INTO `list` VALUES ('玉剑掀澜', 5, '银临/云の泣/清弄· 英雄联盟2019玉剑传说系列皮肤同人主题曲', 56);
INSERT INTO `list` VALUES ('我爱祖国的蓝天', 5, '毛阿敏· 《中国机长》电影主题曲', 57);
INSERT INTO `list` VALUES ('远方', 5, '金志文· 《在远方》电视剧主题曲', 58);
INSERT INTO `list` VALUES ('青春狂想曲', 5, '陈学冬', 59);
INSERT INTO `list` VALUES ('问少年', 5, '肖战· 《诛仙I》电影放肆版主题曲', 60);
INSERT INTO `list` VALUES ('净土谣', 5, '小魂/谷江山· 八音掌土-苏与白人物曲', 61);
INSERT INTO `list` VALUES ('今后我与自己流浪', 5, '张碧晨· 《哪吒之魔童降世》电影片尾曲', 62);
INSERT INTO `list` VALUES ('王昭君', 5, '陈雪凝· 《王者荣耀》英雄主打歌', 63);
INSERT INTO `list` VALUES ('进退无路', 5, '南征北战NZBZ', 64);
INSERT INTO `list` VALUES ('Ethereal', 5, '痛仰乐队', 65);
INSERT INTO `list` VALUES ('噩梦', 5, 'Tizzy T', 66);
INSERT INTO `list` VALUES ('Fall', 5, '易烊千玺', 67);
INSERT INTO `list` VALUES ('少年', 5, '郑棋元· 《光荣时代》电视剧插曲', 68);
INSERT INTO `list` VALUES ('Shyuwa shyuwa', 5, '洛天依', 69);
INSERT INTO `list` VALUES ('彩虹冰淇淋', 5, '周艺轩· 《我不能恋爱的女朋友》恋爱暖身曲', 70);
INSERT INTO `list` VALUES ('小欢喜', 5, '刘瑞琦· 《小欢喜》电视剧同名主题曲', 71);
INSERT INTO `list` VALUES ('梦', 5, '蔡徐坤', 72);
INSERT INTO `list` VALUES ('与未来对话', 5, '范丞丞', 73);
INSERT INTO `list` VALUES ('第一次告白', 5, 'TFBOYS', 74);
INSERT INTO `list` VALUES ('大力水手', 5, '黄旭', 75);
INSERT INTO `list` VALUES ('流光卷', 5, '河图/汐音社', 76);
INSERT INTO `list` VALUES ('寻光', 5, '戴景耀· 《呼吸》电影中文推广曲', 78);
INSERT INTO `list` VALUES ('孤岛', 5, '胡夏· 《空降利刃》电视剧插曲', 77);
INSERT INTO `list` VALUES ('容身之所', 5, '双笙· 《罗小黑战记》电影印象曲', 79);
INSERT INTO `list` VALUES ('情意结', 5, '周深· 《诛仙I》电影片尾曲', 80);
INSERT INTO `list` VALUES ('翱翔天地', 5, '胡夏· 《中国机长》电影插曲', 81);
INSERT INTO `list` VALUES ('听我说说', 5, '赵天宇· 《我的莫格利男孩》电视剧插曲', 83);
INSERT INTO `list` VALUES ('碌碌无为', 5, '刘彬濠', 84);
INSERT INTO `list` VALUES ('避难所/Sanctuary', 5, '周深· 《我在未来等你》电视剧暗恋主题曲', 82);
INSERT INTO `list` VALUES ('爱我行不行', 5, '徐良/二珂· 《我不能恋爱的女朋友》插曲', 85);
INSERT INTO `list` VALUES ('陷落美好', 5, '易烊千玺', 86);
INSERT INTO `list` VALUES ('各自安好', 5, '高嘉朗', 87);
INSERT INTO `list` VALUES ('来日没有那么长', 5, '虎二', 89);
INSERT INTO `list` VALUES ('良人遮', 5, '刘珂矣', 88);
INSERT INTO `list` VALUES ('栽种梦想', 5, 'ONER', 90);
INSERT INTO `list` VALUES ('如果当时', 5, '胡夏· 《上海堡垒》电影推广曲', 91);
INSERT INTO `list` VALUES ('巅峰之上', 5, '毛不易· 《全职高手》电视剧主题曲', 92);
INSERT INTO `list` VALUES ('我和我的祖国 (童声版)', 5, '邓文怡/邓力玮', 93);
INSERT INTO `list` VALUES ('蒙着眼', 5, '蔡徐坤', 94);
INSERT INTO `list` VALUES ('阴天', 5, '痛仰乐队', 95);
INSERT INTO `list` VALUES ('好吗, 好啦, 好吧', 5, '刘柏辛Lexie', 96);
INSERT INTO `list` VALUES ('讲真的', 5, '摩登兄弟', 97);
INSERT INTO `list` VALUES ('一个人旅行', 5, '李凡一', 98);
INSERT INTO `list` VALUES ('告白前一秒', 5, '永彬Ryan.B', 99);
INSERT INTO `list` VALUES ('Drown', 3, '<NAME>/<NAME>', 3);
INSERT INTO `list` VALUES ('Stupid Love', 3, '<NAME>', 4);
INSERT INTO `list` VALUES ('I Found You', 3, 'Cash Cash/Andy Grammer', 6);
INSERT INTO `list` VALUES ('Loyal Brave True (From \"Mulan\")', 3, '<NAME>', 5);
INSERT INTO `list` VALUES ('Roar', 3, '<NAME>', 7);
INSERT INTO `list` VALUES ('Only The Young (Featured in Miss Americana)', 3, '<NAME>', 8);
INSERT INTO `list` VALUES ('I Love Me (Explicit)', 3, '<NAME>', 9);
INSERT INTO `list` VALUES ('Drugs & The Internet (Explicit)', 3, 'Lauv', 10);
INSERT INTO `list` VALUES ('Oh My God', 3, '<NAME>', 11);
INSERT INTO `list` VALUES ('The Book of You & I', 3, '<NAME>', 12);
INSERT INTO `list` VALUES ('What Goes Up', 3, 'Lenka', 13);
INSERT INTO `list` VALUES ('The Other Side', 3, 'SZA/<NAME>', 14);
INSERT INTO `list` VALUES ('Bammer (Explicit)', 3, '<NAME>/Mustard', 15);
INSERT INTO `list` VALUES ('Feel Me', 3, '<NAME>', 16);
INSERT INTO `list` VALUES ('Yummy (Country Remix)', 3, '<NAME>/Florida Georgia Line', 17);
INSERT INTO `list` VALUES ('The Man (Live From Paris)', 3, '<NAME>', 18);
INSERT INTO `list` VALUES ('AAA', 3, 'NYK/Shelhiel', 19);
INSERT INTO `list` VALUES ('No Time To Die', 3, '<NAME>', 20);
INSERT INTO `list` VALUES ('Mistakes (Explicit)', 3, '<NAME>/<NAME>', 21);
INSERT INTO `list` VALUES ('Shake It Off', 3, '<NAME>', 22);
INSERT INTO `list` VALUES ('Let\'s Go', 3, 'Tobu', 23);
INSERT INTO `list` VALUES ('This is Us', 3, '<NAME>/<NAME>', 24);
INSERT INTO `list` VALUES ('i\'m so tired...', 3, 'Lauv/<NAME>', 25);
INSERT INTO `list` VALUES ('I Don’t Wanna Live Forever (Fifty Shades Darker) (From \"Fifty Shades Darker (Original Motion Picture Soundtrack)\")', 3, 'ZAYN/Taylor Swift', 26);
INSERT INTO `list` VALUES ('To Die For', 3, '<NAME>', 27);
INSERT INTO `list` VALUES ('Sorry', 3, '<NAME>', 28);
INSERT INTO `list` VALUES ('fuck, i\'m lonely (Explicit)', 3, 'Lauv/Anne-Marie', 29);
INSERT INTO `list` VALUES ('Poker Face', 3, '<NAME>', 30);
INSERT INTO `list` VALUES ('Alone, Pt. II', 3, 'Alan Walker/Ava Max', 31);
INSERT INTO `list` VALUES ('Lonely Eyes', 3, 'Lauv', 32);
INSERT INTO `list` VALUES ('Alone, Pt. II (Live at Château de Fontainebleau)', 3, 'Alan Walker/Ava Max', 33);
INSERT INTO `list` VALUES ('Modern Loneliness (Explicit)', 3, 'Lauv', 34);
INSERT INTO `list` VALUES ('Young & Alive', 3, 'Bazzi', 35);
INSERT INTO `list` VALUES ('As Long As You Love Me (Acoustic Version)', 3, '<NAME>', 36);
INSERT INTO `list` VALUES ('Into the Unknown', 3, 'AURORA', 37);
INSERT INTO `list` VALUES ('Dancing Next To Me', 3, 'Greyson Chance', 38);
INSERT INTO `list` VALUES ('CHIME OF THE DAWN BELLS(黎明的编钟声)', 3, '<NAME>/<NAME>', 39);
INSERT INTO `list` VALUES ('Baby Pluto (Explicit)', 3, 'Lil Uzi Vert', 40);
INSERT INTO `list` VALUES ('Feelings', 3, 'Lauv', 41);
INSERT INTO `list` VALUES ('Priceless', 3, 'Beatrich', 42);
INSERT INTO `list` VALUES ('Not Alone', 3, 'Skytech/TWISTERZ', 43);
INSERT INTO `list` VALUES ('Canada', 3, 'Lauv/<NAME>a', 45);
INSERT INTO `list` VALUES ('Honest', 3, '<NAME>', 44);
INSERT INTO `list` VALUES ('Any Song(Tik Tok Dance Challenge Version)[Originally Performed by ZICO]', 3, '<NAME>', 46);
INSERT INTO `list` VALUES ('Intentions', 3, '<NAME>/Quavo', 47);
INSERT INTO `list` VALUES ('Despacito', 3, '<NAME>/<NAME>', 48);
INSERT INTO `list` VALUES ('Physical', 3, '<NAME>', 49);
INSERT INTO `list` VALUES ('After Hours', 3, 'The Weeknd', 50);
INSERT INTO `list` VALUES ('Always (Alan Walker Remix)', 3, '<NAME>/<NAME>', 51);
INSERT INTO `list` VALUES ('Girls Like You', 3, 'Boyce Avenue', 52);
INSERT INTO `list` VALUES ('Sims (Explicit)', 3, 'Lauv', 53);
INSERT INTO `list` VALUES ('I Luv U (R3HAB VIP Remix)', 3, 'Sofia Carson/R3HAB', 54);
INSERT INTO `list` VALUES ('In the End', 3, 'Linkin Park', 55);
INSERT INTO `list` VALUES ('My Sunset (Original Mix)', 3, 'Feint', 56);
INSERT INTO `list` VALUES ('Billy', 3, 'Lauv', 57);
INSERT INTO `list` VALUES ('fear', 3, 'gnash', 58);
INSERT INTO `list` VALUES ('SUGAR (feat. Dua Lipa) (Remix)', 3, 'Brockhampton/<NAME>', 59);
INSERT INTO `list` VALUES ('Believed', 3, 'Lauv', 60);
INSERT INTO `list` VALUES ('Mean', 3, '<NAME>', 61);
INSERT INTO `list` VALUES ('Love Yourself', 3, '<NAME>', 63);
INSERT INTO `list` VALUES ('On My Side', 3, 'Lenka', 62);
INSERT INTO `list` VALUES ('El Mejor Guerrero (De \"Mulán\")', 3, '<NAME>', 64);
INSERT INTO `list` VALUES ('To Die For (Ólafur Arnalds Remix)', 3, '<NAME>', 65);
INSERT INTO `list` VALUES ('Mean It', 3, 'Lauv/LANY', 66);
INSERT INTO `list` VALUES ('For Now', 3, 'Lauv', 67);
INSERT INTO `list` VALUES ('Gaslighter', 3, '<NAME>', 68);
INSERT INTO `list` VALUES ('Flashback', 3, 'Beatrich', 69);
INSERT INTO `list` VALUES ('Tell My Mama', 3, 'Lauv', 70);
INSERT INTO `list` VALUES ('River', 3, 'Bishop Briggs', 71);
INSERT INTO `list` VALUES ('We Will Rock You', 3, 'Nickelback', 72);
INSERT INTO `list` VALUES ('Dance Monkey (Original remix)', 3, 'Tones and I/Dj Afonso De Vic', 73);
INSERT INTO `list` VALUES ('All Around Me', 3, '<NAME>', 74);
INSERT INTO `list` VALUES ('Rare (Alexander 23 Edit)', 3, '<NAME>/Alexander 23', 75);
INSERT INTO `list` VALUES ('Señorita', 3, 'Boyce Avenue', 78);
INSERT INTO `list` VALUES ('Yummy', 3, '<NAME>', 76);
INSERT INTO `list` VALUES ('Please Don\'t Go', 3, 'BEAUZ/BSY/JSY/CAPPA', 77);
INSERT INTO `list` VALUES ('Right Here Waiting', 3, '<NAME>', 79);
INSERT INTO `list` VALUES ('Call Me Maybe', 3, '<NAME>', 80);
INSERT INTO `list` VALUES ('Changes', 3, 'Lauv', 81);
INSERT INTO `list` VALUES ('The Storm', 3, 'TheFatRat/Maisy Kay', 82);
INSERT INTO `list` VALUES ('Numb', 3, 'Linkin Park', 83);
INSERT INTO `list` VALUES ('Counting Stars', 3, 'OneRepublic', 84);
INSERT INTO `list` VALUES ('7 rings', 3, '<NAME>', 85);
INSERT INTO `list` VALUES ('Life Is Good (Explicit)', 3, 'Future/Drake', 86);
INSERT INTO `list` VALUES ('Rare (Live From The Village Studio)', 3, '<NAME>', 87);
INSERT INTO `list` VALUES ('Forever Yours (Avicii Tribute)', 3, 'Kygo/Avicii/<NAME>', 89);
INSERT INTO `list` VALUES ('Stay With You', 3, 'Gavrio/<NAME> Jr.', 88);
INSERT INTO `list` VALUES ('El Tejano (Explicit)', 3, 'Lauv/Sofia Reyes', 91);
INSERT INTO `list` VALUES ('Come Around Me', 3, '<NAME>', 90);
INSERT INTO `list` VALUES ('Julia', 3, 'Lauv', 92);
INSERT INTO `list` VALUES ('Stand By Me', 3, '<NAME>', 93);
INSERT INTO `list` VALUES ('Old Me (Explicit)', 3, '5 Seconds Of Summer', 95);
INSERT INTO `list` VALUES ('How To Love(feat. GRAY)', 3, 'ALLY/GRAY (그레이)', 94);
INSERT INTO `list` VALUES ('Apologize (Album Version)', 3, 'OneRepublic', 96);
INSERT INTO `list` VALUES ('Rojo', 3, '<NAME>', 97);
INSERT INTO `list` VALUES ('Friendships (2020 Dance Remix)', 3, '<NAME>', 98);
INSERT INTO `list` VALUES ('Birthday', 3, 'Anne-Marie', 99);
INSERT INTO `list` VALUES ('你要相信这不是最后一天', 27, '华晨宇', 4);
INSERT INTO `list` VALUES ('End of Time', 27, 'K-391/Alan Walker/Ahrix', 5);
INSERT INTO `list` VALUES ('冬日', 27, '鞠婧祎', 6);
INSERT INTO `list` VALUES ('Will You Marry Me', 27, '一口甜', 7);
INSERT INTO `list` VALUES ('给女孩(单曲)', 27, '李宇春', 8);
INSERT INTO `list` VALUES ('终于', 27, '双笙· 《两世欢》电视剧片头主题曲', 9);
INSERT INTO `list` VALUES ('朋友请听好', 27, '何炅/谢娜/易烊千玺· 《朋友请听好》芒果TV自制综艺同名主题曲', 10);
INSERT INTO `list` VALUES ('眠冬', 27, '满舒克/黄明昊', 11);
INSERT INTO `list` VALUES ('时光与你都很甜', 27, '吕小雨/孙泽源· 《时光与你都很甜》网剧同名主题曲', 12);
INSERT INTO `list` VALUES ('知晚', 27, '叶炫清· 《两世欢》电视剧插曲', 15);
INSERT INTO `list` VALUES ('海月之端', 27, '双笙', 13);
INSERT INTO `list` VALUES ('每个人都是孤独的', 27, '苏晗', 14);
INSERT INTO `list` VALUES ('身边', 27, '孙泽源· 《时光与你都很甜》网剧片尾曲', 16);
INSERT INTO `list` VALUES ('因为我们在一起', 27, '王一博', 17);
INSERT INTO `list` VALUES ('FIESTA', 27, 'IZ*ONE (아이즈원)', 18);
INSERT INTO `list` VALUES ('想你', 27, '艾辰', 19);
INSERT INTO `list` VALUES ('王源:快跟着我进入文物的时空漫游吧!', 27, '王源', 20);
INSERT INTO `list` VALUES ('孤单的人', 27, '海来阿木', 22);
INSERT INTO `list` VALUES ('青春不打烊', 27, '郭静· 《时光与你都很甜》网剧片头曲', 21);
INSERT INTO `list` VALUES ('영웅 (英雄; Kick It)', 27, 'NCT 127 (엔씨티 127)', 23);
INSERT INTO `list` VALUES ('不完美的完美', 27, '金玟岐· 《完美关系》电视剧宣传主题曲', 24);
INSERT INTO `list` VALUES ('Drown', 27, '<NAME>/<NAME>', 25);
INSERT INTO `list` VALUES ('自己', 27, '刘亦菲· 电影《花木兰》中文主题曲', 26);
INSERT INTO `list` VALUES ('Stupid Love', 27, '<NAME>', 27);
INSERT INTO `list` VALUES ('也许', 27, '于文文· 《谁都渴望遇见你》网台剧片尾曲', 28);
INSERT INTO `list` VALUES ('Never Worn White', 27, '<NAME>', 29);
INSERT INTO `list` VALUES ('平安回来', 27, '景甜/谭松韵/白宇', 30);
INSERT INTO `list` VALUES ('下凡', 27, '祝眠', 31);
INSERT INTO `list` VALUES ('渴望遇见', 27, '周深· 《谁都渴望遇见你》网台剧主题曲', 32);
INSERT INTO `list` VALUES ('Loyal Brave True (From \"Mulan\")', 27, '<NAME>', 33);
INSERT INTO `list` VALUES ('No Time To Die', 27, '<NAME>', 34);
INSERT INTO `list` VALUES ('橱窗', 27, '冯希瑶· 《安家》电视剧片尾曲', 35);
INSERT INTO `list` VALUES ('Who (feat. BTS)', 27, 'Lauv/BTS (防弹少年团)', 36);
INSERT INTO `list` VALUES ('逃离', 27, '王金金· 《谁都渴望遇见你》网台剧插曲', 37);
INSERT INTO `list` VALUES ('Yummy (Country Remix)', 27, '<NAME>/Florida Georgia Line', 38);
INSERT INTO `list` VALUES ('二十岁的遗言', 27, '陈思键', 39);
INSERT INTO `list` VALUES ('Oh My God', 27, '<NAME>', 40);
INSERT INTO `list` VALUES ('有你在身边', 27, '韩庚/杨颖/王一博/郑爽', 41);
INSERT INTO `list` VALUES ('走散', 27, '都智文· 《少主且慢行》电视剧插曲', 42);
INSERT INTO `list` VALUES ('꿈 (Boom) (梦)', 27, 'NCT 127 (엔씨티 127)', 43);
INSERT INTO `list` VALUES ('Feel Me', 27, '<NAME>', 44);
INSERT INTO `list` VALUES ('不如先庆祝能在一起', 27, '萧亚轩', 45);
INSERT INTO `list` VALUES ('어떤 말도 (No Words)', 27, 'Crush (크러쉬)· 《梨泰院Class》韩剧插曲', 46);
INSERT INTO `list` VALUES ('I Found You', 27, 'Cash Cash/Andy Grammer', 47);
INSERT INTO `list` VALUES ('The Man (Live From Paris)', 27, '<NAME>', 48);
INSERT INTO `list` VALUES ('Elevator (127F)', 27, 'NCT 127 (엔씨티 127)', 49);
INSERT INTO `list` VALUES ('雨水', 27, '音阙诗听/李佳思', 50);
INSERT INTO `list` VALUES ('保重', 27, '王俊凯/谢霆锋/萧敬腾', 51);
INSERT INTO `list` VALUES ('Sit Down!', 27, 'NCT 127 (엔씨티 127)', 52);
INSERT INTO `list` VALUES ('TING TING TING with Oliver Heldens', 27, 'ITZY (있지)/Oliver Heldens', 53);
INSERT INTO `list` VALUES ('NOBODY LIKE YOU', 27, 'ITZY (있지)', 54);
INSERT INTO `list` VALUES ('晚吟', 27, '李俊毅· 《两世欢》电视剧插曲', 55);
INSERT INTO `list` VALUES ('그때 그 아인 (Someday, The Boy)', 27, '金弼 (김필)· 《梨泰院Class》韩剧插曲', 56);
INSERT INTO `list` VALUES ('自从遇见你', 27, '虞书欣· 《少主且慢行》电视剧插曲', 57);
INSERT INTO `list` VALUES ('메아리 (Love Me Now) (回响)', 27, 'NCT 127 (엔씨티 127)', 58);
INSERT INTO `list` VALUES ('백야 (White Night) (白夜)', 27, 'NCT 127 (엔씨티 127)', 62);
INSERT INTO `list` VALUES ('时光成语花落地', 27, '宁桓宇· 《完美关系》电视剧片尾曲', 59);
INSERT INTO `list` VALUES ('THAT’S A NO NO', 27, 'ITZY (있지)', 60);
INSERT INTO `list` VALUES ('우산 (Love Song) (雨伞)', 27, 'NCT 127 (엔씨티 127)', 61);
INSERT INTO `list` VALUES ('낮잠 (Pandora\'s Box) (午睡)', 27, 'NCT 127 (엔씨티 127)', 63);
INSERT INTO `list` VALUES ('YOU MAKE ME', 27, 'ITZY (있지)', 64);
INSERT INTO `list` VALUES ('Not Alone', 27, 'NCT 127 (엔씨티 127)', 65);
INSERT INTO `list` VALUES ('To Die For', 27, '<NAME>', 66);
INSERT INTO `list` VALUES ('Day Dream (白日夢)', 27, 'NCT 127 (엔씨티 127)', 67);
INSERT INTO `list` VALUES ('我的回答', 27, '王啸坤· 《谁都渴望遇见你》网台剧人物主题曲', 68);
INSERT INTO `list` VALUES ('我不是她', 27, 'HANA菊梓乔· 《法证先锋IV》电视剧片尾曲', 69);
INSERT INTO `list` VALUES ('뿔 (MAD DOG) (角)', 27, 'NCT 127 (엔씨티 127)', 70);
INSERT INTO `list` VALUES ('一心一念', 27, '欧阳娜娜· 《北灵少年志之大主宰》电视剧片尾曲', 71);
INSERT INTO `list` VALUES ('一世倾心', 27, '双笙· 《热血同行》电视剧插曲', 72);
INSERT INTO `list` VALUES ('微光/Gleam', 27, '郑云龙/蔡程昱', 73);
INSERT INTO `list` VALUES ('不爱而别', 27, '火箭少女101紫宁· 《少主且慢行》电视剧插曲', 74);
INSERT INTO `list` VALUES ('Tell me', 27, 'milet (ミレイ)· 《Fate/Grand Order -绝对魔兽战线巴比伦尼亚-》TV动画片尾曲', 75);
INSERT INTO `list` VALUES ('The Other Side', 27, 'SZA/<NAME>', 76);
INSERT INTO `list` VALUES ('Say', 27, '尹美莱 (윤미래)· 《梨泰院Class》韩剧插曲', 77);
INSERT INTO `list` VALUES ('少年战', 27, '汪苏泷· 《热血同行》电视剧片尾曲、主题曲', 78);
INSERT INTO `list` VALUES ('AYAYAYA', 27, 'IZ*ONE (아이즈원)', 79);
INSERT INTO `list` VALUES ('RED MOON', 27, 'KARD (카드)', 80);
INSERT INTO `list` VALUES ('爱的桥梁 (粤语版)〝我知道〞', 27, '刘德华', 81);
INSERT INTO `list` VALUES ('我不是病毒', 27, '音阙诗听/昆玉', 82);
INSERT INTO `list` VALUES ('24HRS', 27, 'ITZY (있지)', 83);
INSERT INTO `list` VALUES ('AAA', 27, 'NYK/Shelhiel', 84);
INSERT INTO `list` VALUES ('Dreams Come True', 27, 'NCT 127 (엔씨티 127)', 85);
INSERT INTO `list` VALUES ('This is Us', 27, '<NAME>/<NAME>', 86);
INSERT INTO `list` VALUES ('달이 태양을 가릴 때 (Eclipse)', 27, '玟星 (문별)', 87);
INSERT INTO `list` VALUES ('Always (Alan Walker Remix)', 27, '<NAME>/<NAME>', 90);
INSERT INTO `list` VALUES ('Alone, Pt. II (Live at Château de Fontainebleau)', 27, 'Alan Walker/Ava Max', 91);
INSERT INTO `list` VALUES ('I’m Falling in Love', 27, '郭静/宁桓宇· 《少主且慢行》电视剧插曲', 88);
INSERT INTO `list` VALUES ('时间里的小偷', 27, '庄心妍', 89);
INSERT INTO `list` VALUES ('天下局', 27, '高天鹤', 92);
INSERT INTO `list` VALUES ('Interlude: Neo Zone', 27, 'NCT 127 (엔씨티 127)', 93);
INSERT INTO `list` VALUES ('I DON’T WANNA DANCE', 27, 'ITZY (있지)', 94);
INSERT INTO `list` VALUES ('この歌に誓おう (以此歌为誓)', 27, '吉田亚纪子 (KOKIA)· 《魔道祖师》日文版广播剧主题曲|《何以歌》日语版', 96);
INSERT INTO `list` VALUES ('What Goes Up', 27, 'Lenka', 97);
INSERT INTO `list` VALUES ('一样美丽 (同心版)', 27, '周兴哲/黄妍/林奕匡/E.Viewz/Sezairi/陈柏宇/<NAME>/Ben&Ben/郑心慈/Narelle/陈明憙Jocelyn/NYK/Hà Lê/Wafa Bahiyya Haneesa/Fatin', 95);
INSERT INTO `list` VALUES ('솔직히 지친다 (Everybody Has)', 27, '金请夏 (김청하)', 99);
INSERT INTO `list` VALUES ('Come Around Me', 27, '<NAME>', 98);
INSERT INTO `list` VALUES ('ありがとうはこっちの言葉 (谢谢是我要说的话)', 17, '森山直太朗 (もりやま なおたろう)· 《索玛丽与森林之神》TV动画片头曲', 6);
INSERT INTO `list` VALUES ('無限大 (INFINITY)', 17, 'JO1 (ジェイオーワン)', 4);
INSERT INTO `list` VALUES ('パプリカ (红辣椒)', 17, '米津玄師 (よねづ けんし)', 5);
INSERT INTO `list` VALUES ('Tell me', 17, 'milet (ミレイ)· 《Fate/Grand Order -绝对魔兽战线巴比伦尼亚-》TV动画片尾曲', 7);
INSERT INTO `list` VALUES ('ミスターフィクサー (Mr. Fixer)', 17, 'Sou· 《异度侵入 ID:INVADED》TV动画片头曲', 8);
INSERT INTO `list` VALUES ('Running', 17, 'JO1 (ジェイオーワン)', 9);
INSERT INTO `list` VALUES ('永遠の不在証明 (永远的不在场证明)', 17, '東京事変· 《名侦探柯南:绯色的子弹》剧场版主题曲', 10);
INSERT INTO `list` VALUES ('Sacrifice', 17, 'majiko (まじ娘)', 11);
INSERT INTO `list` VALUES ('アリシア (Alicia)', 17, 'ClariS (クラリス)· 《魔法纪录 魔法少女小圆外传》TV动画片尾曲', 12);
INSERT INTO `list` VALUES ('La Pa Pa Pam', 17, 'JO1 (ジェイオーワン)', 13);
INSERT INTO `list` VALUES ('One Summer\'s Day (from \'Spirited Away\')', 17, '久石让 (ひさいし じょう)/新日本フィルハーモニー交響楽団 (New Japan Philharmonic Orchestra)', 14);
INSERT INTO `list` VALUES ('Tiny Light', 17, '鬼頭明里 (きとう あかり)· 《地缚少年花子君》TV动画片尾曲', 15);
INSERT INTO `list` VALUES ('Prover', 17, 'milet (ミレイ)· 《Fate/Grand Order -绝对魔兽战线巴比伦尼亚-》TV动画片尾曲', 16);
INSERT INTO `list` VALUES ('Good Night', 17, '佐々木李子 (ささき りこ)· 《因为太怕痛就全点防御力了》TV动画插曲', 17);
INSERT INTO `list` VALUES ('モラトリアム (Moratorium)', 17, 'Omoinotake (オモイノタケ)· 《鸣鸟不飞:乌云密布》动画电影主题曲', 18);
INSERT INTO `list` VALUES ('光れ', 17, '鹿乃 (かの)', 19);
INSERT INTO `list` VALUES ('I LOVE...', 17, 'Official髭男dism (Official Hige Dandism)· 《将恋爱进行到底》日剧主题曲', 20);
INSERT INTO `list` VALUES ('エスカルゴ (蜗牛)', 17, 'majiko (まじ娘)', 21);
INSERT INTO `list` VALUES ('Summer', 17, '久石让 (ひさいし じょう)/新日本フィルハーモニー交響楽団 (New Japan Philharmonic Orchestra)', 22);
INSERT INTO `list` VALUES ('unlasting', 17, 'LiSA (織部里沙)· 《刀剑神域 Ⅲ》TV动画片尾曲', 23);
INSERT INTO `list` VALUES ('yours', 17, '鹿乃 (かの)', 24);
INSERT INTO `list` VALUES ('No.7', 17, '生田鷹司 (いくた ようじ)/大石昌良 (オーイシマサヨシ)/ZiNG· 《地缚少年花子君》TV动画片头曲', 25);
INSERT INTO `list` VALUES ('聴いて', 17, '鹿乃 (かの)', 26);
INSERT INTO `list` VALUES ('KILIG', 17, '鹿乃 (かの)', 27);
INSERT INTO `list` VALUES ('漫ろ雨', 17, '鹿乃 (かの)', 28);
INSERT INTO `list` VALUES ('はじまりの詩', 17, '初音未来 (初音ミク)/東北きりたん/神様うさぎ', 29);
INSERT INTO `list` VALUES ('Kiki\'s Delivery Service (From \'Kiki\'s Delivery Service\')', 17, '久石让 (ひさいし じょう)/London Symphony Orchestra', 30);
INSERT INTO `list` VALUES ('have a nice day', 17, '浅葱喵asagiinyo', 31);
INSERT INTO `list` VALUES ('罰と罰 (罚与罚)', 17, '鹿乃 (かの)', 32);
INSERT INTO `list` VALUES ('CHAIN', 17, 'ASCA (アスカ)· 《达尔文游戏》TV动画片头曲', 33);
INSERT INTO `list` VALUES ('Innocent (映画「天空の城ラピュタ」より)', 17, '久石让 (ひさいし じょう)', 34);
INSERT INTO `list` VALUES ('エンディングノート (Ending Note)', 17, '鹿乃 (かの)', 35);
INSERT INTO `list` VALUES ('さよならの今日に (在告別的今天)', 17, '爱缪 (あいみょん)· 《news zero》新闻节目主题曲', 38);
INSERT INTO `list` VALUES ('No.7 (オーイシマサヨシver.)', 17, '大石昌良 (オーイシマサヨシ)', 36);
INSERT INTO `list` VALUES ('Merry-Go-Round', 17, '久石让 (ひさいし じょう)', 37);
INSERT INTO `list` VALUES ('In The Flames', 17, 'Chanmina (ちゃんみな)', 39);
INSERT INTO `list` VALUES ('YOUNG (JO1 ver.)', 17, 'JO1 (ジェイオーワン)', 41);
INSERT INTO `list` VALUES ('おかえり', 17, '鹿乃 (かの)', 40);
INSERT INTO `list` VALUES ('GrandMaster (JO1 ver.)', 17, 'JO1 (ジェイオーワン)', 42);
INSERT INTO `list` VALUES ('ツカメ~It\'s Coming~ (JO1 ver.)', 17, 'JO1 (ジェイオーワン)', 43);
INSERT INTO `list` VALUES ('Running', 17, 'JO1 (ジェイオーワン)', 44);
INSERT INTO `list` VALUES ('ランデヴー (Rendezvous)', 17, '三月的幻想 (三月のパンタシア)', 45);
INSERT INTO `list` VALUES ('モラトリアム (Moratorium)', 17, 'Omoinotake (オモイノタケ)· 《鸣鸟不飞:乌云密布》动画电影主题曲', 46);
INSERT INTO `list` VALUES ('グリム (格林)', 17, 'majiko (まじ娘)', 47);
INSERT INTO `list` VALUES ('REAL×EYEZ', 17, 'J (小野瀬潤)/T.M.Revolution (ティー・エム・レボリューション)· 《假面骑士ZERO-ONE》特摄剧主题曲', 48);
INSERT INTO `list` VALUES ('群青', 17, '神山羊 (かみやま よう)· 《猎龙飞船》TV动画片头曲', 50);
INSERT INTO `list` VALUES ('フレンズ (Friends)', 17, 'wacci (ワッチ)· 《家有圆圆?!我家的圆圆你知道吗?》TV动画片头曲', 49);
INSERT INTO `list` VALUES ('Tiny Light (TV Size)', 17, '鬼頭明里 (きとう あかり)· 《地缚少年花子君》TV动画片尾曲', 51);
INSERT INTO `list` VALUES ('23', 17, 'Rude-α (ルードアルファ)', 52);
INSERT INTO `list` VALUES ('スタンドバイミー (Stand By Me)', 17, '神山羊 (かみやま よう)', 53);
INSERT INTO `list` VALUES ('in my youth', 17, 'リリィ、さよなら。 (Lily Sayonara)', 54);
INSERT INTO `list` VALUES ('つつみ込むように... (深情包围)', 17, 'MISIA (米希亚)', 55);
INSERT INTO `list` VALUES ('センス・オブ・ワンダー (Sense of Wonder)', 17, 'sumika', 56);
INSERT INTO `list` VALUES ('Till the End', 17, 'ReoNa· 刀剑神域刊行十周年纪念主题曲', 57);
INSERT INTO `list` VALUES ('叶问', 17, '川井宪次 (かわい けんじ)· 《叶问4》电影配乐', 58);
INSERT INTO `list` VALUES ('金字塔', 17, 'Reol (れをる)', 59);
INSERT INTO `list` VALUES ('Black Catcher', 17, 'ビッケブランカ (VICKEBLANKA)· 《黑色五叶草》TV动画片头曲', 60);
INSERT INTO `list` VALUES ('From The Seeds', 17, '上白石萌音· 《7SEEDS 第二季》Web动画片头曲', 61);
INSERT INTO `list` VALUES ('HBD', 17, '女王蜂 (じょおうばち)', 62);
INSERT INTO `list` VALUES ('I\'m a slave for you', 17, '川口レイジ (Reiji Kawaguchi)· 《这个男人是我人生中最大的错误》日剧主题曲', 64);
INSERT INTO `list` VALUES ('Driver', 17, 'the engy (ジ・エンギー)· 《心动讯号》日剧主题曲', 63);
INSERT INTO `list` VALUES ('Mozart: Piano Sonata No.2 in F, K.280 - 3. Presto', 17, '<NAME>', 65);
INSERT INTO `list` VALUES ('青空', 17, 'aiko (あいこ)', 66);
INSERT INTO `list` VALUES ('Higher', 17, 'SHE\'S· 第92回選抜高等学校野球大会 MBS公式テーマソング', 67);
INSERT INTO `list` VALUES ('STAYIN\' ALIVE', 17, 'JUJU (ジュジュ)· 《顶级手术刀-天才脑外科医生的条件》日剧主题曲', 68);
INSERT INTO `list` VALUES ('夢のような (如梦一般)', 17, '佐伯ユウスケ (saekiyouthk)· 《石纪元》TV动画片尾曲', 69);
INSERT INTO `list` VALUES ('BL', 17, '女王蜂 (じょおうばち)· 《10的秘密》日剧片头曲', 70);
INSERT INTO `list` VALUES ('ユニゾン (Unison)', 17, 'ClariS (クラリス)', 71);
INSERT INTO `list` VALUES ('無限大 (INFINITY)', 17, 'JO1 (ジェイオーワン)', 72);
INSERT INTO `list` VALUES ('Let\'s☆Go!! Girls', 17, '大黒摩季 (おおぐろ まき)', 73);
INSERT INTO `list` VALUES ('シリタイ', 17, 'SPICY CHOCOLATE (スパイシーチョコレート)/C&K (シーアンドケー)/CYBERJAPAN DANCERS', 74);
INSERT INTO `list` VALUES ('ポラリス (北极星)', 17, 'BLUE ENCOUNT (ブルーエンカウント)· 《我的英雄学院 第四季》TV动画片头曲', 76);
INSERT INTO `list` VALUES ('エスカルゴ (蜗牛)', 17, 'majiko (まじ娘)', 75);
INSERT INTO `list` VALUES ('ワスレナグサ (勿忘草)', 17, '蓮花 (れんか)', 77);
INSERT INTO `list` VALUES ('Sissy Sky', 17, '宮川愛李· 《名侦探柯南》TV动画片尾曲', 78);
INSERT INTO `list` VALUES ('チューリングラブ (Turing Love)', 17, 'ナナヲアカリ (Nanawoakari)/Sou· 《理科生坠入情网故尝试证明》TV动画片尾曲', 79);
INSERT INTO `list` VALUES ('シグナル (信号)', 17, 'ClariS (クラリス)· 《魔法纪录 魔法少女小圆外传:集结的百祸篇》游戏印象曲', 80);
INSERT INTO `list` VALUES ('Your Light', 17, 'milet (ミレイ)', 82);
INSERT INTO `list` VALUES ('Silence', 17, '久石让 (ひさいし じょう)', 81);
INSERT INTO `list` VALUES ('トロイの馬', 17, 'majiko (まじ娘)', 83);
INSERT INTO `list` VALUES ('チューリップ (郁金香)', 17, 'indigo la End (インディゴ ラ エンド)', 84);
INSERT INTO `list` VALUES ('STOP', 17, '川口レイジ (Reiji Kawaguchi)· 《这个男人是我人生中最大的错误》日剧片尾曲', 85);
INSERT INTO `list` VALUES ('New Page', 17, 'INTERSECTION (交差点)· 《黑色五叶草》TV动画片尾曲', 86);
INSERT INTO `list` VALUES ('ありがとうはこっちの言葉 (谢谢是我要说的话) (TV version)', 17, '森山直太朗 (もりやま なおたろう)· 《索玛丽与森林之神》TV动画片头曲', 87);
INSERT INTO `list` VALUES ('窓辺の即興曲 (窗边的即兴曲)', 17, 'オワタP (OwataP)/初音未来 (初音ミク)', 88);
INSERT INTO `list` VALUES ('ムズイ', 17, '22/7· 《22/7》TV动画片头曲', 89);
INSERT INTO `list` VALUES ('Kiki\'s Delivery Service', 17, '久石让 (ひさいし じょう)', 90);
INSERT INTO `list` VALUES ('Play the world', 17, '佐々木李子 (ささき りこ)· 《因为太怕痛就全点防御力了》TV动画片尾曲', 91);
INSERT INTO `list` VALUES ('光の道標 (光之路标)', 17, '鹿乃 (かの)· 《碧蓝航线》TV动画片尾曲', 92);
INSERT INTO `list` VALUES ('P R I D E', 17, '女王蜂 (じょおうばち)', 93);
INSERT INTO `list` VALUES ('あの日の未来', 17, 'リリィ、さよなら。 (Lily Sayonara)', 94);
INSERT INTO `list` VALUES ('星が降るユメ (繁星降落之梦)', 17, '蓝井艾露 (藍井エイル)· 《Fate/Grand Order -绝对魔兽战线巴比伦尼亚-》TV动画片尾曲', 95);
INSERT INTO `list` VALUES ('丸の内サディスティック', 17, '椎名林檎 (しいな りんご)', 97);
INSERT INTO `list` VALUES ('ユーモア (幽默)', 17, 'King Gnu (キング・ヌー)', 96);
INSERT INTO `list` VALUES ('Runnin\' feat. kZm, SIRUP', 17, 'BIM/kZm/SIRUP (シラップ)', 98);
INSERT INTO `list` VALUES ('サンサーラ (轮回)', 17, 'majiko (まじ娘)', 99);
INSERT INTO `list` VALUES ('够爱', 4, '胜屿', 4);
INSERT INTO `list` VALUES ('End of Time', 4, 'K-391/Alan Walker/Ahrix', 5);
INSERT INTO `list` VALUES ('我这一生', 4, '小曼', 6);
INSERT INTO `list` VALUES ('Will You Marry Me', 4, '一口甜', 7);
INSERT INTO `list` VALUES ('我这一生', 4, '马健涛', 8);
INSERT INTO `list` VALUES ('给女孩(单曲)', 4, '李宇春', 9);
INSERT INTO `list` VALUES ('心愿便利贴', 4, '王欣宇', 10);
INSERT INTO `list` VALUES ('借 (Live)', 4, '毛不易', 11);
INSERT INTO `list` VALUES ('冬日', 4, '鞠婧祎', 12);
INSERT INTO `list` VALUES ('你是对的人', 4, '戚薇/李俊昊 (이준호)· 《爱情回来了》电视剧片尾曲|《天天炫舞》背景音乐', 13);
INSERT INTO `list` VALUES ('春娇与志明', 4, '街道办GDC/欧阳耀莹', 14);
INSERT INTO `list` VALUES ('Monsters', 4, 'Katie Sky', 15);
INSERT INTO `list` VALUES ('后继者', 4, '任然', 16);
INSERT INTO `list` VALUES ('每个人都是孤独的', 4, '苏晗', 17);
INSERT INTO `list` VALUES ('惊雷', 4, 'MC阳子', 18);
INSERT INTO `list` VALUES ('夜空中最亮的星', 4, '逃跑计划', 19);
INSERT INTO `list` VALUES ('海月之端', 4, '双笙', 20);
INSERT INTO `list` VALUES ('盗墓笔记·十年人间', 4, '李常超· 八一七稻米节主题推广曲', 21);
INSERT INTO `list` VALUES ('WANNABE', 4, 'ITZY (있지)', 22);
INSERT INTO `list` VALUES ('Dancing With Your Ghost', 4, '<NAME>', 23);
INSERT INTO `list` VALUES ('因为我们在一起', 4, '王一博', 24);
INSERT INTO `list` VALUES ('王源:快跟着我进入文物的时空漫游吧!', 4, '王源', 25);
INSERT INTO `list` VALUES ('我这一生', 4, '半吨兄弟', 26);
INSERT INTO `list` VALUES ('红黑', 4, '小星星Aurora', 27);
INSERT INTO `list` VALUES ('Manta', 4, '刘柏辛Lexie', 28);
INSERT INTO `list` VALUES ('这就是爱吗?', 4, '容祖儿', 29);
INSERT INTO `list` VALUES ('Coming Home', 4, 'Diddy-Dirty Money/Skylar Grey', 30);
INSERT INTO `list` VALUES ('敢爱敢做', 4, '林子祥· 《神奇两女侠》电影主题曲', 31);
INSERT INTO `list` VALUES ('天空之外', 4, '解语花', 32);
INSERT INTO `list` VALUES ('让我欢喜让我忧', 4, '杨小壮/鹏鹏', 33);
INSERT INTO `list` VALUES ('迷人的危险', 4, '馅儿/neko', 34);
INSERT INTO `list` VALUES ('孤单的人', 4, '海来阿木', 35);
INSERT INTO `list` VALUES ('十年', 4, '陈奕迅· 《明年今日》国语版|《隐婚男女》电影插曲|《摆渡人》电影插曲', 36);
INSERT INTO `list` VALUES ('无人之岛', 4, '任然', 37);
INSERT INTO `list` VALUES ('无心斗艳', 4, '大布/苏泽龙', 38);
INSERT INTO `list` VALUES ('太阳 (女生版)', 4, '吕口口', 39);
INSERT INTO `list` VALUES ('年少有为 (Cover李荣浩)', 4, '酷', 40);
INSERT INTO `list` VALUES ('Sold Out', 4, '<NAME>', 41);
INSERT INTO `list` VALUES ('口是心非', 4, '杨小壮/鹏鹏', 42);
INSERT INTO `list` VALUES ('영웅 (英雄; Kick It)', 4, 'NCT 127 (엔씨티 127)', 43);
INSERT INTO `list` VALUES ('分手的话', 4, '苏谭谭', 44);
INSERT INTO `list` VALUES ('想你', 4, '艾辰', 45);
INSERT INTO `list` VALUES ('自己', 4, '刘亦菲· 电影《花木兰》中文主题曲', 46);
INSERT INTO `list` VALUES ('房间', 4, '刘瑞琦', 47);
INSERT INTO `list` VALUES ('平安回来', 4, '景甜/谭松韵/白宇', 49);
INSERT INTO `list` VALUES ('火苗 (男生版)', 4, '王不难', 48);
INSERT INTO `list` VALUES ('你走以后1.0', 4, '王恩信Est/二胖u', 50);
INSERT INTO `list` VALUES ('下凡', 4, '祝眠', 51);
INSERT INTO `list` VALUES ('好的 晚安 (Live)', 4, '邓见超', 54);
INSERT INTO `list` VALUES ('NUMB', 4, 'XXXTentacion', 52);
INSERT INTO `list` VALUES ('言不由衷', 4, '徐佳莹', 53);
INSERT INTO `list` VALUES ('你说的以后', 4, '蒋雪儿', 55);
INSERT INTO `list` VALUES ('红色高跟鞋', 4, '蔡健雅· 《爱情左右》电影主题曲', 56);
INSERT INTO `list` VALUES ('苏幕遮', 4, '张晓棠', 57);
INSERT INTO `list` VALUES ('U Make Me (Natan Chaim & Asketa Remix)', 4, 'Disco Fries/Raque<NAME>', 58);
INSERT INTO `list` VALUES ('据说真的有神', 4, '木秦', 59);
INSERT INTO `list` VALUES ('二十岁的遗言', 4, '陈思键', 60);
INSERT INTO `list` VALUES ('豆浆油条', 4, '林俊杰· 《医馆笑传2》电视剧插曲', 61);
INSERT INTO `list` VALUES ('心欲止水', 4, '张碧晨· 《三生三世枕上书》电视剧插曲', 63);
INSERT INTO `list` VALUES ('最美的伤口', 4, '半吨兄弟', 62);
INSERT INTO `list` VALUES ('父亲写的散文诗 (时光版)', 4, '许飞', 64);
INSERT INTO `list` VALUES ('어떤 말도 (No Words)', 4, 'Crush (크러쉬)· 《梨泰院Class》韩剧插曲', 65);
INSERT INTO `list` VALUES ('Loyal Brave True (From \"Mulan\")', 4, '<NAME>', 66);
INSERT INTO `list` VALUES ('Who (feat. BTS)', 4, 'Lauv/BTS (防弹少年团)', 67);
INSERT INTO `list` VALUES ('挪威的森林', 4, '伍佰', 68);
INSERT INTO `list` VALUES ('시작 (开始)', 4, 'Gaho (가호)· 《梨泰院Class》韩剧插曲', 69);
INSERT INTO `list` VALUES ('关键词', 4, '林俊杰', 70);
INSERT INTO `list` VALUES ('天后', 4, '陈势安· 《面具》国语版', 71);
INSERT INTO `list` VALUES ('清明上河图', 4, '李玉刚', 72);
INSERT INTO `list` VALUES ('꿈 (Boom) (梦)', 4, 'NCT 127 (엔씨티 127)', 73);
INSERT INTO `list` VALUES ('我要找到你', 4, '连音社', 74);
INSERT INTO `list` VALUES ('消愁 (Live)', 4, '毛不易', 75);
INSERT INTO `list` VALUES ('以后的以后', 4, '庄心妍', 76);
INSERT INTO `list` VALUES ('我要找到你', 4, '小阿枫', 77);
INSERT INTO `list` VALUES ('黄沙', 4, '名决', 78);
INSERT INTO `list` VALUES ('秘语', 4, '欧阳娜娜/陈飞宇· 《秘果》电影悸动版推广曲', 79);
INSERT INTO `list` VALUES ('Elevator (127F)', 4, 'NCT 127 (엔씨티 127)', 80);
INSERT INTO `list` VALUES ('Turn All the Lights On', 4, 'T-Pain/Ne-Yo', 81);
INSERT INTO `list` VALUES ('快醒醒', 4, '黄晨晨', 82);
INSERT INTO `list` VALUES ('Touch The Sky', 4, '<NAME>/Digital Farm Animals/D<NAME>', 83);
INSERT INTO `list` VALUES ('DJDJ给我一条K (抖音完整版)', 4, '新旭', 84);
INSERT INTO `list` VALUES ('老街', 4, '李荣浩', 86);
INSERT INTO `list` VALUES ('来生再去拥抱你', 4, '一只舟', 85);
INSERT INTO `list` VALUES ('我爱他', 4, '王小帅', 87);
INSERT INTO `list` VALUES ('来我怀里', 4, 'Smeng', 88);
INSERT INTO `list` VALUES ('再见只是陌生人', 4, '庄心妍', 89);
INSERT INTO `list` VALUES ('年少有为', 4, '李荣浩', 90);
INSERT INTO `list` VALUES ('奢香夫人', 4, '凤凰传奇', 91);
INSERT INTO `list` VALUES ('今生相爱', 4, '泽尔丹/扎西措', 92);
INSERT INTO `list` VALUES ('演员', 4, '薛之谦', 93);
INSERT INTO `list` VALUES ('后会无期', 4, 'G.E.M. 邓紫棋· 《后会无期》电影同名主题歌|《The End Of The World》中文版', 94);
INSERT INTO `list` VALUES ('Monsters', 4, 'Timeflies/Katie Sky', 95);
INSERT INTO `list` VALUES ('TING TING TING with <NAME>', 4, 'ITZY (있지)/<NAME>', 96);
INSERT INTO `list` VALUES ('不是因为寂寞才想你', 4, '王小帅', 97);
INSERT INTO `list` VALUES ('Love Story', 4, '<NAME>', 98);
INSERT INTO `list` VALUES ('丫头', 4, '王童语· 《多少爱,可以重来》电视剧插曲', 99);
INSERT INTO `list` VALUES ('出征(大风歌)', 58, '宝石Gem', 3);
INSERT INTO `list` VALUES ('差不多姑娘', 58, 'G.E.M. 邓紫棋', 4);
INSERT INTO `list` VALUES ('两个普普通通小青年', 58, '李荣浩/刘柏辛Lexie', 5);
INSERT INTO `list` VALUES ('贰叁', 58, '吴亦凡', 6);
INSERT INTO `list` VALUES ('当渣男你不配', 58, 'coco这个李文', 7);
INSERT INTO `list` VALUES ('Don’t Wanna Lie (feat. 8lak, Hosea)', 58, '派伟俊/8lak/Hosea', 8);
INSERT INTO `list` VALUES ('野狼Disco (国风版)', 58, 'SING女团', 9);
INSERT INTO `list` VALUES ('生来如此', 58, '福克斯', 10);
INSERT INTO `list` VALUES ('归山', 58, '福克斯', 11);
INSERT INTO `list` VALUES ('玫瑰星云 Holy', 58, '刘柏辛Lexie', 12);
INSERT INTO `list` VALUES ('角儿无大小', 58, '十一少年的秋天/R1SE', 13);
INSERT INTO `list` VALUES ('空城', 58, 'KIT翌', 14);
INSERT INTO `list` VALUES ('失眠', 58, 'Ice Paper', 15);
INSERT INTO `list` VALUES ('第一顺位', 58, '吴亦凡/杨和苏KeyNG', 16);
INSERT INTO `list` VALUES ('浮云', 58, '任嘉伦', 17);
INSERT INTO `list` VALUES ('镜子', 58, '直火帮XZT/直火帮StraightFireGang', 18);
INSERT INTO `list` VALUES ('潘洛斯阶梯 Penrose', 58, '刘柏辛Lexie', 19);
INSERT INTO `list` VALUES ('野狼Disco (吃鸡版)', 58, '宝石Gem/沫子Mozz', 20);
INSERT INTO `list` VALUES ('summer holiday', 58, 'Young T', 21);
INSERT INTO `list` VALUES ('有空一起吃饭 (问候版)', 58, '新裤子/GAI', 22);
INSERT INTO `list` VALUES ('超能力', 58, 'Ice Paper', 23);
INSERT INTO `list` VALUES ('玩家的战歌', 58, '艾福杰尼· 《穿越火线:枪战王者》四周年主题曲', 24);
INSERT INTO `list` VALUES ('哎', 58, '黄子韬/韬斯曼', 25);
INSERT INTO `list` VALUES ('风吹草动', 58, '吴亦凡/大傻DamnShine', 26);
INSERT INTO `list` VALUES ('不是你的错', 58, '满舒克/董又霖', 27);
INSERT INTO `list` VALUES ('当你从没来过 pt.3', 58, 'StickyT/Over $ize', 28);
INSERT INTO `list` VALUES ('巾帼木兰', 58, 'VaVa毛衍七· 《部落冲突》巾帼木兰皮肤主题曲', 29);
INSERT INTO `list` VALUES ('Miss Me', 58, '王鹤棣/Ty.', 30);
INSERT INTO `list` VALUES ('城市烟火', 58, '王自健/丁嘉乐(Real Rascal)· 《安家》电视剧片头曲', 31);
INSERT INTO `list` VALUES ('也许这就是长大', 58, '爆音BOOM', 32);
INSERT INTO `list` VALUES ('Million Swag', 58, '黄旭', 33);
INSERT INTO `list` VALUES ('2020全都要稳', 58, '永彬Ryan.B', 34);
INSERT INTO `list` VALUES ('街头霸王', 58, '新秀', 35);
INSERT INTO `list` VALUES ('如果(If..)', 58, 'BOY STORY', 36);
INSERT INTO `list` VALUES ('肥龙过江', 58, '甄子丹/Jasmine Yen· 《肥龙过江》电影宣传曲', 37);
INSERT INTO `list` VALUES ('雨季', 58, '王齐铭WatchMe', 38);
INSERT INTO `list` VALUES ('Forever Young (ft. 福克斯)', 58, 'AR(刘夫阳)/福克斯', 39);
INSERT INTO `list` VALUES ('孤独行刑者 (刺客版)', 58, 'JX3暗箱组合· 剑网3凌雪藏锋版本宣传曲', 40);
INSERT INTO `list` VALUES ('催婚', 58, '孙八一', 41);
INSERT INTO `list` VALUES ('希望', 58, 'AR(刘夫阳)/Q.luv', 42);
INSERT INTO `list` VALUES ('黑暗中闪烁', 58, '8点组乐团', 43);
INSERT INTO `list` VALUES ('异地恋', 58, 'Max马俊', 44);
INSERT INTO `list` VALUES ('COLORFUL', 58, '娄峻硕', 45);
INSERT INTO `list` VALUES ('凌晨五点', 58, 'L4WUDU', 46);
INSERT INTO `list` VALUES ('如果真的我想要', 58, '黄旭', 47);
INSERT INTO `list` VALUES ('China Town', 58, 'Kigga/派克特', 49);
INSERT INTO `list` VALUES ('不退', 58, '杨和苏KeyNG· 《魔域》热血战歌', 48);
INSERT INTO `list` VALUES ('最冷的一天', 59, '谢东闵· 《庆余年》粤语版电视剧主题曲', 3);
INSERT INTO `list` VALUES ('我不是她', 59, 'HANA菊梓乔· 《法证先锋IV》电视剧片尾曲', 4);
INSERT INTO `list` VALUES ('圆谎', 59, '侧田· 《法证先锋IV》电视剧主题曲', 6);
INSERT INTO `list` VALUES ('Mad', 59, 'AGA', 7);
INSERT INTO `list` VALUES ('低半度', 59, '卫兰', 5);
INSERT INTO `list` VALUES ('不要流泪', 59, '郑俊弘· 《法证先锋IV》电视剧主题曲', 8);
INSERT INTO `list` VALUES ('嫁给爱情', 59, '杨千嬅· 《多功能老婆》电视剧主题曲', 9);
INSERT INTO `list` VALUES ('很久以后', 59, 'G.E.M. 邓紫棋· 《可不可以,你也刚好喜欢我》电影主题曲', 10);
INSERT INTO `list` VALUES ('那些没说出口的话', 59, '容祖儿· 《完美关系》电视剧情感主题曲', 11);
INSERT INTO `list` VALUES ('透明', 59, 'G.E.M. 邓紫棋', 12);
INSERT INTO `list` VALUES ('摩天动物园', 59, 'G.E.M. 邓紫棋', 13);
INSERT INTO `list` VALUES ('中华民族', 59, '莫文蔚/韩磊/谭维维/孙楠', 14);
INSERT INTO `list` VALUES ('似水流年', 59, '吴若希· 《大酱园》电视剧片尾曲', 15);
INSERT INTO `list` VALUES ('阿兹与海默', 59, '黎晓阳', 16);
INSERT INTO `list` VALUES ('果子', 59, '卢冠廷', 17);
INSERT INTO `list` VALUES ('亲密距离', 59, '刘美君', 18);
INSERT INTO `list` VALUES ('真心不变', 59, '谭嘉仪· 《大酱园》电视剧主题曲', 19);
INSERT INTO `list` VALUES ('没身份妒忌', 59, '胡鸿钧', 20);
INSERT INTO `list` VALUES ('日光', 59, '梁钊峰/陈仕燊', 21);
INSERT INTO `list` VALUES ('今宵多珍重', 59, '谭嘉仪· 《金宵大厦》剧集主题曲', 22);
INSERT INTO `list` VALUES ('你喜欢说谎', 59, 'HANA菊梓乔· 《黄金有罪》电视剧片尾曲', 23);
INSERT INTO `list` VALUES ('玩具成熟时', 59, '吴业坤', 24);
INSERT INTO `list` VALUES ('找到一个人', 59, '曾乐彤', 25);
INSERT INTO `list` VALUES ('喜剧收场', 59, '洪卓立', 26);
INSERT INTO `list` VALUES ('快闪', 59, '郑俊弘· 《黄金有罪》电视剧主题曲', 27);
INSERT INTO `list` VALUES ('零分', 59, 'JUDE曾若华', 28);
INSERT INTO `list` VALUES ('上善若水', 59, '黄子华/农夫· 《乜代宗师》电影主题曲', 29);
INSERT INTO `list` VALUES ('差不多姑娘', 59, 'G.E.M. 邓紫棋', 30);
INSERT INTO `list` VALUES ('透明的存在', 59, '许靖韵· 《完美关系》电视剧插曲', 31);
INSERT INTO `list` VALUES ('Walk on Water', 59, 'G.E.M. 邓紫棋· 《终结者:黑暗命运》电影中国区主题曲', 32);
INSERT INTO `list` VALUES ('一秒', 59, '林欣彤', 33);
INSERT INTO `list` VALUES ('说分手', 59, '连诗雅', 34);
INSERT INTO `list` VALUES ('最后晚餐 (2019)', 59, 'Supper Moment', 35);
INSERT INTO `list` VALUES ('我为我坚强', 59, '谷娅溦· 《独孤皇后》电视剧主题曲', 36);
INSERT INTO `list` VALUES ('Two at a time', 59, 'AGA', 37);
INSERT INTO `list` VALUES ('拼命无恙', 59, '林家谦', 38);
INSERT INTO `list` VALUES ('造就更好', 59, '容祖儿', 39);
INSERT INTO `list` VALUES ('是你令我再次找到心跳 (2019)', 59, 'Supper Moment', 40);
INSERT INTO `list` VALUES ('愿留住你 (Can You Hear 广东合唱版)', 59, '谭嘉仪/马国明', 41);
INSERT INTO `list` VALUES ('每段爱还是错', 59, '吴若希· 《多功能老婆》电视剧插曲', 42);
INSERT INTO `list` VALUES ('高攀爱', 59, '李靖筠· 《我的笋盘男友》电影主题曲', 43);
INSERT INTO `list` VALUES ('最安静的时候 (2019)', 59, 'Supper Moment', 44);
INSERT INTO `list` VALUES ('天光前分手', 59, '戴祖仪· 《多功能老婆》电视剧插曲', 45);
INSERT INTO `list` VALUES ('P.S. I Love You (2019)', 59, 'Supper Moment', 46);
INSERT INTO `list` VALUES ('将心比己', 59, '许廷铿', 47);
INSERT INTO `list` VALUES ('相信一切是最好的安排', 59, '陈蕾', 48);
INSERT INTO `list` VALUES ('平安夜 (打打气版)', 59, '梁咏琪', 50);
INSERT INTO `list` VALUES ('逆光飞翔', 59, 'HANA菊梓乔· 《凤弈》 电视剧主题曲', 49);
INSERT INTO `list` VALUES ('想勇敢一次', 59, '谭嘉仪· 《丫鬟大联盟》电视剧主题曲', 51);
INSERT INTO `list` VALUES ('初音', 59, '林二汶', 52);
INSERT INTO `list` VALUES ('冷处理', 59, '陈凯彤', 53);
INSERT INTO `list` VALUES ('黑方格', 59, '林奕匡/<NAME>', 54);
INSERT INTO `list` VALUES ('爱不起', 59, '王浩信· 《解决师》电视剧片尾曲', 55);
INSERT INTO `list` VALUES ('爱斯基摩人之吻', 59, '冯允谦', 56);
INSERT INTO `list` VALUES ('仙水', 59, '罗力威', 57);
INSERT INTO `list` VALUES ('了解中', 59, '卫诗', 58);
INSERT INTO `list` VALUES ('我说不可以', 59, '洪嘉豪', 60);
INSERT INTO `list` VALUES ('爱没怀疑', 59, '吴浩康', 59);
INSERT INTO `list` VALUES ('未知道', 59, '陈健安', 61);
INSERT INTO `list` VALUES ('你可能未必不喜欢我', 59, '许廷铿', 62);
INSERT INTO `list` VALUES ('逃生门 (门外版)', 59, '周国贤/王灏儿', 63);
INSERT INTO `list` VALUES ('有你有我 (2019)', 59, 'Supper Moment', 65);
INSERT INTO `list` VALUES ('最后的一个收费亭', 59, '陈柏宇', 64);
INSERT INTO `list` VALUES ('人魂道', 59, 'ToNick· 倩女幽魂2游戏主题曲', 66);
INSERT INTO `list` VALUES ('世事何曾是绝对', 59, '谭嘉仪', 67);
INSERT INTO `list` VALUES ('附近的人', 59, 'Yellow!', 68);
INSERT INTO `list` VALUES ('寻找白金汉 (合唱版)', 59, '冯允谦/黄淑蔓', 69);
INSERT INTO `list` VALUES ('Dear Christmas', 59, 'Dear Jane', 70);
INSERT INTO `list` VALUES ('今夜酒气吹过 (2019)', 59, 'Supper Moment', 71);
INSERT INTO `list` VALUES ('星空漫步 (Can You See 广东版)', 59, '谭嘉仪', 72);
INSERT INTO `list` VALUES ('刮骨', 59, '黄妍', 76);
INSERT INTO `list` VALUES ('面对', 59, '卫兰', 73);
INSERT INTO `list` VALUES ('懂得快乐 (2019)', 59, 'Supper Moment', 74);
INSERT INTO `list` VALUES ('我会想念他', 59, '何雁诗· 《牛下女高音》电视剧片尾曲', 75);
INSERT INTO `list` VALUES ('爸爸的礼物', 59, '陈柏宇', 77);
INSERT INTO `list` VALUES ('头顶有角', 59, '关智斌/黄宇希', 78);
INSERT INTO `list` VALUES ('荒废之绿洲', 59, '许廷铿', 80);
INSERT INTO `list` VALUES ('等等… (2019)', 59, 'Supper Moment', 79);
INSERT INTO `list` VALUES ('很久没拥抱 (2019)', 59, 'Supper Moment', 81);
INSERT INTO `list` VALUES ('奔向未来日子 (电影\"英雄本色续集\"主题曲)', 59, '张国荣', 82);
INSERT INTO `list` VALUES ('游乐 (粤语版)', 59, '陈明憙Jocelyn', 83);
INSERT INTO `list` VALUES ('Goodnight City (2019)', 59, 'Supper Moment', 84);
INSERT INTO `list` VALUES ('望', 59, '方皓玟', 85);
INSERT INTO `list` VALUES ('天知', 59, '梁钊峰/陈健安· 《解决师》电视剧主题曲', 86);
INSERT INTO `list` VALUES ('阿郎恋曲 (电影《阿郎的故事》歌曲)', 59, '许冠杰', 87);
INSERT INTO `list` VALUES ('最紧要好玩 (电影《打工皇帝》主题曲)', 59, '许冠杰', 88);
INSERT INTO `list` VALUES ('沙燕之歌 (2019)', 59, 'Supper Moment', 89);
INSERT INTO `list` VALUES ('家门', 59, '卫兰/冯允谦', 90);
INSERT INTO `list` VALUES ('譲我跟你走', 59, '叶丽仪', 91);
INSERT INTO `list` VALUES ('Lonely (广东版)', 59, '谭嘉仪', 92);
INSERT INTO `list` VALUES ('闲话当年', 59, '叶丽仪', 93);
INSERT INTO `list` VALUES ('永恒少年', 59, '曾乐彤', 94);
INSERT INTO `list` VALUES ('第千次重逢', 59, '李靖筠', 95);
INSERT INTO `list` VALUES ('肥皂泡 (2019)', 59, 'Supper Moment', 96);
INSERT INTO `list` VALUES ('桥下十三郎', 59, '陈柏宇', 97);
INSERT INTO `list` VALUES ('音乐说故事 (第一集 电脑)', 59, '梁咏琪/涂毓麟', 98);
INSERT INTO `list` VALUES ('重读兴趣班', 59, '林奕匡', 99);
INSERT INTO `list` VALUES ('Amazing(迷人的你)', 61, '林世民· 《下一站是幸福》电视剧片尾曲', 4);
INSERT INTO `list` VALUES ('安和', 61, '苏慧伦', 6);
INSERT INTO `list` VALUES ('一样美丽 (同心版)', 61, '周兴哲/黄妍/林奕匡/E.Viewz/Sezairi/陈柏宇/<NAME>/Ben&Ben/郑心慈/Narelle/陈明憙Jocelyn/NYK/Hà Lê/W<NAME>ahiyya Haneesa/Fatin', 5);
INSERT INTO `list` VALUES ('温柔 #MaydayBlue20th', 61, '五月天/孙燕姿', 7);
INSERT INTO `list` VALUES ('Forever Your Dad', 61, '王力宏', 8);
INSERT INTO `list` VALUES ('一心一念', 61, '欧阳娜娜· 《北灵少年志之大主宰》电视剧片尾曲', 9);
INSERT INTO `list` VALUES ('悬日', 61, '田馥甄', 10);
INSERT INTO `list` VALUES ('I’m Falling in Love', 61, '郭静/宁桓宇· 《少主且慢行》电视剧插曲', 12);
INSERT INTO `list` VALUES ('气温37度的遐想', 61, '苏慧伦/魏如萱', 13);
INSERT INTO `list` VALUES ('仰望', 61, '陈威全', 11);
INSERT INTO `list` VALUES ('永远的一天', 61, '苏慧伦', 14);
INSERT INTO `list` VALUES ('为你变成他', 61, '苏慧伦', 15);
INSERT INTO `list` VALUES ('你的影子是我的海', 61, '吴青峰· from 王小苗诗集《邪恶的纯真》pp.108-110.', 16);
INSERT INTO `list` VALUES ('Don’t Wanna Lie (feat. 8lak, Hosea)', 61, '派伟俊/8lak/Hosea', 17);
INSERT INTO `list` VALUES ('你会想念我吗', 61, '苏慧伦', 18);
INSERT INTO `list` VALUES ('量力而为', 61, '苏慧伦', 19);
INSERT INTO `list` VALUES ('烂醉', 61, '颜人中', 20);
INSERT INTO `list` VALUES ('远行', 61, '苏慧伦', 21);
INSERT INTO `list` VALUES ('你', 61, '毕书尽', 22);
INSERT INTO `list` VALUES ('坚信爱会赢', 61, '王力宏/田桐/成龙/李光洁/肖战/吴京/沈腾/宋佳/杨培安/张蕾/陈建斌/林永健/佟丽娅/海霞/黄晓明/舒楠/雷佳/谭维维', 23);
INSERT INTO `list` VALUES ('点亮一束光', 61, '陈志朋', 24);
INSERT INTO `list` VALUES ('与生俱来的黑', 61, '苏慧伦', 26);
INSERT INTO `list` VALUES ('亲爱的全部', 61, '苏慧伦', 25);
INSERT INTO `list` VALUES ('幸福特写', 61, '陈立农', 27);
INSERT INTO `list` VALUES ('背光旅行', 61, '黄伟晋', 28);
INSERT INTO `list` VALUES ('迷人的危险', 61, '蔡黄汝', 29);
INSERT INTO `list` VALUES ('红红的太阳', 61, '张韶涵', 30);
INSERT INTO `list` VALUES ('小时候的我们', 61, '周兴哲', 31);
INSERT INTO `list` VALUES ('我喜欢你', 61, '彭佳慧', 32);
INSERT INTO `list` VALUES ('像风', 61, '郭静· 《将夜2》影视剧插曲', 33);
INSERT INTO `list` VALUES ('Colorful', 61, '郭静· 《身为一个胖子》电视剧主题曲', 34);
INSERT INTO `list` VALUES ('少年', 61, '周华健', 35);
INSERT INTO `list` VALUES ('春到了', 61, '黄小琥', 36);
INSERT INTO `list` VALUES ('当你和心跳一起出现', 61, '萧亚轩', 38);
INSERT INTO `list` VALUES ('默念你', 61, '宋念宇', 37);
INSERT INTO `list` VALUES ('你的情歌', 61, 'Tank', 39);
INSERT INTO `list` VALUES ('在我成为井井有条的大人之前', 61, '郭采洁', 40);
INSERT INTO `list` VALUES ('Be Me', 61, '李玉玺', 41);
INSERT INTO `list` VALUES ('受够', 61, '周兴哲', 43);
INSERT INTO `list` VALUES ('爱永远', 61, '柯以敏', 42);
INSERT INTO `list` VALUES ('借我一生', 61, '张芸京· 《将夜2》影视剧插曲', 44);
INSERT INTO `list` VALUES ('我很快乐', 61, '周兴哲', 45);
INSERT INTO `list` VALUES ('情人节的许愿', 61, '阿沁', 46);
INSERT INTO `list` VALUES ('我一直都在这里', 61, '徐佳莹· 《熊出没·狂野大陆》电影主题曲', 47);
INSERT INTO `list` VALUES ('背光', 61, '杨宗纬· 《被光抓走的人》电影主题曲', 48);
INSERT INTO `list` VALUES ('七十亿分之一加一', 61, '吴卓源/娄峻硕', 49);
INSERT INTO `list` VALUES ('让爱逆行', 61, '郭品超/汪东城/辰亦儒', 50);
INSERT INTO `list` VALUES ('够不着的你', 61, '安心亚· 《坠爱》爱奇艺片尾曲', 51);
INSERT INTO `list` VALUES ('你钉起来真好听 (儿童版)', 61, '方冉星', 52);
INSERT INTO `list` VALUES ('梦里千回', 61, '徐怀钰· 《将夜2》影视剧插曲', 53);
INSERT INTO `list` VALUES ('民谣.唐', 61, '李佩玲· 《少年李白花月离》网络电影主题曲', 54);
INSERT INTO `list` VALUES ('带我去找夜生活', 61, '告五人', 55);
INSERT INTO `list` VALUES ('狂浪', 61, '彭于晏/王彦霖/辛芷蕾/王雨甜/徐洋/陈家乐/李岷城· 《紧急救援》电影宣传曲', 56);
INSERT INTO `list` VALUES ('离开我的依赖', 61, '王艳薇', 57);
INSERT INTO `list` VALUES ('流浪狗 (黄明志独唱版本)', 61, '黄明志', 58);
INSERT INTO `list` VALUES ('时间梯', 61, '万芳', 59);
INSERT INTO `list` VALUES ('COLORFUL', 61, '娄峻硕', 60);
INSERT INTO `list` VALUES ('逆行', 61, '张惠春/郝澄泉RogerQ', 61);
INSERT INTO `list` VALUES ('相信爱', 61, '周兴哲', 62);
INSERT INTO `list` VALUES ('大明星', 61, 'AJ张杰', 63);
INSERT INTO `list` VALUES ('<NAME> - 双截棍 (<NAME>)', 61, '派伟俊', 64);
INSERT INTO `list` VALUES ('假装', 61, '梁一贞', 65);
INSERT INTO `list` VALUES ('泰国情哥 (亚洲通话新歌发布会现场版本)', 61, '黄明志', 66);
INSERT INTO `list` VALUES ('示爱嫌疑', 61, '董又霖', 67);
INSERT INTO `list` VALUES ('我知道你都知道', 61, '陈威全', 68);
INSERT INTO `list` VALUES ('请珍重', 61, '罗大佑', 70);
INSERT INTO `list` VALUES ('其实你并没那么孤单', 61, '周兴哲', 69);
INSERT INTO `list` VALUES ('女士优先(feat. ?te)', 61, '老莫/李怀特', 71);
INSERT INTO `list` VALUES ('In the Works', 61, '周兴哲', 72);
INSERT INTO `list` VALUES ('世界为你醒来 (好声音接力9)', 61, '刘明湘/李佩玲/黄一/关诗敏/陈颖恩/古洁萦/长宇/吕纬青/罗金荣/吴映香', 73);
INSERT INTO `list` VALUES ('上古情歌', 61, '齐豫· 《大明风华》电视剧插曲', 74);
INSERT INTO `list` VALUES ('我最骄傲爱过的人 (Demo版)', 61, '张简君伟', 75);
INSERT INTO `list` VALUES ('我知道', 61, 'CT2', 76);
INSERT INTO `list` VALUES ('无关幸福', 61, '曾静玟', 77);
INSERT INTO `list` VALUES ('不忘', 61, '范玮琪', 78);
INSERT INTO `list` VALUES ('江湖吾路 (霹雳侠峰片头曲)', 61, '刘昱贤/霹雳布袋戏', 79);
INSERT INTO `list` VALUES ('在名为未来的波浪里', 61, '原子邦妮', 80);
INSERT INTO `list` VALUES ('破晓', 61, '杨培安', 81);
INSERT INTO `list` VALUES ('天使爱大象', 61, '徐佳莹· 《极道千金》NETFLIX原创影集片尾曲', 82);
INSERT INTO `list` VALUES ('迷途 (相见版)', 61, '周华健', 83);
INSERT INTO `list` VALUES ('鲸落(Whale Fall)', 61, '林采欣', 84);
INSERT INTO `list` VALUES ('冰岛', 61, '周华健', 85);
INSERT INTO `list` VALUES ('Something About You', 61, '周兴哲', 86);
INSERT INTO `list` VALUES ('That\'s Why I Like You', 61, '周兴哲', 87);
INSERT INTO `list` VALUES ('Room for You', 61, '周兴哲', 88);
INSERT INTO `list` VALUES ('我陪你哭', 61, '陈威全', 89);
INSERT INTO `list` VALUES ('Rollercoasters', 61, '周兴哲', 90);
INSERT INTO `list` VALUES ('Me and You', 61, '周兴哲', 91);
INSERT INTO `list` VALUES ('U sTuPiD', 61, 'Karencici/ØZI', 92);
INSERT INTO `list` VALUES ('妈妈教会我', 61, '徐佳莹· from 王小苗诗集《邪恶的纯真》pp. 4-5.', 93);
INSERT INTO `list` VALUES ('CHEERIO', 61, '蔡佩轩', 94);
INSERT INTO `list` VALUES ('5 am', 61, '吴卓源', 95);
INSERT INTO `list` VALUES ('带我去找夜生活 - 健康版', 61, '告五人', 96);
INSERT INTO `list` VALUES ('欢欢喜喜过新年', 61, '董又霖/Casper卡斯柏/徐圣恩/谷蓝帝/丁飞俊/陆思恒', 97);
INSERT INTO `list` VALUES ('一首唱不红的歌', 61, 'AJ张杰', 98);
INSERT INTO `list` VALUES ('38F', 61, 'RPG', 99);
INSERT INTO `list` VALUES ('关键词', 60, '林俊杰', 5);
INSERT INTO `list` VALUES ('苏幕遮', 60, '张晓棠', 6);
INSERT INTO `list` VALUES ('Manta', 60, '刘柏辛Lexie', 4);
INSERT INTO `list` VALUES ('你是对的人', 60, '戚薇/李俊昊 (이준호)· 《爱情回来了》电视剧片尾曲|《天天炫舞》背景音乐', 8);
INSERT INTO `list` VALUES ('桥边姑娘', 60, '海伦', 7);
INSERT INTO `list` VALUES ('Dancing With Your Ghost', 60, '<NAME>', 9);
INSERT INTO `list` VALUES ('春娇与志明', 60, '街道办GDC/欧阳耀莹', 10);
INSERT INTO `list` VALUES ('十年', 60, '陈奕迅· 《明年今日》国语版|《隐婚男女》电影插曲|《摆渡人》电影插曲', 11);
INSERT INTO `list` VALUES ('晴天', 60, '周杰伦', 12);
INSERT INTO `list` VALUES ('无心斗艳', 60, '大布/苏泽龙', 13);
INSERT INTO `list` VALUES ('世界这么大还是遇见你', 60, '程响· 清新的小女孩(中文版)', 14);
INSERT INTO `list` VALUES ('光年之外', 60, 'G.E.M. 邓紫棋· 《太空旅客(Passengers)》电影中国区主题曲', 15);
INSERT INTO `list` VALUES ('七里香', 60, '周杰伦', 16);
INSERT INTO `list` VALUES ('无人之岛', 60, '任然', 17);
INSERT INTO `list` VALUES ('稻香', 60, '周杰伦', 18);
INSERT INTO `list` VALUES ('年少有为', 60, '李荣浩', 19);
INSERT INTO `list` VALUES ('冬眠', 60, '司南', 21);
INSERT INTO `list` VALUES ('莫问归期', 60, '蒋雪儿', 20);
INSERT INTO `list` VALUES ('只要平凡', 60, '张杰/张碧晨· 《我不是药神》电影主题曲', 22);
INSERT INTO `list` VALUES ('句号', 60, 'G.E.M. 邓紫棋', 23);
INSERT INTO `list` VALUES ('下山', 60, '要不要买菜', 24);
INSERT INTO `list` VALUES ('嚣张', 60, 'en', 25);
INSERT INTO `list` VALUES ('等你下课 (with 杨瑞代)', 60, '周杰伦', 26);
INSERT INTO `list` VALUES ('麻雀', 60, '李荣浩', 27);
INSERT INTO `list` VALUES ('体面', 60, '于文文· 《前任3:再见前任》电影插曲', 28);
INSERT INTO `list` VALUES ('像鱼', 60, '王贰浪', 29);
INSERT INTO `list` VALUES ('泡沫', 60, 'G.E.M. 邓紫棋', 30);
INSERT INTO `list` VALUES ('芒种', 60, '音阙诗听/赵方婧', 31);
INSERT INTO `list` VALUES ('你的答案', 60, '阿冗', 32);
INSERT INTO `list` VALUES ('红色高跟鞋', 60, '蔡健雅· 《爱情左右》电影主题曲', 33);
INSERT INTO `list` VALUES ('你的酒馆对我打了烊', 60, '陈雪凝', 34);
INSERT INTO `list` VALUES ('火红的萨日朗', 60, '要不要买菜', 35);
INSERT INTO `list` VALUES ('无赖', 60, '郑中基', 36);
INSERT INTO `list` VALUES ('50 Feet (Explicit)', 60, 'SoMo', 37);
INSERT INTO `list` VALUES ('我的名字', 60, '焦迈奇', 38);
INSERT INTO `list` VALUES ('火苗', 60, '苏晗', 39);
INSERT INTO `list` VALUES ('这一生关于你的风景', 60, '枯木逢春', 40);
INSERT INTO `list` VALUES ('那女孩对我说 (完整版)', 60, 'Uu', 41);
INSERT INTO `list` VALUES ('借 (Live)', 60, '毛不易', 42);
INSERT INTO `list` VALUES ('来自天堂的魔鬼', 60, 'G.E.M. 邓紫棋', 43);
INSERT INTO `list` VALUES ('遇见', 60, '孙燕姿· 《向左走,向右走》电影主题曲', 44);
INSERT INTO `list` VALUES ('一生与你擦肩而过', 60, '阿悠悠', 45);
INSERT INTO `list` VALUES ('想见你想见你想见你', 60, '八三夭乐团· 《想见你》电视剧片尾曲', 46);
INSERT INTO `list` VALUES ('无期', 60, '光头华夏', 47);
INSERT INTO `list` VALUES ('牧马城市', 60, '毛不易· 《老男孩》电视剧片尾曲', 48);
INSERT INTO `list` VALUES ('野狼disco', 60, '宝石Gem', 49);
INSERT INTO `list` VALUES ('画 (Live Piano Session Ⅱ)', 60, 'G.E.M. 邓紫棋', 50);
INSERT INTO `list` VALUES ('缘分一道桥', 60, '王力宏/谭维维· 《长城》电影片尾曲', 51);
INSERT INTO `list` VALUES ('修炼爱情', 60, '林俊杰', 52);
INSERT INTO `list` VALUES ('我走后', 60, '小咪', 53);
INSERT INTO `list` VALUES ('可不可以', 60, '张紫豪', 54);
INSERT INTO `list` VALUES ('贝贝', 60, '李荣浩', 55);
INSERT INTO `list` VALUES ('云烟成雨', 60, '房东的猫· 《我是江小白》动画片尾曲', 56);
INSERT INTO `list` VALUES ('绿色', 60, '陈雪凝', 57);
INSERT INTO `list` VALUES ('你是我唯一的执着', 60, '马健涛', 58);
INSERT INTO `list` VALUES ('溯 (Reverse) feat. 马吟吟', 60, 'CORSAK胡梦周/马吟吟', 59);
INSERT INTO `list` VALUES ('Faded', 60, '<NAME>/<NAME>', 60);
INSERT INTO `list` VALUES ('心如止水', 60, 'Ice Paper', 61);
INSERT INTO `list` VALUES ('单车', 60, '陈奕迅', 62);
INSERT INTO `list` VALUES ('夜空中最亮的星', 60, '逃跑计划', 63);
INSERT INTO `list` VALUES ('多想在平庸的生活拥抱你 (Live)', 60, '隔壁老樊', 64);
INSERT INTO `list` VALUES ('勇气', 60, '棉子', 65);
INSERT INTO `list` VALUES ('一个人挺好', 60, '孟颖', 66);
INSERT INTO `list` VALUES ('安和桥', 60, '宋冬野', 67);
INSERT INTO `list` VALUES ('一个人挺好', 60, '杨小壮', 68);
INSERT INTO `list` VALUES ('演员', 60, '薛之谦', 69);
INSERT INTO `list` VALUES ('侧脸', 60, '于果', 70);
INSERT INTO `list` VALUES ('爱情堡垒 (DJ版)', 60, '杨小壮', 71);
INSERT INTO `list` VALUES ('追光者', 60, '岑宁儿· 《夏至未至》电视剧插曲', 73);
INSERT INTO `list` VALUES ('清新的小女孩', 60, '<NAME>', 72);
INSERT INTO `list` VALUES ('你笑起来真好看', 60, '李昕融(ariel li)/樊桐舟/李凯稠', 74);
INSERT INTO `list` VALUES ('黎明前的黑暗 (Live)', 60, '张韶涵/王晰', 75);
INSERT INTO `list` VALUES ('可惜没如果', 60, '林俊杰· 《杜鹃之巢》韩剧中文主题曲|《对我而言,可爱的她》韩剧中文片尾曲', 76);
INSERT INTO `list` VALUES ('一曲相思', 60, '半阳', 77);
INSERT INTO `list` VALUES ('成都', 60, '赵雷', 78);
INSERT INTO `list` VALUES ('百花香', 60, '魏新雨', 79);
INSERT INTO `list` VALUES ('时间的过客', 60, '名决', 80);
INSERT INTO `list` VALUES ('太阳 (正式版)', 60, '曲肖冰', 81);
INSERT INTO `list` VALUES ('欧若拉', 60, '张韶涵', 82);
INSERT INTO `list` VALUES ('感谢你曾来过', 60, 'Ayo97/周思涵', 83);
INSERT INTO `list` VALUES ('琵琶行', 60, '奇然/沈谧仁', 84);
INSERT INTO `list` VALUES ('大眠 (Cover:王心凌)', 60, '王茗', 85);
INSERT INTO `list` VALUES ('你若三冬', 60, '阿悠悠', 86);
INSERT INTO `list` VALUES ('酒醉的蝴蝶', 60, '崔伟立', 87);
INSERT INTO `list` VALUES ('那些你很冒险的梦', 60, '林俊杰', 88);
INSERT INTO `list` VALUES ('海阔天空', 60, 'BEYOND', 89);
INSERT INTO `list` VALUES ('That Girl', 60, '<NAME>', 90);
INSERT INTO `list` VALUES ('红昭愿', 60, '音阙诗听', 91);
INSERT INTO `list` VALUES ('暗示分离', 60, 'en', 92);
INSERT INTO `list` VALUES ('山楂树の恋', 60, '程jiajia', 93);
INSERT INTO `list` VALUES ('空空如也', 60, '胡66', 94);
INSERT INTO `list` VALUES ('消愁 (Live)', 60, '毛不易', 95);
INSERT INTO `list` VALUES ('Hero', 60, 'Cash Cash/Christina Perri', 96);
INSERT INTO `list` VALUES ('再见只是陌生人', 60, '庄心妍', 97);
INSERT INTO `list` VALUES ('大雪', 60, '音阙诗听/王梓钰', 98);
INSERT INTO `list` VALUES ('许多年以后', 60, '赵鑫', 99);
INSERT INTO `list` VALUES ('都市丽人生存报告', 52, '大籽', 3);
INSERT INTO `list` VALUES ('风月梦', 52, '泥鳅Niko', 4);
INSERT INTO `list` VALUES ('早知道在家待这么久', 52, '张尕怂', 5);
INSERT INTO `list` VALUES ('晴空一尾鲤', 52, 'hanser', 7);
INSERT INTO `list` VALUES ('春山', 52, '子弥', 8);
INSERT INTO `list` VALUES ('美丽的遗憾', 52, '平凡的艾岩', 6);
INSERT INTO `list` VALUES ('2020~此间未来~', 52, '千月兔/封茗囧菌/等什么君/洛少爷/叶洛洛/双笙/Smile_小千/俺酱/奇然/笛呆子囚牛/妖蝠/洛劫/宗顺康/小连杀/执素兮/玄觞/只有影子/小时姑娘/叶里/千界SUMI/栩影酱/小吴太太/心然/醋醋/祈Inory/茶理理理子', 9);
INSERT INTO `list` VALUES ('渺渺', 52, '伦桑', 10);
INSERT INTO `list` VALUES ('山水墨', 52, '小曲儿', 11);
INSERT INTO `list` VALUES ('地铁上的陌生人', 52, '零6/陆怡雯', 12);
INSERT INTO `list` VALUES ('宅在家里的日子', 52, '马晓晨', 13);
INSERT INTO `list` VALUES ('逾期回忆(Feat.魏然)', 52, 'MOP17', 15);
INSERT INTO `list` VALUES ('波心月', 52, '萧忆情Alex', 14);
INSERT INTO `list` VALUES ('我想和你看夕阳', 52, '李甜', 16);
INSERT INTO `list` VALUES ('风起了', 52, '<NAME> (铁阳)', 17);
INSERT INTO `list` VALUES ('ᐇ', 52, 'W/', 18);
INSERT INTO `list` VALUES ('每一片落叶都知你名姓', 52, '西瓜JUN', 19);
INSERT INTO `list` VALUES ('穿行者', 52, '丁于/丫蛋蛋(马启涵)', 20);
INSERT INTO `list` VALUES ('其实', 52, '宋宇航', 21);
INSERT INTO `list` VALUES ('归山', 52, '福克斯', 22);
INSERT INTO `list` VALUES ('念故清欢', 52, '张十二', 23);
INSERT INTO `list` VALUES ('好久没见过', 52, '大喜', 24);
INSERT INTO `list` VALUES ('Careful', 52, '北一街', 25);
INSERT INTO `list` VALUES ('意料之外', 52, '赵晨唏', 26);
INSERT INTO `list` VALUES ('最甜情歌', 52, '高博深', 27);
INSERT INTO `list` VALUES ('等待天亮', 52, '钱润玉/FACEVÔID', 28);
INSERT INTO `list` VALUES ('小人物', 52, '赵雷', 29);
INSERT INTO `list` VALUES ('对悲观过于乐观', 52, '钟声', 30);
INSERT INTO `list` VALUES ('CHINA-新春', 52, '徐梦圆', 31);
INSERT INTO `list` VALUES ('水瓶先生', 52, '司徒赫伦', 32);
INSERT INTO `list` VALUES ('告白', 52, '一口甜', 33);
INSERT INTO `list` VALUES ('好好的', 52, '虎二', 34);
INSERT INTO `list` VALUES ('Planet', 52, '袁景翔', 35);
INSERT INTO `list` VALUES ('姐姐', 52, '贾盛强', 36);
INSERT INTO `list` VALUES ('热岛症', 52, '双笙', 37);
INSERT INTO `list` VALUES ('海棠 (纯音乐)', 52, 'Jin', 38);
INSERT INTO `list` VALUES ('凌晨两点的北京', 52, '谢宇伦', 39);
INSERT INTO `list` VALUES ('雨魅', 52, '孔柏森/杨胖雨', 40);
INSERT INTO `list` VALUES ('人间烟火', 52, '陈硕子', 41);
INSERT INTO `list` VALUES ('不是你的错', 52, '满舒克/董又霖', 42);
INSERT INTO `list` VALUES ('黑暗中闪烁', 52, '8点组乐团', 43);
INSERT INTO `list` VALUES ('其后', 52, '文兆杰', 44);
INSERT INTO `list` VALUES ('画中人', 52, '小魂', 45);
INSERT INTO `list` VALUES ('AM', 52, '李霄云', 46);
INSERT INTO `list` VALUES ('summer holiday', 52, 'Young T', 47);
INSERT INTO `list` VALUES ('当渣男你不配', 52, 'coco这个李文', 48);
INSERT INTO `list` VALUES ('等一树花开', 52, '简弘亦', 49);
INSERT INTO `list` VALUES ('我是你永远得不到的爸爸', 52, 'Q.luv/CLOUDWANG 王云/Ki.DAstronaut', 50);
INSERT INTO `list` VALUES ('LOU', 52, '尬倍儿 Gabier S.R.', 51);
INSERT INTO `list` VALUES ('温软宇宙', 52, 'Crazy Bucket/浮云心丶/Warma', 52);
INSERT INTO `list` VALUES ('胜利者', 52, '棉子', 53);
INSERT INTO `list` VALUES ('Million Swag', 52, '黄旭', 54);
INSERT INTO `list` VALUES ('青春记录号', 52, '街道办GDC/阿细', 55);
INSERT INTO `list` VALUES ('Turn me on', 52, '林嘉莹/玛尔斯Mars/霹雳杰瑞', 56);
INSERT INTO `list` VALUES ('炙热阳光 (S制造群星)', 52, '「S制造」群星/永彬Ryan.B/都智文/谢宇伦/崔天琪QiQi/麦吉_Maggie/洛松维/孟西/李艺玟Evan/丛琳潼elf/洛伊ChloeYin/江苹果', 57);
INSERT INTO `list` VALUES ('致陌生的你', 52, '河图', 58);
INSERT INTO `list` VALUES ('青玉案·元夕', 52, '赵景旭[Winky诗]', 59);
INSERT INTO `list` VALUES ('空城', 52, 'KIT翌', 60);
INSERT INTO `list` VALUES ('村花', 52, 'willen', 61);
INSERT INTO `list` VALUES ('他的夏', 52, 'LunaLiu刘不语', 62);
INSERT INTO `list` VALUES ('没有派对', 52, '方盒子', 63);
INSERT INTO `list` VALUES ('Catalyst', 52, 'Jiaye', 64);
INSERT INTO `list` VALUES ('镜子', 52, '直火帮XZT/直火帮StraightFireGang', 65);
INSERT INTO `list` VALUES ('Money', 52, '<NAME>', 66);
INSERT INTO `list` VALUES ('追梦', 52, 'LuckyMaxx', 68);
INSERT INTO `list` VALUES ('加油武汉 (Demo)', 52, '脑浊乐队', 67);
INSERT INTO `list` VALUES ('在我想你的时候', 52, 'Shang/<NAME>/superluckyqi', 69);
INSERT INTO `list` VALUES ('等风停靠', 52, '袁野夕', 70);
INSERT INTO `list` VALUES ('众志成城 抗击疫情 (Demo)', 52, '4U乐队', 71);
INSERT INTO `list` VALUES ('侠客行 (Demo)', 52, '肖恩<NAME>', 72);
INSERT INTO `list` VALUES ('锦书莫', 52, 'KBShinya', 73);
INSERT INTO `list` VALUES ('小院', 52, '暗杠', 74);
INSERT INTO `list` VALUES ('白色', 52, '牛佳钰', 75);
INSERT INTO `list` VALUES ('心头的刺', 52, '谣君', 76);
INSERT INTO `list` VALUES ('北半球', 52, '十豆彡', 77);
INSERT INTO `list` VALUES ('催婚', 52, '孙八一', 78);
INSERT INTO `list` VALUES ('千山写尽', 52, '潇梦临', 81);
INSERT INTO `list` VALUES ('旧友', 52, '银临', 79);
INSERT INTO `list` VALUES ('疫情结束后我们见面吧', 52, '<NAME>', 80);
INSERT INTO `list` VALUES ('也许这就是长大', 52, '爆音BOOM', 82);
INSERT INTO `list` VALUES ('勿忘我', 52, '星弟', 83);
INSERT INTO `list` VALUES ('Escape', 52, 'A7i', 84);
INSERT INTO `list` VALUES ('不可理喻', 52, 'StickyT', 86);
INSERT INTO `list` VALUES ('忽然有一天我变得特别喜欢你', 52, '乔万旭', 85);
INSERT INTO `list` VALUES ('武汉加油!中国加油!', 52, '侯兵一', 88);
INSERT INTO `list` VALUES ('守候', 52, '布衣乐队/RN', 87);
INSERT INTO `list` VALUES ('总是不完美', 52, 'SycoTyrant', 89);
INSERT INTO `list` VALUES ('武汉加油', 52, '廉山', 91);
INSERT INTO `list` VALUES ('战疫', 52, 'HKG-嘻哈幼稚园', 90);
INSERT INTO `list` VALUES ('武汉别哭', 52, 'AeyE', 92);
INSERT INTO `list` VALUES ('不安', 52, '张北', 93);
INSERT INTO `list` VALUES ('52HZ', 52, 'Ellie', 94);
INSERT INTO `list` VALUES ('宣战', 52, '觉醒乐队/吴可', 95);
INSERT INTO `list` VALUES ('老三', 52, '排骨教主', 96);
INSERT INTO `list` VALUES ('别怕,我也在这里', 52, '苟瀚中/李代沫', 97);
INSERT INTO `list` VALUES ('夜行动物', 52, 'KEYI杨豪', 98);
INSERT INTO `list` VALUES ('因为你在', 52, '达闻西乐队/福禄寿FloruitShow', 99);
INSERT INTO `list` VALUES ('春娇与志明', 26, '街道办GDC/欧阳耀莹', 5);
INSERT INTO `list` VALUES ('Dancing With Your Ghost', 26, 'Sasha Sloan', 6);
INSERT INTO `list` VALUES ('麻雀', 26, '李荣浩', 7);
INSERT INTO `list` VALUES ('嚣张', 26, 'en', 8);
INSERT INTO `list` VALUES ('关键词', 26, '林俊杰', 9);
INSERT INTO `list` VALUES ('红色高跟鞋', 26, '蔡健雅· 《爱情左右》电影主题曲', 10);
INSERT INTO `list` VALUES ('苏幕遮', 26, '张晓棠', 11);
INSERT INTO `list` VALUES ('想见你想见你想见你', 26, '八三夭乐团· 《想见你》电视剧片尾曲', 12);
INSERT INTO `list` VALUES ('晴天', 26, '周杰伦', 13);
INSERT INTO `list` VALUES ('句号', 26, 'G.E.M. 邓紫棋', 14);
INSERT INTO `list` VALUES ('百花香', 26, '魏新雨', 15);
INSERT INTO `list` VALUES ('无期', 26, '光头华夏', 16);
INSERT INTO `list` VALUES ('我们', 26, '陈奕迅· 《后来的我们》电影主题曲', 17);
INSERT INTO `list` VALUES ('处处吻', 26, '杨千嬅', 18);
INSERT INTO `list` VALUES ('火红的萨日朗', 26, '要不要买菜', 19);
INSERT INTO `list` VALUES ('无人之岛', 26, '任然', 20);
INSERT INTO `list` VALUES ('芒种', 26, '音阙诗听/赵方婧', 21);
INSERT INTO `list` VALUES ('贝贝', 26, '李荣浩', 22);
INSERT INTO `list` VALUES ('会好的', 26, '张艺兴', 23);
INSERT INTO `list` VALUES ('体面', 26, '于文文· 《前任3:再见前任》电影插曲', 24);
INSERT INTO `list` VALUES ('勇气', 26, '棉子', 25);
INSERT INTO `list` VALUES ('那女孩对我说 (完整版)', 26, 'Uu', 26);
INSERT INTO `list` VALUES ('Monsters', 26, 'Katie Sky', 27);
INSERT INTO `list` VALUES ('光年之外', 26, 'G.E.M. 邓紫棋· 《太空旅客(Passengers)》电影中国区主题曲', 28);
INSERT INTO `list` VALUES ('十年', 26, '陈奕迅· 《明年今日》国语版|《隐婚男女》电影插曲|《摆渡人》电影插曲', 29);
INSERT INTO `list` VALUES ('Manta', 26, '刘柏辛Lexie', 30);
INSERT INTO `list` VALUES ('七里香', 26, '周杰伦', 31);
INSERT INTO `list` VALUES ('让我欢喜让我忧', 26, '杨小壮/鹏鹏', 33);
INSERT INTO `list` VALUES ('年少有为', 26, '李荣浩', 32);
INSERT INTO `list` VALUES ('像鱼', 26, '王贰浪', 34);
INSERT INTO `list` VALUES ('多想在平庸的生活拥抱你 (Live)', 26, '隔壁老樊', 35);
INSERT INTO `list` VALUES ('牧马城市', 26, '毛不易· 《老男孩》电视剧片尾曲', 36);
INSERT INTO `list` VALUES ('时间的过客', 26, '名决', 37);
INSERT INTO `list` VALUES ('稻香', 26, '周杰伦', 38);
INSERT INTO `list` VALUES ('口是心非', 26, '杨小壮/鹏鹏', 39);
INSERT INTO `list` VALUES ('你的酒馆对我打了烊', 26, '陈雪凝', 40);
INSERT INTO `list` VALUES ('这一生关于你的风景', 26, '枯木逢春', 41);
INSERT INTO `list` VALUES ('野狼disco', 26, '宝石Gem', 42);
INSERT INTO `list` VALUES ('一个人挺好', 26, '孟颖', 43);
INSERT INTO `list` VALUES ('大眠 (Cover:王心凌)', 26, '王茗', 44);
INSERT INTO `list` VALUES ('给女孩(单曲)', 26, '李宇春', 45);
INSERT INTO `list` VALUES ('DJDJ给我一条K (抖音原版)', 26, '新旭', 49);
INSERT INTO `list` VALUES ('少年', 26, '梦然', 46);
INSERT INTO `list` VALUES ('泡沫', 26, 'G.E.M. 邓紫棋', 47);
INSERT INTO `list` VALUES ('退后', 26, '周杰伦', 48);
INSERT INTO `list` VALUES ('借 (Live)', 26, '毛不易', 50);
INSERT INTO `list` VALUES ('缘分一道桥', 26, '王力宏/谭维维· 《长城》电影片尾曲', 51);
INSERT INTO `list` VALUES ('我爱你', 26, '程jiajia', 52);
INSERT INTO `list` VALUES ('一生与你擦肩而过', 26, '阿悠悠', 54);
INSERT INTO `list` VALUES ('来自天堂的魔鬼', 26, 'G.E.M. 邓紫棋', 55);
INSERT INTO `list` VALUES ('说好不哭(with 五月天阿信)', 26, '周杰伦', 53);
INSERT INTO `list` VALUES ('告白气球', 26, '周杰伦', 56);
INSERT INTO `list` VALUES ('搁浅', 26, '周杰伦', 57);
INSERT INTO `list` VALUES ('我走后', 26, '小咪', 58);
INSERT INTO `list` VALUES ('一路向北', 26, '周杰伦· 《头文字D》电影插曲', 59);
INSERT INTO `list` VALUES ('黎明前的黑暗 (Live)', 26, '张韶涵/王晰', 60);
INSERT INTO `list` VALUES ('听妈妈的话', 26, '周杰伦', 61);
INSERT INTO `list` VALUES ('太阳 (正式版)', 26, '曲肖冰', 62);
INSERT INTO `list` VALUES ('绿色', 26, '陈雪凝', 63);
INSERT INTO `list` VALUES ('50 Feet (Explicit)', 26, 'SoMo', 65);
INSERT INTO `list` VALUES ('溯 (Reverse) feat. 马吟吟', 26, 'CORSAK胡梦周/马吟吟', 64);
INSERT INTO `list` VALUES ('你若三冬', 26, '阿悠悠', 66);
INSERT INTO `list` VALUES ('莫问归期', 26, '蒋雪儿', 67);
INSERT INTO `list` VALUES ('修炼爱情', 26, '林俊杰', 68);
INSERT INTO `list` VALUES ('云烟成雨', 26, '房东的猫· 《我是江小白》动画片尾曲', 71);
INSERT INTO `list` VALUES ('可不可以', 26, '张紫豪', 69);
INSERT INTO `list` VALUES ('等你下课 (with 杨瑞代)', 26, '周杰伦', 70);
INSERT INTO `list` VALUES ('心如止水', 26, 'Ice Paper', 72);
INSERT INTO `list` VALUES ('安和桥', 26, '宋冬野', 73);
INSERT INTO `list` VALUES ('画 (Live Piano Session Ⅱ)', 26, 'G.E.M. 邓紫棋', 74);
INSERT INTO `list` VALUES ('遇见', 26, '孙燕姿· 《向左走,向右走》电影主题曲', 75);
INSERT INTO `list` VALUES ('一个人挺好', 26, '杨小壮', 76);
INSERT INTO `list` VALUES ('Faded', 26, '<NAME>/<NAME>', 77);
INSERT INTO `list` VALUES ('清新的小女孩', 26, '<NAME>', 78);
INSERT INTO `list` VALUES ('我的名字', 26, '焦迈奇', 79);
INSERT INTO `list` VALUES ('最美的伤口', 26, 'DJ小鱼儿', 80);
INSERT INTO `list` VALUES ('Last Dance', 26, '伍佰/China Blue', 82);
INSERT INTO `list` VALUES ('侧脸', 26, '于果', 81);
INSERT INTO `list` VALUES ('只要平凡', 26, '张杰/张碧晨· 《我不是药神》电影主题曲', 83);
INSERT INTO `list` VALUES ('你笑起来真好看', 26, '李昕融(ariel li)/樊桐舟/李凯稠', 84);
INSERT INTO `list` VALUES ('给我一首歌的时间', 26, '周杰伦', 85);
INSERT INTO `list` VALUES ('酒醉的蝴蝶', 26, '崔伟立', 86);
INSERT INTO `list` VALUES ('可惜没如果', 26, '林俊杰· 《杜鹃之巢》韩剧中文主题曲|《对我而言,可爱的她》韩剧中文片尾曲', 87);
INSERT INTO `list` VALUES ('追光者', 26, '岑宁儿· 《夏至未至》电视剧插曲', 88);
INSERT INTO `list` VALUES ('夜空中最亮的星', 26, '逃跑计划', 89);
INSERT INTO `list` VALUES ('蒲公英的约定', 26, '周杰伦', 90);
INSERT INTO `list` VALUES ('演员', 26, '薛之谦', 91);
INSERT INTO `list` VALUES ('一曲相思', 26, '半阳', 92);
INSERT INTO `list` VALUES ('爱的飞行日记', 26, '周杰伦/杨瑞代', 93);
INSERT INTO `list` VALUES ('欧若拉', 26, '张韶涵', 95);
INSERT INTO `list` VALUES ('海阔天空', 26, 'BEYOND', 94);
INSERT INTO `list` VALUES ('大鱼', 26, '周深· 《大鱼海棠》动画电影印象曲', 96);
INSERT INTO `list` VALUES ('夜曲', 26, '周杰伦', 97);
INSERT INTO `list` VALUES ('山楂树の恋', 26, '程jiajia', 98);
INSERT INTO `list` VALUES ('青花瓷', 26, '周杰伦', 99);
INSERT INTO `list` VALUES ('시작 (开始)', 16, 'Gaho (가호)· 《梨泰院Class》韩剧插曲', 3);
INSERT INTO `list` VALUES ('TING TING TING with Oliver Heldens', 16, 'ITZY (있지)/Oliver Heldens', 4);
INSERT INTO `list` VALUES ('어떤 말도 (No Words)', 16, 'Crush (크러쉬)· 《梨泰院Class》韩剧插曲', 5);
INSERT INTO `list` VALUES ('꿈 (Boom) (梦)', 16, 'NCT 127 (엔씨티 127)', 6);
INSERT INTO `list` VALUES ('Sit Down!', 16, 'NCT 127 (엔씨티 127)', 7);
INSERT INTO `list` VALUES ('THAT’S A NO NO', 16, 'ITZY (있지)', 8);
INSERT INTO `list` VALUES ('NOBODY LIKE YOU', 16, 'ITZY (있지)', 9);
INSERT INTO `list` VALUES ('메아리 (Love Me Now) (回响)', 16, 'NCT 127 (엔씨티 127)', 11);
INSERT INTO `list` VALUES ('낮잠 (Pandora\'s Box) (午睡)', 16, 'NCT 127 (엔씨티 127)', 10);
INSERT INTO `list` VALUES ('YOU MAKE ME', 16, 'ITZY (있지)', 13);
INSERT INTO `list` VALUES ('Love The Moon (달을 사랑해)', 16, 'VIINI (권현빈)/李秀贤 (이수현)/BLOO (블루)', 12);
INSERT INTO `list` VALUES ('백야 (White Night) (白夜)', 16, 'NCT 127 (엔씨티 127)', 14);
INSERT INTO `list` VALUES ('뿔 (MAD DOG) (角)', 16, 'NCT 127 (엔씨티 127)', 15);
INSERT INTO `list` VALUES ('우산 (Love Song) (雨伞)', 16, 'NCT 127 (엔씨티 127)', 16);
INSERT INTO `list` VALUES ('24HRS', 16, 'ITZY (있지)', 17);
INSERT INTO `list` VALUES ('Day Dream (白日夢)', 16, 'NCT 127 (엔씨티 127)', 18);
INSERT INTO `list` VALUES ('FIESTA', 16, 'IZ*ONE (아이즈원)', 19);
INSERT INTO `list` VALUES ('Not Alone', 16, 'NCT 127 (엔씨티 127)', 20);
INSERT INTO `list` VALUES ('I DON’T WANNA DANCE', 16, 'ITZY (있지)', 21);
INSERT INTO `list` VALUES ('돌덩이 (Diamond)', 16, '河铉雨 (하현우)· 《梨泰院Class》韩剧插曲', 23);
INSERT INTO `list` VALUES ('Interlude: Neo Zone', 16, 'NCT 127 (엔씨티 127)', 22);
INSERT INTO `list` VALUES ('Dreams Come True', 16, 'NCT 127 (엔씨티 127)', 24);
INSERT INTO `list` VALUES ('솔직히 지친다 (Everybody Has)', 16, '金请夏 (김청하)', 25);
INSERT INTO `list` VALUES ('Psycho', 16, 'Red Velvet (레드벨벳)', 26);
INSERT INTO `list` VALUES ('My Bad (KSHMR Edit)', 16, 'SHAUN (숀)/어드밴스드 (Advanced)/Julie Bergan', 27);
INSERT INTO `list` VALUES ('Dreams Come True (Feat. Golden, Jay Park)', 16, 'CLUB 33 (KIRIN & SUMIN)/Golden/朴宰范 (박재범)', 28);
INSERT INTO `list` VALUES ('With Us', 16, 'VERIVERY (베리베리)· 《梨泰院Class》韩剧插曲', 29);
INSERT INTO `list` VALUES ('너를 사랑하고 있어 (MY LOVE)', 16, '伯贤 (백현)· 《浪漫医生金师傅2》韩剧插曲', 30);
INSERT INTO `list` VALUES ('그때 그 아인 (Someday, The Boy)', 16, '金弼 (김필)· 《梨泰院Class》韩剧插曲', 31);
INSERT INTO `list` VALUES ('너에게 난 나에게 넌 (You are to me I am to you)', 16, '郑恩地 (정은지)', 32);
INSERT INTO `list` VALUES ('RED MOON', 16, 'KARD (카드)', 35);
INSERT INTO `list` VALUES ('Sunrise Yellow', 16, 'FTISLAND (에프티 아일랜드)', 33);
INSERT INTO `list` VALUES ('Go away go away', 16, '灿烈 (찬열)/PUNCH (펀치)· 《浪漫医生金师傅2》韩剧插曲', 34);
INSERT INTO `list` VALUES ('AYAYAYA', 16, 'IZ*ONE (아이즈원)', 36);
INSERT INTO `list` VALUES ('달이 태양을 가릴 때 (Eclipse)', 16, '玟星 (문별)', 37);
INSERT INTO `list` VALUES ('Still Fighting It', 16, '이찬솔 (Lee Chan Sol)· 《梨泰院Class》韩剧插曲', 38);
INSERT INTO `list` VALUES ('다시 난, 여기 (Here I Am Again)', 16, '白艺潾 (백예린)· 《爱的迫降》韩剧插曲', 39);
INSERT INTO `list` VALUES ('Defence', 16, '박성일 (朴成一)/FRAKTAL· 《梨泰院Class》韩剧插曲', 40);
INSERT INTO `list` VALUES ('EYES', 16, 'IZ*ONE (아이즈원)', 41);
INSERT INTO `list` VALUES ('우린 친구뿐일까 (Maybe)', 16, 'Sondia (손디아)· 《梨泰院Class》韩剧插曲', 43);
INSERT INTO `list` VALUES ('SPACESHIP', 16, 'IZ*ONE (아이즈원)', 42);
INSERT INTO `list` VALUES ('우연인 듯 운명 (But it\'s Destiny)', 16, '10cm (십센치)· 《爱的迫降》韩剧插曲', 44);
INSERT INTO `list` VALUES ('바빠서 (Feat. 헤이즈) (Cold)', 16, '개코/Heize (헤이즈)', 45);
INSERT INTO `list` VALUES ('HARMONY', 16, '东海 (동해)/BewhY (비와이)', 47);
INSERT INTO `list` VALUES ('DREAMLIKE', 16, 'IZ*ONE (아이즈원)', 46);
INSERT INTO `list` VALUES ('HOME', 16, 'Yezi (예지)', 48);
INSERT INTO `list` VALUES ('둘만의 세상으로 가 (Let Us Go)', 16, 'Crush (크러쉬)· 《爱的迫降》韩剧插曲', 49);
INSERT INTO `list` VALUES ('노을 (Sunset)', 16, 'Davichi (다비치)· 《爱的迫降》韩剧插曲', 50);
INSERT INTO `list` VALUES ('내 마음의 사진 (Photo of My Mind)', 16, '宋佳人 (송가인)', 51);
INSERT INTO `list` VALUES ('Digital Lover', 16, 'Crush (크러쉬)', 53);
INSERT INTO `list` VALUES ('시그리스빌 (사랑의 불시착 Title Full Ver.)', 16, '金京熙 (김경희)· 《爱的迫降》韩剧插曲', 52);
INSERT INTO `list` VALUES ('You Make Me Back', 16, '김우성 (金佑星)· 《 梨泰院Class》韩剧插曲', 54);
INSERT INTO `list` VALUES ('Maybe', 16, 'Sondia (손디아)· 《梨泰院Class》韩剧插曲', 55);
INSERT INTO `list` VALUES ('Good Guy (Japanese ver.)', 16, 'SF9 (에스에프나인)', 57);
INSERT INTO `list` VALUES ('She Knows Everything', 16, '郑容和 (정용화)', 56);
INSERT INTO `list` VALUES ('별처럼 빛나는 시간 (Time, like a shining star)', 16, '朴智敏 (박지민)· 《你好 再见,妈妈!》韩剧插曲', 58);
INSERT INTO `list` VALUES ('WELCOME TO THE Y\'S CITY', 16, '郑容和 (정용화)', 60);
INSERT INTO `list` VALUES ('낯선날 (Weird Day)', 16, '玟星 (문별)/PUNCH (펀치)', 59);
INSERT INTO `list` VALUES ('버스 안에서 (On the bus)', 16, '장준/TAG/Kei (케이)', 61);
INSERT INTO `list` VALUES ('ONE&ONLY', 16, 'ASTRO (아스트로)', 62);
INSERT INTO `list` VALUES ('SEDANSOGU (세상에 단 하나뿐인 소중한 그대)', 16, 'SUHO (수호)', 63);
INSERT INTO `list` VALUES ('PAY DAY', 16, 'CHANGMO (창모)/ASH ISLAND/郑基高 (정기고)', 64);
INSERT INTO `list` VALUES ('SO CURIOUS', 16, 'IZ*ONE (아이즈원)', 65);
INSERT INTO `list` VALUES ('In & Out', 16, 'Red Velvet (레드벨벳)', 66);
INSERT INTO `list` VALUES ('그리움의 언덕 (The Hill of Yearning)', 16, 'April 2nd (에이프릴 세컨드)', 67);
INSERT INTO `list` VALUES ('우연인 듯 운명 (But it\'s Destiny)', 16, '10cm (십센치)· 《爱的迫降》韩剧插曲', 68);
INSERT INTO `list` VALUES ('자꾸 더 보고싶은 사람 (I Miss You)', 16, 'MAMAMOO (마마무)', 69);
INSERT INTO `list` VALUES ('HIP (Japanese ver.)', 16, 'MAMAMOO (마마무)', 70);
INSERT INTO `list` VALUES ('우리의 밤', 16, 'Sondia (손디아)', 71);
INSERT INTO `list` VALUES ('나의 모든 날 (All of My Days)', 16, '金世正 (세정)', 73);
INSERT INTO `list` VALUES ('HERE GOES NOTHING', 16, 'DPR LIVE (라이브)', 72);
INSERT INTO `list` VALUES ('언젠가 우리의 밤도 지나가겠죠 (SOMEDAY)', 16, 'IZ*ONE (아이즈원)', 75);
INSERT INTO `list` VALUES ('Dejavu (Prod. iDeal)', 16, 'BLNK/Simon Dominic (사이먼 도미닉)', 74);
INSERT INTO `list` VALUES ('노을 (Sunset)', 16, 'Davichi (다비치)· 《爱的迫降》韩剧插曲', 76);
INSERT INTO `list` VALUES ('GO BABY', 16, 'KARD (카드)', 77);
INSERT INTO `list` VALUES ('mirror', 16, '玟星 (문별)', 78);
INSERT INTO `list` VALUES ('다시 난, 여기 (Here I am Again)', 16, '白艺潾 (백예린)· 《爱的迫降》韩剧插曲', 79);
INSERT INTO `list` VALUES ('인간중독 (Feat. 유라 (youra)) (Prod. TOIL) (Human Addict)', 16, 'Leellamarz (릴러말즈)/TOIL/Youra (유라)', 80);
INSERT INTO `list` VALUES ('Nobody Knows', 16, '金润雅 (김윤아)· 《谤法》韩剧插曲', 81);
INSERT INTO `list` VALUES ('너의 하루는 좀 어때 (YOUR DAY)', 16, 'Gummy (거미)· 《浪漫医生金师傅2》韩剧插曲', 82);
INSERT INTO `list` VALUES ('우연이 아니야 (DESTINY)', 16, 'IZ*ONE (아이즈원)', 83);
INSERT INTO `list` VALUES ('ENEMY', 16, 'KARD (카드)', 85);
INSERT INTO `list` VALUES ('ILJIDO', 16, '玟星 (문별)', 84);
INSERT INTO `list` VALUES ('SWING', 16, 'TWICE (트와이스)', 87);
INSERT INTO `list` VALUES ('어떤 날엔 (Someday)', 16, '金在奂 (김재환)· 《爱的迫降》韩剧插曲', 86);
INSERT INTO `list` VALUES ('YOU & I', 16, 'IZ*ONE (아이즈원)', 88);
INSERT INTO `list` VALUES ('OPEN YOUR EYES', 16, 'IZ*ONE (아이즈원)', 89);
INSERT INTO `list` VALUES ('LEGACY', 16, 'DPR LIVE (라이브)', 92);
INSERT INTO `list` VALUES ('시행착오 (Trial and Error)', 16, 'DAVII (다비)/Babylon (베이빌론)/敏雅 (민아)', 90);
INSERT INTO `list` VALUES ('I Need You', 16, 'OVAN (오반)', 91);
INSERT INTO `list` VALUES ('PINK BLUSHER', 16, 'IZ*ONE (아이즈원)', 93);
INSERT INTO `list` VALUES ('나의 그대 (My Love)', 16, '金请夏 (김청하)', 94);
INSERT INTO `list` VALUES ('Summer Night In Heaven', 16, '郑容和 (정용화)', 95);
INSERT INTO `list` VALUES ('TO WHOEVER', 16, 'DPR LIVE (라이브)', 97);
INSERT INTO `list` VALUES ('형을 위한 노래 (Feat. 정혁) (The Song for My Brother)', 16, '南惠胜 (남혜승|Nam Hye Seung)/정혁/高恩静 (고은정)', 98);
INSERT INTO `list` VALUES ('어색한 사이', 16, '脸红的思春期 (볼빨간사춘기)/Vanilla Acoustic (바닐라 어쿠스틱)/Sweden Laundry (스웨덴세탁소)/Twenty Years (스무살)/Letter flow (레터 플로우)/金智秀 (김지수)/WH3N (웬)/Boramiyu (보라미유)/최유리', 96);
INSERT INTO `list` VALUES ('Asteroid', 16, 'IMLAY/刘扬扬', 99);
SET FOREIGN_KEY_CHECKS = 1;
| 2dd38df98abe0f43a9a346676b8968911f62723a | [
"SQL"
] | 5 | SQL | OneKissAndOneShot/chatBiao | 269573b073bd3dc4e14b54a22c588d63297ed760 | 74d564137c6ffdb4d7c8ec367f74e0cb7f15d7f2 |
refs/heads/master | <repo_name>emily-wu/7-wonders-duel-score-sheet<file_sep>/java/com/firebaseapp/emwu/duelpointtracker/MainActivity.java
package com.firebaseapp.emwu.duelpointtracker;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
int myPoints = 0;
int yourPoints = 0;
public void calculate(View view) {
displayMyTotal();
displayYourTotal();
Toast.makeText(getBaseContext(), toastMessage() , Toast.LENGTH_SHORT ).show();
}
public void reset(View view) {
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private String getMyName() {
TextView myName = (TextView) findViewById(R.id.myName);
String mName = myName.getText().toString();
return mName;
}
private String getYourName() {
TextView yourName = (TextView) findViewById(R.id.yourName);
String yName = yourName.getText().toString();
return yName;
}
private void displayMyTotal() {
TextView myTotal = (TextView) findViewById(R.id.myTotal);
myTotal.setText(String.valueOf(addMyPoints()));
}
public void displayYourTotal() {
TextView yourTotal = (TextView) findViewById(R.id.yourTotal);
yourTotal.setText(String.valueOf(addYourPoints()));
}
public int addMyPoints() {
myPoints = parseInput(R.id.myBlues) + parseInput(R.id.myGreens) + parseInput(R.id.myYellows) + parseInput(R.id.myPurples) + parseInput(R.id.myWonders) + parseInput(R.id.mySciences) + parseInput(R.id.myCoins) + parseInput(R.id.myArmies);
return myPoints;
}
public int addYourPoints() {
yourPoints = parseInput(R.id.yourBlues) + parseInput(R.id.yourGreens) + parseInput(R.id.yourYellows) + parseInput(R.id.yourPurples) + parseInput(R.id.yourWonders) + parseInput(R.id.yourSciences) + parseInput(R.id.yourCoins) + parseInput(R.id.yourArmies);
return yourPoints;
}
public int parseInput(Integer integer) {
TextView myView = (TextView) findViewById(integer);
String myBluesString = myView.getText().toString();
if (myBluesString.matches("")){
myBluesString = "0";
}
int myInt = Integer.parseInt(myBluesString);
return myInt;
}
private String toastMessage() {
String message = "";
if (myPoints == yourPoints) {
message = "It's a tie! ";
}else if (myPoints > yourPoints) {
message = getMyName() + " Wins!";
}else {
message = getYourName() + " Wins!";
}
return message;
}
}
| 146bb21ebfc692c9f0ed98d5a69c39a2ec800b39 | [
"Java"
] | 1 | Java | emily-wu/7-wonders-duel-score-sheet | 64ad1bdd0e8ae5606fe1ff880137ea59706cb08c | c524629f8faf390860d8268e5e969fab126574dc |
refs/heads/master | <file_sep>'use strict'
const test = require('japa')
const FcmMessage = require('../../src/FcmMessage')
test.group('FcmMessage', () => {
test('should return snake case json data from FcmMessage instance', assert => {
const message = new FcmMessage({
collapseKey: 'demo',
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 3,
restrictedPackageName: 'somePackageName',
dryRun: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.'
}
})
assert.deepEqual(message.toJSON(), {
collapse_key: 'demo',
priority: 'high',
content_available: true,
delay_while_idle: true,
time_to_live: 3,
restricted_package_name: 'somePackageName',
dry_run: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.'
}
})
})
test('assign message using fluent api', assert => {
const message = new FcmMessage()
message
.setCollapseKey('demo')
.setPriority('high')
.setContentAvailable(true)
.setDelayWhileIdle(true)
.setTimeToLive(3)
.setRestrictedPackageName('somePackageName')
.setDryRun(true)
.setData({
key1: 'message1',
key2: 'message2'
})
.setTitle('Hello, World')
.setIcon('ic_launcher')
.setBody('This is a notification that will be displayed if your app is in the background.')
.setSound('test_sound')
.setBadge('test_badge')
.setTag('test_tag')
.setColor('test_color')
.setClickAction('test_click_action')
.setBodyLocKey('test_body_loc_key')
.setBodyLocArgs(['body0', 'body1'])
.setTitleLocKey('test_title_loc_key')
.setTitleLocArgs(['title0', 'title1'])
assert.deepEqual(message.toJSON(), {
collapse_key: 'demo',
priority: 'high',
content_available: true,
delay_while_idle: true,
time_to_live: 3,
restricted_package_name: 'somePackageName',
dry_run: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.',
sound: 'test_sound',
badge: 'test_badge',
tag: 'test_tag',
color: 'test_color',
click_action: 'test_click_action',
body_loc_key: 'test_body_loc_key',
body_loc_args: '["body0","body1"]',
title_loc_key: 'test_title_loc_key',
title_loc_args: '["title0","title1"]'
}
})
})
test('assign message using setters', assert => {
const message = new FcmMessage()
message.collapseKey = 'demo'
message.priority = 'high'
message.contentAvailable = true
message.delayWhileIdle = true
message.timeToLive = 3
message.restrictedPackageName = 'somePackageName'
message.dryRun = true
message.data = {
key1: 'message1',
key2: 'message2'
}
message.title = 'Hello, World'
message.icon = 'ic_launcher'
message.body = 'This is a notification that will be displayed if your app is in the background.'
message.sound = 'test_sound'
message.badge = 'test_badge'
message.tag = 'test_tag'
message.color = 'test_color'
message.clickAction = 'test_click_action'
message.bodyLocKey = 'test_body_loc_key'
message.bodyLocArgs = ['body0', 'body1']
message.titleLocKey = 'test_title_loc_key'
message.titleLocArgs = ['title0', 'title1']
assert.equal(message.collapseKey, 'demo')
assert.equal(message.priority, 'high')
assert.equal(message.contentAvailable, true)
assert.equal(message.delayWhileIdle, true)
assert.equal(message.timeToLive, 3)
assert.equal(message.restrictedPackageName, 'somePackageName')
assert.equal(message.dryRun, true)
assert.deepEqual(message.data, {
key1: 'message1',
key2: 'message2'
})
assert.equal(message.title, 'Hello, World')
assert.equal(message.icon, 'ic_launcher')
assert.equal(message.body, 'This is a notification that will be displayed if your app is in the background.')
assert.equal(message.sound, 'test_sound')
assert.equal(message.badge, 'test_badge')
assert.equal(message.tag, 'test_tag')
assert.equal(message.color, 'test_color')
assert.equal(message.clickAction, 'test_click_action')
assert.equal(message.bodyLocKey, 'test_body_loc_key')
assert.equal(message.bodyLocArgs, '["body0","body1"]')
assert.equal(message.titleLocKey, 'test_title_loc_key')
assert.equal(message.titleLocArgs, '["title0","title1"]')
assert.deepEqual(message.toJSON(), {
collapse_key: 'demo',
priority: 'high',
content_available: true,
delay_while_idle: true,
time_to_live: 3,
restricted_package_name: 'somePackageName',
dry_run: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.',
sound: 'test_sound',
badge: 'test_badge',
tag: 'test_tag',
color: 'test_color',
click_action: 'test_click_action',
body_loc_key: 'test_body_loc_key',
body_loc_args: '["body0","body1"]',
title_loc_key: 'test_title_loc_key',
title_loc_args: '["title0","title1"]'
}
})
})
})
<file_sep>'use strict'
const path = require('path')
const { Config } = require('@adonisjs/sink')
const { ioc, registrar } = require('@adonisjs/fold')
const run = async () => {
ioc.singleton('Adonis/Src/Config', () => {
const config = new Config()
config.set('services.fcm.apiKey', process.env.FCM_API_KEY)
return config
})
ioc.alias('Adonis/Src/Config', 'Config')
ioc.singleton('Adonis/Src/Event', () => {
const Event = require('@adonisjs/framework/src/Event')
return new Event(ioc.use('Config'))
})
ioc.alias('Adonis/Src/Event', 'Event')
await registrar
.providers([
'adonis-notifications/providers/NotificationsProvider',
path.join(__dirname, '../providers/FcmNotificationChannelProvider')
])
.registerAndBoot()
class User {
routeNotificationFor () {
return 'routeNotificationForFcm'
}
routeNotificationForFcm () {
return [process.env.DEVICE_TOKEN]
}
}
const FcmMessage = ioc.use('FcmMessage')
class PushTestNotification {
constructor (animal) {
this.animal = animal
}
static get type () {
return 'pushtest'
}
via () {
return ['fcm']
}
toFcm () {
const message = new FcmMessage()
switch (this.animal) {
case 'cat':
message.addNotification('title', 'Cat')
message.addNotification('body', 'Meow!')
message.addNotification('icon', 'cat_black')
message.addNotification('color', '#ffab00')
message.addNotification('sound', 'default')
message.addData('animal', 'cat')
break
case 'cow':
message.addNotification('title', 'Cow')
message.addNotification('body', 'Moo!')
message.addNotification('icon', 'cow_black')
message.addNotification('color', '#aeaeaf')
message.addNotification('sound', 'default')
message.addData('animal', 'cow')
break
case 'dog':
message.addNotification('title', 'Dog')
message.addNotification('body', 'Woof!')
message.addNotification('icon', 'dog_black')
message.addNotification('color', '#b19267')
message.addNotification('sound', 'default')
message.addData('animal', 'dog')
break
case 'duck':
message.addNotification('title', 'Duck')
message.addNotification('body', 'Quack!')
message.addNotification('icon', 'duck_black')
message.addNotification('color', '#bd7f00')
message.addNotification('sound', 'default')
message.addData('animal', 'duck')
break
case 'pig':
message.addNotification('title', 'Pig')
message.addNotification('body', 'Oink!')
message.addNotification('icon', 'pig_black')
message.addNotification('color', '#d37b93')
message.addNotification('sound', 'default')
message.addData('animal', 'pig')
break
default:
message.addNotification('title', 'Animal')
message.addNotification('body', 'A wild animal has appeared!')
message.addNotification('sound', 'default')
break
}
return message
}
}
const Notifications = ioc.use('Notifications')
return Notifications.send(new User(), new PushTestNotification())
}
run()
.then(response => {
console.log('Response', response)
})
.catch(console.error)
<file_sep># Adonis Firebase Notification Channel
[](https://travis-ci.org/enniel/adonis-fcm-notification-channel)
[](https://coveralls.io/github/enniel/adonis-fcm-notification-channel?branch=master)
Firebase Notification Channel for [adonis-notifications](https://github.com/enniel/adonis-notifications).
## Installation
1. Add package:
```bash
$ npm i adonis-fcm-notification-channel --save
```
or
```bash
$ yarn add adonis-fcm-notification-channel
```
2. Register providers inside the your `start/app.js` file.
```js
const providers = [
...
'adonis-fcm-notification-channel/providers/FcmNotificationChannelProvider',
...
]
```
3. Add configuration to `config/services.js` file.
```js
...
fcm: {
apiKey: <YOUR API KEY>,
// optional
requestOptions: {
proxy: 'http://127.0.0.1:8888',
timeout: 5000
}
}
...
```
See [node-gcm](https://github.com/ToothlessGear/node-gcm) for more information.
## Usage example
```js
// app/Model/User.js
'use strict'
const Lucid = use('Lucid')
class User extends Lucid {
static get traits () {
return [
'@provider:Morphable',
'@provider:HasDatabaseNotifications',
'@provider:Notifiable'
]
}
// array, promise or generator
routeNotificationForFcm () {
return ['token1', 'token2', ... ]
}
}
module.exports = User
```
```js
// app/Notifications/FcmNotification.js
'use strict'
const FcmMessage = use('FcmMessage')
class MyNotification {
via () {
return ['fcm']
}
toFcm () {
// from object
const message = new FcmMessage({
collapse_key: 'demo',
priority: 'high',
content_available: true,
delay_while_idle: true,
time_to_live: 3,
restricted_package_name: 'somePackageName',
dry_run: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.',
sound: 'test_sound',
badge: 'test_badge',
tag: 'test_tag',
color: 'test_color',
click_action: 'test_click_action',
body_loc_key: 'test_body_loc_key',
body_loc_args: '["body0","body1"]',
title_loc_key: 'test_title_loc_key',
title_loc_args: '["title0","title1"]'
}
})
// using fluent api
message
.setCollapseKey('demo')
.setPriority('high')
.setContentAvailable(true)
.setDelayWhileIdle(true)
.setTimeToLive(3)
.setRestrictedPackageName('somePackageName')
.setDryRun(true)
.setData({
key1: 'message1',
key2: 'message2'
})
.setTitle('Hello, World')
.setIcon('ic_launcher')
.setBody('This is a notification that will be displayed if your app is in the background.')
.setSound('test_sound')
.setBadge('test_badge')
.setTag('test_tag')
.setColor('test_color')
.setClickAction('test_click_action')
.setBodyLocKey('test_body_loc_key')
.setBodyLocArgs(['body0', 'body1'])
.setTitleLocKey('test_title_loc_key')
.setTitleLocArgs(['title0', 'title1'])
// using setters
message.collapseKey = 'demo'
message.priority = 'high'
message.contentAvailable = true
message.delayWhileIdle = true
message.timeToLive = 3
message.restrictedPackageName = 'somePackageName'
message.dryRun = true
message.data = {
key1: 'message1',
key2: 'message2'
}
message.title = 'Hello, World'
message.icon = 'ic_launcher'
message.body = 'This is a notification that will be displayed if your app is in the background.'
message.sound = 'test_sound'
message.badge = 'test_badge'
message.tag = 'test_tag'
message.color = 'test_color'
message.clickAction = 'test_click_action'
message.bodyLocKey = 'test_body_loc_key'
message.bodyLocArgs = ['body0', 'body1']
message.titleLocKey = 'test_title_loc_key'
message.titleLocArgs = ['title0', 'title1']
// you can set up configuration for current notification
// using configure method
message.configure({
apiKey: '<YOUR API KEY>',
// optional
requestOptions: {
proxy: 'http://127.0.0.1:8888',
timeout: 5000
}
})
// or setters
message
.setApiKey('<YOUR API KEY>')
.setRequestOptions({
proxy: 'http://127.0.0.1:8888',
timeout: 5000
})
message.apiKey = '<YOUR API KEY>'
message.requestOptions = {
proxy: 'http://127.0.0.1:8888',
timeout: 5000
}
return message
}
}
module.exports = MyNotification
```
or
```js
// app/Notifications/FcmNotification.js
'use strict'
class MyNotification {
via () {
return ['fcm']
}
toJSON () {
return {
collapse_key: 'demo',
priority: 'high',
content_available: true,
delay_while_idle: true,
time_to_live: 3,
restricted_package_name: 'somePackageName',
dry_run: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.',
sound: 'test_sound',
badge: 'test_badge',
tag: 'test_tag',
color: 'test_color',
click_action: 'test_click_action',
body_loc_key: 'test_body_loc_key',
body_loc_args: '["body0","body1"]',
title_loc_key: 'test_title_loc_key',
title_loc_args: '["title0","title1"]'
}
}
}
}
module.exports = MyNotification
```
## Credits
- [<NAME>](https://github.com/enniel)
## Support
Having trouble? [Open an issue](https://github.com/enniel/adonis-fcm-notification-channel/issues/new)!
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
<file_sep>'use strict'
const Message = require('node-gcm').Message
class FcmMessage {
constructor (data) {
this.message = new Message(data)
return new Proxy(this, {
get (target, name) {
if (typeof target[name] !== 'undefined') {
return target[name]
}
return target.message[name]
}
})
}
setApiKey (apiKey) {
this._apiKey = apiKey
return this
}
set apiKey (apiKey) {
this.setApiKey(apiKey)
}
get apiKey () {
return this._apiKey
}
setRequestOptions (requestOptions) {
this._requestOptions = requestOptions
return this
}
set requestOptions (requestOptions) {
this.setRequestOptions(requestOptions)
return this
}
get requestOptions () {
return this._requestOptions
}
configure ({ apiKey, requestOptions }) {
this.setApiKey(apiKey)
this.setRequestOptions(requestOptions)
return this
}
setRecipient (recipient) {
this._recipient = recipient
return this
}
set recipient (recipient) {
this.setRecipient(recipient)
}
get recipient () {
return this._recipient
}
setData (data) {
this.addData(data)
return this
}
set data (data) {
this.addData(data)
}
get data () {
return this.message.params.data
}
setCollapseKey (collapseKey) {
this.message.params.collapseKey = collapseKey
return this
}
set collapseKey (collapseKey) {
this.setCollapseKey(collapseKey)
}
get collapseKey () {
return this.message.params.collapseKey
}
setPriority (priority) {
this.message.params.priority = priority
return this
}
set priority (priority) {
this.setPriority(priority)
}
get priority () {
return this.message.params.priority
}
setContentAvailable (contentAvailable) {
this.message.params.contentAvailable = contentAvailable
return this
}
set contentAvailable (contentAvailable) {
this.setContentAvailable(contentAvailable)
}
get contentAvailable () {
return this.message.params.contentAvailable
}
setDelayWhileIdle (delayWhileIdle) {
this.message.params.delayWhileIdle = delayWhileIdle
return this
}
set delayWhileIdle (delayWhileIdle) {
this.setDelayWhileIdle(delayWhileIdle)
}
get delayWhileIdle () {
return this.message.params.delayWhileIdle
}
setTimeToLive (timeToLive) {
this.message.params.timeToLive = timeToLive
return this
}
set timeToLive (timeToLive) {
this.setTimeToLive(timeToLive)
}
get timeToLive () {
return this.message.params.timeToLive
}
setRestrictedPackageName (restrictedPackageName) {
this.message.params.restrictedPackageName = restrictedPackageName
return this
}
set restrictedPackageName (restrictedPackageName) {
this.setRestrictedPackageName(restrictedPackageName)
}
get restrictedPackageName () {
return this.message.params.restrictedPackageName
}
setDryRun (dryRun) {
this.message.params.dryRun = dryRun
return this
}
set dryRun (dryRun) {
this.setDryRun(dryRun)
}
get dryRun () {
return this.message.params.dryRun
}
setTitle (title) {
this.addNotification('title', title)
return this
}
set title (title) {
this.setTitle(title)
}
get title () {
return this.message.params.notification.title
}
setBody (body) {
this.addNotification('body', body)
return this
}
set body (body) {
this.setBody(body)
}
get body () {
return this.message.params.notification.body
}
setIcon (icon) {
this.addNotification('icon', icon)
return this
}
set icon (icon) {
this.setIcon(icon)
}
get icon () {
return this.message.params.notification.icon
}
setSound (sound) {
this.addNotification('sound', sound)
return this
}
set sound (sound) {
this.setSound(sound)
}
get sound () {
return this.message.params.notification.sound
}
setBadge (badge) {
this.addNotification('badge', badge)
return this
}
set badge (badge) {
this.setBadge(badge)
}
get badge () {
return this.message.params.notification.badge
}
setTag (tag) {
this.addNotification('tag', tag)
return this
}
set tag (tag) {
this.setTag(tag)
}
get tag () {
return this.message.params.notification.tag
}
setColor (color) {
this.addNotification('color', color)
return this
}
set color (color) {
this.setColor(color)
}
get color () {
return this.message.params.notification.color
}
setClickAction (clickAction) {
this.addNotification('click_action', clickAction)
return this
}
set clickAction (clickAction) {
this.setClickAction(clickAction)
}
get clickAction () {
return this.message.params.notification['click_action']
}
setBodyLocKey (bodyLocKey) {
this.addNotification('body_loc_key', bodyLocKey)
return this
}
set bodyLocKey (bodyLocKey) {
this.setBodyLocKey(bodyLocKey)
}
get bodyLocKey () {
return this.message.params.notification['body_loc_key']
}
setBodyLocArgs (bodyLocArgs) {
if (Array.isArray(bodyLocArgs)) {
bodyLocArgs = JSON.stringify(bodyLocArgs)
}
this.addNotification('body_loc_args', bodyLocArgs)
return this
}
set bodyLocArgs (bodyLocArgs) {
this.setBodyLocArgs(bodyLocArgs)
}
get bodyLocArgs () {
return this.message.params.notification['body_loc_args']
}
setTitleLocKey (titleLocKey) {
this.addNotification('title_loc_key', titleLocKey)
return this
}
set titleLocKey (titleLocKey) {
this.setTitleLocKey(titleLocKey)
}
get titleLocKey () {
return this.message.params.notification['title_loc_key']
}
setTitleLocArgs (titleLocArgs) {
if (Array.isArray(titleLocArgs)) {
titleLocArgs = JSON.stringify(titleLocArgs)
}
this.addNotification('title_loc_args', titleLocArgs)
return this
}
set titleLocArgs (titleLocArgs) {
this.setTitleLocArgs(titleLocArgs)
}
get titleLocArgs () {
return this.message.params.notification['title_loc_args']
}
toJSON () {
return this.toJson()
}
}
module.exports = FcmMessage
<file_sep>'use strict'
const test = require('japa')
const FcmMessage = require('../../src/FcmMessage')
const FcmChannel = require('../../src/FcmChannel')
test.group('FcmChannel', () => {
test('getMessage should return instanceof FcmMessage (from toFcm)', async assert => {
class FcmNotification {
toFcm () {
return new FcmMessage({
collapseKey: 'demo',
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 3,
restrictedPackageName: 'somePackageName',
dryRun: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.'
}
})
}
}
const message = await new FcmChannel().getMessage(null, new FcmNotification())
assert.instanceOf(message, FcmMessage)
})
test('getMessage should return instanceof FcmMessage (from toJSON)', async assert => {
class FcmNotification {
toJSON () {
return {
collapseKey: 'demo',
priority: 'high',
contentAvailable: true,
delayWhileIdle: true,
timeToLive: 3,
restrictedPackageName: 'somePackageName',
dryRun: true,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: 'Hello, World',
icon: 'ic_launcher',
body: 'This is a notification that will be displayed if your app is in the background.'
}
}
}
}
const message = await new FcmChannel().getMessage(null, new FcmNotification())
assert.instanceOf(message, FcmMessage)
})
})
<file_sep>'use strict'
const NE = require('node-exceptions')
const Sender = require('node-gcm').Sender
const CouldNotSendNotification = require('./CouldNotSendNotification')
const exceptionMessages = {
400: 'Invalid JSON',
401: 'Authentication Error',
500: 'Internal Server Error',
503: 'Service Temporarily Unavailable'
}
class FcmSender {
constructor (apiKey, requestOptions = {}) {
this.apiKey = apiKey
this.requestOptions = requestOptions
}
send (message, recipient) {
const apiKey = message.apiKey || this.apiKey
const requestOptions = message.requestOptions || this.requestOptions
if (!apiKey) {
throw CouldNotSendNotification.missingApiKey()
}
const sender = new Sender(apiKey, requestOptions)
return new Promise((resolve, reject) => {
sender.send(message, recipient, (err, response) => {
if (err) {
if (typeof err === 'number') {
const exceptionMessage = exceptionMessages[err] || 'Undefined error'
err = new NE.HttpException(exceptionMessage, err)
}
reject(err)
return
}
resolve(response)
})
})
}
}
module.exports = FcmSender
| d9cb1e1d11dc1fd0d05b15eaa32f4daef9f35790 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | enniel/adonis-fcm-notification-channel | f7bf2822e7e0eedfec4796881dcf59f7260c6c97 | 5c0c08b525d646636eec79e1649d44b1bbf314e5 |
refs/heads/3.0 | <repo_name>Wesley-yang/think-swoole<file_sep>/src/PidManager.php
<?php
namespace think\swoole;
use Swoole\Process;
class PidManager
{
/** @var string */
protected $file;
public function __construct(string $file)
{
$this->file = $file;
}
public function getPid()
{
if (is_readable($this->file)) {
return (int) file_get_contents($this->file);
}
return 0;
}
/**
* 是否运行中
* @return bool
*/
public function isRunning()
{
$pid = $this->getPid();
if ($pid) {
if (Process::kill($pid, 0)) {
return true;
}
//清理pid文件
@unlink($this->file);
}
return false;
}
/**
* Kill process.
*
* @param int $sig
* @param int $wait
*
* @return bool
*/
public function killProcess($sig, $wait = 0)
{
$pid = $this->getPid();
$pid > 0 && Process::kill($pid, $sig);
if ($wait) {
$start = time();
do {
if (!$this->isRunning()) {
break;
}
usleep(100000);
} while (time() < $start + $wait);
}
return $this->isRunning();
}
}
| 6d4bb0bb6f57dea449b5a11c4eb2b61d436c8fb8 | [
"PHP"
] | 1 | PHP | Wesley-yang/think-swoole | fda0569d1787bddffd728bf41978b56686274049 | 06ab24323243a8d46299f3703d7b0e7ddd6a0e06 |
refs/heads/master | <file_sep>package com.xs.tweet;
import com.xs.tweet.bean.UserBean;
import com.xs.tweet.net.TweetRetrofitUtil;
import com.xs.tweet.net.apiservices.TweetServices;
import org.junit.Test;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
//test api
@Test
public void getUserInfo(){
TweetServices tweetServices = TweetRetrofitUtil.getInstance().getApiServices(TweetServices.class);
tweetServices.getUser().observeOn(Schedulers.io())
.subscribe(new Observer<UserBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(UserBean value) {
System.out.println("success:" + value.getNick());
}
@Override
public void onError(Throwable e) {
System.out.println("error:");
e.printStackTrace();
}
@Override
public void onComplete() {
}
});
}
}<file_sep>package com.xs.tweet.bean;
/**
* 作者:xq on 2018/8/29 17:11
* 邮箱:<EMAIL>
*/
public class ImageBean {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.xs.tweet"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
configurations.all {
resolutionStrategy.force 'com.android.support:support-annotations:26.1.0'
}
dependencies {
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:1.1.1"
// Room
implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
api 'com.google.code.gson:gson:2.7'
//okhttp
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
//retrofit2
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
//回调adapter
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
//round imageview
implementation 'agency.tango.android:avatar-view:0.0.2'
implementation 'agency.tango.android:avatar-view-glide:0.0.2'
//universalimageloader
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
//refresh layout
implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.4-7'
implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.4-7'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
<file_sep>package com.xs.tweet.model;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import com.xs.tweet.Repository.TweeterRespository;
import com.xs.tweet.bean.TweetBean;
import com.xs.tweet.bean.UserBean;
import java.util.List;
/**
* view model
* 作者:xq on 2018/8/29 18:53
* 邮箱:<EMAIL>
*/
public class TweetViewModel extends ViewModel {
private static Object LOCK = new Object();
private static TweetViewModel INSTANCE;
private TweeterRespository mTweeterResponsitory;
public static TweetViewModel getInstance(){
synchronized (LOCK){
if(INSTANCE == null){
INSTANCE = new TweetViewModel();
}
return INSTANCE;
}
}
public TweetViewModel(){
mTweeterResponsitory = TweeterRespository.getInstance();
}
public MutableLiveData<UserBean> getUser(){
return mTweeterResponsitory.getUser();
}
public MutableLiveData<List<TweetBean>> getTweetList(){
return mTweeterResponsitory.getTweetList();
}
public MutableLiveData<List<TweetBean>> getTweetList(int page){
return mTweeterResponsitory.getTweetList(page);
}
}
<file_sep>package com.xs.tweet.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.xs.tweet.R;
import com.xs.tweet.ui.widget.NineGridLayout;
import agency.tango.android.avatarview.views.AvatarView;
/**
* 作者:xq on 2018/8/30 16:36
* 邮箱:<EMAIL>
*/
public class TweetListHolder extends RecyclerView.ViewHolder {
private NineGridLayout mNineGridLayout;
private TextView userNameTv;
private AvatarView iconIv;
private TextView contextTv;
private TextView commtentTv;
public TweetListHolder(View itemView) {
super(itemView);
mNineGridLayout = itemView.findViewById(R.id.layout_nine_grid);
userNameTv = itemView.findViewById(R.id.user_name);
iconIv = itemView.findViewById(R.id.user_icon);
contextTv = itemView.findViewById(R.id.user_content);
commtentTv = itemView.findViewById(R.id.user_comment);
}
public NineGridLayout getNineGridLayout(){
return mNineGridLayout;
}
public AvatarView getIconIv(){
return iconIv;
}
public TextView getUserNameTv(){
return userNameTv;
}
public TextView getContextTv(){
return contextTv;
}
public TextView getCommtentTv(){
return commtentTv;
}
}
| 18583f208e7b2b2e5fb3fcebd99ac09e3f0222e4 | [
"Java",
"Gradle"
] | 5 | Java | 08xq/SimnpleWechat | 39581be3eac920bb8dcf8964ed7636055fd9301c | c0260aec60eba7ff748395ebc040e6669dd200c7 |
refs/heads/master | <repo_name>TheFalseTruth/LIBPRO<file_sep>/base.cpp
#include
#include
#include
#define USER_MAX 1000
using namespace std;
struct user{
string identification_code, SSN, name, birthday, occpation, email;
};
void storeUserData(user a);
int main()
{
user nUser[USER_MAX];
return 0;
}
void storeUserData(user a){
};
| 81a33bea4c4407c1d88adcaf057fe4bb6fd3fff9 | [
"C++"
] | 1 | C++ | TheFalseTruth/LIBPRO | d63bdbd8371c12c3f15476b36c683708a794c428 | 7028708012a1a0d049dc1c7901669fbb1812fa64 |
refs/heads/master | <file_sep>package com.urlshortener.service;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
@Service
public class RandomKeyGenerator {
static final String possibilities = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public String generate(int length) {
SecureRandom secureRandom = new SecureRandom();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
stringBuilder.append(possibilities.charAt(secureRandom.nextInt(possibilities.length())));
}
return stringBuilder.toString();
}
}
<file_sep>package com.urlshortener.model;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface UrlRepository extends CrudRepository<UrlShortener, Long> {
@Query(value="SELECT full_url FROM urlshortener WHERE urlshortener.url_key = ?1", nativeQuery=true)
String findByUrlKey(String urlKey);
}
<file_sep># URL-Shortener
## Overview
This application is developed using Spring (Java 8) and PostgreSQL database.
It is deployed on AWS Elastic BeanStalk and is accessible via the link: https://smolurl.net/
## Set Up (local)
1. Clone the code to your local machine.
2. Ensure that your JAVA_HOME environment has been set and pointing to your your Java JDK.
MacOS example (Terminal, vim ~/.bash_profile):
```
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home
```
3. Ensure that you have maven installed (eg. run mvn -v does not return an error and shows you a version of your maven).
Else, set up mvn (MacOS)
```
brew install maven
```
4. Ensure that you have postgresql installed. (eg. run psql on terminal)
Else, set up postgresql (MacOS) via terminal below. Alternatively, you can download it from their site at https://www.postgresql.org/download/
```
brew install postgresql
```
5. Open the source code and ensure that the JDK is set up for the project in your IDE.
6. At the root directory, run `maven clean install` to download all dependencies and build the executable JAR.
7. To run the application locally, update the user and password of your postgres DB in application.properties and create a Database table called `urlshortener` in your local postgres.
Example:
```
CREATE DATABASE urlshortener;
```
8. Then, run the application using `java -jar target/urlshortener-0.0.1-SNAPSHOT.jar`.
9. Finally, you can access the app at http://localhost:5000/
<file_sep>-- INSERT INTO urlshortener (url_key, full_url) VALUES
-- ('111111', 'http://google.com'),
-- ('111112', 'http://yahoo.com'),
-- ('111113', 'http://bing.com');
<file_sep>package com.urlshortener.controller;
import com.urlshortener.model.UrlRequest;
import com.urlshortener.model.UrlResponse;
import com.urlshortener.service.RandomKeyGenerator;
import com.urlshortener.service.UrlService;
import com.urlshortener.service.UrlTransformer;
import org.apache.commons.validator.routines.UrlValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import java.util.Objects;
@Controller
public class UrlController {
Logger logger = LoggerFactory.getLogger(UrlController.class);
private static String server;
UrlService urlService;
UrlTransformer urlTransformer;
RandomKeyGenerator randomKeyGenerator;
@Autowired
UrlController(@Value("${server.url}") String server, UrlService urlService,
UrlTransformer urlTransformer, RandomKeyGenerator randomKeyGenerator) {
this.server = server;
this.urlService = urlService;
this.urlTransformer = urlTransformer;
this.randomKeyGenerator = randomKeyGenerator;
}
// query DB for actual url
// check if exists - if yes then setUrl to retrieved URL. if not, redirect back to homepage
@GetMapping("/{key}")
public RedirectView getActualURL(@PathVariable String key, RedirectAttributes redir) {
RedirectView redirectView = new RedirectView("/", true);
String url = urlService.getUrlFromKey(key);
if (Objects.nonNull(url)) {
redirectView.setUrl(url);
} else {
redir.addAttribute("redirected", true);
}
return redirectView;
}
@GetMapping("/")
public String generateUrl(@RequestParam(value = "redirected", defaultValue = "false", required = false) boolean redirected,
Model model) {
model.addAttribute("isRedirected", redirected);
model.addAttribute("urlRequest", new UrlRequest());
return "generateUrl";
}
// get the full form of the URL - ie with http:// or https://
// validate URL
@PostMapping("/")
public String generateUrl(@ModelAttribute UrlRequest urlRequest, Model model) {
model.addAttribute("errorMessage", "");
model.addAttribute("previousUrlRequest", urlRequest);
String url = urlRequest.getUrl();
url = urlTransformer.transform(url);
UrlValidator urlValidator = new UrlValidator();
if (!urlValidator.isValid(url)) {
model.addAttribute("errorMessage", "invalid Url");
}
String key = randomKeyGenerator.generate(6);
// ensure atomic and correctness
while (!urlService.insertURL(key, url)) {
key = randomKeyGenerator.generate(6);
}
UrlResponse response = new UrlResponse(url, server + key);
model.addAttribute("urlRequest", new UrlRequest());
model.addAttribute("urlResponse", response);
logger.info("Generated URL. Shortened Url: " + response.getShortenedUrl() + "Full URL: " + response.getFullUrl());
return "generateUrlResponse";
}
}
<file_sep>package com.urlshortener.model;
public class UrlResponse {
private String fullUrl;
private String shortenedUrl;
public UrlResponse(String fullUrl, String shortenedUrl) {
this.fullUrl = fullUrl;
this.shortenedUrl = shortenedUrl;
}
public String getFullUrl() {
return fullUrl;
}
public void setFullUrl(String fullUrl) {
this.fullUrl = fullUrl;
}
public String getShortenedUrl() {
return shortenedUrl;
}
public void setShortenedUrl(String shortenedUrl) {
this.shortenedUrl = shortenedUrl;
}
}
| 6e60b79f1800264394eed3ab7dae8f519fb136b4 | [
"Markdown",
"Java",
"SQL"
] | 6 | Java | jityong/URL-Shortener | f718ae169c348714065f43121d6bcc9df354b481 | a619eed49bd4b5c93afee3a07a1d2b238bbaf4e1 |
refs/heads/master | <file_sep>FreshBooks::Base.establish_connection!('XXXX.freshbooks.com', 'XXXXXX')
<file_sep>source :rubyforge
source :rubygems
gem 'freshbooks-rb', :git => "git://github.com/turingstudio/freshbooks-rb.git", :branch => 'master'
gem 'activesupport'
#gem 'freshbooks'
group :development, :test do
gem 'map_by_method'
gem 'what_methods'
gem 'net-http-spy'
gem 'hirb'
gem 'sketches'
end
| 6b50698e998ab505dc1ab981c16972439ad58644 | [
"Ruby"
] | 2 | Ruby | hh/fresh-invoice | 2cefac76cdf3cae87d912d9a190cec670a9ada08 | be8ba8c194919550d9e6aa2109de21207efe40f5 |
refs/heads/master | <repo_name>yuanzhitang/CommunicationTech<file_sep>/WCFDuplexDemo/Contract/ICallBack.cs
using System.ServiceModel;
namespace Contract
{
public interface ICallBack
{
[OperationContract]
string UserId();
[OperationContract(IsOneWay = true)]
void SayHello(string mes);
}
}
<file_sep>/ChatRoom_WCF_Duplex_Sample/Contract/IChatCallback.cs
using System.ServiceModel;
namespace ChatRoom.Contract
{
public interface IChatCallback
{
[OperationContract]
string UserId();
[OperationContract(IsOneWay = true)]
void SayHello(string user, string mes);
[OperationContract(IsOneWay = true)]
void Online(string user);
[OperationContract(IsOneWay = true)]
void Offline(string user);
}
}
<file_sep>/WCFDuplexDemo/Contract/IMessageService.cs
using System.ServiceModel;
namespace Contract
{
[ServiceContract(CallbackContract = typeof(ICallBack))]
public interface IMessageService
{
[OperationContract]
void RegisterClient();
[OperationContract]
void SendMessage(string msg, string userId);
}
}
<file_sep>/ChatRoom_WCF_Duplex_Sample/Contract/IMessageService.cs
using System.ServiceModel;
namespace ChatRoom.Contract
{
[ServiceContract(CallbackContract = typeof(IChatCallback))]
public interface IMessageService
{
[OperationContract]
void RegisterClient();
[OperationContract]
void SendMessage(string msg, string userId);
}
}
<file_sep>/SignalR_Sample/SignalRDemo1/SignalRDemo1/Hubs/ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRDemo1.Hubs
{
public class ChatHub : Hub
{
public async Task Login(string name)
{
await Clients.AllExcept(Context.ConnectionId).
SendAsync("online", $"{name} 进入了群聊!");
}
public async Task SignOut(string name)
{
await Clients.AllExcept(Context.ConnectionId)
.SendAsync("online", $"{name} 离开了群聊!");
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
public async Task SendMessageByServer(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, "系统通知:" + message);
}
}
}
<file_sep>/SignalR_Sample/SignalRDesktop/SignalRDesktop/MainWindow.xaml.cs
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SignalRDesktop
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
HubConnection connection;
public MainWindow()
{
InitializeComponent();
connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44345/chatHub")
.Build();
connection.On<string>("online", (msg) =>
{
this.Dispatcher.Invoke(() =>
{
txtInfo.Text += msg + "\r\n";
});
});
connection.On<string, string>("ReceiveMessage", (user, msg) =>
{
this.Dispatcher.Invoke(() =>
{
txtMsg.Text += $"{user}:{msg} \r\n";
});
});
connection.StartAsync();
}
private void btnIn_Click(object sender, RoutedEventArgs e)
{
string title = $"监工{new Random().Next(1, 99999)}号";
Title = title;
connection.InvokeAsync("Login", title);
btnSend.IsEnabled = true;
}
private void btnOut_Click(object sender, RoutedEventArgs e)
{
connection.InvokeAsync("SignOut", Title);
connection.StopAsync();
this.Close();
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
if (txtSend.Text == "") return;
connection.InvokeAsync("SendMessage", Title, txtSend.Text);
}
}
}
<file_sep>/ChatRoom_SignalR_Sample/SignalR_Server/Hubs/ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ChatRoomSite.Hubs
{
public class ChatHub : Hub
{
//private IList<string> Users = new List<string>();
public async Task Login(string name)
{
await Clients.AllExcept(Context.ConnectionId).
SendAsync("Login", name);
//foreach(var user in Users)
//{
// await Clients.Client(Context.ConnectionId).SendAsync("Login", user);
//}
//if (!Users.Contains(name))
//{
// Users.Add(name);
//}
}
public async Task SignOut(string name)
{
await Clients.AllExcept(Context.ConnectionId)
.SendAsync("SignOut", $"{name} 离开了群聊!");
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
public async Task SendMessageByServer(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, "系统通知:" + message);
}
}
}
<file_sep>/WCFDuplexDemo/Client/MyCallBack.cs
using Contract;
using System;
using System.Threading;
namespace Client
{
public class MyCallBack : ICallBack
{
private string userId;
public MyCallBack(string userId)
{
this.userId = userId;
}
public void SayHello(string mes)
{
Console.WriteLine(mes);
}
public string UserId()
{
return userId;
}
}
}
<file_sep>/ChatRoom_WCF_Duplex_Sample/Server/Program.cs
using ChatRoom.Contract;
using System;
using System.ServiceModel;
namespace ChatRoom.Server
{
class Program
{
private const string Address = "net.tcp://localhost:9099";
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(MessageService)))
{
host.AddServiceEndpoint(typeof(IMessageService), new NetTcpBinding(), Address);
host.Opening += Host_Opening;
host.Open();
Console.WriteLine("Press Any Key to Exit...");
Console.ReadLine();
host.Close();
}
}
private static void Host_Opening(object sender, EventArgs e)
{
Console.WriteLine("Server Started:{0}", DateTime.Now.ToString());
}
}
}
<file_sep>/ChatRoom_WCF_Duplex_Sample/Chat/ChatCallBack.cs
using ChatRoom.Contract;
using System;
using System.Threading;
namespace ChatRoom.Chat
{
public class ChatCallBack : IChatCallback
{
private string userId;
public event Action<string, string> OnSayHello;
public event Action<string> OnLogin;
public event Action<string> OnLogout;
public ChatCallBack(string userId)
{
this.userId = userId;
}
public void SayHello(string user, string mes)
{
OnSayHello?.Invoke(user, mes);
}
public string UserId()
{
return userId;
}
public void Online(string user)
{
OnLogin?.Invoke(user);
}
public void Offline(string user)
{
OnLogout?.Invoke(user);
}
}
}
<file_sep>/WCFDuplexDemo/Client/Program.cs
using Contract;
using System;
using System.ServiceModel;
namespace Client
{
class Program
{
//private const string ClientAddress = "http://localhost:";
private const string ServerAddress = "net.tcp://localhost:9099";
static void Main(string[] args)
{
//Console.Write($"Enter a Port:");
//var port = Console.ReadLine();
Console.Write($"Enter your name:");
var user = Console.ReadLine();
ICallBack callback = new MyCallBack(user);
InstanceContext context = new InstanceContext(callback);
NetTcpBinding binding = new NetTcpBinding();
//binding.ClientBaseAddress = new Uri(ClientAddress+port);
using (var proxy = new DuplexChannelFactory<IMessageService>(context, binding))
{
IMessageService client = proxy.CreateChannel(new EndpointAddress(ServerAddress));
client.RegisterClient();
while (true)
{
Console.Write($"[{user}]:");
var msg = Console.ReadLine();
client.SendMessage(msg, user);
}
}
}
}
}
<file_sep>/ChatRoom_WCF_Duplex_Sample/Chat/Proxy/ChatServerProxy.cs
using ChatRoom.Contract;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace ChatRoom.Chat
{
public class ChatServerProxy : ClientBase<IMessageService>, IMessageService
{
public ChatServerProxy()
{
}
public ChatServerProxy(Binding binding, EndpointAddress remoteAddress)
: base(binding, remoteAddress)
{
}
public ChatServerProxy(string endpointConfigurationName, EndpointAddress remoteAddress)
: base(endpointConfigurationName, remoteAddress)
{
}
public ChatServerProxy(InstanceContext callbackInstance, string endpointConfigurationName) : base(callbackInstance,endpointConfigurationName)
{
}
public void RegisterClient()
{
Channel.RegisterClient();
}
public void SendMessage(string msg, string userId)
{
Channel.SendMessage(msg, userId);
}
}
}
<file_sep>/WCFDuplexDemo/Server/MessageService.cs
using Contract;
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace Server
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class MessageService : IMessageService, IDisposable
{
public static List<ICallBack> CallBackList
{
get;
set;
}
public MessageService()
{
CallBackList = new List<ICallBack>();
}
public void RegisterClient()
{
ICallBack callback = OperationContext.Current.GetCallbackChannel<ICallBack>();
string sessionid = OperationContext.Current.SessionId;
var ms = OperationContext.Current.IncomingMessageProperties;
var remp = ms[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
Console.WriteLine($"SessionId: {sessionid}, User:{callback.UserId()}, Address:{remp.Address}, Port:{remp.Port} is registered");
OperationContext.Current.Channel.Closing +=
delegate
{
lock (CallBackList)
{
CallBackList.Remove(callback);
Console.WriteLine("SessionId: {0}, User:{1} is removed", sessionid, callback.UserId());
}
};
CallBackList.Add(callback);
}
public void SendMessage(string msg, string userId)
{
Console.WriteLine($"{userId}:{msg}");
NotifyClients(userId);
}
public static void NotifyClients(string userId="")
{
lock (MessageService.CallBackList)
{
foreach (ICallBack callback in MessageService.CallBackList)
{
if (!string.IsNullOrEmpty(userId) && callback.UserId() == userId)
{
callback.SayHello($"Welcome: {userId}");
}
}
}
}
public void Dispose()
{
CallBackList.Clear();
}
}
}
<file_sep>/ChatRoom_WCF_Duplex_Sample/Chat/Proxy/ProxyFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace ChatRoom.Chat
{
class ProxyFactory
{
private const string EndpointConfigurationName = "ChatServerEndpoint";
public static ChatServerProxy CreateChatServerProxy(ChatCallBack chatCallback)
{
var context = new InstanceContext(chatCallback);
var proxy = new ChatServerProxy(context, EndpointConfigurationName);
return proxy;
}
}
}
<file_sep>/ChatRoom_SignalR_Sample/ChatClient/MainWindow.xaml.cs
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Threading.Tasks;
using System.Windows;
namespace ChatRoom.Chat
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
HubConnection connection;
string CurrentUser;
public MainWindow()
{
InitializeComponent();
connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44345/chatHub")
.Build();
connection.On<string>("Login", (msg) =>
{
MyCallBack_OnLogin(msg);
});
connection.On<string>("SignOut", (msg) =>
{
ChatCallback_OnLogout(msg);
});
connection.On<string, string>("ReceiveMessage", (user, msg) =>
{
MainWindow_OnSayHello(user, msg);
});
connection.StartAsync();
}
private void Connect(object sender, RoutedEventArgs e)
{
var user = txtUser.Text.Trim();
if (string.IsNullOrEmpty(user))
{
return;
}
CurrentUser = user;
btnIn.IsEnabled = false;
btnIn.Content = "Connecting";
Task.Run(() =>
{
connection.InvokeAsync("Login", user);
//btnSend.IsEnabled = true;
//var chatCallback = new ChatCallBack(user);
//chatCallback.OnSayHello += MainWindow_OnSayHello;
//chatCallback.OnLogin += MyCallBack_OnLogin;
//chatCallback.OnLogout += ChatCallback_OnLogout;
//proxy = ProxyFactory.CreateChatServerProxy(chatCallback);
//proxy.RegisterClient();
this.Dispatcher.BeginInvoke(new Action(() =>
{
btnSend.IsEnabled = true;
btnIn.Content = "Connected";
}));
});
}
private void ChatCallback_OnLogout(string user)
{
Action method = new Action(() =>
{
if (txtInfo.Items.Contains(user))
{
txtInfo.Items.Remove(user);
}
txtMsg.Text += $"User:{user} is exited\r\n";
});
this.Dispatcher.BeginInvoke(method);
}
private void MyCallBack_OnLogin(string user)
{
Action method = new Action(() =>
{
txtInfo.Items.Add(user);
txtMsg.Text += $"User:{user} has joined the chat\r\n";
});
this.Dispatcher.BeginInvoke(method);
}
private void MainWindow_OnSayHello(string user, string msg)
{
Action action = () =>
{
txtMsg.Text += $"{DateTime.Now.ToString()}\r\n[{user}]:{msg} \r\n\r\n";
};
Dispatcher.BeginInvoke(action);
}
private void btnOut_Click(object sender, RoutedEventArgs e)
{
connection.InvokeAsync("SignOut", CurrentUser);
this.Close();
}
private void btnSend_Click(object sender, RoutedEventArgs e)
{
if (txtSend.Text == "")
{
return;
}
var message = txtSend.Text.Trim();
Dispatcher.BeginInvoke(new Action(() =>
{
connection.InvokeAsync("SendMessage", CurrentUser, message);
}));
this.Dispatcher.Invoke(() =>
{
txtSend.Text = string.Empty;
});
}
}
}
<file_sep>/WCFDuplexDemo/Server/Program.cs
using Contract;
using System;
using System.ServiceModel;
namespace Server
{
class Program
{
private const string Address = "net.tcp://localhost:9099";
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(MessageService)))
{
host.AddServiceEndpoint(typeof(IMessageService), new NetTcpBinding(), Address);
host.Opening += Host_Opening;
host.Open();
while (true)
{
Console.WriteLine("Commands:");
Console.WriteLine("[notify]: Notify all clients");
Console.WriteLine("[close] : Close the Server");
Console.Write("Enter command:");
string command = Console.ReadLine();
switch (command)
{
case "notify":
lock (MessageService.CallBackList)
{
MessageService.NotifyClients();
}
break;
case "close":
host.Close();
break;
default:
break;
}
}
}
}
private static void Host_Opening(object sender, EventArgs e)
{
Console.WriteLine("Server Started:{0}", DateTime.Now.ToString());
}
}
}
| 54cb0a86d255f45b03a37648f8ab913a8053d02f | [
"C#"
] | 16 | C# | yuanzhitang/CommunicationTech | 8db5017237934781c7888f0eb601615277f77b94 | cd79ed81987f4c7f9ec4c0f8496fc62faab3682f |
refs/heads/master | <repo_name>manhtai/manhtai.com<file_sep>/main.ts
import 'virtual:windi-base.css'
import 'virtual:windi-components.css'
import 'virtual:windi-utilities.css'
import './main.css'
<file_sep>/README.md
# manhtai.com
## Setup
```
pnpm i
pnpm dev
```
| 3fa5f6addc3bab137c49ef9f6af3bf7331b6b672 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | manhtai/manhtai.com | 7429e5c147ff3c1a51e0ca6c0566c95eb453a776 | 955eb7522b45af54f4b3a7885cadb291d84526ab |
refs/heads/main | <repo_name>YXRBC/cs35L_project<file_sep>/server.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const session = require('express-session');
const mongoose = require('mongoose')
const {url} = require('./db.js')
const indexRouter= require('./routes/index')
const {userRouter}= require('./routes/users')
const {isLogin} = require('./routes/users')
const commentRouter = require('./routes/comment')
const searchRouter = require('./routes/search')
const app = express()
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended: false}))
app.use('/comment', commentRouter)
app.use('/',indexRouter)
app.use('/',userRouter)
const connectionParams={
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
mongoose.connect(url,connectionParams)
.then( () => {
console.log('Connected to database ')
})
.catch( (err) => {
console.error(`Error connecting to the database. \n${err}`);
})
app.use('/search',searchRouter)
app.use(express.static('public'));
app.get('/', (req, res)=> {
res.redirect('/login')
})
// catch 404 and forward to error handler
app.use(function(req, res) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000)
<file_sep>/routes/comment.js
const { request } = require('express')
const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const {classSchema} = require('./schema.js')
const {commentSchema} = require('./schema.js')
const {url} = require('../db.js')
var {myStorage} = require('./users.js')
//connect to database
const connectionParams={
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
}
mongoose.connect(url,connectionParams)
.then( () => {
console.log('Connected to database ')
})
.catch( (err) => {
console.error(`Error connecting to the database. \n${err}`);
})
var Class = mongoose.model("class",classSchema)
var comment = mongoose.model("comment",commentSchema)
//create new comment
router.get('/new/:id', (req, res) => {
if(myStorage.getItem('isLogin')===false){
res.redirect('/login')
}
var class_id = req.params.id
Class.findById(class_id).exec(function(err,response){
if(err){
console.log("error in finding class")
throw err
}
class_post = response
res.render('comment/new', {class: class_post})
})
})
//display classpage
router.get('/classpage/:id',(req,res)=>{
if(myStorage.getItem('isLogin')===false){
res.redirect('/login')
}
var display_class
var display_comment
var class_id = req.params.id
Class.findById(class_id).exec(function(err,response){
if (err){
console.log("error in finding class")
throw err
}
display_class = response
comment.find({class: display_class.name},function(err,response_1){
if (err){
console.log("error in finding class")
throw err
}
display_comment = response_1.sort(function(a,b){return (b.commentAt-a.commentAt)})
res.render('comment/index', {comment: display_comment, class_id: display_class})
})
})
})
router.get('/add_class',(req,res)=>{
if(myStorage.getItem('isAdmin')===true){
res.render('comment/create')
} else {
res.redirect('/search')
}
})
//add a new class to the database
//add success only if the class isn't already in the database
router.post('/addition',(req,res)=>{
var new_class = new Class({
name: req.body.class_name,
info: req.body.info,
professors: req.body.professor,
summary:req.body.summary,
overall_rating: 0,
num_rating: 0
})
Class.find({name: req.body.class_name},function(err,response){
if (err){
console.log("error in finding class")
throw err
}
if(response.length > 0){
console.log("class already exist in database")
}
else{
new_class.save(function(err,Class){
if(err){
console.log("database error: fail save new class")
}
else{
console.log("new class added to database")
}
})
}
})
res.redirect('/comment/add_class')
})
//update comment usefulness count
router.post('/useful/:id', (req,res) =>{
var comment_id = req.params.id
comment.findById(comment_id).exec(function(err,response){
var useful = response.usefulness +1
comment.findOneAndUpdate({_id: comment_id}, {usefulness: useful}, function(err_2, response_1) {
if(err_2){
console.log("unsuccessful update of rating")
throw err
}
})
Class.find({name: response.class}, function(err_1, class_get){
if(err_1){
console.log("unsuccessful update of rating, find class")
throw err
}
let class_id = class_get[0]._id
res.redirect('/comment/classpage/'+class_id)
})
})
//res.redirect('/comment/classpage/'+class_id)
})
//update overall rating of the class
router.post('/rate/:id', (req,res)=>{
var display_class
var class_id = req.params.id
Class.findById(class_id).exec(function(err,response){
if (err){
console.log("can't find class")
throw err
}
display_class = response
var num = req.body.rate *1
var total = (display_class.overall_rating * display_class.num_rating) + num
var rate_num = display_class.num_rating +1
Class.findOneAndUpdate({_id: class_id}, {overall_rating: total/rate_num, num_rating:rate_num}, function(err, response) {
if(err){
console.log("unsuccessful update of rating")
throw err
}
})
res.redirect('/comment/classpage/'+class_id)
})
//res.redirect('/comment/classpage')
})
//save new comment to database
router.post('/add_comment/:id', (req,res) =>{
class_id = req.params.id
Class.findById(class_id).exec(function(err,response){
if(err){
console.log("error in finding class")
throw err
}
var new_comment = new comment ({
class: response.name,
user: myStorage.getItem('user'),
commentAt: Date.now(),
courseComment: req.body.comment,
usefulness: 0
})
new_comment.save(function(err, comment){
if(err){
console.log("database error: fail to save new comment")
}
else{
console.log("new comment added to database")
}
})
})
res.redirect('/comment/classpage/'+class_id)
})
module.exports = router
<file_sep>/README.md
## SEASWALK - Web app for rating CS and EE major classes
Over the past few years, students in CS and EE major have often complained about the bruinwalk, since they were unable to always get the information they needed efficiently for the incoming courses. Facing the same issue, our group proposed to offer a new app, Seaswalk, that is designed for evaluating courses in CS and EE departments.
## Steps before cloning and installing
1. Make sure you have node.js installed in your computer.
2. Make sure you have a MongoDB Atlas database ready for use
## Cloning repository and installing the app for use
Open the terminal/command line and navigate to the directory you wish to clone the repository to. Then type the following code in the command line:
```
git clone https://github.com/YXRBC/cs35L_project.git
```
After this, enter the following commands in order:
```
cd cs35L_project
npm install
```
Make sure you have installed the following packages:
- MongoDB Atalas
- Express
- Node.js
- Cookie-parse
- Http-errors
- Morgan
- Express-session
If you don't have the packages installed, the code for installing the packages are:
```
npm install [package name]
```
Add a file *db.js* in the same directory as *server.js*
This file is code containing the username and password for connecting to the database, which is used in other files
The file should be the following format:
```
var url = [the connection string the MongoDB Atalas provides you for database connection]
module.exports ={url};
```
Now to run the app, in the main directory, enter the following code in the command line:
```
npm start
```
Open `localhost:3000` or `localhost:3000/login` from your favourite browser
## Creators
- <NAME> (Jimmy)
- <NAME> (Rebecca)
- <NAME> (Sawyer)
- <NAME> (Clarissa)
- <NAME> (Eric)
- <NAME>
<file_sep>/routes/index.js
var express = require('express');
var router = express.Router();
//render login page
router.get('/login', (req, res) => {
res.render('login',(''))
})
//render register page
router.get('/regist', (req, res) => {
res.render('regist',(''))
})
module.exports = router;
| 0205237ad27a31b2a7deaf0beb6635514d38feaf | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | YXRBC/cs35L_project | 9916d1909f4da569c05ece4edc06d9168ab09ea0 | 30872dd9f6193242b4175b352f307114d65ee838 |
refs/heads/master | <repo_name>ceclin/arduino-neohandler<file_sep>/src/neohandler.cpp
#include "neohandler.h"
bool neohandler::BaseHandler::UpdateMillis()
{
unsigned long temp = millis();
if (temp - this->millis_ >= this->interval())
{
this->millis_ = temp;
return true;
}
else
return false;
}
bool neohandler::BaseHandler::Update()
{
return this->CurrentState() == neohandler::State::RUNNING && this->UpdateMillis();
}
neohandler::State neohandler::BaseHandler::CurrentState()
{
using neohandler::State;
if (this->state_ & B00000001)
return State::RUNNING;
else
return State::PAUSED;
}
neohandler::LoopHandler::LoopHandler(unsigned long interval) : BaseHandler{interval}
{
this->Resume();
}
void neohandler::CallbackLoopHandler::CallIfUpdated()
{
if (this->Update())
{
this->InvokeCallback();
}
}
neohandler::RepeatHandler::RepeatHandler(unsigned long interval, uint8_t times) : BaseHandler{interval}
{
this->set_times(times);
}
void neohandler::RepeatHandler::set_times(uint8_t times)
{
this->times_ = times;
if (times == 0)
this->Pause();
else // times > 0
this->Resume();
}
bool neohandler::RepeatHandler::Update()
{
if (this->BaseHandler::Update())
{
this->set_times(this->times() - 1);
return true;
}
return false;
}
void neohandler::CallbackRepeatHandler::CallIfUpdated()
{
if (this->RepeatHandler::Update())
{
this->InvokeCallback();
}
}
<file_sep>/examples/blink.cpp
#include <Arduino.h>
#include <neohandler.h>
using neohandler::CallbackLoopHandler;
CallbackLoopHandler handler(1000, [] {
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
});
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
}
void loop()
{
handler.CallIfUpdated();
}
<file_sep>/src/neohandler.h
#ifndef NEOHANDLER_H_
#define NEOHANDLER_H_
#include <Arduino.h>
namespace neohandler
{
enum State : uint8_t
{
PAUSED,
RUNNING,
};
class CallbackHandler
{
private:
void (*callback_)();
protected:
explicit CallbackHandler(void (*callback)()) : callback_{callback} {}
inline void InvokeCallback()
{
if (callback_ != nullptr)
callback_();
}
public:
inline void (*callback())()
{
return this->callback_;
}
inline void set_callback(void (*callback)())
{
this->callback_ = callback;
}
virtual void CallIfUpdated() = 0;
};
class BaseHandler
{
private:
unsigned long millis_;
unsigned long interval_;
bool UpdateMillis();
protected:
uint8_t state_ = B00000000;
explicit BaseHandler(unsigned long interval = 0) : millis_{millis()}, interval_{interval} {}
public:
inline unsigned long interval()
{
return this->interval_;
}
inline void set_interval(unsigned long interval)
{
this->interval_ = interval;
}
inline void Pause()
{
this->state_ &= B11111110;
}
inline void Resume()
{
this->state_ |= B00000001;
}
inline void RefreshTime()
{
this->millis_ = millis();
}
virtual bool Update();
State CurrentState();
};
class LoopHandler : public BaseHandler
{
private:
unsigned long interval_;
public:
explicit LoopHandler(unsigned long interval = 0);
};
class CallbackLoopHandler : public LoopHandler, public CallbackHandler
{
public:
CallbackLoopHandler(unsigned long interval = 0, void (*callback)() = nullptr)
: LoopHandler{interval}, CallbackHandler{callback} {}
void CallIfUpdated() override;
};
class RepeatHandler : public BaseHandler
{
private:
unsigned long interval_;
/**
* If times_ is modified, you must set the corresponding state.
*/
uint8_t times_;
public:
RepeatHandler(unsigned long interval = 0, uint8_t times = 0);
inline uint8_t times()
{
return this->times_;
}
void set_times(uint8_t times);
bool Update() override;
};
class CallbackRepeatHandler : public RepeatHandler, public CallbackHandler
{
public:
CallbackRepeatHandler(unsigned long interval = 0, uint8_t times = 0, void (*callback)() = nullptr)
: RepeatHandler{interval, times}, CallbackHandler{callback} {}
void CallIfUpdated() override;
};
} // namespace neohandler
#endif // NEOHANDLER_H_
<file_sep>/README.md
# arduino-neohandler
[](https://travis-ci.org/ceclin/arduino-neohandler)
Arduino library for nonblocking operations
| c5fa694c517e38c46c555399a7bf95149b209146 | [
"Markdown",
"C++"
] | 4 | C++ | ceclin/arduino-neohandler | 66015eb965f512852153d15b92893818a2b05df6 | 8524e96769e453aac063b61e58e9fa0cee3ef06a |
refs/heads/master | <file_sep>#spring.jpa.database=POSTGRESQL
#spring.datasource.platform=postgres
#spring.datasource.url=jdbc:postgresql://ec2-34-200-101-236.compute-1.amazonaws.com:5432/d4io22rtpk51k8?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory
#spring.datasource.username=ujtqunbiqxznpn
#spring.datasource.password=<PASSWORD>
#spring.jpa.show-sql=true
#spring.jpa.generate-ddl=true
#spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
#spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
#spring.datasource.driver-class-name=org.postgresql.Driver
<file_sep># ECI-STAURANT
Integrantes:
* <NAME>
* <NAME>
* <NAME>
[](https://circleci.com/gh/ECI-Staurant-App/ECI-Staurant)
[](https://eci-staurant.herokuapp.com/)
### Descripción (antecedentes, problema que se resuelve, etc.):
Diariamente, los estudiantes de la Escuela Colombiana de Ingenieria se enfrentan a entornos caoticos a la hora del almuerzo, pues se presentan extensas filas en los restaurantes, existe un acaparamiento de mesas del campus por parte de otros estudiantes que no emplean las mismas para comer.
Actualmente no existe una solucion para estas problematicas y como solución proponemos crear una aplicación web que permita administrar el manejo de las mesas de una manera mas óptima y el pedido de los almuerzos a travez de la aplicación.
#### Diagrama de clases

#### Diagrama Entidad-Relación

### Historias de usuario:

* COMO estudiante
QUIERO registrarme a la plataforma
PARA PODER disfrutar de los beneficios de esta.
* COMO estudiante
QUIERO realizar pedidos
PARA PODER evitar filas en los horarios de almuerzo
* COMO estudiante
QUIERO buscar mesa
PARA PODER encontrar facilmente una mesa disponible para comer
* COMO estudiante
QUIERO recibir mesa
PARA PODER acceder facilmente una mesa disponible para comer

* COMO administrador
QUIERO administrar saldos
PARA PODER tener actualizada la información de los saldos de los clientes
* COMO administrador
QUIERO administrar ecursos
PARA PODER ampliar,eliminar y controlar los recursos ofrecidos

* COMO restaurante
QUIERO recibir pedidos
PARA PODER agilizar manera de atender clientes
* COMO restaurante
QUIERO despachar pedidos
PARA PODER entregar el producto solicitado
### Mockups
Ver [Mockups](mockups)
### Backlog [Link backlog](https://tree.taiga.io/project/andresmarcelo7-eci-staurant-app/backlog)
<file_sep>package edu.eci.arsw.EciStaurant.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping( value = "/")
public class EcistaurantController {
public String getMensaje() {
String ans = "Estamos Trabajando en ECI-STAURANT ;)";
return ans;
}
}
<file_sep>package edu.eci.arsw.EciStaurant.model;
/*import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity*/
public class Estudiante {
}
| cd704d47623dacb001e6dc3fdc3f89a55b2c9121 | [
"Markdown",
"Java",
"INI"
] | 4 | INI | ECI-Staurant-App/ECI-Staurant | 401e2f41d55f6308e05d115920d522202bb1fe25 | ba75e8d918effc12d6dbc729b3abb64218d21004 |
refs/heads/master | <repo_name>maKSiM89/SPA<file_sep>/src/app/app.controller.js
;(function() {
angular
.module('app')
.controller('AppController', AppController);
/*ngInject*/
function AppController($rootScope, authService) {
$rootScope.logout = logout;
function logout() {
authService.unAuth();
}
}
})();<file_sep>/src/app/layouts/layouts.module.js
angular.module('layouts', [
'auth-restricted'
]);<file_sep>/src/app/components/login/login.service.js
;(function() {
angular
.module('login')
.factory('loginService', loginService);
/*ngInject*/
function loginService($q, authService) {
return {
login: login
};
function login(name) {
var deferred = $q.defer();
if (name == 'Vasya') {
authService.auth(name);
deferred.resolve(name);
} else {
deferred.reject();
}
return deferred.promise;
}
}
})(); | d10709b34af619d40c89c7fe8cf52802d76e5572 | [
"JavaScript"
] | 3 | JavaScript | maKSiM89/SPA | c9c87aa19aef8f8cbb3692c0cd64b6d889b74e67 | 925399573c61ed6ece43af891bea81cd5d05b0a2 |
refs/heads/main | <file_sep># vue-example-demo
vue案例初始化项目,直接通过它可以开发了
| 8d890a8ea80342eb37c3bea830611f9e9636895c | [
"Markdown"
] | 1 | Markdown | weijunh/vue-example-demo | 2def810be27078942f9c4f57b6e9c21f24e21d42 | e7b27d4a1c97e589d139483fbb4d7b75a1af9a59 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import './App.scss';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Login from './components/Login';
import Header from './components/Header';
import Home from './components/Home';
import Room from './components/Room';
import PrivateRoom from './components/PrivateRoom';
import { connectSocket, disconnectSocket } from './services/socket';
//Route me permet d'afficher le composant lorsque la route route / est appelé.
class App extends Component {
handleSocketConnection(token) {
if (token) {
connectSocket(token);
} else {
disconnectSocket();
}
}
componentDidMount() {
this.handleSocketConnection(this.props.token);
}
componentDidUpdate(prevProps) {
if (this.props.token === prevProps.token) return;
this.handleSocketConnection(this.props.token);
}
render() {
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/room/:roomName" component={Room} />
<Route path="/room/:roomName/messages" component={PrivateRoom} />
<Route path="/" component={Home} />
</Switch>
</Router>
);
}
}
const mapStateToProps = state => {
return {
token: state.token,
};
};
export default connect(mapStateToProps)(App);
<file_sep>const http = require('http');
const socketio = require('socket.io');
const jwt = require('jsonwebtoken');
const sql = require('./services/sql');
const { JWT_SECRET } = require('./users/controller');
let io;
function init(app) {
const httpServer = http.createServer(app);
io = socketio(httpServer);
io.use(async (socket, next) => {
const token = socket.handshake.query.token;
jwt.verify(token, JWT_SECRET, async function(err, decryptedToken) {
if (!decryptedToken || err) {
socket.disconnect();
return;
}
socket.__user = {
id: decryptedToken.id,
name: decryptedToken.username,
};
// get all rooms for a user_id and join all rooms for this socket
const knex = sql.get();
const userRooms = await knex('room_user')
.where({
user_id: decryptedToken.id,
})
.innerJoin('rooms', 'room_id', 'rooms.id')
.select('rooms.name');
userRooms.forEach(userRoom => {
socket.join(userRoom.name);
});
return next();
});
});
io.on('connection', function(socket) {
console.log(`New socket connected for user ${socket.__user.id}`);
});
httpServer.listen(3007, function() {
console.log('listening on *:3007');
});
}
function getSocketById(id) {
const sockets = Object.values(io.sockets.clients().sockets);
const matchingSocket = sockets.find(socket => socket.__user.id === id);
return matchingSocket;
}
function get() {
return io;
}
module.exports = {
init,
get,
getSocketById,
};
// connexion a un fichier socketio pour éviter une dépendance ciruculaire
<file_sep>const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const sql = require('../services/sql');
const BCRYPT_SALT_ROUNDS = 10;
const JWT_SECRET = 'Os7èsSAàDOijqdspoUk';
const getAll = async (req, res) => {
const knex = sql.get();
try {
const users = await knex('users').select(['id', 'username']);
res.status(200).send(users);
} catch (error) {
res.status(500).send(error);
}
};
const create = async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).send();
}
const hash = await bcrypt.hashSync(password, BCRYPT_SALT_ROUNDS);
// je créé un objet qui va me permettre de recuperer ce que l'utilisateur rentre suivant le model
const newUser = {
username,
password: <PASSWORD>,
};
const knex = sql.get();
try {
const [user] = await knex('users').insert(newUser, ['id', 'username']);
res.status(200).send(user);
} catch (error) {
res.status(500).send(error);
}
};
const login = async (req, res) => {
const { username, password } = req.body;
let isSamePassword;
let user;
const knex = sql.get();
try {
const users = await knex('users').where({ username }, '*');
user = users[0];
if (!user) {
return res.status(401).send();
}
isSamePassword = await bcrypt.compareSync(password, user.password);
if (!isSamePassword) {
return res.status(401).send();
}
const token = jwt.sign(
{
id: user.id,
username: user.username,
},
JWT_SECRET,
{ expiresIn: '3 hours' },
);
res.status(200).send({ token });
} catch (error) {
res.status(401).send({});
}
};
const remove = async (req, res) => {
const knex = sql.get();
try {
await knex('users')
.where({ id: req.params._id })
.del();
res.status(200).send();
} catch (error) {
res.status(500).send(error);
}
};
module.exports = {
create,
login,
getAll,
remove,
JWT_SECRET,
};
<file_sep>require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const users = require('./users');
const userRouter = require('./users/router');
const roomsRouter = require('./rooms/router');
const socket = require('./socket');
const mysqlService = require('./services/sql');
async function init() {
await mysqlService.init();
app.use(
bodyParser.urlencoded({
extended: true,
}),
);
app.use(express.json());
app.use(cors());
app.post('/login', users.controller.login);
app.use('/users', userRouter);
app.use('/rooms', roomsRouter);
app.listen(4332, () => {
console.info('This app is on port 4332!');
});
socket.init(app);
}
init();
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import RoomCreation from '../RoomCreation';
import Rooms from '../Rooms';
import Layout from '../Layout';
// import { Link } from 'react-router-dom';
import './Home.scss';
class Home extends Component {
state = {
users: [],
};
createRoom = roomName => {
fetch('http://localhost:4332/rooms', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.token}`,
},
body: JSON.stringify({
name: roomName,
}),
}).then(async res => {
const room = await res.json();
this.props.history.push(`/room/${room.id}`);
});
};
render() {
return (
<Layout>
<p className="Home_message">Welcome Here :)</p>
</Layout>
);
}
}
const mapStateToProps = state => ({ token: state.token });
export default connect(mapStateToProps)(Home);
<file_sep>const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../users/controller');
async function authMiddleware(req, res, next) {
const token = req.headers.authorization
? req.headers.authorization.replace('Bearer ', '')
: undefined;
jwt.verify(token, JWT_SECRET, (err, decryptedToken) => {
if (!decryptedToken || err) {
res.status(403).send('Forbidden');
return;
}
req.__user = decryptedToken;
next();
});
}
module.exports = authMiddleware;
<file_sep>import moment from 'moment';
import React, { Component } from 'react';
import { subscribe } from '../../services/socket';
import { connect } from 'react-redux';
import Layout from '../Layout';
import './Room.scss';
import '../../../node_modules/font-awesome/css/font-awesome.min.css';
class Room extends Component {
state = {
message: '',
messages: [],
room: {},
};
componentDidUpdate(nextProps) {
if (this.props.match.params.roomName !== nextProps.match.params.roomName) {
this.setState({
message: '',
messages: [],
room: {},
});
this.getMessages();
this.getRoom();
}
}
componentDidMount() {
this.getMessages();
this.getRoom();
subscribe('MESSAGE', message => {
if (String(message.room_id) !== String(this.props.match.params.roomName))
return;
this.setState({
messages: this.state.messages.concat(message),
});
});
}
onMessageChange = e => {
this.setState({ message: e.target.value });
};
addMessage = () => {
const body = JSON.stringify({ message: this.state.message });
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.token}`,
};
fetch(
`http://localhost:4332/rooms/${this.props.match.params.roomName}/messages`,
{
method: 'POST',
headers,
body,
},
)
.then(res => res.json())
.then(() => {
this.setState({ message: '' });
})
.catch(err => console.warn(err));
};
getRoom = () => {
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.token}`,
};
fetch(`http://localhost:4332/rooms/${this.props.match.params.roomName}`, {
method: 'GET',
headers,
})
.then(res => res.json())
.then(room => {
this.setState({
room,
});
})
.catch(err => console.warn(err));
};
getMessages = () => {
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.token}`,
};
fetch(
`http://localhost:4332/rooms/${this.props.match.params.roomName}/messages`,
{
method: 'GET',
headers,
},
)
.then(res => res.json())
.then(messages => {
this.setState({
messages,
});
})
.catch(err => console.warn(err));
};
formatDate(date) {
return moment(date).fromNow();
}
render() {
return (
<Layout>
<div className="Room">
<div className="Room_header">
<h2>
{this.state.room
? this.state.room.name
: this.props.match.params.roomName}
</h2>
<p>{this.state.room ? this.state.room.usersCount : '-'} user(s)</p>
</div>
<ul className="Room_messages">
{this.state.messages.map(message => {
return (
<li key={message.id}>
<div className="Room_user">
<strong>{message.username}</strong>
<i>{this.formatDate(message.date)}</i>
</div>
<p className="Room_text">{message.text}</p>
</li>
);
})}
</ul>
<form
className="Room_form"
onSubmit={e => {
e.preventDefault();
this.addMessage(this.state.message);
}}
>
<input
className="Room_input"
type="text"
name="message"
value={this.state.message}
onChange={this.onMessageChange}
></input>
<button className="Room_button" value="Envoyer" type="submit">
<i className="fa fa-paper-plane"></i>
</button>
</form>
</div>
</Layout>
);
}
}
const mapStateToProps = state => {
return {
token: state.token,
};
};
export default connect(mapStateToProps)(Room);
<file_sep>const io = require('../socket');
const sql = require('../services/sql');
// création de la route qui permet de rejoindre une room
const getAll = async (req, res) => {
const knex = sql.get();
try {
const rooms = await knex('rooms').select(['id', 'name']);
res.status(200).send({ rooms });
} catch (error) {
res.status(500).send(error);
}
};
const createRoom = async (req, res) => {
const knex = sql.get();
try {
const [room] = await knex('rooms').insert({ name: req.body.name }, '*');
await knex('room_user').insert({
room_id: room.id,
user_id: req.__user.id,
});
const socket = io.getSocketById(req.__user.id);
if (socket) {
socket.join(room.name);
}
res.status(200).send(room);
} catch (error) {
res.status(500).send(error);
}
};
const joinRoom = async (req, res) => {
try {
const knex = sql.get();
const [existingRoom] = await knex('rooms').where({ id: req.params.roomId });
if (!existingRoom) {
return res.status(404).send();
}
const roomUser = {
room_id: existingRoom.id,
user_id: req.__user.id,
};
const [hasRoomRelation] = await knex('room_user').where(roomUser);
if (hasRoomRelation) {
return res.status(200).send();
}
const socket = io.getSocketById(req.__user.id);
socket.join(existingRoom.name);
await knex('room_user').insert(roomUser);
res.status(200).send();
} catch (error) {
res.status(500).send(error);
}
};
const addMessage = async (req, res) => {
try {
const knex = sql.get();
const [message] = await knex('messages').insert(
{
user_id: req.__user.id,
room_id: req.params.roomId,
text: req.body.message,
},
'*',
);
const [room] = await knex('rooms').where({ id: req.params.roomId }, 'name');
io.get()
.in(room.name)
.emit('MESSAGE', {
...message,
username: req.__user.username,
});
res.status(200).send(message);
} catch (error) {
res.status(500).send(error);
}
};
const getMessages = async (req, res) => {
try {
const knex = sql.get();
const messages = await knex('messages')
.where({ room_id: req.params.roomId })
.innerJoin('users', 'user_id', 'users.id')
.select(['messages.id', 'username', 'room_id', 'text', 'date']);
res.status(200).send(messages);
} catch (error) {
res.status(500).send(500);
}
};
const getRoom = async (req, res) => {
try {
const knex = sql.get();
const [room] = await knex('rooms').where({ id: req.params.roomId }, '*');
const [{ count }] = await knex('room_user')
.where({ room_id: req.params.roomId })
.count('*');
res.status(200).send({ ...room, usersCount: count });
} catch (error) {
res.status(500).send(500);
}
};
module.exports = {
getRoom,
getAll,
createRoom,
addMessage,
getMessages,
joinRoom,
};
<file_sep>const express = require('express');
const roomRouter = express.Router();
const controller = require('./controller');
const authMiddleware = require('../middlewares/auth.middleware');
roomRouter.get('/', authMiddleware, controller.getAll);
roomRouter.post('/', authMiddleware, controller.createRoom);
roomRouter.get('/:roomId', authMiddleware, controller.getRoom);
roomRouter.post('/:roomId/join', authMiddleware, controller.joinRoom);
roomRouter.post('/:roomId/messages', authMiddleware, controller.addMessage);
roomRouter.get('/:roomId/messages', authMiddleware, controller.getMessages);
module.exports = roomRouter;
<file_sep>import io from 'socket.io-client';
//connection a socket.io
let socket;
export function connectSocket(token) {
if (socket) {
socket.disconnect();
}
socket = io(`http://localhost:3007?token=${token}`);
socket.on('MESSAGE', payload => {
triggerEvent('MESSAGE', payload);
});
}
export function disconnectSocket() {
if (socket) {
socket.disconnect();
socket = undefined;
}
}
const subscribers = {
// MESSAGE: [callback1, callback2]
};
export function subscribe(eventName, callback) {
if (!subscribers[eventName]) subscribers[eventName] = [];
subscribers[eventName].push(callback);
// unsubscribe function
return () => {
subscribers[eventName] = subscribers[eventName].filter(
cb => cb !== callback,
);
};
}
function triggerEvent(eventName, payload) {
if (!subscribers[eventName]) return;
subscribers[eventName].forEach(callback => {
callback(payload);
});
}
<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Rooms from '../Rooms';
import RoomCreation from '../RoomCreation';
import './Layout.scss';
class Layout extends Component {
render() {
return (
<div className="Layout">
<div className="Layout_sidebar">
<RoomCreation />
<Rooms className="Layout_rooms" />
<Link className="Layout_logout" to="/login">
Log out
</Link>
</div>
<div className="Layout_main">{this.props.children}</div>
</div>
);
}
}
export default Layout;
<file_sep>import React, { Component } from 'react';
import './RoomCreation.scss';
class RoomCreation extends Component {
state = {
roomName: '',
};
setRoomName = e => {
this.setState({ roomName: e.target.value });
};
onSubmit = () => {
this.props.onRoomCreation(this.state.roomName);
};
render() {
return (
<div className="NewRoom">
<label htmlFor="newRoom" className="NewRoom_label">
Create a room
</label>
<form className="NewRoom_form" onSubmit={this.onSubmit}>
<input
type="text"
id="newRoom"
required
placeholder="Room name"
onChange={this.setRoomName}
className="NewRoom_input"
/>
<button className="NewRoom_button" type="submit">
Submit
</button>
</form>
</div>
);
}
}
export default RoomCreation;
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import './Rooms.scss';
class Rooms extends Component {
state = {
rooms: [],
};
async componentDidMount() {
const res = await fetch('http://localhost:4332/rooms', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.token}`,
},
});
const { rooms } = await res.json();
this.setState({ rooms });
}
joinRoom = roomId => {
fetch(`http://localhost:4332/rooms/${roomId}/join`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.token}`,
},
}).then(() => {
this.props.history.push(`/room/${roomId}`);
});
};
render() {
return (
<ul className="Rooms">
{this.state.rooms.map(room => {
return (
<li key={room.id} className="Rooms_item">
<button
className="Rooms_button"
type="button"
onClick={() => this.joinRoom(room.id)}
>
{room.name}
</button>
</li>
);
})}
</ul>
);
}
}
const mapStateToProps = state => ({ token: state.token });
export default connect(mapStateToProps)(withRouter(Rooms));
<file_sep>import React, { Component } from 'react';
class PrivateRoom extends Component {
render() {
return(
<p>Tu reçois les messages nrml</p>
)
}
}
export default PrivateRoom;<file_sep>import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import reducer from './reducer';
const persistedReducer = persistReducer({
key: 'myreducer',
storage: storage,
}, reducer)
export default function configureStore() {
const store = createStore(persistedReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
const persistor = persistStore(store);
return { store, persistor };
}
// J'instaure la connexion au tools redux, et j'instaure le persistRedux pour garder le token lorsque je refresh <file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setToken } from '../../redux/actions';
import './SignUp.scss';
class SignUp extends Component {
state = {
username: '',
password: '',
};
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
postSignUp = event => {
event.preventDefault();
const { username, password } = this.state;
const body = JSON.stringify({ username, password });
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
fetch('http://localhost:4332/users/signup', {
method: 'POST',
headers,
body,
})
.then(res => {
if (res.status !== 200) {
throw new Error('Invalid credentials');
}
return res.json();
})
.then(() => {
return fetch('http://localhost:4332/users/signin', {
method: 'POST',
headers,
body,
});
})
.then(res => {
if (res.status !== 200) {
throw new Error('Cannot create user');
}
return res.json();
})
.then(data => {
this.props.setToken(data.token);
this.props.onSuccess(data);
})
.catch(err => console.warn(err));
};
render() {
return (
<>
<div className="sign-up_content">
<div className="sign-up_title">
<h2>Sign Up</h2>
</div>
<form className="sign-up_form" onSubmit={this.postSignUp}>
<div className="sign-up_form-element sign-up_form-username">
<input
type="text"
name="username"
required
placeholder="Username"
value={this.state.username}
onChange={this.handleChange}
></input>
</div>
<div className="sign-up_form-element sign-up_form-password">
<input
type="<PASSWORD>"
name="password"
required
placeholder="<PASSWORD>"
value={this.state.password}
onChange={this.handleChange}
></input>
</div>
<div className="sign-up_form-element sign-up_form-password">
<input
type="password"
name="confirmed_password"
required
placeholder="Confirmed password"
></input>
</div>
<div className="sign-up_button">
<button className="sign-up_submit" value="Sign Up" type="submit">
Sign Up
</button>
</div>
</form>
</div>
</>
);
}
}
const mapDispatchToProps = {
setToken: setToken,
};
export default connect(
undefined,
mapDispatchToProps,
)(SignUp);
<file_sep>const express = require('express');
const userRouter = express.Router();
const controller = require('./controller');
userRouter.post('/signin', controller.login);
userRouter.post('/signup', controller.create);
userRouter.get('/', controller.getAll);
userRouter.delete('/:id', controller.remove);
module.exports = userRouter;
<file_sep>import React, { Component } from 'react';
import SignIn from '../SignIn';
import SignUp from '../SignUp';
import { connect } from 'react-redux';
import { setToken } from '../../redux/actions';
import './Login.scss';
class Login extends Component {
componentDidMount() {
this.props.setToken(undefined)
}
onSignInSuccess = () => {
this.props.history.push('/');
}
render() {
return(
<div className="login_content">
<SignUp onSuccess={this.onSignInSuccess} setToken={setToken}/>
<SignIn onSuccess={this.onSignInSuccess} setToken={setToken}/>
</div>
)
}
}
const mapDispatchToProps = {
setToken: setToken,
}
export default connect(undefined, mapDispatchToProps)(Login); | bc8c4f5258e5f130f806e64e0578c6c88dca9cd7 | [
"JavaScript"
] | 18 | JavaScript | jennafauconnier/chat_projet-pro | 3537b507f082a5b5c5afc46a50719fc49e8c4006 | bf8de446fe7af752f6219cfcf6e2a2bb6d210695 |
refs/heads/master | <repo_name>charlychiu/google-sheets-project<file_sep>/README.md
# Google Sheets for Laravel Demo project
Demo site
https://sheets.kawax.biz/
https://docs.google.com/spreadsheets/d/1SUNw7QzAMx-xXUwr5s-mJrZC9NGFRl4RqyzSL6CogkQ/edit?usp=sharing
https://github.com/kawax/laravel-google-sheets
<file_sep>/app/Http/Controllers/Sheets/ShowController.php
<?php
namespace App\Http\Controllers\Sheets;
use App\Http\Controllers\Controller;
use Google;
use Illuminate\Http\Request;
use Sheets;
/**
* 2. sheetList.
*/
class ShowController extends Controller
{
public function __invoke(Request $request, $spreadsheet_id)
{
// Facade
// $token = $request->user()->access_token;
//
// Google::setAccessToken($token);
//
// $sheets = Sheets::setService(Google::make('sheets'))
// ->spreadsheet($spreadsheet_id)
// ->sheetList();
// GoogleSheets Trait
$sheets = $request->user()
->sheets()
->spreadsheet($spreadsheet_id)
->sheetList();
return view('sheets.show')->with(compact('spreadsheet_id', 'sheets'));
}
}
<file_sep>/tests/Feature/ExampleTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Revolution\Google\Sheets\Facades\Sheets;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
Sheets::shouldReceive('spreadsheet->sheet->get')->once()->andReturn(collect([
['id', 'name'],
['1', 'test'],
]));
$posts = collect([
[
'id' => '1',
'name' => 'test',
],
]);
Sheets::shouldReceive('collection')->once()->andReturn($posts);
$response = $this->get('/');
$response->assertStatus(200)
->assertViewHas('posts', $posts);
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'HomeController');
Route::post('post', 'PostController')->name('post.store');
//Route::name('login')->get('login', 'LoginController@redirect');
//Route::get('callback', 'LoginController@callback');
//Route::name('logout')->post('logout', 'LoginController@logout');
//
//Route::middleware('auth')->prefix('home')->namespace('Sheets')->group(function () {
// Route::name('sheets.index')->get('/', 'IndexController');
// Route::name('sheets.show')->get('/{spreadsheet_id}', 'ShowController');
// Route::name('sheets.sheet')->get('/{spreadsheet_id}/sheet/{sheet_id}', 'SheetController');
//});
<file_sep>/app/Console/Commands/ResetCommand.php
<?php
namespace App\Console\Commands;
use Faker\Factory;
use Illuminate\Console\Command;
use Revolution\Google\Sheets\Facades\Sheets;
class ResetCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sheets:reset';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Sheets::spreadsheet(config('sheets.post_spreadsheet_id'))
->sheet(config('sheets.post_sheet_id'))
->clear();
$faker = Factory::create();
$append = [];
for ($i = 1; $i <= 10; $i++) {
$append[] = [
$faker->name,
$faker->sentence,
now()->toDateTimeString(),
];
}
Sheets::append($append);
}
}
<file_sep>/app/Http/Controllers/Sheets/SheetController.php
<?php
namespace App\Http\Controllers\Sheets;
use App\Http\Controllers\Controller;
use Google;
use Illuminate\Http\Request;
use Sheets;
/**
* 3. sheet.
*/
class SheetController extends Controller
{
public function __invoke(Request $request, $spreadsheet_id, $sheet_id)
{
// Facade
// $token = $request->user()->access_token;
//
// Google::setAccessToken($token);
//
// $rows = Sheets::setService(Google::make('sheets'))
// ->spreadsheet($spreadsheet_id)
// ->sheet($sheet_id)
// ->get();
// GoogleSheets Trait
$rows = $request->user()
->sheets()
->spreadsheet($spreadsheet_id)
->sheet($sheet_id)
->get();
$headers = $rows->pull(0);
return view('sheets.sheet')->with(compact('headers', 'rows'));
}
}
<file_sep>/app/Http/Controllers/LoginController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Socialite;
class LoginController extends Controller
{
public function redirect()
{
return Socialite::driver('google')
->scopes(config('google.scopes'))
->with([
'access_type' => config('google.access_type'),
'approval_prompt' => config('google.approval_prompt'),
])
->redirect();
}
public function callback(Request $request)
{
if (! $request->has('code')) {
return redirect('/');
}
/**
* @var \Laravel\Socialite\Two\User $user
*/
$user = Socialite::driver('google')->user();
/**
* @var \App\User $loginUser
*/
$loginUser = User::updateOrCreate(
[
'email' => $user->email,
],
[
'name' => $user->name,
'email' => $user->email,
'access_token' => $user->token,
'refresh_token' => $user->refreshToken,
]);
auth()->login($loginUser, false);
return redirect('/home');
}
public function logout()
{
auth()->logout();
return redirect('/');
}
}
<file_sep>/app/Http/Controllers/Sheets/IndexController.php
<?php
namespace App\Http\Controllers\Sheets;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use PulkitJalan\Google\Facades\Google;
use Revolution\Google\Sheets\Facades\Sheets;
/**
* 1. spreadsheetList.
*/
class IndexController extends Controller
{
public function __invoke(Request $request)
{
// Facade
// $user = $request->user();
//
// $token = [
// 'access_token' => $user->access_token,
// 'refresh_token' => $user->refresh_token,
// 'expires_in' => 3600,
// 'created' => $user->updated_at->getTimestamp(),
// ];
//
// $spreadsheets = Sheets::setAccessToken($token)
// ->spreadsheetList();
// GoogleSheets Trait
$spreadsheets = $request->user()
->sheets()
->spreadsheetList();
return view('sheets.index')->with(compact('spreadsheets'));
}
}
| 3ec7f8ec3a31182696b6cb8a42426bb01e80ca0d | [
"Markdown",
"PHP"
] | 8 | Markdown | charlychiu/google-sheets-project | 17988205f6c123fc92540bad2068daf16203813e | e9aabae66dbf5236a18497c18bff5d5d9d657fce |
refs/heads/master | <repo_name>e0828330/operationManager<file_sep>/operationManager/operationManager-newsbeeper/src/main/java/newsbeeper/Main.java
package newsbeeper;
import model.Notification;
import model.dto.Message;
import model.dto.NotificationDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import service.INewsbeeperService;
import service.INotificationService;
import service.IQueueListener;
import service.IQueueService;
import config.RabbitMQConfig;
@Component
public class Main implements InitializingBean {
private Logger logger = LoggerFactory.getLogger(Main.class);
@Autowired
private IQueueService queueService;
@Autowired
private INewsbeeperService newsbeeperService;
@Autowired
private INotificationService notificationService;
private static ApplicationContext context;
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("/spring/application-config.xml");
Main prog = new Main();
AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
factory.autowireBeanProperties(prog, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
}
private void listenOnQueue() {
queueService.registerListener(RabbitMQConfig.NEWSBEEPER_Q, new IQueueListener() {
@Override
public void handleMessage(Message m) {
Notification tmp = newsbeeperService.handleNotification((NotificationDTO) m);
if (tmp != null) notificationService.save(tmp);
}
});
}
@Override
public void afterPropertiesSet() throws Exception {
logger.info("Started listening");
listenOnQueue();
}
}
<file_sep>/operationManager/operationManager-web/src/test/java/rest/TestServer.java
package rest;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import testData.DatabaseTest;
public abstract class TestServer extends DatabaseTest {
protected static Server server;
@BeforeClass
public static void startServer() throws Exception {
server = new Server(8080);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/operationManager-web");
webapp.setWar("src/main/webapp");
server.setHandler(webapp);
server.start();
}
@AfterClass
public static void stopServer() throws Exception {
server.stop();
}
}
<file_sep>/operationManager/operationManager-web/src/main/java/webGui/overview/OverviewPanel.java
package webGui.overview;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import model.OPSlot;
import model.OperationStatus;
import model.OperationType;
import model.Role;
import model.dto.OPSlotFilter;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.datetime.PatternDateConverter;
import org.apache.wicket.datetime.markup.html.basic.DateLabel;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.EnumLabel;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.EnumChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.time.Duration;
import org.springframework.data.domain.Sort;
import service.IOPSlotService;
import session.OperationManagerWebSession;
import webGui.CreateOPSlotPage;
import webGui.ReservationPage;
import com.googlecode.wicket.kendo.ui.form.datetime.DatePicker;
import com.googlecode.wicket.kendo.ui.form.datetime.TimePicker;
import com.googlecode.wicket.kendo.ui.panel.KendoFeedbackPanel;
public class OverviewPanel extends Panel {
private static final long serialVersionUID = 1L;
@SpringBean
IOPSlotService opSlotService;
private IModel<OPSlotFilter> filterModel;
private DataTable<OPSlot, String> table;
public OverviewPanel(String id) {
super(id);
filterModel = new CompoundPropertyModel<OPSlotFilter>(new OPSlotFilter());
}
@Override
protected void onInitialize() {
super.onInitialize();
final OperationManagerWebSession session = (OperationManagerWebSession) getSession();
Form<OPSlotFilter> filterForm = new Form<OPSlotFilter>("filterForm", filterModel);
final KendoFeedbackPanel feedback = new KendoFeedbackPanel("feedback");
filterForm.add(feedback);
filterForm.add(new DatePicker("date", Locale.GERMAN));
filterForm.add(new TimePicker("from", Locale.GERMAN));
filterForm.add(new TimePicker("to", Locale.GERMAN));
filterForm.add(new TextField<String>("patient").setVisible(isPatientShown(session)));
filterForm.add(new TextField<String>("hospital").setVisible(isHospitalShown(session)));
filterForm.add(new TextField<String>("doctor").setVisible(isDoctorShown(session)));
filterForm.add(new DropDownChoice<OperationType>("type", Arrays.asList(OperationType.values()),
new EnumChoiceRenderer<OperationType>(OverviewPanel.this)));
filterForm.add(new DropDownChoice<OperationStatus>("status", Arrays.asList(OperationStatus.values()),
new EnumChoiceRenderer<OperationStatus>(OverviewPanel.this)).setVisible(isStatusShown(session)));
filterForm.add(new Button("filterButton", new ResourceModel("filterButton")));
add(filterForm);
table = new DefaultDataTable<OPSlot, String>("overviewTable", getColumns(session), getDataProvider(), 10);
table.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)));
add(table);
String buttonResource = session.getActiveRole().equals(Role.DOCTOR) ? "buttonTextDoctor" : "buttonTextHospital";
add(new Link<Void>("opSlotButton") {
private static final long serialVersionUID = 1L;
@Override
public boolean isVisible() {
return session.getActiveRole().equals(Role.DOCTOR) || session.getActiveRole().equals(Role.HOSPITAL);
}
@Override
public void onClick() {
if (session.getActiveRole().equals(Role.DOCTOR)) {
setResponsePage(ReservationPage.class);
}
if (session.getActiveRole().equals(Role.HOSPITAL)) {
setResponsePage(CreateOPSlotPage.class);
}
}
}.add(new AttributeAppender("value", Model.of(getString(buttonResource)))));
}
private List<IColumn<OPSlot, String>> getColumns(final OperationManagerWebSession session) {
List<IColumn<OPSlot, String>> columns = new ArrayList<IColumn<OPSlot, String>>();
//Date
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new DateLabel(componentId, new Model<Date>(slot.getDate()), new PatternDateConverter("dd.MM.YYYY", false)));
}
@Override
protected String getColumnPropertyName() {
return "date";
}
});
//From
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new DateLabel(componentId, new Model<Date>(slot.getFrom()), new PatternDateConverter("HH:mm", false)));
}
@Override
protected String getColumnPropertyName() {
return "from";
}
});
//To
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new DateLabel(componentId, new Model<Date>(slot.getTo()), new PatternDateConverter("HH:mm", false)));
}
@Override
protected String getColumnPropertyName() {
return "to";
}
});
//Type
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new EnumLabel<OperationType>(componentId, slot.getType()));
}
@Override
protected String getColumnPropertyName() {
return "type";
}
});
//Hospital
if (isHospitalShown(session)) {
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new Label(componentId, slot.getHospital() == null ? "-" : slot.getHospital().getName()));
}
@Override
protected String getColumnPropertyName() {
return "hospital";
}
});
}
//Doctor
if (isDoctorShown(session)) {
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new Label(componentId, slot.getDoctor() == null ? "-" : slot.getDoctor().getLastName()));
}
@Override
protected String getColumnPropertyName() {
return "doctor";
}
});
}
//Patient
if (isPatientShown(session)) {
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new Label(componentId, slot.getPatient() == null ? "-" : slot.getPatient().getFirstName() + " " + slot.getPatient().getLastName()));
}
@Override
protected String getColumnPropertyName() {
return "patient";
}
});
}
//Status
if (isStatusShown(session)) {
columns.add(new OPSlotColumn() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, IModel<OPSlot> rowModel) {
OPSlot slot = rowModel.getObject();
cellItem.add(new EnumLabel<OperationStatus>(componentId, slot.getStatus()));
}
@Override
protected String getColumnPropertyName() {
return "status";
}
});
}
//remove link
if (session.getActiveRole() == Role.DOCTOR || session.getActiveRole() == Role.HOSPITAL) {
columns.add(new IColumn<OPSlot, String>() {
private static final long serialVersionUID = 1L;
@Override
public void populateItem(Item<ICellPopulator<OPSlot>> cellItem,
String componentId, final IModel<OPSlot> rowModel) {
cellItem.add(new Link<Void>(componentId) {
private static final long serialVersionUID = 1L;
@Override
protected void onComponentTag(ComponentTag tag) {
//cellItem is usually a div, so we change it to a link
tag.setName("a");
super.onComponentTag(tag);
}
@Override
public IModel<?> getBody() {
return new StringResourceModel(session.getActiveRole() == Role.DOCTOR ? "storno" : "delete", OverviewPanel.this, null, (Object[]) null);
}
@Override
public void onComponentTagBody(
MarkupStream markupStream, ComponentTag openTag) {
super.onComponentTagBody(markupStream, openTag);
}
@Override
public void onClick() {
if (session.getActiveRole().equals(Role.DOCTOR)) {
opSlotService.cancelReservation(rowModel.getObject());
}
else if (session.getActiveRole().equals(Role.HOSPITAL)) {
opSlotService.deleteOPSlot(rowModel.getObject());
}
}
});
}
@Override
public void detach() {
}
@Override
public Component getHeader(String componentId) {
//add invisible dummy container
return new WebMarkupContainer(componentId).setVisible(false);
}
@Override
public String getSortProperty() {
return null;
}
@Override
public boolean isSortable() {
return false;
}
});
}
return columns;
}
private boolean isHospitalShown(OperationManagerWebSession session) {
return session.getActiveRole() != Role.HOSPITAL;
}
private boolean isDoctorShown(OperationManagerWebSession session) {
return session.getActiveRole() != Role.DOCTOR;
}
private boolean isPatientShown(OperationManagerWebSession session) {
return session.getActiveRole() == Role.DOCTOR || session.getActiveRole() == Role.HOSPITAL;
}
private boolean isStatusShown(OperationManagerWebSession session) {
return session.getActiveRole() == Role.DEFAULT;
}
private ISortableDataProvider<OPSlot, String> getDataProvider() {
return new SortableDataProvider<OPSlot, String>() {
private static final long serialVersionUID = 1L;
OperationManagerWebSession session = (OperationManagerWebSession) getSession();
@Override
public Iterator<? extends OPSlot> iterator(long first, long count) {
SortParam<String> sortParam = getSort();
Sort sort = null;
if (sortParam != null) {
sort = new Sort(getSort().isAscending() ? Sort.Direction.ASC : Sort.Direction.DESC, getSort().getProperty());
}
return opSlotService.getOPSlots(session.getActiveUser(), sort, filterModel.getObject(), table.getCurrentPage(), table.getItemsPerPage()).iterator();
}
@Override
public IModel<OPSlot> model(OPSlot object) {
return new Model<OPSlot>(object);
}
@Override
public long size() {
return opSlotService.getOPSlotCount(session.getActiveUser(), filterModel.getObject());
}
};
}
private abstract class OPSlotColumn implements IColumn<OPSlot, String>, Serializable {
private static final long serialVersionUID = -4730014859884285134L;
protected abstract String getColumnPropertyName();
@Override
public void detach() {
}
@Override
public Component getHeader(String componentId) {
return new Label(componentId, getString(getColumnPropertyName()));
}
@Override
public String getSortProperty() {
return getColumnPropertyName();
}
@Override
public boolean isSortable() {
return true;
}
}
}
<file_sep>/operationManager/operationManager-shared/src/main/java/service/mock/MockedNotificationService.java
package service.mock;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import model.Notification;
import model.NotificationType;
import model.OperationStatus;
import model.OperationType;
import model.User;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import service.INotificationService;
@Service
public class MockedNotificationService {
@Bean
INotificationService getMockedNotificationService() {
INotificationService mock = Mockito.mock(INotificationService.class);
Mockito.when(mock.getForUser(Mockito.any(User.class))).thenAnswer(new Answer<List<Notification>>() {
@Override
public List<Notification> answer(InvocationOnMock invocation)
throws Throwable {
User user = (User) invocation.getArguments()[0];
List<Notification> list = new ArrayList<Notification>();
list.add(getMockedNotification(user, NotificationType.RESERVATION_SUCESSFULL));
list.add(getMockedNotification(user, NotificationType.RESERVATION_FAILED));
list.add(getMockedNotification(user, NotificationType.RESERVATION_DELETED));
return list;
}
});
return mock;
}
public Notification getMockedNotification(User user, NotificationType type) {
Notification notification = new Notification();
notification.setTimestamp(new Date());
notification.setRecipient(user);
notification.setSlot(MockedOPSlotService.getMockedOPSlot("1", OperationType.eye, "SMZ", "Dr. Augfehler", "Adelheid", "Abesser", OperationStatus.reserved));
notification.setMessage("notification text");
notification.setType(type);
return notification;
}
}
<file_sep>/README.md
operationManager
================
<file_sep>/operationManager/operationManager-web/src/main/java/session/OperationManagerWebSession.java
package session;
import model.Role;
import model.User;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.IAuthenticationService;
public class OperationManagerWebSession extends AuthenticatedWebSession {
private static final long serialVersionUID = 8512888632456915860L;
@SpringBean(name="getAuthenticationService")
IAuthenticationService authenticationService;
// Data for login
private Role activeRole = Role.DEFAULT;
private User activeUser = null;
// For authentication
private Roles roles = new Roles();
/**
* Returns the active roles for authentication.
* If no user is logged in, it will store DEFAULT.
* Otherwise it will consist one of the values: DOCTOR, HOSPITAL or PATIENT of Enum Role.
* @return The current authenticated Role.
*/
public Role getActiveRole() {
return this.activeRole;
}
/**
* Returns the active user for authentication.
* If no user is logged in, it will store null.
* @return The current authenticated User.
*/
public User getActiveUser() {
if (this.activeUser == null) {
this.activeUser = new User();
this.activeUser.setRole(Role.DEFAULT);
}
return this.activeUser;
}
public OperationManagerWebSession(Request request) {
super(request);
Injector.get().inject(this);
}
@Override
public boolean authenticate(String username, String password) {
// reset stored login
this.roles.clear();
this.activeRole = Role.DEFAULT;
this.activeUser = null;
// check login
this.checkLogin(username, password);
// store role
this.roles.add(this.activeRole.name());
return this.activeRole != Role.DEFAULT;
}
@Override
public Roles getRoles() {
if (this.roles.isEmpty()) {
roles.add(this.activeRole.name());
}
return roles;
}
public void logout() {
this.roles.clear();
this.activeUser = null;
this.activeRole = Role.DEFAULT;
}
private void checkLogin(String username, String password) {
this.activeUser = authenticationService.authenticate(username, password);
this.activeRole = this.activeUser.getRole();
}
}
<file_sep>/operationManager/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>operationManager</groupId>
<artifactId>operationManager</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>3.0</servlet.version>
<wicket.version>6.14.0</wicket.version>
<!-- Spring -->
<spring-framework.version>4.0.2.RELEASE</spring-framework.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
<mockito.version>1.9.0</mockito.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>provided</scope>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.5.0.RC1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.12.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<!-- CLOUD -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>cloudfoundry-connector</artifactId>
<version>0.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-service-connector</artifactId>
<version>0.9.5</version>
</dependency>
<dependency>
<groupId>org.cloudfoundry</groupId>
<artifactId>cloudfoundry-runtime</artifactId>
<version>0.8.5</version>
</dependency>
<!-- rest-assured -->
<!-- https://code.google.com/p/rest-assured/wiki/FAQ -->
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.3.1</version>
<exclusions>
<!-- Exclude Groovy because of classpath issue -->
<exclusion>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
</exclusion>
</exclusions>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<!-- Needs to be the same version that REST Assured depends on -->
<version>2.2.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>sonatype-snapshots</id>
<name>Sonatype Snapshots Repository</name>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>org.springframework.maven.milestone</id>
<name>Spring Maven Milestone Repository</name>
<url>http://repo.spring.io/milestone</url>
</repository>
<repository>
<id>opencast-public</id>
<url>http://repository.opencastproject.org/nexus/content/repositories/public/</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<modules>
<module>operationManager-shared</module>
<module>operationManager-georesolver</module>
<module>operationManager-web</module>
<module>operationManager-newsbeeper</module>
</modules>
</project>
<file_sep>/operationManager/operationManager-shared/src/main/java/cloudConfig/MongoConfig.java
package cloudConfig;
import org.bson.BSON;
import org.bson.Transformer;
import org.cloudfoundry.runtime.env.CloudEnvironment;
import org.cloudfoundry.runtime.env.MongoServiceInfo;
import org.cloudfoundry.runtime.service.document.MongoServiceCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@Configuration
@EnableMongoRepositories
public class MongoConfig {
@Bean
public MongoDbFactory mongoDbFactory() {
// Workaround for enum bug
// See: https://jira.mongodb.org/browse/JAVA-268
// And: https://jira.spring.io/browse/DATAMONGO-627
BSON.addEncodingHook(Enum.class, new Transformer() {
@Override
public Object transform(Object o) {
return o.toString();
}
});
CloudEnvironment cloudEnvironment = new CloudEnvironment();
MongoServiceInfo serviceInfo = cloudEnvironment.getServiceInfo("DB", MongoServiceInfo.class);
MongoServiceCreator serviceCreator = new MongoServiceCreator();
return serviceCreator.createService(serviceInfo);
}
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoDbFactory());
}
}
<file_sep>/operationManager/operationManager-shared/src/main/java/model/Hospital.java
package model;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;
@Data
@EqualsAndHashCode(callSuper=true)
public class Hospital extends User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
@GeoSpatialIndexed
private Point position;
}
<file_sep>/operationManager/operationManager-newsbeeper/src/main/java/service/real/NewsbeeperService.java
package service.real;
import java.util.Date;
import model.Doctor;
import model.Hospital;
import model.Notification;
import model.OPSlot;
import model.Patient;
import model.User;
import model.dto.NotificationDTO;
import newsbeeper.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.DoctorRepository;
import repository.HospitalRepository;
import service.INewsbeeperService;
import service.IOPSlotService;
import service.IPatientService;
@Service
public class NewsbeeperService implements INewsbeeperService {
private Logger logger = LoggerFactory.getLogger(NewsbeeperService.class);
@Autowired
private DoctorRepository repoD;
@Autowired
private HospitalRepository repoH;
@Autowired
private IPatientService patientService;
@Autowired
private IOPSlotService opSlotService;
@Override
public Doctor getDoctorById(String id) {
return repoD.findOne(id);
}
@Override
public Hospital getHospitalById(String id) {
return repoH.findOne(id);
}
@Override
public Notification handleNotification(NotificationDTO notificationDTO) {
if (notificationDTO == null) return null;
if (notificationDTO.getRecipientID() == null) {
return null;
}
try {
Notification notification = new Notification();
notification.setMessage(notificationDTO.getMessage());
notification.setType(notificationDTO.getType());
logger.info("Got request: " + notificationDTO);
Patient patient = patientService.getById(notificationDTO.getRecipientID());
OPSlot slot = notificationDTO.getOpSlotID() == null ? null : opSlotService.getById(notificationDTO.getOpSlotID());
if (patient != null) {
notification.setRecipient((User) patient);
} else {
Doctor doctor = getDoctorById(notificationDTO.getRecipientID());
if (doctor != null) {
notification.setRecipient((User) doctor);
} else {
Hospital hospital = getHospitalById(notificationDTO.getRecipientID());
if (hospital != null) {
notification.setRecipient((User) hospital);
} else {
logger.info("No User found with id = " + notificationDTO.getRecipientID());
return null;
}
}
}
if (slot == null) {
logger.info("No slot found.");
}
notification.setSlot(slot);
notification.setTimestamp(new Date());
return notification;
} catch (Exception e) {
logger.error("Failed to handle message", e);
}
return null;
}
}
<file_sep>/operationManager/operationManager-web/src/main/java/webGui/ReservationPage.properties
patient=Patient
type=Typ
from=von
to=bis
distance=Distanz (km)
save=Speichern
timeValidationError=Ende des Zeitraums darf nicht vor dem Beginn des Zeitraums sein.
pastTimeValidationError=Datum darf nicht in der Vergangenheit liegen.
OperationType.eye=Augen
OperationType.ortho=Ortho
OperationType.cardio=Kardio
OperationType.hno=HNO
OperationType.neuro=NEURO<file_sep>/operationManager/operationManager-web/src/main/java/service/IAuthenticationService.java
package service;
import model.User;
public interface IAuthenticationService {
public User authenticate(String username, String password);
}
<file_sep>/operationManager/operationManager-shared/src/main/java/repository/impl/OPSlotRepositoryImpl.java
package repository.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import model.OPSlot;
import model.OperationStatus;
import model.OperationType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import repository.OPSlotRepositoryCustom;
public class OPSlotRepositoryImpl implements OPSlotRepositoryCustom {
@Autowired
private MongoTemplate template;
@Override
public OPSlot findBestInRange(Point point, Distance distance, OperationType type, Date from, Date to) {
/* Filter date, type and status */
Query query = new Query();
Criteria queryCriteria = new Criteria().andOperator(Criteria.where("type").is(OperationType.values()[type.ordinal()]),
Criteria.where("status").is(OperationStatus.values()[OperationStatus.free.ordinal()]),
Criteria.where("date").gte(from).lte(to));
query.addCriteria(queryCriteria);
/* Do the geo query */
NearQuery nearQuery = NearQuery.near(point).spherical(true).maxDistance(distance).query(query);
GeoResults<OPSlot> rawResults = ((MongoOperations) template).geoNear(nearQuery, OPSlot.class);
/* No results -> return null */
if (rawResults.getContent().size() == 0) {
return null;
}
/* Sort results by date if they have the same distance */
List<GeoResult<OPSlot>> results = new ArrayList<>(rawResults.getContent());
Collections.sort(results, new Comparator<GeoResult<OPSlot>>() {
@Override
public int compare(GeoResult<OPSlot> s1, GeoResult<OPSlot> s2) {
int distanceDiff = Double.compare(s1.getDistance().getValue(), s2.getDistance().getValue());
if (distanceDiff == 0) {
return s1.getContent().getFrom().compareTo(s2.getContent().getFrom());
}
else {
return distanceDiff;
}
}
});
/* Return the best (i.e first) result */
return results.get(0).getContent();
}
}
<file_sep>/operationManager/operationManager-shared/src/main/java/service/IQueueService.java
package service;
import model.dto.NotificationDTO;
import model.dto.OPSlotDTO;
public interface IQueueService {
/**
* Sends the OPSlot data to the georesolver queue
*
* @param slot
*/
public void sendToGeoResolver(OPSlotDTO slot);
/**
* Sends the resulting opslot to the newsbeeper queue
*
* @param slot
*/
public void sendToNewsBeeper(NotificationDTO notification);
/**
* Registers an async listener which receives messages from the queue
*
* @param queueName
* @param listener
*/
public void registerListener(String queueName, IQueueListener listener);
/**
* Unregisters an async listener which receives messages from the queue
*
* @param queueName
* @param listener
*/
public void unregisterListener(String queueName, IQueueListener listener);
}
<file_sep>/operationManager/operationManager-shared/src/main/java/repository/HospitalRepository.java
package repository;
import model.Hospital;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface HospitalRepository extends MongoRepository<Hospital, String> {
public Hospital findByUsernameAndPassword(String username, String password);
}
<file_sep>/build_and_deploy.sh
#!/bin/bash
pushd operationManager
# Clean shared jar
pushd operationManager-shared
mvn clean
popd
# Build code, run test and install shared component
mvn install || { echo -e "\e[1mFailure at install not deploying." ; tput sgr0 ; exit 1; }
# georesolver
pushd operationManager-georesolver
mvn cf:push -DskipTests
popd
# newsbeeper
pushd operationManager-newsbeeper
mvn cf:push -DskipTests
popd
# web
pushd operationManager-web
mvn cf:push -DskipTests
popd
popd
<file_sep>/operationManager/operationManager-shared/src/main/java/model/User.java
package model;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import lombok.Data;
@Data
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7357377694702848930L;
@Id
private String id;
private String username;
private String password;
protected Role role;
}
<file_sep>/operationManager/operationManager-shared/src/main/java/service/IQueueListener.java
package service;
import model.dto.Message;
public interface IQueueListener {
/**
* Called when a new message arrives at the queue
*
* @param slot
*/
public void handleMessage(Message m);
}
<file_sep>/operationManager/operationManager-web/src/test/java/service/AuthServiceTest.java
package service;
import static org.junit.Assert.assertEquals;
import model.Role;
import model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import testData.DatabaseTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/application-config.xml" })
public class AuthServiceTest extends DatabaseTest {
@Autowired
@Qualifier("getAuthenticationService")
private IAuthenticationService service;
@Test
public void testLogin_correct_patient_credentials() {
User user = service.authenticate("abesser", "<PASSWORD>");
assertEquals(Role.PATIENT, user.getRole());
}
@Test
public void testLogin_correct_doctor_credentials() {
User user = service.authenticate("maria", "<PASSWORD>09");
assertEquals(Role.DOCTOR, user.getRole());
}
@Test
public void testLogin_correct_hospital_credentials() {
User user = service.authenticate("lkhbaden", "<PASSWORD>12");
assertEquals(Role.HOSPITAL, user.getRole());
}
@Test
public void testLogin_wrong_credentials() {
User user = service.authenticate("wrong", "wrong");
assertEquals(Role.DEFAULT, user.getRole());
}
}
<file_sep>/operationManager/operationManager-web/src/test/java/rest/LoadTest.java
package rest;
import static com.jayway.restassured.RestAssured.given;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import model.OperationType;
import model.dto.RestPatientDTO;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class LoadTest {
private final int numberOfRequests = 1024;
/**
* Should point to web instance in the format
* http://host:PORT/path
* when no host / port are given it defaults to localhost:8080
*/
//private final String baseURL = "operationManager-web";
private final String baseURL = "http://operationmanager-web.cfapps.io:80";
private List<RestPatientDTO> getPatients() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
String json = given().param("username", "maria").param("password", "<PASSWORD>").get(baseURL + "/rest/getPatients/").asString();
List<RestPatientDTO> result = mapper.readValue(json, new TypeReference<List<RestPatientDTO>>() {});
return result;
}
private class ReservationWorker implements Runnable {
private String patientId;
private String operationType;
public ReservationWorker(String patientId, String operationType) {
this.patientId = patientId;
this.operationType = operationType;
}
@Override
/***
* Worker thread, sends the request
*/
public void run() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
given().param("username", "maria").
param("password", "<PASSWORD>").
param("patientId", patientId).
param("operationType", operationType).
param("from", dateFormat.format(new Date())).
param("to", "01.01.2016").
param("distance", "150").
post(baseURL + "/rest/reserveOPSlot/");
}
}
@Test
/**
* Flood rest service with reservation requests
*
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
* @throws InterruptedException
*/
public void loadTest() throws JsonParseException, JsonMappingException, IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
List<RestPatientDTO> patients = getPatients();
for (int i = 0; i < numberOfRequests; i++) {
RestPatientDTO p = patients.get(i % patients.size());
String type = OperationType.values()[i % OperationType.values().length].toString();
executor.execute(new ReservationWorker(p.getId(), type));
}
executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
}
}
<file_sep>/operationManager/operationManager-shared/src/test/java/testData/DatabaseTest.java
package testData;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import model.Doctor;
import model.Hospital;
import model.OPSlot;
import model.OperationStatus;
import model.OperationType;
import model.Patient;
import model.Role;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import repository.DoctorRepository;
import repository.HospitalRepository;
import repository.NotificationRepository;
import repository.OPSlotRepository;
import repository.PatientRepository;
import utils.Utils;
public class DatabaseTest {
@Autowired
protected PatientRepository patientRepo;
@Autowired
protected HospitalRepository hsRepo;
@Autowired
protected OPSlotRepository opSlotRepo;
@Autowired
protected DoctorRepository doctorRepo;
@Autowired
protected NotificationRepository notifRepo;
/**
* Adds some empty slots for a given hospital
*
* @param hospital
*/
protected void fillinSlots(Hospital hospital) {
Calendar calDate = Calendar.getInstance();
calDate.setTime(new Date());
calDate.set(Calendar.HOUR_OF_DAY, 0);
calDate.set(Calendar.MINUTE, 0);
calDate.add(Calendar.DATE, 45);
for (int i = 0; i < 7; i ++) {
Calendar calFrom = Calendar.getInstance();
calFrom.setTime(calDate.getTime());
Calendar calTo = Calendar.getInstance();
calTo.setTime(calDate.getTime());
for (int j = 8; j <= 20; j+=2) {
calFrom.add(Calendar.HOUR_OF_DAY, j);
calTo.add(Calendar.HOUR_OF_DAY, j + 2);
OPSlot slot = new OPSlot();
slot.setDate(calDate.getTime());
slot.setFrom(calFrom.getTime());
slot.setTo(calTo.getTime());
slot.setHospital(hospital);
slot.setStatus(OperationStatus.free);
slot.setType(OperationType.values()[i * j % OperationType.values().length]);
opSlotRepo.save(slot);
}
calDate.add(Calendar.DATE, 1);
}
}
@Before
public void generateTestDB() throws NoSuchAlgorithmException {
cleanDataBase();
// Patients
Patient p = new Patient();
p.setFirstName("Adelheid");
p.setLastName("Abesser");
p.setUsername("abesser");
p.setPassword(Utils.computeHash("<PASSWORD>"));
p.setRole(Role.PATIENT);
p.setPosition(new Point(48.2065, 16.384821));
patientRepo.save(p);
p = new Patient();
p.setFirstName("Peter");
p.setLastName("Berger");
p.setUsername("berger");
p.setPassword(Utils.computeHash("<PASSWORD>"));
p.setRole(Role.PATIENT);
p.setPosition(new Point(48.2065, 16.384821));
patientRepo.save(p);
p = new Patient();
p.setFirstName("Beatrix");
p.setLastName("Bauer");
p.setUsername("bauer");
p.setPassword(Utils.computeHash("<PASSWORD>"));
p.setRole(Role.PATIENT);
p.setPosition(new Point(48.2065, 16.384821));
patientRepo.save(p);
p = new Patient();
p.setFirstName("Franz");
p.setLastName("Fiedler");
p.setUsername("franz");
p.setPassword(Utils.computeHash("<PASSWORD>"));
p.setRole(Role.PATIENT);
p.setPosition(new Point(48.2065, 16.384821));
patientRepo.save(p);
p = new Patient();
p.setFirstName("Gloria");
p.setLastName("Geraus");
p.setUsername("geraus");
p.setPassword(Utils.computeHash("test05"));
p.setRole(Role.PATIENT);
p.setPosition(new Point(48.2065, 16.384821));
patientRepo.save(p);
p = new Patient();
p.setFirstName("Manfred");
p.setLastName("Takacs");
p.setUsername("takacs");
p.setPassword(Utils.computeHash("test06"));
p.setRole(Role.PATIENT);
p.setPosition(new Point(48.2065, 16.384821));
patientRepo.save(p);
// Doctors
Doctor d = new Doctor();
d.setFirstName("Albert");
d.setLastName("Aufschneider");
d.setUsername("albert");
d.setPassword(Utils.computeHash("test07"));
d.setRole(Role.DOCTOR);
doctorRepo.save(d);
d = new Doctor();
d.setFirstName("Emily");
d.setLastName("Ehmoser");
d.setUsername("emily");
d.setPassword(Utils.computeHash("test08"));
d.setRole(Role.DOCTOR);
doctorRepo.save(d);
d = new Doctor();
d.setFirstName("Adam");
d.setLastName("Augefehler");
d.setUsername("adam");
d.setPassword(Utils.computeHash("test08"));
d.setRole(Role.DOCTOR);
doctorRepo.save(d);
d = new Doctor();
d.setFirstName("Maria");
d.setLastName("Morks");
d.setUsername("maria");
d.setPassword(Utils.computeHash("test09"));
d.setRole(Role.DOCTOR);
doctorRepo.save(d);
// Hospitals
Hospital h = new Hospital();
h.setName("<NAME>");
h.setUsername("smzost");
h.setPassword(Utils.computeHash("<PASSWORD>"));
h.setRole(Role.HOSPITAL);
h.setPosition(new Point(48.219218, 16.464200));
hsRepo.save(h);
fillinSlots(h);
h = new Hospital();
h.setName("<NAME>");
h.setUsername("lkhkrems");
h.setPassword(Utils.computeHash("<PASSWORD>"));
h.setRole(Role.HOSPITAL);
h.setPosition(new Point(48.412252, 15.614987));
hsRepo.save(h);
fillinSlots(h);
h = new Hospital();
h.setName("<NAME>");
h.setUsername("lkhbaden");
h.setPassword(Utils.computeHash("<PASSWORD>"));
h.setRole(Role.HOSPITAL);
h.setPosition(new Point(48.000463, 16.254158));
hsRepo.save(h);
fillinSlots(h);
h = new Hospital();
h.setName("Rudolfinerhaus");
h.setUsername("rudolfinerhaus");
h.setPassword(Utils.computeHash("<PASSWORD>"));
h.setRole(Role.HOSPITAL);
h.setPosition(new Point(48.243323, 16.347580));
hsRepo.save(h);
fillinSlots(h);
}
protected void cleanDataBase() {
patientRepo.deleteAll();
doctorRepo.deleteAll();
hsRepo.deleteAll();
opSlotRepo.deleteAll();
notifRepo.deleteAll();
}
}
<file_sep>/operationManager/operationManager-shared/src/main/java/model/dto/OPSlotDTO.java
package model.dto;
import java.util.Date;
import lombok.Data;
import lombok.EqualsAndHashCode;
import model.OperationType;
@Data
@EqualsAndHashCode(callSuper=true)
public class OPSlotDTO extends Message {
private static final long serialVersionUID = 1L;
private String doctorID;
private String patientID;
private Date from;
private Date to;
private OperationType type;
private int distance;
}
<file_sep>/operationManager/operationManager-georesolver/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>operationManager</groupId>
<artifactId>operationManager</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>operationManager-georesolver</groupId>
<artifactId>operationManager-georesolver</artifactId>
<dependencies>
<dependency>
<groupId>operationManager-shared</groupId>
<artifactId>operationManager-shared</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>operationManager-shared</groupId>
<artifactId>operationManager-shared</artifactId>
<version>0.0.1-SNAPSHOT</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>WebContent\WEB-INF\web.xml</webXml>
</configuration>
</plugin>
<plugin>
<groupId>org.cloudfoundry</groupId>
<artifactId>cf-maven-plugin</artifactId>
<version>1.0.2</version>
<configuration>
<server>operationManager</server>
<target>https://api.run.pivotal.io</target>
<org>operationManager</org>
<space>development</space>
<appname>operationManager-georesolver</appname>
<memory>512</memory>
<instances>2</instances>
<services>
<service>
<name>DB</name>
</service>
<service>
<name>MoM</name>
</service>
</services>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/operationManager/operationManager-shared/src/main/java/service/IPatientService.java
package service;
import java.util.List;
import model.Patient;
public interface IPatientService {
/**
* Returns the patient with the given id
*
* @param id
* @return
*/
public Patient getById(String id);
/**
* Returns the list of patients
*
* @return
*/
public List<Patient> getPatients();
/**
* Returns the list of patients for a given keyword
* (searches first and lastname)
*
* The case is not case sensitve
*
* @return
*/
public List<Patient> getPatients(String search);
}
<file_sep>/operationManager/operationManager-web/src/main/java/webGui/ReservationPage.java
package webGui;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import model.Doctor;
import model.OperationType;
import model.Patient;
import model.dto.OPSlotDTO;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.EnumChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.IOPSlotService;
import service.IPatientService;
import session.OperationManagerWebSession;
import com.googlecode.wicket.kendo.ui.form.datetime.DatePicker;
@AuthorizeInstantiation(value = {"DOCTOR"})
public class ReservationPage extends IndexPage {
private static final long serialVersionUID = 1L;
@SpringBean
IPatientService patientService;
@SpringBean
IOPSlotService opSlotService;
public ReservationPage(PageParameters parameters) {
super(parameters);
}
@Override
protected void onInitialize() {
super.onInitialize();
OperationManagerWebSession session = (OperationManagerWebSession) WebSession.get();
Doctor doctor = (Doctor) session.getActiveUser();
OPSlotDTO slot = new OPSlotDTO();
//set fixed/standard values
slot.setDoctorID(doctor.getId());
slot.setDistance(12);
final Model<OPSlotDTO> model = new Model<OPSlotDTO>(slot);
LoadableDetachableModel<List<Patient>> patientsModel = new LoadableDetachableModel<List<Patient>>() {
private static final long serialVersionUID = 1L;
@Override
protected List<Patient> load() {
return patientService.getPatients();
}
};
//The dropdownchoice works with Patient objects, but in the dto we only save the string, so we need a special model for that.
IModel<Patient> patientModel = new IModel<Patient>() {
private static final long serialVersionUID = 1L;
@Override
public void detach() {
}
@Override
public Patient getObject() {
return patientService.getById(model.getObject().getPatientID());
}
@Override
public void setObject(Patient object) {
model.getObject().setPatientID(object.getId());
}
};
add(new FeedbackPanel("feedback"));
Form<OPSlotDTO> form = new Form<OPSlotDTO>("form", new CompoundPropertyModel<OPSlotDTO>(model)) {
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit() {
opSlotService.reserveOPSlot(model.getObject());
setResponsePage(StartPage.class);
}
};
final DatePicker from = new DatePicker("from", Locale.GERMAN);
final DatePicker to = new DatePicker("to", Locale.GERMAN);
form.add(new DropDownChoice<Patient>("patient", patientModel, patientsModel, new IChoiceRenderer<Patient>() {
private static final long serialVersionUID = 1L;
@Override
public Object getDisplayValue(Patient object) {
return object.getFirstName() + " " + object.getLastName();
}
@Override
public String getIdValue(Patient object, int index) {
return object.getId();
}
}).setRequired(true));
form.add(new DropDownChoice<OperationType>("type", Arrays.asList(OperationType.values()),
new EnumChoiceRenderer<OperationType>(ReservationPage.this)).setRequired(true));
form.add(from.setRequired(true));
form.add(to.setRequired(true));
form.add(new TextField<Integer>("distance"));
form.add(new SubmitLink("save"));
form.add(new AbstractFormValidator() {
private static final long serialVersionUID = 1L;
@Override
public FormComponent<?>[] getDependentFormComponents() {
return new FormComponent<?>[] { from, to };
}
@Override
public void validate(Form<?> form) {
if (to.getConvertedInput().before(from.getConvertedInput())) {
form.error(getString("timeValidationError"));
}
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
if (from.getConvertedInput().before(today.getTime()) || to.getConvertedInput().before(today.getTime())) {
form.error(getString("pastTimeValidationError"));
}
}
});
add(form);
}
}
<file_sep>/operationManager/operationManager-shared/src/main/java/service/real/OPSlotService.java
package service.real;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import lombok.Data;
import model.Doctor;
import model.Hospital;
import model.NotificationType;
import model.OPSlot;
import model.OperationStatus;
import model.Patient;
import model.User;
import model.dto.NotificationDTO;
import model.dto.OPSlotDTO;
import model.dto.OPSlotFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import repository.OPSlotRepository;
import service.IOPSlotService;
import service.IQueueService;
@Service
public class OPSlotService implements IOPSlotService {
@Autowired
private OPSlotRepository repo;
@Autowired
private IQueueService queueService;
@Data
/**
* Used to avoid having to duplicate the param parsing
*/
private class FilterParams {
private String patient;
private String hospital;
private String doctor;
private String status;
private String type;
private String dateMin;
private String dateMax;
private Integer fromMinute;
private Integer toMinute;
public FilterParams(OPSlotFilter filter) {
status = "";
type = "";
if (filter.getPatient() == null) {
setPatient("");
} else {
setPatient(filter.getPatient());
}
if (filter.getHospital() == null) {
setHospital("");
} else {
setHospital(filter.getHospital());
}
if (filter.getDoctor() == null) {
setDoctor("");
} else {
setDoctor(filter.getDoctor());
}
if (filter.getStatus() != null) {
status = filter.getStatus().name();
}
if (filter.getType() != null) {
type = filter.getType().name();
}
// Handle dates
Calendar cal = Calendar.getInstance();
if (filter.getDate() != null) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
setDateMin(df.format(filter.getDate()));
cal.setTime(filter.getDate());
cal.add(Calendar.DATE, 1);
setDateMax(df.format(cal.getTime()));
}
// Convert time to number of minutes
if (filter.getFrom() != null) {
cal.setTime(filter.getFrom());
setFromMinute(cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE));
}
// Convert time to number of minutes
if (filter.getTo() != null) {
cal.setTime(filter.getTo());
setToMinute(cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE));
}
}
}
@Override
public List<OPSlot> getOPSlots(User user, Sort sort, OPSlotFilter filter, long page, long itemsPerPage) {
FilterParams filterParams = new FilterParams(filter);
/* Sort and paging */
PageRequest pager;
if (sort != null) {
pager = new PageRequest((int) page, (int) itemsPerPage, sort);
} else {
pager = new PageRequest((int) page, (int) itemsPerPage);
}
List<OPSlot> result = null;
/* Call the correct method based on the user's role */
switch (user.getRole()) {
case DEFAULT:
result = (List<OPSlot>) repo.findByFilter(filterParams.getHospital(), filterParams.getDoctor(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute(), pager);
break;
case PATIENT:
result = (List<OPSlot>) repo.findByFilterForPatient(((Patient) user).getId(), filterParams.getHospital(), filterParams.getDoctor(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute(), pager);
break;
case DOCTOR:
result = (List<OPSlot>) repo.findByFilterForDoctor(((Doctor) user).getId(), filterParams.getPatient(), filterParams.getHospital(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute(), pager);
break;
case HOSPITAL:
result = (List<OPSlot>) repo.findByFilterForHospital(((Hospital) user).getId(), filterParams.getPatient(), filterParams.getDoctor(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute(), pager);
}
return result;
}
@Override
public long getOPSlotCount(User user, OPSlotFilter filter) {
FilterParams filterParams = new FilterParams(filter);
long result = 0;
/* Call the correct method based on the user's role */
switch (user.getRole()) {
case DEFAULT:
result = repo.countByFilter(filterParams.getHospital(), filterParams.getDoctor(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute());
break;
case PATIENT:
result = repo.countByFilterForPatient(((Patient) user).getId(), filterParams.getHospital(), filterParams.getDoctor(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute());
break;
case DOCTOR:
result = repo.countByFilterForDoctor(((Doctor) user).getId(), filterParams.getPatient(), filterParams.getHospital(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute());
break;
case HOSPITAL:
result = repo.countByFilterForHospital(((Hospital) user).getId(), filterParams.getPatient(), filterParams.getDoctor(), filterParams.getStatus(), filterParams.getType(),
filterParams.getDateMin(), filterParams.getDateMax(), filterParams.getFromMinute(), filterParams.getToMinute());
}
return result;
}
@Override
public void saveOPSlot(OPSlot slot) {
repo.save(slot);
}
@Override
public void reserveOPSlot(OPSlotDTO slot) {
queueService.sendToGeoResolver(slot);
}
@Override
public void deleteOPSlot(OPSlot slot) {
repo.delete(slot);
}
@Override
public void cancelReservation(OPSlot slot) {
NotificationDTO notification = new NotificationDTO();
notification.setOpSlotID(slot.getId());
notification.setRecipientID(slot.getDoctor().getId());
notification.setType(NotificationType.RESERVATION_DELETED);
notification.setMessage("Reservierung stoniert");
queueService.sendToNewsBeeper(notification);
notification.setRecipientID(slot.getPatient().getId());
queueService.sendToNewsBeeper(notification);
notification.setRecipientID(slot.getHospital().getId());
queueService.sendToNewsBeeper(notification);
slot.setDoctor(null);
slot.setPatient(null);
slot.setStatus(OperationStatus.free);
repo.save(slot);
}
@Override
public OPSlot getById(String id) {
return repo.findOne(id);
}
}
<file_sep>/operationManager/operationManager-web/src/main/java/webGui/CreateOPSlotPage.properties
type=Typ
date=Datum
from=von
to=bis
save=Speichern
timeValidationError=Startzeitpunkt des OP-Slots muss vor dem Endzeitpunkt sein.
OperationType.eye=Augen
OperationType.ortho=Ortho
OperationType.cardio=Kardio
OperationType.hno=HNO
OperationType.neuro=NEURO<file_sep>/operationManager/operationManager-web/src/main/java/webGui/notification/NotificationsPage.properties
emptyList=Es sind keine Notifications verfügbar
RESERVATION_SUCESSFULL = ✓ (OK)
RESERVATION_FAILED = ⚠ (Fehlgeschlagen)
RESERVATION_DELETED = ✗ (Storniert)<file_sep>/operationManager/operationManager-shared/src/main/java/service/IOPSlotService.java
package service;
import java.util.List;
import model.OPSlot;
import model.User;
import model.dto.OPSlotDTO;
import model.dto.OPSlotFilter;
import org.springframework.data.domain.Sort;
public interface IOPSlotService {
/**
* returns a list of OP slots
*
* @param user the current user
* @param sort the sort parameter
* @param filter a filter object to narrow the results
* @param page the page of results to display
* @param itemsPerPage the number of elements to include in a page
* @return
*/
public List<OPSlot> getOPSlots(User user, Sort sort, OPSlotFilter filter, long page, long itemsPerPage);
/**
* returns the number of found OP slots
*
* @param user the current user
* @param filter a filter object to narrow the results
* @return
*/
public long getOPSlotCount(User user, OPSlotFilter filter);
/**
* Saves the passed in OP slot
* @param slot
*/
public void saveOPSlot(OPSlot slot);
/**
* Sends the given slot to the georesolver queue for reservation
*
* @param slot
*/
public void reserveOPSlot(OPSlotDTO slot);
/**
* Deletes the given slot from the database
* @param slot
*/
public void deleteOPSlot(OPSlot slot);
/**
* Cancels a reservation for the given slot
*
* @param slot
*/
public void cancelReservation(OPSlot slot);
/**
* Returns a slot that has the given id
*
* @param id
* @return
*/
public OPSlot getById(String id);
}
<file_sep>/operationManager/operationManager-web/src/main/java/model/dto/RestPatientDTO.java
package model.dto;
import java.io.Serializable;
import lombok.Data;
import model.Patient;
@Data
public class RestPatientDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8523849840056533437L;
private String id;
private String firstName;
private String lastName;
public RestPatientDTO() {
}
public RestPatientDTO(Patient patient) {
id = patient.getId();
firstName = patient.getFirstName();
lastName = patient.getLastName();
}
}
<file_sep>/operationManager/operationManager-shared/src/main/java/service/real/PatientService.java
package service.real;
import java.util.List;
import model.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import repository.PatientRepository;
import service.IPatientService;
@Service
public class PatientService implements IPatientService {
@Autowired
private PatientRepository patientRepo;
@Override
public List<Patient> getPatients() {
return patientRepo.findAll();
}
@Override
public List<Patient> getPatients(String keyword) {
return patientRepo.findByKeyword(keyword);
}
@Override
public Patient getById(String id) {
return id == null ? null: patientRepo.findOne(id);
}
}
<file_sep>/operationManager/operationManager-georesolver/src/main/java/service/IGeoResolverService.java
package service;
import service.exceptions.ServiceException;
import model.OPSlot;
import model.dto.OPSlotDTO;
public interface IGeoResolverService {
/**
* Finds a free slot in the database that matches the given params
* passed in via the opslot dto object
*
* @param params
* @return
* @throws ServiceException
*/
public OPSlot findSlot(OPSlotDTO params) throws ServiceException;
}
<file_sep>/operationManager/operationManager-web/src/test/java/webGui/AbstractBaseTest.java
package webGui;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.apache.wicket.util.tester.WicketTester;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/test-config.xml"})
public class AbstractBaseTest {
protected WicketTester tester;
@Autowired
private ApplicationContext applicationContext;
@Before
public void init() {
tester = new WicketTester(new WicketApplication() {
@Override
protected void setUpInjector() {
this.getComponentInstantiationListeners().add(
new SpringComponentInjector(this,
applicationContext));
}
});
}
}
<file_sep>/operationManager/operationManager-web/src/main/java/service/real/AuthenticationService.java
package service.real;
import java.security.NoSuchAlgorithmException;
import model.Doctor;
import model.Hospital;
import model.Patient;
import model.Role;
import model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import repository.DoctorRepository;
import repository.HospitalRepository;
import repository.PatientRepository;
import service.IAuthenticationService;
import utils.Utils;
@Service
public class AuthenticationService implements IAuthenticationService {
@Autowired
private PatientRepository patientRepo;
@Autowired
private HospitalRepository hsRepo;
@Autowired
private DoctorRepository doctorRepo;
@Bean
static IAuthenticationService getAuthenticationService() {
return new AuthenticationService();
}
@Override
public User authenticate(String username, String password) {
User noAuth = new User();
noAuth.setRole(Role.DEFAULT);
try {
// First look for patient
Patient patient = this.patientRepo.findByUsernameAndPassword(username, Utils.computeHash(password));
if (patient != null && patient.getRole() != null) {
return (User)patient;
}
// Look for doctor
Doctor doctor = this.doctorRepo.findByUsernameAndPassword(username, Utils.computeHash(password));
if (doctor != null && doctor.getRole() != null) {
return (User)doctor;
}
// Look for hospital
Hospital hospital = this.hsRepo.findByUsernameAndPassword(username, Utils.computeHash(password));
if (hospital != null && hospital.getRole() != null) {
hospital.setPosition(null);
return (User)hospital;
}
} catch (NoSuchAlgorithmException e) {
return noAuth;
}
return noAuth;
}
}<file_sep>/operationManager/operationManager-newsbeeper/src/main/java/service/INewsbeeperService.java
package service;
import model.Doctor;
import model.Hospital;
import model.Notification;
import model.dto.NotificationDTO;
public interface INewsbeeperService {
/**
* Get a doctor with the identification @id
*
* @param id The id of the doctor
* @return Returns the Doctor object or null if not found
*/
public Doctor getDoctorById(String id);
/**
* Get a hospital with the identification @id
*
* @param id The id of the hospital
* @return Returns the Hospital object or null if not found
*/
public Hospital getHospitalById(String id);
/**
* Handles the notification for doctors, patients, hospitals
* @param dto
* @return
*/
public Notification handleNotification(NotificationDTO dto);
}
<file_sep>/operationManager/operationManager-web/src/test/java/webGui/TestCreateOPSlotPage.java
package webGui;
import model.OPSlot;
import org.apache.wicket.Session;
import org.apache.wicket.util.tester.FormTester;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import service.IOPSlotService;
import session.OperationManagerWebSession;
public class TestCreateOPSlotPage extends AbstractBaseTest {
@Autowired
IOPSlotService opSlotService;
@Test
public void test_access_right() {
tester.startPage(CreateOPSlotPage.class);
//default user is not allowed to view this page, so there should be a redirect to the start page
tester.assertRenderedPage(StartPage.class);
}
@Test
public void test_save_button() {
OperationManagerWebSession session = (OperationManagerWebSession)Session.get();
session.authenticate("hospital", "a");
tester.startPage(CreateOPSlotPage.class);
tester.assertRenderedPage(CreateOPSlotPage.class);
FormTester formTester = tester.newFormTester("form");
formTester.select("type", 0);
formTester.setValue("date", DateTimeFormat.forPattern("dd.MM.YY").print(new DateTime().plusDays(1)));
formTester.setValue("from", DateTimeFormat.forPattern("HH:mm").print(new DateTime()));
formTester.setValue("to", DateTimeFormat.forPattern("HH:mm").print(new DateTime().plusHours(1)));
formTester.submit();
Mockito.verify(opSlotService).saveOPSlot(Mockito.any(OPSlot.class));
tester.assertRenderedPage(StartPage.class);
}
}
<file_sep>/operationManager/operationManager-web/src/main/java/webGui/IndexPage.java
package webGui;
import model.Doctor;
import model.Hospital;
import model.Patient;
import model.Role;
import model.User;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import session.OperationManagerWebSession;
import utils.TemplateConstants;
import webGui.notification.NotificationsPage;
public class IndexPage extends WebPage {
private static final long serialVersionUID = -4448644188854079942L;
private String defaultTitle = "Startpage OperationsManager";
public IndexPage(final PageParameters parameters) {
final OperationManagerWebSession session = (OperationManagerWebSession) WebSession.get();
if (parameters != null && !parameters.isEmpty() && !parameters.get("authenticated").isEmpty()) {
if (parameters.get("authenticated").toString().equals("success")) {
add(new Label("authentication_failure").setVisible(false));
}
else {
add(new Label("authentication_failure", "Login fehlgeschlagen!").setVisible(true));
}
}
else {
add(new Label("authentication_failure").setVisible(false));
}
// Login form
CompoundPropertyModel<User> loginModel = new CompoundPropertyModel<User>(new User());
Form<User> loginForm = new Form<User>(TemplateConstants.LOGIN_FORM, loginModel) {
private static final long serialVersionUID = 1L;
protected void onSubmit() {
User user = getModelObject();
PageParameters pageParameters = new PageParameters();
pageParameters.add("authenticated", !session.authenticate(user.getUsername(), user.getPassword()) ? "failure" : "success");
setResponsePage(StartPage.class, pageParameters);
};
};
loginForm.add(new TextField<String>("username"));
loginForm.add( new PasswordTextField("<PASSWORD>"));
// Logout form
Form<?> logoutForm = new Form<Void>(TemplateConstants.LOGOUT_FORM) {
private static final long serialVersionUID = 1L;
protected void onSubmit() {
session.logout();
setResponsePage(StartPage.class);
};
};
// If logged in, hide login form
if (!session.getActiveUser().getRole().equals(Role.DEFAULT)) {
loginForm.setVisible(false);
logoutForm.setVisible(true);
if (session.getActiveUser() instanceof Patient) {
Patient p = (Patient) session.getActiveUser();
logoutForm.add(new Label("wloginrole", p.getFirstName() + " " + p.getLastName()));
}
else if (session.getActiveUser() instanceof Doctor) {
Doctor d = (Doctor) session.getActiveUser();
logoutForm.add(new Label("wloginrole", d.getFirstName() + " " + d.getLastName()));
}
else if (session.getActiveUser() instanceof Hospital){
Hospital h = (Hospital) session.getActiveUser();
logoutForm.add(new Label("wloginrole", h.getName()));
}
logoutForm.add(new BookmarkablePageLink<>("notificationsLink", NotificationsPage.class));
logoutForm.add(new BookmarkablePageLink<>("startPageLink", StartPage.class));
}
else {
loginForm.setVisible(true);
logoutForm.setVisible(false);
}
add(new Label(TemplateConstants.PAGE_TITLE, this.defaultTitle));
add(loginForm);
add(logoutForm);
}
}
<file_sep>/operationManager/operationManager-web/src/main/java/webGui/overview/OverviewPanel.properties
date=Datum
from=von
to=bis
type=Typ
hospital=KH
doctor=Arzt/Ärztin
status=Status
patient=PatientIn
filterButton=Filtern
storno=Stornieren
delete=Löschen
OperationType.eye=Augen
OperationType.ortho=Ortho
OperationType.cardio=Kardio
OperationType.hno=HNO
OperationType.neuro=NEURO
OperationStatus.reserved=reserviert
OperationStatus.free=frei
buttonTextDoctor=Reservierung für eine PatientIn vornehmen
buttonTextHospital=Neuen Slot anlegen<file_sep>/operationManager/operationManager-shared/src/main/java/model/OPSlot.java
package model;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document
public class OPSlot implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String id;
private Date date;
private Date from;
private Date to;
private OperationType type;
private Hospital hospital;
private Doctor doctor;
private OperationStatus status;
private Patient patient;
}
<file_sep>/operationManager/operationManager-web/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>operationManager</groupId>
<artifactId>operationManager</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>operationManager-web</groupId>
<artifactId>operationManager-web</artifactId>
<dependencies>
<dependency>
<groupId>operationManager-shared</groupId>
<artifactId>operationManager-shared</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>operationManager-shared</groupId>
<artifactId>operationManager-shared</artifactId>
<version>0.0.1-SNAPSHOT</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<!-- WICKET DEPENDENCIES -->
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-extensions</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-spring</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-util</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-datetime</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-auth-roles</artifactId>
<version>${wicket.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.wicket-jquery-ui</groupId>
<artifactId>wicket-jquery-ui</artifactId>
<version>6.15.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.wicket-jquery-ui</groupId>
<artifactId>wicket-kendo-ui</artifactId>
<version>6.15.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>9.1.3.v20140225</version>
</dependency>
</dependencies>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/test</contextPath>
</webApp>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<excludes>
<!-- only makes sense on cloud -->
<exclude>**/LoadTest.java</exclude>
<!-- is abstract -->
<exlcude>**/AbstractBaseTest.java</exlcude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>src\main\webapp\WEB-INF\cloud\web.xml</webXml>
</configuration>
</plugin>
<plugin>
<groupId>org.cloudfoundry</groupId>
<artifactId>cf-maven-plugin</artifactId>
<version>1.0.2</version>
<configuration>
<server>operationManager</server>
<target>https://api.run.pivotal.io</target>
<org>operationManager</org>
<url>operationmanager-web.cfapps.io</url>
<space>development</space>
<appname>operationManager-web</appname>
<memory>512</memory>
<services>
<service>
<name>DB</name>
</service>
<service>
<name>MoM</name>
</service>
</services>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<filtering>false</filtering>
<directory>src/main/resources</directory>
</resource>
<resource>
<filtering>false</filtering>
<directory>src/main/java</directory>
<includes>
<include>**</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
</build>
</project>
<file_sep>/operationManager/operationManager-web/src/test/java/webGui/TestStartPage.java
package webGui;
import model.OPSlot;
import org.apache.wicket.datetime.markup.html.basic.DateLabel;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.markup.html.basic.EnumLabel;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.util.tester.FormTester;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import service.IOPSlotService;
import com.googlecode.wicket.kendo.ui.form.datetime.DatePicker;
import com.googlecode.wicket.kendo.ui.form.datetime.TimePicker;
public class TestStartPage extends AbstractBaseTest {
@Autowired
IOPSlotService opSlotService;
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/test");
webapp.setWar("src/main/webapp");
webapp.setOverrideDescriptor("src/main/webapp/WEB-INF/web-test.xml");
server.setHandler(webapp);
server.start();
server.join();
}
/**
* asserts the necessary form components, fills the user name and a password, and submits the form
* @param user
*/
private void login(String user) {
tester.assertComponent("loginForm:username", TextField.class);
tester.assertComponent("loginForm:password", PasswordTextField.class);
FormTester formTester = tester.newFormTester("loginForm");
formTester.setValue("username", user);
formTester.setValue("password", "a");
formTester.submit();
}
@Test
public void page_renders() {
tester.startPage(StartPage.class);
tester.assertRenderedPage(StartPage.class);
}
@Test
public void table_renders() {
page_renders();
tester.assertComponent("overview:overviewTable", DataTable.class);
}
@Test
public void all_components_render_role_default() {
page_renders();
tester.assertComponent("overview:filterForm", Form.class);
tester.assertComponent("overview:filterForm:date", DatePicker.class);
tester.assertComponent("overview:filterForm:from", TimePicker.class);
tester.assertComponent("overview:filterForm:to", TimePicker.class);
tester.assertInvisible("overview:filterForm:patient");
tester.assertComponent("overview:filterForm:hospital", TextField.class);
tester.assertComponent("overview:filterForm:doctor", TextField.class);
tester.assertComponent("overview:filterForm:type", DropDownChoice.class);
tester.assertComponent("overview:filterForm:status", DropDownChoice.class);
tester.assertComponent("overview:overviewTable:body:rows:1:cells:1:cell", DateLabel.class); //Date
tester.assertComponent("overview:overviewTable:body:rows:1:cells:2:cell", DateLabel.class); //From
tester.assertComponent("overview:overviewTable:body:rows:1:cells:3:cell", DateLabel.class); //To
tester.assertComponent("overview:overviewTable:body:rows:1:cells:4:cell", EnumLabel.class); //Type
tester.assertLabel("overview:overviewTable:body:rows:1:cells:5:cell", "SMZ"); //Hospital
tester.assertLabel("overview:overviewTable:body:rows:1:cells:6:cell", "Dr. Augfehler"); //Doctor
tester.assertComponent("overview:overviewTable:body:rows:1:cells:7:cell", EnumLabel.class); //Status
}
@Test
public void all_components_render_role_patient() {
page_renders();
login("patient");
tester.assertComponent("overview:filterForm", Form.class);
tester.assertComponent("overview:filterForm:date", DatePicker.class);
tester.assertComponent("overview:filterForm:from", TimePicker.class);
tester.assertComponent("overview:filterForm:to", TimePicker.class);
tester.assertInvisible("overview:filterForm:patient");
tester.assertComponent("overview:filterForm:hospital", TextField.class);
tester.assertComponent("overview:filterForm:doctor", TextField.class);
tester.assertComponent("overview:filterForm:type", DropDownChoice.class);
tester.assertInvisible("overview:filterForm:status");
tester.assertComponent("overview:overviewTable:body:rows:1:cells:1:cell", DateLabel.class); //Date
tester.assertComponent("overview:overviewTable:body:rows:1:cells:2:cell", DateLabel.class); //From
tester.assertComponent("overview:overviewTable:body:rows:1:cells:3:cell", DateLabel.class); //To
tester.assertComponent("overview:overviewTable:body:rows:1:cells:4:cell", EnumLabel.class); //Type
tester.assertLabel("overview:overviewTable:body:rows:1:cells:5:cell", "SMZ"); //Hospital
tester.assertLabel("overview:overviewTable:body:rows:1:cells:6:cell", "Dr. Augfehler"); //Doctor
}
@Test
public void all_components_render_role_hospital() {
page_renders();
login("hospital");
tester.assertComponent("overview:filterForm", Form.class);
tester.assertComponent("overview:filterForm:date", DatePicker.class);
tester.assertComponent("overview:filterForm:from", TimePicker.class);
tester.assertComponent("overview:filterForm:to", TimePicker.class);
tester.assertComponent("overview:filterForm:patient", TextField.class);
tester.assertInvisible("overview:filterForm:hospital");
tester.assertComponent("overview:filterForm:doctor", TextField.class);
tester.assertComponent("overview:filterForm:type", DropDownChoice.class);
tester.assertInvisible("overview:filterForm:status");
tester.assertComponent("overview:overviewTable:body:rows:1:cells:1:cell", DateLabel.class); //Date
tester.assertComponent("overview:overviewTable:body:rows:1:cells:2:cell", DateLabel.class); //From
tester.assertComponent("overview:overviewTable:body:rows:1:cells:3:cell", DateLabel.class); //To
tester.assertComponent("overview:overviewTable:body:rows:1:cells:4:cell", EnumLabel.class); //Type
tester.assertLabel("overview:overviewTable:body:rows:1:cells:5:cell", "Dr. Augfehler"); //Doctor
tester.assertLabel("overview:overviewTable:body:rows:1:cells:6:cell", "<NAME>"); //Patient
tester.assertComponent("overview:overviewTable:body:rows:1:cells:7:cell", Link.class); //remove link
}
@Test
public void all_components_render_role_doctor() {
page_renders();
login("doctor");
tester.assertComponent("overview:filterForm", Form.class);
tester.assertComponent("overview:filterForm:date", DatePicker.class);
tester.assertComponent("overview:filterForm:from", TimePicker.class);
tester.assertComponent("overview:filterForm:to", TimePicker.class);
tester.assertComponent("overview:filterForm:patient", TextField.class);
tester.assertComponent("overview:filterForm:hospital", TextField.class);
tester.assertInvisible("overview:filterForm:doctor");
tester.assertComponent("overview:filterForm:type", DropDownChoice.class);
tester.assertInvisible("overview:filterForm:status");
tester.assertComponent("overview:overviewTable:body:rows:1:cells:1:cell", DateLabel.class); //Date
tester.assertComponent("overview:overviewTable:body:rows:1:cells:2:cell", DateLabel.class); //From
tester.assertComponent("overview:overviewTable:body:rows:1:cells:3:cell", DateLabel.class); //To
tester.assertComponent("overview:overviewTable:body:rows:1:cells:4:cell", EnumLabel.class); //Type
tester.assertLabel("overview:overviewTable:body:rows:1:cells:5:cell", "SMZ"); //Hospital
tester.assertLabel("overview:overviewTable:body:rows:1:cells:6:cell", "<NAME>"); //Patient
tester.assertComponent("overview:overviewTable:body:rows:1:cells:7:cell", Link.class); //remove link
tester.assertComponent("overview:opSlotButton", Link.class);
}
@Test
public void test_reservation_button() {
page_renders();
login("doctor");
tester.clickLink("overview:opSlotButton");
tester.assertRenderedPage(ReservationPage.class);
}
@Test
public void test_cancel_reservation_link() {
page_renders();
login("doctor");
tester.clickLink("overview:overviewTable:body:rows:1:cells:7:cell");
Mockito.verify(opSlotService).cancelReservation(Mockito.any(OPSlot.class));
}
@Test
public void test_create_button() {
page_renders();
login("hospital");
tester.clickLink("overview:opSlotButton");
tester.assertRenderedPage(CreateOPSlotPage.class);
}
@Test
public void test_delete_slot_link() {
page_renders();
login("hospital");
tester.clickLink("overview:overviewTable:body:rows:1:cells:7:cell");
Mockito.verify(opSlotService).deleteOPSlot(Mockito.any(OPSlot.class));
}
}
<file_sep>/operationManager/operationManager-web/src/main/java/webGui/CreateOPSlotPage.java
package webGui;
import java.util.Arrays;
import java.util.Locale;
import model.Hospital;
import model.OPSlot;
import model.OperationStatus;
import model.OperationType;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.EnumChoiceRenderer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.validation.AbstractFormValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.IOPSlotService;
import session.OperationManagerWebSession;
import com.googlecode.wicket.kendo.ui.form.datetime.DatePicker;
import com.googlecode.wicket.kendo.ui.form.datetime.TimePicker;
@AuthorizeInstantiation(value = {"HOSPITAL"})
public class CreateOPSlotPage extends IndexPage {
private static final long serialVersionUID = 1L;
@SpringBean
IOPSlotService opSlotService;
public CreateOPSlotPage(PageParameters parameters) {
super(parameters);
}
@Override
protected void onInitialize() {
super.onInitialize();
LoadableDetachableModel<OPSlot> model = new LoadableDetachableModel<OPSlot>() {
private static final long serialVersionUID = 1L;
@Override
protected OPSlot load() {
OperationManagerWebSession session = (OperationManagerWebSession) WebSession.get();
Hospital hospital = (Hospital) session.getActiveUser();
OPSlot slot = new OPSlot();
//set fixed values
slot.setHospital(hospital);
slot.setStatus(OperationStatus.free);
return slot;
}
};
add(new FeedbackPanel("feedback"));
Form<OPSlot> form = new Form<OPSlot>("form", new CompoundPropertyModel<OPSlot>(model)) {
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit() {
opSlotService.saveOPSlot(getModelObject());
setResponsePage(StartPage.class);
}
};
final TimePicker from = new TimePicker("from", Locale.GERMAN);
final TimePicker to = new TimePicker("to", Locale.GERMAN);
form.add(new DropDownChoice<OperationType>("type", Arrays.asList(OperationType.values()),
new EnumChoiceRenderer<OperationType>(CreateOPSlotPage.this)).setRequired(true));
form.add(new DatePicker("date", Locale.GERMAN).setRequired(true));
form.add(from.setRequired(true));
form.add(to.setRequired(true));
form.add(new SubmitLink("save"));
form.add(new AbstractFormValidator() {
private static final long serialVersionUID = 1L;
@Override
public FormComponent<?>[] getDependentFormComponents() {
return new FormComponent<?>[] { from, to };
}
@Override
public void validate(Form<?> form) {
if (!from.getConvertedInput().before(to.getConvertedInput())) {
form.error(getString("timeValidationError"));
}
}
});
add(form);
}
}
<file_sep>/operationManager/operationManager-shared/src/main/java/cloudConfig/RabbitMQConfig.java
package cloudConfig;
import org.cloudfoundry.runtime.env.CloudEnvironment;
import org.cloudfoundry.runtime.env.RabbitServiceInfo;
import org.cloudfoundry.runtime.service.messaging.RabbitServiceCreator;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.config.java.ServiceScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ServiceScan
public class RabbitMQConfig {
public static final String GEORESOLVER_Q = "geoResolverQueue";
public static final String NEWSBEEPER_Q = "newsBeeperQueue";
@Bean
public ConnectionFactory connectionFactory() {
CloudEnvironment cloudEnvironment = new CloudEnvironment();
RabbitServiceInfo serviceInfo = cloudEnvironment.getServiceInfo("MoM", RabbitServiceInfo.class);
RabbitServiceCreator serviceCreator = new RabbitServiceCreator();
return serviceCreator.createService(serviceInfo);
}
@Bean
public AmqpAdmin amqpAdmin() {
return new RabbitAdmin(connectionFactory());
}
@Bean
public RabbitTemplate rabbitTemplate() {
return new RabbitTemplate(connectionFactory());
}
@Bean
public Queue geoResolverQueue() {
return new Queue(GEORESOLVER_Q, true);
}
@Bean
public Queue newsBeeperQueue() {
return new Queue(NEWSBEEPER_Q, true);
}
}
<file_sep>/operationManager/operationManager-georesolver/src/main/java/georesolver/Main.java
package georesolver;
import model.NotificationType;
import model.OPSlot;
import model.OperationStatus;
import model.dto.Message;
import model.dto.NotificationDTO;
import model.dto.OPSlotDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import service.IGeoResolverService;
import service.IOPSlotService;
import service.IQueueListener;
import service.IQueueService;
import service.exceptions.ServiceException;
import config.RabbitMQConfig;
@Component
public class Main implements InitializingBean {
private Logger logger = LoggerFactory.getLogger(Main.class);
@Autowired
private IQueueService queueService;
@Autowired
private IOPSlotService opSlotService;
@Autowired
private IGeoResolverService geoResolverService;
private static ApplicationContext context;
@Override
public void afterPropertiesSet() throws Exception {
logger.info("Started listening");
listenOnQueue();
}
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("/spring/application-config.xml");
Main prog = new Main();
AutowireCapableBeanFactory factory = context.getAutowireCapableBeanFactory();
factory.autowireBeanProperties(prog, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
}
private void listenOnQueue() {
queueService.registerListener(RabbitMQConfig.GEORESOLVER_Q, new IQueueListener() {
@Override
public void handleMessage(Message m) {
try {
OPSlotDTO slotDTO = (OPSlotDTO) m;
logger.info("Got request: " + m);
/*
* We need to send a notification to patient, doctor and
* hospital
*/
NotificationDTO notificationDoc = new NotificationDTO();
NotificationDTO notificationPat = new NotificationDTO();
NotificationDTO notificationHos = new NotificationDTO();
OPSlot opSlot = null;
try {
opSlot = geoResolverService.findSlot(slotDTO);
} catch (ServiceException e) {
notificationDoc.setMessage("Registrierung fehlgeschlagen!");
notificationDoc.setType(NotificationType.RESERVATION_FAILED);
notificationPat.setMessage("Registrierung fehlgeschlagen!");
notificationPat.setType(NotificationType.RESERVATION_FAILED);
}
if (opSlot != null) {
opSlot.setStatus(OperationStatus.reserved);
opSlotService.saveOPSlot(opSlot);
notificationDoc.setOpSlotID(opSlot.getId());
notificationDoc.setMessage("Registrierung erfolgreich!");
notificationDoc.setType(NotificationType.RESERVATION_SUCESSFULL);
notificationPat.setOpSlotID(opSlot.getId());
notificationPat.setMessage("Registrierung erfolgreich!");
notificationPat.setType(NotificationType.RESERVATION_SUCESSFULL);
notificationHos.setOpSlotID(opSlot.getId());
notificationHos.setMessage("Registrierung erfolgreich!");
notificationHos.setType(NotificationType.RESERVATION_SUCESSFULL);
notificationHos.setRecipientID(opSlot.getHospital().getId());
queueService.sendToNewsBeeper(notificationHos);
} else {
notificationDoc.setMessage("Registrierung fehlgeschlagen!");
notificationDoc.setType(NotificationType.RESERVATION_FAILED);
notificationPat.setMessage("Registrierung fehlgeschlagen!");
notificationPat.setType(NotificationType.RESERVATION_FAILED);
}
notificationDoc.setRecipientID(slotDTO.getDoctorID());
notificationPat.setRecipientID(slotDTO.getPatientID());
queueService.sendToNewsBeeper(notificationDoc);
queueService.sendToNewsBeeper(notificationPat);
} catch (Exception e) {
logger.error("Failed to handle message", e);
}
}
});
}
}
<file_sep>/operationManager/operationManager-newsbeeper/src/test/java/service/NewsbeeperTest.java
package service;
import static org.junit.Assert.*;
import model.Doctor;
import model.NotificationType;
import model.Patient;
import model.Role;
import model.dto.NotificationDTO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import repository.DoctorRepository;
import repository.PatientRepository;
import testData.DatabaseTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/application-config.xml" })
public class NewsbeeperTest extends DatabaseTest {
@Autowired
private INewsbeeperService newsbeeperService;
@Autowired
private DoctorRepository repoD;
@Autowired
private PatientRepository repoP;
@Test
public void testhandleNotificationNull() {
assertNull(newsbeeperService.handleNotification(null));
}
@Test
public void testhandleNotificationNullWithEmptyObject() {
NotificationDTO dto = new NotificationDTO();
assertNull(newsbeeperService.handleNotification(dto));
}
@Test
public void testhandleNotificationNullWithNotExistingRecipient() {
NotificationDTO dto = new NotificationDTO();
dto.setMessage("Test");
dto.setType(NotificationType.RESERVATION_SUCESSFULL);
dto.setRecipientID("test_id");
dto.setOpSlotID("opslot_id");
assertNull(newsbeeperService.handleNotification(dto));
}
@Test
public void testhandleNotificationWithExistingDoctor() {
NotificationDTO dto = new NotificationDTO();
dto.setMessage("Test");
dto.setType(NotificationType.RESERVATION_SUCESSFULL);
dto.setOpSlotID("opslot_id");
Doctor d = new Doctor();
d.setFirstName("fname");
d.setLastName("lname");
d.setRole(Role.DOCTOR);
d.setUsername("uname01");
repoD.save(d);
dto.setRecipientID(d.getId());
assertEquals(d.getUsername(), newsbeeperService.handleNotification(dto).getRecipient().getUsername());
repoD.delete(d);
}
@Test
public void testhandleNotificationWithExistingPatient() {
NotificationDTO dto = new NotificationDTO();
dto.setMessage("Test");
dto.setType(NotificationType.RESERVATION_SUCESSFULL);
dto.setOpSlotID("opslot_id");
Patient p = new Patient();
p.setFirstName("fname");
p.setLastName("lname");
p.setRole(Role.PATIENT);
p.setUsername("uname02");
repoP.save(p);
dto.setRecipientID(p.getId());
assertEquals(p.getUsername(), newsbeeperService.handleNotification(dto).getRecipient().getUsername());
repoP.delete(p);
}
}
| d553d5c0792d08e6d9bfeb076694afaa9da83874 | [
"Markdown",
"Maven POM",
"INI",
"Java",
"Shell"
] | 45 | Java | e0828330/operationManager | 9e93a949d0e3b2a04e73bc274b564599c67ec7ad | 842b807127dc79053751a6678e5f9afe5053f19b |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Threading;
namespace School
{
class Program
{
static void Main(string[] args)
{
//lista för byrån
List<String> byra = new List<string>()
{
"Sten",
"Fot",
"Trosor",
"Råtta",
};
//lägg ins aker i byrån, ska kunna ta ut saker,
// vad som finns i byrån
// avsluta
/*Utskrift till konsollen
Inmatning av data, spara variabler i korrekt datatyp
Selektion, if eller switch för meny
Loop som accepterar menyval tills användaren väljer att avsluta programmet*/
Console.WriteLine("Starting system");
Thread.Sleep(800);
Console.WriteLine("...");
Console.WriteLine("Det här är din mögliga byrå. Vad vill du göra?");
string menyval = "0";
while (menyval != "5")
{
// skriver ut huvudmenyn
Console.WriteLine("Välj ett alternativ:");
Console.WriteLine("1. Lägg in ett föremål");
Console.WriteLine("2. Ta ut föremål");
Console.WriteLine("3. Läs upp vilka föremål det finns i byrån");
Console.WriteLine("4. Rensa byrån");
Console.WriteLine("5. Stäng byrån");
menyval = Console.ReadLine();
//tom rad innan användarens val körs
Console.WriteLine(" ");
// switchen
switch (menyval)
{
case "1":
Console.WriteLine("Vad vill du lägga in?");
Console.WriteLine($"Det som redan finns i byrån är:");
foreach (var list in byra)
{
Console.WriteLine(list);
}
byra.Add(Console.ReadLine());
break;
case "2":
Console.WriteLine($"Det som finns i byrån är:");
foreach (var list in byra)
{
Console.WriteLine(list);
}
Console.WriteLine("Vad vill du ta ut?");
byra.Remove(Console.ReadLine());
break;
case "3":
Console.WriteLine($"Det som finns i byrån är:");
foreach (var list in byra)
{
Console.WriteLine(list);
}
break;
case "4":
Console.WriteLine("Rensa byrån");
byra.Clear();
Console.WriteLine("Allt är nu superduper clean!");
break;
case "5":
Environment.Exit(-1);
break;
default:
Console.WriteLine("Du valde inte ett giltigt alternativ");
break;
}
//Tom rad innan nästa körning
Console.WriteLine("Tryck på valfri knapp för att komma till huvudmenyn igen");
Console.ReadKey();
Console.Clear();
}
}
}
}
| 93b5e82f4a520a85134c76a7737a5024909511a2 | [
"C#"
] | 1 | C# | zizouhernandez/School | 3edf4d2e27ffb152be16fc2051cf9bab3d0edfe3 | 505a75c77c8ad6daa0bd75b64ee268657ab5ab01 |
refs/heads/master | <file_sep>use emails;
create sequence ruleID START 1 INCREMENT 1;
create table rule (ID int primary key DEFAULT nextval('ruleID'),
sent_to STRING,
sent_from STRING,
subject STRING,
words_in STRING,
owner STRING,
actionName STRING,
field1 STRING,
field2 STRING
);
GRANT ALL ON emails.rule TO testuser;
GRANT UPDATE,INSERT ON TABLE emails.ruleID TO testuser;
<file_sep>package CommandPattern.Emails.Controller;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
public class SingletonClassLoader {
private static ClassLoader classLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String s) throws ClassNotFoundException {
return super.loadClass(s);
}
};
public static void update(){
classLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String s) throws ClassNotFoundException {
return super.loadClass(s);
}
};
try {
InputStream input = new FileInputStream("src/main/java/CommandPattern/Emails/Controller/configCommandMap.properties");
if (input == null) {
throw new Exception();
}
Properties prop = new Properties();
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
Class loadedClass = null;
if(!key.equals("timestamp"))
{
loadedClass = classLoader.loadClass("CommandPattern.Emails." + value);
System.out.println("Key : " + key + ", Value : " + value);
}
}
}
catch (Exception e){
}
}
}
<file_sep>package CommandPattern.Emails.Controller;
import CommandPattern.Command;
import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import java.io.File;
public class DeleteCommandCommand implements Command {
public JSONObject execute(JSONObject json) {
ClassLoader classLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String s) throws ClassNotFoundException {
return super.loadClass(s);
}
};
try{
File file = (File) json.get("file");
String command = json.getString("command_name");
file.delete();
MapHandler.removeProperty(command);
classLoader = null;
} catch (Exception e){
e.printStackTrace();
return new JSONObject("{ \"message\" : \"Error in deleting class\" }");
}
return new JSONObject();
}
}
<file_sep>package Redis;
import redis.clients.jedis.Jedis;
public class Redis {
private static Jedis jedis = new Jedis("localhost");
public static Jedis getJedis() {
return jedis;
}
}
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import sun.awt.image.IntegerInterleavedRaster;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.Exception;
public class ListEmailsCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject viewInbox(String email) throws Exception {
ResultSet res = con.createStatement().executeQuery("select * from email INNER JOIN recipient on" +
" email.id = recipient.email_id where recipient.recipient_email = '"+ email + "' and email.type = 'sent' and recipient.spam = 'false' and recipient.deleted = 'false';");
JSONArray jsonresult = ResultSetConverter.convertResultSetIntoJSON(res);
ResultSet res2 = con.createStatement().executeQuery("select * from email INNER JOIN cc on" +
" email.id = cc.email_id where cc.cc_email = '"+ email + "' and email.type = 'sent' and cc.spam" +
" = 'false' and cc.deleted = 'false';");
JSONArray jsonresult2 = ResultSetConverter.convertResultSetIntoJSON(res2);
ResultSet res3 = con.createStatement().executeQuery("select * from email INNER JOIN bcc on" +
" email.id = bcc.email_id where bcc.bcc_email = '"+ email + "' and email.type = 'sent' and bcc.spam = 'false' and bcc.deleted = 'false';");
JSONArray jsonresult3 = ResultSetConverter.convertResultSetIntoJSON(res3);
JSONArray jsonresult4 = ResultSetConverter.concatArray(jsonresult,jsonresult2,jsonresult3);
String out = ResultSetConverter.outify(jsonresult4);
if (out.equals("{}")){
out = "{\"message\":\"Inbox is empty\"}";
}
JSONObject result = new JSONObject(out);
System.out.println("OUTTTT"+jsonresult.length());
System.out.println(out);
return result;
}
public static void main(String[] args) throws SQLException {
}
public JSONObject execute(JSONObject json) {
try {
String email = json.getString("email");
return viewInbox(email);
} catch (Exception ex) {
ex.printStackTrace();
String message = "Error in viewing inbox";
return new JSONObject(message);
}
}
}
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import sun.awt.image.IntegerInterleavedRaster;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.Exception;
public class AddEmailToFolderCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject addEmailToFolder(int id, String folderName, String email) throws Exception {
con.createStatement().executeUpdate("UPDATE recipient SET folder = '"+folderName+
"' where email_id ="+id+" and recipient_email = '"+email+"';");
con.createStatement().executeUpdate("UPDATE cc SET folder = '"+folderName+
"' where email_id ="+id+" and cc_email = '"+email+"';");
con.createStatement().executeUpdate("UPDATE bcc SET folder = '"+folderName+
"' where email_id ="+id+" and bcc_email = '"+email+"';");
String message = "{ \"message\": \"Email added to folder\"}";
return new JSONObject(message);
}
public JSONObject execute(JSONObject json) {
try {
int id = Integer.parseInt(json.getString("emailID"));
String folderName = json.getString("folderName");
String email = json.getString("email");
return addEmailToFolder(id, folderName, email);
} catch (Exception ex) {
String message = "{ \"message\": \"Error in adding email to folder\"}";
return new JSONObject(message);
}
}
}
<file_sep>package CommandPattern.Emails.Controller;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ControlCommandMap {
private static ConcurrentMap<String, Class<?>> cmdMap = new ConcurrentHashMap<>();
public static void instantiate(){
cmdMap.put("set_max_thread_count", SetMaxThreadCountCommand.class);
cmdMap.put("freeze", FreezeCommand.class);
cmdMap.put("continue", ContinueCommand.class);
cmdMap.put("set_max_db_connections_count", SetMaxDBConnectionsCountCommand.class);
cmdMap.put("add_command", AddCommandCommand.class);
cmdMap.put("update_command", UpdateCommandCommand.class);
cmdMap.put("delete_command", DeleteCommandCommand.class);
cmdMap.put("update_class", UpdateClassCommand.class);
cmdMap.put("addProperty",PropertiesHandler.class);
}
public static Class<?> queryClass(String cmd){
return cmdMap.get(cmd);
}
public static ConcurrentMap getinstance(){
return cmdMap;
}
}
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.Exception;
public class DeleteEmailCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject deleteEmail(int id, String email) throws Exception {
JSONObject result;
try {
// MOVE TO TRASH!
// int s = con.createStatement().executeUpdate("UPDATE email SET type = 'deleted' WHERE ID="+id
// +" and sender = '"+email+"';");
int s = 0;
s += con.createStatement().executeUpdate("UPDATE recipient SET deleted = 'trash' WHERE "
+"email_id ="+id+" and recipient_email ='"+email+"' and deleted = 'false'");
s += con.createStatement().executeUpdate("UPDATE bcc SET deleted = 'trash' WHERE "
+"email_id ="+id+" and bcc_email ='"+email+"' and deleted = 'false'");
s += con.createStatement().executeUpdate("UPDATE cc SET deleted = 'trash' WHERE "
+"email_id ="+id+" and cc_email ='"+email+"' and deleted = 'false'");
if (s == 0)
throw new Exception();
String message = "{\"message\":\"Email deleted\"}";
result = new JSONObject(message);
}
catch(Exception ex){
System.out.println(ex.toString());
String message = "{\"message\":\"Failed to delete email\"}";
result = new JSONObject(message);
}
return result;
}
public static void main(String[] args) throws SQLException {
}
public JSONObject execute(JSONObject json) {
try {
int id = Integer.parseInt(json.getString("email_id"));
String email = json.getString("email");
return deleteEmail(id,email);
} catch (Exception ex) {
String message = "{ \"message\": \"Error in deleting email\"}";
return new JSONObject(message);
}
}
}
<file_sep>package CommandPattern.Emails.Controller;
import CommandPattern.Command;
import CommandPattern.Emails.RPCServer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import sun.misc.Cache;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import java.io.File;
import java.util.Arrays;
public class UpdateCommandCommand implements Command {
public JSONObject execute(JSONObject json) {
ClassLoader classLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String s) throws ClassNotFoundException {
return super.loadClass(s);
}
};
try{
File file = (File) json.get("file");
file.createNewFile();
String name = FilenameUtils.removeExtension(file.getName());
Class loadedClass = classLoader.loadClass("CommandPattern.Emails." + name);
MapHandler.addProperty(json.getString("command_name"),FilenameUtils.removeExtension(file.getName()));
} catch (Exception e){
e.printStackTrace();
return new JSONObject("{ \"message\" : \"Error in updating class\" }");
}
return new JSONObject();
}
}
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SearchInboxCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject search(String value, String email) throws Exception {
ResultSet res = con.createStatement().executeQuery("select * from email INNER JOIN " +
"recipient on email.id = recipient.email_id " +
"where recipient.recipient_email ='"+email+"' " +
"and email.type = 'sent' and recipient.deleted = 'false' and " +
"( email.subject like '%"+value +"%' OR email.body like '%" + value +"%' );");
// return res;
// String result = "";
JSONArray jsonresult = ResultSetConverter.convertResultSetIntoJSON(res);
String out = ResultSetConverter.outify(jsonresult);
if (out.equals("{}")){
out = "{\"message\":\"No emails found\"}";
}
JSONObject result = new JSONObject(out);
return result;
}
public JSONObject execute(JSONObject json) {
try {
String value = json.getString("value");
String email = json.getString("email");
return search(value,email);
} catch (Exception ex) {
String message = "{ \"message\": \"Error in searching inbox\"}";
return new JSONObject(message);
}
}
}
<file_sep>create database emails;
use emails;
create sequence emailID START 1 INCREMENT 1;
create sequence threadID START 1 INCREMENT 1;
create sequence attachmentID START 1 INCREMENT 1;
create table folder (name STRING primary key);
create table email (ID int primary key DEFAULT nextval('emailID'),
timest timestamp,
sender STRING,
subject STRING,
body STRING,
thread_id int DEFAULT nextval('threadID'),
type STRING,
folder STRING,
foreign key (folder) references folder(name) ON DELETE NO ACTION ON UPDATE CASCADE
);
create table recipient (
email_id int,
recipient_email STRING,
primary key(email_id, recipient_email),
foreign key (email_id) references email(ID) ON DELETE CASCADE ON UPDATE CASCADE
);
create table bcc (
email_id int ,
bcc_email STRING,
primary key(email_id, bcc_email),
foreign key (email_id) references email(ID) ON DELETE CASCADE ON UPDATE CASCADE
);
create table cc (
email_id int ,
cc_email STRING,
primary key(email_id, cc_email),
foreign key (email_id) references email(ID) ON DELETE CASCADE ON UPDATE CASCADE
);
create table attachment (
ID int primary key DEFAULT nextval('attachmentID'),
email_id int,
attachment_address STRING,
foreign key (email_id) references email(ID) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO folder(name)
VALUES ('Scalable');
INSERT INTO folder(name)
VALUES ('Work');
INSERT INTO folder(name)
VALUES ('Default');
/* Email Table Entries */
INSERT INTO email(timest,sender,subject,body,type,folder)
VALUES ('2019-01-19 03:14:07','<EMAIL>','Scalable Milestone','This is the submission link','sent','Scalable');
INSERT INTO email(timest,sender,subject,body,thread_id,type,folder)
VALUES ('2019-01-19 05:20:17','yasmineabd<EMAIL>','Scalable Milestone','I submitted',1,'sent','Scalable');
INSERT INTO email(timest,sender,subject,body,type,folder)
VALUES ('2019-02-10 09:24:37','<EMAIL>','Draft','This is a draft','drafts','Default');
INSERT INTO email(timest,sender,subject,body,type,folder)
VALUES ('2019-01-23 13:14:15','<EMAIL>','CV','This is my CV','sent','Work');
INSERT INTO email(timest,sender,subject,body,type,folder)
VALUES ('2019-02-09 07:34:45','<EMAIL>','','Check the attachments','sent','Default');
/* Recipient Table Entries */
INSERT INTO recipient(email_id,recipient_email)
VALUES (1 ,'<EMAIL>');
INSERT INTO recipient(email_id,recipient_email)
VALUES (2,'<EMAIL>');
INSERT INTO recipient(email_id,recipient_email)
VALUES (3,'<EMAIL>');
INSERT INTO recipient(email_id,recipient_email)
VALUES (4,'<EMAIL>');
INSERT INTO recipient(email_id,recipient_email)
VALUES (5,'<EMAIL>');
/* CC Table Entries */
INSERT INTO cc(email_id,cc_email)
VALUES (1,'<EMAIL>');
INSERT INTO cc(email_id,cc_email)
VALUES (1,'<EMAIL>');
INSERT INTO cc(email_id,cc_email)
VALUES (2,'<EMAIL>');
INSERT INTO cc(email_id,cc_email)
VALUES (3,'<EMAIL>');
INSERT INTO cc(email_id,cc_email)
VALUES (4,'<EMAIL>');
/* BCC Table Entries */
INSERT INTO bcc(email_id,bcc_email)
VALUES (5,'<EMAIL>');
INSERT INTO bcc(email_id,bcc_email)
VALUES (4,'<EMAIL>');
INSERT INTO bcc(email_id,bcc_email)
VALUES (3,'<EMAIL>');
INSERT INTO bcc(email_id,bcc_email)
VALUES (2,'<EMAIL>');
INSERT INTO bcc(email_id,bcc_email)
VALUES (1,'<EMAIL>');
/* Attachment Table Entries */
INSERT INTO attachment(email_id,attachment_address)
VALUES (1,'https://mail.google.com/mail/u/0/#sent/KtbxLzGHhZzPDDkbJfsGfjrhgjbwu');
INSERT INTO attachment(email_id,attachment_address)
VALUES (2,'https://mail.google.com/mail/u/0/#sent/Redhfrtejgyasbdsm');
INSERT INTO attachment(email_id,attachment_address)
VALUES (4,'https://mail.google.com/mail/u/0/#draft/WjrnerfbhjdffjndfksuFtdbhasj');
INSERT INTO attachment(email_id,attachment_address)
VALUES (4,'https://mail.google.com/mail/u/1/#sent/RhewjyfbdsmFTwtsadwed');
INSERT INTO attachment(email_id,attachment_address)
VALUES (5,'https://mail.google.com/mail/u/3/#sent/YndsjhewRmdnbsTnajd');
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
public class SendEmailCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject sendEmail(int id, String sender) throws Exception {
JSONObject result;
try {
// Delete completely
//DELETE FROM account_details WHERE account_id = 1 RETURNING *;
ResultSet email = con.createStatement().executeQuery("UPDATE email SET type = 'sent' WHERE " +
"type = 'draft' and " + "ID="+id+" and sender = '"+sender+"' returning subject, body");
JSONArray jsonresult = ResultSetConverter.convertResultSetIntoJSON(email);
System.out.println(jsonresult);
result = jsonresult.getJSONObject(0);
String body = result.getString("body");
String subject = result.getString("subject");
ResultSet recipients = con.createStatement().executeQuery("SELECT * FROM recipient" +
" where email_id = " + id + ";");
JSONArray recs = ResultSetConverter.convertResultSetIntoJSON(recipients);
for(int i = 0; i < recs.length(); i++)
{
System.out.println("Getting recs in send email");
applyRule(id,recs.getJSONObject(i).getString("recipient_email"), recs, sender,
subject, body );
}
email = con.createStatement().executeQuery("select * from email where " +
"ID="+id+";");
jsonresult = ResultSetConverter.convertResultSetIntoJSON(email);
System.out.println(jsonresult);
result = jsonresult.getJSONObject(0);
body = result.getString("body");
subject = result.getString("subject");
String encBody = EncryptDecrypt.encrypt("Bar12345Bar12345","RandomInitVector", body);
String encSubject = EncryptDecrypt.encrypt("Bar12345Bar12345","RandomInitVector", subject);
result.remove("body");
result.remove("subject");
result.put("body", encBody);
result.put("subject", encSubject);
//String message = "{\"message\":\"Email sent\"}";
//result = new JSONObject(message);
}
catch(Exception ex){
ex.printStackTrace();
String message = "{\"message\":\"Failed to send email\"}";
result = new JSONObject(message);
}
return result;
}
public JSONObject execute(JSONObject json) {
try {
String sender = json.getString("email");
int id = Integer.parseInt(json.getString("emailID"));
return sendEmail(id, sender);
} catch (Exception ex) {
ex.printStackTrace();
String message = "{ \"message\": \"Error in sending email\"}";
return new JSONObject(message);
}
}
public static void applyRule(int id, String owner, JSONArray recipients, String sender, String subject, String body){
try{
ResultSet recRules = con.createStatement().executeQuery("SELECT * FROM rule where owner = '" + owner + "';");
JSONArray jsonresult = ResultSetConverter.convertResultSetIntoJSON(recRules);
System.out.println("JSON RULE: " + jsonresult);
for(int i = 0; i < jsonresult.length(); i++) {
System.out.println("Looping over rec rules: " + owner);
JSONObject rule = jsonresult.getJSONObject(i);
String action = rule.getString("actionname");
String field1 = rule.getString("field1");
String field2 = rule.getString("field2");
String sent_to = rule.getString("sent_to");
String sent_from = rule.getString("sent_from");
String subject_rule = rule.getString("subject");
String body_rule = rule.getString("words_in");
if(sent_to.length() > 0){
String [] to_arr = sent_to.split(",");
for(int j = 0; j < recipients.length(); j++) {
String rec = recipients.getJSONObject(j).getString("recipient_email");
if(Arrays.asList(to_arr).contains(rec) && rec.length() > 0){
// apply rule
doAction(id, owner, action, field1, field2);
}
}
}
else if(sent_from.length() > 0){
String [] from_arr = sent_from.split(",");
if(Arrays.asList(from_arr).contains(sender)){
// apply rule
doAction(id, owner, action, field1, field2);
}
}
else if(subject_rule.length() > 0){
System.out.println("CHECK SUBJECT");
String [] subject_arr = subject_rule.split(",");
for(int j = 0; j < subject_arr.length; j++) {
if (subject.contains(subject_arr[j])) {
doAction(id, owner, action, field1, field2);
}
}
}
else if(body_rule.length() > 0){
String [] body_arr = body_rule.split(",");
for(int j = 0; j < body_arr.length; j++) {
if (body.contains(body_arr[j])) {
// apply rule
doAction(id, owner, action, field1, field2);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("in catch");
}
}
public static void doAction(int id, String owner, String action, String field1, String field2) throws Exception{
System.out.print("IN do actionn");
switch(action){
case "forward": ForwardEmailCommand.forwardEmail(id,owner,field1,"","");break;
case "folder": AddEmailToFolderCommand.addEmailToFolder(id, field1, owner);break;
case "reply": ReplyToEmailCommand.replyToEmail(id,owner,field2,"");break;
case "delete": DeleteEmailCommand.deleteEmail(id, owner);break;
default: throw new Exception();
}
}
}
<file_sep>package CommandPattern.Emails.Controller;
import CommandPattern.Command;
import CommandPattern.Emails.RPCServer;
import org.json.JSONObject;
public class ContinueCommand implements Command {
public JSONObject execute(JSONObject json) {
PropertiesHandler.addProperty("freeze", "false");
return new JSONObject();
}
}
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import sun.awt.image.IntegerInterleavedRaster;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.Exception;
public class DeleteFromTrashCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject deleteFromTrash(int id, String email) throws Exception {
JSONObject result;
try {
// Delete completely
//DELETE FROM account_details WHERE account_id = 1 RETURNING *;
int s = 0;
s += con.createStatement().executeUpdate("UPDATE recipient SET deleted = 'true' WHERE "
+"email_id ="+id+" and recipient_email ='"+email+"' and deleted = 'trash'");
s += con.createStatement().executeUpdate("UPDATE bcc SET deleted = 'true' WHERE "
+"email_id ="+id+" and bcc_email ='"+email+"' and deleted = 'trash'");
s += con.createStatement().executeUpdate("UPDATE cc SET deleted = 'true' WHERE "
+"email_id ="+id+" and cc_email ='"+email+"' and deleted = 'trash'");
if (s == 0)
throw new Exception();
String message = "{\"message\":\"Email deleted\"}";
result = new JSONObject(message);
}
catch(Exception ex){
System.out.println(ex.toString());
String message = "{\"message\":\"Failed to delete email\"}";
result = new JSONObject(message);
}
return result;
}
public static void main(String[] args) throws SQLException {
}
public JSONObject execute(JSONObject json) {
try {
int id = Integer.parseInt(json.getString("email_id"));
String email = json.getString("email");
return deleteFromTrash(id, email);
} catch (Exception ex) {
String message = "{ \"message\": \"Error in deleting from trash\"}";
return new JSONObject(message);
}
}
}
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ViewDraftsCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject viewDrafts(String email) throws Exception {
ResultSet res = con.createStatement().executeQuery("SELECT * FROM email WHERE type= 'draft' and"
+" sender = '"+email +"';");
// return res;
// String result = "";
JSONArray jsonresult = ResultSetConverter.convertResultSetIntoJSON(res);
String out = ResultSetConverter.outify(jsonresult);
if (out.equals("{}")){
out = "{\"message\":\"There are no saved drafts\"}";
}
JSONObject result = new JSONObject(out);
return result;
}
public static void main(String[] args) throws SQLException {
}
public JSONObject execute(JSONObject json) {
try {
String email = json.getString("email");
return viewDrafts(email);
} catch (Exception ex) {
ex.printStackTrace();
String message = "{\"message\":\"Error in viewing drafts\"}";
return new JSONObject(message);
}
}
}<file_sep>import CommandPattern.Emails.Controller.Controller;
import CommandPattern.Emails.Controller.PropertiesHandler;
import CommandPattern.Emails.RPCServer;
public class Microservice {
public static void main(String [] args)
{
RPCServer x = RPCServer.getInstance();
Controller r = Controller.getInstance();
PropertiesHandler.loadPropertiesHandler();
try{
x.main(args);
r.main(args);
}
catch(Exception e){
e.printStackTrace();
}
//Thread.sleep(60000);
}
}
<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Timer;
import java.util.TimerTask;
public class ScheduleEmailsCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
public static JSONObject scheduleEmail(int id, java.sql.Timestamp timest) throws Exception{
// String query = "UPDATE email SET timest="+timest+" WHERE ID="+id+";" ;
// con.createStatement().executeQuery(query);
// query = "UPDATE email SET folder = sent WHERE ID="+id+";" ;
// con.createStatement().executeQuery(query);
ResultSet res = con.createStatement().executeQuery("SELECT * FROM email WHERE ID = "+id+";");
JSONArray jsonresult = ResultSetConverter.convertResultSetIntoJSON(res);
JSONObject result = jsonresult.getJSONObject(0);
System.out.println(result);
return result;
}
public JSONObject execute(JSONObject json) {
try {
System.out.println("TIME NOW: ");
int id = Integer.parseInt(json.getString("id"));
String email = json.getString("email");
String timestStr = json.getString("timest");
Date target_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+0000").parse(timestStr);
System.out.println("TARGET DATE:"+target_date);
Date now_date = new java.util.Date();
long difference = target_date.getTime() - now_date.getTime();
System.out.println("\ndifference: " + difference);
java.sql.Timestamp timest = new java.sql.Timestamp (target_date.getTime());
Timer timer = new Timer ();
TimerTask task = new ScheduleEmailTimerTask(id, timest, email);
timer.schedule(task, difference);
return scheduleEmail( id, timest);
} catch (Exception ex) {
ex.printStackTrace();
String message = "{ \"message\": \"Error in scheduling email\"}";
return new JSONObject(message);
}
}
}
class ScheduleEmailTimerTask extends TimerTask {
int id;
String email;
java.sql.Timestamp timest;
static Connection con;
public ScheduleEmailTimerTask (int id, java.sql.Timestamp timest, String email){
this.id = id;
this.timest = timest;
this.email = email;
}
public void run () {
try {
SendEmailCommand.sendEmail(id, email);
// con = DBConnection.getInstance().getConnection();
// String query = "UPDATE email SET timest='" + timest + "' WHERE ID=" + id + ";";
// con.createStatement().executeUpdate(query);
// query = "UPDATE email SET type = 'sent' WHERE ID=" + id + ";";
// con.createStatement().executeUpdate(query);
}
catch (Exception ex){
ex.printStackTrace();
String message = "Error in scheduling email";
}
}
}<file_sep>package CommandPattern.Emails;
import CommandPattern.Command;
import CommandPattern.ResultSetConverter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.Exception;
public class CreateFolderCommand implements Command {
static Connection con = DBConnection.getInstance().getConnection();
// private static void writeResultSetToJson(final ResultSet rs,
// final JsonGenerator jg)
// throws SQLException, IOException {
// final var rsmd = rs.getMetaData();
// final var columnCount = rsmd.getColumnCount();
// jg.writeStartArray();
// while (rs.next()) {
// jg.writeStartObject();
// for (var i = 1; i <= columnCount; i++) {
// jg.writeObjectField(rsmd.getColumnName(i), rs.getObject(i));
// }
// jg.writeEndObject();
// }
// jg.writeEndArray();
// }
public static JSONObject createFolder(String folderName) throws Exception {
System.out.println(folderName);
con.createStatement().executeUpdate("INSERT INTO folder(name) VALUES('"+folderName+"');");
ResultSet res = con.createStatement().executeQuery("SELECT * FROM folder WHERE name = ('"+folderName+"');");
// return res;
// String result = "";
JSONArray jsonresult = ResultSetConverter.convertResultSetIntoJSON(res);
JSONObject result = jsonresult.getJSONObject(0);
System.out.println(result);
// int i = 1;
// JSONObject result = new JSONObject();
// while (res.next()) {
// String s = res.getString("sender");
//// System.out.println(s);
// result.put(i+"", s);
// i++;
//// result += res.getString("sender") + "\n";
//// System.out.println(res.getString("sender"));
// }
// System.out.println(result.toString());
return result;
}
public static void main(String[] args) throws SQLException {
// Connect to the "email" database.
try {
createFolder("Folder Name");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public JSONObject execute(JSONObject json) {
try {
String folderName = json.getString("folderName");
return createFolder(folderName);
} catch (Exception ex) {
String message = "{ \"message\": \"Error in creating folder\"}";
return new JSONObject(message);
}
}
}
<file_sep># scalableXmahaba
Google services backend implemented using Java.
To run the http-server:
1. Open IntelliJ
2. Run NettyHTTPServer.java
3. Server will be listening at localhost:8083
4. Use Insomnia to send JSON objects that include the property "service", which will include the name of your app.
To run the rabbitMQ code (which will allow you to listen to the request):
1. Open IntelliJ.
2. Open CorrelationID/RPCServer.java
3. Rename RPC_QUEUE_NAME to the value written in "service".
4. Run RPCServer.java.
5. A successful insomnia request will return the sentence "What I'll be getting from running my application".
To add your project:
1. Create your own branch.
2. Navigate to /src/main/java/CommandPattern.
3. Add one file named after your service that contains all setters and getters.
4. Add a folder that contains all your commands (follow email example).
To install jdbc on your machine:
run from vm terminal: yay -S postgresql-jdbc --noconfirm
<file_sep>package CommandPattern.Emails;
import CommandPattern.Emails.Controller.MapHandler;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class CommandMap {
private static ConcurrentMap<String, Class<?>> cmdMap;
private static String timestamp = (new Date()).getTime() + "";
public static void instantiate(){
cmdMap = new ConcurrentHashMap<>();
/* cmdMap.put("ListEmails", ListEmailsCommand.class);
cmdMap.put("AddEmailToFolder", AddEmailToFolderCommand.class);
cmdMap.put("RemoveEmailFromFolder", RemoveEmailFromFolderCommand.class);
cmdMap.put("CreateFolder", CreateFolderCommand.class);
cmdMap.put("DeleteFolder", DeleteFolderCommand.class);
cmdMap.put("ViewFolder", ViewFolderCommand.class);
cmdMap.put("ViewFolders", ViewFoldersCommand.class);
cmdMap.put("ReportEmailForSpam", ReportEmailForSpamCommand.class);
cmdMap.put("ViewThread", ViewThreadCommand.class);
cmdMap.put("OrderEmails", OrderEmailsCommand.class);
cmdMap.put("DeleteEmail", DeleteEmailCommand.class);
cmdMap.put("CreateEmail", CreateEmailCommand.class);
cmdMap.put("ViewTrash", ViewTrashCommand.class);
cmdMap.put("DeleteFromTrash", DeleteFromTrashCommand.class);
cmdMap.put("ViewSent", ViewSentCommand.class);
cmdMap.put("SendEmail", SendEmailCommand.class);
cmdMap.put("EditEmailDraft", EditEmailDraftCommand.class);
cmdMap.put("ViewDrafts", ViewDraftsCommand.class);
cmdMap.put("ReplyToEmail", ReplyToEmailCommand.class);
cmdMap.put("SearchInbox", SearchInboxCommand.class);
cmdMap.put("ForwardEmail", ForwardEmailCommand.class);
cmdMap.put("ScheduleEmails", ScheduleEmailsCommand.class);
cmdMap.put("CreateRule", CreateRuleCommand.class);*/
ClassLoader classLoader = new ClassLoader() {
@Override
public Class<?> loadClass(String s) throws ClassNotFoundException {
return super.loadClass(s);
}
};
FileInputStream input = null;
try {
input = new FileInputStream("src/main/java/CommandPattern/Emails/Controller/configCommandMap.properties");
if (input == null) {
throw new Exception();
}
Properties prop = new Properties();
prop.load(input);
timestamp = MapHandler.getProperty("timestamp");
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = prop.getProperty(key);
Class loadedClass = null;
if(!key.equals("timestamp"))
{
loadedClass = classLoader.loadClass("CommandPattern.Emails." + value);
System.out.println("Key : " + key + ", Value : " + value);
cmdMap.put(key,loadedClass);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addCommand(String name, Class<?> command) {
cmdMap.put(name, command);
}
public static void updateCommand(String name, Class<?> command) {
cmdMap.replace(name, command);
}
public static void deleteCommand(String name) {
cmdMap.remove(name);
}
public static Class<?> queryClass(String cmd){
if(!MapHandler.getProperty("timestamp").equals(timestamp)){
instantiate();
System.out.println("Updating command map");
}
return cmdMap.get(cmd);
}
public static ConcurrentMap getinstance(){
return cmdMap;
}
}
| aa66d69203553e73658984c3a78c642657c36622 | [
"Java",
"SQL",
"Markdown"
] | 20 | SQL | heshamelsherif97/docker-emails-final | f9369052939dd6c11cdf121686df1bd17ba46d39 | 81e810ca6d7c23e1341e0eacba1f27ec9006c542 |
refs/heads/master | <repo_name>CoderCharm/notes<file_sep>/01_getting-started/10_pprof/memory_test/main.go
/*
* @Time : 2021-02-20 22:05
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
go run main.go
会生成一个文件 mem.pprof 路径会有所变化
go tool pprof -http=:9999 /<KEY>profile718597885/mem.pprof
**/
package main
import (
"github.com/pkg/profile"
"math/rand"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randomString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func concat(n int) string {
s := ""
for i := 0; i < n; i++ {
s += randomString(n)
}
return s
}
func main() {
defer profile.Start(profile.MemProfile, profile.MemProfileRate(1)).Stop()
concat(100)
}
<file_sep>/01_getting-started/03_Variable/03_array/04_array_slice_test.go
/*
* @Time : 2021-01-15 19:47
* @Author : CoderCharm
* @File : 04_array_slice_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
数组 和 切片的区别
array vs slice
数组和切片的最大区别就是
数组是值传递,相当于复制
切片是指针传递,可直接修改原来的值
**/
package _3_array
import (
"fmt"
"testing"
)
func modifyArray(a [3]int) {
a[0] = 666
}
func modifySlice(n []int) {
n[0] = 777
}
func TestArrayVSSlice(t *testing.T) {
// 声明一个 int类型长度为3的数组 数组是值传递 相当于复制
intArray := [3]int{1, 2, 3}
t.Log(fmt.Sprintf("数组修改前: %v", intArray))
modifyArray(intArray)
t.Log(fmt.Sprintf("数组修改后: %v", intArray))
// 声明一个 int类型的切片 切片是指针传递
intSlice := []int{1, 2, 3}
t.Log(fmt.Sprintf("切片修改前: %v", intSlice))
// 切片是指针传递,会修改原来的值
modifySlice(intSlice)
t.Log(fmt.Sprintf("切片修改后: %v", intSlice))
}
<file_sep>/03_case_demo/09_custom_web_framework/README.md
# 自定义web框架
## 目标
基于标准库 `net/http` 构建一个微型的`gin`框架,拥有基本的功能,如路由分组,中间件等,异常恢复。
最终使用目录结构。
```
gee/ // 自定义gee框架
|-- gee.go // 核心文件 封装net/http
|-- xxx.go // 其他扩展文件
|-- ...
main.go // 用户web服务代码
go.mod
```
## 目的
学习web框架的构建原理,方便使用Go web框架。
## 参考:
- https://geektutu.com/post/gee-day1.html<file_sep>/GinStudy/model/response/sys_user.go
/*
* @Time : 2021-01-08 19:15
* @Author : CoderCharm
* @File : sys_user.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package response
import "gin_study/model"
type SysUserResponse struct {
User model.SysUser `json:"user"`
}
type LoginResponse struct {
User model.SysUser `json:"user"`
Token string `json:"token"`
ExpiresAt int64 `json:"expiresAt"`
}
<file_sep>/02_algorithm/README.md
# Go 算法练习
## 目录
[冒泡排序](./sorts/bubble_sort_test.go)
<file_sep>/GinStudy/utils/directory.go
/*
* @Time : 2021-01-05 17:11
* @Author : CoderCharm
* @File : directory.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package utils
import (
"os"
)
// @title PathExists
// @description 文件目录是否存在
// @auth (2020/04/05 20:22)
// @param path string
// @return err error
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
<file_sep>/03_case_demo/02_http_demo/req1_get_test.go
/*
* @Time : 2020-12-26 21:52
* @Author : CoderCharm
* @File : req1_get_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
最基本的发送请求解析内容
req2 比较完善
**/
package http_demo
import (
"fmt"
"io/ioutil"
"net/http"
"testing"
)
func GetHtml(url string) {
// 构建http请求
resp, err := http.Get(url)
if err != nil {
fmt.Println("http get error", err)
return
}
fmt.Println(fmt.Sprintf("响应状态 %s", resp.Status))
// 记得关闭客户端
defer resp.Body.Close()
// 读取内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("read error", err)
return
}
fmt.Println(string(body))
}
func TestReq(t *testing.T) {
url := "https://www.charmcode.cn/"
GetHtml(url)
}
<file_sep>/03_case_demo/04_qiniu_upload/online_upload/upload_test.go
/*
* @Time : 2021-01-04 18:01
* @Author : CoderCharm
* @File : upload_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
七牛云上传 在线视频
**/
package online_upload
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/parnurzeal/gorequest"
"github.com/qiniu/api.v7/v7/auth/qbox"
"github.com/qiniu/api.v7/v7/storage"
"strings"
"testing"
)
const (
Bucket = ""
AccessKey = ""
SecretKey = ""
DomainPath = ""
)
func QiniuUpLoad(targetUrl string) (string, error) {
// 请求资源
_, body, err := gorequest.New().Get(targetUrl).End()
if err != nil {
return "", errors.New(fmt.Sprintf("URL: %s 请求错误 原因: %s", targetUrl, err))
}
// 上传项目文件名
suffix := getSuffixByUrl(targetUrl)
//key := "<KEY>"
key := fmt.Sprintf("%s.%s", GetUUID(), suffix)
putPolicy := storage.PutPolicy{
Scope: fmt.Sprintf("%s:%s", Bucket, key),
}
// 认证
mac := qbox.NewMac(AccessKey, SecretKey)
upToken := putPolicy.UploadToken(mac)
// 字节上传
data := []byte(body)
dataLen := int64(len(data))
// 上传相关配置 是否启用https 选择上传机房 是否使用CDN上传加速 等配置 自行见文档
cfg := storage.Config{}
formUploader := storage.NewFormUploader(&cfg)
ret := storage.PutRet{}
putExtra := storage.PutExtra{}
// 上传
qiniuErr := formUploader.Put(context.Background(), &ret, upToken, key, bytes.NewReader(data), dataLen, &putExtra)
if qiniuErr != nil {
return "", errors.New(fmt.Sprintf("URL: %s 七牛云上传错误 原因: %s", targetUrl, err))
}
return fmt.Sprintf("%s/%s\n", DomainPath, ret.Key), nil
}
// 通过url截取 资源文件后缀
func getSuffixByUrl(targetUrl string) string {
suffix := strings.Split(targetUrl, "?")
suffix = strings.Split(suffix[0], ".")
return suffix[len(suffix)-1]
}
// 获取uuid
func GetUUID() string {
return uuid.New().String()
}
func TestUpload(t *testing.T) {
mp4Url := "https://xxx.xxx.com/mv/0dd06bdcdf1e5e7f0d1988c21cfa91fe949dadf2.mp4"
newUrl, err := QiniuUpLoad(mp4Url)
fmt.Println(newUrl, err)
}
<file_sep>/01_getting-started/10_pprof/README.md
# pprof 性能分析
安装 graphviz
```
内置的pprof
https://github.com/google/pprof
```
```
go run main.go > cpu.pprof
go tool pprof -http=:9999 cpu.pprof
// 交互模式查看
go tool pprof cpu.pprof
```
https://geektutu.com/post/hpg-pprof.html<file_sep>/GinStudy/service/article.go
/*
* @Time : 2020-11-24 10:33
* @Author : CoderCharm
* @File : article.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package service
import (
"gin_study/global"
"gin_study/model"
"gin_study/model/request"
)
/*
获取推荐文章
*/
func FetchRecommendArticleList() (RecommendArticleList []model.RecommendArticle) {
// 执行原生SQL语句
//global.GIN_DB.Raw("select id,title,content from article").Scan(&article)
global.GIN_DB.Table("article_article").
Where("is_recommend = ?", "1").
Order("update_time DESC").Limit(5).
Scan(&RecommendArticleList)
return RecommendArticleList
}
/*
获取文章列表
*/
func FetchArticleIndexList(Category request.ArticleCategory) (ArticleIndexList []model.ArticleIndex, total int64) {
limit := Category.PageSize
offset := Category.PageSize * (Category.Page - 1)
cateId := Category.CateId
if cateId == 0 {
global.GIN_DB.Table("article_article").Where("is_open = ?", "1").Count(&total)
global.GIN_DB.Table("article_article").Where("is_open = ?", "1").
Order("add_time DESC").Limit(limit).Offset(offset).Scan(&ArticleIndexList)
} else {
global.GIN_DB.Table("article_article").
Where("is_open = ?", "1").
Where("category_id = ?", cateId).
Count(&total)
global.GIN_DB.Table("article_article").
Where("is_open = ?", "1").Where("category_id = ?", cateId).
Order("add_time DESC").Limit(limit).
Offset(offset).Scan(&ArticleIndexList)
}
return ArticleIndexList, total
}
/*
获取所有分类
*/
func FetchCategoryList() (CategoryList []model.Category) {
global.GIN_DB.Table("article_category").
Where("active = ?", "1").
Scan(&CategoryList)
return CategoryList
}
/*
获取文章详情
*/
func FetchArticleDetail(DetailHref request.ArticleDetail) (DetailArticle model.ArticleDetail) {
href := DetailHref.Href
global.GIN_DB.Table("article_article").
Where("is_open = ?", "1").
Where("article_url = ?", href).
Scan(&DetailArticle)
return DetailArticle
}
<file_sep>/03_case_demo/10_RabbmitMQ/01_simple/Recieve/mainRecieve.go
/*
* @Time : 2021-02-16 20:24
* @Author : CoderCharm
* @File : mainRecieve.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import "practice/03_case_demo/10_RabbmitMQ/01_simple/RabbitMQ"
func main() {
rabbitmq := RabbitMQ.NewRabbitMQSimple("wxy")
rabbitmq.ConsumeSimple()
}
<file_sep>/03_case_demo/03_go_mysql/demo_gorm/read_config_test.go
/*
* @Time : 2021-01-02 16:10
* @Author : CoderCharm
* @File : read_config_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package demo_gorm
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"testing"
)
type Mysql struct {
Path string `mapstructure:"path" json:"path" yaml:"path"`
Config string `mapstructure:"config" json:"config" yaml:"config"`
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"`
Username string `mapstructure:"username" json:"username" yaml:"username"`
Password string `mapstructure:"password" json:"password" yaml:"password"`
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"`
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"`
LogMode bool `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"`
}
type Server struct {
Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
}
var (
GlobalConfig Server
)
func Viper(path ...string) *viper.Viper {
var config string
if len(path) == 0 {
config = "config.yaml"
fmt.Printf("您正在使用默认配置文件名称,config的路径为%v\n", config)
} else {
config = path[0]
fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config)
}
v := viper.New()
v.SetConfigFile(config)
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
// 如果配置文件改变可以自动变化
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err := v.Unmarshal(&GlobalConfig); err != nil {
fmt.Println(err)
}
})
if err := v.Unmarshal(&GlobalConfig); err != nil {
fmt.Println(err)
}
return v
}
func TestRead(t *testing.T) {
//_ = Viper()
//fmt.Println(GlobalConfig.Mysql.Path)
}
<file_sep>/03_case_demo/09_custom_web_framework/04_gee_context/gee/gee.go
/*
* @Time : 2021-02-01 20:35
* @Author : CoderCharm
* @File : gee.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package gee
import "net/http"
type HandlerFunc func(c *Context)
type Engine struct {
router *Route
}
// Engine 必须实现 ServeHTTP
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := NewContext(w, r)
e.router.handle(c)
}
func New() *Engine {
return &Engine{router: NewRoute()}
}
// 给router 套一层壳添加 请求方式和请求处理函数
func (e *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
e.router.addRoute(method, pattern, handler)
}
// 添加 GET 方法的请求处理函数
func (e *Engine) GET(pattern string, handler HandlerFunc) {
e.addRoute("GET", pattern, handler)
}
// 添加POST 方法的请求处理函数
func (e *Engine) POST(pattern string, handler HandlerFunc) {
e.addRoute("POST", pattern, handler)
}
// 启动web服务
func (e *Engine) Run(addr string) (err error) {
return http.ListenAndServe(addr, e)
}
<file_sep>/01_getting-started/07_runtime/02_channel/chan4_test.go
/*
* @Time : 2020-12-29 23:20
* @Author : CoderCharm
* @File : chan4_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
生产者 消费者
**/
package _2_channel
import (
"fmt"
"sync"
"testing"
"time"
)
// 不断的生产
func Producer1(c chan int, wg *sync.WaitGroup) {
for i := 0; i <= 10; i++ {
fmt.Println(fmt.Sprintf("生产了++++++ %d", i))
time.Sleep(time.Millisecond * 100)
c <- i
}
// 关闭channel
close(c)
//c <- 22 // 关闭后就不能发了 panic: send on closed channel
wg.Done()
}
// 不断的从chanel里面拿
func Consumer(c chan int, wg *sync.WaitGroup) {
for {
//time.Sleep(time.Millisecond*800)
// 判断生产者是否已经停止了
v, ok := <-c
if ok {
fmt.Println(fmt.Sprintf("-------消费了 %d", v))
} else {
fmt.Println("结束")
break
}
}
wg.Done()
}
func TestChan4(t *testing.T) {
//
var wg sync.WaitGroup
c := make(chan int, 20)
wg.Add(2)
go Producer1(c, &wg)
go Consumer(c, &wg)
wg.Wait()
}
<file_sep>/GinStudy/model/article.go
/*
* @Time : 2020-11-24 10:30
* @Author : CoderCharm
* @File : article.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 对应表数据的 结构体
**/
package model
import "time"
// 推荐文章 轮播
type RecommendArticle struct {
Title string `json:"title"`
Desc string `json:"desc"`
SeoMetaKey string `json:"seo_meta_key"`
Cover string `json:"cover"`
ArticleUrl string `json:"article_url"`
}
/*
列表页 文章查询
*/
type ArticleIndex struct {
Title string `json:"title"`
Cover string `json:"cover"`
ArticleUrl string `json:"article_url"`
ClickCount int64 `json:"click_count"`
AddTime time.Time `json:"add_time"`
}
/*
文章分类
*/
type Category struct {
Id int `json:"id"`
Name string `json:"name"`
}
/*
文章详情
*/
type ArticleDetail struct {
Title string `json:"title"`
Cover string `json:"cover"`
Content string `json:"content"`
ArticleUrl string `json:"article_url"`
ClickCount int64 `json:"click_count"`
AddTime time.Time `json:"add_time"`
}
<file_sep>/02_algorithm/leetcode_everday/338_countBits/count_bite_test.go
/*
* @Time : 2021-03-03 21:32
* @Author : CoderCharm
* @File : count_bite_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
338. 比特位计数 中等
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
示例 1:
输入: 2
输出: [0,1,1]
示例 2:
输入: 5
输出: [0,1,1,2,1,2]
进阶:
给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
要求算法的空间复杂度为O(n)。
你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/counting-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
package _38_countBits
import "testing"
func onesCount(x int) (ones int) {
// 利用位运算的技巧,可以在一定程度上提升计算速度。按位与运算(&)的一个性质是:
// 对于任意整数 x,令 x=x&(x−1),该运算将 x 的二进制表示的最后一个 1 变成 0。
// 因此,对 x 重复该操作,直到 x 变成 0,则操作次数即为 x 的「一比特数」。
for ; x > 0; x &= x - 1 {
ones++
}
return
}
func countBits(num int) []int {
//
bits := make([]int, num+1)
for i := range bits {
bits[i] = onesCount(i)
}
return bits
}
// 解法2 评论上的
func count2Bites(num int) []int {
// 1: 0001 3: 0011 0: 0000
// 2: 0010 6: 0110 1: 0001
// 4: 0100 12: 1100 2: 0010
// 8: 1000 24: 11000 3: 0011
// 16:10000 48: 110000 4: 0100
// 32:100000 96: 1100000 5: 0101
//
// 由上可见:
// 1、如果 i 为偶数,那么f(i) = f(i/2) ,因为 i/2 本质上是i的二进制左移一位,低位补零,所以1的数量不变。
// 2、如果 i 为奇数,那么f(i) = f(i - 1) + 1, 因为如果i为奇数,那么 i - 1必定为偶数,而偶数的二进制最低位一定是0,
// 那么该偶数 +1 后最低位变为1且不会进位,所以奇数比它上一个偶数bit上多一个1,即 f(i) = f(i - 1) + 1。
// 时间复杂度 O(N) num越大循环次数越多
// 空间复杂度 O(N) num越大,res 切片不断的增大
res := []int{0}
for i := 1; i <= num; i++ {
if i%2 == 0 {
res = append(res, res[i/2])
} else {
res = append(res, res[i-1]+1)
}
}
return res
}
func TestCount(t *testing.T) {
t.Log(countBits(2))
t.Log(countBits(5))
t.Log(count2Bites(2))
t.Log(count2Bites(5))
}
<file_sep>/01_getting-started/09_reflect/02_test.go
/*
* @Time : 2021-01-18 18:25
* @Author : CoderCharm
* @File : 02_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _9_reflect
import (
"fmt"
"reflect"
"testing"
)
func TestIntReflect(t *testing.T) {
n := map[int]int{1: 2, 2: 3}
typ := reflect.TypeOf(n) // a reflect.Type
val := reflect.ValueOf(n) // a reflect.Type
t.Log(typ) // int
t.Log(typ.String()) // int
t.Log(typ.Kind()) // 返回此类型的特定种类
// 注意 数字字符串 不能获取字段数量
//num := val.NumField() // 获取值字段的数量
//t.Log(num)
t.Log(val.Kind())
// 数组切片 map
//t.Log(val.Len())
//t.Log(val.String())
//t.Log(val.Kind())
//
//// 通过反射直接修改类型直接修改
//pTyp := reflect.TypeOf(&n)
//pVal := reflect.ValueOf(&n)
//
//t.Log(pTyp)
//
//pVal.Elem().SetInt(999)
//
//t.Log(n)
}
func TestSliceReflect(t *testing.T) {
//sliceA := []string{"a", "b", "c"}
//check(sliceA)
z := -1123
check(z)
}
func check(anyData interface{}) {
t := reflect.TypeOf(anyData)
fmt.Println(t)
v := reflect.ValueOf(anyData)
switch v.Kind() {
case reflect.Slice:
fmt.Println("是一个切片")
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fmt.Println("整数类型")
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
fmt.Println("无符号类型")
case reflect.Float32, reflect.Float64:
fmt.Println("浮点类型")
default:
fmt.Println("有问题")
}
}
<file_sep>/01_getting-started/09_reflect/04_test.go
/*
* @Time : 2021-01-23 11:35
* @Author : CoderCharm
* @File : 04_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
利用反射校验参数
源项目参考地址
https://github.com/flipped-aurora/gin-vue-admin
尝试添加一项 正则校验
**/
package _9_reflect
import (
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
)
// 定义一些简单等参数校验函数
// 小于 <
func Lt(mark string) string {
return "lt=" + mark
}
// 小于等于 <=
func Le(mark string) string {
return "le=" + mark
}
// 等等于 ==
func Eq(mark string) string {
return "eq=" + mark
}
// 大于等于 >=
func Ge(mark string) string {
return "ge=" + mark
}
// 大于 >
func Gt(mark string) string {
return "gt=" + mark
}
// ...其他就不列举了
// 非空
func NotEmpty() string {
return "notEmpty"
}
// 正则判断
func Regex(regex string) string {
return "regex=" + regex
}
func verify(st interface{}, roleMap Rules) (err error) {
// 限定 比较返回值为 以下几个
compareMap := map[string]bool{
"lt": true,
"le": true,
"eq": true,
"ne": true,
"ge": true,
"gt": true,
}
typ := reflect.TypeOf(st)
val := reflect.ValueOf(st)
// 判断待验证参数 是否是结构体 不是直接返回错误
if val.Kind() != reflect.Struct {
return errors.New("expect struct")
}
// 遍历结构体的所有字段
for i := 0; i < val.NumField(); i++ {
// 获取反射后的具体字段
tagVal := typ.Field(i)
val := val.Field(i)
// 判断此字段是否有校验规则 >0 则说明有
if len(roleMap[tagVal.Name]) > 0 {
// 循环此字段的校验规则(一个字段可以存在多个校验规则) 规则为 各个判断类型函数 返回值
for _, v := range roleMap[tagVal.Name] {
switch {
// 非空判断
case v == "notEmpty":
if isBlank(val) {
return errors.New(tagVal.Name + "值不能为空")
}
// 正则校验
case strings.Split(v, "=")[0] == "regex":
if !isRegexMatch(val.String(), v) {
return errors.New(tagVal.Name + "正则校验不合法" + v)
}
// 比较符判断 分割返回值里面的 = 符号 compareMap 确保输入的函数正确
case compareMap[strings.Split(v, "=")[0]]:
// 比较值 val 为反射字段后的值 v为 lt=1等校验值
if !compareVerify(val, v) {
return errors.New(tagVal.Name + "长度或值不在合法范围," + v)
}
default:
fmt.Println("检查 Rules 校验函数输入是否正确: " + v)
}
}
}
}
return nil
}
// 判断是否为空
func isBlank(value reflect.Value) bool {
switch value.Kind() {
case reflect.String:
return value.Len() == 0
case reflect.Bool:
return !value.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return value.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return value.Uint() == 0
case reflect.Float32, reflect.Float64:
return value.Float() == 0
case reflect.Interface, reflect.Ptr:
return value.IsNil()
}
return reflect.DeepEqual(value.Interface(), reflect.Zero(value.Type()).Interface())
}
// 正则校验
func isRegexMatch(value string, VerifyStr string) bool {
regexStr := strings.Split(VerifyStr, "=")[1]
match, _ := regexp.MatchString(regexStr, value)
return match
}
func compareVerify(value reflect.Value, VerifyStr string) bool {
switch value.Kind() {
case reflect.String, reflect.Slice, reflect.Array:
return compare(value.Len(), VerifyStr)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return compare(value.Uint(), VerifyStr)
case reflect.Float32, reflect.Float64:
return compare(value.Float(), VerifyStr)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return compare(value.Int(), VerifyStr)
default:
return false
}
}
func compare(value interface{}, VerifyStr string) bool {
VerifyStrArr := strings.Split(VerifyStr, "=")
val := reflect.ValueOf(value)
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
// 分割后的string转换为整数类型
VInt, VErr := strconv.ParseInt(VerifyStrArr[1], 10, 64)
if VErr != nil {
return false
}
switch {
case VerifyStrArr[0] == "lt":
return val.Int() < VInt
case VerifyStrArr[0] == "le":
return val.Int() <= VInt
case VerifyStrArr[0] == "eq":
return val.Int() == VInt
case VerifyStrArr[0] == "ne":
return val.Int() != VInt
case VerifyStrArr[0] == "ge":
return val.Int() >= VInt
case VerifyStrArr[0] == "gt":
return val.Int() > VInt
default:
return false
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
VInt, VErr := strconv.Atoi(VerifyStrArr[1])
if VErr != nil {
return false
}
switch {
case VerifyStrArr[0] == "lt":
return val.Uint() < uint64(VInt)
case VerifyStrArr[0] == "le":
return val.Uint() <= uint64(VInt)
case VerifyStrArr[0] == "eq":
return val.Uint() == uint64(VInt)
case VerifyStrArr[0] == "ne":
return val.Uint() != uint64(VInt)
case VerifyStrArr[0] == "ge":
return val.Uint() >= uint64(VInt)
case VerifyStrArr[0] == "gt":
return val.Uint() > uint64(VInt)
default:
return false
}
case reflect.Float32, reflect.Float64:
VFloat, VErr := strconv.ParseFloat(VerifyStrArr[1], 64)
if VErr != nil {
return false
}
switch {
case VerifyStrArr[0] == "lt":
return val.Float() < VFloat
case VerifyStrArr[0] == "le":
return val.Float() <= VFloat
case VerifyStrArr[0] == "eq":
return val.Float() == VFloat
case VerifyStrArr[0] == "ne":
return val.Float() != VFloat
case VerifyStrArr[0] == "ge":
return val.Float() >= VFloat
case VerifyStrArr[0] == "gt":
return val.Float() > VFloat
default:
return false
}
default:
return false
}
}
// 任意一个函数
func AnyFunc() string {
return "任意函数的返回值"
}
// 存放验证规则的地方 一个字段可以有多个校验方法
type Rules map[string][]string
var (
// AnyFunc() 为非法的校验函数 避免人为写错
UserInfoVerify = Rules{"Page": {Ge("1"), AnyFunc()}, "PageSize": {Le("50")}, "Name": {Regex(`^\d{3}$`), NotEmpty()}}
)
type UserInfo struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
Name string `json:"name"`
}
func TestVerify(t *testing.T) {
// 参数信息
u := UserInfo{Page: 1, PageSize: 30, Name: "234"} // 合法
//u := UserInfo{Page:1, PageSize:30, Name: "1234"} // Name非法
// 验证参数是否合法
if err := verify(u, UserInfoVerify); err != nil {
t.Log(fmt.Sprintf("验证失败 %s \n", err))
} else {
t.Log("success")
}
}
<file_sep>/03_case_demo/09_custom_web_framework/06_router_group_hook/middleware_test.go
/*
* @Time : 2021-02-03 19:55
* @Author : CoderCharm
* @File : middleware_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"fmt"
"testing"
)
type HandlerFunc func(c *Context)
// HandlersChain defines a HandlerFunc array.
type HandlersChain []HandlerFunc
// 管理中间件的上下文
type Context struct {
// middleware
handlers HandlersChain //存储顺序 [中间件1, 中间件2, 中间件3...., 请求处理函数]
index int
}
func newContext() *Context {
return &Context{
// gin 里面初始化变量
// https://github.com/gin-gonic/gin/blob/master/context.go#L91
index: -1,
}
}
// 下一步调用
func (c *Context) Next() {
// 如果把 Next() c.index++ 去掉,就会一直卡在第一个中间件上了,必然死循环。
// 每调用一次 Next(), c.index 必须得 +1,否则 c.index 就会一直是 0
c.index++ // 0
s := len(c.handlers) // 3
for ; c.index < s; c.index++ {
c.handlers[c.index](c)
}
}
// 直接中断响应
func (c *Context) Fail(code int, err string) {
// 直接让计数下角标 == 中间件数组长度, 即上Next的 index < 3 不成立
c.index = len(c.handlers)
// 返回响应信息等 操作
fmt.Println(err)
}
// A 中间件
func middlewareA(c *Context) {
fmt.Println("A--1")
//c.Fail(500, "中断操作")
c.Next()
fmt.Println("A--2")
}
// B 中间件
func middlewareB(c *Context) {
fmt.Println("B-------1")
c.Next()
fmt.Println("B-------2")
}
// 请求处理到函数
func handleFunc(c *Context) {
fmt.Println("请求处理函数")
}
func TestMiddleware(t *testing.T) {
n := newContext()
n.handlers = append(n.handlers, middlewareA)
n.handlers = append(n.handlers, middlewareB)
n.handlers = append(n.handlers, handleFunc)
// 启动
n.Next()
// A--1
// B-------1
// 请求处理函数
// B-------2
// A--2
// 最终执行顺序就是: A1-> B1 -> 处理函数 -> B2 -> A1
}
<file_sep>/GinStudy/global/global.go
/*
* @Time : 2020-11-19 10:31
* @Author : CoderCharm
* @File : global.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 全局变量
**/
package global
import (
"gin_study/config"
"github.com/go-redis/redis"
"github.com/robfig/cron/v3"
"github.com/spf13/viper"
"go.uber.org/zap"
"gorm.io/gorm"
)
var (
GIN_DB *gorm.DB
GIN_VP *viper.Viper
GIN_CONFIG config.Server
GIN_LOG *zap.Logger
GIN_REDIS *redis.Client
GIN_CRON *cron.Cron
)
<file_sep>/04_desgin_pattern/README.md
## Go设计模式学习案例
- 简单工程模式<file_sep>/01_getting-started/11_os/01_file_size/read_file_test.go
/*
* @Time : 2021/3/15 20:36
* @Author : CoderCharm
* @File : read_file_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
读取本地文件操作
读取文件大小
https://stackoverflow.com/questions/17133590/how-to-get-file-length-in-go
**/
package _1_file_size
import (
"os"
"testing"
)
// 不打开文件直接使用 os.Stat 效率更高。
func readFileSize(path string) (int64, error) {
file, err := os.Stat(path)
if err != nil {
return 0, err
}
// 获取文件大小
size := file.Size()
return size, nil
}
// 打开文件
func readFileSize2(path string) (int64, error) {
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
// 再调用文件资源具柄对象
fi, err := file.Stat()
if err != nil {
return 0, err
}
// 获取文件大小
return fi.Size(), nil
}
func TestReadFile(t *testing.T) {
fileSize, err := readFileSize("./foo.text")
if err != nil {
t.Log(err)
} else {
t.Log(fileSize)
}
}
func TestRead2File(t *testing.T) {
fileSize, err := readFileSize2("./foo.text")
if err != nil {
t.Log(err)
} else {
t.Log(fileSize)
}
}
<file_sep>/GinStudy/model/request/sys_user.go
/*
* @Time : 2021-01-08 20:58
* @Author : CoderCharm
* @File : sys_user.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package request
// User register structure
type Register struct {
Username string `json:"userName"`
Password string `json:"<PASSWORD>"`
NickName string `json:"nickName" gorm:"default:'王小右'"`
HeaderImg string `json:"headerImg" gorm:"default:'https://image.3001.net/images/20200504/1588558613_5eaf7b159c8e9.jpeg'"`
AuthorityId string `json:"authorityId" gorm:"default:888"`
}
// User login structure
type Login struct {
Username string `json:"username"`
Password string `json:"<PASSWORD>"`
Captcha string `json:"captcha"`
CaptchaId string `json:"captchaId"`
}
<file_sep>/01_getting-started/08_panic_recover/demo3_test.go
/*
* @Time : 2021-01-13 19:26
* @Author : CoderCharm
* @File : demo3_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _8_panic_recover
import (
"errors"
"testing"
"time"
)
var (
customErr = errors.New("自定义错误")
)
func TestRecover(t *testing.T) {
// 主线程中的 defer 没有执行
defer println("in main")
go func() {
// `panic` 只会触发当前 `Goroutine` 的 `defer`
defer func() {
if err := recover(); err != nil {
//恢复错误
t.Log("恢复错误")
// 捕获自定义错误
if err == customErr {
t.Log(err)
} else {
t.Log("其他错误")
}
}
}()
defer println("in goroutine")
// 抛出自定义错误
panic(customErr)
}()
time.Sleep(1 * time.Second)
}
<file_sep>/01_getting-started/03_Variable/01_variable/01_make_test.go
/*
* @Time : 2021-01-15 19:56
* @Author : CoderCharm
* @File : 01_make_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _1_variable
import (
"testing"
)
func TestMake(t *testing.T) {
//n := map[string]string{}
//t.Log(n)
//t.Log(reflect.TypeOf(n))
//
//z := make(map[string]string)
//t.Log(z)
//t.Log(reflect.TypeOf(z))
b := []int{1, 2, 3}
t.Log(b)
//f := make([]int{1, 2, 3})
//c[1] = 'c'
//s2 := string(c) // 再转换回 string 类型
//fmt.Printf("%s\n", s2)
}
<file_sep>/GinStudy/config/redis.go
/*
* @Time : 2020-12-18 15:58
* @Author : CoderCharm
* @File : redis.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 读取redis配置
**/
package config
type Redis struct {
DB int `mapstructure:"db" json:"db" yaml:"db"`
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"`
Password string `mapstructure:"password" json:"password" yaml:"password"`
}
<file_sep>/GinStudy/utils/constant.go
/*
* @Time : 2020-11-22 15:31
* @Author : CoderCharm
* @File : constant.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 配置文件名常量
**/
package utils
const (
ConfigEnv = "GIN_CONFIG"
ConfigFile = "config.yaml"
)
<file_sep>/03_case_demo/09_custom_web_framework/03_gee_demo/gee/gee.go
/*
* @Time : 2021-02-01 20:20
* @Author : CoderCharm
* @File : gee.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package gee
import (
"fmt"
"net/http"
)
// HandlerFunc defines the request handler used by gee
type HandlerFunc func(http.ResponseWriter, *http.Request)
// Engine implement the interface of ServeHTTP
type Engine struct {
// 存储请求方法-匹配参数 和 处理请求的函数
router map[string]HandlerFunc
}
// New is the constructor of gee.Engine
func New() *Engine {
return &Engine{router: make(map[string]HandlerFunc)}
}
// 把请求路径 和 处理函数放入 router 这个map中
func (engine *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
key := method + "-" + pattern
engine.router[key] = handler
}
// GET defines the method to add GET request
func (engine *Engine) GET(pattern string, handler HandlerFunc) {
engine.addRoute("GET", pattern, handler)
}
// POST defines the method to add POST request
func (engine *Engine) POST(pattern string, handler HandlerFunc) {
engine.addRoute("POST", pattern, handler)
}
// Run defines the method to start a http server
func (engine *Engine) Run(addr string) (err error) {
return http.ListenAndServe(addr, engine)
}
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
key := req.Method + "-" + req.URL.Path
// 通过方法和请求路径 匹配到 handler请求处理函数
if handler, ok := engine.router[key]; ok {
handler(w, req)
} else {
w.WriteHeader(http.StatusNotFound)
// 没有匹配到则表示 路径和请求方法不存在
_, _ = fmt.Fprintf(w, "404 NOT FOUND: %s\n", req.URL)
}
}
<file_sep>/GinStudy/api/v1/sys_cron.go
/*
* @Time : 2021-01-06 20:11
* @Author : CoderCharm
* @File : sys_cron.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
定时任务调度接口
**/
package v1
<file_sep>/01_getting-started/03_Variable/04_map/map_set_test.go
/*
* @Time : 2020-12-26 21:31
* @Author : CoderCharm
* @File : ch8_map_set.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _04_map
import (
"testing"
)
func TestMapSet(t *testing.T) {
mySet := map[int]bool{}
mySet[1] = true
n := 1
if mySet[n] {
t.Log("n is existing")
} else {
t.Log("n not existing")
}
mySet[3] = false
t.Log(len(mySet))
delete(mySet, 1)
if mySet[n] {
t.Log("n is existing")
} else {
t.Log("n not existing")
}
}
<file_sep>/03_case_demo/03_go_mysql/demo_mysql/curd_test.go
/*
* @Time : 2021-01-01 17:39
* @Author : CoderCharm
* @File : curd_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package demo_mysql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"testing"
"time"
)
type Employee struct {
Id int `json:"id"`
Name string `json:"name"`
City string `json:"city"`
}
var emp Employee
var empList []Employee
func dbConn() *sql.DB {
db, err := sql.Open("mysql", "root:Admin12345-@tcp(172.16.137.129:3306)/temp_db_date?timeout=90s&collation=utf8mb4_unicode_ci")
if err != nil {
panic(err)
}
// See "Important settings" section. https://github.com/go-sql-driver/mysql#important-settings
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
return db
}
func SelectDB(db *sql.DB) []Employee {
rows, err := db.Query("SELECT * FROM employee ORDER BY id DESC")
if err != nil {
panic(err.Error())
}
for rows.Next() {
err = rows.Scan(&emp.Id, &emp.Name, &emp.City)
if err != nil {
panic(err.Error())
}
empList = append(empList, emp)
}
return empList
}
func InsertDB(name, city string, db *sql.DB) (lastId int64, affectId int64) {
rows, err := db.Exec("INSERT INTO employee(`name`, city) VALUE (?, ?)", name, city)
if err != nil {
panic("数据插入错误")
}
lastId, err = rows.LastInsertId()
affectId, err = rows.RowsAffected()
return lastId, affectId
}
func UpdateDB(id int, name string, city string, db *sql.DB) (lastId, affectId int64) {
rows, err := db.Exec("UPDATE employee SET name=?, city=? WHERE id=?", name, city, id)
if err != nil {
panic(fmt.Sprintf("更新错误 %s", err))
}
lastId, err = rows.LastInsertId()
affectId, err = rows.RowsAffected()
return lastId, affectId
}
func DeleteDB(id int, db *sql.DB) (lastId, affectId int64) {
//rows, err := db.Exec("UPDATE employee SET name=?, city=? WHERE id=?", name, city, id)
rows, err := db.Exec("DELETE FROM employee WHERE id=?", id)
if err != nil {
panic(fmt.Sprintf("更新错误 %s", err))
}
//rows.LastInsertId()
//lastId := rows.LastInsertId()
//rows.RowsAffected()
lastId, err = rows.LastInsertId()
affectId, err = rows.RowsAffected()
return lastId, affectId
}
func TestCURD(t *testing.T) {
db := dbConn()
defer db.Close()
res := SelectDB(db)
fmt.Println(fmt.Sprintf("查询结果: %+v \n", res))
//lastId, affectId := InsertDB("小明", "wuhan", db)
//fmt.Println(fmt.Sprintf("插入结果rowsId: %d", lastId))
//fmt.Println(fmt.Sprintf("影响函数: %d", affectId))
//lastId, affectId := UpdateDB(3,"小明", "湖北", db)
//fmt.Println(fmt.Sprintf("插入结果rowsId: %d", lastId))
//fmt.Println(fmt.Sprintf("影响函数: %d", affectId))
lastId, affectId := DeleteDB(5, db)
fmt.Println(fmt.Sprintf("插入结果rowsId: %d", lastId))
fmt.Println(fmt.Sprintf("影响函数: %d", affectId))
}
<file_sep>/03_case_demo/06_cron_task/README.md
# 定时任务
## 参考
- [https://github.com/robfig/cron](https://github.com/robfig/cron)
- [ cron 文档](https://godoc.org/github.com/robfig/cron)<file_sep>/docs/Linux/elasticsearch/ch01_desc.md
# Elasticsearch 介绍
## Docker 安装运行 ES
docker 官方 es 镜像地址: https://hub.docker.com/_/elasticsearch
拉取镜像
```
docker pull elasticsearch:7.10.1
```
启动
```shell
docker run --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -d elasticsearch:7.10.1
```
本地访问以下地址: `http://127.0.0.1:9200/`, 可以访问出现以下内容则说明安装正常。
```json
{
"name": "cc4951b1e3a3",
"cluster_name": "docker-cluster",
"cluster_uuid": "Yn2FIYPURbmWLaMcQQDTJQ",
"version": {
"number": "7.10.1",
"build_flavor": "default",
"build_type": "docker",
"build_hash": "1c34507e66d7db1211f66f3513706fdf548736aa",
"build_date": "2020-12-05T01:00:33.671820Z",
"build_snapshot": false,
"lucene_version": "8.7.0",
"minimum_wire_compatibility_version": "6.8.0",
"minimum_index_compatibility_version": "6.0.0-beta1"
},
"tagline": "You Know, for Search"
}
```
## 安装jk
https://github.com/medcl/elasticsearch-analysis-ik/releases
<file_sep>/02_algorithm/leetcode_everday/227_basic_calc_2/calc_test.go
/*
* @Time : 2021/3/11 23:52
* @Author : CoderCharm
* @File : calc_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
中级
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
示例 1:
输入:s = "3+2*2"
输出:7
示例 2:
输入:s = " 3/2 "
输出:1
示例 3:
输入:s = " 3+5 / 2 "
输出:5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/basic-calculator-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1 <= s.length <= 3 * 105
s 由整数和算符 ('+', '-', '*', '/') 组成,中间由一些空格隔开
s 表示一个 有效表达式
表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
题目数据保证答案是一个 32-bit 整数
思路:
1 减法可以用 负数表示
**/
package basic_calc_2
import "testing"
func calculate(s string) (res int) {
// 用于存储 计算好乘法和除法的数据 最后各项相加即可
var stack []int
// 默认计算符号为 + 号
preSign := '+'
// 由于不使用eval函数 用这种方式把字符串还原成数字
num := 0
for k, v := range s {
// 判断是否是数字
isDigit := '0' <= v && v <= '9'
if isDigit {
// 把字符串还原成数字
num = num*10 + int(v-'0')
}
// 根据运算符判断操作
if !isDigit && v != ' ' || k == len(s)-1 {
switch preSign {
case '+':
stack = append(stack, num)
case '-':
stack = append(stack, -num)
case '*':
// 乘除法 可以直接与栈顶元素计算
stack[len(stack)-1] *= num
default:
stack[len(stack)-1] /= num
}
preSign = v
num = 0
}
}
// 栈内 数据累加
for _, v := range stack {
res += v
}
return
}
func TestCalc(t *testing.T) {
t.Log(calculate(" 3/2 "))
num := 0
num = num*10 + int('3'-'0')
t.Log(num)
}
<file_sep>/03_case_demo/08_casbin/03_casbin_gorm/demo_test.go
/*
* @Time : 2021-01-20 21:44
* @Author : CoderCharm
* @File : demo_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _3_casbin_gorm
import (
"fmt"
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/util"
gormadapter "github.com/casbin/gorm-adapter/v3"
"strings"
"testing"
)
//@author: [piexlmax](https://github.com/piexlmax)
//@function: ParamsMatch
//@description: 自定义规则函数
//@param: fullNameKey1 string, key2 string
//@return: bool
func ParamsMatch(fullNameKey1 string, key2 string) bool {
key1 := strings.Split(fullNameKey1, "?")[0]
// 剥离路径后再使用casbin的keyMatch2
return util.KeyMatch2(key1, key2)
}
//@author: [piexlmax](https://github.com/piexlmax)
//@function: ParamsMatchFunc
//@description: 自定义规则函数
//@param: args ...interface{}
//@return: interface{}, error
func ParamsMatchFunc(args ...interface{}) (interface{}, error) {
name1 := args[0].(string)
name2 := args[1].(string)
return ParamsMatch(name1, name2), nil
}
// 动态添加角色权限
func TestCasbin(t *testing.T) {
a, _ := gormadapter.NewAdapter("mysql", "root:Admin12345-@tcp(172.16.137.129:3306)/go_casbin", true)
e, err := casbin.NewEnforcer("./model.conf", a)
if err != nil {
panic(err)
}
e.AddFunction("ParamsMatch", ParamsMatchFunc)
_ = e.LoadPolicy()
ok, err := e.AddPolicy("99", "/api/getJob", "GET")
//sub := "10" // the user that wants to access a resource.
//obj := "/api/getList" // the resource that is going to be accessed.
//act := "GET" // the operation that the user performs on the resource.
//
////验证
//ok, err := e.Enforce(sub, obj, act)
//
if err != nil {
// handle err
t.Log(fmt.Sprintf("错误 %v", err))
}
if ok == true {
// permit alice to read data1
t.Log("ok")
} else {
// deny the request, show an error
t.Log("fail")
}
}
<file_sep>/03_case_demo/09_custom_web_framework/06_router_group_hook/gee/context.go
/*
* @Time : 2021-02-02 20:15
* @Author : CoderCharm
* @File : context.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package gee
import (
"encoding/json"
"fmt"
"net/http"
)
// 用于返回JSON数据
type H map[string]interface{}
// 存储请求上下文信息
type Context struct {
// 其他对象
Writer http.ResponseWriter
Req *http.Request
// 请求信息
Path string
Method string
Params map[string]string
// 响应信息
StatusCode int
// 中间件
handlers []HandlerFunc
index int
}
// 构建上下文实例
func NewContext(w http.ResponseWriter, r *http.Request) *Context {
return &Context{
Req: r,
Writer: w,
StatusCode: 200,
Path: r.URL.Path,
Method: r.Method,
index: -1, // 用于记录执行到那个中间件
}
}
//
func (c *Context) Next() {
c.index++
s := len(c.handlers)
for ; c.index < s; c.index++ {
c.handlers[c.index](c)
}
}
// 直接中断响应
func (c *Context) Fail(code int, err string) {
c.index = len(c.handlers)
c.JSON(code, H{"message": err})
}
func (c *Context) Param(key string) string {
value, _ := c.Params[key]
return value
}
// 获取url的查询参数
func (c *Context) Query(name string) string {
return c.Req.URL.Query().Get(name)
}
// 获取表单参数
func (c *Context) PostForm(key string) string {
return c.Req.FormValue(key)
}
// 设置状态码
func (c *Context) Status(code int) {
c.StatusCode = code
c.Writer.WriteHeader(code)
}
// 设置header
func (c *Context) SetHeader(key string, value string) {
c.Writer.Header().Set(key, value)
}
// 快速构建响应
// 返回字符串
func (c *Context) String(code int, format string, values ...interface{}) {
c.SetHeader("Content-Type", "text/plain;charset=utf-8")
c.Status(code)
_, _ = c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}
// 返回json数据
func (c *Context) JSON(code int, obj interface{}) {
c.SetHeader("Content-Type", "application/json;charset=utf-8")
c.Status(code)
encoder := json.NewEncoder(c.Writer)
if err := encoder.Encode(obj); err != nil {
http.Error(c.Writer, err.Error(), 500)
}
}
// 返回字节流数据
func (c *Context) Data(code int, data []byte) {
c.Status(code)
_, _ = c.Writer.Write(data)
}
// 返回html数据
func (c *Context) HTML(code int, html string) {
c.SetHeader("Content-Type", "text/html;charset=utf-8")
c.Status(code)
_, _ = c.Writer.Write([]byte(html))
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/07_struct/04_serialize/main.go
/*
结构体的序列化 和反序列化
*/
package main
import (
"encoding/json"
"fmt"
)
type Cat struct {
// 大写公有原则 小写私有
Name string `json:"Name"` // 序列化时取别名
Color string `json:"Color"`
}
func main() {
// 实力化一个结构体
Tom := Cat{Name: "Tom", Color: "grey"}
// 序列化
v, err := json.Marshal(&Tom)
if err != nil {
fmt.Println("序列化出错了")
}
fmt.Println(string(v))
var t Cat
// json格式到字符串
jsonRes := `{"Name": "HaHa","Color": "qqq"}`
// 反序列化
err = json.Unmarshal([]byte(jsonRes), &t)
if err != nil {
fmt.Println("反序列化出错了")
}
fmt.Println(t)
}
<file_sep>/GinStudy/utils/md5.go
/*
* @Time : 2021-01-07 20:27
* @Author : CoderCharm
* @File : md5.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package utils
import (
"crypto/md5"
"encoding/hex"
)
func MD5V(str []byte) string {
h := md5.New()
h.Write(str)
return hex.EncodeToString(h.Sum(nil))
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/07_struct/README.md
# go 结构体
> go 结构体相当于类了
```go
// 普通实例化结构体
P := person{"Tom", 25}
//
P := new(person) 获取到结构体地址
```<file_sep>/docs/Golang/rabbitMQ/ch01_desc.md
# RabbitMQ 介绍<file_sep>/02_algorithm/leetcode_everday/922_sort_by_parity/sort_by_parity_test.go
/*
* @Time : 2021/3/15 23:02
* @Author : CoderCharm
* @File : sort_by_parity_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
922. 按奇偶排序数组 II 难度简单
给定一个非负整数数组A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当A[i] 为奇数时,i也是奇数;当A[i]为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
示例:
输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
提示:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路: 用两个指针 一个为奇数 一个为偶数,不断移动其中一个,每次移动两个单位,根据条件跳转位置。
时间复杂度: O(N)
空间复杂度:O(1)
**/
package _22_sort_by_parity
import "testing"
// 假设输入的值是正确的
func sortArrayByParityII(nums []int) []int {
// 使用双指针 i为偶数下角标 j为奇数
for i, j := 0, 1; i < len(nums); i += 2 {
// 判断是否为奇数
if nums[i]%2 == 1 {
// 循环找到奇数的值
for nums[j]%2 == 1 {
j += 2
}
// 两树互换
nums[i], nums[j] = nums[j], nums[i]
}
}
return nums
}
func TestSort(t *testing.T) {
t.Log(sortArrayByParityII([]int{4, 2, 5, 7}))
}
<file_sep>/05_micro_service/README.md
# 微服务学习笔记
关于微服务的介绍,以及相关概念。
[从单体应用到微服务架构 中文版](https://wangwei1237.gitee.io/monolith-to-microservices/) https://wangwei1237.gitee.io/monolith-to-microservices/
学一个新技术,比如 A 这个新技术,我习惯用这样的通用法则(出自郝斌老师C语言):
- 什么是A?
- 为什么需要A?
- 如何使用A? (需要注意的问题,也就是避免踩坑)
- A的重要程度? (决定是否需要花大量精力学习)
个人笔记只存储相关代码,没有阐述过多概念,可以自己了解这些微服务相关的概念。
## 知识点
- 服务注册配置中心 consul or etcd
<file_sep>/03_case_demo/07_jwt/generate_token_test.go
/*
* @Time : 2021-01-05 20:47
* @Author : CoderCharm
* @File : generate_token_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac
生成Token
**/
package _7_jwt
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"testing"
"time"
)
const Key = "kkkkk"
func TestGenerateToken(t *testing.T) {
//n := time.Now().Unix()
//
//fmt.Println(n)
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"foo": "bar",
//"any_key": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
"any_key": time.Now().Unix(),
})
//Key := "kkkkk"
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(Key))
if err != nil {
fmt.Printf("错误: %s \n", err)
}
fmt.Println(tokenString)
}
<file_sep>/02_algorithm/sorts/README.md
## 各种排序
可以通过这个网站查看各种排序动态图式
```
https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html
```
先把基础算法在过一遍,然后在刷`leetcode`,因为有的题目,完全没思路。<file_sep>/01_getting-started/04_Control_statements_and_functions/06_02_func.go
/*
函数传入和返回不同类型的参数
*/
package main
import "fmt"
func main() {
a := [3]int{4, 5, 6}
fmt.Println(test1(a))
}
func test1(t1 [3]int) (v int) {
z := 0
for _, v := range t1 {
z += v
}
return v
}
<file_sep>/01_getting-started/11_os/README.md
## 记录`os`模块操作<file_sep>/GinStudy/model/sys_casbin.go
/*
* @Time : 2021-01-07 19:20
* @Author : CoderCharm
* @File : sys_casbin.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package model
type CasbinModel struct {
Ptype string `json:"ptype" gorm:"column:p_type"`
AuthorityId string `json:"rolename" gorm:"column:v0"`
Path string `json:"path" gorm:"column:v1"`
Method string `json:"method" gorm:"column:v2"`
}
<file_sep>/03_case_demo/09_custom_web_framework/06_router_group_hook/router_test.go
/*
* @Time : 2021-02-03 19:46
* @Author : CoderCharm
* @File : router_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
简单 写一个 路由分组的例子 来测试一下
**/
package main
import (
"fmt"
"testing"
)
// 路由分组
// https://github.com/gin-gonic/gin/blob/master/routergroup.go#L41
type RouterGroup struct {
prefix string // 前缀
engine *Engine // 内部的Engine始终保证为共享的一个
parent *RouterGroup // 父路由
}
// 核心
type Engine struct {
*RouterGroup // 使Engine 也拥有RouterGroup的方法
}
// Get方法 这里没有实现响应处理函数
func (group *RouterGroup) Get(pattern string) {
fmt.Printf("Get %s%s\n", group.prefix, pattern)
}
// 创建路由分组
func (group *RouterGroup) Group(prefix string) *RouterGroup {
return &RouterGroup{
prefix: group.prefix + prefix, // 前缀为上一个 路由分组前缀 加下一个
parent: group, // 当前路由设置为父路由
}
}
func New() *Engine {
engine := &Engine{}
// RouterGroup里面的 engine属性为 自身的engine 确保所有的engine 为一个
engine.RouterGroup = &RouterGroup{engine: engine}
return engine
}
func TestRouter(t *testing.T) {
// 创建实例
r := New()
r.Get("/index")
// 路由分组
api := r.Group("/api")
api.Get("/123")
// api子路由分组
v1 := api.Group("/v1")
v1.Get("/666")
// 输出
// Get /index
// Get /api/123
// Get /api/v1/666
}
<file_sep>/GinStudy/model/sys_authority_menu.go
/*
* @Time : 2021-01-07 19:17
* @Author : CoderCharm
* @File : sys_authority_menu.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package model
type SysMenu struct {
SysBaseMenu
MenuId string `json:"menuId" gorm:"comment:菜单ID"`
AuthorityId string `json:"-" gorm:"comment:角色ID"`
Children []SysMenu `json:"children" gorm:"-"`
Parameters []SysBaseMenuParameter `json:"parameters" gorm:"foreignKey:SysBaseMenuID;references:MenuId"`
}
func (s SysMenu) TableName() string {
return "authority_menu"
}
<file_sep>/GinStudy/utils/callUrl/call_url.go
/*
* @Time : 2020-12-31 11:16
* @Author : CoderCharm
* @File : call_url.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 业务回掉地址
**/
package callUrl
<file_sep>/03_case_demo/08_casbin/02_casbin_gorm/01_test.go
/*
* @Time : 2021-01-19 21:13
* @Author : CoderCharm
* @File : 01_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
go get github.com/casbin/gorm-adapter/v3
**/
package _2_casbin_gorm
import (
"github.com/casbin/casbin/v2"
gormadapter "github.com/casbin/gorm-adapter/v3"
"testing"
)
// 动态添加角色权限
func TestCasbin(t *testing.T) {
a, _ := gormadapter.NewAdapter("mysql", "root:Admin12345-@tcp(172.16.137.129:3306)/go_casbin", true)
e, err := casbin.NewEnforcer("./model.conf", a)
if err != nil {
panic(err)
}
// 查询
//res := e.GetAllSubjects()
//res := e.GetAllObjects()
//res := e.GetAllActions()
//res := e.GetPolicy()
res := e.GetFilteredPolicy(0, "10")
t.Log(res)
// 动态添加策略 自己定义比如 权限id 接口 请求
//res, err := e.AddPolicy("20", "/api/delUser", "DELETE")
// AddNamedPolicies 添加多个
// 删除策略
//res, err := e.RemovePolicy("10", "/api/getUserList", "GET")
// RemovePolicies 删除多个
// 更新策略 UpdatePolicy 此方法暂时未实现
//res, err := e.UpdatePolicy([]string{"10", "/api/getUserList", "GET"}, []string{"100", "/api/getUserList", "GET"})
//if err != nil{
// panic(err)
//}else{
// t.Log(res)
//}
//sub := "Jack" // the user that wants to access a resource.
//obj := "data1" // the resource that is going to be accessed.
//act := "read" // the operation that the user performs on the resource.
// 验证
//ok, err := e.Enforce(sub, obj, act)
//
//if err != nil {
// // handle err
// t.Log(fmt.Sprintf("错误 %v", err))
//}
//
//if ok == true {
// // permit alice to read data1
// t.Log("ok")
//} else {
// // deny the request, show an error
// t.Log("fail")
//}
}
<file_sep>/go.mod
module practice
go 1.15
require (
github.com/asim/go-micro/cmd/protoc-gen-micro/v3 v3.0.0-20210120213617-60010e82e2c7 // indirect
github.com/asim/go-micro/v3 v3.0.1
github.com/casbin/casbin/v2 v2.20.2
github.com/casbin/gorm-adapter/v3 v3.0.5
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/elazarl/goproxy v0.0.0-20210110162100-a92cc753f88e // indirect
github.com/fsnotify/fsnotify v1.4.9
github.com/go-sql-driver/mysql v1.5.0
github.com/golang/protobuf v1.4.3
github.com/google/uuid v1.1.2
github.com/kr/text v0.2.0 // indirect
github.com/magiconair/properties v1.8.4 // indirect
github.com/micro/go-micro/v2 v2.9.1
github.com/micro/go-plugins/config/source/consul/v2 v2.9.1 // indirect
github.com/micro/go-plugins/registry/consul/v2 v2.9.1 // indirect
github.com/mitchellh/mapstructure v1.4.0 // indirect
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
github.com/parnurzeal/gorequest v0.2.16
github.com/pelletier/go-toml v1.8.1 // indirect
github.com/pkg/profile v1.5.0 // indirect
github.com/qiniu/api.v7/v7 v7.8.0
github.com/robfig/cron/v3 v3.0.1
github.com/spf13/afero v1.5.1 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/spf13/cobra v1.1.1
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.7.1
github.com/streadway/amqp v1.0.0
github.com/uber/jaeger-client-go v2.25.0+incompatible // indirect
github.com/uber/jaeger-lib v2.4.0+incompatible // indirect
golang.org/x/net v0.0.0-20201224014010-6772e930b67b // indirect
golang.org/x/sys v0.0.0-20201231184435-2d18734c6014 // indirect
golang.org/x/text v0.3.4 // indirect
golang.org/x/tools v0.0.0-20191216173652-a0e659d51361
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d // indirect
google.golang.org/grpc v1.34.0
google.golang.org/protobuf v1.25.0
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 // indirect
gorm.io/driver/mysql v1.0.3
gorm.io/gorm v1.20.9
moul.io/http2curl v1.0.0 // indirect
)
<file_sep>/03_case_demo/09_custom_web_framework/05_gee_dynamic_route/main.go
/*
* @Time : 2021-02-02 19:05
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
这一章 路由知识 没有细究
性能肯定是不如 04_gee_context 因为动态路由匹配这里,不如上一章 map[key] 匹配效率高。
# 路由匹配的第三方库
https://github.com/julienschmidt/httprouter
django 1.x 版本是用正则匹配路由,后面2.x+版本就改了
路由参数这一块 实现起来感觉有点绕,而且也不常用路径参数,一般用Query参数居多
核心就是 insert 和 search 对路由操作的方法。
// 路由结构体改造 两个属性
type router struct {
Roots map[string]*node # 存储节点信息
Handlers map[string]HandlerFunc # 存储所有的路由信息 和 请求处理函数
}
**/
package main
import (
"log"
"net/http"
"practice/03_case_demo/09_custom_web_framework/05_gee_dynamic_route/gee"
)
func main() {
r := gee.New()
r.GET("/", func(c *gee.Context) {
c.HTML(http.StatusOK, "<h1>Hello Gee</h1>")
})
r.GET("/hello", func(c *gee.Context) {
// expect /hello?name=大家好
c.String(http.StatusOK, "gee %s, you're at %s\n", c.Query("name"), c.Path)
})
r.GET("/hello/:name", func(c *gee.Context) {
// expect /hello/你好
c.String(http.StatusOK, "gee %s, you're at %s\n", c.Param("name"), c.Path)
})
r.POST("/hello", func(c *gee.Context) {
c.JSON(200, gee.H{
"hello": "I'am fine!",
})
})
r.GET("/assets/*filepath", func(c *gee.Context) {
c.JSON(http.StatusOK, gee.H{"filepath": c.Param("filepath")})
})
// 可以不暴露出 Router 该成小写
log.Println(r.Router.Roots)
log.Println(r.Router.Handlers)
_ = r.Run("127.0.0.1:7054")
}
<file_sep>/01_getting-started/10_pprof/cpu_test/main.go
/*
* @Time : 2021-02-21 19:44
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
cd 当前文件目录下
go run main.go > cpu.pprof
// web界面查看
go tool pprof -http=:9999 cpu.pprof
// 交互界面查看
go tool pprof cpu.pprof
> help // 查看所有命令
**/
package main
import (
"math/rand"
"os"
"runtime/pprof"
"time"
)
// 随机生成 整型数组
func generate(n int) []int {
rand.Seed(time.Now().UnixNano())
nums := make([]int, 0)
for i := 0; i < n; i++ {
nums = append(nums, rand.Int())
}
return nums
}
// 冒泡 排序
func bubbleSort(arr []int) []int {
swapped := true
for swapped {
swapped = false
for i := 0; i < len(arr)-1; i++ {
if arr[i+1] > arr[i] {
arr[i+1], arr[i] = arr[i], arr[i+1]
swapped = true
}
}
}
return arr
}
func main() {
_ = pprof.StartCPUProfile(os.Stdout)
defer pprof.StopCPUProfile()
n := 10
for i := 0; i < 5; i++ {
nums := generate(n)
bubbleSort(nums)
n *= 10
}
}
<file_sep>/GinStudy/model/request/jwt.go
/*
* @Time : 2021-01-08 20:30
* @Author : CoderCharm
* @File : jwt.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package request
import (
"github.com/dgrijalva/jwt-go"
uuid "github.com/satori/go.uuid"
)
// Custom claims structure
type CustomClaims struct {
UUID uuid.UUID
ID uint
Username string
NickName string
AuthorityId string
BufferTime int64
jwt.StandardClaims
}
<file_sep>/GinStudy/docs/docs.go
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag
package docs
import (
"bytes"
"encoding/json"
"strings"
"github.com/alecthomas/template"
"github.com/swaggo/swag"
)
var doc = `{
"schemes": {{ marshal .Schemes }},
"swagger": "2.0",
"info": {
"description": "{{.Description}}",
"title": "{{.Title}}",
"contact": {},
"version": "{{.Version}}"
},
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/mini/api/article/get/category": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"ArticleAPI"
],
"summary": "获取文章分类",
"responses": {
"200": {
"description": "{\"code\":200,\"msg\":\"success\",\"data\":{}}",
"schema": {
"type": "string"
}
}
}
}
},
"/mini/api/article/get/detail": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"ArticleAPI"
],
"summary": "获取文章详情",
"parameters": [
{
"description": "文章href链接",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/request.ArticleDetail"
}
}
],
"responses": {
"200": {
"description": "{\"code\":200,\"msg\":\"success\",\"data\":{}}",
"schema": {
"type": "string"
}
}
}
}
},
"/mini/api/article/get/list": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"ArticleAPI"
],
"summary": "获取文章列表",
"parameters": [
{
"description": "分页",
"name": "pageInfo",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/request.PageInfo"
}
},
{
"description": "文章分类",
"name": "cateInfo",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/request.ArticleCategory"
}
}
],
"responses": {
"200": {
"description": "{\"code\":200,\"msg\":\"success\",\"data\":{}}",
"schema": {
"type": "string"
}
}
}
}
},
"/mini/api/article/get/recommend": {
"get": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"ArticleAPI"
],
"summary": "获取推荐文章",
"responses": {
"200": {
"description": "{\"code\":200,\"msg\":\"success\",\"data\":{}}",
"schema": {
"type": "string"
}
}
}
}
}
},
"definitions": {
"request.ArticleCategory": {
"type": "object",
"properties": {
"cateId": {
"type": "integer"
}
}
},
"request.ArticleDetail": {
"type": "object",
"properties": {
"href": {
"type": "string"
}
}
},
"request.PageInfo": {
"type": "object",
"properties": {
"page": {
"type": "integer"
},
"pageSize": {
"type": "integer"
}
}
}
}
}`
type swaggerInfo struct {
Version string
Host string
BasePath string
Schemes []string
Title string
Description string
}
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = swaggerInfo{
Version: "",
Host: "",
BasePath: "",
Schemes: []string{},
Title: "",
Description: "",
}
type s struct{}
func (s *s) ReadDoc() string {
sInfo := SwaggerInfo
sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1)
t, err := template.New("swagger_info").Funcs(template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
}).Parse(doc)
if err != nil {
return doc
}
var tpl bytes.Buffer
if err := t.Execute(&tpl, sInfo); err != nil {
return doc
}
return tpl.String()
}
func init() {
swag.Register(swag.Name, &s{})
}
<file_sep>/01_getting-started/02_Package/util/name.go
package util2
var Name = "This is util"
<file_sep>/01_getting-started/03_Variable/03_array/02_array_test.go
/*
* @Time : 2020-10-15 09:55
* @Author : CoderCharm
* @File : test02_array.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
快速判断字符串是否在一个数组中 类似Python in 函数
https://mp.weixin.qq.com/s/ffcGphLoU-V-TO31wbJjsg
**/
package _3_array
import (
"fmt"
"sort"
"testing"
)
// 首先用循环实现 但是这种方式有一个弊端,就是要遍历整个字符串数组 这是一个非常费时间的操作
func loopIn(target string, strArray []string) bool {
for _, element := range strArray {
if target == element {
return true
}
}
return false
}
// 如果是有序的整型数组,那么我们可以使用二分查找,把时间复杂度O(n)降到对数时间复杂度。字符串能不能也这样操作呢?实际上是可以的。
func in(target string, strArray []string) bool {
// sort.Strings()函数,可以对字符串数组进行排序
sort.Strings(strArray)
// sort.SearchStrings()函数,会用二分法在一个有序字符串数组中寻找特定字符串的索引
index := sort.SearchStrings(strArray, target)
if index < len(strArray) && strArray[index] == target {
return true
}
return false
}
func TestArray(t *testing.T) {
nameList := []string{"赵云", "王小右", "张飞"}
myName := "王小右"
fmt.Println(loopIn(myName, nameList))
fmt.Println(in(myName, nameList))
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/07_struct/03_struct/main.go
package main
import (
"fmt"
)
// 声明一个结构体
type Cat struct {
name string
color string
sex bool
couple Mouse // 这里赋值为 另一个结构体, 如果和结构体名一样 可以省略一个
}
// 结构体挂载方法
func (c *Cat) CaptureMouse(name string) (res bool) {
if c.name == name {
fmt.Println("名字为Tom,能捉到老鼠")
// 由于使用了指针, 可以改变结构体的值
c.name = "old tom "
return true
} else {
fmt.Println("名字不为Tom, 捉不到老鼠")
return false
}
}
// 在定义一个结构体
type Mouse struct {
name string
color string
sex bool
}
// 结构体挂载方法 不使用指针
func (m Mouse) Eat(stuff string) (res bool) {
if stuff == "奶酪" {
fmt.Println(m.name, "喜欢吃", stuff)
// 不能改变外部结构体的值
m.name = "old jerry"
return true
} else {
fmt.Println(m.name, "不喜欢吃", stuff)
return false
}
}
// 模拟构造方法
func NewMouse(name string, color string, sex bool) (m Mouse) {
return Mouse{
name: name,
color: color,
sex: sex,
}
}
func main() {
// 实例化结构体
Tom := Cat{
name: "Tom",
color: "white",
sex: true,
couple: Mouse{
name: "Jerry",
},
}
// 调用方法
res := Tom.CaptureMouse("Tom")
fmt.Println(res)
fmt.Println(Tom)
// 通过子类属性调用子类的方法(我自己取的名字)
Tom.couple.Eat("糖")
Tom.couple.Eat("奶酪")
// 构造方法实例化
Tuffy := Mouse{"Tuffy", "grey", true}
fmt.Println(Tuffy)
}
<file_sep>/GinStudy/initialize/router.go
/*
* @Time : 2020-11-17 11:35
* @Author : CoderCharm
* @File : router.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 初始化路由
**/
package initialize
import (
_ "gin_study/docs"
"gin_study/global"
"gin_study/middleware"
"gin_study/router"
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
)
func Routers() *gin.Engine {
var Router = gin.Default()
// 跨域
Router.Use(middleware.CORSMiddleware())
if global.GIN_CONFIG.System.Env == "debug" {
Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
// 方便统一添加路由组前缀 多服务器上线使用
V1ApiGroup := Router.Group("/api/v1")
router.InitUserRouter(V1ApiGroup) // 注册用户路由
router.InitArticleRouter(V1ApiGroup) // 注册文章路由
return Router
}
<file_sep>/03_case_demo/08_casbin/01_official_demo/casbin_test.go
/*
* @Time : 2021-01-18 23:48
* @Author : CoderCharm
* @File : casbin_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
前置条件先搞懂 各个模型 策略的关系
https://casbin.org/docs/zh-CN/how-it-works
https://casbin.org/zh-CN/editor
本文件代码来源
https://casbin.org/docs/zh-CN/get-started
go get github.com/casbin/casbin/v2
**/
package _1_official_demo
import (
"fmt"
"github.com/casbin/casbin/v2"
"testing"
)
// 最基础的demo
func TestCasbin01(t *testing.T) {
e, err := casbin.NewEnforcer("./model.conf", "./policy.csv")
sub := "nick" // the user that wants to access a resource.
obj := "data1" // the resource that is going to be accessed.
act := "read" // the operation that the user performs on the resource.
ok, err := e.Enforce(sub, obj, act)
if err != nil {
// handle err
t.Log(fmt.Sprintf("错误 %v", err))
}
if ok == true {
// permit alice to read data1
t.Log("ok")
} else {
// deny the request, show an error
t.Log("fail")
}
}
// 动态添加角色权限
func TestCasbin02(t *testing.T) {
e, err := casbin.NewEnforcer("./model.conf", "./policy.csv")
sub := "Jack" // the user that wants to access a resource.
obj := "data1" // the resource that is going to be accessed.
act := "read" // the operation that the user performs on the resource.
// 动态添加策略
added, err := e.AddPolicy("Jack", "data1", "read")
t.Log(added)
ok, err := e.Enforce(sub, obj, act)
if err != nil {
// handle err
t.Log(fmt.Sprintf("错误 %v", err))
}
if ok == true {
// permit alice to read data1
t.Log("ok")
} else {
// deny the request, show an error
t.Log("fail")
}
}
<file_sep>/01_getting-started/09_reflect/03_test.go
/*
* @Time : 2021-01-22 08:54
* @Author : CoderCharm
* @File : 03_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _9_reflect
import (
"fmt"
"reflect"
"testing"
)
func TestReflect03(t *testing.T) {
// Go里面不能 直接比较两个 slice map之类的
// https://stackoverflow.com/questions/37900696/why-cant-go-slice-be-used-as-keys-in-go-maps-pretty-much-the-same-way-arrays-ca
// Slice, map, and function values are not comparable
sliceA := []int{1, 2, 3}
sliceB := []int{1, 2, 3}
//t.Log(sliceA == sliceB) // panic
//mapA := map[int]int{1:2, 2:3}
//mapB := map[int]int{1:2, 2:3}
t.Log(reflect.DeepEqual(sliceA, sliceB))
fmt.Println()
// 支持指针地址比较 但是这样总是不想等的
//sliceC := &[]int{1, 2, 3}
//sliceD := &[]int{1, 2, 3}
//t.Log(sliceC)
}
<file_sep>/03_case_demo/05_go_grpc/go_micro/server.go
/*
* @Time : 2021-01-26 19:16
* @Author : CoderCharm
* @File : server.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"context"
"fmt"
"github.com/asim/go-micro/v3"
imooc "practice/03_case_demo/05_go_grpc/go_micro/proto"
)
type NemoServer struct{}
// 实现接口
func (c *NemoServer) SayHello(ctx context.Context, req *imooc.SayRequest, res *imooc.SayResponse) error {
res.Answer = "Just For Fun"
return nil
}
func main() {
// create a new service
service := micro.NewService(
micro.Name("nemo.server"),
)
// initialise flags
service.Init()
// 注册服务
_ = imooc.RegisterNemoHandler(service.Server(), &NemoServer{})
// start the service
if err := service.Run(); err != nil {
fmt.Println(err)
}
}
<file_sep>/01_getting-started/08_panic_recover/demo2_test.go
/*
* @Time : 2021-01-13 19:23
* @Author : CoderCharm
* @File : demo2_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _8_panic_recover
import (
"errors"
"fmt"
"testing"
)
func TestPanicVxExit(t *testing.T) {
defer println("Finally!")
defer func() {
if err := recover(); err != nil {
t.Log(fmt.Sprintf("recovered from %s", err))
}
}()
t.Log("Start")
panic(errors.New("Something wrong!"))
// os.Exit 退出时不会调用 defer 指定的函数
// os.Exit 退出时不输出当前调用栈信息
//os.Exit(-1)
//fmt.Println("End")
}
<file_sep>/docs/guide/index.md
# 笔记目录
> 记录自己学习过程中的历程,见证自己的成长。本来只是想简单的把代码丢到 `GitHub` 就行了,但是后面感觉没有整理,习惯不好。
刚好看到 `VitePress` 新玩意目前(2021/02/19) 2.2K star,几天前更新的,介绍说是`VuePress`的小弟,
加上反正也只是文档,无所谓了,就尝试用这个试一下,个人网站服务器到期后,也不想掏钱了,索性以后就维护这个。
<file_sep>/GinStudy/api/v1/sys_user.go
/*
* @Time : 2021-01-07 17:00
* @Author : CoderCharm
* @File : sys_user.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package v1
import (
"gin_study/global"
"gin_study/middleware"
"gin_study/model"
"gin_study/model/request"
"gin_study/model/response"
"gin_study/service"
"gin_study/utils"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"time"
)
// @Tags SysUser
// @Summary 用户注册账号
// @Produce application/json
// @Param data body model.SysUser true "用户名, 昵称, 密码, 角色ID"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"注册成功"}"
// @Router /user/register [post]
func Register(c *gin.Context) {
registerInfo := request.Register{}
_ = c.ShouldBindJSON(®isterInfo)
if err := utils.Verify(registerInfo, utils.RegisterVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
user := &model.SysUser{Username: registerInfo.Username, NickName: registerInfo.NickName,
Password: registerInfo.Password,
HeaderImg: registerInfo.HeaderImg,
AuthorityId: registerInfo.AuthorityId}
userReturn, err := service.Register(*user)
if err != nil {
global.GIN_LOG.Error("注册失败", zap.Any("err", err))
response.FailWithDetailed(response.SysUserResponse{User: userReturn}, "注册失败", c)
} else {
response.OkWithDetailed(response.SysUserResponse{User: userReturn}, "注册成功", c)
}
}
// @Tags Base
// @Summary 用户登录
// @Produce application/json
// @Param data body request.Login true "用户名, 密码, 验证码"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"登陆成功"}"
// @Router /base/login [post]
func Login(c *gin.Context) {
var L request.Login
_ = c.ShouldBindJSON(&L)
if err := utils.Verify(L, utils.LoginVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
U := &model.SysUser{Username: L.Username, Password: <PASSWORD>}
if user, err := service.Login(U); err != nil {
global.GIN_LOG.Error("登陆失败! 用户名不存在或者密码错误", zap.Any("err", err))
response.FailWithMessage("用户名不存在或者密码错误", c)
} else {
tokenNext(*user, c)
}
}
// 登录以后签发jwt
func tokenNext(user model.SysUser, c *gin.Context) {
j := &middleware.JWT{SigningKey: []byte(global.GIN_CONFIG.JWT.SigningKey)} // 唯一签名
claims := request.CustomClaims{
UUID: user.UUID,
ID: user.ID,
NickName: user.NickName,
Username: user.Username,
AuthorityId: user.AuthorityId,
BufferTime: global.GIN_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
StandardClaims: jwt.StandardClaims{
NotBefore: time.Now().Unix() - 1000, // 签名生效时间
ExpiresAt: time.Now().Unix() + global.GIN_CONFIG.JWT.ExpiresTime, // 过期时间 7天 配置文件
Issuer: "wxy", // 签名的发行者
},
}
token, err := j.CreateToken(claims)
if err != nil {
global.GIN_LOG.Error("获取token失败", zap.Any("err", err))
response.FailWithMessage("获取token失败", c)
return
}
if !global.GIN_CONFIG.System.UseMultipoint {
response.OkWithDetailed(response.LoginResponse{
User: user,
Token: token,
ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
}, "登录成功", c)
return
}
}
<file_sep>/01_getting-started/07_runtime/01_goroutine/goroutine_test.go
/*
* @Time : 2020-12-28 21:42
* @Author : CoderCharm
* @File : goroutine_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _1_goroutine
import (
"fmt"
"runtime"
"testing"
)
func task(i int) {
runtime.Gosched() // runtime.Gosched () 表示让 CPU 把时间片让给别人,下次某个时候继续恢复执行该 goroutine。
fmt.Println(i)
}
func TestGoRoutine(t *testing.T) {
for i := 0; i < 10; i++ {
go task(i)
}
task(999)
//time.Sleep(time.Second*1)
}
<file_sep>/GinStudy/main.go
/*
* @Time : 2020-11-17 10:42
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"gin_study/core"
"gin_study/global"
"gin_study/initialize"
)
func main() {
global.GIN_VP = core.Viper() // 初始化Viper
global.GIN_LOG = core.Zap() // 初始化zap日志库
global.GIN_DB = initialize.Gorm() // gorm连接数据库
global.GIN_CRON = initialize.SysCron() // 初始化定时任务
// 程序结束前关闭数据库链接
db, _ := global.GIN_DB.DB()
defer db.Close()
//initialize.MysqlTables(global.GIN_DB)
// 启动定时任务
//go global.GIN_CRON.Start()
//defer global.GIN_CRON.Stop()
core.RunWindowsServer()
}
<file_sep>/01_getting-started/07_runtime/02_channel/chan1_test.go
/*
* @Time : 2020-12-29 09:47
* @Author : CoderCharm
* @File : chan_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
channel 基本使用
只能使用 make关键字创建
ch := make(chan type, value)
**/
package _2_channel
import (
"fmt"
"testing"
)
func TestChan(t *testing.T) {
// 声明一个channel Buffer为3 表示可以存储 3个 int 数据
c := make(chan int, 3)
//c := make(chan int)
c <- 1
c <- 2
c <- 8
// 取出一个数据(可以选择不接收) 队列顺序
<-c
//n := <-c
//t.Log(n)
// 查看channel的 Buffer 容量
t.Log(cap(c))
c <- 9
// 也可以多次取值
x, y := <-c, <-c
t.Log(fmt.Sprintf("%d + %d = %d", x, y, x+y))
}
<file_sep>/01_getting-started/08_panic_recover/demo01_goroutine_test.go
/*
* @Time : 2021-01-13 19:13
* @Author : CoderCharm
* @File : demo01_goroutine_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _8_panic_recover
import (
"testing"
"time"
)
func TestGoroutineRecover(t *testing.T) {
// 主线程中的 defer 没有执行
defer println("in main")
go func() {
defer println("in goroutine")
// goroutine 中的错误 会直接影响主线程
panic("自定义错误")
}()
time.Sleep(1 * time.Second)
}
<file_sep>/GinStudy/model/response/common.go
/*
* @Time : 2020-11-24 09:58
* @Author : CoderCharm
* @File : common.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package response
type PageResult struct {
Data interface{} `json:"data"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
}
<file_sep>/GinStudy/go.mod
module gin_study
go 1.13
require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 // indirect
github.com/fsnotify/fsnotify v1.4.9
github.com/gin-gonic/gin v1.6.3
github.com/go-redis/redis v6.15.9+incompatible
github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 // indirect
github.com/jonboulle/clockwork v0.2.2 // indirect
github.com/lestrrat-go/file-rotatelogs v2.3.0+incompatible
github.com/lestrrat-go/strftime v1.0.3 // indirect
github.com/onsi/ginkgo v1.14.2 // indirect
github.com/onsi/gomega v1.10.4 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/robfig/cron/v3 v3.0.1
github.com/satori/go.uuid v1.2.0
github.com/spf13/viper v1.7.1
github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14
github.com/swaggo/gin-swagger v1.3.0
github.com/swaggo/swag v1.7.0
github.com/tebeka/strftime v0.1.5 // indirect
go.uber.org/zap v1.16.0
gorm.io/driver/mysql v1.0.3
gorm.io/gorm v1.20.9
)
<file_sep>/01_getting-started/03_Variable/main.go
package main
import "fmt"
//a := 1 // error
var abc string
//示例代码
var isActive bool // 全局变量声明
var enabled, disabled = true, false // 忽略类型的声明
func test() {
var available bool // 一般声明
valid := false // 简短声明
available = true // 赋值操作
abc = "abcAbc"
fmt.Println("-----")
fmt.Println(abc[1:4])
fmt.Println("-----")
fmt.Println(available)
fmt.Println(valid)
fmt.Println(isActive)
}
func main() {
//a := 1
//fmt.Print("hello")
//fmt.Println(a)
//
//fmt.Printf("%d \n", 22)
//fmt.Printf("%d - %b - %x \n", 42, 42, 42)
//fmt.Printf("%d - %b - %#x \n", 42, 42, 42)
//fmt.Printf("%d - %b - %#X \n", 42, 42, 42)
//fmt.Printf("%d \t %b \t %#X \n", 42, 42, 42)
//a := 10
b := "golang"
c := 4.17
d := true
e := "Hello"
f := `
Do you like
my hat?
`
g := 'M'
var h = "aaa"
var k, l int
l = 7
var m, n string = "mmm", "abc"
//zzz := 123 // 变量声明之后必须得使用
o := `this is golang program`
fmt.Printf("%v \n", abc)
fmt.Printf("%v \n", b)
fmt.Printf("%v \n", c)
fmt.Printf("%v \n", d)
fmt.Printf("%v \n", e)
fmt.Printf("%v \n", f)
fmt.Printf("%v \n", g)
fmt.Println(h)
fmt.Println(k, l)
fmt.Println(m, n)
fmt.Println("o - ", o)
test()
}
<file_sep>/01_getting-started/11_os/01_file_size/open_part_test.go
/*
* @Time : 2021/3/15 20:50
* @Author : CoderCharm
* @File : open_part_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
分段打开文件
https://stackoverflow.com/questions/1821811/how-to-read-write-from-to-file-using-go
**/
package _1_file_size
import (
"fmt"
"math"
"os"
"testing"
)
func openFile(filePath string) {
f, err := os.Open(filePath)
if err != nil {
panic(fmt.Sprintf("文件打开错误, %s", err))
}
// 最后关闭文件
defer func() {
if err := f.Close(); err != nil {
panic(fmt.Sprintf("文件关闭错误, %s", err))
}
}()
// 读取全部文件
//content, err := ioutil.ReadAll(f)
//fmt.Println(string(content))
// 读取全部文件
file, _ := os.Stat(filePath)
// 获取文件大小
allSize := file.Size()
// 分段文件大小 5个字节
partSize := 5
// 计算全部分段
partNum := math.Ceil(float64(allSize / int64(partSize)))
// 分段读取文件
for i := 0; i <= int(partNum); i++ {
buf := make([]byte, partSize)
byteLen, _ := f.Read(buf)
fmt.Println(byteLen, string(buf))
}
//// 文件指针
//_, _ = f.Seek(5, 1)
//_, _ = f.Seek(5, 1)
}
func TestOpenFile(t *testing.T) {
openFile("./foo.text")
}
<file_sep>/03_case_demo/02_http_demo/test_gorequest/req01_test.go
/*
* @Time : 2020-12-31 11:24
* @Author : CoderCharm
* @File : req01_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package test_gorequest
import (
"encoding/json"
"errors"
"fmt"
"github.com/parnurzeal/gorequest"
"testing"
)
func StringToMap(content string) (map[string]interface{}, error) {
var resMap map[string]interface{}
err := json.Unmarshal([]byte(content), &resMap)
if err != nil {
return nil, err
}
return resMap, nil
}
var UserAgent = "this is custom user agent"
func GetRequest(targetUrl string, queryMap map[string]string) (content string, err error) {
resp, body, errs := gorequest.New().Get(targetUrl).Query(queryMap).
Set("User-Agent", UserAgent).
End()
if errs != nil {
return "", errors.New(fmt.Sprintf("%s 请求错误 %s", targetUrl, errs))
}
// 可以使用 _ 接收 resp
fmt.Printf("url:%s 请求状态 %s \n", targetUrl, resp.Status)
return body, nil
}
type UserInfo struct {
Name string `json:"name"`
Age string `json:"age"`
}
func PostRequest(targetUrl string) (body string, err error) {
// 设置post json数据 也开始使用下面的 Send(`{"user": "aaa"}`)
jsonData := UserInfo{Name: "Nick", Age: "25"}
resp, body, errs := gorequest.New().Post(targetUrl).Send(jsonData).Query(map[string]string{"go": "go_on_learn"}).
Set("User-Agent", UserAgent).
Send(`{"user": "aaa"}`).Type("multipart").
End()
fmt.Printf("url:%s 请求状态 %s \n", targetUrl, resp.Status)
if errs != nil {
return "", errors.New(fmt.Sprintf("%s 请求错误 %s", targetUrl, errs))
}
return body, nil
}
func Test01(t *testing.T) {
getUrl := "https://httpbin.org/get"
// 查询参数
queryMap := map[string]string{"Python": "learn"}
resStr, err := GetRequest(getUrl, queryMap)
if err != nil {
panic(fmt.Sprintf("请求错误 %s", err))
}
fmt.Printf(resStr)
fmt.Printf("\n\n\n------------------------\n\n\n")
postUrl := "https://httpbin.org/post"
resPostStr, err := PostRequest(postUrl)
if err != nil {
panic(fmt.Sprintf("请求错误 %s", err))
}
fmt.Printf(resPostStr)
}
<file_sep>/01_getting-started/05_Pointer/01_demo.go
/*
练习指针
*/
package main
import "fmt"
func main() {
a := 123
fmt.Println(a)
var b *int // 定义b为指针类型
b = &a // & 取地址符号
*b = 666 // 表示的就是值
fmt.Println(a, &a, b, *b, &*b)
// 函数传入地址, 函数内部可以修改值
changeA1(&a)
fmt.Println(a) // 777
changeA2(a)
fmt.Println(a) // 还是777 不会变成888
// 同理其他 数据类型 数组 map struct等 可以定义指针
}
func changeA1(z *int) {
*z = 777
}
func changeA2(n int) {
n = 888
}
<file_sep>/03_case_demo/09_custom_web_framework/04_gee_context/gee/router.go
/*
* @Time : 2021-02-01 20:36
* @Author : CoderCharm
* @File : router.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package gee
import "net/http"
type Route struct {
// 存储 请求方式-路由 : 请求处理函数
handlers map[string]HandlerFunc
}
// 初始化路由
func NewRoute() *Route {
return &Route{
handlers: make(map[string]HandlerFunc),
}
}
// 路由内部添加添加方法
func (r *Route) addRoute(method string, pattern string, handler HandlerFunc) {
// 拼接请求方式 和 路由
key := method + "-" + pattern
// 存储到路由处理的映射中 和 请求处理函数 一一对应
r.handlers[key] = handler
}
// 找到并执行处理请求函数
func (r *Route) handle(c *Context) {
key := c.Method + "-" + c.Path
if handler, ok := r.handlers[key]; ok {
handler(c)
} else {
// 没有找到直接 404
c.String(http.StatusNotFound, "404 NOT FOUND: %s\n", c.Path)
}
}
<file_sep>/03_case_demo/02_http_demo/test_gorequest/README.md
# 使用第三方库 发送请求
https://github.com/parnurzeal/gorequest
最基础的测试
<file_sep>/docs/Golang/index.md
# golang
## Golang 基础
eqweqweq
## 示例<file_sep>/02_algorithm/leetcode_everday/232_queue_use_stack/queue_use_stack_test.go
/*
* @Time : 2021-03-05 20:55
* @Author : CoderCharm
* @File : queue_use_stack_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
简单
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
进阶:
你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
package _32_queue_use_stack
import (
"testing"
)
type myQueue struct {
list []int
}
/** Initialize your data structure here. */
func constructor() myQueue {
return myQueue{}
}
/** Push element x to the back of queue. */
func (this *myQueue) push(x int) {
this.list = append(this.list, x)
}
/** Removes the element from in front of queue and returns that element. */
func (this *myQueue) pop() int {
n := this.list[len(this.list)-1]
this.list = this.list[:len(this.list)-1]
return n
}
/** Get the front element. */
func (this *myQueue) peek() int {
return this.list[0]
}
/** Returns whether the queue is empty. */
func (this *myQueue) empty() bool {
return len(this.list) == 0
}
func TestQueue(t *testing.T) {
// 这个题目看错了, 规定使用双栈
obj := constructor()
obj.push(3)
obj.push(6)
obj.push(8)
t.Log(obj.list)
t.Log(obj.peek())
t.Log(obj.pop())
t.Log(obj.pop())
t.Log(obj.pop())
t.Log(obj.list)
t.Log(obj.empty())
}
<file_sep>/GinStudy/middleware/jwt.go
/*
* @Time : 2021-01-08 20:25
* @Author : CoderCharm
* @File : jwt.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package middleware
import (
"errors"
"gin_study/global"
"gin_study/model/request"
"gin_study/model/response"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
// 我们这里jwt鉴权取头部信息 x-token 登录时回返回token信息 这里前端需要把token存储到cookie或者本地localStorage中 不过需要跟后端协商过期时间 可以约定刷新令牌或者重新登录
token := c.Request.Header.Get("token")
if token == "" {
response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
c.Abort()
return
}
j := NewJWT()
// parseToken 解析token包含的信息
claims, err := j.ParseToken(token)
if err != nil {
if err == TokenExpired {
response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
c.Abort()
return
}
response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
c.Abort()
return
}
c.Set("claims", claims)
c.Next()
}
}
type JWT struct {
SigningKey []byte
}
var (
TokenExpired = errors.New("Token is expired")
TokenNotValidYet = errors.New("Token not active yet")
TokenMalformed = errors.New("That's not even a token")
TokenInvalid = errors.New("Couldn't handle this token:")
)
func NewJWT() *JWT {
return &JWT{
[]byte(global.GIN_CONFIG.JWT.SigningKey),
}
}
// 创建一个token
func (j *JWT) CreateToken(claims request.CustomClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(j.SigningKey)
}
// 解析 token
func (j *JWT) ParseToken(tokenString string) (*request.CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &request.CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
return j.SigningKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
// Token is expired
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, TokenNotValidYet
} else {
return nil, TokenInvalid
}
}
}
if token != nil {
if claims, ok := token.Claims.(*request.CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, TokenInvalid
} else {
return nil, TokenInvalid
}
}
<file_sep>/03_case_demo/07_jwt/token_summary_test.go
/*
* @Time : 2021-01-05 21:24
* @Author : CoderCharm
* @File : token_summary_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
汇总生成 和 解析
**/
package _7_jwt
import (
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"testing"
)
type CustomClaims struct {
ID uint
Username string
jwt.StandardClaims
}
// 生成token
func generateToken(claims CustomClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(Key))
}
var (
TokenExpired = errors.New("Token is expired")
TokenNotValidYet = errors.New("Token not active yet")
TokenMalformed = errors.New("That's not even a token")
TokenInvalid = errors.New("Couldn't handle this token:")
)
// 解析token
func parseToken(tokenString string) (*CustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (i interface{}, e error) {
return []byte(Key), nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
// Token is expired
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, TokenNotValidYet
} else {
return nil, TokenInvalid
}
}
}
if token != nil {
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, TokenInvalid
} else {
return nil, TokenInvalid
}
}
func TestToken(t *testing.T) {
//fmt.Println(123)
//claims := &CustomClaims{ID:123, Username:"222"}
//claims.ExpiresAt = time.Now().Unix() + 3600
//token, err := generateToken(*claims)
//fmt.Println(token, err)
token := "<KEY>"
claims, err := parseToken(token)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(*claims)
}
}
<file_sep>/04_desgin_pattern/01_simple_factory/factory_test.go
/*
* @Time : 2021-02-17 14:43
* @Author : CoderCharm
* @File : factory_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
go语言里面结构体没有构造函数这个说法,所以一般会采用`Newxxx`这样的来初始化
NewXXX 函数返回接口时就是简单工厂模式。
**/
package _1_simple_factory
import (
"testing"
)
// 声明一个接口
type Animal interface {
action() string
}
// 声明一个结构体 实现action方法
type Dog struct {
Bark string
}
func (d *Dog) action() string {
return d.Bark
}
// 同样声明另一个
type Cat struct {
Sound string
}
func (c *Cat) action() string {
return c.Sound
}
// 实例化
func NewAnimal(category bool) Animal {
if category {
return &Cat{"小猫喵喵喵"}
} else {
return &Dog{"小狗汪汪叫"}
}
}
func TestFactory(t *testing.T) {
a := NewAnimal(true)
t.Log(a.action())
}
<file_sep>/05_micro_service/02_jaeger/main.go
/*
* @Time : 2021-02-10 23:25
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
https://www.jaegertracing.io/docs/1.21/getting-started/
**/
package main
<file_sep>/03_case_demo/01_mini_game/main.go
package main
import (
"fmt"
"math/rand"
"time"
)
/*
随机数
0为石头
1为剪刀
2为布
*/
func GetRandomNum() int {
// 让随机数重置
rand.Seed(time.Now().UnixNano())
return rand.Intn(3)
}
/*
检测数据合法性
*/
func CheckInput(num int) bool {
if num >= 0 && num <= 2 {
return true
} else {
return false
}
}
/*
转换对应的数字
*/
func TransNum(num int) string {
switch {
case num == 0:
return "✊"
case num == 1:
return "✂️"
default:
return "🤚"
}
}
func main() {
// 整体无限循环
for {
var num int
var randomNum = GetRandomNum()
fmt.Printf("请输入数字【0:✊; 1:✂️; 2:🤚】:")
_, err := fmt.Scanf("%d", &num)
if err != nil {
fmt.Println("输入数据不合法", num)
continue
}
res := CheckInput(num)
if res == false {
fmt.Println("输入数据应>=0并且<=2")
continue
}
fmt.Println("电脑出的", TransNum(randomNum), " VS ", "你出的", TransNum(num))
if (num == 0 && randomNum == 1) || (num == 1 && randomNum == 2) || (num == 2 && randomNum == 0) {
fmt.Println("你赢了")
} else if num == randomNum {
fmt.Println("平局")
} else {
fmt.Println("电脑赢了")
}
}
}
<file_sep>/01_getting-started/07_runtime/README.md
# go 并发编程
<file_sep>/03_case_demo/05_go_grpc/go_micro/client.go
/*
* @Time : 2021-01-26 21:32
* @Author : CoderCharm
* @File : client.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"context"
"fmt"
"github.com/asim/go-micro/v3"
imooc "practice/03_case_demo/05_go_grpc/go_micro/proto"
)
func main() {
// create a new service
service := micro.NewService(
micro.Name("nemo.client"),
)
service.Init()
capImooc := imooc.NewNemoService("nemo.server", service.Client())
//
res, err := capImooc.SayHello(context.TODO(), &imooc.SayRequest{Message: "hhhhhhh"})
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
<file_sep>/01_getting-started/06_data_struct/02_demo/01_stack_test.go
/*
* @Time : 2020-08-28 00:03
* @Author : CoderCharm
* @File : 01_stack_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _2_demo
import (
"testing"
)
type Foo struct {
Allen string
Levy string
}
// Foo 指定类型 Spoke 与 Allen Levy 变量 不在同一层
type Bar struct {
Spoke int
Foo Foo
}
// 相当于继承 Foo Zek 和 Allen Levy 变量在同一层
type Titan struct {
Zek string
Foo
}
func TestA(t *testing.T) {
b := Bar{1, Foo{"阿尔敏", "利维"}}
t.Log(b)
t.Log(b.Spoke)
//t.Log(b.Allen) // 不能取到
t.Log(b.Foo.Allen) // 只能这样取到
t.Log("------\n")
titan := Titan{"吉克", Foo{"aaaaa", "llll"}}
t.Log(titan)
t.Log(titan.Zek)
t.Log(titan.Allen) // 可以直接取到 Foo的值
t.Log(titan.Levy)
t.Log(titan.Foo)
}
<file_sep>/03_case_demo/09_custom_web_framework/03_gee_demo/main.go
/*
* @Time : 2021-02-01 20:25
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
go 不推荐相对导入, 这里直接用的绝对导入
**/
package main
import (
"fmt"
"net/http"
"practice/03_case_demo/09_custom_web_framework/03_gee_demo/gee"
)
func main() {
r := gee.New()
r.GET("/", func(w http.ResponseWriter, req *http.Request) {
_, _ = fmt.Fprintf(w, "URL.Path = %q\n", req.URL.Path)
})
r.GET("/hello", func(w http.ResponseWriter, req *http.Request) {
for k, v := range req.Header {
_, _ = fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
}
})
_ = r.Run("127.0.0.1:7052")
}
<file_sep>/01_getting-started/09_reflect/01_test.go
/*
* @Time : 2021-01-17 15:40
* @Author : CoderCharm
* @File : 01_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _9_reflect
import (
"fmt"
"reflect"
"testing"
)
type userInfo struct {
User string `json:"user"foo:"test_tag"`
Avatar string `json:"avatar"bar:""`
Age int `json:"age"`
}
func (u userInfo) SayName(name string) {
fmt.Printf("用户名是 %s\n", name)
}
func (u userInfo) SayAge() {
fmt.Printf("年龄是 %d\n", u.Age)
}
// 常见的类型检测场景
func CheckType(v interface{}) {
t := reflect.TypeOf(v)
switch t.Kind() {
case reflect.Float32, reflect.Float64:
fmt.Println("Float")
case reflect.Int, reflect.Int32, reflect.Int64:
fmt.Println("Integer")
default:
fmt.Println("Unknown", t)
}
}
// 通过断言判断类型
func AssertionType(v interface{}) {
switch v.(type) {
case int, int16, int32, int64:
fmt.Printf("整数类型 %d \n", v)
case userInfo:
fmt.Printf("是 userInfo 类型 %v ", v)
fmt.Printf("年龄 %d \n", v.(userInfo).Age)
// 断言调用方法
v.(userInfo).SayAge()
default:
fmt.Println("没有匹配到")
}
}
func TestReflect(t *testing.T) {
// 实例化结构体
user := userInfo{User: "Nike", Age: 18}
// 断言判断类型 功能不如反射强大
AssertionType(user)
AssertionType(1111)
typ := reflect.TypeOf(user) // 获取reflect的类型
t.Log(typ)
val := reflect.ValueOf(user) // 获取reflect的值
t.Log(val)
kd := val.Kind() // 获取对应的类别
t.Log(kd)
num := val.NumField() // 获取值字段的数量
t.Log(num)
// 通过反射调用方法
m1 := val.MethodByName("SayName")
//m1 := val.Method(0)
m1.Call([]reflect.Value{reflect.ValueOf("测试")}) // 传参数
// 私有方法不可反射调用 Java反射可以暴力调用私有方法
m2 := val.MethodByName("SayAge")
m2.Call([]reflect.Value{}) // 不传参数
tagVal := typ.Field(2) // 获取index为2的类型信息
val = val.Field(2) // 获取index为2实例化后的值
t.Log(tagVal)
t.Log(val)
t.Log(tagVal.Type) // 输出结构体字段的类型
t.Log(tagVal.Name) // 输出结构体字段名称
// 获取结构体的tag 没有则为空 Get 实际就是调用的Lookup
t.Log(tagVal.Tag.Get("foo"))
// 返回两个值 第一个为tag值 第二个为bool值 true表示设置了此tag 无论是否为空字符串
t.Log(tagVal.Tag.Lookup("foo"))
t.Log(typ.Field(1).Tag.Lookup("bar")) // 设置了tag为bar 但是为空字符串 依旧为true
t.Log(typ.Field(1).Tag.Lookup("any_tag")) // 没有设置此tag 就为false
// 必须使用地址 才可以修改原来的值 否则会panic (反射第三定律,值可以被修改)
modifyVal(&user)
t.Log(user)
}
// 通过反射修改值
func modifyVal(user interface{}) {
// 获取变量的指针
pVal := reflect.ValueOf(user) // 获取reflect的值
// 获取指针指向的变量
v := pVal.Elem()
// 找到并更新变量的值
v.FieldByName("User").SetString("Jack")
}
<file_sep>/01_getting-started/07_runtime/01_goroutine/counter_test.go
/*
* @Time : 2020-12-28 23:10
* @Author : CoderCharm
* @File : counter_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _1_goroutine
import (
"sync"
"testing"
"time"
)
func TestGo(t *testing.T) {
counter := 0
for i := 0; i < 5000; i++ {
go func() {
counter++
}()
}
time.Sleep(time.Second * 1)
t.Log(counter)
}
func TestLock(t *testing.T) {
// 声明一个锁
var m sync.Mutex
counter := 0
for i := 0; i < 5000; i++ {
go func() {
// 最后都要解锁
defer func() {
m.Unlock()
}()
// 先锁住
m.Lock()
counter++
}()
}
// sleep 1 秒时间随机的 让协程执行完
time.Sleep(time.Second * 1)
t.Log(counter)
}
func TestWait(t *testing.T) {
// 声明一个锁
var m sync.Mutex
var wg sync.WaitGroup
counter := 0
for i := 0; i < 5000; i++ {
// 添加一个等待
wg.Add(1)
go func() {
// 最后都要解锁
defer func() {
m.Unlock()
}()
// 先锁住
m.Lock()
counter++
// 一个结束
wg.Done()
}()
}
// 等待协程全部执行完
wg.Wait()
t.Log(counter)
}
<file_sep>/README.md
# go 语言学习笔记
## 笔记说明
> 练习代码,都以编写测试程序的方式书写,注意`go`以文件夹为包单位,同一文件夹下包名一样。
- 1 源码文件以`_test.go`结尾, 如`str_test.go`
- 2 测试方法名以大写`Test`开头,如`func TestXXX(t *testing.T){t.Log(111)}`
如以下代码结构
```go
// 在一个空文件夹下新建一个`hello_test.go`文件
package hello
import "testing"
func TestString(t *testing.T){
t.Log("hello world")
}
```
## 目录
### 1 入门学习
- [1 hello world](01_getting-started/01_HelloWorld/README.md)
### 2 基础算法学习
### 3 一些案例框架练习
- [2 go http请求库的使用](03_case_demo/02_http_demo/README.md)
- [3 go mysql 和 gorm的基本使用(使用Viper读取yaml配置文件)](03_case_demo/)
- [4 go 七牛云上传在线视频](03_case_demo/04_qiniu_upload)
- [5 gRPC学习使用](03_case_demo/05_go_grpc/README.md)
- [6 cron定时任务基本使用](03_case_demo/06_cron_task/README.md)
- [7 JWT token的基本使用](03_case_demo/07_jwt/README.md)
- [8 casbin权限管理demo](03_case_demo/08_casbin/README.md)
- [9 标准库net/http仿写一个gin框架](03_case_demo/09_custom_web_framework)
### 参考
- [https://github.com/overnote/over-golang](https://github.com/overnote/over-golang)
- [github.com/inancgumus/learngo](https://github.com/inancgumus/learngo)
- [极客go学习笔记](https://github.com/CoderCharm/gostudy)
- [go语言程序设计](https://docs.hacknode.org/gopl-zh/index.html)
- [go web编程在线书籍](https://learnku.com/docs/build-web-application-with-golang)
- [go web编程代码](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/preface.md)
- [go在线练习](https://tour.golang.org/list)
- [https://golang.google.cn/](https://golang.google.cn/)
- [JSON解析](https://stackoverflow.com/questions/35583735/unmarshaling-into-an-interface-and-then-performing-type-assertion)
- [Go语言设计与实现](https://draveness.me/golang/)
- [Go语言高级编程](https://hezhiqiang8909.gitbook.io/go/)
- [Go夜读](https://space.bilibili.com/326749661)
- [https://github.com/hantmac/Mastering_Go_ZH_CN](https://github.com/hantmac/Mastering_Go_ZH_CN)
- [极客兔兔 Go7天从零实现系列](https://github.com/geektutu/7days-golang)<file_sep>/GinStudy/initialize/sys_cron.go
/*
* @Time : 2021-01-06 20:02
* @Author : CoderCharm
* @File : sys_cron.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
初始化 cron 定时任务
不支持持久化
不支持调度后立即运行 得手动 go func() https://github.com/robfig/cron/issues/297
**/
package initialize
import (
"github.com/robfig/cron/v3"
"time"
)
// 初始化定时任务
func SysCron() *cron.Cron {
// 时区北京时间
nyc, _ := time.LoadLocation("Asia/Shanghai")
// 支持秒级别任务
return cron.New(
cron.WithLocation(nyc),
cron.WithSeconds(),
)
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/01_if.go
package main
import "fmt"
func main() {
a := 1
//b := getB()
fmt.Printf("a: %d - b: %d\n", a, getB())
if a > getB() {
fmt.Println("a > b")
} else {
fmt.Println("a < b")
}
// 计算获取值x,然后根据x返回的大小,判断是否大于10。
if x := getB(); x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}
//这个地方如果这样调用就编译出错了,因为x是条件里面的变量
//fmt.Println(x)
}
func getB() int {
return 5
}
<file_sep>/03_case_demo/02_http_demo/README.md
# go 原生库`net/http`构建 http 请求
# GET 请求
- [1 最基础的GET请求演示](req1_get_test.go)
- [2 较为完善的GET请求](req2_get_test.go) 携带参数,友好提示错误信息
# POST 请求
- [1 POST form表单请求](req3_post_test.go)
- [2 POST JSON请求](req4_post_test.go)
- 注意设置`Content-Type`这个属性
<file_sep>/01_getting-started/04_Control_statements_and_functions/07_struct/02_embedded_fields/main.go
/*
embedded v 把…牢牢地嵌入(或插入、埋入);派遣(战地记者、摄影记者等);嵌入(在I'm aware that she knows句中,she knows为内嵌句)
struct的匿名字段 嵌入字段
我们上面介绍了如何定义一个struct,定义的时候是字段名与其类型一一对应,实际上Go支持只提供类型,
而不写字段名的方式,也就是匿名字段,也称为嵌入字段。
当匿名字段是一个struct的时候,那么这个struct所拥有的全部字段都被隐式地引入了当前定义的这个struct。
让我们来看一个例子,让上面说的这些更具体化
*/
package main
import "fmt"
type skill []string
type Human struct {
name string
age int
weight int
}
type Student struct {
Human // // 匿名字段,struct 嵌套更准确
skill // 匿名字段,自定义的类型string slice
//int // 内置类型作为匿名字段
speciality string
hobby []string
}
func main() {
otis := Student{Human: Human{"Otis", 35, 100}, speciality: "Biology"}
fmt.Println(otis)
otis.Human.age = 15
otis.hobby = []string{"read book"}
otis.skill = []string{"cook"}
fmt.Println(otis)
}
<file_sep>/01_getting-started/05_Pointer/README.md
# Go语言基础学习 指针和地址
有几个很不错的学习教程,感觉很不错
- GitHub开源go学习教程 https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/preface.md
- B站教程 https://space.bilibili.com/322210472/channel/detail?cid=108884
最后就是go官网了
- https://golang.org/doc/
- go官网练习 https://tour.golang.org/list
## 指针和地址
> 上来咱就讲指针和地址,go各种数据类型,字符串,数组,map看看语法,多敲敲
可以参考下知乎问题[为什么要有指针](https://www.zhihu.com/question/26623283)
我现在的理解就是, 指针通俗来讲就是内存地址,直接通过内存地址修改某个值,这是最直接,也是效率最高的。
<file_sep>/01_getting-started/04_Control_statements_and_functions/08_interface/02_demo.go
/*
* @Time : 2020-08-26 21:16
* @Author : CoderCharm
* @File : 02_demo.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"errors"
"fmt"
)
var err1 = errors.New("错误1")
var err2 = errors.New("错误2")
func fibonacci(n int) ([]int, error) {
if n < 2 {
return nil, err1
}
if n > 100 {
return nil, err2
}
fibList := []int{1, 1}
for i := 2; i < n; i++ {
fibList = append(fibList, fibList[i-2]+fibList[i-1])
}
return fibList, nil
}
func main() {
if v, err := fibonacci(1); err != nil {
if err == err1 {
fmt.Println("是错误1")
}
fmt.Println("出错了", err)
} else {
fmt.Println(v)
}
}
<file_sep>/01_getting-started/03_Variable/04_map/map_test.go
/*
map也就是Python中字典的概念,它的格式为map[keyType]valueType
我们看下面的代码,map的读取和设置也类似slice一样,通过key来操作,
只是slice的index只能是`int`类型,而map多了很多类型,可以是int,可以是string及所有完全定义了==与!=操作的类型。
*/
package _04_map
import (
"testing"
)
func TestMap(t *testing.T) {
// 声明一个key是字符串,值为int的字典,这种方式的声明需要在使用之前使用make初始化
var numbers map[string]int // 还需要make
//numbers := map[string]int{} // 缩写后面加 {}
//numbers := make(map[string]int) // 或者直接 make
// 另一种map的声明方式
numbers2 := make(map[string]int)
numbers2["one"] = 1 //赋值
numbers2["ten"] = 10 //赋值
numbers2["three"] = 3
// 没有赋值 int类型默认为 0
foo := numbers2["four"]
t.Log(foo)
//numbers2["five"] = 0
// 如果赋值为0 如何判断是空值 还是赋的值
if v, ok := numbers2["five"]; ok {
t.Log("有five这个key的值", v)
} else {
t.Log("没有有five这个key的值", v)
}
t.Log("第三个数字是: ", numbers["three"]) // 读取数据
// 打印出来如:第三个数字是: 3
/*
使用map过程中需要注意的几点:
map是无序的,每次打印出来的map都会不一样,它不能通过index获取,而必须通过key获取
map的长度是不固定的,也就是和slice一样,也是一种引用类型
内置的len函数同样适用于map,返回map拥有的key的数量
map的值可以很方便的修改,通过numbers["one"]=11可以很容易的把key为one的字典值改为11
map和其他基本型别不同,它不是thread-safe,在多个go-routine存取时,必须使用mutex lock机制
*/
// 初始化一个字典
rating := map[string]float32{"C": 5, "Go": 4.5, "Python": 4.5, "C++": 2}
t.Log("初始化长度是: ", len(rating))
delete(rating, "C")
t.Log(len(rating))
// 循环map k v 如果不想使用key或者value 可使用 _ 丢弃
for k, v := range rating {
t.Log(k, v)
}
t.Log("分割---------")
// map有两个返回值,第二个返回值,如果不存在key,那么ok为false,如果存在ok为true
csharpRating, ok := rating["C#"]
if ok {
t.Log("C# is in the map and its rating is ", csharpRating)
} else {
t.Log("We have no rating associated with C# in the map")
t.Log("csharpRating", csharpRating)
}
delete(rating, "C") // 删除key为C的元素
t.Log("---------------")
//上面说过了,map也是一种引用类型,如果两个map同时指向一个底层,那么一个改变,另一个也相应的改变:
m := make(map[string]string)
m["Hello"] = "Bonjour"
m1 := m
m1["Hello"] = "Salut" // 现在m["hello"]的值已经是Salut了
/*
map[Hello:Salut]
map[Hello:Salut]
*/
t.Log(m)
t.Log(m1)
// 定义 一个接口map
m4 := make(map[string]interface{})
m4["a"] = 123
m4["b"] = "666"
m4["c"] = true
m4["d"] = []interface{}{1, "2", "3", true}
t.Log(m4)
}
<file_sep>/03_case_demo/06_cron_task/01_demo/demo02_test.go
/*
* @Time : 2021-01-04 21:13
* @Author : CoderCharm
* @File : demo02_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _1_demo
import (
"github.com/robfig/cron/v3"
"testing"
"time"
)
func Test02Cron(t *testing.T) {
// 设置时区
nyc, _ := time.LoadLocation("Asia/Shanghai")
c := cron.New(cron.WithLocation(nyc))
_, _ = c.AddFunc("* * * * *", jobTask)
// 定时运行一次 https://github.com/robfig/cron/pull/317 目前不支持
//_, _ = c.AddFunc("@once 2021-01-09 10:45:00", func() {
// fmt.Println("Hello! Now is 2021-01-09 10:45:00")
//})
c.Start()
//time.Sleep(3 * time.Minute)
// 阻塞
select {}
//t1 := time.NewTimer(time.Second * 10)
//
//for {
// select {
// case <-t1.C:
// t1.Reset(time.Second * 10)
// }
//}
}
<file_sep>/03_case_demo/03_go_mysql/demo_mysql/link_test.go
/*
* @Time : 2021-01-01 15:25
* @Author : CoderCharm
* @File : mysql01_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
https://www.golangprograms.com/example-of-golang-crud-using-mysql-from-scratch.html
**/
package demo_mysql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"testing"
"time"
)
func TestMySQL(t *testing.T) {
db, err := sql.Open("mysql", "root:Admin12345-@tcp(172.16.137.129:3306)/temp_db_date?timeout=90s&collation=utf8mb4_unicode_ci")
if err != nil {
panic(err)
}
// See "Important settings" section. https://github.com/go-sql-driver/mysql#important-settings
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
selDB, err := db.Query("SELECT * FROM employee ORDER BY id DESC")
if err != nil {
panic(err.Error())
}
fmt.Println(selDB.Next())
defer db.Close()
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/02_goto.go
/*
goto
Go有goto语句——请明智地使用它。用goto跳转到必须在当前函数内定义的标签。
例如假设这样一个循环:
在我的印象里 就C 有goto,而且感觉这个语法很不友好,用不好很混乱,
Python 直接没有goto
Java goto作为保留字,也没有用
*/
package main
func main() {
print("123")
myFunc()
}
func myFunc() {
i := 0
Here: //这行的第一个词,以冒号结束作为标签 标签名是大小写敏感的。
println(i)
i++
if i >= 10 {
return
}
goto Here //跳转到Here去
}
<file_sep>/03_case_demo/02_http_demo/req4_down_test.go
/*
* @Time : 2020-12-28 20:56
* @Author : CoderCharm
* @File : req4_down_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package http_demo
import (
"fmt"
"io"
"net/http"
"os"
"testing"
)
func downloadFile(url, filename string) {
r, err := http.Get(url)
if err != nil {
panic(err)
}
defer r.Body.Close()
f, err := os.Create(filename)
if err != nil {
panic(err)
}
defer f.Close()
n, err := io.Copy(f, r.Body)
fmt.Println(n, err)
}
type Reader struct {
io.Reader
Total int64
Current int64
}
func (r *Reader) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
r.Current += int64(n)
fmt.Printf("\r进度 %.2f%%", float64(r.Current*10000/r.Total)/100)
return
}
func DownloadFileProgress(url, filename string) {
r, err := http.Get(url)
if err != nil {
panic(err)
}
defer r.Body.Close()
f, err := os.Create(filename)
if err != nil {
panic(err)
}
defer f.Close()
reader := &Reader{
Reader: r.Body,
Total: r.ContentLength,
}
_, _ = io.Copy(f, reader)
}
func SoDownloadFile(url, filepath string) (err error) {
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Check server response
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", resp.Status)
}
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func TestDownFile(t *testing.T) {
url := "https://bigota.d.miui.com/V12.0.5.0.QGHCNXM/miui_PHOENIX_V12.0.5.0.QGHCNXM_fc51e1211b_10.0.zip"
filename := "miui.zip"
_ = SoDownloadFile(url, filename)
}
<file_sep>/03_case_demo/10_RabbmitMQ/01_simple/Publish/mainPublish.go
/*
* @Time : 2021-02-16 20:23
* @Author : CoderCharm
* @File : mainPublish.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"fmt"
"practice/03_case_demo/10_RabbmitMQ/01_simple/RabbitMQ"
)
func main() {
rabbitmq := RabbitMQ.NewRabbitMQSimple("wxy")
defer rabbitmq.Destory()
rabbitmq.PublishSimple("Hello MQ!")
fmt.Println("发送成功!")
}
<file_sep>/03_case_demo/02_http_demo/test_gorequest/req02_test.go
/*
* @Time : 2020-12-31 16:32
* @Author : CoderCharm
* @File : req02_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
使用gorequest clone 模式 重用通用设置
**/
package test_gorequest
import (
"encoding/json"
"fmt"
"github.com/parnurzeal/gorequest"
"testing"
"time"
)
var baseRequest = gorequest.New().Timeout(5*time.Second).Set("User-Agent", UserAgent)
// 构建响应的json格式 只需要设置需要的字段就像 struct tag 得要设置对应字段key
type bodyResp struct {
Args interface{} `json:"args"`
Headers struct {
UserAgent string `json:"User-Agent"`
Host string `json:"Host"`
} `json:"headers"`
Origin string `json:"origin"`
Url string `json:"url"`
}
func TestReq2(t *testing.T) {
getUrl := "https://httpbin.org/get"
resp, body, errs := baseRequest.Clone().Get(getUrl).End()
if errs != nil {
panic(fmt.Sprintf("URL:%s 请求错误: %s", getUrl, errs))
}
//fmt.Println(resp)
// 可以使用 _ 接收 resp
fmt.Printf("url:%s 请求状态 %s \n", getUrl, resp.Status)
//fmt.Println(body)
b := &bodyResp{}
err := json.Unmarshal([]byte(body), b)
//
if err != nil {
t.Error(err)
}
fmt.Printf("%v \n", b.Headers.UserAgent)
}
<file_sep>/03_case_demo/05_go_grpc/README.md
# gRPC 使用案例
> "Definition - gRPC is a modern, open source remote procedure call (RPC) framework that can run anywhere"
> gRPC 使用了google的`protobuf`消息格式,而不是传统的`JSON`, 相对`JSON`,`protobuf`具有速度快,序列化效率高,天然的加密(得有.proto文件)
目前个人只是看看demo,还没有场景需要用到这个。目前还是REST API使用更多一些, 也可以构建 RESTful 服务发送`protobuf`消息。
Goland 可以安装第三方插件`protobuf` [Goland2019 插件离线下载地址](https://github.com/ksprojects/protobuf-jetbrains-plugin/releases)
`proto`文件就可以直接语法提示
## 依赖安装
```shell
go get -u google.golang.org/grpc
```
## gRPC 和 REST的区别
- gRPC 使用 HTTP/2 而 REST 使用 HTTP 1.1.(参考[StackOverflow](https://stackoverflow.com/questions/43682366/how-is-grpc-different-from-rest))
- gRPC 使用 protocol buffer 数据格式,而不是REST中常常使用的JSON数据格式。
- 可以使用 gRPC HTTP/2 的功能,例如 服务器到客户端流, 客户端到服务器流 或者 双向流媒体.
## gRPC REST GraphQL Web
## 使用场景
## 示例
- `/helloworld` gRPC demo
- `/go_micro` go-micro demo
# 参考
- [官方文档](https://grpc.io/docs/languages/go/quickstart/)
- [官方示例](https://github.com/grpc/grpc-go/tree/master/examples/helloworld)
- [https://tutorialedge.net/golang/go-grpc-beginners-tutorial/](https://tutorialedge.net/golang/go-grpc-beginners-tutorial/)
- [https://nordicapis.com/when-to-use-what-rest-graphql-webhooks-grpc/](https://nordicapis.com/when-to-use-what-rest-graphql-webhooks-grpc/)
- [https://docs.microsoft.com/en-us/aspnet/core/grpc/comparison?view=aspnetcore-5.0](https://docs.microsoft.com/en-us/aspnet/core/grpc/comparison?view=aspnetcore-5.0)
- [https://stackoverflow.com/questions/43682366/how-is-grpc-different-from-rest](https://stackoverflow.com/questions/43682366/how-is-grpc-different-from-rest)
- [http2 对比 websocket](https://stackoverflow.com/questions/28582935/does-http-2-make-websockets-obsolete)
<file_sep>/GinStudy/model/response/response.go
/*
* @Time : 2020-11-23 17:10
* @Author : CoderCharm
* @File : response.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package response
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
const (
ERROR = 400
SUCCESS = 200
)
func Result(code int, msg string, data interface{}, c *gin.Context) {
// 开始时间
c.JSON(http.StatusOK, Response{
code,
msg,
data,
})
}
func Ok(c *gin.Context) {
Result(SUCCESS, "success", map[string]interface{}{}, c)
}
func OkWithMessage(message string, c *gin.Context) {
Result(SUCCESS, message, map[string]interface{}{}, c)
}
func OkWithData(data interface{}, c *gin.Context) {
Result(SUCCESS, "success", data, c)
}
func OkWithDetailed(data interface{}, message string, c *gin.Context) {
Result(SUCCESS, message, data, c)
}
func Fail(c *gin.Context) {
Result(ERROR, "failure", map[string]interface{}{}, c)
}
func FailWithMessage(message string, c *gin.Context) {
Result(ERROR, message, map[string]interface{}{}, c)
}
func FailWithDetailed(data interface{}, message string, c *gin.Context) {
Result(ERROR, message, data, c)
}
<file_sep>/01_getting-started/05_Pointer/03_demo.go
package main
import "fmt"
// 定义一个结构体
type Cat struct {
name string
color string
sex bool
}
func main() {
// 实例化
tom := Cat{
name: "Tom",
color: "white",
sex: true,
}
fmt.Println(tom)
// 定义一个结构体指针
var tom2 *Cat
// 地址赋值给结构体指针
tom2 = &tom
fmt.Println(tom)
// 结构体指针改变 值
(*tom2).name = "<NAME>"
fmt.Println(tom)
}
<file_sep>/01_getting-started/01_HelloWorld/README.md
# GoLang 入门学习
## `go`环境变量
`go env GOPATH ` 这个命令可以有效输出当前使用go的路径。
如果没有设置环境变量,就回打印默认安装位置
一般为了更方便,可以把工作区的`/bin`子目录添加到路径中,如下:
`export PATH=$PATH:$(go env GOPATH)/bin`
-----
## 第一个程序
> https://golang.google.cn/doc/code.html#Overview
1 第一步,创建一个 `hello.go` 文件
```go
package main // 定义包名
// You must statement the package name in the code first line (not notes) of the source files, e.g. package main,
// package main indicates a program that independent and enforceable, each go application should be included a package called main.
import "fmt" // The full name of fmt package is format, which implements the function of formatting IO (input / output).
func main() {
fmt.Println("Hello, world.") // Line feed printing
}
```
<file_sep>/GinStudy/middleware/zaplogger.go
/*
* @Time : 2020-11-23 09:28
* @Author : CoderCharm
* @File : log_req.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 记录请求中间件
**/
package middleware
import (
"gin_study/global"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"time"
)
func ZapLogger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
cost := time.Since(start)
global.GIN_LOG.Info(path,
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("query", query),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.Request.UserAgent()),
zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
zap.Duration("cost", cost),
)
}
}
<file_sep>/03_case_demo/03_go_mysql/demo_gorm/curd_gorm_test.go
/*
* @Time : 2021-01-02 16:05
* @Author : CoderCharm
* @File : curd_gorm.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package demo_gorm
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"testing"
)
type Employee struct {
Id int `json:"id"`
Name string `json:"name"`
City string `json:"city"`
}
var emp Employee
// GormMysql 初始化Mysql数据库
func GormMysql() *gorm.DB {
m := GlobalConfig.Mysql
dsn := m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config
mysqlConfig := mysql.Config{
DSN: dsn, // DSN data source name
DefaultStringSize: 191, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据版本自动配置
}
if db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig(m.LogMode)); err != nil {
//os.Exit(0)
return nil
} else {
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(m.MaxIdleConns)
sqlDB.SetMaxOpenConns(m.MaxOpenConns)
return db
}
}
// gormConfig 根据配置决定是否开启日志
func gormConfig(mod bool) *gorm.Config {
if mod {
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
DisableForeignKeyConstraintWhenMigrating: true,
}
} else {
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
DisableForeignKeyConstraintWhenMigrating: true,
}
}
}
func SelectGorm(db *gorm.DB) (EmployeeList []Employee) {
db.Table("employee").First(&emp)
db.Table("employee").Scan(&EmployeeList)
return EmployeeList
}
func TestGorm(t *testing.T) {
_ = Viper()
GormDB := GormMysql()
//fmt.Println(GormDB)
employeeList := SelectGorm(GormDB)
t.Log(emp)
t.Log(employeeList)
}
<file_sep>/03_case_demo/02_http_demo/req2_get_test.go
/*
* @Time : 2020-12-26 22:49
* @Author : CoderCharm
* @File : demo2.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
添加请求 发送请求 然后获取 解析json数据
**/
package http_demo
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"testing"
)
func Requests(url string) (content string, err error) {
// 创建 http 客户端
client := &http.Client{}
// 创建请求
req, _ := http.NewRequest("GET", url, nil)
// GET 请求携带查询参数
q := req.URL.Query()
q.Add("auth_key", "sky_kk")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
//req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")
// 设置请求头
req.Header.Set("User-Agent", "test")
// 发送请求
resp, err := client.Do(req)
if err != nil {
// 格式化返回错误
return "", errors.New(fmt.Sprintf("请求出错 %s", err))
}
// 最后关闭连接
defer resp.Body.Close()
// 读取内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.New(fmt.Sprintf("解析内容出错 %s", err))
}
//fmt.Println(string(body))
return string(body), nil
}
func StringToMap(content string) map[string]interface{} {
var resMap map[string]interface{}
err := json.Unmarshal([]byte(content), &resMap)
if err != nil {
fmt.Println("string转map失败", err)
}
return resMap
}
func TestReqUrl(t *testing.T) {
url := "https://httpbin.org/get"
content, err := Requests(url)
if err != nil {
fmt.Println("请求错误", err)
return
}
t.Log(fmt.Sprintf("结果 \n %s", content))
jsonContent := StringToMap(content)
t.Log(jsonContent)
}
<file_sep>/GinStudy/utils/verify_test.go
/*
* @Time : 2021-01-15 19:25
* @Author : CoderCharm
* @File : verify_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
测试参数验证
**/
package utils
import (
"errors"
"reflect"
"strings"
"testing"
)
func verify(st interface{}, roleMap Rules) (err error) {
compareMap := map[string]bool{
"lt": true,
"le": true,
"eq": true,
"ne": true,
"ge": true,
"gt": true,
}
typ := reflect.TypeOf(st)
val := reflect.ValueOf(st) // 获取reflect.Type类型
kd := val.Kind() // 获取到st对应的类别
if kd != reflect.Struct {
return errors.New("expect struct")
}
num := val.NumField()
// 遍历结构体的所有字段
for i := 0; i < num; i++ {
tagVal := typ.Field(i)
val := val.Field(i)
// 如果有此规则设置 就验证
if len(roleMap[tagVal.Name]) > 0 {
for _, v := range roleMap[tagVal.Name] {
switch {
case v == "notEmpty":
if isBlank(val) {
return errors.New(tagVal.Name + "值不能为空")
}
case compareMap[strings.Split(v, "=")[0]]:
if !compareVerify(val, v) {
return errors.New(tagVal.Name + "长度或值不在合法范围," + v)
}
}
}
}
}
return nil
}
type userInfo struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
User string `json:"user"a:"123"`
Avatar string `json:"avatar"`
}
var (
demoInfoVerify = Rules{"Page": {Ge("1")}, "PageSize": {Le("50")}, "User": {NotEmpty()}}
)
func TestVerify(t *testing.T) {
u := userInfo{Page: 1, PageSize: 60, User: "Nike"}
typ := reflect.TypeOf(u) // 获取reflect的类型
val := reflect.ValueOf(u) // 获取reflect的值
t.Log(typ)
t.Log(val)
kd := val.Kind() // 获取到st对应的类别
t.Log(kd)
num := val.NumField() // 获取值字段的数量
t.Log(num)
tagVal := typ.Field(2) // 获取index为2的类型信息
val = val.Field(2) // 获取index为2实例化后的值
t.Log(tagVal)
t.Log(val)
t.Log(tagVal.Type)
t.Log(demoInfoVerify[tagVal.Name])
z := len(demoInfoVerify["User"])
t.Log(z)
//if err := verify(u, demoInfoVerify); err != nil {
// t.Log(err)
//}
t.Log("over")
}
<file_sep>/03_case_demo/03_go_mysql/README.md
# 学习Go 操作mysql的基本使用
- [原生mysql的curd操作](./demo_mysql)
- [使用gorm的curd操作](./demo_gorm)<file_sep>/01_getting-started/pkg/pkg.go
/*
* @Time : 2021-01-09 16:23
* @Author : CoderCharm
* @File : pkg.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package pkg
var Id = 9527
<file_sep>/01_getting-started/02_Package/main/main.go
package main
import (
. "fmt"
)
func main() {
const aaa = 123
Println(aaa)
//fmt.Println(extends.Hello)
//fmt.Println(util2.Name) // package name
//fmt.Println(util2.Zzz)
}
<file_sep>/GinStudy/router/sys_user.go
/*
* @Time : 2021-01-08 20:57
* @Author : CoderCharm
* @File : sys_user.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package router
import (
"gin_study/api/v1"
"github.com/gin-gonic/gin"
)
func InitUserRouter(Router *gin.RouterGroup) {
UserRouter := Router.Group("user") //.Use(middleware.OperationRecord())
{
UserRouter.POST("register", v1.Register) // 注册
UserRouter.POST("login", v1.Login) // 登录
//UserRouter.POST("changePassword", v1.ChangePassword) // 修改密码
//UserRouter.POST("getUserList", v1.GetUserList) // 分页获取用户列表
//UserRouter.POST("setUserAuthority", v1.SetUserAuthority) // 设置用户权限
//UserRouter.DELETE("deleteUser", v1.DeleteUser) // 删除用户
//UserRouter.PUT("setUserInfo", v1.SetUserInfo) // 设置用户信息
}
}
<file_sep>/01_getting-started/07_runtime/02_channel/chan2_test.go
/*
* @Time : 2020-12-29 11:16
* @Author : CoderCharm
* @File : chan2_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
单个 channel 的使用
可以利用 Range 和 Close 多次取 和 存
**/
package _2_channel
import (
"fmt"
"testing"
)
func addChan(n int, c chan string) {
for i := 0; i < n; i++ {
// 循环添加到
c <- fmt.Sprintf("--- %d ---", i)
}
// 结束添加
close(c)
}
func TestChan2(t *testing.T) {
// 声明一个 string chan
c := make(chan string, 10)
// 协程异步调用 添加到chan
go func(n int, c chan string) {
for i := 0; i < n; i++ {
// 循环添加到
c <- fmt.Sprintf("--- %d ---", i)
}
// 结束添加
close(c)
}(cap(c), c)
// 循环取出
for v := range c {
t.Log(v)
}
}
<file_sep>/01_getting-started/03_Variable/03_array/03_slice_test.go
/*
空数组, 这个就和Python的 list 很相似了
https://www.digitalocean.com/community/tutorials/understanding-arrays-and-slices-in-go
slice
在很多应用场景中,数组并不能满足我们的需求。在初始定义数组时,我们并不知道需要多大的数组,因此我们就需要“动态数组”。
在Go里面这种数据结构叫slice
slice并不是真正意义上的动态数组,而是一个引用类型。slice总是指向一个底层array,slice的声明也可以像array一样,只是不需要长度。
对于slice有几个有用的内置函数:
len 获取slice的长度
cap 获取slice的最大容量
append 向slice里面追加一个或者多个元素,然后返回一个和slice一样类型的slice
copy 函数copy从源slice的src中复制元素到目标dst,并且返回复制的元素的个数
*/
package _3_array
import (
"fmt"
"testing"
)
func TestSlice(t *testing.T) {
// 和声明array一样,只是少了长度
var fslice [10]int
fmt.Println(fslice)
slice := []byte{'a', 'b', 'c', 'd'}
var z []byte
z = slice[0:1]
/*
len 获取slice的长度
cap 获取slice的最大容量
append 向slice里面追加一个或者多个元素,然后返回一个和slice一样类型的slice
copy 函数copy从源slice的src中复制元素到目标dst,并且返回复制的元素的个数
*/
fmt.Println(z)
fmt.Println(cap(fslice)) //
fmt.Println(len(slice))
var array [10]int
var newSlice []int
newSlice = array[2:4:7]
fmt.Println(newSlice)
}
func TestSliceCURD(t *testing.T) {
// 切片的操作
strSlice := []string{"a", "z", "1", "2", "3"}
// 添加
strSlice = append(strSlice, "666")
t.Log(strSlice)
// 修改 和数组一样
strSlice[0] = "aaaa"
t.Log(strSlice)
// 删除使用append实现 重新赋值
// 删除第一个元素 [1:]
//strSlice = strSlice[1:]
//
//t.Log(strSlice)
//
//// 删除第二个元素 a = append(a[:i], a[i+1:]...) // 删除中间第i个元素(只删除一个)
//strSlice = append(strSlice[:1], strSlice[2:]...)
//t.Log(strSlice)
//
//strSlice = remove(strSlice, 2)
//
//t.Log(strSlice)
//
//strSlice = newRemove01(strSlice, 1)
//t.Log(strSlice)
strSlice = newRemove02(strSlice, 1)
t.Log(strSlice)
}
// 利用上面的方式 封装程一个函数 效率很低 因为是copy重新赋值操作
func remove(slice []string, s int) []string {
return append(slice[:s], slice[s+1:]...)
}
func newRemove01(s []string, i int) []string {
s[len(s)-1], s[i] = s[i], s[len(s)-1]
return s[:len(s)-1]
}
//参考 https://stackoverflow.com/questions/37334119/how-to-delete-an-element-from-a-slice-in-golang
func newRemove02(s []string, i int) []string {
s[i] = s[len(s)-1]
// We do not need to put s[i] at the end, as it will be discarded anyway
return s[:len(s)-1]
}
<file_sep>/GinStudy/config/config.go
/*
* @Time : 2020-11-19 10:41
* @Author : CoderCharm
* @File : config.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 读取配置文件
**/
package config
type Server struct {
JWT JWT `mapstructure:"jwt" json:"jwt" yaml:"jwt"`
System System `mapstructure:"system" json:"system" yaml:"system"`
Zap Zap `mapstructure:"zap" json:"zap" yaml:"zap"`
Redis Redis `mapstructure:"redis" json:"redis" yaml:"redis"`
Mysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`
}
<file_sep>/03_case_demo/06_cron_task/01_demo/demo01_test.go
/*
* @Time : 2021-01-04 20:31
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _1_demo
import (
"fmt"
"github.com/robfig/cron/v3"
"testing"
"time"
)
// 定时任务
func jobTask() {
fmt.Printf("任务启动: %s \n", time.Now().Format("2006-01-02 15:04:05"))
}
func TestCron(t *testing.T) {
// 创建一个cron对象
c := cron.New()
// 任务调度
enterId, err := c.AddFunc("@every 3s", jobTask)
if err != nil {
panic(err)
}
fmt.Printf("任务id是 %d \n", enterId)
// 同步执行任务会阻塞当前执行顺序 一般使用Start()
//c.Run()
//fmt.Println("当前执行顺序.......")
// goroutine 协程启动定时任务(看到后面Start函数和run()函数,就会明白启动这一步也可以写在任务调度之前执行)
c.Start()
// Start()内部有一个running 布尔值 限制只有一个Cron对象启动 所以这一步多个 c.Start() 也只会有一个运行
c.Start()
c.Start()
// 用于阻塞 后面可以使用 select {} 阻塞
time.Sleep(time.Second * 9)
// 关闭定时任务(其实不关闭也可以,主进程直接结束了, 内部的goroutine协程也会自动结束)
c.Stop()
}
<file_sep>/03_case_demo/02_http_demo/test_gorequest/req03_pool_test.go
/*
* @Time : 2020-12-31 17:31
* @Author : CoderCharm
* @File : req03_pool_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
创建一个请求对象池, 并发请求
**/
package test_gorequest
import (
"errors"
"fmt"
"github.com/parnurzeal/gorequest"
"testing"
"time"
)
// 定义一个请求对象池
type ReqPool struct {
poolChan chan *gorequest.SuperAgent
}
// 获取一个请求对象
func (p *ReqPool) FetchReq(timeout time.Duration) (req *gorequest.SuperAgent, err error) {
select {
case req = <-p.poolChan:
return req, nil
case <-time.After(timeout): //超时控制
return nil, errors.New("time out")
}
}
// 释放请求 到请求池
func (p *ReqPool) ReleaseReq(req *gorequest.SuperAgent) error {
select {
case p.poolChan <- req:
return nil
default:
return errors.New("request pools overflow")
}
}
// New请求池
func NewReqPool(poolNum int) *ReqPool {
// 实例化
poolObj := ReqPool{}
// 创建请求对象channel
poolObj.poolChan = make(chan *gorequest.SuperAgent, poolNum)
for i := 0; i < poolNum; i++ {
baseRequest := gorequest.New().Timeout(5*time.Second).Set("User-Agent", UserAgent).
Set("self_token", "111")
poolObj.poolChan <- baseRequest
}
return &poolObj
}
func TestReqPool(t *testing.T) {
requestPool := NewReqPool(10)
req, err := requestPool.FetchReq(time.Second * 5)
if err != nil {
panic("获取请求对象错误")
}
defer func(requestPool *ReqPool, req *gorequest.SuperAgent) {
_ = requestPool.ReleaseReq(req)
}(requestPool, req)
getUrl := "https://httpbin.org/get"
resp, body, errs := req.Clone().Get(getUrl).End()
if errs != nil {
panic(fmt.Sprintf("URL:%s 请求错误: %s", getUrl, errs))
}
fmt.Println(resp)
// 可以使用 _ 接收 resp
fmt.Printf("url:%s 请求状态 %s \n", getUrl, resp.Status)
fmt.Println(body)
//fmt.Println(runtime.NumGoroutine())
}
<file_sep>/03_case_demo/05_go_grpc/go_micro/README.md
# go-micro demo
## 声明
此案例运行失败
安装v3版本
```shell
go get github.com/asim/go-micro/cmd/protoc-gen-micro/v3
```
## 官方示例
https://github.com/asim/go-micro/tree/master/cmd/protoc-gen-micro
生成其他文件
```shell
// 先安装
$ go get github.com/golang/protobuf/protoc-gen-go
// 自己手动生成
protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. greeter.proto
```
慕课网教程 xxxx为慕课网购买课程后的校验码
```shell
sudo docker run --rm -v $(pwd):$(pwd) -w $(pwd) -e ICODE=xxxxx cap1573/cap-protoc -I ./ --go_out=./ --micro_out=./ ./cap/imooc.proto
```<file_sep>/GinStudy/initialize/redis.go
/*
* @Time : 2020-12-18 16:00
* @Author : CoderCharm
* @File : redis.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : Redis 初始化
**/
package initialize
import (
"gin_study/global"
"github.com/go-redis/redis"
"go.uber.org/zap"
)
func Redis() {
redisCfg := global.GIN_CONFIG.Redis
client := redis.NewClient(&redis.Options{
Addr: redisCfg.Addr,
Password: redisCfg.Password, // no password set
DB: redisCfg.DB, // use default DB
})
pong, err := client.Ping().Result()
if err != nil {
global.GIN_LOG.Error("redis connect ping failed, err:", zap.Any("err", err))
} else {
global.GIN_LOG.Info("redis connect ping response:", zap.String("pong", pong))
global.GIN_REDIS = client
}
}
<file_sep>/03_case_demo/06_cron_task/01_demo/demo03_test.go
/*
* @Time : 2021-01-05 21:41
* @Author : CoderCharm
* @File : demo03_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _1_demo
import (
"fmt"
"github.com/robfig/cron/v3"
"testing"
"time"
)
type testJob struct {
Name string
}
//实现了 type Job interface {Run()} func名字必须为Run
func (t *testJob) Run() {
fmt.Println("test job 参数为", t.Name)
}
func Test03Cron(t *testing.T) {
// 设置时区
nyc, _ := time.LoadLocation("Asia/Shanghai")
// 设置时区, 支持秒级调度
GlobalCron := cron.New(cron.WithLocation(nyc), cron.WithSeconds())
// 调用第一个
entryId01, _ := GlobalCron.AddFunc("@every 1s", jobTask)
fmt.Printf("第一个id %v \n", entryId01)
// 执行第二个
entryId02, _ := GlobalCron.AddJob("*/2 * * * * *", &testJob{"JobName"})
fmt.Printf("第二个id %v \n", entryId02)
GlobalCron.Start()
select {}
}
<file_sep>/01_getting-started/02_Package/util/name2.go
package util2
var Zzz = "this is name222"
//var zzz = "this is zzz" error
<file_sep>/03_case_demo/09_custom_web_framework/04_gee_context/main.go
/*
* @Time : 2021-02-01 20:43
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"practice/03_case_demo/09_custom_web_framework/04_gee_context/gee"
)
func main() {
r := gee.New()
r.GET("/", func(c *gee.Context) {
c.String(200, "测试首页 你输入的name为%s 路径为 %s", c.Query("name"), c.Path)
})
r.GET("/json", func(c *gee.Context) {
c.JSON(200, gee.H{
"json": "Value",
})
})
_ = r.Run("127.0.0.1:7053")
}
<file_sep>/03_case_demo/08_casbin/README.md
# Casbin 权限控制管理
前置条件先搞懂 各个模型 策略的关系
- https://casbin.org/docs/zh-CN/how-it-works
- https://casbin.org/zh-CN/editor
## 参考
- [Casbin官网](https://casbin.org/docs/zh-CN/get-started)
- [Casbin官方模式编辑器](https://casbin.org/zh-CN/editor)
- [奇淼大佬的B站教程 上](https://www.bilibili.com/video/BV1qz4y167XP)
- [奇淼大佬的B站教程 下](https://www.bilibili.com/video/BV13r4y1M7AC)
<file_sep>/GinStudy/utils/rotatelogs_unix.go
/*
* @Time : 2020-11-19 10:45
* @Author : CoderCharm
* @File : rotatelogs_unix.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package utils
import (
"gin_study/global"
zaprotatelogs "github.com/lestrrat-go/file-rotatelogs"
"go.uber.org/zap/zapcore"
"os"
"path"
"time"
)
// GetWriteSyncer zap logger中加入file-rotatelogs
func GetWriteSyncer() (zapcore.WriteSyncer, error) {
fileWriter, err := zaprotatelogs.New(
path.Join(global.GIN_CONFIG.Zap.Director, "%Y-%m-%d.log"),
zaprotatelogs.WithLinkName(global.GIN_CONFIG.Zap.LinkName),
zaprotatelogs.WithMaxAge(7*24*time.Hour),
zaprotatelogs.WithRotationTime(24*time.Hour),
)
if global.GIN_CONFIG.Zap.LogInConsole {
return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter)), err
}
return zapcore.AddSync(fileWriter), err
}
<file_sep>/GinStudy/config/system.go
/*
* @Time : 2020-12-31 10:27
* @Author : CoderCharm
* @File : system.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 读取系统配置
**/
package config
type System struct {
Env string `mapstructure:"env" json:"env" yaml:"env"`
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"`
UseMultipoint bool `mapstructure:"use-multipoint" json:"useMultipoint" yaml:"use-multipoint"`
}
<file_sep>/02_algorithm/leetcode_everday/354_Russian_Doll_Envelopes/russian_doll_envelopes_test.go
/*
* @Time : 2021-03-04 20:46
* @Author : CoderCharm
* @File : russian_doll_envelopes_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
俄罗斯套娃 困难
给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。
当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
注意:不允许旋转信封。
示例 1:
输入:envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出:3
解释:最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
示例 2:
输入:envelopes = [[1,1],[1,1],[1,1]]
输出:1
提示:
1 <= envelopes.length <= 5000
envelopes[i].length == 2
1 <= wi, hi <= 104
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/russian-doll-envelopes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
动态规划 不熟 后面再回来解
**/
package _54_Russian_Doll_Envelopes
import "testing"
//func maxEnvelopes(envelopes [][]int) int {
//
//}
func TestLopes(t *testing.T) {
}
<file_sep>/01_getting-started/05_Pointer/02_demo.go
/*
*/
package main
import (
"fmt"
)
func main() {
a := [3]string{"a", "b", "c"}
// 定义一个数组指针 外部是一个指针 内部是元素
var b *[3]string
b = &a
// 先通过*b取出array值 然后修改 array里面的值
(*b)[0] = "zzz"
fmt.Println(a)
c := [3]string{"q", "w", "e"}
// 定义一个指针数组 外部是array 里面元素是指针
d := [3]*string{&c[0], &c[1], &c[2]}
fmt.Println(c)
*d[0] = "qqqqq"
fmt.Println(d, *d[0])
fmt.Println(c)
// 定义一个map key为值 value为 字符串指针
e := map[string]*string{}
f := "r"
e["a"] = &f
fmt.Println("e是", e)
// 定义一个map key value都为 字符串指针
g := map[*string]*string{}
h := "t"
i := "y"
// 字符串指针 key赋予地址 value也赋予地址
g[&h] = &i
fmt.Println("g是", g, "取value值", *g[&h])
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/05_func.go
/*
函数是Go里面的核心设计,它通过关键字func来声明,它的格式如下:
func funcName(input1 type1, input2 type2) (output1 type1, output2 type2) {
//这里是处理逻辑代码
//返回多个值
return value1, value2
}
上面的代码我们看出
关键字func用来声明一个函数funcName
函数可以有一个或者多个参数,每个参数后面带有类型,通过,分隔
函数可以返回多个值
上面返回值声明了两个变量output1和output2,如果你不想声明也可以,直接就两个类型
如果只有一个返回值且不声明返回值变量,那么你可以省略 包括返回值 的括号
如果没有返回值,那么就直接省略最后的返回信息
如果有返回值, 那么必须在函数的外层添加return语句
*/
package main
import "fmt"
func myMax(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
// func 注意go里面函数内部不能声明函数
// 但是能返回函数 闭包
var maxValue int
a, b := 1, 3
var (
x = 1
y = 2
z = 3
)
fmt.Println(myMax(x, y))
fmt.Println(myMax(x, z))
fmt.Println(myMax(y, z))
maxValue = myMax(a, b)
fmt.Println(maxValue)
fmt.Println("-----")
e, f := SumAndProduct(x, z)
fmt.Println(e, f)
}
/*
上面的例子我们可以看到直接返回了两个参数,当然我们也可以命名返回参数的变量,这个例子里面只是用了两个类型,我们也可以改成如下这样的定义,
然后返回的时候不用带上变量名,因为直接在函数里面初始化了。但如果你的函数是导出的(首字母大写),
官方建议:最好命名返回值,因为不命名返回值,虽然使得代码更加简洁了,但是会造成生成的文档可读性差。
*/
func SumAndProduct(A, B int) (add int, Multiplied int) {
add = A + B
Multiplied = A * B
return
}
<file_sep>/GinStudy/global/common_model.go
/*
* @Time : 2021-01-07 19:09
* @Author : CoderCharm
* @File : common_model.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
表通用的一些字段
**/
package global
import (
"gorm.io/gorm"
"time"
)
// ORM 通用字段
type COMMON_MODEL struct {
ID uint `gorm:"primarykey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
<file_sep>/03_case_demo/02_http_demo/req3_post_test.go
/*
* @Time : 2020-12-27 15:11
* @Author : CoderCharm
* @File : req3_post_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
post form 请求
**/
package http_demo
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"testing"
)
func PostReq(targetUrl string) (content string, err error) {
// 最简单的发送 post请求 携带 form参数
resp, err := http.PostForm(targetUrl, url.Values{"username": {"wxy"}, "password": {"<PASSWORD>"}})
// 相当于这种
//req.Header.Set("Content-Type", "multipart/form-data")
if err != nil {
return "", errors.New(fmt.Sprintf("请求错误 %s", err))
}
fmt.Println(fmt.Sprintf("响应状态 %s", resp.Status))
// 记得关闭客户端
defer resp.Body.Close()
// 读取内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.New(fmt.Sprintf("读取内容错误 %s", err))
}
content = string(body)
return content, nil
}
func TestReq3(t *testing.T) {
targetUrl := "https://httpbin.org/post"
content, err := PostReq(targetUrl)
if err != nil {
fmt.Println("请求错误", err)
return
}
fmt.Println(content)
}
<file_sep>/docs/index.md
---
home: true
heroImage: https://cdn.jsdelivr.net/gh/CoderCharm/notes@master/docs/logo.png
heroAlt: Logo image
heroText: Just For Fun
tagline: 王小右个人笔记
actionText: 开始
actionLink: /guide/
features:
- title: Golang
details: Go基础相关笔记,Gin框架学习,Go微服务相关知识.
- title: Python
details: Python基础笔记,FastAPI框架学习,爬虫相关内容分享.
- title: JavaScript & Vue
details: JavaScript笔记,Vue技术栈为主,记录学习路径.
footer: MIT Licensed | Copyright © 2021-present 王小右 基于vitepress创建
---<file_sep>/01_getting-started/03_Variable/04_map/test05_make_new.go
/*
make、new操作
make用于内建类型(map、slice 和channel)的内存分配。new用于各种类型的内存分配。
内建函数new本质上说跟其它语言中的同名函数功能一样:new(T)分配了零值填充的T类型的内存空间,并且返回其地址,
即一个*T类型的值。用Go的术语说,它返回了一个指针,指向新分配的类型T的零值。有一点非常重要:
new返回指针。
内建函数make(T, args)与new(T)有着不同的功能,make只能创建slice、map和channel,
并且返回一个有初始值(非零)的T类型,而不是*T。本质来讲,导致这三个类型有所不同的原因是指向数据结构的引用在使用前必须被初始化。
例如,一个slice,是一个包含指向数据(内部array)的指针、长度和容量的三项描述符;在这些项目被初始化之前,slice为nil。
对于slice、map和channel来说,make初始化了内部的数据结构,填充适当的值。
make返回初始化后的(非零)值。
*/
package _04_map
<file_sep>/03_case_demo/09_custom_web_framework/06_router_group_hook/main.go
/*
* @Time : 2021-02-02 20:12
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package main
import (
"log"
"net/http"
"practice/03_case_demo/09_custom_web_framework/06_router_group_hook/gee"
"time"
)
func LogHook() gee.HandlerFunc {
return func(c *gee.Context) {
// Start timer
t := time.Now()
// 如果错误 可以直接返回
//c.Fail(500, "Internal Server Error")
// 计算请求解析时间
log.Printf("[%d] %s in %v for group v2", c.StatusCode, c.Req.RequestURI, time.Since(t))
}
}
func main() {
r := gee.New()
// 捕获所有异常中间件
r.Use(gee.Recovery())
// 使用自定义中间件
r.Use(LogHook())
r.GET("/index", func(c *gee.Context) {
names := []string{"test_str"}
c.String(http.StatusOK, names[100])
})
v1 := r.Group("/v1")
{
v1.GET("", func(c *gee.Context) {
c.HTML(http.StatusOK, "<h1>Hello Gee</h1>")
})
v1.GET("/hello", func(c *gee.Context) {
// expect /hello?name=Erwin
c.String(http.StatusOK, "hello %s, you're at %s\n", c.Query("name"), c.Path)
})
}
v2 := r.Group("/v2")
{
v2.GET("/hello/:name", func(c *gee.Context) {
// expect /hello/Levi
c.String(http.StatusOK, "hello %s, you're at %s\n", c.Param("name"), c.Path)
})
v2.POST("/login", func(c *gee.Context) {
c.JSON(http.StatusOK, gee.H{
"username": c.PostForm("username"),
"password": c.PostForm("<PASSWORD>"),
})
})
}
_ = r.Run("127.0.0.1:7055")
}
<file_sep>/GinStudy/utils/tools.go
/*
* @Time : 2020-12-31 11:46
* @Author : CoderCharm
* @File : tools.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 常见工具类
**/
package utils
import "encoding/json"
// string 转 map
func StringToMap(content string) (map[string]interface{}, error) {
var resMap map[string]interface{}
err := json.Unmarshal([]byte(content), &resMap)
if err != nil {
return nil, err
}
return resMap, nil
}
<file_sep>/GinStudy/config/jwt.go
/*
* @Time : 2021-01-08 20:27
* @Author : CoderCharm
* @File : jwt.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package config
type JWT struct {
SigningKey string `mapstructure:"signing-key" json:"signingKey" yaml:"signing-key"`
ExpiresTime int64 `mapstructure:"expires-time" json:"expiresTime" yaml:"expires-time"`
BufferTime int64 `mapstructure:"buffer-time" json:"bufferTime" yaml:"buffer-time"`
}
<file_sep>/03_case_demo/09_custom_web_framework/02_router_select/main.go
/*
* @Time : 2021-02-01 19:50
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
package http
// A Handler responds to an HTTP request.
//
// ServeHTTP should write reply headers and data to the ResponseWriter
// and then return. Returning signals that the request is finished; it
// is not valid to use the ResponseWriter or read from the
// Request.Body after or concurrently with the completion of the
// ServeHTTP call.
//
// Depending on the HTTP client software, HTTP protocol version, and
// any intermediaries between the client and the Go server, it may not
// be possible to read from the Request.Body after writing to the
// ResponseWriter. Cautious handlers should read the Request.Body
// first, and then reply.
//
// Except for reading the body, handlers should not modify the
// provided Request.
//
// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
// that the effect of the panic was isolated to the active request.
// It recovers the panic, logs a stack trace to the server error log,
// and either closes the network connection or sends an HTTP/2
// RST_STREAM, depending on the HTTP protocol. To abort a handler so
// the client sees an interrupted response but the server doesn't log
// an error, panic with the value ErrAbortHandler.
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
func ListenAndServe(address string, h Handler) error
这种是实现 Handler接口 ServeHTTP(ResponseWriter, *Request) 的方式启动服务。
该接口只定义了一个方法,只要一个类型实现了这个 ServeHTTP 方法,
就可以把该类型的变量直接赋值给 Handler接口,本次demo就是基于这种方式实现
后面的gee也是这种方式
**/
package main
import (
"fmt"
"net/http"
)
type Engine struct {
router router
}
// 定义请求函数类型
type handler func(w http.ResponseWriter, r *http.Request)
// 定义路由 - 对应 处理请求函数
type router map[string]handler
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 只通过路径 匹配处理请求的方法 不区分 GET or POST
// r.URL.Path
if handler, ok := engine.router[r.URL.Path]; ok {
handler(w, r)
} else {
_, _ = fmt.Fprintf(w, "404")
}
}
func hello(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "Hello World")
}
func main() {
r := router{}
r["/"] = func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "首页")
}
r["/hello"] = hello
//engine := new(Engine)
engine := &Engine{
router: r,
}
addr := "127.0.0.1:7051"
fmt.Println("服务启动:", addr)
_ = http.ListenAndServe(addr, engine)
}
<file_sep>/docs/.vitepress/config.js
module.exports = {
title: '王小右笔记',
description: 'Just For Fun',
lang: 'zh-CN',
heroImage: "https://cdn.jsdelivr.net/gh/CoderCharm/notes@master/docs/logo.png",
base: "/notes/",
themeConfig: {
repo: 'CoderCharm/notes',
docsDir: 'docs',
editLinks: true,
editLinkText: 'Edit this page on GitHub',
lastUpdated: 'Last Updated',
nav: [
{
text: 'Golang',
link: '/Golang/',
activeMatch: '^/Golang/'
},
{
text: 'Python',
link: '/Python/',
activeMatch: '^/Python/'
},
{
text: 'JavaScript',
link: '/JavaScript/',
activeMatch: '^/JavaScript/'
},
{
text: 'Linux',
link: '/Linux/',
activeMatch: '^/Linux/'
},
{
text: 'Database',
link: '/Database/',
activeMatch: '^/Database/'
},
],
sidebar: {
'/guide/': getGuideSidebar(),
'/Golang/': getGolangConfig(),
// '/': getGuideSidebar()
}
}
};
function getGuideSidebar() {
return [
{
text: '笔记目录',
children: [{text: '说明', link: '/guide/index'}]
},
{
text: '分类',
children: [
{text: 'Golang', link: '/Golang/index'},
{text: 'Python', link: '/Python/index'},
{text: 'JavaScript', link: '/JavaScript/index'},
{text: 'Linux', link: '/Linux/index'},
{text: 'Database', link: '/Database/index'},
]
}
]
}
function getGolangConfig() {
return [
{
text: 'Go基础',
children: [{text: '说明', link: '/Golang/index'}]
},
{
text: 'Go进阶',
children: [
{
text: 'RabbitMQ',
children: [
{text: 'RabbitMQ介绍', link: '/Golang/rabbitMq/ch01_desc'},
]
},
]
}
]
}<file_sep>/GinStudy/utils/verify.go
/*
* @Time : 2020-11-25 21:34
* @Author : CoderCharm
* @File : verify.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 参数验证
**/
package utils
var (
PageInfoVerify = Rules{"Page": {Ge("1")}, "PageSize": {Le("50")}}
ArticleDetailVerify = Rules{"Href": {NotEmpty()}}
RegisterVerify = Rules{"Username": {NotEmpty()}, "Password": {NotEmpty()}}
LoginVerify = Rules{"Username": {NotEmpty()}, "Password": {NotEmpty()}}
)
<file_sep>/02_algorithm/sorts/bubble_sort_test.go
/*
* @Time : 2020-11-10 14:58
* @Author : CoderCharm
* @File : bubblesort.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package sorts
import (
"testing"
)
func BubbleSort(arr []int) []int {
swapped := true
for swapped {
swapped = false
for i := 0; i < len(arr)-1; i++ {
if arr[i+1] > arr[i] {
arr[i+1], arr[i] = arr[i], arr[i+1]
swapped = true
}
}
}
return arr
}
func TestBubbleSort(t *testing.T) {
v := []int{5, 1, 3, 2, 4}
t.Log(BubbleSort(v))
}
<file_sep>/03_case_demo/02_http_demo/req4_post_test.go
/*
* @Time : 2020-12-27 19:03
* @Author : CoderCharm
* @File : req4_post_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package http_demo
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"testing"
)
// post form请求 务必设置 Content-Type
func ReqPostForm(targetUrl string) (content string, err error) {
// 创建 http 客户端
client := &http.Client{}
form := url.Values{}
form.Add("ln", "ln222")
form.Add("ip", "1.1.1.1")
form.Add("ua", "ua123")
// 创建请求
req, _ := http.NewRequest("POST", targetUrl, strings.NewReader(form.Encode()))
req.Header.Set("User-Agent", "test")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// 发送请求
resp, err := client.Do(req)
if err != nil {
// 格式化返回错误
return "", errors.New(fmt.Sprintf("请求出错 %s", err))
}
// 最后关闭连接
defer resp.Body.Close()
// 读取内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.New(fmt.Sprintf("解析内容出错 %s", err))
}
return string(body), nil
}
// post json方式请求
func ReqPostJson(targetUrl string) (content string, err error) {
var jsonStr = []byte(`{"title":"this is a title", "cate": 1}`)
req, _ := http.NewRequest("POST", targetUrl, bytes.NewBuffer(jsonStr))
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", errors.New(fmt.Sprintf("请求出错 %s", err))
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
return string(body), nil
}
func TestReqPost(t *testing.T) {
targetUrl := "https://httpbin.org/post"
c1, _ := ReqPostForm(targetUrl)
t.Log(fmt.Sprintf("\nfrom表单返回: \n %s", c1))
c2, _ := ReqPostJson(targetUrl)
t.Log(fmt.Sprintf("\nJson请求返回: \n %s", c2))
}
<file_sep>/02_algorithm/sorts/quick_sort_test.go
/*
* @Time : 2021-03-08 20:47
* @Author : CoderCharm
* @File : quick_sort_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
快排
**/
package sorts
import (
"math/rand"
"testing"
)
func QuickSort(arr []int) []int {
if len(arr) <= 1 {
return arr
}
median := arr[rand.Intn(len(arr))]
lowPart := make([]int, 0, len(arr))
highPart := make([]int, 0, len(arr))
middlePart := make([]int, 0, len(arr))
for _, item := range arr {
switch {
case item < median:
lowPart = append(lowPart, item)
case item == median:
middlePart = append(middlePart, item)
case item > median:
highPart = append(highPart, item)
}
}
lowPart = QuickSort(lowPart)
highPart = QuickSort(highPart)
lowPart = append(lowPart, middlePart...)
lowPart = append(lowPart, highPart...)
return lowPart
}
func TestQuickSort(t *testing.T) {
l := []int{4, 2, 77, 23, 67, 23, 56, 9, 1, 0, 99}
t.Log(QuickSort(l))
}
<file_sep>/01_getting-started/08_panic_recover/README.md
参考
- https://draveness.me/golang/docs/part2-foundation/ch05-keyword/golang-panic-recover/
- https://hezhiqiang8909.gitbook.io/go/ch1-basic/ch1-07-error-and-panic
> Go中大量的 err != nil 给人感觉很不好。
## panic 触发的递归延迟调用
- `panic` 能够改变程序的控制流,调用 `panic` 后会立刻停止执行当前函数的剩余代码,并在当前 `Goroutine` 中递归执行调用方的 `defer`;
- `recover` 可以中止 `panic 造成的程序崩溃。它是一个只能在 `defer` 中发挥作用的函数,在其他作用域中调用不会发挥作用;
我们先通过几个例子了解一下使用 `panic` 和 `recover` 关键字时遇到的现象,部分现象也与上一节分析的 `defer` 关键字有关:
- `panic` 只会触发当前 `Goroutine` 的 `defer`;
- `recover` 只有在 `defer` 中调用才会生效;
- `panic` 允许在 `defer` 中嵌套多次调用;
<file_sep>/02_algorithm/leetcode_everday/50_first_show_string/first_show_string_test.go
/*
* @Time : 2021-03-04 20:55
* @Author : CoderCharm
* @File : first_show_string_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
简单
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
限制:
0 <= s 的长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
package _0_first_show_string
import (
"testing"
)
// 时间复杂度 O(2N) 两次for循环 随着N增长而增长
// 空间复杂度 O(1) list 大小是固定的,并不会随着N增长变化
func firstUniqChar(s string) byte {
// 一共26个字母 构建长度26的数组
list := make([]int, 26)
for _, v := range s {
// 循环字符串为bite - 97即a 为数组中的位置 +1 表示有值
list[v-97]++
}
for _, v := range s {
// 当前位置有值
if list[v-97] == 1 {
return byte(v)
}
}
return ' '
}
func TestFirstChar(t *testing.T) {
z := firstUniqChar("abaccdeff")
t.Log(z)
}
<file_sep>/01_getting-started/07_runtime/02_channel/chan3_test.go
/*
* @Time : 2020-12-29 14:38
* @Author : CoderCharm
* @File : chan3_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
channel select 多channel操作
与case的顺序无关
**/
package _2_channel
import (
"fmt"
"sync"
"testing"
"time"
)
func AsyncCh1(n int, c chan string, wg *sync.WaitGroup) {
for i := 0; i < n; i++ {
c <- fmt.Sprintf("++ %d ++", i)
}
wg.Done()
}
func AsyncCh2(n int, c chan string, wg *sync.WaitGroup) {
for i := n; i > 0; i-- {
c <- fmt.Sprintf("-- %d --", i)
}
wg.Done()
}
func TestSelect(t *testing.T) {
var wg sync.WaitGroup
ch1 := make(chan string, 5)
ch2 := make(chan string, 5)
wg.Add(2)
go AsyncCh1(cap(ch1), ch1, &wg)
//wg.Add(1)
go AsyncCh2(cap(ch2), ch2, &wg)
// 等待协程全部执行完
wg.Wait()
for i := 0; i < 10; i++ {
select {
case ret1 := <-ch1:
t.Log(ret1)
case ret2 := <-ch2:
t.Log(ret2)
case <-time.After(time.Millisecond * 100):
t.Error("time out")
}
}
}
<file_sep>/02_algorithm/leetcode_everday/232_queue_use_stack/double_stack_test.go
/*
* @Time : 2021-03-05 21:15
* @Author : CoderCharm
* @File : double_stack_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
仅使用两个栈实现先入先出队列
将一个栈当作输入栈,用于push数据 一个当作输出栈,用于pop和peek
**/
package _32_queue_use_stack
import "testing"
type MyQueue struct {
inStack, outStack []int
}
/** Initialize your data structure here. */
func Constructor() MyQueue {
return MyQueue{}
}
/** Push element x to the back of queue. */
func (m *MyQueue) Push(x int) {
m.inStack = append(m.inStack, x)
}
/**
一次把 inStack 的数据压入到 outStack里面
*/
func (m *MyQueue) in2OutStack() {
for len(m.inStack) > 0 {
// 最后一个元素依次压入到输出栈
m.outStack = append(m.outStack, m.inStack[len(m.inStack)-1])
// 输入栈 去掉 压入到输出栈里的数据
m.inStack = m.inStack[:len(m.inStack)-1]
}
}
/** Removes the element from in front of queue and returns that element. */
func (m *MyQueue) Pop() int {
if len(m.outStack) == 0 {
m.in2OutStack()
}
n := m.outStack[len(m.outStack)-1]
m.outStack = m.outStack[:len(m.outStack)-1]
return n
}
/** Get the front element. */
func (m *MyQueue) Peek() int {
if len(m.outStack) == 0 {
m.in2OutStack()
}
// 输出栈 最后的一个 元素即为 最前面的元素
return m.outStack[len(m.outStack)-1]
}
///** Returns whether the queue is empty. */
func (m *MyQueue) Empty() bool {
return len(m.inStack) == 0 && len(m.outStack) == 0
}
func TestQueueStack(t *testing.T) {
obj := Constructor()
obj.Push(3)
obj.Push(6)
obj.Push(8)
t.Log(obj.inStack)
t.Log(obj.outStack)
t.Log(obj.Peek())
t.Log(obj.Pop())
t.Log(obj.Pop())
t.Log(obj.Pop())
t.Log(obj.inStack)
t.Log(obj.outStack)
t.Log(obj.Empty())
}
<file_sep>/GinStudy/README.md
# Golang Web框架 Gin学习笔记
参考
- https://goproxy.io/zh/
- Go Modules 官网 https://blog.golang.org/using-go-modules
> 由于是练习,所有Go笔记代码都写在一个仓库里面,由于使用goland IDE,所以把`GinStudy`标记为根目录
## 环境配置 Go 版本是 1.13 及以上 (推荐)
```
go env -w GO111MODULE=auto
go env -w GOPROXY=https://goproxy.io,direct
```
### ide goland 配置
```
setting->Go->Go Modules->Proxy:https://goproxy.io
```
Enable Go Mod 打勾
## 项目目录说明
<details>
<summary>目录</summary>
```
.
|____api 接口目录
| |____v1 v1
| | |____article.go 文章接口
|____config 配置文件
| |____config.go 汇聚配置文件结构体
| |____zap.go 定义读取配置文件yaml格式
| |____gorm.go 定义读取数据库配置文件yaml格式
|____core 核心的基础服务配置
| |____server.go 通过全局路由 启动http服务
| |____zap.go 日志文件配置
| |____viper.go 读取配置文件
|____global 定义全局变量
| |____global.go
|____initialize 各种初始化文件
| |____router.go 汇聚各模块路由
| |____gorm.go 定义`gorm`数据库配置
|____middleware 定义中间价
| |____cors.go 跨域中间件
| |____zaplogger.go 记录日志中间价
|____model 定义各种model
| |____request 请求参数model
| | |____common.go 通用请求参数
| |____response 响应参数model
| | |____common.go 通用响应参数
| | |____response.go
| |____article.go 文章表model
|____router 路由分组(配置中间价)
| |____article.go 文章model路由
|____service 表操作逻辑
| |____article.go 文章表的curd操作
|____utils 通用的工具方法
| |____rotatelogs_unix.go
| |____directory.go
| |____constant.go
|____config.yaml 配置文件
|____go.mod
|____go.sum
|____main.go 启动文件
|____README.md
```
</details>
### 初始化
```
cd 项目文件夹 // 进入项目文件夹下
go mod init gin_stydy // gin_stydy为项目名(随意取)
// 就会创建go.mod文件
```
## GO Modules常见命令
```
go list // 列出主模块(当前模块)
```
```
go list -m all // 列出了当前模块及其所有依赖项
```
删除未使用的依赖项
```
go mod tidy
```
github 拉取 他人含有go.mod的项目时,下载所有第三方包
```
go mod download
```
验证依赖是否正确
```
go mod verify
```
升级库依赖, 比如Gin框架 升级
```
go get -u github.com/gin-gonic/gin
```
安装依赖指定版本
```
go get github.com/gin-gonic/gin@version
```
安装依赖指指定分支
```
go get github.com/gin-gonic/gin@master
```<file_sep>/01_getting-started/04_Control_statements_and_functions/README.md
## 流程和函数
这小节我们要介绍Go里面的流程控制以及函数操作。
#### 流程控制
> 流程控制在编程语言中是最伟大的发明了,因为有了它,你可以通过很简单的流程描述来表达很复杂的逻辑。
Go中流程控制分三大类:条件判断,循环控制和无条件跳转。
if 语句
```go
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is less than 10")
}
```<file_sep>/01_getting-started/07_runtime/03_channel_context/first_response_test.go
/*
* @Time : 2020-12-30 15:20
* @Author : CoderCharm
* @File : first_response_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
并发控制
**/
package _3_channel_context
import (
"fmt"
"runtime"
"testing"
"time"
)
func runTask(id int) string {
time.Sleep(10 * time.Millisecond)
return fmt.Sprintf("The result is from %d", id)
}
func FirstResponse() string {
numOfRunner := 10
// 不指定buffer会协程泄漏 函数返回后 还有其他协程存活 耗尽资源
//ch := make(chan string)
// numOfRunner 防止协程泄漏
ch := make(chan string, numOfRunner)
for i := 0; i < numOfRunner; i++ {
go func(i int) {
ret := runTask(i)
ch <- ret
//ch <- fmt.Sprintf("result is from %d", i)
}(i)
}
// 注意 当channel里面有值的时候 就回立即返回 没有就会阻塞
return <-ch
}
func TestFirstResponse(t *testing.T) {
// 会输出当前系统中的协程数
t.Log("Before:", runtime.NumGoroutine())
// 响应每次不一致 是由于 channel的阻塞机制
t.Log(FirstResponse())
//
time.Sleep(time.Second * 5)
t.Log("After:", runtime.NumGoroutine())
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/06_01_func.go
/*
参数
变参
Go函数支持变参。接受变参的函数是有着不定数量的参数的。为了做到这点,首先需要定义函数使其接受变参:
传值与传指针
当我们传一个参数值到被调用函数里面时,实际上是传了这个值的一份copy,当在被调用函数中修改参数值的时候,调用函数中相应实参不会发生任何变化,因为数值变化只作用在copy上。
为了验证我们上面的说法,我们来看一个例子
*/
package main
import "fmt"
//变参
func haHa(arg ...int) {
// arg ...int告诉Go这个函数接受不定数量的参数。
// 注意,这些参数的类型全部是int。在函数体中,变量arg是一个int的slice:
for i, v := range arg {
fmt.Println(i, v)
}
}
//简单的一个函数,实现了参数+1的操作
func add1(a *int) (z int) { // 请注意,
*a = *a + 1 // 修改了a的值
return *a
}
/*
defer v.推迟;延缓;展期;
Go语言中有种不错的设计,即延迟(defer)语句,你可以在函数中添加多个defer语句。当函数执行到最后时,
这些defer语句会按照逆序执行,最后该函数返回。特别是当你在进行一些打开资源的操作时,遇到错误需要提前返回,
在返回前你需要关闭相应的资源,不然很容易造成资源泄露等问题。如下代码所示,我们一般写打开一个资源是这样操作的:
*/
func myDefer() {
a := "aaaa"
b := "bbbb"
defer fmt.Println(a)
defer fmt.Println(b)
for i := 0; i < 5; i++ {
defer fmt.Printf("%d ", i)
}
}
func main() {
haHa(4, 5, 8, 9)
x := 1
fmt.Println("x = ", x) // 应该输出 "x = 3"
x1 := add1(&x) // 调用 add1(&x) 传x的地址
//add1(&x)
fmt.Println("x+1 = ", x1) // 应该输出 "x+1 = 4"
fmt.Println("x = ", x) // 应该输出 "x = 4"
myDefer()
}
<file_sep>/GinStudy/core/server.go
/*
* @Time : 2020-11-17 11:47
* @Author : CoderCharm
* @File : server.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 启动服务
**/
package core
import (
"gin_study/global"
"gin_study/initialize"
"go.uber.org/zap"
"net/http"
"time"
)
func RunWindowsServer() {
// 初始化redis
initialize.Redis()
// 初始化路由
Router := initialize.Routers()
// 取系统配置的地址 并格式化:
address := global.GIN_CONFIG.System.Addr
global.GIN_LOG.Info("当前地址为:", zap.Any("ipAddress", address))
//_ = Router.Run(address) // gin启动web服务
// 启用原生的 web服务器 方便其他配置
s := &http.Server{
Addr: address,
Handler: Router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe().Error()
}
<file_sep>/01_getting-started/06_data_struct/01_stack/main.go
/*
* @Time : 2020-08-27 22:42
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 用slice实现的最基本的栈结构
**/
package main
import (
"encoding/json"
"fmt"
)
type Stack struct {
items []int
}
func (s *Stack) push(n int) {
// 压入栈
s.items = append(s.items, n)
}
func (s *Stack) pop() int {
// 弹出栈 没有判断范围
value := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return value
}
func (s *Stack) peek() int {
// 查看栈顶元素
return s.items[len(s.items)-1]
}
func (s *Stack) isEmpty() bool {
// 判断是否为空
return len(s.items) == 0
}
func (s *Stack) size() int {
// 查看栈长度
return len(s.items)
}
func (s *Stack) toString() string {
// 返回栈字符串
v, _ := json.Marshal(s.items)
return string(v)
}
func main() {
var s Stack
s.push(1)
fmt.Println("压入栈", s.items)
s.push(2)
fmt.Println("压入栈", s.items)
s.push(3)
fmt.Println("压入栈", s.items)
fmt.Println("toString返回字符形式", s.toString())
fmt.Println("peek查看栈顶元素", s.peek())
fmt.Println("isEmpty查看栈是否为空", s.isEmpty())
fmt.Println("size查看栈个数", s.size())
fmt.Println(s.pop())
fmt.Println(s.pop())
fmt.Println(s.pop())
fmt.Println(s.items)
fmt.Println("isEmpty查看栈是否为空", s.isEmpty())
}
<file_sep>/01_getting-started/07_runtime/02_channel/async_test.go
/*
* @Time : 2020-12-28 23:33
* @Author : CoderCharm
* @File : async_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
CSP 并发机制
**/
package _2_channel
import (
"fmt"
"testing"
"time"
)
func service() string {
time.Sleep(time.Millisecond * 50)
return "Done"
}
func otherTask() {
fmt.Println("Other Task 111111")
time.Sleep(time.Millisecond * 50)
fmt.Println("Task is done")
}
//func TestService(t *testing.T) {
// fmt.Println(service())
// otherTask()
//}
func AsyncService() chan string {
// 创建一个channel
retCh := make(chan string)
//retCh := make(chan string, 1)
// 协程函数 异步执行
go func() {
ret := service()
fmt.Println("before return result")
// 往channel 存入值
retCh <- ret
fmt.Println("service exited.")
}()
return retCh
}
func TestAsyncService(t *testing.T) {
retCh := AsyncService()
otherTask()
fmt.Println(<-retCh)
time.Sleep(1 * time.Second)
//c := make(chan string, 4) // 修改 2 为 1 就报错,修改 2 为 3 可以正常运行
//c <- "1"
////c <- 2
//fmt.Println(<-c)
//fmt.Println(<-c)
}
<file_sep>/01_getting-started/07_runtime/04_obj_pool/obj_pool_test.go
/*
* @Time : 2020-12-30 21:59
* @Author : CoderCharm
* @File : obj_pool_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package _4_obj_pool
import (
"errors"
"fmt"
"testing"
"time"
)
// 新建一个空结构体 相当于对象
type Tool struct {
name string
}
// 对象池 用于存储 Tool对象
type ToolsBox struct {
// 属性是一个 channel 内容是 Tool 结构体指针
bufChan chan *Tool
}
// 获取工具 给结构体绑定方法
func (p *ToolsBox) GetTool(timeout time.Duration) (*Tool, error) {
select {
case tool := <-p.bufChan:
return tool, nil
case <-time.After(timeout): //超时控制
return nil, errors.New("time out")
}
}
// 用完归还(释放)
func (p *ToolsBox) ReleaseTool(tool *Tool) error {
select {
case p.bufChan <- tool:
return nil
default:
return errors.New("overflow")
}
}
// new一个 ToolBox对象
func NewToolsBox(poolNum int) *ToolsBox {
objPool := ToolsBox{}
objPool.bufChan = make(chan *Tool, poolNum)
for i := 0; i < poolNum; i++ {
// 生成一个 工具结构体
tool := &Tool{fmt.Sprintf("🔧--%d", i)}
// 存入对象池
objPool.bufChan <- tool
}
return &objPool
}
func TestObjPool(t *testing.T) {
pool := NewToolsBox(5)
//tool,_ := pool.GetTool(time.Second * 1)
//t.Log(fmt.Sprintf("取出一个当前容量%d", len(pool.bufChan)))
//t.Log(tool)
//
//_ = pool.ReleaseTool(tool)
//t.Log(fmt.Sprintf("归还后当前容量%d", len(pool.bufChan)))
for i := 0; i < 8; i++ {
tool, err := pool.GetTool(time.Second * 1)
if err != nil {
t.Log(fmt.Sprintf("---取出有问题 %s 当前容量%d", tool, len(pool.bufChan)))
} else {
// 取出没问题
t.Log(fmt.Sprintf("----取出一个 %s 当前容量%d", tool, len(pool.bufChan)))
// 接着就释放 和判断写在一起
if err := pool.ReleaseTool(tool); err != nil {
t.Log("释放有问题")
} else {
t.Log(fmt.Sprintf("释放一个 +++ %s 当前容量%d", tool, len(pool.bufChan)))
}
}
}
t.Log("结束")
}
<file_sep>/01_getting-started/07_runtime/03_channel_context/once_test.go
/*
* @Time : 2020-12-30 14:19
* @Author : CoderCharm
* @File : once_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
只运行一次, 类似单例模式
var once sync.Once
var obj *SingletonObj
func GetSingletonObj() *SingletonObj {
once.Do(func(){
fmt.Println("Create Singleton obj.")
obj = &SingletonObj{}
})
return obj
}
**/
package _3_channel_context
import (
"fmt"
"sync"
"testing"
"time"
)
// 新建一个结构体用于测试 查看是否地址 是否
type Singleton struct {
}
var singleInstance *Singleton
type ObjItem struct {
}
var genObjItem *ObjItem
var once sync.Once
func GetSingletonObj(i int) *Singleton {
fmt.Printf("单例程序执行 %d----\n", i)
once.Do(func() {
// 这里面只执行一次
fmt.Println("Create Singleton obj.")
singleInstance = new(Singleton)
})
return singleInstance
}
func GenObj(i int) *ObjItem {
fmt.Printf("生成程序执行 %d----\n", i)
genObjItem = new(ObjItem)
return genObjItem
}
func NormalFunc(i int) {
timeStr := time.Now().Format("2006-01-02 15:04:05")
fmt.Printf(" %d 测试函数 %s \n", i, timeStr)
}
func SingleFunc(i int) {
fmt.Printf("单例测试函数执行++ %d \n", i)
once.Do(func() {
// 这里面只执行一次
timeStr := time.Now().Format("2006-01-02 15:04:05")
fmt.Printf("%d------单例子测试函数 只执行一次 %s \n", i, timeStr)
//singleInstance = new(Singleton)
})
}
func TestGetSingletonObj(t *testing.T) {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int) {
//obj := GetSingletonObj(i)
//fmt.Printf("单例: %d++++%x\n", i, unsafe.Pointer(obj))
NormalFunc(i)
SingleFunc(i)
wg.Done()
}(i)
}
wg.Wait()
}
<file_sep>/03_case_demo/10_RabbmitMQ/README.md
## Golang 操作 RabbitMQ
## docker 安装 RabbitMQ
https://hub.docker.com/_/rabbitmq
安装tag 带有 `management`也就是带有web管理界面的
拉取镜像
```
docker pull rabbitmq:3.8-management
```
启动
```
docker run --name rabbitmq -d -p 15672:15672 -p 5672:5672 rabbitmq:3.8-management
```
```
--name指定了容器名称
-d 指定容器以后台守护进程方式运行
-p指定容器内部端口号与宿主机之间的映射,rabbitMq默认要使用15672为其web端界面访问时端口,5672为数据通信端口
```
然后会有默认的账号访问
```
http://127.0.0.1:15672
账号: guest
密码: <PASSWORD>
```
## 设置新的用户
查看容器运行 找到运行容器id
```
docker ps
```
进入容器shell交互环境 `49bced9dea83`为运行rabbitmq容器id
```
docker exec -i -t 49bced9dea83 bin/bash
```
新增超级管理员角色
```
// 设置用户名为 root 密码为<PASSWORD>
rabbitmqctl add_user root admin12345
// 设置所有权限
rabbitmqctl set_permissions -p / root ".*" ".*" ".*"
// 设置root用户administrator角色
rabbitmqctl set_user_tags root administrator
```
删除默认角色
```
rabbitmqctl delete_user guest
```
<file_sep>/GinStudy/api/v1/article.go
/*
* @Time : 2020-11-17 11:26
* @Author : CoderCharm
* @File : article.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package v1
import (
"gin_study/model/request"
"gin_study/model/response"
"gin_study/service"
"gin_study/utils"
"github.com/gin-gonic/gin"
)
// @Tags ArticleAPI
// @Summary 获取推荐文章
// @accept application/json
// @Produce application/json
// @Success 200 string {string}"{"code":200,"msg":"success","data":{}}"
// @Router /mini/api/article/get/recommend [get]
func GetRecommendArticle(c *gin.Context) {
RecommendArticleList := service.FetchRecommendArticleList()
//global.GIN_REDIS.Set()
response.OkWithData(RecommendArticleList, c)
}
// @Tags ArticleAPI
// @Summary 获取文章列表
// @accept application/json
// @Produce application/json
// @Param cateInfo body request.ArticleCategory true "文章分类"
// @Success 200 string {string}"{"code":200,"msg":"success","data":{}}"
// @Router /mini/api/article/get/list [get]
func GetArticleList(c *gin.Context) {
// 初始化请求参数
cateInfo := request.ArticleCategory{CateId: 0,
PageInfo: request.PageInfo{Page: 1, PageSize: 10},
}
_ = c.ShouldBindQuery(&cateInfo)
if err := utils.Verify(cateInfo.PageInfo, utils.PageInfoVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
articleList, total := service.FetchArticleIndexList(cateInfo)
response.OkWithDetailed(response.PageResult{
Data: articleList,
Total: total,
Page: cateInfo.Page,
PageSize: cateInfo.PageSize,
}, "success", c)
}
// @Tags ArticleAPI
// @Summary 获取文章分类
// @accept application/json
// @Produce application/json
// @Success 200 string {string}"{"code":200,"msg":"success","data":{}}"
// @Router /mini/api/article/get/category [get]
func GetCategoryList(c *gin.Context) {
CategoryList := service.FetchCategoryList()
response.OkWithData(CategoryList, c)
}
// @Tags ArticleAPI
// @Summary 获取文章详情
// @accept application/json
// @Produce application/json
// @Param data body request.ArticleDetail true "文章href链接"
// @Success 200 string {string}"{"code":200,"msg":"success","data":{}}"
// @Router /mini/api/article/get/detail [get]
func GetArticleDetail(c *gin.Context) {
href := request.ArticleDetail{}
_ = c.ShouldBindQuery(&href)
if err := utils.Verify(href, utils.ArticleDetailVerify); err != nil {
response.FailWithMessage(err.Error(), c)
return
}
DetailArticle := service.FetchArticleDetail(href)
response.OkWithData(DetailArticle, c)
}
<file_sep>/GinStudy/service/sys_user.go
/*
* @Time : 2021-01-07 20:25
* @Author : CoderCharm
* @File : sys_user.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package service
import (
"errors"
"gin_study/global"
"gin_study/model"
"gin_study/utils"
"github.com/satori/go.uuid"
"gorm.io/gorm"
)
//@author: [piexlmax](https://github.com/piexlmax)
//@function: Register
//@description: 用户注册
//@param: u model.SysUser
//@return: err error, userInter model.SysUser
func Register(u model.SysUser) (userInter model.SysUser, err error) {
var user model.SysUser
if !errors.Is(global.GIN_DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
return userInter, errors.New("用户名已注册")
}
// 否则 附加uuid 密码md5简单加密 注册
u.Password = utils.MD5V([]byte(u.Password))
u.UUID = uuid.NewV4()
err = global.GIN_DB.Create(&u).Error
return u, err
}
//@author: [piexlmax](https://github.com/piexlmax)
//@function: Login
//@description: 用户登录
//@param: u *model.SysUser
//@return: err error, userInter *model.SysUser
func Login(u *model.SysUser) (userInter *model.SysUser, err error) {
var user model.SysUser
u.Password = utils.MD5V([]byte(u.Password))
err = global.GIN_DB.Where("username = ? AND password = ?", u.Username, u.Password).Preload("Authority").First(&user).Error
return &user, err
}
<file_sep>/01_getting-started/03_Variable/README.md
# Go variable define
### Go variable type
-
在Go语言中,同时声明多个常量、变量,或者导入多个包时,可采用分组的方式进行声明。
```go
import "fmt"
import "os"
const i = 100
const pi = 3.1415
const prefix = "Go_"
var i int
var pi float32
var prefix string
```
可以分组写成如下形式:
```go
import(
"fmt"
"os"
)
const(
i = 100
pi = 3.1415
prefix = "Go_"
)
var(
i int
pi float32
prefix string
)
```
_(下划线)是个特殊的变量名,任何赋予它的值都会被丢弃。在这个例子中,我们将值35赋予b,并同时丢弃34:
```
_, b := 34, 35
```
## Go程序设计的一些规则
Go之所以会那么简洁,是因为它有一些默认的行为:
- 大写字母开头的变量是可导出的,也就是其它包可以读取的,是公有变量;小写字母开头的就是不可导出的,是私有变量。
- 大写字母开头的函数也是一样,相当于class中的带public关键词的公有函数;小写字母开头的就是有private关键词的私有函数。
### reference
- https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.2.md
- https://www.tutorialspoint.com/go/go_data_types.htm
<file_sep>/GinStudy/model/sys_user.go
/*
* @Time : 2021-01-07 19:36
* @Author : CoderCharm
* @File : sys_user.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package model
import (
"gin_study/global"
"github.com/satori/go.uuid"
)
type SysUser struct {
global.COMMON_MODEL
UUID uuid.UUID `json:"uuid" gorm:"comment:用户UUID"`
Username string `json:"userName" gorm:"comment:用户登录名"`
Password string `json:"-" gorm:"comment:用户登录密码"`
NickName string `json:"nickName" gorm:"default:系统用户;comment:用户昵称" `
HeaderImg string `json:"headerImg" gorm:"default:https://image.3001.net/images/20200504/1588558613_5eaf7b159c8e9.jpeg;comment:用户头像"`
Authority SysAuthority `json:"authority" gorm:"foreignKey:AuthorityId;references:AuthorityId;comment:用户角色"`
AuthorityId string `json:"authorityId" gorm:"default:888;comment:用户角色ID"`
}
<file_sep>/02_algorithm/leetcode_everday/441_sort_coin/coin_sort_test.go
/*
* @Time : 2021/3/18 22:21
* @Author : CoderCharm
* @File : coin_sort_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
441 硬币排序 简单
你总共有n枚硬币,你需要将它们摆成一个阶梯形状,第k行就必须正好有 k 枚硬币。
给定一个数字n,找出可形成完整阶梯行的总行数。
n是一个非负整数,并且在32位有符号整型的范围内。
示例 1:
n = 5
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤
因为第三行不完整,所以返回2.
示例 2:
n = 8
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
因为第四行不完整,所以返回3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/arranging-coins
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
package _41_sort_coin
import "testing"
// 解法 1
// 直接循环 减去每一行所需要的硬币 剩下的硬币 >= 当前行 则继续分, 否则直接返回行数
// 时间复杂度 O(N) 就一个for循环
// 空间复杂度 O(1) 也没涉及到数据的占用空间大的变量
// 执行用时: 8 ms, 在所有 Go 提交中击败了100.00%的用户
// 内存消耗: 2.2 MB, 在所有 Go 提交中击败了100.00%的用户
func arrangeCoins(n int) int {
// 默认第一行为1
i := 1
// 判断最后 一行的条件是否满足
for n >= i {
// n 依次减去每行的硬币
n -= i
// 最后 + 1 代表换行
i++
}
// 减去 最后 + 1 多的值
return i - 1
}
// 解法 2 二分查找
// 看的答案 明显这种 执行用时最短
// 执行用时: 0 ms, 在所有 Go 提交中击败了100.00%的用户
// 内存消耗: 2.2 MB, 在所有 Go 提交中击败了100.00%的用户
//
func sortCoins(n int) int {
l, r := 0, n
for l <= r {
mid := (l + r) >> 1
v := n - (mid+1)*mid/2
switch {
case v == 0:
return mid
case v > 0:
l = mid + 1
case v < 0:
r = mid - 1
}
}
return r
}
func TestSortCoin(t *testing.T) {
t.Log(arrangeCoins(10))
t.Log(sortCoins(10))
}
<file_sep>/03_case_demo/07_jwt/parse_token_test.go
/*
* @Time : 2021-01-05 20:58
* @Author : CoderCharm
* @File : parse_token_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac
**/
package _7_jwt
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"testing"
)
func TestParseToken(t *testing.T) {
// sample token string taken from the New example
tokenString := "<KEY>"
// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application. The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
return []byte(Key), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Println(claims)
} else {
fmt.Println(err)
}
}
<file_sep>/GinStudy/router/article.go
/*
* @Time : 2020-11-17 11:13
* @Author : CoderCharm
* @File : article.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 路由分组
**/
package router
import (
"gin_study/api/v1"
"gin_study/middleware"
"github.com/gin-gonic/gin"
)
func InitArticleRouter(Router *gin.RouterGroup) {
InitArticleGroup := Router.Group("/article").
Use(middleware.ZapLogger()).
Use(middleware.JWTAuth()) //.Use(middleware.CasbinHandler())
{
InitArticleGroup.GET("/get/recommend", v1.GetRecommendArticle) // 获取所有文章
InitArticleGroup.GET("/get/list", v1.GetArticleList) // 获取所有文章
InitArticleGroup.GET("/get/category", v1.GetCategoryList) // 获取所有文章
InitArticleGroup.GET("/get/detail", v1.GetArticleDetail) // 获取文章详情
}
}
<file_sep>/GinStudy/model/request/common.go
/*
* @Time : 2020-11-24 10:16
* @Author : CoderCharm
* @File : common.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
**/
package request
// Paging common input parameter structure
type PageInfo struct {
Page int `json:"page" form:"page"`
PageSize int `json:"pageSize" form:"pageSize"`
}
// 请求文章分类
type ArticleCategory struct {
CateId int `json:"cateId" form:"cateId"`
PageInfo
}
// 请求文章详情
type ArticleDetail struct {
Href string `json:"href" form:"href"`
}
// Find by id structure
type GetById struct {
Id float64 `json:"id" form:"id"`
}
type IdsReq struct {
Ids []int `json:"ids" form:"ids"`
}
// Get role by id structure
type GetAuthorityId struct {
AuthorityId string
}
type Empty struct{}
<file_sep>/01_getting-started/02_Package/extends/hello.go
package extends
const Hello = "hello 👋"
<file_sep>/01_getting-started/04_Control_statements_and_functions/03_for.go
/*
for 循环 没啥特殊的, 基础用法和js java里面差不多
Go里面最强大的一个控制逻辑就是for,它既可以用来循环读取数据,又可以当作while来控制逻辑,还能迭代操作。它的语法如下:
for expression1; expression2; expression3 {
//...
}
expression1、expression2和expression3都是表达式,
其中expression1和expression3是变量声明或者函数调用返回值之类的,
expression2是用来条件判断,expression1在循环开始之前调用,expression3在每轮循环结束之时调用。
一个例子比上面讲那么多更有用,那么我们看看下面的例子吧:
*/
package main
import "fmt"
func main() {
sum := 0
for i := 1; i < 10; i++ {
sum += i
}
fmt.Println("sum is equal to ", sum)
myBBB()
myCCC()
myEEE()
myFFF()
}
// 输出:sum is equal to 45
/*
有些时候需要进行多个赋值操作,由于Go里面没有,操作符,那么可以使用平行赋值i, j = i+1, j-1
有些时候如果我们忽略expression1和expression3:
*/
func myBBB() {
sum := 1
for sum < 10 {
sum += sum
}
fmt.Println("myBBB>>", sum)
}
/*
其中;也可以省略,那么就变成如下的代码了,是不是似曾相识?对,这就是while的功能。
*/
func myCCC() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println("myCCC>>", sum)
}
/*
在循环里面有两个关键操作break和continue ,break操作是跳出当前循环,continue是跳过本次循环。
当嵌套过深的时候,break可以配合标签使用,即跳转至标签所指定的位置,详细参考如下例子:
*/
func myDDD() {
for index := 10; index > 0; index-- {
if index == 5 {
break // 或者continue
}
fmt.Println(index)
}
// break打印出来10、9、8、7、6
// continue打印出来10、9、8、7、6、4、3、2、1
}
/*
break和continue还可以跟着标号,用来跳到多重循环中的外层循环
for配合range可以用于读取slice和map的数据:
*/
func myEEE() {
a := make(map[string]int)
a["a"] = 1
a["b"] = 2
a["c"] = 999
for k, v := range a {
fmt.Println("map's key:", k)
fmt.Println("map's val:", v)
}
}
/*
循环 slice 类似
*/
func myFFF() {
a := []int32{1, 2, 3}
for i, v := range a {
fmt.Println("slice's val:", i, v)
}
}
<file_sep>/05_micro_service/01_consul/main.go
/*
* @Time : 2021-02-08 09:33
* @Author : CoderCharm
* @File : main.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
使用consul的用处
1 服务发现 (不必关心服务端的IP和端口)
2 健康检查 (需要服务注册,能检测到服务端运行状况,不健康的会被主动剔除)
3 key/value 配置 (统一配置 相当于全局变量)
// 另一个注册配置中心
https://etcd.io/docs/v3.3.12/learning/why/#consul
两个重要的协议
gossip 八卦协议
raft 选举协议
docker pull consul
// 启动(不要改动端口)
docker run -d -p 8500:8500 consul
// 内部端口不能改,对外端口可以更改 如下, 访问地址就为 http://127.0.0.1:8600
// docker run -d -p 8600:8500 consul
// 注意事项 部署需要数据落盘
从 consul 中读取key/value配置
// 设置 key/value
http://127.0.0.1:8500/ui/dc1/kv/create
// 读取路径
micro/config/mysql
// 设置值
{
"host": "172.16.137.129",
"user": "root",
"pwd": "<PASSWORD>-",
"port": 3306,
"database": "micro"
}
**/
package main
import (
"fmt"
"github.com/micro/go-micro/v2/config"
"github.com/micro/go-plugins/config/source/consul/v2"
"strconv"
)
//设置配置中心
func GetConsulConfig(host string, port int64, prefix string) (config.Config, error) {
consulSource := consul.NewSource(
//设置配置中心的地址
consul.WithAddress(host+":"+strconv.FormatInt(port, 10)),
//设置前缀,不设置默认前缀 /micro/config
consul.WithPrefix(prefix),
//是否移除前缀,这里是设置为true,表示可以不带前缀直接获取对应配置
consul.StripPrefix(true),
)
//配置初始化
newConfig, err := config.NewConfig()
if err != nil {
return newConfig, err
}
//加载配置
err = newConfig.Load(consulSource)
return newConfig, err
}
// MySQL配置结构体
type MysqlConfig struct {
Host string `json:"host"`
User string `json:"user"`
Pwd string `json:"pwd"`
Database string `json:"database"`
Port int64 `json:"port"`
}
//获取 mysql 的配置
func GetMysqlFromConsul(config config.Config, path ...string) *MysqlConfig {
mysqlConfig := &MysqlConfig{}
_ = config.Get(path...).Scan(mysqlConfig)
return mysqlConfig
}
func main() {
//配置中心
consulConfig, err := GetConsulConfig("127.0.0.1", 8500, "/micro/config")
if err != nil {
fmt.Println(err)
}
//获取mysql配置,路径中不带前缀
mysqlInfo := GetMysqlFromConsul(consulConfig, "mysql")
fmt.Println(mysqlInfo)
}
<file_sep>/GinStudy/config/zap.go
/*
* @Time : 2020-11-19 10:40
* @Author : CoderCharm
* @File : zap.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc : 读取日志配置
**/
package config
type Zap struct {
Level string `mapstructure:"level" json:"level" yaml:"level"`
Format string `mapstructure:"format" json:"format" yaml:"format"`
Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"`
Director string `mapstructure:"director" json:"director" yaml:"director"`
LinkName string `mapstructure:"link-name" json:"linkName" yaml:"link-name"`
ShowLine bool `mapstructure:"show-line" json:"showLine" yaml:"showLine"`
EncodeLevel string `mapstructure:"encode-level" json:"encodeLevel" yaml:"encode-level"`
StacktraceKey string `mapstructure:"stacktrace-key" json:"stacktraceKey" yaml:"stacktrace-key"`
LogInConsole bool `mapstructure:"log-in-console" json:"logInConsole" yaml:"log-in-console"`
}
<file_sep>/03_case_demo/09_custom_web_framework/06_router_group_hook/gee/recovery.go
/*
* @Time : 2021-02-04 19:23
* @Author : CoderCharm
* @File : recovery.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
Go错误捕获机制参考
https://stackoverflow.com/questions/35212985/is-it-possible-get-information-about-caller-function-in-golang
**/
package gee
import (
"fmt"
"log"
"net/http"
"runtime"
"strings"
)
// print stack trace for debug
func trace(message string) string {
var pcs [32]uintptr
n := runtime.Callers(3, pcs[:]) // skip first 3 caller
var str strings.Builder
str.WriteString(message + "\nTraceback:")
for _, pc := range pcs[:n] {
fn := runtime.FuncForPC(pc)
file, line := fn.FileLine(pc)
str.WriteString(fmt.Sprintf("\n\t%s:%d", file, line))
}
return str.String()
}
func Recovery() HandlerFunc {
return func(c *Context) {
defer func() {
if err := recover(); err != nil {
message := fmt.Sprintf("%s", err)
log.Printf("%s\n\n", trace(message))
c.Fail(http.StatusInternalServerError, "Internal Server Error")
}
}()
c.Next()
}
}
<file_sep>/01_getting-started/09_reflect/README.md
# 反射
## 参考
- [Go语言程序设计 反射章节](https://docs.hacknode.org/gopl-zh/ch12/ch12-01.html)
- [Go夜读 反射应用及源码分析](https://www.bilibili.com/video/BV1My4y117gQ)
- [奇淼 断言 Assertion 和 反射 reflect](https://www.bilibili.com/video/BV1S5411x7Bz)
- [Go语言设计与实现](https://draveness.me/golang/docs/part2-foundation/ch04-basic/golang-reflect/#43-%E5%8F%8D%E5%B0%84)
<file_sep>/01_getting-started/04_Control_statements_and_functions/08_interface/01_demo.go
package main
//
//接口练习
//
//https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.6.md
//https://www.bilibili.com/video/BV1WA411b7ZF
//
//结构需要定义 和实现方法
//
//实现接口方法时,要绑定结构体
//package main
//
//import "fmt"
//
//// 定义一个动物接口 有两个方法
//type Animal interface {
// Eat(food string) // 无返回值 可以不定义类型
// Run() bool // 有返回值 得定义类型
//}
//
//// 定一个Cat结构体
//type Cat struct {
// name string
//}
//
//// 实现接口的方法
//func (c *Cat) Eat(food string) {
// fmt.Println(c.name + " 吃 " + food)
//}
//func (c Cat) Run() bool{
// fmt.Println(c.name + "跑223")
// return true
//}
//
//// 定义一个Dog结构体
//type Dog struct {
// name string
//}
//
//func (d Dog) Eat(food string) {
// fmt.Println(d.name + " 吃 " + food)
//}
//
//func (d Dog) Run() bool{
// fmt.Println(d.name + "跑666")
// return false
//}
//
//func main() {
// // 声明一个接口
// var A Animal
// // 实例结构体
// Tom := Cat{name: "Tom"}
//
// // 只要实现一个接口的方法为指针 就得传地址
// A = &Tom
// A.Eat("鱼")
// A.Run()
//
// // 声明接口B
// var B Animal
// // 直接 把实例化对象 赋值给接口B
// B = Dog{name: "Park"}
// // 接口B调用方法
// B.Eat("骨头")
// B.Run()
//
//}
<file_sep>/03_case_demo/07_jwt/README.md
# 简单练习JWT sign生成和验证
## 依赖
```shell
go get -u github.com/dgrijalva/jwt-go
```
## Token 生成和解析
> 这个所有语言都是一样,就是库生成参数的不一样,可以参考我之前Python写的JWT token生成
https://www.charmcode.cn/article/2020-07-23_fastapi_jwt
## 参考
- [https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac)
- [https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac)<file_sep>/01_getting-started/07_runtime/02_channel/chan5_test.go
/*
* @Time : 2020-12-30 21:00
* @Author : CoderCharm
* @File : chan5_test.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
channel 设置只读 和 只写
**/
package _2_channel
import (
"fmt"
"testing"
)
func Producer5(writeC chan<- int) {
for i := 0; i < 5; i++ {
fmt.Printf("生产+++%d\n", i)
writeC <- i
}
}
func Producer6(writeC chan<- int) {
for i := 5; i < 10; i++ {
fmt.Printf("生产+++%d\n", i)
writeC <- i
}
}
func Consumer5(redC <-chan int) {
for i := 0; i < 10; i++ {
fmt.Printf("-----------------消费 %d \n", <-redC)
}
}
func TestChannelCommunication(t *testing.T) {
c := make(chan int, 15)
// 只读
var redC <-chan int = c
// 只写
var writeC chan<- int = c
// 生产
go Producer5(writeC)
go Producer6(writeC)
// 消费
Consumer5(redC)
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/04_swtich.go
/*
Python写多了, 对switch很不习惯,感觉好多余, 哈哈哈哈
switch
有些时候你需要写很多的if-else来实现一些逻辑处理,这个时候代码看上去就很丑很冗长,
而且也不易于以后的维护,这个时候switch就能很好的解决这个问题。它的语法如下
switch sExpr {
case expr1:
some instructions
case expr2:
some other instructions
case expr3:
some other instructions
default:
other code
}
sExpr和expr1、expr2、expr3的类型必须一致。Go的switch非常灵活,
表达式不必是常量或整数,执行的过程从上至下,直到找到匹配项;
而如果switch没有表达式,它会匹配true。
*/
package main
import "fmt"
func main() {
myAAA()
}
func myAAA() {
i := 1
switch i {
case 1:
fmt.Println("1")
case 2:
fmt.Printf("2")
case 3:
fmt.Println(3)
default:
fmt.Println("以上都不是", i)
}
}
<file_sep>/01_getting-started/03_Variable/03_array/01_array_test.go
/*
array就是数组,它的定义方式如下:
var arr [n]type
在[n]type中,n表示数组的长度,type表示存储元素的类型。对数组的操作和其它语言类似,都是通过[]来进行读取或赋值:
*/
package _3_array
import (
"fmt"
"reflect"
"testing"
)
func Test01(t *testing.T) {
var arr [10]int // 声明了一个int类型的数组
arr[0] = 42 // 数组下标是从0开始的
arr[1] = 13 // 赋值操作
t.Log(fmt.Sprintf("The first element is %d \n", arr[0])) // 获取数据,返回42
t.Log(fmt.Sprintf("The second element is %d \n", arr[1])) // 获取数据,返回13
t.Log(fmt.Sprintf("The last element is %d \n", arr[9])) //返回未赋值的最后一个元素,默认返回0
t.Log(fmt.Sprintf("The all elements is %d \n", arr)) //输出全部数据
var myAll [2]string
//myAll = append(myAll, 1)
//myAll = append(myAll, 1)
t.Log(fmt.Sprintf("myAll type: %T \n", myAll))
t.Log(fmt.Sprintf("myAll type: %s \n", reflect.TypeOf(arr)))
t.Log("-----------------")
}
func Test02(t *testing.T) {
a := [3]int{1, 2, 3} // 声明了一个长度为3的int数组
b := [10]int{1, 2, 3} // 声明了一个长度为10的int数组,其中前三个元素初始化为1、2、3,其它默认为0
c := [...]int{4, 5, 6} // 可以省略长度而采用`...`的方式,Go会自动根据元素个数来计算长度
t.Log(a)
t.Log(b)
t.Log(c)
// 声明了一个二维数组,该数组以两个数组作为元素,其中每个数组中又有4个int类型的元素
doubleArray := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}}
// 上面的声明可以简化,直接忽略内部的类型
easyArray := [2][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
t.Log(doubleArray)
t.Log(easyArray)
}
func Test03(t *testing.T) {
// interface{} 就能放入各种类型的值
xy := [4]interface{}{1, "2", "3", true}
t.Log(xy)
}
func Test04(t *testing.T) {
// 数组的操作 只能修改数据,无法调整大小
tempXy := [5]string{"a", "b", "c"}
// https://stackoverflow.com/questions/41668053/cap-vs-len-of-slice-in-golang
t.Log(len(tempXy))
t.Log(cap(tempXy))
for _, v := range tempXy {
t.Log(v)
}
tempXy[4] = "e"
t.Log(tempXy)
}
<file_sep>/03_case_demo/09_custom_web_framework/01_simple_demo/hello_world.go
/*
* @Time : 2021-02-01 19:46
* @Author : CoderCharm
* @File : hello_world.go
* @Software: GoLand
* @Github : github/CoderCharm
* @Email : <EMAIL>
* @Desc :
一个最基础的返回JSON 数据的web服务器
https://stackoverflow.com/questions/31622052/how-to-serve-up-a-json-response-using-go
以下为Golang http 标准库核心服务
https://github.com/golang/go/blob/e491c6eea9ad599a0ae766a3217bd9a16ca3a25a/src/net/http/server.go#L2951
func (srv *Server) Serve(l net.Listener) error {
if fn := testHookServerServe; fn != nil {
fn(srv, l) // call hook with unwrapped listener
}
origListener := l
l = &onceCloseListener{Listener: l}
defer l.Close()
if err := srv.setupHTTP2_Serve(); err != nil {
return err
}
if !srv.trackListener(&l, true) {
return ErrServerClosed
}
defer srv.trackListener(&l, false)
baseCtx := context.Background()
if srv.BaseContext != nil {
baseCtx = srv.BaseContext(origListener)
if baseCtx == nil {
panic("BaseContext returned a nil context")
}
}
var tempDelay time.Duration // how long to sleep on accept failure
ctx := context.WithValue(baseCtx, ServerContextKey, srv)
// 最外层死循环
for {
// 监听listener的请求
rw, err := l.Accept()
if err != nil {
select {
case <-srv.getDoneChan():
return ErrServerClosed
default:
}
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay)
continue
}
return err
}
connCtx := ctx
if cc := srv.ConnContext; cc != nil {
connCtx = cc(connCtx, rw)
if connCtx == nil {
panic("ConnContext returned nil")
}
}
tempDelay = 0
c := srv.newConn(rw)
c.setState(c.rwc, StateNew) // before Serve can return
go c.serve(connCtx) // 每新进来一个连接,就开一个 goroutine 处理
}
}
每个 goroutine 最小只需要2K的内存
https://github.com/golang/go/blob/bbd25d26c0a86660fb3968137f16e74837b7a9c6/src/runtime/stack.go#L72
如果当前 HTTP 服务接收到了海量的请求,会在内部创建大量的 Goroutine,这可能会使整个服务质量明显降低无法处理请求
比 标准库net/http 快10倍的第三方http库
https://github.com/valyala/fasthttp
测试设备以及结果
https://github.com/valyala/fasthttp/issues/4
为什么fasthttp 比 net/http 快10倍
https://stackoverflow.com/questions/41627931/why-is-fasthttp-faster-than-net-http
基于 fasthttp的 web框架 https://github.com/gofiber/fiber
**/
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
// 获取url参数
fmt.Println(r.URL.Query().Get("aaa"))
// 设置编码 一定得要设置字符集编码 否则中文乱码
w.Header().Set("Content-Type", "text/html;charset=utf-8")
_, _ = w.Write([]byte("<h2 style='color:blue'>你好!首页</h2>"))
}
type DemoData struct {
Hello string `json:"Hello"`
}
type H map[string]interface{}
func helloWorld(w http.ResponseWriter, r *http.Request) {
// 返回json数据
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
//data := DemoData{"World"}
//_ = json.NewEncoder(w).Encode(data)
encoder := json.NewEncoder(w)
obj := H{"Hello": "World"}
if err := encoder.Encode(obj); err != nil {
http.Error(w, err.Error(), 500)
}
}
func main() {
// 设置两个路由
http.HandleFunc("/", indexHandler)
http.HandleFunc("/hello", helloWorld)
addr := "127.0.0.1:7050"
fmt.Println("启动地址为:", addr)
server := http.Server{
Addr: addr,
}
// 监听服务
_ = server.ListenAndServe()
}
<file_sep>/01_getting-started/04_Control_statements_and_functions/07_struct/01_struct_type/main.go
/*
Go语言中,也和C或者其他语言一样,我们可以声明新的类型,作为其它类型的属性或字段的容器。
例如,我们可以创建一个自定义类型person代表一个人的实体。这个实体拥有属性:姓名和年龄。这样的类型我们称之struct。如下代码所示:
*/
package main
import "fmt"
// 声明一个新的类型
type person struct {
name string
age int
sex bool
}
// 定义一个函数,比较年龄大小 返回年龄差
func older(p1, p2 person) (v1 person, v2 int) {
if p1.age > p2.age {
return p1, p1.age - p2.age
}
return p2, p2.age - p1.age
}
func main() {
var tom person // P现在就是person类型的变量了
tom.name = "Alice" // 赋值"Alice"给P的name属性.
tom.age = 25 // 赋值"25"给变量P的age属性
tom.sex = false
fmt.Printf("The person's name is %s \n", tom.name) // 访问P的name属性.
/*
除了上面这种P的声明使用之外,还有另外几种声明使用方式:
1.按照顺序提供初始化值
P := person{"Tom", 25}
2.通过field:value的方式初始化,这样可以任意顺序
P := person{age:24, name:"Tom"}
3.当然也可以通过new函数分配一个指针,此处P的类型为*person
P := new(person) 获取到结构体地址
*/
eric := person{
name: "Eric",
age: 15,
sex: true,
}
who, diff := older(eric, tom)
fmt.Println("person", who, "diff", diff)
P := new(person)
fmt.Println(*P)
}
| b491fede9e8bae4be434ee206cf4598c6ef56cce | [
"Markdown",
"Go Module",
"Go",
"JavaScript"
] | 181 | Go | CoderCharm/notes | d83cd11735b36301dcb2ed2ca4617e7ba66db307 | 7b2e1a920a40b507e6fede06c6ebe7ed1bd57b76 |
refs/heads/master | <file_sep>package serie09;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
private class Kruskal {
private Map<Integer, Node> vertices;
PriorityQueue<Edge> edges;
public Kruskal(Scanner in) {
int n = in.nextInt();
int m = in.nextInt();
initVertices(n);
initPriorityQueue(m, in);
}
/**
* We create for each vertex an entry in the map to keep track whether or not they are
* already completely merged
*/
private void initVertices(int n) {
vertices = new HashMap<Integer, Node>();
for (int i = 1; i <= n; i++) {
vertices.put(new Integer(i), makeSet(i));
}
}
/**
* We store all edges in a priority queue so that we always retrieve the one with the lowest costs
*/
private void initPriorityQueue(int m, Scanner in) {
edges = new PriorityQueue<Edge>();
for (int i = 0; i < m; i++) {
Edge edge = new Edge();
edge.u = vertices.get(in.nextInt());
edge.v = vertices.get(in.nextInt());
edge.cost = in.nextInt();
edges.add(edge);
}
}
private int minSpanningTreeCost() {
int res = Integer.MIN_VALUE;
// merge the single vertices until we have one entry in the map
while (vertices.size() > 1) {
Edge e = edges.poll();
Node u = find(e.u);
Node v = find(e.v);
if (u != v) {
union(e);
}
}
// make sure that we have only one entry and return the costs calculated
if (vertices.size() == 1) {
for (Entry<Integer, Node> entry : vertices.entrySet()) {
res = entry.getValue().cost;
break;
}
}
return res;
}
private Node makeSet(int i) {
Node n = new Node();
n.parent = n;
n.value = new Integer(i);
n.rank = 0;
n.cost = 0;
return n;
}
private Node find(Node n) {
if (!n.parent.equals(n)) {
n.parent = find(n.parent);
}
return n.parent;
}
private void union(Edge e) {
Node uRoot = find(e.u);
Node vRoot = find(e.v);
if (uRoot != vRoot) {
if (uRoot.rank < vRoot.rank) {
uRoot.parent = vRoot;
vRoot.cost += uRoot.cost + e.cost;
vertices.remove(uRoot.value);
} else if (uRoot.rank > vRoot.rank) {
vRoot.parent = uRoot;
uRoot.cost += vRoot.cost + e.cost;
vertices.remove(vRoot.value);
} else {
vRoot.parent = uRoot;
uRoot.cost += vRoot.cost + e.cost;
vRoot.rank++;
vertices.remove(vRoot.value);
}
}
}
}
private class Node {
private Node parent;
private Integer value;
private Integer rank;
private Integer cost;
}
private class Edge implements Comparable<Edge> {
private Node u = null;
private Node v = null;
private Integer cost = Integer.MIN_VALUE;
/**
* We need this so that the {@link PriorityQueue} can sort the single edges properly
*/
@Override
public int compareTo(Edge edge) {
int thisCost = this.cost;
int edgeCost = edge.cost;
return (thisCost < edgeCost ? -1 : (thisCost == edgeCost ? 0 : 1));
}
}
public static void main(String[] args) {
Main main = new Main();
// call the method which executes the program
List<String> res = main.doIt(System.in);
// print the result
for (String entry : res)
System.out.println(entry);
}
public List<String> doIt(InputStream is) {
List<String> res = new ArrayList<String>();
Scanner in = null;
try {
in = new Scanner(is);
// we get the nr of tests
int nrOfTests = in.nextInt();
for (int i = 0; i < nrOfTests; i++) {
// init the datastructures we need to calculate the min spanning tree
Kruskal kk = new Kruskal(in);
res.add(Integer.toString(kk.minSpanningTreeCost()));
}
} finally {
if (in != null)
in.close();
}
return res;
}
}
<file_sep>package serie08;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main main = new Main();
// call the method which executes the program
List<String> res = main.doIt(System.in);
// print the result
for (String entry : res)
System.out.println(entry);
}
public List<String> doIt(InputStream is) {
List<String> res = new ArrayList<String>();
Scanner in = null;
try {
in = new Scanner(is);
// we get the nr of tests
int nrOfTests = in.nextInt();
for (int i = 0; i < nrOfTests; i++) {
// the first line contains two values, n and W
String a = in.next();
String b = in.next();
res.add(longestCommonSubsequence(a, b));
}
} finally {
if (in != null)
in.close();
}
return res;
}
public String longestCommonSubsequence(String a, String b) {
String res = "";
int aLength = a.length();
int bLength = b.length();
int[][] array = new int[aLength + 1][bLength + 1];
for (int i = 1; i < array.length; i++) {
for (int j = 1; j < array[i].length; j++) {
if (a.charAt(i - 1) == b.charAt(j - 1)) {
array[i][j] = array[i - 1][j - 1] + 1;
} else {
array[i][j] = Math.max(array[i - 1][j], array[i][j - 1]);
}
}
}
int count = array[aLength][bLength];
res += count;
// decrease the values of the string pointers by one
aLength--;
bLength--;
// create the array with values
String subSeq = "";
for (int i = count - 1; i >= 0; i--) {
while (a.charAt(aLength) != b.charAt(bLength)) {
if (aLength > 0 && array[aLength + 1][bLength + 1] == array[aLength][bLength + 1]) {
aLength--;
} else {
bLength--;
}
}
subSeq = a.charAt(aLength) + subSeq;
aLength--;
bLength--;
}
return (res + " " + subSeq).trim();
}
}
<file_sep>package serie01;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main main = new Main();
// call the method which executes the program
List<Long> res = main.doIt(System.in);
// print the result
for (Long entry : res) {
System.out.println(entry);
}
}
public List<Long> doIt(InputStream is) {
List<Long> res = new ArrayList<Long>();
Scanner in = null;
try {
in = new Scanner(is);
// first we need to get rid of the first line
int nrOfLines = in.nextInt();
while (in.hasNextInt()) {
// read the values out of the stream
int i = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int d = in.nextInt();
// store the values in an array
res.add(calculateR(i, a, b, c, d));
}
if (nrOfLines != res.size())
throw new RuntimeException("Number of results do not match number of inputs!");
} finally {
if (in != null)
in.close();
}
return res;
}
public static long calculateR(int i, int a, int b, int c, int d) {
long[] res = { 0, 0, 0 };
for (int j = 0; j <= i; j++) {
// first move all the values of r into the next array field so we
// have them at the needed index
res[2] = res[1];
res[1] = res[0];
// do the right execution depending on what i is
switch (j) {
case 0:
res[0] = a;
break;
case 1:
res[0] = b;
break;
default:
res[0] = c * res[1] + d * res[2];
break;
}
}
// return the value that is on index 0, as we store at this position Ri
return res[0];
}
}
<file_sep>package serie03;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
class Heap {
private int[] heap;
// index of last element in the heap
private int lastElIndex = -1;
public Heap(int size) {
this.heap = new int[size];
}
public void insert(int i) {
heap[++lastElIndex] = i;
heapify(lastElIndex);
}
public int extractMin() {
int min = heap[0];
heap[0] = heap[lastElIndex--];
// make sure that we have the heap condition fulfilled
siftDown(0, lastElIndex);
return min;
}
public int queryLast() {
return heap[lastElIndex];
}
private void heapify(int count) {
int start = (count - 1) / 2;
while(start >= 0) {
siftDown(start, count);
start--;
}
}
private void siftDown(int start, int end) {
// as long as we have a left son we can go on
while(2*start + 1 <= end) {
// check which child we need for the swap check
int child = 2 * start + 1;
if(child + 1 <= end)
child = heap[child] > heap[child + 1] ? child + 1 : child;
// now swap the values and go to the 'subtree' of the bigger value
if(heap[start] > heap[child])
swap(start, child);
else
break;
start = child;
}
}
private void swap(int i, int j) {
int tmp = heap[i];
heap[i] = heap[j];
heap[j] = tmp;
}
}
public static void main(String[] args) {
Main main = new Main();
// call the method which executes the program
List<String> res = main.doIt(System.in);
// print the result
for (String entry : res)
System.out.println(entry);
}
public List<String> doIt(InputStream is) {
List<String> res = new ArrayList<String>();
Scanner in = null;
try {
in = new Scanner(is);
// first we need to get rid of the first line
in.nextInt();
// iterate over all test instances
while (in.hasNextInt()) {
// the first int tells us how many elements this line has, which we use for creating
// a new Heap object with a array of that size
int count = in.nextInt();
Heap heap = new Heap(count);
String queryLast = "";
String extractMin = "";
// fill the heap and get after every insert the last element in the heap
for (int i = 0; i < count; i++) {
heap.insert(in.nextInt());
queryLast += heap.queryLast() + " ";
}
res.add(queryLast.trim());
// finally get all elements out of the heap again
for (int i = 0; i < count; i++)
extractMin += heap.extractMin() + " ";
res.add(extractMin.trim());
}
} finally {
if (in != null)
in.close();
}
return res;
}
}
<file_sep>package serie06;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main main = new Main();
// call the method which executes the program
List<String> res = main.doIt(System.in);
// print the result
for (String entry : res)
System.out.println(entry);
}
public List<String> doIt(InputStream is) {
List<String> res = new ArrayList<String>();
Scanner in = null;
try {
in = new Scanner(is);
// we get the nr of tests
int nrOfTests = in.nextInt();
for (int i = 0; i < nrOfTests; i++) {
// get the number of the values and create an array of that size
int nrOfKeys = in.nextInt();
int[] array = new int[nrOfKeys];
for (int j = 0; j < nrOfKeys; j++) {
array[j] = in.nextInt();
}
res.add(blum(array, 0, array.length));
}
} finally {
if (in != null)
in.close();
}
return res;
}
private String blum(int[] array, int left, int right) {
if (left == right)
return "" + array[left];
String res = "";
// get the medians of the given array
int[] medians = getMedians(array, right, left);
for (int m : medians) {
res += m + " ";
}
// get the median of the medians
int pivot = getMedianOfArray(medians);
res += pivot + " ";
// now we sort the part of the array
int pivotIdx = sortSubArray(array, left, right - 1, pivot);
// get the median position in the array
int medianIdx = getMedianPosition(array);
// figure out whether we already have the pivot on the median position, otherwise we
// recursively iterate until we have it
if (pivotIdx == medianIdx) {
res += pivot;
} else if (medianIdx > pivotIdx) {
blum(array, pivotIdx + 1, right);
res += array[medianIdx];
} else if (medianIdx < pivotIdx) {
blum(array, left, pivotIdx);
res += array[medianIdx];
}
return res.trim();
}
private int[] getMedians(int[] array, int right, int left) {
// create an array in which we can store the medians
int medians[] = new int[(int) Math.ceil((right - left) / 5.0)];
// now extract the medians of each group of 5
int j = 0;
for (int i = left; i < right; i += 5) {
int r = i + 5;
if (r > right) {
r = right;
}
medians[j++] = getMedianOfArray(Arrays.copyOfRange(array, i, r));
}
return medians;
}
private int getMedianOfArray(int[] copyOfRange) {
Arrays.sort(copyOfRange);
return copyOfRange[getMedianPosition(copyOfRange)];
}
private int getMedianPosition(int[] copyOfRange) {
int medianPos = (int) Math.floor(copyOfRange.length / 2.0);
// for the even numbers we need to use the lower value
if (copyOfRange.length % 2 == 0 && copyOfRange.length != 0) {
medianPos--;
}
return medianPos;
}
private int sortSubArray(int[] array, int left, int right, int pivot) {
int pivotIdx = -1;
// get the index of the pivot element
for (int i = 0; i < array.length; i++) {
if (array[i] == pivot) {
pivotIdx = i;
break;
}
}
swap(array, pivotIdx, right);
int storeIdx = left;
for (int i = left; i < right; i++) {
if (array[i] <= pivot) {
swap(array, i, storeIdx);
storeIdx++;
}
}
swap(array, storeIdx, right);
return storeIdx;
}
private void swap(int[] array, int a, int b) {
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
}
| 96affedd4c3ce0a438646e15e02440ae03723514 | [
"Java"
] | 5 | Java | elft3r/datenstrukturen-und-algorithmen | cd94a198a6fd3bb05edc7feafaa16c57c8a5ec7d | 508172a8d74065e00a5077b9e8cd39a8ee2c0f24 |
refs/heads/master | <repo_name>pau1a/Mikrotik<file_sep>/README.md
# Mikrotik
Enhancements to Mikrotik Hotspot
<file_sep>/database.php
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
//connect to mysql - I prefer prepared statements as the variables are prepared for safety when sent to MySQL
$connect = mysqli_connect('hostname','db-user','password','database');
mysqli_query( $connect, "INSERT INTO visitors(postcode,email) VALUES('$postcode','$email')");
};
?>
| e080b4851ce7397d7dd665a9fab0926b386bd652 | [
"Markdown",
"PHP"
] | 2 | Markdown | pau1a/Mikrotik | 26f542257885d6aee07a5d271ac3d5c91b6e5855 | fdb9f4259ac9757001da86460f47c255e3ca9814 |
refs/heads/master | <file_sep># Ask user's name
puts "Hey this is the Name Printer, what is your name?"
# Store name
name = gets.chomp
# Print out name
puts "Success!"
puts "You entered #{name}"
<file_sep># Name Checker
This app is a simple Ruby terminal app to show some documentation basics. The app itself takes your name and prints it within the terminal.
### Features
- Submit your own name and have it printed in the terminal back to you
### Support Ruby Versions
All versions supported
### Usage
1. Start the Ruby terminal app
```sh
$ ruby app.rb
```
2. Give user input
Wait for prompt and enter your name.
3. Read results
Output should look similar to this:

### Contributing
If you are considering contributing that would be welcome. All app logic is in `app.rb`. Please submit a Pull Request when your contribution is ready.
| 80c6d3734e176d0dc173e2481fcbf4400c1afa2c | [
"Markdown",
"Ruby"
] | 2 | Ruby | jcerexhe/documentation-demo | bfcc4da9725a81ba8634658578ca4f28597bc125 | 877b777bc5f232771ed620a3bef262ead89a600d |
refs/heads/main | <file_sep>function AddItemBtn(props) {
return <button>{props.value}</button>;
}
export default AddItemBtn;
<file_sep>import AccountForm from "./AccountForm";
import "../informationBox/AccountWrapper.css";
function NewAccount(props) {
const saveHandleAccountData = (enteredAccountData) => {
const accountData = {
...enteredAccountData,
id: Math.random().toString(),
};
console.log(accountData);
props.onAddAccount(accountData);
};
return (
<div>
<AccountForm onSaveAccountData={saveHandleAccountData} />
</div>
);
}
export default NewAccount;
<file_sep>import React, { useState } from "react";
import AccountItem from "./AccountItem";
import Header from "../header/Header";
import NewAccount from "../NewAccount/NewAccount";
import "./AccountWrapper.css";
const INITIAL_ACCOUNTS = [
{
title: "..",
balance: { amount: 570, currency: "EURO" },
},
{
title: "My Business Account",
balance: { amount: 500, currency: "EURO" },
amount: 200,
currency: "$",
},
{
title: "Personal Safe",
balance: { amount: 100, currency: "£" },
amount: "0",
currency: "YEN",
},
{
title: "Discretionary funds",
balance: { amount: 300, currency: "YEN" },
note: "3",
},
];
function AccountWrapper() {
const [accounts, setAccount] = useState(INITIAL_ACCOUNTS);
const addAccountHandler = (account) => {
setAccount((prevAccounts) => {
console.log(account);
return [account, ...prevAccounts];
});
};
// ===============================================
return (
<div className="wrap">
<div className="account_wrapper">
<div className="clr_btn">
<div className="one btn"></div>
<div className="two btn"></div>
<div className="three btn"></div>
</div>
<Header />
{console.log(accounts)}
<AccountItem items={accounts} />
</div>
</div>
);
}
export default AccountWrapper;
| d0f1a509b93e713774859876d558d6a36f819d22 | [
"JavaScript"
] | 3 | JavaScript | Amal-Jama-93/Myapp | 0ff74f7535c8450fe63eeed994d4334289ea18b8 | b9dd7b71bfd953d1c7d3746b9d18136d5b45f62f |
refs/heads/master | <file_sep># u-management
1、首先你得安装nodejs+mongodb+express(4.X),这个我就帮不了你们了
2、进入项目路径cd u-management&&npm install,安装所需要的模块
3、进入mongodb的bin目录下启动数据库,cd bin , mongod --dbpath ../u-management/(设置u-management文件夹为我们工程的存储目录并启动数据库,所以你得先建一个u-management文件夹,如果不是在mongodb路径下,记得修改上面的文件夹路径)
4、数据库准备好了,启动项目 npm start,在浏览器输入localhost:3000查看(首页只有一个人员管理是可以点击的,其他的只是为美观,大家无视)
注意:我的项目并没有注册,而是直接用账号:admin 密码:<PASSWORD>直接登录,有想法的可以自己搞个注册上去,也不费事
5、目前项目中所有的数据交互都是通过模板渲染,每次都需要重新加载整个页面,我想大家都知道有ajax的存在,最近正在整体修改,实现数据的局部刷新
三、实现ajax弹框添加更新数据,传送:https://github.com/hddck/u-management-ajax
<file_sep>var mongoose=require('./db').mongoose;
var studentSchema = new mongoose.Schema({
name: {type : String,
required:true
},
sex: {type : String,
enum:['男','女']
},
age: {type : Number,
min:7,
max:45
},
tel: {type : Number
}
});
var studentModel = mongoose.model('students', studentSchema);
module.exports = studentModel;<file_sep>var express = require('express');
var crypto = require('crypto');
var studentModel = require('../models/student.js')
var mongoose = require('mongoose');
module.exports = function(app) {
//判断是否登录
app.get('/', function(req, res) {
if(! req.session.user) {
return res.redirect('login', {});
}else{
return res.render('index', {});
}
});
//登录
app.get('/login', function(req, res){
return res.render('login', {});
});
app.post('/login', function(req, res){
var md5 = crypto.createHash('md5');
var username = req.body.username;
var password = req.body.password;
if (username === 'admin' && password === '<PASSWORD>') {
//在session中存入用户信息
req.session.user = {
username: username
};
req.flash('success', '登录成功');
return res.redirect('/');
}
req.flash('error','请确定用户名或密码是否正确' );
return res.redirect('/login');
});
//退出
app.get('/logout', function(req, res) {
req.session.user = null;
req.flash('success', '您已经成功退出');
return res.redirect('/');
});
//信息界面
app.get('/edit',function (req, res){
studentModel.find({}, function (err,result) {
if(err){
req.flash('error', err);
}
return res.render('edit', {
data: result,
name: "人员管理"
});
});
});
//添加
app.get('/add', function(req, res) {
return res.render('add', {
name: "添加数据"
});
});
app.post('/add', function(req, res) {
var newStudent = {
name: req.body.name,
sex: req.body.sex,
age: req.body.age,
tel: req.body.tel
};
var model = new studentModel(newStudent);
model
.save()
.then(function (data) {
console.log(data);
})
.catch(function(err){
console.log(err);
});
res.redirect('/edit');
});
//删除
app.get('/del', function(req, res) {
var id = req.query.id;
studentModel.remove({_id:id}, function(err) {
if(err) {
console.log(err);
}
});
res.redirect('edit');
});
//更新
app.get('/update', function(req, res) {
var id = req.query.id;
studentModel.findById({_id:id}, function(err, result) {
if(err) {
console.log(err);
}
return res.render('update', {
data:result,
name: "更新数据"
});
});
});
app.post('/update', function(req, res){
var conditions = req.query.id;
var update = {$set: {name: req.body.name,
sex: req.body.sex,
age: req.body.age,
tel: req.body.tel
}};
var options = {multi: true};
studentModel.update({_id:conditions}, update, options,function(err) {
if(err) {
console.log(err, 'update error');
}
});
res.redirect('/edit');
});
//查找
app.get('/find', function(req, res) {
var query = {};
req.query.name && ( query.name = req.query.name );
req.query.sex && ( query.sex = req.query.sex );
req.query.age && ( query.age = req.query.age );
req.query.tel && ( query.tel = req.query.tel );
studentModel.find(query, function(err, result) {
if(err){
console.log(err, 'find error');
}
var name = req.query.name?req.query.name:null;
var sex = req.query.sex?req.query.sex:null;
var age = req.query.age?req.query.age:null;
var tel = req.query.tel?req.query.tel:null;
return res.render('find', {
data: result,
name: "查找数据",
names: name,
sex: sex,
age: age,
tel: tel
});
});
});
};
| c4c5a7a1f8ca3f75efcf770c5d15c970874510ac | [
"Markdown",
"JavaScript"
] | 3 | Markdown | hddck/u-management | 657855bbb54b1bbf8fac82f5555dfb02c6f40809 | dc90c5c87671eb946f58c0e76c89861d82535ac1 |
refs/heads/master | <file_sep>WebcamSwiper
============
An experiment/hack using getUserMedia to watch for swipes left and right with a hand. This could be applied to many different uses. Flipping through pictures in an image carousel, moving to the next item in a list, flipping pages of a book or magazine, etc.
[Demo](http://iambrandonn.github.com/WebcamSwiper)
[Blog Post](http://tripleequals.blogspot.com/2012/09/webcam-swiper.html)
Usage
-----
Two custom events are added to the body tag by the library. You need to bind callbacks to these events and initialize the library. If desired you can stop the library with the destroy method as well.
1. Include the webcam-swiper-0.1.js with a script tag or the loader of your choice.
2. Bind the swipe events however you choose. Example with jQuery:
`$("body").bind("webcamSwipeLeft", yourLeftEventHandler);
$("body").bind("webcamSwipeRight", yourRightEventHandler);`
3. Start the webcam access with a call to the global initializeWebcamSwiper function like this:
`window.initializeWebcamSwiper();`
4. Now it is running! If you choose to stop it call
`window.destroyWebcamSwiper();`<file_sep> // 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
var videos = {
'sex in the city': 'a6738DN4I3s',
'game of thrones': 'y0OqdTUf4sc',
'american psycho': 'qQx_AN02XuM',
'top gear': 'FssQhpAqv1I',
'top gear 2': 'DrUVMdkb4_k',
'football': 'NurlfAcY378',
'forrest gump': 'wvJ4wh1kwR8',
'the prestige': 'ijXruSzfGEc',
'star wars': 'tUW7EDJmWUA',
'fifty': 'SfZWFDs0LxA',
'gopro': 'wTcNtgA6gHs',
'national': 'cr-er44rr2M',
'bond': 'BsBd9tPK4uE',
'mission': 'TTrUyOvsHeM',
'wing': 'o6mPnvrBYrE',
}
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: window.innerHeight,
width: window.innerWidth,
videoId: videos['national'],
startSeconds: 8,
suggestedQuality: 'highres',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function updateVideo(people) {
if (people.length == 1 && people[0].gender == 'male') {
changeVideo('national')
// $("#adtext").empty().append($("<p></p>").text('Buy The National Geographic Movie'))
}
else if (people.length && people[0].gender == 'female') {
changeVideo('sex in the city')
} else if (people.length == 2) {
changeVideo('mission')
// $("#adtext").empty().append($("<p></p>").text('Buy The Mission Impossible Movie'))
} else if (people.length == 3) {
changeVideo('star wars')
} else if (people.length > 4) {
changeVideo('wing')
}
}
var justSwitched = false
function changeVideo(i) {
console.log("change", i)
var next = videos[i]
var current = player.getVideoData()['video_id'];
if (next != current) {
justSwitched = true
player.loadVideoById({
videoId: next,
startSeconds: 8,
suggestedQuality: 'highres',
iv_load_policy: 3
})
}
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
// setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
<file_sep>var express = require('express');
var app = express();
var _ = require('underscore');
var async = require("async");
var recs = require('./app/recommendations');
var filters = require('./app/filters');
var qt = require('quickthumb');
app.use(qt.static(__dirname + '/'));
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
app.get('/', function(req, res, next) {
var number_of_people = req.query.num;
var photo = req.query.ages.split(',').map(Number);
var gender = req.query.genders.split(',');
var tags = filters.getFilters(photo, number_of_people, gender);
console.log(tags)
recs.getMatches(tags)
.then(function(results) {
var match = results[getRandomInt(0, results.length)]
match.thumb = '/images/' + match.programme_uuid + '.jpeg';
res.json({
matches: match
});
})
.catch(function(error) {
console.error(error);
return next(new Error("Something went wrong"));
});
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
<file_sep>function changePhoto(fname) {
$("#frame img").attr("src", fname)
}
function updateVideo(people) {
if (people.length && people[0].gender == 'female'&&people[0].age<50) {
changePhoto('victoria.png')
}
else if (people.length && people[0].gender=='male') {
changePhoto('zara.png')
}
else if (people.length && people[0].age>50) {
changePhoto('ms.png')
}
}
<file_sep>'use strict';
var _ = require('underscore');
var knex = require('knex')({
client: 'sqlite3',
connection: {
filename: "./data/sky_programme_metadata.sqlite"
}
});
module.exports = {
getMatches: function(res) {
var query = knex
.distinct('name', 'tags', 'programme_uuid')
.select()
.from('sky_programme_metadata');
var subquery = knex
.select('name')
res.sub_genres.forEach(function(sub_genre) {
subquery.orWhere('sub-genres', 'like', '%' + sub_genre + '%')
});
if (res.no_sub_genres.length <= 0 ) {
res.no_sub_genres = ['test']
};
var subquery2 = knex
.select('name')
res.no_sub_genres.forEach(function(no_sub_genre) {
subquery2.orWhere('sub-genres', 'like', '%' + no_sub_genre + '%')
});
var subquery3 = knex
.select('name')
res.tags.forEach(function(tag) {
subquery3.orWhere('tags', 'like', '%' + tag + '%')
});
query
.andWhere('name', 'in', subquery3)
.andWhere('name', 'not in', subquery2)
.andWhere('name', 'in', subquery)
return query.then(function(rows) {
return rows;
});
},
getTags: function(key_word) {
return knex.select('tags')
.from('sky_programme_metadata')
.then(function(rows) {
return _.pluck(rows, 'tags');
});
}
};
<file_sep># SelfieTV
SelfieTV - An Artificially Intelligent TV That Changes The Program Based On Who Is Watching
<file_sep># API Key
db6186737e2c71d84fc9b05a889f1ff606a52fb3
<file_sep>
var video = document.querySelector('video');
var canvas = document.getElementById('photo');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
function choose(arr) {
return arr[Math.floor(Math.random() * myArray.length)]
}
function capture() {
ctx.drawImage(video, 0, 0);
var img = document.createElement('img');
var dataURL = canvas.toDataURL('img/png');
img.src = dataURL;
console.log(img.src);
upload(dataURItoBlob(dataURL))
// document.body.appendChild(img)
}
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type: mimeString});
}
function detect(imageDataBlob) {
return $.ajax({
url: "https://api.projectoxford.ai/face/v1.0/detect?returnFaceAttributes=age,gender,headPose,smile,facialHair",
beforeSend: function (xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", 'application/octet-stream');
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "<KEY>");
},
type: "POST",
// Request body
data: imageDataBlob,
processData: false
})
.done(function (data) {
console.log("success");
console.log(data)
})
.fail(function (e) {
console.log(e)
});
}
function emotion(imageDataBlob) {
return $.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function (xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", 'application/octet-stream');
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "e1276d5f08ae438ca10b0a7c19ef4e8c");
},
type: "POST",
// Request body
data: imageDataBlob,//.replace(/^data:image.+;base64,/, ""),
processData: false
})
.done(function (data) {
console.log("success");
console.log(data)
})
.fail(function (e) {
console.log(e)
});
}
//JSON data
function upload(imageDataBlob) {
var e = emotion(imageDataBlob)
var d = detect(imageDataBlob)
e.then(function (eData) {
d.then(function (dData) {
var i = 0
var people = []
$("#messages").html("<ol>" + dData.map(function (dd) {
var ee = eData[i++]
var max = 0
var maxEmotion = ""
Object.keys(ee.scores).forEach(function (k) {
var x = ee.scores[k]
if(x > max) {
maxEmotion = k
max = x
}
})
if (ee) {
var person = {
position: dd.faceRectangle,
age: dd.faceAttributes.age,
gender: dd.faceAttributes.gender,
emotion: maxEmotion,
beard: Math.round(dd.faceAttributes.facialHair.beard * 10) / 10,
moustache: Math.round(dd.faceAttributes.facialHair.moustache * 10) / 10,
smile: dd.faceAttributes.smile == null ? 0 : Math.round(dd.faceAttributes.smile * 10) / 10
}
people.push(person)
return "<li>" +
"<ul>" +
"<li>Age: " + person.age + "</li>" +
"<li>Gender: " + person.gender + "</li>" +
"<li>Beard: " + person.beard + "</li>" +
"<li>Moustache: " + person.moustache + "</li>" +
"<li>Smile: " + person.smile + "</li>" +
"<li>Emotion: " + maxEmotion + " </li>" +
"</ul>"
+ "</li>"
}
}) + "</ol>")
updateVideo(people)
$(".facebox").remove()
people.forEach(function(p) {
var factor = $("video").width() / $("canvas").width()
var pos = p.position;
var top = Math.round(pos.top * factor);
var left = Math.round(pos.left * factor);
var width = Math.round(pos.width * factor);
var height = Math.round(pos.height * factor);
var facebox = $("<div class='facebox' style='border: 3px solid "
+ (p.gender == 'male' ? 'blue' : 'pink') +
"; position: absolute'></div>")
.css({top: top + "px", left: left + "px", width: width + "px", height: height + "px"})
$("#webcam").append(facebox)
})
console.log(people)
// build params to movie ajax req
var ages = []
var genders = []
people.forEach(function (p) {
ages.push(p.age);
genders.push(p.gender == 'male' ? 'm' : 'f')
})
$.get( "http://54.88.61.20/?num=" + people.length + "&ages=" + ages.join(',') + "&genders=" + genders.join(','), function( data ) {
try{
if(data.matches){
$(".suggestions").empty();
$(".suggestions").append("<p>"+ data.matches.name +"<p>");
$(".suggestions").append("<img style='height: " + 90 + "px; width: " + 120 + "px;' src='http://192.168.127.12/" + data.matches.thumb + "'/>");
}
}
catch (e) {
}
});
setTimeout(function () {
$(".facebox").remove()
}, 1000)
})
})
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({video: true}, function (stream) {
if (window.URL) {
video.src = window.URL.createObjectURL(stream);
} else {
video.src = stream; // Opera.
}
video.onerror = function (e) {
stream.stop();
};
stream.onended = function () {
};
var alreadyDone = false
function launch() {
if(!alreadyDone) {
alreadyDone = true
console.log("Setting height", video.videoHeight)
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
setInterval(capture, 4000)
capture()
}
}
video.onloadedmetadata = launch;
// Since video.onloadedmetadata isn't firing for getUserMedia video, we have
// to fake it.
setTimeout(launch, 4000);
}, function () {
console.log("No video :(")
});
<file_sep>/**
* Created by Ben on 06/12/2015.
*/
var smileSeries = [new TimeSeries(), new TimeSeries(), new TimeSeries(), new TimeSeries(), new TimeSeries(), new TimeSeries()]
var colours = ['#00ff00', '#ff7c11', '#0000ff']
function chart(x, n) {
smileSeries[n].append(new Date().getTime(), x)
}
$(function createTimeline() {
var chart = new SmoothieChart({maxValue:1,minValue:0, millisPerPixel:80,grid:{fillStyle:'rgba(0,0,0,0.29)',strokeStyle:'transparent',borderVisible:false},timestampFormatter:SmoothieChart.timeFormatter}),
canvas = document.getElementById('chart')
smileSeries.forEach(function (s) {
chart.addTimeSeries(s, {lineWidth:2.5,strokeStyle:choose(colours)});
s.append(new Date().getTime(), 0)
})
chart.streamTo(canvas, 500);
}) | 36b2b896531288bfeecc90498008fd0157d85bf3 | [
"Markdown",
"JavaScript"
] | 9 | Markdown | kadvani1/SelfieTV | 9889ac530a9118226a3ce0fd1eac242c316583f3 | 9cc021894d59d2bca3e4528549128e22c62ddf43 |
refs/heads/master | <repo_name>dhavalMindinventory/JetDevsAndroidTest<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/sharedprefs/SharedPrefs.kt
package com.mi.imaginatoprac.data.sharedprefs
import android.content.SharedPreferences
class SharedPrefs(
private val sharedPreferences: SharedPreferences,
private val securityGuards: SecurityGuards
) : BaseSharedPreferences(securityGuards) {
val accessTokenWithPrefix: String?
get() = accessToken.takeIf { it.isNotEmpty() }?.let {
StringBuilder().append(PREFIX_ACCESS_TOKEN).append(" ").append(it).toString()
}
var accessToken: String
set(value) = sharedPreferences.put(PREF_SESSION_ACCESS_TOKEN, value)
get() = sharedPreferences.get(PREF_SESSION_ACCESS_TOKEN, String::class.java)
var userId: String
set(value) = sharedPreferences.put(USER_ID, value)
get() = sharedPreferences.get(USER_ID, String::class.java)
var email: String
set(value) = sharedPreferences.put(EMAIL, value)
get() = sharedPreferences.get(EMAIL, String::class.java)
var uuid: String
set(value) = sharedPreferences.put(UUID, value)
get() = sharedPreferences.get(UUID, String::class.java)
var name: String
set(value) = sharedPreferences.put(NAME, value)
get() = sharedPreferences.get(NAME, String::class.java)
fun isLoggedIn(): Boolean {
return userId.isNotEmpty()
}
override fun clear() {
sharedPreferences.edit().clear().apply()
}
fun onErrorCallback(callback: SecurityGuards.ErrorCallback) {
securityGuards.onErrorCallback(callback)
}
companion object {
internal const val PREFS_NAME = "AppPreferences"
private const val PREFIX = "AppPreferences_"
private const val PREF_SESSION_ACCESS_TOKEN = PREFIX + "access_token"
private const val PREF_REFRESH_TOKEN = "refreshToken"
private const val SESSION_INVALID = "sessionInvalid"
private const val IS_DEVICE_TOKEN_SENT = "isDeviceTokenSent"
private const val PREFIX_ACCESS_TOKEN = "Bearer"
private const val USER_ID = "id"
private const val EMAIL = "email"
private const val NAME = "name"
private const val PHONE_MOBILE = "phoneMobile"
private const val UUID = "uuid"
private const val PREFIX_ERROR = "SharedPref Error : %s"
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/base/BaseActivity.kt
package com.mi.imaginatoprac.ui.base
import android.os.Bundle
import androidx.annotation.CallSuper
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import com.basestructure.app.R
abstract class BaseActivity(@LayoutRes layoutRes: Int) : AppCompatActivity(layoutRes) {
private val navHostFragment by lazy {
supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment
}
private val navController by lazy {
navHostFragment.navController
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initViews()
}
@CallSuper
protected open fun initViews() {
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/account/respository/UserApi.kt
package com.mi.imaginatoprac.data.account.respository
import com.mi.imaginatoprac.data.account.entity.LoginResponse
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.FieldMap
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
interface UserApi {
@POST("login")
suspend fun login(@Body param: HashMap<String, String>): Response<LoginResponse>
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/domain/account/repository/UserRepository.kt
package com.mi.imaginatoprac.domain.account.repository
import com.mi.imaginatoprac.data.account.entity.LoginResponse
import com.mi.imaginatoprac.domain.account.entity.User
interface UserRepository {
suspend fun signInRequest(param: HashMap<String, String>): LoginResponse?
suspend fun getUserData(): User
suspend fun isUserLoggedIn(): Boolean
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/splash/SplashActivity.kt
package com.mi.imaginatoprac.ui.splash
import android.content.Intent
import com.basestructure.app.R
import com.mi.imaginatoprac.common.extension.initViewModel
import com.mi.imaginatoprac.common.extension.safeObserve
import com.mi.imaginatoprac.ui.base.BaseViewModelActivity
import com.mi.imaginatoprac.ui.main.MainActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class SplashActivity : BaseViewModelActivity<SplashViewModel>(R.layout.activity_splash) {
override fun buildViewModel() = initViewModel<SplashViewModel>()
override fun initLiveDataObservers() {
super.initLiveDataObservers()
with(viewModel) {
sessionStateEvent.safeObserve(this@SplashActivity, ::handleSessionState)
}
}
private fun handleSessionState(isLoggedId: Boolean) {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/sharedprefs/utils/KeystoreWrapper.kt
package com.mi.imaginatoprac.data.sharedprefs.utils
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.security.KeyPairGeneratorSpec
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import com.basestructure.app.BuildConfig
import java.math.BigInteger
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey
import java.security.SecureRandom
import java.util.Calendar
import java.util.HashMap
import javax.security.auth.x500.X500Principal
class KeystoreWrapper(private val context: Context) {
companion object {
private const val SIZE_KEY = 2048
private const val AMOUNT_DURATION = 30
private const val KEYSTORE_TYPE = "AndroidKeyStore"
private const val RSA_ALGORITHM = "RSA"
private const val AES_BYTE_KEY_SIZE = 16
const val AES_MASTER_KEY = "AES_MASTER"
const val AES_VECTOR_KEY = "AES_VECTOR"
}
private val versionSecurityGuards: Int = BuildConfig.SECURITY_GUARD_VERSION
private val keystoreAliasName = "AndroidAlias$versionSecurityGuards"
private val keyStore: KeyStore = createAndroidKeyStore()
fun isAndroidKeyStoreAsymmetricKeyExist(): Boolean {
return keyStore.containsAlias(keystoreAliasName)
}
fun removeAndroidKeyStoreKey() = keyStore.deleteEntry(keystoreAliasName)
/**
* @return asymmetric keypair from Android Key Store or null if any key with given alias exists
*/
fun androidKeyStoreAsymmetricKeyPair(): KeyPair? {
val privateKey = keyStore.getKey(keystoreAliasName, null) as PrivateKey?
val publicKey = keyStore.getCertificate(keystoreAliasName)?.publicKey
return if (privateKey != null && publicKey != null) {
KeyPair(publicKey, privateKey)
} else {
null
}
}
fun createDefaultSymmetricKey(): HashMap<String, ByteArray> {
val key = ByteArray(AES_BYTE_KEY_SIZE)
val ivSpec = ByteArray(AES_BYTE_KEY_SIZE)
SecureRandom().apply {
nextBytes(key)
nextBytes(ivSpec)
}
return hashMapOf(
AES_MASTER_KEY to key,
AES_VECTOR_KEY to ivSpec
)
}
/**
* Creates asymmetric RSA key with default [KeyProperties.BLOCK_MODE_ECB] and
* [KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1] and saves it to Android Key Store.
*/
@TargetApi(Build.VERSION_CODES.M)
fun createAndroidKeyStoreAsymmetricKey(): KeyPair? {
val generator = KeyPairGenerator.getInstance(RSA_ALGORITHM, KEYSTORE_TYPE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
initGeneratorWithKeyGenParameterSpec(generator)
} else {
initGeneratorWithKeyPairGeneratorSpec(generator)
}
return try {
generator.generateKeyPair()
} catch (e: IllegalStateException) {
null
}
}
@TargetApi(Build.VERSION_CODES.M)
private fun initGeneratorWithKeyGenParameterSpec(generator: KeyPairGenerator) {
val keyGenParameterSpec = KeyGenParameterSpec.Builder(
keystoreAliasName,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).run {
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
setDigests(KeyProperties.DIGEST_SHA256)
setKeySize(SIZE_KEY)
build()
}
generator.initialize(keyGenParameterSpec)
}
private fun initGeneratorWithKeyPairGeneratorSpec(generator: KeyPairGenerator) {
val start = Calendar.getInstance()
val end = Calendar.getInstance()
end.add(Calendar.YEAR, AMOUNT_DURATION)
val keyGenParameterSpec = KeyPairGeneratorSpec.Builder(context).run {
setAlias(keystoreAliasName)
setSubject(X500Principal("CN=$keystoreAliasName"))
setSerialNumber(BigInteger.TEN)
setStartDate(start.time)
setEndDate(end.time)
build()
}
generator.initialize(keyGenParameterSpec)
}
private fun createAndroidKeyStore(): KeyStore {
val keyStore = KeyStore.getInstance(KEYSTORE_TYPE)
keyStore.load(null)
return keyStore
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/home/HomeFragment.kt
package com.mi.imaginatoprac.ui.home
import com.basestructure.app.R
import com.basestructure.app.databinding.FragmentHomeBinding
import com.mi.imaginatoprac.common.extension.initViewModel
import com.mi.imaginatoprac.ui.base.BaseViewModelFragment
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class HomeFragment :
BaseViewModelFragment<HomeViewModel, FragmentHomeBinding>(R.layout.fragment_home) {
override fun buildViewModel() = initViewModel<HomeViewModel>()
override fun getClassName(): String {
return this::class.java.simpleName
}
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/common/extension/EditTextExts.kt
package com.mi.imaginatoprac.common.extension
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.EditText
import com.google.android.material.textfield.TextInputLayout
fun EditText.setCustomInputFilters(length: Int) {
this.filters = arrayOf(InputFilter { source, start, end, _, _, _ ->
for (i in start until end) {
if (!Character.isLetterOrDigit(source[i])) {
return@InputFilter ""
}
}
null
}, InputFilter.LengthFilter(length))
}
fun TextInputLayout.removeErrorState() {
isErrorEnabled = false
error = null
}
fun EditText.setTextWatcher(relativeTextInputLayout: TextInputLayout) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
if (p0.toString().checkNotEmpty()) {
relativeTextInputLayout.error = null
}
}
})
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/sharedprefs/SecurityGuards.kt
package com.mi.imaginatoprac.data.sharedprefs
interface SecurityGuards {
fun getStringDecrypted(encryptedString: String?): String
fun reset()
fun getUUID(): String
fun encryptedValue(value: String): String
fun setSecureKey(key: String, value: String): Boolean
fun getSecureKey(key: String): String
fun onErrorCallback(callback: ErrorCallback)
interface ErrorCallback {
fun onEncryptionError(msg: String)
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/account/entity/LoginResponse.kt
package com.mi.imaginatoprac.data.account.entity
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import androidx.annotation.Keep
import kotlinx.serialization.Transient
@Keep
@Serializable
data class LoginResponse(
@SerialName("data") var `data`: Data? = null,
@SerialName("error_message") var errorMessage: String? = null,
@SerialName("result") var result: Int?
) {
@Keep
@Serializable
data class Data(
@SerialName("user") var user: User? = null
) {
@Keep
@Serializable
data class User(
@SerialName("created_at") var createdAt: String? = "",
@SerialName("userId") var userId: Int? = 0,
@SerialName("userName") var userName: String? = ""
)
}
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/sharedprefs/securityguards/SecurityGuardsImpl.kt
package com.mi.imaginatoprac.data.sharedprefs.securityguards
import android.content.Context
import android.content.SharedPreferences
import com.basestructure.app.BuildConfig
import com.mi.imaginatoprac.data.sharedprefs.SecurityGuards
import com.mi.imaginatoprac.data.sharedprefs.cipher.KeystoreCipher
import com.mi.imaginatoprac.data.sharedprefs.cipher.KeystoreCipherImpl
import com.mi.imaginatoprac.data.sharedprefs.utils.KeystoreWrapper
import timber.log.Timber
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.UnrecoverableKeyException
import java.util.UUID
import javax.crypto.AEADBadTagException
import javax.crypto.BadPaddingException
import javax.crypto.IllegalBlockSizeException
import javax.crypto.NoSuchPaddingException
import javax.inject.Inject
class SecurityGuardsImpl @Inject constructor(
private val cipherSharedPrefs: SharedPreferences,
private val cipher: KeystoreCipher
) : SecurityGuards {
companion object {
private const val SECURED_PREFS_NAME = "SecurityGuardConfig"
private const val SECURED_PREFIX = "cipher_"
private const val PREF_AES_KEY = SECURED_PREFIX + "securedKey01"
private const val PREF_IV_SPEC = SECURED_PREFIX + "securedKey02"
private const val PREF_UID = SECURED_PREFIX + "Uid"
}
class Factory {
fun create(context: Context): SecurityGuards {
val versionSecurityGuards = BuildConfig.SECURITY_GUARD_VERSION
val keystoreWrapper = KeystoreWrapper(context)
val cipher = KeystoreCipherImpl(keystoreWrapper)
val sharedPrefs = context.getSharedPreferences(
StringBuilder().append(
SECURED_PREFS_NAME
).append(
versionSecurityGuards
).toString(),
Context.MODE_PRIVATE
)
return SecurityGuardsImpl(sharedPrefs, cipher)
}
}
init {
try {
cipher.getMasterKeyAsymmetric()
} catch (exception: UnrecoverableKeyException) {
reset()
}
try {
if (aesKey.isEmpty() || ivSpec.isEmpty()) {
createNewAesKey()
} else {
cipher.setAesKey(aesKey, ivSpec)
}
if (getUUID().isEmpty()) {
val uuid = UUID.randomUUID().toString()
setSecureKey(PREF_UID, uuid)
}
} catch (ex: IllegalStateException) {
/*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* */
Timber.e("initial error : $ex")
reset()
} catch (ex: IllegalArgumentException) {
/*
* @exception IllegalArgumentException if <code>algorithm</code>
* is null or <code>key</code> is null or empty.
*/
Timber.e("initial error : $ex")
reset()
} catch (ex: NoSuchAlgorithmException) {
/*
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is null, empty, in an invalid format,
* or if no Provider supports a CipherSpi implementation for the
* specified algorithm.
*/
Timber.e("initial error : $ex")
reset()
} catch (ex: NoSuchPaddingException) {
/*
* @exception NoSuchPaddingException if <code>transformation</code>
* contains a padding scheme that is not available.
*/
Timber.e("initial error : $ex")
reset()
} catch (ex: InvalidKeyException) {
/*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or its keysize exceeds the maximum allowable
* keysize (as determined from the configured jurisdiction policy files).
*/
Timber.e("initial error : $ex")
reset()
} catch (ex: InvalidAlgorithmParameterException) {
/*
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or this cipher requires
* algorithm parameters and <code>params</code> is null, or the given
* algorithm parameters imply a cryptographic strength that would exceed
* the legal limits (as determined from the configured jurisdiction
* policy files).
*/
Timber.e("initial error : $ex")
reset()
} catch (ex: UnsupportedOperationException) {
/*
* @throws UnsupportedOperationException if (@code opmode} is
* {@code WRAP_MODE} or {@code UNWRAP_MODE} but the mode is not implemented
* by the underlying {@code CipherSpi}.
*/
Timber.e("initial error : $ex")
reset()
} catch (ex: IllegalBlockSizeException) {
/*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
*/
Timber.e("initial error : $ex")
reset()
} catch (ex: BadPaddingException) {
/*
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
Timber.e("initial error : ${ex.localizedMessage}")
reset()
} catch (ex: AEADBadTagException) {
/*
* @exception AEADBadTagException if this cipher is decrypting in an
* AEAD mode (such as GCM/CCM), and the received authentication tag
* does not match the calculated value
*/
Timber.e("initial error : ${ex.localizedMessage}")
reset()
}
}
private var errorCallback: SecurityGuards.ErrorCallback? = null
private var aesKey: String
set(value) = cipherSharedPrefs.put(PREF_AES_KEY, value)
get() = cipherSharedPrefs.get(PREF_AES_KEY, String::class.java)
private var ivSpec: String
set(value) = cipherSharedPrefs.put(PREF_IV_SPEC, value)
get() = cipherSharedPrefs.get(PREF_IV_SPEC, String::class.java)
private fun createNewAesKey() {
val keyPair = cipher.getNewAesKey()
aesKey = keyPair.first
ivSpec = keyPair.second
}
override fun onErrorCallback(callback: SecurityGuards.ErrorCallback) {
this.errorCallback = callback
}
override fun getStringDecrypted(encryptedString: String?): String {
return try {
encryptedString?.let { cipher.decrypt(it) } ?: ""
} catch (ex: IllegalStateException) {
/*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* */
errorHandler(ex.localizedMessage)
ex.printStackTrace()
reset()
""
} catch (ex: IllegalArgumentException) {
/*
* @exception IllegalArgumentException if <code>algorithm</code>
* is null or <code>key</code> is null or empty.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: NoSuchAlgorithmException) {
/*
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is null, empty, in an invalid format,
* or if no Provider supports a CipherSpi implementation for the
* specified algorithm.
*
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: NoSuchPaddingException) {
/*
* @exception NoSuchPaddingException if <code>transformation</code>
* contains a padding scheme that is not available.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: InvalidKeyException) {
/*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or its keysize exceeds the maximum allowable
* keysize (as determined from the configured jurisdiction policy files).
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: InvalidAlgorithmParameterException) {
/*
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or this cipher requires
* algorithm parameters and <code>params</code> is null, or the given
* algorithm parameters imply a cryptographic strength that would exceed
* the legal limits (as determined from the configured jurisdiction
* policy files).
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: UnsupportedOperationException) {
/*
* @throws UnsupportedOperationException if (@code opmode} is
* {@code WRAP_MODE} or {@code UNWRAP_MODE} but the mode is not implemented
* by the underlying {@code CipherSpi}.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: IllegalBlockSizeException) {
/*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: BadPaddingException) {
/*
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: AEADBadTagException) {
/*
* @exception AEADBadTagException if this cipher is decrypting in an
* AEAD mode (such as GCM/CCM), and the received authentication tag
* does not match the calculated value
*/
errorHandler(ex.localizedMessage)
""
}
}
override fun encryptedValue(value: String): String {
return try {
return cipher.encrypt(value)
} catch (ex: IllegalStateException) {
/*
* @exception IllegalStateException if this cipher is in a wrong state
* (e.g., has not been initialized)
* */
errorHandler(ex.localizedMessage)
ex.printStackTrace()
reset()
""
} catch (ex: IllegalArgumentException) {
/*
* @exception IllegalArgumentException if <code>algorithm</code>
* is null or <code>key</code> is null or empty.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: NoSuchAlgorithmException) {
/*
* @exception NoSuchAlgorithmException if <code>transformation</code>
* is null, empty, in an invalid format,
* or if no Provider supports a CipherSpi implementation for the
* specified algorithm.
*
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: NoSuchPaddingException) {
/*
* @exception NoSuchPaddingException if <code>transformation</code>
* contains a padding scheme that is not available.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: InvalidKeyException) {
/*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this cipher, or its keysize exceeds the maximum allowable
* keysize (as determined from the configured jurisdiction policy files).
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: InvalidAlgorithmParameterException) {
/*
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this cipher,
* or this cipher requires
* algorithm parameters and <code>params</code> is null, or the given
* algorithm parameters imply a cryptographic strength that would exceed
* the legal limits (as determined from the configured jurisdiction
* policy files).
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: UnsupportedOperationException) {
/*
* @throws UnsupportedOperationException if (@code opmode} is
* {@code WRAP_MODE} or {@code UNWRAP_MODE} but the mode is not implemented
* by the underlying {@code CipherSpi}.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: IllegalBlockSizeException) {
/*
* @exception IllegalBlockSizeException if this cipher is a block cipher,
* no padding has been requested (only in encryption mode), and the total
* input length of the data processed by this cipher is not a multiple of
* block size; or if this encryption algorithm is unable to
* process the input data provided.
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: BadPaddingException) {
/*
* @exception BadPaddingException if this cipher is in decryption mode,
* and (un)padding has been requested, but the decrypted data is not
* bounded by the appropriate padding bytes
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: AEADBadTagException) {
/*
* @exception AEADBadTagException if this cipher is decrypting in an
* AEAD mode (such as GCM/CCM), and the received authentication tag
* does not match the calculated value
*/
errorHandler(ex.localizedMessage)
""
} catch (ex: Exception) {
""
}
}
override fun reset() {
Timber.e("securityGuards >> reset")
cipherSharedPrefs.edit().clear().apply()
cipher.deleteMasterKey()
cipher.getNewMasterKeyAsymmetric()
createNewAesKey()
}
override fun getUUID(): String {
return getSecureKey(PREF_UID)
}
override fun setSecureKey(key: String, value: String): Boolean {
cipherSharedPrefs.put(key, cipher.encrypt(value))
return cipherSharedPrefs.get(key, String::class.java).isNotEmpty()
}
override fun getSecureKey(key: String): String {
val encryptedString = cipherSharedPrefs.get(key, String::class.java)
return cipher.decrypt(encryptedString)
}
private fun errorHandler(errorMsg: String) {
reset()
errorCallback?.onEncryptionError(errorMsg)
}
@Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY")
private fun <T> SharedPreferences.get(key: String, clazz: Class<T>): T =
when (clazz) {
String::class.java -> getString(key, "")
Boolean::class.java -> getBoolean(key, false)
Float::class.java -> getFloat(key, -1f)
Double::class.java -> getFloat(key, -1f)
Int::class.java -> getInt(key, -1)
Long::class.java -> getLong(key, -1L)
else -> null
} as T
private fun <T> SharedPreferences.put(key: String, data: T) {
val editor = edit()
when (data) {
is String -> editor.putString(key, data)
is Boolean -> editor.putBoolean(key, data)
is Float -> editor.putFloat(key, data)
is Double -> editor.putFloat(key, data.toFloat())
is Int -> editor.putInt(key, data)
is Long -> editor.putLong(key, data)
}
editor.apply()
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/sharedprefs/cipher/KeystoreCipher.kt
package com.mi.imaginatoprac.data.sharedprefs.cipher
interface KeystoreCipher {
fun setAesKey(key: String, vectorSpec: String)
fun getNewAesKey(): Pair<String, String>
fun decrypt(encrypted: String): String
fun encrypt(value: String): String
fun getMasterKeyAsymmetric()
fun getNewMasterKeyAsymmetric()
fun deleteMasterKey()
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/di/module/ApiDBModule.kt
package com.mi.imaginatoprac.di.module
import android.content.Context
import androidx.room.Room
import androidx.room.RoomDatabase
import com.basestructure.app.BuildConfig
import com.mi.imaginatoprac.data.AppDatabase
import com.mi.imaginatoprac.data.account.respository.UserApi
import com.mi.imaginatoprac.data.account.respository.UserDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class ApiDBModule {
@Singleton
@Provides
fun provideRoomDatabase(@ApplicationContext context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabase::class.java, BuildConfig.DATABASE_NAME)
.setJournalMode(RoomDatabase.JournalMode.TRUNCATE)
.build()
}
@Singleton
@Provides
fun provideAccountApi(retrofit: Retrofit): UserApi {
return retrofit.create(UserApi::class.java)
}
@Singleton
@Provides
fun provideDao(database: AppDatabase): UserDao {
return database.accountDao()
}
}
<file_sep>/flavors.gradle
ext.flavorConfig = {
flavorDimensions "environment"
productFlavors {
mock {
dimension "environment"
applicationIdSuffix ".mock"
resValue "string", "app_name", "ImaginatoPrac(MOCK)"
buildConfigField 'String', 'API_BASE_URL', '"http://imaginato.mocklab.io/"'
}
development {
dimension "environment"
applicationIdSuffix ".dev"
resValue "string", "app_name", "ImaginatoPrac(DEV)"
buildConfigField 'String', 'API_BASE_URL', '"http://imaginato.mocklab.io/"'
}
staging {
dimension "environment"
applicationIdSuffix ".stage"
resValue "string", "app_name", "ImaginatoPrac(STAGE)"
buildConfigField 'String', 'API_BASE_URL', '"http://imaginato.mocklab.io/"'
}
production {
dimension "environment"
resValue "string", "app_name", "ImaginatoPrac"
buildConfigField 'String', 'API_BASE_URL', '"http://imaginato.mocklab.io/"'
}
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/main/MainActivity.kt
package com.mi.imaginatoprac.ui.main
import com.basestructure.app.R
import com.mi.imaginatoprac.ui.base.BaseActivity
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : BaseActivity(R.layout.activity_main)
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/base/BaseDao.kt
package com.mi.imaginatoprac.data.base
import androidx.room.Insert
import androidx.room.OnConflictStrategy
interface BaseDao<T> {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertReplace(region: T)
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/account/respository/UserDao.kt
package com.mi.imaginatoprac.data.account.respository
import androidx.room.Dao
import androidx.room.Query
import com.mi.imaginatoprac.data.base.BaseDao
import com.mi.imaginatoprac.domain.account.entity.COLUMN_USER_ID
import com.mi.imaginatoprac.domain.account.entity.TABLE_NAME
import com.mi.imaginatoprac.domain.account.entity.User
@Dao
interface UserDao : BaseDao<User> {
@Query("SELECT * FROM $TABLE_NAME WHERE $COLUMN_USER_ID = :id")
fun getUser(id: String): User
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/login/LoginViewModel.kt
package com.mi.imaginatoprac.ui.login
import androidx.databinding.Bindable
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.basestructure.app.BR
import com.mi.imaginatoprac.common.extension.checkNotEmpty
import com.mi.imaginatoprac.common.extension.setApiResponse
import com.mi.imaginatoprac.common.extension.setError
import com.mi.imaginatoprac.common.extension.setLoading
import com.mi.imaginatoprac.common.util.KeyUtils
import com.mi.imaginatoprac.common.util.ValidationUtils.isValidEmail
import com.mi.imaginatoprac.common.util.ValidationUtils.isValidPassword
import com.mi.imaginatoprac.data.account.entity.LoginResponse
import com.mi.imaginatoprac.domain.account.usecase.LoginUseCase
import com.mi.imaginatoprac.domain.base.UiState
import com.mi.imaginatoprac.ui.base.BaseViewModel
import com.mi.imaginatoprac.ui.base.SingleLiveEvent
import com.mi.imaginatoprac.ui.login.validation.LoginConstant
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
private var loginUseCase: LoginUseCase
) : BaseViewModel() {
@Bindable
var email = ""
set(value) {
field = value
checkValidation()
notifyPropertyChanged(BR.email)
}
@Bindable
var password = ""
set(value) {
field = value
checkValidation(false)
notifyPropertyChanged(BR.password)
}
@Bindable
var enableLoginButton = false
set(value) {
field = value
notifyPropertyChanged(BR.enableLoginButton)
}
internal val validationLiveLiveEvent = SingleLiveEvent<LoginConstant>()
private val _loginSingleLiveEvent = SingleLiveEvent<UiState<LoginResponse?>>()
internal val loginSingleLiveEvent: LiveData<UiState<LoginResponse?>> = _loginSingleLiveEvent
private fun checkValidation(isEmail : Boolean = true) {
enableLoginButton = false
when {
isEmail && !email.checkNotEmpty() -> {
validationLiveLiveEvent.value = LoginConstant.EMPTY_EMAIL
}
isEmail && !isValidEmail(email) -> {
validationLiveLiveEvent.value = LoginConstant.INVALID_EMAIL
}
!isEmail && !password.checkNotEmpty() -> {
validationLiveLiveEvent.value = LoginConstant.EMPTY_PASSWORD
}
!isEmail && !isValidPassword(password) -> {
validationLiveLiveEvent.value = LoginConstant.INVALID_PASSWORD
}
else ->{
enableLoginButton = true
validationLiveLiveEvent.value = LoginConstant.NONE
}
}
}
fun performLogin() {
_loginSingleLiveEvent.setLoading()
val map = HashMap<String, String>().apply {
put(KeyUtils.EMAIL, email)
put(KeyUtils.PASSWORD, <PASSWORD>)
}
loginUseCase.invoke(
scope = viewModelScope,
params = LoginUseCase.Param(map)
) {
it.result(_loginSingleLiveEvent::setApiResponse, _loginSingleLiveEvent::setError)
}
}
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/common/extension/ContextExt.kt
package com.mi.imaginatoprac.common.extension
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
fun Context.getColorRes(@ColorRes colorRes: Int): Int {
return ContextCompat.getColor(this, colorRes)
}
fun Context.getDrawableRes(@DrawableRes drawableRes: Int): Drawable? {
return ContextCompat.getDrawable(this, drawableRes)
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/AppDatabase.kt
package com.mi.imaginatoprac.data
import androidx.room.Database
import androidx.room.RoomDatabase
import com.basestructure.app.BuildConfig
import com.mi.imaginatoprac.data.account.respository.UserDao
import com.mi.imaginatoprac.domain.account.entity.User
@Database(
entities = [User::class],
version = BuildConfig.VERSION_CODE
)
abstract class AppDatabase : RoomDatabase() {
abstract fun accountDao(): UserDao
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/domain/account/usecase/LoginUseCase.kt
package com.mi.imaginatoprac.domain.account.usecase
import com.mi.imaginatoprac.data.account.entity.LoginResponse
import com.mi.imaginatoprac.domain.account.repository.UserRepository
import com.mi.imaginatoprac.domain.base.BaseUseCase
import javax.inject.Inject
class LoginUseCase @Inject constructor(
private val userRepository: UserRepository,
) : BaseUseCase<LoginResponse, LoginUseCase.Param>() {
data class Param(val data: HashMap<String, String>)
override suspend fun execute(params: Param): LoginResponse {
return userRepository.signInRequest(params.data)!!
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/domain/account/entity/User.kt
package com.mi.imaginatoprac.domain.account.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
const val TABLE_NAME = "User"
const val COLUMN_USER_ID = "user_id"
const val COLUMN_X_ACC = "x_acc"
const val COLUMN_USER_NAME = "user_name"
@Entity(tableName = TABLE_NAME)
data class User(
@PrimaryKey
@ColumnInfo(name = COLUMN_USER_ID)
val userId: String,
@ColumnInfo(name = COLUMN_X_ACC)
val authHeader: String,
@ColumnInfo(name = COLUMN_USER_NAME)
val userName: String
)<file_sep>/app/src/main/java/com/mi/imaginatoprac/common/extension/StringExts.kt
package com.mi.imaginatoprac.common.extension
fun String?.checkNotEmpty(): Boolean {
return this != null && isNotEmpty() && isNotBlank()
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/home/HomeViewModel.kt
package com.mi.imaginatoprac.ui.home
import com.mi.imaginatoprac.ui.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
) : BaseViewModel()<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/login/LoginFragment.kt
package com.mi.imaginatoprac.ui.login
import androidx.navigation.fragment.findNavController
import com.mi.imaginatoprac.ui.login.validation.LoginConstant
import com.basestructure.app.R
import com.basestructure.app.databinding.FragmentLoginBinding
import com.mi.imaginatoprac.common.extension.*
import com.mi.imaginatoprac.common.util.ProgressDialogUtil
import com.mi.imaginatoprac.data.account.entity.LoginResponse
import com.mi.imaginatoprac.domain.base.UiState
import com.mi.imaginatoprac.ui.base.BaseViewModelFragment
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class LoginFragment :
BaseViewModelFragment<LoginViewModel, FragmentLoginBinding>(R.layout.fragment_login) {
override fun buildViewModel() = initViewModel<LoginViewModel>()
override fun initLiveDataObservers() {
super.initLiveDataObservers()
with(viewModel) {
validationLiveLiveEvent.safeObserve(viewLifecycleOwner, ::handleValidations)
loginSingleLiveEvent.safeObserve(viewLifecycleOwner, ::handleSignInResponse)
}
}
override fun initViews() {
super.initViews()
binding.loginViewModel = viewModel
}
// Handle Error message on text input
private fun handleValidations(loginConstant: LoginConstant) {
with(binding) {
when (loginConstant) {
LoginConstant.EMPTY_EMAIL -> {
tilEmail.isErrorEnabled = true
tilEmail.error =
resources.getString(R.string.enter_email)
}
LoginConstant.EMPTY_PASSWORD -> {
tiPassword.isErrorEnabled = true
tiPassword.error =
resources.getString(R.string.enter_password)
}
LoginConstant.INVALID_EMAIL -> {
tilEmail.isErrorEnabled = true
tilEmail.error =
resources.getString(R.string.msg_invalid_email)
}
LoginConstant.INVALID_PASSWORD -> {
tiPassword.isErrorEnabled = true
tiPassword.error =
resources.getString(R.string.msg_password)
}
LoginConstant.NONE ->{
tilEmail.removeErrorState()
tiPassword.removeErrorState()
}
}
}
}
// handle response of api in loading , error and success state
private fun handleSignInResponse(response: UiState<LoginResponse?>) {
binding.apply {
tilEmail.removeErrorState()
tiPassword.removeErrorState()
}
when (response) {
is UiState.Loading -> {
context?.let(ProgressDialogUtil::showProgressDialog)
}
is UiState.Success -> {
ProgressDialogUtil.hideProgressDialog()
view.showSnackBar(getString(R.string.msg_login_success))
findNavController().navigate(R.id.action_loginFragment_to_homeFragment)
}
is UiState.Error -> {
ProgressDialogUtil.hideProgressDialog()
view.showSnackBar(response.throwable.message)
}
}
}
override fun getClassName(): String {
return this::class.java.simpleName
}
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/login/validation/LoginConstant.kt
package com.mi.imaginatoprac.ui.login.validation
//Login Validation Constant for different scenarios
enum class LoginConstant {
EMPTY_EMAIL,
INVALID_EMAIL,
EMPTY_PASSWORD,
INVALID_PASSWORD,
NONE
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/common/util/ProgressDialogUtil.kt
package com.mi.imaginatoprac.common.util
import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.Window
import androidx.core.content.ContextCompat
import com.basestructure.app.R
object ProgressDialogUtil {
private var dialog: Dialog? = null
fun showProgressDialog(context: Context) {
if (dialog == null) {
dialog = Dialog(context)
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog?.setContentView(R.layout.dialog_progress)
dialog?.window?.setBackgroundDrawable(
ColorDrawable(
ContextCompat.getColor(
context,
android.R.color.transparent
)
)
)
dialog?.setCancelable(false)
}
dialog?.show()
}
fun hideProgressDialog() {
if (dialog != null) {
if (dialog!!.isShowing) {
dialog?.dismiss()
}
dialog = null
}
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/account/respository/UserRepositoryImpl.kt
package com.mi.imaginatoprac.data.account.respository
import com.mi.imaginatoprac.common.util.KeyUtils.HTTP_SUCCESS
import com.mi.imaginatoprac.data.account.entity.LoginResponse
import com.mi.imaginatoprac.data.sharedprefs.SharedPrefs
import com.mi.imaginatoprac.domain.account.entity.User
import com.mi.imaginatoprac.domain.account.repository.UserRepository
import javax.inject.Inject
class UserRepositoryImpl @Inject constructor(
private val userApi: UserApi,
private val userDao: UserDao,
private val sharedPrefs: SharedPrefs
) : UserRepository {
override suspend fun isUserLoggedIn(): Boolean {
return sharedPrefs.isLoggedIn()
}
override suspend fun getUserData(): User {
return userDao.getUser(sharedPrefs.userId)
}
override suspend fun signInRequest(param: HashMap<String, String>): LoginResponse? {
val loginRes = userApi.login(param)
loginRes.let { response ->
val accountHeader = response.headers().get("X-Acc")
if (!accountHeader.isNullOrEmpty()) {
response.body().let {
if (it?.result == HTTP_SUCCESS) {
it.data?.user?.let{user->
sharedPrefs.userId = user.userId?.toString().orEmpty()
val user = User(user.userId?.toString().orEmpty(), accountHeader, user.userName.orEmpty())
userDao.insertReplace(user)
}
}else{
throw Exception(it?.errorMessage)
}
}
}else{
throw Exception(loginRes.body()?.errorMessage)
}
}
return loginRes.body()
}
}<file_sep>/app/src/main/java/com/mi/imaginatoprac/di/module/RepositoryModule.kt
package com.mi.imaginatoprac.di.module
import com.mi.imaginatoprac.data.account.respository.UserRepositoryImpl
import com.mi.imaginatoprac.domain.account.repository.UserRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Singleton
@Binds
abstract fun bindAccountRepository(
userRepository: UserRepositoryImpl
): UserRepository
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/common/util/ValidationUtils.kt
package com.mi.imaginatoprac.common.util
import androidx.core.util.PatternsCompat
import java.util.regex.Pattern
object ValidationUtils {
val passwordREGEX = Pattern.compile(
"^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=\\S+$)" + //no white spaces
".{8,16}" + //at least 8 characters
"$"
)
fun isValidEmail(email: String): Boolean {
return PatternsCompat.EMAIL_ADDRESS.matcher(email).matches()
}
fun isValidPassword(password: String): Boolean {
return passwordREGEX.matcher(password).matches()
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/ui/splash/SplashViewModel.kt
package com.mi.imaginatoprac.ui.splash
import androidx.lifecycle.viewModelScope
import com.mi.imaginatoprac.domain.splash.usecase.SplashUseCase
import com.mi.imaginatoprac.ui.base.BaseViewModel
import com.mi.imaginatoprac.ui.base.SingleLiveEvent
import dagger.hilt.android.lifecycle.HiltViewModel
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@HiltViewModel
class SplashViewModel @Inject constructor(
private val splashUseCase: SplashUseCase
) : BaseViewModel() {
internal val sessionStateEvent = SingleLiveEvent<Boolean>()
override fun loadPage(multipleTimes: Boolean): Boolean {
navigateNextScreen()
return super.loadPage(multipleTimes)
}
private fun navigateNextScreen() {
val params = SplashUseCase.Params(TimeUnit.SECONDS.toMillis(3))
splashUseCase.invoke(scope = viewModelScope, params = params) {
it.result(sessionStateEvent::setValue) { throwable ->
Timber.e(throwable)
}
}
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/di/module/SecurityModule.kt
package com.mi.imaginatoprac.di.module
import android.content.Context
import android.content.SharedPreferences
import com.basestructure.app.BuildConfig
import com.mi.imaginatoprac.data.sharedprefs.SecurityGuards
import com.mi.imaginatoprac.data.sharedprefs.SharedPrefs
import com.mi.imaginatoprac.data.sharedprefs.securityguards.SecurityGuardsImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class SecurityModule {
@Singleton
@Provides
fun provideSecurityGuards(@ApplicationContext context: Context): SecurityGuards {
return SecurityGuardsImpl.Factory().create(context)
}
@Singleton
@Provides
fun provideSharedPreferences(@ApplicationContext context: Context): SharedPreferences {
val versionSecurityGuards: Int = BuildConfig.SECURITY_GUARD_VERSION
val cacheName = StringBuilder().append(
SharedPrefs.PREFS_NAME
).append(
versionSecurityGuards.toString()
).toString()
return context.getSharedPreferences(cacheName, Context.MODE_PRIVATE)
}
@Singleton
@Provides
fun provideSharedPrefs(
sharedPreferences: SharedPreferences,
securityGuards: SecurityGuards
): SharedPrefs {
return SharedPrefs(sharedPreferences, securityGuards)
}
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/data/sharedprefs/cipher/KeystoreCipherImpl.kt
package com.mi.imaginatoprac.data.sharedprefs.cipher
import android.util.Base64
import com.mi.imaginatoprac.data.sharedprefs.utils.KeystoreWrapper
import java.security.Key
import java.security.KeyPair
import java.security.UnrecoverableKeyException
import java.security.spec.MGF1ParameterSpec
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.OAEPParameterSpec
import javax.crypto.spec.PSource
import javax.crypto.spec.SecretKeySpec
@Suppress("DEPRECATION")
class KeystoreCipherImpl(private val keystoreWrapper: KeystoreWrapper) : KeystoreCipher {
private var aesKey: ByteArray? = null
private var aesVectorSpecs: ByteArray? = null
private var masterKeyAsymmetric: KeyPair? = null
init {
if (!keystoreWrapper.isAndroidKeyStoreAsymmetricKeyExist()) {
keystoreWrapper.createAndroidKeyStoreAsymmetricKey()
}
}
@Throws(UnrecoverableKeyException::class)
override fun getMasterKeyAsymmetric() {
masterKeyAsymmetric = keystoreWrapper.androidKeyStoreAsymmetricKeyPair()
}
override fun getNewMasterKeyAsymmetric() {
keystoreWrapper.createAndroidKeyStoreAsymmetricKey()
masterKeyAsymmetric = keystoreWrapper.androidKeyStoreAsymmetricKeyPair()
}
override fun setAesKey(key: String, vectorSpec: String) {
aesKey = decryptRSA(key)
aesVectorSpecs = decryptRSA(vectorSpec)
}
override fun getNewAesKey(): Pair<String, String> {
val mapSymmetric = keystoreWrapper.createDefaultSymmetricKey()
aesKey = mapSymmetric[KeystoreWrapper.AES_MASTER_KEY]
aesVectorSpecs = mapSymmetric[KeystoreWrapper.AES_VECTOR_KEY]
val keyEncrypted = encryptRSA(aesKey) ?: ""
val ivEncrypted = encryptRSA(aesVectorSpecs) ?: ""
return Pair(keyEncrypted, ivEncrypted)
}
@Throws(IllegalStateException::class)
override fun decrypt(encrypted: String): String {
if (encrypted.isEmpty()) return ""
return try {
val aesCipher = Cipher.getInstance(AES_TRANSFORMATION)
val iv = IvParameterSpec(aesVectorSpecs)
val skeySpec = SecretKeySpec(aesKey, AES_ALGORITHM)
aesCipher.init(Cipher.DECRYPT_MODE, skeySpec, iv)
val original = aesCipher.doFinal(encrypted.decodeToByteArray())
String(original, Charsets.UTF_8)
} catch (e: Exception) {
""
}
}
override fun encrypt(value: String): String {
if (value.isEmpty()) return ""
return try {
val aesCipher = Cipher.getInstance(AES_TRANSFORMATION)
val iv = IvParameterSpec(aesVectorSpecs)
val skeySpec = SecretKeySpec(aesKey, AES_ALGORITHM)
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv)
val encrypted = aesCipher.doFinal(value.toByteArray(Charsets.UTF_8))
encrypted.encodeToString()
} catch (e: Exception) {
""
}
}
private val sp by lazy {
OAEPParameterSpec(SHA_256, MGF, MGF1ParameterSpec(SHA_1), PSource.PSpecified.DEFAULT)
}
private fun encryptRSA(value: ByteArray?): String? {
if (value == null || masterKeyAsymmetric?.public == null) {
return null
}
val rsaCipher = Cipher.getInstance(RSA_TRANSFORMATION)
val publicKey = masterKeyAsymmetric?.public
val encryptedByteArray = rsaCipher.apply {
init(Cipher.ENCRYPT_MODE, publicKey, sp)
}.doFinal(value)
return encryptedByteArray.encodeToString()
}
private fun decryptRSA(value: String): ByteArray? {
if (masterKeyAsymmetric?.private == null) {
return null
}
val rsaCipher = Cipher.getInstance(RSA_TRANSFORMATION)
val privateKey = masterKeyAsymmetric?.private
val byteArray = value.decodeToByteArray()
return rsaCipher.apply {
init(Cipher.DECRYPT_MODE, privateKey, sp)
}.doFinal(byteArray)
}
override fun deleteMasterKey() {
keystoreWrapper.removeAndroidKeyStoreKey()
}
/**
* Wraps(encrypts) a key with another key.
*/
fun wrapKey(keyToBeWrapped: Key): String {
val rsaCipher = Cipher.getInstance(RSA_TRANSFORMATION)
rsaCipher.init(Cipher.WRAP_MODE, masterKeyAsymmetric?.public)
val decodedData = rsaCipher.wrap(keyToBeWrapped)
return Base64.encodeToString(decodedData, Base64.DEFAULT)
}
/**
* Unwraps(decrypts) a key with another key. Requires wrapped key algorithm and type.
*/
fun unWrapKey(wrappedKeyData: String, algorithm: String, wrappedKeyType: Int): Key {
val rsaCipher = Cipher.getInstance(RSA_TRANSFORMATION)
val encryptedKeyData = Base64.decode(wrappedKeyData, Base64.DEFAULT)
rsaCipher.init(Cipher.UNWRAP_MODE, masterKeyAsymmetric?.private)
return rsaCipher.unwrap(encryptedKeyData, algorithm, wrappedKeyType)
}
companion object {
private const val AES_ALGORITHM = "AES"
private const val AES_TRANSFORMATION = "AES/CBC/PKCS5Padding"
private const val SHA_256 = "SHA-256"
private const val SHA_1 = "SHA-1"
private const val MGF = "MGF1"
private const val RSA_TRANSFORMATION = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"
}
private fun String.decodeToByteArray(): ByteArray = Base64.decode(this, Base64.DEFAULT)
private fun ByteArray.encodeToString(): String = Base64.encodeToString(this, Base64.DEFAULT)
}
<file_sep>/app/src/main/java/com/mi/imaginatoprac/domain/splash/usecase/SplashUseCase.kt
package com.mi.imaginatoprac.domain.splash.usecase
import com.mi.imaginatoprac.domain.account.repository.UserRepository
import com.mi.imaginatoprac.domain.base.BaseUseCase
import kotlinx.coroutines.delay
import javax.inject.Inject
class SplashUseCase @Inject constructor(
private val userRepository: UserRepository
) : BaseUseCase<Boolean, SplashUseCase.Params>() {
data class Params(val delayInMillis: Long)
override suspend fun execute(params: Params): Boolean {
delay(params.delayInMillis)
return userRepository.isUserLoggedIn()
}
}
| 89fd6bdd696bf9d59d7364f8f332c12e7d34722a | [
"Kotlin",
"Gradle"
] | 34 | Kotlin | dhavalMindinventory/JetDevsAndroidTest | a698949bc5bd86c02b44d570217c89abf07f51d5 | 173a7d62eafea8838f75312e67e990645b4ade4c |
refs/heads/master | <repo_name>anurupr/Scripts<file_sep>/asianetlogin.sh
#!/bin/bash
# ----------------------------------------------------------------------
# AsianetLogin
# Copyright (c) 2011 <NAME>
# mailme:<EMAIL>
# https://github.com/anurupr/Shell-Scripts
#
# This script allows the automatic login for the asianet dataline
# [unlimited] connection. It uses another shell script designed by
# zyxware.com which does the actual login. This script just makes sure
# that the login script runs after 10 seconds
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# ----------------------------------------------------------------------
while true
do
result=$(gksudo autologin)
echo $result
sleep 10
done
<file_sep>/changebackground.sh
#!/bin/bash
# Script to randomly set Background from files in a directory
# Directory Containing Pictures
DIR=/home/anurup/backgrounds
LOG=/home/anurup/logs/backgrounds.log
# Command to Select a random file from directory
while true
do
PIC=$(
for p in [jJ][pP][gG] [pP][nN][gG] ; do
ls $DIR/*.$p
done | shuf -n1
)
# Command to set Background Image
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ] ; then
# this is because of gconftool bug in cron
TMP=~/.dbus/session-bus
export $(grep -h DBUS_SESSION_BUS_ADDRESS= $TMP/$(ls -1t $TMP | head -n 1))
echo $DBUS_SESSION_BUS_ADDRESS >> $LOG
fi
# Change the background
gconftool-2 -t string -s /desktop/gnome/background/picture_filename "$PIC"
sleep 3600
done
<file_sep>/nautcurrent.sh
#!/bin/bash
# ----------------------------------------------------------------------
# NautCurrent
# Copyright (c) 2011 <NAME>
# mailme:<EMAIL>
# https://github.com/anurupr/Shell-Scripts
#
# This script allows the loading of the nautilus tool with the current working
# directory
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# ----------------------------------------------------------------------
echo "'`pwd`'" | xargs nautilus --browser
<file_sep>/esm.sh
#!/bin/bash
# ----------------------------------------------------------------------
# Easy Samba Mount
# Copyright (c) 2011 <NAME>
# mailme:<EMAIL>
# https://github.com/anurupr/Shell-Scripts
#
# This script allows the mounting of samba shares.
# Input : IP Address / Computer Name
# Share Name
# Username & Password
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# ----------------------------------------------------------------------
#HOST=$(zenity --entry --title="Hostname" --text="Enter the IP Address/Hostname")
SHARE=$(zenity --entry --title="Sharename" --text="Enter the share name")
#MOUNTPATH=$(zenity --entry --title="Mountpath" --text="Enter the mount path")
#USERNAME=$(zenity --entry --title="Username" --text="Enter the server username")
#PASSWORD=$(zenity --entry --title="Password" --text="Enter the server password")
var=$(sudo smbmount //192.168.10.6/$SHARE /mnt/win -o username=UNFORGIVEN,password=<PASSWORD>; echo $?)
if [ $var -eq 0 ]; then
`nautilus --browser /mnt/win`
else
echo "Share not found. Please try again"
fi
| 4d2b472567a1e3fecb41a394203be0f5f57cd2e4 | [
"Shell"
] | 4 | Shell | anurupr/Scripts | 689cac9b59a18f6ed1d66117c1ed8f05901a64a5 | 4dd9260ffaf83be82538c6f45f58fca6def39937 |
refs/heads/master | <repo_name>theSinster/dojos<file_sep>/tall-people/src/main/java/TallPeople.java
public class TallPeople {
public int[] getPeople(String[] people) {
// TODO http://community.topcoder.com/stat?c=problem_statement&pm=2923&rd=5854
return new int[2];
}
}
<file_sep>/settings.gradle
include 'business-tasks', 'tall-people'
<file_sep>/business-tasks/src/main/java/BusinessTasks.java
import java.util.ArrayList;
import java.util.Arrays;
public class BusinessTasks {
public String getTask(String[] list, int n) {
ArrayList<String> taskList = new ArrayList<>(Arrays.asList(list));
int indexToBeRemoved = 0;
while (taskList.size() > 1) {
indexToBeRemoved = calculateIndexToBeRemoved(taskList.size(), n, indexToBeRemoved);
taskList.remove(indexToBeRemoved);
}
return taskList.get(0);
}
private int calculateIndexToBeRemoved(int sizeOfList, int seed, int currentIndex) {
int newPosition = (seed + currentIndex) % sizeOfList;
if (newPosition == 0) {
return sizeOfList - 1;
}
return newPosition - 1;
}
}
<file_sep>/build.gradle
ext {
logbackVersion = "1.0.13"
slf4jVersion = "1.7.5"
guavaVersion = "15.0"
junitVersion = "4.+"
hamcrestVersion = "1.3"
spockVersion = "0.7+"
}
subprojects {
repositories {
maven {
url "http://repo1.maven.org/maven2/"
}
}
apply plugin: "java"
apply plugin: "groovy"
}
| 94d48491360b12c1cdaae5e5a187d20b036e6853 | [
"Java",
"Gradle"
] | 4 | Java | theSinster/dojos | d177bb7ba643ab09f8779bb4ca2d2a92aa5ab8c1 | 13f8b833487e99603cbc92a6709c8fae4c2d6b0e |
refs/heads/master | <repo_name>matoboor/Raspberry-Pi-Smart-home-kivy-<file_sep>/main.py
# -*- coding: utf-8 -*-
import kivy
kivy.require('1.0.6') # replace with your current kivy version !
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.videoplayer import VideoPlayer
from kivy.uix.listview import ListView, ListItemButton
from kivy.adapters.listadapter import ListAdapter
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle
import RPi.GPIO as GPIO
import time, datetime
from functools import partial
import dht11
import os, subprocess
import mysql.connector
import smbus
#for now, use a global for blink speed (better implementation TBD):
ringing = False
ledOn = False
lastTouch = datetime.datetime.now()
sleepTime = 15
lastMotion = datetime.datetime.now()
lastLedButtonOn = datetime.datetime.now()
tempHumi =[0,0]
sleep = False
night = False
# Set up GPIO:
beepPin = 17
ledPin = 27
BellButton = 22
PIR = 4
Light = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(beepPin, GPIO.OUT)
GPIO.output(beepPin, GPIO.LOW)
GPIO.setup(ledPin, GPIO.OUT)
GPIO.output(ledPin, GPIO.LOW)
GPIO.setup(BellButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(PIR, GPIO.IN)
instance = dht11.DHT11(pin=14)
# Define some helper functions:
# This callback will be bound to the LED toggle button
def press_callback(obj):
global ringing
global ledOn
global lastLedButtonOn
if obj.text == 'LED':
if obj.state == "down":
GPIO.output(ledPin, GPIO.HIGH)
ledOn=True
lastLedButtonOn = datetime.datetime.now()
else:
ledOn=False
#Wake Up Display from sleep
def wakeUpDisplay():
subprocess.call('xset dpms force on', shell=True)
#Sleep display
def sleepDisplay(dt):
subprocess.call('xset dpms force off', shell=True)
def setDisplaySleepTime(sec,dt):
string = 'xset dpms ' + str(sec) + ' ' + str(sec) + ' ' + str(sec)
subprocess.call(string, shell=True)
print 'time to sleep display was setted to: '+str(sec)+' seconds.'
#sleep button event /0.2 s delay for filter double click by mistake
def sleepDisplayButton(dt):
global sleep
Clock.schedule_once(sleepDisplay,0.2)
sleep = True
#ring event making bell ringing and LED flashing,
#preventing from multiple ringing and logging event
# self param is ButtonImage instance represents bell icon /for flashing logo
def rg(self, dt):
global ringing
if not ringing:
Clock.schedule_once(partial(flashIcon,self,20), 0.01)
Clock.schedule_once(partial(ring,10), 0.01)
logBell()
#This function recursively call's self (with decreased cnt param).
#In each iteration are switched GPIO ports for LED and BELL on or off
def ring(cnt,dt):
global ringing
global night
if cnt>0:
ringing = True
GPIO.output(ledPin, not GPIO.input(ledPin))
GPIO.output(beepPin, not GPIO.input(beepPin))
Clock.schedule_once(partial(ring, cnt-1), 1)
else:
ringing = False
#if LED was turned on manualy, turn it on again after ringing
if ledOn or (((lastMotion+datetime.timedelta(seconds=30))-datetime.datetime.now()).total_seconds()>0 and night):
GPIO.output(ledPin,True)
#Blinking bell icon when ringing /speed is set by Clock.shcedule param (0.5)
#Used by rg() function
def flashIcon(self, cnt, dt):
if cnt>0:
if self.source=='Bell.png':
self.source='BellR.png'
else:
self.source='Bell.png'
Clock.schedule_once(partial(flashIcon,self,cnt-1), 0.5)
#polling GPIO pin state for bell push button. If button is pushed,
#display is waked up and ringing is scheduled for next frame
def bellImageRefresh(self, dt):
global ringing
if GPIO.input(BellButton) == False and not ringing: #If button is pressed
wakeUpDisplay()
Clock.schedule_once(partial(rg, self), 0)
#refreshing every second Time label with actual time
def timeRefresh(self,dt):
self.text = datetime.datetime.now().strftime('%H:%M:%S')
#returns array of (timestamp, note) from MySql DB.
#you can specify count of entries by param count
#if count==0, count is setted to 50
def getBells(count):
result = []
conn = mysql.connector.connect(user='smarthome', password='<PASSWORD>', host='127.0.0.1', database='smarthome')
cursor = conn.cursor()
data = count
if count==0:
data=50
selectQuerry = "SELECT * FROM bells ORDER BY timestamp DESC LIMIT "+str(data)
cursor.execute(selectQuerry)
for timestamp in cursor:
result.append(timestamp[0])
cursor.close()
conn.close()
return result
#Log timestamp and note for bell into the MySql DB
def logBell():
conn = mysql.connector.connect(user='smarthome', password='<PASSWORD>', host='127.0.0.1', database='smarthome')
cursor = conn.cursor()
insertQuerry = ("INSERT INTO bells (timestamp, note)"
"VALUES (%s, %s)")
data = (datetime.datetime.now(),'n')
cursor.execute(insertQuerry,data)
conn.commit()
cursor.close()
conn.close()
#Log timestamp, temp, humi and note into the MySql DB
def logTempAndHumi(th):
conn = mysql.connector.connect(user='smarthome', password='<PASSWORD>', host='127.0.0.1', database='smarthome')
cursor = conn.cursor()
insertQuerry = ("INSERT INTO temperatures (timestamp, temperature, humidity, note)"
"VALUES (%s, %s, %s, %s)")
data = (datetime.datetime.now(),th[0],th[1],'chodba_vstup')
cursor.execute(insertQuerry,data)
conn.commit()
cursor.close()
conn.close()
#Get temp and humi from sensor (DHT11), fill global variable temphumi (array)
#log data
def tempHumiMeasure(dt):
global tempHumi
result = instance.read()
if result.is_valid():
tempHumi[0]=result.temperature
tempHumi[1]=result.humidity
logTempAndHumi(tempHumi)
else:
Clock.schedule_once(tempHumiMeasure, 1)
#refreshing Temp label with actual temperature
def tempRefresh(self, dt):
global tempHumi
self.text = "Teplota: "+str(tempHumi[0])+" °C"
#refreshing Humi label with actual humidity
def humiRefresh(self, dt):
global tempHumi
self.text = "Vlhkosť: "+str(tempHumi[1])+" %"
#manually turn off LED
def ledOff(self, dt):
global ledOn
#GPIO.output(ledPin,False)
self.state='normal'
ledOn=False
#class for Image with Button behavior
class ImageButton(ButtonBehavior, Image):
pass
#Gets last 5 entries from MySql DB and show it in popup
def showLastBells(self):
data = getBells(5)
txt = ''
for timestamp in data:
txt += str(timestamp.strftime('%d. %b - %H:%M:%S'))+ "\n"
layout = BoxLayout(orientation='vertical')
lb1 = Label(text=txt, font_size='20sp')
btn = Button(text='Zatvoriť', size_hint_y=0.2)
layout.add_widget(lb1)
layout.add_widget(btn)
popup = Popup(title='Posledné zvonenia',
content=layout,
size_hint=(None, None), size=(400, 400))
btn.bind(on_press=popup.dismiss)
popup.open()
def videoArchiveItemSelected(player,popup,self):
id = self.selection[0].text.split(" ")[0]
data = getVideoList()
video = next(v for v in data if v.id==id)
player.source=video.path
player.state='play'
popup.title='Video archív - ' + video.time.strftime('%d. %b - %H:%M:%S')
class VideoListItemButton(ListItemButton):
deselected_color=[0, 0, 0, 1]
def videoArchiveBtnCallback(self):
setDisplaySleepTime(9999,1)
data = getVideoList()
listData = []
for d in data:
listData.append(d.id + " " + d.time.strftime('%d. %b - %H:%M:%S'))
list_adapter = ListAdapter(data=listData,
cls=VideoListItemButton,
selection_mode='single',
allow_empty_selection=False)
player = VideoPlayer(source=data[0].path, state='play', options={'allow_stretch': True})
root = GridLayout(cols=2)
popup = Popup(title='Video archív - '+data[0].time.strftime('%d. %b - %H:%M:%S'),
content=root,
size_hint=(1, 1))
list_adapter.bind(on_selection_change=partial(videoArchiveItemSelected,player, popup))
layout1 = BoxLayout(orientation='vertical')
layout2 = BoxLayout(orientation='vertical')
videoList = ListView(adapter=list_adapter)
btn = Button(text='Zatvoriť', size_hint_y=0.2)
layout1.add_widget(videoList)
layout2.add_widget(player)
layout2.add_widget(btn)
root.add_widget(layout1)
root.add_widget(layout2)
btn.bind(on_press=partial(videoArchiveExitBtnCallback,popup))
popup.open()
def videoArchiveExitBtnCallback(popup,self):
popup.dismiss()
setDisplaySleepTime(15,1)
class VideoFile:
def __init__(self, id, time, path):
self.id=id
self.time=time
self.path=path
def getVideoList():
path = "/mnt/motionvideos"
result=[]
for file in os.listdir(path):
if file.endswith(".avi"):
result.append(VideoFile(file.split('-')[0],datetime.datetime.strptime(file.split('-')[1].split('.')[0],'%Y%m%d%H%M%S%f'), os.path.join(path, file)))
return sorted(result, key=lambda x: x.time, reverse=True)
def Night(dt):
global night
DEVICE = 0x23 # I2C device address
bus = smbus.SMBus(1) # RconvertToNumber
data = convertToNumber(bus.read_i2c_block_data(DEVICE,0x11))
if not(data > 1):
night=True
else:
night=False
def convertToNumber(data):
return ((data[1] + (256 * data[0])) / 1.2)
def motion():
return GPIO.input(PIR)
def ledAuto(dt):
global night
global ledOn
global lastMotion
global ringing
time = 7
if motion():
lastMotion = datetime.datetime.now()
if night and not GPIO.input(ledPin) and not ringing:
GPIO.output(ledPin, True)
print "On"
else:
if not ledOn and GPIO.input(ledPin) and not ringing:
if ((lastMotion+datetime.timedelta(seconds=time))-datetime.datetime.now()).total_seconds()<0:
GPIO.output(ledPin,False)
print "Off"
def refreshLedButton(btn,dt):
global lastLedButtonOn
if ((lastLedButtonOn+datetime.timedelta(seconds=120))-datetime.datetime.now()).total_seconds()<0 and GPIO.input(ledPin) and not ringing:
ledOff(btn,1)
class MyGridLayout(GridLayout):
def on_touch_down(self, touch):
global lastTouch
global sleepTime
global sleep
print touch
print str(lastTouch) + "ontouch"
if ((lastTouch+datetime.timedelta(seconds=sleepTime))-datetime.datetime.now()).total_seconds()<0 or sleep:
wakeUpDisplay()
lastTouch = datetime.datetime.now()
sleep = False
else:
super(MyGridLayout,self).on_touch_down(touch)
lastTouch = datetime.datetime.now()
#main class
class MyApp(App):
def build(self):
# Set up the layout:
layout = MyGridLayout(cols=4, spacing=30, padding=30, row_default_height=150)
# Make the background gray:
with layout.canvas.before:
Color(.2,.2,.2,1)
self.rect = Rectangle(size=(800,600), pos=layout.pos)
#Start Temp adn Humidity measurment
Clock.schedule_interval(tempHumiMeasure,900)
Clock.schedule_once(tempHumiMeasure,5)
Clock.schedule_interval(Night,1)
Clock.schedule_interval(ledAuto,0)
Clock.schedule_once(partial(setDisplaySleepTime,15),1)
# Instantiate the first UI object (the GPIO input indicator):
bellImage = ImageButton(source='Bell.png')
bellImage.bind(on_press=showLastBells)
# Schedule the update of the state of the GPIO input button:
Clock.schedule_interval(partial(bellImageRefresh,bellImage), 1.0/10.0)
# Create the rest of the UI objects (and bind them to callbacks, if necessary):
outputControl = ToggleButton(text="LED",font_size='25sp')
outputControl.bind(on_press=press_callback)
Clock.schedule_interval(partial(refreshLedButton,outputControl),0.5)
timeLabel = Label(text='time',font_size='50sp')
Clock.schedule_interval(partial(timeRefresh,timeLabel), 1)
# Add the UI elements to the layout:
layout1 = BoxLayout(orientation='vertical')
l1 = Label(text="temp",font_size='25sp')
Clock.schedule_interval(partial(tempRefresh,l1), 60)
Clock.schedule_once(partial(tempRefresh,l1), 5)
l2 = Label(text="humi",font_size='25sp')
Clock.schedule_interval(partial(humiRefresh,l2), 60)
Clock.schedule_once(partial(humiRefresh,l2), 5)
l3 = Label(text=" ",font_size='25sp')
videoArchiveBtn = Button(text='Video archív')
videoArchiveBtn.bind(on_press=videoArchiveBtnCallback)
layout1.add_widget(timeLabel)
layout1.add_widget(l1)
layout1.add_widget(l2)
layout1.add_widget(l3)
layout1.add_widget(videoArchiveBtn)
layout2 = FloatLayout()
sleepBtn = ImageButton(source='sleep.png', pos=(670,405))
sleepBtn.bind(on_press=sleepDisplayButton)
layout2.add_widget(sleepBtn)
layout1.add_widget(layout2)
layout.add_widget(layout1)
layout.add_widget(bellImage)
layout.add_widget(outputControl)
return layout
if __name__ == '__main__':
MyApp().run()
<file_sep>/README.md
# Raspberry-Pi-SmartHome
Môj projekt domácej automatizácie, ktorý ovláda svetlo v stupnej chodbe, domový zvonček, sníma teplotu, vlhkosť a intenzitu svetla.
Pripojená je aj Web kamera, ktorá slúži ako bezpečnostná kamera s detekciou pohybu.
Obslužná aplikácia je naprogramovaná vo frameworku Kivi a je určená pre dotykové displeje.
Raspberry Pi 3
RPi.GPIO
Python
Kivi
MySQL
Motion
| 8bab223ff70f1022735fee9a75d2f3bce967c58d | [
"Markdown",
"Python"
] | 2 | Python | matoboor/Raspberry-Pi-Smart-home-kivy- | f8e8efad742f8dc0bc5ad10c9bec85a876729ef6 | 734199ba9db2e827c280fc2a880ef8e1c83a4a77 |
refs/heads/dev | <repo_name>akshaymittal143/FizzBuzzChallenge<file_sep>/FizzBuzzTests/FizzBuzzTest.cs
using FizzBuzz;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FizzBuzzTests
{
[TestClass]
public class FizzBuzzTest
{
[TestMethod]
public void TestMethod1()
{
var result = new FizzBuzzClass();
result.FizzBuzz(10);
}
[TestMethod]
public void TestMethod2()
{
var result = new FizzBuzzClass();
result.FizzBuzz(100);
}
[TestMethod]
public void TestMethod3()
{
var result = new FizzBuzzClass();
result.FizzBuzz(1000);
}
}
}
<file_sep>/FizzBuzz/FizzBuzzClass.cs
using System;
namespace FizzBuzz
{
public class FizzBuzzClass
{
public void FizzBuzz(int input)
{
for (int number = 1; number <= input; number++)
{
//Console.WriteLine("{0}", i % 15 == 0 ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0 ? "Buzz" : i.ToString())));
//intialize string variable to empty
string result = "";
//checking if divible by 3
if (number % 3 == 0) result = "Fizz";
//checking if diving by 5 and if divisible by 3 and 5 =FizzBuzz
if (number % 5 == 0) result = result + "Buzz";
//print number if not divisble by 3 or 5
if (result.Length == 0) result = number.ToString();
Console.WriteLine(result);
}
}
}
}
<file_sep>/Fizbuzztrial/Program.cs
using FizzBuzz;
using System;
namespace FizzBuzzProgram
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a Maximum Number:");
int number = Convert.ToInt32(Console.ReadLine());
FizzBuzzClass result = new FizzBuzzClass();
result.FizzBuzz(number);
Console.ReadLine();
}
}
}
| 8ff11b0a827b3e612abd650635138ac2171d9e2f | [
"C#"
] | 3 | C# | akshaymittal143/FizzBuzzChallenge | 882a61856739dd2226a0b2664d3e0aa9603df274 | 45f9942db7e53f231645adafff5951040fec50dd |
refs/heads/master | <file_sep>local com = {}
local devices = {}
function com.isAvailable(pid,devName)
end
function com.invoke(pid,devName,...)
end
function com.proxy(devName)
end
function com.init()
for k,v in components.list() do
devices[v] = {["type"] = components.type(v)} -- components type
end
end
function com.runtime()
while true do
local eD = {coroutine.yield()}
if eD[1] == "component_added" then -- component added
devices[eD[2]] = {["type"] = eD[3]}
elseif eD[1] == "component_removed" then -- component removed
end
end
end
return com<file_sep>-- system api extension
function assert(ok, ...)
if not ok then
error(...)
end
end
function table.copy(tab)
local ret = {}
for k, v in pairs(tab) do
if type(v) == "table" then
ret[k] = table.copy(v)
else
ret[k] = v
end
end
return ret
end
function string.split(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
local i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
-- following functions read and write on system drive
local sysdrv = {}
function sysdrv.getFolders(path)
end
function sysdrv.getFiles(path)
end
function sysdrv.readFile(filename)
-- read file
end
function sysdrv.readFileTab(filename)
-- read file and create table
end
function sysdrv.writeFile(filename, txt)
-- write text / table to file
end
local driverControl = {}
local signalControl = {}
for dev, evs in pairs(sysdrv.readFileTab("/apps/drivers.cfg")) do
for ev, pos in pairs(evs) do
driverControl[ev] = {dev, pos}
end
end
local defaultPackageRunning = {
enabled = false
neededFor = {}
}
for name, info in pairs(packList) do
info.running = table.copy(defaultPackageRunning)
end
local apiSet = {}
local shortcuts = {["fs"]="filesystem"}
-- internal runtime api
local runtime = {}
local running = {} -- { thread , }
_G.runtime = runtime
local metaAccess = function(hid, data)
return (type(hid) == "table" and setmetatable({}, {__index=function(t, k)
return metaAccess(hid[k], data)
end})) or (type(hid) == "function" and function(...)
return (data and hid(table.copy(data), ...)) or hid(...)
end) or hid
end
function runtime.add(scriptFunction, dataTable, ...)
local env = setmetatable({}, {__index=function(t, k)
return metaAccess(apiSet[shortcuts[k] or k])
end})
local cor, err = coroutine.create(scriptFunction, env)
if not cor then
return false, err
end
local pid = table.maxn(running) + 1
data = data or {}
data.runtime = data.runtime or {}
local r = data.runtime
for k, v in pairs({
isDaemon = false,
byModule = "",
sourceType = "unknown" -- unknown , module , package , filesystem , sideLoaded | filesystem means it was a file what is not registered as part of a package
sourceInfo = "" -- nil , moduleName , packageName , path , executingPid
}) do
r[k] = r[k] or v
end
running[pid] = data
running[pid].thread = cor
local ok, err = coroutine.resume(cor, ...)
if not ok then
return false, err
end
return pid
end
function runtime.status(pid)
return coroutine.status(running[pid].thread)
end
-- module initialization
local modules = {runtime = runtime, sysdrv = sysdrv}
local modEnv = setmetatable({}, {__index = function(t, k)
return metaAccess(modules[k] or _G[k])
end, __newindex = function(t, k, v) end})
print("Preinstalled modules")
for k, v in pairs(modules) do
print(" "..k)
end
print("Load external modules")
for k, v in pairs(getFiles("/system/runtime")) do
if v:sub(-4) == ".lua" then
local name = tostring(v:sub(1, -5))
assert(_G[name] or modules[name], "ZockerCore: Name of Module \""..name.."\" is not valid", 0)
print(" "..name)
local raw = sysdrv.readFile("/system/runtime/"..name..".lua")
assert(type(raw) ~= "string", "ZockerCore: Module "..name.." cannot be loaded", 0)
local bin, err = load(raw, "modules."..name, "t", modEnv)
assert(bin, err, 0)
modules[name] = bin()
end
end
print("Initialize modules")
for k, v in pairs(modules) do
if type(v.init) == "function" then
print(" "..k)
v.init()
end
end
print("Add modules to runtime")
for k, v in pairs(modules) do
if type(v.runtime) == "function" then
local name, desc = k, "/system/runtime/"..k..".lua"
if type(v.infos) == "function" then
name, desc = v.infos()
end
print(" "..name)
local ok, err = runtime.add(v, {
runtime = {
name = name,
description = desc,
isDaemon = true,
byModule = k,
},
access = {
level = 4
},
})
assert(ok, err, 0)
end
end
-- run sequence
print("Pass control to modules")
computer.pushSignal("boot_completed")
while true do
local eD = {computer.pullSignal()}
end<file_sep>local acc = {}
-- level : 0: guests (controlled by other app) | 1: user | 2: admin | 3:system
-- options : 4: with argument | 8: single asking
local perms = { -- "permName" , "permName#argument"
changePermissions = 3+4+8,
useMainComponent = 1+4,
useSystemComponent = 2+4,
bindComponent = 2+4,
releaseComponent = 3+4+8,
bindComponentType = 3+4,
releaseComponentType = 3+4+8,
changeFilesystem = 3+4,
releaseDefaultFilesystem = 2+4+8,
releaseMainFilesystem = 3+4+8,
createWindows = 1,
changeToWindow = 2,
useNetwork = 0,
bindDefaultPort = 2+4,
bindMainPort = 3+4,
releasePort = 3+4+8,
changePackages = 3+4+8,
}
local appPerms = {} -- "packageName" -> "permName" , "packageName#permName#argument"
local cfg = readFileTab("/apps/access.cfg")
local function splitPerm(name)
if type(name) ~= "string" or name:len() < 1 then
return false
end
local s = string.split(name,"#")
if not s[1] then return false end
if perms[s[1]] then
return true,nil,s[1],s[2]
end
if s[2] and appPerms[s[1]] and appPerms[s[1]][s[2]] then
return true,s[1],s[2],s[3]
end
return false
end
local function getLevel(perm)
local b,p,r,a = splitPerm(perm)
if not b then
return false,"Permission does not exist"
end
if p then
return appPerms[p][r] % 4
else
return perms[perm] % 4
end
end
local function hasArgument(perm)
local b,p,r,a = splitPerm(perm)
if not b then
return false,"Permission does not exist"
end
if p then
return appPerms[p][r] % 4
else
return perms[perm] % 4
end
return bit32.extract(perms[p],2) == 1
end
local function isSingleAsk(perm)
if not perms[perm] then
return false,"Permission does not exist"
end
return bit32.extract(perms[perm],3) == 1
end
function acc.giveAccessTo(pack,perm)
if not perms[perm] then
return false,"Permission does not exist"
end
if not package.isEnabled(pack) then
return false,"Package is not enabled"
end
if not cfg[pack] then
cfg[pack] = {}
end
cfg[pack][perm] = true
return true
end
function acc.askAccessTo(pack,perm)
if not perms[perm] then
return false,"Permission does not exist"
end
if not package.isEnabled(pack) then
return false,"Package is not enabled"
end
if not cfg[pack] then
cfg[pack] = {}
end
end
function acc.hasAccessTo(pack,perm)
if not perms[perm] then
return false,"Permission does not exist"
end
if not package.isEnabled(pack) then
return false,"Package is not enabled"
end
if not cfg[pack] then
cfg[pack] = {}
end
local ok = cfg[pack][perm] ~= nil
if ok and
end
function acc.canHaveAccessTo(pack,perm)
if not perms[perm] then
return false,"Permission does not exist"
end
if not package.isEnabled(pack) then
return false,"Package is not enabled"
end
if not cfg[pack] then
cfg[pack] = {}
end
end
function acc.removeAccessTo(pack,perm)
if not perms[perm] then
return false,"Permission does not exist"
end
if not package.isEnabled(pack) then
return false,"Package is not enabled"
end
if not cfg[pack] then
cfg[pack] = {}
end
cfg[pack][perm] = false
return true
end
function acc.save()
writeFile("/apps/access.cfg",cfg)
end
function acc.infos()
return "",
end
function acc.init()
for
end
function acc.runtime() -- also second init
local l = {}
for k,v in pairs(cfg) do
if not package.isInstalled(k) then
l[k] = true
end
end
for k,v in pairs(l) do
cfg[k] = nil
end
acc.save()
end
return acc<file_sep>local package = {}
local packList = readFileTab("/apps/installed.cfg")
local packageLoading = {}
function package.setEntry(name,info)
packList[name] = info
info.running = {}
info.running.enabled = false
end
local function packageEnableFor(info,forName)
info.running.enabled = true
if forName then
info.running.neededFor[forName] = true
end
end
function package.enableFor(name,forName)
local info = packList[name]
if not info then
return false,"Package is not installed"
end
if packageLoading[name] then
return true
end
if info.running.enabled then
return packageEnabledFor(info,forName)
end
if info.enabledState < 0 then
return false,"Package is disabled"
end
if not info.requirements then
return packageEnabledFor(info,forName)
end
packageLoading[name] = true
for _,v in pairs(info.requirements) do
if not package.enable(v,name) then
return false,"Requirements are missing"
end
end
return packageEnabledFor(info,forName)
end
function package.isInstalled(name)
return packList[name] ~= nil
end
function package.enable(name)
return package.enableFor(name,nil)
end
function package.isEnabled(name)
local info = packList[name]
if not info then
return false,"Package is not installed"
end
return info.running.enabled
end
function package.disable(name) do
local info = packList[name]
if not info then
return false,"Package is not installed"
end
if packageLoading[name] then
return true
end
packageLoading[name] = true
for k,v in pairs(info.running.neededBy)
package.disable(name)
end
if info.requirements then
for k,v in pairs(info.requirements) do
package.disableUnneded(v)
end
end
for k,v in pairs(info.running.neededFor) do
package.disable(k)
end
info.running.neededFor = {}
info.running.enabled = false
return true
end
function package.disableUnneeded(name)
local info = packList[name]
if not info then
return false,"Package is not installed"
end
if info.running.disabled then
return true
end
if info.enabledState > 0 then
return false,"Package should be activated"
end
local needed = false
for k,v in pairs(info.running.neededFor)
if v then
return false,"Package is needed"
end
end
return package.disable(name)
end
function package.save()
local sav = table.copy(packList)
for name,info in pairs(sav)
info.running = nil
end
writeFile("/apps/installed.cfg",sav)
end
function package.init()
print("Load packages ...")
for name,info in pairs(packList) do
if info.enabledState > 0 then
local ok,err = package.enable(name)
print(" "..name..((not ok and " could not be enabled: "..err) or " enabled"))
end
end
end
function package.runtime()
end
return package | 1a28e5304d8f17b255aab15089556efcd67f17b6 | [
"Lua"
] | 4 | Lua | Zocker1999NET/ocZockerOS | 98277f549d162a9d55e389393782b620ee1d8f5a | 9cb3b45244dd76457cb621d78cc2ff6d8c3b0a2e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.