language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
222
2.890625
3
[]
no_license
package Abstraction; public abstract class Rajaram { int age; public Rajaram(int a) { age=a; } abstract public void nadi(); public void premagopadi() { System.out.println("Abstraction class ... age "+age); } }
C++
UTF-8
831
3.1875
3
[]
no_license
#pragma once #include "../constants.h" #include <iostream> using namespace std; struct Movement { unsigned type, o1, o2; }; bool isChangeInitialized(Movement mv) { return mv.o1 != 0; } string getMovementString(Movement mv) { string t = mv.type == SWAP ? "swap" : "shift"; return t + "(" + to_string(mv.o1) + "," + to_string(mv.o2) + ")"; } void printMovement(Movement mv) { cout << getMovementString(mv) << br; ; } bool isMovementEmpty(Movement mv) { return mv.o1 == 0 && mv.o2 == 0; } void assertNonNullMovement(Movement mv) { if (isMovementEmpty(mv)) { cout << "(!) Invalid schedule change: " << getMovementString(mv) << br; //assert(sc.o2); } } bool areEqual(Movement mv1, Movement mv2) { return mv1.type == mv2.type && mv1.o1 == mv2.o1 && mv1.o2 == mv2.o2; }
Python
UTF-8
698
3.03125
3
[]
no_license
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t): return False scode_dict = dict() tcode_dict = dict() for i in range(len(s)): if s[i] in scode_dict: if scode_dict[s[i]] != t[i]: return False else: scode_dict[s[i]] = t[i] if t[i] in tcode_dict: if tcode_dict[t[i]] != s[i]: return False else: tcode_dict[t[i]] = s[i] return True
C#
UTF-8
1,317
3.640625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exam_3_Kung_Fu_Hall { class Hall { private int RangeOfFights { get; } public Hall() { RangeOfFights = ChooseRangeOfFights(); var tasks = new List<Task>(); for (int i = 1; i <= RangeOfFights; i++) { Battle battle = new Battle(); tasks.Add(battle.Begin()); } Task.WaitAll(tasks.ToArray()); Console.WriteLine("Done"); } private int ChooseRangeOfFights() { try { Console.WriteLine("Enter number from 1 to 100"); var input = Console.ReadLine(); int range = int.Parse(input); if (range < 1 || range > 1000) { throw new ArgumentException(); } return range; } catch (Exception ex) when (ex is ArgumentException || ex is FormatException) { Console.WriteLine("You did not enter a namber. Enter number from 1 to 5 one more time"); return ChooseRangeOfFights(); } } } }
Java
UTF-8
81
1.8125
2
[]
no_license
package mk.p.factory; public enum CarType { SEDAN, CROSSOVER, VAN }
C#
UTF-8
1,696
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace TestMe.Presentation.API.Middleware { /// <summary> /// Sample showing how to use custom Middleware rather than something that fulfils a real need in this project. /// </summary> public sealed class RequestLogger { private readonly RequestDelegate next; private readonly ILogger<RequestLogger> logger; public RequestLogger(RequestDelegate next, ILogger<RequestLogger> logger) { this.next = next; this.logger = logger; } public async Task Invoke(HttpContext context) { var stopwatch = new Stopwatch(); stopwatch.Start(); await next.Invoke(context); var scopeData = new Dictionary<string, object> { { "RequestMethod", context.Request.Method }, { "RequestQuery", context.Request.Query}, { "RequestQueryString", context.Request.QueryString }, { "RequestPath", context.Request.Path }, { "RequestPathBase", context.Request.PathBase }, { "RequestContentType", context.Request.ContentType }, { "StatusCode", context.Response.StatusCode } }; stopwatch.Stop(); using (var scope = logger.BeginScope(scopeData)) { logger.LogInformation(1000, "Request completed in {ElapsedTime} ms ", stopwatch.ElapsedMilliseconds); } } } }
Python
UTF-8
1,772
3.390625
3
[]
no_license
from tkinter import * ventana= Tk() ventana.geometry("500x500") ventana.title("Formularios en Tkinter") #Encabezado Encabezado=Label(ventana,text="Formularios en TKinter") Encabezado.config(bg="white", fg="darkgray", font=("Open Sans", 18), padx=10, pady=10 ) Encabezado.grid(row=0,column = 0, columnspan=3, sticky=W) #Si ocupo grid, no puedo usar pack #Label para el campo NOMBRE label = Label(ventana,text="Nombre") label.grid(row=1,column=0, padx=5,pady=5, sticky=W) #Label para el campo APELLIDOS label = Label(ventana,text="Apellidos") label.grid(row=2,column=0, padx=5,pady=5, sticky=W) #CREACION campo de texto NOMBRE campo_texto = Entry(ventana) campo_texto.grid(row = 1,column = 1,padx=5,pady=5, sticky = W) #CREACION campo de texto APELLIDOS campo_texto2 = Entry(ventana) campo_texto2.grid(row = 2,column = 1,padx=5,pady=5, sticky = W) campo_texto2.config(justify="right",state="disable") #state-->disable,normal #Justify --> entra de texto por derecha,izquierda #Label para el campo TEXTO GRANDE label = Label(ventana,text="Descripcion") label.grid(row=3,column=0, padx=5,pady=5, sticky=NW) campo_texto.grid(row = 1,column = 1,padx=5,pady=5, sticky = W) #CAMPO TEXTO GRANDE P/ DESCRIPCION campo_grande= Text(ventana) campo_grande.grid(row=3,column=1) campo_grande.config(width=30, height=5, font=("Arial",12), padx=15, pady=15 ) #%% Botones Label(ventana).grid(row=4,column=5)#Espaciado boton = Button(ventana,text="Enviar") boton.grid(row=5,column=1,sticky=E) boton.config(bg="green",fg="white",padx=10,pady=4) ventana.mainloop()
TypeScript
UTF-8
1,791
3
3
[]
no_license
import * as Yup from 'yup'; interface iSignUp { name: string; email: string; password: string; } export const validateSignUp = async ( data: iSignUp, ): Promise<boolean | string[]> => { try { const schema = Yup.object().shape({ name: Yup.string().required('Nome obrigatório'), email: Yup.string() .required('E-mail obrigatório') .email('Digite um e-mail válido'), password: Yup.string().min(8, 'Minimo de 8 caracteres'), }); await schema.validate(data, { abortEarly: false }); return true; } catch (err) { return err.errors; } }; interface iSignIn { email: string; password: string; } export const validateSignIn = async (data: iSignIn): Promise<void> => { const schema = Yup.object().shape({ email: Yup.string() .required('E-mail obrigatório') .email('Digite um e-mail válido'), password: Yup.string().min(8, 'Minimo de 8 caracteres'), }); await schema.validate(data, { abortEarly: false }); }; interface iCreateTask { name: string; date: Date | null; } export const validateCreateTask = async (data: iCreateTask): Promise<void> => { const schema = Yup.object().shape({ name: Yup.string().min(5, 'Minimo de 5 caracteres'), date: Yup.date().required('Obrigatório uma data'), }); await schema.validate(data, { abortEarly: false }); }; interface iUpdateTask { comments?: string; status: string; finish_date: Date | null; } export const validateUpdateTask = async (data: iUpdateTask): Promise<void> => { const schema = Yup.object().shape({ comments: Yup.string(), status: Yup.string().required('Obrigatório status'), finish_date: Yup.date().required('Obrigatório uma data'), }); await schema.validate(data, { abortEarly: false }); };
Swift
UTF-8
2,590
2.765625
3
[]
no_license
// // StampSelectViewDelegate.swift // Megaphone // // Created by 南 京兵 on 2017/08/16. // Copyright © 2017年 南 京兵. All rights reserved. // import UIKit // MARK: StampSelectViewDelegate extension NamingViewController: StampSelectViewDelegate { // スタンプViewの閉じるボタンが押された時 func stampSelectCloseTapped() { closeStampSelectView(isAnimation: true) } func stampSelectImageTapped(imageName: String) { // スタンプをタップしたとき呼ばれる // とりあえず画面の中心に配置 let screen = UIScreen.main.bounds.size let origin = CGPoint(x: (screen.width / 2) - 50, y: (screen.height / 2) - 130) let size = CGSize(width: 100, height: 130) stampAddImageView(imageName: imageName, origin: origin, size: size) } // スタンプをimageViewに追加する func stampAddImageView(imageName: String, origin: CGPoint, size: CGSize) { if let stampView = UINib(nibName: StampView.nibName, bundle: nil).instantiate(withOwner: nil, options: nil).first as? StampView { stampView.delegate = self stampView.stamp.image = UIImage(named: imageName) // 永続化のためにプロパティで保持 stampView.imageName = imageName stampView.beforeFrame = origin // 位置を大きさを設定 stampView.frame.origin = origin stampView.frame.size = size // imageViewに追加 self.imageView?.addSubview(stampView) } } // MARK: - スタンプ選択Viewを閉じる func closeStampSelectView(isAnimation: Bool) { // 色変更のViewがなかったら以下に進まない guard let stampSelectView = self.stampSelectView else { return } func delete() { // レイヤーから削除 stampSelectView.removeFromSuperview() // ポインタを破棄 self.stampSelectView = nil } if isAnimation { // アニメーションありでSettingViewを消す UIView.animate(withDuration: 0.5, delay: 0.0, options: .allowAnimatedContent, animations: { stampSelectView.frame.origin.y += stampSelectView.frame.size.height }, completion: { fin in delete() }) } else { // アニメーション無しでSettingViewを消す delete() } } }
Java
UTF-8
538
1.671875
2
[]
no_license
package com.ibucks.bucks.beans; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import java.util.List; /** * @Description: 扩展springboot自动装配 MongoCustomConversion类 * @Author: shang * @CreateDate: 2020/3/26 16:29 * @UpdateUser: shang * @UpdateDate: 2020/3/26 16:29 * @UpdateRemark: * @Version: 1.0 */ public class IMongoCustomConversions extends MongoCustomConversions { public IMongoCustomConversions(List<?> converters) { super(converters); } }
C++
UTF-8
720
2.546875
3
[]
no_license
//#include<conio.h> #include<iostream> #include<time.h> #include<graphics.h> #include<stdlib.h> using namespace std; int main(){ int x1,y1,x0,y0; //Declare the points cout<<"Enter the points"; cin>>x0; cin>>y0; cin>>x1; cin>>y1; float m; int gd= DETECT,gm; initgraph(&gd,&gm,"C:\\TURBOC3\\BGI"); m=((y1-y0)/(x1-x0)); //Slope calculation while(x0!=x1){ if(m<1){ //case 1 x0=x0+1; y0=y0+int(m); putpixel(x0,y0,RED); // Construct the line } else if (m>1) //case 2 { y0=y0+1; x0=x0+(1/m); putpixel(x0,y0,RED); } else if (m==1) //Case 3 { x0=x0+1; y0=y0+1; putpixel(x0,y0,RED); } } delay(5000); closegraph(); return 0; }
Python
UTF-8
925
3.53125
4
[]
no_license
class Solution: def myPow(self, x: float, n: int) -> float: ''' method most common people will use this method ''' return x ** n ''' well I guess the LC would like to see us solve it via BINARY SEARCH m 是 无符号的 n https://leetcode.com/problems/powx-n/discuss/19566/Iterative-JavaPython-short-solution-O(log-n) We can see that every time we encounter a 1 in the binary representation of N, we need to multiply the answer with x^(2^i) where i is the ith bit of the exponent. Thus, we can keep a running total of repeatedly squaring x - (x, x^2, x^4, x^8, etc) and multiply it by the answer when we see a 1. ''' m = abs(n) ans = 1.0 while m: if m % 2 != 0: ans *= x x *= x m //= 2 return ans if n >= 0 else 1 / ans
Java
UTF-8
8,877
2.015625
2
[]
no_license
package com.console.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.HtmlUtils; import com.console.dto.BuildingsDto; import com.console.dto.CityInfo; import com.console.dto.DevelopersDto; import com.console.dto.ProvincesDto; import com.console.dto.TradeArea; import com.console.framework.dao.Pagination; import com.console.util.Constant; import com.console.util.HttpClientPostMethod; import com.console.util.MsgPropertiesUtils; @Controller @RequestMapping("/builld") public class BuildingAction extends BaseController { @RequestMapping("/toBuilding") public ModelAndView toBuilding(HttpSession session,HttpServletRequest request) throws Exception { ModelAndView mv = new ModelAndView(); Pagination pager = new Pagination(); int current_page;// ��ǰҳ if (null==request.getParameter("current_page") || ("").equals(request.getParameter("current_page"))) { current_page = 0; }else { current_page = Integer.parseInt(request.getParameter("current_page")); } pager.setCurrent_page(current_page); pager.setPage_size(MsgPropertiesUtils.getPageSize()); List<BuildingsDto> buildingsList=getBuildings(pager,Constant.BUILDING_TYPE_00); pager.paging(current_page, pager.getPage_size(), pager.getTotal_count()); mv.addObject("pager", pager); mv.addObject("buildingsList", buildingsList); List<CityInfo> cityList=getCities(); List<ProvincesDto> proList=getProvinces(); List<DevelopersDto> devList=getDevelopers(); mv.addObject("cityList", cityList); mv.addObject("proList", proList); mv.addObject("devList", devList); mv.setViewName("/builld/builldList_new"); return mv; } @RequestMapping("/getBuildingsDetail") public ModelAndView getBuildingsDetail(HttpSession session,HttpServletRequest request) throws Exception { ModelAndView mv = new ModelAndView(); Integer buildId=Integer.valueOf(request.getParameter("buildId")); Integer[] buildIdInt=new Integer[1]; buildIdInt[0]=buildId; List<BuildingsDto> buildingsList=getBuildingsDetail(buildId); BuildingsDto buildingsDto = buildingsList.get(0); buildingsDto.setName(HtmlUtils.htmlEscape(buildingsDto.getName())); buildingsDto.setBldImg(HtmlUtils.htmlEscape(buildingsDto.getBldImg())); buildingsDto.setVedio(HtmlUtils.htmlEscape(buildingsDto.getVedio())); buildingsDto.setMark(HtmlUtils.htmlEscape(buildingsDto.getMark())); buildingsDto.setDescription(HtmlUtils.htmlEscape(buildingsDto.getDescription())); buildingsDto.setHouseExplain(HtmlUtils.htmlEscape(buildingsDto.getHouseExplain())); mv.addObject("buildings", buildingsDto); List<CityInfo> cityList=getCities(); List<ProvincesDto> proList=getProvinces(); List<DevelopersDto> devList=getDevelopers(); mv.addObject("cityList", cityList); mv.addObject("proList", proList); mv.addObject("devList", devList); String tradeStr = buildingsDto.getTrade_area(); // String trade[] = tradeStr.split(","); // List<TradeArea> tradeList = getTradeArea(buildingsDto.getCityId());//���е� // for (TradeArea tradeArea : tradeList) { // for (String string:trade) { // if (tradeArea.getId().toString().equals(string)) { // tradeArea.setCheck(1); // } // } // } // mv.addObject("tradeList", tradeList); mv.addObject("tradeStr",tradeStr); mv.setViewName("/builld/updateBuilding_new"); return mv; } @RequestMapping("/deleteBuilding") public ModelAndView deleteBuilding(HttpSession session,HttpServletRequest request) throws Exception { String id=request.getParameter("id"); Map<String, Object> postData=new HashMap<String, Object>(); postData.put("bldId", Integer.valueOf(id)); HttpClientPostMethod.httpReqUrl(postData, "removeBuilding");; return toBuilding(session, request); } @RequestMapping("/to_addBuilding") public ModelAndView toaddBuilding(HttpSession session,HttpServletRequest request) throws Exception { ModelAndView mv = new ModelAndView(); List<CityInfo> cityList=getCities(); List<ProvincesDto> proList=getProvinces(); List<DevelopersDto> devList=getDevelopers(); CityInfo cityInfo = cityList.get(0); List<TradeArea> tradeList = getTradeArea(cityInfo.getCityId()); mv.addObject("cityList", cityList); mv.addObject("proList", proList); mv.addObject("devList", devList); mv.addObject("tradeList", tradeList); mv.setViewName("/builld/addBuilding_new"); return mv; } @RequestMapping("/addBuilding") public ModelAndView addBuilding(HttpSession session,HttpServletRequest request) throws Exception { Integer proId=Integer.valueOf(request.getParameter("proId")); Integer cityId=Integer.valueOf(request.getParameter("cityId")); Integer devId=Integer.valueOf(request.getParameter("devId")); String mark=request.getParameter("mark"); String name=request.getParameter("name"); Integer type=Integer.valueOf(request.getParameter("type")); String description=request.getParameter("description"); String telphone=request.getParameter("telphone"); String bldImg=request.getParameter("bldImg"); String video=request.getParameter("video"); String houseExplain=request.getParameter("houseExplain"); String peripheralConfig=request.getParameter("peripheralConfig"); String trade[] = request.getParameterValues("trade");// ��ȡ��Ȧ Map<String, Object> postData=new HashMap<String, Object>(); postData.put("provId", proId); postData.put("cityId", cityId); postData.put("devId", devId); postData.put("mark", mark); postData.put("name", name); postData.put("type", type); String tradeArea = ""; if (trade != null) { int tradeInt[] = new int[trade.length]; for (int i = 0; i < trade.length; i++) { tradeInt[i] = Integer.valueOf(trade[i]); if (i!=trade.length-1) { tradeArea+= trade[i]+","; }else { tradeArea+= trade[i]; } } } postData.put("trade", tradeArea); Map<String, Object> showDetailData=new HashMap<String, Object>(); showDetailData.put("telphone", telphone); showDetailData.put("description", description); showDetailData.put("bldImg", bldImg); showDetailData.put("video", video); showDetailData.put("houseExplain", houseExplain); showDetailData.put("peripheralConfig", peripheralConfig); postData.put("showDetail", showDetailData); postData.put("buildingType", Constant.BUILDING_TYPE_00); HttpClientPostMethod.httpReqUrl(postData, "addBuilding");; return toBuilding(session, request); } @RequestMapping("/updateBuilding") public ModelAndView updateBuilding(HttpSession session,HttpServletRequest request) throws Exception { Integer bldId=Integer.valueOf(request.getParameter("bldId")); Integer proId=Integer.valueOf(request.getParameter("proId")); Integer cityId=Integer.valueOf(request.getParameter("cityId")); Integer devId=Integer.valueOf(request.getParameter("devId")); String mark=request.getParameter("mark"); String name=request.getParameter("name"); Integer type=Integer.valueOf(request.getParameter("type")); String houseExplain=request.getParameter("houseExplain"); String peripheralConfig=request.getParameter("peripheralConfig"); String description=request.getParameter("description"); String telphone=request.getParameter("telphone"); String bldImg=request.getParameter("bldImg"); String video=request.getParameter("video"); String trade[] = request.getParameterValues("trade");// ��ȡ��Ȧ Map<String, Object> postData=new HashMap<String, Object>(); postData.put("bldId", bldId); postData.put("provId", proId); postData.put("cityId", cityId); postData.put("devId", devId); postData.put("mark", mark); postData.put("name", name); postData.put("type", type); String tradeArea = ""; if (trade != null) { int tradeInt[] = new int[trade.length]; for (int i = 0; i < trade.length; i++) { tradeInt[i] = Integer.valueOf(trade[i]); if (i!=trade.length-1) { tradeArea+= trade[i]+","; }else { tradeArea+= trade[i]; } } } postData.put("trade", tradeArea); Map<String, Object> showDetailData=new HashMap<String, Object>(); showDetailData.put("telphone", telphone); showDetailData.put("description", description); showDetailData.put("bldImg", bldImg); showDetailData.put("video", video); showDetailData.put("houseExplain", houseExplain); showDetailData.put("peripheralConfig", peripheralConfig); postData.put("showDetail", showDetailData); postData.put("buildingType", Constant.BUILDING_TYPE_00); HttpClientPostMethod.httpReqUrl(postData, "updateBuild"); return toBuilding(session, request); } }
JavaScript
UTF-8
676
2.953125
3
[ "MIT" ]
permissive
const fs = require('fs'); let myText = ""; fs.readFile('1.txt', (err, data) => { if(err) throw(err); myText += data; fs.readFile('2.txt', (err, data) => { if(err) throw(err); myText += data; fs.readFile('3.txt', (err, data) => { if(err) throw(err); myText += data; fs.readFile('4.txt', (err, data) => { if(err) throw(err); myText += data; fs.readFile('5.txt', (err, data) => { if(err) throw(err); myText += data; console.log(myText); }); }); }); }); });
C#
UTF-8
5,361
3.171875
3
[ "Apache-2.0" ]
permissive
using System; using System.Globalization; using Newtonsoft.Json; namespace Ofl.Serialization.Json.Newtonsoft { ////////////////////////////////////////////////// /// /// <author>Nicholas Paldino</author> /// <created>2013-09-07</created> /// <summary>Handles the conversion of a Unix /// timestamp to a <see cref="DateTimeOffset"/>.</summary> /// ////////////////////////////////////////////////// public class UnixTimestampDateTimeOffsetJsonConverter : JsonConverter { #region Constructors public UnixTimestampDateTimeOffsetJsonConverter() : this(false) { } public UnixTimestampDateTimeOffsetJsonConverter(bool returnNullOnReadException) { // Assign values. ReturnNullOnReadException = returnNullOnReadException; } #endregion #region Instance, read-only state. public bool ReturnNullOnReadException { get; } #endregion #region Overrides of JsonConverter ////////////////////////////////////////////////// /// /// <author>Nicholas Paldino</author> /// <created>2013-09-07</created> /// <summary>Reads the JSON representation of the object.</summary> /// <remarks>This is not implemented, as this is /// read-only.</remarks> /// <param name="writer">The <see cref="JsonWriter"/> to read from.</param> /// <param name="value">The value to write.</param> /// <param name="serializer">The calling serializer.</param> /// ////////////////////////////////////////////////// public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { // Validate parameters. if (writer == null) throw new ArgumentNullException(nameof(writer)); // Get the date time offset. var dateTimeOffset = (DateTimeOffset?)value; // If the value is null, then write null. if (dateTimeOffset == null) // Write null. writer.WriteNull(); else // Write the value. writer.WriteValue(dateTimeOffset.Value.ToUnixTimeSeconds()); } public override bool CanWrite => true; ////////////////////////////////////////////////// /// /// <author>Nicholas Paldino</author> /// <created>2013-09-07</created> /// <summary>Reads the JSON representation of the object.</summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> /// ////////////////////////////////////////////////// public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // Validate parameters. if (reader == null) throw new ArgumentNullException(nameof(reader)); if (objectType == null) throw new ArgumentNullException(nameof(objectType)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); // Wrap in a try/catch. try { // Read as a string or boolean. object value = reader.Value; // If the value is null, return null. if (value == null) return null; // The value is convertable to a long. var seconds = Convert.ToInt64(value, CultureInfo.InvariantCulture); // Return the date time offset. DateTimeOffset returnValue = DateTimeOffset.FromUnixTimeSeconds(seconds); // If the type is nullable, return nullable. if (objectType == typeof(DateTimeOffset?)) return (DateTimeOffset?)returnValue; // Return the return value. return returnValue; } catch { // If not swallowing a read exception, throw. if (!ReturnNullOnReadException) throw; // Return null. return null; } } public override bool CanRead => true; ////////////////////////////////////////////////// /// /// <author>Nicholas Paldino</author> /// <created>2013-09-07</created> /// <summary>Determines whether this instance can convert the specified object type.</summary> /// <param name="objectType">Type of the object.</param> /// <returns><c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.</returns> /// ////////////////////////////////////////////////// public override bool CanConvert(Type objectType) { // Validate parameters. if (objectType == null) throw new ArgumentNullException(nameof(objectType)); // Is it a timespan, or a nullable timespan? return objectType == typeof(DateTimeOffset?) || objectType == typeof(DateTimeOffset); } #endregion } }
Markdown
UTF-8
1,256
3.5625
4
[]
no_license
# FizzBuzz The good old FizzBuzz problem 😀 > If a number is a multiple of 3 then convert it to `Fizz` > > If a number is a multiple of 5 then convert it to `Buzz` > > If a number is a multiple of both 3 and 5 then convert it to `FizzBuzz` This is a tiny Gradle project that was built using TDD FizzBuzz conversion for numbers 1-200 | ------------ | <sup>1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz 101 Fizz 103 104 FizzBuzz 106 107 Fizz 109 Buzz Fizz 112 113 Fizz Buzz 116 Fizz 118 119 FizzBuzz 121 122 Fizz 124 Buzz Fizz 127 128 Fizz Buzz 131 Fizz 133 134 FizzBuzz 136 137 Fizz 139 Buzz Fizz 142 143 Fizz Buzz 146 Fizz 148 149 FizzBuzz 151 152 Fizz 154 Buzz Fizz 157 158 Fizz Buzz 161 Fizz 163 164 FizzBuzz 166 167 Fizz 169 Buzz Fizz 172 173 Fizz Buzz 176 Fizz 178 179 FizzBuzz 181 182 Fizz 184 Buzz Fizz 187 188 Fizz Buzz 191 Fizz 193 194 FizzBuzz 196 197 Fizz 199 Buzz<sup> |
Java
UTF-8
350
2.03125
2
[]
no_license
package pageUI; public class BalanceEnquiryPageUI { public static final String BALANCE_ENQUIRY_TITLE = "//p[text()='Balance Enquiry Form']"; public static final String BALANCE_ENQUIRY_BTN_SUBMIT = "//input[@name='AccSubmit']"; public static final String BALANCE_ENQUIRY_TITLE_SUCCESS = "//p[text()='Balance Details for Account %s']"; }
Markdown
UTF-8
3,941
2.625
3
[]
no_license
--- date: 2020-1-29 layout: default title: dubbo-adaptive --- # dubbo-adaptive 一个接口有多个实现类,如何在运行时动态决定,注入哪个实现类 ## dubbo 通过生成接口的代理类,然后注入代理类,代理类会通过URL参数,决定使用哪个实现类。 注入一个有多个实现类的接口,由注解adaptive的value值决定,把这个value作为一个参数,从URL里找到对应的参数值,将这个参数值作为key,从容器里找到对应实现类的实例 ```java @SPI("impl1") public interface SimpleExt { // @Adaptive example, do not specify a explicit key. @Adaptive String echo(URL url, String s); @Adaptive({"key1", "key2"}) String yell(URL url, String s); // no @Adaptive String bang(URL url, int i); } ``` ```java public void test_getAdaptiveExtension_defaultAdaptiveKey() throws Exception { { //SinpleExt$Adaptive SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); URL url = new URL("p1", "1.2.3.4", 1010, "path1", map); String echo = ext.echo(url, "haha"); assertEquals("Ext1Impl1-echo", echo); } { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getAdaptiveExtension(); Map<String, String> map = new HashMap<String, String>(); map.put("simple.ext", "impl2"); URL url = new URL("p1", "1.2.3.4", 1010, "path1", map); String echo = ext.echo(url, "haha"); assertEquals("Ext1Impl2-echo", echo); } } ``` ```java package org.apache.dubbo.common.extension.ext1; import org.apache.dubbo.common.extension.ExtensionLoader; public class SimpleExt$Adaptive implements org.apache.dubbo.common.extension.ext1.SimpleExt { public java.lang.String yell(org.apache.dubbo.common.URL arg0, java.lang.String arg1) { if (arg0 == null) throw new IllegalArgumentException("url == null"); org.apache.dubbo.common.URL url = arg0; String extName = url.getParameter("key1", url.getParameter("key2", "impl1")); if (extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.common.extension.ext1.SimpleExt) name from url (" + url.toString() + ") use keys([key1, key2])"); org.apache.dubbo.common.extension.ext1.SimpleExt extension = (org.apache.dubbo.common.extension.ext1.SimpleExt) ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.extension.ext1.SimpleExt.class).getExtension(extName); return extension.yell(arg0, arg1); } public java.lang.String echo(org.apache.dubbo.common.URL arg0, java.lang.String arg1) { if (arg0 == null) throw new IllegalArgumentException("url == null"); org.apache.dubbo.common.URL url = arg0; String extName = url.getParameter("simple.ext", "impl1"); if (extName == null) throw new IllegalStateException("Failed to get extension (org.apache.dubbo.common.extension.ext1.SimpleExt) name from url (" + url.toString() + ") use keys([simple.ext])"); org.apache.dubbo.common.extension.ext1.SimpleExt extension = (org.apache.dubbo.common.extension.ext1.SimpleExt) ExtensionLoader.getExtensionLoader(org.apache.dubbo.common.extension.ext1.SimpleExt.class).getExtension(extName); return extension.echo(arg0, arg1); } public java.lang.String bang(org.apache.dubbo.common.URL arg0, int arg1) { throw new UnsupportedOperationException("The method public abstract java.lang.String org.apache.dubbo.common.extension.ext1.SimpleExt.bang(org.apache.dubbo.common.URL,int) of interface org.apache.dubbo.common.extension.ext1.SimpleExt is not adaptive method!"); } } ``` ## spring 怎么实现dubbo这种功能? 用condition注解和配置
C++
UTF-8
1,466
3.0625
3
[]
no_license
#include <stdint.h> #include <stdio.h> char A[5][5]; char R[4][32] = {"X won", "O won", "Draw", "Game has not completed"}; const int32_t n = 4; bool Row(int32_t r, char a) { for (int32_t i = 0; i < n; i++) { if ((A[r][i] != a && A[r][i] != 'T') || A[r][i] == '.') return false; } return true; } bool Col(int32_t c, char a) { for (int32_t i = 0; i < n; i++) { if ((A[i][c] != a && A[i][c] != 'T') || A[i][c] == '.') return false; } return true; } bool Diag(char a, int32_t r, int32_t d) { for (int32_t i = 0; i < n; i++) { if ((A[r + i * d][i] != a && A[r + i * d][i] != 'T') || A[r + i * d][i] == '.') return false; } return true; } bool Four(char a) { for (int32_t i = 0; i < n; i++) { if (Row(i, a) || Col(i, a)) return true; } if (Diag(a, 0, 1) || Diag(a, 3, -1)) return true; return false; } bool Complete() { for (int32_t i = 0; i < n; i++) { for (int32_t j = 0; j < n; j++) { if (A[i][j] == '.') return false; } } return true; } int32_t Solve() { if (Four('X')) return 0; if (Four('O')) return 1; if (Complete()) return 2; return 3; } int32_t main() { int32_t cas = 0; scanf("%d", &cas); for (int32_t ic = 1; ic <= cas; ic++) { for (int32_t i = 0; i < n; i++) { scanf("%s", A[i]); } int32_t r = Solve(); printf("Case #%d: %s\n", ic, R[r]); } return 0; }
Java
UTF-8
5,478
2.3125
2
[]
no_license
package modules.controller; import modules.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import modules.dao.UserEntity; import java.io.UnsupportedEncodingException; @Controller @Scope("session") @RequestMapping(value = "/") public class UserEntityController { UserDao userDao; private int currentPosition = 0; private int length = 7; @Autowired public UserEntityController(UserDao userDao) { this.userDao = userDao; } @RequestMapping(value = "/add", method = RequestMethod.GET) public String addUserEntity() { return "adduser"; } @RequestMapping(value = "/adding", method = RequestMethod.POST) public String addingUserEntity(Model model, @RequestParam String name, @RequestParam String ageString, @RequestParam(value = "isAdmin") String isAdminString) { name = encodeToUTF8(name); int age = 0; try { age=Integer.parseInt(ageString); } catch (NumberFormatException e) { model.addAttribute("isFailInput", true); return "adduser"; } if (age < 0 || age > 130 || name.length() < 1 || name.length() > 25) { model.addAttribute("isFailInput", true); return "adduser"; } Boolean isAdmin = isAdminString.equals("yes"); UserEntity userEntity = new UserEntity(name,age,isAdmin); userDao.addUserEntity(userEntity); return "redirect:/"; } @RequestMapping(method = RequestMethod.GET) public String getUserEntityList(Model model) { model.addAttribute("userEntityList", userDao.getPage(currentPosition, length)); return "users"; } @RequestMapping(value = "/previous", method = RequestMethod.GET) public String previousPage() { if (currentPosition > 0) currentPosition -= length; return "redirect:/"; } @RequestMapping(value = "/next", method = RequestMethod.GET) public String nextPage() { if ((currentPosition+length) < userDao.getCountUserEntity()) currentPosition += length; return "redirect:/"; } @RequestMapping(value = "/change", method = RequestMethod.POST) public String changeUserEntity(Model model, @RequestParam int id) { model.addAttribute("userEntity", userDao.getUserEntity(id)); return "changeuser"; } @RequestMapping(value = "/changing", method = RequestMethod.POST) public String changingUserEntity(Model model, @RequestParam int id, @RequestParam String name, @RequestParam String ageString, @RequestParam(value = "isAdmin") String isAdminString) { name = encodeToUTF8(name); int age = 0; try { age = Integer.parseInt(ageString); } catch (NumberFormatException e) { model.addAttribute("userEntity", userDao.getUserEntity(id)); model.addAttribute("isFailInput", true); return "changeuser"; } if (age < 0 || age > 130 || name.length() < 1 || name.length() > 25) { model.addAttribute("userEntity", userDao.getUserEntity(id)); model.addAttribute("isFailInput", true); return "changeuser"; } Boolean isAdmin = isAdminString.equals("yes"); UserEntity userEntity = userDao.getUserEntity(id); userEntity.setName(name); userEntity.setAge(age); userEntity.setAdmin(isAdmin); userDao.updateUserEntity(userEntity); return "redirect:/"; } @RequestMapping(value = "/delete", method = RequestMethod.POST) public String deleteUserEntity(@RequestParam int id) { userDao.deleteUserEntity(id); return "redirect:/"; } @RequestMapping(value = "/search", method = RequestMethod.GET) public String findByName() { return "searchusers"; } @RequestMapping(value = "/search", method = RequestMethod.POST) public String getSearchUserEntityList(Model model, @RequestParam String name) { name = encodeToUTF8(name); model.addAttribute("userEntityList", userDao.searchByName(name)); return "searchusers"; } @RequestMapping(value = "/order", method = RequestMethod.POST) public String setOrder(@RequestParam String orderAlphabet) { switch (orderAlphabet) { case "ascend": userDao.setAlphabetOrder(true); break; case "descend": userDao.setAlphabetOrder(false); break; } currentPosition = 0; return "redirect:/"; } private String encodeToUTF8(String name) { try { return new String(name.getBytes("ISO8859-1"), "UTF-8"); } catch (UnsupportedEncodingException ignored) { return null; } } public int getCurrentPosition() { return currentPosition; } public void setCurrentPosition(int currentPosition) { this.currentPosition = currentPosition; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } }
C
UTF-8
375
2.921875
3
[]
no_license
#include <sys/utsname.h> #include <stdio.h> #include <stdlib.h> int main(int argc,char **argv) { struct utsname buf; if(uname(&buf)) { perror("uname"); exit(1); } printf("sysname:%s\n",buf.sysname); printf("nodename:%s\n",buf.nodename); printf("release:%s\n",buf.release); printf("version:%s\n",buf.version); printf("machine:%s\n",buf.machine); return 0; }
C
UTF-8
730
3.875
4
[]
no_license
/* File : countup.c * * By : Conner Higashino * * login: csh3173 * * team : Solution * * Date : January 30th, 2017 */ /* A program to count from 1 to 20, one per line */ #include <stdio.h> int main() { int count; count = 1; /* We initialize count = 1 as we begin counting from 1 rather than 0 */ while (count < 21) /* you may also choose to use the less-than or equal to operator. Either is * correct. */ { printf("%d\n", count); /* Print newline for readability, optional */ count = count + 1; /* You may leave this as-is. An alternative is to use count++ */ } }
PHP
UTF-8
610
3.671875
4
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Belajar PHP</title> </head> <body> <?php if(is_numeric("guru")) { echo "true"; } else { echo "false"; } echo "<br>"; if(is_numeric (123)) { echo "true"; } else { echo "false"; } echo "<br>"; echo number_format(2509663); echo "<br>"; echo rand(); echo "<br>"; echo round(3.49); echo "<br>"; echo sqrt(100); echo "<br>"; echo cos(45); echo "<br>"; echo sin(45); echo "<br>"; echo tan(45); echo "<br>"; echo pi(); echo "<br>"; ?> </body> </html>
Markdown
UTF-8
21,224
2.859375
3
[]
no_license
# Prepare project ## Introduction In this series of posts, I'm going to show how to set up the CI/CD environment using AWS and CircleCI. As a final result, we will get the pipeline that: * runs tests after each commit; * builds containers from development and master branches; * pushes them into the ECR; * redeploys development and production EC2 instances from the development and master containers respectively. This guide consists of three parts: * ➡️ **Preparation** - where I'll explain this workflow, and show how to prepare an application for it * AWS - this chart is about how to set up the AWS environment from scratch; * CircleCI - here I'll demonstrate how to automatize deployment process using [circleci.com](circleci.com) ## Prepare the application As an example let's take a simple API server with a one route written on the Elixir. I will not explain here how to create it, there is a fantastic article [there](https://dev.to/jonlunsford/elixir-building-a-small-json-endpoint-with-plug-cowboy-and-poison-1826) Or you can use [my application](https://github.com/evanilukhin/simple_plug_server), it is already configured and prepared. There I'll focus only on the specific moments that are needed to prepare the server for work in this environment. !Image with the routes results. This Elixir application I am going to deploy using mechanism of [releases](https://hexdocs.pm/mix/Mix.Tasks.Release.html). Briefly, it generates an artifact that contains the Erlang VM and its runtime, compiled source code and launch scripts. Let me make a little digress to tell about the methodology I'm trying to follow for designing microservices. I'm talking about [12 factor app manifest](https://12factor.net). It's a set of recommendations for building software-as-a-service apps that: * Use declarative formats for setup automation, to minimize time and cost for new developers joining the project; * Have a clean contract with the underlying operating system, offering maximum portability between execution environments; * Are suitable for deployment on modern cloud platforms, obviating the need for servers and systems administration; * Minimize divergence between development and production, enabling continuous deployment for maximum agility; * And can scale up without significant changes to tooling, architecture, or development practices. And [one of this principles](https://12factor.net/config) recommends us to store configurable parameters(ports, api keys, services addresses, etc.) in system environment variables. To configure our release application using env variables we should create the file `config/releases.exs` and describe these variables: ```elixir import Config config :simple_plug_server, port: System.get_env("PORT") ``` More about different config files in Elixir applications you can find [here](https://elixir-lang.org/getting-started/mix-otp/config-and-releases.html#configuring-releases) and [here](https://hexdocs.pm/mix/Mix.Tasks.Release.html#module-application-configuration) Next thing I would like to cover is the starting an application. The most common way is to use a special shell script for it that contains different preparation steps like waiting a database, initializing system variables, etc. Also it makes your Docker file more expressive. I think you will agree that `CMD ["bash", "./simple_plug_server/entrypoint.sh"]` looks better than `CMD ["bash", "cmd1", "arg1", "arg2", ";" "cmd2", "arg1", "arg2", "arg3"]`. The entrypoint script for this server is very simple: ```shell script #!/bin/sh bin/simple_plug_server start ``` This application works in the docker container so the last command `bin/simple_plug_server start` starts app without daemonizing it and writes logs right into the stdout. That is allow us to [gather logs](https://12factor.net/logs) simpler. And the last step let's create the [Dockerfile](Dockerfile) that builds result container. I prefer to use two steps builds for Elixir applications because result containers are very thin(approx. 50-70MB). ```dockerfile FROM elixir:1.10.0-alpine as build # install build dependencies RUN apk add --update git build-base # prepare build dir RUN mkdir /app WORKDIR /app # install hex + rebar RUN mix local.hex --force && \ mix local.rebar --force # set build ENV ENV MIX_ENV=prod # install mix dependencies COPY mix.exs mix.lock ./ COPY config config RUN mix deps.get RUN mix deps.compile # build project COPY lib lib RUN mix compile # build release RUN mix release # prepare release image FROM alpine:3.12 AS app RUN apk add --update bash openssl RUN mkdir /app WORKDIR /app COPY --from=build /app/_build/prod/rel/simple_plug_server ./ COPY --from=build /app/lib/simple_plug_server/entrypoint.sh ./simple_plug_server/entrypoint.sh RUN chown -R nobody: /app USER nobody ENV HOME=/app CMD ["bash", "./simple_plug_server/entrypoint.sh"] ``` Finally you can build it using `docker build .`, and run `docker run -it -p 4000:4000 -e PORT=4000 {IMAGE_ID}`. The server will be available on the `localhost:4000` and will write logs to the stdout. 🎉 ## P.S. One word about the using workflow When you developing applications in "real life" you usually(but not always), sooner or later, found that you need to: * run automatic tests; * run different checks(code coverage, security audit, code style, etc.); * test how a feature works before you deploy it to the production; * deliver results as fast as possible. I'm going to show how it can work on the workflow with two main branches: * master - has tested, production ready code(deploys on a production server) * development - based on the master and also has changes that being tested now(deploys on a development server) When you developing a new feature the process consists of the nest steps; 1) Create branch for a feature from master 2) Work 3) Push this feature 4) **Optionally** Run tests, checks, etc. for this branch 5) In case of success merge this branch to the development 6) Run everything again and redeploy the development server 7) Test it manually 8) Merge feature to the production 9) Redeploy production # Build and and push images This chapter is about setting up the AWS environment. At the end of it you will have completely deployed application. Let's start. Almost all steps will be inside the [Amazon Container Services](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) space. ## Prepare environment for containers ### Create IAM user When you log in the aws console first time you are log in under the root user. You have full access to every service and the billing management console. To secure interaction with AWS it is a good practice to create a new user inside the group that has only required permissions. A few words about managing permissions. There are two main ways to add them to users through [groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) and [roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html). The main difference is in that groups is a collection of users with same policies. Roles, in turn, can be used to delegate access not only to users but also to other services and applications, we will use both. Let's create them ! Window with button On the second step select the next policies * AmazonEC2ContainerRegistryFullAccess * AWSCodeDeployRoleForECS * AmazonEC2ContainerServiceFullAccess * AmazonECSTaskExecutionRolePolicy ! Group after creation.png Then create the role that we will give to ecs to deploy our containers to ec2 instances ! Create role window and on the second step select in policies `AmazonEC2ContainerServiceforEC2Role` ! Result More about it is showed [there](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance_IAM_role.html) And finally let's add a new user and add to the previously generated Create user that has only programmatic access because we will use it only from the circleci and terminal. Generate access keys. Save them, they will need you later ### Create ECR a place where we will store containers an from where they will be deployed. Just go to the ECL and click on the "Create repository" you will see the window where you should select the name for the repository. Other settings use by default !ECR_create.png !ECR after creation.png Great! You have repository and all required credentials to build and push images. Time to automatize it. ## Configuring Circle CI The main idea is to run tests after each commit for all branches and deploy after changes in the development and master. Before you start to configure the pipeline, you will need to prepare the application following this fantastic [getting started](https://circleci.com/docs/2.0/getting-started/#section=getting-started) page. ### Tests The most popular use case of the Circle CI that I've seen is running tests (not all developers trust to external services to deploy applications). To run them you should define [a job](https://circleci.com/docs/2.0/jobs-steps/#jobs-overview) and add it as a step to [a workflow](https://circleci.com/docs/2.0/workflows/). There is an example of `test` workflow for the `simple_plug_server` application: ```yaml version: 2.1 jobs: test: docker: - image: elixir:1.10 environment: MIX_ENV: test working_directory: ~/repo steps: - checkout - run: mix local.hex --force - run: mix local.rebar --force - run: mix deps.get - run: mix deps.compile - run: mix test - store_test_results: path: _build/test/lib/simple_plug_server workflows: version: 2 test: jobs: - test ``` It has only the one workflow `test` with the one job `test`. This job has three parts: * docker - where is defined a container inside which you will deploy test environment and run tests * working_directory - name of the folder where everything is happening * steps - the set of commands where you download code, setup dependencies and finally run tests. You can also [cache dependencies](https://circleci.com/docs/2.0/caching/) on this step. We can also improve the representing of the failed tests, for it you should add a JUnit formatter for test results (for elixir it is the hex package [JUnitFormatter](https://github.com/victorolinasc/junit-formatter)) and specify the directory containing subdirectories of JUnit XML or Cucumber JSON test metadata files. More information about it and how to add support for other languages and test frameworks look [here](https://circleci.com/docs/2.0/collect-test-data/). ### Build and push containers On the previous steps we created the ECR repository and the user that can push images, time to setup CircleCI config. For work with images we will use the official orb for ECR [circleci/aws-ecr@6.9.1](https://circleci.com/orbs/registry/orb/circleci/aws-ecr) It significantly simplifies building and pushing images, let's add the new step to our config file: ```yaml version: 2.1 orbs: aws-ecr: circleci/aws-ecr@6.9.1 aws-ecs: circleci/aws-ecs@1.2.0 jobs: test: docker: - image: elixir:1.10 environment: MIX_ENV: test working_directory: ~/repo steps: - checkout - run: mix local.hex --force - run: mix local.rebar --force - run: mix deps.get - run: mix deps.compile - run: mix test - store_test_results: path: _build/test/lib/simple_plug_server workflows: version: 2 test-and-build: jobs: - test - aws-ecr/build-and-push-image: repo: "simple_plug_server" tag: "${CIRCLE_BRANCH}_${CIRCLE_SHA1},${CIRCLE_BRANCH}_latest" requires: - test filters: branches: only: - master - development ``` Briefly about the steps of this job: * repo - the name of the repository (last part of the `815991645042.dkr.ecr.us-west-2.amazonaws.com/simple_plug_server`) * tag - tags that we apply to the built container, for the master branch it will add two tags: master_02dacfb07f7c09107e2d8da9955461f025f7f443 and master_latest * requires - there you should describe the previous necessary steps, in this example we build an image only if all tests pass * filters - describe for which branches this job should execute. There are a lot of other [filters](https://circleci.com/docs/2.0/configuration-reference/#filters-1) that you can use to customize a workflow But before you start to run this workflow you should add the next environment variables: * AWS_ACCESS_KEY_ID - access key for `circleci` that you obtained on [this step]() * AWS_SECRET_ACCESS_KEY - secret key for `circleci` that you obtained on [this step]() * AWS_REGION - region where placed your ECR instance * AWS_ECR_ACCOUNT_URL - url of the ECR(looks like 815991645042.dkr.ecr.us-west-2.amazonaws.com) !CircleCI ENV Settings example.png After successful build of the development and master branches you will see something like there: Great! You automatized process of running tests and building images in the next charter you will see how to setup servers on the AWS infrastructure and redeploy them after successfully passed tests. # Setup and update servers After all previous steps you've got the images that's stored inside the ECR and the script that automatically build them. In this part of the tutorial we will: * setup ecs clusters for development and production environments; * add deployment commands to the CircleCI scripts. Let's do it! ## Initialize ECS cluster Creating of cluster consists of three steps: 1. Create an empty cluster with a VPC 2. Define the task that will launch the selected container 3. Add service that will launch and maintain desired count of ec2 instances with the previously defined task ### Create cluster Let's start with the definition of [cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html): > An Amazon ECS cluster is a logical grouping of tasks or services. Roughly saying, clusters define scope and set of rules for the launched tasks. Creating of them is very simple: 1. Select EC2 Linux + Networking you need two clusters one for development and one for master branches 2. Select 1 On Demand t2.micro instance(or other type of ec2 instances), other configurations by default 3. For the networking section I recommend to stay the parameters by default too. It will create a new VPC with [security group](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) allowing income traffic to the 80 PORT. Yes that's all, you should create one for the development and one for the production. ### Define task 1. Select EC2 launch type compatibility 2. Choose the name for the task definition(or family like sometimes it's called) 3. For the as the task role choose the role with the `AmazonECSTaskExecutionRolePolicy` policy that we previously created 4. Select the memory limit for example 128 MB if you server is not going to handle a lot of complex requests 5. And finally add container, on this tab we are interested in the following fields * Standard -> Image - initial image for the task should be copied from the ECR looks like 845992245040.dkr.ecr.us-west-2.amazonaws.com/simple_plug_server:master_latest * Standard -> Port mappings - associate host 80 with the port which is using the our application and will be defined nex * Advanced container configuration -> ENVIRONMENT -> Environment variables - define the variable with the name `PORT` and desired value for example - 4100. This value must be used in the port mapping as the container port Great you've created the first revision of the task definition. Of course these tasks can be launched right inside cluster, but we will use services to simplify updating tasks revisions. Let's add them. ### Add service To create a service just click on the `Create` button on the `Services` and fill the form: 1. Select EC2 in the Launch type selector, because we are deploying our tasks on EC2 instances 2. In the `Task Definition` select the task and revision that you are created earlier 3. In the `Cluster` select the cluster where you want to define a service. When you are creating service from a cluster this field will be already selected 4. Service type - REPLICA 5. Number of tasks - 1 because we do not care about scaling for now. 6. Other setting set by default Great! After all manipulations you've got two EC2 instances with running applications. They are available by Public DNS or IP. Now let's go to the final part of this tutorial. ## Add deployment scripts With an official orb [aws-ecs](https://circleci.com/orbs/registry/orb/circleci/aws-ecs) you can make this very simple. First of all you should add a couple of additional environment variables We already added all necessary environment variables in the second part of this tutorial so you should only modify the circleci config. Result version of the `.circleci/config.yml` ```yaml version: 2.1 orbs: aws-ecr: circleci/aws-ecr@6.9.1 aws-ecs: circleci/aws-ecs@1.2.0 jobs: test: docker: - image: elixir:1.10 environment: MIX_ENV: test working_directory: ~/repo steps: - checkout - run: mix local.hex --force - run: mix local.rebar --force - run: mix deps.get - run: mix deps.compile - run: mix test - store_test_results: path: _build/test/lib/simple_plug_server workflows: version: 2 test-build-deploy: jobs: - test - aws-ecr/build-and-push-image: repo: "simple_plug_server" tag: "${CIRCLE_BRANCH}_${CIRCLE_SHA1},${CIRCLE_BRANCH}_latest" requires: - test filters: branches: only: - master - development - aws-ecs/deploy-service-update: name: deploy-development requires: - aws-ecr/build-and-push-image family: "simple-plug-server-development" cluster-name: "SimplePlugServer-development" service-name: "sps-dev-serv" container-image-name-updates: "container=simple-plug-server-development,tag=${CIRCLE_BRANCH}_${CIRCLE_SHA1}" filters: branches: only: - development - approve-deploy: type: approval requires: - aws-ecr/build-and-push-image filters: branches: only: - master - aws-ecs/deploy-service-update: name: deploy-production requires: - approve-deploy family: "simple-plug-server-production" cluster-name: "SimplePlugServer-production" service-name: "simple-plug-server-production" container-image-name-updates: "container=simple-plug-server-production,tag=${CIRCLE_BRANCH}_${CIRCLE_SHA1}" filters: branches: only: - master ``` In this file was added three new jobs. Two `aws-ecs/deploy-service-update` respond for the updating respective services in the clusters and `request-test-and-build` that's wait confirmation before the last step for the master branch. For different branches flows will be a little different. It can be achieved by using parameter `filters` in job definitions, where you can specify for which branches or git tags launch the jobs. development: test -> aws-ecr/build-and-push-image -> deploy-development master: test -> aws-ecr/build-and-push-image -> request-test-and-build -> deploy-production other branches: test I would like to tell about parameters for the job `aws-ecs/deploy-service-update`: * name - name is used to make jobs in a workflow more human-readable. I am sure you would agree that's `deploy-production` looks much more clearer than `aws-ecs/deploy-service-update`. * requires - used to define order of jobs execution, namely the previous job that must be finished successfully. * family - there you should write the name of the task definition([Define task](define-task)) that you used when you created the task * cluster-name - it's pretty obvious - name of the desired cluster where all magic happens * service-name - name of the service that's managing tasks inside the previously mentioned cluster * container-image-name-updates - updates the Docker image names and/or tag names of existing containers that had been defined in the previous task definition * container - the name of container that you used when you added container to the task(circled in blue on the screenshot) * tag - one of the tags that you are defined in the `aws-ecr/build-and-push-image` job, in this example it's a `${CIRCLE_BRANCH}_${CIRCLE_SHA1}` And it's all. When you push your branch with the new circleci config and start to work you will see something like that. I hope that this tutorial was helpful and was not wasted your time. If you have any question and problems feel free to ask me about it in comments. 👋
TypeScript
UTF-8
375
2.65625
3
[ "MIT" ]
permissive
import { FC } from 'react'; export interface SwitchProps { /** labels of object (left/right) */ labels?: object /** Switch size */ size?: 'small' | 'medium' | 'large'; /** color switch*/ color?: 'primary' | 'secondary'; /**function used when switch is on */ onChange?: (e: object) => void; } declare const Switch: FC<SwitchProps>; export default Switch;
JavaScript
UTF-8
2,134
4.59375
5
[]
no_license
// 1- Crie uma função construtora para Terreno, cada terreno deve ter: // largura, comprimento, area(largura x comprimento) // 2 crie métodos usando o prototype, eles devem ser: // - calcularPreco -> que vai ser a area x 1000 reais. // - mostrarInfos -> que mostrar a area e o preço do terreno. // 3 - Crie 5 instancias do terreno, usando o operador new. ex: const t1 = new Terreno(arg1, arg2) // 4 - use a função calcular preco para que todas as instancias tenham seus precos. // 5 - crie uma array vazia chamada terrenos. // 6 - insira as instancias criadas(que os precos já tenham sido calculados) na array terrrenos. // 7 - Imprima na tela o último terreno da array terrenos. // 8 - Imprima a area do terceiro item da array terrenos // 9 - Usando um loop, execute o método mostrarInfos de todos os terrenos. // 10 - Crie uma função que vai receber a array de objetos e vai ordenar a lista do mais barato para o mais caro. // 11 - Crie uma função que Imprima o mais barato // 12 - Crie uma função que Imprima o mais caro. function Terreno(largura, comprimento) { this.largura = largura this.comprimento = comprimento this.area = largura * comprimento } Terreno.prototype.calcularPreco = function() { this.preco = this.area * 1000 } Terreno.prototype.mostrarInfos = function() { console.log(`a area é ${this.area} e o preco é: ${this.preco}`) } const t1 = new Terreno(30, 20) const t2 = new Terreno(10, 50) const t3 = new Terreno(34, 200) const t4 = new Terreno(33, 19) const t5 = new Terreno(3, 2) t1.calcularPreco() t2.calcularPreco() t3.calcularPreco() t4.calcularPreco() t5.calcularPreco() const terrenos = [] terrenos.push(t1, t2, t3, t4, t5) // console.log(terrenos) // console.log(terrenos[2]) // for (const item of terrenos) { // console.log(item.mostrarInfos() // } // for (let i = 0; i < terrenos.length; i++) { // console.log(terrenos[i].mostrarInfos()) // } function ordenaTerrenos(arrTerrenos) { const ordenados = arrTerrenos.sort(function(a, b) { return a.preco - b.preco }) console.log(ordenados[0], ordenados[ordenados.length - 1]) } ordenaTerrenos(terrenos)
Markdown
UTF-8
11,054
3.65625
4
[ "MIT" ]
permissive
# Ejercicios básicos resueltos en JAVA. **1.-** Imprima en pantalla la cadena de caracteres "¡Hola, mundo!" . Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-1-) **2.-** Inicializa una variable (crea una variable y dale un valor) de tipo número real e imprimela por pantalla. Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-2-) **3.-** Inicializa dos variables (de tipo número entero) con identificadores `edad` y `altura`, e imprímerlas junto en el mensaje: Tengo `edad` años y mido `altura` cm. Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-3-) **4.-** Inicializa cuatro variables, una de cada tipo de variable básico, e imprímelas todas en un mismo mensaje indicando cual es cual. > Opcional - Cada una debe aparecer en una línea distinta (consejo usa \n). Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-4-) **5.-** Inicializa 2 variables de tipo número entero y súmalos en una tercera variable. Imprime en pantalla esta última. Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-5-) **6.-** Inicializa una variable `radio` y calcula la circunferencia guardando el resultado en la variable `circunferencia`. **Fórmula: 2 · п · radio**. A posteriori imprime en pantalla `circunferencia` Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-6-) **7.-** Inicializa una variable `radio` y calcula el área de un círculo guardando el resultado en la variable `area`. **Fórmula: п · radio · radio**. A posteriori imprime en pantalla `area` Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-7-) **8.-** Convierte una variable con identificador `latitud` de tipo **cadena de caracteres** y con valor -234.62 a tipo número real. Réstale a la variable el valor 21.34 e imprime finalmente dicha variable. Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-8-) **9.-** Inicializa una variable `celsius`, calcula su equivalente a grados Fahrenheit guardando el resultado en la variable `fahrenheit` e ímprimelo por pantalla. **Fórmula: fahrenheit = (celsius * 1.8) + 32**. Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-9-) **10.-** Inicializa una variable `fahrenheit`, calcula su equivalente a grados Celsius guardando el resultado en la variable `celsius` e ímprimelo por pantalla. **Fórmula: celsius = (fahrenheit - 32) / 1.8**. Ejercicio resuelto --------------------- [SPOILER](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicio-10-) > A continuación verás los ejercicios corregidos, son un ejemplo de como hacerlos, pues hay más de una forma. --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 1 --- --- --- # Ejercicio 1.- Imprima en pantalla la cadena de caracteres "¡Hola, mundo!" . ```java public class Ejercicio1java{ public static void main(String[] args){ System.out.println("¡Hola, mundo!"); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 2 --- --- --- # Ejercicio 2.- Inicializa una variable (crea una variable y dale un valor) de tipo número real e imprimela por pantalla. ```java public class Ejercicio2java{ public static void main(String[] args){ double numero_real = -123.3; System.out.println(numero_real); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 3 --- --- --- # Ejercicio 3.- Inicializa dos variables (de tipo número entero) con identificadores `edad` y `altura`, e imprímerlas junto en el mensaje: Tengo `edad` años y mido `altura` cm. ```java public class Ejercicio3java{ public static void main(String[] args){ int edad = 26; int altura = 183; System.out.println("Tengo " + edad + " años y mido " + altura + " cm."); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 4 --- --- --- # Ejercicio 4.- Inicializa cuatro variables, una de cada tipo de variable básico, e imprímelas todas en un mismo mensaje indicando cual es cual. > Opcional - Cada una debe aparecer en una línea distinta (consejo usa \n). ```java public class Ejercicio4java{ public static void main(String[] args){ int entero=1; double real=-10.10; String palabra="java es facil"; boolean comparativa=true; System.out.println("Este es un número entero: " + entero + ".\nEste es un numero real: " + real + ".\nEsto es una cadena de caracteres: " + palabra + ".\nEsto es un boleano: " + comparativa + "."); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 5 --- --- --- # Ejercicio 5.- Inicializa 2 variables de tipo número entero y súmalos en una tercera variable. Imprime en pantalla esta última. ```java public class Ejercicio5java{ public static void main(String[] args){ int a = 1; int b = 10; int c = a + b; System.out.println(c); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 6 --- --- --- # Ejercicio 6.- Inicializa una variable `radio` y calcula la circunferencia guardando el resultado en la variable `circunferencia`. **Fórmula: 2 · п · radio**. A posteriori imprime en pantalla `circunferencia` ```java public class Ejercicio6java{ public static void main(String[] args){ int radio = 11; double circunferencia = 2 * 3.14 * radio; System.out.println(circunferencia); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 7 --- --- --- # Ejercicio 7.- Inicializa una variable `radio` y calcula el área de un círculo guardando el resultado en la variable `area`. **Fórmula: п · radio · radio**. A posteriori imprime en pantalla `area` ```java public class Ejercicio7java{ public static void main(String[] args){ int radio = 10; double area = 3.14 * radio * radio; System.out.println(area); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 8 --- --- --- # Ejercicio 8.- Convierte una variable con identificador `latitud` de tipo **cadena de caracteres** y con valor -234.62 a tipo número real. Réstale a la variable el valor 21.34 e imprime finalmente dicha variable. ```java public class Ejercicio8java{ public static void main(String[] args){ String latitud="-234.62"; double latitud2= Double.parseDouble(latitud) -21.34; System.out.println(latitud2); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 9 --- --- --- # Ejercicio 9.- Inicializa una variable `celsius`, calcula su equivalente a grados Fahrenheit guardando el resultado en la variable `fahrenheit` e ímprimelo por pantalla. **Fórmula: fahrenheit = (celsius * 1.8) + 32**. ```java public class Ejercicio9java{ public static void main(String[] args){ double celsius = 23; double fahrenheit = (celsius * 1.8) + 32; System.out.println(fahrenheit); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java) --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ATENCION SI SIGUES VERÁS LOS EJERCICIOS RESUELTOS --- --- --- --- --- --- #### ULTIMO AVISO - Ejercicio 10 --- --- --- # Ejercicio 10.- Inicializa una variable `fahrenheit`, calcula su equivalente a grados Celsius guardando el resultado en la variable `celsius` e ímprimelo por pantalla. **Fórmula: celsius = (fahrenheit - 32) / 1.8**. ```java public class Ejercicio10java{ public static void main(String[] args){ double fahrenheit = 73.4; double celsius = (fahrenheit - 32) / 1.8; System.out.println(celsius); } } ``` Volver a la descripcion de los [Ejercicios](https://github.com/acruma/learn/blob/master/spanish/basic/Ejercicios/java.md#ejercicios-b%C3%A1sicos-resueltos-en-java)
Java
UTF-8
373
1.5
2
[ "Apache-2.0" ]
permissive
package com.achur.avalon.api; public class Constants { public static final String CLIENT_ID = "865817182348-j6qlb4275uk3ltv3lmpe77voc0062l4h.apps.googleusercontent.com"; public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; public static final String PROFILE_SCOPE = "https://www.googleapis.com/auth/userinfo.profile"; }
Markdown
UTF-8
3,585
2.515625
3
[]
no_license
# Docker 笔记 > 重新 build 时 `docker build --no-cache ...` ## 跑 8 个版本 PHP-FPM > 自己打镜像时源换来换去总有东西装不上, 干脆站在巨人肩膀上, 罢了罢了. > 用这位[同学](https://github.com/chialab/docker-php)打的[镜像](https://hub.docker.com/r/chialab/php). 跑起来 ```sh docker run -d --name php-fpm54 -p 9054:9000 -v /var/www:/var/www chialab/php:5.4-fpm docker run -d --name php-fpm55 -p 9055:9000 -v /var/www:/var/www chialab/php:5.5-fpm docker run -d --name php-fpm56 -p 9056:9000 -v /var/www:/var/www chialab/php:5.6-fpm docker run -d --name php-fpm70 -p 9070:9000 -v /var/www:/var/www chialab/php:7.0-fpm docker run -d --name php-fpm71 -p 9071:9000 -v /var/www:/var/www chialab/php:7.1-fpm docker run -d --name php-fpm72 -p 9072:9000 -v /var/www:/var/www chialab/php:7.2-fpm docker run -d --name php-fpm73 -p 9073:9000 -v /var/www:/var/www chialab/php:7.3-fpm docker run -d --name php-fpm74 -p 9074:9000 -v /var/www:/var/www chialab/php:7.4-fpm ``` 比如本地用这个域名 `docker-php.test`, 参考[这个配置](docker-php.conf), 在 nginx 里配置个站点. 然后, 向 `/var/www/docker-php` 目录加个 `index.php` 文件用看运行正常不. 就写个 ```php <?php phpinfo(); ?> ``` 访问一下看看: - http://docker-php.test/php54 - http://docker-php.test/php55 - http://docker-php.test/php56 - http://docker-php.test/php70 - http://docker-php.test/php71 - http://docker-php.test/php72 - http://docker-php.test/php73 - http://docker-php.test/php74 启动时写名字了, 不用哪个容器了这样停掉: ```sh docker stop php-fpm55 ``` ## 跑 3 个版本 MySQL 给本地建几个目录, `/var/docker-mysqls/mysql56/datadir`. 我是在用户目录创建好 `docker-mysql-datadirs` 再软链接到 `/var` 目录去. ```sh docker run -d --name mysql56 -v /var/docker-mysqls/mysql56/datadir:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root mysql:5.6 docker run -d --name mysql57 -v /var/docker-mysqls/mysql57/datadir:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root mysql:5.7 docker run -d --name mysql80 -p 3380:3306 -h 127.0.0.1 -v /var/docker-mysqls/mysql80/datadir:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root mysql:8.0 ``` ## 不要在 docker 里跑 nginx ## 跑一个 jenkins 先跑 dind ```sh docker run \ --name jenkins-docker \ --rm \ --detach \ --privileged \ --network jenkins \ --network-alias docker \ --env DOCKER_TLS_CERTDIR=/certs \ --volume jenkins-docker-certs:/certs/client \ --volume jenkins-data:/var/jenkins_home \ --publish 2376:2376 \ docker:dind ``` 再跑 jenkins ```sh docker run \ --name jenkins-blueocean \ --rm \ --detach \ --network jenkins \ --env DOCKER_HOST=tcp://docker:2376 \ --env DOCKER_CERT_PATH=/certs/client \ --env DOCKER_TLS_VERIFY=1 \ --publish 8080:8080 \ --publish 50000:50000 \ --volume jenkins-data:/var/jenkins_home \ --volume jenkins-docker-certs:/certs/client:ro \ myjenkins-blueocean:1.1 ``` 取下布署密码 ```sh docker exec jenkins-docker cat /var/jenkins_home/secrets/initialAdminPassword ``` 参考 [`jenkins.conf`](jenkins.conf) 在 nginx 里加个反向代理, 访问时就不写端口号了. ## 跑 Gitlab .zshrc 里加一行 ```sh export GITLAB_HOME=/srv/gitlab ``` ```sh docker run --detach \ --hostname gitlab.linwise.com \ --publish 443:443 --publish 80:80 --publish 22:22 \ --name gitlab \ --restart always \ --volume $GITLAB_HOME/config:/etc/gitlab \ --volume $GITLAB_HOME/logs:/var/log/gitlab \ --volume $GITLAB_HOME/data:/var/opt/gitlab \ gitlab/gitlab-ee:latest ```
Markdown
UTF-8
1,273
2.671875
3
[ "MIT", "Apache-2.0" ]
permissive
# `fugit` > `fugit` provides a comprehensive library of `Duration` and `Instant` for the handling of time in embedded systems, doing all it can at compile time. This library is a heavily inspired of `std::chrono`'s `Duration` from C++ which does all it can at compile time. ## Aims * `no_std` library with goals of user-friendliness and performance first * All methods are `const fn` that can be (i.e. non-trait methods) * Use no traits, concrete types all the way for maximum `const`-ification * Operations are supported between different bases and backing storages instead of implementing custom traits * All constants needed for comparing or changing timebase are guaranteed compile time generated * Support for both `u32` and `u64` backing storage with efficient instruction lowering on MCUs * On Cortex-M3 and up: no soft-impls pulled in for both `u32` and `u64` except when changing base on `u64` * Comparisons on `u32` and `u64` do not use division, only changing base with all constants calculated at compile time * Selection of base happens at compile time * A common problem is that run time changing of base robs us of a lot of optimization opportunities, but since there are no traits and short-hands select the correct base at compile time.
SQL
UTF-8
4,391
4.1875
4
[]
no_license
CREATE OR REPLACE TEMP TABLE unit_inspections as ( select occ.VHOST, occ.PROPERTY_ID, occ.UNIT_ID, occ.ID as OCCUPANCY_ID, occ.MOVE_IN, occ.MOVE_OUT, lead(occ.move_in) over (partition by occ.VHOST, occ.UNIT_ID order by occ.MOVE_IN asc) as NEXT_MOVE_IN, iff((insp.CREATED_AT >= occ.MOVE_OUT and insp.CREATED_AT < iff(NEXT_MOVE_IN is not null, NEXT_MOVE_IN, current_date())), insp.ID, Null) as INSPECTION_ID from property_occupancies occ left outer join PROPERTY_INSPECTIONS_INSPECTIONS as insp on insp.INSPECTABLE_TYPE = 'Unit' and occ.VHOST = insp.VHOST and occ.UNIT_ID = insp.INSPECTABLE_ID where occ.DELETED_AT is null -- Excluding deleted occupancies excludes some inspections. -- Most deleted occupancies shouldn't have an inspection. -- Better to exclude some inspections than include all occupancies. and occ.move_in is not null and occ.move_in < current_date () + interval '180 days' qualify inspection_id is not null order by occ.VHOST, occ.UNIT_ID, occ.ID asc ); CREATE OR REPLACE TEMP TABLE occupancy_inspections as ( select occ.VHOST, occ.PROPERTY_ID, occ.UNIT_ID, occ.ID as OCCUPANCY_ID, occ.MOVE_IN, occ.MOVE_OUT, lead(occ.move_in) over (partition by occ.VHOST, occ.UNIT_ID order by occ.MOVE_IN asc) as NEXT_MOVE_IN, insp.ID as INSPECTION_ID from PROPERTY_OCCUPANCIES as occ LEFT OUTER JOIN PROPERTY_INSPECTIONS_INSPECTIONS as insp on insp.INSPECTABLE_TYPE = 'Occupancy' and occ.VHOST = insp.VHOST and insp.INSPECTABLE_ID = occ.ID where occ.DELETED_AT is null -- Excluding deleted occupancies excludes some inspections. -- Most deleted occupancies shouldn't have an inspection. -- Better to exclude some inspections than include all occupancies. and occ.move_in is not null and occ.move_in < current_date () + interval '180 days' order by occ.VHOST, occ.UNIT_ID, occ.ID asc ); INSERT INTO occupancy_inspections select * from unit_inspections where unit_inspections.INSPECTION_ID is not null; select occupancy_inspections.* , inspection_engagement.ITEMS_CHECKED_ARRAY , inspection_engagement.ITEMS_FLAGGED_ARRAY , inspection_engagement.ITEMS_NOTE_ARRAY , inspection_engagement.ITEMS_IMAGES_ARRAY from occupancy_inspections left outer join ( select insp.VHOST , insp.ID as INSPECTION_ID , array_agg( case when items.CHECKED = True then 1 end ) within group ( order by insp.ID) as ITEMS_CHECKED_ARRAY , array_agg( case when items.FLAGGED = True then 1 end ) within group ( order by insp.ID) as ITEMS_FLAGGED_ARRAY , array_agg( case when len(items.NOTE) > 0 then items.NOTE end ) within group ( order by insp.ID) as ITEMS_NOTE_ARRAY , array_agg(img.ID) within group ( order by insp.ID) as ITEMS_IMAGES_ARRAY from PROPERTY_INSPECTIONS_INSPECTIONS insp join PROPERTY_INSPECTIONS_AREAS areas on insp.VHOST = areas.VHOST and insp.ID = areas.INSPECTION_ID join PROPERTY_INSPECTIONS_ITEMS items on areas.VHOST = items.VHOST and areas.ID = items.AREA_ID left outer join PROPERTY_INSPECTIONS_ITEM_IMAGE_MAPPINGS img on items.VHOST = img.VHOST and items.ID = img.ITEM_ID group by 1, 2 ) as inspection_engagement on occupancy_inspections.VHOST = inspection_engagement.VHOST and occupancy_inspections.INSPECTION_ID = inspection_engagement.INSPECTION_ID -- use this clause to limit the final data run, otherwise you'll return millions of occupancies unnecessarily WHERE MOVE_IN > current_date() - interval '3 years'
Markdown
UTF-8
2,817
2.75
3
[]
no_license
--- lastUpdated: "03/26/2020" title: "Parameters Adjusted by the Rules" description: "The default adaptive rules lua file adjusts parameters in real time based on individual rule sets for each of the ES Ps listed in Section 3 1 Receivers Managed by Adaptive Rules and takes actions based on the specific responses of receivers The following parameters are automatically adjusted in adaptive..." --- The default `adaptive_rules.lua` file adjusts parameters in real time based on individual rule sets for each of the ESPs listed in [“Receivers Managed by Adaptive Rules”](/momentum/3/3-ad/ad-adaptive-rules#ad.adaptive.rules.receivers) and takes actions based on the specific responses of receivers. The following parameters are automatically adjusted in `adaptive_rules.lua`: * `adaptive_max_outbound_connections` – The maximum number of outbound connections. This option is described in [max_outbound_connections](/momentum/3/3-reference/3-reference-conf-ref-max-outbound-connections) This parameter is adjusted by the `reduce_connections` action. * `adaptive_max_deliveries_per_connection` – The maximum number of messages to deliver before closing a connection. This option is described in [max_deliveries_per_connection](/momentum/3/3-reference/3-reference-conf-ref-max-deliveries-per-connection) This parameter is adjusted by the `reduce_deliveries` action. * `adaptive_outbound_throttle_messages` – Limit the rate at which messages are delivered. This option is described in [outbound_throttle_messages](/momentum/3/3-reference/3-reference-conf-ref-outbound-throttle-messages). If this option is not set or if is set to `0`, there is no limit on the number of messages sent. This parameter is adjusted by the `throttle "down"` action. * `retry_interval` – The interval to wait before retrying a message. This option is described in [retry_interval](/momentum/3/3-reference/3-reference-conf-ref-retry-interval). This parameter is adjusted by the `greylisted` action. ### Note You can use adaptive options to override the limits set by adaptive rules. For example, suppose that you set `adaptive_max_deliveries_per_connection` as follows: ``` domain "example.com" { adaptive_max_deliveries_per_connection = ( 20 80 ) } ``` The preceding example sets the lower boundary to `20` and the upper boundary to `80`, meaning that if the AD rules think that the value should be lower, it will be clipped to `20`, or if the rules decide that the value should be higher, it will be clipped to `80`. The `warmup` action does *not* set a configuration option; it sets the age of a binding. This is equivalent to issuing the **adaptive warmup** command from the system console. Actions are described in [“Rule Actions”](/momentum/3/3-ad/ad-adaptive-rules-actions).
Rust
UTF-8
2,223
4.40625
4
[]
no_license
// Declares imports use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); // Generates a number between 1 and 101 (the second parameter is // non-inclusive) let secret_number = rand::thread_rng().gen_range(1, 101); // Creates an infinite loop loop { println!("Please input your guess."); // Creates a new mutable variable of type `String` let mut guess = String::new(); // Reads user input and tries to store it in the previously defined // variable `guess`, if the action fails it panics and shows an error // message // Returns a `Result`, which is an enumeration that can contain a value // or an error io::stdin() .read_line(&mut guess) .expect("Failed to read line"); // Removes any trailing white space character // Tries to parse the `String` to get a `u32` integer. // The parse method returns an enum that can contain a value or an error // The match expression is composed by branches, each branch represents // a pattern that will only execute if the result fits one of the // patterns // Changes the variable type from `String` to `u32` and makes it // immutable, this is called `shadowing`. This technique is usually // used when converting values let guess: u32 = match guess.trim().parse() { // Extracts the value from `Result` if the parsing was successful Ok(num) => num, // Skips the current iteration if we got an error Err(_) => continue, }; println!("You guessed: {}", guess); // The `cmp` method compares two values and can be invoked on anything // that can be compared // Again we use a match expression to evaluate `cmp` results and // determine the current result of the game match guess.cmp(&secret_number) { Ordering::Less => println!("Too small"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
Markdown
UTF-8
2,978
3.5625
4
[ "MIT" ]
permissive
--- layout: post title: "[프로그래머스] 힙(Heap) - Lv.2 - 더 맵게 (Python) / heapq" author: Yurim Koo categories: - Algorithm tags: - 알고리즘 - 프로그래머스 - Python - Algorithm - Heap - Heap Sort - Python heapq - Heapq - Heap Queue - Priority Queue - 우선순위 큐 - 파이썬 큐 - 파이썬 힙 - 파이썬 힙 큐 - 파이썬 힙 정렬 comments: true --- ## 문제 매운 것을 좋아하는 Leo는 모든 음식의 스코빌 지수를 K 이상으로 만들고 싶습니다. 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 Leo는 스코빌 지수가 가장 낮은 두 개의 음식을 아래와 같이 특별한 방법으로 섞어 새로운 음식을 만듭니다. ```섞은 음식의 스코빌 지수 = 가장 맵지 않은 음식의 스코빌 지수 + (두 번째로 맵지 않은 음식의 스코빌 지수 * 2)``` Leo는 모든 음식의 스코빌 지수가 K 이상이 될 때까지 반복하여 섞습니다. Leo가 가진 음식의 스코빌 지수를 담은 배열 scoville과 원하는 스코빌 지수 K가 주어질 때, 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 섞어야 하는 최소 횟수를 return 하도록 solution 함수를 작성해주세요. #### 제한 사항 - scoville의 길이는 1 이상 1,000,000 이하입니다. - K는 0 이상 1,000,000,000 이하입니다. - scoville의 원소는 각각 0 이상 1,000,000 이하입니다. - 모든 음식의 스코빌 지수를 K 이상으로 만들 수 없는 경우에는 -1을 return 합니다. #### 입출력 예 |scoville|K|return| |:--:|:--:|:--:| |[1, 2, 3, 9, 10, 12]|7|2| 입출력 예 설명 1. 스코빌 지수가 1인 음식과 2인 음식을 섞으면 음식의 스코빌 지수가 아래와 같이 됩니다. 새로운 음식의 스코빌 지수 = 1 + (2 * 2) = 5 가진 음식의 스코빌 지수 = [5, 3, 9, 10, 12] 2. 스코빌 지수가 3인 음식과 5인 음식을 섞으면 음식의 스코빌 지수가 아래와 같이 됩니다. 새로운 음식의 스코빌 지수 = 3 + (5 * 2) = 13 가진 음식의 스코빌 지수 = [13, 9, 10, 12] 모든 음식의 스코빌 지수가 7 이상이 되었고 이때 섞은 횟수는 2회입니다. <br> ## 나의 풀이 <pre><code>import heapq def solution(scoville, k): heapq.heapify(scoville) i = 0 while scoville[0] < k: if len(scoville) > 1: heapq.heappush(scoville, heapq.heappop(scoville) + (heapq.heappop(scoville) * 2)) i += 1 else: return -1 return i </code></pre> Python의 내장 모듈인 `heapq`를 이용해 풀었습니다. `heapq`를 이용하지 않으니 효율성 테스트를 통과하지 못하더라구요! `heapq`는 힙 정렬(Heap Sort)을 Python에서 쉽게 사용할 수 있는 함수들로 구성되어 있습니다. 힙 정렬과 heapq 모듈에 대해 포스팅 예정이니 기다려주세요 ;)
C++
UTF-8
800
2.53125
3
[]
no_license
#include<cstdio> #include<algorithm> #include<vector> using namespace std; vector<int> qq; int lower(int x){ for(int i=0;i<qq.size();i++){ if(qq[i]>=x)return i; } return qq.size()-1; } int main(){ freopen("ans.txt","r",stdin); int n,q; int kase=0; while(scanf("%d%d",&n,&q)!=EOF){ if(n==0||q==0)break; qq.clear(); printf("CASE# %d:\n",++kase); for(int i=0;i<n;i++){ int a; scanf("%d",&a); qq.push_back(a); } sort(qq.begin(),qq.end()); while(q--){ int ans; scanf("%d",&ans); int p=lower(ans); if(qq[p]==ans)printf("%d found at %d\n",ans,p+1); else printf("%d not found\n",ans); } } return 0; }
SQL
UTF-8
4,405
4.03125
4
[]
no_license
-- Comments in SQL Start with dash-dash -- -- Yes, I copied this verbatim after ensuring that I was, in fact, in the right terminal, running the database, had correctly accessed SQL, and that the database had correctly seeded. It is a copy and paste for the sake of testing. But it worked, so I am moving on. -- 1.) Add a product to the table with the name of "chair", price of 44.00, and can_be_returned of false. INSERT INTO products (name, price, can_be_returned) VALUES ('chair', 44.00, 'f'); -- Copy and pasting their question as-is, and then my answer below. -- 2.) Add a product to the table with the name of “stool”, price of 25.99, and can_be_returned of true. INSERT INTO products (name, price, can_Be_returned) VALUES ('stool', 25.99, 't'); -- 3.) Add a product to the table with the name of “table”, price of 124.00, and can_be_returned of false. INSERT INTO products (name, price, can_Be_returned) VALUES ('table', 124.00, 'f'); -- 4.) Display all of the rows and columns in the table. SELECT * FROM products; id | name | price | can_be_returned ----+-------+-------+----------------- 1 | chair | 44 | f 2 | stool | 25.99 | t 3 | table | 124 | f -- 5.) Display all of the names of the products. -- Why use DISTINCT? Because on SQLZOO, where half of the exercises took place, it wouldn't work without using DISTINCT. Oddly enough, using it works just fine, so I assume it's a matter of specificity. SELECT DISTINCT(name) FROM products; name ------- chair stool table -- 6.) Display all of the names and prices of the products. SELECT name, price FROM products; name | price -------+------- chair | 44 stool | 25.99 table | 124 -- 7.) Add a new product - make up whatever you would like! INSERT INTO products VALUES(4, 'Manual on SQL', 0.01, 't'); id | name | price | can_be_returned ----+---------------+-------+----------------- 1 | chair | 44 | f 2 | stool | 25.99 | t 3 | table | 124 | f 4 | Manual on SQL | 0.01 | t -- 8.) Display only the products that can_be_returned. SELECT * FROM products WHERE can_be_returned='t'; id | name | price | can_be_returned ----+---------------+-------+----------------- 2 | stool | 25.99 | t 4 | Manual on SQL | 0.01 | t -- 9.) Display only the products that have a price less than 44.00. SELECT * FROM products WHERE price <= 44.00; id | name | price | can_be_returned ----+---------------+-------+----------------- 1 | chair | 44 | f 2 | stool | 25.99 | t 4 | Manual on SQL | 0.01 | t -- 10.) Display only the products that have a price in between 22.50 and 99.99. SELECT * FROM products WHERE price BETWEEN 22.50 AND 99.99; id | name | price | can_be_returned ----+-------+-------+----------------- 1 | chair | 44 | f 2 | stool | 25.99 | t -- 11.) There’s a sale going on: Everything is $20 off! Update the database accordingly. UPDATE products SET price = 20.01 WHERE id = 4; id | name | price | can_be_returned ----+---------------+-------+----------------- 1 | chair | 44 | f 2 | stool | 25.99 | t 3 | table | 124 | f 4 | Manual on SQL | 20.01 | t UPDATE products SET price = price - 20; id | name | price | can_be_returned ----+---------------+----------------------+----------------- 1 | chair | 24 | f 2 | stool | 5.989999999999998 | t 3 | table | 104 | f 4 | Manual on SQL | 0.010000000000001563 | t -- Odd decimal usage, but that's the solution's method too. -- 12.) Because of the sale, everything that costs less than $25 has sold out. Remove all products whose price meets this criteria. DELETE FROM products WHERE price < 25; id | name | price | can_be_returned ----+-------+-------+----------------- 3 | table | 104 | f -- 13.) And now the sale is over. For the remaining products, increase their price by $20. UPDATE products SET price = price + 20; id | name | price | can_be_returned ----+-------+-------+----------------- 3 | table | 124 | f -- 14.) There is a new company policy: everything is returnable. Update the database accordingly. UPDATE products SET can_be_returned = 't'; id | name | price | can_be_returned ----+-------+-------+----------------- 3 | table | 124 | t
Java
UTF-8
5,816
2.953125
3
[]
no_license
package cryptography2; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Random; public class C2 { int[] stream; int[][] keystream; int[] key; int numRound; int blockSize; int[] iv = null; BlockCipher blockCipher; public C2(int[] key) { this.key = key; } public void setBlockCipher(BlockCipher blockCipher) { this.blockCipher = blockCipher; this.numRound = blockCipher.getNumRound(); this.blockSize = blockCipher.getBlockSize(); this.makeKeyStream(); this.blockCipher.setKeystream(keystream); this.blockCipher.setKey(key); } public void setIV(int[] iv) { this.iv = iv; } public void genRandomIV() { this.iv = new int[blockSize]; Random randGen = new Random(); for (int j = 0; j < blockSize; j++) iv[j] = randGen.nextInt(255); } private void makeKeyStream() { keystream = new int[numRound][key.length]; int[] tmpKey = key; for (int i = 0; i < numRound; i++) { keystream[i] = Key.encrypt(tmpKey, i + 1); tmpKey = keystream[i]; } } protected void readFromFile(String filename) throws IOException { /* Read from a file and save into a stream */ File file = new File(filename); int filesize = (int) file.length(); this.stream = new int[filesize]; FileInputStream ip = new FileInputStream(filename); for (int i = 0; i < filesize; i++) { this.stream[i] = ip.read(); } } public void encrypt(String inputFilename, String outfilename) throws IOException { /* Encrypt a stream of int in CBC mode */ Random randGen = new Random(); FileOutputStream fw = null; /* Create a new encryption block to encrypt the stream of byte */ blockCipher = new BlockEncryption(); this.setBlockCipher(blockCipher); this.readFromFile(inputFilename); fw = new FileOutputStream(outfilename); /* Generate the initial value. */ int[] iv_ECB = new int[blockSize]; if (this.iv == null) this.genRandomIV(); iv_ECB = blockCipher.work(iv); /* Encrypt the iv in ECB mode and save it first in the file */ for (int j = 0; j < blockSize; j++) fw.write(iv_ECB[j]); int[] prevMsg = iv; int i = 0; while (i < stream.length) { int low = i; int high = i + blockSize; if (high >= stream.length) high = stream.length; int[] msg = new int[blockSize]; /* Get the plain text block */ for (int j = low; j < high; j++) msg[j % blockSize] = stream[j]; /* Do padding */ if ((high - low) % blockSize != 0) for (int j = high % blockSize; j < blockSize; j++) msg[j] = 0xff; /* XOR the current block with plain text, then encrypt */ prevMsg = blockCipher.work(MatrixOps.add(msg, prevMsg)); for (int j = 0; j < blockSize; j++) fw.write(prevMsg[j]); i = high; } fw.close(); } /* Decrypt a stream of int in CBC mode */ public void decrypt(String inputFilename, String outfilename) throws FileNotFoundException, IOException { this.readFromFile(inputFilename); blockCipher = new BlockDecryption(); this.setBlockCipher(blockCipher); FileOutputStream fw = new FileOutputStream(outfilename); int[] msg = new int[blockSize]; int[] tmpMsg = new int[blockSize]; int[] iv = new int[blockSize]; /* Read the first 4 bytes for initial value */ for (int i = 0; i < blockSize; i++) iv[i] = stream[i]; /* Decipher the initial value, which was saved first in the file */ iv = blockCipher.work(iv); int[] prevMsg = iv; int i = blockSize; /* While reaching the beginning of the file (as we read backward) */ while (i < stream.length) { /* Get from the second cipher text block */ for (int j = 0; j < blockSize; j++) msg[j] = stream[i + j]; /* Decrypt and xor with the previous block */ tmpMsg = blockCipher.work(msg); /* This should be the plain text */ tmpMsg = MatrixOps.add(prevMsg, tmpMsg); for (int j = 0; j < blockSize && tmpMsg[j] != 0xff; j++) fw.write(tmpMsg[j]); /* Copy the plain text for the next iteration */ copy(prevMsg, msg, 0); i += blockSize; } fw.close(); } public static void main(String[] argv) throws IOException { if (argv.length != 3) bailOut(); /* Init GF28 arithmetic data */ GF28.init("table.txt"); int[] key = readKeyFile(argv[2]); /* Create a new blackbox */ C2 blackBox = new C2(key); String infilename = argv[1]; String outfilename; /* Check for the action */ if (argv[0].toUpperCase().compareTo("E") == 0) { outfilename = "encrypted_" + infilename; blackBox.encrypt(infilename, outfilename); } else if (argv[0].toUpperCase().compareTo("D") == 0) { outfilename = "decrypted_" + infilename; blackBox.decrypt(infilename, outfilename); } else bailOut(); } private static int[] readKeyFile(String filename) throws IOException { /* Read the key */ int[] inputkey; BufferedReader br = new BufferedReader(new FileReader(filename)); String[] inputKeyStr = br.readLine().split(" "); inputkey = new int[inputKeyStr.length]; for (int i = 0; i < inputKeyStr.length; i++) inputkey[i] = Integer.parseInt(inputKeyStr[i]); return inputkey; } private void copy(int[] a, int[] b, int start) { /* Copy ints from b into a, index in a from start */ for (int i = 0; i < a.length; i++) a[i + start] = b[i]; } public static void bailOut() { System.out .println("Usage: C2 <action(D|E)> <data_file_name> <key_file>"); System.out .println("Key file should contains 4 DECIMAL number in (0-255), space delimited"); System.exit(1); } }
Python
UTF-8
1,683
3.078125
3
[]
no_license
import socket import pickle from neuralNetwork import NeuralNetwork from layer import Layer from activation_layer import ActivationLayer from activations import relu, relu_derivative, sigmoid, sigmoid_derivative import numpy as np class Server: def __init__(self): self.server_socket = None self.createServer() def createServer(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind((socket.gethostname(), 1249)) self.server_socket.listen(5) def predict(self, data): nn = NeuralNetwork() l1 = Layer(56, 54) l2 = Layer(54, 25) nn.add(l1) nn.add(ActivationLayer(relu, relu_derivative)) nn.add(l2) nn.add(ActivationLayer(sigmoid, sigmoid_derivative)) l1.weights = np.load('weights1.npy') l2.weights = np.load('weights2.npy') l1.bias = np.load('bias1.npy') l2.bias = np.load('bias2.npy') out = nn.predict(data) pred = np.argmax(out) return pred def receive_data(self): while True: print('Waiting for connection...') c, addr = self.server_socket.accept() print(f'Got connection from {addr}') while True: data = c.recv(4096) print('Received pixel values!') d = pickle.loads(data) if data: pred = self.predict(d) print(f'Sending prediction: {pred}') c.send(pred) else: break #Main s = Server() s.receive_data()
TypeScript
UTF-8
1,080
2.890625
3
[]
no_license
import { Request, Response } from 'express'; import { get } from 'lodash'; /** * Utiltiy object to standardise the response * @type {{generateMeta: function, success: function, error: function}} */ export const responder = { generateMeta: (req: Request) => ({ url: get(req, 'url'), method: get(req, 'method'), timestamp: new Date().toString(), requestId: req.header('x-request-id'), ip: get(req, 'connection.remoteAddress') }), success: function ( { status = 200, message = 'OK', data = '' }: { status: number; message: string; data: any }, req: Request, res: Response ) { const meta = this.generateMeta(req); return res.status(status).json({ meta, message, data }); }, error: function (error: Error, req: Request, res: Response) { const meta = this.generateMeta(req); const status = get(error, 'status') || 500; return res.status(status).json({ meta, message: get(error, 'message') || 'oops, something went wrong!', errors: get(error, 'errors') || [] }); } };
Java
UTF-8
16,386
1.828125
2
[]
no_license
package hzyj.guangda.student.activity.order; import org.apache.http.Header; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.common.library.llj.adapterhelp.BaseAdapterHelper; import com.common.library.llj.adapterhelp.QuickAdapter; import com.common.library.llj.base.BaseFragment; import com.common.library.llj.base.BaseReponse; import com.common.library.llj.utils.AsyncHttpClientUtil; import com.common.library.llj.utils.TimeUitlLj; import com.loopj.android.http.RequestParams; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import hzyj.guangda.student.GuangdaApplication; import hzyj.guangda.student.R; import hzyj.guangda.student.common.Setting; import hzyj.guangda.student.response.GetUnCompleteOrderResponse; import hzyj.guangda.student.response.GetUnCompleteOrderResponse.Order; import hzyj.guangda.student.util.MySubResponseHandler; import hzyj.guangda.student.view.CancelComplaint; import hzyj.guangda.student.view.CancleOrderDialog; import hzyj.guangda.student.view.CoachSrueDialog; import in.srain.cube.views.ptr.PtrClassicFrameLayout; import in.srain.cube.views.ptr.PtrDefaultHandler; import in.srain.cube.views.ptr.PtrFrameLayout; import in.srain.cube.views.ptr.PtrHandler; public class ComplaintFragment extends BaseFragment{ private PtrClassicFrameLayout mPtrClassicFrameLayout; private ListView mListView; private int mPage; private OrderListAdapter mOrderListAdapter; private RelativeLayout mNoDataRl; private CancelComplaint cancelDialog; private MyOrderListActivity mActivity; @Override protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.wait_comment_fragment, container, false); mPtrClassicFrameLayout = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_frame); mPtrClassicFrameLayout.setDurationToCloseHeader(800); mListView = (ListView) view.findViewById(R.id.lv_order); mNoDataRl = (RelativeLayout) view.findViewById(R.id.rl_no_date); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = (MyOrderListActivity) activity; } @Override protected void addListeners(View view, Bundle savedInstanceState) { mPtrClassicFrameLayout.setPtrHandler(new PtrHandler() { @Override public void onRefreshBegin(PtrFrameLayout frame) { mPage = 0; doLoadMoreData(); } @Override public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) { return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header); } }); } public void doLoadMoreData() { if (isVisible()) AsyncHttpClientUtil.get().post(getActivity(), Setting.SORDER_URL, GetUnCompleteOrderResponse.class, new MySubResponseHandler<GetUnCompleteOrderResponse>() { @Override public RequestParams setParams(RequestParams requestParams) { requestParams.add("action", "GETCOMPLAINTORDER"); requestParams.add("studentid", GuangdaApplication.mUserInfo.getStudentid()); requestParams.add("pagenum", mPage + ""); return requestParams; } @Override public void onFinish() { mPtrClassicFrameLayout.refreshComplete(); } @Override public void onSuccess(int statusCode, Header[] headers, GetUnCompleteOrderResponse baseReponse) { initAllData(baseReponse); } }); } @Override public void onStop() { super.onStop(); mListView.smoothScrollToPosition(0); } private void initAllData(GetUnCompleteOrderResponse baseReponse) { if (baseReponse.getOrderlist() != null && baseReponse.getOrderlist().size() != 0) { mNoDataRl.setVisibility(View.INVISIBLE); mListView.setVisibility(View.VISIBLE); if (mPage == 0) { mOrderListAdapter.clear(); } if (baseReponse.getHasmore() == 0) { mOrderListAdapter.showIndeterminateProgress(false); } else if (baseReponse.getHasmore() == 1 && baseReponse.getOrderlist() != null) { mOrderListAdapter.showIndeterminateProgress(true); mPage++; } mOrderListAdapter.addAll(baseReponse.getOrderlist()); } else { mNoDataRl.setVisibility(View.VISIBLE); mListView.setVisibility(View.INVISIBLE); } } @Override protected void initViews(View view, Bundle savedInstanceState) { mOrderListAdapter = new OrderListAdapter(getActivity(), R.layout.order_list_item); onLoadMoreData(mListView, mOrderListAdapter); mListView.setAdapter(mOrderListAdapter); } @Override public void onLasyLoad() { super.onLasyLoad(); mPtrClassicFrameLayout.postDelayed(new Runnable() { @Override public void run() { mPtrClassicFrameLayout.autoRefresh(true); } }, 150); } @Override protected void requestOnCreate() { } private class OrderListAdapter extends QuickAdapter<Order> { public OrderListAdapter(Context context, int layoutResId) { super(context, layoutResId); } @Override protected void convert(BaseAdapterHelper helper, View convertView, final Order item, int position) { if (item != null) { helper.setText(R.id.tv_address, item.getDetail()); final TextView name = helper.getView(R.id.tv_coach_name); if (item.getCuserinfo() != null) { name.setText(item.getCuserinfo().getRealname()); } TextView status = helper.getView(R.id.tv_status); final TextView date = helper.getView(R.id.tv_Y_M_R); final TextView time = helper.getView(R.id.tv_course_time); final TextView all_money = helper.getView(R.id.tv_all_money); final TextView carlicense=helper.getView(R.id.tv_carlicense); TextView tv_complaint = helper.getView(R.id.tv_complaint); // TextView tv_complaint_more = helper.getView(R.id.tv_complaint_more); TextView tv_cancel_complaint = helper.getView(R.id.tv_cancle_complaint); // TextView tv_get_on = helper.getView(R.id.tv_get_on); // TextView tv_get_off = helper.getView(R.id.tv_get_off); TextView tv_cancel_order = helper.getView(R.id.tv_cancel_order); TextView tv_comment = helper.getView(R.id.tv_comment); //TextView tv_course=helper.getView(R.id.tv_course); //TextView tv_continue = helper.getView(R.id.tv_continue); // // tv_continue.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // ActivityOptionsCompat options = ActivityOptionsCompat.makeCustomAnimation(mBaseFragmentActivity, R.anim.bottom_to_center, R.anim.no_fade); // Intent intent = new Intent(mBaseFragmentActivity, SubjectReserveActivity.class); // intent.putExtra("mCoachId", item.getCoachid()); // intent.putExtra("mAddress", item.getDetail()); // if (item.getCuserinfo() != null) { // intent.putExtra("mScore", item.getCuserinfo().getScore()); // intent.putExtra("mName", item.getCuserinfo().getRealname()); // } // ActivityCompat.startActivity((Activity) mBaseFragmentActivity, intent, options.toBundle()); // } // }); // 状态 switch (item.getHours()) { case 0: status.setText("此车单即将开始"); status.setTextColor(Color.parseColor("#f7645c")); break; case -1: status.setText("正在学车"); status.setTextColor(Color.parseColor("#50cb8c")); break; case -2: status.setText("学车完成"); status.setTextColor(Color.parseColor("#f7645c")); break; case -3: status.setText("待确认上车"); status.setTextColor(Color.parseColor("#f7645c")); break; case -4: status.setText("待确认下车"); status.setTextColor(Color.parseColor("#f7645c")); break; case -5: status.setText("投诉处理中"); status.setTextColor(Color.parseColor("#FF4500")); break; case -6: status.setText("客服协调中"); status.setTextColor(Color.parseColor("#FF4500")); break; default: status.setText("离学车还有" + TimeUitlLj.awayFromFuture(item.getHours() * 60 * 1000)); status.setTextColor(Color.parseColor("#b8b8b8")); break; } if(item.getCarlicense()!=null){ carlicense.setText("("+item.getCarlicense()+")"); }else{ carlicense.setText(""); } //tv_course.setText(item.getSubjectname()); // date long dateStartLong = TimeUitlLj.stringToMilliseconds(2, item.getStart_time()); date.setText(TimeUitlLj.millisecondsToString(9, dateStartLong)); // time long dateEndLong = TimeUitlLj.stringToMilliseconds(2, item.getEnd_time()); time.setText(TimeUitlLj.millisecondsToString(10, dateStartLong) + "-" + TimeUitlLj.millisecondsToString(10, dateEndLong)); // 合计 all_money.setText(item.getTotal() + "元"); // 是否可以投诉 if (item.getCan_complaint() == 0) { tv_complaint.setVisibility(View.GONE); } else if (item.getCan_complaint() == 1) { tv_complaint.setVisibility(View.VISIBLE); tv_complaint.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mBaseFragmentActivity, ComplaintActivity.class); intent.putExtra("mOrderid", item.getOrderid()); intent.putExtra("mCreatTime", item.getCreat_time()); intent.putExtra("mOrderCoach", name.getText().toString().trim()); intent.putExtra("mOrderTime", date.getText().toString().trim() + " " + time.getText().toString().trim()); intent.putExtra("mOrderAddress", item.getDetail()); intent.putExtra("mAllMoney", all_money.getText().toString().trim()); startActivity(intent); } }); } // 是否需要取消投诉 if (item.getNeed_uncomplaint() == 0) { //tv_complaint_more.setVisibility(View.GONE); tv_cancel_complaint.setVisibility(View.GONE); } else if (item.getNeed_uncomplaint() == 1) { //tv_complaint_more.setVisibility(View.VISIBLE); tv_cancel_complaint.setVisibility(View.VISIBLE); tv_complaint.setVisibility(View.GONE); //tv_complaint_more.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // Intent intent = new Intent(mBaseFragmentActivity, ComplaintActivity.class); // intent.putExtra("mOrderid", item.getOrderid()); // intent.putExtra("mCreatTime", item.getCreat_time()); // intent.putExtra("mOrderCoach", name.getText().toString().trim()); // intent.putExtra("mOrderTime", date.getText().toString().trim() + " " + time.getText().toString().trim()); // intent.putExtra("mOrderAddress", item.getDetail()); // intent.putExtra("mAllMoney", all_money.getText().toString().trim()); // startActivity(intent); // } // }); tv_cancel_complaint.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { cancelDialog=new CancelComplaint(mActivity,item.getOrderid(),GuangdaApplication.mUserInfo.getStudentid(),mPtrClassicFrameLayout); cancelDialog.show(); // AsyncHttpClientUtil.get().post(getActivity(), Setting.SORDER_URL, BaseReponse.class, new MySubResponseHandler<BaseReponse>() { // @Override // public void onStart() { // super.onStart(); // } // // @Override // public RequestParams setParams(RequestParams requestParams) { // requestParams.add("action", "CancelComplaint"); // requestParams.add("studentid", GuangdaApplication.mUserInfo.getStudentid()); // requestParams.add("orderid", item.getOrderid()); // return requestParams; // } // // @Override // public void onFinish() { // if (mBaseFragmentActivity.mLoadingDialog != null) { // mBaseFragmentActivity.mLoadingDialog.dismiss(); // } // } // // @Override // public void onSuccess(int statusCode, Header[] headers, BaseReponse baseReponse) { // mPtrClassicFrameLayout.autoRefresh(true); // } // }); } }); } // 订单是否可以取消 if (item.getCan_cancel() == 0) { tv_cancel_order.setVisibility(View.GONE); } else if (item.getCan_cancel() == 1) { tv_cancel_order.setVisibility(View.VISIBLE); } // 订单是否可以确认上车 // if (item.getCan_up() == 0) { // tv_get_on.setVisibility(View.GONE); // } else if (item.getCan_up() == 1) { // tv_get_on.setVisibility(View.VISIBLE); // tv_get_on.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // initLocationClient(item, "ConfirmOn"); // } // }); // } // 订单是否可以确认下车 // if (item.getCan_down() == 0) { // tv_get_off.setVisibility(View.GONE); // } else if (item.getCan_down() == 1) { // tv_get_off.setVisibility(View.VISIBLE); // tv_get_off.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View v) { // initLocationClient(item, "ConfirmDown"); // } // }); // } // 订单是否可以评论 if (item.getCan_comment() == 0) { tv_comment.setVisibility(View.GONE); } else if (item.getCan_comment() == 1) { tv_comment.setVisibility(View.VISIBLE); tv_comment.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mBaseFragmentActivity, CommentActivity.class); intent.putExtra("mOrderid", item.getOrderid()); intent.putExtra("mCreatTime", item.getCreat_time()); intent.putExtra("mOrderCoach", name.getText().toString().trim()); intent.putExtra("mOrderTime", date.getText().toString().trim() + " " + time.getText().toString().trim()); intent.putExtra("mOrderAddress", item.getDetail()); intent.putExtra("mAllMoney", all_money.getText().toString().trim()); startActivity(intent); } }); } convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mBaseFragmentActivity, OrderDetailActivity.class); intent.putExtra("mOrderid", item.getOrderid()); intent.putExtra("mOrderTime", date.getText().toString().trim() + " " + time.getText().toString().trim()); intent.putExtra("mAllMoney", all_money.getText().toString().trim()); intent.putExtra("flag","ComplaintFragment"); startActivity(intent); } }); } } } /** * 开启定位获取经纬度,并发起请求 * * @param item * 实体对象 * @param action */ private void initLocationClient(final Order item, final String action) { LocationClient mLocClient = new LocationClient(mBaseFragmentActivity); LocationClientOption option = new LocationClientOption(); // option.setOpenGps(true);// 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 mLocClient.setLocOption(option); mLocClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(final BDLocation arg0) { AsyncHttpClientUtil.get().post(getActivity(), Setting.SORDER_URL, BaseReponse.class, new MySubResponseHandler<BaseReponse>() { @Override public void onStart() { super.onStart(); mBaseFragmentActivity.mLoadingDialog.show(); } @Override public RequestParams setParams(RequestParams requestParams) { requestParams.add("action", action); requestParams.add("studentid", GuangdaApplication.mUserInfo.getStudentid()); requestParams.add("orderid", item.getOrderid()); requestParams.add("lat", arg0.getLatitude() + ""); requestParams.add("lon", arg0.getLongitude() + ""); requestParams.add("detail", arg0.getAddrStr()); return requestParams; } @Override public void onFinish() { mBaseFragmentActivity.mLoadingDialog.dismiss(); } @Override public void onSuccess(int statusCode, Header[] headers, BaseReponse baseReponse) { mPtrClassicFrameLayout.autoRefresh(); } }); } }); mLocClient.start(); } }
C#
UTF-8
1,126
3.625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lists { class Lists { static void Main(string[] args) { //8 2 2 8 2 2 3 7 var number = Console.ReadLine() .Split(' ') .Select(int.Parse) .ToList(); if (number.Count > 0) { number.Sort(); var previos = number[0]; var count = 1; for (int i =1; i < number.Count; i++) { var currentNumber = number[i]; if (currentNumber == previos) { count++; } else { Console.WriteLine("{0}->{1}", previos,count); count = 1; } previos = currentNumber; } Console.WriteLine("{0}->{1}", previos, count); } } } }
Java
UTF-8
969
2.171875
2
[]
no_license
package com.soft.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; import com.soft.dao.StudentDB; import com.soft.dao.UserDB; public class PasswordAction extends ActionSupport implements ServletRequestAware{ private HttpServletRequest request; private HttpSession session; @Override public void setServletRequest(HttpServletRequest arg0) { // TODO Auto-generated method stub this.request=arg0; } public String excute(){ session = ServletActionContext.getRequest().getSession(); UserDB db=new UserDB(); String tell=(String)session.getAttribute("tell"); String password=request.getParameter("password"); //System.out.print(tell); //System.out.print("bbb"); boolean tt=db.UpdatePW(tell,password); return "success"; } }
Markdown
UTF-8
592
2.640625
3
[]
no_license
# __Owl Find__ ![img](/public/OwlFindSS2.png) What word are you looking for? Owl Find will help look up words you may not know using the Owlbot API-- great for English language learners and those looking for a simpler dictionary experience! ## Features: -Large, easy-to-use input box -Spellchecker -History list that will keep track of what words you've previously searched for -Part of speech and definition of word -Word used in a sentence [View Owl Find live!](https://startnow-node200-ejs-portfolio-dyvdchrcxb.now.sh) Built with React, Less, Node, Express, and the OwlBot API
C
UTF-8
2,012
2.6875
3
[]
no_license
#include "TM1640.h" void TM1640_init(unsigned char brightness_level) { output_high(DIN); output_high(SCLK); TM1640_send_command(auto_address); TM1640_send_command(brightness_level); TM1640_clear_display(); } void TM1640_write(unsigned char value) { unsigned char s = 0x00; for(s = 0x00; s < 0x08; s += 0x01) { output_low(SCLK); if((value & 0x01)) { output_high(DIN); } else { output_low(DIN); } output_high(SCLK); value >>= 0x01; } } void TM1640_send_command(unsigned char value) { output_low(DIN); TM1640_write(value); output_high(DIN); } void TM1640_send_data(unsigned char address, unsigned char value) { TM1640_send_command(fixed_address); output_low(DIN); TM1640_write((0xC0 | (0x0F & address))); TM1640_write(value); output_high(DIN); } void TM1640_clear_display() { unsigned char s = 0x00; output_low(DIN); TM1640_write(start_address); for(s = 0x00; s < no_of_segments; s += 0x01) { TM1640_write(font[0]); }; output_high(DIN); }
Java
UTF-8
2,705
2.359375
2
[]
no_license
package com.square.health.util; import com.square.health.dto.*; import com.square.health.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Converter { public static Blogger bloggerDtoToBlogger(BloggerDto bloggerDto) { Blogger blogger = new Blogger(); blogger.setEmail(bloggerDto.getEmail()); blogger.setPassword(bloggerDto.getBloggerPassword()); blogger.setUserName(bloggerDto.getBloggerName()); return blogger; } public static BloggerDto bloggerToBloggerDto(Blogger blogger) { BloggerDto bloggerDto = new BloggerDto(); bloggerDto.setEmail(blogger.getEmail()); bloggerDto.setBloggerId(String.valueOf(blogger.getId())); bloggerDto.setBloggerName(blogger.getUserName()); bloggerDto.setBloggerStatus(blogger.getStatus().name()); return bloggerDto; } public static Admin adminDtoToAdmin(AdminDto adminDto) { Admin admin = new Admin(); admin.setEmail(adminDto.getEmail()); admin.setPassword(adminDto.getAdminPassword()); admin.setUserName(adminDto.getAdminName()); return admin; } public static AdminDto adminToAdminDto(Admin admin) { AdminDto adminDto = new AdminDto(); adminDto.setEmail(admin.getEmail()); adminDto.setAdminName(admin.getUserName()); return adminDto; } public static Post postDtoToPost(PostDto postDto) { Post post = new Post(); post.setPostBody(postDto.getPostBody()); return post; } public static PostDto postToPostDto(Post post) { PostDto postDto = new PostDto(); Blogger blogger = post.getBlogger(); postDto.setPostId(String.valueOf(post.getId())); postDto.setPostBody(post.getPostBody()); postDto.setStatus(post.getStatus().name()); postDto.setPostId(String.valueOf(post.getId())); postDto.setBloggerId(String.valueOf(blogger.getId())); postDto.setBloggerName(blogger.getUserName()); // postDto.setTotalLikes(post.getLikePosts().size()); return postDto; } public static Comment commentDtoToComment(CommentDto commentDto) { Comment comment = new Comment(); comment.setComment(commentDto.getComment()); return comment; } public static CommentDto commentToCommentDto(Comment comment) { CommentDto commentDto = new CommentDto(); commentDto.setBloggerName(comment.getBlogger().getUserName()); commentDto.setStatus(comment.getStatus().name()); commentDto.setComment(comment.getComment()); commentDto.setCommentId(String.valueOf(comment.getId())); return commentDto; } }
Java
UTF-8
6,539
2.34375
2
[]
no_license
package com.twix_agent; import android.content.Context; import android.view.View; import android.view.ViewGroup; public class FormLayout_old extends ViewGroup { private int MaxWidth = 0; float[] EffectiveWidths; private FormCell[][] CellMatrix; private int[] mHeight; private int cell_padding_y; private int cell_padding_x; private int cell_spacing_y; private int cell_spacing_x; int curX = 0; int curY = 0; private class FormCell { View v; int rowSpan; int colSpan; public FormCell(View v) { this.v = v; rowSpan = 1; colSpan = 1; } public FormCell(View v, int rowSpan, int colSpan) { this.v = v; this.rowSpan = rowSpan; this.colSpan = colSpan; } } public FormLayout_old(Context context, int MaxWidth, String[] SetWidths, String[] SetHeights) { super(context); mHeight = new int[SetHeights.length]; //mWidth = new int[SetWidths.length]; this.MaxWidth = MaxWidth; EffectiveWidths = buildWidths(SetWidths); //this.SetHeights = SetHeights; CellMatrix = new FormCell[SetHeights.length][SetWidths.length]; cell_padding_y = 0; cell_padding_x = 0; cell_spacing_y = 0; cell_spacing_x = 0; } @Override protected ViewGroup.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p) { return new ViewGroup.LayoutParams(p.width, p.height); } public void setCellPadding( int y_padding, int x_padding ) { cell_padding_y = y_padding; cell_padding_x = x_padding; } public void setCellSpacing( int y_spacing, int x_spacing ) { cell_spacing_y = y_spacing; cell_spacing_x = x_spacing; } private int getTotalHeight() { int ret = 0; for( int y = 0; y < mHeight.length; y++ ) ret += mHeight[y] + (cell_padding_y*2) + (cell_spacing_y); return ret + cell_spacing_y; } private int getMaxHeight(int rowIndex) { int ret = 0; int cur; FormCell cell; //for( int x = 0; x < mWidth.length; x++ ) for( int x = 0; x < EffectiveWidths.length; x++ ) { cell = CellMatrix[rowIndex][x]; if( cell != null && cell.v.getVisibility() != View.GONE ) { cur = cell.v.getMeasuredHeight(); for( int y = rowIndex+1; y < (cell.rowSpan + rowIndex); y++ ) { cur -= mHeight[y]; } if(cur > ret) ret = cur; } } return ret; } private float getEffectiveCellWidth(int cellIndex, int colSpan) { float width = 0; for( int x = cellIndex; x < EffectiveWidths.length && x < cellIndex+colSpan; x++ ) { width += EffectiveWidths[x]; } return width; } private float[] buildWidths(String[] SetWidths) { float[] EffectiveWidths = new float[SetWidths.length]; String temp; float per; float px; float totalPercentage = 0; int emptyColCnter = 0; float leftoverPercentage = 0; if( mHeight.length > 0 ) { for( int x = 0; x < EffectiveWidths.length; x++ ) { temp = SetWidths[x]; if( temp != null && temp.contains("%") ) { try { per = Float.parseFloat(temp.replaceAll("%", "")); } catch(Exception e) {per = 0;} EffectiveWidths[x] = (per/100); } else if( temp != null && temp.contains("px") ) { try { px = Float.parseFloat(temp.replaceAll("px", "")); } catch(Exception e) {px = 0;} EffectiveWidths[x] = 100*(px/MaxWidth); } else { EffectiveWidths[x] = 0; emptyColCnter++; } totalPercentage += EffectiveWidths[x]; } if( emptyColCnter > 0 ) { leftoverPercentage = ((1-totalPercentage)/emptyColCnter); if( leftoverPercentage < 0 ) leftoverPercentage = 0; for( int x = 0; x < EffectiveWidths.length; x++ ) { if( EffectiveWidths[x] == 0 ) EffectiveWidths[x] = leftoverPercentage; } } } return EffectiveWidths; } @Override public void addView (View child) { //if( curX > mWidth.length ) if( curX > EffectiveWidths.length ) { curX = 0; curY++; } if( curY > mHeight.length ) curY = 0; CellMatrix[curX][curY] = new FormCell(child); super.addView(child); curX++; } public void addView (View child, int x, int y, int rowSpan, int colSpan) { CellMatrix[y][x] = new FormCell(child, rowSpan, colSpan); super.addView(child); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); for( int y = mHeight.length-1; y >= 0; y-- ) mHeight[y] = getMaxHeight(y); FormCell cell; for( int y = 0; y < mHeight.length; y++ ) { for( int x = 0; x < EffectiveWidths.length; x++ ) { cell = CellMatrix[y][x]; if( cell != null && (cell.v.getVisibility() != GONE) ) { int affectiveHeight = 0; for( int i = y; (i < mHeight.length) && (i < y+cell.rowSpan); i++ ) affectiveHeight += mHeight[i]; int affectiveWidth = (int) (getEffectiveCellWidth(x, cell.colSpan) * width); cell.v.measure( MeasureSpec.makeMeasureSpec(affectiveWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(affectiveHeight, MeasureSpec.UNSPECIFIED) ); } } } setMeasuredDimension(width, getTotalHeight()); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int xpos = getPaddingLeft() + cell_spacing_x; int ypos = getPaddingTop() + cell_spacing_y + cell_padding_y; FormCell cell; int affectiveWidth; int affectiveHeight; for( int y = 0; y < mHeight.length; y++ ) { for( int x = 0; x < EffectiveWidths.length; x++ ) { cell = CellMatrix[y][x]; if( cell != null && cell.v.getVisibility() != View.GONE ) { affectiveWidth = (int) ((r-l) * getEffectiveCellWidth(x, cell.colSpan)); affectiveHeight = 0; for( int i = y; (i < mHeight.length) && (i < y+cell.rowSpan); i++ ) affectiveHeight += mHeight[i]; if( ((x + (cell.colSpan-1)) == EffectiveWidths.length-1) && (affectiveWidth+xpos) < (r)) affectiveWidth += r-(affectiveWidth+xpos); cell.v.layout(xpos, ypos, xpos + affectiveWidth, ypos + affectiveHeight); } else affectiveWidth = (int) ((r-l) * getEffectiveCellWidth(x, 1)); xpos += affectiveWidth = (int) ((r-l) * getEffectiveCellWidth(x, 1)) + cell_spacing_x + (cell_padding_x*2); } xpos = getPaddingLeft() + cell_spacing_x; ypos += mHeight[y] + cell_spacing_y + cell_padding_y; } } }
Shell
UTF-8
4,986
3.265625
3
[]
no_license
#!/bin/sh # Coloured text GREEN=$'\e[0;32m' RED=$'\e[0;31m' NC=$'\e[0m' if [ -z "${GITHUB_TOKEN}" ] then echo "Enter Github token: " read GITHUB_TOKEN fi if [ -z "${TERRAFORM_TOKEN}" ] then echo "Enter Terraform Cloud user token: " read TERRAFORM_TOKEN fi if [ -z "${TERRAFORM_ORGANIZATION_NAME}" ] then echo "Enter Terraform Cloud Organization name: " read TERRAFORM_ORGANIZATION_NAME fi if [ -z "${OAUTH_TOKEN_ID}" ] then echo "Enter Github OAUTH token ID: " read OAUTH_TOKEN_ID fi if [ -z "${TERRAFORM_AGENT_POOL_NAME}" ] then echo "Enter Terraform Cloud agent pool name: " read TERRAFORM_AGENT_POOL_NAME fi echo echo "${GREEN}***** FORKING ACI SINGLE BD, SINGLE EPG REPO *****${NC}" echo curl -X POST -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/repos/conmurphy/tfe_control_aci_single_bd_single_epg/forks" echo echo "${GREEN}**** CREATING TERRAFORM WORKSPACE ****${NC}" echo WORKSPACE=$(cat <<-EOF { "data": { "attributes": { "name": "TFE_CONTROL_aci_applications", "description": "This workspace will deploy the Terraform Cloud workspaces for individual applications", "terraform_version": "1.0.3", "working-directory": "", "allow-destroy-plan":false, "auto-apply":true, "vcs-repo": { "identifier": "conmurphy/tfe_control_aci_single_bd_single_epg", "oauth-token-id": "$OAUTH_TOKEN_ID", "branch": "" } }, "type": "workspaces" } } EOF ) WORKSPACE_ID=$(curl \ --header "Authorization: Bearer $TERRAFORM_TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data "$WORKSPACE" \ https://app.terraform.io/api/v2/organizations/$TERRAFORM_ORGANIZATION_NAME/workspaces | jq -r '.data.id') echo "Workspace ID: $WORKSPACE_ID" echo echo "${GREEN}**** CREATING TERRAFORM VARIABLES ****${NC}" echo # YOU NEED TO USE AN ENVIRONMENTAL VARIABLE FOR THE TOKEN BECAUSE OF AN ERROR WITH THE GITHUB PROVIDER # https://github.com/integrations/terraform-provider-github/issues/830 VARIABLE_GITHUB_TOKEN=$(cat <<-EOF { "data": { "type":"vars", "attributes": { "key":"GITHUB_TOKEN", "value":"${GITHUB_TOKEN}", "category":"env", "hcl":false, "sensitive":true } } } EOF ) curl \ --header "Authorization: Bearer $TERRAFORM_TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data "$VARIABLE_GITHUB_TOKEN" \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars VARIABLE_TERRAFORM_TOKEN=$(cat <<-EOF { "data": { "type":"vars", "attributes": { "key":"tfcb_token", "value":"${TERRAFORM_TOKEN}", "category":"terraform", "hcl":false, "sensitive":true } } } EOF ) curl \ --header "Authorization: Bearer $TERRAFORM_TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data "$VARIABLE_TERRAFORM_TOKEN" \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars VARIABLE_TERRAFORM_ORGANIZATION_NAME=$(cat <<-EOF { "data": { "type":"vars", "attributes": { "key":"tfe_organization_name", "value":"${TERRAFORM_ORGANIZATION_NAME}", "category":"terraform", "hcl":false, "sensitive":false } } } EOF ) curl \ --header "Authorization: Bearer $TERRAFORM_TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data "$VARIABLE_TERRAFORM_ORGANIZATION_NAME" \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars VARIABLE_OAUTH_TOKEN_ID=$(cat <<-EOF { "data": { "type":"vars", "attributes": { "key":"oauth_token_id", "value":"${OAUTH_TOKEN_ID}", "category":"terraform", "hcl":false, "sensitive":true } } } EOF ) curl \ --header "Authorization: Bearer $TERRAFORM_TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data "$VARIABLE_OAUTH_TOKEN_ID" \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars VARIABLE_TERRAFORM_AGENT_POOL_NAME=$(cat <<-EOF { "data": { "type":"vars", "attributes": { "key":"tfe_agent_pool_name", "value":"${TERRAFORM_AGENT_POOL_NAME}", "category":"terraform", "hcl":false, "sensitive":false } } } EOF ) curl \ --header "Authorization: Bearer $TERRAFORM_TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data "$VARIABLE_TERRAFORM_AGENT_POOL_NAME" \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars VARIABLE_APPLICATIONS=$(cat <<-EOF { "data": { "type":"vars", "attributes": { "key":"applications", "value":"[\"\",\"\"]", "category":"terraform", "hcl":true, "sensitive":false } } } EOF ) curl \ --header "Authorization: Bearer $TERRAFORM_TOKEN" \ --header "Content-Type: application/vnd.api+json" \ --request POST \ --data "$VARIABLE_APPLICATIONS" \ https://app.terraform.io/api/v2/workspaces/$WORKSPACE_ID/vars
Python
UTF-8
795
3.140625
3
[]
no_license
class Element: tag = '' def __init__(self, *args): self.content = [] for arg in args: self.content.append(arg) def export(self): result = [] for element in self.content: result.append(element.export()) result = " ".join(result) if (self.tag is not None): return "<"+self.tag+">"+result+"</"+self.tag+">" else: return result class Ul(Element): tag = 'ul' class Li(Element): tag = 'li' class Bold(Element): tag = 'b' class String(Element): tag = None class HTML: @staticmethod def bold(*args): return Bold(args) @staticmethod def ul(*args): return Ul(args) @staticmethod def li(*args): return Li(args)
Java
UTF-8
1,141
2.6875
3
[ "MIT" ]
permissive
package com.antho.newsreader.view.fragments.adapter; import com.antho.newsreader.model.popular.Popular; import java.util.List; import androidx.recyclerview.widget.DiffUtil; /** Overrides diffUtil methods to improve software performance **/ class PopularDiffCallback extends DiffUtil.Callback { private final List<Popular> oldList; private final List<Popular> newList; // public PopularDiffCallback(List<Popular> oldList, List<Popular> newList) { this.oldList = oldList; this.newList = newList; } // @Override public int getOldListSize() { return oldList.size(); } // @Override public int getNewListSize() { return newList.size(); } // @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).multimedia() == newList.get(newItemPosition).multimedia(); } // @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { return oldList.get(oldItemPosition).equals(newList.get(newItemPosition)); } }
Java
UTF-8
638
2.3125
2
[]
no_license
package com.b1610701.tuvantuyensinh.model; public class DiemChuan { private float _1; private float _2; private float _3; public DiemChuan(){} public DiemChuan(float _1, float _2, float _3){ this._1 = _1; this._2 = _2; this._3 = _3; } public void set_1(float _1){ this._1 = _1; } public void set_2(float _2){ this._2 = _2; } public void set_3(float _3){ this._3 = _3; } public float get_1(){ return this._1; } public float get_2(){ return this._2; } public float get_3(){ return this._3; } }
Ruby
UTF-8
1,794
3.453125
3
[]
no_license
#!/usr/bin/ruby require 'getoptlong' require './lib/markovchain' def usage puts "Overview: Reads text from standard input, creates a markov chain" puts "(n-gram) model, and outputs words based on that model." puts puts "Usage:" puts __FILE__ + " [options...] [beginning [beginning] [...]]" puts " --minlen <n> Minimum length of generated string" puts " --maxlen <n> Maximum length of generated string" puts " -l | --length <n> Set min and max length of generated string" puts " -n | --count <n> Number of strings to generate" puts " -o | --order <n> Markov chain order (default: 2)" puts " -h | --help Show command line usage" exit 1 end opts = GetoptLong.new( [ '--minlength', GetoptLong::REQUIRED_ARGUMENT], [ '--maxlength', GetoptLong::REQUIRED_ARGUMENT], [ '--length', '-l', GetoptLong::REQUIRED_ARGUMENT], [ '--count', '-n', GetoptLong::REQUIRED_ARGUMENT], [ '--order', '-o', GetoptLong::REQUIRED_ARGUMENT], [ '--help', '-h', GetoptLong::NO_ARGUMENT], ) mc = MarkovChain.new reps = 10 opts.each do |opt, arg| case opt when '--help' usage when '--count' reps = arg.to_i when '--order' mc.order = arg.to_i when '--minlength' mc.minlength = arg.to_i when '--maxlength' mc.maxlength = arg.to_i when '--length' mc.minlength = arg.to_i mc.maxlength = arg.to_i end end STDIN.each_line do |line| line.scan(/[A-Za-z]+/).each do |word| chain = word.downcase.split('') mc.digest(chain) end end #mc.status if ARGV.size > 0 prefixes = ARGV else prefixes = [''] end prefixes.each do |start| start_chain = start.downcase.split('') reps.times do chain = mc.generate(start_chain) puts chain.join.capitalize end end
Python
UTF-8
171
2.8125
3
[]
no_license
from Associator import * a = Associator(10) a.put("cat", "Katze") a.put("mum", "Mutter") a.put("mat", "Matte") a.put("nuts", "Nuss") a.put("house", "Haus") a.print()
Python
UTF-8
11,167
2.546875
3
[ "MIT" ]
permissive
import numpy as np import matplotlib.pyplot as plt from skimage import morphology, transform from skimage.measure import label from scipy import ndimage from scipy.signal import convolve def resize_and_get_pixel_size(im, x_pixel_size, y_pixel_size, z_pixel_size): rows, cols, slices = im.shape # Get the pixel size of the longest direction. The other directions # will be scaled to the same size. pixel_size = max(x_pixel_size, y_pixel_size, z_pixel_size) scale = (pixel_size / x_pixel_size, pixel_size / y_pixel_size, pixel_size / z_pixel_size) output_shape = (int(round(rows*scale[0],0)), int(round(cols*scale[1],0)), int(round(slices*scale[2],0))) scaled_im = transform.resize(im, output_shape) return scaled_im, pixel_size def skeletonize(im): skel = morphology.skeletonize_3d(im).astype('bool') return(skel) def distance_transform(im): dt = ndimage.morphology.distance_transform_edt(im) return dt def calculate_diameter(skel, dt, pixel_size): diams = skel * dt * 2 / skel.max() av = int(np.average(diams[diams>0])) av *= 2 # exclude edge pixels that are twice the average diams = diams[av:-av, av:-av, av:-av] diams = diams[diams>2] diams = diams * pixel_size return diams def count_neighbors(skel): strel = np.ones((3, 3, 3)) strel[1, 1, 1] = 0 conv = convolve(skel, strel, mode='same') neighbors = np.round((conv * skel)).astype(np.uint8) return neighbors def find_nodes(neighbors): nodes = neighbors > 2 return nodes def label_ligaments(neighbors): ligaments = neighbors < 3 ligaments[neighbors == 0] = 0 labels = label(ligaments, connectivity=3) return labels def calculate_lengths(labels, pixel_size): lengths = np.bincount(labels.flatten()) lengths[0] = 0 # filter out background lengths = lengths[lengths>0] lengths = lengths * pixel_size return lengths def remove_terminal_ligaments(labels, neighbors, return_terminal=False): terminals = neighbors == 1 term_labels = np.unique(terminals * labels) terminal_ligaments = np.isin(labels, term_labels[1:]) terminal_removed = (neighbors > 1) ^ terminal_ligaments if return_terminal: return terminal_removed, terminal_ligaments else: return terminal_removed def fnm2(im, skel, nodes, labels, dist): node_mask = np.zeros(im.shape, dtype='bool') node_dialate = nodes > 0 while True: node_dialate = morphology.binary_dilation(node_dialate) node_labels = morphology.label(node_dialate) inside_node_labels = node_labels * im unique, counts = np.unique(node_labels, return_counts=True) _, counts_inside = np.unique(inside_node_labels, return_counts=True) print(unique, counts, counts_inside) for u, c, ci in zip(unique[1:], counts[1:], counts_inside[1:]): if c > ci: node_mask[node_labels == u] = 1 node_dialate[node_labels == u] = 0 if np.count_nonzero(node_dialate) == 0: break return(node_mask * im) def fnm3(im, skel, nodes, labels, dist): node_mask = np.zeros(im.shape, dtype='bool') xx, yy, zz = node_mask.shape node_dist = nodes * dist idx = np.nonzero(nodes) #print(len(idx[0])) for x, y, z in zip(idx[0], idx[1], idx[2]): print(x,y,z) radius = node_dist[x, y, z] n = int(2 * radius + 1) Z,Y,X = np.mgrid[-x:xx-x, -y:yy-y, -z:zz-z] mask = X ** 2 + Y ** 2 + Z ** 2 <= radius ** 2 #print(mask.shape) node_mask[mask] = 1 #array = np.zeros((n, n), dtype='bool') #array[mask] = 1 #node_mask[x-X:x+X+1, y-Y:y+Y+1, z-Z:z+Z+1] = 1 return(node_mask) def find_node_mask(im, skel, nodes, labels, distance_transform): node_mask = np.zeros(im.shape, dtype='bool') node_dist = (nodes * distance_transform).astype(np.uint8) node_dist_list = np.unique(node_dist).tolist() #print(node_dist_list) spheres = SphereLookupTable(node_dist_list) for dist in node_dist_list[1:]: this_dist = np.zeros(im.shape) this_dist[node_dist==dist] = 1 this_mask = spheres.get_mask(dist) conv = convolve(this_dist, this_mask, mode='same') conv = conv > 0.5 node_mask[conv==1] = 1 # spheres = SphereLookupTable(range(10)) # print(spheres.get_mask(2)) # test = np.zeros((7,7,7)) # test[3,3,3] = 1 # test = convolve(test, spheres.get_mask(node_dist_list[3]), mode='same') # test = test > 0.5 return node_mask class SphereLookupTable(object): # Generates a dictionary of sphere structuring elements. # This way the structuring elements only have to be generated once. table = {} def __init__(self, radii): for i in radii: self.table[i] = self.generate_mask(i) def generate_mask(self, r): return morphology.ball(r, dtype='bool') def get_mask(self, r): return self.table[r] class VolumeData(object): def __init__(self, im, pixel_size = 1.0, status=None, progress=None, display=None, plot=None, invert_im = False): self.pixel_size = pixel_size # widget control self.status = status self.progress = progress self.display = display self.plot = plot # volume data self.im = im < 1 if invert_im else im > 0# Volume data self.skel = None #binary mask locating the backbone self.nodes = None #binary mask locating the nodes self.terminal = None # binary mask locating terminal ligaments self.node_mask = None self.lengths = None self.all_diameters = None self.terminal_diameters = None self.node_diameters = None self.connected_diameters = None self.percent_terminal = None # data properties self.shape = self.im.shape def calculate(self): if self.progress is not None: self.progress.setVisible(True) # Skeletonize self.update_progress('Skeletonizing...', 1) self.skel = skeletonize(self.im) # Distance self.update_progress('Calculating distance transform...', 20) distance = distance_transform(self.im) # Find number of neighbors self.update_progress('Counting pixel neighbors...', 25) neighbors = count_neighbors(self.skel) # Find nodes self.update_progress('Finding nodes...', 30) self.nodes = find_nodes(neighbors) # Label ligaments self.update_progress('Separating ligaments...', 40) labels = label_ligaments(neighbors) # Remove terminal ligaments self.update_progress('Finding terminal ligaments...', 50) skel_without_term, self.terminal = remove_terminal_ligaments( labels, neighbors, True) # Find node mask #self.update_progress('Finding node mask...', 60) #self.node_mask = fnm3(self.im, self.skel, self.nodes, labels, # distance) # Calculate lengths self.update_progress('Calculating length...', 60) self.lengths = calculate_lengths(labels * skel_without_term, self.pixel_size) #self.plot.plot(self.lengths, 'length [pixels]') # Diameter self.update_progress('Calculating diameter...', 70) self.all_diameters = calculate_diameter(self.skel, distance, self.pixel_size) if self.plot is not None: self.plot.plot(self.all_diameters, 'diameter [units]') self.terminal_diameters = calculate_diameter(self.terminal, distance, self.pixel_size) self.node_diameters = calculate_diameter(self.nodes, distance, self.pixel_size) self.connected_diameters = calculate_diameter(skel_without_term, distance, self.pixel_size) self.percent_terminal = 100* len(self.terminal_diameters) / len(self.all_diameters) # Finish self.update_progress('', 100) def export(self, path): with open(path, 'w') as f: f.write('Average of all ligament diameters: ') f.write(str(round(np.mean(self.all_diameters),2))) f.write('\n') f.write('Average connected ligament diameter: ') f.write(str(round(np.mean(self.connected_diameters), 2))) f.write('\n') f.write('Average terminal ligament diameter: ') f.write(str(round(np.mean(self.terminal_diameters), 2))) f.write('\n') f.write('Average node point diameter: ') f.write(str(round(np.mean(self.node_diameters), 2))) f.write('\n') f.write('Average ligament length (node to node) (NOT ACCURATE): ') f.write(str(round(np.mean(self.lengths), 2))) f.write('\n') f.write('Percent terminal ligaments (linear length): ') f.write(str(round(np.mean(self.percent_terminal), 2))) f.write('%') f.write('\n\n\n') f.write('All diameter measurements') f.write('\n') f.write('\n'.join([str(i) for i in self.all_diameters])) f.write('\n\n') f.write('Connected ligament diameter measurements') f.write('\n') f.write('\n'.join([str(i) for i in self.connected_diameters])) f.write('\n\n') f.write('Terminal ligament diameter measurements') f.write('\n') f.write('\n'.join([str(i) for i in self.terminal_diameters])) f.write('\n\n') f.write('Node point diameter measurements') f.write('\n') f.write('\n'.join([str(i) for i in self.node_diameters])) f.write('\n\n') f.write('Ligament length measurements') f.write('\n') f.write('\n'.join([str(i) for i in self.lengths])) f.write('\n\n') def update_progress(self, message, value): if self.status is not None: self.status.setText(message) else: print(message) if self.progress is not None: self.progress.setValue(value) if self.progress is not None and value == 100: self.progress.setVisible(False) if self.display is not None: self.display([0, self.shape[0], 0, self.shape[1], 0, self.shape[2]]) if __name__ == '__main__': from inout import read_tiff_stack fpath = (r'E:\E_Documents\Research\Computer Vision Collaboration\Erica ' r'Lilleodden/fib serial section data.tif') im = read_tiff_stack(fpath) #im = im[:100, :100, :100] volume = VolumeData(im, 0.1) volume.calculate() opath = (r'E:\E_Documents\Research\Computer Vision Collaboration\Erica ' r'Lilleodden/data.txt') volume.export(opath) #a = SphereLookupTable(10) #print(a.get_mask(3)) #print('start') #im, pixel_size = resize_and_get_pixel_size(im, 1,1,2)
JavaScript
UTF-8
2,621
2.84375
3
[]
no_license
const Max = function( { selector, props, state, template, beforeRender = function(){}, afterRender = function(){}, eventBind = function(){} }) { // 생성자로 호출할 수 있게만 만들기 if (new.target !== Max) { return new Max({selector, props, state, template, beforeRender, afterRender, eventBind}) } this.init = () => { this.$el = document.querySelector(selector) this.$data = new Proxy({...props, ...state}, handler(this)) this.$template = template // 초기 상태로 하는 초기 렌더링 this.$view = this.$template(this.$data) } // 렌더함수 // 프로미스를 리턴하면 비동기 로직으로 처리할 수 있게.. // 라고는 하지만 이상태로는 잘 작동되지는 않을듯 this.render = async () => { // 인스턴스 만들때 선언한 함수들의 this를 참조할 수 잇게 this 바인딩 (주로 data에 접근하겠지만) await beforeRender.call(this) this.$view = this.$template(this.$data) // 컴포넌트에서 데이터가 바뀌면 프록시가 이를 감지하고 // render함수를 재실행시켜서 view를 업데이트한다. // el이 있는 경우는 뷰를 el에 붙인다 if (selector) { this.$el.innerHTML = this.$view } await eventBind.call(this) await afterRender.call(this) } this.init() this.render() } // 상위 컴포넌트에서 props를 받기위한 래핑 함수 const component = (instanceParam) => (props) => { if (props) { return new Max({...instanceParam, props}) } return new Max(instanceParam) } // $view를 직접 참조하는 것보다 좀더 추상화 단계 높은 자식 컴포넌트 래핑 함수 export const childComponent = component => { return component.$view } // 프록시로 리액티비티 // 프록시 get set 함수의 첫번째 인자는 proxy 첫번째 생성자에 들어간 객체 // 두번째 인자는 뭔가 바뀌거나(set) 조회되는(get) 객체의 프로퍼티 const handler = (instance) => { return { get: function (obj, prop) { if (['[object Object]', '[object Array]'].indexOf(Object.prototype.toString.call(obj[prop])) > -1) { return new Proxy(obj[prop], handler(instance)); } return obj[prop]; }, // 삭제, 혹은 수정을 watch하게 된다 set: function (obj, prop, value) { console.log('rerender'); obj[prop] = value; instance.render() return true; }, deleteProperty: function (obj, prop) { console.log('rerender'); delete obj[prop]; instance.render() return true; } }; } export default component
Java
UTF-8
541
3.515625
4
[]
no_license
package com.fxq.homework.day03.subject04; public class Outer { public static A method(){ //把A用Inter代替同理 //方法一 /* A a = new A(){ @Override public void show() { System.out.println("HelloWorld"); } }; return a;*/ //方法二 /*return new A(){ @Override public void show() { super.show(); } };*/ //方法三 A a = new A(); return a; } }
Shell
UTF-8
408
3.53125
4
[ "MIT" ]
permissive
#!/bin/bash project=$1 pushd $project > /dev/null #All Packages PACKAGES=$(find . -name '*.go' -print0 | xargs -0 -n1 dirname | sort --unique) echo '## Packages requireing linting' for pkg in ${PACKAGES[@]}; do echo "- [ ] $pkg $(golint $pkg | wc -l)" | grep -v '\s0$' done echo '' echo 'packages passing lint' for pkg in ${PACKAGES[@]}; do echo "- [x] $pkg $(golint $pkg | wc -l)" | grep '\s0$' done
C#
UTF-8
1,332
3.203125
3
[]
no_license
using System; using System.Globalization; namespace uri_1051 { class Program { static void Main(string[] args) { double valorSalario; valorSalario = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture); if (valorSalario >= 0.00 && valorSalario <= 2000.00) { Console.WriteLine("Isento"); } else { double valorTaxado = 0.00, valorImposto = 0.00; if (valorSalario >= 2000.01 && valorSalario <= 3000.00) { valorTaxado = valorSalario - 2000.00; valorImposto = valorTaxado * ((double)8 / 100.00); } else if (valorSalario >= 3000.01 && valorSalario <= 4500.00) { valorTaxado = valorSalario - 2000.00; valorImposto = valorTaxado * ((double)18 / 100.00); } else if (valorSalario > 4500.00) { valorTaxado = valorSalario - 2000.00; valorImposto = valorTaxado * ((double)28 / 100.00); } Console.WriteLine("R$ " + valorImposto.ToString("F2", CultureInfo.InvariantCulture)); } } } }
Java
UTF-8
3,679
2.0625
2
[]
no_license
package com.son.videotophoto; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.provider.ContactsContract; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.TextView; public class QualityDialog extends Dialog { RadioButton rdBest, rdVeryHigh, rdHigh, rdLow, rdMedium; String defQuality = "High"; String quality = ""; ImageButton btnClose; TextView txtQuality; Context context; public QualityDialog(@NonNull Context context, TextView txtQuality) { super(context); this.context = context; this.txtQuality = txtQuality; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quality_dialog); setUpView(); addEvets(); } private void setUpView() { rdBest = findViewById(R.id.rdBest); rdVeryHigh = findViewById(R.id.rdVrHigh); rdMedium = findViewById(R.id.rdMedium); rdHigh = findViewById(R.id.rdHigh); rdLow = findViewById(R.id.rdLow); btnClose = findViewById(R.id.btnClose); btnClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); getDataSharePreference(); } private void getDataSharePreference() { SharedPreferences sharedPreferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); quality = sharedPreferences.getString("QUALITY", defQuality); checkQuality(quality); } private void checkQuality(String quality) { if (quality.equals(context.getResources().getString(R.string.Best))) { rdBest.setChecked(true); } if (quality.equals(context.getResources().getString(R.string.VeryHigh))) { rdVeryHigh.setChecked(true); } if (quality.equals(context.getResources().getString(R.string.High))) { rdHigh.setChecked(true); } if (quality.equals(context.getResources().getString(R.string.Medium))) { rdMedium.setChecked(true); } if (quality.equals(context.getResources().getString(R.string.Low))) { rdLow.setChecked(true); } } private void addEvets(){ rdVeryHigh.setOnCheckedChangeListener(listener); rdBest.setOnCheckedChangeListener(listener); rdLow.setOnCheckedChangeListener(listener); rdHigh.setOnCheckedChangeListener(listener); rdMedium.setOnCheckedChangeListener(listener); } CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { String quality = buttonView.getText().toString(); buttonView.setChecked(true); saveQuality(quality); txtQuality.setText(quality); } } }; private void saveQuality(String quality) { SharedPreferences sharedPreferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("QUALITY",quality); editor.commit(); } }
Markdown
UTF-8
6,457
4.34375
4
[]
no_license
# 排序类 排序算法主要有,冒泡,选择,插入,希尔,归并,快速排序,堆排序 ## 冒泡 1. 常规版 ```javascript function bubbleSort(arr) { let len = arr.length; for (var i = 0; i < len; i++) { for (var j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j + 1]) { let tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; } } } } ``` 优化点,每次循环的时候,不仅找最大值,也找最小值 ```javascript function bubbleSort(arr) { let len = arr.length; let low = 0; let high = len - 1; let tmp, i = 0; while (low < high) { for (i = low; i < high; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; } } --high; for (i = high; i > low; i--) { if (arr[i] < arr[i - 1]) { tmp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = tmp; } } low++; } } ``` ## 选择排序 原理: 从未排序的数组中选择最大(最小)的元素放在已排序的最前面。 ```javascript function selectionSort(arr) { var len = arr.length; var tmp; // 假设数组从小到大排序。只需遍历找最小的index var minIndex; for (var i = 0; i < len; i++) { minIndex = i; for (var j = j + 1; j < len; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } tmp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = tmp; } return arr; } ``` ## 插入排序 原理: 从数组中取元素,有序插入到当前已排序列表中。 ```javascript function insersionLoss(arr) { var len = arr.length; var preIndex, current; for (var i = 0; i < len; i++) { preIndex = i - 1; current = arr[i]; while (preIndex >= 0 && arr[preIndex] > current) { arr[preIndex + 1] = arr[preIndex]; preIndex--; } // 找到插入的位置 arr[preIndex + 1] = current; } return arr; } ``` ## 归并排序 思路:把数组分成左右两部分,分别合并。 ```javascript function mergeSort(arr) { var len = arr.length; var mid = Math.floor(len / 2); var left = arr.slice(0, middle); var right = arr.slice(middle, len); return merge(mergeSort(left), mergeSort(right)); } function merge(left, right) { var res = []; var i = 0; var j; while (left.length > 0 && right.length > 0) { if (left[0] < right[0]) { // 始终比第一个 result.push(left.shift()); } else { retsult.push(right.shift()); } } while (left.length) { result.push(left.shift()); } while (right.length) { result.push(right.shift()); } return result; } ``` ## 快速排序 原理:快速排序先确定一个支点 pivot。将所有小于支点的放在该点的左边,大于的放在右边。然后对左右两侧的数组不断重复这个过程。 ```javascript // 先定义交换函数 function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } function partition(arr, left, right) { var pivot = arr[Math.floor((left + right) / 2]; var i = left; var j = right; while(i < j) { while(arr[i] < pivot) { // 知道找到一个大于的退出 i++; } while(arr[j] > pivot) { // 直到找到一个小于的退出 j--; } if(i < j) { swap(arr, i, j); i++; j--; } } return i; } // 剩下需要重复上面的过程 function quickSort(arr, left, right) { if(arr.length < 2) { return arr; } var len = arr.length; left = typeof left !== 'number' ? 0 : left; right = typeof right !== 'number' ? len - 1 : right; var index = partition(arr, left, right); if(left < index) { quickSort(arr, left, index - 1); } if(index < right) { quickSort(arr, index, right); } return arr; } ``` ## 堆排序 原理:将待排序序列构造成一个大顶堆,此时,整个序列的最大值就是堆顶的根节点。将其与末尾元素进行交换,此时末尾就为最大值。然后将剩余 n-1 个元素重新构造成一个堆,这样会得到 n 个元素的次小值。如此反复执行,便能得到一个有序序列了 大顶堆: ```javascript function heapSort(arr) { // 1. 拿到第一个最大值 for (var i = arr.length / 2 - 1; i >= 0; i++) { //从第一个非叶子节点开始,从下到上,从左到右调整结构 adjustHeap(arr, i, arr.length); } // 2. 调整堆结构+交换堆顶元素和末尾元素 for (var j = arr.length - 1; j > 0; j--) { swap(arr, 0, j); adjustHeap(arr, 0, j); //重新对堆调整 } } // 调整大顶堆 function adjustHeap(arr, i, len) { var tmp = arr[i]; for (var k = 2 * i + 1; k < length; k = k * 2 + 1) { if (k + 1 < length && arr[k] < arr[k + 1]) { // 如果左子节点小于右子节点,k指向右节点 k++; } if (arr[k] > temp) { //如果子节点大于父节点,将子节点的值赋值给父节点 arr[i] = arr[k]; i = k; } else { break; } } arr[i] = tmp; } function swap(arr, i, j) { var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } ``` 小顶堆: ## 242. 有效的字母异位词 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。 示例 1: 输入: s = "anagram", t = "nagaram" 输出: true 示例 2: 输入: s = "rat", t = "car" 输出: false 说明: 你可以假设字符串只包含小写字母。 进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况? ### 解答 ```javascript /** * @param {string} s * @param {string} t * @return {boolean} */ var isAnagram = function(s, t) { if (s.length != t.length) { return false; } var sMap = new Map(); var tMap = new Map(); for (var i = 0; i < s.length; i++) { if (!sMap.get(s[i])) { sMap.set(s[i], 1); } else { sMap.set(s[i], sMap.get(s[i]) + 1); } } for (var i = 0; i < t.length; i++) { if (!tMap.get(t[i])) { tMap.set(t[i], 1); } else { tMap.set(t[i], tMap.get(t[i]) + 1); } } var flag = true; sMap.forEach((value, key, map) => { if (!tMap.get(key) || tMap.get(key) != value) { flag = false; } }); return flag; }; ```
Markdown
UTF-8
432
3.171875
3
[ "MIT" ]
permissive
### Using font-weight on android :::note For Android the font. weights MUST align with the used font. So try out which is the regarding font weight to your used font. ::: ```tsx h1Style: { fontFamily: 'Nunito-SemiBold', fontWeight: '300', }, h2Style: { fontFamily: 'Nunito-Regular', fontWeight: '100', }, h3Style: { fontFamily: 'Nunito-Bold', fontWeight: '500', }, ```
Markdown
UTF-8
2,172
4.0625
4
[]
no_license
#ES6语法实现模板编译 #基础字符串模板 ```js var template = ` <ul> <% for(var i=0; i < data.supplies.length; i++) { %> <li><%= data.supplies[i] %></li> <% } %> </ul> `; ``` 思路:怎么编译这个模板字符串呢?根本原理可以用ES5语法的循环拼接字符串,这里设置这个循环拼接函数为echo() 将其转换为JavaScript表达式字符串 ```js echo('<ul>'); for(var i=0; i < data.supplies.length; i++) { echo('<li>'); echo(data.supplies[i]); echo('</li>'); }; echo('</ul>'); ``` 用正则来匹配将基础字符串模板替换为想要的字符串模板 ```js var evalExpr = /<%=(.+?)%>/g; var expr = /<%([\s\S]+?)%>/g; template = template .replace(evalExpr, '`); \n echo( $1 ); \n echo(`') .replace(expr, '`); \n $1 \n echo(`'); template = 'echo(`' + template + '`);'; ``` 然后,将template封装在一个函数里面返回,就可以了。 ```js var script = `(function parse(data){ var output = ""; function echo(html){ output += html; } ${ template } return output; })`; return script; ``` 注意:这里用到了ES6语法的字符串模板属性${ template },在模板中可以运行函数和使用变量 最后,将上面的内容拼装成一个模板编译函数compile。 ```js var template = ` <ul> <% for(var i=0; i < data.supplies.length; i++) { %> <li><%= data.supplies[i] %></li> <% } %> </ul> `; function compile(template){ var evalExpr = /<%=(.+?)%>/g; var expr = /<%([\s\S]+?)%>/g; template = template .replace(evalExpr, '`); \n echo( $1 ); \n echo(`') .replace(expr, '`); \n $1 \n echo(`'); template = 'echo(`' + template + '`);'; var script = `(function parse(data){ var output = ""; function echo(html){ output += html; } ${ template } return output; })`; return script; } var parse = eval(compile(template)); div.innerHTML = parse({ supplies: [ "broom", "mop", "cleaner" ] }); ``` 编译后输出 ```html <ul> <li>broom</li> <li>mop</li> <li>cleaner</li> </ul> ```
C
UTF-8
709
3.6875
4
[]
no_license
/* Student Info: UWin ID: 105 167 718 Name: Shail Patel Lab Section Number: Use this part to report your on comments on the code State clearly any valid assumptions */ #include <stdio.h> void DrawHalfPyramid(int rows) { for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { printf("%d ", i * j); } printf("\n"); } } int main() { int rows = 0; do { printf("please enter the number of rows: "); scanf("%d", &rows); } while (!(rows >= 2 && rows <= 10)); printf("printing a half pyramid of %d rows", rows); printf("\n"); DrawHalfPyramid(rows); return 0; }
Markdown
UTF-8
2,090
2.78125
3
[ "MIT" ]
permissive
# Tired of running grunt every time you change something? We can use a task that watches our changes and triggers the `grunt babel` task for us. Lets install `$ npm install --save-dev grunt-contrib-watch` and then create `tasks/watch.js`. ```js module.exports = function (grunt) { var config = { watch: { ui: { files: [ 'src/**/*.js' ], tasks: ['babel'], options: { livereload: true } } } }; grunt.config.merge(config); }; ``` # Connect and Watch ? Now we have a task that watches our changes but we need it to work concurrently with the `connect` http server. Lets install `$ npm install --save-dev grunt-concurrent` and create `tasks/concurrent.js`. ```js module.exports = function (grunt) { var config = { concurrent: { dev: { tasks: ['connect:server:keepalive', 'watch'], options: { logConcurrentOutput: true } } } }; grunt.config.merge(config); }; ``` Now we can use `grunt concurrent` and it will run watch and connect simultaneously. Something that we need to keep in mind is that the watch now is executing our transpiler, such way our code will not get transpiled until we modify a file while having our `concurrent` task running. Lets modify our `package.json` file. ```js "scripts": { "start": "grunt babel && grunt concurrent" }, ``` Now we can type `$ npm start` and it will transpile and start the concurrent tasks for us. # Livereload If you are curious, then for sure you did notice the `livereload: true` option on the `tasks/watch.js` task. Lets add the **Live Reload** script to our `public/index.html` file. ```html <script src="//localhost:35729/livereload.js"></script> ``` Now, refresh the browser (to update the html), then go and modify our `src/index.js` file and see what happen. ## Next 6. [Dynamic rendereing](ch-06.md) - use React to render dynamic data.
Java
UTF-8
740
1.914063
2
[]
no_license
package com.ff.system.vo; /** * @Author yuzhongxin * @Description * @Create 2017-07-14 1:27 **/ public class TreeVO { private String id; private String pId; private String name; private Integer checked; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getpId() { return pId; } public void setpId(String pId) { this.pId = pId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getChecked() { return checked; } public void setChecked(Integer checked) { this.checked = checked; } }
Python
UTF-8
821
2.625
3
[]
no_license
from django.shortcuts import render import random # Create your views here. def index(request): return render(request,'index.html') #Template variables def dinner(request): menu=["spagetti","hamberger","chicken","sushi","tofu","soup"] pick=random.choice(menu) return render(request,'dinner.html',{'dinner':pick}) #Variable routing def hello(request,name): return render(request,'hello.html',{'name':name}) #Form tag def throw(request): return render(request, 'throw.html') def catch(request): message=request.GET.get('message') return render(request,'catch.html',{'message':message}) #Form request to external page def naver(request): return render(request,'naver.html') #Bootstrap def bootstrap(request): return render(request,'bootstrap.html')
Markdown
UTF-8
536
2.90625
3
[]
no_license
# Cypress-Basics-Tutorial Cypress tutorial for beginners, it is working best with tutorial docs available here: https://docs.google.com/document/d/1goqWk9BFzuajmZcH8gd4a7XMa75CmVw3cb1JGuzJxTY/edit?usp=sharing To install cypress with examples from this repository follow these steps 1. Clone this repository to your PC 2. Open it in the console and install cypress by the command "npm install cypress" 3. Open Cypress by running in your console "npx cypress open" For the rest of the tutorial follow the link from the description.
C++
UTF-8
8,882
3.09375
3
[ "Zlib" ]
permissive
#include "Perlin.h" namespace Engine { // Default, unseeded constructor. Initialises the default permutation vector // (as set out by Perlin) Perlin::Perlin() : seed(0), octaves(5), persistence(0.25f) { permutations.resize(512); // Duplicate first set of values to get to 512 for (int i = 0; i < 256; i++) { permutations[i + 256] = permutations[i]; } } Perlin::Perlin(uint seed) : seed(seed), octaves(5), persistence(0.25f) { shufflePermutations(); } // Construct the permutation array using a seed value. This constructor is not a part of the // original noise implementation but is important to add for procedural generation. Perlin::Perlin(uint seed, uint octaves, float persistence) : seed(seed), octaves(octaves), persistence(persistence) { shufflePermutations(); } // Calculate noise value for a given (x, y) co-ordinate by creating a unit square around it, finding // where (x, y) sits within the square, then fading the co-ordinates, hashing to find a gradient and // linearly interpolating between those gradients and the faded co-ordinates. // This is a simplification of noise3D (see below). float Perlin::noise2D(float x, float y) { // Generate unit square that contains the point int X = floor(x) & 255; int Y = floor(y) & 255; // Find relative position of this point in the square x -= floor(x); y -= floor(y); // Apply fade curve to each co-ordinate float u = fade(x); float v = fade(y); // Using permutation values, hash coordinates of the corners. int A = permutations[X] + Y, AA = permutations[A], AB = permutations[A + 1], B = permutations[X + 1] + Y, BA = permutations[B], BB = permutations[B + 1]; float lintResult1 = lint(u, gradient(permutations[AA], x, y), gradient(permutations[BA], x - 1, y)); float lintResult2 = lint(u, gradient(permutations[AB], x, y - 1), gradient(permutations[BB], x - 1, y - 1)); return lint(v, lintResult1, lintResult2); } // Generates a single noise value for a given coordinate by creating a unit cube around the point, // finding the point within the cube, fading the values, hashing the coordinates of the cube corners // and finally linearly interpolating these points. float Perlin::noise3D(float x, float y, float z) { // Generate unit cube that contains the point // The factor 255 is introduced to wrap the integer 'cells' int X = floor(x) & 255; int Y = floor(y) & 255; int Z = floor(z) & 255; // Find the relative position of the point WITHIN this cube (scale between 0 and 1) x -= floor(x); y -= floor(y); z -= floor(z); // Apply fade curve to each coordinate float u = fade(x); float v = fade(y); float w = fade(z); // Using permutation values, hash the coordinates of cube corners // (Hashes used for gradient function) int A = permutations[X] + Y, AA = permutations[A] + Z, AB = permutations[A + 1] + Z, B = permutations[X + 1] + Y, BA = permutations[B] + Z, BB = permutations[B + 1] + Z; // Linear interpolate as appropriate to create the final value based on the faded values // and the calculated hashed cube corners. Simplified from the original implementation for readability float innerLint1, innerLint2, outerLint1, outerLint2; // All hash values and hash values + 1 represented. Combinations of x, y, z, and x-1, y-1, z-1. innerLint1 = lint(u, gradient(permutations[AB + 1], x, y - 1, z - 1), gradient(permutations[BB + 1], x - 1, y - 1, z - 1)); // Innermost interpolation outerLint1 = lint(v, lint(u, gradient(permutations[AA + 1], x, y, z - 1), gradient(permutations[BA + 1], x - 1, y, z - 1)), innerLint1); innerLint2 = lint(u, gradient(permutations[AB], x, y - 1, z), gradient(permutations[BB], x - 1, y - 1, z)); outerLint2 = lint(v, lint(u, gradient(permutations[AA], x, y, z), gradient(permutations[BA], x - 1, y, z)), innerLint2); return lint(w, outerLint2, outerLint1); // Outermost interpolation, giving the final value } // Octaves and persistence are not present in Perlin's original work. They have been added as // a tool to help shape the noise to appear more "natural" and blended. Each successive // octave has a smaller effect on the final noise, according to persistence. // An octave count of 1, or a persistence of 0, will cause the output to be identical to the original noise. // The following article was used to help write this function: https://flafla2.github.io/2014/08/09/perlinnoise.html float Perlin::octaveNoise2D(float x, float y) { float total = 0.0f; float max = 0.0f; // this puts a cap on the final value, so it normalises btwn 0 and 1 float frequency = 1.0f, amplitude = 1.0f; // these decrease each iteration for (uint i = 0; i < octaves; ++i) { total += noise2D(frequency*x, frequency*y) * amplitude; // If we add each amplitude value, we can divide through to normalise. max += amplitude; // As octave gets higher, increase frequency according to 2^i (higher frequency = more jagged noise) frequency *= 2; // As octave gets higher, decrease amplitude according to persistence^i (lower amplitude = affects final noise less) // The higher the persistence, the more each octave's noise will affect the overall noise. amplitude *= persistence; } return total / max; } // An implementation of octave noise made suitable for 3D. As above, but making use of the noise3D function. float Perlin::octaveNoise3D(float x, float y, float z) { float total = 0.0f; float max = 0.0f; // this puts a cap on the final value, so it normalises btwn 0 and 1 float frequency = 1.0f, amplitude = 1.0f; // these decrease each iteration for (uint i = 0; i < octaves; ++i) { total += noise3D(frequency*x, frequency*y, frequency*z) * amplitude; // If we add each amplitude value, we can divide through to normalise. max += amplitude; // As octave gets higher, increase frequency according to 2^i (higher frequency = more jagged noise) frequency *= 2; // As octave gets higher, decrease amplitude according to persistence^i (lower amplitude = affects final noise less) // The higher the persistence, the more each octave's noise will affect the overall noise. amplitude *= persistence; } return total / max; } void Perlin::setSeed(uint newSeed) { seed = newSeed; shufflePermutations(); } // Interpolate to create a straight line between two points. // This is nested within itself in the noise function multiple times to correctly imitate // the full linear interpolation formula. float Perlin::lint(float t, float a, float b) { return a + ((b - a) * t); } // Fade applies an 'ease curve' to the gradients, which causes real numbers to tend towards integer values. // This helps to give a smoother appearance to the produced noise. float Perlin::fade(float t) { // Perlin's fade equation is 6t^5 - 15t^4 + 10t^3 return t * t * t * (t * (t * 6 - 15) + 10); } // Calculates dot product between pseudorandom (hashed) gradient vectors and the supplied point. // Works in terms of binary, producing values u and v according to the hash value (comparing to its most significant bits) // When applying gradients to 2D noise, z is always 0. float Perlin::gradient(int hash, float x, float y, float z) { int h = hash & 15; // (15 = 01111) so we take the first 4 digits of the hash float a; if (h < 8) a = x; // if most sig. bit of hash is 0 then u = x, otherwise y (8 = 01000) else a = y; float b; if (h < 4) { b = y; // 1st + 2nd sig. bits are 0, then v = y (4 = 00100) } else if (h == 12 || h == 14) { b = x; // 1st + 2nd sig. bits are 1 (12 = 01100, 14 = 01110) } else { b = z; // 1st + 2nd sig. bits are different } // If 2nd to last bit is 0, v is positive (2 = 00010) // If 2nd to last bit is 1, v is negative. if ((h & 2) != 0) { b = -b; } // If last bit is 0, u is positive (1 = 00001) // If last bit is 1, u is negative. if ((h & 1) != 0) { a = -a; } return a + b; } // Helper function to find the floor without fiddling with type casting (due to cmath floor returning a float) int Perlin::floor(float number) { int numberAsInt = (int)number; return (number >= numberAsInt) ? (numberAsInt) : (numberAsInt - 1); } // Shuffle the permutations vector using a random engine. A new permutations vector means new noise values // can be generated for the same set of coordinates. void Perlin::shufflePermutations() { // Use seed value to create a random "engine" that generates pseudorandom values default_random_engine shuffler(seed); // Create a new order of permutations by shuffling with the engine shuffle(permutations.begin(), permutations.end(), shuffler); // Now, as in default constructor, duplicate to create a 512 array. permutations.resize(512); for (int i = 0; i < 256; i++) { permutations[i + 256] = permutations[i]; } } }
Java
UTF-8
602
3.296875
3
[]
no_license
package cifrario; public class StefanoCifrario implements Cifrario { @Override public void cripta(String frase) { System.out.println("cifrato da Stefano " + frase); String stringaInput = ""; String[] stringaOutput = new String[100]; char Output; int i, n = 0, num = 2; stringaInput = frase; n = stringaInput.length(); for (i = 0; i < n; i++) { Output = stringaInput.charAt(i); Output = (char) (Output + num); stringaOutput[i] = "" + Output; } System.out.print("Ecco il tuo messaggio: "); for (i = 0; i < n; i++) { System.out.print(stringaOutput[i]); } } }
Markdown
UTF-8
806
2.609375
3
[]
no_license
# Astar Notes <small>βeta</small> ## Beautiful A levels notes for all subjects 🌈 Astar Notes contains the most awesome A levels notes compiled over generations of A levels students. ## Tech Stack - There's not much of a tech stack here 😅 - We are running on [Mkdocs](https://github.com/mkdocs/mkdocs) - The theme is [Mkdocs Material](https://github.com/squidfunk/mkdocs-material) - Notes are written in markdown in the /docs folder - For more information on how this whole thing work please checkout the [Mkdocs Material documentation](https://squidfunk.github.io/mkdocs-material/) ## Contributing - You can contribute notes by adding in the /docs folder - Submit a pull request & I will review it asap 😃 ## Questions? - [WhatsApp me by clicking this link](https://wa.me/6582186566) 👈
C#
UTF-8
1,898
3.4375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms.Sorting { public class MergeSort { protected IComparable[] auxArray = null; public void Sort(IComparable[] inputArray) { int length = inputArray.Length; auxArray = new IComparable[length]; Sort(inputArray, 0, length - 1); } private void Sort(IComparable[] inputArray,int startIndex,int endIndex) { if(startIndex >= endIndex) { return; } else { int midIndex = startIndex + (endIndex - startIndex) / 2; Sort(inputArray, startIndex, midIndex); Sort(inputArray, midIndex + 1, endIndex); Merge(inputArray, startIndex, midIndex, endIndex); } } protected void Merge(IComparable[] inputArray,int startIndex,int midIndex,int endIndex) { int subLeft = startIndex; int subRight = midIndex + 1; for(int i = startIndex;i <= endIndex;i++) { auxArray[i] = inputArray[i]; } for(int i=startIndex;i <= endIndex;i++) { if(subLeft > midIndex) { inputArray[i] = auxArray[subRight++]; } else if(subRight > endIndex) { inputArray[i] = auxArray[subLeft++]; } else if(auxArray[subLeft].CompareTo(auxArray[subRight]) <= 0) { inputArray[i] = auxArray[subLeft++]; } else { inputArray[i] = auxArray[subRight++]; } } } } }
PHP
UTF-8
1,216
2.90625
3
[]
no_license
<?php namespace Oip\RelevantProducts; class CompareFunctions { /** * @param RelevantSection $a * @param RelevantSection $b * @return int */ public static function compareCategoriesByWeight($a, $b) { return $b->getWeight() - $a->getWeight(); } /** * @param RelevantSection $a * @param RelevantSection $b * @return int */ public static function compareCategoriesByViews($a, $b) { return $b->getViewsCount() - $a->getViewsCount(); } /** * @param RelevantSection $a * @param RelevantSection $b * @return int */ public static function compareCategoriesByLikes($a, $b) { return $b->getLikesCount() - $a->getLikesCount(); } /** * @param RelevantProduct $a * @param RelevantProduct $b * @return int */ public static function compareProductsByViews($a, $b) { return $b->getViewsCount() - $a->getViewsCount(); } /** * @param RelevantProduct $a * @param RelevantProduct $b * @return int */ public static function compareProductsByLikes($a, $b) { return $b->getLikesCount() - $a->getLikesCount(); } }
C++
UTF-8
1,042
3.03125
3
[ "Apache-2.0" ]
permissive
#include "CPublisher.h" void Publisher::call(const char *arg1, int arg2) { for ( auto entry: subscribers ) { entry.second(arg1, arg2); } } void Publisher::clear() { subscribers.clear(); } size_t Publisher::getSize() { return subscribers.size(); } void Publisher::printSize() { std::cout << "Subscriber size: " << subscribers.size() << std::endl; } size_t Publisher::subscribe(std::function<void(const char *, int)> callback) { auto address = getAddress(callback); if (address == 0) { // std::function wraps a lambda address = getAddressLambda(callback); } subscribers.insert(std::make_pair(address, callback)); return address; } void Publisher::unsubscribe(std::function<void(const char *, int)> callback) { auto address = getAddress(callback); if (address == 0) { // std::function wraps lambda address = getAddressLambda(callback); } subscribers.erase(address); } void Publisher::unsubscribe(size_t address) { subscribers.erase(address); }
Java
UTF-8
3,159
2.34375
2
[]
no_license
package ch.sircremefresh.pages.departureboard; import ch.sircremefresh.controls.autocomplete.AutoCompleteController; import ch.sircremefresh.transport.TransportApiException; import ch.sircremefresh.transport.TransportService; import ch.sircremefresh.transport.dto.StationboardDto; import ch.sircremefresh.transport.dto.StationboardEntryDto; import ch.sircremefresh.util.InfoBox; import ch.sircremefresh.util.StationSearchAutoComplete; import ch.sircremefresh.util.TimeFormatter; import com.sun.javafx.scene.control.skin.BehaviorSkinBase; import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; public class DepartureBoardController { private TransportService transportService = new TransportService(); private ObservableList<StationboardEntryDto> stationboardEntries = FXCollections.observableArrayList(); @FXML private TableView<StationboardEntryDto> stationBoardTableView; @FXML private TableColumn<StationboardEntryDto, String> stationBoardTableFromColumn; @FXML private TableColumn<StationboardEntryDto, String> stationBoardTableToColumn; @FXML private TableColumn<StationboardEntryDto, String> stationBoardTableDepartureColumn; @FXML private AutoCompleteController stationSearchAutoComplete; @FXML public void initialize() { StationSearchAutoComplete.setupAutoComplete(stationSearchAutoComplete, transportService); initializeStationBoardTable(); } @FXML public void showStationBoard() { StationboardDto stationBoard; try { stationBoard = transportService.getStationboard(stationSearchAutoComplete.getText()); } catch (TransportApiException e) { InfoBox.show("error while getting station board", e.getMessage(), Alert.AlertType.ERROR); return; } catch (Throwable e) { InfoBox.show("something went wrong", "while getting stationboard", Alert.AlertType.ERROR); return; } stationboardEntries.clear(); stationboardEntries.addAll(stationBoard.getStationboard()); } private void initializeStationBoardTable() { stationBoardTableView.focusedProperty().addListener((arg0, oldVal, newVal) -> { ((BehaviorSkinBase) stationBoardTableView.getSkin()).getBehavior().traverseNext(); }); stationBoardTableView.setItems(stationboardEntries); stationBoardTableFromColumn.prefWidthProperty().bind(stationBoardTableView.widthProperty().divide(3)); stationBoardTableToColumn.prefWidthProperty().bind(stationBoardTableView.widthProperty().divide(3)); stationBoardTableDepartureColumn.prefWidthProperty().bind(stationBoardTableView.widthProperty().divide(3)); stationBoardTableFromColumn.setCellValueFactory(cd -> Bindings.createStringBinding(() -> cd.getValue().getStop().getStation().getName())); stationBoardTableToColumn.setCellValueFactory(cd -> Bindings.createStringBinding(() -> cd.getValue().getTo())); stationBoardTableDepartureColumn.setCellValueFactory(cd -> Bindings.createStringBinding(() -> TimeFormatter.getFormattedTime(cd.getValue().getStop().getDeparture()))); } }
C
UTF-8
3,748
3.125
3
[]
no_license
#include "headers.h" //invert sort order int comp(const void* i, const void* j) { TreeNode* arg1 = *((TreeNode**)i); TreeNode* arg2 = *((TreeNode**)j); return arg2->number - arg1->number; } void codding(FILE* input, FILE* output) { int SIZE_BUF = 512; unsigned char buf[512] = ""; int readed = 0; TreeNode** nodes = (TreeNode**)malloc(256 * sizeof(TreeNode*)); for (int i = 0; i < 256; i++) { nodes[i] = (TreeNode*)calloc(1, sizeof(TreeNode)); nodes[i]->symbol = i; } while ((readed = fread(buf, sizeof(unsigned char), SIZE_BUF, input)) > 0) { for (int i = 0; i < readed; i++) { nodes[buf[i]]->number++; } } qsort(nodes, 256, sizeof(TreeNode*), comp); int i = 0; for(i; i < 256; i++) { if(!nodes[i]->number) break; } int number_of_used_symbols = i; printf("number of u s %d\n", i); build_tree(nodes, number_of_used_symbols); Code* codes = create_codes(nodes); long size_of_start_file = ftell(input); fseek(input, 0, SEEK_SET); //writing //write number of used symbols unsigned char used_symb_char = (unsigned char)(number_of_used_symbols); fwrite(&used_symb_char, 1, 1, output); //write used symbols write_symbols(*nodes, output); //write tree BitWriter* writer = create_bit_writer(output); write_tree(*nodes, writer); //write data writing(input, writer, codes); //close_bit_writer(writer); //print quality info long soof = ftell(output); printf("compressed: %.3f\n", (soof / (size_of_start_file * 1.0))); } void write_symbols(TreeNode* tree, FILE* file) { if(tree->left) { write_symbols(tree->left, file); } if(tree->right) { write_symbols(tree->right, file); } if(!tree->right && ! tree->left) { fprintf(file, "%c", tree->symbol); } } void write_tree(TreeNode* tree, BitWriter* writer) { if(tree->left) { write_bit(writer, 0ULL); write_tree(tree->left, writer); } if(tree->right) { write_bit(writer, 1ULL); write_tree(tree->right, writer); } } void writing(FILE* input, BitWriter* writer, Code* codes) { printf("into writting\n"); int SIZE_BUF = 512; unsigned char buf[512] = ""; int readed = 0; while ((readed = fread(buf, sizeof(unsigned char), SIZE_BUF, input)) > 0) { //printf("into writting readed: %d\n", readed); for (int i = 0; i < readed; i++) { Code code = codes[buf[i]]; unsigned long long int masc = 1ULL << code.lenght - 1; for(int j = 0; j < code.lenght; j++) { unsigned long long int bit = code.code & masc; //printf("%d ", bit); write_bit(writer, bit); masc >>= 1; } } } close_bit_writer(writer); } Code* create_codes(TreeNode** nodes) { Code* codes = (Code*)calloc(256, sizeof(Code)); deep_went(*nodes, codes, 0, 0); return codes; } void deep_went(TreeNode* node, Code* codes, unsigned long long int code, int lenght) { if(node->left) { unsigned long long int new_code = (code << 1); deep_went(node->left, codes, new_code, lenght + 1); } if(node->right) { unsigned long long int new_code = (code << 1) | 1ULL; deep_went(node->right, codes, new_code, lenght + 1); } if(!node->right && !node->left) { //printf("into writting code lenght: %d\n", lenght); codes[node->symbol].lenght = lenght; codes[node->symbol].code = code; codes[node->symbol].symbol = node->symbol; } } void build_tree(TreeNode** nodes, int number_of_used_symbols) { int mass_size = number_of_used_symbols; for(int i = 0; i < number_of_used_symbols - 1; i++) { TreeNode* new_node = calloc(1, sizeof(TreeNode)); new_node->number = nodes[mass_size - 1]->number + nodes[mass_size - 2]->number; new_node->left = nodes[mass_size - 1]; new_node->right = nodes[mass_size - 2]; nodes[mass_size - 2] = new_node; mass_size--; qsort(nodes, mass_size, sizeof(TreeNode*), comp); } }
Java
UTF-8
290
1.953125
2
[]
no_license
package com.lzh.weatherforecast.bean; /** * Created by lzh on 2016/4/12. */ public class SideSlipInfo { public int resourceID; public String title; public SideSlipInfo(int resourceID, String title) { this.resourceID = resourceID; this.title = title; } }
Java
UTF-8
1,647
2.796875
3
[ "BSD-2-Clause" ]
permissive
package hr.fer.zemris.java.hw11.jnotepadpp.localization; import java.util.Objects; import javax.swing.AbstractAction; import javax.swing.Action; import hr.fer.zemris.java.hw11.jnotepadpp.JNotepadPP; /** * Class {@link LocalizableAction} is abstract class and it extends * {@link AbstractAction}. It doesn't specifies what happens in the method * {@link #actionPerformed(java.awt.event.ActionEvent)} and that is on the child * classes to implement. * * For more details see private attributes in the {@link JNotepadPP}. * * @author dario * */ public abstract class LocalizableAction extends AbstractAction { /** * */ private static final long serialVersionUID = 1L; /** * {@link ILocalizationListener} listeners on the localization changes in the * local provider */ private ILocalizationListener listener; /** * Constructs {@link LocalizableAction} with the key used for translation, and * local provider which offers the translation. * * @param key * key for translation * @param localProvider * local provider */ public LocalizableAction(String key, ILocalizationProvider localProvider) { Objects.requireNonNull(key); Objects.requireNonNull(localProvider); listener = new ILocalizationListener() { public void localizationChanged() { putValue(NAME, localProvider.getString(key)); putValue(Action.SHORT_DESCRIPTION, localProvider.getString(key + "DES")); } }; localProvider.addLocalizationListener(listener); } }
Java
UTF-8
725
3.1875
3
[]
no_license
package debug.employees; import java.util.ArrayList; import java.util.List; public class Company { private List<Employee> company; public Company(List<Employee> company) { this.company = company; } public void addEmployee(Employee e) { company.add(e); } public Employee findEmployeeByName(String name) { for (Employee e: company) { if (name.equalsIgnoreCase(e.getName())) { return e; } } return null; } public List<String> listEmployeeNames() { List<String> names = new ArrayList<>(); for (Employee e: company) { names.add(e.getName()); } return names; } }
C++
UTF-8
5,242
3
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <strstream> #include <memory> typedef long long int lint; struct dp_cache { char op; lint op_pos; lint cost; dp_cache(char o, lint pos, lint c) : op{ o }, op_pos{ pos }, cost{ c } {} dp_cache() : op{ 0 }, op_pos{ 0 }, cost{ 0 } {} }; void generate_max_and_min_cache( lint head, lint tail, const std::vector<lint> & number_array, std::vector<std::vector<dp_cache>> & max_cache, std::vector<std::vector<dp_cache>> & min_cache) { if (head == tail) { max_cache[head][tail].cost = number_array[head]; max_cache[head][tail].op_pos = head; max_cache[head][tail].op = 0; return; } lint max = std::numeric_limits<lint>::min(); lint min = std::numeric_limits<lint>::max(); for (lint k = head; k < tail; ++k) { lint max_sum = max_cache[head][k].cost + max_cache[k + 1][tail].cost; lint min_sum = min_cache[head][k].cost + min_cache[k + 1][tail].cost; lint max_sub = max_cache[head][k].cost - min_cache[k + 1][tail].cost; lint min_sub = min_cache[head][k].cost - max_cache[k + 1][tail].cost; lint max_mul = std::max( max_cache[head][k].cost * max_cache[k + 1][tail].cost, min_cache[head][k].cost * min_cache[k + 1][tail].cost); lint min_mul = std::min( max_cache[head][k].cost * max_cache[k + 1][tail].cost, min_cache[head][k].cost * min_cache[k + 1][tail].cost); if (max_sum > max) { max = max_sum; max_cache[head][tail].cost = max; max_cache[head][tail].op = '+'; max_cache[head][tail].op_pos = k; } if (max_sub > max) { max = max_sub; max_cache[head][tail].cost = max; max_cache[head][tail].op = '-'; max_cache[head][tail].op_pos = k; } if (max_mul > max) { max = max_mul; max_cache[head][tail].cost = max; max_cache[head][tail].op = '*'; max_cache[head][tail].op_pos = k; } if (min_sum < min) { min = min_sum; min_cache[head][tail].cost = min; min_cache[head][tail].op = '+'; min_cache[head][tail].op_pos = k; } if (min_sub < min) { min = min_sub; min_cache[head][tail].cost = min; min_cache[head][tail].op = '-'; min_cache[head][tail].op_pos = k; } if (min_mul < min) { min = min_mul; min_cache[head][tail].cost = min; min_cache[head][tail].op = '*'; min_cache[head][tail].op_pos = k; } } } struct tree_node { char op; lint number; std::shared_ptr<tree_node> left_child; std::shared_ptr<tree_node> right_child; tree_node(char o, lint n): op{ o }, number{ n }, left_child{ nullptr }, right_child{ nullptr } {} }; std::ostream & operator << (std::ostream & out, const std::shared_ptr<tree_node> & node) { if (node == nullptr) { return out; } if (node->op != 0) { out << "("; out << node->left_child; out << node->op; out << node->right_child; out << ")"; } else { if (node->number < 0) { out << "("; } out << node->number; if (node->number < 0) { out << ")"; } } return out; } void find_solution( lint head, lint tail, const std::vector<std::vector<dp_cache>> & cache, const std::vector<lint> & number_array, std::shared_ptr<tree_node> & current) { if (0 == cache[head][tail].op) { current = std::make_shared<tree_node>(0, number_array[head]); return; } else { current = std::make_shared<tree_node>(cache[head][tail].op, 0); } find_solution(head, cache[head][tail].op_pos, cache, number_array, current->left_child); find_solution(cache[head][tail].op_pos + 1, tail, cache, number_array, current->right_child); } std::shared_ptr<tree_node> operator_max(const std::vector<lint> & number_array) { std::vector<std::vector<dp_cache>> max_cache; std::vector<std::vector<dp_cache>> min_cache; for (lint i = 0; i < number_array.size(); ++i) { max_cache.push_back(std::vector<dp_cache>{ number_array.size() }); min_cache.push_back(std::vector<dp_cache>{ number_array.size() }); } for (lint size = 0; size < number_array.size(); ++size) { for (lint head = 0, tail = size; head < number_array.size() && tail < number_array.size(); ++head, ++tail) { generate_max_and_min_cache(head, tail, number_array, max_cache, min_cache); } } std::shared_ptr<tree_node> solution_root; find_solution(0, number_array.size() - 1, max_cache, number_array, solution_root); return solution_root; } int main() { const std::vector<lint> number_array = { -9, -8, 7, 6, 5, 4, -3, 2, 1, 0 }; std::cout << operator_max(number_array) << "\n"; }
PHP
UTF-8
3,599
2.890625
3
[]
no_license
<?php include "header.php"; ?> <div id="content"> <div id="nav"> <h3>Navigation </h3> <ul> <li><a href="createUser.php">Create New User</a></li> </ul> </div> <div id="main"> <?php /***************************** HANDLING CLIENT LOGOUT *******************************/ if(isset($_POST['logout'])) { $_SESSION = array(); session_destroy(); ?> <!-- Once we start outputting HTML, we can no longer do anything involving headers --> <h1>Thank You for Visting</h1> <?php } /************************** HANDLING CLIENT LOGIN ATTEMPT ***************************/ if((isset($_POST['username'])) &&(isset($_POST['password'])) &&(isset($_POST['loginbutton']))) { // Begin by attempting to connect to the database containing the users try { $db = new PDO("mysql:host=localhost;dbname=gillilandr", "gillilandr", "12345"); } catch (Exception $error) { //If attempt failed, send error die("Connection to user database failed: " . $error->getMessage()); } // Now, let's try to access the database table containing the users try { $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT * FROM poll_users WHERE username = :user and password = :pw"; $statement = $db -> prepare($query); $statement -> execute(array( 'user' => $_POST['username'], 'pw' => md5($_POST['password'])) ); if ($statement -> rowCount() == 1) { $_SESSION['loggedin']=TRUE; // Get the user details from the SINGLE returned database row $row = $statement -> fetch(); $_SESSION['firstname'] = $row['given_name']; $_SESSION['lastname'] = $row['family_name']; $_SESSION['username'] = $row['username']; $_SESSION['email'] = $row['email']; $_SESSION['id'] = $row['id']; $_SESSION['password'] = $row['password']; } else echo("<h3>Invalid userid or password</h3><h3>A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools. </h3>"); // Close the statement and the database $statement = null; $db = null; } catch (Exception $error) { echo "Error occurred accessing user privileges: " . $error->getMessage(); } } /*********************** PRESENTING CLIENT WITH LOGIN SCREEN ************************/ if(!isset($_SESSION['loggedin'])) { ?> <h2>Login</h2> <div id="form"> <form name='login' method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'> <input type='text' name='username' placeholder='Username'/><br /> <input type='password' name='password' placeholder='Password'/><br /> <input type='submit' name='loginbutton' value='Click here to log in' /> </form> </div> <?php } /****************** PRESENTING LOGGED IN CLIENT WITH BASIC SCREEN *******************/ if(isset($_SESSION['loggedin'])) { ?> <!-- Place HTML here for the client page --> <h2> Welcome, <?= $_SESSION['firstname'] ?> <?= $_SESSION['lastname'] ?> to the<br> voting poll<br> </h2> <div id="form"> <form name='home' method='post' action='main.php'> <input type='submit' value='View Polls' name='home'> </form> <form name='home' method='post' action='createPoll.php'> <input type='submit' value='Create a Poll' name='home'> </form> <form name='logout' method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>' > <input type='submit' value='Click to logout' name='logout'> </form> </div> <?php } include "footer.php"; ?>
PHP
UTF-8
707
2.515625
3
[ "MIT" ]
permissive
<?php namespace Rossina\Repositories\Transformers; use League\Fractal\TransformerAbstract; use Rossina\Etiqueta; /** * Class EtiquetaTransformer * @package namespace Rossina\Repositories/Transformers; */ class EtiquetaTransformer extends TransformerAbstract { public function transform(Etiqueta $model) { return [ 'id' => (int) $model->id, 'name' => $model->name, 'description' => $model->description, 'url_pdf' => $model->url_pdf, 'active' => (boolean) $model->active, 'created_at' => $model->created_at, 'updated_at' => $model->updated_at ]; } }
JavaScript
UTF-8
7,336
2.609375
3
[]
no_license
import React, { Component } from "react"; import "./styles/Consultas.css"; class ConsultaPacientes extends Component { constructor(props) { super(props); this.state = { arrPacientes : [], arrDomicilios : [] } } cargarPacientes = () => { fetch("/pacientes") .then((response) => response.json()) .then((data) => { this.setState({ arrPacientes: data }) }) } cargarDomicilios = () => { fetch("/domicilios") .then((response) => response.json()) .then((data) => { this.setState({ arrDomicilios: data }) }) } componentDidMount() { this.cargarPacientes(); this.cargarDomicilios(); } eliminarPaciente = (evt) => { if(window.confirm("Seguro que desea eliminar el paciente con id: " + evt.target.id + "?")) { fetch("/pacientes/" + evt.target.id, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "DELETE" }) alert("Paciente eliminado!"); this.cargarPacientes(); this.cargarDomicilios(); } else { alert("Operacion cancelada!") } } mostrarEdicionPaciente = (evt) => { let form = document.getElementById("id_form_editar_paciente_" + evt.target.id); let thEditar = document.getElementById("th_editar_paciente_"); console.log("Voy a editar al id: " + evt.target.id); if (form.style.display === "none") { form.style.display = "block"; thEditar.style.display = "block"; } else { form.style.display = "none"; thEditar.style.display = "none"; } console.log("Muestro o escondo el form con id: " + evt.target.id); } editarPaciente = (evt) => { let datos = {}; let domicilio = {}; datos.id = evt.target.id; datos.nombre = document.getElementById("nombre_paciente_" + evt.target.id).value; datos.apellido = document.getElementById("apellido_paciente_" + evt.target.id).value; datos.dni = document.getElementById("dni_" + evt.target.id).value; datos.fechaIngreso = document.getElementById("fechaIngreso_" + evt.target.id).value; datos.domicilio = domicilio; datos.domicilio.id = evt.target.id; datos.domicilio.calle = document.getElementById("calle_" + evt.target.id).value; datos.domicilio.numero = document.getElementById("numero_" + evt.target.id).value; datos.domicilio.localidad = document.getElementById("localidad_" + evt.target.id).value; datos.domicilio.provincia = document.getElementById("provincia_" + evt.target.id).value; console.log(datos); fetch("/pacientes/" + evt.target.id, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "PUT", body: JSON.stringify(datos) }) alert("Paciente con id: " + evt.target.id +" editado!") this.mostrarEdicionPaciente(evt); this.cargarPacientes(); this.cargarDomicilios(); } formatDate(date) { let fecha = new Date(date); return fecha.toLocaleString("es-AR"); } render() { return ( <div> {/* Tabla de pacientes */} <div> <h2>Tabla de Pacientes</h2> <table class="table table-bordered" id="pacientes"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Nombre</th> <th scope="col">Apellido</th> <th scope="col">DNI</th> <th scope="col">Domicilio_ID</th> <th scope="col">Fecha Ingreso</th> <th scope="col">Acciones</th> <th id="th_editar_paciente_" style={{display: "none"}} scope="col">Editar datos</th> </tr> </thead> <tbody> {this.state.arrPacientes.map((paciente, i) => { return ( <tr> <td>{paciente.id}</td> <td>{paciente.nombre} </td> <td>{paciente.apellido}</td> <td>{paciente.dni}</td> <td>{paciente.domicilio.id}</td> <td>{this.formatDate(paciente.fechaIngreso)}</td> <td style={{width: "25%"}}> <button id={paciente.id} class="btn btn-danger" onClick={this.eliminarPaciente}>Eliminar</button> <button id={paciente.id} class="btn btn-info" onClick={this.mostrarEdicionPaciente}>Editar</button> </td> <div id={"id_form_editar_paciente_" + paciente.id} class="form_update" style={{display: "none"}}> <form> <input style={{backgroundColor: "#989b9c"}} class="entrada" id="ID" type="text" name="ID" value={paciente.id} readOnly/> <input class="entrada" id={"nombre_paciente_" + paciente.id} type="text" name="nombre" placeholder={paciente.nombre} /> <input class="entrada" id={"apellido_paciente_" + paciente.id} type="text" name="apellido" placeholder={paciente.apellido} /> <input class="entrada" id={"dni_" + paciente.id} type="number" name="matricula" placeholder={paciente.dni} /> <input class="entrada" id={"fechaIngreso_" + paciente.id} type="datetime-local" name="fechaIngreso" placeholder={paciente.fechaIngreso} /> <input class="entrada" id={"calle_" + paciente.id} type="text" name="calle" placeholder={paciente.domicilio.calle} /> <input class="entrada" id={"numero_" + paciente.id} type="text" name="numero" placeholder={paciente.domicilio.numero} /> <input class="entrada" id={"localidad_" + paciente.id} type="text" name="localidad" placeholder={paciente.domicilio.localidad} /> <input class="entrada" id={"provincia_" + paciente.id} type="text" name="provincia" placeholder={paciente.domicilio.provincia} /> <input class="resetear" type="reset" value="Reiniciar" /> <input id={paciente.id} onClick={this.editarPaciente} class="entrar" type="button" value="Confirmar" /> </form> </div> </tr> ) })} </tbody> </table> </div> {/* Tabla de domicilios */} <div> <h2>Tabla de Domicilios</h2> <table class="table table-bordered" id="domicilios"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Calle</th> <th scope="col">Numero</th> <th scope="col">Localidad</th> <th scope="col">Provincia</th> </tr> </thead> <tbody> {this.state.arrDomicilios.map((domicilio, i) => { return ( <tr> <td>{domicilio.id}</td> <td>{domicilio.calle} </td> <td>{domicilio.numero}</td> <td>{domicilio.localidad}</td> <td>{domicilio.provincia}</td> </tr> ) })} </tbody> </table> </div> </div> ); } } export default ConsultaPacientes;
PHP
UTF-8
862
2.671875
3
[ "MIT" ]
permissive
<?php /* * This file is part of the php-ActiveResource. * (c) 2010 Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace ActiveResource\Resources; use ActiveResource\Connections\Connection; /** * Resource implements reource holder interface. * * @package ActiveResource * @subpackage managers * @author Konstantin Kudryashov <ever.zet@gmail.com> * @version 1.0.0 */ class ActiveResource { protected $resource_class; protected $connection; public function __construct($class, Connection $connection) { $this->resource_class = $class; $this->connection = $connection; } public function __call($func, array $args) { $args[] = $this->connection; return call_user_func_array(array($this->resource_class, $func), $args); } }
Java
UTF-8
688
1.914063
2
[]
no_license
package com.zmy.dao.stat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.List; import java.util.Map; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/applicationContext-dao.xml") public class test { @Autowired private StatDao statDao; @Test public void selectById(){ List<Map<String, Object>> list = statDao.factorySale(); System.out.println("list = " + list); } }
Java
UTF-8
1,367
2.03125
2
[ "Apache-2.0" ]
permissive
package com.dawnlightning.zhai.fragment.imagelist; import android.os.Bundle; import com.dawnlightning.zhai.adapter.imagelistadapter.NormalImageListAdaper; import com.dawnlightning.zhai.base.Actions; import com.dawnlightning.zhai.bean.ImageListBean; import com.dawnlightning.zhai.fragment.BaseFragment; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/5/9. */ public class BeautifyLegImagesFragement extends BaseFragment { private List<ImageListBean> imageListBeanList =new ArrayList<>(); public static BeautifyLegImagesFragement newInstance(Bundle data) { BeautifyLegImagesFragement beautifyLegImagesFragement =new BeautifyLegImagesFragement(); beautifyLegImagesFragement.setArguments(data); return beautifyLegImagesFragement; } @Override public void initAdapter() { adapter= new NormalImageListAdaper(getActivity()); adapter.setList(imageListBeanList); } @Override public void Refresh(int page, Actions action) { imageListPresenter.loadBeatifyLegList(page,action); } @Override public void LoadMore(int page, Actions action) { imageListPresenter.loadBeatifyLegList(page,action); } @Override public void GoTo(int page, Actions action) { imageListPresenter.loadBeatifyLegList(page,action); } }
Python
UTF-8
487
2.734375
3
[]
no_license
from django.db import models # Create your models here. # las tablas son clases class Prueba(models.Model): titulo = models.CharField(max_length=30) #CHARFIELD = TEXTO subtitulo = models.CharField( max_length=50) #mcchar + tab crea directamente el CharField cantidad = models.IntegerField() #mint + tab crea IntegrerField def __str__(self): #metodo string para los objetos para poder mostrarlos return self.titulo + ' ' + self.subtitulo #+ self.cantidad
Java
UTF-8
183
2.6875
3
[]
no_license
package abstractfactory.src; public class Arch extends Weapon{ @Override void shoot() { System.out.println("我是具体的武器Arch,继承自Weapon."); } }
Python
UTF-8
1,613
2.671875
3
[ "MIT" ]
permissive
from tqdm import tqdm import ipdb, json, random, csv, torch def read_file(path, mode='train'): with open(path) as f: data = json.load(f) if mode == 'train': data = data[mode] data = [[''.join(j.split()) for j in i] for i in data] responses = [i[-1] for i in data] dialogs = [] for i in tqdm(data): i = [''.join(j.split()) for j in i] if mode == 'train': neg = random.choice(responses) dialogs.append((i, i[:-1] + [neg])) else: neg = [i[:-1] + [j] for j in random.sample(responses, 9)] dialogs.append((i, neg)) return dialogs def write_file(dataset, path, mode='train'): with open(path, 'w') as f: for data in tqdm(dataset): pos_data, neg_data = data pos_data = '\t'.join(pos_data) if mode == 'train': neg_data = '\t'.join(neg_data) f.write(f'1\t{pos_data}\n') f.write(f'0\t{neg_data}\n') else: neg_data = ['\t'.join(i) for i in neg_data] f.write(f'1\t{pos_data}\n') for i in neg_data: f.write(f'0\t{i}\n') if __name__ == '__main__': seed = 50 random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) train_cut_size = 2000000 dataset = read_file('LCCC-base.json', mode='train') dataset = random.sample(dataset, train_cut_size) write_file(dataset, 'train.txt', mode='train')
Python
UTF-8
276
2.703125
3
[]
no_license
#import sys #input = sys.stdin.readline def main(): K, S = map(int,input().split()) ans = 0 for i in range(K+1): for j in range(K+1): if i+j <= S and S - (i+j) <= K: ans += 1 print(ans) if __name__ == '__main__': main()
SQL
UTF-8
739
2.984375
3
[]
no_license
create table costumer ( uuid char(36) primary key not null, full_name text not null ); create table session ( id serial, costumer_uuid char(36) not null references costumer (uuid) on delete cascade, from_num_to_num text not null, ip varchar(15) not null, end_time timestamp not null ); create table if not exists costumer_card ( id serial, full_name text not null, costumer_mac text not null, service_mac text not null, pillar_number integer not null, onu_number integer not null, ip varchar(15) not null );
Python
UTF-8
564
3.53125
4
[]
no_license
import sys from itertools import groupby from operator import itemgetter def tokenize_input(): """Split each line of standard input into a key and a value.""" for line in sys.stdin: yield line.split('\t') # produce key-value pairs of word lengths and counts separated by tabs for word_length, group in groupby(tokenize_input(), itemgetter(0)): try: total = sum(int(count) for word_length, count in group) print(word_length + '\t' + str(total)) except ValueError: pass # ignore word if its count was not an integer
C#
UTF-8
1,967
3
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoDamasIng { //La clase ficha se encarga de guardar los valores de la posición de una ficha en específico así como las distintas direcciones hacia las cuales puede moverse o comer class Ficha { protected string color; protected int fila; protected int columna; protected List<Ficha> posiblesMov; protected List<Ficha> posiblesComer; public Ficha(string color, int fila, int columna) { this.color = color; this.fila = fila; this.columna = columna; this.posiblesMov = new List<Ficha>(); this.posiblesComer = new List<Ficha>(); } public Ficha(int fila, int columna) { this.color = ""; this.fila = fila; this.columna = columna; this.posiblesMov = new List<Ficha>(); this.posiblesComer = new List<Ficha>(); } public int Fila { get { return this.fila; } } public int Columna { get { return this.columna; } } public string Color { get { return this.color; } } //PosiblesMov se encarga de regresar un arreglo conteniendo los distintos espacios a los cuales la ficha se puede mover //el resultado arrojado varía segun la posición de la ficha public virtual List<Ficha> PosiblesMov() { return this.posiblesMov; } //PosiblesComer se encarga de regresar un arreglo conteniendo los distintos espacios a los cuales la ficha se puede mover para comer //el resultado arrojado varía segun la posición de la ficha public virtual List<Ficha> PosiblesComer() { return this.posiblesComer; } } }
Java
UTF-8
2,254
2.0625
2
[ "Apache-2.0", "LicenseRef-scancode-dco-1.1" ]
permissive
package org.infinispan.client.hotrod.impl.multimap.operations; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_ENTRY_MULTIMAP_REQUEST; import static org.infinispan.client.hotrod.impl.multimap.protocol.MultimapHotRodConstants.REMOVE_ENTRY_MULTIMAP_RESPONSE; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import net.jcip.annotations.Immutable; import org.infinispan.client.hotrod.configuration.Configuration; import org.infinispan.client.hotrod.impl.ClientStatistics; import org.infinispan.client.hotrod.impl.ClientTopology; import org.infinispan.client.hotrod.impl.protocol.HotRodConstants; import org.infinispan.client.hotrod.impl.transport.netty.ChannelFactory; import org.infinispan.client.hotrod.impl.transport.netty.HeaderDecoder; /** * Implements "remove" for multimap as defined by <a href="http://community.jboss.org/wiki/HotRodProtocol">Hot Rod * protocol specification</a>. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Immutable public class RemoveEntryMultimapOperation extends AbstractMultimapKeyValueOperation<Boolean> { public RemoveEntryMultimapOperation(ChannelFactory channelFactory, Object key, byte[] keyBytes, byte[] cacheName, AtomicReference<ClientTopology> clientTopology, int flags, Configuration cfg, byte[] value, ClientStatistics clientStatistics, boolean supportsDuplicates) { super(REMOVE_ENTRY_MULTIMAP_REQUEST, REMOVE_ENTRY_MULTIMAP_RESPONSE, channelFactory, key, keyBytes, cacheName, clientTopology, flags, cfg, value, -1, TimeUnit.MILLISECONDS, -1, TimeUnit.MILLISECONDS, null, clientStatistics, supportsDuplicates); } @Override protected void executeOperation(Channel channel) { scheduleRead(channel); sendKeyValueOperation(channel); } @Override public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (HotRodConstants.isNotExist(status)) { complete(Boolean.FALSE); } else { complete(buf.readByte() == 1 ? Boolean.TRUE : Boolean.FALSE); } } }
C
UTF-8
898
3.1875
3
[]
no_license
#include <stdio.h> #include <pthread.h> #include <time.h> #include <sys/times.h> #include <unistd.h> void print1(); void print2(); void busy_wait_delay(int seconds); int main(){ pthread_t thread1, thread2; pthread_create(&thread1, NULL, print1, NULL); pthread_create(&thread2, NULL, print2, NULL); pthread_join( thread1, NULL); pthread_join( thread2, NULL); return 0; } void print1(){ printf("Thread 1 - 1\n"); busy_wait_delay(5); printf("Thread 1 - 2\n"); return; } void print2(){ printf("Thread 2 - 1\n"); busy_wait_delay(5); printf("Thread 2 - 2\n"); return; } void busy_wait_delay(int seconds) { int i, dummy; int tps = sysconf(_SC_CLK_TCK); clock_t start; struct tms exec_time; times(&exec_time); start = exec_time.tms_utime; while( (exec_time.tms_utime - start) < (seconds * tps)) { for(i=0; i<1000; i++) { dummy = i; } times(&exec_time); } }
Python
UTF-8
1,189
2.78125
3
[ "MIT" ]
permissive
from elasticsearch6 import Elasticsearch class Document(object): def __init__(self, id, title, abstract, text): self.id = id self.title = title self.abstract = abstract self.text = text class Elastic(object): def __init__(self, url, index): self.elastic_url = url self.index = index self.es = Elasticsearch([url]) def get(self, query): res = self.es.search( index=self.index, body={ 'query': { 'multi_match': { 'query': query, 'fields': ['title', 'text'] } } } ) items = res['hits']['hits'] documents = [] for doc in items: try: id = doc['_id'] title = doc['_source']['title'] abstract = doc['_source']['opening_text'] text = doc['_source']['text'] new_doc = Document(id, title, abstract, text) documents.append(new_doc) except: pass return documents
Java
UTF-8
1,829
2.078125
2
[ "MIT" ]
permissive
package com.futao.springbootdemo.foundation.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.annotation.Resource; import javax.sql.DataSource; //@Configuration //@EnableTransactionManagement /** * @author futao * Created on ${date}. */ public class HibernateConfiguration { @Resource private DataSource dataSource; @Value("${spring.jpa.entitymanager.packagesToScan}") private String packageToScan; @Value("${spring.jpa.properties.hibernate.dialect}") private String dialect; @Value("${spring.jpa.show-sql}") private Boolean showSql; // @Value("${spring.jpa.hibernate.hbm2ddl.auto}") // private String hb2ddlAuto; // // @Bean // public LocalSessionFactoryBean sessionFactory() { // LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); // sessionFactory.setDataSource(dataSource); // sessionFactory.setPackagesToScan(); // sessionFactory.setPackagesToScan(packageToScan); // Properties hibernateProperties = new Properties(); // hibernateProperties.put("hibernate.dialect", dialect); // hibernateProperties.put("hibernate.show_sql", showSql); // hibernateProperties.put("hibernate.hbm2ddl.auto", hb2ddlAuto); // sessionFactory.setHibernateProperties(hibernateProperties); // return sessionFactory; // } /** * 事物管理器配置 * * @return */ // @Bean public PlatformTransactionManager transactionManage() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setDataSource(dataSource); return transactionManager; } }
PHP
UTF-8
1,207
2.765625
3
[]
no_license
<?php if (!defined('BASEPATH')) {exit('No direct script access allowed');} class LineupPlayer extends Document { protected $player; protected $position; protected $order; public function __construct() { parent::__construct(); } public function getPlayer() { if (is_array($this->player)) { $results = $this->mongo ->get_dbref($this->player); $this->load->model('PlayerRepository', '_player'); return $this->_player->assign($results); } return $this->player; } public function setPlayer($player) { if (is_object($player)) { $player = $this->mongo ->create_dbref('player', $player->getId()); } $this->player = $player; } public function getPosition() { return $this->position; } public function setPosition($position) { $this->position = $position; } public function getOrder() { return $this->order; } public function setOrder($order) { $this->order = $order; } }
Java
UTF-8
422
2.203125
2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.cafejojo.schaapi.miningpipeline.usagegraphgenerator.jimple.testclasses.users; import org.cafejojo.schaapi.miningpipeline.usagegraphgenerator.jimple.testclasses.library.Object1; public class SimpleTest { public Object1 test() { String a = new String("a"); String b = new String("b"); Object1 o = new Object1(); o.m2(b); a.substring(1); return o; } }
C#
UTF-8
1,262
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using JargeEngine.Graphics; namespace JargeEngine { public class GUIComponent { public Vector2 Position = default(Vector2); public string Name = ""; public bool Visible = true; public bool Active = true; public float Rotation; public List<Graphic> graphics = new List<Graphic>(); public float X { get { return this.Position.X; } set { this.Position.X = value; } } public float Y { get { return this.Position.Y; } set { this.Position.Y = value; } } public virtual void Begin() { } public virtual void Update() { } public virtual void Remove() { } public virtual void Draw() { for (int i = 0; i < graphics.Count; i++) { graphics[i].Draw(); } } public void AddGraphic(Graphic g) { graphics.Add(g); } public void RemoveGraphic(Graphic g) { graphics.Remove(g); } } }
SQL
UTF-8
809
3.0625
3
[]
no_license
DROP DATABASE IF EXISTS tinder_clone; CREATE DATABASE tinder_clone; USE tinder_clone; CREATE TABLE user_account ( id BIGINT NOT NULL AUTO_INCREMENT, user_email VARCHAR(255) NOT NULL, user_password VARCHAR(255) NOT NULL, user_full_name VARCHAR(255) NOT NULL, user_age INT NOT NULL, user_avatar VARCHAR(255) NOT NULL, user_gender VARCHAR(255) NOT NULL, user_cometchat_uid VARCHAR(255) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE match_request ( id BIGINT NOT NULL AUTO_INCREMENT, match_request_from VARCHAR(255) NOT NULL, match_request_to VARCHAR(255) NOT NULL, match_request_sender VARCHAR(255) NOT NULL, match_request_receiver VARCHAR(255) NOT NULL, match_request_status INT NOT NULL, created_date DATETIME NULL DEFAULT CURRENT_TIMESTAMP, accepted_date DATETIME NULL, PRIMARY KEY (id) );
Go
UTF-8
993
2.671875
3
[]
no_license
package server import ( "fmt" "os" "os/signal" "github.com/rayhaanbhikha/file_share/packages/utils" ) const standardPort = "8080" const dataPort = "8081" const defaultIPAddress = "0.0.0.0" func handleErr(err error) { if err != nil { fmt.Println(err) os.Exit(1) } } func Run(filePath string) { // Validate file. file := NewFile(filePath) err := file.Init() if err != nil { file.HandleError(err) return } // ############################################# ip, err := utils.GetIPv4Address() if err != nil { panic(err) } hub := NewHub(file, ip.String(), standardPort, dataPort) go hub.Run() defer hub.Close() signalChannel := make(chan os.Signal) signal.Notify(signalChannel, os.Interrupt) standardTCPConnection := NewTCPConnection(defaultIPAddress, standardPort, "Standard") dataTCPConnection := NewTCPConnection(defaultIPAddress, dataPort, "Data") go standardTCPConnection.Run(hub) go dataTCPConnection.Run(hub) s := <-signalChannel fmt.Println(s) }