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
8,240
2.53125
3
[ "MIT" ]
permissive
namespace Instagreat.Tests.Services { using System; using System.Threading.Tasks; using Data; using Data.Models; using Instagreat.Services.Implementation; using Microsoft.EntityFrameworkCore; using Xunit; using AutoMapper; using Web.Infrastructure.Mapping; using System.Collections.Generic; public class UsersServiceTests { private readonly InstagreatDbContext db; public UsersServiceTests() { var options = new DbContextOptionsBuilder<InstagreatDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; this.db = new InstagreatDbContext(options); } //AllUsersAsync Tests [Fact] public async Task AllUsersAsyncShouldReturnAllUsersIfAllDataIsValid() { var mockMapper = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperProfile()); }); var mapper = mockMapper.CreateMapper(); var users = new List<User>() { new User { Id = "1", UserName = "Gosho" }, new User { Id = "2", UserName = "Pesho" } }; await this.db.Users.AddRangeAsync(users); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, mapper); var result = await usersService.AllUsersAsync(); Assert.NotNull(result); Assert.NotEmpty(result); } //AddBiograpyAsync Tests [Fact] public async Task AddBiographyShouldReturnTrueIfAllDataIsValid() { var user = new User { Id = "1", UserName = "Gosho" }; await this.db.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.AddBiographyAsync("I'm test biography", "Gosho"); Assert.True(result); } [Fact] public async Task AddBiographyShouldReturnFalseIfUsernameIsNotValid() { var user = new User { Id = "1", UserName = "Gosho" }; await this.db.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.AddBiographyAsync("I'm a test biography", "Pesho"); Assert.False(result); } [Fact] public async Task AddBiographyShouldReturnFalseIfBiographyIsNotValid() { var user = new User { Id = "1", UserName = "Gosho" }; await this.db.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.AddBiographyAsync(" ", "Pesho"); Assert.False(result); } //IsUserActiveAsync Tests [Fact] public async Task IsUserActiveShouldReturnTrueIfAllDataIsValid() { var user = new User { Id = "1", UserName = "Gosho", IsActive = true }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.IsUserActiveAsync("Gosho"); Assert.True(result); } [Fact] public async Task IsUserActiveShouldReturnFalseIfUserIsNotActive() { var user = new User { Id = "1", UserName = "Gosho", IsActive = false }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.IsUserActiveAsync("Gosho"); Assert.False(result); } [Fact] public async Task IsUserActiveShouldReturnFalseIfUsernameIsNotValid() { var user = new User { Id = "1", UserName = "Gosho", IsActive = false }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.IsUserActiveAsync("Pesho"); Assert.False(result); } //GetBiographyAsync Tests [Fact] public async Task GetBiographyShouldReturnTheBiographyIfAllDataIsValid() { var user = new User { Id = "1", UserName = "Gosho", Biography = "I'm a test" }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.GetUserBiographyAsync("Gosho"); Assert.Equal(user.Biography, result); } [Fact] public async Task GetBiographyShouldThrowExceptionIfUsernameIsNotValid() { var user = new User { Id = "1", UserName = "Gosho", Biography = "I'm a test" }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); await Assert.ThrowsAsync<InvalidOperationException>(() => usersService.GetUserBiographyAsync("Pesho")); } //ActivateUserAsync Tests [Fact] public async Task ActivateUserShouldReturnTrueIfAllDataIsValid() { var user = new User { Id = "1", UserName = "Gosho", IsActive = false }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.ActivateUserAsync("1"); Assert.True(result); } [Fact] public async Task ActivateUserShouldReturnFalseIfUserIdIsNotValid() { var user = new User { Id = "1", UserName = "Gosho", IsActive = false }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.ActivateUserAsync("2"); Assert.False(result); } //DeactivateUserAsync Tests [Fact] public async Task DeactivateUserShouldReturnTrueIfAllDataIsValid() { var user = new User { Id = "1", UserName = "Gosho", IsActive = true }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.DeactivateUserAsync("1"); Assert.True(result); } [Fact] public async Task DeactivateUserShouldReturnFalseIfUserIdIsNotValid() { var user = new User { Id = "1", UserName = "Gosho", IsActive = true }; await this.db.Users.AddAsync(user); await this.db.SaveChangesAsync(); var usersService = new UsersService(this.db, null); var result = await usersService.DeactivateUserAsync("2"); Assert.False(result); } } }
Ruby
UTF-8
9,461
2.640625
3
[ "MIT" ]
permissive
path = File.dirname(__FILE__) require "#{path}/tools" ########################################################################### # Author: Coleton Pierson # # Company: Praetorian # # Date: August 20, 2014 # # Project: Ruby Hashcat # # Description: Main parser class. Parses ocl stdout and pot file. # ########################################################################### module RubyHashcat module Parse ########################################################################### # @method RubyHashcat::Parse.stdout(file) # # @param file: [String] Path to oclHashcat stdout file # # @description Parses the oclHashcat stdout file into hashes. # # @return [Array][Hash] Array of Hashes with oclHashcat status. # ########################################################################### def self.stdout(file) array = [] return array unless File.exists?(file) placement = -1 string = [] File.open(file).each_line do |x| string << x end string.each do |line| if line.include?('Session.Name.') placement += 1 array[placement] = {} elsif placement < 0 next elsif line.include?('Status.') tmp = line.split(':') array[placement][:status] = tmp[-1].chomp.strip elsif line.include?('Rules.Type.') tmp = line.split(':') array[placement][:rules] = tmp[-1].chomp.strip elsif line.include?('Input.Mode.') tmp = line.split(':') array[placement][:input] = tmp[-1].chomp.strip elsif line.include?('Input.Base.') # Label only used in combination attack tmp = line.split(':') array[placement][:input_base] = tmp[-1].chomp.strip elsif line.include?('Input.Mod.') # Label only used in combination attack tmp = line.split(':') array[placement][:input_mod] = tmp[-1].chomp.strip elsif line.include?('Hash.Target.') tmp = line.split(':') array[placement][:target] = tmp[-1].chomp.strip elsif line.include?('Hash.Type.') tmp = line.split(':') array[placement][:type] = tmp[-1].chomp.strip elsif line.include?('Time.Started.') tmp = line.split(':') tmp.delete_at(0) tmp = tmp.join(':') array[placement][:started] = tmp.chomp.strip elsif line.include?('Time.Estimated.') tmp = line.split(':') tmp.delete_at(0) tmp = tmp.join(':') array[placement][:estimated] = tmp.chomp.strip elsif line.include?('Speed.GPU.') # Must account for x amount of GPUs tmp = line.split(':') tmp[0].gsub!('Speed.GPU.', '') tmp[0].gsub!('.', '') tmp[0].gsub!('#', '') num = tmp[0].to_i if num == 1 array[placement][:speed] = [] end array[placement][:speed][num-1] = tmp[-1].chomp.strip elsif line.include?('Recovered.') tmp = line.split(':') array[placement][:recovered] = tmp[-1].chomp.strip elsif line.include?('Progress.') tmp = line.split(':') array[placement][:progress] = tmp[-1].chomp.strip elsif line.include?('Rejected.') tmp = line.split(':') array[placement][:rejected] = tmp[-1].chomp.strip elsif line.include?('HWMon.GPU.') # Must account for x amount of GPUs tmp = line.split(':') tmp[0].gsub!('HWMon.GPU.', '') tmp[0].gsub!('.', '') tmp[0].gsub!('#', '') num = tmp[0].to_i if num == 1 array[placement][:hwmon] = [] end array[placement][:hwmon][num-1] = tmp[-1].chomp.strip end end array end ########################################################################### # @method RubyHashcat::Parse.status_automat(file) # # @param file: [String] Path to oclHashcat stdout file # # @description Parses the oclHashcat status-automat stdout format. # # @return [Array][Hash] Array of Hashes with oclHashcat status. # ########################################################################### def self.status_automat(file) array = [] return array unless File.exists?(file) string = [] File.open(file).each_line do |x| string << x end string.each do |line| line = line.chomp line = line.strip line = line.gsub(' ', ' ') unless line.include?('STATUS') next end split = line.split(' ') stat = {} i = 0 if split[i] == 'STATUS' stat[:status] = split[i+1].chomp.strip i += 2 end if split[i] == 'SPEED' i += 1 speed = 0 si = 0 while split[i] != 'CURKU' calc = split[i].to_f duration = split[i+1].to_f if calc == 0.0 and duration == 0.0 stat["speed_gpu_#{si+1}".to_sym] = 0 else stat["speed_gpu_#{si+1}".to_sym] = (calc/duration).round speed += (calc/duration).round end si += 1 i += 2 end stat[:total_speed] = speed end if split[i] == 'CURKU' stat[:checkpoint] = split[i+1] i += 2 end if split[i] == 'PROGRESS' current_prog = split[i+1].to_f total_prog = split[i+2].to_f stat[:progress] = ((((current_prog + 0.0)/(total_prog + 0.0)) * 10000).round)/10000.0 i += 3 end if split[i] == 'RECHASH' rec_count = split[i+1].to_f.to_i rec_total = split[i+2].to_f.to_i stat[:rec_hash] = "#{rec_count}/#{rec_total}" i += 3 end if split[i] == 'RECSALT' rec_count = split[i+1].to_f.to_i rec_total = split[i+2].to_f.to_i stat[:rec_salt] = "#{rec_count}/#{rec_total}" i += 3 end if split[i] == 'TEMP' i += 1 si = 0 while i < split.count stat["temp_gpu_#{si+1}".to_sym] = split[i].to_i si += 1 i += 1 end end array << stat end array end ########################################################################### # @method RubyHashcat::Parse.pot_file(file) # # @param file: [String] Path to oclHashcat cracked passwords # # @description Parses the cracked passwords into a hash. # # @return [Array][Hash] Array of Hashes with cracked passwords. # ########################################################################### def self.pot_file(file) arr = [] return arr unless File.exists?(file) File.open(file).each_line do |x| split = x.split(':') plain = self.hex_to_bin(split[-1]) split.delete_at(-1) hash = split.join(':') arr << {:hash => hash, :plain => plain} end arr end ########################################################################### # @method RubyHashcat::Parse.hash(hash) # # @param hash: [Hash] Original Hash with strings as keys. # # @description Parses a hash with strings as keys and converts them # # to symbols. # # @return [Hash] Hash with all keys as symbols. # ########################################################################### def self.hash(obj) return obj.reduce({}) do |memo, (k, v)| memo.tap { |m| m[k.to_sym] = hash(v) } end if obj.is_a? Hash return obj.reduce([]) do |memo, v| memo << hash(v); memo end if obj.is_a? Array obj end ########################################################################### # @method RubyHashcat::Parse.bin_to_hex(s) # # @param s: [String] Normal String # # @description Converts a string to hex # # @return [String] Hexed String # ########################################################################### def self.bin_to_hex(s) s.each_byte.map { |b| b.to_s(16) }.join end ########################################################################### # @method RubyHashcat::Parse.hex_to_bin(s) # # @param s: [String] Hexed String # # @description Converts hex to a string # # @return [String] Normal String # ########################################################################### def self.hex_to_bin(s) s.scan(/../).map { |x| x.hex.chr }.join end end end
Ruby
UTF-8
534
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# This module holds funtions for network URI's module Puppet::Network::Uri # Mask credentials in given URI or address as string. Resulting string will # contain '***' in place of password. It will only be replaced if actual # password is given. # # @param uri [URI|String] an uri or address to be masked # @return [String] a masked url def mask_credentials(uri) if uri.is_a? URI uri = uri.dup else uri = URI.parse(uri) end uri.password = '***' unless uri.password.nil? uri.to_s end end
Java
UTF-8
845
3.046875
3
[]
no_license
/*** * GameHelper.java * 19-Jan-2014 : 12:00:11 am * */ package head.first.java.chapter06; import java.io.*; /** * @author ubuntu * @packageName = head.first.java.chapter05:GameHelper.java * @createdOn: 19-Jan-2014 : 12:00:11 am * * This is a file for my practice and notes of "Head First * Java, 2nd edition.". * Anyone can fork this repo, also the official code is available * @(http://headfirstlabs.com/books/hfjava/) */ public class GameHelper { public String getUserInput(String prompt){ String inputLine = null; System.out.println(prompt); try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); inputLine = is.readLine(); if(inputLine.length() == 0){ return null; } } catch (IOException e) { System.out.println("IOExceptio: " +e); } return inputLine; } }
C#
UTF-8
4,429
2.671875
3
[]
no_license
namespace WayGUI.CustomControls { using System.Drawing; using System.Windows.Forms; public class ThreadSafeRichTextBox : RichTextBox { public override string Text { get { return GetText(); } set { if(InvokeRequired) Invoke(new MethodInvoker(() => base.Text = value)); base.Text = value; } } public new bool Enabled { get { return GetEnabled(); } set { if(InvokeRequired) Invoke(new MethodInvoker(() => base.Enabled = value)); base.Enabled = value; } } public override Color BackColor { get { return GetBackColor(); } set { if(InvokeRequired) { Invoke(new MethodInvoker(() => { base.BackColor = value; })); } else base.BackColor = value; } } public override Color ForeColor { get { return GetForeColor(); } set { if(InvokeRequired) { Invoke(new MethodInvoker(() => { base.ForeColor = value; })); } base.ForeColor = value; } } public new void Select() { if(InvokeRequired) { Invoke(new MethodInvoker(() => base.Select())); return; } base.Select(); } public new void Select(int start, int length) { if(InvokeRequired) { Invoke(new MethodInvoker(() => base.Select(start, length))); return; } base.Select(start, length); } public new void Select(bool directed, bool forward) { if(InvokeRequired) { Invoke(new MethodInvoker(() => base.Select(directed, forward))); return; } base.Select(directed, forward); } public new void SelectAll() { if(InvokeRequired) { Invoke(new MethodInvoker(() => base.SelectAll())); return; } base.SelectAll(); } public new void ScrollToCaret() { if(InvokeRequired) { Invoke(new MethodInvoker(() => base.ScrollToCaret())); return; } base.ScrollToCaret(); } public new void AppendText(string text) { if(string.IsNullOrEmpty(text)) return; if(InvokeRequired) Invoke(new MethodInvoker(() => base.AppendText(text))); else base.AppendText(text); } public new void Clear() { if(InvokeRequired) Invoke(new MethodInvoker(() => base.Clear())); else base.Clear(); } private string GetText() { if(!InvokeRequired) return base.Text; GetStringDelegate del = GetText; return Invoke(del) as string; } private bool GetEnabled() { if(!InvokeRequired) return base.Enabled; GetBoolDelegate del = GetEnabled; return Invoke(del) is bool && (bool) Invoke(del); } private Color GetBackColor() { if(!InvokeRequired) return base.BackColor; GetColorDelegate del = GetBackColor; return Invoke(del) is Color ? (Color) Invoke(del) : new Color(); } private Color GetForeColor() { if(!InvokeRequired) return base.ForeColor; GetColorDelegate del = GetForeColor; return Invoke(del) is Color ? (Color) Invoke(del) : new Color(); } #region Nested type: GetBoolDelegate private delegate bool GetBoolDelegate(); #endregion #region Nested type: GetColorDelegate private delegate Color GetColorDelegate(); #endregion #region Nested type: GetStringDelegate private delegate string GetStringDelegate(); #endregion } }
PHP
UTF-8
204
2.703125
3
[]
no_license
<?php // イヌ科 class Canidae extends Mammalian{ public function __construct($nameJP, $nameEN, $img){ parent::__construct($nameJP, $nameEN, $img, 'イヌ科', 'Canidae'); } } ?>
Rust
UTF-8
4,587
3.046875
3
[]
no_license
use glifparser::*; extern crate xmlwriter; use xmlwriter::*; fn point_type_to_string(ptype: PointType) -> Option<String> { return match ptype{ PointType::Undefined => None, PointType::OffCurve => None, PointType::QClose => None, // should probably be removed from PointType PointType::Move => Some(String::from("move")), PointType::Curve => Some(String::from("curve")), PointType::QCurve => Some(String::from("qcurve")), PointType::Line => Some(String::from("line")), } } fn write_ufo_point_from_handle(mut writer: XmlWriter, handle: Handle) -> XmlWriter { match handle { Handle::At(x, y) => { writer.start_element("point"); writer.write_attribute("x", &x); writer.write_attribute("y", &y); writer.end_element(); }, _ => {} } return writer; } pub fn write_ufo_glif<T>(glif: Glif<T>) -> String { let mut writer = XmlWriter::new(Options::default()); writer.start_element("glyph"); writer.write_attribute("name", &glif.name); writer.write_attribute("format", &glif.format); writer.start_element("advance"); writer.write_attribute("width", &glif.width); writer.end_element(); match glif.unicode { Codepoint::Hex(hex) => { writer.start_element("unicode"); writer.write_attribute("hex", &format!(r#"{:X}"#, hex as u32)); writer.end_element(); }, Codepoint::Undefined => {} } match glif.anchors { Some(anchor_vec) => { for anchor in anchor_vec { writer.start_element("anchor"); writer.write_attribute("x", &anchor.x); writer.write_attribute("y", &anchor.y); writer.write_attribute("name", &anchor.class); // Anchor does not currently contain a color, or identifier attribute writer.end_element(); } }, None => {} } match glif.outline { Some(outline) => { writer.start_element("outline"); // if we find a move point at the start of things we set this to false for contour in outline { let open_contour = if contour.first().unwrap().ptype == PointType::Move { true } else { false }; writer.start_element("contour"); let mut last_point = None; for point in &contour { if let Some(lp) = last_point { // if there was a point prior to this one we emit our b handle writer = write_ufo_point_from_handle(writer, point.b); } writer.start_element("point"); writer.write_attribute("x", &point.x); writer.write_attribute("y", &point.y); match point_type_to_string(point.ptype) { Some(ptype_string) => writer.write_attribute("type", &ptype_string), None => {} } match &point.name { Some(name) => writer.write_attribute("name", &name), None => {} } // Point>T> does not contain fields for smooth, or identifier. writer.end_element(); match point.ptype { PointType::Line | PointType::Curve => { writer = write_ufo_point_from_handle(writer, point.a); }, PointType::QCurve => { //QCurve currently unhandled. This needs to be implemented. }, _ => { } // I don't think this should be reachable in a well formed Glif object? } last_point = Some(point); } // if a move wasn't our first point then we gotta close the shape by emitting the first point's b handle if !open_contour { writer = write_ufo_point_from_handle(writer, contour.first().unwrap().b); } writer.end_element(); } writer.end_element(); }, None => {} } writer.end_document() }
Python
UTF-8
1,199
2.703125
3
[]
no_license
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Project :auto_test_interface # File :test_logout.py # IDE :PyCharm # Author :Runner # Date :2021/1/26 16:22 from testcases.base_test_case import BaseCase from page_objects.app.navigation_page import NavigationPage from page_objects.app.my_page import MyPage from page_objects.app.settings_page import SettingsPage class TestLogout(BaseCase): name = '登出功能' def test_logout(self, signed_in_driver): self.logger.info('**********{}开始测试**********'.format(self.name)) # 前置为已登录,通过夹具实现 # 点击我的柠檬,保证后面可以定位到设置 self.driver = signed_in_driver np = NavigationPage(signed_in_driver) np.click_my() # 点击设置 mp = MyPage(signed_in_driver) mp.enter_settings_page() # 点击退出 sp = SettingsPage(signed_in_driver) sp.logout() # 点击弹框的确认 sp.click_confirm() # 断言 self.assert_equal(sp.get_logout_toast(), '退出登录成功') self.logger.info('**********{}测试结束**********'.format(self.name))
Java
UTF-8
1,395
2.25
2
[]
no_license
package iswc.test; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.parser.ParsedQuery; import org.openrdf.query.parser.sparql.SPARQLParser; public class MatView { private String query; private int number; private int cost; private String name; private String graph; private TupleExpr te; public MatView(String name, int number, String graph, int cost){ this.name = name; this.cost = cost; this.graph = graph; this.number = number; } public String getQuery(){ return query; } public void setQuery(String qry){ query = qry; SPARQLParser sprqlQ = new SPARQLParser(); try { ParsedQuery pquerMV = sprqlQ.parseQuery(this.query, "http://10.15.120.1:8890/sparql"); te = pquerMV.getTupleExpr(); } catch (MalformedQueryException e) { // TODO Auto-generated catch block e.printStackTrace(); te = null; } } public TupleExpr getTupleExpr(){ return te; } public int getCost(){ return cost; } public void setCost(int cost){ this.cost = cost; } public String getGraph(){ return graph; } public void setGraph(String graph){ this.graph = graph; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getNumber(){ return number; } public void setNumber(int number){ this.number = number; } }
Java
UTF-8
2,290
2.28125
2
[ "MIT" ]
permissive
package pl.t32.newmathtools.ap; import android.os.Bundle; import android.app.Fragment; import android.support.design.widget.Snackbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import butterknife.BindString; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import pl.t32.newmathtools.R; import static pl.t32.newmathtools.MyUtils.getValue; public class ArithmeticProgressionFragment extends Fragment implements ArithmeticProgressionContract.View { private ArithmeticProgressionContract.Presenter presenter; @BindView(R.id.ap_initial_term) EditText initialTerm; @BindView(R.id.ap_common_diff) EditText commonDiff; @BindView(R.id.ap_terms_number) EditText termsNumber; @BindView(R.id.sumOrProductSwitch) Switch sumOrProduct; @BindView(R.id.textView) TextView textView; @BindString(R.string.error_message_numbers_only) String messageNumbersOnly; @OnClick(R.id.button) void onButtonClick() { if (sumOrProduct.isChecked()) { presenter.computeProduct( getValue(initialTerm), getValue(commonDiff), getValue(termsNumber)); } else { presenter.computeSum( getValue(initialTerm), getValue(commonDiff), getValue(termsNumber)); } } @OnClick(R.id.sumOrProductSwitch) void onSwitchCheckedChange() { sumOrProduct.setText(sumOrProduct.isChecked() ? R.string.compute_product : R.string.compute_sum); onButtonClick(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_arithmetic_progression, container, false); ButterKnife.bind(this, view); presenter = new ArithmeticProgressionPresenter(this); return view; } @Override public void showImproperValuesPassedError() { Snackbar.make(textView, messageNumbersOnly, Snackbar.LENGTH_LONG).show(); } @Override public void showComputationResult(String result) { textView.setText(result); } }
C#
UTF-8
829
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DO { public class Person { public string Id { get; set; } public IdTypes IdType { get; set; } public Status Status { get; set; } public string Password { get; set; } public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNomber { get; set; } public override string ToString() { return "ID : " + Id + "\nLast name : " + LastName + "\nFirst name : " + FirstName + "\nEmail : " + Email + "\nPhone nomber : " + PhoneNomber + "\n"; } } }
Python
UTF-8
5,886
2.5625
3
[]
no_license
# -*- encoding: utf-8 -*- import binascii import socket import struct import sys def arp_parser(packet): arp_length = 28 # fixed arp = struct.unpack("!2s2s1s1s2s6s4s6s4s", packet[0:arp_length]) print ("ARP Header :") print (" |_ SHA: {0} -> THA: {1}".format(binascii.hexlify(arp[5]), binascii.hexlify(arp[7]))) print (" |_ SPA: {0} -> TPA: {1}".format(socket.inet_ntoa(arp[6]), socket.inet_ntoa(arp[8]))) print (" |_ HTYPE : {0}".format(binascii.hexlify(arp[0]))) print (" |_ PTYPE : {0}".format(binascii.hexlify(arp[1]))) print (" |_ HLEN : {0}".format(binascii.hexlify(arp[2]))) print (" |_ PLEN : {0}".format(binascii.hexlify(arp[3]))) print (" |_ OPER : {0}".format(binascii.hexlify(arp[4]))) #print (" |_ SHA : {0}".format(binascii.hexlify(arp[5]))) #print (" |_ SPA : {0}".format(socket.inet_ntoa(arp[6]))) #print (" |_ THA : {0}".format(binascii.hexlify(arp[7]))) #print (" |_ TPA : {0}".format(socket.inet_ntoa(arp[8]))) # Padding dump packet[arp_length:] print (" |_ Data : {0}".format(binascii.hexlify(packet[arp_length:]))) def icmp_parser(packet): icmp_length = 4 icmp = struct.unpack("!BBH", packet[0:icmp_length]) print ("ICMP Header :") print (" |_ Type : {0}".format(icmp[0])) print (" |_ Code : {0}".format(icmp[1])) print (" |_ Checksum : {0} ({1})".format(icmp[2], hex(icmp[2]))) # Padding dump packet[icmp_length:] print (" |_ Data : {0}".format(binascii.hexlify(packet[icmp_length:]))) def tcp_parser(packet): tcp_length = 20 tcp = struct.unpack("!HHLLBBHHH", packet[0:tcp_length]) # Real tcp header length tcp_length = (tcp[4] >> 4) * 4 Flags = ((tcp[4] & 0x0f) << 8) + tcp[5] print ("TCP Header :") print (" |_ Src Port: {0} -> Dst Port: {1}".format(tcp[0], tcp[1])) print (" |_ Sequence : {0} ({1})".format(tcp[2], hex(tcp[2]))) print (" |_ Acknowledgment : {0} ({1})".format(tcp[3], hex(tcp[3]))) print (" |_ Length : {0}".format(tcp_length)) print (" |_ Flags : {0}".format(hex(Flags))) print (" |_ Window size : {0}".format(tcp[6])) print (" |_ Checksum : {0} ({1})".format(tcp[7], hex(tcp[7]))) print (" |_ Urgent pointer : {0}".format(tcp[8])) # Padding dump packet[icmp_length:] print (" |_ Data : {0}".format(binascii.hexlify(packet[tcp_length:]))) def udp_parser(packet): udp_length = 8 udp = struct.unpack("!HHHH", packet[0:udp_length]) print ("UDP Header :") print (" |_ Src Port: {0} -> Dst Port: {1}".format(udp[0], udp[1])) print (" |_ Length : {0}".format(udp[2])) print (" |_ Checksum : {0} ({1})".format(udp[3], hex(udp[3]))) # Padding dump packet[icmp_length:] print (" |_ Data : {0}".format(binascii.hexlify(packet[udp_length:]))) def ip_parser(packet): ip_length = 20 ip = struct.unpack("!BBHHHBBH4s4s", packet[0:ip_length]) version = ip[0] >> 4 IHL = (ip[0] & 0xf) * 4 DiffServ = ip[1] >> 2 ECN = ip[1] & 0x03 Flags = ip[4] >> 13 Frag_offset = ip[4] & 0x1fff print ("IP Header :") print (" |_ From: {0} -> To: {1}".format(socket.inet_ntoa(ip[8]), socket.inet_ntoa(ip[9]))) print (" |_ Version : {0}".format(version)) print (" |_ Header Length : {0}".format(IHL)) print (" |_ DiffServ : {0}".format(DiffServ)) print (" |_ ECN : {0}".format(ECN)) print (" |_ Total Length : {0}".format(ip[2])) print (" |_ Identification : {0} ({1})".format(ip[3], hex(ip[3]))) print (" |_ Flags : {0}".format(Flags)) print (" |_ Fragment Offset: {0}".format(Frag_offset)) print (" |_ TTL : {0}".format(ip[5])) print (" |_ Protocol : {0}".format(hex(ip[6]))) print (" |_ Checksum : {0} ({1})".format(ip[7], hex(ip[7]))) # next header if ip[6] == 1: # ICMP = 0x01 icmp_parser(packet[IHL:]) elif ip[6] == 6: # TCP = 0x06 tcp_parser(packet[IHL:]) elif ip[6] == 17: # UDP = 0x11 udp_parser(packet[IHL:]) else: pass def ethernet_parser(packet): eth_length = 14 # fixed eth = struct.unpack("!6s6s2s", packet[0:eth_length]) print ("ETHERNET Header :") print (" |_ From: {1} -> To: {0}".format(binascii.hexlify(eth[0]), binascii.hexlify(eth[1]))) print (" |_ Type: {0}".format(binascii.hexlify(eth[2]))) # parser next header if eth[2] == b'\x08\x06': arp_parser(packet[eth_length:]) elif eth[2] == b'\x08\x00': ip_parser(packet[eth_length:]) else: pass def linux_main(): rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) # Bind the interface, likes eth0 rawSocket.bind(("lo", 0)) while True: packet = rawSocket.recvfrom(2048)[0] ethernet_parser(packet) rawSocket.close() def windows_main(): # create a raw socket and bind it to the public interface rawSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) # Bind a interface with public IP HOST = socket.gethostbyname(socket.gethostname()) rawSocket.bind((HOST, 0)) print ("Bind a interface : {0}".format(HOST)) rawSocket.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Include IP headers rawSocket.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) # receive all packages while True: packet = rawSocket.recvfrom(2048)[0] ip_parser(packet) print ("") rawSocket.close() if __name__ == '__main__': if sys.platform.lower().startswith("win"): windows_main() else: linux_main()
C++
UTF-8
9,290
2.734375
3
[]
no_license
#include "Lexer.h" Lexer::Lexer(std::string JSONpath) { source.setJSON(JSONpath); } Lexer::Lexer() { } Lexer::~Lexer() { } void Lexer::setJSON(std::string JSONpath) { source.setJSON(JSONpath); } void Lexer::goToBegin() { source.goToBegin(); } void Lexer::skipWhitespaces() { while (!source.getFoundEOF() && isspace(source.currentChar())) source.nextChar(); } Lexer::checkResult Lexer::EOFToken() { if (source.getFoundEOF()) return std::make_pair(true, Token("EndOfFile", TokenType::EndOfFile, source.getPosition())); return std::make_pair(false, Token()); } Lexer::checkResult Lexer::SingleCharToken() { Token token; switch (source.currentChar()) { case '{': token = Token("{", TokenType::LeftCurlyBracket, source.getPosition()); source.nextChar(); return std::make_pair(true, token); case '}': token = Token("}", TokenType::RightCurlyBracket, source.getPosition()); source.nextChar(); return std::make_pair(true, token); case '[': token = Token("[", TokenType::LeftSquareBracket, source.getPosition()); source.nextChar(); return std::make_pair(true, token); case ']': token = Token("]", TokenType::RightSquareBracket, source.getPosition()); source.nextChar(); return std::make_pair(true, token); case ':': token = Token(":", TokenType::Colon, source.getPosition()); source.nextChar(); return std::make_pair(true, token); case ',': token = Token(",", TokenType::Comma, source.getPosition()); source.nextChar(); return std::make_pair(true, token); default: return std::make_pair(false, token); } } Lexer::checkResult Lexer::NonQuotWordToken() { Token token; token.setPosition(source.getPosition()); std::string value; if (isalpha(source.currentChar())) { do { value.push_back(source.currentChar()); source.nextChar(); } while (!source.getFoundEOF() && isalpha(source.currentChar())); token.setValue(value); if (value == "true") { token.setType(TokenType::True); return std::make_pair(true, token); } if (value == "false") { token.setType(TokenType::False); return std::make_pair(true, token); } if (value == "null") { token.setType(TokenType::Null); return std::make_pair(true, token); } ErrorsCommunicator::communicateAndExit("LEXER", token.getPosition(), "'true' or 'false' or 'null'", value); } return std::make_pair(false, token); } std::string Lexer::getExpPart() { std::string value; value.push_back(source.currentChar()); source.nextChar(); if (source.getFoundEOF()) ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "'+' or '-' or digit", "End Of File"); if (source.currentChar() == '+' || source.currentChar() == '-') { value.push_back(source.currentChar()); source.nextChar(); if (source.getFoundEOF()) ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "digit", "End Of File"); } if (isdigit(source.currentChar())) { do { value.push_back(source.currentChar()); source.nextChar(); } while (!source.getFoundEOF() && isdigit(source.currentChar())); return value; } std::string found; found.push_back(source.currentChar()); ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "digit", found); } std::string Lexer::getDotPart() { std::string value; value.push_back(source.currentChar()); source.nextChar(); if (source.getFoundEOF()) ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "digit", "End Of File"); if (isdigit(source.currentChar())) { do { value.push_back(source.currentChar()); source.nextChar(); } while (!source.getFoundEOF() && isdigit(source.currentChar())); return value; } std::string found; found.push_back(source.currentChar()); ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "digit", found); } Lexer::checkResult Lexer::NumberToken() { Token token; token.setPosition(source.getPosition()); std::string value; if (isdigit(source.currentChar()) || source.currentChar() == '-') { if(source.currentChar() == '-') { value.push_back(source.currentChar()); source.nextChar(); } if (isdigit(source.currentChar())) { do { value.push_back(source.currentChar()); source.nextChar(); } while (!source.getFoundEOF() && isdigit(source.currentChar())); if (source.getFoundEOF()) { token.setValue(value); token.setType(TokenType::Int); return std::make_pair(true, token); } if (source.currentChar() == 'e' || source.currentChar() == 'E') { value = value + getExpPart(); token.setValue(value); token.setType(TokenType::IntExp); return std::make_pair(true, token); } if (source.currentChar() == '.') { value = value + getDotPart(); if (source.getFoundEOF()) { token.setValue(value); token.setType(TokenType::IntFrac); return std::make_pair(true, token); } if (source.currentChar() == 'e' || source.currentChar() == 'E') { value = value + getExpPart(); token.setValue(value); token.setType(TokenType::IntFracExp); return std::make_pair(true, token); } token.setValue(value); token.setType(TokenType::IntFrac); return std::make_pair(true, token); } token.setValue(value); token.setType(TokenType::Int); return std::make_pair(true, token); } else { std::string found; found.push_back(source.currentChar()); ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "digit", found); } } return std::make_pair(false, token); } Lexer::checkResult Lexer::QuotWordToken() { Token token; token.setPosition(source.getPosition()); std::string value; std::array<char,9> arr{ {'"','\\','/','b','f','n','r','t','u'} }; if (source.currentChar() == '"') { bool backslashFound = false; do { if(!backslashFound && source.currentChar() == '\\') backslashFound = true; else if (backslashFound && std::find(arr.begin(), arr.end(), source.currentChar()) != arr.end()) { backslashFound = false; if(source.currentChar() == 'u') { value.push_back(source.currentChar()); source.nextChar(); value = value + check4Get3HexDigits(); } } else if(backslashFound) { std::string expected = "'\"'' or '\\'' or '/'' or 'b' or 'f' or 'n' or 'r' or 't' or 'u'"; std::string found; found.push_back(source.currentChar()); ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), expected, found); } value.push_back(source.currentChar()); source.nextChar(); } while (!source.getFoundEOF() && (source.currentChar() != '"' || backslashFound)); if (source.getFoundEOF() && !backslashFound) ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "char", "End Of File"); if (source.getFoundEOF() && backslashFound) { std::string expected = "'\"'' or '\\'' or '/'' or 'b' or 'f' or 'n' or 'r' or 't' or 'u'"; ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), expected, "End Of File"); } value.push_back(source.currentChar()); source.nextChar(); token.setValue(value); token.setType(TokenType::String); return std::make_pair(true, token); } return std::make_pair(false, token); } std::string Lexer::check4Get3HexDigits() { std::string value; std::array<char,12> arr{ {'A','B','C','D','E','F','a','b','c','d','e','f'} }; for(int i = 0; i < 3; ++i) { if (source.getFoundEOF()) ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "hexadecimal digit", "End Of File"); if(!isdigit(source.currentChar()) && std::find(arr.begin(), arr.end(), source.currentChar()) == arr.end()) { std::string found; found.push_back(source.currentChar()); ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "hexadecimal digit", found); } value.push_back(source.currentChar()); source.nextChar(); } if (source.getFoundEOF()) ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "hexadecimal digit", "End Of File"); if(!isdigit(source.currentChar()) && std::find(arr.begin(), arr.end(), source.currentChar()) == arr.end()) { std::string found; found.push_back(source.currentChar()); ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), "hexadecimal digit", found); } return value; } Token Lexer::nextToken() { checkResult result; skipWhitespaces(); result = EOFToken(); if (result.first) return result.second; result = SingleCharToken(); if (result.first) return result.second; result = NonQuotWordToken(); if (result.first) return result.second; result = QuotWordToken(); if (result.first) return result.second; result = NumberToken(); if (result.first) return result.second; std::string expected = "End Of File or '{' or '}' or '[' or ']' or ':' or ',' or \" or \" or alpha or digit"; std::string found; found.push_back(source.currentChar()); ErrorsCommunicator::communicateAndExit("LEXER", source.getPosition(), expected, found); }
Shell
UTF-8
445
3.640625
4
[]
no_license
#!/bin/bash obs=$1 if [ ! $1 ]; then echo "No observation ID given." exit 1 fi project_id=$(get_projid.py -o $obs) if [ project_id ]; then if [ $project_id != "G0009" ] && [ $project_id != "G0010" ]; then echo "Project ID for obs: $obs, does not match either G0009 nor G0010" exit 1 else echo "Project ID matches G0009 or G0010" exit 0 fi else echo "Could not get project ID for obs : $obs" exit 1 fi
Markdown
UTF-8
2,123
2.59375
3
[ "MIT" ]
permissive
--- id: 48 title: 'Check Mysql user&#8217;s privileges' date: 2016-11-02T22:55:41+00:00 author: Navy Su layout: post --- Show root user&#8217;s privileges: ~~~shell mysql> SHOW GRANTS FOR 'root'@'localhost'; +---------------------------------------------------------------------+ | Grants for root@localhost | +---------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION | +---------------------------------------------------------------------+ ~~~ Show current user&#8217;s privileges: ~~~shell mysql> show grants; +---------------------------------------------------------------------+ | Grants for root@localhost | +---------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION | | GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION | +---------------------------------------------------------------------+ 2 rows in set (0.00 sec) mysql> show grants for current_user; +---------------------------------------------------------------------+ | Grants for root@localhost | +---------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION | | GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION | +---------------------------------------------------------------------+ 2 rows in set (0.00 sec) mysql> show grants for current_user(); +---------------------------------------------------------------------+ | Grants for root@localhost | +---------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION | | GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION | +---------------------------------------------------------------------+ 2 rows in set (0.00 sec) ~~~
Python
UTF-8
2,432
2.625
3
[]
no_license
import logging, os, shutil, json, time def weiboLogin(driver, username, password): driver.get('https://www.weibo.com/Login.php') driver.find_element_by_id('loginname').send_keys(username) driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div[2]/div[1]/div[2]/div/div[2]/div[1]/div[2]/div[1]/div/div/div/div[3]/div[2]/div/input').send_keys(password) time.sleep(10) driver.find_element_by_css_selector('div.info_list:nth-child(6) > a:nth-child(1)').click() time.sleep(20) cookies = driver.get_cookies() json.dump(cookies, open('cookies.json', 'w')) def copyFile(ori_file, dest_folder): _, filename = os.path.split(ori_file) dest_file = os.path.join(dest_folder, filename) print('copy %s into %s' % (ori_file, dest_file)) shutil.copy(ori_file, dest_file) def showTimeDuration(time_length): re_time = '' if time_length > 5: # above 5 seconds days = int(time_length // (24 * 60 * 60)) time_length = time_length - days * 24 * 60 * 60 hours = int(time_length // (60 * 60)) time_length = time_length - hours * 60 * 60 mins = int(time_length // 60) secs = time_length - mins * 60 if days: re_time += '{}d '.format(days) if hours: re_time += '{}h '.format(hours) if mins: re_time += '{}m '.format(mins) re_time += '{:.0f}s'.format(secs) else: re_time += '{:.3f}s'.format(time_length) return re_time class WatchLogger(): """WatchLogger""" def __init__(self, write_console=True, write_file=None): super(WatchLogger, self).__init__() self.watch_logger = logging.getLogger(__name__) self.watch_logger.setLevel(logging.INFO) formatter = logging.Formatter( fmt="%(asctime)s - %(message)s", datefmt="%y/%m/%d %H:%M:%S") if write_console: # whether print on console console_logging = logging.StreamHandler() console_logging.setLevel(logging.INFO) console_logging.setFormatter(formatter) self.watch_logger.addHandler(console_logging) if write_file: # whether print on file file_logging = logging.FileHandler(write_file) file_logging.setLevel(logging.INFO) file_logging.setFormatter(formatter) self.watch_logger.addHandler(file_logging) def __call__(self, message): # default is info self.watch_logger.info(message) def debug(self, message): self.watch_logger.debug(message) def info(self, message): self.watch_logger.info(message) def warning(self, message): self.watch_logger.warning(message)
C
UTF-8
1,179
2.625
3
[]
no_license
#include <linux/module.h> #include <linux/kernel.h> #include <linux/proc_fs.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/uaccess.h> //author : afang //comment: what a nice day, isn't it?! //linux kernel module template int len, temp; char *msg; int read_proc(struct file *filep, char *buf, size_t count, loff_t *offp){ if(count>temp){ count = temp; } //not pretty clear ops about temp. temp = temp - count; copy_to_user(buf,msg,count); if(count==0){ //reset temp temp = len; } return count; } int write_proc(struct file *filep, const char *buf, size_t count, loff_t *offp){ copy_from_user(msg,buf,count); len = count; temp = len; return count; } struct file_operations proc_fops = { read: read_proc, write: write_proc }; void create_new_proc_entry(void){ msg = kmalloc(10*sizeof(char), GFP_KERNEL); //kmalloc size 10 for usage. printk("space allocated at : %p\n", msg); proc_create("hellomod", 0666, NULL, &proc_fops); } int proc_init(void){ create_new_proc_entry(); return 0; } void proc_cleanup(void){ remove_proc_entry("hellomod", NULL); } MODULE_LICENSE("GPL"); module_init(proc_init); module_exit(proc_cleanup);
PHP
UTF-8
996
2.640625
3
[]
no_license
<?php namespace SnowIO\Magento2DataModel\Command; use SnowIO\Magento2DataModel\Inventory\SourceItemDataSet; class SaveSourceItemsCommand extends Command { public static function of(SourceItemDataSet $sourceItemDataSet): self { $result = new self; $result->sourceItems = $sourceItemDataSet; return $result; } public function getSourceItems(): SourceItemDataSet { return $this->sourceItems; } public function withStore(string $store): self { $result = clone $this; $result->store = $store; return $result; } public function toJson(): array { $json = parent::toJson() + [ "sourceItems" => $this->sourceItems->toJson(), ]; if ($this->store) { $json["@store"] = $this->store; } return $json; } /** @var SourceItemDataSet */ private $sourceItems; private $store; private function __construct() { } }
Swift
UTF-8
508
2.546875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Created by Tyler Hedrick on 9/12/19. // Copyright © 2019 Airbnb Inc. All rights reserved. import UIKit /// A view that responds to being highlighted within a `CollectionView`. public protocol HighlightableView: UIView { /// Implement this method on your view to react to highlight events. Do NOT use this method to /// manage internal state for your view. /// /// Example use case: override to animate a shrink / grow effect when the user highlights a cell. func didHighlight(_ highlighted: Bool) }
Java
UTF-8
2,292
2.84375
3
[]
no_license
package com.Utilities; import java.io.File; import java.io.FileInputStream; import java.util.Properties; public class ReadConfig { // Properties Class Properties pro; // Constructor public ReadConfig() { File src = new File("./Configuration/config.properties"); // Creating File object try { // Open FileInputStream and Read data FileInputStream fis = new FileInputStream(src); pro = new Properties(); pro.load(fis); // Load config.properties file } catch (Exception e) { // If config.properties file is not available it will throw an exception System.out.println("Exception is " + e.getMessage()); } } // Methods to read data from config.properties public String getApplicationURL() // ok - add new url in config.properties { String url=pro.getProperty("baseURL"); // Value from config.properties stored in url variable return url; } public String getSpecificday() { return pro.getProperty("specificday"); } public String getUsername1() // new { String username1=pro.getProperty("username1"); return username1; } public String getUsername2() // new { String username2=pro.getProperty("username2"); return username2; } public String getUsername3() // new { String username3=pro.getProperty("username3"); return username3; } public String getUsername4() // new { String username4=pro.getProperty("username4"); return username4; } public String getPassword() { String password=pro.getProperty("password"); return password; } public String getChromePath() { String chromepath=pro.getProperty("chromepath"); return chromepath; } public String getIEPath() { String iepath=pro.getProperty("iepath"); return iepath; } public String getFirefoxPath() { String firefoxpath=pro.getProperty("firefoxpath"); return firefoxpath; } public String getZipcode() { String zipcode=pro.getProperty("zipcode"); return zipcode; } public String getHomePageTitle() { String homePageTitle =pro.getProperty("homepagetitle"); return homePageTitle; } public String getSearchPageTitle() { return pro.getProperty("searchpagetitle"); } }
PHP
UTF-8
1,241
2.8125
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Minichat amélioré</title> </head> <body> <?php try { // Pour fonctionner, ce script doit d'abord être "initialisé" avec le fichier sql contenant notamment la création de la base et les infos user comme ci-dessous : // create database minichat; // create user 'minichat_user'@'localhost' identified by 'minichat_password'; // grant all on minichat.* to 'minichat_user'@'localhost'; $bdd = new PDO("mysql:host=localhost;dbname=minichat", "minichat_user", "minichat_password", array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); $bdd->exec("SET CHARACTER SET utf8"); } catch(Exception $e) { die("Erreur : Accès base impossible. Avez-vous importé le fichier sql fourni pour pouvoir utiliser ce script ?"); } ?> <div> <form action="minichat_post.php" method="POST"> <input type="text" value="" name="pseudo"/> <textarea name="message"></textarea> </form> </div> <?php $req = $bdd->prepare('select * from messages order by date desc limit 0,10'); try{$req->execute();} catch (Exception $e) { die("Erreur rencontrée : <b>".$e->getMessage()."</b>"); } while ($data = $req->fetch()) { } ?> </body> </html>
C++
UTF-8
1,746
3.15625
3
[]
no_license
// // Created by djf on 2016/12/21 0021. // #ifndef INC_03_SINGLELINKEDCIRCULARLIST_DOUBLELINKEDLIST_DOUBLELINKEDLIST_H #define INC_03_SINGLELINKEDCIRCULARLIST_DOUBLELINKEDLIST_DOUBLELINKEDLIST_H #include "LinearList.h" using namespace std; template <typename T> struct doubleChainNode{ T element; doubleChainNode<T>* next; doubleChainNode<T>* previous; doubleChainNode() {} doubleChainNode(const T& e) { this->element = e;} doubleChainNode(const T& e, doubleChainNode<T>* p,doubleChainNode<T>* n) { this->element=e;this->previous=p;this->next=n;} }; template <typename T> class DoubleLinkedList: public LinearList<T> { public: class iterator{ }; public: //construct copy destroy DoubleLinkedList():listSize() { headerNode = new doubleChainNode<T>();headerNode->next=headerNode;headerNode->previous=headerNode;} DoubleLinkedList(const DoubleLinkedList& D); ~DoubleLinkedList(); //ADT bool empty() const override ; int size() const override ; T& get(int index) const override ; int indexof(const T& theElement) const override ; void erase(int index) override ; void insert(int index,const T& theElement) override ; void output(ostream& out) const override ; //extend void clear() override ; void push_back(const T& theElement) override ; protected: void checkIndex(int index); int listSize; doubleChainNode<T>* headerNode; }; template <typename T> void DoubleLinkedList::checkIndex(int index) { if(index<0 || index>listSize) cerr << "----! index outrange !----" << endl; } #endif //INC_03_SINGLELINKEDCIRCULARLIST_DOUBLELINKEDLIST_DOUBLELINKEDLIST_H
JavaScript
UTF-8
7,266
2.59375
3
[ "MIT" ]
permissive
const const_url = "http://localhost:5984" const const_colecao = "projetocrud" var jsonAluno = {} var jsonResultSearch = {} var i=0; var nretorno = -1; function couchRest(pmetodo, ptype, pchavedoc){ // Responsável para comunicação do REST com JavaScript. // JavaScript + AJAX. var curl = "" if(pmetodo == ""){ curl = const_url+"/"+const_colecao; }else{ curl = const_url+"/"+const_colecao+"/"+pmetodo; } if (pchavedoc == ""){ }else{ curl = curl + "/"+pchavedoc } $.ajax({ url : curl, type : ptype, data : JSON.stringify(jsonAluno), contentType : "application/json", success : function(jsonResultSearch){ if(ptype == "POST"){ alert("Aluno Inserido com sucesso"); }else{ alert("Aluno Alterado com sucesso"); } }, error : function(error){ alert(error.error); } }) return; } function AlunoInserir(){ /* busca na coleção projetocrud para saber se aluno_nome e aluno_sobre estão incluídos na minha coleção do couchdb. */ jsonAluno = {}; jsonAluno.selector = {"$and" : [{"nome":document.getElementById("aluno_nome").value}, {"sobrenome" :document.getElementById("aluno_sobrenome").value}]}; jsonAluno.fields = ["nome", "sobrenome"]; $.ajax({ url : "http://127.0.0.1:5984/projetocrud/_find", type : "POST", data : JSON.stringify(jsonAluno), contentType : "application/json", success : function(jsonResultSearch){ if(jsonResultSearch.docs.length > 0){ // mostrar mensagem alert("Aluno [nome,sobrenome] já existentes"); }else{ // inserir jsonAluno.nome = document.getElementById("aluno_nome").value; jsonAluno.sobrenome = document.getElementById("aluno_sobrenome").value; jsonAluno.cidade = document.getElementById("aluno_cidade").value; jsonAluno.dtnascimento = document.getElementById("aluno_nascimento").value; couchRest("", "POST", ""); } }, error : function(error){ alert(error.error); } }) jsonAluno = {}; return 1; } function RedirecionarRelacionarLivro(){ document.location.href = "livro.html"; } function RedirecionarCadastro(){ document.location.href = "index.html"; } function AlunoBuscar(){ pnome = prompt("Informe um nome", "Busca de nome"); jsonAluno.selector = {"nome":pnome}; jsonAluno.fields = ["nome", "sobrenome"]; pmetodo = "_find"; curl = const_url+"/"+const_colecao+"/"+pmetodo; $.ajax({ url : curl, type : "POST", data : JSON.stringify(jsonAluno), contentType : "application/json", success : function(result){ //alert(JSON.stringify(result)); //alert("fez o acesso"); jsonResultSearch = result; if (jsonResultSearch.docs.length > 0) { for (var j=0; j <= jsonResultSearch.docs.length; j++){ $('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='nome" +i+"' type='text' placeholder='Nome' value='"+jsonResultSearch.docs[j].nome+"' class='form-control input-md' readonly/> </td>" + " <td><input name='sobrenome" +i+"' type='text' placeholder='Sobrenome' value='"+jsonResultSearch.docs[j].sobrenome +"' class='form-control input-md' readonly></td> " + " <td><input list='livrog1' class='form-control input-list'><datalist id='livrog1'> <option value='Livro A'><option value='Livro B'><option value='Livro C'> <option value='Livro D'><option value='Livro E'></datalist></td>" + " <td><input list='livrog1' class='form-control input-list'><datalist id='livrog2'> <option value='Livro A'><option value='Livro B'><option value='Livro C'> <option value='Livro D'><option value='Livro E'></datalist></td>" ); $('#tab_alunos').append('<tr id="addr'+(i+1)+'"></tr>'); i++; } }else{ alert("Aluno não encontrado"); } jsonResultSearch = {} }, error : function(error){ alert(error.error); } }) jsonAluno = {}; return 1; } function AlunoRelacionarLivro(){ var tbr_aluno = document.getElementById('tab_alunos').rows; var array_todos = null; // percorrendo os registros da minha tabela. for(var i = 0 ; i < tbr_aluno.length ; i++){ array_todos = tbr_aluno[i].cells; if (i > 0){ cNome = array_todos[1].getElementsByTagName("input")[0].value; alert(cNome); cSobrenome = array_todos[2].getElementsByTagName("input")[0].value; alert(cSobrenome); cLivroG1 = array_todos[3].getElementsByTagName("input")[0].value; alert(cLivroG1); cLivroG2 = array_todos[4].getElementsByTagName("input")[0].value; alert(cLivroG2); jsonAluno = {}; jsonAluno.selector = {"$and" : [{"nome":cNome}, {"sobrenome":cSobrenome}]}; jsonAluno.fields = ["_id", "_rev", "nome", "sobrenome", "cidade", "dtnascimento" ]; // enviar o parametro JSON via REST $.ajax({ url : "http://127.0.0.1:5984/projetocrud/_find", type : "POST", data : JSON.stringify(jsonAluno), contentType : "application/json", success : function(jsonResultSearch){ // o retorno do json (jsonResultSearch) if(jsonResultSearch.docs.length > 0){ // se ele encontrar o documento jsonAluno = {}; jsonAluno.nome = jsonResultSearch.docs[0].nome; jsonAluno.sobrenome = jsonResultSearch.docs[0].sobrenome; jsonAluno.cidade = jsonResultSearch.docs[0].cidade; jsonAluno.dtnascimento = jsonResultSearch.docs[0].dtnascimento; jsonAluno.livrog1 = cLivroG1; jsonAluno.livroG2 = cLivroG2; jsonAluno.livros = {"g1":cLivroG1, "g2":cLivroG2}; jsonAluno._rev = jsonResultSearch.docs[0]._rev; couchRest("", "PUT", jsonResultSearch.docs[0]._id); } }, error : function(error){ alert(error.error); } }); // o retorno deverá retornar o ID e o _rev // alterar o documento e incluir as 2 colunas // livrog1 e livrog2. // enviar novamente via REST // couchrest("","PUT", ""); } } }
Java
UTF-8
2,458
2.375
2
[]
no_license
package com.example.rajan.myfirstandroidapp; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class homeactivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.home_activity); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.homemenu,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==R.id.menu1) { Toast.makeText(homeactivity.this,"menu1 clicked",Toast.LENGTH_SHORT).show(); // Intent sendtonextpage=new Intent(homeactivity.this,mytaskfragment.class); // startActivity(sendtonextpage); FragmentTransaction transaction1=getSupportFragmentManager().beginTransaction(); transaction1.addToBackStack("mytaskfragment"); transaction1.replace(R.id.container,new MyTaskFragment()).commit(); } else if(item.getItemId()== R.id.menu2) { Toast.makeText(homeactivity.this,"menu2 clicked",Toast.LENGTH_SHORT).show(); /* fragmenttwo two=new fragmenttwo(); FragmentTransaction transaction=getSupportFragmentManager().beginTransaction(); transaction.addToBackStack("two"); transaction.add(R.id.container,two).commit();*/ } else if(item.getItemId()== R.id.menu3) { /* fragmentthree three=new fragmentthree(); FragmentTransaction transaction=getSupportFragmentManager().beginTransaction(); transaction.addToBackStack("three"); transaction.add(R.id.container,three).commit();*/ } else if(item.getItemId()== R.id.menu4) { finish(); /* fragmentfour fragfour=new fragmentfour(); FragmentTransaction transaction=getSupportFragmentManager().beginTransaction(); transaction.addToBackStack("fragfour"); transaction.replace(R.id.container,fragfour).commit();*/ } return super.onOptionsItemSelected(item); } }
Python
UTF-8
274
2.78125
3
[]
no_license
from sklearn.svm import LinearSVR # 조미 체소 -> 규제 파라미터 c = 1이 가장 좋은 성능 def linear_svr(X, y, epsilon=1.5, random_state=42): linear_svr = LinearSVR(epsilon=epsilon, random_state=random_state) linear_svr.fit(X, y) return linear_svr
Java
UTF-8
4,715
2.140625
2
[]
no_license
package ite.kmitl.project.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.List; import ite.kmitl.project.R; import ite.kmitl.project.adapter.ProductAdapter; import ite.kmitl.project.adapter.StaffManageAdapter; import ite.kmitl.project.dao.ProductItemDao; import ite.kmitl.project.dao.StaffDao; /** * Created by nuuneoi on 11/16/2014. */ @SuppressWarnings("unused") public class StaffManageFragment extends Fragment { private List<StaffDao> response_data; private StaffManageAdapter dataAdapter; private RecyclerView mRecyclerView; private FirebaseDatabase firebaseDatabase; private DatabaseReference databaseReference; public StaffManageFragment() { super(); } @SuppressWarnings("unused") public static StaffManageFragment newInstance() { StaffManageFragment fragment = new StaffManageFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(savedInstanceState); if (savedInstanceState != null) onRestoreInstanceState(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_staff_manage, container, false); initInstances(rootView, savedInstanceState); return rootView; } private void init(Bundle savedInstanceState) { // Init Fragment level's variable(s) here firebaseDatabase = FirebaseDatabase.getInstance(); databaseReference = firebaseDatabase.getReference("staff"); response_data = new ArrayList<>(); } @SuppressWarnings("UnusedParameters") private void initInstances(View rootView, Bundle savedInstanceState) { // Init 'View' instance(s) with rootView.findViewById here mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false)); dataAdapter = new StaffManageAdapter(response_data); mRecyclerView.setAdapter(dataAdapter); bindingData(); } private void bindingData() { databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { StaffDao staffDao = dataSnapshot.getValue(StaffDao.class); staffDao.print(); Log.d("test_key",dataSnapshot.getKey()); staffDao.setKeyRef(dataSnapshot.getKey()); response_data.add(staffDao); dataAdapter.notifyDataSetChanged(); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } /* * Save Instance State Here */ @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Save Instance State here } /* * Restore Instance State Here */ @SuppressWarnings("UnusedParameters") private void onRestoreInstanceState(Bundle savedInstanceState) { // Restore Instance State here } }
Java
UTF-8
8,750
1.960938
2
[]
no_license
package br.com.pointstore.util; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import br.com.pointstore.Adapter.ListaDePontosAdapter; import br.com.pointstore.Adapter.Menssagem; import br.com.pointstore.Adapter.Vendas2; import br.com.pointstore.CadastrarSeusPontos; import br.com.pointstore.ListarAnunciosActivity; import br.com.pointstore.R; import br.com.pointstore.model.Pontos; import br.com.pointstore.model.Usuario; import rest.PontosService; import rest.UsuarioService; import rest.VendasService; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; /** * Created by Juan on 23/03/2017. */ public class CadastrarVendas extends AppCompatActivity { private EditText editTextQtdPontos; private EditText editTextValorPontos; private UsuarioService mUsuarioService; private Usuario usuario; private VendasService mVendasService; private PontosService mPontosService; private Vendas2 vendas2; private String idUsuario; private ArrayList<Pontos> listaDePontos = new ArrayList<Pontos>(); private Pontos pontosSelecionado= new Pontos(); private int adaptadorLayout = android.R.layout.simple_list_item_1; private TextView NomeSelecionadotextView; private Button BT_ANUNCIAR_VENDAS; private Spinner spinner; private List<String> pontos = new ArrayList<String>(); private String ponto; /**/ private ListView listViewPontos; /**/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastrar_vendas2); listViewPontos = (ListView) findViewById(R.id.listViewDePontos); //NomeSelecionadotextView = (TextView) findViewById(R.id.pontoSelecionadovenda); BT_ANUNCIAR_VENDAS = (Button)findViewById(R.id.buttonAnunciarVenda); Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://10.0.3.2") .addConverterFactory(JacksonConverterFactory.create()) .build(); pontos.add("Tipo de Ponto:"); pontos.add("Tam"); pontos.add("Gol"); spinner = (Spinner) findViewById(R.id.spinnervenda); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, pontos); ArrayAdapter<String> spinnerArrayAdapter = arrayAdapter; spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item); spinner.setAdapter(spinnerArrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View v, int posicao, long id) { //pega nome pela posição ponto = parent.getItemAtPosition(posicao).toString(); //imprime um Toast na tela com o nome que foi selecionado Snackbar.make(findViewById(R.id.buttonAnunciarVenda), ponto + " Selecionado", Snackbar.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mVendasService = retrofit.create(VendasService.class); this.usuario = (Usuario) getIntent().getSerializableExtra("user"); this.mPontosService = retrofit.create(PontosService.class); /*Recebendo por intent o ide de usuário para fazer busca*/ idUsuario = this.usuario.getIdUsuario().toString(); Call<List<Pontos>> pontosCall = mPontosService.meusPontos(idUsuario); pontosCall.enqueue(new Callback<List<Pontos>>() { @Override public void onResponse(Call<List<Pontos>> call, Response<List<Pontos>> response) { List<Pontos>novalistaDePontos = response.body(); ArrayList<Pontos> arrayListPontos = new ArrayList<>(); arrayListPontos = (ArrayList<Pontos>) response.body(); //if ((!response.isSuccessful())){ return;} /* É preciso saber que toda operação feita dentro do metodo on response, precisa ter continuidade aqui * como por exemplo, tratar evento de click, evento de cadastrar qualquer dado qu seja exbido ou carregao pelo retrofit * * Evento de botão dentre outros serão implementados dentro desse onresponse * */ /* final ArrayAdapter adaptadorListaResponse = new ArrayAdapter(CadastrarSeusPontos.this, adaptadorLayout,novalistaDePontos); */ final ListaDePontosAdapter adaptadorListaResponse = new ListaDePontosAdapter(CadastrarVendas.this, R.layout.adapter_view_pontos_layout,arrayListPontos); listViewPontos.setAdapter(adaptadorListaResponse); } @Override public void onFailure(Call<List<Pontos>> call, Throwable t) { } }); editTextQtdPontos = (EditText) findViewById(R.id.editTextQtdPontos); editTextValorPontos = (EditText) findViewById(R.id.editTextValorPontos); } public void cadastrarVendas (View v) { final Vendas2 vendas2 = new Vendas2(); vendas2.setQuantidade(editTextQtdPontos.getText().toString()); vendas2.setValor(editTextValorPontos.getText().toString()); vendas2.setTipoDePontos(ponto); vendas2.setIdUsuario(this.usuario.getIdUsuario()); //Intent cadastrarVendas = new Intent(this, ListarAnunciosActivity.class); //startActivity(cadastrarVendas); //Call<Vendas3> vendasCall = mVendasService.cadastrarVendas(vendas2); if ((editTextQtdPontos.getText().length() > 0) && ((editTextValorPontos.getText().length() > 0))) { Call<Menssagem> menssagemCall = mVendasService.msgvenda(vendas2); menssagemCall.enqueue(new Callback<Menssagem>() { @Override public void onResponse(Call<Menssagem> call, Response<Menssagem> response) { Menssagem menssagem = response.body(); if (menssagem != null ) { Context context = getApplicationContext(); Toast toast = Toast.makeText(context, " : "+menssagem.getMensagem(), Toast.LENGTH_SHORT); toast.show(); Intent cadastrarVendas = new Intent(CadastrarVendas.this, ListarAnunciosActivity.class); startActivity(cadastrarVendas); /* Context context1 = getApplicationContext(); Toast toast1 = Toast.makeText(context1, "Quantidade de pontos : "+ vendas2.getQuantidade(), Toast.LENGTH_SHORT); toast.show(); */ this.finish(); } else { Context context = getApplicationContext(); Toast toast = Toast.makeText(context, "Venda não cadastrada" , Toast.LENGTH_SHORT); toast.show(); } } private void finish() { } @Override public void onFailure(Call<Menssagem> call, Throwable t) { } }); } else { if ((editTextQtdPontos.getText().length() <= 0)) { editTextQtdPontos.setError("Quantidade de Pontos Vazio!"); } if ((editTextValorPontos.getText().length() <= 0)) { editTextValorPontos.setError("Valor Vazio!"); } } } public void cadastrarSeusPontos(View view) { Intent cadastrarseuspontos = new Intent (this, CadastrarSeusPontos.class); startActivity(cadastrarseuspontos); } }
Markdown
UTF-8
3,239
2.65625
3
[]
no_license
# CTGU图书馆预约位置 本脚本实现了自动预约图书馆位置,配合定时任务,每天定时预约。 ~~后续将推出云函数版本,方便各位无服务器同学部署到云端。~~ 已推出云函数版本,可自行部署至云端! ## :memo:Updated recently **!!!每次更新后请务必重新获取并部署代码,防止影响以后预约。** ### 10.31更新公告: * 暂时解决服务器反爬虫机制问题。 * 新增微信通知,登录失败或是预约座位失败可以收到通知。 ### 11.02更新公告: * 修复云函数时区不一致的问题。 ## :sparkles:Can do what? 1.考研党不用每天在卡卡的系统里着急的选常去位置了,将脚本设置每天运行,你的位置一直属于你。 2.情侣\室友可以一起学习了,本脚本支持多线程同时抢多个邻近的位置,不用担心不在一起学习了。 3.只想要窗边的位置?备选位置满足你,脚本支持无限备选,总抢得到你要的位置! ## :rocket:How to use? ### 服务器定时任务 1.使用 `git clone https://github.com/zzzjoy-620/ctgu_book_seat.git` 克隆本项目到本地。 2.安装依赖 `pip install -r requirements.txt`。 3.修改config.py的配置,具体看注释。 4.为book_seat.py设置定时任务,具体自行百度。 ### 部署至云函数(new~) 1.[注册腾讯云函数](https://console.cloud.tencent.com/),[新建python空白函数](https://console.cloud.tencent.com/scf/list-create?rid=4&ns=default&keyword=helloworld%20%E7%A9%BA%E7%99%BD%E6%A8%A1%E6%9D%BF%E5%87%BD%E6%95%B0&python3),直接下一步。 2.配置「函数代码」。复制本项目的 [index.py](https://github.com/zzzjoy-620/ctgu_book_seat/blob/master/index.py) 文件至函数代码栏里。 ![image-20211029072424918](https://gitee.com/zzzjoy/My_Pictures/raw/master/202110290724038.png) 3.修改自己的配置。在上一步代码的末尾是相关配置,根据注释说明自行配置。 4.修改「高级配置」。将函数超时时间修改为900秒。 ![image-20211029072601406](https://gitee.com/zzzjoy/My_Pictures/raw/master/202110290726461.png) 5.配置「触发器配置」。将触发方式修改为定时触发,cron表达式为 `45 30 6 * * * *`,代表每天6:30:45运行脚本。 ![image-20211029080949163](https://gitee.com/zzzjoy/My_Pictures/raw/master/202110290809230.png) 6.部署完成,可以试试点击右边的 测试 进行测试,在左侧的 日志查询 中查看结果。 ![image-20211029073944915](https://gitee.com/zzzjoy/My_Pictures/raw/master/202110290739053.png) ## :pencil2:Others 本来想在学校的预约网址上套写一套后端项目,用来管理定时任务,通过网页就能新建和取消定时任务,这样就不用每天登录服务器\云函数改配置了,奈何技术不够,暂且写个python脚本吧,等哪天想整了再回来写。 这个项目对你有用的话,欢迎打赏我,支持用爱发电。 ![image-20211028210639165](https://gitee.com/zzzjoy/My_Pictures/raw/master/202110282106213.png) **免责声明:该项目仅用于交流学习,对使用者不负责任,请勿用于二次收费。** ## :see_no_evil:TODO **To much to do...**
Markdown
UTF-8
1,747
3.25
3
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "MIT", "OFL-1.1" ]
permissive
# Angular Style Guide Kibana is written in Angular, and uses several utility methods to make using Angular easier. ## Defining modules Angular modules are defined using a custom require module named `ui/modules`. It is used as follows: ```js const app = require('ui/modules').get('app/namespace'); ``` `app` above is a reference to an Angular module, and can be used to define controllers, providers and anything else used in Angular. While you can use this module to create/get any module with ui/modules, we generally use the "kibana" module for everything. ## Promises A more robust version of Angular's `$q` service is available as `Promise`. It can be used in the same way as `$q`, but it comes packaged with several utility methods that provide many of the same useful utilities as Bluebird. ```js app.service('CustomService', (Promise, someFunc) => { new Promise((resolve, reject) => { ... }); const promisedFunc = Promise.cast(someFunc); return Promise.resolve('value'); }); ``` ### Routes Angular routes are defined using a custom require module named `routes` that removes much of the required boilerplate. ```js import routes from 'ui/routes'; routes.when('/my/object/route/:id?', { // angular route code goes here }); ``` ## Private modules A service called `Private` is available to load any function as an angular module without needing to define it as such. It is used as follows: ```js import PrivateExternalClass from 'path/to/some/class'; app.controller('myController', function($scope, otherDeps, Private) { const ExternalClass = Private(PrivateExternalClass); ... }); ``` **Note:** Use this sparingly. Whenever possible, your modules should not be coupled to the angular application itself.
Python
UTF-8
394
3.109375
3
[]
no_license
def solution(numbers): answer = [] while len(numbers)>=1: a=numbers.pop(0) for i in range(len(numbers)): answer.append(a+numbers[i]) for k in range(len(answer)): b=answer.pop(0) for l in range(len(answer)): if(b==answer[l]): break else: answer.append(b) answer.sort() return answer
Java
UTF-8
5,675
2.359375
2
[]
no_license
package cn.lmjia.market.dealer.service; import cn.lmjia.market.core.entity.Login; import cn.lmjia.market.core.entity.MainOrder; import cn.lmjia.market.core.entity.cache.LoginRelation; import cn.lmjia.market.core.entity.deal.AgentLevel; import cn.lmjia.market.core.entity.deal.AgentSystem; import cn.lmjia.market.core.repository.cache.LoginRelationRepository; import cn.lmjia.market.core.service.SystemService; import cn.lmjia.market.core.service.cache.LoginRelationCacheService; import cn.lmjia.market.dealer.DealerServiceTest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; /** * 晋升测试 * * @author CJ */ public class PromotionServiceTest extends DealerServiceTest { private static final Log log = LogFactory.getLog(PromotionServiceTest.class); @Autowired private PromotionService promotionService; @Autowired private SystemService systemService; @Autowired private LoginRelationCacheService loginRelationCacheService; @Autowired private LoginRelationRepository loginRelationRepository; @Test public void go() { boolean debug = true; // 首先构造一个代理体系 Login agentLoginRoot = newRandomAgent(); AgentLevel agentRoot = agentService.highestAgent(agentLoginRoot); // 设置每一个级别的晋级标准 都为1-3 int[] ups = new int[systemService.systemLevel()]; for (int i = 0; i < systemService.systemLevel(); i++) { assertThat(promotionService.promotionCountForAgentLevel(i)) .isEqualTo(5); ups[i] = 2 + (debug ? 0 : random.nextInt(3)); // promotionService.updatePromotionCountForAgentLevel(i, ups[i]); } // 最早它只是一个客户 :) MainOrder firstOrder = newRandomOrderFor(agentLoginRoot, agentLoginRoot); makeOrderPay(firstOrder); makeOrderDone(firstOrder); // ok 现在需要升级了 从等级中倒过来 Login login = guideBy(agentLoginRoot); makeLoginTo(login, ups, systemService.systemLevel() - 2); // 第一步 检查所有的代理商逻辑是OK的 final AgentSystem system = agentRoot.getSystem(); agentService.healthCheck(system); // 这下是深层次了 // 41 long current = loginRelationRepository.countBySystem(system); List<LoginRelation> currentList = loginRelationRepository.findBySystem(system); loginRelationCacheService.rebuildAgentSystem(system); List<LoginRelation> allList = loginRelationRepository.findBySystem(system); log.info("临时关系比永久关系多"); showDiff(currentList, allList); log.info("永久关系比临时关系多"); showDiff(allList, currentList); assertThat(loginRelationRepository.countBySystem(system)) .isEqualTo(current); } private void showDiff(List<LoginRelation> bigOne, List<LoginRelation> lessOne) { final Comparator<LoginRelation> c = (o1, o2) -> (int) (o1.getFrom().getId() * 1000000 - o2.getFrom().getId() * 1000000 + o1.getTo().getId() * 1000 - o2.getTo().getId() * 1000 + o1.getLevel() - o2.getLevel()); ArrayList<LoginRelation> allList = new ArrayList<>(bigOne); allList.sort(c); allList.removeAll(lessOne); allList.forEach(System.out::println); } /** * 新增一个身份 是来自login推荐的 * * @param login * @return 新增的身份 */ private Login guideBy(Login login) { return loginService.newLogin(Login.class, randomMobile(), login, UUID.randomUUID().toString()); } /** * 让login成为 level 代理商 * * @param owner 下单者 * @param ups 需要数量 * @param level 目标等级 */ private void makeLoginTo(Login owner, int[] ups, int level) { if (level >= ups.length) { // 这个时候只需要成交即可 MainOrder order = newRandomOrderFor(owner, owner, randomMobile()); makeOrderPay(order); makeOrderDone(order); return; } // 如果要升级到level 得先升级到level+1 makeLoginTo(owner, ups, level + 1); // 然后邀请到足够的 同级选手 int count = ups[level] - 1; while (count-- > 0) { // 发展出来的人 Login sub = guideBy(owner); // Login sub = newRandomOrderFor(owner, owner).getCustomer().getLogin(); // 让它发展出来的人 发展到level+1等级 makeLoginTo(sub, ups, level + 1); } // 这个时候 它还没到目标等级 final AgentLevel agentLevel = agentService.highestAgent(owner); if (agentLevel != null) assertThat(agentLevel.getLevel()) .as("数量不足,应该还是无法成为" + level) .isGreaterThan(level); // 再来一个 Login sub = guideBy(owner); makeLoginTo(sub, ups, level + 1); final AgentLevel agentLevel1 = agentService.highestAgent(owner); assertThat(agentLevel1) .as("满足了条件,必然升级成为了代理商") .isNotNull(); assertThat(agentLevel1.getLevel()) .as("奖励足够,应该成为" + level) .isEqualTo(level); } }
TypeScript
UTF-8
347
2.5625
3
[]
no_license
import TokenManager, { TokenRefreshResponse } from "./TokenManager"; export default class NonRefreshingTokenManager implements TokenManager { constructor(accessTokenFunc: () => string | null); readonly getAccessToken: () => string | null; supportsRefresh: boolean; refreshAccessToken: () => Promise<TokenRefreshResponse>; }
JavaScript
UTF-8
313
2.71875
3
[]
no_license
function XHRrx() { var xhr = new XMLHttpRequest(); xhr.open("GET","http://__localhost__/user_info.html",false); xhr.send(); if( xhr.status != 200) { alert(xhr.status + ': ' + xhr.statusText); } else { var userdata = document.getElementById('userinfo'); userdata.innerHTML = xhr.responseText; } }
Java
UTF-8
1,607
1.96875
2
[]
no_license
package com.example.xiamuyao.sumtopnews.constant; /** * ================================================ * 作 者:夏沐尧 Github地址:https://github.com/XiaMuYaoDQX * 版 本:1.0 * 创建日期: 2018/11/12 * 描 述: * 修订历史: * ================================================ */ public class XConstant { /** * ui解析的xml文件路径 */ // public static String UIFILE = Environment.getExternalStorageDirectory().getPath()+"/uidump.xml"; public static String UIFILE = "/sdcard/uidump.xml"; /** * 1 东方头条详情页 */ public static int PAGETYPE = 0; /** * 东方头条主页 */ public static final String DONGFANG = "com.songheng.eastfirst.common.view.activity.MainActivity"; /** * 东方头条详情页 */ public static final String DONGFANGINFO = "com.songheng.eastfirst.business.newsdetail.view.activity.NewsDetailH5Activity"; /** * 东方头条推送Dialog */ public static final String DONGFANGPUSHDIALOG = "com.songheng.eastfirst.common.view.widget.dialog.PushDialog"; public static final String ZHONGQING = "com.weishang.wxrd.activity.MainActivity"; /** * 中青首页 */ public static final String ZHONGQINGALERT = "com.weishang.wxrd.activity.MainActivity";//com.weishang.wxrd.activity.MainActivity public static final String ZHONGQING_WEBVIEW = "com.weishang.wxrd.activity.WebViewActivity"; // 文章页面 public static final String ZHOGNQING_REDPACKET = "com.weishang.wxrd.ui.RedPacketFirstActivity";//红包页面 }
Swift
UTF-8
1,472
2.5625
3
[]
no_license
// // ViewController.swift // CallNumberApp // // Created by Yurii Vients on 8/2/17. // Copyright © 2017 Yurii Vients. All rights reserved. // import UIKit import MessageUI class ViewController: UIViewController , MFMailComposeViewControllerDelegate{ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func Call(_ sender: Any) { if let url = URL(string:"tel://1234567"), UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } @IBAction func SentMessage(_ sender: Any) { let mailCompose = MFMailComposeViewController() mailCompose.mailComposeDelegate = self mailCompose.setToRecipients(["yvients@gmail.com"]) mailCompose.setSubject("Test") mailCompose.setMessageBody("Enter the text", isHTML: false) if MFMailComposeViewController.canSendMail() { self.present(mailCompose, animated: true, completion: nil) } else { print("Error !!!") } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } }
Python
UTF-8
516
2.6875
3
[ "CC-BY-SA-4.0", "CC-BY-SA-3.0", "CC-BY-NC-SA-4.0", "Python-2.0", "Apache-2.0" ]
permissive
from typing import Optional from torch import Tensor, linspace from torch import device as torch_device def thresholds_between_min_and_max( preds: Tensor, num_thresholds: int = 100, device: Optional[torch_device] = None ) -> Tensor: return linspace(start=preds.min(), end=preds.max(), steps=num_thresholds, device=device) def thresholds_between_0_and_1(num_thresholds: int = 100, device: Optional[torch_device] = None) -> Tensor: return linspace(start=0, end=1, steps=num_thresholds, device=device)
Java
UTF-8
584
1.84375
2
[]
no_license
package ua.springboot.web.domain.user; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.web.multipart.MultipartFile; import ua.springboot.web.entity.enumeration.UserRole; @NoArgsConstructor @Getter @Setter public class EditUserRequest { private int id; private String email; private String firstName; private String lastName; private String telephone; private int age; private UserRole role; private MultipartFile file; private String oldImage; private String password; private String isActivated; }
C#
UTF-8
611
2.640625
3
[]
no_license
using Abc.Core.Entities; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace Abc.Core.DataAccess { public interface IEntityRepository<T> where T:class , IEntity,new() //Generic olacak o yüzden T. { T Get(Expression<Func<T,bool>> filter=null); //Get=Bir id ye karşılık gelen müşterinin bilgileri yani tek bir nesne çekmek için bunu kullanırız.(Parametre ile) List<T> GetList(Expression<Func<T, bool>> filter = null); void Add(T entity); void Update(T entity); void Delete(T entity); } }
Java
UTF-8
463
2.34375
2
[]
no_license
package art_gallery_simpler; class edge { Point strt; Point nd; Point cutoff = null; public edge(Point p1,Point p2) { strt = p1; nd = p2; } public edge(Point p1,Point p2,Point cut) { strt = p1; nd = p2; cutoff = cut; } Point getCutPnt() { return cutoff; } Point getEnd() { return nd; } Point getStart() { return strt; } }
JavaScript
UTF-8
439
2.84375
3
[]
no_license
// jQuery zawsze podlaczaj najpierw, dopiero ponizej podlaczaj skrypty ktore korzystaja z jquery // A tak sie podlacza ja: // <script src="/js/jquery-2.2.1.js"></script> // zeby sprawdzi czy jest jQuery, wystarczy w consol.lo wpisac doalra console.log($); // $ i obiekt jQuery TO DOKLADNIE TO SAMO !! : console.log(jQuery === $); // TRUE // UWAGA ! jQuery TO JEST FNKCJA ! I Zawsze bedziemy wywolywac ja para nawiasow ! -> jQuery()
Java
UTF-8
1,081
3.390625
3
[]
no_license
package ol.leet.Strings.ReverseInteger; public class Solution { public int reverse(int x) { if (Integer.MAX_VALUE <= x || Integer.MIN_VALUE >= x) { return 0; } int result = 0; if (Integer.MAX_VALUE / 10 >= x && Integer.MIN_VALUE / 10 <= x) { while (x != 0) { result = result * 10 + x % 10; x /= 10; } } else { int result10 = 0; while (x != 0) { int toAdd = x % 10; if ((x > 0 && Integer.MAX_VALUE / 10 < result) || (x < 0 && Integer.MIN_VALUE / 10 > result) ) { return 0; } result10 = result * 10; if ((x > 0 && Integer.MAX_VALUE - toAdd <= result10) || (x < 0 && Integer.MIN_VALUE - toAdd >= result10)) { return 0; } result = result10 + toAdd; x /= 10; } } return result; } }
SQL
UTF-8
527
3.328125
3
[]
no_license
CREATE OR REPLACE FORCE VIEW V_GETBUYORDERINFO_BY_SYMBOL AS ( SELECT SEACCTNO, SUM(RECEIVING) SERECEIVING FROM ( SELECT OD.SEACCTNO, EXECQTTY RECEIVING FROM ODMAST OD, ODTYPE TYP, SYSVAR SY WHERE OD.STSSTATUS IN ('N','C') AND OD.EXECTYPE IN ('NB', 'BC') and sy.grname='SYSTEM' and sy.varname='HOSTATUS' And OD.ACTYPE = TYP.ACTYPE --AND OD.TXDATE =(select to_date(VARVALUE,'DD/MM/YYYY') from sysvar where grname='SYSTEM' and varname='CURRDATE') ) GROUP BY SEACCTNO ) ;
C++
UTF-8
758
2.9375
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int main(){ int i,j,k,m,n,sign; int a[10]; while(cin >> a[0] >> a[1] >> a[2]){ if(a[0] <= 0 || a[1] <= 0 || a[2] <= 0){ cout << "invalid\n"; continue; } sign = 0; if(a[0] + a[1] <= a[2])sign = 1; if(a[1] + a[2] <= a[0])sign = 1; if(a[0] + a[2] <= a[1])sign = 1; if(sign == 1){ cout << "invalid\n"; continue; } sort(a,a+3); if(a[0]*a[0] + a[1]*a[1] > a[2]*a[2])cout << "acute\n"; if(a[0]*a[0] + a[1]*a[1] == a[2]*a[2])cout << "right\n"; if(a[0]*a[0] + a[1]*a[1] < a[2]*a[2])cout <<"obtuse\n"; } return 0; }
Markdown
UTF-8
646
3.15625
3
[]
no_license
Contribution Guide Lines * __NSFW images aren't allowed due to [Github Site Policy](https://docs.github.com/en/site-policy);__ * Pictures can't be related to cryptocurrency or its technologies; * Images must have descriptive file names in the following format (The file doesn't have to be "png" format, this is just an example): Name_Name_Book_Book.png * Add your images to the folder that best describes the subject matter of the book that the girl is holding. If no existing folder applies create a new one, the simpler the name, the best; * All Characters must be female presenting (either canonically female or look/act like girls).
PHP
UTF-8
1,821
2.5625
3
[]
no_license
<?php namespace Modules\finance\Entity; use core\CoreClasses\services\EntityClass; use core\CoreClasses\services\FieldInfo; use core\CoreClasses\db\dbquery; use core\CoreClasses\db\dbaccess; use core\CoreClasses\services\FieldType; /** *@author Hadi AmirNahavandi *@creationDate 1396-09-07 - 2017-11-28 18:02 *@lastUpdate 1396-09-07 - 2017-11-28 18:02 *@SweetFrameworkHelperVersion 2.014 *@SweetFrameworkVersion 1.018 */ class finance_committypeEntity extends EntityClass { public function __construct(dbaccess $DBAccessor) { $this->setDatabase(new dbquery($DBAccessor)); $this->setTableName("finance_committype"); $this->setTableTitle("finance_committype"); $this->setTitleFieldName("title"); /******** title ********/ $TitleInfo=new FieldInfo(); $TitleInfo->setTitle("title"); $this->setFieldInfo(finance_committypeEntity::$TITLE,$TitleInfo); $this->addTableField('1',finance_committypeEntity::$TITLE); /******** issuccessful ********/ $IssuccessfulInfo=new FieldInfo(); $IssuccessfulInfo->setTitle("issuccessful"); $this->setFieldInfo(finance_committypeEntity::$ISSUCCESSFUL,$IssuccessfulInfo); $this->addTableField('2',finance_committypeEntity::$ISSUCCESSFUL); } public static $TITLE="title"; /** * @return mixed */ public function getTitle(){ return $this->getField(finance_committypeEntity::$TITLE); } /** * @param mixed $Title */ public function setTitle($Title){ $this->setField(finance_committypeEntity::$TITLE,$Title); } public static $ISSUCCESSFUL="issuccessful"; /** * @return mixed */ public function getIssuccessful(){ return $this->getField(finance_committypeEntity::$ISSUCCESSFUL); } /** * @param mixed $Issuccessful */ public function setIssuccessful($Issuccessful){ $this->setField(finance_committypeEntity::$ISSUCCESSFUL,$Issuccessful); } } ?>
Python
UTF-8
2,140
4.40625
4
[]
no_license
#Previously, you wrote a class called ExerciseSession that #had three attributes: an exercise name, an intensity, and a #duration. # #Add a new method to that class called calories_burned. #calories_burned should have no parameters (besides self, as #every method in a class has). It should return an integer #representing the number of calories burned according to the #following formula: # # - If the intensity is "Low", 4 calories are burned per # minute. # - If the intensity is "Moderate", 8 calories are burned # per minute. # - If the intensity is "High", 12 calories are burned per # minute. # #You may copy your class from the previous exercise and just #add to it. #Add your code here! class ExerciseSession: def __init__(self, exercise, intensity, duration): self.exercise = exercise self.intensity = intensity self.duration = duration def get_exercise(self): return self.exercise def get_intensity(self): return self.intensity def get_duration(self): return self.duration def set_exercise(self, new_exercise): self.exercise = new_exercise def set_intensity(self, new_intensity): self.intensity = new_intensity def set_duration(self, new_duration): self.duration = new_duration #add new code def calories_burned(self): if self.intensity == "Low": self.calories = self.duration*4 elif self.intensity == "Moderate": self.calories = self.duration*8 elif self.intensity == "High": self.calories = self.duration*12 else: pass return self.calories #If your code is implemented correctly, the lines below #will run error-free. They will result in the following #output to the console: #240 #360 new_exercise = ExerciseSession("Running", "Low", 60) print(new_exercise.calories_burned()) new_exercise.set_exercise("Swimming") new_exercise.set_intensity("High") new_exercise.set_duration(30) print(new_exercise.calories_burned())
Java
UTF-8
1,292
2.265625
2
[ "MIT" ]
permissive
package dev.voidframework.core.conditionalfeature.condition; import com.typesafe.config.Config; import dev.voidframework.core.conditionalfeature.AnnotationMetadata; import java.util.Arrays; import java.util.List; /** * Indicates that the feature will only be loaded if the condition is met. The value * is retrieved from the configuration, properties or environment variables. * * @since 1.5.0 */ public class ConfigurationCondition implements Condition { @Override public boolean isEnabled(final Config configuration, final Class<?> annotatedClassType, final AnnotationMetadata annotationMetadata) { final List<String> expectedValueList = Arrays.asList(annotationMetadata.getStringArray("expectedValue")); final String[] keyArray = annotationMetadata.getStringArray("value"); for (final String key : keyArray) { final String currentValue; if (configuration.hasPath(key)) { currentValue = configuration.getString(key); } else { currentValue = System.getenv(key); } if (expectedValueList.contains(currentValue)) { return true; } } return false; } }
Java
UTF-8
1,333
3.859375
4
[]
no_license
import java.util.ArrayList; import java.util.List; //Find all possible combinations of k numbers that add up to a number n, // given that only numbers from 1 to 9 can be used and each combination // should be a unique set of numbers. // // // Example 1: // // Input: k = 3, n = 7 // // Output: // // [[1,2,4]] // // Example 2: // // Input: k = 3, n = 9 // // Output: // // [[1,2,6], [1,3,5], [2,3,4]] public class CombinationSumIII { public static List<List<Integer>> combinationSum(int k, int n) { List<List<Integer>> res = new ArrayList<>(); List<Integer> item = new ArrayList<>(); helper(res, item, k, n, 1); return res; } private static void helper(List<List<Integer>> res, List<Integer> item, int k, int n, int pos) { if (n < 0 || k < 0 || k + pos > 10) { return; } if (n == 0 && k == 0) { res.add(new ArrayList<>(item)); } for (int i = pos; i < 10; i++) { item.add(i); helper(res, item, k - 1, n - i, i + 1); item.remove(item.size() - 1); } } public static void main(String[] args) { List<List<Integer>> res = combinationSum(3, 9); // 1 2 6 | 1 3 5 | 2 3 4 System.out.println(res); } }
Java
UTF-8
611
3.6875
4
[]
no_license
/* Write a program to check whether the number is divisible by 5 & 11 or not. Input : 55 Output : 55 is divisible by 5 & 11 */ import java.util.Scanner; class Pro5{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter Number : "); int num = sc.nextInt(); if(num%5==0 && num%11==0) System.out.println(num+" is divisible by 5 & 11"); else System.out.println(num+" is NOT divisible by 5 & 11"); } }
JavaScript
UTF-8
311
3.59375
4
[]
no_license
let numbers = [5, 9, 3, 19, 70, 8, 100, 2, 35, 27]; let isOdd; let count = 0; for(let index = 0; index < numbers.length; index += 1){ if(numbers[index] % 2 !== 0){ count += 1; } } if(count === 0){ console.log('No number is odd.') }else{ console.log('Total of odd numbers = ', count); }
C++
UTF-8
783
3.3125
3
[]
no_license
#include <unistd.h> #include "nonFlyingBird.h" #include "FlyingBird.h" #include <vector> int main(){ Bird* b = new Bird("tweety"); b->canFly(); cout << b->getName() << endl; b->getLunch(2); Bird* nfb = new NonFlyingBird("Strolly"); nfb->canFly(); cout << nfb->getName() << endl; Bird* fb = new FlyingBird("floaty"); fb->canFly(); cout << fb->getName() << endl; cout << "-----------" << endl; cout << "-----------" << endl; //create a vector of Bird* vector<Bird*> v; //add to the vector v.push_back(b); v.push_back(nfb); v.push_back(fb); //iterate over the vector for(vector<Bird*>::iterator it = begin(v); it != end(v); ++it) { (*it)->canFly(); (*it)->getLunch(3); } //release memory delete b; delete nfb; delete fb; return 0; }
C++
UTF-8
3,169
3.578125
4
[]
no_license
//File Name: Assignment11Exercise02.cpp //Author: Adam Mejia //Email: adamrooski@gmail.com //Description: This program will determine clothing sizes based on height, weight and age. //Last Modified: 10/12/2014 #include <iostream> using namespace std; double hatsize(double weight_par, double height_par); double chestmod(double age_par); double chestsize(double chestmod_par, double height_par, double weight_par); double waistmod(double age_par); double waistsize(double weight_par, double waistmod_par); int main() { //DECLARE VARIABLES char ans('y'); double weight(0), height(0), age(0); //BEGIN PLAY AGAIN LOOP while(ans == 'y' || ans == 'Y') { cout << "Please enter your height (in inches):"; cin >> height; cout << "\nPlease enter your weight (in pounds):"; cin >> weight; cout << "\nPlease enter your age (in years):"; cin >> age; cout << "\n"; cout << "Your hatsize is:" << hatsize(weight, height) << "\nYour jacket size is:" << chestsize(chestmod(age), height, weight) << "\nYour waist size is:" << waistsize(weight, waistmod(age)) << "\n"; //PLAY AGAIN WITH VALIDATION cout << "Would you like to run the calculations again?(Y/N)\n"; cin >> ans; while (ans != 'y' && ans != 'Y' && ans != 'n' && ans != 'N') { cout << "I'm sorry I don't understand.\nWould you like to run the calculations again?(Y/N)\n"; cin >> ans; } } return 0; } double hatsize(double weight_par, double height_par) { const double hatconst(2.9); return ((weight_par/height_par)*hatconst); } double chestmod(double age_par) { double modifier(0); double age; age = age_par; if(age_par >= 40) { for(age; age >=40; age = age - 10) { modifier += .125; } return modifier; } else { return 0; } } double chestsize(double chestmod_par, double height_par, double weight_par) { const double chestconst(288); return (((height_par*weight_par)/chestconst)+chestmod_par); } double waistmod(double age_par) { double modifier(0); double age; age = age_par; if(age_par >= 30) { for(age; age >= 30; age = age - 2) { modifier += .1; } return modifier; } else { return 0; } } double waistsize(double weight_par, double waistmod_par) { const double waistconst(5.7); return ((weight_par/waistconst)+waistmod_par); } //TEST RUN /* Please enter your height (in inches):70 Please enter your weight (in pounds):200 Please enter your age (in years):20 Your hatsize is:8.28571 Your jacket size is:48.6111 Your waist size is:35.0877 Would you like to run the calculations again?(Y/N) y Please enter your height (in inches):70 Please enter your weight (in pounds):200 Please enter your age (in years):60 Your hatsize is:8.28571 Your jacket size is:48.9861 Your waist size is:36.6877 Would you like to run the calculations again?(Y/N) n Press <RETURN> to close this window... */
Java
UTF-8
712
2.375
2
[]
no_license
package com.NBS.FM.ICA.business; import java.sql.*; public class GetAccessFlag{ public boolean getAccess(String user, String access) throws Exception { Connection conn = null; boolean outputFlag = false; try { conn = DBUtil.getConnection(); CallableStatement cStmt = conn.prepareCall("{? = call ftdev01.checkMeOut(?,?)}"); cStmt.registerOutParameter(1, java.sql.Types.BOOLEAN); cStmt.setString(2, user); cStmt.setString(3, access); cStmt.execute(); outputFlag = cStmt.getBoolean(1); cStmt.close(); conn.close(); } catch(SQLException ex){ DBUtil.showErrorMessage(ex); } finally{ if (conn != null) conn.close(); } return outputFlag; } }
Java
UTF-8
580
2.078125
2
[]
no_license
package com.javatechie.spring.soap.api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.javatechie.spring.soap.api.bean.LimitConfiguraion; @RestController public class LimitsConfigurationController { @Autowired public Configuration configuration; @GetMapping("/limits") public LimitConfiguraion retrieveLimitFromConfiguration() { return new LimitConfiguraion(configuration.getMinimum(),configuration.getMaximum()); } }
Java
UTF-8
2,042
2.328125
2
[]
no_license
package service; import models.User; import play.Application; import play.Logger; import play.mvc.Http.Context; import providers.MyUsernamePasswordAuthProvider; import com.amazonaws.services.opsworks.model.App; import com.feth.play.module.pa.user.AuthUser; import com.feth.play.module.pa.user.AuthUserIdentity; import com.feth.play.module.pa.providers.oauth2.facebook.FacebookAuthUser; import com.feth.play.module.pa.service.UserServicePlugin; public class MyUserServicePlugin extends UserServicePlugin { public MyUserServicePlugin(final Application app) { super(app); } @Override public Object save(final AuthUser authUser) { final boolean isLinked = User.existsByAuthUserIdentity(authUser); if (!isLinked) { Logger.debug("MyUserServicePlugin > save"); User usr = User.create(authUser); //TODO replace this with message queue way of sending email //send welcome email if(authUser instanceof FacebookAuthUser) { MyUsernamePasswordAuthProvider prv = new MyUsernamePasswordAuthProvider(super.getApplication()); prv.sendWelcomeMessageMailing(usr, null); } return usr.id; } else { // we have this user already, so return null return null; } } @Override public Object getLocalIdentity(final AuthUserIdentity identity) { // For production: Caching might be a good idea here... // ...and dont forget to sync the cache when users get deactivated/deleted final User u = User.findByAuthUserIdentity(identity); if(u != null) { return u.id; } else { return null; } } @Override public AuthUser merge(final AuthUser newUser, final AuthUser oldUser) { if (!oldUser.equals(newUser)) { User.merge(oldUser, newUser); } return oldUser; } @Override public AuthUser link(final AuthUser oldUser, final AuthUser newUser) { User.addLinkedAccount(oldUser, newUser); return newUser; } @Override public AuthUser update(final AuthUser knownUser) { // User logged in again, bump last login date User.setLastLoginDate(knownUser); return knownUser; } }
PHP
UTF-8
1,346
2.515625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Adam * Date: 07/02/2018 * Time: 19:53 */ namespace App\Http\Controllers\News; use App\Http\Controllers\Controller; use App\News; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; class PostController extends Controller { public function __construct() { $this->middleware('auth'); } public function create(Request $request) { if($request->isMethod('post')){ $validator = Validator::make($request->all(),[ 'subject' => 'required|max:128', 'short_content' => 'required|max:1000', 'content' => 'required' ]); if ($validator->fails()) { return redirect('/news/create') ->withInput() ->withErrors($validator); } $news = new News; $news->posted_by = Auth::id(); $news->subject = $request['subject']; $news->short_content = $request['short_content']; $news->content = $request['content']; $news->save(); return redirect('news/'.$news->id); } return view('news/create'); } public function edit() { return view('news/create'); } }
TypeScript
UTF-8
478
2.6875
3
[ "MIT" ]
permissive
import {Plane} from "../plane/Plane"; import {PlaneElement} from "../plane/PlaneElement"; import {Position} from "../plane/Position"; export class Fruit { readonly planeElement: PlaneElement; private constructor(position: Position, plane: Plane) { this.planeElement = plane.getPlaneElementForPosition(position); this.planeElement.setFruit(); } static newInstance = (position: Position, plane: Plane) => new Fruit(position, plane); }
JavaScript
UTF-8
456
2.609375
3
[ "MIT" ]
permissive
// @ts-check /** * @typedef {(page:any)=>Promise<void>} PageTransformer */ module.exports = class PageTransformers { constructor() { /** @type {PageTransformer[]} */ this._all = [] } /** * @param {PageTransformer} transformer */ add(transformer) { this._all.push(transformer) } /** * @param {any} page */ async transform(page) { for(const transformer of this._all) { await transformer(page) } } }
Java
UTF-8
4,038
2.421875
2
[]
no_license
package com.library.view; import com.library.controller.LibraryController; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.JTextField; import com.library.model.domain.AvailableItems; import com.library.model.domain.Book; import com.library.model.domain.CD; import com.library.model.domain.Movie; import com.library.view.Utils; import com.library.view.MainJFrame; public class RentItemsJFrameController { public MainJFrame libraryJFrame; public RentItemsJFrame rentalJFrame; /** Creates a new instance of RentItemsJFrameController */ public RentItemsJFrameController() { } /* * Copy constructor */ public RentItemsJFrameController (RentItemsJFrame rentalJFrame, MainJFrame libraryJFrame) { this.rentalJFrame = rentalJFrame; //add all the action listeners here libraryJFrame.getButtonRent().addActionListener((ActionListener) this); rentalJFrame.getCatalogNumberText().addActionListener((ActionListener) this); rentalJFrame.getButtonRentScreen().addActionListener((ActionListener) this); Utils.centerWindow(libraryJFrame); libraryJFrame.setVisible(true); } /* * (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) throws FileNotFoundException, ClassNotFoundException, IOException { System.out.println ("Inside RentalJFrameController::actionPerformed"); if (event.getSource().equals(libraryJFrame.getButtonRent())) { getRentalStatus_actionPerformed(event, rentalJFrame.getCatalogNumberText().getText(), rentalJFrame.getResultsTextField()); } else if (event.getSource().equals(rentalJFrame.getButtonBackToSearch())) { getSearchPage_actionPerformed(event); } else if (event.getSource().equals(rentalJFrame.getButtonRentScreen())) { getRentalStatus_actionPerformed(event, rentalJFrame.getCatalogNumberText().getText(), rentalJFrame.getResultsTextField()); } } public void getRentalStatus_actionPerformed(ActionEvent event, String text, JTextField jResultsTextField) throws FileNotFoundException, ClassNotFoundException, IOException { //jResultsTextField.setText("Clicked Rent"); System.out.println("Inside getRentalStatus_actionPerformed"); performRentOperation(text, jResultsTextField); } private void performRentOperation(String text, JTextField jResultsTextField) throws FileNotFoundException, IOException, ClassNotFoundException { //SearchItemsManager searchItemsManager; //RentItemsManager rentItemsManager; AvailableItems availableItems = new AvailableItems(); boolean rentSuccess = false; String catNum = text; //searchItemsManager = SearchItemsManager.getInstance(); //rentItemsManager = RentItemsManager.getInstance(); //LibraryJDBCDaoImpl jdbcDB = new LibraryJDBCDaoImpl(); //LibraryHibernateDaoImpl dbConnection = new LibraryHibernateDaoImpl(); LibraryController libController = new LibraryController(); //availableItems = dbConnection.getAvailableItems(); rentSuccess = libController.performActionRent("Rent", availableItems, catNum); if (rentSuccess == true) { jResultsTextField.setText("Rent Successful, Catalog Number: " + text); } else { jResultsTextField.setText("Rent Unsuccessful, Item may be invalid or not available"); } } public void getRentalPage_actionPerformed(ActionEvent actionEvent, String string, JTextField jResultsTextField) throws FileNotFoundException, IOException, ClassNotFoundException { new RentItemsJFrame().setVisible(true); } //end getSearchItems_actionPerformed public void getSearchPage_actionPerformed(ActionEvent actionEvent) { System.out.println("Back to Search Page"); new MainJFrame().setVisible(true); } }
C++
UTF-8
2,284
3.8125
4
[]
no_license
#include <iostream> #include <cstdlib> #include <ctime> #include <string> void determineWinner(int, int); int getPlayerChoice(int); int getComputerChoice(int); int main() { int computerChoice; int playerChoice; char playAgain = 'y'; while(playAgain == 'y') { playerChoice = getPlayerChoice(playerChoice); computerChoice = getComputerChoice(computerChoice); determineWinner(playerChoice, computerChoice); std::cout << "Do you want to play again? y/n\n"; std::cin >> playAgain; std::cout << "\033[H\033[2J\033[3J"; if (playAgain == 'n') { break; } } return 0; } void determineWinner(int playerChoice, int computerChoice) { if (playerChoice == computerChoice) { std::cout << "Draw!\n"; } else if (playerChoice == 1 && computerChoice == 3) { std::cout << "You win!\n"; } else if (playerChoice == 2 && computerChoice == 1) { std::cout << "You win!\n"; } else if (playerChoice == 3 && computerChoice == 2) { std::cout << "You win!\n"; } else { std::cout << "Computer Wins!\n"; } } int getPlayerChoice(int playerChoice) { std::cout << "\tWelcome to Rock, Paper Scissors!\n\n"; std::cout << "---Game Menu---\n"; std::cout << "1) Rock\n"; std::cout << "2) Paper\n"; std::cout << "3) Scissors\n"; std::cout << "Choose Wisely: \n"; std::cin >> playerChoice; std::cout << "You chose:\n"; switch(playerChoice) { case 1: // rock std::cout << "Rock\n\n"; break; case 2: // paper std::cout << "Paper\n\n"; break; case 3: // scissors std::cout << "Scissors\n\n"; break; default: std::cout << "Invalid Option\n\n"; } return playerChoice; } int getComputerChoice(int computerChoice) { // initialize seed generator srand (time(NULL)); computerChoice = rand() % 3 + 1; std::cout << "Computer chose:\n"; switch(computerChoice) { case 1: std::cout << "Rock\n\n"; break; case 2: // paper std::cout << "Paper\n\n"; break; case 3: // scissors std::cout << "Scissors\n\n"; break; default: std::cout << "Invalid Option\n\n"; } return computerChoice; }
Java
UTF-8
3,543
2.421875
2
[]
no_license
package com.example.jarry.persell.Adapter; import android.app.Activity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.jarry.persell.Entity.MessageChat; import com.example.jarry.persell.R; import com.example.jarry.persell.Util.DateToString; import com.facebook.login.widget.ProfilePictureView; import java.util.ArrayList; /** * Created by Jarry on 4/3/2016. */ public class MessagingAdapter extends BaseAdapter { private ArrayList<MessageChat> messageChats; private LayoutInflater mInflater; private String userid,ownerName,username; public MessagingAdapter(Activity activity,String userid,ArrayList<MessageChat> messageChats,String username,String ownerName) { mInflater = activity.getLayoutInflater(); this.messageChats = messageChats; this.userid=userid; this.username=username; this.ownerName=ownerName; } public void addMessage(MessageChat message,int direction) { if(direction==1){ if(messageChats.size()!=0){ if(checkSimilar(message)){ messageChats.add(message); notifyDataSetChanged(); } }else{ messageChats.add(message); notifyDataSetChanged(); }} else if(direction==0){ messageChats.add(message); notifyDataSetChanged(); } } public Boolean checkSimilar(MessageChat message){ for(int i=0;i<messageChats.size();i++){ if(messageChats.get(i).getUserID().equals(message.getUserID()) && messageChats.get(i).getMessage().equals(message.getMessage()) && messageChats.get(i).getDate().equals(message.getDate())){ return false; } } return true; } public void addMessages(ArrayList<MessageChat> messages) { messageChats=messages; } @Override public int getCount() { return messageChats.size(); } @Override public Object getItem(int i) { return messageChats.get(i); } @Override public long getItemId(int i) { return 0; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(int i, View convertView, ViewGroup viewGroup) { MessageChat msg = messageChats.get(i); String name=""; int res = 0; if (msg.getUserID().equals(userid)){ res = R.layout.message_right; name=username; } else{ res = R.layout.message_left; name=ownerName; } convertView = mInflater.inflate(res, viewGroup, false); DateToString date=new DateToString(); ProfilePictureView profilePictureView=(ProfilePictureView)convertView.findViewById(R.id.imageUser); profilePictureView.setProfileId(userid); TextView txtMessage = (TextView) convertView.findViewById(R.id.txtMessage); TextView txtDate = (TextView) convertView.findViewById(R.id.txtDate); TextView tvName=(TextView)convertView.findViewById(R.id.tvName); profilePictureView.setProfileId(msg.getUserID()); tvName.setText(name); txtMessage.setText(msg.getMessage()); txtDate.setText(" "+date.string2Time(msg.getDate())+" "); return convertView; } }
Python
UTF-8
663
2.671875
3
[]
no_license
import net from control import Control # ESP32 pinouts PIN_X = 35 # blue PIN_Y = 34 # violet PIN_SW = 32 # green wlan = net.connect_wifi() ctrl = Control() ctrl.setup_joy(PIN_X, PIN_Y, PIN_SW) counter = 0 while True: print('Awaiting connection to socket') connection = net.connect_socket() if not connection: continue print('Socket connected, awaiting commands') while True: ctrl.read_joy() # print("Seding on server " + str(ctrl)) response = net.send_command(connection, str(ctrl)) if not response: print('No response or socket error') break print(response)
Python
UTF-8
159
3.484375
3
[]
no_license
def transit(f): c = 5 / 9 * (f - 32) print(round(c, 2), end = ' ') def printtable(): for i in range(0, 300, 20): transit(i) printtable()
C#
UTF-8
1,173
3.671875
4
[]
no_license
namespace certificacao_csharp_roteiro.Aula_2___tipos_de_referencia._1___Tipos_de_Referencia { class TiposDeReferencia : IAulaItem { public void Executar() { var cliente1 = new Cliente("José", 32); //conceito de ponteiros >>> var cliente2 = cliente1; //não faz uma cópia independente, faz uma referencia a um objeto que está em outro lugar da memória System.Console.WriteLine($"cliente1: {cliente1}"); System.Console.WriteLine($"cliente2: {cliente2}"); cliente1.Nome = "Maria"; //como cliente2 é um tipo de referencia, irá ser alterado tbm cliente1.Idade = 29; System.Console.WriteLine($"cliente1: {cliente1}"); System.Console.WriteLine($"cliente2: {cliente2}"); } } class Cliente { public Cliente(string nome, int idade) { Nome = nome; Idade = idade; } public string Nome { get; set; } public int Idade { get; set; } public override string ToString() { return $"Nome: {Nome}, Idade: {Idade}"; } } }
Markdown
UTF-8
1,344
2.953125
3
[ "MIT" ]
permissive
## English words today: 2018-07-17 | English Words | Word's property | Chinese description | | :-----------: | :-------------: | :-----------------: | | crass | adj. | 粗鲁的 | | dazzle | v. | 使…目眩, 使...惊叹 | | demonstrable | adj. | 可证明的 | | designate | adj. | 指定的, 选定的 | | digress | v. | 偏题, 跑题 | | discontinue | v. | 终止 | | distress | v. | 使......紧张, 忧虑, 不适 | | forthcoming | adj. | 直白的 | | genteel | adj. | 有教养的, 彬彬有礼的 | | glamorous | adj. | 有吸引力的 | | hedge | n. | 故意模棱两可不绝对的言论 | | impersonal | adj. | 没有人情味的 | | insufferable | adj. | 无法忍受的 | | lurid | adj. | 令人震惊的, 耸人听闻的 | | malign | adj. | 邪恶的, 恶毒的 | | multifarious | adj. | 各种各样的 | | necessitate | v. | 使成为必要 | | offhand | adj. | 即时的;未经准备的 | | omnipresent | adj. | 处处都有的 | | oppressive | adj. | 压迫的 | | ostensible | adj. | 表面的, 虚假的 | | ostentatious | adj. | 炫耀的 | | panegyric | n. | 赞文, 赞美 | | pathetic | adj. | 可怜的 | | perfidious | adj. | 不可信赖的 | | pillory | v. | 批评 | | pine | v. | 渴望 | | ponder | v. | 沉思, 仔细思考 | | quintessential | adj. | 精华的, 典型的 | | rationale | n. | 理由 |
Java
UTF-8
233
1.945313
2
[]
no_license
package com.socialinspectors.utils.messages; public enum MessageProperties { HEADER { @Override public String toString() { return "header"; } }, BODY { @Override public String toString() { return "body"; } } }
Python
UTF-8
3,363
2.734375
3
[]
no_license
import face_recognition import cv2 import array VIDEO_DIR = "test.mp4" #视频的路径 TRACKING_FACE_DIR = ["face1.jpg" ,"face2.jpg","face3.jpg", "face4.jpg", "face5.jpg", "face6.jpg"] #在这里输入识别的脸的图片 TRACKING_FACE_LABEL = ["Sheldon", "Leonard", "Penny", "Howard", "Rajesh", "Amy"] #在这里输入识别的脸的名称 VIDEO_SCALE = 1 #视频识别时的缩放倍数 FRAMES_READ = 1 #每次读取帧数的间隔 UNKNOWN_NAME = "Unknown" capture = cv2.VideoCapture(VIDEO_DIR) #数字0是调用摄像头 ''' 以下是将检测结果写入视频 ''' #获得码率及尺寸 fps = capture.get(cv2.CAP_PROP_FPS) size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) #size = (704, 576) videoWriter = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), fps, size) ''' 以上是将检测结果写入视频 ''' tracking_image_encodings = [] for face_dir in TRACKING_FACE_DIR: tracking_image = face_recognition.load_image_file(face_dir) #此处输入跟踪的脸部目标 tracking_image_encodings.append(face_recognition.face_encodings(tracking_image)[0]) #对变量初始化 face_locations = [] face_encodings = [] face_labels = [] do_this_frame = True while True: #对帧的抓取 for i in range(FRAMES_READ): ret, frame = capture.read() #print(frame) #缩小所截取的帧以减少运算 cutdown_frame = cv2.resize(frame, (0, 0), fx = 1/VIDEO_SCALE, fy = 1/VIDEO_SCALE)#这里的fx,fy是缩小的倍数 #print("OKOK") if do_this_frame: face_locations = face_recognition.face_locations(cutdown_frame) face_encodings = face_recognition.face_encodings(cutdown_frame, face_locations) face_labels = [] #print("OKOK2") #for tracking_face in tracking_image_encodings: #print("OKOK3") for face_rec in face_encodings: match = face_recognition.compare_faces(tracking_image_encodings, face_rec, tolerance = 0.6) #print(match) has_match = False for if_match in match: if if_match : name = TRACKING_FACE_LABEL[match.index(if_match)] face_labels.append(name) has_match = True if not has_match: name = UNKNOWN_NAME face_labels.append(name) #index = tracking_image_encodings.index(tracking_face) #print(face_labels) do_this_frame = not do_this_frame #print(face_labels) #显示结果 for(top, right, bottom, left), name in zip(face_locations, face_labels): top *= VIDEO_SCALE right *= VIDEO_SCALE bottom *= VIDEO_SCALE left *= VIDEO_SCALE #if name != "unknown" cv2.rectangle(frame, (left, top), (right,bottom), (0,69,255), 2) #框出人脸 cv2.rectangle(frame, (left, bottom), (right, bottom + 35), (0, 59, 255), cv2.FILLED) #画出标签的底色 font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom + 29), font, 1.0, (0,255,255), 1) #标出标签 cv2.imshow('Playing...', frame) videoWriter.write(frame) #写视频帧 if cv2.waitKey(1) & 0xFF == ord('q'): break capture.release() cv2.destroyAllWindows
PHP
UTF-8
1,697
2.6875
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="styles.css" rel ="stylesheet"> <title>View Corporation Database</title> </head> <body> <?php include_once 'dbconnect.php'; $db = dbconnect(); $stmnt = $db->prepare("SELECT * from corps"); $results = array(); if ($stmnt->execute() && $stmnt->rowCount() > 0) { $results = $stmnt->fetchAll(PDO::FETCH_ASSOC); } ?> <h1> Corporations Table </h1> <table border="1" class="table table-striped"> <tr> <th class="center">Corp Name</th> <th class="center">Read</th> <th class="center">Update</th> <th class="center">Delete</th> </tr> <?php foreach ($results as $row): ?> <tr class="center"> <td class="tableLeft"><?php echo $row['corp']; ?></td> <td><a class="btn btn-primary" href = "read.php?id=<?php echo $row['id']; ?>">Read</a></td> <td><a class ="btn btn-default" href = "update.php?id=<?php echo $row['id']; ?>">Update</a></td> <td><a class="btn btn-warning" href = "delete.php?id=<?php echo $row['id']; ?>">Delete</a></td> </tr> <?php endforeach; ?> </table> <a class="btn btn-success" href="add.php">Add Corporation</a> </body> </html>
Java
UTF-8
3,983
3.359375
3
[]
no_license
package prop.domain; import prop.ErrorString; import prop.PropException; import java.util.ArrayList; /** * Class ListSet, represents a set of playlists. * @author Carles Garcia Cabot * @see List */ public class ListSet { private static final char delimiter = '\n'; private TernarySearchTree<List> lists; /* CONSTRUCTORS */ /** * ListSet default constructor. Creates a ListSet with 0 lists */ public ListSet() { lists = new TernarySearchTree<>(); } /* GETTERS */ public ArrayList<List> getLists() { return new ArrayList<>(lists.getList()); } /* OTHER METHODS */ /** * Adds a list to the set * @param list list to be added (Precondition: the list isn't already contained and is not null) */ public void add(List list) throws PropException { if (!contains(list.obtainTitle())) lists.put(list.obtainTitle(), list); else throw new PropException(ErrorString.EXISTING_LIST); } /** * Searches the list with a certain id * @param name name of the list to search (not null). The list must be contained in the ListSet * @return Returns the list */ public List getList(String name) { if (lists.contains(name)) return lists.get(name); throw new IllegalArgumentException("The list with this id isn't contained in the ListSet"); } /** * Obtains Lists whose title starts by a specific prefix * @param prefix (not null) * @return ArrayList with the lists */ public ArrayList<List> findLists(String prefix) { return lists.matchPrefix(prefix); } /** * Gets the songIndex id of the songIndex in the position {@code songIndex} of the listIndex in the position {@code listIndex} * @param listIndex the position of the listIndex * @param songIndex the position of the songIndex * @return the songIndex id */ public String[] getSongId(int listIndex, int songIndex) { Song s = lists.getList().get(listIndex).obtainSong(songIndex); String id[] = new String[2]; id[0] = s.getTitle(); id[1] = s.getArtist(); return id; } /** * Removes the list with a specific title from the set * @param name String title of the list to be removed (Precondition: the list is contained in the set and is not null) */ public void remove(String name) throws PropException { if (lists.contains(name)) { lists.remove(name); } else throw new PropException(ErrorString.UNEXISTING_LIST); } /** * Indicates if a list with this title is contained in the set * @param title string title of the list to look up (not null) * @return true if found, false otherwise */ public boolean contains(String title) { if (lists.contains(title)) return true; else return false; } /** * Indicates if a list is contained in the set * @param l list to look up (not null) * @return true if found, false otherwise */ public boolean contains(List l) { if (lists.contains(l.obtainTitle())) return true; else return false; } /** * Total duration of all the playlists in the set * @return int total time */ public int totalTime() { int time = 0; for (List l : lists.getList()) time += l.obtainTotalTime(); return time; } /** * Returns the number of lists contained in the set * @return int size */ public int size() { return lists.getSize(); } /** * Removes ALL lists from the set */ public void clear() { lists = new TernarySearchTree<>(); } @Override public String toString() { String s = ""; s += String.valueOf(lists.getSize()) + delimiter; for (List l : lists.getList()) { s += l.toString() + delimiter; } return s; } }
SQL
UTF-8
318
2.53125
3
[]
no_license
create or replace view dm_AccountBudgets_attr as select _sys_transform_id, TenantId, AccountBudgetAttrId, IncorrectScenarioId, ScenarioId, AccountBudgetId from out_AccountBudgets_attr where _sys_transform_id = (select max(id) from _sys_transform_id where ts_end is not null and entity = 'dm_AccountBudgets_attr');
Markdown
UTF-8
737
2.578125
3
[ "MIT" ]
permissive
--- title: "Формування грудей" --- ![Формування грудей](chestshaping.svg) Вертикальна величина, яку потрібно розрізати & розсунути верхню частину передньої панелі, щоб надати форму грудей, як фактор обхвату грудей. ## Вплив цієї опції на шаблон ![На цьому зображенні показано вплив цієї опції шляхом накладання декількох варіантів, які мають різне значення для цієї опції](jaeger_chestshaping_sample.svg "Вплив цієї опції на шаблон")
C#
UTF-8
4,824
2.71875
3
[]
no_license
using Fenogeno.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace Fenogeno.DataAccess { public class ComentarioDAO { public void Inserir(Comentario obj) { using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Db"].ConnectionString)) { string strSQL = @"INSERT INTO COMENTARIO (ID_NOTICIA , ID_USUARIO,TEXTO) VALUES (@ID_NOTICIA, @ID_USUARIO, @TEXTO);"; using (SqlCommand cmd = new SqlCommand(strSQL)) { cmd.Connection = conn; cmd.Parameters.Add("@ID_NOTICIA", SqlDbType.Int).Value = obj.Noticia.Cod; cmd.Parameters.Add("@ID_USUARIO", SqlDbType.Int).Value = obj.Usuario.Id; cmd.Parameters.Add("@TEXTO", SqlDbType.VarChar).Value = obj.Texto; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } } public List<Comentario> BuscarTodos() { var lstComentarios = new List<Comentario>(); using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Db"].ConnectionString)) { string strSQL = @"SELECT * FROM COMENTARIO;"; using (SqlCommand cmd = new SqlCommand(strSQL)) { conn.Open(); cmd.Connection = conn; cmd.CommandText = strSQL; var dataReader = cmd.ExecuteReader(); var dt = new DataTable(); dt.Load(dataReader); conn.Close(); foreach (DataRow row in dt.Rows) { var comentario = new Comentario() { Id = Convert.ToInt32(row["ID"]), Noticia = new Noticia() { Cod = Convert.ToInt32(row["ID_NOTICIA"]), }, Usuario = new Usuario() { Id = Convert.ToInt32(row["ID_USUARIO"]), }, DataHora = Convert.ToDateTime(row["DATAHORA"]), Texto = row["TEXTO"].ToString() }; lstComentarios.Add(comentario); } } } return lstComentarios; } public List<Comentario> BuscarPorNoticia(int codNoticia) { var lstComentarios = new List<Comentario>(); using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Db"].ConnectionString)) { string strSQL = @"SELECT C.*, U.NOME AS NOME_USUARIO FROM COMENTARIO C INNER JOIN USUARIO U ON (U.ID = C.ID_USUARIO) WHERE C.ID_NOTICIA = @ID_NOTICIA;"; using (SqlCommand cmd = new SqlCommand(strSQL)) { conn.Open(); cmd.Connection = conn; cmd.Parameters.Add("@ID_NOTICIA", SqlDbType.Int).Value = codNoticia; cmd.CommandText = strSQL; var dataReader = cmd.ExecuteReader(); var dt = new DataTable(); dt.Load(dataReader); conn.Close(); foreach (DataRow row in dt.Rows) { var comentario = new Comentario() { Id = Convert.ToInt32(row["ID"]), Noticia = new Noticia() { Cod = Convert.ToInt32(row["ID_NOTICIA"]), }, Usuario = new Usuario() { Id = Convert.ToInt32(row["ID_USUARIO"]), Nome = row["NOME_USUARIO"].ToString() }, DataHora = Convert.ToDateTime(row["DATAHORA"]), Texto = row["TEXTO"].ToString() }; lstComentarios.Add(comentario); } } } return lstComentarios; } } }
Markdown
UTF-8
7,027
2.625
3
[ "CC-BY-4.0" ]
permissive
# 【金刚经浅尝】第十三章 修炼佛法 {% file src=".gitbook/assets/jin-gang-jing-13.m4a" %} (点击👆文件,打开新的页面,然后点`观看` 进行收听\) ![](https://mmbiz.qpic.cn/mmbiz_png/xws7d9qricCbwIak0wqdMQYFVKKnBFNCiaB9FbCf9icN50hflrFdU7LsnicwlBzLVlzXMNFl7Gky6rk96KQUf1iaVxw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1) 金刚经至此都在用各种方式告诉我们,成长、修行的精髓是不可住于相、要做到一切不住。**修行的第一法门是布施(利他)**,而利他也有深浅之分,财布施是非常了不起的,以身布施(愿意牺牲自己的性命去利他)更是难得,但这些全都比不上自己了悟了金刚经(其实是了悟了生命真谛、大彻大悟)并受持讲解给他人、度化他人来的福德大 - 这是所谓法布施。接下来我们一句一句的讲解。   **【尔时,须菩提白佛言:世尊,当何名此经?我等云何奉持?佛告须菩提:是经名为金刚般若波罗密,以是名字,汝当奉持。】** 译文:此时,须菩提问佛陀说:佛陀,你至此讲的法,我们把它编辑成经书,应该如何取名呢?我们又应该如何恭敬护持它呢?佛陀告诉须菩提说:这本经就叫“金刚般若波罗密经”,这个名称包含了整本经书的义理,你们可以以此信奉受持。   **【所以者何?须菩提,佛说般若波罗密,即非般若波罗密,是名般若波罗密。】** 译文:这是为什么呢?须菩提,佛陀所说的金刚般若波罗密法并没有定法,并非真的有一个般若波罗密可以得取,这只是一个名字用来度化众人而已。 **佛法是没有定法的,没有固定的形式。**学习西藏密宗非得吃荤,学习某些教又非得吃素,学习别的派系又开始不吃猪肉,这些拘于形式的所谓的“修行”,都并非究竟真正能够获取大智慧的方式。真正的提升智慧、修行,是不可以执着一法为佛法,不可以执着一法为开悟法的。 **我们可以用有形的方式方法入门,但要出师就得不住于相**,能在平凡、平淡的事事、人人、时时悟到大智慧。 我们往往是通过人生重大的转折、打击、痛苦、烦恼等等的经历,受到了“改变”的刺激,而开始有意识地成长、扩展自己的意识、提升自己的智慧去重新认识生命的本质和真谛。很多时候打开了这扇门之后,**更多的成长是在平凡的一点一滴,在与人的一个互动,自己的一个念头里,生活中平凡的小事中获得智慧。** **【须菩提,于意云何?如来有所说法不?须菩提白佛言:世尊,如来无所说。须菩提,于意云何?三千大千世界所有微尘,是为多不?须菩提言:甚多,世尊。】** 译文:须菩提,你觉得怎么样?我有说佛法吗?须菩提回答佛陀说:佛陀,据我了解您并没有说佛法。须菩提,你觉得怎么样,三千大千世界里所有的微尘加在一起,多不多?须菩提回答说:那是非常多的,佛陀。 [第十一章](jin-gang-jing-qian-chang-di-shi-yi-zhang-wu-wei-fu-gao-yu-yi-qie.md)解释过三千大千世界。佛陀的世界观里有三千大千世界一说,一千个像我们太阳系这样的叫小千世界,一千个小千世界叫中千世界,一千个中千世界,叫大千世界,三千大千世界就相当于三兆(3 Trillion)个太阳系,也是佛陀的一种比喻来说宇宙里有不可计量的世界。那今天的科学也确实证明了如此,银河系里有3000多个类似太阳系的星系,NASA的科学家说可能有一千亿(100 Billion)个类似银河系的星系,真是多如沙粒。 这个宇宙观,按照今天的科技确实可观测可证明,但最终也只是虚幻的相 - **凡所有相,皆是虚妄**。真正明白这一点是不容易的,而能够自己证得体悟这一点的更是极少数。 **【须菩提,诸微尘,如来说非微尘,是名微尘。如来说世界,非世界,是名世界。】** 译文:须菩提,一切微尘,并非真实存在,微尘只是一个暂时的名相而已。三千大千世界也是一样,并非真实存在,世界只是一个暂时的名相而已。 释迦摩尼说佛法,说的是方便法(方便大家理解的修行方法),佛法并没有一个实体存在,如果执着于佛法要这么读、那么抄写、由谁来传递等等的表相,那就是法执住相了,不可得。 佛陀讲微尘、就像电子原子一般,来讲述世界上的物质和现象是如何物化出来的,但是同样的,微尘在真理本质层面也是没有实体的 - “非微尘”,但我们借助它来描述世界、理解生命而已 - “是名微尘”。佛陀讲世界和三千大千世界的世界观亦是如此。 **【须菩提,于意云何?可以三十二相见如来不?不也,世尊。不可以三十二相得见如来。何以故?如来说三十二相,即是非相,是名三十二相。】** 译文:须菩提,你觉得怎么样?能不能通过佛的三十二种相貌特征见到佛陀吗?(须菩提回答说:)不能够啊,佛陀。不能够用三十二种相貌特征见到佛陀。这是为什么呢?佛陀说的成佛所得的三十二相,并非无相的法身,只是用来度化众人的表象,三十二相是暂时的名相而已。 前面[第五章](jin-gang-jing-qian-chang-di-wu-zhang-ru-he-jian-dao-shi-xiang.md)佛陀也讲过,不能以三十二相见如来,“若见诸相非相,即见如来”。其实佛经上说佛有三十二相,比如“手过膝相”、“身金色相”、“身端直相”,但如果我们是用这些有形的表相来判断自己是否见到佛了,那就是住“相”了,佛/了悟真理/大彻大悟是不能用有形的方式来获得或者见到/得到的。所有的圣人都反对偶像崇拜,**我们拜的崇敬的也只是我们自己、内在的生命而已**。 如果你能看透各种表相都是虚幻相,那么你就见到佛了,你就了悟了。**世上最高的智慧,不是唯物的,是唯心的 - 心物一元。** **【须菩提,若有善男子、善女人,以恒河沙等身命布施。若复有人,于此经中乃至受持四句偈等,为他人说,其福甚多。】** 译文:须菩提,如果有善男子、善女人,用恒河沙数一般多的生命,以身布施助人,比财布施所得的福德要大得多。如果有人能够受持了悟金刚经,哪怕只是经中的四句偈语,向他人解说,那他的福德要比用恒河沙数一般多的生命去以身布施还要多得多! 钱财和生命都是凡人难以割舍的东西。所以能以财布施、或者以身布施而不住,都是非常了不起的。释迦摩尼说虽然如此,但这些都比不上法布施,自度然后度他,自悟然后悟他,这是最大的福德。
Python
UTF-8
905
2.53125
3
[]
no_license
from numpy import * import scipy.weave as weave from trapz import * from week0 import * JMAX =20 ORDER = 5 JMAXP = JMAX+1 K=5 def romberg(func, a, b,full = False,EPS = 1e-6): s = linspace(0.0,0.0,JMAXP) h = linspace(0.0,0.0,JMAXP) h[0] = 1.0 y = [] dy = [] index = [] for j in range(JMAX): s[j] = trapz_custom(func,a,b,j+1,s[j]) if j>K-1: p = h[j-K:j+1] q = s[j-K:j+1] p = p[::-1] q = q[::-1] ss,dss,x = polint( array(p),array(q),array([0.0]),5) print ss,dss y.append(ss[0]) dy.append(dss[0]) index.append(j) if abs(dss)<EPS*abs(ss): if full==False: return (ss,j) else: return (ss,j,y,dy,index) s[j+1] = s[j] h[j+1] = 0.25*h[j] print "ERROR"
Java
UTF-8
401
2.078125
2
[]
no_license
package com.dcat.ReCo.vos; public class RestaurantVO { private Long restaurantId; private Long districtId; public Long getRestaurantId() { return restaurantId; } public void setRestaurantId(Long restaurantId) { this.restaurantId = restaurantId; } public Long getDistrictId() { return districtId; } public void setDistrictId(Long districtId) { this.districtId = districtId; } }
Python
UTF-8
795
2.65625
3
[]
no_license
import json import requests from rest_framework.response import Response from rest_framework.decorators import api_view from django.http import JsonResponse from .to_prod.calculate_level_new import get_level_from_raw_text # @route POST api/level/ # @access Public @api_view(['POST']) def get_level(request): # Вытаскиваем из запроса текст в переменную text text = request.data['text'] # Здесь с текстом должна совершаться магия level = get_level_from_raw_text(text) # Передамем уровень текста в переменную level #level = 'upper-intermediate_aaa' responseJson = { "level": level, "text": text } return JsonResponse(responseJson)
Shell
UTF-8
3,078
3.6875
4
[]
no_license
#! /bin/sh echo 'name:' $USERNAME echo 'host:' $HOSTNAME exit 0 ---------------------------------------------------------------------------- #! /bin/sh num1=100 num2=$num1+100 echo $num2 num3=`expr $num1 + 100` echo $num3 ---------------------------------------------------------------------------- #! /bin/sh echo "file name: $0" echo "arguments : $1, $2" echo $* exit 0 ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- [1] 점수를 매개변수로 받아서 A~F학점 출력 #gedit score.sh ***************************************** #! /bin/sh echo 점수입력 : read score if [ $score = 100 ] then echo "A학점" elif [ $score -lt 100 ] && [ $score -ge 90 ]; then echo "B학점" elif [ $score -lt 90 ] && [ $score -ge 80 ]; then echo "C학점" elif [ $score -lt 80 ] && [ $score -ge 70 ]; then echo "D학점" elif [ $score -lt 70 ] && [ $score -ge 60 ]; then echo "E학점" else echo "F학점" fi exit 0 ***************************************** [2] 점수를 매개변수로 받아서 A~F 학점 출력 #gedit score2.sh ***************************************** #! /bin/sh echo 점수입력 : read score2 case $score2 in 100|9?) echo "A학점";; 90|8?) echo "B학점";; 80|7?) echo "C학점";; 70|6?) echo "D학점";; *) echo "F학점";; esac exit 0 ***************************************** [3] 1~100까지의 홀수의 합과 짝수의 합 출력 #gedit sum.sh ***************************************** #! /bin/sh even=0 odd=0 for i in {1..100} do let "j=$i%2" if [ $j -eq 0 ] then even=`expr $even + $i` else odd=`expr $odd + $i` fi done echo "짝수의 합 : $even" echo "홀수의 합 : $odd" exit 0 ***************************************** [4] 1부터 10까지의 합을 출력 #gedit while.sh ***************************************** #! /bin/sh sum=0 i=1 while [ $i -le 10 ] do sum=`expr $sum + $i` su=`expr $i + 1` done echo '총합계 : '$sum exit 0 ***************************************** [5] 두 수와 연산자 입력받아 함수로 보내고 함수의 리턴값을 출력 #gedit input.sh ***************************************** #! /bin/sh add() { total=`expr $num1 + $num2` echo "$num1 + $num2 = $total" } minus() { total=`expr $num1 - $num2` echo "$num1 - $num2 = $total" } multi() { total=`expr $num1 \* $num2` echo "$num1 * $num2 = $total" } divi() { total=`expr $num1 / $num2` echo "$num1 / $num2 = $total" } echo "첫번째 숫자를 입력하세요." read num1 echo "두번째 숫자를 입력하세요." read num2 echo "연산자를 입력하세요." read operator if [ $operator == '+' ]; then add elif [ $operator == '-' ]; then minus elif [ $operator == '*' ]; then multi elif [ $operator == '/' ]; then divi else echo "잘못 입력하셨습니다." fi exit 0 *****************************************
Java
UTF-8
1,157
2.03125
2
[]
no_license
package com.example.quartz.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Date; import java.util.List; @ToString @Data @NoArgsConstructor @AllArgsConstructor public class SchedulerJob implements Serializable { private String jobId; private String jobName; private String jobGroup; /** * 任务状态 是否启动任务 */ private String jobStatus; /** * Cron 表达式 */ private String cronExpression; /** * 描述 */ private String description; /** * 任务执行时调用哪个类的方法,全限定名 */ private String beanClass; /** * 任务执行的方法名 */ private String methodName; /** * 任务是否有状态 */ private String isConcurrent; /** * spring bean */ private String springId; /** * 方法参数 */ private List<?> methodParams; private LocalDateTime createTime; private LocalDateTime updateTime; }
Java
UTF-8
404
2.640625
3
[]
no_license
package alternativemods.awl.logic; import alternativemods.awl.api.logic.AbstractLogic; /** * Author: Lordmau5 * Date: 06.03.14 * Time: 15:14 */ public class LogicLatch extends AbstractLogic { @Override public void work(boolean powered) { if(powered) setPowered(!this.isPowered()); } @Override public String getName() { return "Logic Latch"; } }
C
UTF-8
1,244
3.28125
3
[]
no_license
#include "api.h" struct arv { int chave; Arv *esq; Arv *dir; }; Arv *arv_criavazia(void) { return NULL; } Arv *insere(Arv *a, int chave) { if (busca(a, chave) != NULL) return a; if (a == NULL) { a = (Arv *)malloc(sizeof(Arv)); a->chave = chave; a->esq = a->dir = NULL; } else if (chave < a->chave) a->esq = insere(a->esq, chave); else a->dir = insere(a->dir, chave); return a; } Arv *busca(Arv *a, int chave) { if (a == NULL) return NULL; else if (a->chave > chave) return busca(a->esq, chave); else if (a->chave < chave) return busca(a->dir, chave); else return a; } static int max2(int a, int b) { return (a > b) ? a : b; } int altura(Arv *a) { if (a == NULL) return -1; else return 1 + max2((altura(a->esq)), (altura(a->dir))); } void arv_imprime(Arv *a) { printf("<"); if (a != NULL) { printf("%d", a->chave); arv_imprime(a->esq); arv_imprime(a->dir); } printf(">"); } Arv *arv_libera(Arv *a) { if (a != NULL) { arv_libera(a->esq); arv_libera(a->dir); free(a); } return NULL; }
TypeScript
UTF-8
1,653
2.578125
3
[]
no_license
import * as utils from '@modeldata/utils'; const KEY = "__after__"; export function after(proto: any, fname: string) { if (!proto[fname]) { console.warn(`找不到fname = ${fname}`); return null; } return function (target: any, name: string, desc: PropertyDescriptor) { const obj = target[KEY] = target[KEY] || {}; const arr = obj[name] = obj[name] || []; arr.push({ proto, fname }); }; } const list: any[] = []; export function handleAfter(thisArgs: any) { const target = Object.getPrototypeOf(thisArgs); if (list.indexOf(target) == -1) { updateDescriptor(target); list.push(target); } else { } } function updateDescriptor(target: any) { const obj = target[KEY] || {}; utils.forEach(obj, function (arr: any[], name: string) { const desc = Object.getOwnPropertyDescriptor(target, name); const originValue = desc.value; desc.value = function () { const _this = this; const args = Array.prototype.slice.call(arguments); const result = originValue.call(this, ...args); utils.forEach(arr, function (item: { proto: any, fname: string }) { // 因为proto[fname]对象的原始方法, 在代码装饰器处理过程中可能被修改了, 所以需要动态获取该函数 const fn = Object.getOwnPropertyDescriptor(item.proto, item.fname).value; fn.call(_this, result); }); return result; } Object.defineProperty(target, name, desc); }); }
Markdown
UTF-8
2,487
2.734375
3
[ "MIT" ]
permissive
--- title: "SpringBoot로 완성하는 URL Shortener (1)" comment: true date: 2020-04-26 categories: [Programing, Java] tags: [URL-Shortener, SpringBoot] --- ## SpringBoot로 완성하는 URL Shortener (1) #### 1. URL 주소 줄이기 , Url-Shortener란 ? 유투브나 또는 카페의 게시물을 친구에게 공유해 본 경험이 있다면 엄청난 URL 길이를 보고 놀랐던 경우가 있을 것이다. 이런 URL이 길 수 밖에 없는 원인은 URL은 페이지가 동작을 하게 만드는 많은 정보들이 같이 포함 되어 있기 때문이다. 이러한 URL을 축약 해주는 서비스들이 바로 Url Shortener라고 할 수 있다. #### 2. URL을 축약 해주는 여러 서비스들 - ~~구글 - https://goo.gle/~~ (서비스 중단) - 비틀리 - http://bitly.kr/ - Short Url - https://www.shorturl.at/ - 등 너무 많음.. #### 3. 서비스를 하는 이유 그렇다면 이들은 어떤 이유로 이런 서비스를 제공 하는지 알아 볼 필요가 있다. URL 축약 서비스는 무료료 서비스 되고 있다. URL 축약서비스의 기본적인 개념이 Url을 짧게 만들어서 서비스 주체가 되는도메인의 하위에 축약된 URL에 원래의 URL로 리다이렉트하는 기능이 주가 되기 때문에 URL을 축약하고 축약된 URL을 공유하면 공유 받은 모든 사람들이 서비스 주체가 되는 도메인의 URL을 거쳐서 원래의 페이지로 이동한다. 이러한 축약 사이트들이 위와 같은 공유 과정에서 엄청난 정보를 획득(접속/통계 등) 할수 있을 것이다. #### 4. Url Shortener 개념 알기 ![Url-Shortener-Diagram](https://user-images.githubusercontent.com/5414251/80403196-3031e800-88fa-11ea-95b6-7a6e61ed07d6.png) 위 다이어 그램과 같은 방식의 처리를 진행 - 첫번째 URL 축소하는 방법 - 실제 URL을 축소시키는 방법이 아닌 , URL을 저장하고 저장된 URL의 시퀀스를 인코딩 - URL 을 리다이렉트 하는 방법 - 도메인 하위에 빈 껍데기 HTML을 만들고 헤더에 리다이렉트 명령을 사용 #### 5.마치며.. 이번에는 UrlShortener의 개념을 알아보았습니다. 다음에는 실제 코드작성을 통한 포스팅을 하겠습니다. `Spring-boot`, `H2`, `JPA/Hibernate` 를 이용해서 만들어 보겠습니다. 먼저 코드를 확인 하실분은 [Github](https://github.com/antkdi/url-shortener) 를 확인 해주세요.
Markdown
UTF-8
689
3.640625
4
[ "CC-BY-4.0", "MIT", "LicenseRef-scancode-public-domain" ]
permissive
--- layout: exercise topic: Loops title: Basic Vector language: R --- The following code capitalizes the first letter of `pet`, puts it in a sentence, and stores it as `my_pet`: ``` pet <- "spot" pet_name <- stringr::str_to_title(pet) my_pet <- paste("My pet's name is ", pet_name, ".", sep = "") ``` Modify the code to loop over a vector of multiple pet names and print them to the screen one line at a time. Use the vector of pet names: ``` pets <- c("spot", "gigantor", "fluffy") ``` This code uses the excellent [`stringr` package](http://cran.r-project.org/web/packages/stringr/stringr.pdf) for working with the sequence data. You'll need to install this package before using it.
C++
UTF-8
1,464
2.875
3
[]
no_license
#ifndef QUATERNION_H #define QUATERNION_H // credits to https://github.com/carrino // // struct EulerAngles { double roll, pitch, yaw; }; class Quaternion { public: double a; double b; double c; double d; Quaternion() {a = 1; b = c = d = 0;} Quaternion(double x, double y, double z) {a = 0; b = x; c = y; d = z;} static const Quaternion from_euler_rotation(double x, double y, double z); static const Quaternion from_euler_rotation_approx(double x, double y, double z); Quaternion & operator=(const Quaternion &rhs) { a = rhs.a; b = rhs.b; c = rhs.c; d = rhs.d; return *this; } Quaternion & operator*=(const Quaternion &q); const Quaternion operator* (const Quaternion& q) const { return Quaternion(*this) *= q; } Quaternion & operator+=(const Quaternion &q); const Quaternion operator+(const Quaternion& q) const { return Quaternion(*this) += q; } Quaternion & operator*=(double scale); const Quaternion operator*(double scale) const { return Quaternion(*this) *= scale; } double norm() const; Quaternion & normalize(); const Quaternion conj() const; const Quaternion rotation_between_vectors(const Quaternion& v) const; double dot_product(const Quaternion& q) const; const Quaternion rotate(const Quaternion& q) const; Quaternion & fractional(double f); EulerAngles ToEulerAngles() const; }; #endif
C++
UTF-8
247
2.640625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int>a; int x; for(int i=0;i<n;i++){ cin>>x; a.push_back(x); } cout<<accumulate(a.begin(),a.end(),0)<<endl; }
Python
UTF-8
418
2.859375
3
[]
no_license
import pandas as pd from datetime import date,timedelta dates=list() link = "https://us.trend-calendar.com/trend/{}.html" today = date.today() today = today - timedelta(days=1) number_of_days = 30 for _ in range(number_of_days): dates.append(link.format(today)) today = today - timedelta(days=1) temp = { 'input':dates } df = pd.DataFrame(temp, columns=['input']) df.to_csv("input_links.csv",index=False)
Java
UTF-8
1,385
3.5
4
[]
no_license
package letters; /** * Class which defines a ThanksLetter which is sent when an inhabitant receives * a PromissaryNote * * @author Thomas OSTROWSKI * */ public class ThanksLetter extends Letter<Content> { /** * Constructor of the ThanksLetter which is initialized with the * PromissaryNote given in parameters * * @param promissaryNote * PromissaryNote that will trigger the sending of the * ThanksLetter */ public ThanksLetter(PromissaryNote promissaryNote) { super(promissaryNote.getSender(), promissaryNote.getReceiver(), promissaryNote.getContent()); } public double getCost() { return 1; } public void doAction() { }; public String getType() { return "thanks letter"; } public String toString() { String s = ""; Text thksText = new Text( "thanks for a promissary note letter whose content is a money content(" + super.c.toString() + ")"); super.c = thksText; s += "-> " + this.receiver.getName() + " mails a " + this.getType() + " which is a simple letter whose content is a text content (" + thksText + ") to " + this.sender.getName() + " for a cost of " + this.getCost() + " euro"; s += "\n\t-" + this.getCost() + " euro is debited from " + this.receiver.getName() + " account whose balance is now " + (receiver.getBankaccount().getAmount() - this.getCost()); return s; } }
C++
UTF-8
2,040
3.296875
3
[]
no_license
#include <math.h> #include "Line2D.h" #define TOLERANCE_LINE2D 1e-6 // had to reduce tolerance from 1e-8 float Line2D::getLength(Point2D startPoint, Point2D endPoint) { return getLength(startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); } float Line2D::getLength(float startX, float startY, float endX, float endY) { return sqrtf((startX - endX) * (startX - endX) + (startY - endY) * (startY - endY)); } Point2D Line2D::getIntersection(Point2D start1, Point2D end1, Point2D start2, Point2D end2) { float x1 = start1.X, y1 = start1.Y; float x2 = end1.X, y2 = end1.Y; float x3 = start2.X, y3 = start2.Y; float x4 = end2.X, y4 = end2.Y; float pX, pY; float denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (fabs(denominator) < TOLERANCE_LINE2D) return { -INFINITY, -INFINITY }; // lines are parallel else { pX = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / denominator; pY = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / denominator; return { pX, pY }; } } bool Line2D::isbetween(Point2D pointA, Point2D pointB, Point2D pointC) { float lengthAB = getLength(pointA, pointB); float lengthAC = getLength(pointA, pointC); float lengthBC = getLength(pointB, pointC); return fabs(lengthAB + lengthBC - lengthAC) < TOLERANCE_LINE2D; } Point2D Line2D::getTrueIntersection(Point2D start1, Point2D end1, Point2D start2, Point2D end2) { Point2D generalIntersect = getIntersection(start1, end1, start2, end2); if (generalIntersect.X == -INFINITY && generalIntersect.Y == -INFINITY) return generalIntersect; else { bool check1 = isbetween(start1, generalIntersect, end1); bool check2 = isbetween(start2, generalIntersect, end2); if (isbetween(start1, generalIntersect, end1) && isbetween(start2, generalIntersect, end2)) return generalIntersect; // intersection is on both segments else return { -INFINITY, -INFINITY }; // intersection not on segments } }
Java
UTF-8
1,408
3.875
4
[]
no_license
package com.cert.string; import java.util.Objects; /** * Created by sridhar on 12/4/16. */ public class Equality { public static void runTest1() { String Str1 = new String("This is really not immutable!!"); String Str2 = Str1; String Str3 = new String("This is really not immutable!!"); boolean retVal; retVal = Str1.equals( Str2 ); System.out.println("Returned Value = " + retVal); retVal = Str1.equals( Str3 ); System.out.println("Returned Value = " + retVal); System.out.println(Str1 == Str3); //false // These two have the same value System.out.println(new String("test").equals("test")); // --> true // ... but they are not the same object System.out.println(new String("test") == "test"); // --> false // ... neither are these System.out.println(new String("test") == new String("test")); // --> false // ... but these are because literals are interned by // the compiler and thus refer to the same object System.out.println("test" == "test"); // --> true // ... but you should really just call Objects.equals() System.out.println(Objects.equals("test", new String("test"))); // --> true System.out.println(Objects.equals(null, "test")); // --> false } public static void main(String[] args) { Equality.runTest1(); } }
Go
UTF-8
356
2.765625
3
[]
no_license
package stand import ( "fmt" "os" ) func RequireEnv(key string) string { value, ok := os.LookupEnv(key) if !ok { panic(fmt.Sprintf("environment variable %s is required but was not found", key)) } return value } func DefaultEnv(key, defaultValue string) string { value, ok := os.LookupEnv(key) if !ok { return defaultValue } return value }
JavaScript
UTF-8
343
3.078125
3
[]
no_license
function Sum(...params){ const sumParams = params.reduce((a,b) => a + b); console.log(sumParams); } function Mult(valorToMult, ...rest){ const multNumbers = rest.map(value => (value * valorToMult)); const sumMultNumbers = multNumbers.reduce((a,b) => a + b); console.log(sumMultNumbers); } module.exports = {Sum, Mult};
Python
UTF-8
2,654
2.75
3
[]
no_license
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from os import listdir from sklearn.decomposition import * from sklearn.manifold import LocallyLinearEmbedding def printLoss(): loss = np.load("loss_64.npy") epoch = [x*10 for x in range(1,101)] print(epoch) fig,ax = plt.subplots() #定義一個圖像窗口 ax.plot(epoch, loss) ax.set(xlabel="epoch", ylabel="loss") plt.savefig("loss_em64.jpg") plt.show() def printScatter(id2label): article_emb_w = tf.get_variable("article_emb_w", [1816, 64], initializer=tf.random_normal_initializer(0, 0.1)) keyword_emb_w = tf.get_variable("keyword_emb_w", [4200, 64], initializer=tf.random_normal_initializer(0, 0.1)) with tf.Session() as sess: saver = tf.train.Saver() saver.restore(sess, "model1000.ckpt") artical = sess.run(article_emb_w) # PCA data = [] # for i in artical: # data.append(i.reshape(1,64)) pca = PCA(n_components=2) reduced_data_pca = pca.fit_transform(artical) print(reduced_data_pca) AIDS_X=[] AIDS_Y=[] dengue_X=[] dengue_Y=[] Ebola_X=[] Ebola_Y=[] for i in range(len(reduced_data_pca)-1): # print(artical[i]) if id2label[str(i)]=='AIDS': AIDS_X.append(reduced_data_pca[i][0]) AIDS_Y.append(reduced_data_pca[i][1]) elif id2label[str(i)]=='dengue': dengue_X.append(reduced_data_pca[i][0]) dengue_Y.append(reduced_data_pca[i][1]) else: Ebola_X.append(reduced_data_pca[i][0]) Ebola_Y.append(reduced_data_pca[i][1]) plt.scatter(AIDS_X, AIDS_Y, s=30, c='red', marker='o', alpha=0.5, label='AIDS') plt.scatter(dengue_X, dengue_Y, s=30, c='blue', marker='x', alpha=0.5, label='Dengue') plt.scatter(Ebola_X, Ebola_Y, s=30, c='green', marker='s', alpha=0.5, label='Ebola') plt.xlabel('variables x') plt.ylabel('variables y') plt.legend(loc='upper right') # 这个必须有,没有你试试看 plt.show() # 这个可以没有 def productLable(): pubmedid2id = {} pubmedid2label = {} with open("data/articleTable.txt",'r') as rf: for i in rf.readlines(): pubmedid2id[i.split()[1]] = i.split()[0] files = listdir("data/text_pre/")[1:] for f in files: pubmedid2label[f.split(".xml")[1]] = f.split(".xml")[0] id2label = {} for i in pubmedid2id: id2label[pubmedid2id[i]] = pubmedid2label[i] print(id2label) return id2label printScatter(productLable())
C++
UTF-8
465
2.703125
3
[]
no_license
#include <iostream> using namespace std; //подсчет кол-ва ребер оринтированного графа int g[100][100]; int n; int main(){ cin >> n; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cin >> g[i][j]; } } int x = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(g[i][j] == 1){ x++; } } } cout << x; }
C#
UTF-8
3,530
4.125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Write a program that can solve these tasks: //Reverses the digits of a number //Calculates the average of a sequence of integers //Solves a linear equation a * x + b = 0 //Create appropriate methods. //Provide a simple text-based menu for the user to choose which task to solve. //Validate the input data: //The decimal number should be non-negative //The sequence should not be empty //a should not be equal to 0 namespace Problem_13_Solve_tasks { class SolveTasks { static void ReverseNumber(double number) { string reversed = new string(number.ToString().Reverse().ToArray()); Console.WriteLine("The reversed number: " + reversed); } static void Average(double[] numbers) { double average = numbers.Average(); Console.WriteLine("The average of the sequence of numbers is: {0}",average); } static void LinearEquation(double a, double b) { double x = -b / a; Console.WriteLine("\"X\" = {0}",x); } static void Main() { Console.WriteLine("To reverse the digits of your number press 1.\nTo calculate the average of numbers press 2.\nTo solve a linear equation of type \"a * x + b = 0\" press 3. "); int choice = int.Parse(Console.ReadLine()); while (choice < 1 || choice > 3) { Console.WriteLine("There are only three choices!!! CHOOSE A NUMBER BETWEEN 1 AND 3!!!"); choice = int.Parse(Console.ReadLine()); } if (choice == 1) { Console.Write("Enter your number: "); double number = double.Parse(Console.ReadLine()); while (number < 0) { Console.Write("The number can't be negative!\nEnter another number: "); number = double.Parse(Console.ReadLine()); } ReverseNumber(number); } if (choice == 2) { Console.Write("Enter numbers separeted by space or comma: "); string input = Console.ReadLine(); string[] array = input.Split(new char[]{',',' '}, StringSplitOptions.RemoveEmptyEntries); double[] sequenceOfNums = new double[array.Length]; while (array.Length==0) { Console.WriteLine("The input CAN'T be empty!\nTry again: "); input = Console.ReadLine(); } for (int i = 0; i < array.Length; i++) { sequenceOfNums[i] = Convert.ToDouble(array[i]); } Average(sequenceOfNums); } if (choice == 3) { Console.Write("Enter valiue for \"a\": "); double a = double.Parse(Console.ReadLine()); while (a == 0) { Console.Write("\"A\" can't be equal to \"0\"!\nEnter another value for \"A\": "); a = double.Parse(Console.ReadLine()); } Console.Write("Enter valiue for \"b\": "); double b = double.Parse(Console.ReadLine()); LinearEquation(a, b); } } } }
C++
UTF-8
649
2.796875
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#include <iostream> #include <assert.h> #include "predicate.h" using namespace std; void Predicate::str() const { cout << *this << endl; } ostream& operator<<(ostream& os, const Predicate& p) { os << p.name; return os; } //ostream& operator<<(ostream& os, const Predicate& p) { // os << p.name << "("; // switch (p.type) { // case PERSISTENT: // os << "P,"; // break; // case ENTAILMENT: // os << "E,"; // break; // case MOVE: // os << "M,"; // break; // case FUNCTION: // os << "F,"; // break; // default: // assert(false); // } // os << p.arity << ")"; // return os; //}
Java
UTF-8
393
2.390625
2
[]
no_license
package org.practise.algorithm.leetcode.topologicalsorting; import org.testng.Assert; import org.testng.annotations.Test; public class AlienDictionaryTest { private AlienDictionary obj = new AlienDictionary(); @Test public void testAlienDictionary() { String[] words = {"wrt","wrf","er","ett","rftt"}; Assert.assertEquals(obj.alienOrder(words), "wertf"); } }
Python
UTF-8
749
4.0625
4
[]
no_license
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. #Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def func(n_1, n_2): try: n_1, n_2 = int(n_1), int(n_2) func = n_1 / n_2 except ValueError: return "Ошибка, повторите ввод" except ZeroDivisionError: return 'На ноль делить нельзя' return round(func, 4) #float(func) print(func(input('Введите первое число: '),input('Введите второе число: ')))
Python
UTF-8
956
3.328125
3
[ "MIT" ]
permissive
import RPi.GPIO as GPIO import random import time rPin =26 gPin =19 bPin =13 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(rPin, GPIO.OUT) GPIO.setup(gPin, GPIO.OUT) GPIO.setup(bPin, GPIO.OUT) GPIO.output(rPin, GPIO.LOW) GPIO.output(gPin, GPIO.LOW) GPIO.output(bPin, GPIO.LOW) red= GPIO.PWM(rPin, 100) green= GPIO.PWM(gPin, 100) blue= GPIO.PWM(bPin, 100) red.start(0) green.start(0) blue.start(0) def changeColor(r_value, g_value, b_value): red.ChangeDutyCycle(r_value) green.ChangeDutyCycle(g_value) blue.ChangeDutyCycle(b_value) r, g , b =0,0,0 while True: values = input("Enter comma separated values(RGB) : ") l = values.split(',') print(values) if len(l)==3: r, g , b = l r, g, b =int(r), int(g) , int(b) changeColor(r, g, b) elif l[0]=='exit': break else: changeColor(r, g, b) print(f'red : {r} green : {g} blue : {b}') time.sleep(0.5)
Python
UTF-8
2,115
2.625
3
[ "Apache-2.0" ]
permissive
import logging import os import sys import time import boto3 from boto3.dynamodb.conditions import Attr from utils import get_secret log = logging.getLogger('worker') aws_access_key_id, aws_secret_access_key = get_secret() out_hdlr = logging.StreamHandler(sys.stdout) out_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s')) out_hdlr.setLevel(logging.INFO) log.addHandler(out_hdlr) log.setLevel(logging.INFO) sqs = boto3.resource('sqs', region_name='eu-central-1', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) dynamodb = boto3.resource('dynamodb', region_name='eu-central-1', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) table = dynamodb.Table('stocks') queue = sqs.get_queue_by_name(QueueName='stock-of-the-day') def monitor_queue(): # Process messages by printing out body and optional author name for message in queue.receive_messages(MessageAttributeNames=['StockName', 'LogoUrl']): # Get the custom author message attribute if it was set if message.message_attributes is not None: stock_name = message.message_attributes.get('StockName').get('StringValue') logo_url = message.message_attributes.get('LogoUrl').get('StringValue') update_dynamo_item(stock_name, logo_url) # Let the queue know that the message is processed message.delete() def update_dynamo_item(stock_name, logo_url): stock_id = get_id(stock_name) table.update_item( Key={ 'stock_id': stock_id }, UpdateExpression="set logo_url = :l", ExpressionAttributeValues={ ':l': logo_url }, ReturnValues="UPDATED_NEW" ) def get_id(stock_name): filter_expression = Attr('name').eq(stock_name) response = table.scan( FilterExpression=filter_expression ) response = response['Items'][0] return response['stock_id'] while True: log.info("Checking for new messages to process ... ") monitor_queue() time.sleep(1)
JavaScript
UTF-8
1,141
2.625
3
[]
no_license
(function($, s, b){ b.lfgList.click(function(e){ var targ = e.target; if(targ.nodeName === "LI"){ /* Ping the LFG folks */ console.log(targ.id); s.emit("ping", targ.id); }; }); var pingList = $("#pinged").click(function(e){ var targ = e.target; var pongQid = ""; if(targ.nodeName === "LI"){ /* Pong the LFM dood */ pongQid = targ.getAttribute("data-qid"); s.emit("pong", pongQid); pongList.append("<li>" + pongQid + "</li>"); console.log(pongQid); }; }); var pongList = $("#ponged"); s.on("pong", function (data) { /* Only LFM peeps should get these and these are confirmation that they approve and should contact you */ console.log("pong = " + data); bus.connections[data].ponged = pongList.append('<li>' + data + '</li>'); }); s.on("ping", function (data) { /* Only LFG peeps should get these and have something happend */ console.log("ping = " + data); console.log(data); bus.connections[data.qid].pinged = pingList.append( '<li data-qid="' + data.qid + '">' + data.realm + '/' + data.name + ' = ' + data.bnEmail + '</li>' ); }); })(jQuery, socket, bus);