language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Shell
UTF-8
1,400
2.734375
3
[]
no_license
#!/bin/sh -f # qsub STAR_2pass.pbs #PBS -l nodes=1:ppn=20 ##PBS -l pmem=1gb #PBS -A open #PBS -l walltime=23:50:00 #PBS -j oe #PBS -o STAR_2pass.out #PBS -N STAR_2pass #PBS -M juc326@psu.edu #PBS -m abe ####################################### module load gcc/5.3.1 samtools/0.1.19 bedtools/2.26.0 export PATH=~/work/STAR-2.5/bin/Linux_x86_64:$PATH export PATH=~/work/subread-1.5.3-Linux-x86_64/bin:$PATH cd $PBS_O_WORKDIR # STAR make genome index STAR --runThreadN 20 --runMode genomeGenerate --genomeDir ~/work/STAR.idx --genomeFastaFiles ~/work/Zea_mays.AGPv4.fa --sjdbGTFfile ~/work/Zea_mays.AGPv4.32.gtf --sjdbOverhang 49 for DIR in */ ; do cd "$DIR" # first alignment STAR --runThreadN 20 --genomeDir ~/work/STAR.idx --readFilesIn data.fa --outSAMtype BAM SortedByCoordinate mkdir idx # generate new genome index using splice junction information STAR --runThreadN 20 --runMode genomeGenerate --genomeDir idx/STAR-2pass.idx --genomeFastaFiles ~/work/Zea_mays.AGPv4.fa --sjdbFileChrStarEnd SJ.out.tab --sideOverhang 49 # 2nd alignment STAR --runThreadN 20 --genomeDir idx/STAR-2pass.idx --readFilesIn data.fa --outSAMtype BAM SortedByCoordinate cd ../ done featureCounts -T 20 -t exon -g gene_id -a ../Zea_mays.AGPv4.32.gtf -o Counts_exon_geneESW.txt */Aligned.sortedByCoord.out.bam ####################################### echo "Job Started" echo "Job Ended"
JavaScript
UTF-8
8,342
2.609375
3
[]
no_license
//alert("math") function math_fun(visual){ switch(visual){ case 1: clear(view); test_display(); scale_() stair_step() math_ksur() math_ttva() math_test() break; case 2: clear(view); test_display(); scale_() stair_step_w() math_ttva_w() math_test() break;} } function math(visual){ switch(visual){ case 1: data_stair() display_visible("main"); math_fun(count_math_fun) break; case 2: math_fun(count_math_fun) if (visual_VAR=="count_vis_ttva"){//тетева и размеры if (count_vis_ttva == 1) { document.getElementById("sizettva").style["background"] = 'red'; visual_ttva=1// отображение элемента лестницы. visual_stair_step=0 // отображение элемента лестницы. visual_ksur=0// отображение элемента лестницы. math_fun(count_math_fun) size_ttva(count_math_fun); }; if (count_vis_ttva == 2) { visual_sizeElem()// показываем исходное состояние кнопок sizeElem math_fun(count_math_fun) }; }; // end if visual_VAR if (visual_VAR=="count_vis_ksur"){// ksur и размеры if (count_vis_ksur == 1) { document.getElementById("sizeksur").style["background"] = 'red'; visual_ttva=0// отображение элемента лестницы. visual_stair_step=0 // отображение элемента лестницы. visual_ksur=1// отображение элемента лестницы. math_fun(count_math_fun) size_ksur(count_math_fun); }; if (count_vis_ksur == 2) { visual_sizeElem()// показываем исходное состояние кнопок sizeElem math_fun(count_math_fun) }; }; // end if visual_VAR if (visual_VAR=="count_vis_stair_step"){// ksur и размеры if (count_vis_stair_step == 1) { document.getElementById("sizeStairStep").style["background"] = 'red'; visual_ttva=0// отображение элемента лестницы. visual_stair_step=1 // отображение элемента лестницы. visual_ksur=0// отображение элемента лестницы. math_fun(count_math_fun) size_stair_step(count_math_fun); }; if (count_vis_stair_step == 2) { visual_sizeElem()// показываем исходное состояние кнопок sizeElem math_fun(count_math_fun) }; }; // end if visual_VAR break; case 3: display_visible("staircad"); break; }//end switch } //end function math function stair_step(){ // расчёт ступеней и подступёнков test_work ("test5",0) step_style=0; // коррекция размера ступени substep_style=0;// коррекция размера подступёнка if (stepstyle == "step") { substep_style = data.width;}// первичные данные стыка ступени step = []; // объявляем массив ступени pod_step = []; // объявляем массив подступёнка for(i=0; i<data.number; i++){ if (stepstyle == "step" && i==data.number-1) {substep_style = 0;} //вторичные данные стыка ступени if (stepstyle == "sub_step" && i==1) {step_style = data.width2;} step[i] = { start_x: x1-step_style*scale, start_y: y1, finish_x: (data.lenght+step_style +data.going ) *scale, finish_y: data.width*scale, } x1 = x1 + data.lenght*scale; pod_step[i] = { start_x: x1-data.width2*scale, start_y: y1+data.width*scale, finish_x: data.width2*scale, finish_y: (data.height+substep_style) *scale, } y1 = y1 + (data.width+data.height)*scale; // if(stepstyle2 == "step" ){y2 = y2 - data.width*scale} } // end for max_x = x1// край по ступени max_y = y1// низ по подсупёнку test_work("test3", "max x:<b>"+ parseInt(max_x) ); test_work("test3.1","max y:<b>"+ parseInt(max_y) ); test_work("test2",0); test_work ("test5",1) count_stair_step++ test_work ("test5.1",'запуск:'+ count_stair_step ); if (visual_stair_step == 1) {stair_step_drow()};// условие функции отрисовки } // end stair_step() function math_ttva(){//расчёт тетевы // срезы концов тетевы:расчёт верен ttva_cutX = cut (ksur_g[1].ax,ksur_g[1].ay, ksur_g[1].dx,ksur_g[1].dy,data.s_ksur,data.s_ttva); ttva_cutY = cut ( ksur_v[0].cx,ksur_v[0].cy, ksur_v[0].dx,ksur_v[0].dy,data.s_ksur,data.s_ttva); ttva = { ax: step[0].start_x, ay: pod_step[0].start_y + triangle_alfa(data.width2, data.lenght, data.height+data.width) *scale,// triangle_alfa (min_a,max_a,max_b) bx: max_x - (data.width2*scale) - triangle_alfa (data.width, data.height + data.width , data.lenght )*scale, by: max_y, } ttva_back = {//отрисовка обратной стороны тетевы cx: ttva.bx - ttva_cutX*scale, cy: max_y, dx: ttva.ax, dy: ttva.ay + ttva_cutY*scale, }; test_work("ttvaCut", (parseInt(ttva_cutX*10))/10); test_work("ttvaCut.2", (parseInt(ttva_cutY*10))/10); test_work("ttvaDrow",0); test_work("ttva_bx", (parseInt(ttva.bx*10))/10 ); contrPoint() if (visual_ttva == 1) {ttva_drow()};// условие функции отрисовки } // end function math_ttva() function math_control_ttva(){//контрольная линия для тетевы control_ttva = { // линия соприкосновения тетевы и косоура ax: step[0].start_x-(data.width2*scale), ay: pod_step[0].start_y,// triangle_alfa (min_a,max_a,max_b) bx: max_x-(data.width2*scale), by: max_y+(data.width*scale), } // test_work("CttvaDrow",0); control_ttva_drow(count_math_fun) } // end function math_ttva() function math_ksur(){ // расчёт ступеней и подступёнков //test_work ("mathKsur",0) ksur_g_start=0; // коррекция размера первой ступени substep_style=0;// коррекция размера подступёнка ksur_g = []; // объявляем массив горизонтального косоура ksur_v = []; // объявляем массив вертикального косоура fase_ksur_g = triangle_alfa (data.s_ksur ,data.height+data.width, data.lenght );//срез подступёнка косоура fase_ksur_v = triangle_alfa (data.s_ksur , data.lenght,data.height+data.width);//срез подступёнка косоура for(i=0; i<data.number; i++){ if (i > 0) { ksur_g_start= data.width2;} //условие для первой ступени косоура ksur_g[i] = { ax: x2-ksur_g_start*scale, bx: pod_step[i].start_x, cx: pod_step[i].start_x, dx: x2-data.width2*scale + fase_ksur_g*scale, ay: y2+data.width*scale, by: y2+data.width*scale, cy: y2+ (data.width+data.s_ksur) *scale, dy: y2+ (data.width+data.s_ksur) *scale, } x2 = x2 + data.lenght*scale; ksur_v[i] = { ax: x2- (data.width2+data.s_ksur) *scale, bx: pod_step[i].start_x, cx: pod_step[i].start_x, dx: x2- (data.width2+data.s_ksur) *scale, ay: y2+ (data.width+data.s_ksur) *scale, by: y2+ (data.width+data.s_ksur) *scale, cy: y2+data.width*scale+(data.width+data.height)*scale, dy: y2+data.width*scale -fase_ksur_v*scale+(data.width+data.height)*scale, };//ksur_v y2 = y2 + (data.width+data.height)* scale; } // end for i=i-1; if(i<0){i=0}; // дебаг для значения 1 ступень max_x = x1// край по ступени max_y = y1// низ по подсупёнку // ttva.bx: ksur_ttva_down = max_x - (data.width2*scale) - triangle_alfa (data.width, data.height + data.width , data.lenght )*scale;// точка ttva.bx // ttva.a - промежуточная точка верхнего гор.косоура ksur_dax = data.x - navGNum; ksur_day = data.y -navVNum+data.width*scale+triangle_alfa(data.width2, data.lenght, data.height+data.width) *scale; test_work("ksur_v_dx", (parseInt(ksur_v[i].dx*10))/10 ); test_work("ksur_drow",0); ksur_cutY = triangle_alfa (ksur_ttva_down - ksur_v[i].dx , data.lenght,data.height+data.width); // высота среза нижнего косоура по Y if (visual_ksur == 1) {ksur_drow()};// условие функции отрисовки } // end stair_step() function math_grid(){ for(i=0; i<360; i++){ //координатная сетка } grid_drow() }
C++
UTF-8
541
3
3
[ "MIT" ]
permissive
//向量vector #include"iostream" #include"vector" using namespace std; int main() { vector<int>v1,v2; int a[]={1949,10,1},i; vector<int>::iterator It; v1.assign(a,a+3); v2.assign(3,10); for(i=1;i<=5;i++) v1.push_back(i); v1.pop_back(); v1.front()-=v1.back(); for(It=v1.begin();It<v1.end();It++) v2.push_back(*It); v2.insert(v2.begin(),2,300); v2.erase(v2.begin()+5); cout<<"v1="; for(i=0;i<v1.size();i++) cout<<v1[i]<<" "; cout<<endl; cout<<"v2="; for(i=0;i<v2.size();i++) cout<<v2[i]<<" "; cout<<endl; return 0; }
C++
UTF-8
624
3.234375
3
[]
no_license
#ifndef __TOOLARGEARGUMENT_HPP__ #define __TOOLARGEARGUMENT_HPP__ #include "BaseInclude.hpp" class TooLargeArgumentException : public std::exception { std::string msg_; public: TooLargeArgumentException(const size_t &pos, const size_t &val, const size_t &max_val) { this->msg_ = "Format value (" + std::to_string(val) + ") at position " + std::to_string(pos) + " is larger or equal to number of arguments (" + std::to_string(max_val) + ")"; } virtual const char *what() const noexcept override { return msg_.c_str(); } }; #endif // __TOOLARGEARGUMENT_HPP__
C++
GB18030
801
2.53125
3
[]
no_license
#ifndef SDL_COMMONINCLUDE_H #define SDL_COMMONINCLUDE_H #define _SDL_DEBUG #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <string> using std::string; //ͷļ #ifdef _SDL_DEBUG #include <iostream> using std::cout; using std::endl; #endif //ͨñ extern int SCREEN_WIDTH; extern int SCREEN_HEIGHT; const int MAP_WIDTH = 1600; const int MAP_HEIGHT = 800; //ͨú /**ײ *const SDL_Rect& Cbject :壻 *const SDL_Rect& Area : *bool Border :Ƿֻ߿ʱײ *ֵ :⵽ײtrue򷵻false *Ա :Ѳԣ */ bool CheckCollision(const SDL_Rect& Object, const SDL_Rect& Area,bool Border = false); #endif
C#
UTF-8
543
2.640625
3
[ "Apache-2.0" ]
permissive
namespace Pims.Api.Mapping.Converters { /// <summary> /// ParcelConverter static class, provides converters for parcels. /// </summary> public static class ParcelConverter { /// <summary> /// Convert the formatted PID string into a number. /// </summary> /// <param name="pid"></param> /// <returns></returns> public static int ConvertPID(string pid) { int.TryParse(pid?.Replace("-", "") ?? "", out int value); return value; } } }
Java
UTF-8
1,047
2.640625
3
[]
no_license
package com.worldtechq.blog.Helper; import com.google.firebase.database.Exclude; public class Upload { private String mname; private String murl; //create variable to access the database unique key for image. private String mkey; public Upload() { //empty constructor needed } public Upload(String iname, String imurl) { //to set the name and image url if (iname.trim().equals("")) { iname = "no name"; } mname = iname; murl = imurl; } //gtter setter methods //to get the private variable in another activity public String getMname() { return mname; } //to set its attribute public void setMname(String mname) { this.mname = mname; } public String getMurl() { return murl; } public void setMurl(String murl) { this.murl = murl; } @Exclude public String getkey() { return mkey; } public void setkey(String key) { this.mkey = key; } }
C
UTF-8
1,372
4.09375
4
[]
no_license
#include <stdio.h> #include "pilha.h" /*Função para criar uma pilha!*/ Pilha* create_stack (int tam) { Pilha *p = (Pilha *)malloc(sizeof(Pilha)); p->topo = 0; p->tam = tam; p->vetor = (int *)malloc(tam * sizeof(int)); return p; } /* Função para inverter uma pilha */ Pilha* reverse_stack (Pilha *original) { Pilha *reverse = create_stack (original->tam); int aux; while (!empty_stack(original)) { push (reverse, pop (original) ); } destroy_stack (original); return reverse; } /*Função para empilhar um elemento!*/ void push (Pilha *p, int elem) { if (full_stack(p)) { printf ("Pilha cheia\n"); exit(1); } p->vetor[p->topo] = elem; p->topo++; } /*Função para desempilhar um elemento!*/ int pop (Pilha *p) { if (empty_stack(p)) { printf ("Pilha vazia\n"); exit(1); } p->topo--; return p->vetor[p->topo]; } /*Funão para testar se a pilha está vazia!*/ int empty_stack (Pilha *p) { return (p->topo == 0); } /*Funão para imprimir uma pilha */ void print_stack(Pilha *p) { int i; for (i = p->topo - 1; i >= 0; i--) printf("%d ", p->vetor[i]); } /*Funão para testar se a pilha está cheia!*/ int full_stack (Pilha *p) { return (p->topo == p->tam); } /*Função para liberar a memória alocada.*/ void destroy_stack (Pilha *p) { free(p->vetor); free(p); }
Java
UTF-8
151
1.804688
2
[]
no_license
package com.demo.osl.rick.Bean; public class MainMessage extends EventBean { public MainMessage(String message) { super(message); } }
C
UTF-8
2,233
3.09375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap_best_pos.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ikhadem <ikhadem@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/17 15:48:10 by ikhadem #+# #+# */ /* Updated: 2021/09/17 15:59:28 by ikhadem ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" static int count_ops(int a, int b) { if (a * b > 0) return (ft_math_max(ft_math_abs(a), ft_math_abs(b))); else return (ft_math_abs(a) + ft_math_abs(b)); } static int find_place(t_stack **a, int x) { int i; int max_val_pos; int size; i = 0; size = t_stack_size(*a); while (i < size) { if (x < t_stack_index(*a, i) && x > t_stack_index(*a, i - 1)) return (i); if (x > t_stack_index(*a, -i) && x < t_stack_index(*a, -i + 1)) return (-i + 1); i++; } max_val_pos = t_stack_index_of(*a, t_stack_max(*a)) + 1; if (max_val_pos == size) max_val_pos = 0; if (max_val_pos > size - max_val_pos) max_val_pos = -(size - max_val_pos); return (max_val_pos); } static void set_value(int *res, int val1, int val2) { res[0] = val1; res[1] = val2; } int *find_best(t_stack **a, t_stack **b) { t_stack *iter; int i; static int res[2]; int tmp; i = 0; iter = *b; set_value(res, -t_stack_size(*a), t_stack_size(*b)); while (iter) { if (count_ops(i, 0) >= count_ops(res[0], res[1])) break ; tmp = find_place(a, t_stack_index(*b, i)); if (count_ops(tmp, i) < count_ops(res[0], res[1])) set_value(res, tmp, i); tmp = find_place(a, t_stack_index(*b, -i)); if (count_ops(tmp, -i) < count_ops(res[0], res[1])) set_value(res, tmp, -i); i++; iter = iter->next; } return (res); }
C#
UTF-8
424
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace tut2 { public class ActualParkType { private int _myType; public int MyType { get => default(int); set { } } public int ShowType() { return Convert.ToInt16(MyType); } } }
Java
UTF-8
1,177
2.21875
2
[]
no_license
package com.switchfully.orderfromscratch.api; import com.switchfully.orderfromscratch.service.CustomerService; import com.switchfully.orderfromscratch.service.dto.GetCustomerDto; import com.switchfully.orderfromscratch.service.dto.CustomerDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(path="/customers") public class CustomerController { private CustomerService customerService; @Autowired public CustomerController(CustomerService customerService) { this.customerService = customerService; } @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) public void createCustomer(@RequestBody CustomerDto customerDto){ customerService.createCustomer(customerDto); } @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<GetCustomerDto> getAllCustomers(){ return customerService.getAllCustomers(); } }
Markdown
UTF-8
9,084
2.9375
3
[]
no_license
# restful-api-examples Examples of how to make RESTful API calls and create server-side web API's from Debian-based systems using different languages and bindings. These examples and files aren't necesserily exclusive to Debian-based systems, but the aptitude (apt) packaging system is. In order to install some of these libraries, you need to obtain the software in some other way. ## Index * [Basic GET API Clients](#basic-get-api-clients) * [Basic GET API Servers](#basic-get-api-servers) ## Introduction A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. (http://searchcloudstorage.techtarget.com/definition/RESTful-API) The following are examples of how to make the API's and API requests. A great tool for testing to see if you are making requests correctly is to use: https://httpbin.org A great list of public API's can be found here: https://github.com/toddmotto/public-apis Especially in web development, the ideal way to make a RESTful API request is to d it from the backend using something other than JavaScript. The reason for this is you can't always make a request from the browser because CORS headers are required. Better to use a backend technology such as shell, Python, Ruby, or something else. ## Basic GET API Clients The GET method is probably the easiest HTTP method to work with. The following will use the ipify API that simply gives you back your public IP address. Later on we will use some different and unique API's to experiment with. ### Shell `curl` is the command to make requests from the Linux shell. To get your current public IP address, do: ``` #!/bin/bash ip=$(curl -s https://api.ipify.org) echo "My public IP address is: $ip" ``` Here is an API request that gives back JSON objects full of information on Studio Ghibli films: ``` curl -X GET -H "Content-Type: application/json" https://ghibliapi.herokuapp.com/films ``` If for some reason `curl` is not installed, you can perform `apt-get install curl` to download and install it. ### Python You can make API request sin Python using the `requests` module. ``` from requests import get ip = get('https://api.ipify.org').text print('My public IP address is: {}'.format(ip)) ``` If the requests library is not installed, the you can download and install it with `apt-get install python-requests` ### Ruby Ruby has API requests built in! ``` require "net/http" ip = Net::HTTP.get(URI("https://api.ipify.org")) puts "My public IP Address is: " + ip ``` You can also use the `rest-client` library by using `apt-get install ruby-rest-client` and do this: ``` require 'rest-client' response = RestClient.get 'https://api.ipify.org' puts 'My public IP Address is: ' + response ``` For more information and examples for `rest`client`, visit: https://github.com/rest-client/rest-client ### PHP To perform a GET request, you can use the `file_get_contents()` function ``` <?php $ip = file_get_contents('https://api.ipify.org'); echo "My public IP address is: " . $ip; ?> ``` PHP is usualy ran via website actions, but you can execute this script via `php php_api_client.php` from the terminal. ### Node.js In the terminal, run `node node_api_client.js` or `nodejs node_api_client.js` ``` var http = require('http'); http.get({'host': 'api.ipify.org', 'port': 80, 'path': '/'}, function(resp) { resp.on('data', function(ip) { console.log("My public IP address is: " + ip); }); }); ``` ### Java ``` try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("https://api.ipify.org").openStream(), "UTF-8").useDelimiter("\\A")) { System.out.println("My current IP address is " + s.next()); } catch (java.io.IOException e) { e.printStackTrace(); } ``` ### Perl Perl also has API requests built in! ``` use strict; use warnings; use LWP::UserAgent; my $ua = new LWP::UserAgent(); my $ip = $ua->get('https://api.ipify.org')->content; print 'My public IP address is: '. $ip; ``` ### Lua In order to do API requests, some libraries will need to be installed. The `lua-socket` library can be used: ``` http = require "socket.http" r, c, h, s = http.request("http://api.ipify.org") print('My public IP address is: ' .. r) ``` But this only supports HTTP requests, not SSL/HTTPS. To install `lua-socket`, perform an `apt-get install lua-socket` For HTTPS requests, you can use the `lua-sec` package and do something like this: ``` require("socket") local https = require("ssl.https") local body, code, headers, status = https.request("https://www.google.com") print(status) ``` Install LuaSec with `apt-get install lua-sec`. ### C# Networking is bult into the .NET framework. The code below was ran using version 4.7 .NET which supports language versions up to C# 5. ``` // C#_API_Client.cs using System; using System.Net; namespace Ipify.Examples { class Program { public static void Main (string[] args) { WebClient webClient = new WebClient(); string publicIp = webClient.DownloadString("https://api.ipify.org"); Console.WriteLine("My public IP Address is: {0}", publicIp); } } } ``` Compile via: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe C#_API_Client.cs` which will create a .exe program. ### Windows PowerShell REST API networking is also built into PowerShell ``` $ip = Invoke-RestMethod -Uri 'https://api.ipify.org?format=json' "My public IP address is: $($ip.ip)" ``` ## Basic GET API Servers We make API requests to get information that would otherwise be difficult to get ourselves. With that said, if you were to look at the server API code, it could get complicated really quick. But theoretically, getting a simple API server set up is really quite easy, it just depends on what you are doing. The following will show you how to send back a string of text when it is requested from a client. I'll show you a PHP version of this first since it is super simple. THIS IS IMPORTANT!!!A lot of this actually depends on the framework you are using. With PHP you can just put PHP files in the `/var/www/html/` directory to get it to run, but in order for other server-side scripts to run, they may need to be placed in the `/usr/lib/cgi-bin/` in order to execute. If that directory is not available, you can do the following to perform cgi-requests(assuming you have root access): ``` a2enmod cgi service apache2 restart ``` You must also give your server-side scripts execution rights with the following: `chmod +x whatever_the_name_of_the_server_script_is.file_name`. Then, you can access run the script via: `http://localhost/cgi-bin/whatever_the_name_of_the_server_script_is.file_name`. It is also importany to note that you don't need a special client to access these server-based API's. You can just use your web browser and type the URL. ### PHP Our simple PHP script can look like this stored in the `/var/www/html/` directory with the filename `php_api_server.php`: ``` <?php echo 'Hello from the server!'; ?> ``` then if we have a Python client like this calling the PHP server script ``` # This example requires the requests library be installed. You can learn more # about the Requests library here: http://docs.python-requests.org/en/latest/ from requests import get message = get('http://localhost/php_api_server.php').text print('The server says: {}'.format(message)) ``` It should give us back: `The server says: Hello from the server!` You could also place that PHP server script in the `/usr/lib/cgi-bin/` (which is actually preffered) and navigate the request to `http://localhost/cgi-bin/php_api_server.php`. ### Python Server-side Python script: ``` #!/usr/bin/python print('Content-type: text/html\n') print('Hello from the server!') ``` - Make sure to include the first line: `#!/usr/bin/python` - Make sure you have this line: `print('Content-type: text/html\n')` - Place it in the `/usr/lib/cgi-bin/` directory - Give it execution rights with `chmod +x python_api_server.py` Ruby client-side script: ``` require "net/http" message = Net::HTTP.get(URI("http://localhost/cgi-bin/python_api_server.py")) puts "The server says: " + message ``` Should give you the message: `The server says: Hello from the server!` ### Perl Server-side script: ``` #!/usr/bin/perl print "Content-type: text/html\n\n"; print "Hello from the server!"; ``` - Make sure to include the first line: `#!/usr/bin/perl` - Make sure you have this line: `print "Content-type: text/html\n\n";` - Place it in the `/usr/lib/cgi-bin/` directory - Give it execution rights with `chmod +x perl_api_server.py` Lua client-side script: ``` http = require "socket.http" r, c, h, s = http.request("http://localhost/cgi-bin/perl_api_server.pl") print('The server says: ' .. r) ``` Should give you the message: `The server says: Hello from the server!` I think you get the general idea. Depending on what kind of data the client is expecting to receive back from the server, the content type needs to be specified. In the previous examples we are just sending back plain text, but other popular types of data are JSON, XML, and more!
Java
UTF-8
1,255
2.1875
2
[]
no_license
package com.zhifeng.cattle.adapters; import android.content.Context; import android.widget.ImageView; import com.lgh.huanglib.util.config.GlideUtil; import com.zhifeng.cattle.R; import com.zhifeng.cattle.modules.OrderListDto; /** * * @ClassName: 退货列表商品适配器 * @Description: * @Author: lgh * @CreateDate: 2019/9/12 9:32 * @Version: 1.0 */ public class SalesReturnGoodsAdapter extends BaseRecyclerAdapter<OrderListDto.DataBean.GoodsBean> { Context context; public SalesReturnGoodsAdapter(Context context) { super(R.layout.layout_item_sales_return_goods); this.context = context; } @Override protected void onBindViewHolder(SmartViewHolder holder, OrderListDto.DataBean.GoodsBean model, int position) { holder.setIsRecyclable(false); holder.text(R.id.tv_item_sales_return_name,model.getGoods_name());//商品名称 holder.text(R.id.tv_item_sales_return_spec,model.getSpec_key_name());//商品规格 holder.text(R.id.tv_item_sales_return_num,"×"+model.getGoods_num());//商品数量 ImageView img = holder.itemView.findViewById(R.id.iv_item_sales_return_img); GlideUtil.setImage(context,model.getImg(),img); } }
C
UTF-8
10,616
3.28125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <memory.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #include <sys/times.h> #define CLK sysconf(_SC_CLK_TCK) void generate(FILE **file1, size_t size, size_t nmemb) { // size - size of records, nmemb - number of records if((*file1) == NULL) { puts("File not opened propetly to generate data into"); exit(EXIT_FAILURE); } FILE *file2 = fopen("/dev/random","r"); if(file2 == NULL) { puts("Couldn't open /dev/random file"); exit(EXIT_FAILURE); } void *ptr = malloc(size); // points to the place where data will be stored; size, because we need the size-of-records-wide memory cells for(int i=0;i<nmemb;++i) { size_t readRandomRecordsNumber = fread(ptr, size, 1, file2); if(readRandomRecordsNumber != 1) { puts("Couldn't read the data from /dev/random file"); exit(EXIT_FAILURE); } size_t savedRecordsNumber = fwrite(ptr,size,1,*file1); //fwrite returns the number of records created if(savedRecordsNumber != 1) { puts("Couldn't generate data to file"); exit(EXIT_FAILURE); } } free(ptr); } void printFile(FILE *file1, size_t size, size_t nmemb) { void *ptr = malloc(size*nmemb); fseek(file1,0,SEEK_SET); // going back to the beggining of the file size_t readRecords = fread(ptr,size,nmemb,file1); if(readRecords != nmemb) { puts("Cannot read from file in print function"); exit(EXIT_FAILURE); } unsigned char* start = (unsigned char*) ptr; printf("\n\nWhole file: %s\n",start); for(int i=0;i<nmemb;++i) { printf("\n%d. Block of code: ",i+1); for(int j=0;j<size;++j) { printf(" [%x] ",start[j]); } start+=size; } free(ptr); } void shufflesys(int fd, size_t size, size_t nmemb) { void *ptr = malloc(size); void *qtr = malloc(size); int n = (int) nmemb; for(int i=n-1;i>=1;--i) { lseek(fd,i*size,SEEK_SET); ssize_t bytesRead = read(fd,ptr,size); if(bytesRead != size) { puts("Failed to read data in shufflesys (i)"); exit(EXIT_FAILURE); } int j = rand()%(i+1); // 0 <= j <= i lseek(fd,j*size,SEEK_SET); bytesRead = read(fd,qtr,size); if(bytesRead != size) { puts("Failed to read data in shufflesys (j)"); exit(EXIT_FAILURE); } lseek(fd,j*size,SEEK_SET); ssize_t bytesWrite = write(fd,ptr,size); if(bytesWrite != size) { puts("Failed to save data in shufflesys (i)"); exit(EXIT_FAILURE); } lseek(fd,i*size,SEEK_SET); bytesWrite = write(fd,qtr,size); if(bytesWrite != size) { puts("Failed to save data in shufflesys (i)"); exit(EXIT_FAILURE); } } free(ptr); free(qtr); } void shufflelib(FILE **file1, size_t size, size_t nmemb) { void *ptr = malloc(size); void *qtr = malloc(size); int n = (int) nmemb; for(int i=n-1;i>=1;--i) { fseek(*file1,i*size,SEEK_SET); //going to i record in the file size_t readRecord = fread(ptr,size,1,*file1); if(readRecord != 1 ) { puts("Failed to read data in shufflelib (i)"); exit(EXIT_FAILURE); } int j = rand()%(i+1); // 0 <= j <= i fseek(*file1,j*size,SEEK_SET); //going to j record in the file readRecord = fread(qtr,size,1,*file1); if(readRecord != 1) { puts("Failed to read data in shufflelib (j)"); exit(EXIT_FAILURE); } fseek(*file1,size*j,SEEK_SET); size_t recordWriten = fwrite(ptr,size,1,*file1); if(recordWriten != 1) { puts("Failed to save data in shufflelib (i)"); } fseek(*file1,size*i,SEEK_SET); recordWriten = fwrite(qtr,size,1,*file1); if(recordWriten != 1) { puts("Failed to save data in shufflelib (j)"); } } free(ptr); free(qtr); } void sortlib(FILE **file1, size_t size, size_t nmemb) { void *ptr = malloc(size); void *qtr = malloc(size); int n = (int) nmemb; for(int i=n;i>1;--i) { for(int j=0;j<n-1;++j) { fseek(*file1,j*size,SEEK_SET); size_t recordRead = fread(ptr,size,1,*file1); if(recordRead != 1){ puts("Failed to read data in sortlib (1)"); exit(EXIT_FAILURE); } fseek(*file1,(j+1)*size,SEEK_SET); recordRead = fread(qtr,size,1,*file1); if(recordRead != 1) { puts("Failed to read data in sortlib (2)"); exit(EXIT_FAILURE); } unsigned char* a = (unsigned char*) ptr; unsigned char* b = (unsigned char*) qtr; if(a[0] > b[0]) { // then swap fseek(*file1,size*j,SEEK_SET); size_t recordWriten = fwrite(qtr,size,1,*file1); if(recordWriten != 1) { puts("Failed to save data in sortlib (1)"); exit(EXIT_FAILURE); } fseek(*file1,size*(j+1),SEEK_SET); recordWriten = fwrite(ptr,size,1,*file1); if(recordWriten != 1) { puts("Failed to save data in sortlib (2)"); exit(EXIT_FAILURE); } } } } free(ptr); free(qtr); } void sortsys(int fd, size_t size, size_t nmemb) { void *ptr = malloc(size); void *qtr = malloc(size); int n = (int) nmemb; for(int i=n;i>1;--i) { for(int j=0;j<n-1;++j) { lseek(fd,j*size,SEEK_SET); ssize_t bytesRead = read(fd,ptr,size); if(bytesRead != size){ puts("Failed to read data in sortsys (1)"); exit(EXIT_FAILURE); } lseek(fd,(j+1)*size,SEEK_SET); bytesRead = read(fd,qtr,size); if(bytesRead != size) { puts("Failed to read data in sortsys (2)"); exit(EXIT_FAILURE); } unsigned char* a = (unsigned char*) ptr; unsigned char* b = (unsigned char*) qtr; if(a[0] > b[0]) { // then swap lseek(fd,size*j,SEEK_SET); ssize_t bytesWriten = write(fd,qtr,size); if(bytesWriten != size) { puts("Failed to save data in sortsys (1)"); exit(EXIT_FAILURE); } lseek(fd,size*(j+1),SEEK_SET); bytesWriten = write(fd,ptr,size); if(bytesWriten != size) { puts("Failed to save data in sortsys (2)"); exit(EXIT_FAILURE); } } } } free(ptr); free(qtr); } typedef struct timeStruct { double r; // real double u; // user double s; // system } timeStruct; void loadTimes(struct timeStruct **time1) { if((*time1) == NULL) { (*time1) = malloc(sizeof(timeStruct)); } struct tms userSystemTimeStruct; times(&userSystemTimeStruct); // struct loaded; (*time1)->s = (double)userSystemTimeStruct.tms_stime / CLK; (*time1)->u = (double)userSystemTimeStruct.tms_utime / CLK; (*time1)->r = (double)clock() / CLOCKS_PER_SEC; } void printTimes(char* title, struct timeStruct *prevTime, struct timeStruct *afterTime) { double real = afterTime->r - prevTime->r; double user = afterTime->u - prevTime->u; double system = afterTime->s - prevTime->s; printf("\n%s \nReal: \t\t User: \t\t System:\n", title); printf("%lf \t %lf \t %lf\n",real,user,system); } int stoi(char *s) { int res = 0; int n; for(n=0;s[n]!='\0';++n); for(int i=n-1,multiplier=1;i>=0;--i) { res += (s[i]-48)*multiplier; multiplier*=10; } return res; } int main(int argc, char **argv) { if(argc == 5 && strcmp(argv[1],"generate") == 0) { FILE *file1 = fopen(argv[2],"rw+"); if(file1 == NULL) { puts("Couldn't create/open file to generate"); exit(EXIT_FAILURE); } generate(&file1,(size_t)(stoi(argv[4])),(size_t)(stoi(argv[3]))); puts("Generated file with random data"); fclose(file1); exit(EXIT_SUCCESS); } if(argc != 5 && argc !=6) { puts("Wrong number of parameters"); exit(EXIT_FAILURE); } char* type = argv[1]; char* operation = argv[2]; char* filePath = argv[3]; char* recordSize = argv[5]; char* recordNumber = argv[4]; int _size = stoi(recordSize); int _nmemb = stoi(recordNumber); size_t size = (size_t) _size; size_t nmemb = (size_t) _nmemb; struct timeStruct* prevTime = NULL; struct timeStruct* afterTime = NULL; if(strcmp(type,"sys") == 0) { int fd = open(filePath,O_RDWR); if(fd<0) { puts("Couldn't open file in sys mode"); exit(EXIT_FAILURE); } if(strcmp(operation,"shuffle")==0) { loadTimes(&prevTime); shufflesys(fd,size,nmemb); loadTimes(&afterTime); printTimes("Sys functions shuffle time:",prevTime,afterTime); } else if (strcmp(operation, "sort") == 0) { loadTimes(&prevTime); sortsys(fd,size,nmemb); loadTimes(&afterTime); printTimes("Sys functions sort time:",prevTime,afterTime); } else { puts("Wrong parameters. (eg. ./program sys shuffle datafile 100 512"); } close(fd); } else if (strcmp(type,"lib") == 0) { FILE *file1 = fopen(filePath, "rw+"); // w+ - read and write + create/wipe out the file if(file1 == NULL) { puts("Couldn't open file in lib mode"); exit(EXIT_FAILURE); } if(strcmp(operation,"shuffle")==0) { loadTimes(&prevTime); shufflelib(&file1,size,nmemb); loadTimes(&afterTime); printTimes("Lib functions shuffle time:",prevTime,afterTime); } else if(strcmp(operation,"sort") == 0) { loadTimes(&prevTime); sortlib(&file1,size,nmemb); loadTimes(&afterTime); printTimes("Lib functions sort time:",prevTime,afterTime); } else { puts("Wrong parameters. (eg. ./program sys shuffle datafile 100 512"); } fclose(file1); } return 0; }
C++
UTF-8
2,128
3.453125
3
[]
no_license
#include <iostream> #include <string> #include <memory> #include <vector> #include <sstream> #include <cmath> #include <math.h> #include <iomanip> using namespace std; class Figure { public: virtual double Perimeter() const = 0; virtual double Area() const = 0; virtual string Name() const = 0; }; class Rect : public Figure { public: explicit Rect(istringstream & par) { par >> width_ >> height_; } string Name() const override { return "RECT"; } double Perimeter() const override { return width_ * 2 + height_ * 2; } double Area() const override { return width_ * height_; } private: double width_{}, height_{}; }; class Circle : public Figure { public: explicit Circle(istringstream & par) { par >> r; } string Name() const override { return "CIRCLE"; } double Perimeter() const override { return 2 * 3.14 * r; } double Area() const override { return 3.14 * r * r; } private: double r{}; }; class Triangle : public Figure { public: explicit Triangle(istringstream & par) { par >> a >> b >> c; } string Name() const override { return "TRIANGLE"; } double Perimeter() const override { return a + b + c; } double Area() const override { double s = (a + b + c) / 2; return sqrt(s * (s - a) * (s - b) * (s - c)); } private: double a{}, b{}, c{}; }; shared_ptr<Figure> CreateFigure(istringstream & is) { shared_ptr<Figure> created; string type; is >> type; if (type == "RECT") { created = make_shared<Rect>(is); } else if (type == "TRIANGLE") { created = make_shared<Triangle>(is); } else { created = make_shared<Circle>(is); } return created; } int main() { vector<shared_ptr<Figure>> figures; for (string line; getline(cin, line); ) { istringstream is(line); string command; is >> command; if (command == "ADD") { is >> ws; figures.push_back(CreateFigure(is)); } else if (command == "PRINT") { for (const auto& current_figure : figures) { cout << fixed << setprecision(3) << current_figure->Name() << " " << current_figure->Perimeter() << " " << current_figure->Area() << endl; } } } return 0; }
Python
UTF-8
291
3.71875
4
[]
no_license
numberA = float(500) numberB = float(100) plus = numberA+numberB minus = numberA-numberB multiple = numberA*numberB divis = numberA/numberB print(numberA,"+",numberB,"=",plus) print(numberA,"-",numberB,"=",minus) print(numberA,"*",numberB,"=",multiple) print(numberA,"/",numberB,"=",divis)
JavaScript
UTF-8
1,299
3.1875
3
[]
no_license
const readline = require('readline'); const yargs = require('yargs'); const rl = readline.createInterface({ input : process.stdin, output : process.stdout, terminal:false }); const note = require('./note.js'); console.log("STARTING NOTE APP"); var argv = yargs.argv; rl.on('line',(data)=>{ if(data==='1' || data ==='add'|| data==='ADD'){ console.log('\nEnter your note\n'); addNote(); }else if(data==='2' || data ==='remove'|| data==='REMOVE'){ removeNote(); }else if(data==='3' || data ==='see'|| data==='SEE'|| data ==='see all notes'|| data ==='SEE ALL NOTES'){ seeNote(); }else if(data==='4' || data ==='exit'|| data==='EXIT'){ process.exit(); } }); const addNote = ()=>{ rl.question('\nPlease enter the title : ',(title)=>{ rl.question('\nPlease Enter your note : \n ',(body)=>{ note.add(title,body); }) }) } const removeNote =()=>{ rl.question('please enter the title of the note you want to remove\n', (title)=>{ note.remove(title); }); }; const seeNote = ()=>{ note.see(); }; rl.setPrompt('\nEnter your Query : \n 1.ADD NOTE\n 2.REMOVE NOTE\n 3.SEE ALL NOTES\n 4.EXIT\n') ; rl.prompt();
PHP
UTF-8
1,892
2.65625
3
[]
no_license
<?php class Mdelivery extends Models { public function __construct(){ parent::__construct(); } public function processDelivery( $dataProc ){ try { $stmt2 = $this->db()->prepare("CALL `_proses_delivery_apk_detail` ( ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $stmt2->execute( $dataProc ); }catch(PDOException $e) { $error = $e->getMessage(); }; } public function processDeliveryItem( $dataProc ){ try { $stmt2 = $this->db()->prepare("CALL `_proses_delivery_apk_detail_list` ( ?, ?, ?, ?, ? )"); $stmt2->execute( $dataProc ); }catch(PDOException $e) { $error = $e->getMessage(); }; } public function getColumnFilterUserDA( $type ){ $result = null; if( Mkey::isDriver( $type ) ){ $result = "nip_driver"; }else if( Mkey::isDriverAssistant( $type ) ){ $result = "nip_asisten_driver"; }; return $result; } public function getListDeliveryData( $nip, $type, $id = null ){ $data = null; $filterColumn = $this->getColumnFilterUserDA( $type ); if( $filterColumn != null ){ $selectStatement = $this->db() ->select() ->from( 'tv_trans_delivery' ) ->where( 'id_status', '=', 2 ) ->where( $filterColumn, '=', $nip ); $stmt = $selectStatement->execute(); $data = $stmt->fetchAll(); }; return $data; } public function getListDeliveryDetailData( $IDP_Delivery, $id = null ){ $selectStatement = $this->db() ->select() ->from( 'tv_trans_delivery_detail' ) ->where( 'idp_delivery', '=', $IDP_Delivery ); $stmt = $selectStatement->execute(); $data = $stmt->fetchAll(); return $data; } public function getListDeliveryItemData( $ID_Barang, $id = null ){ $selectStatement = $this->db() ->select() ->from( 'tv_trans_delivery_detail_list_android' ) ->where( 'id_barang', '=', $ID_Barang ); $stmt = $selectStatement->execute(); $data = $stmt->fetchAll(); return $data; } }
JavaScript
UTF-8
1,361
4
4
[]
no_license
class Walk { constructor(location, distance) { this.location = location; this.distance = distance; this.timestamp = new Date(); } display(){ console.log(`${this.timestamp.getDate()}/` + `${this.timestamp.getMonth()+1}/` + `${this.timestamp.getFullYear()} ` + `${this.timestamp.getHours()}:` + `${this.timestamp.getMinutes()}:` + `${this.timestamp.getSeconds()}` + ` - Walked ${this.distance}Km in ${this.location}`); } } class Dog { constructor(name, location) { this.name = name; this.location = location this.walks = []; } speak(){ console.log(`Woof! my name is ${this.name}`); } walk(location, distance) { let walk = new Walk(location, distance); this.walks.push(walk); } display_walks() { for (let walk of this.walks){ walk.display(); } } total_distance(){ let total = 0; for (let walk of this.walks) total += walk.distance; return total; } } d1 = new Dog("Ruben", "Ashfield"); d1.walk("Ashield", 5); d1.walk("Burwood", 7); d1.walk("Summer Hills", 10); d1.display_walks(); console.log(`Total km ${d1.total_distance()}`);
PHP
UTF-8
2,183
3.078125
3
[]
no_license
<?php use PHPUnit\Framework\TestCase; use Smbkr\Checkout; use Smbkr\Catalogue; class CheckoutTest extends TestCase { /** * Tests that Checkout can fail gracefully if given an empty order. * @test */ public function it_returns_0_for_empty_string() { $catalogueMock = $this->createMock(Catalogue::class); $checkout = new Checkout($catalogueMock); $this->assertEquals(0, $checkout->getTotal("")); } /** * Tests that Checkout is calling hte getPriceFor method on Catalogue to * determine a product's cost. * @test */ public function it_returns_the_value_for_a_product_code() { $catalogueMock = $this->createMock(Catalogue::class); $catalogueMock->method('isAvailable') ->willReturn(true); $catalogueMock->method('getPriceFor') ->willReturn(300); $checkout = new Checkout($catalogueMock); $this->assertEquals(300, $checkout->getTotal("A")); } /** * Test that Checkout will loop over each product type, calling getPriceFor * on Catalogue for each product. * @test */ public function it_sums_the_price_for_multiple_products() { $catalogueMock = $this->createMock(Catalogue::class); $catalogueMock->method('isAvailable') ->willReturn(true); $catalogueMock->method('getPriceFor') ->will($this->onConsecutiveCalls(100, 200, 300, 400)); $checkout = new Checkout($catalogueMock); $this->assertEquals(1000, $checkout->getTotal("ABCD")); } /** * @test * @review what is the desired behaviour when given an invalid ID? throw an * exception, or recover and continue by ignoring the invalid ID? My feeling * is that if we accept "" (empty string) returns zero, to go with the latter. */ public function it_guards_against_invalid_products() { $catalogueMock = $this->createMock(Catalogue::class); $catalogueMock->method('isAvailable') ->willReturn(false); $checkout = new Checkout($catalogueMock); $this->assertEquals(0, $checkout->getTotal('Z')); } }
Java
UTF-8
6,132
2.390625
2
[]
no_license
package com.lei.admin.service.impl; import com.aliyun.oss.OSS; import com.aliyun.oss.model.*; import com.lei.admin.entity.FileInfo; import com.lei.admin.mapper.FileInfoMapper; import com.lei.admin.service.IOSService; import com.lei.admin.utils.OSSUtils; import com.lei.admin.vo.OSSFileVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.*; /** * @Author LEI * @Date 2021/3/15 10:29 * @Description TODO */ @Service public class OSServiceImpl implements IOSService { @Autowired private FileInfoMapper fileInfoMapper; @Override public String uploadOSSFile(OSSFileVO ossFileVO) throws IOException { MultipartFile file = ossFileVO.getFile(); String userName = ossFileVO.getUserName(); Integer classificationId = ossFileVO.getClassificationId(); String bucketName = "test-0230"; String objectName = Objects.requireNonNull(file.getContentType()).replaceAll("/", "") + "/" + file.getOriginalFilename(); OSS ossClient = OSSUtils.getOssClient(); // 创建InitiateMultipartUploadRequest对象。 InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName); // 如果需要在初始化分片时设置文件存储类型,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // request.setObjectMetadata(metadata); // 初始化分片。 InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request); // 返回uploadId,它是分片上传事件的唯一标识,您可以根据这个uploadId发起相关的操作,如取消分片上传、查询分片上传等。 String uploadId = upresult.getUploadId(); // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。 List<PartETag> partETags = new ArrayList<>(); // 计算文件有多少个分片。 final long partSize = 1024 * 1024L; // 1MB final MultipartFile sampleFile = ossFileVO.getFile(); long fileLength = sampleFile.getSize(); int partCount = (int) (fileLength / partSize); if (fileLength % partSize != 0) { partCount++; } // 遍历分片上传。 for (int i = 0; i < partCount; i++) { long startPos = i * partSize; long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize; InputStream instream = sampleFile.getInputStream(); // 跳过已经上传的分片。 instream.skip(startPos); UploadPartRequest uploadPartRequest = new UploadPartRequest(); uploadPartRequest.setBucketName(bucketName); uploadPartRequest.setKey(objectName); uploadPartRequest.setUploadId(uploadId); uploadPartRequest.setInputStream(instream); // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。 uploadPartRequest.setPartSize(curPartSize); // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出这个范围,OSS将返回InvalidArgument的错误码。 uploadPartRequest.setPartNumber(i + 1); // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。 UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest); // 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。 partETags.add(uploadPartResult.getPartETag()); } // 创建CompleteMultipartUploadRequest对象。 // 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。 CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags); // 如果需要在完成文件上传的同时设置文件访问权限,请参考以下示例代码。 // completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.PublicRead); // 完成上传。 CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest); // 关闭OSSClient。 ossClient.shutdown(); String url = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objectName; FileInfo fileInfo = new FileInfo(); fileInfo.setFileName(file.getOriginalFilename()); fileInfo.setIdentifier(uploadId); fileInfo.setTotalSize((int) file.getSize()); fileInfo.setLocation(url); fileInfo.setFileType(file.getContentType()); fileInfo.setClassificationId(classificationId); fileInfo.setUploadUser(userName); fileInfo.setUploadTime(new Date()); fileInfoMapper.insert(fileInfo); return url; } @Override public String uploadPhoto(MultipartFile file) { OSS ossClient = OSSUtils.getOssClient(); String bucketName = "bysj01"; String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String fileName = "photo" + "/" + uuid + file.getOriginalFilename(); String url = ""; try { InputStream inputStream = file.getInputStream(); ossClient.putObject(bucketName, fileName, inputStream); ossClient.shutdown(); url = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + fileName; } catch (Exception e) { e.printStackTrace(); } return url; } }
C++
UTF-8
2,249
3.359375
3
[]
no_license
#include <iostream> int main() { // The magic starts here int gryffindor=0,hufflepuff=0,ravenclaw=0,slytherin=0; int answer1=0,answer2=0,answer3=0,answer4=0; std::cout<<"The Sorting Hat Quiz!\n"; std::cout<<"Q1) When I'm dead, I want people to remember me as:\n"; std::cout<<"\n"; std::cout<<" 1) The Good\n"; std::cout<<" 2) The Great\n"; std::cout<<" 3) The Wise\n"; std::cout<<" 4) The Bold\n\n"; std::cin>>answer1; if(answer1==1) hufflepuff++; else if(answer1==2) slytherin++; else if(answer1==3) ravenclaw++; else if(answer1==4) gryffindor++; else std::cout<<"Invalid input.\n"; std::cout<<"Q2) Dawn or Dusk?\n\n"; std::cout<<"1) Dawn\n"; std::cout<<"2) Dusk\n\n"; std::cin>>answer2; if(answer2==1) { gryffindor++; ravenclaw++; } else if(answer2==2) { hufflepuff++; slytherin++; } else { std::cout<<"Invalid input\n"; } std::cout<<"Q3) Which kind of instrument most pleases your ear?\n\n"; std::cout<<"1) The violin\n"; std::cout<<"2) The trumpet\n"; std::cout<<"3) The piano\n"; std::cout<<"4) The drum\n"; std::cin>>answer3; if(answer3==1) slytherin++; else if(answer3==2) hufflepuff++; else if(answer3==3) ravenclaw++; else if(answer3==4) gryffindor++; else std::cout<<"Invalid input\n"; std::cout<<"Q4) Which road tempts you most?\n\n"; std::cout<<"1) The wide, sunny grassy lane\n"; std::cout<<"2) The narrow, dark, lantern-lit alley\n"; std::cout<<"3) The twisting, leaf-strewn path through woods\n"; std::cout<<"4) The cobbled street lined (ancient buildings)\n"; std::cin>>answer4; if(answer4==1) hufflepuff++; else if(answer4==2) slytherin++; else if(answer4==4) ravenclaw++; else if(answer4==3) gryffindor++; else std::cout<<"Invalid input\n"; std::string house; int max=0; if (gryffindor > max) { max = gryffindor; house = "Gryffindor"; } else if (hufflepuff > max) { max = hufflepuff; house = "Hufflepuff"; } else if (ravenclaw > max) { max = ravenclaw; house = "Ravenclaw"; } else if(slytherin > max) { max = slytherin; house = "Slytherin"; } std::cout << house << "!\n"; return 0; }
JavaScript
UTF-8
1,985
2.921875
3
[]
no_license
/** * @des 将图片地址转成base64 */ export function getBase64 (imgUrl, callback) { window.URL = window.URL || window.webkitURL var xhr = new XMLHttpRequest() xhr.open('get', imgUrl, true) // 至关重要 xhr.responseType = 'blob' xhr.onload = function () { if (this.status == 200) { // 得到一个blob对象 var blob = this.response // 至关重要 let oFileReader = new FileReader() oFileReader.onloadend = function (e) { let base64 = e.target.result callback && callback(base64) } oFileReader.readAsDataURL(blob) } } xhr.send() } /** * @des 图片懒加载 * @param {el} wrap 图片容器 * @param {HTMLCollection} imageArr 图片列表 * @param {String} derection 整体列表滑动方向['down','up'] * @param {Number} lastShowImageIndex 上次展示图片的索引 */ export function lazyloadImage ({ wrap, imageArr, derection = 'down', lastShowImageIndex = 0 }) { let imageLen = imageArr.length let listScrollTop = wrap.scrollTop let listClientHeight = wrap.clientHeight switch (derection) { case 'down': for (let i = lastShowImageIndex; i < imageLen; i++) { let item = imageArr[i] let originUrl = item.getAttribute('originurl') let url = item.getAttribute('src') if (item.offsetTop - listScrollTop <= listClientHeight) { if (originUrl && originUrl != url) item.setAttribute('src', originUrl) } else { return i >= 1 ? i - 1 : 0 } } break case 'up': listClientHeight += 100 for (let i = imageLen - 1; i >= 0; i--) { let item = imageArr[i] let originUrl = item.getAttribute('originurl') let url = item.getAttribute('src') let top = item.getBoundingClientRect().top if (top >= 0 && top <= listClientHeight) { if (originUrl && originUrl != url) item.setAttribute('src', originUrl) } } break } }
PHP
UTF-8
2,589
2.53125
3
[]
no_license
<?php include 'admin_includes/header.php'; ?> <?php $msg = ""; if (isset($_POST['signup']) && !empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['first_name']) && !empty($_POST['last_name'])) { $user = new User(); $user->username = $_POST['username']; $user->set_file($_FILES['user_image']); $user->save_user_image(); $user->password = $_POST['password']; $user->first_name = $_POST['first_name']; $user->last_name = $_POST['last_name']; $user->save(); $msg = "<div class='alert alert-success'>User added. You can add more or <a href='users.php'>view all.</a></div>"; } ?> <div id="wrapper"> <?php include 'admin_includes/top_nav.php'; ?> <?php include 'admin_includes/left_nav.php'; ?> <div id="page-wrapper"> <div class="container-fluid"> <!-- Page Heading --> <div class="row"> <div class="col-lg-12 enlarge"> <h1 class="page-header">Add User</h1> <?php echo $msg; ?> <form action="" method="POST" enctype="multipart/form-data"> <div class="col-md-8"> <div class="form-group"> <label for="username" class="label label-primary">Username</label> <input type="text" name="username" id="username" class="form-control"> </div> <div class="form-group"> <label for="picture" class="label label-primary">Picture</label> <br> <input type="file" name="user_image" id="picture"> </div> <div class="form-group"> <label for="password" class="label label-primary">Password</label> <input type="password" name="password" id="password" class="form-control"> </div> <div class="form-group"> <label for="first_name" class="label label-primary">First name</label> <input type="text" name="first_name" id="first_name" class="form-control"> </div> <div class="form-group"> <label for="last_name" class="label label-primary">Last name</label> <input class="form-control" name="last_name" id="last_name"> </div> <input type="submit" name="signup" value="Sign up" class="btn btn-primary"> </div> </div> </form> </div> </div> <!-- /.row --> </div> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <?php include 'admin_includes/footer.php'; ?>
C#
UTF-8
2,457
2.59375
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Http; using System.Runtime.InteropServices.ComTypes; using System.Web.Http; namespace VersionedRestApi.Examples.Controllers { public class ExamplesApiController : ApiController { [HttpGet] public string HelloWorld() { return "hello world"; } /* this method handles POST requests to version 1 all the way through the current version of the API (as specified by * the currentApiVersion app setting) since no versions are explicitly specified. * For example, if the currentApiVersion == 8, then this action will respond to * all of these: /v1/Examples/ /v2/Examples/ /v3/Examples/ /v4/Examples/ /v5/Examples/ /v6/Examples/ /v7/Examples/ /v8/Examples/ */ [ApiRoute("Examples/")] [HttpPost] public string Post() { return "Return value for the POST method."; } //this method handles GET requests to "/v1/Examples/" [ApiRoute("Examples/", AcceptedVersions = new [] {1} )] [HttpGet] public string Get() { return "Return value for GET /v1/Examples/"; } /* this method handles GET requests to any of the following: /v2/Examples/ /v3/Examples/ /v4/Examples/ /v5/Examples/ /v6/Examples/ */ [ApiRoute("Examples/", AcceptedVersions = new[] {2, 3, 4, 5, 6} )] [HttpGet] public string SomeBreakingChangeToTheGetAction() { return "Return value for GET /v(2|3|4|5|6)/Examples/"; } /* * This method handles requests to version 7 and up (e.g. /v7/Examples/) */ [ApiRoute("Examples/", AcceptedVersions = new[] { 7, 8, 9, 10, 11, 12 })] [HttpGet] public string YetAnotherBreakingChangeToGet() { return "Return value for GET /v(7|8|9|10|11|12)/Examples/"; } [ApiRoute("Examples/", StartingVersion = 13)] [HttpGet] public string LatestBreakingChangeToGet() { return "Return value for GET /v(13|14})/Examples/ ; assuming the current version is at 14."; } } }
Python
UTF-8
308
3.078125
3
[]
no_license
import math class Pet: """ this is a Pet class for demo purpose """ is_human = False owner = "Mike Smith" def __init__(self, height): self.height = height pass # testing this class if __name__ == '__main__': chubbles = Pet(height = 5) print(chubbles.__doc__) print(chubbles.__dir__)
Python
UTF-8
2,937
2.578125
3
[ "Apache-2.0" ]
permissive
# Copyright (C) 2018 Cancer Care Associates # 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. """Compare Mosaiq fields using MetersetMap """ import itertools from pymedphys._imports import numpy as np import matplotlib.pyplot as plt import pymedphys def plot_metersetmaps(labels, metersetmap_results): for label, results in zip(labels, metersetmap_results): xx = results[0] yy = results[1] metersetmap = results[2] plt.figure() plt.pcolormesh(xx, yy, metersetmap) plt.colorbar() plt.title("MetersetMap | {}".format(label)) plt.xlabel("MLC direction (mm)") plt.ylabel("Jaw direction (mm)") plt.gca().invert_yaxis() def plot_gantry_collimator(labels, deliveries): plt.figure() plt.title("Gantry Angle") for label, delivery_data in zip(labels, deliveries): plt.plot( delivery_data.monitor_units, delivery_data.gantry, label=label, alpha=0.5 ) plt.xlabel("Monitor Units") plt.ylabel("Gantry Angle") plt.legend() plt.figure() plt.title("Collimator Angle") for label, delivery_data in zip(labels, deliveries): plt.plot( delivery_data.monitor_units, delivery_data.collimator, label=label, alpha=0.5, ) plt.xlabel("Monitor Units") plt.ylabel("Collimator Angle") plt.legend() def compare_mosaiq_fields(servers, field_ids): unique_servers = list(set(servers)) with pymedphys.mosaiq.connect(unique_servers) as cursors: deliveries = [ pymedphys.Delivery.from_mosaiq(cursors[server], field_id) for server, field_id in zip(servers, field_ids) ] metersetmap_results = [delivery_data.metersetmap() for delivery_data in deliveries] metersetmaps = [results[2] for results in metersetmap_results] labels = [ "Server: `{}` | Field ID: `{}`".format(server, field_id) for server, field_id in zip(servers, field_ids) ] plot_gantry_collimator(labels, deliveries) plot_metersetmaps(labels, metersetmap_results) metersetmaps_match = np.all( [ np.all(np.abs(metersetmap_a - metersetmap_b) < 0.1) for metersetmap_a, metersetmap_b in itertools.combinations(metersetmaps, 2) ] ) plt.show() print("MetersetMaps match: {}".format(metersetmaps_match)) return deliveries, metersetmaps
TypeScript
UTF-8
4,579
3.109375
3
[ "MIT" ]
permissive
import { ICookie, ICookieMap, IBarPrinterInput, IBarPrinterParam } from "./entities"; import inquirer from 'inquirer'; import chalk from 'chalk'; /** * Convert header set cookie string into an object * @param cookieString Set cookie header string */ export const parseCookies = (cookieString: string): ICookieMap => { // Split string const cookieArray: string[] = cookieString.split(','); // Sub strings const cookieSubArray: string[][] = cookieArray.map( cookie => cookie.split(';').map(c => c.trim()) ); // Join date strings back to the parent cookie array const mergedCookieArray: string[][] = []; for (let i = 0; i < cookieSubArray.length; i++) { if (i + 1 < cookieSubArray.length && cookieSubArray[i + 1][0].search(/[0-9]/) === 0) { cookieSubArray[i][cookieSubArray[i].length - 1] += ', ' + cookieSubArray[i + 1][0]; cookieSubArray[i + 1].splice(0, 1); mergedCookieArray.push(cookieSubArray[i].concat(cookieSubArray[i + 1])); i += 1; } else { mergedCookieArray.push(cookieSubArray[i]); } } // Convert to object const cookieObject: ICookieMap = {}; mergedCookieArray.map(mergedCookie => { const keyValueArray: string[][] = mergedCookie.map(cookie => cookie.split('=')) const singleCookieObject: any = {}; keyValueArray.map(c => { if (c[0] == keyValueArray[0][0]) { singleCookieObject['name'] = keyValueArray[0][0]; singleCookieObject['value'] = c[1]; } else singleCookieObject[c[0]] = c[1] ? c[1] : true; }) cookieObject[keyValueArray[0][0]] = <ICookie>singleCookieObject; }); return cookieObject; } /** * Read input from user * @param question Question asked to the user for input */ export const readUserInput = async (question: string, isSensitive: Boolean = false): Promise<string> => { const answers = await inquirer.prompt([ { name: 'key', message: question, type: isSensitive ? 'password' : 'input' }, ]) if (!answers.key) // When email address is invalid throw new Error('Invalid input.'); else // When email address ia valid return answers.key; } // Month index to words export const monthNames: string[] = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; // Weekday index to words export const weekdayNames: string[] = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; /** * Print bars on console * @param data Values for printing * @param limit Max number of elements to print * @param width Max with of bar in the terminal */ export const printBars = (data: IBarPrinterParam, displayCost: Boolean = true, performSort: Boolean = false, limit: number = 10, width: number = 50) => { console.log('here') const block: string = '\u2580'; // Convert object to const labelValueArr: IBarPrinterInput[] = Object.keys(data).map(key => { return data[key] ? { label: key, value: data[key].total ? data[key].total : 0, count: data[key].count } : { label: key, value: 0, count: 0 } }); // Calculate max value for normalization const maxValue = Math.max(...labelValueArr.map(x => x.count)); labelValueArr // Select max elements to display .slice(0, limit) // Reverse sort .sort((a: IBarPrinterInput, b: IBarPrinterInput) => performSort ? b.count - a.count : 0) // Print bars .forEach(({ label, value, count }) => { // Remove decimals const truncatedValue = Math.trunc(count); console.log( // Display initial white space ' '.repeat(1), // Display count chalk.whiteBright(truncatedValue), // Display white space depending on number of digits in count ' '.repeat(4 - String(truncatedValue).length), // Display bars with normalized values block.repeat(width * truncatedValue / maxValue), // Display key chalk.yellow(label), // Display cost chalk.red(displayCost ? '₹' + value.toFixed(0) : ''), ); }); };
Java
UTF-8
11,566
1.523438
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.12.07 at 11:39:25 AM EST // package com.windsor.node.plugin.icisnpdes.generated; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import com.windsor.node.plugin.common.xml.bind.annotation.adapters.IntegerAdapter; import org.jvnet.jaxb2_commons.lang.Equals; import org.jvnet.jaxb2_commons.lang.EqualsStrategy; import org.jvnet.jaxb2_commons.lang.HashCode; import org.jvnet.jaxb2_commons.lang.HashCodeStrategy; import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy; import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy; import org.jvnet.jaxb2_commons.locator.ObjectLocator; import org.jvnet.jaxb2_commons.locator.util.LocatorUtils; /** * <p>Java class for SSOMonthlyEventReport complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SSOMonthlyEventReport"> * &lt;complexContent> * &lt;extension base="{http://www.exchangenetwork.net/schema/icis/5}SSOMonthlyEventReportKeyElements"> * &lt;sequence> * &lt;element ref="{http://www.exchangenetwork.net/schema/icis/5}SSOMonthlyEventMonth" minOccurs="0"/> * &lt;element ref="{http://www.exchangenetwork.net/schema/icis/5}SSOMonthlyEventYear" minOccurs="0"/> * &lt;element ref="{http://www.exchangenetwork.net/schema/icis/5}NumberSSOEventsReachUSWatersPerMonth" minOccurs="0"/> * &lt;element ref="{http://www.exchangenetwork.net/schema/icis/5}VolumeSSOEventsReachUSWatersPerMonth" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SSOMonthlyEventReport", propOrder = { "ssoMonthlyEventMonth", "ssoMonthlyEventYear", "numberSSOEventsReachUSWatersPerMonth", "volumeSSOEventsReachUSWatersPerMonth" }) @Embeddable public class SSOMonthlyEventReport extends SSOMonthlyEventReportKeyElements implements Serializable, Equals, HashCode { private final static long serialVersionUID = 1L; @XmlElement(name = "SSOMonthlyEventMonth", type = String.class) @XmlJavaTypeAdapter(IntegerAdapter.class) protected Integer ssoMonthlyEventMonth; @XmlElement(name = "SSOMonthlyEventYear", type = String.class) @XmlJavaTypeAdapter(IntegerAdapter.class) protected Integer ssoMonthlyEventYear; @XmlElement(name = "NumberSSOEventsReachUSWatersPerMonth", type = String.class) @XmlJavaTypeAdapter(IntegerAdapter.class) protected Integer numberSSOEventsReachUSWatersPerMonth; @XmlElement(name = "VolumeSSOEventsReachUSWatersPerMonth", type = String.class) @XmlJavaTypeAdapter(IntegerAdapter.class) protected Integer volumeSSOEventsReachUSWatersPerMonth; /** * Gets the value of the ssoMonthlyEventMonth property. * * @return * possible object is * {@link String } * */ @Basic @Column(name = "SSO_MONTHLY_EVT_MN", scale = 0) public Integer getSSOMonthlyEventMonth() { return ssoMonthlyEventMonth; } /** * Sets the value of the ssoMonthlyEventMonth property. * * @param value * allowed object is * {@link String } * */ public void setSSOMonthlyEventMonth(Integer value) { this.ssoMonthlyEventMonth = value; } @Transient public boolean isSetSSOMonthlyEventMonth() { return (this.ssoMonthlyEventMonth!= null); } /** * Gets the value of the ssoMonthlyEventYear property. * * @return * possible object is * {@link String } * */ @Basic @Column(name = "SSO_MONTHLY_EVT_YEAR", scale = 0) public Integer getSSOMonthlyEventYear() { return ssoMonthlyEventYear; } /** * Sets the value of the ssoMonthlyEventYear property. * * @param value * allowed object is * {@link String } * */ public void setSSOMonthlyEventYear(Integer value) { this.ssoMonthlyEventYear = value; } @Transient public boolean isSetSSOMonthlyEventYear() { return (this.ssoMonthlyEventYear!= null); } /** * Gets the value of the numberSSOEventsReachUSWatersPerMonth property. * * @return * possible object is * {@link String } * */ @Basic @Column(name = "NUM_SSO_EVTS_REC_US_WTR_PER_MN", scale = 0) public Integer getNumberSSOEventsReachUSWatersPerMonth() { return numberSSOEventsReachUSWatersPerMonth; } /** * Sets the value of the numberSSOEventsReachUSWatersPerMonth property. * * @param value * allowed object is * {@link String } * */ public void setNumberSSOEventsReachUSWatersPerMonth(Integer value) { this.numberSSOEventsReachUSWatersPerMonth = value; } @Transient public boolean isSetNumberSSOEventsReachUSWatersPerMonth() { return (this.numberSSOEventsReachUSWatersPerMonth!= null); } /** * Gets the value of the volumeSSOEventsReachUSWatersPerMonth property. * * @return * possible object is * {@link String } * */ @Basic @Column(name = "VOL_SSO_EVTS_REC_US_WTR_PER_MN", scale = 0) public Integer getVolumeSSOEventsReachUSWatersPerMonth() { return volumeSSOEventsReachUSWatersPerMonth; } /** * Sets the value of the volumeSSOEventsReachUSWatersPerMonth property. * * @param value * allowed object is * {@link String } * */ public void setVolumeSSOEventsReachUSWatersPerMonth(Integer value) { this.volumeSSOEventsReachUSWatersPerMonth = value; } @Transient public boolean isSetVolumeSSOEventsReachUSWatersPerMonth() { return (this.volumeSSOEventsReachUSWatersPerMonth!= null); } public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) { if (!(object instanceof SSOMonthlyEventReport)) { return false; } if (this == object) { return true; } if (!super.equals(thisLocator, thatLocator, object, strategy)) { return false; } final SSOMonthlyEventReport that = ((SSOMonthlyEventReport) object); { Integer lhsSSOMonthlyEventMonth; lhsSSOMonthlyEventMonth = this.getSSOMonthlyEventMonth(); Integer rhsSSOMonthlyEventMonth; rhsSSOMonthlyEventMonth = that.getSSOMonthlyEventMonth(); if (!strategy.equals(LocatorUtils.property(thisLocator, "ssoMonthlyEventMonth", lhsSSOMonthlyEventMonth), LocatorUtils.property(thatLocator, "ssoMonthlyEventMonth", rhsSSOMonthlyEventMonth), lhsSSOMonthlyEventMonth, rhsSSOMonthlyEventMonth)) { return false; } } { Integer lhsSSOMonthlyEventYear; lhsSSOMonthlyEventYear = this.getSSOMonthlyEventYear(); Integer rhsSSOMonthlyEventYear; rhsSSOMonthlyEventYear = that.getSSOMonthlyEventYear(); if (!strategy.equals(LocatorUtils.property(thisLocator, "ssoMonthlyEventYear", lhsSSOMonthlyEventYear), LocatorUtils.property(thatLocator, "ssoMonthlyEventYear", rhsSSOMonthlyEventYear), lhsSSOMonthlyEventYear, rhsSSOMonthlyEventYear)) { return false; } } { Integer lhsNumberSSOEventsReachUSWatersPerMonth; lhsNumberSSOEventsReachUSWatersPerMonth = this.getNumberSSOEventsReachUSWatersPerMonth(); Integer rhsNumberSSOEventsReachUSWatersPerMonth; rhsNumberSSOEventsReachUSWatersPerMonth = that.getNumberSSOEventsReachUSWatersPerMonth(); if (!strategy.equals(LocatorUtils.property(thisLocator, "numberSSOEventsReachUSWatersPerMonth", lhsNumberSSOEventsReachUSWatersPerMonth), LocatorUtils.property(thatLocator, "numberSSOEventsReachUSWatersPerMonth", rhsNumberSSOEventsReachUSWatersPerMonth), lhsNumberSSOEventsReachUSWatersPerMonth, rhsNumberSSOEventsReachUSWatersPerMonth)) { return false; } } { Integer lhsVolumeSSOEventsReachUSWatersPerMonth; lhsVolumeSSOEventsReachUSWatersPerMonth = this.getVolumeSSOEventsReachUSWatersPerMonth(); Integer rhsVolumeSSOEventsReachUSWatersPerMonth; rhsVolumeSSOEventsReachUSWatersPerMonth = that.getVolumeSSOEventsReachUSWatersPerMonth(); if (!strategy.equals(LocatorUtils.property(thisLocator, "volumeSSOEventsReachUSWatersPerMonth", lhsVolumeSSOEventsReachUSWatersPerMonth), LocatorUtils.property(thatLocator, "volumeSSOEventsReachUSWatersPerMonth", rhsVolumeSSOEventsReachUSWatersPerMonth), lhsVolumeSSOEventsReachUSWatersPerMonth, rhsVolumeSSOEventsReachUSWatersPerMonth)) { return false; } } return true; } public boolean equals(Object object) { final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE; return equals(null, null, object, strategy); } public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) { int currentHashCode = super.hashCode(locator, strategy); { Integer theSSOMonthlyEventMonth; theSSOMonthlyEventMonth = this.getSSOMonthlyEventMonth(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "ssoMonthlyEventMonth", theSSOMonthlyEventMonth), currentHashCode, theSSOMonthlyEventMonth); } { Integer theSSOMonthlyEventYear; theSSOMonthlyEventYear = this.getSSOMonthlyEventYear(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "ssoMonthlyEventYear", theSSOMonthlyEventYear), currentHashCode, theSSOMonthlyEventYear); } { Integer theNumberSSOEventsReachUSWatersPerMonth; theNumberSSOEventsReachUSWatersPerMonth = this.getNumberSSOEventsReachUSWatersPerMonth(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "numberSSOEventsReachUSWatersPerMonth", theNumberSSOEventsReachUSWatersPerMonth), currentHashCode, theNumberSSOEventsReachUSWatersPerMonth); } { Integer theVolumeSSOEventsReachUSWatersPerMonth; theVolumeSSOEventsReachUSWatersPerMonth = this.getVolumeSSOEventsReachUSWatersPerMonth(); currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "volumeSSOEventsReachUSWatersPerMonth", theVolumeSSOEventsReachUSWatersPerMonth), currentHashCode, theVolumeSSOEventsReachUSWatersPerMonth); } return currentHashCode; } public int hashCode() { final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE; return this.hashCode(null, strategy); } }
JavaScript
UTF-8
1,452
3.125
3
[]
no_license
class Selectors { constructor(name) { this.elHP = document.getElementById(`health-${name}`); this.elProgressbar = document.getElementById(`progressbar-${name}`); this.imgId = document.getElementById(`sprite-${name}`); this.pokemonName = document.getElementById(`name-${name}`) } } class Pokemon extends Selectors{ constructor({name, hp, type, selectors, attacks=[], img}) { super(selectors); this.name = name; this.hp = { current: hp, total: hp }; this.type = type; this.attacks = attacks; this.img = img; this.renderHP(); } renderHP = () => { this.renderLifeHP(); this.renderProgressbarHP(); } renderLifeHP = () => { this.elHP.innerText = this.hp.current + ' / ' + this.hp.total; } renderProgressbarHP = () => { const percent = (this.hp.current * 100)/this.hp.total; this.elProgressbar.style.width = percent + '%'; if(percent < 60 && percent > 20) { this.elProgressbar.classList.add('low'); } if(percent < 25) { this.elProgressbar.classList.add('critical') } } changeHP = (count, cb) => { this.hp.current -= count; if(this.hp.current <= 0) { this.hp.current = 0; } this.renderHP(); cb && cb(count); } } export default Pokemon;
Python
UTF-8
1,352
4.40625
4
[]
no_license
##Write a function named printTable() that takes a list of lists of strings ##and displays it in a well-organized table with each column right-justified. ##Assume that all the inner lists will contain the same number of strings. ##For example, the value could look like this: ##tableData = [['apples', 'oranges', 'cherries', 'banana'], ## ['Alice', 'Bob', 'Carol', 'David'], ## ['dogs', 'cats', 'moose', 'goose']] ##Your printTable() function would print the following: ## ## apples Alice dogs ## oranges Bob cats ##cherries Carol moose ## banana David goose #def printTable(): #input is a list of strings #output is an orgniased table with each column rjust tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] rows = len(tableData) #number of lists cols = len(tableData[0]) #number of cols maxlength = 0 for i in range(0,(rows)): #loop for number of rows for x in tableData[i]: #loop for the each item in the row if maxlength < len(x): #find the max length of the words maxlength = len(x) for k in range(0, (cols)): for v in range(0, (rows)): print((tableData[v][k]).rjust(maxlength), end = ' ') print()
Shell
UTF-8
785
2.640625
3
[ "Apache-2.0", "MIT" ]
permissive
#!/bin/sh # Homebrew clang is a bit different from /usr/bin/clang. Invoke clang++ -xc++ -fsyntax-only -v /dev/null to get a list of C/C++ search paths. # then add them as -isystem into the shell script wrapper. For example: exec /usr/local/bin/ccls --init='{"clang":{"extraArgs":[ "-std=c11", "-isystem/usr/local/include", "-isystem/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1", "-isystem/Library/Developer/CommandLineTools/usr/lib/clang/14.0.0/include", "-isystem/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include", "-isystem/Library/Developer/CommandLineTools/usr/include", "-isystem/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks" ]}}' "$@" # "-isystem/usr/local/Cellar/sdl2/2.24.0/include/SDL2"
Ruby
UTF-8
788
3.390625
3
[]
no_license
module BoardPrint def print_board(code=nil) print_secret_code(code) # for testing purpose; uses an optional parameter 'code' board.each_with_index do |row, idx| i = (idx + 1).to_s i = " #{i}" if i.length < 2 row_print = "#{i} " row.holes.each do |hole| row_print += add_text(hole, 'X') end if row.correct_positions row_print += " | Positions => #{row.correct_positions}" row_print += " | Colors => #{row.correct_colors}" end puts row_print end return end def print_secret_code(code) if code str = " " code.each { |color| str += add_text(color, '') } end puts str end def add_text(el, default) el == nil ? str = " #{default}" : str = " #{el[0]}" end end
Python
UTF-8
944
4.0625
4
[]
no_license
r""" 给定一个n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1。 示例 1: 输入: nums = [-1,0,3,5,9,12], target = 9 输出: 4 解释: 9 出现在 nums 中并且下标为 4 示例 2: 输入: nums = [-1,0,3,5,9,12], target = 2 输出: -1 解释: 2 不存在 nums 中因此返回 -1   提示: (1) 你可以假设 nums 中的所有元素是不重复的。 (2) n 将在 [1, 10000]之间。 (3) nums 的每个元素都将在 [-9999, 9999]之间。 """ class Solution: def search(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) - 1 while l <= r: m = l + (r - l) // 2 if nums[m] == target: return m elif nums[m] > target: r = m - 1 elif nums[m] < target: l = m + 1 return -1
JavaScript
UTF-8
4,583
3.046875
3
[]
no_license
// Require all of the modules needed for this application const express = require("express"); const bodyParser = require("body-parser"); const fileUpload = require("express-fileupload"); const fs = require("fs"); const path = require("path"); // Set up the packages that we have just required const app = express(); // Setup the port environment that we will use const port = '3000'; // Setup the middleware for our program app.use(bodyParser.urlencoded({ extended: false })); app.use(fileUpload()); // uploadDirectory is the path to our directory named uploaded, where we will store our cached files, path.sep provides the platform specific path segment separator const uploadDirectory = __dirname + path.sep + "uploaded"; // Server the uploaded folder to the server, allowing the users to download cached information. app.use(express.static("uploaded")); // app.use(express.static("public/")); app.use(express.static(__dirname + "/pages")); // Declare a variable named caches, define it as an empty object let caches = {}; // Promised version of Read and Write files // writeFile is a function which takes the name of the file and the body (data) for storage - it will write the file to our uploadDirectory 'uploaded', this promise resolves with the name of the file function writeFile(name, body) { return new Promise((resolve, reject) => { fs.writeFile(uploadDirectory + path.sep + name, body, (err) => { if (err) { return reject(err); } else { resolve(name); } }); }).then(readFile); } // readFile is a function which takes the file as an input, it goes to the 'uploaded' directory that we serve via express. It will then look for the name of the file that we pass into the function, the promise will resolve with the body of the file (the data) function readFile(file) { return new Promise((resolve, reject) => { fs.readFile(uploadDirectory + path.sep + file, (err, body) => { if (err) { return reject(err); } else { resolve(body); } }); }); } app.get("/", (req, res) => { // logic for reading your uploaded file and storing al the data back into a cache reach reload res.sendFile(__dirname + "/pages/index.html"); }); console.log(caches); app.post("/files", (req, res) => { // after the request path upload.single('upload'), console.log(req.files); if (req.files.upload instanceof Array) { for (var i = 0; i < req.files.upload.length; i++) { let file = req.files.upload[i].name; let data = req.files.upload[i].data; caches[file] = writeFile(file, data); console.log(caches); caches[file] .then(() => res.end( "Wow you sent a file, can you remember how to download it? Goto your browser, url: localhost:3000/uploaded/:file-name" ) ) .catch((error) => { console.log(error); res.end(error); }); } } else { console.log(req.files); let file = req.files.upload.name; let data = req.files.upload.data; caches[file] = writeFile(file, data); caches[file] .then(() => res.send( "Wow you sent a file, can you remember how to download it? Goto your browser, url: localhost:3000/uploaded/:file-name" ) ) .catch((e) => res.status(500).send(e.message)); } }); app.get("/uploaded/:name", (req, res) => { if (caches[req.params.name] == null) { console.log("reading from folder"); caches[req.params.name] = readFile(req.params.name); } console.log(caches); console.log(caches[req.params.name]); caches[req.params.name] .then((body) => { console.log(body); res.send(body); }) .catch((e) => res.status(500).send(e.message)); }); app.listen(port, () => { console.log(`Application Listening to port: ${port}`); console.log(__dirname) }); //This application doesnt have buttons or anything to download the file. In order to download the file, you must emulate the route that has been set up. // app.get('/files/:name' where the name is the file name that you've uploaded.
Markdown
UTF-8
641
2.5625
3
[ "MIT" ]
permissive
# Portfolio ## Author Roy Rasugu ## Description This website is my portfolio with various sections like an about, experience which is the websites I've worked on and contact section ## Livepage https://royrasugu.github.io/project/ ## Setup and instruction installations * Open Terminal (Ctrl+Alt+T) * git clone https://github.com/RoyRasugu/project.git * cd to the project directory * code . or atom . to access the code and view it in whichever browser you prefer ## Technologies Used * HTML5 * CSS * Bootstrap ## Contact Information You can reach me on my email [royratchizi@gmail.com] ## License * *MIT License:* * Copyright (c) 2021 **Roy Rasugu**
Python
UTF-8
4,608
3.078125
3
[]
no_license
import re import csv import math from io import StringIO from datetime import datetime from time import time from flask_restful import Resource, request from ..mongo_documents.station import Station, RoadPosition from ..mongo_documents.traffic_reading import TrafficReading, ValidationLevel #The strings that express valid traffic directions. LEFT_TO_RIGHT_STRINGS = ["L-Right", "Left-to-Right"] #i.e directionLeftToRight = True RIGHT_TO_LEFT_STRINGS = ["R-Left", "Right-to-Left"] #i.e. directionLeftToRight = False #A class string is of the form "class-<C>-<S>". #MAX_SUBCLASS_BY_CLASS[C - 1] gives the max value S should be, given C. MAX_SUBCLASS_BY_CLASS = [1, 1, 3, 4, 7, 3, 3, 5, 7, 6, 3, 9, 7, 1, 1] MAX_VALID_SPEED = 200 #Any speeds recorded over this value should be considered invalid. ''' @summary: Create a TrafficReading from a list representing a CSV row. Set the TrafficReading's validation level based on the validity of the given data. @param: readingData The data that validated and used to contruct the reading @param validationTimestamp: The system time at which the validation should be considered as occuring. ''' def constructValidatedTrafficReading(readingData, road_position_string, validationTimestamp): reading = TrafficReading() reading.rawSourceData = ','.join([ s for s in readingData ]) #Assume data is valid, the level will be dropped if invalid data is found. reading.validationLevel = ValidationLevel.FULL #Attempt to parse the date and time. try: reading.dateTime = datetime.strptime(readingData[0] + " " + readingData[1], "%Y-%m-%d %H:%M:%S") except(ValueError): reading.validationLevel = ValidationLevel.INVALID_FORMAT #Attempt to parse the speed as a float. try: reading.speed = float(readingData[2].split(" ")[0]) except(ValueError): reading.validationLevel = ValidationLevel.INVALID_FORMAT #Validate format of the string describing direction. if(readingData[3] in LEFT_TO_RIGHT_STRINGS + RIGHT_TO_LEFT_STRINGS): reading.directionLeftToRight = readingData[3] in LEFT_TO_RIGHT_STRINGS else: reading.validationLevel = ValidationLevel.INVALID_FORMAT #Validate format of the string describing the vechile class. if TrafficReading.classStringHasValidFormat(readingData[4]): reading.vehicleClass = TrafficReading.convertVehicleClassString(readingData[4]) else: reading.validationLevel = ValidationLevel.INVALID_FORMAT #Validate the format of the road_position string. try: reading.sourceRoadPosition = RoadPosition.parseFromString(road_position_string) except ValueError: reading.validationLevel = ValidationLevel.INVALID_FORMAT #If the data has passed all format validation checks, then the values of the #data itself can be validated. if(reading.validationLevel != ValidationLevel.INVALID_FORMAT): #The station referenced by the data should be a station in the database. if Station.objects(roadPosition=reading.sourceRoadPosition).first() == None: reading.validationLevel = ValidationLevel.INVALID_DATA #Any data dated after the time at which the data is being validated should #be considered speculative data, which we are not interested in. if reading.dateTime.timestamp() > validationTimestamp: reading.validationLevel = ValidationLevel.INVALID_DATA #The speed should be a positive number that does not excceed the max valid speed. if math.isnan(reading.speed) or reading.speed < 0 or reading.speed > MAX_VALID_SPEED: reading.validationLevel = ValidationLevel.INVALID_DATA #The subclass should be correct considering the class, i.e. should not exceed the #max subclass the class is expected to have, e.g class 5 has 7 expected subclasses, #so "class-5-9" would be an invalid value for the vehicle class. if(reading.vehicleClass.sub > MAX_SUBCLASS_BY_CLASS[reading.vehicleClass.main - 1]): reading.validationLevel = ValidationLevel.INVALID_DATA return reading class ReadingsRawCSVSubmissionResource(Resource): def post(self, road_position_string): text_data = request.get_data().decode("utf-8"); #Get the request body text as a string dataReader = csv.reader(StringIO(text_data), delimiter=",") #Parse the body text as csv data currentTime = time() for reading in dataReader: constructValidatedTrafficReading(reading, road_position_string, currentTime).save()
TypeScript
UTF-8
7,320
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import type {Reducer} from 'react'; import {useReducer} from 'react'; import type {FieldStates, ErrorValue} from '../../../types'; import type {FieldAction} from '../../field'; import { reduceField, updateErrorAction as updateFieldError, initialFieldState, } from '../../field'; import {mapObject} from '../../../utilities'; export type ListAction<Item> = | ReinitializeAction<Item> | AddFieldItemAction<Item> | EditFieldItemAction<FieldStates<object>> | MoveFieldItemAction | RemoveFieldItemAction | RemoveFieldItemsAction | UpdateErrorAction<Item> | UpdateAction<Item, keyof Item> | ResetAction<Item, keyof Item> | NewDefaultAction<Item, keyof Item> | ResetListAction; interface ReinitializeAction<Item> { type: 'reinitialize'; payload: {list: Item[]}; } interface AddFieldItemAction<Item> { type: 'addFieldItem'; payload: {list: Item[]}; } interface EditFieldItemAction<Item extends object> { type: 'editFieldItem'; payload: { index: number; editedItem: Item; }; } interface MoveFieldItemAction { type: 'moveFieldItem'; payload: {fromIndex: number; toIndex: number}; } interface ResetListAction { type: 'resetList'; } interface RemoveFieldItemAction { type: 'removeFieldItem'; payload: {indexToRemove: number}; } interface RemoveFieldItemsAction { type: 'removeFieldItems'; payload: {indicesToRemove: number[]}; } interface TargetedPayload<Item, Key extends keyof Item> { target: { index: number; key: Key; }; value: Item[Key]; } interface UpdateErrorAction<Item> { type: 'updateError'; payload: { target: { index: number; key: keyof Item; }; error: ErrorValue; }; } interface ResetAction<Item, Key extends keyof Item> { type: 'reset'; payload: { target: { index: number; key: Key; }; }; } interface UpdateAction<Item, Key extends keyof Item> { type: 'update'; payload: TargetedPayload<Item, Key>; } interface NewDefaultAction<Item, Key extends keyof Item> { type: 'newDefaultValue'; payload: TargetedPayload<Item, Key>; } export function reinitializeAction<Item>( list: Item[], ): ReinitializeAction<Item> { return { type: 'reinitialize', payload: {list}, }; } export function addFieldItemAction<Item>( list: Item[], ): AddFieldItemAction<Item> { return { type: 'addFieldItem', payload: {list}, }; } export function editFieldItemAction<Item extends object>( editedItem: Item, index: number, ): EditFieldItemAction<Item> { return { type: 'editFieldItem', payload: { editedItem, index, }, }; } export function moveFieldItemAction( fromIndex: number, toIndex: number, ): MoveFieldItemAction { return { type: 'moveFieldItem', payload: {fromIndex, toIndex}, }; } export function removeFieldItemAction( indexToRemove: number, ): RemoveFieldItemAction { return { type: 'removeFieldItem', payload: {indexToRemove}, }; } export function removeFieldItemsAction( indicesToRemove: number[], ): RemoveFieldItemsAction { return { type: 'removeFieldItems', payload: {indicesToRemove}, }; } export function updateAction<Item, Key extends keyof Item>( payload: TargetedPayload<Item, Key>, ): UpdateAction<Item, Key> { return { type: 'update', payload, }; } export function resetAction<Item, Key extends keyof Item>( payload: ResetAction<Item, Key>['payload'], ): ResetAction<Item, Key> { return { type: 'reset', payload, }; } export function resetListAction(): ResetListAction { return { type: 'resetList', }; } export function newDefaultAction<Item, Key extends keyof Item>( payload: TargetedPayload<Item, Key>, ): NewDefaultAction<Item, Key> { return { type: 'newDefaultValue', payload, }; } export function updateErrorAction<Item>( payload: UpdateErrorAction<Item>['payload'], ): UpdateErrorAction<Item> { return { type: 'updateError', payload, }; } export interface ListState<Item extends object> { list: FieldStates<Item>[]; initial: Item[]; } export function useListReducer<Item extends object>(initial: Item[]) { return useReducer<Reducer<ListState<Item>, ListAction<Item>>>(reduceList, { list: initial.map(initialListItemState), initial, }); } function reduceList<Item extends object>( state: ListState<Item>, action: ListAction<Item>, ) { switch (action.type) { case 'reinitialize': { return { initial: action.payload.list, list: action.payload.list.map(initialListItemState), }; } case 'moveFieldItem': { const {fromIndex, toIndex} = action.payload; if ( fromIndex >= state.list.length || fromIndex < 0 || toIndex >= state.list.length || toIndex < 0 ) { throw new Error(`Failed to move item from ${fromIndex} to ${toIndex}`); } const newList = [...state.list]; const [item] = newList.splice(action.payload.fromIndex, 1); newList.splice(action.payload.toIndex, 0, item); return { ...state, list: newList, }; } case 'addFieldItem': { return { ...state, list: [...state.list, ...action.payload.list.map(initialListItemState)], }; } case 'editFieldItem': { const {editedItem, index} = action.payload; // Don't do a full rewrite of the object, only edit data which is supplied. const list = state?.list?.map?.((item, i) => i === index ? {...item, ...editedItem} : item, ); return { ...state, list, }; } case 'removeFieldItem': { const newList = [...state.list]; newList.splice(action.payload.indexToRemove, 1); return { ...state, list: newList, }; } case 'removeFieldItems': { const indicesToRemove = action?.payload?.indicesToRemove ?? []; const list = state.list.filter((_, i) => !indicesToRemove.includes(i)); return { ...state, list, }; } case 'updateError': { const { payload: {target, error}, } = action; const {index, key} = target; const currentItem = state.list[index]; currentItem[key] = reduceField( currentItem[key], updateFieldError(error), ) as any; return {...state, list: [...state.list]}; } case 'reset': { const { payload: {target}, } = action; const {index, key} = target; const currentItem = state.list[index]; currentItem[key] = reduceField(currentItem[key], {type: 'reset'}); return {...state, list: [...state.list]}; } case 'resetList': { return {...state, list: state.initial.map(initialListItemState)}; } case 'update': case 'newDefaultValue': { const { payload: {target, value}, } = action; const {index, key} = target; const currentItem = state.list[index]; currentItem[key] = reduceField(currentItem[key], { type: action.type, payload: value, } as FieldAction<typeof value>); return {...state, list: [...state.list]}; } } } function initialListItemState<Item extends object>(item: Item) { return mapObject<FieldStates<Item>>(item, initialFieldState); }
Markdown
UTF-8
5,178
3.171875
3
[]
no_license
# Liquor World ## Data Centric Development Milestone Project ![mockup image](static/images/Mockup-image.PNG) ### **Introduction** There are many different types of liquor mixes, each with its own unique name and preparation method. For all liquor lovers, bartenders, pub owners and many more, this website allows them to share their creations or concoct the drinks per their client's request if they are able to find the requested liquor here. The users are able to add, update, or delete their creation here, as well as add, update or delete reviews. <br/> The link is as follows: [Liquor_world](https://ojhj-project3.herokuapp.com/) *** ### **User Experience (UX)** **User stories** For someone who wanted to try different sorts of mixes, I want to: - Be able to navigate freely and easily - Able to search for what i want easily - Be able to add reviews or feedbacks For someone who is a liquor guru, I want to: - Be able to share my creations easily - Be able to edit my creations easily - Be able to delete my creations easily - Be able to look at the reviews and reply For bartenders/pub owners etc, I want to: - Be able to search for the liquor easily should customer request - Be able to easily view the details and preparation method **Some UX considerations** - The navbar at the top is found on every page, for easy navigation. - Adding and upload of image is made simple with clear instructions. - Images are fixed into squares to make the page looks neat - Hovering above the selected image will show a prominent pop-up for user - Back buttons are added to allow users to return should no actions to be made - Alert messages are prompted should users want to delete - Flash messages are added after an action is executed - Easy search filter by categories or name search provided ### **UI** - Navbar is presented on every page, with the website logo. #### Home page - A simple navbar for users to navigate and a jumbotron with an add button #### Edit liquor page - Page is divided cleanly in half, with details to be added on left and image to be uploaded on right. Image uploaded will be shown which explains the space. - Submit and add button at the bottom for execution #### Liquor listing page - Name filter and category filter is found and can be used - Reset search button to clear search results and display all items - Cards are arranged neatly in 3 columns and images are made squared for neatness #### Liquor details page - Image name will be displayed to indicate which liquor user is at - A larger image of the liquor is displayed on the left with its details on the right - Information here are all read only - Reviews of the liquor are displayed below - Buttons to edit or delete the liquor are presented on this page - Add review button is available here as well for users to add their reviews - The reviews are presented in boxes, with their respective details - Edit or delete for reviews are indicated with the edit or delete symbols #### Add review page - User can input their username and comment here - Date is tracked separately the moment submit button is clicked #### Edit review page - The username and date will not be shown or allowed to edit - Only comments can be edited #### Delete liquor/review page - Prompt whether to proceed or cancel to return to previous page *** ### **Technologies used** - HTML - CSS - Python - Bootstrap (4.4.1) - Fontawesome - Cloudinary to store and import files to MongoDB - Flask with Jinja2 - Pymongo - MongoDB as the noSQL database *** ### **Testing** The test site is tested to be responsive for: - iphone 4 - galaxy s5 - iphone 5/se - iphone 6/7/8 - iphone 6/7/8 plus - iphone X - ipad - ipad pro - google chrome - microsoft edge - safari - internet explorer Basic checks include: - Testing that the C(Create), R(Read), U(Update), D(Delete) functions for liquor and reviews are working - Checking that the filter for both name search and category search are working - Testing that the navbar link categories are working - Testing that the read only fields cannot be edited - Testing that the route for all buttons are set correctly and working fine Known errors: - If updating on liquor details, need to reupload the image again - Time saved at review paged is in UTC (Coordinated Universal Time) Features left to implement: - User logins and logouts - Editing feature to be limited to what user input only - Replies to comments/reviews - Advanced filter options *** ### **Deployment** The code is written using gitpod and pushed to github. Since Flask and Mongo is being used, deployment is done with the help of Heroku and pushed to Heroku Master as well. *** ### **Credits** - Site images are taken from [unsplash.com](https://unsplash.com/) - Liquor images and details are taken from [wikipedia](https://en.wikipedia.org/wiki/List_of_cocktails) - Icons are taken from [fontawesome](https://fontawesome.com/) - Logo is made using [hatchful](https://hatchful.shopify.com/) - Colour gradient is taken from [webgradients](https://webgradients.com/) - Mock up is obtained from [mockup_generator](https://techsini.com/multi-mockup/index.php) *Site is strictly for educational purposes
Python
UTF-8
4,659
2.78125
3
[ "MIT" ]
permissive
#!/bin/env python3 import argparse import json import logging import os import subprocess import tempfile from typing import List from urllib import request REPO = 'https://raw.githubusercontent.com/gockelhahn/qual-o-mat-data' class Party: def __init__(self, id: int, name: str): self.id = id self.name = name self.answers = dict() def answer(self, statement: int, answer: int): if answer == 0: # positive self.answers[statement] = 1.0 elif answer == 1: # negative self.answers[statement] = 0.0 else: # neutral self.answers[statement] = 0.5 def answer_normalized(self, statement: int, answer: float): self.answers[statement] = answer * 20.0 def similar(self, party) -> int: value = 0 for index, answer in self.answers.items(): value += abs(answer - party.answers[index]) return value * 2.0 class Renderer: def __init__(self, data_key): self.data_key = data_key self.parties = dict() def open_data(self, path): if self.data_key[0] == ".": logging.info('Opening file ' + self.data_key + path) return open(self.data_key + path, "r") else: logging.info('Requesting ' + REPO + '/master/data/' + self.data_key + path) return request.urlopen(REPO + '/master/data/' + self.data_key + path) def get_parties(self): with self.open_data('/party.json') as response: logging.info('Parsing response') for party in json.load(response): self.parties[party['id']] = Party(party['id'], party['name']) def load_answers(self, normalized): with self.open_data('/opinion.json') as response: logging.info('Parsing response') for opinion in json.load(response): if normalized: self.parties[opinion['party']].answer_normalized(opinion['statement'], opinion['answer']) else: self.parties[opinion['party']].answer(opinion['statement'], opinion['answer']) def create_nodes(self, dotfile): for party in self.parties.values(): dotfile.write(' "' + party.name + '"') dotfile.write('[fillcolor="#ffffff",fontname=opensans,fontsize=11,') dotfile.write('height=0.5,margin=.04,shape=ellipse,style=filled];\n') def create_edges(self, dotfile): for party1 in self.parties.values(): for party2 in self.parties.values(): if party1.id >= party2.id: continue distance = float(party1.similar(party2)) / 8.0 dotfile.write(' "' + party1.name + '" -- "' + party2.name + '"') dotfile.write('[arrowtype=none,color="#aaaaaa",len=' + str(distance) + '];\n') def render(self, neato: str, output: str): fd, dotfilepath = tempfile.mkstemp(suffix='.dot', text=True) logging.info('Writing graph to ' + dotfilepath) dotfile = os.fdopen(fd, "w") dotfile.write('graph {\n') dotfile.write(' graph [outputorder=edgesfirst,rankdir=LR];\n') dotfile.write(' node [label="\\N"];\n') self.create_nodes(dotfile) self.create_edges(dotfile) dotfile.write('}\n') dotfile.close() args = [neato, dotfilepath, '-Tpng', '-o', output] logging.info('Running ' + ' '.join(args)) subprocess.run(args, check=True) os.remove(dotfilepath) def main(): parser = argparse.ArgumentParser(description='Visualize wahl-o-mat data.') parser.add_argument('-n', '--neatopath', dest='neato', type=str, default='neato', help='Path to neato executable (default: "neato")') parser.add_argument('-o', '--output', dest='output', type=str, default='wahlomat.png', help='Destination for generated visualization (default: "wahlomat.png")') parser.add_argument('-v', '--verbose', dest='verbose', default=False, action="store_true", help="Increase output verbosity") parser.add_argument('--normalized', dest='normalized', default=False, action='store_true', help='Treat answers as normalized values between 0.0 and 1.0.' + 'By default answers are expected to be one of positive (1), neutral(0) or negative(-1).') parser.add_argument('data', type=str, help='Path to data in github.com/gockelhahn/qual-o-mat-data repository (e.g. 2019/europa).' + 'If "data" starts with ".", it will treates as relative local path, e.g. "./lilliput".') args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.INFO) renderer = Renderer(args.data) renderer.get_parties() renderer.load_answers(args.normalized) renderer.render(args.neato, args.output) logging.info('Done') if __name__ == '__main__': main()
Python
UTF-8
1,383
2.96875
3
[ "BSD-2-Clause" ]
permissive
#!/usr/bin/env python3 # # memmap.py - small utility to print the memory map of a process on Linux (and probably other Unices as well) # *and* Windows (similiar to the pmap command found on Linux and Solaris) # # Copyright(C) 2019 Constantin Wiemer import psutil import os import sys # # format size of the memory mapping so that it's human-readable # def fmtsize (size): if size > 1073741824: size = str(int(size / 1073741824)) + 'G' elif size > 1048576: size = str(int(size / 1048576)) + 'M' elif size > 1024: size = str(int(size / 1024)) + 'K' return size p = psutil.Process(int(sys.argv[1])) print('{:33}\t{:>5} / {:>5}\t{}\t{}'.format('ADDRESS RANGE', 'RSS', 'SIZE', 'PERM', 'NAME')) for m in p.memory_maps(grouped=False): if sys.platform == 'win32': start = int(m.addr, 16) end = start + int(m.rss) print('{:016x}-{:016x}\t{:>5} / {:>5}\t{}\t{}'.format( start, end, fmtsize(m.rss), '?', m.perms, os.path.basename(m.path) )) else: start, end = [int(x, 16) for x in m.addr.split('-')] print('{:016x}-{:016x}\t{:>5} / {:>5}\t{}\t{}'.format( start, end, fmtsize(m.rss), fmtsize(m.size), m.perms, os.path.basename(m.path) ))
Java
UTF-8
680
1.960938
2
[]
no_license
package com.testyle.dao; import com.testyle.model.Data; import com.testyle.model.Project; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; public interface IDataDao { List<Data> select(Data data); int insert(Data data); int delete(@Param("table")String table, @Param("taskID")long taskID); int update(Data data); int insertList(@Param("table") String table,@Param("dataList")List<Data> dataList); long selOne(Data data); int updateList(@Param("table") String table,@Param("list")List<Data> dataList); List<Map<String,Object>> getRecord(long proID); List<Map<String,Object>> getItem(long recordID); }
Python
UTF-8
702
2.640625
3
[]
no_license
import math from _ast import List from raytracer.hitable import Hitable, HitRecord from raytracer.ray import Ray class HitableList(Hitable): def __init__(self, hitables=None): self.hitables = hitables def get_hitables(self): return self.hitables def hit(self, ray: Ray, t_min: float, t_max: float) -> HitRecord: hit_record = None closest_so_far = t_max for hitable in self.hitables: temp_record = hitable.hit(ray, t_min, closest_so_far) if temp_record is not None: closest_so_far = temp_record.get_t() hit_record = temp_record return hit_record
C#
UTF-8
3,456
2.828125
3
[]
no_license
using CocosSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HeroesRpg.Client.Game.Graphic.Element { /// <summary> /// /// </summary> public class EnergyBar : CCDrawNode { public Func<float> CurrentEnergy { get; private set; } public Func<float> MaxEnergy { get; private set; } public float Ratio { get { return CurrentEnergy() / Math.Max(1, MaxEnergy()); } } public float Width { get; set; } public float Height { get; set; } public float MidWidth { get { return Width / 2; } } public float MidHeight { get { return Height / 2; } } public Func<CCColor4B> Foreground { get; private set; } public Func<CCColor4B> Background { get; private set; } public Func<CCColor4B> TextColor { get; private set; } private Label TextLabel { get; set; } /// <summary> /// /// </summary> /// <param name="currentEnergy"></param> /// <param name="maxEnergy"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="bg"></param> /// <param name="fg"></param> /// <param name="textColor"></param> public EnergyBar(float width, float height, Func<float> currentEnergy, Func<float> maxEnergy, Func<CCColor4B> bg, Func<CCColor4B> fg, Func<CCColor4B> textColor) : this(width, height) { Initialize(currentEnergy, maxEnergy, bg, fg, textColor); } /// <summary> /// /// </summary> public EnergyBar(float width, float height) { Width = width; Height = height; TextLabel = new Label("?/?", CCColor3B.White); TextLabel.PositionX = PositionX + MidWidth; TextLabel.PositionY = PositionY + MidHeight + 0.5f; TextLabel.AnchorPoint = CCPoint.AnchorMiddle; TextLabel.Scale = 0.50f; AddChild(TextLabel); } /// <summary> /// /// </summary> /// <param name="currentEnergy"></param> /// <param name="maxEnergy"></param> /// <param name="bg"></param> /// <param name="fg"></param> /// <param name="textColor"></param> public void Initialize(Func<float> currentEnergy, Func<float> maxEnergy, Func<CCColor4B> bg, Func<CCColor4B> fg, Func<CCColor4B> textColor) { CurrentEnergy = currentEnergy; MaxEnergy = maxEnergy; Background = bg; Foreground = fg; TextColor = textColor; Redraw(); } /// <summary> /// /// </summary> public void Redraw() { const float padding = 1.5f; const float doblepadding = 2 * padding; Cleanup(); var txtColor = TextColor(); var bgColor = Background(); var fgColor = Foreground(); TextLabel.Color = new CCColor3B(txtColor); TextLabel.Text = $"{Math.Round(CurrentEnergy(), 1)}/{MaxEnergy()}"; DrawRect(new CCRect(-padding, -padding, Width + doblepadding, Height + doblepadding), bgColor, 0.5f, CCColor4B.Blue); DrawRect(new CCRect(0, 0, Width * Math.Min(1, Ratio), Height), fgColor); } } }
C++
UTF-8
1,709
2.8125
3
[]
no_license
#include <QDebug> #include <QDir> #include <QFile> #include <QApplication> #include "stylesheetmanager.h" StyleSheetManager::StyleSheetManager(QObject *parent) : QObject(parent) { } StyleSheetManager::StyleSheetManager( const QString &filePath, QObject *parent ) : QObject(parent) { setFilePath(filePath); } bool StyleSheetManager::load(const QString &styleStr) { if (!styleStr.isEmpty() && qApp) { qApp->setStyleSheet(styleStr); setFilePath(styleStr); return true; } return false; } bool StyleSheetManager::loadFile(const QString &path) { QString styleStr = readFile(path); return load(styleStr); } //1.2加载指定文件夹下的所有qss文件 bool StyleSheetManager::loadDir(const QString &path) { QString styleStr; QDir dir(path); QFileInfoList fileList = dir.entryInfoList(QDir::Files); foreach (const QFileInfo& file, fileList) { styleStr += readFile(file.absoluteFilePath()); } return load(styleStr); } bool StyleSheetManager::reload() { return loadFile(filePath()); } bool StyleSheetManager::switchTo(const QString &path) { if (isSameFile(path)) { return false; } return loadFile(path); } QString StyleSheetManager::readFile(const QString &path) const { QString ret; QFile file(path); if (file.open(QIODevice::ReadOnly)) { ret = file.readAll(); file.close(); } return ret; } bool StyleSheetManager::isSameFile(const QString &path) const { return filePath() == path; } QString StyleSheetManager::filePath() const { return m_filePath; } void StyleSheetManager::setFilePath(const QString &path) { m_filePath = path; }
JavaScript
UTF-8
5,463
3.640625
4
[]
no_license
(function(window, document, undefined) { /* loops over each flavor in function */ function forEachFlavor(functionToDo) { var container = document.getElementById('container'); var flavors = container.getElementsByClassName('flavor'); for(var i = 0; i < flavors.length; i++) { functionToDo(flavors[i]); } } /* Sets a random integer quantity in range [1, 20] for each flavor. */ function setQuantities() { forEachFlavor(function(flavor) { var title = flavor.getElementsByTagName('div')[0]; var span = document.createElement('span'); var numLeft = Math.floor(Math.random() * 20); span.className = "numLeft"; span.innerHTML = numLeft; title.insertBefore(span, title.childNodes[0]); }); } /* Extracts and returns an array of flavor objects based on data in the DOM. Each * flavor object should contain five properties: * * element: the HTMLElement that corresponds to the .flavor div in the DOM * name: the name of the flavor * description: the description of the flavor * price: how much the flavor costs * quantity: how many cups of the flavor are available */ function extractFlavors() { var flaveArr = []; forEachFlavor( function(flavor) { flaveArr[flaveArr.length] = flavor; }); flaveArr = flaveArr.map(function(flavor){ return { element: flavor, name: flavor.querySelector('.description h2').textContent, description: flavor.querySelector('.description p').textContent, price: flavor.querySelector('.meta .price').textContent, quantity: flavor.querySelector('.meta .numLeft').textContent, } }); return flaveArr; } /* Calculates and returns the average price of the given set of flavors. The * average should be rounded to two decimal places. */ function calculateAveragePrice(flavors) { var sum = 0; flavors.forEach(function(flavor) { sum+= parseFloat(flavor.price.replace('$', '')); }); return (sum/flavors.length).toFixed(2); } /* Finds flavors that have prices below the given threshold. Returns an array * of strings, each of the form "[flavor] costs $[price]". There should be * one string for each cheap flavor. */ function findCheapFlavors(flavors, threshold) { var cheapFlavs = []; flavors.forEach(function(flavor) { var price = parseFloat(flavor.price.replace('$', '')); if( price < threshold ) { var toAdd = flavor.name + " costs " + flavor.price; cheapFlavs[cheapFlavs.length] = toAdd; } }); return cheapFlavs; } /* Populates the select dropdown with options. There should be one option tag * for each of the given flavors. */ function populateOptions(flavors) { var flavChoices = document.querySelector('#footer select[name="flavor"]'); var i = 0; flavors.forEach(function(flavor) { var newOp = document.createElement('option'); newOp.innerHTML = flavor.name; newOp.value = i++; flavChoices.insertBefore(newOp); }); } function addEventListenerToSubmit(flavors, addEventFunc) { var select = document.querySelector('#footer input[type="submit"]'); select.addEventListener("click", function(event) { event.preventDefault(); var input = document.querySelector('#footer select[name="flavor"]'); var flavor = flavors[input.value]; var flavElem = flavor.element; addEventFunc(flavor, flavElem); }); } /* Processes orders for the given set of flavors. When a valid order is made, * decrements the quantity of the associated flavor. */ function processOrders(flavors) { addEventListenerToSubmit(flavors, function(flavor, flavElem) { var amount = document.querySelector('#footer input[name="amount"]').value; if(flavor.quantity - amount >= 0) { flavor.quantity -= amount; flavElem.querySelector('.numLeft').innerHTML = flavor.quantity; } else console.log("invalid number entered, not enough " + flavor.name); }); } /* Highlights flavors when clicked to make a simple favoriting system. */ function highlightFlavors(flavors) { flavors.forEach(function(flavor) { var flavElem = flavor.element; flavElem.addEventListener("click", function(event) { if(!flavElem.classList.contains("highlighted")) flavElem.classList.add("highlighted"); else flavElem.classList.remove("highlighted"); })}); } /***************************************************************************/ /* */ /* Please do not modify code below this line, but feel free to examine it. */ /* */ /***************************************************************************/ var CHEAP_PRICE_THRESHOLD = 1.50; // setting quantities can modify the size of flavor divs, so apply the grid // layout *after* quantities have been set. setQuantities(); var container = document.getElementById('container'); new Masonry(container, { itemSelector: '.flavor' }); // calculate statistics about flavors var flavors = extractFlavors(); var averagePrice = calculateAveragePrice(flavors); console.log('Average price:', averagePrice); var cheapFlavors = findCheapFlavors(flavors, CHEAP_PRICE_THRESHOLD); console.log('Cheap flavors:', cheapFlavors); // handle flavor orders and highlighting populateOptions(flavors); processOrders(flavors); highlightFlavors(flavors); })(window, document);
Java
UTF-8
198
2.5625
3
[]
no_license
import java.util.Scanner; class Main { public static void main (String[] args) { Scanner el= new Scanner(System.in); int n1=el.nextInt(); int a=n1*n1; System.out.print(a); } }
Java
UTF-8
5,911
2.375
2
[]
no_license
package org.matcha.server.concurrent; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Executor; import org.matcha.server.net.DefaultServerSocketFactory; import org.matcha.server.net.SocketWrapper; import org.matcha.server.po.CreateSocketType; import org.matcha.server.po.MongoBean; import org.matcha.server.po.SocketPropertityBean; import org.matcha.server.proxy.ConfigProxy; import org.matcha.server.scheduler.job.impl.DataTransferJobImmediate; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yuxindata.iomp.util.StringUtils; public class ServerSocketListener{ Logger logger = LoggerFactory.getLogger(getClass()); protected volatile boolean running = true; public void start() { //申请处理线程池 setExecutor(ExecutorFactory.getDefaultExecutor()); ServerSocketThread serverSocketThread = new ServerSocketThread(); Thread thread = new Thread(serverSocketThread); thread.start(); } /** * 关闭当前socket * @param socket */ private void closeSocket(Socket socket) { // TODO Auto-generated method stub try { socket.close(); } catch (IOException e) { // 直接忽略 } } /** * 线程执行者 */ private Executor executor = null; public void setExecutor(Executor executor) { this.executor = executor; } public Executor getExecutor() { return executor; } /** * 切断连接 */ protected void countDownConnection() { // TODO Auto-generated method stub //未完待续 } /** * 若达到了最大连接数则等待 */ protected void countUpOrAwaitConnection() { // TODO Auto-generated method stub //未完待续 } private static final String SCHEDULE_SWITCH = "matcha.schedule.switch"; /** * 处理此次请求 * @param socket * @return */ protected boolean processSocket(Socket socket) { //根据system配置文件决定接收的socket是否需要即时处理 String offOrOn = (String) ConfigProxy.getSystemConfigMap().get(SCHEDULE_SWITCH); SocketWrapper<Socket> wrapper; if(offOrOn.equalsIgnoreCase("on")) { wrapper = new SocketWrapper<Socket>(socket); } else { wrapper = new SocketWrapper<Socket>(socket,true); } //如果停止了则直接返回 if(!running) { return false; } getExecutor().execute(new SocketProcessor(wrapper)); return true; } private class ServerSocketThread implements Runnable { @Override public void run() { // TODO Auto-generated method stub //获取socket配置信息 SocketPropertityBean socketPropertityBean = ConfigProxy.getSocketProperty(); DefaultServerSocketFactory socketFactory = new DefaultServerSocketFactory(); ServerSocket serverSocket = null; try{ if(socketPropertityBean.getCreateSocketType().equals(CreateSocketType.BY_PORT)) { serverSocket = socketFactory.createSocket(socketPropertityBean.getPort()); }else if(socketPropertityBean.getCreateSocketType().equals(CreateSocketType.BY_PORT_BACKLOG)) { serverSocket = socketFactory.createSocket(socketPropertityBean.getPort(), socketPropertityBean.getBacklog()); } else if(socketPropertityBean.getCreateSocketType().equals(CreateSocketType.BY_PORT_BACKLOG_IP)) { InetAddress ifAddress = InetAddress.getByName(socketPropertityBean.getIpAddress()); serverSocket = socketFactory.createSocket(socketPropertityBean.getPort(), socketPropertityBean.getBacklog(), ifAddress); } }catch (InstantiationException e) { // TODO Auto-generated catch block //未完待续 e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block //未完待续 e.printStackTrace(); } while(running) { //如果达到最大连接数则等待 countUpOrAwaitConnection(); Socket socket = null; try { socket = socketFactory.acceptSocket(serverSocket); logger.info(socket.getInetAddress()+"已经连接上"); } catch (IOException e) { // TODO Auto-generated catch block countDownConnection(); e.printStackTrace(); } if(!processSocket(socket)) { countDownConnection(); // Close socket right away closeSocket(socket); } } } } protected class SocketProcessor implements Runnable { protected SocketWrapper<Socket> socket = null; public SocketProcessor(SocketWrapper<Socket> socket) { if (socket==null) throw new NullPointerException(); this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub synchronized (socket) { try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getSocket().getInputStream())); String line = in.readLine(); while(line!=null) { if(socket.isImmediateProcessing()) { String [] data = line.split(" "); MongoBean bean = new MongoBean() .withTarget(data[0]) .withValue(data[1]) .withTimestamp(data[2]); DataTransferJobImmediate dataTransferJobImmediate = new DataTransferJobImmediate(bean); try { dataTransferJobImmediate.execute(null); } catch (JobExecutionException e) { // TODO Auto-generated catch block //直接忽略 } } else { String [] data = line.split(" "); ConcurrentList.putDataInList(new MongoBean() .withTarget(data[0]) .withValue(data[1]) .withTimestamp(data[2])); } line = in.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
Python
UTF-8
310
3.78125
4
[]
no_license
print("----------") print("Calculator") print("----------") print("x=?") x = input() print("y=?") y = input() Plus = int(x)+int(y) minute = int(x)-int(y) Multiplacation = int(x)*int(y) Devide = int(x)/int(y) print("x+y","=",Plus) print("x-y","=",minute) print("x*y","=",Multiplacation) print("x/y","=",Devide)
Java
UTF-8
1,961
2.453125
2
[]
no_license
package com.synaptix.component.impl; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.synaptix.component.IPropertyChangeCapable; public abstract class PropertyChangeCapableImpl implements IPropertyChangeCapable { protected transient final List<PropertyChangeListener> propertyChangeListeners = new ArrayList<PropertyChangeListener>(); protected transient final Map<String, List<PropertyChangeListener>> propertyChangeListenerMap = new HashMap<String, List<PropertyChangeListener>>(); @Override public void addPropertyChangeListener(PropertyChangeListener l) { propertyChangeListeners.add(l); } @Override public void removePropertyChangeListener(PropertyChangeListener l) { propertyChangeListeners.remove(l); } @Override public void addPropertyChangeListener(String propertyName, PropertyChangeListener l) { List<PropertyChangeListener> ls = propertyChangeListenerMap.get(propertyName); if (ls == null) { ls = new ArrayList<PropertyChangeListener>(); propertyChangeListenerMap.put(propertyName, ls); } ls.add(l); } @Override public void removePropertyChangeListener(String propertyName, PropertyChangeListener l) { List<PropertyChangeListener> ls = propertyChangeListenerMap.get(propertyName); if (ls != null) { ls.remove(l); if (ls.isEmpty()) { propertyChangeListenerMap.remove(propertyName); } } } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { PropertyChangeEvent evt = new PropertyChangeEvent(this, propertyName, oldValue, newValue); for (PropertyChangeListener l : propertyChangeListeners) { l.propertyChange(evt); } List<PropertyChangeListener> ls = propertyChangeListenerMap.get(propertyName); if (ls != null) { for (PropertyChangeListener l : ls) { l.propertyChange(evt); } } } }
Java
UTF-8
761
2.140625
2
[]
no_license
package ru.vksychev.cart.controller; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @ControllerAdvice(annotations = RestController.class) public class ExceptionHandlingController { /** * Возвращение CONFLICT статуса после DataIntegrityViolationException */ @ResponseStatus(value= HttpStatus.CONFLICT) @ExceptionHandler(DataIntegrityViolationException.class) public void conflict(){ } }
Markdown
UTF-8
2,434
2.78125
3
[]
no_license
# SFRA Webpack builder ## Why use it? Webpack can be cumbersome to setup, especially in multicartridge projects for SFRA. This plugin let you bundle all your `js`, `scss` and `jsx` files out of the box. - One pre-build `webpack.config.js` for all cartridges and plugins - No more `sgmf-script`, which interferes with `Prophet uploader` - Supports multicartridge projects due to simple configuration - Supports aliases for `require` loading ## Prerequisite - Run `npm install` to install all needed `node_modules` - Install [SFRA](https://github.com/SalesforceCommerceCloud/storefront-reference-architecture) - Run `npm install` in *SFRA* - Install all SFRA related plugins you would like to use and install their dependencies - Clone the repository and place it in a folder structure like this *** make sure you installed node_modules in your plugins as well using npm install command *** **Other structures are also supported as long as you configure the path accordingly in `sfraBuilderConfig.js`** Example Structure ``` . +-- storefront-reference-applicaton +-- plugin_one +-- plugin_two +-- .... +-- sfra-webpack-builder ``` ## Usage - Run `npm install`. - Copy `webpackHandling/example_sfraBuilderConfig.js` to `webpackHandling/sfraBuilderConfig.js` to define your own config - Configure *cartridges* and *aliases* in `webpackHandling/sfraBuilderConfig.js` **(Ensure that the paths in `webpackHandling/sfraBuilderConfig.js` point correctly to the included SFRA and plugins according to your directory structure)** The paths needs to be set relatively to *webpack.config.js* - Run `npm run watch` or `npm run prod`. This will compile all related `js/jsx & css` files included in the directories which are defined in `webpackHandling/sfraBuilderConfig.js` ### Aliases `module.exports.aliasConfig` let you specify, how to load module packages inside your plugin. ```js module.exports.aliasConfig = { // enter all aliases to configure base: path.resolve( process.cwd(), '../storefront-reference-architecture/cartridges/app_storefront_base/cartridge/client/default/' ), CustomPlugin: path.resolve( process.cwd(), '../plugin_wishlists/cartridges/plugin_wishlists/cartridge/client/default/' ) } ``` `CustomPlugin` allows to retrieve use modules through catrdiges using `require('CustomPlugin/default/js/myFile.js');` or `import Foo from CustomPlugin/default/js/myFile`;
PHP
UTF-8
813
2.546875
3
[]
no_license
<?php class admin_page_COMMENTS extends RF_Admin_Page { function __construct() { $this->name = "comments"; $this->label = "Comment"; $this->label_plural = "Comments"; $this->admin_menu = 40; $this->icon = "forums"; $this->permissions = array( "all" => "manage_comments" ); // Be sure to set up the parent parent::__construct(); } function index($args) { } function edit($args) { } function save($args) { } function delete($args) { } /** * Permission Overrides * Uncomment and use these permissions functions to set exact permission behavior */ /* protected function can_view($args) { } protected function can_edit($args) { } protected function can_save($args) { } protected function can_delete($args) { } */ } new admin_page_COMMENTS();
Java
UTF-8
1,297
2.078125
2
[]
no_license
package no.nmdc.oaipmh.provider.init; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; /** * Application initalization. This allows us to init without the web.xml file. * * @author kjetilf */ public class ApplicationInit extends AbstractDispatcherServletInitializer { @Override protected String[] getServletMappings() { return new String[]{"/request/*"}; } @Override protected WebApplicationContext createRootApplicationContext() { AnnotationConfigWebApplicationContext cxt = new AnnotationConfigWebApplicationContext(); cxt.scan("no.nmdc.oaipmh.provider"); return cxt; } @Override public void onStartup(final ServletContext servletContext) throws ServletException { super.onStartup(servletContext); } @Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext cxt = new AnnotationConfigWebApplicationContext(); return cxt; } }
TypeScript
UTF-8
3,968
2.5625
3
[ "MIT" ]
permissive
import { Body, Controller, Delete, Get, HttpException, HttpStatus, Param, Post, Put, UseInterceptors } from '@nestjs/common'; import { exception } from 'console'; import { ValidatorInterceptor } from 'src/interceptors/validator.interceptor'; import { CreateAddressContract } from '../contracts/customer/create-address.contract'; import { CreateCustomerContract } from '../contracts/customer/create-customer.contract'; import { CreatePetContract } from '../contracts/customer/create-pet.contract'; import { CreateCustomerDto } from '../dtos/create-customer-dto'; import { Address } from '../models/address.model'; import { Customer } from '../models/customer.model'; import { Pet } from '../models/pet.model'; import { Result } from '../models/result.model'; import { User } from '../models/user.model'; import { AccountService } from '../services/account.service'; import { CustomerService } from '../services/customer.service'; //localhost:3000/customers @Controller('v1/customers') //Base da Url export class CustomerController { constructor( private readonly accountService: AccountService, private readonly customerService: CustomerService) { } @Get() get() { return new Result(null, true, [], null); } @Get(':document') getById(@Param('document') document) { return new Result(null, true, {}, null); } @Post() @UseInterceptors(new ValidatorInterceptor(new CreateCustomerContract)) async post(@Body() model: CreateCustomerDto) { try { const user = await this.accountService.create( new User(model.document, model.password, true) ); const customer = new Customer(model.name, model.document, model.email, null, null, null, null, user) const res = await this.customerService.create(customer); return new Result('Cliente Criado com sucesso', true, res, null); }catch(error){ throw new HttpException(new Result('Não foi possível realizar seu cadastro', false, null, error), HttpStatus.BAD_REQUEST); } } @Post(':document/address/billing') @UseInterceptors(new ValidatorInterceptor(new CreateAddressContract)) async AddBillingAddress(@Param('document') document, @Body() model:Address){ try { await this.customerService.AddBillingAddress(document, model); return new Result(null, true, model, null); } catch (error) { throw new HttpException(new Result('Não foi possível adicionar seu endereço', false, null, error), HttpStatus.BAD_REQUEST); } } @Post(':document/address/shipping') @UseInterceptors(new ValidatorInterceptor(new CreateAddressContract)) async AddShippingAddress(@Param('document') document, @Body() model:Address){ try { await this.customerService.AddShippingAddress(document, model); return new Result(null, true, model, null); } catch (error) { throw new HttpException(new Result('Não foi possível adicionar seu endereço', false, null, error), HttpStatus.BAD_REQUEST); } } @Post(':document/pets') @UseInterceptors(new ValidatorInterceptor(new CreatePetContract)) async CreatePet(@Param('document') document, @Body() model:Pet){ try { await this.customerService.CreatePet(document, model); return new Result(null, true, model, null); } catch (error) { throw new HttpException(new Result('Não foi possível adicionar seu pet', false, null, error), HttpStatus.BAD_REQUEST); } } @Put(':document') put(@Param('document') document, @Body() body) { return new Result('Cliente atualizado com sucesso', true, body, null); } @Delete(':document') delete(@Param('document') document, @Body() body) { return new Result('Cliente removido com sucesso', true, body, null); } }
C#
UTF-8
23,964
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; namespace Snake { class Snake { #region pola klasy private ContentManager content; private Texture2D head; private Texture2D ogon; private Texture2D srodek; private Texture2D zakret; private Vector2 polozenieGlowy; private Vector2 polozenieOgona; private List<Vector2> polozenieZakretow; static public float Pi = (float)Math.PI; private int kierunek;////1-gora 2-dol 3-prawo 4-lewo private int kierunekOgona; private Vector2 obrotOgona; private float rotacjaOgona; private Vector2 obrotGlowy; private float rotacjaGlowy; #endregion //----------------------------------------------------------------------------------------------- public int Kierunek { get { return kierunek; } } //----------------------------------------------------------------------------------------------- public List<Vector2> Poleznia() { List<Vector2> zwracnie = new List<Vector2>(); zwracnie.Add(polozenieOgona); for (int i = polozenieZakretow.Count - 1; i >= 0; i--) { zwracnie.Add(polozenieZakretow[i]); } return zwracnie; } //----------------------------------------------------------------------------------------------- public Vector2 GlowaPolozenie { get { return polozenieGlowy; } } //----------------------------------------------------------------------------------------------- public Snake(ContentManager content)//konstruktor pobiera tylko content { this.content = content; } //----------------------------------------------------------------------------------------------- public void Initialize()//przygotowanie klasy do rozpoczecia gry { head = content.Load<Texture2D>("glowa"); ogon = content.Load<Texture2D>("ogon"); srodek = content.Load<Texture2D>("srodek"); zakret = content.Load<Texture2D>("zakret1"); polozenieZakretow = new List<Vector2>(); rotacjaGlowy = 0f; rotacjaOgona = 0f; obrotGlowy = new Vector2(0f, 0f); obrotOgona = new Vector2(0f, 0f); polozenieGlowy = new Vector2(680, 352); polozenieOgona = new Vector2(552, 352); kierunek = 3; kierunekOgona = kierunek; } //----------------------------------------------------------------------------------------------- private void DrawMiddleRightLeft(float first, float second, float y, SpriteBatch spriteBatch) { for (int i = (int)first; i < second; i += 64) { spriteBatch.Draw(srodek, new Vector2(i, y), Color.White); } } //----------------------------------------------------------------------------------------------- private void DrawMiddleUpDown(float first, float second, float x, SpriteBatch spriteBatch) { for (int i = (int)first; i < second; i += 64) { spriteBatch.Draw(srodek, new Vector2(x, i), null, Color.White, 1.5f * Pi, new Vector2(64, 0), 1f, SpriteEffects.None, 0f); } } //----------------------------------------------------------------------------------------------- private void DrawBettwenCorner(Vector2 first, Vector2 second, SpriteBatch spriteBatch) { if (first.Y == second.Y)//jesli zakret i ogon sa w jednym poziomie { if (first.X < second.X)//ogon ma kierunek w prawa strone { DrawMiddleRightLeft(first.X + 64, second.X, first.Y, spriteBatch); } else { DrawMiddleRightLeft(second.X + 64, first.X, first.Y, spriteBatch); } } else//jesli zakret i ogon sa w pionie { if (first.Y > second.Y) { DrawMiddleUpDown(second.Y + 64, first.Y, first.X, spriteBatch); } else { DrawMiddleUpDown(first.Y + 64, second.Y, first.X, spriteBatch); } } } //----------------------------------------------------------------------------------------------- private void DrawTurns(Vector2 first, Vector2 second, Vector2 third, SpriteBatch spriteBatch) { if (first.Y == second.Y) { if (first.X < second.X) { if (second.Y > third.Y) { spriteBatch.Draw(zakret, second, null, Color.White, 1f * Pi, new Vector2(64, 64), 1f, SpriteEffects.None, 0f);//tick } else { spriteBatch.Draw(zakret, second, null, Color.White, 0.5f * Pi, new Vector2(0, 64), 1f, SpriteEffects.None, 0f);//tick } } else { if (second.Y > third.Y) { spriteBatch.Draw(zakret, second, null, Color.White, 1.5f * Pi, new Vector2(64, 0), 1f, SpriteEffects.None, 0f);//tick } else { spriteBatch.Draw(zakret, second, null, Color.White);//tick } } } else { if (first.Y < second.Y) { if (second.X < third.X) { spriteBatch.Draw(zakret, second, null, Color.White, 1.5f * Pi, new Vector2(64, 0), 1f, SpriteEffects.None, 0f); } else { spriteBatch.Draw(zakret, second, null, Color.White, 1f * Pi, new Vector2(64, 64), 1f, SpriteEffects.None, 0f);//tick } } else { if (second.X < third.X) { spriteBatch.Draw(zakret, second, null, Color.White);//tick } else { spriteBatch.Draw(zakret, second, null, Color.White, 0.5f * Pi, new Vector2(0, 64), 1f, SpriteEffects.None, 0f);//tick } } } } //----------------------------------------------------------------------------------------------- public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(head, polozenieGlowy, null, Color.White, rotacjaGlowy, obrotGlowy, 1f, SpriteEffects.None, 0f);//rysowanie glowy spriteBatch.Draw(ogon, polozenieOgona, null, Color.White, rotacjaOgona, obrotOgona, 1f, SpriteEffects.None, 0f);//rysowanie ogona #region Rysowanie snake bez zakretow if (polozenieZakretow.Count == 0) { if (polozenieGlowy.Y == polozenieOgona.Y) { if (polozenieGlowy.X > polozenieOgona.X) { DrawMiddleRightLeft(polozenieOgona.X + 64, polozenieGlowy.X, polozenieGlowy.Y, spriteBatch); } else { DrawMiddleRightLeft(polozenieGlowy.X + 64, polozenieOgona.X, polozenieGlowy.Y, spriteBatch); } } else { if (polozenieGlowy.Y < polozenieOgona.Y) { DrawMiddleUpDown(polozenieGlowy.Y + 64, polozenieOgona.Y, polozenieGlowy.X, spriteBatch); } else { DrawMiddleUpDown(polozenieOgona.Y + 64, polozenieGlowy.Y, polozenieGlowy.X, spriteBatch); } } } #endregion #region rysowanie snaka z zakretami else { for (int i = polozenieZakretow.Count - 1; i >= 0; i--) { if (i == polozenieZakretow.Count - 1) { DrawBettwenCorner(polozenieOgona, polozenieZakretow[i], spriteBatch); if (i - 1 < 0) { DrawTurns(polozenieOgona, polozenieZakretow[i], polozenieGlowy, spriteBatch); } else { DrawTurns(polozenieOgona, polozenieZakretow[i], polozenieZakretow[i - 1], spriteBatch); } } else { DrawBettwenCorner(polozenieZakretow[i + 1], polozenieZakretow[i], spriteBatch); if (i - 1 < 0) { DrawTurns(polozenieZakretow[i + 1], polozenieZakretow[i], polozenieGlowy, spriteBatch); } else { DrawTurns(polozenieZakretow[i + 1], polozenieZakretow[i], polozenieZakretow[i - 1], spriteBatch); } } } DrawBettwenCorner(polozenieZakretow[0], polozenieGlowy, spriteBatch); } #endregion } //------------------------------------------------------------------------------------------------ private bool HeadMove(int distance)//przemieszcza glowe o dany dystans { switch (kierunek) { case 1: if (polozenieGlowy.Y - 64 < 32) { return true; } if (CzyWSiebie(polozenieGlowy) == true) { return true; } rotacjaGlowy = 1.5f * Pi; obrotGlowy = new Vector2(64, 0); polozenieGlowy.Y -= distance; break; case 2: if (polozenieGlowy.Y + 64 > 672) { return true; } if (CzyWSiebie(polozenieGlowy) == true) { return true; } rotacjaGlowy = 0.5f * Pi; obrotGlowy = new Vector2(0, 64); polozenieGlowy.Y += distance; break; case 3: if (polozenieGlowy.X + 64 > 1256) { return true; } if (CzyWSiebie(polozenieGlowy) == true) { return true; } rotacjaGlowy = 0f; obrotGlowy = new Vector2(0, 0); polozenieGlowy.X += distance; break; case 4: if (polozenieGlowy.X - 64 < 40) { return true; } if (CzyWSiebie(polozenieGlowy) == true) { return true; } rotacjaGlowy = Pi; obrotGlowy = new Vector2(64, 64); polozenieGlowy.X -= distance; break; } return false; } //------------------------------------------------------------------------------------------------ private void TailMove(int distance)//przemieszcza ogona o dany dystans { if (polozenieZakretow.Count == 0) { switch (kierunekOgona) { case 1: rotacjaOgona = 1.5f * Pi; obrotOgona = new Vector2(64, 0); polozenieOgona.Y -= distance; break; case 2: rotacjaOgona = 0.5f * Pi; obrotOgona = new Vector2(0, 64); polozenieOgona.Y += distance; break; case 3: rotacjaOgona = 0f; obrotOgona = new Vector2(0, 0); polozenieOgona.X += distance; break; case 4: rotacjaOgona = Pi; obrotOgona = new Vector2(64, 64); polozenieOgona.X -= distance; break; } } else { #region przemieszczania ogona po zakretach switch (kierunekOgona) { case 1: #region if (polozenieZakretow[polozenieZakretow.Count - 1].Y >= polozenieOgona.Y - 64) { polozenieOgona = polozenieZakretow[polozenieZakretow.Count - 1]; polozenieZakretow.RemoveAt(polozenieZakretow.Count - 1); if (polozenieZakretow.Count == 0) { obrotOgona = obrotGlowy; rotacjaOgona = rotacjaGlowy; kierunekOgona = kierunek; } else { if (polozenieZakretow[polozenieZakretow.Count - 1].X < polozenieOgona.X)//zakert po prawej stronie ogona { rotacjaOgona = Pi; obrotOgona = new Vector2(64, 64); kierunekOgona = 4; } else //zakret po lewej stronie ogona { rotacjaOgona = 0f; obrotOgona = new Vector2(0, 0); kierunekOgona = 3; } } } else { polozenieOgona.Y -= 64; } #endregion break; case 2: #region if (polozenieZakretow[polozenieZakretow.Count - 1].Y <= polozenieOgona.Y + 64) { polozenieOgona = polozenieZakretow[polozenieZakretow.Count - 1]; polozenieZakretow.RemoveAt(polozenieZakretow.Count - 1); if (polozenieZakretow.Count == 0) { obrotOgona = obrotGlowy; rotacjaOgona = rotacjaGlowy; kierunekOgona = kierunek; } else { if (polozenieZakretow[polozenieZakretow.Count - 1].X < polozenieOgona.X)//zakert po prawej stronie ogona { rotacjaOgona = Pi; obrotOgona = new Vector2(64, 64); kierunekOgona = 4; } else //zakret po lewej stronie ogona { rotacjaOgona = 0f; obrotOgona = new Vector2(0, 0); kierunekOgona = 3; } } } else { polozenieOgona.Y += 64; } #endregion break; case 3: #region if (polozenieZakretow[polozenieZakretow.Count - 1].X <= polozenieOgona.X + 64) { polozenieOgona = polozenieZakretow[polozenieZakretow.Count - 1]; polozenieZakretow.RemoveAt(polozenieZakretow.Count - 1); if (polozenieZakretow.Count == 0) { obrotOgona = obrotGlowy; rotacjaOgona = rotacjaGlowy; kierunekOgona = kierunek; } else { if (polozenieZakretow[polozenieZakretow.Count - 1].Y < polozenieOgona.Y)//zakert nad ogonem { rotacjaOgona = 1.5f * Pi; obrotOgona = new Vector2(64, 0); kierunekOgona = 1; } else //zakret pod ogonem { rotacjaOgona = 0.5f * Pi; obrotOgona = new Vector2(0, 64); kierunekOgona = 2; } } } else { polozenieOgona.X += 64; } #endregion break; case 4: #region if (polozenieZakretow[polozenieZakretow.Count - 1].X >= polozenieOgona.X - 64) { polozenieOgona = polozenieZakretow[polozenieZakretow.Count - 1]; polozenieZakretow.RemoveAt(polozenieZakretow.Count - 1); if (polozenieZakretow.Count == 0) { obrotOgona = obrotGlowy; rotacjaOgona = rotacjaGlowy; kierunekOgona = kierunek; } else { if (polozenieZakretow[polozenieZakretow.Count - 1].Y < polozenieOgona.Y)//zakert nad ogonem { rotacjaOgona = 1.5f * Pi; obrotOgona = new Vector2(64, 0); kierunekOgona = 1; } else //zakret pod ogonem { rotacjaOgona = 0.5f * Pi; obrotOgona = new Vector2(0, 64); kierunekOgona = 2; } } } else { polozenieOgona.X -= 64; } #endregion break; } #endregion } } //------------------------------------------------------------------------------------------------ public bool Move() { bool zwroc = HeadMove(64); if (zwroc == false) { TailMove(64); } return zwroc; } //------------------------------------------------------------------------------------------------- public bool ChangeDirection(int kierunek) { Vector2 temp = polozenieGlowy; this.kierunek = kierunek; bool zwroc = HeadMove(64); if (zwroc == false) { polozenieZakretow.Insert(0, temp); TailMove(64); } return zwroc; } //------------------------------------------------------------------------------------------------- public void Add() { switch (kierunekOgona) { case 1: polozenieOgona.Y += 64; break; case 2: polozenieOgona.Y -= 64; break; case 3: polozenieOgona.X -= 64; break; case 4: polozenieOgona.X += 64; break; } } //------------------------------------------------------------------------------------------------- private bool CzyWSiebie(Vector2 glowa) { if (polozenieZakretow.Count < 2) { return false; } else { for (int i = polozenieZakretow.Count - 1; i > 0; i--) { if (i == polozenieZakretow.Count - 1) { if (polozenieOgona.X == polozenieZakretow[i].X && polozenieOgona.X == glowa.X) { if ((((polozenieOgona.Y + 30) - glowa.Y) > 0 && (polozenieZakretow[i].Y - (glowa.Y + 30)) < 0)) { return true; } if (((polozenieOgona.Y - (glowa.Y + 30)) < 0 && ((polozenieZakretow[i].Y + 30) - glowa.Y) > 0)) { return true; } } if (polozenieOgona.Y == polozenieZakretow[i].Y && polozenieOgona.Y == glowa.Y) { if ((((polozenieOgona.X + 30) - glowa.X) > 0 && (polozenieZakretow[i].X - (glowa.X + 30)) < 0)) { return true; } if ((polozenieOgona.X - (glowa.Y + 30)) < 0 && ((polozenieZakretow[i].X + 30) - glowa.X) > 0) { return true; } } } else { if (polozenieZakretow[i + 1].X == polozenieZakretow[i].X && polozenieZakretow[i + 1].X == glowa.X) { if ((((polozenieZakretow[i + 1].Y + 30) - glowa.Y) > 0 && (polozenieZakretow[i].Y - (glowa.Y + 30)) < 0)) { return true; } if ((polozenieZakretow[i + 1].Y - (glowa.Y + 30)) < 0 && ((polozenieZakretow[i].Y + 30) - glowa.Y) > 0) { return true; } } if (polozenieZakretow[i + 1].Y == polozenieZakretow[i].Y && polozenieZakretow[i + 1].Y == glowa.Y) { if ((((polozenieZakretow[i + 1].X + 30) - glowa.X) > 0 && (polozenieZakretow[i].X - (glowa.X + 30)) < 0)) { return true; } if ((polozenieZakretow[i + 1].X - (glowa.Y + 30)) < 0 && ((polozenieZakretow[i].X + 30) - glowa.X) > 0) { return true; } } } } } return false; } } }
Python
UTF-8
2,473
3.09375
3
[]
no_license
""" partial convolution implementation """ import torch import torch.nn.functional as F class PConv2d(torch.nn.Conv2d):# bias false per the karpathy tweet 6/30/18 """A partial convolution layer, implemented from Liu et al (2018)""" def __init__(self, in_channels, out_channels, kernel_size, stride=1,\ padding=0, dilation=1, groups=1, bias=False): super().__init__(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=0, dilation=dilation, groups=groups, bias=bias) self.mask_filters = torch.ones(out_channels, in_channels, kernel_size, kernel_size) self.window_size = in_channels * kernel_size * kernel_size self.pad = padding def __call__(self, inp, mask): return self.pforward(inp, mask) def pforward(self, inp, mask): """ The partial convolution forward operation Parameters: ------ inp : the input tensor mask : the mask tensor, which is a map of 0's and 1's corresponding to the points in our image tensor that have been convolved with unmaked pixels Returns ------ f : the featuremap of a 2D partial convolution after the forward new_mask : updated mask to cover parts of the featuremap that have received a bit of influence from the unobscured parts of the image """ if self.pad: mask = F.pad(mask, (self.pad, self.pad, self.pad, self.pad), 'reflect') inp = F.pad(inp, (self.pad, self.pad, self.pad, self.pad), 'reflect') # update after seeing Liu's imp # The mask_ratio from his imp is the gamechanger, should solve the numerical instability (lots of v small numbers leading to nans) # much nicer idiom for skipping gradient calcs with torch.no_grad(): # performs Equation 2 new_mask = F.conv2d(mask, self.mask_filters,\ stride=self.stride, padding=0) mask_ratio = self.window_size/(new_mask + 1e-8) new_mask = torch.clamp(new_mask, 0, 1) mask_ratio = torch.mul(mask_ratio, new_mask) # performs the operation in Equation 1 f = self.forward((inp * mask)) f = torch.mul(f, mask_ratio) return f, new_mask
PHP
UTF-8
1,474
2.515625
3
[ "MIT" ]
permissive
<?php namespace DTL\Extension\Fink\Tests\Integration\Model\Publisher; use DTL\Extension\Fink\Model\Publisher; use DTL\Extension\Fink\Model\ReportBuilder; use DTL\Extension\Fink\Model\Publisher\CsvStreamPublisher; use DTL\Extension\Fink\Model\Url; use DTL\Extension\Fink\Tests\IntegrationTestCase; class CsvStreamPublisherTest extends IntegrationTestCase { public const EXAMPLE_FILEANME = 'test'; public function testPublishesToCsvFile() { $report = ReportBuilder::forUrl(Url::fromUrl('https://www.dantleech.com')) ->withStatus(200) ->build(); $serialized = $this->create()->publish($report); $this->assertEquals(<<<'EOT' https://www.dantleech.com,0,,200,0, EOT , file_get_contents($this->workspace()->path(self::EXAMPLE_FILEANME))); } public function testPublishesToCsvFileWithHeaders() { $report = ReportBuilder::forUrl(Url::fromUrl('https://www.dantleech.com')) ->withStatus(200) ->build(); $serialized = $this->create(true)->publish($report); $this->assertEquals(<<<'EOT' url,distance,referrer,status,request-time,exception https://www.dantleech.com,0,,200,0, EOT , file_get_contents($this->workspace()->path(self::EXAMPLE_FILEANME))); } private function create(bool $withHeaders = false): Publisher { return new CsvStreamPublisher($this->workspace()->path(self::EXAMPLE_FILEANME), $withHeaders); } }
Markdown
UTF-8
1,079
3.09375
3
[ "MIT" ]
permissive
# Anime Quote Generator A random anime quote generator that generates random quotes from different anime series or movies. This generator was made as part of finishing the freeCodeCamp "Build a Random Quote Machine" Zipline challenge. Current amount of quotes: **82** ## Interested in adding more quotes? If you would like to contribute. Just head over to "script.js" and commit the following to the file along with quote you wish to add: ``` anime_quote[] = { "quotenumber": , "quotesentence": "", "quotecharacter": "", "quoteanime": "" } ``` Here's an example. ``` anime_quote[15] = { "quotenumber": 16, "quotesentence": "People tend to show off their act of kindness. It is not an act of good will, it is a demand because they are expecting a word of grace as a reward.", "quotecharacter": "- Itoshiki Nozomu,", "quoteanime": " Sayonara Zetsubou Sensei" } ``` ## Use it in node.js [![NPM](https://nodei.co/npm/animequote.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/animequote/)
Markdown
UTF-8
1,001
2.75
3
[]
no_license
# R-Shiny金融科技概念股公司資料分析<h1> 前面是一些簡單的研究說明和變數介紹<h3> ![GITHUB]( https://upload.cc/i1/2020/03/15/qRUSfO.png) 之後可以查詢公司的各項資料(總資產、股東權益總額、營業費用等...)<h4> 下面可以選擇要不要顯示這個公司的股票資料<h4> ![GITHUB]( https://upload.cc/i1/2020/03/15/Vtsl7z.png) 選擇顯示公司資料,可以選擇想要知道的資料<h4> ![GITHUB]( https://upload.cc/i1/2020/03/15/bHyVEG.png) 比較兩間公司的股票情況<h3> ![GITHUB]( https://upload.cc/i1/2020/03/15/OcYfJV.png) 選擇你想要分析的資料,並顯示兩變數的相關係數(如果選擇公司是不能顯示的喔!!因為公司不是數值資料XD)<h3> P.S.兩個數值資料也沒辦法跑長條圖,要選擇散佈圖喔!!<h3> ![GITHUB](https://upload.cc/i1/2020/03/15/5ZriSQ.png) 最後是每間公司的地圖位置<h3> ![GITHUB](https://upload.cc/i1/2020/03/15/KdjSCA.png)
C
UTF-8
2,464
2.59375
3
[ "MIT" ]
permissive
#include "ColorFrameBuffer.h" ColorFrameBuffer:: ColorFrameBuffer(GLsizei width, GLsizei height) : FrameBuffer(), _width(width), _height(height) { GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_FLOAT, NULL); bind(); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { switch (status) { case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: throw RuntimeError("Incomplete frame buffer attachment."); case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: throw RuntimeError("No color attachment in draw buffer."); case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: throw RuntimeError("No color attachment in read buffer."); case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: throw RuntimeError("Frame buffer is missing an attachment."); case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: throw RuntimeError("The frame buffer specifies different sampling sizes."); case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: throw RuntimeError("Not all frame buffer attachments are layered."); case GL_FRAMEBUFFER_UNSUPPORTED: throw RuntimeError("The frame buffer configuration is unsupported."); default: throw RuntimeError("Unknown frame buffer error."); } } unbind(); } void ColorFrameBuffer:: write() { bind(); const GLsizei DATA_SIZE = _width * _height * (GLsizei) sizeof(GL_UNSIGNED_BYTE) * (GLsizei) 4; GLubyte *data = new GLubyte[(unsigned) DATA_SIZE]; glReadPixels(0, 0, _width, _height, GL_RGBA, GL_UNSIGNED_BYTE, data); png::image<png::rgb_pixel> image((long unsigned) _width, (long unsigned) _height); GLsizei index = 0; for (GLsizei y = 0; y < _height; y++) { for (GLsizei x = 0; x < _width; x++) { image[(size_t) (_height - y - 1)][(size_t) x] = png::rgb_pixel(data[index], data[index + 1], data[index + 2]); index += 4; } } image.write("screen_shot.png"); unbind(); }
C++
UTF-8
2,589
3.421875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; typedef unsigned long long uint_type; const int facteur_limite = 100; const uint_type limite = 1000000000; // Prototype de fonction std::vector<int, std::allocator<int> > Crible_Eratosthene_vect(int); uint_type compteur_Hamming(std::vector<int>, uint_type, uint_type); int main() { // Va chercher un vecteur booléen avec les facteurs premiers inférieurs // au facteur limite. std::vector<int, std::allocator<int> > facteurs_premiers = Crible_Eratosthene_vect(facteur_limite); std::vector<int, std::allocator<int> > liste_facteur; // Convertie le vector booléen facteurs_premiers pour avoir directement // le facteurs_premiers en base 10. for (size_t i = 2; i < facteurs_premiers.size(); i++) { if (facteurs_premiers[i] == 1) { liste_facteur.push_back(i); } } // Libère la memoire. std::vector<int>().swap(facteurs_premiers); // On ajoute 1 au compteur puisque 1 est compris comme facteur premier. std::cout << compteur_Hamming(liste_facteur, 1, 0) + 1 << '\n'; } // Fonction récursive où on calcul toute les combinaisons entre // les facteurs premiers inférieurs au "type" (100 dans ce cas-ci). uint_type compteur_Hamming(std::vector<int> facteurs_premiers, uint_type produit, uint_type index){ uint_type compteur = 0; do { // Rapelle la fonction avec chaque nouveau produit en testant toute les // facteurs premiers if( index != facteurs_premiers.size() - 1 ) compteur += compteur_Hamming(facteurs_premiers, produit, index + 1); else // Tant que la limite n'est pas atteinte, on continue de multiplier le // produit par les facteurs premiers à l'index courant et on compte // chacune des combinaisons qui répondent au critère. ++compteur; produit *= facteurs_premiers[index]; } // Produit supérieur à la limite? while(produit < limite); return compteur; } // Donne le vecteur des facteurs premiers inférieurs à un nombre donné. // Méthode du crible d'Eratosthène std::vector<int, std::allocator<int> > Crible_Eratosthene_vect(int limite_superieur){ std::vector<int, std::allocator<int> > // Chaque valeur est initialement à 1. Composite ((size_t)limite_superieur + 1, 1); // Pour toutes les positions multiples de chaque element. Valeur = 0 for (int element = 2; element * element <= limite_superieur; element++) if (Composite[element]) for (int multiple = element + element; multiple <= limite_superieur; multiple += element) Composite[multiple] = 0; return Composite; }
Shell
UTF-8
503
2.734375
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. set -e echo "Setting up Python environment..." if [ ! -f "env/bin/activate" ] then python3.8 -m venv env fi source env/bin/activate pip install --disable-pip-version-check -q -U -e ./python/ pip install --disable-pip-version-check -q -U -r ./doc/requirements.txt echo "Python environment successfully setup" sphinx-autobuild -b html doc doc/html --host localhost --port 8080
Java
TIS-620
1,086
2.078125
2
[]
no_license
package cn.sdut.test; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import cn.sdut.persistence.dao.interfaces.Lg20Dao; public class Lg20DaoTest { private static ApplicationContext act = new FileSystemXmlApplicationContext( "C:/Users/Administrator/git/CRM/CRM/WebRoot/WEB-INF/applicationContext.xml"); private static Lg20Dao dao = act.getBean("lg20dao", Lg20Dao.class); private static Map dto = new HashMap(); public static void main(String[] args) { dao.setMapDto(dto); try { //queryByIdTest(); queryForPageTest(); } catch (Exception e) { e.printStackTrace(); } } private static void queryByIdTest() throws Exception{ dto.put("lg2001", "1"); List res = dao.queryById(); System.out.println(res); } private static void queryForPageTest() throws Exception{ dto.put("qlg2002", ""); List res = dao.queryForPage(); System.out.println(res); } }
JavaScript
UTF-8
1,440
4.53125
5
[ "MIT" ]
permissive
/** * 객체 리터럴, 생성자 함수 */ // 빈 객체 생성 var dog = {}; // 프로퍼티 하나 추가 dog.name = "Benji"; // 메서드 추가 dog.getName = function () { return dog.name; }; // 메서드 재정의 dog.getName = function () { return "Fido"; }; // 프로퍼티나 메서드 삭제 delete dog.name; // 생성 시점에 프로퍼티와 메서드 추가 var dog = { name: "Benji", getName: function () { return this.name; } }; // 생성자 함수 var Person = function (name) { this.name = name; this.say = function () { return "I am " + this.name; }; }; // 위의 코드와 동일한 역할 var Person = function (name) { var this = Object.create(Person.prototype); this.name = name; this.say = function () { return "I am " + this.name; }; return this; }; var adam = new Person("Adam"); adam.say(); // 생성자의 반환값. 반환 값이 될 객체를 따로 정할 수 있음. var Objectmarker = function () { this.name = "This is it"; var that = {}; that.name = "And that's that"; return that; }; // 스스로를 호출하는 생성자 function Waffle() { if (!(this instanceof Waffle)) { return new Waffle() } this.tastes = "yummy"; } Waffle.prototype.wantAnother = true; var first = new Waffle(), second = Waffle(); console.log(first.tastes); console.log(second.tastes); console.log(first.wantAnother); console.log(second.wantAnother);
Python
UTF-8
2,893
2.65625
3
[]
no_license
import os from DBModule import DBModule from host_config.config_reader import read_login_config from RemoteModule import RemoteModule from util.command_utils import parse_size_info_response_lines from util.common_utils import is_localhost, print_error def find_host_all_tablespace_remain_size_dic(host, database_name): """This host`s all tablespace remain size(left size) :param host: :param database_name: :return: {tablespace_name:remain_size,...} unit:B """ tablespace_name_remain_size_dic = {} tablespace_name_size_info_dic = find_tablespace_disk_space_info_dic(host, database_name) for tablespace_name, size_info in tablespace_name_size_info_dic.iteritems(): remain_size = size_info["Available"] tablespace_name_remain_size_dic[tablespace_name] = remain_size return tablespace_name_remain_size_dic def find_tablespace_disk_space_info_dic(host, database_name="postgres"): """get the disk usage of each tablespace path Tips: 1. be clear that the value "Used" do not means this tablespace`s size. :param host: :param database_name: :return: {tablespace:{"Available": ,"Used": ,"TotalSize": }} """ # 1.get all tablespace and path tablespace_name_path_dic = find_tablespace_name_path_dic(host, database_name) # 2.get the space information tablespace_disk_space_info_dic = {} response_lines_list = [] if is_localhost(host): for tablespace_name, tablespace_location in tablespace_name_path_dic.iteritems(): cmd = "sudo df %s" % tablespace_location size_info_lines = os.popen(cmd).readlines() response_lines_list.append(size_info_lines) size_info = parse_size_info_response_lines(size_info_lines) tablespace_disk_space_info_dic[tablespace_name] = size_info else: if host == "10.179.1.110": print_error("KOR data no right to access. pass it .") return {host: None} login_user, login_password = read_login_config(host) remote_model = RemoteModule(host, login_user, login_password) for tablespace_name, tablespace_location in tablespace_name_path_dic.iteritems(): cmd = "sudo df %s" % tablespace_location size_info_lines = remote_model.execute_command(cmd) response_lines_list.append(size_info_lines) size_info = parse_size_info_response_lines(size_info_lines) tablespace_disk_space_info_dic[tablespace_name] = size_info remote_model.close() return tablespace_disk_space_info_dic def find_tablespace_name_path_dic(host, database_name="postgres"): """Name:location path""" dm = DBModule(host, database_name) # {name:tablespace_location,...} tablespace_name_path_dic = dm.select_all_tablespace_path_dic() dm.close() return tablespace_name_path_dic
Java
UTF-8
755
2.140625
2
[ "Apache-2.0" ]
permissive
package com.rn.dfsoo.common.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.Date; /** * Description:异常信息对象 * * @author 然诺 * @date 2019/8/28 */ @Getter @Setter @ApiModel(description = "异常信息对象") public class ExRet implements Serializable { @ApiModelProperty(value = "异常时间", required = true) private Date date; @ApiModelProperty(value = "异常类名", required = true) private String type; @ApiModelProperty(value = "异常信息", required = true) private String message; @ApiModelProperty(value = "异常堆栈", required = true) private String stackTrace; }
Java
UTF-8
1,404
3.59375
4
[]
no_license
package com.github.year.main; import java.util.Scanner; import com.github.year.svc.YearValidator; public class Driver { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println("========== Welcome to leap year checker! ==========\n"); while (true) { Long year = getInputYear(); if (YearValidator.getInstance().isLeapYear(year)) { System.out.println(year + " is a leap year!"); } else { System.out.println(year + " is NOT a leap year!"); } System.out.println("Would you like to try again? (yes/no)"); if (!tryAgain()) { break; } } System.out.println("Exiting..."); sc.close(); } private static Long getInputYear() { System.out.println("Please enter the year:"); try { return Long.valueOf(sc.nextLine()); } catch (NumberFormatException e) { System.out.println("Please enter a valid number - Try again!"); } return getInputYear(); } private static boolean tryAgain() { try { String choice = sc.nextLine(); if (choice.equalsIgnoreCase("yes")) { return true; } if (choice.equalsIgnoreCase("no")) { return false; } } catch (Exception e) { System.out.println("Exception while getting tryAgain choice: " + e.getMessage()); e.printStackTrace(); } System.out.println("Invalid input - Please input 'yes' or 'no':"); return tryAgain(); } }
C#
UTF-8
545
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace project1.Singleton { class Program { public static Program instance; public string Name { get; private set; } protected Program(string Name) { this.Name = Name; } public static Program getInstance(string Name) { if (instance == null) instance = new Program(Name); return instance; } } }
Python
UTF-8
1,203
3.84375
4
[ "Apache-2.0" ]
permissive
''' You are given a 0-indexed string word of length n consisting of digits, and a positive integer m. The divisibility array div of word is an integer array of length n such that: div[i] = 1 if the numeric value of word[0,...,i] is divisible by m, or div[i] = 0 otherwise. Return the divisibility array of word. ''' class Solution: def divisibilityArray(self, word: str, m: int) -> List[int]: x=0 a=[] for i in word: x=x*10+int(i) if(x%m==0): a+=[1] else: a+=[0] x%=m return a ---------------------------------------------------------------------------------------------------------------------------- Using the mathematical property that ab (mod m) ≡ ((a (mod m) * 10) + (b (mod m))) mod m We can compute and store the mod of current digit and use it for the next digit. No TLE due to small modulo operations. class Solution: def divisibilityArray(self, word: str, m: int) -> List[int]: mod = 0 div = [] for i in range(0, len(word)): mod = (mod * 10 + int(word[i])) % m div.append(1 if mod % m == 0 else 0) return div
Java
UTF-8
829
3.390625
3
[]
no_license
package T1to50.T38; public class Solution { String[] strings = {"1","11","21","1211", "111221","312211","13112221","1113213211", "31131211131221","13211311123113112211"}; public String countAndSay(int n) { if (n <=0){ return ""; }else if (n <= 10){ return strings[n-1]; }else { String s = countAndSay(n-1); StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { int repeated = 1; while (i <s.length()-1 && s.charAt(i) == s.charAt(i+1)){ i++; repeated++; } sb.append(repeated); sb.append(s.charAt(i)); } return sb.toString(); } } }
JavaScript
UTF-8
127
2.71875
3
[]
no_license
function jediName(firstName, lastName) { return lastName.slice(0,3) + firstName.slice(0,2); } jediName('David', 'LeeTooPoo');
Go
UTF-8
2,997
2.8125
3
[ "Apache-2.0" ]
permissive
package main import ( "bufio" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "io" "os" "regexp" "strings" "github.com/golang/protobuf/proto" "github.com/nknorg/nkn/v2/pb" ) // Base64ToHex convert base64 string input to hex string output func Base64ToHex(in []byte) (out []byte, err error) { // input format should be ':"balabala..."' const prefix, suffix = ":\"", "\"" start, end := len(prefix), len(in)-len(suffix) // b64Str len not contain :" prefix and " suffix // Decode Base64 string to bin bin := make([]byte, base64.StdEncoding.DecodedLen(end-start)) n, err := base64.StdEncoding.Decode(bin, in[start:end]) if err != nil { fmt.Fprintf(os.Stderr, "base64 decode %s error %v\n", in[start:end], err) return []byte{}, err } // Encode bin to hex string hexStr := make([]byte, 2*len(bin[:n])) hex.Encode(hexStr, bin[:n]) // return strcat out = append(out, prefix...) // append :" prefix out = append(out, hexStr...) // append hexStr return append(out, suffix...), err // append " suffix } // Base64Handler will find all matching with pattern in input, and replace them with hex string func Base64Handler(pattern *regexp.Regexp, out io.Writer, in []byte) { seek := 0 // init cursor for _, s := range pattern.FindAllIndex(in, -1) { // foreach matching out.Write(in[seek:s[0]]) // copy string between two matching // append hex string if convert successful or append orig in failed if str, err := Base64ToHex(in[s[0]:s[1]]); err == nil { out.Write(str) } else { fmt.Fprintf(os.Stderr, "%v\n", err) out.Write(in[s[0]:s[1]]) } seek = s[1] // update cursor } out.Write(in[seek:]) // copy remaining string } func main() { // regexp pattern `:"RFC4648"` re := regexp.MustCompile(":\"(?:[a-zA-Z0-9+\\/]{4})*(?:|(?:[a-zA-Z0-9+\\/]{3}=)|(?:[a-zA-Z0-9+\\/]{2}==)|(?:[a-zA-Z0-9+\\/]{1}===))\"") for { l, err := bufio.NewReader(os.Stdin).ReadString('\n') switch err { case nil: // readLine successful from stdin case io.EOF: return default: fmt.Fprintf(os.Stderr, "%v\n", err) continue // read current line error, skip & next } var buf, jStr []byte if buf, err = hex.DecodeString(strings.TrimRight(l, "\n")); err == nil { // hexStr to bin sigChainTxn := &pb.SigChainTxn{} if err = proto.Unmarshal(buf, sigChainTxn); err == nil { // bin to pb struct of SigChainTxnType txn // submitter, _ := new(common.Uint160).SetBytes(sigChainTxn.Submitter).ToAddress() sc := &pb.SigChain{} if err = proto.Unmarshal(sigChainTxn.SigChain, sc); err == nil { // bin to pb struct of sigChain js := map[string]interface{}{"SigChain": sc, "Submitter": sigChainTxn.Submitter} if jStr, err = json.Marshal(js); err == nil { // to json string Base64Handler(re, os.Stdout, jStr) // replace all in jStr to stdout os.Stdout.WriteString("\n") continue } } } } fmt.Fprintf(os.Stderr, "%v\n", err) // any error from above } }
Java
UTF-8
648
2.09375
2
[]
no_license
package com.ss.lms.repo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.ss.lms.entity.Author; @Repository public interface AuthorRepo extends JpaRepository<Author, Integer>{ @Query(" FROM Author where authorId =:authorId") public List<Author> readAuthorById(@Param("authorId") Integer authorId); @Query(" FROM Author where authorName =:authorName") public List<Author> readAuthorByName(@Param("authorName") String authorName); }
Java
UTF-8
866
3.4375
3
[]
no_license
package com.multithreding.Question6; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Reentrant { int level = 0; Lock lock = new ReentrantLock(); public void outer() throws InterruptedException { lock.lock(); inner(); lock.unlock(); } public synchronized void inner() throws InterruptedException { level++; lock.lock(); try { System.out.println("level-->"+ level); if (level <= 3) { inner(); if (level == 2) { Thread.sleep(1000); } } else { Thread.sleep(1000); } } finally { lock.unlock(); level--; System.out.println("final level-->"+ level); } } }
Java
UTF-8
2,866
1.96875
2
[]
no_license
//package com.imran; // //import java.io.IOException; //import java.util.Arrays; //import java.util.List; // //import org.drools.decisiontable.DecisionTableProviderImpl; //import org.kie.api.KieServices; //import org.kie.api.builder.KieBuilder; //import org.kie.api.builder.KieFileSystem; //import org.kie.api.builder.KieModule; //import org.kie.api.builder.KieRepository; //import org.kie.api.builder.ReleaseId; //import org.kie.api.io.Resource; //import org.kie.api.runtime.KieContainer; //import org.kie.api.runtime.KieSession; //import org.kie.internal.builder.DecisionTableConfiguration; //import org.kie.internal.builder.DecisionTableInputType; //import org.kie.internal.builder.KnowledgeBuilderFactory; //import org.kie.internal.io.ResourceFactory; // //public class DroolsBeanFactory { // // private static final String RULES_PATH = "rules/"; // private KieServices kieServices = KieServices.Factory.get(); // // private KieFileSystem getKieFileSystem() throws IOException { // KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); // List<String> rules = Arrays.asList("discountTwo.xlsx"); // for (String rule : rules) { // kieFileSystem.write(ResourceFactory.newClassPathResource(rule)); // } // return kieFileSystem; // // } // // public KieContainer getKieContainer() throws IOException { // getKieRepository(); // KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem()); // kb.buildAll(); // KieModule kieModule = kb.getKieModule(); // KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId()); // return kContainer; // // } // // private void getKieRepository() { // final KieRepository kieRepository = kieServices.getRepository(); // kieRepository.addKieModule(new KieModule() { // public ReleaseId getReleaseId() { // return kieRepository.getDefaultReleaseId(); // } // }); // } // // public KieSession getKieSession() { // getKieRepository(); // KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); // kieFileSystem.write(ResourceFactory.newClassPathResource("rules/discountTwo.xlsx")); // // KieBuilder kb = kieServices.newKieBuilder(kieFileSystem); // kb.buildAll(); // KieModule kieModule = kb.getKieModule(); // // KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId()); // // return kContainer.newKieSession(); // // } // // public KieSession getKieSession(Resource dt) { // KieFileSystem kieFileSystem = kieServices.newKieFileSystem().write(dt); // KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem).buildAll(); // KieRepository kieRepository = kieServices.getRepository(); // ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId(); // KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId); // KieSession ksession = kieContainer.newKieSession(); // // return ksession; // } // // // //}
Markdown
UTF-8
1,157
2.546875
3
[]
no_license
# 真香 [☞ [2018-08-19] 真香 ](https://mp.weixin.qq.com/s/ux3UdIAtCdE-MEBupOiPWA) ###### 朗文当代高级英语辞典(英英·英汉双解)(第 4 版) >**smell** » The stew smelted delicious . 这炖菜闻起来真香。 ###### 麦克米伦高阶英汉双解词典 >**aah** /ɑː/ *interjection* used for showing that you are happy , satisfied , or surprised (表示快乐、满意或惊讶)啊 » Aah, the food smells wonderful! 啊,这食物闻起来真香! ###### 柯林斯 COBUILD 高阶英汉双解学习词典 >**yummy** Yummy food tastes very good. 美味的;可口的 » I'll bet they have yummy ice cream... 我敢打赌他们有非常好吃的冰激凌。 » It smells yummy. 它闻起来很香。 ###### 英汉大词典(第 2 版) >**churn** » The smell was so good, my stomach began to churn. 味道真香,我的胃开始蠕动起来了。 ## Want to Listen **The Night Circus** >By: Erin Morgenstern Narrated by: Jim Dale Length: 13 hrs and 40 mins Unabridged Audiobook Release date: 09-13-11 Language: English Publisher: Random House Audio -EOF-
Python
UTF-8
1,575
3.765625
4
[]
no_license
import sys import os # get the directory path of this file. dirname = os.path.dirname(os.path.abspath(__file__)) # get the root of this child directory. rootdir = os.path.dirname(dirname) sys.path.append(rootdir) import palindromechecker class TestPalindromeClass(object): """ This checks whether the method is able to check if a word is a palindrome regardless of case. """ def test_palindrome(self): #arrange text = "Anna" expected = True #act result = palindromechecker.palindrome(text) #assert assert result == expected def test_palindrome_from(self, tmpdir): """ This checks whether the method can read list of words from a text file. Then calculate the number of palindrome in the text. """ # arrange filepath = tmpdir.mkdir("temp").join("palindrome.txt") palindromes = [] palindromes.append("Anna\n") palindromes.append("Amma\n") palindromes.append("Ada\n") palindromes.append("Abba\n") palindromes.append("Eve\n") palindromes.append("eYe\n") palindromes.append("civic\n") palindromes.append("pip\n") palindromes.append("rotator\n") palindromes.append("IrorI\n") palindrome_str = ''.join(palindromes) # output the string to the file. filepath.write(palindrome_str) expected = 10 # act result = palindromechecker.palindrome_from(filepath) # assert assert result == expected
Java
UTF-8
704
2.625
3
[]
no_license
package com.itdlc.android.library.hook.base; import java.lang.reflect.Method; /** * Created by felear on 2018/4/25. */ public abstract class BaseMethodHandler { protected abstract boolean beforeHood(Object realObject, Method method, Object[] args); protected abstract void afterHood(Object realObject, Method method, Object[] args); public Object innerHood(Object realObject, Method method, Object[] args) throws Throwable { Object result = null; // 返回true时拦截hook if (!beforeHood(realObject, method, args)) { result = method.invoke(realObject, args); } afterHood(realObject, method, args); return result; } }
C
UTF-8
1,507
3.234375
3
[]
no_license
#include<stdio.h> #include<math.h> #include<time.h> #include<stdbool.h> typedef unsigned long long llu; typedef unsigned long lu; typedef struct Triplet__ { int a; int b; int c; } Triplet; FILE *file_log = NULL; lu pow2(int n); bool is_pythagorean(Triplet t); int sum(Triplet t); Triplet even_generator(int a); Triplet odd_generator(int a); bool for_condition(Triplet t); llu pythagorean(); void print_log(Triplet t, int s); lu pow2(int n) { return (lu)pow(n, 2); } bool is_pythagorean(Triplet t) { return pow2(t.a) + pow2(t.b) == pow2(t.c); } int sum(Triplet t) { return t.a + t.b + t.c; } Triplet even_generator(int n) { return (Triplet){n, pow2(n/2) - 1, pow2(n/2) + 1}; } Triplet odd_generator(int n) { return (Triplet){n, pow2(n) / 2, pow2(n) / 2 + 1}; } bool for_condition(Triplet t) { int s = sum(t); print_log(t, s); bool first = is_pythagorean(t) && (s == 1000); if (first) return false; return s < 2000; } llu pythagorean() { Triplet t = {3, 4, 5}; for (int i = 5; for_condition(t); i++) { if (i & 1) { t = odd_generator(i); } else { t = even_generator(i); } } return (llu)t.a * t.b * t.c; } void print_log(Triplet t,int s) { fprintf(file_log, "%-3d | %-3d | %-3d | %-4d\n", t.a, t.b, t.c, s); } int main() { file_log = fopen("pythagorean.log", "w+"); llu result = pythagorean(); printf("%llu\n", result); fclose(file_log); return 0; }
Java
UTF-8
6,729
2.125
2
[]
no_license
package com.example.gauge; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import android.util.Log; public class AsyncHttpRequest extends AsyncTask <String, Void, GaugeHttpResponse> { IGaugeAsync activity; public AsyncHttpRequest(IGaugeAsync mainActivity) { super(); this.activity = mainActivity; } protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException { InputStream in = entity.getContent(); StringBuffer out = new StringBuffer(); int n = 1; while (n>0) { byte[] b = new byte[4096]; n = in.read(b); if (n>0) out.append(new String(b, 0, n)); } return out.toString(); } public void Login(String email, String password) { JSONObject jsonArg = new JSONObject(); try { jsonArg.put("Email", email); jsonArg.put("Password", password); } catch (JSONException e) { Log.d("Json building login JSON object exception", e.getMessage()); } this.execute("POST","http://mortgagecalculator.cloudapp.net/api/login", jsonArg.toString()); } public void Register(String email, String forename, String surname, String password) { JSONObject jsonArg = new JSONObject(); try { jsonArg.put("Email", email); jsonArg.put("Forename", forename); jsonArg.put("Surname", surname); jsonArg.put("Password", password); jsonArg.put("AccountTypeId", "1"); jsonArg.put("Active", true); } catch (JSONException e) { Log.d("Json building register JSON object exception", e.getMessage()); } this.execute("POST","http://mortgagecalculator.cloudapp.net/api/account", jsonArg.toString()); } public void RetrieveAccount(int accountId) { this.execute("GET",String.format("http://mortgagecalculator.cloudapp.net/api/account/%s", accountId)); } public void UpdateAccount(int accountId, String email, String forename, String surname) { JSONObject jsonArg = new JSONObject(); try { jsonArg.put("AccountId", accountId); jsonArg.put("Forename", forename); jsonArg.put("Surname", surname); jsonArg.put("Email", email); } catch (JSONException e) { Log.d("Json building register JSON object exception", e.getMessage()); } this.execute("PUT",String.format("http://mortgagecalculator.cloudapp.net/api/account/%s", accountId), jsonArg.toString()); } public void Calculate(String property_value, String deposit, String term, String interest_rate, String fees, int accountId, UUID customerReference) { JSONObject jsonArg = new JSONObject(); try { jsonArg.put("AccountId", accountId); jsonArg.put("CustomerReference", customerReference); jsonArg.put("HouseValue", property_value); jsonArg.put("Deposit", deposit); jsonArg.put("InterestRate", interest_rate); jsonArg.put("Term", term); jsonArg.put("Fees", fees); jsonArg.put("MortgageType", "repayment"); jsonArg.put("Source", "Gauge Android App"); } catch (JSONException e) { Log.d("Json building calculate JSON object exception", e.getMessage()); } this.execute("POST","http://mortgagecalculator.cloudapp.net/api/mortgage", jsonArg.toString()); } public void Compare(String property_value, String deposit, String term, int accountId, UUID customerReference) { JSONObject jsonArg = new JSONObject(); try { jsonArg.put("AccountId", accountId); jsonArg.put("CustomerReference", customerReference); jsonArg.put("HouseValue", property_value); jsonArg.put("Deposit", deposit); jsonArg.put("Term", term); jsonArg.put("MortgageType", "repayment"); jsonArg.put("Source", "Gauge Android App"); } catch (JSONException e) { Log.d("Json building compare JSON object exception", e.getMessage()); } this.execute("POST","http://mortgagecalculator.cloudapp.net/api/mortgage", jsonArg.toString()); } public void Email(int calculationId, String emailAddress) { JSONObject jsonArg = new JSONObject(); try { jsonArg.put("CalculationId", calculationId); jsonArg.put("Address", emailAddress); } catch (JSONException e) { Log.d("Json building email JSON object exception", e.getMessage()); } this.execute("POST","http://mortgagecalculator.cloudapp.net/api/email", jsonArg.toString()); } public void Favourite(int calculationId) { this.execute("PUT",String.format("http://mortgagecalculator.cloudapp.net/api/mortgage/%s", calculationId)); } @Override protected GaugeHttpResponse doInBackground(String... params) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); GaugeHttpResponse reponseObject = new GaugeHttpResponse(0,params[0], ""); HttpRequestBase request = null; if(params[0] == "POST") { HttpPost httpPost = new HttpPost(params[1]); httpPost.setHeader("Content-Type", "application/json"); try { httpPost.setEntity(new StringEntity(params[2])); } catch (UnsupportedEncodingException ex) { Log.d("Building httpPost - Unable to encode JsonArgs as StringEntity", ex.getMessage()); } request = httpPost; } else if(params[0] == "PUT") { HttpPut httpPut = new HttpPut(params[1]); httpPut.setHeader("Content-Type", "application/json"); if(params.length > 2) { try { httpPut.setEntity(new StringEntity(params[2])); } catch (UnsupportedEncodingException ex) { Log.d("Building httpPut - Unable to encode JsonAnrgs as StringEntity", ex.getMessage()); } } request = httpPut; } else { HttpGet httpGet = new HttpGet(params[1]); request = httpGet; } String text = null; try { HttpResponse response = httpClient.execute(request, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); text = getASCIIContentFromEntity(entity); reponseObject = new GaugeHttpResponse(statusCode, params[0], text); } catch (Exception ex) { Log.d("Building httpPost - Unable to encode JsoArgs as StringEntity", ex.getMessage()); } return reponseObject; } protected void onPostExecute(GaugeHttpResponse results) { this.activity.handleResponse(results); } }
PHP
UTF-8
13,470
2.65625
3
[]
no_license
<?php namespace codename\core\bucket; use \codename\core\app; use codename\core\exception; use codename\login\context\remote; /** * I can manage files on a FTP server. * @package core * @since 2016-05-18 */ class ftp extends \codename\core\bucket implements \codename\core\bucket\bucketInterface { /** * Contains the FTP connection stream * @var resource */ protected $connection = null; /** * Timeout for the FTP connection or followup operations * Defaults to 2 seconds * @var int|null */ protected $timeout = null; /** * Contains the public base URL to the webspace where files are located * @var string */ public $baseurl = ''; /** * Creates the instance, establishes the connection and authenticates * @param array $data * @return \codename\core\bucket */ public function __construct(array $data) { parent::__construct($data); if(count($errors = app::getValidator('structure_config_bucket_ftp')->reset()->validate($data)) > 0) { $this->errorstack->addError('CONFIGURATION', 'CONFIGURATION_INVALID', $errors); throw new \codename\core\exception(self::EXCEPTION_CONSTRUCT_CONFIGURATIONINVALID, \codename\core\exception::$ERRORLEVEL_ERROR, $errors); } $this->basedir = $data['basedir']; // Default timeout fallback for FTP network operations $this->timeout = $data['timeout'] ?? 2; if($data['ftpserver']['ssl'] ?? false) { $this->connection = @ftp_ssl_connect($data['ftpserver']['host'], $data['ftpserver']['port'], $this->timeout); } else { $this->connection = @ftp_connect($data['ftpserver']['host'], $data['ftpserver']['port'], $this->timeout); } if(isset($data['public']) && $data['public']) { $this->baseurl = $data['baseurl']; } if(is_bool($this->connection) && !$this->connection) { $this->errorstack->addError('FILE', 'CONNECTION_FAILED', null); app::getLog('errormessage')->warning('CORE_BACKEND_CLASS_BUCKET_FTP_CONSTRUCT::CONNECTION_FAILED ($host = ' . $data['ftpserver']['host'] .')'); throw new exception('EXCEPTION_BUCKET_FTP_CONNECTION_FAILED', exception::$ERRORLEVEL_ERROR, [ 'host' => $data['ftpserver']['host'] ]); return $this; } if(!@ftp_login($this->connection, $data['ftpserver']['user'], $data['ftpserver']['pass'])) { $this->errorstack->addError('FILE', 'LOGIN_FAILED', null); app::getLog('errormessage')->warning('CORE_BACKEND_CLASS_BUCKET_FTP_CONSTRUCT::LOGIN_FAILED ($user = ' . $data['ftpserver']['user'] .')'); throw new exception('EXCEPTION_BUCKET_FTP_LOGIN_FAILED', exception::$ERRORLEVEL_ERROR, [ 'user' => $data['ftpserver']['user'] ]); } // // Sometimes, the server reports his own IP address // which might be wrong or a local address // advise the client to ignore it and instead connect // to the known endpoint directly // if($data['ftpserver']['ignore_passive_address'] ?? false) { @ftp_set_option($this->connection, FTP_USEPASVADDRESS, false); } // passive mode setting from config if($data['ftpserver']['passive_mode'] ?? false) { $this->enablePassiveMode(true); } return $this; } /** * [enablePassiveMode description] * @param bool $state [description] * @return [type] [description] */ public function enablePassiveMode(bool $state) { @ftp_pasv($this->connection, $state); } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::filePush($localfile, $remotefile) */ public function filePush(string $localfile, string $remotefile) : bool { // Path sanitization $remotefile = $this->normalizeRelativePath($remotefile); if(!app::getFilesystem()->fileAvailable($localfile)) { $this->errorstack->addError('FILE', 'LOCAL_FILE_NOT_FOUND', $localfile); return false; } if($this->fileAvailable($remotefile)) { $this->errorstack->addError('FILE', 'REMOTE_FILE_EXISTS', $remotefile); return false; } $directory = $this->extractDirectory($remotefile); if($directory != '' && !$this->dirAvailable($directory)) { $this->dirCreate($directory); } try { if(!@ftp_put($this->connection, $this->basedir . $remotefile, $localfile, FTP_BINARY)) { $this->errorstack->addError('FILE', 'FTP_PUT_ERROR', $this->basedir . $remotefile); return false; } } catch (\Exception $e) { $this->errorstack->addError('FILE', 'FILE_PUSH_FAILED', $this->basedir . $remotefile); } return $this->fileAvailable($remotefile); } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::filePull($remotefile, $localfile) */ public function filePull(string $remotefile, string $localfile) : bool { // Path sanitization $remotefile = $this->normalizeRelativePath($remotefile); if(app::getFilesystem()->fileAvailable($localfile)) { $this->errorstack->addError('FILE', 'LOCAL_FILE_EXISTS', $localfile); return false; } if(!$this->fileAvailable($remotefile)) { $this->errorstack->addError('FILE', 'REMOTE_FILE_NOT_FOUND', $remotefile); return false; } // This might fail due to various reasons // read error on remote - or write error on local target path if(!@ftp_get($this->connection, $localfile, $this->basedir . $remotefile, FTP_BINARY)) { $this->errorstack->addError('FILE', 'FTP_GET_ERROR', [$localfile, $remotefile]); return false; } return app::getFilesystem()->fileAvailable($localfile); } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::dirAvailable($directory) */ public function dirAvailable(string $directory) : bool { // Path sanitization $directory = $this->normalizeRelativePath($directory); return static::ftp_isdir($this->connection, $directory); } /** * [ftp_isdir description] * @param [type] $conn_id [description] * @param [type] $dir [description] * @return [type] [description] */ protected static function ftp_isdir($conn_id,$dir) { // Try to change the directory // and automatically go up, if it worked if(@ftp_chdir($conn_id,$dir)) { ftp_cdup($conn_id); return true; } else { return false; } } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::dirList($directory) */ public function dirList(string $directory) : array { // Path sanitization $directory = $this->normalizeRelativePath($directory); if(!$this->dirAvailable($directory)) { $this->errorstack->addError('DIRECTORY', 'REMOTE_DIRECTORY_NOT_FOUND', $directory); return array(); } $list = $this->getDirlist($directory); $myList = array(); if(!is_array($list)) { return $myList; } $prefix = $directory != '' ? $directory.'/' : ''; foreach($list as $element) { $myList[] = $prefix.$element; // $myList[] = str_replace('/', '', str_replace(str_replace('//', '/', $this->basedir), '', $directory.'/'.$element)); } return $myList; } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::fileAvailable($remotefile) */ public function fileAvailable(string $remotefile) : bool { // // Neat trick to check for existance - simply use ftp_size // which returns -1 for a nonexisting file // NOTE: directories will also return -1 // return @ftp_size($this->connection, $this->basedir . $remotefile) !== -1; } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::fileDelete($remotefile) */ public function fileDelete(string $remotefile) : bool { // Path sanitization $remotefile = $this->normalizeRelativePath($remotefile); if(!$this->fileAvailable($remotefile)) { $this->errorstack->addError('FILE', 'REMOTE_FILE_NOT_FOUND', $remotefile); return true; } if(!@ftp_delete($this->connection, $this->basedir . $remotefile)) { $this->errorstack->addError('FILE', 'REMOTE_FILE_DELETE_FAILED', $remotefile); return false; } return !$this->fileAvailable($remotefile); } /** * @inheritDoc * @see \codename\core\bucket_interface::fileMove($remotefile, $newremotefile) */ public function fileMove(string $remotefile, string $newremotefile): bool { // Path sanitization $remotefile = $this->normalizeRelativePath($remotefile); $newremotefile = $this->normalizeRelativePath($newremotefile); if(!$this->fileAvailable($remotefile)) { $this->errorstack->addError('FILE', 'REMOTE_FILE_NOT_FOUND', $remotefile); return false; } // check for existance of the new file if($this->fileAvailable($newremotefile)) { $this->errorstack->addError('FILE', 'FILE_ALREADY_EXISTS', $newremotefile); return false; } $directory = $this->extractDirectory($newremotefile); if($directory !== '' && !$this->dirAvailable($directory)) { $this->dirCreate($directory); } @ftp_rename($this->connection, $this->basedir . $remotefile, $this->basedir . $newremotefile); return $this->fileAvailable($newremotefile); } /** * * {@inheritDoc} * @see \codename\core\bucket\bucketInterface::isFile() */ public function isFile(string $remotefile) : bool { $remotefile = $this->normalizeRelativePath($remotefile); // Path sanitization $list = $this->getRawlist($this->extractDirectory($remotefile)); if(!is_array($list)) { return false; } foreach($list as $file) { if(strpos($file, $this->extractFilename($remotefile)) !== false) { return substr($file, 0,1) == 'd' ? false : true; } } return false; } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::fileGetUrl($remotefile) */ public function fileGetUrl(string $remotefile) : string { return $this->baseurl . $remotefile; } /** * * {@inheritDoc} * @see \codename\core\bucket_interface::fileGetInfo($remotefile) */ public function fileGetInfo(string $remotefile) : array {} /** * Creates the given $directory on this instance's remote hostname * @param string $directory * @return bool */ public function dirCreate(string $directory) { // Path sanitization $directory = $this->normalizeRelativePath($directory); if($this->dirAvailable($directory)) { return true; } // // ftp_mkdir is not recursive // therefore, we have to traverse each directory/component // of the given path // // Store current directory for later restoration $prevDir = @ftp_pwd($this->connection); $parts = explode('/', $directory); foreach ($parts as $part) { if(!@ftp_chdir($this->connection, $part)){ @ftp_mkdir($this->connection, $part); @ftp_chdir($this->connection, $part); } } // revert to starting directory. @ftp_chdir($this->connection, $prevDir); return $this->dirAvailable($directory); } /** * Nested function to retrieve a directory List * @param string $directory * @return array | null */ protected function getDirlist(string $directory) { return @ftp_nlist($this->connection, $this->basedir . $directory); } /** * Nested functino to retrieve a RAW directory list * @param string $directory * @return array | null */ protected function getRawlist(string $directory) { return @ftp_rawlist($this->connection, $this->basedir . $directory); } /** * Extracts the directory path from $filename * <br /><b>example:</b> * <br />$name = extractDirectory('/path/to/file.mp3'); * <br /> * <br />// $name is now '/path/to/' * @param string $filename * @return string */ protected function extractDirectory(string $filename) : string { $directory = pathinfo($filename, PATHINFO_DIRNAME); if($directory == '.') { return ''; } else { return $directory; } } /** * Extracts the file name from $filename * <br /><b>example:</b> * <br />$name = extractDirectory('/path/to/file.mp3'); * <br /> * <br />// $name is now 'file.mp3' * @param string $filename * @return string */ protected function extractFilename(string $filename) : string { $filenamedata = explode('/', $filename); return $filenamedata[count($filenamedata) - 1]; } }
Rust
UTF-8
745
2.625
3
[ "MIT" ]
permissive
use warp::{filters::BoxedFilter, Filter, Rejection, Reply}; // Option 1: BoxedFilter // Note that this may be useful for shortening compile times when you are composing many filters. // Boxing the filters will use dynamic dispatch and speed up compilation while // making it slightly slower at runtime. pub fn assets_filter() -> BoxedFilter<(impl Reply,)> { warp::path("assets").and(warp::fs::dir("./assets")).boxed() } // Option 2: impl Filter + Clone pub fn index_filter() -> impl Filter<Extract = (&'static str,), Error = Rejection> + Clone { warp::path::end().map(|| "Index page") } #[tokio::main] async fn main() { let routes = index_filter().or(assets_filter()); warp::serve(routes).run(([127, 0, 0, 1], 3030)).await; }
PHP
UTF-8
6,334
2.71875
3
[]
no_license
<?php namespace App\Models\Traits; use App\Models\Role; use App\Models\Permission; use Illuminate\Support\Collection; trait RolePermission { /** * Cheking has role * @param array $roles include string and number in array * @return boolean [description] */ public function hasPermissionWithRole($permission) { $roles = $this->roles()->get(); if (is_array($permission)) { return $this->hasMultiPermissionWithRole($permission, $roles); } foreach ($roles as $key => $value) { $result = $value->permissions->pluck('name')->contains($permission); if ($result) { return true; } } return false; } protected function hasMultiPermissionWithRole($permissions, $roles) { foreach ($roles as $key => $value) { foreach ($permissions as $permission) { $result = $value->permissions->pluck('name')->contains($permission); if ($result) { return true; } } } return false; } /** * Action to give roles to user * @param array $roles (pluck name) * @return $this */ public function givePermissionsToRole($role, ...$permissions) { $permissions = $this->getAllPermissions(collect($permissions)->flatten()); // is empty on object permission if ($permissions instanceof Collection && $permissions->isEmpty()) { return $this; } $role->permissions()->saveMany($permissions); return $this; } /** * Action to give perimissions to user * @param array $permissions (pluck name) * @return $this */ public function givePermissionTo(...$permissions) { $permissions = $this->getAllPermissions(collect($permissions)->flatten()); // is empty on object permission if ($permissions instanceof Collection && $permissions->isEmpty()) { return $this; } $this->permissions()->saveMany($permissions); return $this; } /** * Action to detach permission on user * @param array $permissions * @return $this */ public function detachPermissionTo(...$permissions) { $permissions = $this->getAllPermissions(collect($permissions)->flatten()); $this->permissions()->detach($permissions); return $this; } /** * Action to update all permissions * @param array $permissions include all permissions * @return $this */ public function updatePermission($permissions) { $this->permissions()->detach(); return $this->givePermissionTo($permissions); } /** * Action to checking the permissions * @param array/string $permission * @return boolean */ public function hasPermissionTo($permission) { if ($permission instanceof Permission) { return $this->hasPermissionThroughRole($permission); } if (is_array($permission)) { return $this->hasPermissionIn($permission); } return $this->hasPermission($permission); } /** * Action to give roles to user * @param array $roles (pluck name) * @return $this */ public function giveRoleTo(...$roles) { $roles = $this->getAllRoles(collect($roles)->flatten()); // is empty on object roles if ($roles->isEmpty()) { return $this; } $this->roles()->saveMany($roles); return $this; } /** * Action to update all roles * @param array $roles include all roles * @return $this */ public function updateRole($roles) { $this->roles()->detach(); return $this->giveRoleTo($roles); } /** * Action to checking the permissions with the array value * @param array $permission * @return boolean */ protected function hasPermissionThroughRole($permission) { if ($permission->roles->isEmpty()) { return false; } foreach ($permission->roles as $role) { if ($this->roles->contains($role)) { return true; } } return false; } /** * Action to checking the permissions with the string/number value * @param string/number $permission [description] * @return boolean */ protected function hasPermission($permission) { return (bool) $this->permissions->where('name', $permission)->count(); } /** * Action to checking the permissions with the string/number value * @param string/number $permission [description] * @return boolean */ protected function hasPermissionIn($permissions) { return (bool) $this->permissions->whereIn('name', $permissions)->count(); } /** * Get all permissions with the match name * @param Collection $permissions [description] * @return /App/Models/Permission */ protected function getAllPermissions(Collection $permissions) { return Permission::whereIn('name', $permissions)->get(); } /** * Get all permissions with the match name * @param array $permissions [description] * @return /App/Models/Permission */ protected function getAllRoles(Collection $roles) { return Role::whereIn('name', $roles)->get(); } /** * Cheking has role * @param array $roles include string and number in array * @return boolean [description] */ public function hasRole(...$roles) { foreach ($roles as $role) { if ($this->roles->contains('name', $role)) { return true; } } return false; } /** * [roles description] * @return [type] [description] */ public function roles() { return $this->belongsToMany(Role::class, 'role_users'); } /** * [permissions description] * @return [type] [description] */ public function permissions() { return $this->belongsToMany(Permission::class, 'permission_users'); } }
C
UTF-8
1,623
2.625
3
[]
no_license
/// \author MiAM Robotique, Matthieu Vigne /// \copyright GNU GPLv3 #include "MiAMEurobot/KalmanFilter.h" void kalman_init(Kalman *k, double angle) { // Default dynamics covariance. k->Q_angle = 0.003; k->Q_bias = 0.1; // Default sensor covariance. k->R_measure = 0.0005; // Initial angle and bias - the gyro is considered to have a 0 average offset. k->angle = angle; k->bias = 0.0; // Initial value of P: we trust the initial guess. k->P[0][0] = 0.0001f; k->P[0][1] = 0.0f; k->P[1][0] = 0.0f; k->P[1][1] = 0.01f; }; double kalman_updateEstimate(Kalman *k, double angleMeasurement, double rateMesurement, double dt) { // Prediction: state dynamics k->rate = rateMesurement - k->bias; double predictedAngle = k->angle + dt * k->rate; // Update covariance k->P[0][0] += dt * (dt*k->P[1][1] - k->P[0][1] - k->P[1][0] + k->Q_angle); k->P[0][1] -= dt * k->P[1][1]; k->P[1][0] -= dt * k->P[1][1]; k->P[1][1] += k->Q_bias * dt; // Innovation double innovation = angleMeasurement - predictedAngle; // Calculate Kalman gain double S = k->P[0][0] + k->R_measure; double K[2]; K[0] = k->P[0][0] / S; K[1] = k->P[1][0] / S; // Update state and covariance. k->angle = predictedAngle + K[0] * innovation; k->bias = k->bias + K[1] * innovation; //~ printf("%f\n", k->bias); double P00_temp = k->P[0][0]; double P01_temp = k->P[0][1]; k->P[0][0] -= K[0] * P00_temp; k->P[0][1] -= K[0] * P01_temp; k->P[1][0] -= K[1] * P00_temp; k->P[1][1] -= K[1] * P01_temp; return k->angle; }
JavaScript
UTF-8
6,028
2.703125
3
[]
no_license
import React, { Component } from "react"; import produce from "immer"; import { v4 as uuid } from "uuid"; import "./App.css"; import Crud from './comps/Crud' export default class App extends Component { nameRef = React.createRef(); state = { selectedOption: "option1", hasBike: false, hasSpine: true, details: { eventName: "Birthday Party" }, people: [ { uuid: uuid(), name: "Leigh", attending: true }, { uuid: uuid(), name: "Pedro", attending: false }, { uuid: uuid(), name: "Dorothy", attending: false }, { uuid: uuid(), name: "Grandma", attending: true } ] }; handleOptionChange = e => { this.setState({ selectedOption: e.target.value }); }; setEventName = value => { // const { details } = this.state; // this.setState({ // details: { ...details, eventName: value } // }); this.setState( produce(draft => { draft.details.eventName = value; }) ); }; updateAttending = (uuid, newAttending) => { // const { people } = this.state; // const newPeople = people.map(person => { // if (person.uuid === uuid) { // return { ...person, attending: newAttending }; // } // return person; // }); // this.setState({ // people: newPeople // }); this.setState( produce(draft => { draft.people.forEach(person => { if (person.uuid === uuid) { person.attending = newAttending; } }); }) ); }; addPerson = name => { // const { people } = this.state; // this.setState({ // people: [...people, { uuid: uuid(), attending: false, name }] // }); this.setState( produce(draft => { draft.people.push({ uuid: uuid(), attending: false, name }); }) ); }; // removePerson = uuid => { // const { people } = this.state; // const newPeople = people.filter(person => person.uuid !== uuid); // this.setState({ // people: newPeople // }); // }; removePerson = uuid => { this.setState(produce(draft => { draft.people.pop(person => person.uuid !== uuid); })); }; toggleHasBike = name => event => { console.log('\n', 'event.target.checked', '\n', '\n', event.target.checked ) this.setState({ ...this.state, [name]: event.target.checked, }) }; toggleHasSpine = event => { console.log('\n', 'event.target.name', '\n', '\n', event.target.name ) this.setState({ ...this.state, [event.target.name]: event.target.checked, }) }; render() { const { details, people, hasBike, hasSpine } = this.state; console.log('\n', 'hasBike', '\n', hasBike, '\n', 'hasSpine', '\n', hasSpine, '\n', ) console.log('\n', 'this.state', '\n', '\n', this.state ) return ( <div className="App"> <input onChange={e => { const value = e.target.value; this.setEventName(value); }} value={details.eventName} /> <ul> {people.map(person => ( <li key={person.uuid}> {person.name} - {person.attending ? "Going" : "Not Going"} <button style={{margin: 10}} onClick={e => { e.preventDefault(); this.updateAttending(person.uuid, !person.attending); }} > {person.attending ? "Not Going" : "Going"} </button> <button onClick={e => { e.preventDefault(); this.removePerson(person.uuid); }} > Remove </button> </li> ))} </ul> <form onSubmit={e => { e.preventDefault(); if (this.nameRef.current.value) { this.addPerson(this.nameRef.current.value); e.target.reset(); } }} > <input ref={this.nameRef} placeholder="Attendee's name" required /> <button>Add</button> </form> <br/> <hr/> <hr/> <hr/> <br/> <h1> CRUD </h1> <Crud /> <br/> <hr/> <hr/> <hr/> <br/> <h1> Checkbox </h1> <input onChange={this.toggleHasSpine} type="checkbox" name="hasSpine" checked={hasSpine} /> <span style={{marginLeft: 20}}> I have a spine </span> <br/> <input onChange={this.toggleHasBike("hasBike")} type="checkbox" checked={hasBike} /> <span style={{marginLeft: 20}}> I have a bike </span> <br /> <h1>Radio</h1> <div className="form-check"> <label> <input type="radio" name="react-tips" value="option1" checked={this.state.selectedOption === "option1"} className="form-check-input" onChange={this.handleOptionChange} /> Option 1 </label> </div> <div className="form-check"> <label> <input type="radio" name="react-tips" value="option2" checked={this.state.selectedOption === "option2"} className="form-check-input" onChange={this.handleOptionChange} /> Option 2 </label> </div> <div className="form-check"> <label> <input type="radio" name="react-tips" value="option3" checked={this.state.selectedOption === "option3"} className="form-check-input" onChange={this.handleOptionChange} /> Option 3 </label> </div> </div> ); } }
Python
UTF-8
660
2.609375
3
[]
no_license
filename='batch.txt' outside=['mountain', 'opencountry', 'forest'] city=['insidecity', 'street', 'tallbuilding'] dist=dict() test=list() for line in open(filename): res=line.strip().split() '''' for idx in range(len(res)): if res[idx] in outside: res[idx]='outside' if res[idx] in city: res[idx]='city' ''' if dist.has_key(res[0]): if res[0]==res[1]: dist[res[0]][0]+=1 else: dist[res[0]][1]+=1 else: if res[0]==res[1]: dist[res[0]]=[1, 0] else: dist[res[0]]=[0, 1] for key in dist.keys(): print(key, dist[key])
JavaScript
UTF-8
717
2.53125
3
[]
no_license
import React from 'react'; export default class SearchForm extends React.Component { constructor(props) { super(); this.state = { input: '', }; this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.setState({ input: e.target.value }); } render() { return ( <div className={ 'search-form' } style={ { textAlign: 'center' } }> <form onSubmit={ e => ( e.preventDefault(), this.props.onSubmit(this.state.input), this.state.input = '' )}> <input type="text" value={ this.state.input } onChange={ this.handleChange } placeholder="Search by Title" /> <button type="submit">SEARCH</button> </form> </div> ) } };
Java
UTF-8
281
2.390625
2
[]
no_license
package com.cjx913.design_mode.behavioral.state; public class ProfessionalLevel extends SecondaryLevel { public ProfessionalLevel(Player player) { super(player); } @Override public void changeCards() { System.out.println("可以换牌"); super.changeCards(); } }
Python
UTF-8
10,100
2.875
3
[]
no_license
import json import time import os from collections import defaultdict from typing import List, Dict, Tuple, Set import boto3 class Config: """ This class represents configuration to be used further. """ # Rekognition will look for any of these words if they belong to its catalogue PERSON_KEYS: List[str] = [ 'Person', 'Human'] # The same applies to potential PPEs, whose words are grouped # in the generic PPE name TARGET_PPE_GROUP_KEYS: Dict[str, List[str]] = { 'helmet' : [ 'Helmet', 'Hardhat'], #'vest' : [ 'Vest', 'Waistcoat', 'Safetyjacket'], #The vest label is not recognized as much as the other PPEs. Discarded. 'boot' : [ 'Boot', 'Shoe' ] } MAX_LABELS: int = 30 # This can be changed MIN_CONFIDENCE: int = 70 # It has work well after testing #A Lambda handler function processes events # It is ran by the runtime #Once it retunrs an answer, it will be available to handle another event def lambda_handler(event: dict, context: object) -> dict: bucket_name: str = event['Records'][0]['s3']['bucket']['name'] image_name: str = event['Records'][0]['s3']['object']['key'] stats: Stats = build_stats(bucket_name, image_name) push_to_cloud_watch( 'PersonsWithSafetyEquip1', stats.equipped_size()) push_to_cloud_watch( 'PersonsWithoutSafetyEquip1', stats.unequipped_size()) output_message: str = stats.prepare_message() print(output_message) s3_client: object = boto3.client('s3') image_url: str = s3_client.generate_presigned_url( 'get_object', Params={'Bucket': bucket_name, 'Key': image_name }) iot_message: dict = stats.prepare_response(image_url) send_message_to_iot_topic(iot_message) return { 'statusCode': 200, 'body': json.dumps(output_message) } class Interval: """ Represents 1-dimensional segments. """ def __init__(self): self.min: int = 0 self.max: int = 0 class BoundingBox: """ Represents bounding box as horizontal and vertical intervals. """ def __init__(self): self.x_interval: Interval = Interval() self.y_interval: Interval = Interval() def make_bounding_box(box_data: dict) -> BoundingBox: """ It creates a bounding box based on above classes """ box: BoundingBox = BoundingBox() width: float; height: float; left: float; right: float; top: float; bottom: float width, height = box_data['Width'], box_data['Height'] left, top = box_data['Left'], box_data['Top'] right, bottom = left + width, top + height box.x_interval.min = min(left, right) box.x_interval.max = max(left, right) box.y_interval.min = min(top, bottom) box.y_interval.max = max(top, bottom) return box def if_intervals_intersect(lhs: Interval, rhs: Interval) -> bool: """ Checks if two intervals intersect. """ if lhs.min > rhs.min: lhs, rhs = rhs, lhs return rhs.min < lhs.max def if_boxes_intersect(lhs_box: BoundingBox, rhs_box: BoundingBox) -> bool: """ Checks if two boxes intersect. """ if_x_intersect: bool = if_intervals_intersect(lhs_box.x_interval, rhs_box.x_interval) if_y_intersect: bool = if_intervals_intersect(lhs_box.y_interval, rhs_box.y_interval) return if_x_intersect and if_y_intersect class Person: """ This class stores a person's index, bounding box, equipment and confidence. """ def __init__(self): self.equipment: Set[str] = set() self.ind: int = None self.box: BoundingBox = None self.confidence: float = None class Stats: """ This class provides population size, who is wearing a specific type of PPE and who is unequipped """ def __init__(self, population: List[Person]): self.population: List[Person] = list() self.equipment2person: Dict[str, List[Person]] = defaultdict(list) person: Person for person in population: self._add_person(person) def population_size(self) -> int: """ Amount of people detected""" return len(self.population) def unequipped_size(self) -> int: """ Amount of unequipped people detected""" return sum([1 for entry in self.population if len(entry.equipment) == 0]) def equipped_size(self) -> int: """ Amount of equipped people detected. """ return self.population_size() - self.unequipped_size() def prepare_message(self) -> str: """ It outputs all the results from an image""" response: str = "Found {} persons.\n".format(self.population_size()) response += "Without equipment: {}.\n".format(self.unequipped_size()) equipment_group: str for equipment_group in Config.TARGET_PPE_GROUP_KEYS: response += "Persons with {}: {}.\n".format( equipment_group, len(self.equipment2person[equipment_group])) idx: int; person: Person for idx, person in enumerate(self.population): if len(person.equipment) > 0: response += ("Person {} wears: " + ", ".join(person.equipment) + ".\n").format(idx) else: response += "Person {} is unequipped.\n".format(idx) return response def prepare_response(self, presigned_url: str) -> dict(): """ Transforms summary into JSON """ result: dict = {} result['Message'] = self.prepare_message() result['ImageUrl'] = presigned_url result['PopulationSize'] = self.population_size() result['UnequippedSize'] = self.unequipped_size() result['EquipmentPerPerson'] = [ {'ind' : person.ind, 'equipment' : list(person.equipment)} for person in self.population ] result['PersonsPerEquipment'] = {} key: str for key in Config.TARGET_PPE_GROUP_KEYS: result['PersonsPerEquipment'][key] = [str(person.ind) for person in self.equipment2person[key]] return result def _add_person(self, person: Person) -> None: # Auxiliary function to add a person to the structure. person.ind = len(self.population) self.population.append(person) key: str for key in person.equipment: self.equipment2person[key].append(person) def build_stats(bucket_name: str, image_name: str) -> Stats: """ Send request to the API and get bounding boxes """ rekognition: object = boto3.client('rekognition', region_name='us-east-1') response_labels: list = rekognition.detect_labels( Image={ 'S3Object': { 'Bucket': bucket_name, 'Name': image_name, } }, MaxLabels=Config.MAX_LABELS, MinConfidence=Config.MIN_CONFIDENCE ) population: List[Person] equipment_boxes: Dict[str, List[BoundingBox]] population, equipment_boxes = parse_objects(response_labels) person: Person for person in population: group: str boxes: List[BoundingBox] for group, boxes in equipment_boxes.items(): for box in boxes: if if_boxes_intersect(person.box, box): person.equipment.add(group) stats: Stats = Stats(population) return stats def parse_objects(response_labels: dict) -> Tuple[List[Person], Dict[str, List[BoundingBox]]]: """ Parses objects in the response labels provided by rekognition API. """ population: List[Person] = list() equipment_boxes: List[BoundingBox] = defaultdict(list) label: dict for label in response_labels['Labels']: if 'Instances' in label: if label['Name'] in Config.PERSON_KEYS: entry: dict for entry in label['Instances']: if 'BoundingBox' in entry and 'Confidence' in entry: person: Person = Person() confidence: float = entry['Confidence'] box_data: dict = entry['BoundingBox'] box: BoundingBox = make_bounding_box(box_data) person.box = box person.confidence = confidence population.append(person) else: group: str names: List[str] for group, names in Config.TARGET_PPE_GROUP_KEYS.items(): entry: dict if label['Name'] not in names: continue for entry in label['Instances']: if 'BoundingBox' in entry and 'Confidence' in entry: box_data: dict = entry['BoundingBox'] box: BoundingBox = make_bounding_box(box_data) confidence: float = entry['Confidence'] equipment_boxes[group].append(box) return population, equipment_boxes def send_message_to_iot_topic(iot_message: str) -> None: """ Sends message to IoT topic. """ topic_name: str = "worker-safety" if "iot_topic" in os.environ: topic_name: str = os.environ['iot_topic'] iot_client: object = boto3.client('iot-data', region_name='us-east-1') response: object = iot_client.publish( topic=topic_name, qos=1, payload=json.dumps(iot_message) ) print("Send message to topic: " + topic_name) def push_to_cloud_watch(name: object, value: object) -> None: """ Pushes key-value pairs to CloudWatch. """ try: cloudwatch: object = boto3.client('cloudwatch', region_name='us-east-1') response: object = cloudwatch.put_metric_data( Namespace='string', MetricData=[ { 'MetricName': name, 'Value': value, 'Unit': 'Count' }, ] ) except Exception as e: print("Unable to push to cloudwatch\n e: {}".format(e)) return True
Java
UTF-8
429
3.171875
3
[]
no_license
class Solution { public int maxArea(int[] height) { int i=0; int j=height.length-1; int totalarea=0; int area=0; while(i<j) { totalarea=(j-i)*Math.min(height[i],height[j]); area=Math.max(totalarea,area); if(height[i]<height[j]) { i++; } else { j--; } } return area; } }
SQL
UTF-8
130
3.1875
3
[]
no_license
# Write your MySQL query statement below SELECT product_id, SUM(quantity) AS total_quantity FROM Sales GROUP BY product_id;
TypeScript
UTF-8
14,246
2.9375
3
[ "BSD-3-Clause" ]
permissive
import { and, assert, assertSoft, eq, implies, not, or, capitalizeFirstLetter} from "./helpers"; import {isDimension, isMeasure } from "./constraints"; function iteFromDict(getValueExpr, dict, type, lastElseValue = 10000){ // dict should be exhaustive // todo: lowp check values in dict are proper /* * Recurse through dict * */ const helper = ([head, ...tail]) => { if (head === undefined) return `${lastElseValue}`; else { const [key, value] = head; return `(ite (= ${getValueExpr} ${capitalizeFirstLetter(key) + type} ) ${value} ${helper(tail)})`; } }; return helper((Object as any).entries(dict)); } /* greg: penalty functions with maximize let us express: if enough constraints at a "lower level" of priority are violated this should override constraints at a higher level in terms of hierarchies (like the channel_penalty) expressing the channel penalty as 8 different constraints, we can't "group them together" to refer to their value and weight that value (it can be done but have to do the multiplication into the weight, and that weight isn't a solved for variable, it is defined before the program runs greg: how to do it with soft constraints for the single valued penalty functions (= (channel e1) key) weight: value */ function oldEncName(enc, i){ return `old_enc${i}`; } function newEncName(enc, i){ return `new_enc${i}`; } // https://github.com/vega/compassql/tree/master/src/ranking // why not use http://rise4fun.com/z3opt/tutorial/ ? // many functions taken from https://docs.google.com/document/d/1RPs3smH5hq4BOwGPc5tx8IlcelpXzTUozi3bFU0M5Ss/edit# export function ranking(fields, query, encs) { let penaltyFunctionDefinitions: string[] = []; let penaltyFunctionNames: string[] = []; let markPenaltyFunctions: string[] = []; // the following penalties are copy-pasted from // compassql/src/ranking/effectiveness/channel.ts on feb 8 // commit e8023aec8bd12c65bfddf36a1866dfd13869fa2d const TERRIBLE = 1000; // From Greg: to get Int arithmetic in z3, I moved decimal // two places to right and rounded up // x = y > size > color (ramp) > text > opacity >>> detail > shape ~ strokeDash ~ row = column const continuous_quant_penalties = { x: 0, y: 0, size: 58, color: 73, text: 200, opacity: 300, shape: TERRIBLE, row: TERRIBLE, column: TERRIBLE, detail: 2 * TERRIBLE }; // x = y > size > color (ramp) > text > row = column >> opacity > shape ~ strokeDash > detail const discretized_ordinal_penalties = (Object as any).assign({ row: 75, column: 75, shape: 310, text: 320, detail: 400 }, continuous_quant_penalties); // x = y > color (hue) > shape ~ strokeDash > text > row = column >> detail >> size > opacity const nominal_penalties = { x: 0, y: 0, color: 60, // TODO: make it adjustable based on preference (shape is better for black and white) shape: 65, row: 70, column: 70, text: 80, detail: 200, size: 300, opacity: 310 }; let penaltyFunctionName = "type_channel_penalty"; let typeChannelPenalty = `(define-fun ${penaltyFunctionName} ((e Encoding)) Int ; (Continuous) Quantitative / Temporal Fields (ite (or (= (type e) Quantitative) ) ${iteFromDict("(channel e)", continuous_quant_penalties, "Channel")} ; else Discretized Quantitative (Binned) / Temporal Fields / Ordinal (ite (or ;(= (type e) Binned) not yet in types (= (type e) Ordinal) ) ${iteFromDict("(channel e)", discretized_ordinal_penalties, "Channel")} ; else it is nominal ${iteFromDict("(channel e)", nominal_penalties, "Channel")} ) ) )`; penaltyFunctionDefinitions.push(typeChannelPenalty); penaltyFunctionNames.push(penaltyFunctionName); // more penalty functions go here that are f(encoding) // Greg: looks like ham's types have changed a bit? // compassql/src/ranking/effectiveness/type.ts // compassql/src/ranking/effectiveness/sizechannel.ts // if mark bar and channel size, penalty 200 const size_channel_penalties_by_mark = { bar: 200, tick: 200, }; penaltyFunctionName = "size_channel_penalty"; typeChannelPenalty = `(define-fun ${penaltyFunctionName} ((e Encoding)) Int (ite ${eq("(channel e)", "SizeChannel")} ${iteFromDict("mark", size_channel_penalties_by_mark, "Mark", 0)} 0 ) )`; penaltyFunctionDefinitions.push(typeChannelPenalty); penaltyFunctionNames.push(penaltyFunctionName); // mark compassql/src/ranking/effectiveness/mark.ts const one_mark_penalties = { point: 0, text: 20, tick: 50, line: 300, area: 300, bar: 300, rule: 300, rect: TERRIBLE }; const two_mark_penalties = { point: 0, text: 20, tick: 50, line: 300, area: 300, bar: 400, rule: 400, rect: TERRIBLE }; const two_b_two_penalties= { bar: 0, rule: 3, point: 5, text: 20, tick: 80, line: 400, area: 400, rect: TERRIBLE }; const three_a_mark_penalties = { tick: 80, point: 100, text: 120, line: 400, area: 400, bar: 500, rule: 800, rect: TERRIBLE }; const three_b_mark_penalties = { bar: 0, point: 21, tick: 40, text: 60, line: 400, area: 400, rule: 800, rect: TERRIBLE }; const four_a_mark_penalties = { rect: 5, point: 20, text: 40, tick: 120, bar: 500, line: 500, area: 500, rule: 500, }; const four_b_mark_penalties = { point: 6, text: 20, rect: 40, tick: 120, line: 400, area: 400, bar: 400, rule: 400, }; let singleVariableMarkPenaltyFunc = (e) => { let type = `(type ${e})`; let agg = `(agg ${e})`; let binned = `(binned ${e})`; return ` (ite ${and(eq(type, "Quantitative"), not(binned))} ${iteFromDict("m", three_a_mark_penalties, "Mark")} ; else not Quantitative (ite ${or(eq(type, "Nominal"), eq(type, "Ordinal"), binned)} (ite ${not(eq(agg, "None"))} ${iteFromDict("m", four_a_mark_penalties, "Mark")} ${iteFromDict("m", four_b_mark_penalties, "Mark")} ) ; should never occur ${TERRIBLE} ) ) `; }; // pattern here is to do x or y case then do the y or x case that mirrors it immediately // after, down the ITE chain. // First we handle the case where y or x or both have no encoding // Then we start the main cases after ; y is not null penaltyFunctionName="mark_penalty"; let mark_penalty_function= `(define-fun ${penaltyFunctionName} ((m Marktype)) Int (ite ${not(and(eq("getXEnc", "nullEnc"), eq("getYEnc", "nullEnc")))} (ite ${not(eq("getXEnc", "nullEnc"))} (ite ${eq("getYEnc", "nullEnc")} ${singleVariableMarkPenaltyFunc("getXEnc")} ; y is not null ; if both are aggregates (ite ${(and(eq("(type getXEnc)", "Quantitative"), not("(binned getXEnc)"), not(eq("(agg getXEnc)", "None")), eq("(type getYEnc)", "Quantitative"), not("(binned getYEnc)"), not(eq("(agg getYEnc)", "None"))))} ${iteFromDict("m", one_mark_penalties, "Mark")} ; else if only one is an aggregate and other not binned quant (ite ${or((and(eq("(type getXEnc)", "Quantitative"), not("(binned getXEnc)"), eq("(agg getXEnc)", "None"), eq("(type getYEnc)", "Quantitative"), not("(binned getYEnc)"), not(eq("(agg getYEnc)", "None")))), (and(eq("(type getXEnc)", "Quantitative"), not("(binned getXEnc)"), not(eq("(agg getXEnc)", "None")), eq("(type getYEnc)", "Quantitative"), not("(binned getYEnc)"), eq("(agg getYEnc)", "None"))))} ${iteFromDict("m", two_b_two_penalties, "Mark")} ; else if only one is an aggregate and other is binned quant (ite ${or((and(eq("(type getXEnc)", "Quantitative"), "(binned getXEnc)", eq("(agg getXEnc)", "None"), eq("(type getYEnc)", "Quantitative"), not("(binned getYEnc)"), not(eq("(agg getYEnc)", "None")))), (and(eq("(type getXEnc)", "Quantitative"), not("(binned getXEnc)"), not(eq("(agg getXEnc)", "None")), eq("(type getYEnc)", "Quantitative"), "(binned getYEnc)", eq("(agg getYEnc)", "None"))))} ${iteFromDict("m", three_b_mark_penalties, "Mark")} ;else if not binned and not aggregates and quant (ite ${(and(eq("(type getXEnc)", "Quantitative"), not("(binned getXEnc)"), eq("(type getYEnc)", "Quantitative"), not("(binned getYEnc)")))} ${iteFromDict("m", two_mark_penalties, "Mark")} ; else if multiple measure values for each dimension (todo: add stats here for multivalue and 3c cases) (ite ${or(and(isDimension("getXEnc"), isMeasure("getYEnc")), and(isDimension("getYEnc"), isMeasure("getXEnc")))} ${iteFromDict("m", three_a_mark_penalties, "Mark")} ;else we are into ordinal and below so all 4 cases ; without adding constraints to show count with color here (ie heatmap-ish) ; overplotting very easy 10 ) ) ) ) ) ) ; x is null and y is not null ${singleVariableMarkPenaltyFunc("getYEnc")} ) ; x and y were null 0 ) )`; /* (ite ${or(and(eq("(type getXEnc)", "Quantitative"),not("(binned getXEnc)")), and(eq("(type getYEnc)", "Quantitative"),not("(binned getYEnc)")))} ${iteFromDict("m", three_b_mark_penalties)} ${iteFromDict("m", three_b_mark_penalties)} */ /* TODO: implement temporal and stats (eg duplicate values) to support diffs in 3 (ite ${and(eq(chan, "Quantitative"), not(eq(agg, "None")))} ${iteFromDict("m", three_a_mark_penalties)} ; else has an aggregation, for now use same ${iteFromDict("m", three_a_mark_penalties)} ) */ // TODO: ask ham to open compassql and use console to output the table directly // will be easier to parse the full table than copy-paste it's generating logic here // double-check with ham that it's a static table (seems to be so) // compassql/src/ranking/effectiveness/dimension.ts // Penalize if facet channels are the only dimensions // if there is an aggregation if (not (= (agg enc) None) // find the encoding that ... ? ask ham encs.forEach((enc, i) => { }); // compassql/src/ranking/effectiveness/facet.ts // effectiveness score for preferred facet // Greg: we don't have preferred facet I think? // we would just enter that as an assertion for having it as row or column directly // in the query part // Ham just does penalty of 1 for the "non-preferred" opposite eg just col or row // now we can have any other penalty functions we need // like if we want one that is comparisonPenalty(oldEncoding, newEncoding) // penalties hold the expression that refers // to z3 functions const penaltyStatements: string[] = []; encs.forEach((enc, i) => { penaltyFunctionNames.forEach( (pf, j) => { // make each constraint penaltyStatements.push( `(${pf} ${enc} )` ); /* // if want to do compared to old solution iteratively penaltyStatements.push( `(- (${pf} ${oldEncName(enc,i)}) (${pf} ${newEncName(enc,i)}) )`); }); */ }); }); // single functions let penaltySumStmt = `(+ ${penaltyStatements.join(" ")} (* 1 (${penaltyFunctionName} mark)))`; let minimizeStmt = `(minimize ${penaltySumStmt})`; // if deisred, we can add a constraint for // sum of the penalties for old > sum of the penalties for the new // but I'm not including that now, since this should just minimize it let definitions = penaltyFunctionDefinitions.join(" "); //definitions = definitions + '\n' + getXEncFunc + '\n' + getYEncFunc + '\n' + mark_penalty_function; definitions = definitions + '\n' + mark_penalty_function; definitions += "\n (declare-const mpen Int) (assert (= mpen (mark_penalty mark))) "; definitions += "\n (declare-const gx Encoding) (assert (= gx getXEnc)) "; definitions += "\n (declare-const gy Encoding) (assert (= gy getYEnc)) "; definitions += `\n (declare-const pen Int) (assert (= pen ${penaltySumStmt})) `; return [definitions, minimizeStmt]; // can also solve for other conditions // START PARETO OPTIMAL /* const penaltyStatements = []; encs.forEach((enc, i) => { penaltyFunctionNames.forEach( (pf, j) => { // make each constraint penaltyStatements.push( `(>= (${pf} ${oldEncName(enc)}) (${pf} ${newEncName(enc)}) )`); }); }); */ // // sum of the penalties for old > sum of the penalties for the new // // END PARETO OPTIMAL // // or can use it via minimize the sum of the penalties // // START MINIMIZE OVERALL // // (assert ${sum of the old penalties} > ${expression for sum of penalties for new}) // // (minimize ${expression for sum of penalties for new}) // // one way to encode that last statement is // to_minimize_expressions += `(- (${pf} oldEnc) (${pf} newEnc))` // solver_minimize = `(minimize (+ ${to_minimize_expressions.join(" ")}))`; }
Java
UTF-8
541
1.757813
2
[]
no_license
package com.qixiaoyi.cariyou.module.T1splash; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import com.qixiaoyi.cariyou.R; import com.qixiaoyi.cariyou.module.T11.EditbusinesshoursActivity; public class SplashActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); startActivity(new Intent(SplashActivity.this,EditbusinesshoursActivity.class)); } }
Python
UTF-8
1,205
3.8125
4
[]
no_license
# def count_word(str1): # list1 = str1.split(" ") # list2 = [] # for i in range(0,len(list1)): # cnt = list1.count(list1[i]) # if list1[i] not in list2: # list2.append(list1[i]) # print (list1[i]," : ",cnt) # if __name__=="__main__": # str1 = input("Enter String : ") # if(str1.isalnum() or str1.find(" ")): # count_word(str1) # else: # print("Enter valid inputs") def count_words(input_l): d = {} for i in input_l: count_word = input_l.count(i) if i not in d: d.update({i: count_word}) return (d) def valid_data(input_l): try: if len(input_l) == 0: return False for i in input_l: if not i.isalpha(): return False except Exception as e: return False return input_l if __name__ == "__main__": #Takes the input from User and convert to list input_l = [x for x in input("Enter String : ").split()] valid_input = valid_data(input_l) if valid_input is False: print ("Please insert string only.") else: answer_dict = count_words(valid_input) for key, value in answer_dict.items() : print (key, " : " ,value)
Python
UTF-8
370
3.359375
3
[]
no_license
factorials=[] val=1 for i in range(1,11): val *= i factorials.append(val) million=1000000 summation=0 addedAmount=[] for i in range(0,len(factorials)): count = 0 while million - summation >= factorials[len(factorials)-1-i]: summation += factorials[len(factorials)-1-i] count+=1 addedAmount.append(count) print(addedAmount)
Java
UTF-8
4,044
2.0625
2
[]
no_license
// // Decompiled by Procyon v0.5.30 // package com.wurmonline.server.intra; import java.nio.ByteBuffer; import java.io.IOException; import java.util.logging.Level; import com.wurmonline.server.Servers; import com.wurmonline.server.ServerEntry; import java.util.logging.Logger; public final class ServerPingCommand extends IntraCommand { private static final Logger logger; private final ServerEntry server; private boolean done; private IntraClient client; private boolean pinging; ServerPingCommand(final ServerEntry serverEntry) { this.done = false; this.pinging = false; this.server = serverEntry; } @Override public boolean poll() { if (this.server.id == Servers.localServer.id) { return true; } if (this.client == null) { if (ServerPingCommand.logger.isLoggable(Level.FINER)) { ServerPingCommand.logger.finer("1 " + this.getLoginServerIntraServerAddress() + ", " + this.getLoginServerIntraServerPort() + ", " + this.getLoginServerIntraServerPassword()); } try { (this.client = new IntraClient(this.getLoginServerIntraServerAddress(), Integer.parseInt(this.getLoginServerIntraServerPort()), this)).login(this.server.INTRASERVERPASSWORD, true); ServerPingCommand.logger.log(Level.INFO, "connecting to " + this.server.id); } catch (IOException iox) { this.server.setAvailable(false, false, 0, 0, 0, 10); this.client.disconnect("Failed."); this.client = null; ServerPingCommand.logger.log(Level.INFO, "Failed"); this.done = true; } } if (this.client != null && !this.done) { if (System.currentTimeMillis() > this.timeOutAt) { this.done = true; } if (!this.done) { try { if (this.client.loggedIn && !this.pinging) { this.client.executePingCommand(); this.pinging = true; this.timeOutAt = System.currentTimeMillis() + this.timeOutTime; } if (!this.done) { this.client.update(); } } catch (IOException iox) { this.server.setAvailable(false, false, 0, 0, 0, 10); this.done = true; } } if (this.done && this.client != null) { this.client.disconnect("Done"); this.client = null; } } return this.done; } @Override public void commandExecuted(final IntraClient aClient) { this.done = true; } @Override public void commandFailed(final IntraClient aClient) { this.server.setAvailable(false, false, 0, 0, 0, 10); this.done = true; } @Override public void dataReceived(final IntraClient aClient) { this.done = true; } @Override public void reschedule(final IntraClient aClient) { this.server.setAvailable(false, false, 0, 0, 0, 10); this.done = true; } @Override public void remove(final IntraClient aClient) { this.done = true; } @Override public void receivingData(final ByteBuffer buffer) { final boolean maintaining = (buffer.get() & 0x1) == 0x1; final int numsPlaying = buffer.getInt(); final int maxLimit = buffer.getInt(); final int secsToShutdown = buffer.getInt(); final int meshSize = buffer.getInt(); this.server.setAvailable(true, maintaining, numsPlaying, maxLimit, secsToShutdown, meshSize); this.timeOutAt = System.currentTimeMillis() + this.timeOutTime; this.done = true; } static { logger = Logger.getLogger(ServerPingCommand.class.getName()); } }
Java
UTF-8
363
1.859375
2
[]
no_license
package com.waiwang1113.myreminder.injection; import com.waiwang1113.myreminder.repository.ReminderTaskRepository; import javax.inject.Singleton; import dagger.Component; /** * Created by wanwe17 on 2/2/2017. */ @Singleton @Component(modules = {AppModule.class}) public interface AppComponent { ReminderTaskRepository provideReminderTaskRepository(); }
Java
UTF-8
2,595
2.046875
2
[ "MIT" ]
permissive
package org.mitallast.queue.rest.action.queue; import com.google.inject.Inject; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import org.mitallast.queue.action.queue.stats.QueueStatsRequest; import org.mitallast.queue.action.queue.stats.QueueStatsResponse; import org.mitallast.queue.common.settings.Settings; import org.mitallast.queue.common.xstream.XStreamBuilder; import org.mitallast.queue.queues.stats.QueueStats; import org.mitallast.queue.rest.BaseRestHandler; import org.mitallast.queue.rest.RestController; import org.mitallast.queue.rest.RestRequest; import org.mitallast.queue.rest.RestSession; import org.mitallast.queue.rest.response.ByteBufRestResponse; import org.mitallast.queue.transport.TransportService; import java.io.IOException; public class RestQueueStatsAction extends BaseRestHandler { private final TransportService transportService; @Inject public RestQueueStatsAction(Settings settings, RestController controller, TransportService transportService) { super(settings); this.transportService = transportService; controller.registerHandler(HttpMethod.GET, "/{queue}/_stats", this); } @Override public void handleRequest(final RestRequest request, final RestSession session) { QueueStatsRequest queueStatsRequest = QueueStatsRequest.builder() .setQueue(request.param("queue").toString()) .build(); transportService.client().<QueueStatsRequest, QueueStatsResponse>send(queueStatsRequest) .whenComplete((response, error) -> { if (error == null) { QueueStats queueStats = response.stats(); ByteBuf buffer = Unpooled.buffer(); try { try (XStreamBuilder builder = createBuilder(request, buffer)) { builder.writeStartObject(); builder.writeStringField("name", queueStats.getQueue().getName()); builder.writeNumberField("size", queueStats.getSize()); builder.writeEndObject(); } session.sendResponse(new ByteBufRestResponse(HttpResponseStatus.OK, buffer)); } catch (IOException e) { session.sendResponse(e); } } else { session.sendResponse(error); } }); } }