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
C++
UTF-8
3,055
2.734375
3
[ "BSL-1.0" ]
permissive
/////////////////////////////////////////////////////////////////////////////// // Copyright Christopher Kormanyos 2007 - 2014. // Distributed under the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef _RING_ALLOCATOR_2010_02_23_H_ #define _RING_ALLOCATOR_2010_02_23_H_ #include <cstddef> #include <cstdint> #include <memory> namespace util { class ring_allocator_base { public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; protected: ring_allocator_base() { } // The ring_allocator's memory allocation. static void* do_allocate(const size_type size); // The ring_allocator's default buffer size. static const size_type buffer_size = 256U; private: static volatile std::uint8_t buffer[buffer_size]; static volatile std::uint8_t* get_ptr; }; // Global comparison operators (required by the standard). inline bool operator==(const ring_allocator_base&, const ring_allocator_base&) throw() { return true; } inline bool operator!=(const ring_allocator_base&, const ring_allocator_base&) throw() { return false; } template<typename T> class ring_allocator; template<> class ring_allocator<void> : public ring_allocator_base { public: typedef void value_type; typedef value_type* pointer; typedef const value_type* const_pointer; template <class U> struct rebind { typedef ring_allocator<U> other; }; }; template<typename T> class ring_allocator : public ring_allocator_base { public: typedef T value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; ring_allocator() throw() { } ring_allocator(const ring_allocator&) throw() { } template <class U> ring_allocator(const ring_allocator<U>&) throw() { } template<class U> struct rebind { typedef ring_allocator<U> other; }; size_type max_size() const throw() { return buffer_size / sizeof(size_type); } pointer address( reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(size_type num, ring_allocator<void>::const_pointer = nullptr) { const size_type chunk_size = num * sizeof(value_type); void* p = do_allocate(chunk_size); return static_cast<pointer>(p); } void construct(pointer p, const value_type& x) { new(static_cast<void*>(p)) value_type(x); } void destroy(pointer p) { p->~value_type(); } void deallocate(pointer, size_type) { } }; } #endif // _RING_ALLOCATOR_2010_02_23_H_
Swift
UTF-8
5,278
2.734375
3
[]
no_license
// // JSONView.swift // wusi-ios // // Created by James Tang on 12/9/14. // Copyright (c) 2014 Wusi. All rights reserved. // import UIKit @objc protocol JsonAttributeAssignable { func setAttribute(value:AnyObject, forKey key:String) } extension UIView { func assignDictionary(dict: [String:AnyObject], recursiveLevel: Int) { if recursiveLevel != 0 { for view in self.subviews { let view = view as UIView view.assignDictionary(dict, recursiveLevel:recursiveLevel - 1) } } for (key, value) in dict { if let s = self as? JsonAttributeAssignable { s.setAttribute(value, forKey:key) } else if self.respondsToSelector(Selector(key)) { println("key: \(key) = \(value)") self.setValue(value, forKeyPath:key) // println("view \(self) setting value '\(value) for '\(key)'") } else { // println("view \(self) not responds to selector '\(key)'") } } } } @IBDesignable class JSONView : UIView { @IBInspectable var load : String? @IBInspectable var identifier : String? @IBInspectable var recursiveLevel : NSNumber? = 1 func commonInit() { if let load = load { self.assignDictionary(JSONLoader(name: load).json as [String:AnyObject], recursiveLevel: 1) } } override func awakeFromNib() { self.commonInit() } override func prepareForInterfaceBuilder() { self.commonInit() } override func assignDictionary(dict: [String : AnyObject], recursiveLevel: Int) { if let identifier = identifier { if let info : AnyObject? = dict[identifier] { if let info = info as? [String : AnyObject] { super.assignDictionary(info, recursiveLevel: self.recursiveLevel ?? recursiveLevel) } } } else { super.assignDictionary(dict, recursiveLevel: self.recursiveLevel ?? recursiveLevel) } } } class JSONLabel : UILabel { @IBInspectable var identifier : String? override func setValue(value: AnyObject!, forKey key: String!) { if key == identifier { super.setValue(value, forKey: "text") } else { super.setValue(value, forKey: key) } } } protocol JSONSource { var json : [String:AnyObject]? {get} } protocol JSONDestination : JSONSource { var json : [String:AnyObject]? {set get} } class JSONViewController: UIViewController, JSONDestination { var json : [String:AnyObject]? override func viewDidLoad() { super.viewDidLoad() self.view.assignDictionary(json!, recursiveLevel: 1) } } @IBDesignable class JSONTableView : UITableView, UITableViewDataSource { var sections : [String]? var info : NSMutableDictionary? = NSMutableDictionary() override func awakeFromNib() { self.dataSource = self } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let identifier = sections?[section] { let data = info?[identifier] as NSDictionary let ids = data["rows"] as [String] return ids.count } return 0 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { let count = sections?.count ?? 0 println("count: \(count)") return count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = sections?[indexPath.section] ?? "cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell let scope = info?[cellIdentifier] as NSDictionary let rows = scope["rows"] as [String] let dataId = rows[indexPath.row] let dict = scope[dataId] as NSDictionary cell.assignDictionary(dict as [String: AnyObject], recursiveLevel: 1) return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let section = sections?[section] ?? "cell" let scope = info?[section] as NSDictionary return scope["header"] as? String } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { let section = sections?[section] ?? "cell" let scope = info?[section] as NSDictionary return scope["footer"] as? String } // MARK: Responder & KVC override func respondsToSelector(aSelector: Selector) -> Bool { var responds = super.respondsToSelector(aSelector) let selector = NSStringFromSelector(aSelector) if let sections = sections { if let index = find(sections, selector) { responds = true } } println("respondsTo \(aSelector) = \(responds)") return responds } override func setValue(value: AnyObject!, forUndefinedKey key: String!) { info?[key] = value } override func valueForUndefinedKey(key: String!) -> AnyObject! { return info?[key] } }
Python
UTF-8
499
2.53125
3
[]
no_license
import json import os tools_file = open("tools.json") tools = json.load(tools_file) print(tools) # tool_name = "" # for key, value in tools.items(): # tool_name += key # if operation != # operation = value # if def get_children(d, parent=None, l=[]): print(d['id'], parent, len(d['children'])) l.append((d['id'], parent)) for child in d['children']: get_children(child, d['id'], l) return l l = get_children(tools) print(l) # if __name__ == '__main__':
Shell
UTF-8
1,193
3.5625
4
[]
no_license
#!/bin/bash echo "O shell permite que se possa criar variáveis e que se possa atribuir valores por ex:" estado="Paraiba" echo "Foi passado uma variavel 'estado' a qual foi atribuido o valor Paraiba, para podermos exibir o valor dessa variável podemos utilizar o conceito de substituição de variáveis, onde utilizamos o '$+nome da variável' para realizarmos essa substituição e se utilizar o comando 'echo 'Meu estado é a '$ + estado' teremos como resultado a substituição de estado pelo nome que foi atribuido, para evitarmos qualquer problema de sintaxe é recomendado que se utilize '$ + {}' para expecificar qual é a variável que sera substituida" echo -e "Ex:\n Meu estado é a ${estado}" echo 'Em relação a subtituição de shell todo comando que seja executado desta forma dentro dos parênteses $() vai ser executado e o seu resultado vai ser alocado no local que esta definido no script ' echo -e "Por ex:\nA data de hoje é $(date +%F)\n'O que está acontecendo é que o comando '$+(date +%F)' está sendo executado pelo shell e está incluindo a saida do seu resultado no local que foi determinado no script gerando aquela que foi exebida na linha anterior ' "
Rust
UTF-8
1,340
2.671875
3
[]
no_license
mod graph; mod matrix; mod render; use matrix::Matrix; use render::coordinates::Point; fn main() { let width = 512usize; let height = 256usize; let dim = Point::new(width as i32, height as i32);; let mut buffer: Vec<[u8; 4]> = vec![[255, 255, 255, 255]; width * height]; let count: usize = std::env::args() .nth(1) .and_then(|a| { let x: usize = a .parse::<usize>() .expect("Argument has to be a positive number"); Some(x) }) .unwrap_or(512); let g = graph::Graph::new_random(count); let mx = Matrix::new((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)) * 64.0; for (p1, p2) in g.edges.iter().map(|(a, b)| (&mx * *a, &mx * *b)) { println!("{:?} to {:?}", p1, p2); let p1: Point<i32> = Point::new(p1.0, p1.1).into(); let p2: Point<i32> = Point::new(p2.0, p2.1).into(); for pxl in render::coordinates::LineIterator::new(p1, p2) { if pxl.pos.in_bounds(Point::new(0, 0), dim) { buffer[pxl.pos.x() as usize + pxl.pos.y() as usize * width] = [0, 0, 0, 255] } } } let mut frame_buffer = mini_gl_fb::gotta_go_fast("Random Graph", width as f64, height as f64); frame_buffer.update_buffer(&buffer); frame_buffer.persist(); }
PHP
UTF-8
1,436
3.046875
3
[]
no_license
<?php namespace Framework\Support; class Asset { /** * The internal path to the resource. * * @var string */ protected $path; /** * The base url. * * @var string */ protected $url; /** * The Constructor of the class * * @return void */ public function __construct($path) { $this->path = $path; } public function makeAssetPath($path) { if (request()->isSubDir()) { $path = str_replace('index.php', 'public/', request()->server('SCRIPT_NAME')) . $path; } return ltrim($path, '/'); } /** * Appends the version hash. * * @param string $asset * @param bool $version * @return void */ protected function makeVersion($asset, $version) { if (! $version) { return; } return '?v=' . filemtime($asset); } /** * Gets an asset path. * * @param string $asset * @param bool $version * @return void */ public function get($asset, $version = false) { if (empty($this->url)) { $this->url = app('request')->urlBase(); } $path = $this->path . $asset; if (! file_exists($path)) { return; } return $this->url . '/' . $this->makeAssetPath($asset) . $this->makeVersion($path, $version); } }
Java
UTF-8
429
2.9375
3
[]
no_license
package org.pattern.lhf.mediator; import java.awt.*; public class ColleageButton extends Button implements Colleage { private Mediator mediator; public ColleageButton(String caption){ super(caption); } @Override public void setMediator(Mediator mediator) { this.mediator=mediator; } @Override public void setColleagueEnable(boolean enable) { setEnabled(enable); } }
JavaScript
UTF-8
1,035
2.59375
3
[]
no_license
const cheerio = require('cheerio') const http = require('http') const fs = require('fs') const path = require('path') const url = 'http://www.ziroom.com/' const getWebData = (data) => { let $ = cheerio.load(data) let imgUrlArr = $('#foucsSlideList') let imgArr = [] imgUrlArr.find('li').each(function(item){ let pic = $(this) let pic_url = pic.children('a').children('img').attr('_src') imgArr.push(pic_url) }) imgArr.forEach((item, index) => { http.get(`http:${item}`, (res) => { let imgData = '' res.setEncoding('binary') res.on('data', (chunk) => { imgData += chunk }) res.on('end', () => { fs.writeFile(path.join(__dirname, 'myImg', `${index}.jpg`), imgData, 'binary', (err) => { if (!err) { console.log('success') } }) }) }) }) } http.get(url, (res) => { let webData = '' res.on('data', (chunk) => { webData += chunk }) res.on('end', () => { getWebData(webData) }) })
Markdown
UTF-8
407
2.515625
3
[]
no_license
# Ho to add new app ```yaml # App Service app: # Configuration for building the docker image for the service build: context: ../httpserver # location of the Dockerfile dockerfile: Dockerfile ports: - "8080:8080" # Ports to expose {host}:{container} restart: unless-stopped expose: - '8080' # Ports to expose to other containers depends_on: - db ```
Shell
UTF-8
445
3.3125
3
[]
no_license
#!/bin/bash # Usage: # integration/docker/build/build.sh # integration/docker/build/build.sh force # Always recreate docker image and container. set -e SCRIPTPATH=$(dirname "$0") echo $SCRIPTPATH if [ "$1" = "force" ] || [[ "$(docker images -q theta_eth_rpc_adaptor_builder 2> /dev/null)" == "" ]]; then docker build -t theta_eth_rpc_adaptor_builder $SCRIPTPATH fi docker run -it -v "$GOPATH:/go" theta_eth_rpc_adaptor_builder
C#
UTF-8
1,831
2.609375
3
[]
no_license
using System; using Amazon.S3; using Amazon.S3.Model; using System.IO; using Amazon; using System.Threading.Tasks; using Carto.Core; namespace data.collection { public static class BucketClient { public static string Name = Conf.S3BucketName; public static string AccessKey = Conf.S3AccessKey; public static string SecretKey = Conf.S3SecretKey; public static string UploadPath = "https://" + Name + ".s3.amazonaws.com/"; /* This is the base path, file name needs to be appended to this path, * e.g. https://s3.amazonaws.com/com.carto.mobile.images/test.jpg */ public static string PublicReadPath = "https://s3.amazonaws.com/" + Name + "/"; static IAmazonS3 client; public static async Task<BucketResponse> Upload(string filename, Stream stream) { BucketResponse response = new BucketResponse(); PutObjectRequest request = new PutObjectRequest { BucketName = Name, Key = filename, CannedACL = S3CannedACL.PublicRead, InputStream = stream }; PutObjectResponse intermediary = new PutObjectResponse(); using (client = new AmazonS3Client(AccessKey, SecretKey, RegionEndpoint.USEast1)) { try { intermediary = await client.PutObjectAsync(request); response.Message = "Image uploaded"; response.Path = PublicReadPath + filename; } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); response.Error = e.Message; } } return response; } } }
C#
UTF-8
15,376
3.109375
3
[]
no_license
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; namespace CMSHelperLib { public static class ImageHelpers { /// <summary> /// Save image as jpeg /// </summary> /// <param name="path">path where to save</param> /// <param name="img">image to save</param> public static void SaveJpeg(string path, Image img) { var qualityParam = new EncoderParameter(Encoder.Quality, 100L); var jpegCodec = GetEncoderInfo("image/jpeg"); var encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(path, jpegCodec, encoderParams); } /// <summary> /// Save image /// </summary> /// <param name="path">path where to save</param> /// <param name="img">image to save</param> /// <param name="imageCodecInfo">codec info</param> public static void Save(string path, Image img, ImageCodecInfo imageCodecInfo) { var qualityParam = new EncoderParameter(Encoder.Quality, 100L); var encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(path, imageCodecInfo, encoderParams); } /// <summary> /// get codec info by mime type /// </summary> /// <param name="mimeType"></param> /// <returns></returns> public static ImageCodecInfo GetEncoderInfo(string mimeType) { return ImageCodecInfo.GetImageEncoders().FirstOrDefault(t => t.MimeType == mimeType); } /// <summary> /// the image remains the same size, and it is placed in the middle of the new canvas /// </summary> /// <param name="image">image to put on canvas</param> /// <param name="width">canvas width</param> /// <param name="height">canvas height</param> /// <param name="canvasColor">canvas color</param> /// <returns></returns> public static Image PutOnCanvas(Image image, int width, int height, Color canvasColor) { var res = new Bitmap(width, height); using (var g = Graphics.FromImage(res)) { g.Clear(canvasColor); var x = (width - image.Width) / 2; var y = (height - image.Height) / 2; g.DrawImageUnscaled(image, x, y, image.Width, image.Height); } return res; } /// <summary> /// the image remains the same size, and it is placed in the middle of the new canvas /// </summary> /// <param name="image">image to put on canvas</param> /// <param name="width">canvas width</param> /// <param name="height">canvas height</param> /// <returns></returns> public static Image PutOnWhiteCanvas(Image image, int width, int height) { return PutOnCanvas(image, width, height, Color.White); } /// <summary> /// resize an image and maintain aspect ratio /// </summary> /// <param name="image">image to resize</param> /// <param name="newWidth">desired width</param> /// <param name="maxHeight">max height</param> /// <param name="onlyResizeIfWider">if image width is smaller than newWidth use image width</param> /// <returns>resized image</returns> public static Image Resize(Image image, int newWidth, int maxHeight, bool onlyResizeIfWider) { if (onlyResizeIfWider && image.Width <= newWidth) newWidth = image.Width; var newHeight = image.Height * newWidth / image.Width; if (newHeight > maxHeight) { // Resize with height instead newWidth = image.Width * maxHeight / image.Height; newHeight = maxHeight; } var res = new Bitmap(newWidth, newHeight); using (var graphic = Graphics.FromImage(res)) { graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; graphic.DrawImage(image, 0, 0, newWidth, newHeight); } return res; } /// <summary> /// Crop an image /// </summary> /// <param name="img">image to crop</param> /// <param name="cropArea">rectangle to crop</param> /// <returns>resulting image</returns> public static Image Crop(Image img, Rectangle cropArea) { var bmpImage = new Bitmap(img); var bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat); return bmpCrop; } public static byte[] ImageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); return ms.ToArray(); } public static Image ByteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; } //The actual converting function public static string GetImage(object img) { return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img); } public static void PerformImageResizeAndPutOnCanvas(string filePath, string filePathResize, int pWidth, int pHeight) { System.Drawing.Image imgBef; imgBef = System.Drawing.Image.FromFile(filePath); System.Drawing.Image _imgR; _imgR = Resize(imgBef, pWidth, pHeight, true); System.Drawing.Image _img2; _img2 = PutOnCanvas(_imgR, pWidth, pHeight, System.Drawing.Color.White); //Save JPEG SaveJpeg(filePathResize, _img2); } } public interface IImageInfo { string Path { get; set; } string ContentType { get; set; } string FileName { get; set; } int FileSize { get; set; } byte[] PhotoStream { get; set; } int Width { get; set; } int Height { get; set; } void Save(); void Save(string newPath); void Save(string newPath, string newFilename); IImageInfo ResizeMe(int? maxHeight, int? maxWidth); } public class ImageInfo : IImageInfo { private string path; private string contentType; private string fileName; private int fileSize; private byte[] photoStream; private int width; private int height; public string Path { get { return this.path; } set { this.path = value; } } public string ContentType { get { return this.contentType; } set { this.contentType = value; } } public string FileName { get { return this.fileName; } set { this.fileName = value; } } public int FileSize { get { return this.fileSize; } set { this.fileSize = value; } } public byte[] PhotoStream { get { return this.photoStream; } set { this.photoStream = value; } } public int Width { get { return this.width; } set { this.width = value; } } public int Height { get { return this.height; } set { this.height = value; } } public void Save(string newPath) { this.path = newPath; Save(); } public void Save(string newPath, string newFileName) { this.fileName = newFileName; this.path = newPath; Save(); } public void Save() { FileManager fMgr = new FileManager(); fMgr.SaveImage(this); } public IImageInfo ResizeMe(int? maxHeight, int? maxWidth) { FileManager fMgr = new FileManager(); return fMgr.GetResizedImage(this, maxHeight, maxWidth); } } public abstract class ImageManagerBase { public static System.Drawing.Image GetImageFromStream(byte[] stream) { return System.Drawing.Image.FromStream(new MemoryStream(stream)); } public static byte[] GetImageByteArray(Stream stream, int contentLength) { byte[] buffer = new byte[contentLength]; stream.Read(buffer, 0, contentLength); return buffer; } public static IImageInfo GetImageInfo(byte[] stream) { IImageInfo info = new ImageInfo(); info.FileSize = stream.Length; info.PhotoStream = stream; Image img = GetImageFromStream(stream); info.Width = img.Size.Width; info.Height = img.Size.Height; return info; } public static IImageInfo GetImageInfo(Stream stream, int contentLength) { IImageInfo info = new ImageInfo(); byte[] imgBuffer = GetImageByteArray(stream, contentLength); info.FileSize = imgBuffer.Length; info.PhotoStream = imgBuffer; Image img = GetImageFromStream(imgBuffer); info.Width = img.Size.Width; info.Height = img.Size.Height; return info; } public IImageInfo GetResizedImage(IImageInfo image, int? maxHeight, int? maxWidth) { if ((!maxHeight.HasValue && !maxWidth.HasValue)) throw new ArgumentOutOfRangeException("maxHeight", "You must provide a non-zero maxHeight or maxWidth"); byte[] resizedStream = GetResizedImageStream(image.PhotoStream, maxHeight, maxWidth, image.ContentType); Image newImg = GetImageFromStream(resizedStream); IImageInfo info = new ImageInfo(); info.ContentType = image.ContentType; info.FileName = image.FileName; info.FileSize = resizedStream.Length; info.PhotoStream = resizedStream; info.Width = newImg.Size.Width; info.Height = newImg.Size.Height; return info; } public static string GetImageSize(IImageInfo image) { string retVal = "Unknown"; FileInfo fi = new FileInfo(GetPath(image.FileName, image.Path)); if (fi.Exists) { retVal = string.Format("{0} Kb", ((int)(fi.Length / 1000)).ToString()); } return retVal; } public byte[] GetResizedImageStream(byte[] stream, int? maxHeight, int? maxWidth, string contentType) { byte[] buffer = stream; Image img = GetImageFromStream(stream); int width = img.Size.Width; int height = img.Size.Height; int mWidth = (maxWidth.HasValue) ? maxWidth.Value : 0; int mHeight = (maxHeight.HasValue) ? maxHeight.Value : 0; bool doWidthResize = (mWidth > 0 && width > mWidth && width > mHeight); bool doHeightResize = (mHeight > 0 && height > mHeight && height > mWidth); //only resize if the image is bigger than the max if (doWidthResize || doHeightResize) { int iStart; Decimal divider; if (doWidthResize) { iStart = width; divider = Math.Abs((Decimal)iStart / (Decimal)mWidth); width = mWidth; height = (int)Math.Round((Decimal)(height / divider)); } else { iStart = height; divider = Math.Abs((Decimal)iStart / (Decimal)mHeight); height = mHeight; width = (int)Math.Round((Decimal)(width / divider)); } Image newImg = img.GetThumbnailImage(width, height, null, new System.IntPtr()); using (MemoryStream ms = new MemoryStream()) { if (contentType.IndexOf("jpeg") > -1) newImg.Save(ms, ImageFormat.Jpeg); else if (contentType.IndexOf("png") > -1) newImg.Save(ms, ImageFormat.Png); else newImg.Save(ms, ImageFormat.Gif); buffer = ms.ToArray(); } } return buffer; } public void SaveImage(IImageInfo image) { //save file to file system string path = GetPath(image.FileName, image.Path); System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create); fs.Write(image.PhotoStream, 0, image.FileSize); SaveImageFile(fs, path); fs.Dispose(); fs.Close(); } internal static string GetPath(string fileName, string path) { string directory = (path != null) ? string.Format("{0}/", path) : ""; return HttpContext.Current.Server.MapPath(string.Format("{0}{1}", directory, fileName)); } internal void SaveImageFile(System.IO.FileStream fs, string path) { Bitmap bmp = new System.Drawing.Bitmap(fs); if (Path.GetExtension(path).Equals(".gif")) bmp.Save(fs, ImageFormat.Gif); else if (Path.GetExtension(path).Equals(".png")) bmp.Save(fs, ImageFormat.Png); else bmp.Save(fs, ImageFormat.Jpeg); bmp.Dispose(); } public static void DeleteImageFromFileSystem(string fileName, string path) { if (fileName == null) throw new ArgumentNullException("fileName"); FileInfo fi = new FileInfo(GetPath(fileName, path)); if (fi.Exists) File.Delete(fi.FullName); else throw new FileNotFoundException("The image file was not found."); } } public partial class FileManager : ImageManagerBase { public void DeleteImageFromFileSystem(string fileName) { DeleteImageFromFileSystem(fileName, null); } public void DeleteImageFromFileSystem(string fileName, string folder) { if (fileName == null) throw new ArgumentNullException("fileName"); FileInfo fi = new FileInfo(GetPath(fileName, folder)); if (fi.Exists) File.Delete(fi.FullName); else throw new FileNotFoundException("The image file was not found."); } } }
Java
UTF-8
2,198
3.0625
3
[]
no_license
import edu.blackburn.cs.cs212.restaurantbase.Money; import edu.blackburn.cs.cs212.restaurantbase.Receipt; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author paul.kline */ public class Runner { /** * @param args the command line arguments */ //Here my cup sizes prices and beverage types are made and initiated public static void main(String[] args) { Size small = new Size("small"); Size medium = new Size("medium"); Size large = new Size("large"); Money price = new Money(5); Money price2 = new Money(3); Money price3 = new Money(6); Money price6 = new Money(1); Money price7 = new Money(8); Receipt receipt = new Receipt(); FancyCoffee cup = new FancyCoffee("latte", small, price); FancyCoffee cup2 = new FancyCoffee("mocha",medium,price3); Syrup chocolate = new Syrup("chocolate", price6); Syrup strawberry = new Syrup("strawberry", price6); cup.add(chocolate); cup.add(strawberry); receipt.add(cup2); receipt.add(cup); Sandwich sandwich = new Sandwich(price7); Meat ham = new Meat("ham",price2); Meat turkey = new Meat("turkey",price2); Toppings mustard = new Toppings("mustard",price6); Toppings mayo = new Toppings("mayo",price6); sandwich.add(ham); sandwich.add(turkey); sandwich.add(mustard); sandwich.add(mayo); receipt.add(sandwich); System.out.println(receipt.prepare()); System.out.println(receipt.getTotalString()); //Estimated time-2 hours, Real time-30min(LAB) //Estimated time-5 hours, Real time- 8hrs 45min(H.W) BECAUSE I CAN'T //FOCUS //Also, i don't understand why the math for getting the total cost works //perfectly fine for sandwich but not FancyCoffee? It's not adding the //chocolate and strawberry syrup as part of the total. So I guess //they're free? ¯\_(ツ)_/¯ } }
C++
UTF-8
291
2.953125
3
[]
no_license
#include <iostream> #include <thread> using namespace std; int main(){ auto foo = [](const int &i, char* buff){ cout << i << endl; cout << buff << endl; }; int i = 10; char buff[] = "hello thread"; thread t1(foo, i, buff); t1.join(); return 0; }
C
UTF-8
159
2.84375
3
[]
no_license
#include<stdio.h> int main(){ int N, tn; while(scanf("%d", &N)!=EOF){ tn = (15*N/7)+1; if(tn%3 && tn%5) tn--; printf("%d\n", tn); } return 0; }
C#
UTF-8
444
3.375
3
[ "MIT" ]
permissive
using System; //연도를 읽어 윤년인지를 판별하는 프로그램 namespace cs2._12_8 { class Program { static void Main(string[] args) { int y = int.Parse(Console.ReadLine()); if ((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) Console.WriteLine("윤년입니다."); else Console.WriteLine("윤년이 아닙니다."); } } }
Java
WINDOWS-1250
2,073
3.3125
3
[]
no_license
package poder; import java.util.ArrayList; import java.util.List; public class AdmPoderes { public List<Poder> poderes; public AdmPoderes(){ this.poderes=new ArrayList<Poder>(); } //Este metodo registra un pode previa validacin de datos necesarios y si elpoder ya existe en la lista public void registrarPoder(String codigoCorto, String nombrePoder, String tipoProducto) throws PoderException{ validarDatosPoder(codigoCorto, nombrePoder, tipoProducto); validarDatosDuplicadosPoder(codigoCorto); Poder poder=new Poder(codigoCorto, nombrePoder, tipoProducto); poderes.add(poder); System.out.println("EL poder ha sido registado correctamente"); } //Este medtodo valida si el poder ya existe y manda una exceocion private void validarDatosDuplicadosPoder(String codigoCorto) throws PoderException { if(poderExiste(codigoCorto)){ System.out.println("Poder duplicado"); throw new PoderException("Poder duplicado"); } } private boolean poderExiste(String codigoCorto) { boolean existe=false; for(Poder poder:poderes){ if(poder.getCodigoCorto().equals(codigoCorto)) existe=true; } return existe; } //Este metodo valida que se registren los datos necesarios private void validarDatosPoder(String codigoCorto, String nombrePoder, String tipoProducto) throws PoderException { String mensaje=""; if(codigoCorto.equals("")) mensaje+="El codigo corto no puede estar vacio"; if(nombrePoder.equals("")) mensaje+="\nEl nombre del poder no puede estar vacio"; if(tipoProducto.equals("")) mensaje+="\nEl tipo de producto no puede estar vacio"; if(!mensaje.equals("")){ System.out.println(mensaje); throw new PoderException(mensaje); } } //Este metodo busca unpoder usando como criterio el codigo corto public Poder bucarPoder(String codigoCorto){ for(Poder poder:poderes){ if(poder.getCodigoCorto().equals(codigoCorto)){ return poder; } } return null; } }
Ruby
UTF-8
1,511
3.875
4
[]
no_license
#write your code here def translate(string) words = string.split(' ') words.map! do |x| if /\A[[:punct:]]/.match(x) #if word begins with punctuation, preserve it while (x[1] =~ /[aeiouy]/) != 0 if /\Aqu/.match(x[1]) x = x[0] + x[3..-1] + x[1..2] else x = x[0] + x[2..-1] + x[1] end end elsif /[[:punct:]]/.match(x[-1]) #if word ends with punctuation, preserve it while (x =~ /\A[aeiouy]/) != 0 if /\Aqu/.match(x[1]) x = x[2..(x =~ /[[:punct:]]/)-1] + x[1..2] + x[(x =~ /[[:punct:]]/)..-1] else x = x[1..(x =~ /[[:punct:]]/)-1] + x[0] + x[(x =~ /[[:punct:]]/)..-1] end end else while (x =~ /\A[aeiouy]/) != 0 #reorder first letters until vowel is first if /\Aqu/.match(x) x = x[2..-1] + x[0..1] else x = x[1..-1] + x[0] end end end if /[[:upper:]]/.match(x) #capitalise first letter if /\A[[:punct:]]/.match(x) x = x[0] + x[1..-1].capitalize else x = x.capitalize end end if /[[:punct:]]/.match(x[-1]) #add 'ay' while preserving punctuation x = x[0..(x =~ /[[:punct:]]/)-1] + 'ay' + x[(x =~ /[[:punct:]]/)..-1] else x = x + 'ay' end end words.join(' ') end
Python
UTF-8
1,525
3.140625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, project_dir) class Solution(object): def findNumberOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) if length < 2: return length # dp[i]表示以第i个元素结尾的LIS(长度, 数量) dp = [[1, 1] for _ in range(length)] # basecase: dp[i] = (1,1) # 状态转移方程 # dp[i] = (dp[j][0]+1, dp[j][1]) (j < i and nums[i] > nums[j] and dp[j][0]+1 > dp[i][0]) # dp[i] = (dp[j][0], dp[j][1] + 1) (j < i and nums[i] > nums[j] and dp[j][0] + 1 == dp[i][0]) max_length = 1 number = length for i in range(1, length): for j in range(i-1, -1, -1): if nums[i] > nums[j]: if dp[j][0] + 1 > dp[i][0]: dp[i][0] = dp[j][0] + 1 dp[i][1] = dp[j][1] elif dp[j][0] + 1 == dp[i][0]: dp[i][1] += dp[j][1] if dp[i][0] > max_length: max_length = dp[i][0] number = dp[i][1] elif max_length != 1 and dp[i][0] == max_length: number += dp[i][1] return number if __name__ == '__main__': s = Solution() s.findNumberOfLIS([2, 2, 2, 2, 2])
Java
UTF-8
155
2.046875
2
[ "LGPL-2.1-only", "MIT", "LGPL-2.1-or-later", "LGPL-2.0-or-later", "BSD-3-Clause" ]
permissive
class UnsatInstOf { public static void main(String[] args) { UnsatInstOf a = new UnsatInstOf(); assert a.getClass() != UnsatInstOf.class; } }
Java
UTF-8
1,730
2.96875
3
[]
no_license
import java.awt.*; import javax.swing.*; /** * @author hyojun */ public class HPDrawPanel extends JPanel { /** * @uml.property name="x" */ private int x; /** * @uml.property name="pl" */ private int pl; /** * @uml.property name="count" */ private int count; /** * @uml.property name="hP" */ private int HP; public HPDrawPanel() { //this.setBackground(Color.cyan); this.setPreferredSize(new Dimension(600, 100)); this.setOpaque(false); pl = 15; x = 80 + pl; HP = 100; count = 4; } /** * @return * @uml.property name="count" */ public int getCount() { return count; } /** * @param count * @uml.property name="count" */ public void setCount(int count) { this.count = count; } /** * @return * @uml.property name="x" */ public int getX() { return x; } /** * @param x * @uml.property name="x" */ public void setX(int x) { this.x = x; } /** * @return * @uml.property name="hP" */ public int getHP() { return HP; } /** * @param hp * @uml.property name="hP" */ public void setHP(int hp) { HP = hp; if (hp > 74) count = 4; else if (hp > 49) count = 3; else if (hp > 24) count = 2; else if (hp > 0) count = 1; else count = 0; } private void HPRed(Graphics page, int x) { page.setColor(new Color(255, 50, 50)); page.fillRect(x, 15, 83, 70); } public void paintComponent(Graphics page) { super.paintComponent(page); page.setColor(Color.white); page.fillArc(30+pl, 10, 80, 80, 90, 180); page.fillArc(400+pl, 10, 80, 80, 270, 180); page.fillRect(70+pl, 10, 370, 80); for (int i = 0; i < getCount(); i++) { HPRed(page, x); x += 90; } x= 80 +pl; } }
Markdown
UTF-8
761
3.375
3
[]
no_license
# DP 方法的计算方式 ## 顺序 dp 基本的方向 都是从前向后的进行计算 dp[i] = func(dp[i-1],dp[i-2]) func 可以为 min/max/sum 这些方式同步 状态转移方程式,可以有很多方法 ### [零钱兑换](https://leetcode-cn.com/problems/coin-change/) 这里是从0-N这种方式同步 状态:加/不加 不加:dp[i] = dp[i-1] 加上:dp[i] = min({dp[i],dp[i-coin]+1},coin<<coins) ## 逆序 从最大到最小的开始同步 ### [最低票价](https://leetcode-cn.com/problems/minimum-cost-for-tickets/) 这里需要注意的是从前向后 进行计算。 这里的状态 可以分成:是否出门, 不出门:dp[i]=dp[i-1] 出门:dp[i] = min(dp[i-1]+costs[0],dp[i-7]+costs[1],dp[i-30]+costs[2])
Java
UTF-8
92
1.96875
2
[]
no_license
package Utils; public interface PasswordEncrypter { String encryptString(String in); }
C++
UTF-8
1,733
2.9375
3
[]
no_license
#include "TableDelim.h" TableDelim::TableDelim() { _picture.reserve(numberDelim); _picture.resize(numberDelim); _picture[static_cast<int>(Delim::ADD_OP)] = "+"; _picture[static_cast<int>(Delim::AND_OP)] = "&&"; _picture[static_cast<int>(Delim::ASS_OP)] = "="; _picture[static_cast<int>(Delim::COMMA)] = ","; _picture[static_cast<int>(Delim::DIV_OP)] = "/"; _picture[static_cast<int>(Delim::DQUOTES)] = "\""; _picture[static_cast<int>(Delim::EQ_OP)] = "=="; _picture[static_cast<int>(Delim::INC_OP)] = "++"; _picture[static_cast<int>(Delim::LARGE_OP)] = ">"; _picture[static_cast<int>(Delim::NOT_OP)] = "!"; _picture[static_cast<int>(Delim::LESS_OP)] = "<"; _picture[static_cast<int>(Delim::MUL_OP)] = "*"; _picture[static_cast<int>(Delim::NEG_OP)] = "-"; _picture[static_cast<int>(Delim::NOTEQ_OP)] = "!="; _picture[static_cast<int>(Delim::OR_OP)] = "||"; _picture[static_cast<int>(Delim::RBRACKETS_L)] = "("; _picture[static_cast<int>(Delim::RBRACKETS_R)] = ")"; _picture[static_cast<int>(Delim::SEMICOLON)] = ";"; _picture[static_cast<int>(Delim::SQUOTES)] = "'"; _picture[static_cast<int>(Delim::BRACKETS_L)] = "{"; _picture[static_cast<int>(Delim::BRACKETS_R)] = "}"; } string_view TableDelim::operator[](long i) const { return _picture[i - 1]; } int TableDelim::look(string value)const { auto a = find(_picture.begin(), _picture.end(), value); return a != _picture.end() ? distance(_picture.begin(), a)+1 : 0; } ostream & operator<<(ostream &stream, const TableDelim &table) { int i = 0; stream << "Delim Table" << endl; stream << " id|val" << endl; for (auto a : table._picture) { if (i !=0) stream << right << setw(3) << i << "|" << "\"" <<a << "\"" << endl; i++; } return stream; }
C++
UTF-8
4,415
3.6875
4
[]
no_license
/* Creator: Bradley Hobbs Date Created: 8/24 Description: The user will guess a randomly generated number between 1 and 100, you have 10 guesses before the game ends, if users guess is to high or to low, it will also tell you how many guesses you have left, if/when you run out of guesses, you lose, if you guess the number before the 10 guesses run out, you win. */ #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; int main() include { string playAgain = "Yes"; string exitGame = "No"; int userGuess; while (playAgain == "Yes" || playAgain == "yEs" || playAgain == "yeS" || playAgain == "YEs" || playAgain == "yES" || playAgain == "YES" || playAgain == "yes") { while (exitGame == "No" || exitGame == "nO" || exitGame == "NO" || exitGame == "no") { int point = 10; srand((unsigned)time(0)); int randNumber = rand() % 100 + 1; cout << "I have generated a number between 1 and 100, you have 10 guesses, if you do not input the correct number, you lose: \n"; cin >> userGuess; while(userGuess < randNumber) { point = point - 1; cout << "The number is higher than " << userGuess << endl; cout << "You have " << point << " guesses left, input new number: \n"; cin >> userGuess; } while(userGuess > randNumber) { point = point - 1; cout << "The number is lower than " << userGuess << endl; cout << "You have " << point << " guesses left, input new number: \n"; cin >> userGuess; } if (userGuess == randNumber); { cout << "Correct, the Number is " << userGuess << ", You Have Won With " << point << " Points Left! \n"; cout << "Do You Wish to Play again? \n Type Yes to Play Again, Type No if You Want to Quit: \n"; cin >> playAgain; if (playAgain == "No" || playAgain == "NO" || playAgain == "no" || playAgain == "nO") { cout << "You Have Chosen to Exit Game, All Data Will Be Lost, Continue?: \n"; cin >> exitGame; if (exitGame == "Yes" || exitGame == "yEs" || exitGame == "yES" || exitGame == "yeS" || exitGame == "YES" || exitGame == "yes") { cout << "Thanks for Playing! \n"; return 0; } } } if (point = 0) { cout << "You Have 0 Guesses Left, You Lose, Play Again?: \n"; cin >> playAgain; if (playAgain == "No" || playAgain == "NO" || playAgain == "no" || playAgain == "nO") { cout << "You Have Chosen to Exit Game, All Data Will Be Lost, Continue?: \n"; cin >> exitGame; if (exitGame == "Yes" || exitGame == "yEs" || exitGame == "yES" || exitGame == "yeS" || exitGame == "YES" || exitGame == "yes") { cout << "Thanks for Playing! \n"; return 0; } } } } } return 0; }
Java
UTF-8
1,496
2.40625
2
[]
no_license
package com.apploidxxx.entity; import com.apploidxxx.core.auth.PasswordChecker; import javax.persistence.*; import java.util.Base64; import java.util.Objects; /** * @author Arthur Kupriyanov */ @Entity public class Session { @Id @GeneratedValue long id; @Column private String sessionId; @OneToOne private User user; public long getId() { return id; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public void generateSession(User user){ user.setSession(this); this.user = user; int randomNumber = (int) (Math.random() * 1520); sessionId = Base64.getEncoder().encodeToString( (user.getUsername() + user.getLastName() + PasswordChecker.hashPassword(user.getPassword()) + "salt" + randomNumber).getBytes()); } public void setId(long id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Session session = (Session) o; return Objects.equals(user, session.user); } @Override public int hashCode() { return Objects.hash(user); } }
Java
UTF-8
97,278
2.53125
3
[]
no_license
package com.vw.util; import com.vw.model.Criteria; import com.vw.model.DetailedResultSet; import com.vw.model.MissingCriteria; import com.vw.model.ResultSetForTotalClaims; import com.vw.model.Usuario; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.text.DecimalFormat; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * This class will manage the connection to the data base and will perform all * the querys to it. * * @author Adrián Ochoa Martínez */ public class DataBaseHelper { private final String dbURL; private Connection connection; private Statement statement; /** * this constructor builds the url to the data base */ public DataBaseHelper() { dbURL = "jdbc:sqlserver://LPVW5306R5F\\SQLEXPRESS:1433;databaseName=criterios_logicos;user=sa;password=Volkswagen1"; } /** * this method loads the class and gets the connection * * @return true if the connectios succeds, false otherwise */ public boolean getConnection() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); connection = (Connection) DriverManager.getConnection(dbURL); return true; } catch (ClassNotFoundException ex) { System.out.println(ex); } catch (SQLException ex) { System.out.println(ex); } return false; } //USERS METHODS /** * This method is used in the LoginServlet * * @param userName * @param password * @return if there's an user with this password, returns the user. Null * otherwise */ public Usuario userExists(String userName, String password) { String queryContent = "USE criterios_logicos\n" + "SELECT [userName]\n" + " ,[rol]\n" + " ,[password]\n" + "FROM [criterios_logicos].[dbo].[usuario]\n" + "WHERE userName = '" + userName + "'\n" + "AND password = '" + password + "'\n" + "AND estatus = 'activo'"; ResultSet resultSet = resultSetFromQuery(queryContent); Usuario usuario = null; try { while (resultSet.next()) { usuario = new Usuario(); usuario.setUserName(resultSet.getString("userName")); usuario.setPassword(resultSet.getString("password")); usuario.setRol(resultSet.getString("rol")); return usuario; } } catch (SQLException ex) { System.out.println(ex); } return usuario; } /** * This method creates a new user for the system It's used in the userAdd * jsp. * * @param userName * @param password * @param rol * @param nombre * @param apP * @param apM * @param email * @param estatus * @return true if the user was created, false otherwise */ public boolean createUser(String userName, String password, String rol, String nombre, String apP, String apM, String email, String estatus) { String tipo = (rol.trim().toLowerCase().equals("administrador")) ? "admin" : "user"; String queryContent = "USE criterios_logicos\n" + "INSERT INTO [criterios_logicos].[dbo].[usuario]\n" + " ([userName]\n" + " ,[rol]\n" + " ,[password]\n" + " ,[nombre]\n" + " ,[apellido_paterno]\n" + " ,[apellido_materno]\n" + " ,[email]\n" + " ,[estatus])\n" + " VALUES\n" + " ('" + userName + "'" + " ,'" + tipo + "'" + " ,'" + password + "'" + " ,'" + nombre + "'" + " ,'" + apP + "'" + " ,'" + apM + "'" + " ,'" + email + "'" + " ,'" + estatus + "')"; return executeQuery(queryContent, false); } /** * This method get the usernames of the active users. It's used in the * deleteUser jsp. * * @param userID * @return a list with just the usernames of the active users of the system */ public List<String> getActiveUserNames(String userID) { List<String> users = null; String queryContent = "USE criterios_logicos\n" + "SELECT [userName]\n" + "FROM [criterios_logicos].[dbo].[usuario]\n" + "WHERE estatus = 'activo'\n" + "AND [userName] != '" + userID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { users = new ArrayList<String>(); while (resultSet.next()) { users.add(resultSet.getString(1)); } return users; } catch (SQLException ex) { System.out.println(ex); } return users; } /** * This method get the usernames of the all the users. It's used in the * editUser jsp. * * @return a list with just the usernames of the all users of the system */ public List<String> getAllUserNames() { List<String> users = null; String queryContent = "USE criterios_logicos\n" + "SELECT [userName]\n" + "FROM [criterios_logicos].[dbo].[usuario]"; ResultSet resultSet = resultSetFromQuery(queryContent); try { users = new ArrayList<String>(); while (resultSet.next()) { users.add(resultSet.getString(1)); } return users; } catch (SQLException ex) { System.out.println(ex); } return users; } /** * this method deactivates a specific user from the system It's used in the * userDelete jsp. * * @param userName * @return true if the user was delete, false otherwise */ public boolean deleteUserByUserName(String userName) { String queryContent = "USE criterios_logicos\n" + "UPDATE [criterios_logicos].[dbo].[usuario]\n" + "SET [estatus] = 'inactivo'\n" + " WHERE [userName] = '" + userName + "'"; return executeQuery(queryContent, false); } //CRITERIA METHODS /** * This method adds a new criteria to the system It's used in the * criteriaAdd jsp/CriteriaAddServlet. * * @param id * @param idNuevo * @param idViejo * @param estatus * @param departamento * @param tipo * @param nivel * @param objetivo * @param grupo * @param contenido * @param comentario * @param datos * @param averia * @param danio * @param marca * @param claveComercial * @param modelo * @param tiposGarantia * @param solicitante * @param fechaCreacion * @param fechaRevision * @param periodo * @param agregadoPor * @return true if the criteria was added, false otherwise */ public boolean addCriteria(String id, String idNuevo, String idViejo, String estatus, String departamento, String tipo, String nivel, String objetivo, String grupo, String contenido, String comentario, String datos, String averia, String danio, String marca, String claveComercial, String modelo, String tiposGarantia, String solicitante, String fechaCreacion, String fechaRevision, int periodo, String agregadoPor, String level) { String queryContent = "INSERT INTO [criterios_logicos].[dbo].[criterio]\n" + " ([criterio_ID]\n" + " ,[criterio_id_nuevo]\n" + " ,[criterio_id_viejo]\n" + " ,[criterio_estatus]\n" + " ,[criterio_departamento]\n" + " ,[criterio_tipo]\n" + " ,[criterio_nivel]\n" + " ,[criterio_objetivo]\n" + " ,[criterio_grupo]\n" + " ,[criterio_contenido]\n" + " ,[criterio_comentario]\n" + " ,[criterio_datos_a_detener]\n" + " ,[criterio_averia]\n" + " ,[criterio_danio]\n" + " ,[criterio_marca]\n" + " ,[criterio_tipo_auto_clave_comercial]\n" + " ,[criterio_anio_modelo]\n" + " ,[criterio_tipos_garantia_afecta]\n" + " ,[criterio_solicitante]\n" + " ,[criterio_fecha_creacion]\n" + " ,[criterio_fecha_revision]\n" + " ,[criterio_periodo_revision]\n" + " ,[criterio_agregado_por]\n" + " ,[criterio_aprobado], [criterio_leve])\n" + " VALUES\n" + " ('" + id + "'\n" + " ,'" + idNuevo + "'\n" + " ,'" + idViejo + "'\n" + " ,'" + estatus + "'\n" + " ,'" + departamento + "'\n" + " ,'" + tipo + "'\n" + " ,'" + nivel + "'\n" + " ,'" + objetivo + "'\n" + " ,'" + grupo + "'\n" + " ,'" + contenido + "'\n" + " ,'" + comentario + "'\n" + " ,'" + datos + "'\n" + " ,'" + averia + "'\n" + " ,'" + danio + "'\n" + " ,'" + marca + "'\n" + " ,'" + claveComercial + "'\n" + " ,'" + modelo + "'\n" + " ,'" + tiposGarantia + "'\n" + " ,'" + solicitante + "'\n" + " ,'" + fechaCreacion + "'\n" + " ,'" + fechaRevision + "'\n" + " ," + periodo + "\n" + " ,'" + agregadoPor + "'\n" + " ,'n', '" + level + "')"; return executeQuery(queryContent, false); } /** * This method updates a specific criteria from the system It's used in the * editCriteriaForm jsp/CriteriaEditServlet * * @param ID * @param estatus * @param departamento * @param tipo * @param nivel * @param objetivo * @param grupo * @param contenido * @param comentario * @param datos * @param averia * @param danio * @param marca * @param claveComercial * @param modelo * @param garantiaAfecta * @param fecha * @return true if the system was edited, false otherwise */ public boolean editCriteria(String ID, String estatus, String departamento, String tipo, String nivel, String objetivo, String grupo, String contenido, String comentario, String datos, String averia, String danio, String marca, String claveComercial, String modelo, String garantiaAfecta, String fecha) { String queryContent = "UPDATE criterios_logicos.dbo.criterio\n" + "SET [criterio_estatus] = '" + estatus + "'\n" + ",[criterio_departamento] = '" + departamento + "'\n" + ",[criterio_tipo] = '" + tipo + "'\n" + ",[criterio_nivel] = '" + nivel + "'\n" + ",[criterio_objetivo] = '" + objetivo + "'\n" + ",[criterio_grupo] = '" + grupo + "'\n" + ",[criterio_contenido] = '" + contenido + "'\n" + ",[criterio_comentario] = '" + comentario + "'\n" + ",[criterio_datos_a_detener] = '" + datos + "'\n" + ",[criterio_averia] = '" + averia + "'\n" + ",[criterio_danio] = '" + danio + "'\n" + ",[criterio_marca] = '" + marca + "'\n" + ",[criterio_tipo_auto_clave_comercial] = '" + claveComercial + "'\n" + ",[criterio_anio_modelo] = '" + modelo + "'\n" + ",[criterio_tipos_garantia_afecta] = '" + garantiaAfecta + "'\n" + ",[criterio_fecha_revision] = '" + fecha + "'\n" + " WHERE [criterio_ID] = '" + ID + "'"; return executeQuery(queryContent, false); } /** * It's used in the criteriaList jsp/CriteriaGetCriteriaServlet * * @return a list with the full info of all criteria */ public List<Criteria> getAllFromCriteria() { List<Criteria> criterios = new ArrayList(); String queryContent = "USE criterios_logicos\n" + "SELECT *\n" + "FROM criterios_logicos.dbo.criterio"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { Criteria criterio = new Criteria(); criterio.setCriterioID(resultSet.getString(1)); criterio.setIdNuevo(resultSet.getString(2)); criterio.setIdViejo(resultSet.getString(3)); criterio.setEstatus(resultSet.getString(4)); criterio.setDepartamento((resultSet.getString(5))); criterio.setTipo(resultSet.getString(6)); criterio.setNivel(resultSet.getString(7)); criterio.setObjetivo(resultSet.getString(8)); criterio.setGrupo(resultSet.getString(9)); criterio.setContenido(resultSet.getString(10)); criterio.setComentario(resultSet.getString(11)); criterio.setDatosDetener(resultSet.getString(12)); criterio.setAveria(resultSet.getString(13)); criterio.setDanio(resultSet.getString(14)); criterio.setMarca(resultSet.getString(15)); criterio.setClaveComercial(resultSet.getString(16)); criterio.setModelo(resultSet.getString(17)); criterio.setGarantiaAfecta(resultSet.getString(18)); criterio.setSolicitante(resultSet.getString(19)); criterio.setFechaCreacion(resultSet.getString(20)); criterio.setFechaRevision(resultSet.getString(21)); criterio.setPeriodoRevision(Integer.toString(resultSet.getInt(22))); criterio.setAgregadoPor(resultSet.getString(23)); criterios.add(criterio); } } catch (SQLException ex) { System.out.println(ex); } return criterios; } /** * This methods return just the editable info of an especific criteria. It's * used in the criteriaEdit jsp/CriteriaSendInfoEditServlet. * * @param ID * @return */ public Criteria getEditableInfoByCriteriaID(String ID) { Criteria criterio = null; String queryContent = "SELECT [criterio_estatus]\n" + " ,[criterio_departamento]\n" + " ,[criterio_tipo]\n" + " ,[criterio_nivel]\n" + " ,[criterio_objetivo]\n" + " ,[criterio_contenido]\n" + " ,[criterio_comentario]\n" + " ,[criterio_datos_a_detener]\n" + " ,[criterio_averia]\n" + " ,[criterio_danio]\n" + " ,[criterio_marca]\n" + " ,[criterio_tipo_auto_clave_comercial]\n" + " ,[criterio_anio_modelo]\n" + " ,[criterio_tipos_garantia_afecta]\n" + " FROM [criterios_logicos].[dbo].[criterio]\n" + " WHERE criterio_ID = '" + ID + "'\n"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { criterio = new Criteria(); criterio.setEstatus(resultSet.getString("criterio_estatus")); criterio.setDepartamento(resultSet.getString("criterio_departamento")); criterio.setTipo(resultSet.getString("criterio_tipo")); criterio.setNivel(resultSet.getString("criterio_nivel")); criterio.setObjetivo(resultSet.getString("criterio_objetivo")); criterio.setContenido(resultSet.getString("criterio_contenido")); criterio.setComentario(resultSet.getString("criterio_comentario")); criterio.setDatosDetener(resultSet.getString("criterio_datos_a_detener")); criterio.setAveria(resultSet.getString("criterio_averia")); criterio.setDanio(resultSet.getString("criterio_danio")); criterio.setMarca(resultSet.getString("criterio_marca")); criterio.setClaveComercial(resultSet.getString("criterio_tipo_auto_clave_comercial")); criterio.setModelo(resultSet.getString("criterio_anio_modelo")); criterio.setGarantiaAfecta(resultSet.getString("criterio_tipos_garantia_afecta")); } } catch (SQLException ex) { System.out.println(ex); } return criterio; } /** * This method will get the the id's of the non-approved criteria. It's used * in the criteriaToBeApproved jsp/CriteriaGetNotApprovedCriteriaServlet * * @return a list with the id's of the non approved criteria. */ public List<String> getNotApprovedCriteria() { String queryContent = "USE criterios_logicos\n" + "SELECT criterio_ID\n" + "FROM criterios_logicos.dbo.criterio\n" + "WHERE criterio_aprobado_negocio = 'n'"; ResultSet resultSet = resultSetFromQuery(queryContent); List<String> criterios = new ArrayList<String>(); try { while (resultSet.next()) { criterios.add(resultSet.getString(1)); } } catch (SQLException ex) { System.out.println(ex); } return criterios; } /** * this method will get the the id's of the active criteria. It's used in * the criteriaDelete jsp/CriteriaGetCriteriaByIDsServlet * * @return a list with the id's of the active criteria. */ public List<String> getActiveCriteriaByID() { String queryContent = "USE criterios_logicos\n" + "SELECT criterio_ID\n" + "FROM criterios_logicos.dbo.criterio\n" + "WHERE criterio_estatus = 'activo'\n" + "AND criterio_aprobado_negocio = 's'\n" + "and criterio_aprobado_admin = 's'"; ResultSet resultSet = resultSetFromQuery(queryContent); List<String> criterios = new ArrayList<String>(); try { while (resultSet.next()) { criterios.add(resultSet.getString(1)); } } catch (SQLException ex) { System.out.println(ex); } return criterios; } /** * this method will get the the id's of the all the criteria. It's used in * the criteriaEdit jsp/CriteriaGetEditableCriteriaServlet * * @return a list with the id's of the active criteria. */ public List<String> getAllCriteriaByID() { String queryContent = "USE criterios_logicos\n" + "SELECT criterio_ID\n" + "FROM criterios_logicos.dbo.criterio\n" + "where criterio_aprobado_negocio = 's'" + "and criterio_aprobado_admin = 's'"; ResultSet resultSet = resultSetFromQuery(queryContent); List<String> criterios = new ArrayList<String>(); try { while (resultSet.next()) { criterios.add(resultSet.getString(1)); } } catch (SQLException ex) { System.out.println(ex); } return criterios; } /** * This method will deactivate an especific criteria It's used in the * criteriaDelete jsp/CriteriaDeleteServlet. * * @param id * @return true if the criteria was successfully deactivated, false * otherwise. */ public boolean deactivateCriteriaByID(String id) { String queryContent = "USE criterios_logicos\n" + "UPDATE [criterios_logicos].[dbo].[criterio]\n" + " SET [criterio_estatus] = 'inactivo'\n" + " WHERE [criterio_ID] = '" + id + "'"; return executeQuery(queryContent, false); } public List<MissingCriteria> getCriteriaDifferencess(String month, String year) { List<MissingCriteria> list = new ArrayList(); HashMap<String, String> activeCriteriaFromCriteriaData = getActiveCriteriaFromDataBase(); HashMap<String, String> activeCriteriaFromMonthlyRoc = getActiveCriteriaFromMonthlyRoc(month, year); for (Map.Entry<String, String> entry : activeCriteriaFromCriteriaData.entrySet()) { String newID = entry.getKey(); String oldID = entry.getValue(); if (!activeCriteriaFromMonthlyRoc.containsKey(newID) && !activeCriteriaFromMonthlyRoc.containsKey(oldID)) { String criteriaID = newID + "/" + oldID; String criteriaMessage = "El criterio " + criteriaID + " se encuentra activo en la base de datos y no hay " + "coincidencia en el archivo ROC Mensual."; list.add(new MissingCriteria(criteriaID, criteriaMessage)); } } for (Map.Entry<String, String> entry : activeCriteriaFromMonthlyRoc.entrySet()) { String criteriaID = entry.getKey(); if (!activeCriteriaFromCriteriaData.containsKey(criteriaID) && !activeCriteriaFromCriteriaData.containsValue(criteriaID)) { String criteriaMessage = "El criterio " + criteriaID + " se encuentra activo en el ROC Mensual y no hay " + "coincidencia en la base de datos de criterios lógicos."; list.add(new MissingCriteria(criteriaID, criteriaMessage)); } } Collections.sort(list); return list; } public HashMap<String, String> getActiveCriteriaFromMonthlyRoc(String month, String year) { HashMap<String, String> map = new HashMap(); String queryContent = "USE criterios_logicos\n" + "SELECT roc_mensual_criterio_ID\n" + "FROM criterios_logicos.dbo.roc_mensual\n" + "WHERE roc_mensual_fecha = '" + year + month + "01'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { String id = resultSet.getString("roc_mensual_criterio_ID"); map.put(id, id); } } catch (SQLException ex) { System.out.println(ex); } return map; } public HashMap<String, String> getActiveCriteriaFromDataBase() { HashMap<String, String> map = new HashMap(); String queryContent = "USE criterios_logicos\n" + "SELECT criterio_ID\n" + "FROM criterios_logicos.dbo.criterio\n" + "where criterio_estatus = 'activo'\n" + "and criterio_aprobado_negocio = 's'\n" + "and criterio_aprobado_admin = 's'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { String bothID = resultSet.getString("criterio_ID"); String[] ids = bothID.split("[*]"); String newID = ids[0]; String oldID; try { oldID = ids[1]; } catch (Exception e) { oldID = ""; } map.put(newID, oldID); } } catch (SQLException ex) { System.out.println(ex); } return map; } //REPORTING METHODS public List<DetailedResultSet> getDetailedReport(String criteriaID, String reportType, String initialDate, String finalDate, String solicitante) { List<DetailedResultSet> result = new ArrayList<DetailedResultSet>(); if (reportType.equals("ajusteAnalista")) { result = getDetailedReportFromAnalistAdjust(criteriaID, initialDate, finalDate, solicitante); } else if (reportType.equals("ajusteCriterio")) { result = getDetailedReportFromCriteriaAdjust(criteriaID, initialDate, finalDate, solicitante); } else if (reportType.equals("canceladosAnalista")) { result = getDetailedReportFromAnalistCanceled(criteriaID, initialDate, finalDate, solicitante, "ROC"); } else if (reportType.equals("canceladosCriterio")) { result = getDetailedReportFromCriteriaCanceled(criteriaID, initialDate, finalDate, solicitante, "Claim Criteria"); } return result; } private List<DetailedResultSet> getDetailedReportFromAnalistCanceled(String criteriaID, String initialDate, String finalDate, String solicitante, String file) { List<DetailedResultSet> result = new ArrayList(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> regularCriteria = getRegularCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromRoc(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by an intelligent criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String criteria = entry.getValue(); String[] criteriaIDs = criteria.split("[*]+"); for (String criteriaID1 : criteriaIDs) { if (regularCriteria.containsKey(criteriaID1) || regularCriteria.containsValue(criteriaID1)) { filteredClaims.put(entry.getKey(), criteriaID1); } } } //At this point, we have all the claims from the claim criteria that were affected by an intelligent criteria //Now, we're gonna get all tha claims from the claim criteria HashMap<String, String> claimCriteriaClaims = getClaimCriteriaClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the easy HashMap<String, String> easyClaims = getEasyClaims(initialDate, finalDate); for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String rocClaimID = entry.getKey(); String criteria = entry.getValue(); if (claimCriteriaClaims.containsKey(rocClaimID)) { continue; } if (dwhClaims.containsKey(rocClaimID)) { continue; } if (easyClaims.containsKey(rocClaimID)) { continue; } if (criteria.equals(criteriaID)) { result.add(getDetailedResultSetFromRoc(rocClaimID, solicitante, criteriaID)); } } return result; } private List<DetailedResultSet> getDetailedReportFromCriteriaCanceled(String criteriaID, String initialDate, String finalDate, String solicitante, String file) { //Here is gonna be the final result List<DetailedResultSet> result = new ArrayList(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> intelligentCriteria = getIntelligentCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromClaimCriteria(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by an intelligent criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String idCriteria = entry.getValue(); if (intelligentCriteria.containsKey(idCriteria) || intelligentCriteria.containsValue(idCriteria)) { filteredClaims.put(entry.getKey(), idCriteria); } } //At this point, we have all the claims from the claim criteria that were affected by an intelligent criteria //Now, we're gonna get all tha claims from the roc HashMap<String, String> rocClaims = getRocClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the easy HashMap<String, String> easyClaims = getEasyClaims(initialDate, finalDate); for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String claimCriteriaClaimID = entry.getKey(); String idCriteria; if (rocClaims.containsKey(claimCriteriaClaimID)) { continue; } if (dwhClaims.containsKey(claimCriteriaClaimID)) { continue; } if (easyClaims.containsKey(claimCriteriaClaimID)) { continue; } idCriteria = entry.getValue(); if (idCriteria.equals(criteriaID)) { DetailedResultSet resultSet = getDetailedResultSetFromClaimCriteria( claimCriteriaClaimID, solicitante, criteriaID, file); result.add(resultSet); } } Collections.sort(result); return result; } private DetailedResultSet getDetailedResultSetFromRoc(String idClaim, String solicitante, String criteriaID, String table) { String id = idClaim; String monto = getClaimAmountFromRocDWH(idClaim); String chasis = getClaimChasis(idClaim); String claimSerial = getClaimSerial(idClaim); String dealer = getClaimDealer(idClaim); return new DetailedResultSet(id, monto, solicitante, chasis, criteriaID, claimSerial, dealer, "DWH"); } private DetailedResultSet getDetailedResultSetFromClaimCriteria(String idClaim, String solicitante, String criteriaID, String table) { String id = idClaim; String monto = (table.equals("ROC")) ? getClaimAmountFromRoc(idClaim) : getClaimAmountFromDWH(idClaim); String chasis = getClaimChasis(idClaim); String claimSerial = getClaimSerial(idClaim); String dealer = getClaimDealer(idClaim); return new DetailedResultSet(id, monto, solicitante, chasis, criteriaID, claimSerial, dealer, table); } private DetailedResultSet getDetailedResultSetFromRoc(String idClaim, String solicitante, String criteriaID) { DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); String monto = "$" + decimalFormat.format(getAmountFromRoc(idClaim)); String chasis = getChasisFromRoc(idClaim); String serial = getSerialFromRoc(idClaim); String dealer = getDealerFromRoc(idClaim); return new DetailedResultSet(idClaim, monto, solicitante, chasis, criteriaID, serial, dealer, "ROC"); } /** * This method will process claim criteria/roc/data warehouse claims and get * the necessary info about this claims * * @param initialDate * @param finalDate * @return a list with the regular criteria and the claims afected by it */ public List<com.vw.model.ResultSet> getAdjustByAnalist(String initialDate, String finalDate) { //Here is gonna be the final result List<com.vw.model.ResultSet> result = new ArrayList(); HashMap<String, com.vw.model.ResultSet> auxResult = new HashMap(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> regularCriteria = getRegularCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromRoc(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by a regular criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String criteriaIDFromOriginalClaim = entry.getValue(); String ids[] = criteriaIDFromOriginalClaim.split("[*]+"); for (int i = 0; i < ids.length; i++) { if (regularCriteria.containsKey(ids[i])) { String claimIDFromOriginalClaim = entry.getKey(); filteredClaims.put(claimIDFromOriginalClaim, ids[i]); } else if (regularCriteria.containsValue(ids[i])) { String claimIDFromOriginalClaim = entry.getKey(); filteredClaims.put(claimIDFromOriginalClaim, ids[i]); } } } //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); HashMap<String, Double> amountsByIdCriteria = new HashMap(); /*Now we're gonna compare the filterecClaims from claim criteria to the claims from roc and datawarehouse*/ for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String claimIDFromFilteredClaims = entry.getKey(); String criteriaIDFromFilteredClaims = entry.getValue(); if (dwhClaims.containsKey(claimIDFromFilteredClaims)) { if (!auxResult.containsKey(criteriaIDFromFilteredClaims)) { com.vw.model.ResultSet resultSet = getResultSetFromDataWarehouse(false, criteriaIDFromFilteredClaims, initialDate, finalDate); double amount = getAmountFromRoc( claimIDFromFilteredClaims) - getAmountFromDWH(claimIDFromFilteredClaims); double d; try { d = amountsByIdCriteria.get(criteriaIDFromFilteredClaims); } catch (NullPointerException ex) { d = 0.0; } amountsByIdCriteria.put(criteriaIDFromFilteredClaims, d + amount); auxResult.put(criteriaIDFromFilteredClaims, resultSet); } else { double amount = getAmountFromRoc( claimIDFromFilteredClaims) - getAmountFromDWH(claimIDFromFilteredClaims); double d; try { d = amountsByIdCriteria.get(criteriaIDFromFilteredClaims); } catch (NullPointerException ex) { d = 0.0; } amountsByIdCriteria.put(criteriaIDFromFilteredClaims, d + amount); } } } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { String criteriaID = entry.getKey(); com.vw.model.ResultSet res = entry.getValue(); DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); //double va=amountsByIdCriteria.get(criteriaID); String amount = "$" + decimalFormat.format(amountsByIdCriteria.get(criteriaID)); if(amount.equals("$-0")) amount="$0"; res.setMonto(amount); auxResult.put(criteriaID, res); } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { result.add(entry.getValue()); } Collections.sort(result); return result; } /** * This method will process claim criteria/roc/data warehouse claims and get * the necessary info about this claims * * @param initialDate * @param finalDate * @return a list with the intelligent criteria and the claims afected by it */ public List<com.vw.model.ResultSet> getAdjustByCriteria(String initialDate, String finalDate) { //Here is gonna be the final result List<com.vw.model.ResultSet> result = new ArrayList(); HashMap<String, com.vw.model.ResultSet> auxResult = new HashMap(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> intelligentCriteria = getIntelligentCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromClaimCriteria(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by an intelligent criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String criteriaID = entry.getValue(); if (intelligentCriteria.containsKey(criteriaID) || intelligentCriteria.containsValue(criteriaID)) { filteredClaims.put(entry.getKey(), criteriaID); } } //At this point, we have all the claims from the claim criteria that were affected by an intelligent criteria //Now, we're gonna get all tha claims from the roc HashMap<String, String> rocClaims = getRocClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); HashMap<String, Double> amountsByCriteria = new HashMap(); /*Now we're gonna compare the filterecClaims from claim criteria to the claims from roc and datawarehouse*/ for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String claimFroClaimCriteriaID = entry.getKey(); String criteriaID = entry.getValue(); if (rocClaims.containsKey(claimFroClaimCriteriaID)) { if (!auxResult.containsKey(criteriaID)) { com.vw.model.ResultSet resultSet = getResultSetFromRoc(true, criteriaID, initialDate, finalDate); // result.add(resultSet); double amount = getAmountFromClaimCriteria(claimFroClaimCriteriaID) - getAmountFromRoc(claimFroClaimCriteriaID); auxResult.put(criteriaID, resultSet); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); System.out.println("ResultSet from roc " + criteriaID); } else { double amount = getAmountFromClaimCriteria(claimFroClaimCriteriaID) - getAmountFromRoc(claimFroClaimCriteriaID); // auxResult.put(criteriaID, resultSet); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); } } else if (dwhClaims.containsKey(claimFroClaimCriteriaID)) { if (!auxResult.containsKey(criteriaID)) { com.vw.model.ResultSet resultSet = getResultSetFromDataWarehouse(true, criteriaID, initialDate, finalDate); // result.add(resultSet); double amount = getAmountFromClaimCriteria(claimFroClaimCriteriaID) - getAmountFromDWH(claimFroClaimCriteriaID); auxResult.put(criteriaID, resultSet); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); auxResult.put(criteriaID, resultSet); System.out.println("ResultSet from dwh " + criteriaID); } else { double amount = getAmountFromClaimCriteria(claimFroClaimCriteriaID) - getAmountFromDWH(claimFroClaimCriteriaID); // auxResult.put(criteriaID, resultSet); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); } } } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { String criteriaID = entry.getKey(); com.vw.model.ResultSet res = entry.getValue(); DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); String amount = "$" + decimalFormat.format(amountsByCriteria.get(criteriaID)); res.setMonto(amount); auxResult.put(criteriaID, res); } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { result.add(entry.getValue()); } Collections.sort(result); return result; } /** * * @param initialDate * @param finalDate * @return */ public List<com.vw.model.ResultSet> getCanceledClaimsByCriteria(String initialDate, String finalDate) { //Here is gonna be the final result List<com.vw.model.ResultSet> result = new ArrayList(); HashMap<String, com.vw.model.ResultSet> auxResult = new HashMap(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> intelligentCriteria = getIntelligentCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromClaimCriteria(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by an intelligent criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String criteriaID = entry.getValue(); if (intelligentCriteria.containsKey(criteriaID) || intelligentCriteria.containsValue(criteriaID)) { filteredClaims.put(entry.getKey(), criteriaID); } } //At this point, we have all the claims from the claim criteria that were affected by an intelligent criteria //Now, we're gonna get all tha claims from the roc HashMap<String, String> rocClaims = getRocClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the easy HashMap<String, String> easyClaims = getEasyClaims(initialDate, finalDate); HashMap<String, Double> amountsByCriteria = new HashMap(); for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String claimCriteriaClaimID = entry.getKey(); String criteriaID; if (rocClaims.containsKey(claimCriteriaClaimID)) { continue; } if (dwhClaims.containsKey(claimCriteriaClaimID)) { continue; } if (easyClaims.containsKey(claimCriteriaClaimID)) { continue; } criteriaID = entry.getValue(); if (!auxResult.containsKey(criteriaID)) { com.vw.model.ResultSet resultSet = getResultSetFromCanceledClaimCriteria(true, criteriaID, initialDate, finalDate); double amount = getAmountFromClaimCriteria(claimCriteriaClaimID); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); auxResult.put(criteriaID, resultSet); } else { double amount = getAmountFromClaimCriteria(claimCriteriaClaimID); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); } } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { String criteriaID = entry.getKey(); com.vw.model.ResultSet res = entry.getValue(); DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); String amount = "$" + decimalFormat.format(amountsByCriteria.get(criteriaID)); res.setMonto(amount); auxResult.put(criteriaID, res); } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { result.add(entry.getValue()); } Collections.sort(result); return result; } /** * * @param initialDate * @param finalDate * @return */ public List<com.vw.model.ResultSet> getCanceledClaimsByAnalist(String initialDate, String finalDate) { //Here is gonna be the final result List<com.vw.model.ResultSet> result = new ArrayList(); HashMap<String, com.vw.model.ResultSet> auxResult = new HashMap(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> regularCriteria = getRegularCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromRoc(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by an intelligent criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String criteriaID = entry.getValue(); String[] criteriaIDs = criteriaID.split("[*]+"); for (String criteriaID1 : criteriaIDs) { if (regularCriteria.containsKey(criteriaID1) || regularCriteria.containsValue(criteriaID1)) { filteredClaims.put(entry.getKey(), criteriaID1); } } } //At this point, we have all the claims from the claim criteria that were affected by an intelligent criteria //Now, we're gonna get all tha claims from the claim criteria HashMap<String, String> claimCriteriaClaims = getClaimCriteriaClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the easy HashMap<String, String> easyClaims = getEasyClaims(initialDate, finalDate); HashMap<String, Double> amountsByCriteria = new HashMap(); for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String claimCriteriaClaimID = entry.getKey(); String criteriaID; if (claimCriteriaClaims.containsKey(claimCriteriaClaimID)) { continue; } if (dwhClaims.containsKey(claimCriteriaClaimID)) { continue; } if (easyClaims.containsKey(claimCriteriaClaimID)) { continue; } criteriaID = entry.getValue(); if (!auxResult.containsKey(criteriaID)) { com.vw.model.ResultSet resultSet = getResultSetFromCanceledRoc(false, criteriaID, initialDate, finalDate); double amount = getAmountFromRoc(claimCriteriaClaimID); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); auxResult.put(criteriaID, resultSet); } else { double amount = getAmountFromRoc(claimCriteriaClaimID); double d; try { d = amountsByCriteria.get(criteriaID); } catch (NullPointerException ex) { d = 0.0; } amountsByCriteria.put(criteriaID, d + amount); } } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { String criteriaID = entry.getKey(); com.vw.model.ResultSet res = entry.getValue(); DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); String amount = "$" + decimalFormat.format(amountsByCriteria.get(criteriaID)); res.setMonto(amount); auxResult.put(criteriaID, res); } for (Map.Entry<String, com.vw.model.ResultSet> entry : auxResult.entrySet()) { result.add(entry.getValue()); } Collections.sort(result); return result; } private List<DetailedResultSet> getDetailedReportFromCriteriaAdjust(String criteriaID, String initialDate, String finalDate, String solicitante) { List<DetailedResultSet> result = new ArrayList<DetailedResultSet>(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> intelligentCriteria = getIntelligentCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromClaimCriteria(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by a regular criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String criteriaIDFromOriginalClaim = entry.getValue(); if (intelligentCriteria.containsKey(criteriaIDFromOriginalClaim)) { String claimIDFromOriginalClaim = entry.getKey(); filteredClaims.put(claimIDFromOriginalClaim, criteriaIDFromOriginalClaim); } else if (intelligentCriteria.containsValue(criteriaIDFromOriginalClaim)) { String claimIDFromOriginalClaim = entry.getKey(); filteredClaims.put(claimIDFromOriginalClaim, criteriaIDFromOriginalClaim); } } //At this point, we have all the claims from the claim criteria that were affected by an intelligent criteria //Now, we're gonna get all tha claims from the roc HashMap<String, String> rocClaims = getRocClaims(initialDate, finalDate); //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); /*Now we're gonna compare the filterecClaims from claim criteria to the claims from roc and datawarehouse*/ for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String claimIDFromFilteredClaims = entry.getKey(); String criteriaIDFromFilteredClaims = entry.getValue(); if (rocClaims.containsKey(claimIDFromFilteredClaims)) { if (criteriaID.equals(criteriaIDFromFilteredClaims)) { DetailedResultSet resultSet = getDetailedResultSetFromClaimCriteria(claimIDFromFilteredClaims, solicitante, criteriaIDFromFilteredClaims, "ROC"); result.add(resultSet); } } else if (dwhClaims.containsKey(claimIDFromFilteredClaims)) { if (criteriaID.equals(criteriaIDFromFilteredClaims)) { DetailedResultSet resultSet = getDetailedResultSetFromClaimCriteria(claimIDFromFilteredClaims, solicitante, criteriaIDFromFilteredClaims, "DWH"); result.add(resultSet); } } } return result; } private List<DetailedResultSet> getDetailedReportFromAnalistAdjust(String criteriaID, String initialDate, String finalDate, String solicitante) { List<DetailedResultSet> result = new ArrayList<DetailedResultSet>(); //Here is a list with all the intelligent criteria LinkedHashMap<String, String> regularCriteria = getRegularCriteria(); //Here is a map which contains all the claims from claim file and the respective criteria ID LinkedHashMap<String, String> originalClaims = getAllClaimsFromRoc(initialDate, finalDate); //The new data is gonna be saved here LinkedHashMap<String, String> filteredClaims = new LinkedHashMap(); //Now we're gonna filters the claims affeected by a regular criteria for (Map.Entry<String, String> entry : originalClaims.entrySet()) { String criteriaIDFromOriginalClaim = entry.getValue(); String[] ids = criteriaIDFromOriginalClaim.split("[*]+"); for (int i = 0; i < ids.length; i++) { if (regularCriteria.containsKey(ids[i])) { String claimIDFromOriginalClaim = entry.getKey(); filteredClaims.put(claimIDFromOriginalClaim, ids[i]); } else if (regularCriteria.containsValue(ids[i])) { String claimIDFromOriginalClaim = entry.getKey(); filteredClaims.put(claimIDFromOriginalClaim, ids[i]); } } } //Now, we're gonna get all the claims from the data warehouse HashMap<String, String> dwhClaims = getDwhClaims(initialDate, finalDate); /*Now we're gonna compare the filterecClaims from claim criteria to the claims from roc and datawarehouse*/ for (Map.Entry<String, String> entry : filteredClaims.entrySet()) { String claimIDFromFilteredClaims = entry.getKey(); String criteriaIDFromFilteredClaims = entry.getValue(); if (dwhClaims.containsKey(claimIDFromFilteredClaims)) { if (criteriaID.equals(criteriaIDFromFilteredClaims)) { DetailedResultSet resultSet = getDetailedResultSetFromRoc(claimIDFromFilteredClaims, solicitante, criteriaIDFromFilteredClaims, ""); result.add(resultSet); } } } return result; } private com.vw.model.ResultSet getResultSetFromCanceledClaimCriteria(boolean isIntelligentCriteria, String criteriaID, String initialDate, String finalDate) { String criteriaType = (isIntelligentCriteria) ? "Inteligente" : getCriteriaType(criteriaID); String hitNumber = getCriteriaHits(criteriaID, initialDate, finalDate); String amount = "0.0"; String applicant = getCriteriaApplicant(criteriaID); String brand = getCriteriaBrand(criteriaID).toUpperCase(); String daysSinceActivation = getCriteriaDaysSinceActivation(criteriaID); String level = getCriteriaLevel(criteriaID); return new com.vw.model.ResultSet(criteriaID, criteriaType, hitNumber, amount, applicant, brand, daysSinceActivation, level); } private com.vw.model.ResultSet getResultSetFromCanceledRoc(boolean isIntelligentCriteria, String criteriaID, String initialDate, String finalDate) { String criteriaType = (isIntelligentCriteria) ? "Inteligente" : getCriteriaType(criteriaID); String hitNumber = getCriteriaHits(criteriaID, initialDate, finalDate); String amount = "0.0"; String applicant = getCriteriaApplicant(criteriaID); String brand = getCriteriaBrand(criteriaID).toUpperCase(); String daysSinceActivation = getCriteriaDaysSinceActivation(criteriaID); String level = getCriteriaLevel(criteriaID); return new com.vw.model.ResultSet(criteriaID, criteriaType, hitNumber, amount, applicant, brand, daysSinceActivation, level); } /** * This method will get the necessay data to fill a result set comparing * data between the claim criteria and the data warehouse It's used by the * getAdjustByAnalist/getAdjustByCriteria methods * * @param isIntelligentCriteria * @param criteriaID * @param filteredClaims * @param dwhClaims * @return a com.vw.model.ResultSet */ private com.vw.model.ResultSet getResultSetFromDataWarehouse(boolean isIntelligentCriteria, String criteriaID, String initialDate, String finalDate) { String criteriaType = (isIntelligentCriteria) ? "Inteligente" : getCriteriaType(criteriaID); String hitNumber = getCriteriaHits(criteriaID, initialDate, finalDate); String amount = "0.0"; String applicant = getCriteriaApplicant(criteriaID); String brand = getCriteriaBrand(criteriaID).toUpperCase(); String daysSinceActivation = getCriteriaDaysSinceActivation(criteriaID); String level = getCriteriaLevel(criteriaID); return new com.vw.model.ResultSet(criteriaID, criteriaType, hitNumber, amount, applicant, brand, daysSinceActivation, level); } /** * This method will get the necessary data to fill a result comparing data * between the claim criteria and the roc It's used by the * getAdjustByAnalist/getAdjustByCriteria methods * * @param isIntelligentCriteria * @param criteriaID * @param filteredClaims * @param rocClaims * @return */ private com.vw.model.ResultSet getResultSetFromRoc(boolean isIntelligentCriteria, String criteriaID, String initialDate, String finalDate) { String criteriaType = (isIntelligentCriteria) ? "Inteligente" : getCriteriaType(criteriaID); String hitNumber = getCriteriaHits(criteriaID, initialDate, finalDate); String amount = "0.0"; String applicant = getCriteriaApplicant(criteriaID); String brand = getCriteriaBrand(criteriaID).toUpperCase(); String daysSinceActivation = getCriteriaDaysSinceActivation(criteriaID); String level = getCriteriaLevel(criteriaID); return new com.vw.model.ResultSet(criteriaID, criteriaType, hitNumber, amount, applicant, brand, daysSinceActivation, level); } /** * This method will get the days_since_activation value for an especific * criteria ID from the monthly roc It's used in the * getResultSetFromRoc/getResultSetFromDataDWarehouse methods * * @param criteriaID * @return */ private String getCriteriaDaysSinceActivation(String criteriaID) { String daysSinceActivation = "0"; String queryContent = "SELECT [roc_mensual_dias_activacion]\n" + "FROM [criterios_logicos].[dbo].[roc_mensual]\n" + "WHERE [roc_mensual_criterio_ID] = '" + criteriaID + "'\n"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { daysSinceActivation = Integer.toString(resultSet.getInt("roc_mensual_dias_activacion")); } } catch (SQLException ex) { System.out.println(ex); } return (daysSinceActivation.isEmpty() || daysSinceActivation == null) ? "0" : daysSinceActivation; } /** * This method will return the brand of an especific criteria from the * criteria table It's used in the * getResultSetFromRoc/getResultSetFromDataDWarehouse methods * * @param criteriaID * @return */ private String getCriteriaBrand(String criteriaID) { String brand = ""; String queryContent = "SELECT [criterio_marca]\n" + "FROM [criterios_logicos].[dbo].[criterio]\n" + "WHERE [criterio_id_nuevo] = '" + criteriaID + "'\n" + "OR [criterio_id_viejo] = '" + criteriaID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { brand = resultSet.getString("criterio_marca"); } } catch (SQLException ex) { System.out.println(ex); } return brand; } /** * This method will return the brand of an especific criteria from the * criteria table It's used in the * getResultSetFromRoc/getResultSetFromDataDWarehouse methods * * @param criteriaID * @return */ private String getCriteriaLevel(String criteriaID) { String brand = ""; String queryContent = "SELECT [criterio_level]\n" + "FROM [criterios_logicos].[dbo].[criterio]\n" + "WHERE [criterio_id_nuevo] = '" + criteriaID + "'\n" + "OR [criterio_id_viejo] = '" + criteriaID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { brand = resultSet.getString("criterio_level"); } } catch (SQLException ex) { System.out.println(ex); } return brand; } /** * This method will return the applicant from a specific criteria from the * criterio table It's used in the * getResultSetFromRoc/getResultSetFromDataDWarehouse methods * * * @param criteriaID * @return */ private String getCriteriaApplicant(String criteriaID) { String applicant = ""; String queryContent = "SELECT [criterio_solicitante]\n" + "FROM [criterios_logicos].[dbo].[criterio]\n" + "WHERE [criterio_id_nuevo] = '" + criteriaID + "'\n" + "OR [criterio_id_viejo] = '" + criteriaID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { applicant = resultSet.getString("criterio_solicitante"); } } catch (SQLException ex) { System.out.println(ex); } return applicant; } /** * This method will get the value of a specific claim in the data warehouse * It's used in the getCriteriaAmountFromDWH method. * * @param claimID * @return */ private double getAmountFromDWH(String claimID) { String queryContent = "SELECT [dwh_total_sin_profit]\n" + "FROM [criterios_logicos].[dbo].[dwh]\n" + "WHERE [dwh_ID] = '" + claimID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); double amount = 0.0; try { while (resultSet.next()) { amount = resultSet.getDouble("dwh_total_sin_profit"); } } catch (SQLException ex) { System.out.println(ex); } return amount; } /** * This method will get the value of a specific claim in the roc It's used * in the getCriteriaAmountFromRoc method * * @param claimID * @return */ private double getAmountFromRoc(String claimID) { String queryContent = "SELECT [roc_amount]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_ID] = '" + claimID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); double amount = 0.0; try { while (resultSet.next()) { amount = Double.parseDouble(resultSet.getString("roc_amount").replace(",", "")); } } catch (SQLException ex) { System.out.println(ex); } return amount; } /** * This method will get the value of a specific claim in the claim criteria * It's used in the getClaimAmountFromDWH/getClaimAmountFromRoc methods * * @param claimID * @return */ private double getAmountFromClaimCriteria(String claimID) { String queryContent = "SELECT [claim_valor_total_imp]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_ID] = '" + claimID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); double amount = 0.0; try { while (resultSet.next()) { amount = resultSet.getDouble("claim_valor_total_imp"); } } catch (SQLException ex) { System.out.println(ex); } return amount; } /** * This method will get the monthly amount of hits of an specific criteria * from the monthly roc It's used in the * getResultSetFromRoc/getResultSetFromDataDWarehouse methods * * @param criteriaID * @return */ private String getCriteriaHits(String criteriaID, String initialDate, String finalDate) { String monthlyID = criteriaID; String queryContent = "SELECT [roc_mensual_numero_hits]\n" + "FROM [criterios_logicos].[dbo].[roc_mensual]\n" + "WHERE [roc_mensual_criterio_ID] = '" + monthlyID + "'\n" + "AND [roc_mensual_fecha] BETWEEN '" + initialDate + "' AND '" + finalDate + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); String hits = "0"; int hitAmount = 0; try { while (resultSet.next()) { hitAmount += resultSet.getInt("roc_mensual_numero_hits"); } } catch (SQLException ex) { System.out.println(ex); } try { hits = Integer.toString(hitAmount); } catch (Exception ex) { System.out.println(ex); } return hits; } /** * This method will get the type of an specific criteria It's used in the * getResultSetFromRoc/getResultSetFromDataDWarehouse methods * * @param criteriaID * @return */ private String getCriteriaType(String criteriaID) { String criteriaType = ""; String queryContent = "SELECT [criterio_tipo]\n" + "FROM [criterios_logicos].[dbo].[criterio]\n" + "WHERE [criterio_id_viejo] = '" + criteriaID + "'\n" + "OR [criterio_id_nuevo] = '" + criteriaID + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { criteriaType = resultSet.getString("criterio_tipo"); } } catch (SQLException ex) { System.out.println(ex); } return (criteriaType == null) ? "No especificado" : criteriaType; } public String getDealerFromRoc(String idClaim) { String dealer = "Reclamación sin chasis"; String query = "SELECT [roc_taller]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { dealer = resultSet.getString("roc_taller"); } } catch (SQLException ex) { System.out.println(ex); } return dealer; } public String getSerialFromRoc(String idClaim) { String serial = "Reclamación sin chasis"; String query = "SELECT [roc_claim_serial]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { serial = resultSet.getString("roc_claim_serial"); } } catch (SQLException ex) { System.out.println(ex); } return serial; } public String getChasisFromRoc(String idClaim) { String chasis = "Reclamación sin chasis"; String query = "SELECT [roc_chasis]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { chasis = resultSet.getString("roc_chasis"); } } catch (SQLException ex) { System.out.println(ex); } return chasis; } public String getClaimDealer(String idClaim) { String dealer = "Reclamación sin dealer"; String query = "SELECT [claim_dealer]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { dealer = resultSet.getString("claim_dealer"); } } catch (SQLException ex) { System.out.println(ex); } return dealer; } public String getClaimSerial(String idClaim) { String serial = "Reclamación sin serial"; String query = "SELECT [claim_serial]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { serial = resultSet.getString("claim_serial"); } } catch (SQLException ex) { System.out.println(ex); } return serial; } public String getClaimChasis(String idClaim) { String chasis = "Reclamación sin chasis"; String query = "SELECT [claim_chasis]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { chasis = resultSet.getString("claim_chasis"); } } catch (SQLException ex) { System.out.println(ex); } return chasis; } public String getClaimAmountFromRoc(String idClaim) { double claimCriteriaAmount = 0.0; double rocAmount = 0.0; String query = "SELECT [claim_valor_total_imp]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { claimCriteriaAmount = resultSet.getDouble("claim_valor_total_imp"); } } catch (SQLException ex) { System.out.println(ex); } query = "SELECT [roc_amount]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_ID] = '" + idClaim + "'"; resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { rocAmount = Double.parseDouble(resultSet.getString("roc_amount").replace(",", "")); } } catch (SQLException ex) { System.out.println(ex); } String amount; DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); amount = "$" + decimalFormat.format(claimCriteriaAmount - rocAmount); return amount; } public String getClaimAmountFromRocDWH(String idClaim) { double rocAmount = 0.0; double dwhAmount = 0.0; String query = "SELECT [roc_amount]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { rocAmount = Double.parseDouble(resultSet.getString("roc_amount").replace(",", "")); } } catch (SQLException ex) { System.out.println(ex); } query = "SELECT [dwh_total_sin_profit]\n" + "FROM [criterios_logicos].[dbo].[dwh]\n" + "WHERE [dwh_ID] = '" + idClaim + "'"; resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { dwhAmount = resultSet.getDouble("dwh_total_sin_profit"); } } catch (SQLException ex) { System.out.println(ex); } String amount; DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); amount = "$" + decimalFormat.format(rocAmount - dwhAmount); return amount; } public String getClaimAmountFromDWH(String idClaim) { double claimCriteriaAmount = 0.0; double dwhAmount = 0.0; String query = "SELECT [claim_valor_total_imp]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_ID] = '" + idClaim + "'"; ResultSet resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { claimCriteriaAmount = resultSet.getDouble("claim_valor_total_imp"); } } catch (SQLException ex) { System.out.println(ex); } query = "SELECT [dwh_total_sin_profit]\n" + "FROM [criterios_logicos].[dbo].[dwh]\n" + "WHERE [dwh_ID] = '" + idClaim + "'"; resultSet = resultSetFromQuery(query); try { while (resultSet.next()) { dwhAmount = resultSet.getDouble("dwh_total_sin_profit"); } } catch (SQLException ex) { System.out.println(ex); } String amount; DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); amount = "$" + decimalFormat.format(claimCriteriaAmount - dwhAmount); return amount; } /** * This method will get the ID's of all the claims from the data warehouse * It's used in the getResultSetFromDataDWarehouse methods * * @return */ private HashMap<String, String> getDwhClaims(String initialDate, String finalDate) { HashMap<String, String> map = new HashMap(); String queryContent = "SELECT [dwh_ID]\n" + "FROM [criterios_logicos].[dbo].[dwh]\n" + "WHERE [dwh_fecha_reclamacion] BETWEEN '" + initialDate + "' AND '" + finalDate + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); String dwhID = ""; try { while (resultSet.next()) { dwhID = resultSet.getString("dwh_ID"); if (!dwhID.equals("") || !dwhID.isEmpty() || dwhID != null) { map.put(dwhID, ""); } } } catch (SQLException ex) { System.out.println(ex); } return map; } /** * This method will return the ID's of all the roc claims It's used in the * getResultSetFromRoc method * * @return */ private HashMap<String, String> getRocClaims(String initialDate, String finalDate) { HashMap<String, String> map = new HashMap(); String queryContent = "SELECT [roc_ID]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_claim_date] BETWEEN '" + initialDate + "' AND '" + finalDate + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); String rocClaimID = ""; try { while (resultSet.next()) { rocClaimID = resultSet.getString("roc_ID"); if (!rocClaimID.isEmpty() || rocClaimID != null || !rocClaimID.equals("")) { map.put(rocClaimID, ""); } } } catch (SQLException ex) { System.out.println(ex); } return map; } /** * This method will get the ID's of all the claims from the easy It's used * in the getCanceledClaimsByCriteria method * * @return */ private HashMap<String, String> getEasyClaims(String initialDate, String finalDate) { HashMap<String, String> map = new HashMap(); String queryConten = "SELECT [easy_ID]\n" + "FROM [criterios_logicos].[dbo].[easy]\n" + "WHERE [easy_claim_date] BETWEEN '" + initialDate + "' AND '" + finalDate + "'"; ResultSet resultSet = resultSetFromQuery(queryConten); String easyClaimID = ""; try { while (resultSet.next()) { easyClaimID = resultSet.getString("easy_ID"); if (!easyClaimID.isEmpty() || easyClaimID != null || !easyClaimID.equals("")) { map.put(easyClaimID, ""); } } } catch (SQLException ex) { System.out.println(ex); } return map; } /** * This method will get the ID's of all the claims from the claim criteria * it's used in the getCanceledClaimsByAnalist method * * @return */ private HashMap<String, String> getClaimCriteriaClaims(String initialDate, String finalDate) { HashMap<String, String> map = new HashMap(); String queryContent = "SELECT [claim_ID]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_claim_date] BETWEEN '" + initialDate + "' AND '" + finalDate + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); String claimCriteriaClimID = ""; try { while (resultSet.next()) { claimCriteriaClimID = resultSet.getString("claim_ID"); if (!claimCriteriaClimID.isEmpty() || claimCriteriaClimID != null || !claimCriteriaClimID.equals("")) { map.put(claimCriteriaClimID, ""); } } } catch (SQLException ex) { System.out.println(ex); } return map; } /** * This method will get all the claims from the claim criteria It's used in * the getAdjustByAnalist/getAdjustByCriteria/getCanceledClaimsByCriteria * methods * * @return */ private LinkedHashMap<String, String> getAllClaimsFromClaimCriteria(String initialDate, String finalDate) { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); String queryContent = "SELECT [claim_ID], [claim_criterio_id]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_claim_date] BETWEEN '" + initialDate + "' AND '" + finalDate + "'\n" + "ORDER BY [claim_ID]"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { map.put(resultSet.getString("claim_ID"), resultSet.getString("claim_criterio_id")); } } catch (SQLException ex) { System.out.println(ex); } return map; } /** * This method will get all the claims from the roc It's used in the * getCanceledByAnalist method * * @return */ private LinkedHashMap<String, String> getAllClaimsFromRoc(String initialDate, String finalDate) { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); String queryContent = "SELECT [roc_ID], [roc_criterios]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_claim_date] BETWEEN '" + initialDate + "' AND '" + finalDate + "'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { map.put(resultSet.getString("roc_ID"), resultSet.getString("roc_criterios")); } } catch (SQLException ex) { System.out.println(ex); } return map; } /** * This method will get all the intelligent criteria It's used in the * getAdjustByCriteria/getCanceledClaimsByCriteria method * * @return a List with the full id of every intelligent criteria */ private LinkedHashMap<String, String> getIntelligentCriteria() { LinkedHashMap<String, String> criteria = new LinkedHashMap(); String queryContent = "SELECT [criterio_id_nuevo], [criterio_id_viejo]\n" + "FROM [criterios_logicos].[dbo].[criterio]\n" + "WHERE [criterio_tipo] = 'inteligente'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { criteria.put(resultSet.getString("criterio_id_nuevo"), resultSet.getString("criterio_id_viejo")); } } catch (SQLException ex) { System.out.println(ex); } return criteria; } /** * This method will return all the non-intelligent criteria It's used in the * getAdjustByAnalist method * * @return */ private LinkedHashMap<String, String> getRegularCriteria() { LinkedHashMap<String, String> criteria = new LinkedHashMap(); String queryContent = "SELECT [criterio_id_nuevo], [criterio_id_viejo]\n" + "FROM [criterios_logicos].[dbo].[criterio]\n" + "WHERE [criterio_tipo] != 'inteligente' " + "AND [criterio_nivel] = 'aviso al importador' " + "OR [criterio_nivel] = 'nota al importador'"; ResultSet resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { criteria.put(resultSet.getString("criterio_id_nuevo"), resultSet.getString("criterio_id_viejo")); } } catch (SQLException ex) { System.out.println(ex); } return criteria; } /** * This method will get all the non repeated claims from roc, data warehouse * and claim criteria and order them by brand It's used int the * reportTotalClaimsByBrand jsp/ReportTotalClaimsByBrandServlet * * @param initalDate * @param finalDate * @return a list of brands and it's respective number of claims (by month) */ public List<ResultSetForTotalClaims> getTotalClaimsByBrand(String initalDate, String finalDate) { //This is gonna be the final result List<ResultSetForTotalClaims> results = new ArrayList(); ResultSet resultSet; String queryContent; //This map will help to not count repeated claims HashMap<String, String> claims = new HashMap(); //Here we get the criterias by brand LinkedHashMap<String, String> productoras = new LinkedHashMap(); LinkedHashMap<String, Integer> countersForProducs = new LinkedHashMap(); //counters for each brand; //This part will get the data warehouse claims queryContent = "SELECT [dwh_id], " + "[dwh_productora], [dwh_marca]\n" + "FROM [criterios_logicos].[dbo].[dwh]\n" + "WHERE [dwh_fecha_reclamacion] BETWEEN '" + initalDate + "' AND '" + finalDate + "'"; resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { String id = resultSet.getString("dwh_id"); String marca = resultSet.getString("dwh_marca").toLowerCase(); marca = (marca.equals("audi")) ? "A" : (marca.equals("seat")) ? "S" : (marca.equals("nfz")) ? "N" : "V"; String fabricante = marca + resultSet.getString("dwh_productora").toUpperCase(); if (!claims.containsKey(id)) { claims.put(id, id); if (!productoras.containsKey(fabricante)) { productoras.put(fabricante, fabricante); Integer integer = countersForProducs.get(fabricante); if (integer == null) { integer = new Integer(0); } countersForProducs.put(fabricante, integer + 1); } else { countersForProducs.put(fabricante, countersForProducs.get(fabricante) + 1); } } } } catch (SQLException ex) { System.out.println(ex); } //This part is for get the claims from roc queryContent = "SELECT [roc_ID]," + "[roc_fabricante]\n" + "FROM [criterios_logicos].[dbo].[roc]\n" + "WHERE [roc_claim_date] BETWEEN '" + initalDate + "' AND '" + finalDate + "'"; resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { String id = resultSet.getString("roc_ID").trim(); String fabricante = resultSet.getString("roc_fabricante").toUpperCase(); if (!claims.containsKey(id)) { claims.put(id, id); if (!productoras.containsKey(fabricante)) { productoras.put(fabricante, fabricante); Integer integer = countersForProducs.get(fabricante); if (integer == null) { integer = new Integer(0); } countersForProducs.put(fabricante, integer + 1); } else { countersForProducs.put(fabricante, countersForProducs.get(fabricante) + 1); } } } } catch (SQLException ex) { System.out.println(ex); } //This part will get the data from claim claims queryContent = "SELECT [claim_ID]\n" + " ,[claim_produc], [claim_manufacturer]\n" + "FROM [criterios_logicos].[dbo].[claim]\n" + "WHERE [claim_claim_date] BETWEEN '" + initalDate + "' AND '" + finalDate + "'"; resultSet = resultSetFromQuery(queryContent); try { while (resultSet.next()) { String id = resultSet.getString("claim_ID"); String fabricante = resultSet.getString("claim_manufacturer"); String rest = resultSet.getString("claim_produc"); rest = (rest.length() == 3) ? "0" + rest : rest; fabricante += rest; if (!claims.containsKey(id)) { claims.put(id, id); if (!productoras.containsKey(fabricante)) { productoras.put(fabricante, fabricante); Integer integer = countersForProducs.get(fabricante); if (integer == null) { integer = new Integer(0); } countersForProducs.put(fabricante, integer + 1); } else { countersForProducs.put(fabricante, countersForProducs.get(fabricante) + 1); } } } } catch (SQLException ex) { System.out.println(ex); } for (Map.Entry<String, Integer> entry : countersForProducs.entrySet()) { results.add(new ResultSetForTotalClaims(Integer.toString(entry.getValue()), entry.getKey())); } Collections.sort(results); return results; } //STANDARD DATA-BASE OPS METHODS /** * this method is used for the SELECT querys * * @param query * @return a resultser with the result of the query */ public ResultSet resultSetFromQuery(String query) { try { statement = connection.createStatement(); return statement.executeQuery(query); } catch (SQLException ex) { System.out.println(ex); } return null; } /** * this method is used for the DELETE, UPDATE and INSERT querys * * @param query * @return true if the query was succesfull, false otherwise */ public boolean executeQuery(String query, boolean updatable) { try { connection.setAutoCommit(false); statement = connection.createStatement(); statement.executeUpdate(query); connection.commit(); statement.close(); return true; } catch (SQLException ex) { if (!ex.getMessage().contains("Infracción de la restricción PRIMARY KEY")) { System.out.println(ex.getMessage() + " " + query); } else { System.out.println("El registro ya existe..."); if (updatable) { query = query.toLowerCase(); String values = query.split("values")[1]; String[] vals = values.split("[,]+"); String rocID = vals[0].replace("(", ""); String numeroHits = vals[2]; String diasActivacion = vals[3]; String queryContent = "UPDATE [criterios_logicos].[dbo].[roc_mensual]\n" + "SET [roc_mensual_numero_hits] = " + numeroHits + "\n" + " ,[roc_mensual_dias_activacion] = " + diasActivacion + "\n" + "WHERE roc_mensual_ID = '" + rocID + "'"; executeQuery(queryContent, false); } } if (connection != null) { try { connection.rollback(); } catch (SQLException ex1) { System.out.println(ex1); } } } return false; } public boolean setBussinessApprovedCriteria(String id) { String queryContent = "use criterios_logicos\n" + "update criterios_logicos.dbo.criterio\n" + "set criterio_aprobado_negocio = 's'\n" + "where criterio_ID = '" + id + "'"; System.out.println(queryContent); return executeQuery(queryContent, false); } public boolean setAdminApprovedCriteria(String id) { String queryContent = "use criterios_logicos\n" + "update criterios_logicos.dbo.criterio\n" + "set criterio_aprobado_admin = 's'\n" + "where criterio_ID = '" + id + "'"; return executeQuery(queryContent, false); } public List<String> getNotAdminApprovedCriteria() { String queryContent = "USE criterios_logicos\n" + "SELECT criterio_ID\n" + "FROM criterios_logicos.dbo.criterio\n" + "WHERE criterio_aprobado_admin = 'n'\n" + "AND criterio_aprobado_negocio = 's'"; ResultSet resultSet = resultSetFromQuery(queryContent); List<String> criterios = new ArrayList<String>(); try { while (resultSet.next()) { criterios.add(resultSet.getString(1)); } } catch (SQLException ex) { System.out.println(ex); } return criterios; } public List<String> getNotBussinessApprovedCriteria() { String queryContent = "USE criterios_logicos\n" + "SELECT criterio_ID\n" + "FROM criterios_logicos.dbo.criterio\n" + "WHERE criterio_aprobado_negocio = 'n'"; ResultSet resultSet = resultSetFromQuery(queryContent); List<String> criterios = new ArrayList<String>(); try { while (resultSet.next()) { criterios.add(resultSet.getString(1)); } } catch (SQLException ex) { System.out.println(ex); } return criterios; } public boolean deleteCriteriaByID(String id) { String queryContent = "use criterios_logicos\n" + "delete from criterios_logicos.dbo.criterio\n" + "where criterio_ID = '" + id + "'"; return executeQuery(queryContent, false); } /** * this method closes the connection to the data base * * @return true if the connection was closed, false otherwise */ public boolean closeConnection() { try { connection.close(); return true; } catch (SQLException ex) { System.out.println(ex.getMessage()); } return false; } }
Python
UTF-8
1,070
3.078125
3
[]
no_license
import json import math import requests import os import search_person from decouple import config def search_score(value): API_KEY = config('API_KEY') id = value # calls tmdb api for full credits url = f'https://api.themoviedb.org/3/person/{id}/combined_credits' params = dict( api_key=API_KEY, query=id ) resp = requests.get(url=url, params=params) data = resp.json() # full credits list movies = data["cast"] # makes empty array for vote scores score_list = [] # makes array of all voters scores above zero for movie in movies: if movie["vote_average"] > 0 and movie["vote_count"] > 10: score_list.append(movie["vote_average"]) print(score_list) print(len(score_list)) # find average score of actor/actress average_score = sum(score_list)/len(score_list) print(average_score) return average_score # rounds score to hundredth def roundscore(average_score, decimals=2): multiplier = 10 ** decimals return math.ceil(average_score * multiplier) / multiplier
Java
UTF-8
1,075
3.859375
4
[]
no_license
import java.util.Comparator; public class Main { public static void main(String[] args) { // anonymous class AbstractClass abstractClassImplemented = new AbstractClass() { @Override public void makeSurrealArt(){ System.out.println("Created by Dali!"); } }; // implementation of a (functional) interface Comparator<String> stringComparator = new Comparator<String>() { @Override public int compare(String firstString, String secondString) { return firstString.compareTo(secondString); } }; stringComparator.compare("Hello", "world"); Comparator<String> stringComparatorLambda = (String firstString, String secondString) -> firstString.compareTo(secondString); System.out.println(stringComparatorLambda.compare("a", "b")); //Concatenator concat = (prependorString, appendorString) -> prependorString + appendorString; //System.out.println(concat.cat("Jan", "Jan")); } }
C++
UTF-8
824
2.515625
3
[]
no_license
/********************************************************************* Project: Dissertation Author: Josh Martin Name: Text Description: A text class for holding inforamtion for font rendering *********************************************************************/ #ifndef TEXT_H #define TEXT_H #include <string> #include <glm/glm.hpp> #include "Model.h" #include "Mesh.h" #include "Texture.h" class Text { public: Text(const char* string = "", double height = 12, Model* model = nullptr); ~Text(); void setColor(glm::vec3 color); glm::vec3& getColor(); double getScaleScreenSpace(); double getScale(); std::string& getString(); Model& getModel(); static Texture* texture; private: void generate(Model* model = nullptr); Model m_model; std::string m_string; glm::vec3 m_color; double m_height; }; #endif
Python
UTF-8
6,376
3.03125
3
[]
no_license
import os import urllib from google.appengine.api import users from google.appengine.ext import ndb import jinja2 import webapp2 template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) default_guestbook_name = 'default_guestbook' error ="" def guestbook_key(guestbook_name=default_guestbook_name): return ndb.Key('Guestbook', guestbook_name) class Author(ndb.Model): """Sub model for representing an author.""" identity = ndb.StringProperty(indexed=False) email = ndb.StringProperty(indexed=False) class Greeting(ndb.Model): """A main model for representing an individual Guestbook entry.""" title = ndb.StringProperty(indexed = False) content = ndb.StringProperty(indexed=False) date = ndb.DateTimeProperty(auto_now_add=True) class Handler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) class MainPage(Handler): def get(self): lessons=["Stage 5: Making Pages Look Good"] sub_topic=["Intro to JavaScript"] sub_topic2=["Use of JavaScript"] sub_topic3=["Replace and Append Functions"] sub_topic4=["Final Thoughts"] sub_topic_list=["JavaScript is the programming language of the web. It can change HTML content and attribitutes, it can make changes to CSS style, and it can be used to validate inpute. It gives immediate visual results from your code and runs natively in the browser. We can easily inspect our code simply by opening the JavaScript Console in the tools section of the browser.Using console.log(variablename) prints whaever information it receives to the console browser making it a very good debugging tool, especially for new developers."] sub_topic_list2=['Like other programming languages, JavaScript allows us to save data in the form of variables. The syntax is in s simpler form and easier to manipulate. The syntax is basic, just the keyword var, variable name equals some value. It looks like this: var age = 35;. Arrays, functions and even objects use the same var syntax.', 'Arrays are used to store multiple values in a single variable.They are referenced as zero index meaning the first entry in an array is in position 0.', 'Objects are variables too, but objects can contain many values. JavaScript objects are containers for named values. Using objects allows us to assign many values to the variable we defined. If we did a var name of John we could assign John an age, eye color, height and so on.'] sub_topic_list3=['JavaScript String Object has a handy function that lets you replace words that occur within the string. This comes in handy if you have a form letter with a default reference of "username". With the replace function you could grab get the persons name with an HTML form or JavaScript prompt and then replace all occurrences of "username" with the value that they entered. Examples can be found in my codepen.', 'The append() method inserts specified content at the end of the selected elements. We can also insert content at the beginning of the selected elements, using the prepend() method. The syntax is $(selector).append(content,function(index,html)).'] sub_topic_list4=['JavaScript and related tools such as jQuery, which is a Javascript Library that simplifies implementing JavaScript, makes website design and manipulation easy. jQuery greatly simplifies JavaScript programming.'] items = self.request.get_all("words") self.render("html-div-lists.html", items = items,lessons=lessons,sub_topic=sub_topic, sub_topic_list=sub_topic_list, sub_topic_list2=sub_topic_list2, sub_topic2=sub_topic2, sub_topic3=sub_topic3, sub_topic_list3=sub_topic_list3, sub_topic4=sub_topic4, sub_topic_list4=sub_topic_list4) class codepenHandler(webapp2.RequestHandler): def get(self): template_values={ 'title': 'Notes To Intro Programming', } template=jinja_env.get_template('codepen.html',) self.response.out.write(template.render(template_values)) #This code identifies the name of the wall class guestbookHandler(Handler): def get(self): guestbook_name = self.request.get('guestbook_name', default_guestbook_name) notes_query = Greeting.query( ancestor = guestbook_key(guestbook_name)).order(-Greeting.date) notes_query_number=10 notes = notes_query.fetch(notes_query_number) user = users.get_current_user() if user: url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' template_values = { 'user' : user , 'notes' : notes , 'url' : url , 'url_linktext' : url_linktext , 'error' : error } template = jinja_env.get_template('guestbook.html') self.response.write(template.render(template_values)) class Validation(webapp2.RequestHandler): def post(self): guestbook_name = self.request.get('guestbook_name', default_guestbook_name) note = Greeting(parent = guestbook_key(guestbook_name)) if not (self.request.get('content') and self.request.get('title')): global error error = "Please Leave Your Name and Comment!" else: global error error = "" note.content = self.request.get('content') note.title = self.request.get('title') note.put() query_params = {'guestbook_name': guestbook_name} self.redirect('/guestbook.html?' + urllib.urlencode(query_params)) app=webapp2.WSGIApplication([('/', MainPage), ('/codepen.html', codepenHandler), ('/guestbook.html', guestbookHandler), ('/notes', Validation) ], debug=True)
C++
UTF-8
526
2.921875
3
[]
no_license
#include <iostream> using namespace std; int main () { int n; int x,y; int left,right; int k; scanf("%d",&n); for ( k = 0; k < n; k++ ) { left = right = 0; scanf("%d %d",&x,&y); while ( !(x==1&&y==1) ) { if ( x > y ) { if ( x % y == 0 ) { left += (x-1); break; } left+=x/y; x = x%y; } else { if ( y % x == 0 ) { right += ( y-1); break; } right+=y/x; y = y%x; } } printf("Scenario #%d:\n%d %d\n\n",k+1,left,right); } return 1; }
C
UTF-8
1,914
2.578125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* server_bonus.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jchene <jchene@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/29 01:41:44 by jchene #+# #+# */ /* Updated: 2021/10/12 18:56:11 by jchene ### ########.fr */ /* */ /* ************************************************************************** */ #include "../minitalk.h" t_stack *get_stack(void) { static t_stack stack; if (stack.init == 0) { ft_bzero(&stack, sizeof(t_stack)); stack.init = 1; } return (&stack); } void decode(void) { int i; char c; int power; i = 0; c = 0; power = 1; while (i < 7) { c = c + ((get_stack()->chr[i] - '0') * power); power = power * 2; i++; } write(1, &c, 1); } void get_sig(int sig, siginfo_t *info, void *context) { (void)sig; (void)context; if (sig == SIGUSR1) get_stack()->chr[get_stack()->bit] = '1'; else if (sig == SIGUSR2) get_stack()->chr[get_stack()->bit] = '0'; else return ; get_stack()->bit++; kill(info->si_pid, SIGUSR1); if (get_stack()->bit >= 7) { get_stack()->bit = 0; decode(); } } int main(void) { struct sigaction sa; sa.sa_sigaction = (void *)get_sig; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO; get_stack()->bit = 0; ft_putnbr(getpid()); ft_putchar('\n'); sigaction(SIGUSR1, &sa, NULL); sigaction(SIGUSR2, &sa, NULL); while (1) pause(); return (0); }
Python
UTF-8
1,526
3.171875
3
[]
no_license
from cryptography.fernet import Fernet def get_switch_input(): # TODO: apply error checking mechanism since this is a dead man's switch telegram_handle = input("Telegram handle to listen on: ") reset_keyword = input("keyword to stop the dead man's switch: ") kill_switch = input("Keyword to immediately destroy key(kill switch): ") time_interval = int(input("The time interval in seconds to check for messages: ")) file = input("Relative path to the file that is about to be encrypted: ") # Check if the program has R/W privileges return telegram_handle, reset_keyword, kill_switch, time_interval, file def encrypt_file(file_path): # Encrypt the file and returns the key key = Fernet.generate_key() f = Fernet(key) with open(file_path, "rb") as file: file_data = file.read() encrypted_data = f.encrypt(file_data) with open(file_path, "wb") as file: file.write(encrypted_data) return key def decrypt_file(file_path, key): # Decrypts the file and returns status boolean f = Fernet(key) try: with open(file_path, "rb") as file: encrypted_data = file.read() decrypted_data = f.decrypt(encrypted_data) with open(file_path, "wb") as file: file.write(decrypted_data) return True except Exception: return False def write_key_to_file(file_path, key): with open("keys.txt", "a") as key_file: key_file.write(f"The key for {file_path}: ${key}") return
Ruby
UTF-8
8,678
2.546875
3
[ "MIT" ]
permissive
require 'microsoft_kiota_abstractions' require_relative '../microsoft_graph' require_relative './models' module MicrosoftGraph module Models class Directory < MicrosoftGraph::Models::Entity include MicrosoftKiotaAbstractions::Parsable ## # Conceptual container for user and group directory objects. @administrative_units ## # Group of related custom security attribute definitions. @attribute_sets ## # Schema of a custom security attributes (key-value pairs). @custom_security_attribute_definitions ## # Recently deleted items. Read-only. Nullable. @deleted_items ## # Configure domain federation with organizations whose identity provider (IdP) supports either the SAML or WS-Fed protocol. @federation_configurations ## # A container for on-premises directory synchronization functionalities that are available for the organization. @on_premises_synchronization ## ## Gets the administrativeUnits property value. Conceptual container for user and group directory objects. ## @return a administrative_unit ## def administrative_units return @administrative_units end ## ## Sets the administrativeUnits property value. Conceptual container for user and group directory objects. ## @param value Value to set for the administrativeUnits property. ## @return a void ## def administrative_units=(value) @administrative_units = value end ## ## Gets the attributeSets property value. Group of related custom security attribute definitions. ## @return a attribute_set ## def attribute_sets return @attribute_sets end ## ## Sets the attributeSets property value. Group of related custom security attribute definitions. ## @param value Value to set for the attributeSets property. ## @return a void ## def attribute_sets=(value) @attribute_sets = value end ## ## Instantiates a new directory and sets the default values. ## @return a void ## def initialize() super end ## ## Creates a new instance of the appropriate class based on discriminator value ## @param parse_node The parse node to use to read the discriminator value and create the object ## @return a directory ## def self.create_from_discriminator_value(parse_node) raise StandardError, 'parse_node cannot be null' if parse_node.nil? return Directory.new end ## ## Gets the customSecurityAttributeDefinitions property value. Schema of a custom security attributes (key-value pairs). ## @return a custom_security_attribute_definition ## def custom_security_attribute_definitions return @custom_security_attribute_definitions end ## ## Sets the customSecurityAttributeDefinitions property value. Schema of a custom security attributes (key-value pairs). ## @param value Value to set for the customSecurityAttributeDefinitions property. ## @return a void ## def custom_security_attribute_definitions=(value) @custom_security_attribute_definitions = value end ## ## Gets the deletedItems property value. Recently deleted items. Read-only. Nullable. ## @return a directory_object ## def deleted_items return @deleted_items end ## ## Sets the deletedItems property value. Recently deleted items. Read-only. Nullable. ## @param value Value to set for the deletedItems property. ## @return a void ## def deleted_items=(value) @deleted_items = value end ## ## Gets the federationConfigurations property value. Configure domain federation with organizations whose identity provider (IdP) supports either the SAML or WS-Fed protocol. ## @return a identity_provider_base ## def federation_configurations return @federation_configurations end ## ## Sets the federationConfigurations property value. Configure domain federation with organizations whose identity provider (IdP) supports either the SAML or WS-Fed protocol. ## @param value Value to set for the federationConfigurations property. ## @return a void ## def federation_configurations=(value) @federation_configurations = value end ## ## The deserialization information for the current model ## @return a i_dictionary ## def get_field_deserializers() return super.merge({ "administrativeUnits" => lambda {|n| @administrative_units = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::AdministrativeUnit.create_from_discriminator_value(pn) }) }, "attributeSets" => lambda {|n| @attribute_sets = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::AttributeSet.create_from_discriminator_value(pn) }) }, "customSecurityAttributeDefinitions" => lambda {|n| @custom_security_attribute_definitions = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::CustomSecurityAttributeDefinition.create_from_discriminator_value(pn) }) }, "deletedItems" => lambda {|n| @deleted_items = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::DirectoryObject.create_from_discriminator_value(pn) }) }, "federationConfigurations" => lambda {|n| @federation_configurations = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::IdentityProviderBase.create_from_discriminator_value(pn) }) }, "onPremisesSynchronization" => lambda {|n| @on_premises_synchronization = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::OnPremisesDirectorySynchronization.create_from_discriminator_value(pn) }) }, }) end ## ## Gets the onPremisesSynchronization property value. A container for on-premises directory synchronization functionalities that are available for the organization. ## @return a on_premises_directory_synchronization ## def on_premises_synchronization return @on_premises_synchronization end ## ## Sets the onPremisesSynchronization property value. A container for on-premises directory synchronization functionalities that are available for the organization. ## @param value Value to set for the onPremisesSynchronization property. ## @return a void ## def on_premises_synchronization=(value) @on_premises_synchronization = value end ## ## Serializes information the current object ## @param writer Serialization writer to use to serialize this model ## @return a void ## def serialize(writer) raise StandardError, 'writer cannot be null' if writer.nil? super writer.write_collection_of_object_values("administrativeUnits", @administrative_units) writer.write_collection_of_object_values("attributeSets", @attribute_sets) writer.write_collection_of_object_values("customSecurityAttributeDefinitions", @custom_security_attribute_definitions) writer.write_collection_of_object_values("deletedItems", @deleted_items) writer.write_collection_of_object_values("federationConfigurations", @federation_configurations) writer.write_collection_of_object_values("onPremisesSynchronization", @on_premises_synchronization) end end end end
TypeScript
UTF-8
801
2.5625
3
[ "MIT" ]
permissive
export interface Page { name: string; path: string; pages?: Page[]; isPrivate?: boolean; } export const INDEX: Page = { name: 'Home', path: '/', }; export const LOGIN: Page = { name: 'Login', path: '/login', }; export const LOGOUT: Page = { name: 'Logout', path: '/logout', }; export const SUBPAGE: Page = { name: 'Subpage', path: '/page-a/subpage', }; export const PAGE_A: Page = { name: 'Page A', path: '/page-a', pages: [SUBPAGE], }; export const PRIVATE: Page = { name: 'Private', path: '/private', isPrivate: true, }; export const USERS: Page = { name: 'Users', path: '/users', }; export const ERROR_404: Page = { name: 'Error 404', path: '*', }; const PAGES = [PAGE_A, PRIVATE, INDEX, LOGIN, LOGOUT, USERS, ERROR_404]; export default PAGES;
PHP
UTF-8
27,293
2.5625
3
[]
no_license
<?php class CG_BitBangedI2CController extends CG_Controller { protected function _GenerateCCode($model=NUll, $processor_type='') { /* SCLPORT */ if($model->scl_port == 'PORTA') { $latSCLName = 'LATA'; $portSCLName = 'PORTA'; $portSCLTris = 'TRISA'; } else if($model->scl_port == 'PORTB') { $latSCLName = 'LATB'; $portSCLName = 'PORTB'; $portSCLTris = 'TRISB'; } else if($model->scl_port == 'PORTC') { $latSCLName = 'LATC'; $portSCLName = 'PORTC'; $portSCLTris = 'TRISC'; } else if($model->scl_port == 'PORTD') { $latSCLName = 'LATD'; $portSCLName = 'PORTD'; $portSCLTris = 'TRISD'; } else if($model->scl_port == 'PORTE') { $latSCLName = 'LATE'; $portSCLName = 'PORTE'; $portSCLTris = 'TRISE'; } else if($model->scl_port == 'PORTJ') { $latSCLName = 'LATJ'; $portSCLName = 'PORTJ'; $portSCLTris = 'TRISJ'; } /* SDAPORT */ if($model->sda_port == 'PORTA') { $latSDAName = 'LATA'; $portSDAName = 'PORTA'; $portSDATris = 'TRISA'; } else if($model->sda_port == 'PORTB') { $latSDAName = 'LATB'; $portSDAName = 'PORTB'; $portSDATris = 'TRISB'; } else if($model->sda_port == 'PORTC') { $latSDAName = 'LATC'; $portSDAName = 'PORTC'; $portSDATris = 'TRISC'; } else if($model->sda_port == 'PORTD') { $latSDAName = 'LATD'; $portSDAName = 'PORTD'; $portSDATris = 'TRISD'; } else if($model->sda_port == 'PORTE') { $latSDAName = 'LATE'; $portSDAName = 'PORTE'; $portSDATris = 'TRISE'; } else if($model->sda_port == 'PORTJ') { $latSDAName = 'LATJ'; $portSDAName = 'PORTJ'; $portSDATris = 'TRISJ'; } /* SCLBIT */ if($model->scl_bit == 'Bit 0') $bitSCL = '0x0001'; else if($model->scl_bit == 'Bit 1') $bitSCL = '0x0002'; else if($model->scl_bit == 'Bit 2') $bitSCL = '0x0004'; else if($model->scl_bit == 'Bit 3') $bitSCL = '0x0008'; else if($model->scl_bit == 'Bit 4') $bitSCL = '0x0010'; else if($model->scl_bit == 'Bit 5') $bitSCL = '0x0020'; else if($model->scl_bit == 'Bit 6') $bitSCL = '0x0040'; else if($model->scl_bit == 'Bit 7') $bitSCL = '0x0080'; else if($model->scl_bit == 'Bit 8') $bitSCL = '0x0100'; else if($model->scl_bit == 'Bit 9') $bitSCL = '0x0200'; else if($model->scl_bit == 'Bit 10') $bitSCL = '0x0400'; else if($model->scl_bit == 'Bit 11') $bitSCL = '0x0800'; else if($model->scl_bit == 'Bit 12') $bitSCL = '0x1000'; else if($model->scl_bit == 'Bit 13') $bitSCL = '0x2000'; else if($model->scl_bit == 'Bit 14') $bitSCL = '0x4000'; else if($model->scl_bit == 'Bit 15') $bitSCL = '0x8000'; /* SDABIT */ if($model->sda_bit == 'Bit 0') $bitSDA = '0x0001'; else if($model->sda_bit == 'Bit 1') $bitSDA = '0x0002'; else if($model->sda_bit == 'Bit 2') $bitSDA = '0x0004'; else if($model->sda_bit == 'Bit 3') $bitSDA = '0x0008'; else if($model->sda_bit == 'Bit 4') $bitSDA = '0x0010'; else if($model->sda_bit == 'Bit 5') $bitSDA = '0x0020'; else if($model->sda_bit == 'Bit 6') $bitSDA = '0x0040'; else if($model->sda_bit == 'Bit 7') $bitSDA = '0x0080'; else if($model->sda_bit == 'Bit 8') $bitSDA = '0x0100'; else if($model->sda_bit == 'Bit 9') $bitSDA = '0x0200'; else if($model->sda_bit == 'Bit 10') $bitSDA = '0x0400'; else if($model->sda_bit == 'Bit 11') $bitSDA = '0x0800'; else if($model->sda_bit == 'Bit 12') $bitSDA = '0x1000'; else if($model->sda_bit == 'Bit 13') $bitSDA = '0x2000'; else if($model->sda_bit == 'Bit 14') $bitSDA = '0x4000'; else if($model->sda_bit == 'Bit 15') $bitSDA = '0x8000'; // if(!$model->ContainsEmptyAttribute()) // { $code = PHP_EOL.'/************************************************'.PHP_EOL; $code .= ' * To obtain a copy of PicCodeGen go to'.PHP_EOL; $code .= ' * http://www.kmitechnology.com/.'.PHP_EOL; $code .= ' *'.PHP_EOL; $code .= ' ************************************************/'.PHP_EOL; $code .= PHP_EOL; $code .= '#include "bbI2C.h"'.PHP_EOL; $code .= PHP_EOL; $code .= PHP_EOL; $code .= "#include <{$processor_type}.h>".PHP_EOL; $code .= PHP_EOL; $code .= PHP_EOL; $code .= '#define I2CSDA1 '.$portSDAName.' = '.$portSDAName.' | '.$bitSDA.PHP_EOL; $code .= '#define I2CSDA0 '.$portSDAName.' = '.$portSDAName.' & ~'.$bitSDA.PHP_EOL; $code .= '#define I2CSDA ('.$portSDAName.' & '.$bitSDA.')'.PHP_EOL; $code .= PHP_EOL; $code .= '#define I2CSDAIN ('.$portSDATris.' = '.$portSDATris.' | '.$bitSDA.')'.PHP_EOL; $code .= '#define I2CSDAOUT ('.$portSDATris.' = '.$portSDATris.' & ~'.$bitSDA.')'.PHP_EOL; $code .= PHP_EOL; $code .= '#define I2CSCL1 '.$portSCLName.' = '.$portSCLName.' | '.$bitSCL.PHP_EOL; $code .= '#define I2CSCL0 '.$portSCLName.' = '.$portSCLName.' & ~'.$bitSCL.PHP_EOL; $code .= '#define I2CSCL ('.$portSCLName.' & '.$bitSCL.')'.PHP_EOL; $code .= PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2cSDA1(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' '.$latSDAName.' = '.$latSDAName.' | '.$bitSDA.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2cSDA0(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' '.$portSDAName.' = '.$portSDAName.' & ~'.$bitSDA.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'unsigned int'.PHP_EOL; $code .= 'i2cSDA(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' return '.$portSDAName.' & '.$bitSDA.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2cSDAIN(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' '.$portSDATris.' = '.$portSDATris.' | '.$bitSDA.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2cSDAOUT(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' '.$portSDATris.' = '.$portSDATris.' & ~'.$bitSDA.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2cSCL1(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' '.$latSCLName.' = '.$latSCLName.' | '.$bitSCL.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2cSCL0(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' '.$portSCLName.' = '.$portSCLName.' & ~'.$bitSCL.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'unsigned int'.PHP_EOL; $code .= 'i2cSCL(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' return '.$portSCLName.' & '.$bitSCL.';'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= 'unsigned char NoACK;'.PHP_EOL; $code .= PHP_EOL; $code .= '//'.PHP_EOL; $code .= '//! @par Function:'.PHP_EOL; $code .= '//! SyncClock'.PHP_EOL; $code .= '//!'.PHP_EOL; $code .= '//! @par Synopsis:'.PHP_EOL; $code .= '//! This routine verifies that the scl is free. If'.PHP_EOL; $code .= '//! this I/O bit remains low then I can\'t toggle it to talk to'.PHP_EOL; $code .= '//! the I2C device attached to the bus.'.PHP_EOL; $code .= '//!'.PHP_EOL; $code .= '//! @return 1 when the clock is working and 0 if the clock isn\'t'.PHP_EOL; $code .= '//! working.'.PHP_EOL; $code .= '//!'.PHP_EOL; $code .= '//! @par Globals:'.PHP_EOL; $code .= '//! None'.PHP_EOL; $code .= '//'.PHP_EOL; $code .= 'unsigned char'.PHP_EOL; $code .= 'SyncClock(void) '.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' int clockbad;'.PHP_EOL; $code .= ' // Configure Timer 0 as a 16-bit timer '.PHP_EOL; $code .= PHP_EOL; $code .= ' clockbad = 0;'.PHP_EOL; $code .= ' // Try to synchronise the clock'.PHP_EOL; $code .= ' while ((I2CSCL == 0) && (clockbad < 16384)) '.PHP_EOL; $code .= ' clockbad++; '.PHP_EOL; $code .= PHP_EOL; $code .= ' if (clockbad == 16384)'.PHP_EOL; $code .= ' {'.PHP_EOL; $code .= ' return 0; // Error - Timeout condition failed'.PHP_EOL; $code .= ' }'.PHP_EOL; $code .= ' return 1; // OK - Clock synchronised'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= '//'.PHP_EOL; $code .= '//! @par Procedure:'.PHP_EOL; $code .= '//! i2cinit'.PHP_EOL; $code .= '//!'.PHP_EOL; $code .= '//! @par Synopsis:'.PHP_EOL; $code .= '//! This routine grabs the necessary two bits for'.PHP_EOL; $code .= '//! I2C communication. It then puts them into the proper state.'.PHP_EOL; $code .= '//!'.PHP_EOL; $code .= '//! @par Globals:'.PHP_EOL; $code .= '//! Changes TRISJ, I2CSDA1, and I2CSCL1.'.PHP_EOL; $code .= '//'.PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2cinit(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= ' i2cSDA1();'.PHP_EOL; $code .= ' i2cSCL1();'.PHP_EOL; $code .= ' '.$portSDATris.' &= ~'.$bitSDA.';'.PHP_EOL; $code .= ' '.$portSCLTris.' &= ~'.$bitSCL.';'.PHP_EOL; $code .= '//#define I2CSDAOUT ('.$portSDATris.' &= ~'.$bitSDA.')'.PHP_EOL; $code .= '// TRISJ &= ~0x03;'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= PHP_EOL; $code .= '//'.PHP_EOL; $code .= '//! @par Procedure:'.PHP_EOL; $code .= '//! i2crelease'.PHP_EOL; $code .= '//!'.PHP_EOL; $code .= '//! @par Synopsis:'.PHP_EOL; $code .= '//! This routine returns the two I2C bits back to the'.PHP_EOL; $code .= '//! system. It changes them to input.'.PHP_EOL; $code .= '//! @par Globals:'.PHP_EOL; $code .= '//! Changes TRISJ'.PHP_EOL; $code .= '//'.PHP_EOL; $code .= 'void'.PHP_EOL; $code .= 'i2crelease(void)'.PHP_EOL; $code .= '{'.PHP_EOL; $code .= '// TRISJ |= 0x03;'.PHP_EOL; $code .= '}'.PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= " //! @par Procedure:".PHP_EOL; $code .= "//! i2cdelay".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This routine is a simple delay routine.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par globals:".PHP_EOL; $code .= "//! none".PHP_EOL; $code .= "//".PHP_EOL; $code .= "void".PHP_EOL; $code .= "i2cdelay(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " long x;".PHP_EOL; $code .= "".PHP_EOL; $code .= " x = 0;".PHP_EOL; $code .= " x++;".PHP_EOL; $code .= " x++;".PHP_EOL; $code .= " x++;".PHP_EOL; $code .= " x++;".PHP_EOL; $code .= " x++;".PHP_EOL; $code .= " x++;".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Procedure:".PHP_EOL; $code .= "//! i2cstart".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This procedure generates a I2C start condition on the".PHP_EOL; $code .= "//! two I2C lines.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! changes I2CSDA and I2CSCL".PHP_EOL; $code .= "//".PHP_EOL; $code .= "void".PHP_EOL; $code .= "i2cstart(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= " i2cSCL1();".PHP_EOL; $code .= " if (SyncClock())".PHP_EOL; $code .= " ;".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSDA0();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSCL0();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Procedure:".PHP_EOL; $code .= "//! i2cstop".PHP_EOL; $code .= "//! ".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This routine generates a stop conditions on the I2C pins.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! Changes I2CSDA AND I2CSCL".PHP_EOL; $code .= "//".PHP_EOL; $code .= "void".PHP_EOL; $code .= "i2cstop(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " i2cSDA0();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSCL1();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Procedure:".PHP_EOL; $code .= "//! i2cres".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This procedure resets all I2C devices on the I2C bus.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! Changes I2CSCL and I2CSDA".PHP_EOL; $code .= "//".PHP_EOL; $code .= "void".PHP_EOL; $code .= "i2cres(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " unsigned char i;".PHP_EOL; $code .= "".PHP_EOL; $code .= " for (i=0; i<9; i++) {".PHP_EOL; $code .= " i2cSCL0();".PHP_EOL; $code .= " i2cSDA0();".PHP_EOL; $code .= " i2cstop();".PHP_EOL; $code .= " }".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Procedure:".PHP_EOL; $code .= "//! i2csendbyte".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This procedure sends a byte to an addressed I2C device.".PHP_EOL; $code .= "//! This routine expects a start to have been generated along with the I2C".PHP_EOL; $code .= "//! device has been addressed. It doesn't do a i2cstop. It leaves the".PHP_EOL; $code .= "//! bus in a state to send another byte.".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @param bytetosend byte to send".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! Changes I2CSDA and I2CSCL".PHP_EOL; $code .= "//".PHP_EOL; $code .= "void".PHP_EOL; $code .= "i2csendbyte(unsigned char bytetosend) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " unsigned char i;".PHP_EOL; $code .= "".PHP_EOL; $code .= " i = 8;".PHP_EOL; $code .= "".PHP_EOL; $code .= "".PHP_EOL; $code .= " while (i > 0) {".PHP_EOL; $code .= " i--;".PHP_EOL; $code .= " if (bytetosend & (1 << i)) {".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= " } else {".PHP_EOL; $code .= " i2cSDA0();".PHP_EOL; $code .= " }".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSCL1();".PHP_EOL; $code .= " if (SyncClock())".PHP_EOL; $code .= " ;".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSCL0();".PHP_EOL; $code .= " //i2cdelay();".PHP_EOL; $code .= " }".PHP_EOL; $code .= " //i2cSDA1();".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Function:".PHP_EOL; $code .= "//! i2cgetack".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This function waits for an ack from the I2C device. If the".PHP_EOL; $code .= "//! device doesn't ack a NoACK value is returned.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! Changes NoAck, I2CSDAIN, I2CSCL, and I2CSDA".PHP_EOL; $code .= "//".PHP_EOL; $code .= "unsigned char".PHP_EOL; $code .= "i2cgetack(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " NoACK = 0;".PHP_EOL; $code .= " i2cSDAIN();".PHP_EOL; $code .= " //i2cSDA1();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSCL1();".PHP_EOL; $code .= " if (SyncClock())".PHP_EOL; $code .= " ;".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " //while (i2csda != 0) ;".PHP_EOL; $code .= " NoACK = i2cSDA();".PHP_EOL; $code .= " i2cSCL0();".PHP_EOL; $code .= " i2cSDAOUT();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " return NoACK;".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Function:".PHP_EOL; $code .= "//! i2cgetbyte".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This function reads a byte from the I2C device. It returns".PHP_EOL; $code .= "//! this byte to the calling routine.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! Changes I2CSCL, I2CSDA, and I2CSDAIN".PHP_EOL; $code .= "//".PHP_EOL; $code .= "unsigned char".PHP_EOL; $code .= "i2cgetbyte(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " unsigned char i;".PHP_EOL; $code .= " unsigned char rxbyte;".PHP_EOL; $code .= "".PHP_EOL; $code .= " rxbyte = 0;".PHP_EOL; $code .= " i = 8;".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= " i2cSDAIN();".PHP_EOL; $code .= " while (i > 0) {".PHP_EOL; $code .= " I2CSCL1;".PHP_EOL; $code .= " if (SyncClock())".PHP_EOL; $code .= " ;".PHP_EOL; $code .= " //i2cdelay();".PHP_EOL; $code .= " i--;".PHP_EOL; $code .= " if (i2cSDA()) {".PHP_EOL; $code .= " rxbyte |= (1 << i);".PHP_EOL; $code .= " }".PHP_EOL; $code .= " i2cSCL0();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " }".PHP_EOL; $code .= " i2cSDA0();".PHP_EOL; $code .= " i2cSDAOUT();".PHP_EOL; $code .= "".PHP_EOL; $code .= " return rxbyte;".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Procedure:".PHP_EOL; $code .= "//! i2csendack".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This procedure sends an ACK to the I2C device.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! changes I2CSDA and I2CSCL".PHP_EOL; $code .= "//".PHP_EOL; $code .= "void".PHP_EOL; $code .= "i2csendack(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " i2cSDA0();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSCL1();".PHP_EOL; $code .= " if (SyncClock())".PHP_EOL; $code .= " ;".PHP_EOL; $code .= " //i2cdelay();".PHP_EOL; $code .= " i2cSCL0();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "//".PHP_EOL; $code .= "//! @par Procedure:".PHP_EOL; $code .= "//! i2csendnack".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Synopsis:".PHP_EOL; $code .= "//! This procedure sends a NACK to the I2C device.".PHP_EOL; $code .= "//!".PHP_EOL; $code .= "//! @par Globals:".PHP_EOL; $code .= "//! changes I2CSDA and I2CSCL".PHP_EOL; $code .= "//".PHP_EOL; $code .= "void".PHP_EOL; $code .= "i2csendnack(void) ".PHP_EOL; $code .= "{".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSCL1();".PHP_EOL; $code .= " if (SyncClock())".PHP_EOL; $code .= " ;".PHP_EOL; $code .= " //i2cdelay();".PHP_EOL; $code .= " i2cSCL0();".PHP_EOL; $code .= " i2cdelay();".PHP_EOL; $code .= " i2cSDA1();".PHP_EOL; $code .= "}".PHP_EOL; $code .= "".PHP_EOL; $code .= "int".PHP_EOL; $code .= "main()".PHP_EOL; $code .= "{".PHP_EOL; $code .= " unsigned char data[8];".PHP_EOL; $code .= "".PHP_EOL; $code .= " AD1PCFG = 0xFFFF;".PHP_EOL; $code .= " data[0] = 1;".PHP_EOL; $code .= " data[1] = 2;".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cinit();".PHP_EOL; $code .= " PORTB = 0x3FF;".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cstart();".PHP_EOL; $code .= " i2csendbyte(0x90);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= " i2csendbyte(0xAC);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cstart();".PHP_EOL; $code .= " i2csendbyte(0x02);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= " i2cstop();".PHP_EOL; $code .= "".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cstart();".PHP_EOL; $code .= " i2csendbyte(0x90);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= " i2csendbyte(0xEE);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= "".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cstop();".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cstart();".PHP_EOL; $code .= " i2csendbyte(0x90);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= " i2csendbyte(0xAA);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= "".PHP_EOL; $code .= " i2cstart();".PHP_EOL; $code .= " i2csendbyte(0x91);".PHP_EOL; $code .= " i2cgetack();".PHP_EOL; $code .= " data[0] = i2cgetbyte();".PHP_EOL; $code .= " i2csendack();".PHP_EOL; $code .= " data[1] = i2cgetbyte();".PHP_EOL; $code .= " i2csendnack();".PHP_EOL; $code .= " i2cstop();".PHP_EOL; $code .= PHP_EOL; $code .= PHP_EOL; $code .= PHP_EOL; $code .= " while (1)".PHP_EOL; $code .= " ;".PHP_EOL; $code .= "}".PHP_EOL; // } return $code; } /* * Bit Banged I2C header file */ protected function _GenerateHCode($model=NULL, $processor_type='') { $hFile = '/************************************************'.PHP_EOL; $hFile .= ' * bbI2C.h is automatically generated by PicCodeGen'.PHP_EOL; $hFile .= ' * Please do not change.'.PHP_EOL; $hFile .= ' *'.PHP_EOL; $hFile .= ' * To obtain a copy of PicCodeGen go to'.PHP_EOL; $hFile .= ' * http://www.kmitechnology.com/.'.PHP_EOL; $hFile .= ' *'.PHP_EOL; $hFile .= ' ************************************************/'.PHP_EOL; $hFile .= PHP_EOL.PHP_EOL.PHP_EOL; $hFile .= 'void i2cinit(void);'.PHP_EOL; $hFile .= 'void i2cstart(void);'.PHP_EOL; $hFile .= 'void i2csendbyte(unsigned char bytetosend);'.PHP_EOL; $hFile .= 'unsigned char i2cgetack(void);'.PHP_EOL; $hFile .= 'unsigned char i2cgetbyte(void);'.PHP_EOL; $hFile .= 'void i2csendack(void);'.PHP_EOL; $hFile .= 'unsigned char i2cgetack(void);'.PHP_EOL; $hFile .= 'void i2cstop(void);'.PHP_EOL; $hFile .= 'void i2csendnack(void);'.PHP_EOL; return $hFile; } }
C
UTF-8
4,265
2.890625
3
[]
no_license
#include "common.h" #include <inttypes.h> void mem_read(uintptr_t block_num, uint8_t *buf); void mem_write(uintptr_t block_num, const uint8_t *buf); static uint64_t cycle_cnt = 0; static uintptr_t tag, group_num, block_num; // 标记,组号,内存块内地址 typedef struct { bool valid_bit; // true已写入, false未写入 bool dirty_bit; // true修改, false未修改 uint8_t Block[64]; // 64B uint32_t tag; } Cache_block; Cache_block Cache[64][4]; // 4*64*64 = 16KB size可以修改,此处为了适配main.c中的初始化 void cycle_increase(int n) { cycle_cnt += n; } // TODO: implement the following functions uint32_t cache_read(uintptr_t addr) { bool is_hit = false; bool empty; tag = (addr >> 12) ; group_num = (addr >> 6) & 0x3f; block_num = addr & 0x3f; uint32_t *ret; for (int i = 0; i < 4; i++){ if (Cache[group_num][i].tag == tag && Cache[group_num][i].valid_bit == true){ ret = (void *)(Cache[group_num][i].Block) + (block_num & ~0x3); is_hit = true; break; } } if (is_hit == false){ empty = false; for (int i = 0; i < 4; i++){ if(Cache[group_num][i]. valid_bit == false){ empty = true; mem_read(addr >> 6, Cache[group_num][i].Block); ret = (void *)(Cache[group_num][i].Block) + (block_num & ~0x3); Cache[group_num][i].tag = tag; Cache[group_num][i].valid_bit = true; Cache[group_num][i].dirty_bit = false; break; } } if (empty == false){ int chose_place = rand() % 4; if (Cache[group_num][chose_place].dirty_bit == true){ mem_write(Cache[group_num][chose_place].tag << 6 | group_num, Cache[group_num][chose_place].Block); } mem_read(addr >> 6, Cache[group_num][chose_place].Block); ret = (void *)(Cache[group_num][chose_place].Block) + (block_num & ~0x3); Cache[group_num][chose_place].tag = tag; Cache[group_num][chose_place].valid_bit = true; Cache[group_num][chose_place].dirty_bit = false; } } return *ret; } void cache_write(uintptr_t addr, uint32_t data, uint32_t wmask) { bool is_hit = false; bool empty; tag = (addr >> 12) ; group_num = (addr >> 6) & 0x3f; block_num = addr & 0x3f; for (int i = 0; i < 4; i++){ if (Cache[group_num][i].tag == tag && Cache[group_num][i].valid_bit == true){ is_hit = true; uint32_t *place = (void *)(Cache[group_num][i].Block) + (block_num & ~0x3); *place = (*place & ~wmask) | (data & wmask); Cache[group_num][i].dirty_bit = true; } } if (is_hit == false){ empty = false; for (int i = 0; i < 4; i++){ if(Cache[group_num][i]. valid_bit == false){ empty = true; mem_read(addr >> 6, Cache[group_num][i].Block); uint32_t *place = (void *)(Cache[group_num][i].Block) + (block_num & ~0x3); *place = (*place & ~wmask) | (data & wmask); mem_write(addr >> 6, Cache[group_num][i].Block); Cache[group_num][i].tag = tag; Cache[group_num][i].valid_bit = true; Cache[group_num][i].dirty_bit = false; break; } } if (empty == false){ int chose_place = rand() % 4; if (Cache[group_num][chose_place].dirty_bit == true){ mem_write(Cache[group_num][chose_place].tag << 6 | group_num, Cache[group_num][chose_place].Block); } mem_read(addr >> 6, Cache[group_num][chose_place].Block); uint32_t *place = (void *)(Cache[group_num][chose_place].Block) + (block_num & ~0x3); *place = (*place & ~wmask) | (data & wmask); mem_write(addr >> 6, Cache[group_num][chose_place].Block); Cache[group_num][chose_place].tag = tag; Cache[group_num][chose_place].valid_bit = true; Cache[group_num][chose_place].dirty_bit = false; } } } void init_cache(int total_size_width, int associativity_width) { int tol_size = 1 << total_size_width; // cache总大小 int association = 1 << associativity_width; // cache关联度大小,也即每组行数 for(int i = 0; i < tol_size / BLOCK_SIZE / association; i ++) for (int j = 0; j < association; j ++){ Cache[i][j].valid_bit = false; Cache[i][j].dirty_bit = false; } } void display_statistic(void) { }
PHP
UTF-8
2,484
2.765625
3
[]
no_license
<?php if (isset($_POST['submit-signup'])) { include_once 'dbh.inc.php'; session_start(); //prepare and bind $stmt = $conn->prepare("INSERT INTO users (user_first, user_last, user_username, user_password, user_email, user_profile_pic) VALUES (?, ?, ?, ?, ?, ?);"); $stmt->bind_param("ssssss", $first, $last, $username, $hashedPassword, $email, $pic); $first = mysqli_real_escape_string($conn, $_POST['first']); $last = mysqli_real_escape_string($conn, $_POST['last']); $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']); $email = mysqli_real_escape_string($conn, $_POST['email']); $pic = 'default.png'; //Error handlers //Check for empty fields if(empty($first) || empty($last) || empty($username) || empty($password) || empty($email)){ header("Location: ../signup.php?signup=empty"); exit(); }else{ //Check if input characters are valid if(!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last) || !preg_match("/^[a-zA-Z0-9]*$/", $username)){ header("Location: ../signup.php?signup=invalid"); exit(); }else{ //Check if email is valid if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ header("Location: ../signup.php?signup=email"); exit(); }else{ //Check if email is taken $sql = "SELECT * FROM users WHERE user_email ='$email'"; $result = mysqli_query($conn, $sql); $resultCheck = mysqli_num_rows($result); if($resultCheck > 0){ header("Location: ../signup.php?signup=emailtaken"); exit(); }else{ $sql = "SELECT * FROM users WHERE user_username ='$username'"; $result = mysqli_query($conn, $sql); $resultCheck = mysqli_num_rows($result); if($resultCheck > 0){ header("Location: ../signup.php?signup=usertaken"); exit(); }else{ //All tests have been passed successfully //Hashing the Password $hashedPassword = password_hash($password, PASSWORD_DEFAULT); //Insert the user into the database //stmt execute $stmt->execute(); header("Location: ../signup.php?signup=success"); exit(); } } } } } }else{ header("Location: ../signup.php"); exit(); }
PHP
UTF-8
513
2.640625
3
[ "MIT" ]
permissive
<?php namespace Otisz\Billingo\Services; use Otisz\Billingo\Facades\Billingo; class PaymentMethods { /** * Get a listing of payment methods * * @example https://billingo.readthedocs.io/en/latest/payment_methods/#list-the-available-payment-methods * * @param string $langCode Language code. Can be any of hu, en, or de * * @return array */ public function all(string $langCode): array { return Billingo::get("payment_methods/{$langCode}"); } }
JavaScript
UTF-8
4,292
2.9375
3
[]
no_license
var redis = require("redis"); // Define amount of cycles var maxcycles = process.env.IMTCYCLES; if (!maxcycles) { maxcycles = 10; } // Create connection, depending on your environment var connection = process.env.IMTCONNECT; if (!connection) { connection = 'LOCALHOST'; } var dbport = process.env.IMTDBPORT; if (!dbport) { dbport = 6379; } var dbip = process.env.IMTDBIP; if (!dbip) { dbip = '127.0.0.1'; } switch (connection) { case "LOCALHOST": var client = redis.createClient(); console.log('Connecting to localhost...') break; case "INTERNET": var client = redis.createClient(dbport, dbip); // This will be parametrized via ENV VAR as well. console.log('Connecting via internet to public port...') break; case "SOCKET": var client = redis.createClient('/tmp/redis.sock'); console.log('Connecting to unix socket...') break; case "DOCKER": var client = redis.createClient(6379, 'redis'); console.log('Connecting to Redis container...') break; default: console.log('Environmental variable IMTCONNECT seems to be not set correctly (LOCALHOST, INTERNET, DOCKER or SOCKET), you will be not able to connect.'); return; } // If you'd like to select database 3, instead of 0 (default), call client.select(3, function() { /* ... */ }); client.on("error", function(err) { console.log("Error: " + err); }); // List of items - products, customers, order types var products = Array("wood", "gold", "fish", "wine"); var customers = Array("AUX1", "BFG2", "CRE3", "DRS4", "EFI5", "FRA6", "GOR1", "AAR1"); var ordertypes = Array("buy", "sell"); // Lambda requires handler being defined: exports.handler = quitter(); // Main function function orderGenerator(cycles, callback) { // Randomiser var randomPrice = Math.floor((Math.random() * 98) + 1); var randomProduct = products[Math.floor(Math.random() * products.length)]; var randomCustomer = customers[Math.floor(Math.random() * customers.length)]; var randomOrderType = ordertypes[Math.floor(Math.random() * ordertypes.length)]; // Evaluator switch (randomOrderType) { case "buy": var redisKey = randomProduct + "-" + randomPrice + "-sell"; client.lrange(redisKey, 0, 0, function(err, reply) { //console.log(reply); if (reply.length === 0) { var pushBuy = randomProduct + "-" + randomPrice + "-buy"; client.rpush(pushBuy, randomCustomer); console.log("New order inserted! " + pushBuy + " " + randomCustomer); } else { console.log("TRADE DETECTED! " + randomCustomer + " just traded " + redisKey + ", best offer by: " + reply + ". Removing from orderbook."); client.lpop(redisKey); } quitter(); // To ensure client.quit at end of loop }); break; case "sell": var redisKey = randomProduct + "-" + randomPrice + "-buy"; client.lrange(redisKey, 0, 0, function(err, reply) { //console.log(reply); if (reply.length === 0) { var pushSell = randomProduct + "-" + randomPrice + "-sell"; client.rpush(pushSell, randomCustomer); console.log("New order inserted! " + pushSell + " " + randomCustomer); } else { console.log("TRADE DETECTED! " + randomCustomer + " just traded " + redisKey + ", best offer by: " + reply + ". Removing from orderbook."); client.lpop(redisKey); } quitter(); // To ensure client.quit at end of loop }); break; } } // To ensure proper client.quit and context succeed at the end of program var quitCycles = 0; function quitter() { ++quitCycles; //console.log(quitCycles); if (quitCycles === maxcycles) { client.quit(); } } // Main loop generating random orders for (var cycles = 0; cycles < maxcycles; cycles++) { orderGenerator(cycles, function(response) { console.log("cycles = " + this.cycles + " , response = " + response); }); }
JavaScript
UTF-8
464
2.703125
3
[]
no_license
describe('practice-7-1', function () { it("get the type of data and log", function () { var v1 = choose == 'a' || choose == 'b' || choose == 'c' || choose == 'd'; var v2 = typeof(all_data) == 'object'; var v3 = logs[0].search(typeof all_data[choose]) >= 8; var v4 = logs[1] == undefined; expect(v1).toBe(true); expect(v2).toBe(true); expect(v3).toBe(true); expect(v4).toBe(true); }); });
Java
UTF-8
1,719
2.078125
2
[]
no_license
package xyz.zaijushou.zhx.sys.web; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import xyz.zaijushou.zhx.common.web.WebResponse; import xyz.zaijushou.zhx.sys.entity.DataOpLog; import xyz.zaijushou.zhx.sys.entity.FileList; import xyz.zaijushou.zhx.sys.service.FileListService; import java.io.File; import java.io.IOException; import java.util.List; /** * Created by looyer on 2019/3/1. */ @Api("案件详情/附件") @RestController public class FileListController { @Autowired private FileListService fileListService; @Value(value = "${detailFile_path}") private String detailFile; @ApiOperation(value = "分頁查询", notes = "分頁查询") @PostMapping("/dataLFile/pageDataFile") public Object pageDataFile(@RequestBody FileList bean) { List<FileList> list = fileListService.listFile(bean); return WebResponse.success(list); } @ApiOperation(value = "保存附件信息", notes = "保存附件信息") @PostMapping("/dataFile/save/import") public Object update(MultipartFile file, FileList bean ) throws IOException { String fileName = file.getOriginalFilename(); file.transferTo(new File(detailFile+fileName)); bean.setFileName(fileName); fileListService.saveFile(bean); return WebResponse.success(); } }
Java
UTF-8
668
2.171875
2
[]
no_license
package com.jpm.hr.daos; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.jpm.hr.entity.Employee; import com.jpm.hr.exceptions.HrExceptions; @Repository("HrDaos") public class HrDaosImpl implements HrDaos{ private static final long serialVersionUID = -2233232235877330385L; @PersistenceContext private EntityManager manager; @Override public Employee getEmpDetails(int empNo) throws HrExceptions { //Employee emp = new Employee(1, "aaa", 8000, 10); Employee emp = manager.find(Employee.class, empNo); return emp; } }
Ruby
UTF-8
701
2.6875
3
[]
no_license
class InviteFiller attr_reader :resource def initialize(resource) @resource = resource end def invites_left? unfilled_invites.count > 0 end def fill_invite(guest_attrs) return with_error(I18n.t(:no_invites_left)) unless invites_left? return with_error(I18n.t(:must_accept_invite)) unless resource.accepted? available_invite.update( invitee: guest_from(guest_attrs) ) end private def available_invite unfilled_invites.first end def unfilled_invites sendable_invites.where(invitee: nil) end def with_error(message) errors.add(:sendable_invites, message) end def guest_from(guest_attrs) Guest.new(guest_attrs) end end
C#
UTF-8
1,207
2.828125
3
[]
no_license
using System.Collections.ObjectModel; using System.Threading.Tasks; using OltivaHotel.PCL.Model; namespace OltivaHotel.PCL.Design { public class DesignDataService : IDataService { private IDownloader _downloader; public DesignDataService(IDownloader downloader) { _downloader = downloader; } public async Task<Menu> GetData() { var menu = new Menu {MenuItems = new ObservableCollection<MenuItem>()}; for (int i = 0; i < 15; i++) { menu.MenuItems.Add(new MenuItem { Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Sed nisl tortor, mattis a venenatis vel, vulputate non nisl. " + "Donec at ipsum eget nibh scelerisque ultricies at eu lorem.", IsTodaysSpecial = i%3 == 0, Name = "Lorem ipsum dolor sit amet " + i, Price = 20 + i, Type = i%3 == 0 ? "breakfast" : "dessert" }); } return menu; } } }
Go
UTF-8
2,252
2.75
3
[ "Apache-2.0" ]
permissive
package main import ( "fmt" kingpin "gopkg.in/alecthomas/kingpin.v2" "os" "reflect" "strconv" "strings" artifactory "artifactory.v401" "github.com/olekukonko/tablewriter" ) var ( repo = kingpin.Arg("repo", "Repo to show").Required().String() ) func makeBaseRow(b artifactory.RepoConfig) []string { s := reflect.ValueOf(b) baseRow := []string{ s.FieldByName("Key").String(), s.FieldByName("RClass").String(), s.FieldByName("PackageType").String(), s.FieldByName("Description").String(), s.FieldByName("Notes").String(), strconv.FormatBool((s.FieldByName("BlackedOut").Bool())), strconv.FormatBool((s.FieldByName("HandleReleases").Bool())), strconv.FormatBool((s.FieldByName("HandleSnapshots").Bool())), s.FieldByName("ExcludesPattern").String(), s.FieldByName("IncludesPattern").String(), } return baseRow } func main() { kingpin.Parse() client := artifactory.NewClientFromEnv() data, err := client.GetRepo(*repo) if err != nil { fmt.Printf("%s\n", err) os.Exit(1) } else { table := tablewriter.NewWriter(os.Stdout) table.SetAutoWrapText(false) baseHeaders := []string{ "Key", "Type", "PackageType", "Description", "Notes", "Blacked Out?", "Releases?", "Snapshots?", "Excludes", "Includes", } // base row data common to all repos baseRow := makeBaseRow(data) // We have to do this to get to the concrete repo type switch data.MimeType() { case artifactory.REMOTE_REPO_MIMETYPE: d := data.(artifactory.RemoteRepoConfig) baseHeaders = append(baseHeaders, "Url") table.SetHeader(baseHeaders) baseRow = append(baseRow, d.Url) table.Append(baseRow) case artifactory.LOCAL_REPO_MIMETYPE: d := data.(artifactory.LocalRepoConfig) baseHeaders = append(baseHeaders, "Layout") baseRow = append(baseRow, d.LayoutRef) table.SetHeader(baseHeaders) table.Append(baseRow) case artifactory.VIRTUAL_REPO_MIMETYPE: d := data.(artifactory.VirtualRepoConfig) baseHeaders = append(baseHeaders, "Repositories") baseRow = append(baseRow, strings.Join(d.Repositories, "\n")) table.SetHeader(baseHeaders) table.Append(baseRow) default: table.SetHeader(baseHeaders) table.Append(baseRow) } table.Render() os.Exit(0) } }
C++
UTF-8
260
2.609375
3
[]
no_license
#include <iostream> using namespace std; int main() { // your code here int cases; int n; long long a; cin>>cases; while(cases--){ cin>>a>>n; if(n==0){ cout<<"Airborne wins."<<endl; }else{ cout<<"Pagfloyd wins."<<endl; } } return 0; }
C#
UTF-8
2,286
2.5625
3
[]
no_license
using PMS.Model; using Prism.Mvvm; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PMS.Algorithm { public class PERT { public bool check(List<PERTTask> calc, List<PERTTask> postTask) { if (postTask.Count() == 0) return true; else foreach (var tmp in postTask) if (!calc.Contains(tmp)) return false; return true; } public List<PERTTask> criticalPath(List<PERTTask> tasks) { PERTTask tt = new PERTTask(); tt.setExpectedTime(tasks); tt.setStandardDeviation(tasks); tt.setVariance(tasks); List<PERTTask> calc = new List<PERTTask>(); List<PERTTask> tmpTaskList = new List<PERTTask>(tasks); while (tmpTaskList.Count() != 0) { bool error = false; foreach (PERTTask task in tmpTaskList.ToList()) { bool tmp = check(calc, task.PostTask); if (tmp) { int critical = 0; foreach (PERTTask t in task.PostTask) if (t.CS > critical) critical = t.CS; task.CS = critical + task.Expected_t; calc.Add(task); tmpTaskList.Remove(task); error = true; } } if (!error) { ErrorMessage er = new ErrorMessage("Cyclic dependency!"); er.ShowDialog(); return new List<PERTTask>(); } } tt.setMC(tasks); List<PERTTask> initialNodes = tt.getInitTask(tasks); tt.calcESAndEF(initialNodes); //ustawienie slack i CC foreach (var task in calc) { tt.setCC(task); tt.setSlack(task); } calc = calc.OrderBy(x => x.Name).ToList(); return calc; } } }
Python
UTF-8
1,516
2.828125
3
[ "MIT" ]
permissive
from .MultiOutput import * import weakref class MultiInputItem(object): def __init__(self, models): self.models = models def __getitem__(self, i): return self.models[i].Y def __setitem__(self, i, value): self.models[i].Y = value def __iter__(self): for md in self.models: yield md.Y def __len__(self): return len(self.models) class MultiInput(object): def __init__(self, model): self.model = model self.items = MultiInputItem(model) @property def Y(self): return self.items def __getitem__(self, i): return self.model[i] def __len__(self): return len(self.model) def __iter__(self): for md in self.model: yield md def input_models(self): for md in self.model: yield get_layer_parent(md) def input_models_with_index(self): for md in self.model: if type(md) == YLayer: yield (get_layer_parent(md), md.i) else: yield (get_layer_parent(md), 0) class XLayer(object): def __init__(self, model, i): # Avoid bidirection reference self.model = weakref.ref(model) self.i = i @property def dX(self): return self.model().dX[self.i] class WeakrefLayer(object): def __init__(self, model): # Avoid bidirection reference self.model = weakref.ref(model) @property def dX(self): return self.model().dX
Java
UTF-8
662
3.203125
3
[]
no_license
/** * Write a description of class daisy here. * * @author (your name) * @version (a version number or a date) */ public class daisy { public static void main(String args[]){ new daisy();} public daisy(){ int num = (int)(Math.random() * 10 + 15); for(num = num ; num < 26 ; num++){ if(num % 2 == 0){ System.out.println("she loves me");} else System.out.println("She loves me not"); try { Thread.sleep(400); } catch(InterruptedException m) { ; } } } }
Markdown
UTF-8
1,446
3.046875
3
[]
no_license
<h1>JSTVRemote</h1> <h2>Control your Smart TV from your browser</h2> This library allows you to develop web apps to control your Smart TVs. Support of features depends on your TV, but it can send remote control keys to your TV, input text or control mouse cursor. Current TVs supported are: <ul> <li>Philips with JointSpace APIs</li> <li>LG with WebOS</li> <li>LG with NetCast</li> </ul> <h2>Official page</h2> <a href='http://webcodingeasy.com/JS-classes/Control-Smart-TV-from-browser' target="_blank">WebCodingEas.com - Control Smart TV from browser</a> <h2>Usage</h2> <h3>Initialization</h3> var tv = JSTVRemote.init(tv, ip, port, callback); providing tv as values like "philips", "lg_netcast", "lg_webos" or directly initializing var tv = new JSTVRemote.Philips(ip, port, callback); var tv = new JSTVRemote.LGNetCast(ip, port, callback); var tv = new JSTVRemote.LGWebOS(ip, port, callback); <h3>Feature query</h3> Each tv instance can have different features. var features = tv.getFeatures(); returns features that API supports var keys = tv.getKeys(); returns keys that API supports sending as TV remote control <h3>Sending key as remote control</h3> tv.sendKey(key, callback); <h3>Input text</h3> tv.inputText(text, callback); <h3>Mouse move</h3> tv.mouseMove(dx, dy, drag, callback); <h3>Mouse click</h3> tv.click(callback); <h3>Scroll</h3> tv.scroll(dx, dy, callback);
C++
UTF-8
1,691
3.765625
4
[]
no_license
#include<bits/stdc++.h> using namespace std; struct Node{ int val; Node* right ; Node* left ; }; Node* newNode(int data){ Node* node = new Node(); node->val = data; node->left = NULL; node->right = NULL; return node; } void preOrder(Node *root){ unordered_map<Node*,int> mp; if(root == NULL) return; stack<Node*> s; s.push(root); while(!s.empty()){ Node* curr = s.top(); if(curr == NULL){ s.pop(); continue; } if(mp[curr]==0) cout << curr ->val <<" "; else if(mp[curr] == 1) s.push(curr->left); else if(mp[curr]== 2) s.push(curr->right); else s.pop(); mp[curr]++; } } int findIndex(string str, int si, int ei) { if (si > ei) return -1; stack<char> s; for (int i = si; i <= ei; i++) { if (str[i] == '(') s.push(str[i]); else if (str[i] == ')') { if (s.top() == '(') { s.pop(); if (s.empty()) return i; } } } return -1; } Node* treeFromString(string str,int si,int ei){ if(si>ei) return NULL; Node* root = newNode(str[si]-'0'); int idx = -1; if(si +1 <= ei && str[si+1]=='(') idx = findIndex(str,si+1,ei); if(idx!=-1){ root -> left = treeFromString(str,si+2,idx-1); root -> right = treeFromString(str,idx+2,ei-1); } return root; } int main() { string str = "4(2(3)(1))(6(5))"; Node* root = treeFromString(str, 0, str.length() - 1); preOrder(root); }
Python
UTF-8
1,975
3.609375
4
[]
no_license
from item import Item, Weapon, Food from chest import Chest from random import randint class MapTile: def __init__(self, x, y): self.x = x self.y = y def describe(self, description): print(description) class Start(MapTile): def __init__(self, x, y): self.description = "Looking around you realize this is where you started your journey." MapTile.__init__(self, x, y) def describe(self): MapTile.describe(self.description) class Path(MapTile): def __init__(self, x, y): self.description = "A dirt path running through a thickly covered forest." MapTile.__init__(self, x, y) def describe(self): MapTile.describe(self.description) class BanditLoot(MapTile): def __init__(self, x, y): self.chest = Chest(randint(0,100)) self.description = "Off to the side of the path there's a chest that some bandits left behind." MapTile.__init__(self, x, y) def describe(self): MapTile.describe(self.description) class Enemies(MapTile): def __init__(self, x, y): self.enemies = [] self.killed_all_enemies = False self.description = "Bandits were hiding along the path... stop them from hurting anyone else!" MapTile.__init__(self, x, y) def describe(self): MapTile.describe(self.description) def add_enemy(self, enemy): self.enemies.append(enemy) def print_enemies(self): print("") print("| Enemies:") print("+------------------------------------------------+") for index, enemy in enumerate(self.enemies): print("| ======== " + str(index + 1) + " ========") print("| " + enemy.name + " Level: " + str(enemy.level)) print("| " + str(enemy.hp) + "/" + str(enemy.maxhp)) print("| Description: " + enemy.description) print("+------------------------------------------------+") print("")
Java
UTF-8
774
3.84375
4
[]
no_license
package sequentialCollection; import java.util.ArrayList; public class AList { public static void main(String args[]) { ArrayList<Integer> grades = new ArrayList<Integer>(); grades.add(100); grades.add(200); grades.add(300); grades.add(400); float total = 0f; // for(int i = 0 ; i < grades.size() ; ++i) // total+= grades.get(i); // Collection interface provides us iterator for (Integer i : grades) total += i; System.out.println("Size of grades is " + grades.size()); System.out.println("Average grades is " + total / grades.size()); grades.remove(2); System.out.println("New size after removing is " + grades.size()); grades.add(60); grades.add(70); System.out.println("New size after inserting is " + grades.size()); } }
Markdown
UTF-8
5,326
3.375
3
[]
no_license
# Getting and Cleaning Data Assignment Repository for Coursera Getting and Cleaning Data Assignment which is based on a [Human Activity Recognition Using Smartphones Data Set](http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones) ## Purpose of assignment (from course project) >The purpose of this project is to demonstrate your ability to collect, work with, and clean a data set. The goal is to prepare tidy data that can be used for later analysis. You will be graded by your peers on a series of yes/no questions related to the project. You will be required to submit: 1) a tidy data set as described below, 2) a link to a Github repository with your script for performing the analysis, and 3) a code book that describes the variables, the data, and any transformations or work that you performed to clean up the data called CodeBook.md. You should also include a README.md in the repo with your scripts. This repo explains how all of the scripts work and how they are connected. >One of the most exciting areas in all of data science right now is wearable computing - see for example this article . Companies like Fitbit, Nike, and Jawbone Up are racing to develop the most advanced algorithms to attract new users. The data linked to from the course website represent data collected from the accelerometers from the Samsung Galaxy S smartphone. A full description is available at the site where the data was obtained: >http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones >Here are the data for the project: >https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip >You should create one R script called run_analysis.R that does the following. >Merges the training and the test sets to create one data set. Extracts only the measurements on the mean and standard deviation for each measurement. Uses descriptive activity names to name the activities in the data set Appropriately labels the data set with descriptive variable names. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. This repository comprises of 5 files: * `README.md` - This document detailing the assignment and files contained in project. * `run_analysis.R` - The R code to extract, manipulate and output a tidy dataset as requested. See below for details. * `CodeBook.md` - A document to indicate all the variables and summaries calculated, along with units, and any other relevant information. * `variable_names.txt` - The full list of variable names present in the final dataset `get_clean_data_tidy.txt`. * `get_clean_data_tidy.txt` - The final tidy dataset as requested. ## run_analysis.R The R code is split into 6 main sections, a preliminary section to import data plus 5 further sections related to the 5 steps laid out in assignment instructions: ### Section 0 Downloads data from [this location](https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip). Unzips the data for use in analysis. Reads in the required text files from location of unzipped files. 8 files are used: * 'features.txt': List of all features. * 'activity_labels.txt': Links the class labels with their activity name. * 'train/X_train.txt': Training set. * 'train/y_train.txt': Training labels. * 'test/X_test.txt': Test set. * 'test/y_test.txt': Test labels. * 'train/subject_train.txt': Each row identifies the subject who performed the activity for each window sample. Ranges from 1 to 30. * 'test/subject_test.txt': Each row identifies the subject who performed the activity for each window sample. Ranges from 1 to 30. ### Section 1 Combines the test and training datasets to create a dataset each for test and train data. `test` dataset created from `subject_test`, `X_test` and `y_test`. `train` dataset created from `subject_train`, `X_train` and `y_train`. ### Section 2 Appends the `test` and `train` datasets created and selects only the required variables: * subject * activity_class * All variables relating to the mean or standard deviation of the measurements (66 measurements in total) ### Section 3 Activites are named using the `activity_labels.txt` file. This is joined using the `activity_class` variable (values 1-6) so the description of activity can be taken (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING). ### Section 4 Descriptive variable names are provided by ammending the existing variable names as given by the `features.txt` file. Various replacements are made using the `str_replace` function from the `stringr` package to make the names more descriptive by expanding on abbreviations. ### Section 5 The dataset created in Section 4 is grouped by `subject` and `activity` to create a tidy dataset with each subject-activity combination having 1 row of data. Each of the 180 rows (6 activities x 30 subjects) has 68 columns including the subject, activity and 66 average measurements calculated (using `group_by` and `summarise_all` from `dplyr` package). The column names are further ammended to indicate that average measurements are now being displayed. This dataset is output as a text file (`get_clean_data_tidy.txt`) for submission.
Go
UTF-8
4,957
2.515625
3
[ "Apache-2.0" ]
permissive
package machine import ( "context" "log" "net" "sync" "time" "github.com/rotisserie/eris" "github.com/sparrc/go-ping" "github.com/talos-systems/talos/api/machine" "github.com/talos-systems/talos/pkg/client" ) const StateUnknown = "unknown" const pingThreshold = 2 * time.Second const serviceCheckInterval = 2 * time.Second // Manager provides a common management structure for keeping track of a // machine, its configuration, and its status. type Manager struct { Spec *Spec Status *Status client *client.Client pingers map[string]*ping.Pinger pingTimestamps map[string]time.Time mu sync.RWMutex } // NewManager creates and runs a new manager for the given machine func NewManager(ctx context.Context, c *client.Client, spec *Spec) (m *Manager, err error) { if spec == nil { return nil, eris.New("spec is required") } if c == nil { return nil, eris.New("talos client is required") } m = &Manager{ Spec: spec, Status: new(Status), client: c, pingers: make(map[string]*ping.Pinger), pingTimestamps: make(map[string]time.Time), } if err = m.addPinger("ipmi", spec.IPMIAddr.String()); err != nil { m.Stop() return nil, eris.Wrapf(err, "failed to add pinger for %q", spec.Name) } if err = m.addPinger("ipv4", spec.IPv4Addr.String()); err != nil { m.Stop() return nil, eris.Wrapf(err, "failed to add pinger for %q", spec.Name) } if err = m.addPinger("ipv6", spec.IPv6Addr.String()); err != nil { m.Stop() return nil, eris.Wrapf(err, "failed to add pinger for %q", spec.Name) } go m.watchServices(ctx) return m, nil } func (m *Manager) addPinger(kind string, addr string) error { p, err := ping.NewPinger(addr) if err != nil { return eris.Wrapf(err, "failed to create %q pinger", kind) } p.OnRecv = func(p *ping.Packet) { m.mu.Lock() m.pingTimestamps[kind] = time.Now() m.mu.Unlock() } m.mu.Lock() m.pingers[kind] = p m.mu.Unlock() go p.Run() return nil } func (m *Manager) updateServiceStatus(ctx context.Context) { ctx = client.WithNodes(ctx, m.Spec.Name) m.Status.mu.Lock() defer m.Status.mu.Unlock() // Reset all states first for _, s := range m.Status.Services { s.State = StateUnknown } resp, err := m.client.ServiceList(ctx) if err == nil { for _, msg := range resp.Messages { m.Status.Services = msg.Services } } } func (m *Manager) updateVersion(ctx context.Context) { ctx = client.WithNodes(ctx, m.Spec.Name) m.Status.mu.Lock() defer m.Status.mu.Unlock() resp, err := m.client.Version(ctx) if err == nil { for _, msg := range resp.GetMessages() { m.Status.TalosVersion = msg.GetVersion().GetTag() } } } func (m *Manager) watchServices(ctx context.Context) { for { select { case <-ctx.Done(): return case <-time.After(serviceCheckInterval): m.updateServiceStatus(ctx) m.updateVersion(ctx) } } } // Stop shuts down the Manager func (m *Manager) Stop() { m.mu.Lock() defer m.mu.Unlock() for _, v := range m.pingers { v.Stop() } m.pingers = nil if m.client != nil { m.client.Close() // nolint } } // PingStatus indicates whether the given ping kind (ipmi,ipv4,ipv6) is up func (m *Manager) PingUp(kind string) bool { m.mu.RLock() defer m.mu.RUnlock() ts, ok := m.pingTimestamps[kind] if !ok { log.Printf("failed to find ping timestamp for %q", kind) return false } return time.Since(ts) < pingThreshold } // ServiceState returns the status of the given service func (m *Manager) ServiceState(name string) string { m.Status.mu.RLock() defer m.Status.mu.RUnlock() for _, s := range m.Status.Services { if s.Id == name { return s.State } } return StateUnknown } // Version returns the Talos version of the machine func (m *Manager) Version() string { m.Status.mu.RLock() defer m.Status.mu.RUnlock() return m.Status.TalosVersion } // Spec is the specification of a machine type Spec struct { // Name is the simple hostname of the machine Name string `json:"name" yaml:"name"` // FQDN is the fully-qualified domain name of the machine FQDN string `json:"fqdn" yaml:"fqdn"` // IPMIAddr is the host/IP of the IPMI interface for the machine IPMIAddr net.IP `json:"ipmiAddr" yaml:"ipmiAddr"` // IPv4Addr is the main IPv4 address of the machine IPv4Addr net.IP `json:"ipv4Addr" yaml:"ipv4Addr"` // IPv6Addr is the main IPv6 address of the machine IPv6Addr net.IP `json:"ipv6Addr" yaml:"ipv6Addr"` } // Status is the status of a machine type Status struct { // IPMI indicates whether the IPMI interface is responsive IPMI bool // HostV4 indicates whether the IPv4 address of the host is responsive HostV4 bool // HostV6 indicates whether the IPv6 address of the host is responsive HostV6 bool // TalosVersion indicates the Talos version which is currently installed (if any) TalosVersion string // Services stores the most recent service states Services []*machine.ServiceInfo mu sync.RWMutex }
Java
UTF-8
1,073
3.6875
4
[]
no_license
package set; public class MyStack { private Node top; public boolean isEmpty() { if(top== null) {//if stack is empty return true return true; } else {// if stack is not empty return false return false; } } public void push(TNode r) { top = new Node(r,top); //adding a new node before the created Node top } public TNode pop() { if (isEmpty()) { //if the stack is empty print a message System.out.println(" the Stack is Empty"); return null; // stack is empty so return nothing } TNode r = top.currentElement; //grabbing current element and equating it to r top = top.nextNode; // references top to the next element in stack return r; //return current element } public TNode top() { TNode currentElement = top.currentElement; //shows top element of stack return currentElement; //return the value } }
Java
UTF-8
988
2.5625
3
[]
no_license
package ejb.simple.examples.local.impl; import ejb.simple.examples.local.inf.BasicCalculatorEjbLocal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ejb.Stateless; /*The initial state of a stateless session bean is the does-not-exist state. This would be the case before a container starts up, for example. The next state is the method-ready pool */ @Stateless public class BasicCalculatorEjbLocalImpl implements BasicCalculatorEjbLocal { private static final Logger LOGGER = LoggerFactory.getLogger(BasicCalculatorEjbLocalImpl.class); @PostConstruct @Override public void setUp() { LOGGER.info("Post Constructor Method setUp() Invoked"); } @PreDestroy @Override public void tearDown() { LOGGER.info("Pre Destruction Method tearDown() Invoked"); } @Override public int add(int i, int j) { return i + j; } }
C++
UHC
1,879
3.828125
4
[]
no_license
/* N S ־ Ƕ̵带 α׷ ۼϽÿ. , N 5̰ S 3 ̶, Ƕ̵ . 3 456 21987 3456789 987654321 S 1 Ѵ. ȣ 1̶ , ¦° ʿ 1 ϵ , Ȧ° Ųٷ ´. ڰ 10 , 1 ٲٰ ٽ Ѵ. Է Է ù ° ٿ N S ־. ( 1N100, 1 S 9) ù ° ٺ Ƕ̵带 Ѵ. ( ٿ ϴ Ȯϰ Ȯֽùٶϴ.) */ #include <stdio.h> int main() { int N, S; scanf("%d %d", &N, &S); int space = N-1, number = 1; int prev_first, prev_last; for(int i=1; i<=N; i++) { for(int j=0; j<space; j++) printf(" "); space--; if(i % 2 == 0) { int cur_first = prev_first + 1; if(cur_first >= 10) cur_first = 1; for(int i=0; i<number; i++) { printf("%d", cur_first); prev_last = cur_first; cur_first++; if(cur_first >= 10) cur_first = 1; } } else { int cur_first; if(i == 1) cur_first = S; else { cur_first = prev_last; for(int i=0; i<number; i++) { cur_first++; if(cur_first >= 10) cur_first = 1; } } prev_first = cur_first; for(int i=0; i<number; i++) { printf("%d", cur_first); cur_first--; if(cur_first <= 0) cur_first = 9; } } number += 2; printf("\n"); } return 0; } /* 5 3 ---------- 3 456 21987 3456789 987654321 */
C++
UTF-8
1,458
3.96875
4
[]
no_license
//Quicksort #include<iostream.h> #include<conio.h> //Function prototypes void quicksort(int a[10],int , int); void display(int a[10],int); //Main function void main() { clrscr(); int a[10]; int i,j,n; cout<<"\nEnter number of elements (max 10) : "; cin>>n; cout<<"\nEnter elements : "; for(i=0;i<n;i++) //Taking elements from user cin>>a[i]; quicksort(a,0,n-1); //Sending the array a,0 and n as parameters to the function quicksort display(a,n); //Calling display function getch(); } //Quicksort function void quicksort(int a[],int left,int right) //left is the initial position and right is the last position { int i = left,temp,j = right,pivot = a[(left+right) / 2]; //Taking pivot element as the middle element while(i<=j) //loop till i is less than j { while(a[i]<pivot) //looping till the left elements are lesser than the pivot element i++; while(a[j]>pivot) //looping till the right elements are greater than the pivot element j--; if(i<=j) //Swapping if i is less than j { temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } }; if(left<j) //recursing if left is less than j quicksort(a,left,j); if(i<right) //recursing if i is less than right quicksort(a,i,right); } //Display function void display(int a[10],int x) { int i; cout<<"\n\nSorted Array : "; for(i=0;i<x;i++) //Loop to display the array { cout<<a[i]<<" "; } }
Python
UTF-8
26,480
2.546875
3
[]
no_license
#!/usr/bin/env python3 import wx,time,math,os,SourceImages import wx.grid from cv2 import imread class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "My Frame", size=(800, 450)) self.createProxyWidget() self.setMenubar() self.SetToolBar() def SetToolBar(self): toolbar = self.CreateToolBar() tsize = (30,30) # help(toolbar.AddTool) t1 = toolbar.AddTool(toolId = 501,bitmap = SourceImages.origin.GetImage().Scale(20,20).ConvertToBitmap(),label = "origin", shortHelp="Set the origin") t2= toolbar.AddTool(toolId = 502,bitmap = SourceImages.point.GetImage().Scale(17,17).ConvertToBitmap(),label = 'getdata',shortHelp = "Get data from a point") t3 = toolbar.AddTool(toolId = 503,bitmap = SourceImages.point.GetImage().Scale(17,17).ConvertToBitmap(),label = 'getinfo',shortHelp = "Get info of a point") toolbar.Realize() self.Bind(wx.EVT_TOOL,dataWindow.OnClick,t1) self.Bind(wx.EVT_TOOL,self.GetDataSwitch,t2) self.Bind(wx.EVT_TOOL,self.GetInfo,t3) def GetInfo(self,evt): if mainWindow.GETINFO==True:mainWindow.GETINFO=False else:mainWindow.GETINFO=True def GetDataSwitch(self,evt): if mainWindow.shape==None:return if mainWindow.setOrigin<0: mainWindow.setOrigin=0 elif mainWindow.setOrigin==0 and len(mainWindow.line)==2: mainWindow.setOrigin=-1 def setMenubar(self): menubar=wx.MenuBar() file0=wx.Menu() edit=wx.Menu() help=wx.Menu() op_file = file0.Append(101,'&Open','Open a new document') save_file = file0.Append(102,'&Export data','Save the data to a file') file0.AppendSeparator() quit_=wx.MenuItem(file0,105,'&Quit\tCtrl+Q','Quit the Application') file0.Append(quit_) edit.Append(201,'&Nothing') help.Append(301,'&About author') menubar.Append(file0,'&File') menubar.Append(edit,'&Edit') menubar.Append(help,'&Help') self.SetMenuBar( menubar ) self.Bind(wx.EVT_TOOL,self.OnFileOpen,op_file ) self.Bind(wx.EVT_TOOL, self.OnSaveFile,save_file) self.Bind(wx.EVT_TOOL,self.OnExit,quit_) def createProxyWidget(self): self.proxyFrame = ProxyFrame(self) def OnSaveFile(self,event): """ Create and show the Save FileDialog """ dlg = wx.FileDialog(self,message="select the Save file style",defaultFile="",wildcard="*.txt;*.csv",style=wx.FD_SAVE) if dlg.ShowModal() == wx.ID_OK: filename="" paths = dlg.GetPaths() #split the paths for path in paths: filename=filename+path #write the contents of the TextCtrl[Contents] into the file file1=open(filename,'w') for i in dataWindow.data: file1.write('%f %f\n'%i) file1.close() #show the save file path dlg.Destroy() def OnFileOpen(self,event): #创建标准文件对话框 dialog = wx.FileDialog(self,"Open file...",os.getcwd(),style=wx.ID_OPEN,wildcard="*.jpg;*.png;*.jpeg,*.bmp") #这里有个概念:模态对话框和非模态对话框. 它们主要的差别在于模态对话框会阻塞其它事件的响应, #而非模态对话框显示时,还可以进行其它的操作. 此处是模态对话框显示. 其返回值有wx.ID_OK,wx.ID_CANEL; if dialog.ShowModal() == wx.ID_OK: self.filename = dialog.GetPath() mainWindow.SetImage(self.filename) #在TopWindow中更新标题为文件名. self.SetTitle(self.filename) #销毁对话框,释放资源. dialog.Destroy() def OnExit(self,evt): self.Close() class ProxyFrame(wx.ScrolledWindow): def __init__(self, parent): wx.ScrolledWindow.__init__(self, parent) self.createWidget() def createWidget(self): self.proxy_split_mult = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE, size=(800, 450)) self.proxy_split_mult.SetMinimumPaneSize(10) #最小面板大小 self.proxy_split_left = wx.SplitterWindow(self.proxy_split_mult) #上结构 self.proxy_split_right = wx.SplitterWindow(self.proxy_split_mult) #下结构 self.proxy_split_mult.SplitVertically(self.proxy_split_left, self.proxy_split_right) #分割面板 ########## 结构左右 ########## self.proxy_scrol_rightTop = wx.ScrolledWindow(self.proxy_split_right) self.proxy_scrol_rightBottom = wx.ScrolledWindow(self.proxy_split_right) self.proxy_scrol_rightBottom.SetBackgroundColour(wx.WHITE) self.proxy_split_right.SetMinimumPaneSize(10) #最小面板大小 self.proxy_split_right.SplitHorizontally(self.proxy_scrol_rightTop, self.proxy_scrol_rightBottom) #分割面板 self.proxy_split_right.SetSashGravity(0.99) ########## 结构下左右 end ########## self.proxy_split_mult.SetSashGravity(0.99) self.SetScrollbars(10, 10, 600, 400) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.proxy_split_mult, 1, flag=wx.EXPAND) #自动缩放 self.SetSizer(sizer) # DragWindow(self.proxy_split_left) # DragWindow(self.proxy_scrol_rightTop) # DragWindow(self.proxy_scrol_rightBottom) mainWindow.__init__(sc=self.proxy_split_left) enlargeWindow.__init__(sc=self.proxy_scrol_rightBottom) dataWindow.__init__(sc=self.proxy_scrol_rightTop) #************************************************** class DragShape: def __init__(self, bmp,pos=(0,0)): self.bmp = bmp self.img = bmp.ConvertToImage() self.pos = pos self.pos0=pos self.shown = True self.subRect = 0,0,self.img.GetWidth(),self.img.GetHeight() self.fullscreen = False self.rate=1 def Fit(self,x,y,w,h): imgW,imgH=self.img.GetWidth(),self.img.GetHeight() if x<0: w+=x x=0 elif x>imgW:return 0,0,0,0 if y<0: h+=y y=0 elif y>imgH:return 0,0,0,0 if w+x>imgW:w=imgW-x if h+y>imgH:h=imgH-y return x,y,w,h def SetRect(self): x,y,w,h=self.subRect x,y,w,h=self.Fit(x-w,y-h,w*3,h*3) dx=self.subRect[0]-x dy=self.subRect[1]-y self.pos=int(self.pos[0]-dx*self.rate),int(self.pos[1]-dy*self.rate) img=self.img.GetSubImage(wx.Rect(x,y,w,h)) self.bmp=img.Scale(w*self.rate,h*self.rate).ConvertToBitmap() self.subRect=x,y,w,h return def GetRect(self,wsize): return def SetBmpScale(self,rate0,rate,mouse_pos,wsize): self.rate=rate mx,my=(mouse_pos[0]-self.pos0[0])/rate0,(mouse_pos[1]-self.pos0[1])/rate0 wLeft,hTop=mouse_pos wLeft/=rate hTop/=rate x,y,w,h=int(mx-wLeft),int(my-hTop),int(wsize[0]/rate)+3,int(wsize[1]/rate)+3 x,y,w,h=self.Fit(x,y,w,h) self.subRect=x,y,w,h self.pos0=int(mouse_pos[0]-mx*rate),int(mouse_pos[1]-my*rate) self.pos=int(mouse_pos[0]-(mx-x)*rate),int(mouse_pos[1]-(my-y)*rate) bmp=self.img.GetSubImage(wx.Rect(x,y,w,h)) self.bmp=bmp.Scale(w*rate,h*rate).ConvertToBitmap() def Draw(self, dc, op = wx.COPY): if self.bmp.IsOk(): memDC = wx.MemoryDC() memDC.SelectObject(self.bmp) dc.Blit(self.pos[0], self.pos[1], self.bmp.GetWidth(), self.bmp.GetHeight(), memDC, 0, 0, op, True) return True else: return False #---------------------------------------------------------------------- class DragCanvas: def __init__(self, sc=None,background=None): if sc==None:return self.window=sc self.dragImage0 = None self.GETINFO=False self.dragShape = None self.hiliteShape = None self.shape=None self.setOrigin=0 #0:不进行设计原点,大于0正在设置原点,小于0原点设置完毕 self.showMark=True self.pen = wx.Pen("green", 2) self.window.SetCursor(wx.Cursor(wx.CURSOR_ARROW)) # self.bg_img=SourceImages.bgc.GetImage() self.bg_img = wx.Image('haiqinyan_wlop.jpg') self.bgSize=0,0 self.bg_bmp = self.bg_img.ConvertToBitmap() self.window.SetBackgroundStyle(wx.BG_STYLE_ERASE) self.window.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) self.mouseWhell=0 # We're not doing anything here, but you might have reason to. # for example, if you were dragging something, you might elect to # 'drop it' when the cursor left the window. def Update(self,size=None,showBmp=True,showMark=True): if size==None: wsize=self.window.GetSize() size=0,0,wsize[0],wsize[1] self.shape.shown,self.showMark=showBmp,showMark self.window.RefreshRect(wx.Rect(*size)) self.window.Update() def SetImage(self,img): self.cv2image=imread(img) img = wx.Image(img,wx.BITMAP_TYPE_ANY) enlargeWindow.SetImage(img=img) bmp=img.ConvertToBitmap() self.shape = DragShape(bmp,pos=(200,10)) self.window.Bind(wx.EVT_PAINT, self.OnPaint) self.window.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.window.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.window.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) self.window.Bind(wx.EVT_MOTION, self.OnMotion) self.window.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow) self.window.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWhell) self.window.Bind(wx.EVT_MIDDLE_DOWN, self.OnMiddleDown) self.InitSetOrigin() dataWindow.Oninit() def InitSetOrigin(self): mainWindow.line=[] mainWindow.circle=[] gridWindow.data=[] self.Update() def OnMiddleDown(self,evt): pass def SetOrigin(self,evt): shape=self.FindShape(evt) pos=evt.GetPosition() dataWindow.SetOrigin(pic_pos=shape.pos0, mouse_pos=(pos.x,pos.y), scale=(shape.img.GetWidth()*shape.rate,shape.img.GetHeight()*shape.rate)) def GetPoint(self,*s): wsize,pos,size,rate=s fx=(pos[0]-wsize[0])/(size[0]*rate) fy=(pos[1]-wsize[1])/(size[1]*rate) intx=int(fx*size[0]) inty=int(fy*size[1]) print((fx,fy),(intx,inty),self.cv2image[inty,intx]) def OnLeftDown(self,evt): shape=self.FindShape(evt) if not shape:return if self.GETINFO==True: pos=evt.GetPosition() self.GetPoint(self.shape.pos0,(pos.x,pos.y),(self.shape.img.GetWidth(),self.shape.img.GetHeight()),shape.rate) if self.setOrigin>0: self.SetOrigin(evt) elif self.setOrigin==0:return else: pos=evt.GetPosition() dataWindow.writedata(self.shape.pos0,(pos.x,pos.y),(self.shape.img.GetWidth()*shape.rate,self.shape.img.GetHeight()*shape.rate)) self.Update() def OnLeaveWindow(self, evt): pass def OnMouseWhell(self,evt): angle=evt.GetWheelRotation() angle/=abs(angle) self.mouseWhell+=angle if self.mouseWhell==2: angle=2 self.mouseWhell=0 elif self.mouseWhell==-2: angle=-2 self.mouseWhell=0 else:return shape = self.shape pos=evt.GetPosition() rate0=shape.rate if angle>0: if rate0<1:rate=rate0+0.2 else:rate=rate0+0.2*rate0 else: if rate0<1:rate=rate0-0.2 else:rate=rate0-0.2*rate0 if rate<0.1 or rate>80:return wsize=self.window.GetSize() shape.SetBmpScale(rate0, rate, (pos.x,pos.y), wsize) self.Update() pos=evt.GetPosition() enlargeWindow.setPos(shape.pos0,(pos.x,pos.y),(shape.img.GetWidth()*shape.rate,shape.img.GetHeight()*shape.rate),wsize) def OnLeaveWindow(self, evt): pass # tile the background bitmap def TileBackground(self, dc): pass # Go through our list of shapes and draw them in whatever place they are. def DrawShapes(self, dc): shape=self.shape if shape.shown: shape.Draw(dc) wp,hp=shape.pos0 w,h=shape.img.GetWidth()*shape.rate,shape.img.GetHeight()*shape.rate ww,hw=self.window.GetSize() if self.showMark==True: dc.SetPen(self.pen) for wr,hr in self.circle: wr=w*wr+wp hr=h*hr+hp if wr>0 and wr<ww and hr>0 and hr<hw: dc.DrawCircle(wr,hr,3) for p1,p2,p3,p4 in self.line: p1=p1*w+wp p2=p2*h+hp p3=p3*w+wp p4=p4*h+hp x,y=p3-p1,p4-p2 if abs(x)>abs(y): t=(ww-p1)/float(x) p3,p4=p1+t*x,p2+t*y t=p1/float(x) p1,p2=p1-t*x,p2-t*y else: t=(hw-p2)/float(y) p3,p4=p1+t*x,p2+t*y t=p2/float(y) p1,p2=p1-t*x,p2-t*y dc.DrawLine(p1,p2,p3,p4) # This is actually a sophisticated 'hit test', but in this # case we're also determining which shape, if any, was 'hit'. def FindShape(self, evt): pos=self.shape.pos mpos=evt.GetPosition() w,h=self.shape.bmp.GetWidth(),self.shape.bmp.GetHeight() pos=mpos.x-pos[0],mpos.y-pos[1] if pos[0]<=w and pos[0]>=0 and pos[1]>=0 and pos[1]<=h: return self.shape else:return None # Clears the background, then redraws it. If the DC is passed, then # we only do so in the area so designated. Otherwise, it's the whole thing. def OnEraseBackground(self, evt): dc = evt.GetDC() if not dc: dc = wx.ClientDC(self.window) rect = self.window.GetUpdateRegion().GetBox() dc.SetClippingRect(rect) sz = self.window.GetClientSize() if sz!=self.bgSize: self.bgSize=sz w=min((sz[0],self.bg_img.GetWidth())) h=min((self.bg_img.GetHeight(),sz[1])) self.bg_bmp=self.bg_img.GetSubImage(wx.Rect(0,0,w,h)).ConvertToBitmap() dc.DrawBitmap(self.bg_bmp, 0, 0) # Fired whenever a paint event occurs def OnPaint(self, evt): dc = wx.PaintDC(self.window) self.DrawShapes(dc) # Left mouse button is down. def OnRightDown(self, evt): shape = self.FindShape(evt) if shape: shape.SetRect() #self.Update() self.ppos=shape.pos self.dragShape = shape self.dragStartPos = evt.GetPosition() # Left mouse button up. def OnRightUp(self, evt): if not self.dragImage0 or not self.dragShape: self.dragImage0 = None self.dragShape = None return # Hide the image, end dragging, and nuke out the drag image. #self.dragImage0.Hide() self.dragImage0.EndDrag() self.dragImage0 = None # if self.hiliteShape: # self.window.RefreshRect(self.hiliteShape.GetRect()) # self.hiliteShape = None # reposition and draw the shape # Note by jmg 11/28/03 # Here's the original: # # self.dragShape.pos = self.dragShape.pos + evt.GetPosition() - self.dragStartPos # # So if there are any problems associated with this, use that as # a starting place in your investigation. I've tried to simulate the # wx.Point __add__ method here -- it won't work for tuples as we # have now from the various methods # # There must be a better way to do this :-) self.dragShape.pos = ( self.dragShape.pos[0] + evt.GetPosition()[0] - self.dragStartPos[0], self.dragShape.pos[1] + evt.GetPosition()[1] - self.dragStartPos[1] ) wsize=self.window.GetSize() self.dragShape = None dx,dy=self.shape.pos[0]-self.ppos[0],self.shape.pos[1]-self.ppos[1] self.shape.pos0=self.shape.pos0[0]+dx,self.shape.pos0[1]+dy pos=evt.GetPosition() self.shape.SetBmpScale(self.shape.rate, self.shape.rate,(pos.x,pos.y), wsize) self.Update() # The mouse is moving def OnMotion(self, evt): pos=evt.GetPosition() shape=self.shape enlargeWindow.setPos(shape.pos0,(pos.x,pos.y),(shape.img.GetWidth()*shape.rate,shape.img.GetHeight()*shape.rate),self.window.GetSize()) # Ignore mouse movement if we're not dragging. if not self.dragShape or not evt.RightIsDown():#or not evt.Dragging() return # if we have a shape, but haven't started dragging yet if self.dragShape and not self.dragImage0: # only start the drag after having moved a couple pixels # refresh the area of the window where the shape was so it # will get erased. wsize=self.window.GetSize() self.showMark=False self.dragShape.shown = False pw,ph=self.shape.pos x0=max((0,pw)) y0=max((0,ph)) x1=min((wsize[0],self.shape.bmp.GetWidth()+pw)) y1=min((wsize[1],self.shape.bmp.GetHeight()+ph)) self.window.RefreshRect(wx.Rect(x0,y0,x1-x0,y1-y0), True) self.window.Update() self.dragImage0 = wx.DragImage(self.dragShape.bmp,wx.Cursor(wx.CURSOR_HAND)) hotspot = self.dragStartPos - self.dragShape.pos self.dragImage0.BeginDrag(hotspot, self.window, self.dragShape.fullscreen) self.dragImage0.Move(pos) self.dragImage0.Show() # if we have shape and image then move it, posibly highlighting another shape. if self.dragShape and self.dragImage0: self.dragImage0.Move(evt.GetPosition()) class LargePicture: def __init__(self,sc=None): if sc==None:return self.window=sc self.cross=SourceImages.cross.GetBitmap() self.cross_shape=self.cross.GetWidth(),self.cross.GetHeight() def SetImage(self,img): self.img=img self.shape=img.GetWidth(),img.GetHeight() self.pos=(0,0) self.scale=(0,0) self.rate=5 self.bmp=None self.rect=None self.window.Bind(wx.EVT_PAINT,self.OnPaint) def setPos(self,pic_pos=None,mouse_pos=None,scale=None,windowSize=None): '''enlarge picture''' if self.img==None:return wsize=self.window.GetSize() x0,y0=-pic_pos[0],-pic_pos[1] x1,y1=x0+windowSize[0],y0+windowSize[1] rr=self.shape[0]/float(scale[0]) xadd=wsize[0]/2.0/(self.rate/rr) yadd=wsize[1]/2.0/(self.rate/rr) x0,y0,x1,y1=int(x0*rr-xadd),int(y0*rr-yadd),int(x1*rr+xadd),int(y1*rr+yadd) m_pos=(mouse_pos[0]-pic_pos[0])*rr,(mouse_pos[1]-pic_pos[1])*rr if x0<0:x0=0 if y0<0:y0=0 if x1>self.shape[0]:x1=self.shape[0] if y1>self.shape[1]:y1=self.shape[1] rect=x0,y0,x1-x0,y1-y0 if rect!=self.rect or scale!=self.scale: self.scale=scale self.rect=rect img=self.img.GetSubImage(wx.Rect(*rect)) self.bmp=img.Scale(int(rect[2]*self.rate/rr),int(rect[3]*self.rate/rr)).ConvertToBitmap() x0=wsize[0]/2-(m_pos[0]-self.rect[0])*self.rate/rr y0=wsize[1]/2-(m_pos[1]-self.rect[1])*self.rate/rr self.pos=int(x0),int(y0) self.window.RefreshRect(wx.Rect(0,0,wsize[0],wsize[1])) self.window.Update() def OnPaint(self,evt): if self.bmp==None:return wsize=self.window.GetSize() dc=wx.PaintDC(self.window) dc.DrawBitmap(self.bmp,self.pos[0],self.pos[1],True) dc.DrawBitmap(self.cross,(wsize[0]-self.cross_shape[0])/2,(wsize[1]-self.cross_shape[1])/2) class gridWindow: def __init__(self,sc=None): if sc==None:return self.window=sc self.setdistribution() self.Oninit() def setdistribution(self): wsize=self.window.GetSize() wsize=wsize[0]-10,wsize[1]-50 # self.area_text = wx.TextCtrl(self.window, -1,'', pos=(5,5),size=(wsize[0], wsize[1]), # style=(wx.TE_MULTILINE | wx.TE_AUTO_SCROLL | wx.TE_DONTWRAP)) self.area_text = wx.TextCtrl(self.window, -1,'', pos=(5,5),size=(wsize[0], wsize[1]), style=(wx.TE_MULTILINE | wx.TE_DONTWRAP)) self.posCtrl = wx.TextCtrl(self.window, -1, "Set origin", pos=(70, wsize[1]+10),size=(100,30)) def Oninit(self): self.data=[] self.originIndex=0 self.xmax,self.xmin,self.ymax,self.ymin=1,0,1,0 self.xmax_pos,self.xmin_pos,self.ymax_pos,self.ymin_pos=(0,0),(0,0),(0,0),(0,0) self.area_text.SetValue('Result data\nX Y') self.setText('Set origin') def SetOrigin(self,pic_pos,mouse_pos,scale): setModel=['set xmax','set ymin','set ymax','successfully'] self.setText(setModel[self.originIndex]) pos=float(mouse_pos[0]-pic_pos[0])/scale[0],float(mouse_pos[1]-pic_pos[1])/scale[1] self.originIndex+=1 if self.originIndex==1: self.xmin_pos=pos self.xmin=float(self.GetValue('Xmin value','0').strip()) elif self.originIndex==2: self.xmax_pos=pos mainWindow.line.append((self.xmin_pos[0],self.xmin_pos[1],pos[0],pos[1])) self.xmax=float(self.GetValue('Xmax value','1').strip()) elif self.originIndex==3: self.ymin_pos=pos self.ymin=float(self.GetValue('Ymin value','0').strip()) elif self.originIndex==4: self.ymax_pos=pos self.ymax=float(self.GetValue('Ymax value','1').strip()) mainWindow.line.append((self.ymin_pos[0],self.ymin_pos[1],pos[0],pos[1])) self.xVector=self.xmax_pos[0]-self.xmin_pos[0],self.xmax_pos[1]-self.xmin_pos[1] self.yVector=self.ymax_pos[0]-self.ymin_pos[0],self.ymax_pos[1]-self.ymin_pos[1] a=self.xVector[0]*self.yVector[0]+self.xVector[1]*self.yVector[1] self.sinAngle=math.sin(math.acos(a/(math.sqrt(self.xVector[0]**2+self.xVector[1]**2)*math.sqrt(self.yVector[0]**2+self.yVector[1]**2)))) self.xCoefficient=(self.xmax-self.xmin)/math.sqrt(self.xVector[0]**2+self.xVector[1]**2) self.yCoefficient=(self.ymax-self.ymin)/math.sqrt(self.yVector[0]**2+self.yVector[1]**2) x0=self.Distance(self.xmin_pos, self.ymin_pos, self.ymax_pos, self.sinAngle) y0=self.Distance(self.ymin_pos, self.xmax_pos, self.xmin_pos, self.sinAngle) self.origin=self.xmin-x0*self.xCoefficient,self.ymin-y0*self.yCoefficient mainWindow.setOrigin=0 print(self.xmin,self.xmax,self.ymin,self.ymax) else:pass def Distance(self,pos,posStart,posStop,sinAngle): vector0=posStop[0]-posStart[0],posStop[1]-posStart[1] vector=pos[0]-posStart[0],pos[1]-posStart[1] area=vector[1]*vector0[0]-vector[0]*vector0[1] d=area/(math.sqrt(vector0[0]*vector0[0]+vector0[1]*vector0[1])*sinAngle) return d def writedata(self,pic_pos=None,mouse_pos=None,scale=None): pos=float(mouse_pos[0]-pic_pos[0])/scale[0],float(mouse_pos[1]-pic_pos[1])/scale[1] mainWindow.circle.append(pos) dy=self.Distance(pos, self.xmax_pos, self.xmin_pos, self.sinAngle) dx=self.Distance(pos, self.ymin_pos, self.ymax_pos, self.sinAngle) t=dx*self.xCoefficient+self.origin[0],dy*self.yCoefficient+self.origin[1] self.data.append(t) self.area_text.AppendText('\n%e , %e' % t) def OnClick(self,evt): self.originIndex=0 mainWindow.InitSetOrigin() mainWindow.setOrigin=1 self.setText('set xmin') def setText(self,text): self.posCtrl.SetValue(text) def GetValue(self,title='Value',default='0'): dlg = wx.TextEntryDialog(self.window, title,'Value Entry Dialog',default) if dlg.ShowModal() == wx.ID_OK: d=dlg.GetValue() else:d=default dlg.Destroy() return d #******************************************************* class MyDialog(wx.Dialog): def __init__(self, parent, title): super(MyDialog, self).__init__(parent, title = title, size = (250,150)) panel = wx.Panel(self) self.posCtrl = wx.TextCtrl(panel, -1, "Set origin", pos=(10, 10),size=(100,30)) self.btn = wx.Button(panel, wx.ID_OK, label = "ok", size = (50,20), pos = (75,50)) #end********************************************************************************************* mainWindow=DragCanvas() enlargeWindow=LargePicture() dataWindow=gridWindow() #******************************************************************************************** def area(polygon): ''' Calculate the area of a polygon polygon:a set of points ''' Direction=lambda a,b,c:(b[0]-a[0])*(c[1]-b[1])-(b[1]-a[1])*(c[0]-b[0]) d=([polygon[0],polygon[1]],[]) i,n,ed=2,len(polygon),0 isBreak=False while i<n: a,b,c=d[0][-2],d[0][-1],polygon[i] if Direction(a,b,c)<0: d[0][-1]=c d[1].append((a,b,c)) else:d[0].append(c) i+=1 def check(ma,mb,mc): while True: a,b,c=d[0][ma],d[0][mb],d[0][mc] if Direction(a,b,c)<0: d[0].pop(mb) d[1].append((a,b,c)) else :break check(-2,-1,0) check(-1,0,1) s,st=0,0 a=d[0][0] for i in range(1,len(d[0])-1): b,c=d[0][i],d[0][i+1] sp=Direction(a,b,c)/2.0 s+=sp for a,b,c in d[1]: sp=Direction(a,b,c)/2.0 st+=sp return d,abs(st+s) #*********************************************************************************************** def main(): #设置了主窗口的初始大小960x540 800x450 640x360 root = wx.App() frame = MainFrame() frame.Show(True) root.MainLoop() #****************end sdf******************** if __name__ == "__main__": main()
Rust
UTF-8
14,440
2.984375
3
[]
no_license
extern crate tempdir; use std::fmt; use std::error; use std::str; use std::io::Write; use std::io::Read; use std::io::Seek; use std::io::SeekFrom; use std::fs::File; use std::fs::OpenOptions; use std::path::PathBuf; #[derive(Debug)] pub enum DbError { MetaUnrecognized, StatementUnrecognized, StatementSyntaxError, TableFull, ParsingError(std::num::ParseIntError), } impl fmt::Display for DbError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { DbError::MetaUnrecognized => write!(f, "Meta command unrecognized"), DbError::StatementUnrecognized => write!(f, "Statement unrecognized"), DbError::StatementSyntaxError => write!(f, "Statement has syntax error"), DbError::TableFull => write!(f, "Table is full"), DbError::ParsingError(ref err) => err.fmt(f), } } } impl error::Error for DbError { fn description(&self) -> &str { match *self { DbError::MetaUnrecognized => "Unrecognized", DbError::StatementUnrecognized => "Unrecognized", DbError::StatementSyntaxError => "Syntax Error", DbError::TableFull => "Table full", DbError::ParsingError(ref err) => err.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { DbError::ParsingError(ref err) => Some(err), _ => None, } } } impl From<std::num::ParseIntError> for DbError { fn from(err: std::num::ParseIntError) -> DbError { DbError::ParsingError(err) } } const USERID_SIZE: usize = 31; const EMAIL_SIZE: usize = 254; // Store size of email/id instead of null terminating // This means we need 2 extra bytes for serialization, // and we still need a paging table of some sort to actually // make this dynamic sizing useful... // To sync with the tutorial, I am going to use 31 and 254 // as the userid and email size instead of 32 and 255 const ROW_SIZE: usize = EMAIL_SIZE + USERID_SIZE + 4 + 2; const PAGE_SIZE: usize = 4096; const ROWS_PER_PAGE: usize = PAGE_SIZE / ROW_SIZE; const TABLE_MAX_PAGES: usize = 100; const TABLE_MAX_ROWS: usize = ROWS_PER_PAGE * TABLE_MAX_PAGES; #[derive(Debug)] struct Row { id: u32, user_id: String, email: String, } impl Row { fn deserialize(data : &[u8]) -> Row { let mut id : u32 = 0; id = id ^ (data[0] as u32); id = id ^ ((data[1] as u32) << 8); id = id ^ ((data[2] as u32) << 16); id = id ^ ((data[3] as u32) << 24); let user_id_len : usize = data[4] as usize; let email_len : usize = data[5] as usize; let user_id = str::from_utf8(&data[6..6+user_id_len]).unwrap(); let email = str::from_utf8(&data[6+user_id_len.. 6+user_id_len+email_len]).unwrap(); Row { id, user_id : user_id.to_string(), email : email.to_string(), } } fn serialize(&self, data : &mut [u8]) -> () { data[0] = self.id as u8; data[1] = (self.id >> 8) as u8; data[2] = (self.id >> 16) as u8; data[3] = (self.id >> 24) as u8; let user_id_len = self.user_id.len(); data[4] = user_id_len as u8; let email_len = self.email.len(); data[5] = email_len as u8; data[6..6+user_id_len].copy_from_slice(self.user_id.as_bytes()); data[6+user_id_len..6+user_id_len+email_len] .copy_from_slice(self.email.as_bytes()); } } struct Pager { file : File, file_length : u64, pages: Vec<Vec<u8>>, } // do I need a drop for Pager so file gets dropped? impl Pager { fn open(filename : PathBuf) -> Pager { let file = OpenOptions::new().read(true) .write(true) .create(true) .open(filename) .expect("Cannot open persistent file"); let meta = file.metadata().expect("Cannot open file metadata"); let mut pager = Pager { file, file_length : meta.len(), pages: Vec::with_capacity(TABLE_MAX_PAGES), }; for _i in 0..TABLE_MAX_PAGES { // vec![] should be of capacity 0 pager.pages.push(vec![]); } pager } fn get(&mut self, page_num : usize) -> &mut [u8] { if page_num > TABLE_MAX_PAGES { panic!("Tried to fetch page number out of bounds. {} > {}\n", page_num, TABLE_MAX_PAGES); } if self.pages[page_num].len() == 0 { self.pages[page_num] = vec![0; PAGE_SIZE]; let mut num_pages : u64 = self.file_length / PAGE_SIZE as u64; if self.file_length % PAGE_SIZE as u64 != 0 { num_pages += 1; } if (page_num as u64) < num_pages { let start_offset = (page_num * PAGE_SIZE) as u64; self.file.seek(SeekFrom::Start(start_offset)) .expect("Unable to read page from file"); // if this is the last page, and not full // then we can only read whatever we have let mut size = PAGE_SIZE; if self.file_length < start_offset + (size as u64) { size = (self.file_length - start_offset) as usize; } self.file.read_exact(&mut self.pages[page_num][..size]) .expect("Unable to read page from file"); } } return &mut self.pages[page_num][..]; } fn flush(&mut self, page_num : usize, size : usize) { if self.pages[page_num].len() == 0 { return; } self.file.seek(SeekFrom::Start((page_num * PAGE_SIZE) as u64)) .expect("Cannot write to file"); self.file.write_all(&self.pages[page_num][..size]) .expect("Cannot write to file"); } } pub struct Table { pager : Pager, num_rows : usize, } impl Table { pub fn db_open(filename : PathBuf) -> Table { let pager = Pager::open(filename); // the tutorial is wrong // let num_rows = pager.file_length / ROW_SIZE as u64; let file_length = pager.file_length as usize; //well.. let pages = file_length / PAGE_SIZE; let additional = (file_length - (pages * PAGE_SIZE)) / ROW_SIZE; let num_rows = additional + pages * ROWS_PER_PAGE; Table { pager, num_rows : num_rows as usize, } } fn add_row(&mut self, row : &Row) -> Result<(), DbError> { { let mut cursor = Cursor::table_end(self); let row_data = cursor.get_row()?; row.serialize(row_data); } self.num_rows += 1; Ok(()) } } impl Drop for Table { fn drop(&mut self) { let full_pages = self.num_rows / ROWS_PER_PAGE; for i in 0..full_pages { self.pager.flush(i, PAGE_SIZE); } let additional_rows = self.num_rows % ROWS_PER_PAGE; if additional_rows > 0 { self.pager.flush(full_pages, additional_rows * ROW_SIZE); } } } pub struct Cursor<'a> { table : &'a mut Table, row_num : usize, end_of_table : bool, } impl<'a> Cursor<'a> { fn table_start(table : &'a mut Table) -> Cursor { let end_of_table = table.num_rows == 0; Cursor { table, row_num : 0, end_of_table, } } fn table_end(table : &'a mut Table) -> Cursor { let row_num = table.num_rows; Cursor { table, row_num, end_of_table : true, } } fn get_row(&mut self) -> Result<&mut [u8], DbError> { let page_num = self.row_num / ROWS_PER_PAGE; if page_num >= TABLE_MAX_PAGES { return Err(DbError::TableFull); } let row_offset : usize = self.row_num % ROWS_PER_PAGE; let byte_offset : usize = row_offset * ROW_SIZE; return Ok(&mut self.table.pager.get(page_num)[byte_offset..byte_offset+ROW_SIZE]); } fn advance(&mut self) { self.row_num += 1; if self.row_num >= self.table.num_rows { self.end_of_table = true; } } } pub fn meta_command(_input : &str) -> Result<(), DbError> { Err(DbError::MetaUnrecognized) } pub fn statement_command(input : &str, mut table : &mut Table, writer : &mut Write) -> Result<(), DbError> { if input.starts_with("select") { let mut cursor = Cursor::table_start(&mut table); while !cursor.end_of_table { let r = Row::deserialize(&(cursor.get_row()?)); writer.write_fmt(format_args!("({}, {}, {})\n", r.id, r.user_id, r.email)).unwrap(); cursor.advance(); } writer.flush().unwrap(); } else if input.starts_with("insert") { if table.num_rows >= TABLE_MAX_ROWS { return Err(DbError::TableFull); } let params : Vec<&str> = input.split_whitespace().collect(); if params.len() != 4 { return Err(DbError::StatementSyntaxError); } let id = params[1].parse::<u32>()?; if params[2].len() > USERID_SIZE || params[3].len() > EMAIL_SIZE { return Err(DbError::StatementSyntaxError); } let row = Row { id, user_id : String::from(params[2]), email : String::from(params[3]), }; table.add_row(&row)?; } else { return Err(DbError::StatementUnrecognized); } Ok(()) } #[cfg(test)] mod tests { use super::*; use tempdir::TempDir; #[test] fn it_works() { let tmp_dir = TempDir::new("simple-db").unwrap(); let file_path = tmp_dir.path().join("test1.db"); let mut table = Table::db_open(file_path); let mut buf : Vec<u8> = vec![]; statement_command("insert 1 user1 person1@example.com", &mut table, &mut buf).unwrap(); statement_command("select", &mut table, &mut buf).unwrap(); assert_eq!(String::from_utf8(buf).unwrap(), String::from("(1, user1, person1@example.com)\n")); } #[test] fn table_max() { let tmp_dir = TempDir::new("simple-db").unwrap(); let file_path = tmp_dir.path().join("test1.db"); let mut table = Table::db_open(file_path); for i in 0..1400 { let mut buf : Vec<u8> = vec![]; let insert_str = format!("insert {} user{} person{}@example.com", i, i, i ); statement_command(&insert_str, &mut table, &mut buf).unwrap(); } let mut buf : Vec<u8> = vec![]; statement_command("select", &mut table, &mut buf).unwrap(); let mut idx = 0; let whole_str = String::from_utf8(buf).unwrap(); let lines = whole_str.lines(); for rec in lines { assert_eq!(rec, format!("({}, user{}, person{}@example.com)", idx, idx, idx)); idx += 1; } assert_eq!(idx, 1400); } #[test] #[should_panic(expected = "Table is full")] fn table_full() { let tmp_dir = TempDir::new("simple-db").unwrap(); let file_path = tmp_dir.path().join("test1.db"); let mut table = Table::db_open(file_path); for _i in 0..1401 { let mut buf : Vec<u8> = vec![]; match statement_command("insert 1 user1 person1@example.com", &mut table, &mut buf) { Ok(_) => (), Err(DbError::TableFull) => panic!("Table is full"), _ => panic!("incorrect panic"), } } } #[test] fn long_name() { let tmp_dir = TempDir::new("simple-db").unwrap(); let file_path = tmp_dir.path().join("test1.db"); let mut table = Table::db_open(file_path); let mut buf : Vec<u8> = vec![]; let long_user = "a".repeat(31); let long_email = "a".repeat(254); let long_insert = format!("insert 1 {} {}", long_user, long_email); statement_command(long_insert.as_str(), &mut table, &mut buf).unwrap(); statement_command("select", &mut table, &mut buf).unwrap(); assert_eq!(String::from_utf8(buf).unwrap(), format!("(1, {}, {})\n", long_user, long_email)); } #[test] #[should_panic(expected = "uint parse error")] fn uint_parse() { let tmp_dir = TempDir::new("simple-db").unwrap(); let file_path = tmp_dir.path().join("test1.db"); let mut table = Table::db_open(file_path); let mut buf : Vec<u8> = vec![]; match statement_command("insert -1 x x", &mut table, &mut buf) { Ok(_) => (), Err(DbError::ParsingError(_)) => panic!("uint parse error"), _ => panic!("incorrect panic"), } } #[test] fn table_max_persist() { let tmp_dir = TempDir::new("simple-db").unwrap(); for total_lines in 0..1400 { let path1 = tmp_dir.path().join(format!("test{}.db",total_lines)); let path2 = path1.clone(); { let mut table = Table::db_open(path1); for i in 0..total_lines { let mut buf : Vec<u8> = vec![]; let insert_str = format!("insert {} user{} person{}@example.com", i, i, i ); statement_command(&insert_str, &mut table, &mut buf).unwrap(); } } { let mut table = Table::db_open(path2); let mut buf : Vec<u8> = vec![]; statement_command("select", &mut table, &mut buf).unwrap(); let mut idx = 0; let whole_str = String::from_utf8(buf).unwrap(); let lines = whole_str.lines(); for rec in lines { assert_eq!(rec, format!("({}, user{}, person{}@example.com)", idx, idx, idx)); idx += 1; } assert_eq!(idx, total_lines); } } } }
Java
UTF-8
3,634
2.359375
2
[]
no_license
package fastboard.checkmove.fastcheck.bcolumn; import fastboard.FastBoardTestCase; import fastboard.checkmove.calc.FastCheckCalc; import fastboard.fastflip.FastBoardFlips; import fastboard.lineconverter.LineConverter; /** * Created by IntelliJ IDEA. * User: knhjp * Date: Nov 29, 2009 * Time: 02:53:25 PM * Tests whether or not FastCheckB6 checks for valid moves properly */ public class FastCheckB6Test extends FastBoardTestCase { public void testIsMoveValidBlack() { FastCheckCalc calc = new FastCheckCalc(); boolean[][] fastCheckCalcArray = calc.calcIsMoveValid(blackLineDecoders); FastCheckB6 check = new FastCheckB6(fastCheckCalcArray); FastBoardFlips flips = new FastBoardFlips(); assertFalse(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("xoooooox"); assertFalse(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("xoooo_xx"); assertTrue(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("xxxxx_ox"); assertTrue(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("_oooo_xo"); flips.a5_d8 = LineConverter.convertStringToLine("______oo"); assertFalse(check.isValidMove(flips)); flips.a5_d8 = LineConverter.convertStringToLine("______ox"); assertTrue(check.isValidMove(flips)); flips.a5_d8 = LineConverter.convertStringToLine("_____o_x"); flips.a6_h6 = LineConverter.convertStringToLine("__xoooox"); assertFalse(check.isValidMove(flips)); flips.a6_h6 = LineConverter.convertStringToLine("__oox___"); assertTrue(check.isValidMove(flips)); flips.a6_h6 = LineConverter.convertStringToLine("__xoxoxo"); flips.a7_g1 = LineConverter.convertStringToLine("__ooooox"); assertFalse(check.isValidMove(flips)); flips.a7_g1 = LineConverter.convertStringToLine("___oooox"); assertTrue(check.isValidMove(flips)); } public void testIsMoveValidWhite() { FastCheckCalc calc = new FastCheckCalc(); boolean[][] fastCheckCalcArray = calc.calcIsMoveValid(whiteLineDecoders); FastCheckB6 check = new FastCheckB6(fastCheckCalcArray); FastBoardFlips flips = new FastBoardFlips(); assertFalse(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("oxxxxxxo"); assertFalse(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("oxxxx_oo"); assertTrue(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("ooooo_xo"); assertTrue(check.isValidMove(flips)); flips.b1_b8 = LineConverter.convertStringToLine("_xxxx_ox"); flips.a5_d8 = LineConverter.convertStringToLine("______xx"); assertFalse(check.isValidMove(flips)); flips.a5_d8 = LineConverter.convertStringToLine("______xo"); assertTrue(check.isValidMove(flips)); flips.a5_d8 = LineConverter.convertStringToLine("_____x_o"); flips.a6_h6 = LineConverter.convertStringToLine("__oxxxxo"); assertFalse(check.isValidMove(flips)); flips.a6_h6 = LineConverter.convertStringToLine("__xxo___"); assertTrue(check.isValidMove(flips)); flips.a6_h6 = LineConverter.convertStringToLine("__oxoxox"); flips.a7_g1 = LineConverter.convertStringToLine("__xxxxxo"); assertFalse(check.isValidMove(flips)); flips.a7_g1 = LineConverter.convertStringToLine("___xxxxo"); assertTrue(check.isValidMove(flips)); } }
Python
UTF-8
2,882
2.828125
3
[]
no_license
import math import pickle from pathlib import Path import matplotlib.pyplot as plt import torch import torch.nn.functional as F from torch import nn from torch import optim from torch.utils.data import DataLoader, TensorDataset def draw(X): print(X.shape) plt.imshow(X.reshape((28, 28)), cmap='gray') plt.show() def read_data(): path = Path('data/mnist/mnist.pkl') if path.exists(): with open('data/mnist/mnist.pkl', 'rb') as f: (XTrain, YTrain), (XTest, YTest), _ = pickle.load(f, encoding='latin-1') return XTrain, YTrain, XTest, YTest else: raise Exception(FileNotFoundError) def generate_validation_set(k=10): global num_train, XTrain, YTrain num_valid = num_train // k num_train -= num_valid XValid, YValid = XTrain[:num_valid], YTrain[:num_valid] XTrain, YTrain = XTrain[num_valid:], YTrain[num_valid:] return XValid, YValid, num_valid XTrain, YTrain, XTest, YTest = read_data() # train: 50000, test: 10000 num_train = XTrain.shape[0] num_test = XTest.shape[0] XValid, YValid, num_valid = generate_validation_set(k=10) XTrain, YTrain, XValid, YValid, XTest, YTest = map(torch.tensor, (XTrain, YTrain, XValid, YValid, XTest, YTest)) class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self).__init__() self.linear = nn.Linear(784, 10) def forward(self, batch_x): return self.linear(batch_x) def accuracy(batch_z, batch_y): temp = torch.argmax(batch_z, dim=1) r = (temp == batch_y) return r.float().mean() # hyper-parameter bs = 64 lr = 0.05 max_epoch = 20 # essential stuff loss_func = F.cross_entropy model = NeuralNet() optimizer = optim.SGD(model.parameters(), lr=lr) # datasets and dataloaders train_set = TensorDataset(XTrain, YTrain) train_loader = DataLoader(train_set, batch_size=bs, shuffle=True) valid_set = TensorDataset(XValid, YValid) valid_loader = DataLoader(valid_set, batch_size=bs * 2, shuffle=False) def train(): print('training...') for epoch in range(max_epoch): model.train() # training: using training set for batch_x, batch_y in train_loader: # forward batch_z = model(batch_x) # backward loss = loss_func(batch_z, batch_y) loss.backward() optimizer.step() optimizer.zero_grad() model.eval() # inference: using validation set with torch.no_grad(): valid_loss = sum(loss_func(model(batch_x), batch_y) for batch_x, batch_y in valid_loader) / num_valid print("epoch %d, validation loss=%.4f" % (epoch, valid_loss)) print('training done.') def test(): print('testing...') ZTest = model(XTest) print('loss=%.4f, accuracy=%.4f' % (loss_func(ZTest, YTest), accuracy(ZTest, YTest))) print('testing done.') train() test()
C#
UTF-8
2,524
2.578125
3
[]
no_license
using Core.DataAccess.EntityFramework; using DataAccess.Abstract; using DataAccess.Concrete.EntityFramework.Context; using Entities.Concrete; using Entities.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DataAccess.Concrete.EntityFramework { public class EfCarDal : EfEntityRepositoryBase<Car, ReCapContext>, ICarDal { public List<CarDTO> GetCarsDetails() { using (var context = new ReCapContext()) { var cars = from c in context.Cars join b in context.Brands on c.BrandId equals b.Id join cl in context.Colors on c.ColorId equals cl.Id select new CarDTO { Brand = b.Name, Color = cl.Name, DailyPrice = c.DailyPrice, Description = c.Description, ModelYear = c.ModelYear }; //var carsDto = context.Cars.Select(x => new CarDTO //{ // Brand = context.Brands.SingleOrDefault(b => b.Id == x.BrandId).Name, // Color = context.Colors.SingleOrDefault(cl => cl.Id == x.ColorId).Name, // DailyPrice = x.DailyPrice, // Description = x.Description, // ModelYear = x.ModelYear //}); return cars.ToList(); } } public CarDTO GetCarDetailsById(int id) { using (var context = new ReCapContext()) { var car = from cr in context.Cars join br in context.Brands on cr.BrandId equals br.Id join cl in context.Colors on cr.ColorId equals cl.Id where cr.Id == id select new CarDTO { Brand = br.Name, Color = cl.Name, DailyPrice = cr.DailyPrice, Description = cr.Description, ModelYear = cr.ModelYear }; return car.SingleOrDefault(); } } } }
TypeScript
UTF-8
1,535
2.71875
3
[ "MIT", "MIT-0" ]
permissive
import { ComponentValue, ComponentValueType, FunctionNode } from '@csstools/css-parser-algorithms'; import { CSSToken, TokenFunction, TokenType } from '@csstools/css-tokenizer'; import { toLowerCaseAZ } from './to-lower-case-a-z'; export function isNumber(componentValue: ComponentValue) { if ( (componentValue.type === ComponentValueType.Token && (componentValue.value as CSSToken)[0] === TokenType.Number) || (componentValue.type === ComponentValueType.Function && mathFunctions.has(toLowerCaseAZ(((componentValue as FunctionNode).name as TokenFunction)[4].value))) ) { return true; } return false; } const mathFunctions = new Set([ 'abs', 'acos', 'asin', 'atan', 'atan2', 'calc', 'clamp', 'cos', 'exp', 'hypot', 'log', 'max', 'min', 'mod', 'pow', 'rem', 'round', 'sign', 'sin', 'sqrt', 'tan', ]); export function isDimension(componentValue: ComponentValue) { if (componentValue.type === ComponentValueType.Token && (componentValue.value as CSSToken)[0] === TokenType.Dimension) { return true; } return false; } export function isIdent(componentValue: ComponentValue) { if (componentValue.type === ComponentValueType.Token && (componentValue.value as CSSToken)[0] === TokenType.Ident) { return true; } return false; } export function isEnvironmentVariable(componentValue: ComponentValue) { if (componentValue.type === ComponentValueType.Function && toLowerCaseAZ(((componentValue as FunctionNode).name as TokenFunction)[4].value) === 'env' ) { return true; } return false; }
Java
UTF-8
598
2.25
2
[]
no_license
package com.example.alexander.sportdiary.ViewHolders; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.example.alexander.sportdiary.R; public class TestViewHolder extends RecyclerView.ViewHolder { private TextView testView; public TestViewHolder(@NonNull View itemView) { super(itemView); testView = itemView.findViewById(R.id.test_name); itemView.setTag(itemView); } public void setData(String test) { testView.setText(test); } }
Python
UTF-8
1,879
4.5625
5
[]
no_license
# Condicionales [Python] # Ejercicios de profundización # Autor: Inove Coding School # Version: 2.0 # NOTA: # Estos ejercicios son de mayor dificultad que los de clase y práctica. # Están pensados para aquellos con conocimientos previo o que dispongan # de mucho más tiempo para abordar estos temas por su cuenta. # Requiere mayor tiempo de dedicación e investigación autodidacta. # IMPORTANTE: NO borrar los comentarios en VERDE o NARANJA # Ejercicios de práctica con números a = int(input("ingrese el primer numero:")) b = int(input("ingrese el segundo numero:")) c = int(input("ingrese el tercer numero:")) if a > b and a > c: print(f"{a} es la temperatura maxima ") elif b > a and b > c: print(f"{b} es la temperatura maxima") elif c > a and c > b: print(f"{c} es la temperatura maxima") if a < b and a < c: print(f"{a} es la temperatura minima") elif b < a and b < c: print(f"{b} es la temperatura minima") elif c < a and c < b: print(f"{c} es la temperatura minima") if a > 0: d = (a+b+c)/3 print(f"el promedio de las temperaturas es {d}") ''' Enunciado: Realice un programa que solicite ingresar tres valores de temperatura De las temperaturas ingresadas por consola determinar: 1 - ¿Cuáles de ellas es la máxima temperatura ingresada? 2 - ¿Cuáles de ellas es la mínima temperatura ingresada? 3 - ¿Cuál es el promedio de las temperaturas ingresadas? En cada caso imprimir en pantalla el resultado IMPORTANTE: Para ordenar las temperatuas debe utilizar condicionales compuestos o anidados, no se busca utilizar bucles o algoritmos de ordenamiento ya que aún no hemos llegado a ese contenido. Recomendamos pensar bien este problema de lógica con un lápiz y papel. ''' print('Ejercicios de práctica con números') # Empezar aquí la resolución del ejercicio
JavaScript
UTF-8
2,189
2.59375
3
[ "Apache-2.0" ]
permissive
import twoInputsReducer, { initState, twoInputsChange, twoInputsChangedDelayed, selectValueOne, selectValueTwo, TWO_INPUTS_CHANGE_DELAYED } from 'app/redux/two-inputs' import twoInputsData from 'app/redux/two-inputs/index.test.data' describe('two-inputs redux', function () { it('should handle TWO_INPUTS/change action', function () { //given const action = twoInputsChange(twoInputsData.valueOne, twoInputsData.valueTwo); //when const newState = twoInputsReducer(undefined, action); const newTotalState = { twoInputs: newState }; //then expect(selectValueOne(newTotalState)).toBe(twoInputsData.valueOne); expect(selectValueTwo(newTotalState)).toBe(twoInputsData.valueTwo); }); it('should return the same state for unknow action', function () { //given const oldState = { twoInputs: twoInputsData }; const dummyAction = { type: 'DUMMY' }; //when const newState = twoInputsReducer(oldState, dummyAction); //then expect(oldState).toEqual(newState); }); it('should have initialized state', function () { //given const dummyAction = { type: 'DUMMY' }; //when const newState = twoInputsReducer(undefined, dummyAction); //then const newTotalState = { twoInputs: newState }; expect(selectValueOne(newTotalState)).toBe(initState.valueOne); expect(selectValueTwo(newTotalState)).toBe(initState.valueTwo); }); it('should create twoInputChangedDelayed action', function () { //when const actionObject = twoInputsChangedDelayed(10, 100); //then expect(actionObject).toEqual({ type: TWO_INPUTS_CHANGE_DELAYED, payload: { valueOne: '10', valueTwo: '100' } }) }); it('should handle twoInputChangedDelayed action', function () { //given const valueOne = 10; const valueTwo = 100; const action = twoInputsChangedDelayed(valueOne, valueTwo); //when const newState = twoInputsReducer(twoInputsData, action); //then expect(newState.valueOne).toBe(valueOne.toString()); expect(newState.valueTwo).toBe(valueTwo.toString()); }) });
Python
UTF-8
8,733
2.609375
3
[]
no_license
# -*- coding:utf-8 -*- # !/bin/python """ Author: Winslen Date: 2019/10/15 Revision: 1.0.0 Description: Description """ import re class FormatSql(object): PARAMERTS_REG = re.compile(r':([_0-9]*[_A-z]+[_0-9]*[_A-z]*)') def __init__(self, tableName, **kwargs): self.kwargs = kwargs self.tableName = tableName self.columnNames = kwargs.get('columnNames', []) self.formatKeyNum = 0 self.formatDict = {} self.whereStr = '' self.orderStr = '' whereParams = kwargs.get('whereParams', {}) if whereParams and whereParams.get('data', {}): whereData = whereParams['data'] joinStr = whereParams.get('joinStr', 'AND') sign = whereParams.get('sign', '=') tmpWhereStr = self.getWhereStr_ByDatas(whereDatas=whereData, joinStr=joinStr, sign=sign) self.setWhereStr(tmpWhereStr) def getNextTmpValueName(self, incr=1): self.formatKeyNum += incr return 'value_%s' % (self.formatKeyNum) def setWhereStr(self, whereStr): self.whereStr = whereStr def addWhereStr(self, whereStr, joinStr='AND'): self.whereStr += ' %s %s' % (joinStr, whereStr) def insertWhereData(self, key, value, sign='='): '''sign: =,>,<,Like''' tmpValueName = self.getNextTmpValueName() if isinstance(value, str): value = value.replace("'", "\\'").replace('"', '\\"') elif isinstance(value, (tuple, list)) and sign == 'in': value = tuple(value) # value = repr(value).replace(",)", ")") self.formatDict[tmpValueName] = value return "`%s` %s :%s" % (key, sign, tmpValueName) def getWhereStr_ByDatas(self, whereDatas, joinStr='AND', sign='='): whereStr = '' for _key, _value in whereDatas.items(): str_ = self.insertWhereData(key=_key, value=_value, sign=sign) whereStr += '%s %s ' % (str_, joinStr) whereStr = whereStr.strip().strip(joinStr).strip() return whereStr def joinWhereStr(self, joinStr='AND', *args): whereStr = '' for _arg in args: whereStr += '(%s) %s ' % (_arg, joinStr) whereStr = whereStr.strip().strip(joinStr).strip() return whereStr def fiterSqlStr(self): sqlStr = '' sqlStr = self.PARAMERTS_REG.sub(r'%(\1)s', sqlStr) return sqlStr def tryGetAllSql(self): '''可以获取sql数据拼接后的语句,但是此处只是预览''' sqlStr = self.fiterSqlStr() for _key, _value in self.formatDict.items(): if isinstance(_value, str): _value = "'%s'" % _value sqlStr = sqlStr.replace(':%s' % _key, str(_value)) return sqlStr def getSqlStrAndArgs(self): return self.fiterSqlStr(), self.formatDict class FormatSql_Insert(FormatSql): def __init__(self, **kwargs): super(FormatSql_Insert, self).__init__(**kwargs) self.datasDict = kwargs.get('datasDict', {}) def fiterSqlStr(self): keyStr = [] valueStr = [] for _key, _value in self.datasDict.items(): tmpValueName = self.getNextTmpValueName() self.formatDict[tmpValueName] = _value keyStr.append(_key) valueStr.append(':%s' % tmpValueName) sqlStr = 'INSERT INTO %s (`%s`) VALUES (%s)' % (self.tableName, '`,`'.join(keyStr), ','.join(valueStr)) sqlStr = sqlStr.replace(' ', ' ') sqlStr = self.PARAMERTS_REG.sub(r'%(\1)s', sqlStr) return sqlStr class FormatSql_Select(FormatSql): def getTableSql(self): '''获取主要的sql语句''' columnNames = self.kwargs.get('columnNames') if columnNames: keysStr = '`,`'.join(columnNames) tableSql = 'SELECT `%s` FROM %s' % (keysStr, self.tableName) else: tableSql = 'SELECT * FROM %s' % (self.tableName) return tableSql def doJoinTable(self): joinType = self.kwargs.get('joinType', 'JOIN') joinTableName = self.kwargs.get('joinTableName', '') onStr = self.kwargs.get('onStr', '') if not joinTableName: return '' if onStr: joinTableStr = '%s %s ON %s' % (joinType, joinTableName, onStr) else: joinTableStr = '%s %s' % (joinType, joinTableName) return joinTableStr def doOrderBy(self): orderBy = self.kwargs.get('orderBy', '') orderType = self.kwargs.get('orderType', 'DESC') if not orderBy: return '' return 'ORDER BY `%s` %s' % (orderBy, orderType) def fiterSqlStr(self): sqlStr = self.getTableSql() joinSql = self.doJoinTable() if joinSql: sqlStr += ' ' + joinSql if self.whereStr: sqlStr += ' WHERE ' + self.whereStr orderStr = self.doOrderBy() if orderStr: sqlStr += ' ' + orderStr sqlStr = sqlStr.replace(' ', ' ') sqlStr = self.PARAMERTS_REG.sub(r'%(\1)s', sqlStr) return sqlStr class FormatSql_Update(FormatSql): def __init__(self, **kwargs): super(FormatSql_Update, self).__init__(**kwargs) self.datasDict = kwargs.get('datasDict', {}) def getSetDataStr(self): setDataStr = self.getWhereStr_ByDatas(self.datasDict, joinStr=',') return setDataStr def fiterSqlStr(self): setData = self.getSetDataStr() sqlStr = 'UPDATE %s SET %s' % (self.tableName, setData) if self.whereStr: sqlStr += ' WHERE ' + self.whereStr sqlStr = self.PARAMERTS_REG.sub(r'%(\1)s', sqlStr) return sqlStr class FormatSql_Delete(FormatSql): def fiterSqlStr(self): sqlStr = 'DELETE FROM %s' % (self.tableName) if self.whereStr: sqlStr += ' WHERE ' + self.whereStr sqlStr = self.PARAMERTS_REG.sub(r'%(\1)s', sqlStr) return sqlStr if __name__ == '__main__': VIDEO_SQL_KEY_1 = ['ym_video.id', 'ym_video.create_time', 'image_url', 'video_url', 'title', 'praiseCount', 'watchCount', 'content', 'director_id', 'nickname', 'user_id', 'avatar_url'] pass # a = FormatSql_Select( # **dict( # tableName='ym_video', # joinTableName='ym_users', # onStr='ym_video.user_id = ym_users.id', # whereParams={ # 'data': {'ym_video.id': '123'}, # 'joinStr': 'AND', # 'sign': '=', # }, # columnNames=VIDEO_SQL_KEY_1, # joinType='LEFT JOIN', # orderBy='create_time', # ) # ) # # print(a.fiterSqlStr()) # # print('#' * 50) # a1 = a.getWhereStr_ByDatas({'ym_video.id': 37, 'title': 'ass'}) # a2 = a.getWhereStr_ByDatas({'ym_video.id': 38, 'title': 'hahahah'}, joinStr='AND') # a3 = a.getWhereStr_ByDatas({'ym_video.id': [39, 40], 'title': ['hahahah', 'hahahahasdsa']}, joinStr='AND', sign='in') # print('a1=>', a1) # print('a2=>', a2) # print('a3=>', a3) # a4 = a.joinWhereStr(joinStr='OR', a1, a2, a3) # print('a4=>', a4) # a.addWhereStr(a4) # print(a.fiterSqlStr()) # print(a.tryGetAllSql()) # a4 = a.joinWhereStr(joinStr='OR', a1, a2, a3) # print('a4=>', a4) # print('#' * 50) # a5 = a.getWhereStr_ByDatas({'ym_video.id': 43, 'title': '1231'}) # print('a5=>', a5) # # a6 = a.joinWhereStr(joinStr='OR', a4, a5) # print('a6=>', a6) # a.setWhereStr(a6) # print(a.formatDict) # a7 = a.fiterSqlStr() # print('a7=>', a7) # a = FormatSql_Insert(**dict( # tableName='ym_video', # datasDict={'id': 2, 'name': '你好'} # )) # print(a.fiterSqlStr()) # print(a.tryGetAllSql()) # a = FormatSql_Update(**dict( # tableName='ym_video', # datasDict={'id': 2, 'name': '你好'}, # whereParams={ # 'data': {'ym_video.id': '123', 'name': '你好'}, # 'joinStr': 'AND', # 'sign': '=', # }, # )) # print(a.fiterSqlStr()) # print(a.tryGetAllSql()) # # a = FormatSql_Delete(**dict( # tableName='ym_video', # whereParams={ # 'data': {'ym_video.id': '123', 'name': '你好'}, # 'joinStr': 'AND', # 'sign': '=', # }, # )) # print(a.fiterSqlStr()) # print(a.tryGetAllSql())
C++
UTF-8
1,540
2.640625
3
[]
no_license
#include <homodeus_arm_interface/ArmInterface.h> // Code to test the arm interface int main(int argc, char **argv) { std::string controlType; ros::init(argc, argv, "arm_interface_node"); ros::NodeHandle n("~"); ArmInterface arm; ROS_INFO("arm_interface_node is now running!"); ros::AsyncSpinner spinner(1); spinner.start(); // n.getParam("control_type", controlType); bool success = false; // if (controlType.compare("j") == 0) // { // ROS_INFO("arm_interface_node: will attempt to move the arm in joints space."); // success = arm.moveToJoint(0.0, 2.7, 0.2, -2.1, 2.0, 1.0, -0.8, 0.0); // } // else if (controlType.compare("c") == 0) // { // ROS_INFO("arm_interface_node: will attempt to move the arm in cartesian space."); // success = arm.moveToCartesian(0.4, -0.3, 0.26, -0.011, 1.57, 0.037); // } ROS_INFO("arm_interface_node: will attempt to move the arm in cartesian space!"); success = arm.moveToCartesian(0.3, 0.3, 1, 0, 0, 0); // else // ROS_ERROR("arm_interface_node: wrong control type! arm_interface_node only takes j for joints space or c for cartesian space!"); if (success) ROS_INFO("arm_interface_node: succeeded!"); else ROS_INFO("arm_interface_node: failed!"); // double frequency = 5; // ros::Rate rate(frequency); // while ( ros::ok()) // { // ros::spinOnce(); // rate.sleep(); // } ros::waitForShutdown(); return 0; }
TypeScript
UTF-8
3,010
3
3
[]
no_license
import { Eff, Impure, Pure, Chain, EffAny } from './index'; import { IO } from './io'; import { Failure } from './failure'; import { Either } from './either'; import { absurd, Expr } from './types'; export type Async<A = any> = | Observable<A> | ToAsync<A> ; export type AsyncEffect<A> = Eff<Async, A>; export type Canceller = () => void; export type Consumer<A> = (x: A) => void; export type Subscribe<A> = (next: Consumer<A>, completed: () => void) => Canceller; export function runAsync<A>(effect: Eff<Async|IO, A>): Subscribe<A> { return (onNext, onComplete) => { if (effect instanceof Pure) { onNext(effect._value); onComplete(); return noopFunc; } if (effect instanceof Impure) { if (effect._value instanceof Observable) { return effect._value._subscribe(onNext, onComplete); } if (effect._value instanceof ToAsync) { return runAsync(new Impure(effect._value.toAsync()))(onNext, onComplete); } if (effect._value instanceof IO) { onNext(effect._value._io()); onComplete(); return noopFunc; } return absurd(effect._value); } if (effect instanceof Chain) { const cancellers = new Map<EffAny, Canceller|null>(); const handleEffect = (e: EffAny) => { cancellers.set(e, null); const _onNext = result => { if (e === effect._first) handleEffect(effect._andThen(result)); else onNext(result); }; const _onComplete = () => { cancellers.delete(e); if (cancellers.size === 0) onComplete(); }; const canceller = runAsync(e)(_onNext, _onComplete); if (cancellers.has(e)) cancellers.set(e, canceller); }; handleEffect(effect._first); if (cancellers.size === 0) return noopFunc; return () => cancellers.forEach(canceller => canceller && canceller()); } return absurd(effect); }; } function create<A>(subscribe: Subscribe<A>): Eff<Observable, A> { return new Impure(new Observable(subscribe)); } function createE<L, R>(subscribe: Subscribe<Either<L, R>>): Eff<Failure<L>|Observable, R> { return create(subscribe).handleError(); } export namespace Subscribe { export function of<A extends Expr>(value: A): Subscribe<A> { return (next, complete) => (next(value), complete(), noopFunc); } export function lazy<F extends (...args) => any>(func: F, ...args: Parameters<F>): Subscribe<ReturnType<F>> { return (next, complete) => (next(func.apply(void 0, args)), complete(), noopFunc); } } export class Observable<A = any> { readonly _A: A; constructor( readonly _subscribe: Subscribe<A>, ) {} } export abstract class ToAsync<A> { readonly _A: A; abstract toAsync(): Async<A>; } export interface Statics { createE: typeof createE; create: typeof create; } export const Async = { create, createE } as Statics; function noopFunc() {}
Ruby
UTF-8
733
4.34375
4
[]
no_license
#Assigns text to X x = "There are #{10} types of people." #Assigns var 'binary' to binary binary = "binary" #Assigns var 'don't' to do_not do_not = "don't" #Assigns text to y and uses interpolators to take vars y = "Those who know #{binary} and those who #{do_not}." #puts x then y in separate lines puts x puts y #Puts text and interpolates x and y into it puts "I said: #{x}." puts "I also said: '#{y}'." #the joke was awful. This confirms it hilarious = false joke_evaluation = "Isn't that joke so funny?! #{hilarious}" #puts joke_evaluation var puts joke_evaluation #Assigns strings to vars w and e w = "This is the left side of..." e = "a string with a right side." #puts the output of w and e added together. puts w + e
Rust
UTF-8
1,313
2.859375
3
[]
no_license
use crate::*; pub struct PackedMessage<A> { inner: Box<MessageProxy<Actor = A> + Send>, } pub struct PackedMessageProxy<A, M> where M: Message { msg: Option<M>, act: std::marker::PhantomData<A>, } pub trait MessageProxy { type Actor: Actor; fn handle(&mut self, act: &mut Self::Actor, ctx: &mut Context<Self::Actor>); } pub trait ToPackedMessage<A, M> { fn pack(msg: M) -> PackedMessage<A>; } impl<A, M> ToPackedMessage<A, M> for Addr<A> where M: Message + Send + 'static, A: Actor + Handler<M> { fn pack(msg: M) -> PackedMessage<A> { PackedMessage { inner: Box::new(PackedMessageProxy{ msg: Some(msg), act: std::marker::PhantomData, }), } } } impl<A, M> MessageProxy for PackedMessageProxy<A, M> where M: Message + Send + 'static, A: Actor + Handler<M>, { type Actor = A; fn handle(&mut self, act: &mut Self::Actor, ctx: &mut Context<Self::Actor>) { if let Some(msg) = self.msg.take() { act.receive(msg, ctx); } } } impl<A> MessageProxy for PackedMessage<A> where A: Actor, { type Actor = A; fn handle(&mut self, act: &mut Self::Actor, ctx: &mut Context<Self::Actor>) { self.inner.handle(act, ctx) } }
C++
UTF-8
1,818
2.515625
3
[]
no_license
/************************************************************************* > File Name: B.cc > Author: sqwlly > Mail: sqw.lucky@gmail.com > Created Time: 2019年08月19日 星期一 21时04分03秒 ************************************************************************/ #include<bits/stdc++.h> using namespace std; #ifndef ONLINE_JUDGE #define dbg(args...) \ do{ \ cout << "\033[32;1m" << #args << " -> "; \ err(args); \ } while(0) #else #define dbg(...) #endif void err() { cout << "\033[39;0m" << endl; } template <template <typename...> class T, typename t, typename... Args> void err(T<t> a, Args... args) { for (auto x : a) cout << x << ' '; err(args...); } template <typename T, typename... Args> void err(T a, Args... args) { cout << a << ' '; err(args...); } /****************************************************************************************************/ typedef long long LL; string a("COFFEE"), b("CHICKEN"); LL size[70]; char solve(int n,LL k) { if(n == 1) { if(k <= 6) return a[k - 1]; else return ' '; }else if(n == 2) { if(k <= 7) return b[k - 1]; else return ' '; } if(k <= size[n - 2]) return solve(n - 2, k); else return solve(n - 1, k - size[n - 2]); } int main() { #ifndef ONLINE_JUDGE freopen("input.in","r",stdin); #endif ios::sync_with_stdio(false); cin.tie(0); int T,n; LL k; size[1] = 6; size[2] = 7; for(int i = 3; i <= 60; ++i) size[i] = size[i - 1] + size[i - 2]; cin >> T; while(T--) { cin >> n >> k; if(n > 60) n = 60; for(LL d = k; d < k + 10; ++d) { if(d <= size[n]) cout << solve(n, d); } cout << endl; } return 0; }
PHP
UTF-8
491
2.625
3
[]
no_license
<?php namespace App\Policies; use App\Models\User; use Illuminate\Auth\Access\HandlesAuthorization; use Symfony\Component\HttpKernel\Exception\HttpException; final class UserPolicy { use HandlesAuthorization; /** * Only "admin" can manage users. * * @param User $user * @return bool */ public function manage(User $user): bool { if ( ! $user->hasRole(User::ROLE_ADMIN)) { return false; } return true; } }
Python
UTF-8
216
3.921875
4
[]
no_license
x=int(input("Enter a number")) sum=0 temp=x while temp>0: num=temp%10 sum+=num**3 temp=temp//10 if x==sum: print(x,"is a Armstrong Number") else: print(x,"is Not a Armstrong number")
TypeScript
UTF-8
782
3.734375
4
[ "MIT", "CC0-1.0" ]
permissive
import toInteger from './toInteger'; import isIterateeCall from './.internal/isIterateeCall'; import toString from './toString'; import baseRepeat from './.internal/baseRepeat'; /** * Repeats the given string `n` times. * * @since 5.7.0 * @category String * @param str The string to repeat. * @param n The number of times to repeat the string. * @returns Returns the repeated string. * @example * * ```js * repeat('*', 3) * // => '***' * * repeat('abc', 2) * // => 'abcabc' * * repeat('abc', 0) * // => '' * ``` */ export function repeat(str: string, n = 1, guard?: any): string { if ((guard ? isIterateeCall(str, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(str), n); } export default repeat;
JavaScript
UTF-8
12,788
2.671875
3
[]
no_license
function MinGestures(conf) { var g = { N: "n", NW: "nw", W: "w", SW: "sw", S: "s", SE: "se", E: "e", NE: "ne" }; // gesture straigh line thresholds var xBackThr = conf && conf.xBackThr ? conf.xBackThr : 3; var yBackThr = conf && conf.yBackThr ? conf.yBackThr : 10; var aspectThr = conf && conf.aspectThr ? conf.aspectThr : 3; var dotThr = conf && conf.dotThr ? conf.dotThr : 5; // Main/Secondary Angular Thresholds var mat = conf && conf.mat ? conf.mat : 10, sat = conf && conf.sat ? conf.sat : 35; // Fit Pearson (SD not tested yet) var fp = conf && conf.fp ? conf.fp : 0.3, fs = conf && conf.fs ? conf.fs : 0.2; function getGestureByAngle(angle) { // convert from radians to degrees angle *=180/Math.PI; // normalize the angle between -180 and 180 angle = (angle + 180)%360 - 180; var code; if (angle >= 90 - mat && angle <= 90 + mat) { code = g.N; } else if (angle >= 135 - sat && angle <= 135 + sat) { code = g.NW; } else if ((angle >= 180 - mat && angle <= 180 + mat) || (angle >= -180 - mat && angle <= -180 + mat)) { code = g.W; } else if (angle >= -135 - sat && angle <= -135 + sat) { code = g.SW; } else if (angle >= -90 - mat && angle <= -90 + mat) { code = g.S; } else if (angle >= -45 - sat && angle <= -45 + sat) { code = g.SE; } else if (angle >= 0 - mat && angle <= 0 + mat) { code = g.E; } else if (angle >= 45 - sat && angle <= 45 + sat) { code = g.NE; } return code; }; this.recognize = function(strokes) { var stroke = []; // mirror y axis so that coordinate system us standard for (var i = 0; i < strokes[0].length; ++i) { stroke.push([strokes[0][i][0], -strokes[0][i][1]]); } var lied = MathLib.fastLieDown(stroke); var bb = MathLib.boundingBox(lied.stroke); var aspectRatio = bb.width/bb.height; if (strokes[0].length <= dotThr || (bb.width < dotThr && bb.height < dotThr)) { return { name: 'dot', score: 1 }; } var pixBwd = MathLib.computePixelsBackwards(lied.stroke); var name; if (pixBwd.x <= xBackThr && pixBwd.y <= yBackThr && aspectRatio >= aspectThr) { // This is a straight line name = getGestureByAngle(lied.fit.angle); return { name: name, score: (1 - 1/aspectRatio + Math.exp(-pixBwd.x) + Math.exp(-pixBwd.y))/3 }; } }; }; var MathLib = { angle: function angle(stroke) { var ini = stroke[0], end = stroke[stroke.length - 1]; var a = Math.atan2(end[1] - ini[1], end[0] - ini[0]); return a * -180/Math.PI; // Positive degrees }, centroid: function(stroke) { if (stroke.length === 0) return undefined; else if (stroke.length === 1) return stroke[0]; else if (stroke.length === 2) return stroke[1]; else { var x = 0.0, y = 0.0; for (var i = 0; i < stroke.length; i++) { x += stroke[i][0]; y += stroke[i][1]; } x /= stroke.length; y /= stroke.length; return [x, y]; } }, indicativeAngle: function(stroke) { if (stroke.length <= 0) return 0; var c = this.centroid(stroke); return Math.atan2(c[1] - stroke[0][1], c[0] - stroke[0][0]); }, fastLieDown: function(stroke) { var newstroke = this.translateToOrigin(stroke, stroke[0]); var angle = this.indicativeAngle(newstroke); newstroke = this.rotate(newstroke, -angle); var fit = { slope: Math.tan(angle), yintercept: 0, angle: angle, xintercept: 0 }; return {stroke: newstroke, fit: fit}; }, verticalFit: function(stroke) { // Split strokes array var i, c, n = stroke.length, xv = [], yv = []; for (i = 0; i < n; ++i) { xv.push(stroke[i][0]); yv.push(stroke[i][1]); } n = xv.length; // Compute means var xavg = this.avg(xv), yavg = this.avg(yv), ssxx = 0, ssyy = 0, ssxy = 0; for (i = 0; i < n; ++i) { ssxx += xv[i] * xv[i]; ssyy += yv[i] * yv[i]; ssxy += xv[i] * yv[i]; } ssxx -= n * (xavg * xavg); ssyy -= n * (yavg * yavg); ssxy -= n * (xavg * yavg); // Correlation coefficient var r = (ssxy * ssxy) / (ssxx * ssyy); // Variance estimator var s = Math.sqrt( (ssyy - (ssxy * ssxy)/ssxx) / (n-2) ); if (ssxx === 0 || ssyy === 0 || r >= 1) { r = 1; s = 0; } return { centroidX: xavg, centroidY: yavg, pearson: r, sd: s }; }, lieDown: function(stroke) { var fit = this.fit(stroke); // rotate line to lie down on the x-axis over x-intercept var newstroke; if (fit.slope != 0) { newstroke = this.rotate(newstroke, -fit.angle, [fit.xintercept, 0]); } else { newstroke = this.rotate(newstroke, -fit.angle); } return {stroke: newstroke, fit: fit}; }, // http://mathworld.wolfram.com/LeastSquaresFittingPerpendicularOffsets.html fit: function(stroke) { var n = stroke.length; // Compute sums and sums of squares var xsum = 0, ysum = 0, ssxx = 0, ssyy = 0, ssxy = 0; // accumulated delta x and y for (var i = 0; i < n; ++i) { xsum += stroke[i][0]; ysum += stroke[i][1]; ssxx += stroke[i][0] * stroke[i][0]; ssyy += stroke[i][1] * stroke[i][1]; ssxy += stroke[i][0] * stroke[i][1]; } //console.log(xsum, ysum, ssxx, ssyy, ssxy); var dx = 0, dy = 0; for (var i = 1; i < n; ++i) { dx += stroke[i][0] - stroke[i-1][0]; dy += stroke[i][1] - stroke[i-1][1]; } //console.log('dx:', dx, 'dy:', dy); var Bn = (ssyy -ysum*ysum/n) - (ssxx - xsum*xsum/n); var Bd = xsum*ysum/n - ssxy; var B = 0.5*Bn/Bd; // y = a + b*x var b = -B + Math.sqrt(B*B + 1); var bm = -B - Math.sqrt(B*B + 1); var a = (ysum - b*xsum)/n; var am = (ysum - bm*xsum)/n; var xintercept = -a/b; var xinterceptm = -am/bm; // if B is infinity then singularity: it is a vertical/hoizontal line if (Math.abs(B) === Infinity) { // horizontal line if (Bn < 0) { b = 0; a = ysum/n; xintercept = Infinity; } // vertical line else { b = Infinity; a = -Infinity; //console.log(xsum, n); xintercept = xsum/n; } } var R = 0, Rm = 0; for (var i = 0; i < n; ++i) { R += Math.abs(stroke[i][1] - (a + b*stroke[i][0])); Rm += Math.abs(stroke[i][1] - (am + bm*stroke[i][0])); } R /= (Math.sqrt(1 + b*b)); Rm /= (Math.sqrt(1 + bm*bm)); var angle = Math.atan(b); var anglem = Math.atan(bm); //console.log('Bn:', Bn, 'Bd:', Bd, 'B:', B, 'b:', b, 'a:', a, 'xi:', xintercept, 'angle:', angle*180/Math.PI, 'R:', R, 'b-:', bm, 'a-:', am, 'xi-:', xinterceptm, 'angle-:', anglem*180/Math.PI, 'R-:', Rm); //console.log(stroke); //console.log('R:',R, 'b:', b, 'a:', a, 'angle:', angle*180/Math.PI); //console.log('R-:', Rm, 'b-:', bm, 'a-:', am, 'xi-:', xinterceptm, 'angle-:', anglem*180/Math.PI); //console.log('dx:', dx, 'dy:', dy); if (Rm < R) { b = bm; a = am; angle = anglem; R = Rm; xintercept = xinterceptm; } // the stroke goes in the inverse direction var dir = Math.atan2(stroke[stroke.length-1][1] - stroke[0][1], stroke[stroke.length-1][0] - stroke[0][0]); //console.log(b, a, xintercept, angle*180/Math.PI, dir*180/Math.PI, Math.abs(dir - angle)*180/Math.PI); if (Math.abs(dir - angle) > Math.PI/2) angle += Math.PI; //if (dx === 0) { // if (angle > 0 && dy < 0) angle -= Math.PI; // else if (angle < 0 && dy > 0) angle += Math.PI; //} if (angle > Math.PI) angle -= 2*Math.PI; return { slope: b, yintercept: a, angle: angle, xintercept: xintercept }; }, perpendicularLSE: function(stroke, fit) { var R = 0, LSE = 0, n = stroke.length; for (var i = 0; i < n; ++i) { var l = Math.abs(stroke[i][1] - (a + b*stroke[i][0])); R += l; LSE += l*l; } R /= (Math.sqrt(1 + b*b)); return { lse: LSE, residuals: R }; }, // translates points translateToOrigin: function(stroke, point) { var newstroke = []; for (var i = 0; i < stroke.length; ++i) { var qx = stroke[i][0] - point[0]; var qy = stroke[i][1] - point[1]; newstroke.push([qx, qy]); } return newstroke; }, rotate: function (stroke, radians, center) { // rotates stroke around centroid var c = (center)?center:[0,0]; var cos = Math.cos(radians); var sin = Math.sin(radians); var newstroke = []; for (var i = 0; i < stroke.length; i++) { var qx = (stroke[i][0] - c[0]) * cos - (stroke[i][1] - c[1]) * sin + c[0]; var qy = (stroke[i][0] - c[0]) * sin + (stroke[i][1] - c[1]) * cos + c[1]; newstroke.push([qx, qy]); } //console.log(radians, c, cos, sin, newstroke); return newstroke; }, boundingBox: function(stroke) { var minX = +Infinity, maxX = -Infinity, minY = +Infinity, maxY = -Infinity; for (var i = 0; i < stroke.length; i++) { minX = Math.min(minX, stroke[i][0]); minY = Math.min(minY, stroke[i][1]); maxX = Math.max(maxX, stroke[i][0]); maxY = Math.max(maxY, stroke[i][1]); } return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; }, computePixelsBackwards: function(stroke) { var n = stroke.length; var xsum = 0, ysum = 0; for(var i=1; i < n; i++) { var dx = stroke[i][0] - stroke[i-1][0]; var dy = stroke[i][1] - stroke[i-1][1]; if (dx < 0) xsum += dx; if (dy < 0) ysum += dy; } return {x: -xsum, y: -ysum}; }, sum: function(arr, startIndex, endIndex) { var ini = startIndex || 0; var end = endIndex || arr.length; var sum = 0; for (var i = ini; i < end; ++i) { sum += arr[i]; } return sum; }, avg: function(arr) { var s = this.sum(arr); return s / arr.length; }, quartile: function(arr, q) { var pos = q * (arr.length + 1); return (arr[Math.floor(pos)-1] + arr[Math.ceil(pos)-1]) / 2; }, median: function(arr) { arr.sort(function(a,b){ return a - b; }); var n = arr.length, half = Math.floor(n/2); if (n % 2) { med = arr[half]; } else { med = (arr[half-1] + arr[half]) / 2; } return med; }, sd: function(arr, mean) { var variance = 0, elem; for (var i = 0; i < arr.length; ++i) { elem = arr[i]; variance += (elem - mean) * (elem - mean); } return Math.sqrt(variance/arr.length); }, }; // Other function not used right now /* function translateToOrigin(stroke) // translates points' centroid { //var c = centroid(stroke); var c = stroke[0]; var newstroke = []; for (var i = 0; i < stroke.length; ++i) { var qx = stroke[i][0] - c[0]; var qy = stroke[i][1] - c[1]; newstroke.push([qx, qy]); } return newstroke; } function scaleToModuleOne(stroke) // uniform scale for lines; assumes 2D gestures { var b = boundingBox(stroke); var len = Math.sqrt((b.width * b.width) + (b.height * b.height)); var xnorm = 1/len; var ynorm = 1/len; //console.log('BoundingBox', xnorm, ynorm, B); var newstroke = []; for (var i = 0; i < stroke.length; i++) { var qx = stroke[i][0] * xnorm; var qy = stroke[i][1] * ynorm; newstroke.push([qx, qy]); } return newstroke; } function centroid(stroke) { if (stroke.length === 0) return undefined; else if (stroke.length === 1) return stroke[0]; else if (stroke.length === 2) return stroke[1]; else { var x = 0.0, y = 0.0; for (var i = 0; i < stroke.length; i++) { x += stroke[i][0]; y += stroke[i][1]; } x /= stroke.length; y /= stroke.length; return [x, y]; } } function indicativeAngle(stroke) { if (stroke.length <= 0) return 0; var c = centroid(stroke); return Math.atan2(stroke[0][1] - c[1], stroke[0][0] - c[0]); } function fourier(stroke, p) { var len = stroke.length; var output = []; var sum = 0; for(var k=0; k < len; k++) { var real = 0; var imag = 0; for(var n=0; n < len; n++) { real += stroke[n][p]*Math.cos(-2*Math.PI*k*n/len); imag += stroke[n][p]*Math.sin(-2*Math.PI*k*n/len); } sum += real; output.push([real, imag]) } return sum; } function curvature(stroke) { var len = stroke.length; var sum = 0; var odx = stroke[1][0] - stroke[0][0], ody = stroke[1][1] - stroke[0][1]; for(var k=2; k < len; k++) { var dx = stroke[k][0] - stroke[k-1][0]; var dy = stroke[k][1] - stroke[k-1][1]; var a = (dx * ody - odx * dy), b = (dx * odx + dy * ody) sum += Math.abs(Math.atan2(a, b)); odx = dx; ody = dy; } return Math.abs(sum); } */
Python
UTF-8
4,295
2.828125
3
[ "MIT" ]
permissive
import unittest import warnings from corpus2graph import FileParser, WordPreprocessor, Tokenizer, WordProcessing, \ SentenceProcessing, WordPairsProcessing, util import configparser config = configparser.ConfigParser() config.read('config.ini') class TestProcessors(unittest.TestCase): """ ATTENTION Normally, data_folder and output_folder should be user defined paths (absolute paths). For unittest, as input and output folders locations are fixed, these two paths are exceptionally relative paths. """ data_folder = 'unittest_data/' output_folder = 'output/' # TODO create edges, dicts, graph folder based on output_folder, no need to define them below. dicts_folder = output_folder + 'dicts_and_encoded_texts/' edges_folder = output_folder + 'edges/' graph_folder = output_folder + 'graph/' file_extension = '.txt' max_window_size = 6 process_num = 3 data_type = 'txt' min_count = 5 max_vocab_size = 3 # APIs def test_word_preprocessor(self): wp = WordPreprocessor() result1 = wp.apply('18') self.assertEqual(result1, '') result2 = wp.apply(',') self.assertEqual(result2, '') result3 = wp.apply('Hello') self.assertEqual(result3, 'hello') def toto(word): return '' wp = WordPreprocessor(remove_numbers = False, remove_punctuations = False, stem_word = False, lowercase = False, wpreprocessor = toto) result4 = wp.apply('Hello') self.assertEqual(result4, '') with warnings.catch_warnings(record=True) as w: wp = WordPreprocessor(remove_numbers=False, remove_punctuations=False, stem_word=False, lowercase=False, wpreprocessor='toto') result5 = wp.apply('Hello') assert "wpreprocessor" in str(w[-1].message) def titi(word): return None wp = WordPreprocessor(remove_numbers=False, remove_punctuations=False, stem_word=False, lowercase=False, wpreprocessor=titi) self.assertRaises(ValueError, wp, 'hello') def test_file_parser(self): tfp = FileParser() filepath = 'unittest_data/AA/wiki_03.txt' lines = list(tfp(filepath)) reflines = ['alfred hitchcock', 'sir alfred joseph hitchcock ( 00 august 0000 – 00 april 0000 ) was ' 'an english film director and producer , at times referred to as " the master of suspense " .he pioneered many elements of the suspense and psychological thriller genres .'] # TODO test by assertEqual, ('\n' is added to the end of the sentence) # TODO test xml and txt parser # TODO NOW user defined parser function #self.assertEqual(lines, reflines) # TODO problem in test code, no problem in source code # tfp = FileParser('txxt') # self.assertRaises(ValueError, tfp, filepath) #self.assertRaises(ValueError, FileParser(file_parser='defined', # xml_node_path=None, fparser=None), filepath) def txt_parser(file_path): with open(file_path, 'r', encoding='utf-8') as file: for line in file: yield line tfp = FileParser(file_parser='defined', xml_node_path=None, fparser=txt_parser) filepath = 'unittest_data/AA/wiki_03.txt' lines = list(tfp(filepath)) #print(lines) def test_tokenizer(self): # TODO test PunktWord tknizer = Tokenizer(word_tokenizer='WordPunct') result = tknizer.apply("this's a test") self.assertEqual(result, ['this', "'", "s", 'a', 'test']) def mytok(s): return list(s) tknizer = Tokenizer(word_tokenizer='', wtokenizer=mytok) self.assertEqual(tknizer('h l'), ['h', ' ', 'l']) # tknizer = Tokenizer(word_tokenizer='tree') # tknizer = Tokenizer(word_tokenizer='', wtokenizer='tt') self.assertRaises(ValueError, Tokenizer, 'tree') with warnings.catch_warnings(record=True) as w: tknizer = Tokenizer(word_tokenizer='', wtokenizer='tt') assert "wtokenizer" in str(w[-1].message) if __name__ == '__main__': unittest.main()
C#
UTF-8
2,290
3.046875
3
[]
no_license
using Alice.Models.Conditions; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Alice.Models.Facts { public class Fact { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("values")] public string[] Values { get; set; } [JsonProperty("condition")] public ICondition Condition { get; set; } public Fact() { } public Fact(string name, ICondition condition, params string[] values) { Name = name; Condition = condition; Values = values; } public Fact(string name, params string[] values) { Name = name; Values = values; } public bool Evaluate(params string[] values) { bool evaluation = true; if (Condition != null) { evaluation = Condition.Evaluate(); } return evaluation; } public bool HasValues(params string[] values) { if (Values.Length == values.Length) { return Values.SequenceEqual(values); } return false; } public bool CheckGivenValues(params string[] values) { if(Values.Length >= values.Length) { for(int i = 0; i < values.Length; i++) { if(values[i] != null && Values[i] != values[i]) { return false; } } return true; } return false; } public string[] GetSpecificValues(params string[] values) { if(values.Length <= Values.Length) { List<string> strings = new List<string>(); for(int i= 0; i< values.Length; i++) { if(values[i] == null) { strings.Add(Values[i]); } } return strings.ToArray(); } return new string[0]; } } }
Shell
UTF-8
1,314
3.953125
4
[]
no_license
#!/bin/sh # Variables for the build export PREFIX="$HOME/opt/cross" export TARGET=i686-elf export PATH="$PREFIX/bin:$PATH" # Variables for the script BINUTILS_URL=https://ftp.gnu.org/gnu/binutils/binutils-2.31.tar.xz GCC_URL=https://ftp.gnu.org/gnu/gcc/gcc-8.2.0/gcc-8.2.0.tar.xz TMP_DIR=~/cross_tmp # Can be c,c++ LANGS=c CURRPWD=$PWD if [ -d "$TMP_DIR" ]; then echo "::: '$TMP_DIR' already exists! Remove that before running this script." #exit 1 fi mkdir $TMP_DIR cd $TMP_DIR echo "::: Downloading binutils from $BINUTILS_URL..." wget $BINUTILS_URL -O binutils.tar.xz echo "::: Downloading GCC from $GCC_URL" wget $GCC_URL -O gcc.tar.xz echo "::: Extracting archives (this might take a while!)..." echo " :::: 1/2 binutils" tar -xf binutils.tar.xz echo " :::: 2/2 gcc" tar -xf gcc.tar.xz echo "::: Starting binutils build..." mkdir binutils-build cd binutils-build ../binutils-2.31/configure --target=$TARGET --prefix="$PREFIX" --with-sysroot --disable-nls --disable-werror make make install cd .. echo "::: Starting GCC build..." mkdir gcc-build cd gcc-build ../gcc-8.2.0/configure --target=$TARGET --prefix="$PREFIX" --disable-nls --enable-languages=$LANGS --without-headers make all-gcc make all-target-libgcc make install-gcc make install-target-libgcc echo "::: Done!" cd $CURRPWD
Python
UTF-8
1,541
2.59375
3
[]
no_license
import torch import numpy as np from torch.autograd import Variable def Val_Training_process(model, epoches, criterion, optimizer, lr_scheduler, train_loader, val_loader, cuda=False): print('Starting to train the U_Net Model...') loss_set = [] for epoch in range(epoches): train_loss = [] for i, data in enumerate(train_loader): inputs, labels = data if cuda: inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda()) else: inputs, labels = Variable(inputs), Variable(labels) optimizer.zero_grad() pred = model(inputs) loss = criterion(pred, labels) loss.backward() optimizer.step() train_loss.append(loss.item()) lr_scheduler.step(int(np.mean(train_loss) * 1000)) loss_set.append(np.mean(train_loss)) print('training the No.{} epoch, loss: {:.4f}'.format(epoch+1, np.mean(train_loss))) model.eval() val_loss = [] for i, data in enumerate(val_loader): val_inputs, val_labels = data if cuda: val_inputs, val_labels = Variable(val_inputs.cuda()), Variable(val_labels.cuda()) else: val_inputs, val_labels = Variable(val_inputs), Variable(val_labels) pred = model(val_inputs) loss = criterion(pred, val_labels) val_loss.append(loss.item()) return loss_set, np.mean(val_loss)
Python
UTF-8
2,830
2.921875
3
[ "MIT" ]
permissive
#!/usr/bin/python # coding: utf-8 # Max Basescu # mbasesc1@jhu.edu import socket import time import os import RPi.GPIO as GPIO import Adafruit_CharLCD as LCD motorPin = 17 os.chdir('/home/pi/DomeTrainingRig/') while True: # Initialize motor pin GPIO.setup(motorPin, GPIO.OUT) # Initialize the LCD using the pins lcd = LCD.Adafruit_CharLCDPlate() lcd.show_cursor(False) # Set backlight color to blue lcd.set_color(0.0, 0.0, 1.0) lcd.clear() # Get ip s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 0)) ipAdd = s.getsockname()[0] welcomeMsg = 'Welcome!\nDOWN for help' lcd.message(welcomeMsg) # Wait for select to be pressed while not lcd.is_pressed(LCD.SELECT): # If left is pressed if lcd.is_pressed(LCD.LEFT): ipMsg = 'IP:\n{}'.format(ipAdd) lcd.clear() lcd.set_color(1.0, 1.0, 0.0) lcd.message(ipMsg) while not (lcd.is_pressed(LCD.UP) or lcd.is_pressed(LCD.DOWN) or lcd.is_pressed(LCD.LEFT) or lcd.is_pressed(LCD.RIGHT) or lcd.is_pressed(LCD.SELECT)): pass; lcd.clear() lcd.set_color(0.0, 0.0, 1.0) lcd.message(welcomeMsg) # If down is pressed elif lcd.is_pressed(LCD.DOWN): helpMsg = ' UP:Prime RT:Off\nSEL:Start LT:IP' lcd.clear() lcd.set_color(0.0, 1.0, 0.0) lcd.message(helpMsg) while not (lcd.is_pressed(LCD.UP) or lcd.is_pressed(LCD.DOWN) or lcd.is_pressed(LCD.LEFT) or lcd.is_pressed(LCD.RIGHT) or lcd.is_pressed(LCD.SELECT)): pass; lcd.clear() lcd.set_color(0.0, 0.0, 1.0) lcd.message(welcomeMsg) # If up is pressed elif lcd.is_pressed(LCD.UP): while lcd.is_pressed(LCD.UP): time.sleep(0.1) # Prime the lines until up is pressed again GPIO.output(motorPin, True) lcd.clear() lcd.set_color(0.0, 1.0, 1.0) lcd.message('Priming motor...\n') while not lcd.is_pressed(LCD.UP): time.sleep(0.05) while lcd.is_pressed(LCD.UP): time.sleep(0.1) # Turn off motor GPIO.output(motorPin, False) lcd.clear() lcd.set_color(0.0, 0.0, 1.0) lcd.message(welcomeMsg) # Shutdown if right is pressed elif lcd.is_pressed(LCD.RIGHT): while lcd.is_pressed(LCD.RIGHT): time.sleep(0.1) # Prompt for confirmation of shutdown lcd.clear() lcd.set_color(1.0, 0.0, 0.0) lcd.message('Are you sure?\nUP=yes, DOWN=no') while not lcd.is_pressed(LCD.UP) and not lcd.is_pressed(LCD.DOWN): pass # Up means yes if lcd.is_pressed(LCD.UP): lcd.clear() lcd.message('Shutting down...\n') os.system('shutdown -h now') # Down means cancel else: while lcd.is_pressed(LCD.DOWN): time.sleep(0.1) lcd.clear() lcd.set_color(0.0, 0.0, 1.0) lcd.message(welcomeMsg) # Wait for select to be released while lcd.is_pressed(LCD.SELECT): time.sleep(0.1) # Runs main program os.system('./TrainingProg')
C
UTF-8
2,057
2.96875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sanhan <sanhan@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/29 21:29:58 by sanhan #+# #+# */ /* Updated: 2020/03/02 00:04:58 by sanhan ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int cal_size(char *s, char c) { int i; int rtn; int s_len; i = 0; rtn = 0; s_len = ft_strlen(s); while (i < s_len) { while (s[i] && s[i] == c) i++; if (s[i] && s[i] != c) rtn++; while (s[i] && s[i] != c) i++; } return (rtn); } static int cal_len(char *s, char c) { int i; i = 0; while (s[i] != c && s[i]) i++; return (i); } static void all_free(char **rtn, int until) { int i; i = 0; while (i < until) { free(rtn[i]); i++; } free(rtn); } static void allocation(char *s, char c, char **rtn, int size) { int i; int j; int k; i = 0; j = 0; while (i < size) { while (s[j] && s[j] == c) j++; if (s[j] && s[j] != c) { rtn[i] = (char *)malloc(sizeof(char) * (cal_len(&s[j], c) + 1)); if (rtn[i] == 0) { all_free(rtn, i); return ; } } k = 0; while (s[j] && s[j] != c) rtn[i][k++] = s[j++]; rtn[i++][k] = '\0'; } rtn[i] = 0; } char **ft_split(char const *s, char c) { int size; char **rtn; size = cal_size((char *)s, c); rtn = (char **)malloc(sizeof(char *) * (size + 1)); if (rtn == 0) return (0); allocation((char *)s, c, rtn, size); return (rtn); }
C++
UTF-8
4,911
3.75
4
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; const char X = 'X'; const char O = 'O'; const char empty = ' '; const char tie = 'T'; const char notOver = 'N'; void displayInstructions(); char askYesNo(string question); int askNumber( string question, int high, int low = 0); char userSymbol(); char opponentTurn(char symbol); void display(const vector<char>& board); char winner(const vector<char>& board); bool legalMove(const vector<char>& board, int move); int userMove(const vector<char>& board, char user); int compMove(const vector<char> board, char comp); void displayWinner(char winner, char comp, char user); int main() { int move; const int sizeBoard = 9; vector<char> board(sizeBoard, empty); displayInstructions(); char user = userSymbol(); char comp = compSymbol(); char turn = X; display(board); while(winner(board) == notOver); { if (turn == user) { move = userMove(board, user); board[move] = user; } else { move = compMove(board, comp); board[move] = comp; } display(board); turn = opponentTurn(turn); } displayWinner(winner(board), comp, user); return 0; } void displayInstructions() { cout << "\t\t Tic Tac Toe \n"; cout << "input moves by typing 0-8 each turn\n"; cout << "Board example: \n\n"; cout << " 0 | 1 | 2 \n"; cout << " 3 | 4 | 5 \n"; cout << " 6 | 7 | 8 \n\n"; cout << "The game begins now!\n\n"; } char askYesNo(string question); { char answer; do { cout<< question << " (Y/N)? "; cin >> answer; } while (answer != 'Y' && answer != 'N'); return answer; } int askNumber( string question, int high, int low = 0); { int num; do { cout<< question << "(" << low << "-" << high << ")?"; cin >> num; } while (num > high || num < low); return num; } char userSymbol(); { char firstQuestion = askYesNo("Do you want to go first?"); if (firstQuestion == 'Y'); return X; else return O; } char opponentTurn(char symbol); { if (symbol == 'X') return O; else return X; } void display(const vector<char>& board); { cout << " board[0] | board[1] | board[2] \n"; cout << " board[3] | board[4] | board[5] \n"; cout << " board[6] | board[7] | board[8] \n\n"; } char winner(const vector<char>& board); { const int waysToWin[8][3] = {{0,1,2},{0,4,8},{0,3,6},{1,4,7},{2,5,8},{2,4,6},{3,4,5},{6,7,8}}; const int rows = 8; //CHECK FOR WINNER for( int i = 0; i <rows; i++) { if( (board[waysToWin[i][0]] != empty) && (board[waysToWin[i][0]] == board[waysToWin[i][1]]) && (board[waysToWin[i][1]] == board[waysToWin[i][2]]) ) return board[waysToWin[i][0]]; } //CHECK FOR TIE if(count(board.begin(), board.end(), empty) == 0) return tie; else return notOver; } inline bool legalMove(const vector<char>& board, int move); { return (board[move] == empty); } int userMove(const vector<char>& board, char user); { int move = askNumber("What is your move?", (board.size()-1)); while(!legalMove(board,move)) { cout << "Not an option, box is taken! \n"; move = askNumber("Try again, what is your move?", (board.size()-1)); } return move; } int compMove(const vector<char> board, char comp); { unsigned int move = 0; bool found = false; /////////////////////////////////////////// //SEE IF COMPUTER COULD WIN while(!found && move < board.size()) { if (legalMove(board, move)) { board[move] = comp; found = winner(board)==computer; board[move] = empty; } ++move; } /////////////////////////////////////////// //SEE IF HUMAN COULD WIN & BLOCK THEM if(!found) { move = 0; char human = opponentTurn(comp); while(!found && move < board.size()) { if (legalMove(board, move)) { board[move] = human; found = winner(board)==human; board[move] = empty; } ++move; } } /////////////////////////////////////////// //PICK THE BEST COMPUTER MOVE if(!found) { move = 0; int i = 0; const int bestMovesOrder[9] = { 4, 0, 2. 6, 8, 1, 3, 5, 7}; while(!found && i < board.size()) { move = bestMovesOrder[i]; if (legalMove(board, move)) found = true; ++i; } } /////////////////////////////////////////// cout << "Computer has chosen square: " << move << endl; return move; } void displayWinner(char winner, char comp, char user); { if(winner == computer) cout << winner << " win the game!\n Please play again\n\n"; else if(winner == user) cout << winner << " win the game!\n Please play again\n\n"; else cout << "It's a tie! No one wins!\n Please play again\n\n"; }
Python
UTF-8
2,092
4.125
4
[]
no_license
""" 输入M和N计算C(M,N) """ # m = int(input('m= ')) # n = int(input('n= ')) # fm = 1 # for num in range(1, m+1): # fm *= num # fn = 1 # for num in range(1, n+1): # fn *= num # fmn = 1 # for num in range(1, m-n+1): # fmn *= num # print(fm // fn // fmn) """ 重构代码 """ # def factorial(num): # result = 1 # for n in range(1, num + 1): # result *= n # return result # m = int(input('m= ')) # n = int(input('n= ')) # print(factorial(m) // factorial(n) // factorial(m-n)) """ 函数的参数 """ # from random import randint # def roll_dice(n=2): # """摇色子""" # total = 0 # for _ in range(n): # total += randint(1, 6) # return total # def add(a=0, b=0, c=0): # return a+b+c # print(roll_dice()) # print(roll_dice(2)) # print(roll_dice(3)) # print(add()) # print(add(1)) # print(add(1,2)) # print(add(1,2,3)) # print(add(c=3, b=2, a=1)) # def add(*args): # total = 0 # for num in args: # total += num # return total # print(add()) # print(add(1)) # print(add(1,2)) # print(add(1,2,3)) """ 练习1:实现计算求最大公约数和最小公倍数的函数。 """ # def gcd(a, b): # (a, b) = (b, a) if a > b else (a, b) # for num in range(a, 0, -1): # if a % num == 0 and b % num == 0: # return num # def lcm(a, b): # return a * b // gcd(a, b) # print(gcd(4,6)) # print(lcm(4,6)) """ 练习2:实现判断一个数是不是回文数的函数 """ def is_palindrome(num): temp = num total = 0 while temp > 0: total = total * 10 + temp % 10 temp //= 10 return total == num """ 练习3:实现判断一个数是不是素数的函数 """ def is_prime(num): for factor in range(2,num): if num % factor == 0: return False return True if num != 1 else False """ 练习4:写一个程序判断输入的正整数是不是回文素数。 """ if __name__ == '__main__': num = int(input('请输入正整数:')) if is_palindrome(num) and is_prime(num): print('%d是回文素数' % num)
Java
UTF-8
702
3.34375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package guvi10; import java.util.Scanner; /** * * @author Student */ public class Guvi10 { public static int dot(int upper,int lower){ int sum=0; int temp=0; for(int i=1;i<upper;i++) temp+=i; for(int j=1;j<lower;j++) sum+=temp*j; return sum; } public static void main(String[] args) { Scanner scr=new Scanner(System.in); System.out.println("Enter number of dots at upper row"); int upper=scr.nextInt(); System.out.println("Enter the number of dots at lower row"); int lower=scr.nextInt(); System.out.println(dot(upper,lower)); } }
Python
UTF-8
579
2.96875
3
[]
no_license
#!/usr/bin/env python n = input() for i in range(1, n+1): num_engines = input() engines = set() for j in range(num_engines): engines.add(raw_input()) num_queries = input() queries = [] for j in range(num_queries): query = raw_input() queries.insert(0, query) print "Case #%d:" % (i), conj_temp = set() cont = 0 while queries != []: while engines != conj_temp: if queries == []: break query = queries.pop() conj_temp.add(query) if engines != conj_temp: break cont += 1 conj_temp = set() conj_temp.add(query) print cont
Python
UTF-8
514
3.265625
3
[]
no_license
import sys inp = sys.stdin t = int(inp.readline()) list = [] for x in range(t): l = inp.readline().strip() list.append(l) song = ['Happy', 'birthday', 'to', 'you', 'Happy', 'birthday', 'to', 'you', 'Happy', 'birthday', 'to', 'Rujia', 'Happy', 'birthday', 'to', 'you' ] temp = 0 flag = True while(flag): for y in range(16): print('{}: {}'.format(list[temp], song[y])) temp = temp + 1 if temp == len(list): temp = 0 flag = False
PHP
UTF-8
264
3.65625
4
[]
no_license
<?php $a = 1; if(is_numeric($a)){ echo "It's a number"; } else{ echo "It's not a number"; } $a = 3.3; if(is_int($a)){ echo "It's a int"; } else{ echo "It's not a int"; } $a = 3/4; if(is_float($a)){ echo "It's a float"; } else{ echo "It's not a float"; } ?>
TypeScript
UTF-8
3,034
2.515625
3
[ "MIT", "LGPL-2.0-or-later" ]
permissive
import chai from 'chai'; import sinonChai from 'sinon-chai'; import sinon from 'sinon'; import sleep from 'await-sleep'; import { BulkUsbSingleton } from './../src/bulkusbdevice'; const expect = chai.expect; chai.should(); chai.use(sinonChai); const dummyCpp = { openDevice: sinon.stub(), listDevice: sinon.stub(), listDevices: sinon.stub(), }; describe('BulkUsbDeviceSingleton', () => { let bulkusbSingleton; beforeEach(() => { bulkusbSingleton = new BulkUsbSingleton(dummyCpp); }); describe('#listDevice', () => { beforeEach(() => { dummyCpp.listDevices.yields([ { vid: 0x21, pid: 0x21, serial: 'serial-3', cookie: 3, }, { vid: 0x21, pid: 0x21, serial: 'serial-2', cookie: 2, }, { vid: 0x21, pid: 0x21, serial: 'serial-1', cookie: 1, } ]); }); it('should return a list of all available Huddly devices', async () => { const devices = await bulkusbSingleton.listDevices(); expect(devices).to.have.length(3); expect(devices[0].serialNumber).to.be.equal('serial-3'); expect(devices[1].serialNumber).to.be.equal('serial-2'); expect(devices[2].serialNumber).to.be.equal('serial-1'); }); }); describe('#onAttach', () => { beforeEach(async () => { dummyCpp.listDevices.yields([ { vid: 0x21, pid: 0x21, serial: 'serial-4', cookie: 4, }, ]); }); it('should emit attach for all new devices', async () => { const attachSpy = sinon.spy(); bulkusbSingleton.onAttach(attachSpy); await sleep(502); expect(attachSpy).to.have.been.calledOnce; }); it('should not emit attach event if device is already seen', async () => { const attachSpy = sinon.spy(); bulkusbSingleton.onAttach(attachSpy); // Two list loops await sleep(251); await sleep(251); expect(attachSpy).to.have.callCount(1); }); }); describe('device #onDetach', () => { beforeEach(() => { dummyCpp.listDevices.yields([ { vid: 0x21, pid: 0x21, serial: 'serial-4', cookie: 4, }, ]); }); it('should emit onDetach callback if device is no longer in list', async () => { const detachSpy = sinon.spy(); bulkusbSingleton.onAttach(d => { d.onDetach(detachSpy); }); // Two list loops await sleep(251); dummyCpp.listDevices.yields([ ]); await sleep(251); expect(detachSpy).to.have.been.calledOnce; }); it('should not emit onDetach cb if device is still in the list', async () => { const detachSpy = sinon.spy(); bulkusbSingleton.onAttach(d => { d.onDetach(detachSpy); }); // Two list loops await sleep(251); await sleep(251); expect(detachSpy).to.have.callCount(0); }); }); });
Python
UTF-8
1,324
2.71875
3
[ "MIT" ]
permissive
import json import logging import os from Xlib import XK class XLeaprConfig(object): def __init__(self, display, path=os.path.join(os.path.dirname(os.path.realpath(__file__)), "default.json")): self.config = {} # Load and parse JSON config with open(path) as data_file: raw_config = json.load(data_file) # Iterate through the items in the object for dkey, value in raw_config.iteritems(): # If a value is not a list type, ignore it if type(value) is not list: logging.error("Key configurations must be listed in arrays.") continue # Convert all of the key strings into their proper codes self.config[dkey] = [] for key in value: code = XK.string_to_keysym(key) # If the returned code is 0, then it could not be found by XK if code is 0: self.config[dkey] = None logging.warning("Key ("+code+") was not recognized by XK") break else: self.config[dkey].append(display.keysym_to_keycode(code)) # Return the keycode for the specified gesture def __getitem__(self, gesture): return self.config.get(gesture, [])
Java
UTF-8
4,851
2.4375
2
[]
no_license
package com.ANP.bean; import org.springframework.lang.Nullable; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.math.BigDecimal; public class EmployeeBean extends CommonAttribute { private String employeeId; @NotBlank(message = "first name is mandatory") @NotNull(message = "first name is mandatory") private String first; private String last; @Pattern(regexp = "\\s*|.{10}", message = "mobile no. should be of 10 digits") private String mobile; private String mobile2; private String type; private int typeInt; private BigDecimal currentsalarybalance; private BigDecimal lastsalarybalance; private BigDecimal initialSalaryBalance; private BigDecimal currentAccountBalance; private BigDecimal initialBalance; private boolean loginrequired; private long accountId; public int getTypeInt() { return typeInt; } public void setTypeInt(int typeInt) { this.typeInt = typeInt; } public long getAccountId() { return accountId; } public void setAccountId(long accountId) { this.accountId = accountId; } public enum EmployeeTypeEnum { SUPER_ADMIN(1), BusinessPartner(2), SalesPerson(3), Labour(4), Accountant(5), VIRTUAL(6), Default(7); private final int value; private EmployeeTypeEnum(int value) { this.value = value; } public int getValue() { return value; } } /* This method will be used for displaying in the UI */ public String getDisplayName() { return this.first + " " + this.last; } public void setCurrentsalarybalance(BigDecimal currentsalarybalance) { this.currentsalarybalance = currentsalarybalance; } public void setLastsalarybalance(BigDecimal lastsalarybalance) { this.lastsalarybalance = lastsalarybalance; } public BigDecimal getInitialSalaryBalance() { return initialSalaryBalance; } public void setInitialSalaryBalance(BigDecimal initialSalaryBalance) { this.initialSalaryBalance = initialSalaryBalance; } public BigDecimal getCurrentAccountBalance() { return currentAccountBalance; } public void setCurrentAccountBalance(BigDecimal currentAccountBalance) { this.currentAccountBalance = currentAccountBalance; } public void setInitialBalance(BigDecimal initialBalance) { this.initialBalance = initialBalance; } public boolean isLoginrequired() { return loginrequired; } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getFirst(){ return first; } public void setFirst(String first){ this.first=first; } public String getLast(){ return last; } public void setLast(String last){ this.last=last; } public String getMobile(){ return mobile; } public void setMobile(String mobile){ this.mobile=mobile; } public String getType(){ return type; } public void setType(String type){ this.type=type; } public BigDecimal getCurrentsalarybalance() { return currentsalarybalance; } public BigDecimal getLastsalarybalance() { return lastsalarybalance; } public BigDecimal getInitialBalance() { return initialBalance; } public boolean getLoginrequired(){ return loginrequired; } public void setLoginrequired(boolean loginrequired){ this.loginrequired = loginrequired; } public String getMobile2() { return mobile2; } public void setMobile2(String mobile2) { this.mobile2 = mobile2; } @Override public String toString() { return "EmployeeBean{" + "employeeId='" + employeeId + '\'' + ", first='" + first + '\'' + ", last='" + last + '\'' + ", mobile='" + mobile + '\'' + ", mobile2='" + mobile2 + '\'' + ", type='" + type + '\'' + ", typeInt=" + typeInt + ", currentsalarybalance=" + currentsalarybalance + ", lastsalarybalance=" + lastsalarybalance + ", initialSalaryBalance=" + initialSalaryBalance + ", currentAccountBalance=" + currentAccountBalance + ", initialBalance=" + initialBalance + ", loginrequired=" + loginrequired + ", accountId=" + accountId + '}'; } }
Java
UTF-8
1,253
3.046875
3
[ "MIT" ]
permissive
package com.example.oauth.service.util; import org.springframework.stereotype.Service; import java.util.regex.Matcher; import java.util.regex.Pattern; @Service public class PasswordValidator { private Pattern pattern = null; /** * No one can make a direct instance */ public PasswordValidator() { pattern = getPattern(true, true, true, 8, 16); } /** * Force the user to build a validator using this way only */ public static Pattern getPattern(boolean forceSpecialChar, boolean forceCapitalLetter, boolean forceNumber, int minLength, int maxLength) { StringBuilder patternBuilder = new StringBuilder("((?=.*[a-z])"); if (forceSpecialChar) { patternBuilder.append("(?=.*[@#$%^&+=!])"); } if (forceCapitalLetter) { patternBuilder.append("(?=.*[A-Z])"); } if (forceNumber) { patternBuilder.append("(?=.*\\d)"); } patternBuilder.append(".{" + minLength + "," + maxLength + "})"); return Pattern.compile(patternBuilder.toString()); } /** * Check if the provided password is valid * * @param password a string value * @return true / false */ public boolean isValid(String password) { Matcher m = pattern.matcher(password); return m.matches(); } }
C++
UTF-8
852
3.9375
4
[]
no_license
// exercise 9 // TODO exercise 9: write out an error if the result cannot be // represented as an int #include "../../std_lib_facilities.h" int main() { int i, n, sum = 0; vector<int> numbers; cout << "Please enter the number of values you want to sum: "; cin >> n; while (n <= 1) { cout << "Cannot do this sum!\nPlease enter a value greater than 1: "; cin >> n; } cout << "Please enter some integers (press '|' to stop): "; while (cin >> i) { numbers.push_back(i); } if (numbers.size() < n) cout << "You asked for a sum of " << n << " numbers, but provided only " << numbers.size() << '\n'; else { for (int i = 0; i < n; ++i) sum += numbers[i]; cout << "The sum of the first 3 numbers = " << sum << '\n'; } }
Java
UTF-8
2,524
2.234375
2
[]
no_license
package atmosphere.android.activity.helper; import interprism.atmosphere.android.R; import android.app.Activity; import android.view.View; import android.widget.Button; import android.widget.EditText; import atmosphere.android.constant.AtmosConstant; import atmosphere.android.dto.SendMessageRequest; import atmosphere.android.dto.SendPrivateMessageRequest; public class SendMessageHelper { public static void initSubmitButton(final Activity activity) { getSendMessageEditText(activity).setText(AtmosConstant.MESSAGE_CLEAR_TEXT); Button submitButton = getSubmitButton(activity); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SendMessageRequest param = new SendMessageRequest(); String message = getSendMessageEditText(activity).getText().toString(); param.message = message; if (message != null && message.length() != 0) { MessageHelper.sendMessage(activity, param); } } }); } public static void initSubmitPrivateButton(final Activity activity) { getSendPrivateMessageEditText(activity).setText(AtmosConstant.MESSAGE_CLEAR_TEXT); getSendPrivateToUserEditText(activity).setText(AtmosConstant.MESSAGE_CLEAR_TEXT); Button submitPrivateButton = getSubmitPrivateButton(activity); submitPrivateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SendPrivateMessageRequest param = new SendPrivateMessageRequest(); String message = getSendPrivateMessageEditText(activity).getText().toString(); param.message = message; param.to_user_id = getSendPrivateToUserEditText(activity).getText().toString(); if (message != null && message.length() != 0) { MessageHelper.sendPrivateMessage(activity, param); } } }); } protected static EditText getSendMessageEditText(Activity activity) { return (EditText) activity.findViewById(R.id.SendMessageEditText); } protected static Button getSubmitButton(Activity activity) { return (Button) activity.findViewById(R.id.SubmitButton); } protected static EditText getSendPrivateMessageEditText(Activity activity) { return (EditText) activity.findViewById(R.id.SendPrivateMessageEditText); } protected static EditText getSendPrivateToUserEditText(Activity activity) { return (EditText) activity.findViewById(R.id.SendPrivateToUserEditText); } protected static Button getSubmitPrivateButton(Activity activity) { return (Button) activity.findViewById(R.id.SubmitPrivateButton); } }
Java
UTF-8
2,607
2.015625
2
[]
no_license
package com.haidaiban.foxlee.model.comment; /** * Created by qixiaohui on 3/29/15. */ import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @Generated("org.jsonschema2pojo") public class Result { @Expose private User user; @Expose private Integer id; @SerializedName("content_type") @Expose private Integer contentType; @SerializedName("object_pk") @Expose private String objectPk; @Expose private String comment; @SerializedName("submit_date") @Expose private String submitDate; @SerializedName("is_removed") @Expose private Boolean isRemoved; /** * * @return * The user */ public User getUser() { return user; } /** * * @param user * The user */ public void setUser(User user) { this.user = user; } /** * * @return * The id */ public Integer getId() { return id; } /** * * @param id * The id */ public void setId(Integer id) { this.id = id; } /** * * @return * The contentType */ public Integer getContentType() { return contentType; } /** * * @param contentType * The content_type */ public void setContentType(Integer contentType) { this.contentType = contentType; } /** * * @return * The objectPk */ public String getObjectPk() { return objectPk; } /** * * @param objectPk * The object_pk */ public void setObjectPk(String objectPk) { this.objectPk = objectPk; } /** * * @return * The comment */ public String getComment() { return comment; } /** * * @param comment * The comment */ public void setComment(String comment) { this.comment = comment; } /** * * @return * The submitDate */ public String getSubmitDate() { return submitDate; } /** * * @param submitDate * The submit_date */ public void setSubmitDate(String submitDate) { this.submitDate = submitDate; } /** * * @return * The isRemoved */ public Boolean getIsRemoved() { return isRemoved; } /** * * @param isRemoved * The is_removed */ public void setIsRemoved(Boolean isRemoved) { this.isRemoved = isRemoved; } }
Ruby
UTF-8
1,431
3.9375
4
[]
no_license
def merge(left, right) result = [] i, j = 0, 0 n, m = left.size, right.size while i < n && j < m if left[i] < right[j] result.push(left[i]) i += 1 else result.push(right[j]) j += 1 end end while i < n result.push(left[i]) i += 1 end while j < m result.push(right[j]) j += 1 end result end def merge_sort(array) size = array.size return array if size < 2 mid = size/2 merge(merge_sort(array[0...mid]), merge_sort(array[mid..-1])) end def merge_in_place(array, left, mid, right) # for economy memory, merge result will be in array # create temporary array for the first half of array temp = array[left..mid] i, j = 0, mid+1 k = left # pointer in result array while i < temp.size && j <= right if temp[i] < array[j] array[k] = temp[i] i += 1 k += 1 else array[k] = array[j] j += 1 k += 1 end end while i < temp.size array[k] = temp[i] i += 1 k += 1 end while j < right array[k] = array[j] j += 1 k += 1 end array end def sort_in_place(array, left, right) return if left >= right mid = (left + right)/2 sort_in_place(array, left, mid) sort_in_place(array, mid + 1, right) merge_in_place(array, left, mid, right) end def merge_sort_in_place(array) size = array.size return array if size < 2 sort_in_place(array, 0, size-1) end