language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
633
2.0625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Negocios; import Datos.DProveClien; import javax.swing.table.DefaultTableModel; /** * * @author gates */ public class NProveClien { public DefaultTableModel NGetProveClien(int IdProveClien,String RazonSocial,String Opcion){ DProveClien Obj = new DProveClien(); Obj.setIdProveClien(IdProveClien); Obj.setRazonSocial(RazonSocial); Obj.setOpcion(Opcion); return Obj.DGetProveClien(Obj); } }
Markdown
UTF-8
3,100
2.734375
3
[]
no_license
# terraform-framework ### Intro The aim of this repo is to reduce the terraform boiler plate code by using modules. All hard coded values between environments are extracted out into tfvars files. The concept is to develop the terraform module once and have it deploy everywhere without changing the underline terraform codes. When a new environment is required the consumers of this repo can create a couple of tfvars files and re-used existing terraform code to build on the new environment. ### To build a new VPC on new-env-name: * Edit the file variables/envs.tf and add the following section as shown below. Note that the new-env-name label is the new terraform "workspace" (environment) you wanted to build ```hcl-terraform new-env-name = { account_id = "111111111111" account = "New Environment Description" workspace_iam_role = "arn:aws:iam::111111111111:role/administrator" region_code = "ew1" region = "eu-west-1" bucket_region = "eu-west-1" bucket = "new-env-tf-infra-state" dynamodb = "new-env-tf-infra-state-lock" } ``` * Create a file tfvars/vpc/<new-env-name>.tfvars to contain the following entries (modified the values according to meet your environment); ```hcl-terraform cidr = "10.0.0.0/16" public_subnets = ["10.0.0.0/22", "10.0.4.0/22", "10.0.8.0/22"] private_subnets = ["10.0.16.0/22", "10.0.20.0/22", "10.0.24.0/22"] database_subnets = ["10.0.32.0/22", "10.0.36.0/22", "10.0.40.0/22"] public_subnet_suffix = "public" private_subnet_suffix = "private" database_subnet_suffix = "database" enable_nat_gateway = true one_nat_gateway_per_az = true enable_dns_hostnames = true enable_dns_support = true # VPC endpoint for S3 enable_s3_endpoint = true shared_tag = "shared" ``` * Create a file tfvars/taggings/<new-env-name>.tfvars to contains the following entries: (Modified to meet you actual env) Note that this is used for consistent naming and taggings of resources. ```hcl-terraform ############################### # Variables added to aws tags # ############################### customer = "data" product = "ops" environment = "dev" cost_centre = "platform-engineering" ################################ ``` * Use the tfplan.py script to build your VPC ```bash # to display help message: .tfplan.py --help usage: tfplan.py [-h] -a ACTION [-c CICD] [-p APPROVE] Required arguments: -a ACTION, --action ACTION Terraform action:--> plan, apply, plan-destroy, or apply-destroy optional arguments: -h, --help show this help message and exit -c CICD, --cicd CICD CI mode? -p APPROVE, --approve APPROVE Auto approve? $ #to plan a module and follow the on screen prompt $ ./tfplan.py -a plan # select the account to build # select module(s) to build # follow instructions on screen ``` Similarly, follow the same concept to build the EKS, modules, etc on your new workspace <new-env-name>
Java
UTF-8
4,656
1.59375
2
[]
no_license
package com.iremote.dataprivilege.interceptorchecker; import com.iremote.common.processorstore.ClassMapper; import com.iremote.dataprivilege.admin.AdminPrivilegeChecker; import com.iremote.dataprivilege.camera.CameraModifyPrivilegeCheckerofPhoneUser; import com.iremote.dataprivilege.camera.CameraOperationPrivilegeCheckerofPhoneUser; import com.iremote.dataprivilege.cameras.CamerasModifyPrivilegeCheckerofPhoneUser; import com.iremote.dataprivilege.devicerawcommand.DeviceRawCommandModifyPrivilegeChecher; import com.iremote.dataprivilege.devicerawcommand.DeviceRawCommandOperationPrivilegeChecker; import com.iremote.dataprivilege.gateway.GatewayModifyPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.infrareddevice.InfraredDeviceModifyPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.infrareddevices.InfraredDevicesModifyPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.partition.PartitionModifyPrivilegeChecker; import com.iremote.dataprivilege.partition.PartitionOperationPrivilegeChecker; import com.iremote.dataprivilege.room.RoomModifyPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.usershare.ShareDeviceModifyPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.usershare.UserShareModifyPrivilegeChecker; import com.iremote.dataprivilege.zwavedevice.DeviceModifyPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.zwavedevice.DeviceOperationPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.zwavedevice.ZwaveDeviceModifyPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.zwavedevice.ZwaveDeviceOperationPrivilegeCheckerforPhoneUser; import com.iremote.dataprivilege.zwavedevices.ZWaveDevicesModifyPrivilegeCheckerforPhoneUser; import com.iremote.domain.PhoneUser; public class DataPrivilegeCheckerStore extends ClassMapper<IURLDataPrivilegeChecker<PhoneUser>> { private static DataPrivilegeCheckerStore instance = new DataPrivilegeCheckerStore(); protected DataPrivilegeCheckerStore() { registProcessor(makekey(DataPrivilegeType.OPERATION , "device") , DeviceOperationPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "device") , DeviceModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "sharedevice") , ShareDeviceModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "gateway") , GatewayModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "infrareddevice") , InfraredDeviceModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "infrareddevices") , InfraredDevicesModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.OPERATION , "zwavedevice") , ZwaveDeviceOperationPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "zwavedevice") , ZwaveDeviceModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "zwavedevices") , ZWaveDevicesModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "room") , RoomModifyPrivilegeCheckerforPhoneUser.class); registProcessor(makekey(DataPrivilegeType.OPERATION , "camera") , CameraOperationPrivilegeCheckerofPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "camera") , CameraModifyPrivilegeCheckerofPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "cameras") , CamerasModifyPrivilegeCheckerofPhoneUser.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "admin") , AdminPrivilegeChecker.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "usershare") , UserShareModifyPrivilegeChecker.class); registProcessor(makekey(DataPrivilegeType.OPERATION , "partition") , PartitionOperationPrivilegeChecker.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "partition") , PartitionModifyPrivilegeChecker.class); registProcessor(makekey(DataPrivilegeType.MODIFY , "devicerawcmd") , DeviceRawCommandModifyPrivilegeChecher.class); registProcessor(makekey(DataPrivilegeType.OPERATION , "devicerawcmd") , DeviceRawCommandOperationPrivilegeChecker .class); } public static DataPrivilegeCheckerStore getInstance() { return instance ; } public IURLDataPrivilegeChecker<PhoneUser> getPhoneUserPrivilgeChecker(DataPrivilegeType privlegetype , String domain) { return super.getProcessor(makekey(privlegetype , domain)) ; } private String makekey(DataPrivilegeType type , String domain) { return String.format("%s_%s", type.toString() , domain); } }
C#
UTF-8
2,922
2.890625
3
[]
no_license
using System; using System.ComponentModel; namespace LED_PI_GMTest.Modules { internal class ConcentricSinusoidLissajous : IModule { private double _step; public ConcentricSinusoidLissajous() { Scale = 100; Step = 0.1; Vertical = 3; Horizontal = 5; LissajousA = 2; LissajousB = 3; LissajousSigma = Math.PI/2; LissajousPreScale = 4; } public void Draw(ref Color[,] image) { _step += Step; for (int i = 0; i < image.GetLength(0); i++) { for (int j = 0; j < image.GetLength(1); j++) { double cx = i + .5 * Math.Sin(_step / Horizontal) - (15 * Math.Sin(LissajousA * (_step / LissajousPreScale) + LissajousSigma) + 15); double cy = j + .5 * Math.Cos(_step / Vertical) - (15 * Math.Sin(LissajousB * (_step / LissajousPreScale)) + 15); double sat = (Math.Sin(Math.Sqrt(Scale + cx * cx + cy * cy + 1) + _step) + 1) / 2; var color = new Color(sat, sat, sat); if (Invert) image[i, j] = color.Invert(); else image[i, j] = color; } } } public object GetSettings() { return this; } [Category("Sine"), Description("Sets the vertical influence of the time.")] public double Vertical { get; set; } [Category("Sine"), Description("Sets the horizontal influence of the time.")] public double Horizontal { get; set; } [Category("Sine"), Description("Sets the step withd, wich is added each frame.")] public double Step { get; set; } [Category("Sine"), Description("Controls sineoids scale.")] public double Scale { get; set; } [Category("Lissajous"), Description("Sets a parameter ofs lissajours curve (A sin(at + sigma))")] public double LissajousA { get; set; } [Category("Lissajous"), Description("Sets b parameter ofs lissajours curve (B sin(bt))")] public double LissajousB { get; set; } [Category("Lissajous"), Description("Sets sigma parameter ofs lissajours curve (A sin(at + sigma))")] public double LissajousSigma { get; set; } [Category("Lissajous"), Description("Sets the time prescale for the movement on the lissajoures curve.")] public double LissajousPreScale { get; set; } public string Name { get { return "Concentric Sinusoids Lissajous"; } } [Category("Color"), Description("Inverts the created colors") ] public bool Invert { set; get; } } }
Java
UTF-8
691
2.140625
2
[]
no_license
package eu.tsvetkov.x_empi.script; /** * @author Vadim Tsvetkov (dev@tsvetkov.eu) */ public class AppleScriptTest extends BaseScriptTest<AppleScriptOld> { @Override protected ITunesScript getLastTrackTags(String playlistName) { return new AppleScriptOld("set lastTrack to last track ofNumber playlist \"" + playlistName + "\"", script.echo("name ofNumber lastTrack & \",\" & artist ofNumber lastTrack & \",\" & album ofNumber lastTrack")); } protected String getPlaylistCountScript() { return script.echo("count ofNumber user playlists"); } @Override String getTracksCountScript() { return script.echo("count ofNumber tracks"); } }
C
UTF-8
413
2.765625
3
[]
no_license
#include <stdio.h> #include <stdint.h> // needed for uinit_XX int main(){ printf("size of two ints: %zu\n", 2*sizeof(int)); printf("size of two ints: %zu\n", sizeof(int[2])); printf("size of a double: %zu\n", sizeof(double)); printf("size of uint32_t: %ld\n", sizeof(uint32_t)); printf("size of uint64_t: %ld\n", sizeof(uint64_t)); printf("size of size_t %ld\n", sizeof(size_t)); }
Java
UTF-8
803
2.96875
3
[]
no_license
package com.somamultiplos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.Scanner; @SpringBootApplication public class SomaMultiplosApplication { public static void main(String[] args) { SpringApplication.run(SomaMultiplosApplication.class, args); SomaMultiplos somaMultiplos = new SomaMultiplos(); Scanner ler = new Scanner(System.in); System.out.printf("Informe um número:\n"); int numero = ler.nextInt(); int total = 0; total = somaMultiplos.somarMultiplos(numero,3); total += somaMultiplos.somarMultiplos(numero,5); System.out.println("A soma dos multiplos de 3 e 5 dos numeros abaixo de "+numero+" é "+ total); } }
C
UTF-8
844
3.078125
3
[]
no_license
int dayofy( int year ) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) return 366 ; else return 365 ; } int dayofm( int day , int mon , int year ) { int i , temp , sum = 0 ; for ( i = 1 ; i < mon ; i++ ) { if ( i == 2 ) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) temp = 29 ; else temp = 28 ; } else if ( i == 4 || i == 6 || i == 9 || i == 11 ) temp = 30 ; else temp = 31 ; sum += temp ; } return sum+day ; } int main () { int syear , smon , sday , eyear , emon , eday , i , j , disyear=0 , disday=0 ; cin >> syear >> smon >> sday >> eyear >> emon >> eday ; for ( i = syear ; i < eyear ; i++ ) { disyear += dayofy(i) ; } disday = dayofm( eday ,emon , eyear ) - dayofm( sday , smon ,syear ) ; cout << disyear+disday << endl ; return 0 ; }
JavaScript
UTF-8
328
2.6875
3
[]
no_license
const calc = require('./calc'); // https://hyunseob.github.io/2016/11/21/misunderstanding-about-const console.log('모듈로 분리한 후 - calc.add 함수 호출 결과 : %d', calc.add(10, 10)); const calc2 = require('./calc2'); console.log('모듈로 분리한 후 - calc2.add 함수 호출 결과 : %d', calc2.add(10, 10));
C#
UTF-8
1,359
2.890625
3
[ "Apache-2.0" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 存储所有UI的信息,并可以创建或者销毁UI /// </summary> public class UIManager { /// <summary> /// 存储所有UI信息的字典,每一个UI信息都会对应一个GameObject /// </summary> private Dictionary<UIType, GameObject> dicUI; public UIManager() { dicUI = new Dictionary<UIType, GameObject>(); } /// <summary> /// 获取一个UI对象 /// </summary> /// <param name="type"></param> /// <returns></returns> public GameObject GetSingleUI(UIType type) { GameObject parent = GameObject.Find("Canvas"); if (!parent) { Debug.LogError("Canvas不存在,请仔细查找有无这个对象"); return null; } if (dicUI.ContainsKey(type)) return dicUI[type]; GameObject ui = GameObject.Instantiate(Resources.Load<GameObject>(type.Path), parent.transform); ui.name = type.Name; return ui; } /// <summary> /// 销毁一个UI对象 /// </summary> /// <param name="type">UI信息</param> public void DestoryUI(UIType type) { if (dicUI.ContainsKey(type)) { DestoryUI(type); dicUI.Remove(type); } } }
Java
UTF-8
1,599
2.125
2
[]
no_license
package com.example.android.mygarden; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import com.example.android.mygarden.ui.MainActivity; public class PlantWidgetProvider extends AppWidgetProvider { static void updateWidget(Context context, AppWidgetManager manager,int imagRes, int id){ Intent i = new Intent(context, MainActivity.class); PendingIntent pi = PendingIntent.getActivity(context,0,i,0); RemoteViews remoteViews = new RemoteViews(context.getPackageName(),R.layout.plant_widget); remoteViews.setOnClickPendingIntent(R.id.plant_image,pi); Intent waterIntent = new Intent(context,PlantWateringService.class); waterIntent.setAction(PlantWateringService.ACTION_WATER_PLANTS); PendingIntent pIntent = PendingIntent.getService(context,0,waterIntent,PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setImageViewResource(R.id.plant_image,imagRes); remoteViews.setOnClickPendingIntent(R.id.water_image,pIntent); manager.updateAppWidget(id,remoteViews); } public static void updateWidgets(Context mcontext , AppWidgetManager manager, int imagRes, int[] ids) { for (int id :ids) updateWidget(mcontext,manager,imagRes,id); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { PlantWateringService.startUpdateWidget(context); } }
Java
UTF-8
929
1.742188
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.dvbviewer.controller.utils; import java.util.LinkedList; import java.util.List; public class ServerConsts { public static final String REC_SERVICE_URL = "http://dms-server"; public static String DMS_URL = "http://"; public static String REC_SERVICE_PROTOCOL = "http"; public static String REC_SERVICE_HOST = ""; public static String REC_SERVICE_PORT = "8089"; public static List<String> REC_SERVICE_PATH = new LinkedList<>(); public static String REC_SERVICE_USER_NAME = ""; public static String REC_SERVICE_MAC_ADDRESS = ""; public static int REC_SERVICE_WOL_PORT = 9; public static String REC_SERVICE_PASSWORD = ""; public static final String URL_FLASHSTREAM = "flashstream/stream"; public static final String URL_M3U8 = "master.m3u8"; public static final String THUMBNAILS_VIDEO_URL = "/thumbnails/video/"; }
Markdown
UTF-8
1,808
2.546875
3
[]
no_license
<a name=top></a> --- <a href=../README.md#top><l style="font-size:30px">Home</l></a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<l style="font-size:35px">Papers</l>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href=../datasets/datasets.md#top><l style="font-size:30px">Datasets</l></a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href=../metrics.md#top><l style="font-size:30px">Metrics</l></a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --- # Papers for vision-based prediction Vison-based prediction papers are categorized in to 6 groups according to their applications and wether they are associated with code. For the list of papers in each category click on the name of the application. Note that some papers present algorithms for multiple tasks so they might appear in more than one category. * <a href=video_papers.md#top>Video</a> or future scene prediction can be regarded as the most generic form of prediction. The objective of video prediction algorithms is to generate future scenes, often in the form of RGB images. * <a href=action_papers.md#top>Action</a> prediction algorithms are used to predict future activities or events given partial or no observations of future activities or events. * <a href=trajectory_papers.md#top>Trajectory</a> prediction algorithms predict the future trajectories of objects, i.e. the future positions of the objects over time. * <a href=motion_papers.md#top>Motion</a> prediction algorithms are those designed to predict future changes in human pose. * <a href=other_papers.md#top>Other</a> prediction includes algorithms such as visual weather prediction, occupancy grid map prediction, contest outcome prediction, etc. * <a href=papers_with_code.md#top>Papers with code</a> page provides an alternative search of papers that have published code available online.
Python
UTF-8
717
4.1875
4
[ "MIT" ]
permissive
# # containsDuplicates # # Given an array of integers, write a function that determines whether the array contains any duplicates. Your function should return true if any element appears at least twice in the array, and it should return false if every element is distinct. # # Example # # For a = [1, 2, 3, 1], the output should be # containsDuplicates(a) = true. # # There are two 1s in the given array. # # For a = [3, 1], the output should be # containsDuplicates(a) = false. # # The given array contains no duplicates. def containsDuplicates(a): seen = set() for item in a: if item in seen: return True else: seen.add(item) return False
Python
UTF-8
8,509
2.765625
3
[]
no_license
#License MIT 2016 Ahmad Retha import pygame pygame.init() WIDTH = 1366 HEIGHT = 720 SCREEN_SIZE = (WIDTH, HEIGHT) screen = pygame.display.set_mode(SCREEN_SIZE) screen = pygame.display.set_mode(SCREEN_SIZE , pygame.RESIZABLE) class Background(pygame.sprite.Sprite): def __init__(self, image_file, location): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.image = pygame.image.load(image_file).convert_alpha() self.rect = self.image.get_rect() self.rect.left, self.rect.top = location BackGround = Background('background.png', [0,0]) ## # Game mode # pygame.display.set_caption('Air-Hockey') clock = pygame.time.Clock() pygame.key.set_repeat(50, 50) pygame.init() FSC = False x_thresh = 20 y_thresh = 28 ## # Game consts # FONT = pygame.font.Font(None, 120) FONT1 = pygame.font.Font(None, 30) BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0 ,0, 255) light_blue = (0,100,200) GRAY = (100, 100, 100) MODE_PLAY = 1 MODE_QUIT = 0 Game = 'stop' FRAME_RATE = 120 ## # Game Vars # PLAY_AREA_COLOR = (120,50,120) PLAY_AREA_WIDTH = 50 PLAY_AREA_LEFT_X = 0 PLAY_AREA_RIGHT_X = WIDTH - PLAY_AREA_WIDTH PLAY_AREA_LEFT_Y = 0 PLAY_AREA_RIGHT_Y = 0 PLAY_AREA_HEIGHT = HEIGHT score_left = 0 score_right = 0 current_mode = MODE_PLAY BALL_SPEED = 4 pos_x = int(0.5 * WIDTH) speed_x = BALL_SPEED pos_y = int(0.5 * HEIGHT) speed_y = BALL_SPEED BALL_COLOR = WHITE BALL_RADIUS = 18 PADDLE_SPEED = 10 PADDLE_HEIGHT = 100 PADDLE_WIDTH = 25 PADDLE_LEFT_COLOR = WHITE PADDLE_RIGHT_COLOR = WHITE PADDLE_LEFT_X = int(0.5*PADDLE_WIDTH) + x_thresh PADDLE_RIGHT_X = WIDTH - int(0.5*PADDLE_WIDTH) - PADDLE_WIDTH - x_thresh paddle_left_y = int(0.5 * HEIGHT - 0.5 * PADDLE_HEIGHT) paddle_right_y = paddle_left_y ## # Game loop # while current_mode == MODE_PLAY: ## # Handle keyboard # for event in pygame.event.get(): if event.type == pygame.QUIT: current_mode = MODE_QUIT elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: current_mode = MODE_QUIT keysPressed = pygame.key.get_pressed() if keysPressed[pygame.K_UP]: paddle_right_y = paddle_right_y - PADDLE_SPEED if paddle_right_y < y_thresh: paddle_right_y = y_thresh elif keysPressed[pygame.K_DOWN]: paddle_right_y = paddle_right_y + PADDLE_SPEED if paddle_right_y > (HEIGHT - PADDLE_HEIGHT - y_thresh): paddle_right_y = HEIGHT - PADDLE_HEIGHT - y_thresh/2-19 if keysPressed[pygame.K_a]: paddle_left_y = paddle_left_y - PADDLE_SPEED if paddle_left_y < y_thresh: paddle_left_y = y_thresh elif keysPressed[pygame.K_z]: paddle_left_y = paddle_left_y + PADDLE_SPEED if paddle_left_y > (HEIGHT - PADDLE_HEIGHT - y_thresh): paddle_left_y = HEIGHT - PADDLE_HEIGHT - y_thresh/2-19 elif keysPressed[pygame.K_F11]: if(FSC): screen = pygame.display.set_mode(SCREEN_SIZE , pygame.RESIZABLE) FSC=False else: screen = pygame.display.set_mode(SCREEN_SIZE, pygame.FULLSCREEN) FSC=True elif keysPressed[pygame.K_F1]: if(Game!='over'): Game='start' score_left = 0 score_right = 0 elif keysPressed[pygame.K_F2]: Game='stop' score_left = 0 score_right = 0 ## # Draw arena and score # # screen.fill(BLACK) screen.fill([255, 255, 255]) screen.blit(BackGround.image, BackGround.rect) # pygame.draw.line(screen, GRAY, [int(0.5 * WIDTH), 0], [int(0.5 * WIDTH), HEIGHT], 1) text = FONT.render("%2s %2s" % (str(score_left), str(score_right)), 5, light_blue) textpos = text.get_rect(center = (WIDTH/2 - 10, 60)) screen.blit(text, textpos) text1 = FONT1.render("F1 : Play", 2, (0,120,120)) textpos1 = text.get_rect(center=(WIDTH/2 - 400, 100)) screen.blit(text1, textpos1) text1 = FONT1.render("F2 : Restart", 2, (0,120,120)) textpos1 = text.get_rect(center=(WIDTH/2 - 400, 150)) screen.blit(text1, textpos1) text1 = FONT1.render("F11 : FullScreen", 2, (0,120,120)) textpos1 = text.get_rect(center=(WIDTH/2 - 400, 200)) screen.blit(text1, textpos1) text1 = FONT1.render("Esc : Exit", 2, (0,120,120)) textpos1 = text.get_rect(center=(WIDTH/2 - 400, 250)) screen.blit(text1, textpos1) ## # Draw paddles # pygame.draw.rect(screen, PADDLE_LEFT_COLOR, (PADDLE_LEFT_X, paddle_left_y, PADDLE_WIDTH, PADDLE_HEIGHT)) pygame.draw.rect(screen, PADDLE_RIGHT_COLOR, (PADDLE_RIGHT_X, paddle_right_y, PADDLE_WIDTH, PADDLE_HEIGHT)) ## # Draw play area # # pygame.draw.rect(screen, PLAY_AREA_COLOR, (PLAY_AREA_LEFT_X, PLAY_AREA_LEFT_Y, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT)) # pygame.draw.rect(screen, PLAY_AREA_COLOR, (PLAY_AREA_RIGHT_X, PLAY_AREA_RIGHT_Y, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT)) ## # Move ball and update scores # if(score_right==1000 or score_left==1000): Game='over' if(Game=='over'): FONT2 = pygame.font.Font(None, 80) text2 = FONT2.render("Game Over", 2, (200,0,0)) textpos2 = text.get_rect(centerx=WIDTH/2-88,centery=HEIGHT/2) screen.blit(text2, textpos2) FONT2 = pygame.font.Font(None, 50) a=0 if(score_right>score_left): a=1 if(a==1): text2 = FONT2.render("You Lose You Win", 2, (200,0,0)) textpos2 = text.get_rect(centerx=WIDTH/2-140, centery=HEIGHT/2+120) screen.blit(text2, textpos2) if(a==0): text2 = FONT2.render("You Win You Lose", 2, (200,0,0)) textpos2 = text.get_rect(centerx=WIDTH/2-140, centery=HEIGHT/2+120) screen.blit(text2, textpos2) else: if(Game=='start'): r = BALL_RADIUS pos_x = pos_x + speed_x if pos_x > WIDTH - x_thresh - 13: if pos_y >= 240 and pos_y<=480: if pos_y > (0.5 * HEIGHT): speed_y = abs(speed_y) else: speed_y = -abs(speed_y) pos_x = int(0.5 * WIDTH) pos_y = int(0.5 * HEIGHT) score_left += 1 else: pos_x = WIDTH - x_thresh - r - 20 speed_x = -speed_x elif pos_x < x_thresh+20: if pos_y >= 240 and pos_y <= 480: if pos_y > (0.5 * HEIGHT): speed_y = abs(speed_y) else: speed_y = -abs(speed_y) pos_x = int(0.5 * WIDTH) pos_y = int(0.5 * HEIGHT) score_right += 1 else: pos_x = x_thresh+20 speed_x = abs(speed_x) pos_y = pos_y + speed_y if pos_y + r > HEIGHT - y_thresh: speed_y = -speed_y elif pos_y - r < y_thresh: speed_y = abs(speed_y) if pos_x <= (PADDLE_LEFT_X + PADDLE_WIDTH)+r and pos_y >= paddle_left_y and pos_y <= (paddle_left_y + PADDLE_HEIGHT): pos_x = PADDLE_LEFT_X + PADDLE_WIDTH + r speed_x = abs(speed_x) elif pos_x >= PADDLE_RIGHT_X-r and pos_y >= paddle_right_y and pos_y <= (paddle_right_y + PADDLE_HEIGHT): pos_x = PADDLE_RIGHT_X-r speed_x = -speed_x if(Game=='stop'): paddle_left_y = int(0.5 * HEIGHT - 0.5 * PADDLE_HEIGHT) paddle_right_y = paddle_left_y pos_x = int(0.5 * WIDTH) pos_y = int(0.5 * HEIGHT) pygame.draw.circle(screen, BALL_COLOR, [pos_x, pos_y], BALL_RADIUS) ## # Bounce ball off paddles # ## # Tick-tock # pygame.display.update() clock.tick(FRAME_RATE) pygame.quit()
C++
UTF-8
1,128
3.1875
3
[]
no_license
#include <vector> #include <iostream> #include <string> #include <unordered_set> #include <unordered_map> #include <stack> #include <queue> #include <map> using namespace std; // bianry的问题 能用bit运算就不用乘法除法 class Solution { public: string addBinary(string a, string b) { if(a.size()==0){return b;} if(b.size()==0){return a;} const int len_a = a.size(); const int len_b = b.size(); string ret; int ia = len_a-1; int ib = len_b-1; int curr = 0; int carry = 0; while(ia>=0 && ib>=0){ curr = (a[ia]-'0') ^ (b[ib]-'0') ^ carry; carry = (((a[ia]-'0') + (b[ib]-'0') + carry)>=2 ? 1 : 0); ret.push_back(curr+'0'); ia--; ib--; } while(ia>=0){ curr = (a[ia]-'0') ^ carry; carry = (a[ia]-'0') & carry; ret.push_back(curr+'0'); ia--; } while(ib>=0){ curr = (b[ib]-'0') ^ carry; carry = (b[ib]-'0') & carry; ret.push_back(curr+'0'); ib--; } if(carry){ ret.push_back('1'); } reverse(ret.begin(), ret.end()); return ret; } };
C++
UTF-8
1,206
3.953125
4
[]
no_license
#include <iostream> #include <string> using namespace std; // l values: // values that have names and are addressable // modifiable if they are not constants // r values: // a va;ie that's not an l-value // a literal // a temporary which is intended to be non-modifiable void l_r() { int x {100}; // x is an l-value, 100 is an r-value int y = x + 200; // (x+200) is an r-value string name; // name is an l-value, "Frank" is an r-value name = "Frank"; // name and x can be used on the left side of an assignment statement int max_num = max(20, 30); // max(20,30) is an r-value // 100 = x; 100 is NOT an l-value // (100 + 20) = x // (100 + 20) is NOT an l-value // r-values can be assigned to l-values explicitly y = 100; // r-value 100 assigned to l-value y x = x + y; // r-value (x+y) assigned to l-value x // the references we've used are l-value references // because we are referenceing l-values int &ref1 = x; // ref1 is a reference to l-value ref1 = 1000; // you can only reference l-values // int &ref2 = 100; ERROR 100 is an r-value }
C#
UTF-8
340
2.953125
3
[]
no_license
var exceptionDemoQuery = from file in files select file; foreach (var item in exceptionDemoQuery) { try { Console.WriteLine("Processing {0}", item); var n = SomeMethodThatMightThrow(item); } catch (Exception ex) { Console.WriteLine(e.Message); } }
Markdown
UTF-8
4,613
3.6875
4
[ "MIT" ]
permissive
![Java](https://s2.ax1x.com/2019/10/29/KRNvw9.md.jpg) > 在 JVM 中允许一个程序有多个线程并发执行,并且每个线程都有优先级,优先级高的线程要优先于优先级低的线程执行。每个线程可能被标记为守护线程,也可能不被标记。当 JVM 运行时,通常就会有一个非守护线程。 ## 进程与线程 <font color="red">进程:就是受操作系统管理的基本运行单元。进程之间的内存是不共享的,进程之间使用 socket 通信。</font><br/> <font color="red">线程:可以理解成是在进程中独立运行的子任务;而多线程则可以理解为是多个线程在同一时间内运行不同种类的任务。线程间的内存是共享,每个运行的线程都对应一个栈(stack)。</font> ### 多线程优点 > 在单任务的环境下,必须等待上一个任务完成后,才会执行下一个任务,这样使 CPU 利用率大幅度降低;而在多任务环境下,CPU 可以在任务之间来回切换,系统的运行效率大大提升。**多线程是异步的。** 如下图所示 ![单任务环境与多任务环境](https://s2.ax1x.com/2019/10/29/KRf1PK.png) ## 创建并启动线程 - Thread:通过继承  `Thread`,重写  `run`  方法创建线程,调用  `start`  方法启动线程。 <br/> ```java public class ExtendsThread extends Thread {   @Override   public void run() {     System.out.println("ExtendsThread");   }   public static void main(String[] args) {     new ExtendsThread().start(); // ExtendsThread   } } ``` - Runnable:通过实现  Runnable  接口,实现  `run`  方法创建线程,调用  `start`  方法启动线程。 <br/> ```java public class ImplementRunnable implements Runnable {   public void run() {     System.out.println("ImplementRunnable");   }   public static void main(String[] args) {     new Thread(new ImplementRunnable).start(); // ImplementRunnable   } } ``` - Executors.newCachedThreadPool:通过线程池创建线程 <br/> ```java public class ExecutorsThreadPool {   public static void main(String[] args) {     ExecutorService executorService = Executors.newCachedThreadPool();     executorService.execute(new Runnable() {       @Override       public void run() {         System.out.println("ExecutorService"); // ExecutorService       }     });     executorService.shutdown();   } } ``` - 通过  Java8 Lambda  表达式创建 <br/> ```java public class LambdaThread {   public static void main(String[] args) {     new Thread(() -> {       System.out.println("LambdaThread"); // LambdaThread     }).start();   } } ``` ## 线程的状态 > 当线程被创建并启动后,它要经过 新建(NEW)、运行(RUNNABLE)、阻塞(BLOCKED)、等待(WAITING)、超时等待(TIMED_WAITING)、终止(TERMINATED)6 种状态,这 6 中状态定义在 Thread.State 中。 ![线程状态图](https://s2.ax1x.com/2019/11/18/M6wADx.png) #### 新建状态(NEW) 实现 Runnable 接口和继承 Thread 类可以得到一个线程类,通过 new 关键字实例化,但是没有调用 start()方法。 #### 运行状态(RUNNABLE) Java 中将 就绪状态(READY) 和 运行中状态(RUNNING) 统称为运行状态(RUNNABLE)。当线程对象被创建并调用 start() 方法,此时该线程进入就绪状态(READY),等待线程调度器执行。 就绪状态(READY) 还可通过以下方式进入: - 调用当前线程的 yield() 方法,当前线程被挂起; - 当前线程 sleep() 方法结束、其他线程 join() 方法结束、等待用户输入完毕、某个线程拿到对象锁; - 当线程时间片用完; 当线程调度器从可运行池中选择一个线程作为当前执行线程时,该线程进入运行中状态(RUNNING)。这也是线程进入运行中状态(RUNNING)的唯一方式。 #### 阻塞状态(BLOCKED) 当前线程在进入 synchronized 关键字修饰的方法或代码(获取锁)时的状态。 #### 等待状态(WAITING) 处于这种状态的线程不会被分配 CPU 执行时间,它们要等待被显式地唤醒,否则会处于无限等待的状态。 #### 超时等待(TIMED_WAITING) 处于这种状态的线程会到达一定时间后被自动唤醒。 #### 终止(TERMINATE) 当线程程序执行完成,该线程将会终止,**在一个终止的线程上调用 start()方法,会抛出 java.lang.IllegalThreadStateException 异常**。
Java
UTF-8
2,383
2.40625
2
[ "Apache-2.0" ]
permissive
/* * * * Copyright 2015 Skymind,Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package jcuda.runtime; /** * Java port of a cudaExtent. * * @see JCuda#cudaMalloc3D * @see JCuda#cudaMemset3D * @see JCuda#cudaMalloc3DArray * */ public class cudaExtent { /** * The width of this cudaExtent, in elements */ public long width; /** * The height of this cudaExtent, in elements */ public long height; /** * The depth of this cudaExtent */ public long depth; /** * Creates a new cudaExtent with all-zero sizes */ public cudaExtent() { } /** * Creates a new cudaExtent with the given sizes * * @param width The width of the cudaExtent * @param height The height of the cudaExtent * @param depth The depth of the cudaExtent */ public cudaExtent(int width, int height, int depth) { this.width = width; this.height = height; this.depth = depth; } /** * Creates a new cudaExtent with the given sizes * * @param width The width of the cudaExtent * @param height The height of the cudaExtent * @param depth The depth of the cudaExtent */ public cudaExtent(long width, long height, long depth) { this.width = width; this.height = height; this.depth = depth; } /** * Returns a String representation of this object. * * @return A String representation of this object. */ @Override public String toString() { return "cudaExtent["+ "width="+width+","+ "height="+height+","+ "depth="+depth+"]"; } }
C++
UTF-8
3,544
3.6875
4
[]
no_license
/* Author: Michael Ranciglio Location: Southeast Missouri State University Class: Computer Science II (CS 265-01) (21141) Date: 2/14/16 Data Type: complexType, a complex number representing a real and imaginary part */ #include <iostream> #include <cstdlib> #include "complexType.h" using namespace std; complexType::complexType(double real /*= 0*/, double imaginary /*= 0*/) // Task: Construct function by setting members to real & imaginary , default = 0 { realPart = real; imaginaryPart = imaginary; } void complexType::setComplex(const double& real, const double& imaginary) // Task: set members to real & imaginary { realPart = real; imaginaryPart = imaginary; } bool complexType::operator==(const complexType& otherComplex) const // Task: return true if complexType objs are equal, else return false { if(this->realPart == otherComplex.realPart && this->imaginaryPart == otherComplex.imaginaryPart) return true; else return false; } //Note: For the next four operators: // a = this->realPart, b = this->imaginaryPart // c = otherComplex.realPart, d = otherComplex.imaginaryPart complexType complexType::operator+(const complexType& otherComplex) const // Task: Add complexType objs together { complexType thisComplex; // (a, b) * (c, d) = (a + c), (b + d) thisComplex.realPart = this->realPart + otherComplex.realPart; thisComplex.imaginaryPart = this->imaginaryPart + otherComplex.imaginaryPart; return thisComplex; } complexType complexType::operator*(const complexType& otherComplex) const // Task: Multiply complexType objs { complexType thisComplex; // (a, b) * (c, d) = (ac - bd), (bc + ad) thisComplex.realPart = (this->realPart * otherComplex.realPart) - (this->imaginaryPart * otherComplex.imaginaryPart); thisComplex.imaginaryPart = (this->imaginaryPart * otherComplex.realPart) + (this->realPart * otherComplex.imaginaryPart); return thisComplex; } complexType complexType::operator-(const complexType& otherComplex) const // Task: Subtract complexType objs { complexType thisComplex; // (a, b) - (c, d) = (a - c), (b - d) thisComplex.realPart = this->realPart - otherComplex.realPart; thisComplex.imaginaryPart = this->imaginaryPart - otherComplex.imaginaryPart; return thisComplex; } complexType complexType::operator/(const complexType& otherComplex) const // Task: Divide complexType objs { complexType thisComplex; // Check for divide by zero logic if(otherComplex.realPart == 0 && otherComplex.imaginaryPart == 0) { cout << "Error: Tried to divide by zero. Exiting Program." << endl; exit(1); } // (a, b) / (c, d) = ((ac + bd)/(c^2 + d^2)), ((bc - ad)/(c^2 + d^2)) thisComplex.realPart = ((this->realPart * otherComplex.realPart) + (this->imaginaryPart * otherComplex.imaginaryPart)) / ((otherComplex.realPart * otherComplex.realPart) + (otherComplex.imaginaryPart * otherComplex.imaginaryPart)); thisComplex.imaginaryPart = ((this->imaginaryPart * otherComplex.realPart) - (this->realPart * otherComplex.imaginaryPart)) / ((otherComplex.realPart * otherComplex.realPart) + (otherComplex.imaginaryPart * otherComplex.imaginaryPart)); return thisComplex; } ostream& operator<<(ostream& out, const complexType& c) // Task: Output complexType obj { out << "(" << c.realPart << ", " << c.imaginaryPart << ")"; return out; } istream& operator>>(istream& in, complexType& c) // Task: Set complexType obj through Input { char filler; cout << "Please enter your ordered pair in the form of (a, b): "; in >> filler >> c.realPart >> filler >> c.imaginaryPart >> filler; return in; }
Python
UTF-8
269
3.609375
4
[]
no_license
x=int(input("enter your x")) y=int(input("enter your y")) x2=int(input("enter your x2")) y2=int(input("enter your y2")) x3=int(input("enter your x3")) y3=int(input("enter your y3")) slope=x*(y2-y3)+x2*(y3-y)+x3*(y-y2) if slope==0: print("line check")
Java
UTF-8
231
2.1875
2
[]
no_license
package com.devproject.tediproject.exception; public class ProfessionalNotFoundException extends RuntimeException { public ProfessionalNotFoundException(Long id) { super("Could not find professional " + id); } }
C++
UTF-8
2,334
3.4375
3
[]
no_license
#include<iostream> #include<stdlib.h> using namespace std; class tree { typedef struct node { struct node *left, *right, *parent ; int data; }node; typedef struct list { struct list *next; node *sibling; }link; public: node *T ; void insert(int n) { node *np = (node *)calloc(3, sizeof(np)), *x, *y; np->data = n; if(T == NULL) T = np; else { x = y = T; while(x) { y = x; if(x->data < n) x = x->right; else x = x->left; } if(y->data < n) y->right = np; else y->left = np; } } void inorder(node *nod) { if(nod->left) inorder(nod->left); cout << nod->data << endl; if(nod->right) inorder(nod->right); } void leftView() { link *stack = NULL, *np, *tail, *x, *y; link *nod; np = (link *)calloc(1, sizeof(np)); np->sibling = T; stack = tail = nod = np; while(nod!= NULL) { cout << nod->sibling->data << endl; x = tail; while(1) { if(nod->sibling->left) { np = (link *)calloc(1, sizeof(np)); np->sibling = nod->sibling->left; tail->next = np; tail = np; } if(nod->sibling->right) { np = (link *)calloc(1, sizeof(np)); np->sibling = nod->sibling->right; tail->next = np; tail = np; } if(nod == x) { nod = nod->next; break; } nod = nod->next; } } } }; int main() { tree ob1; int n, no; int i; cin >> n; ob1.T = NULL; for(i = 0; i < n; i++) { cin >> no; ob1.insert(no); } ob1.leftView(); }
Python
UTF-8
1,034
2.953125
3
[]
no_license
import sys def change(N): if N == 0: N = 1 else: N = 0 return N N = int(sys.stdin.readline()) state = list(map(int,sys.stdin.readline().split())) state.insert(0,9999) Num_student = int(sys.stdin.readline()) for i in range(Num_student): stu_sex = list(map(int,sys.stdin.readline().split())) if stu_sex[0] == 1: count = (len(state)-1) // stu_sex[1] for i in range(1,count+1): state[stu_sex[1]*i] = change(state[stu_sex[1]*i]) else: box = [] for i in range(1,stu_sex[1]+1): if state[stu_sex[1]-i] == state[stu_sex[1]+i]: box.append(stu_sex[1]-i) box.append(stu_sex[1]) box.append(stu_sex[1]+i) else: box.append(stu_sex[1]) box = set(box) for i in box: state[i] = change(state[i]) for k in range(1,len(state)): print(state[k],end=' ')
SQL
UTF-8
2,121
2.984375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 29-10-2021 a las 08:57:29 -- Versión del servidor: 10.4.14-MariaDB -- Versión de PHP: 7.4.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `crud2` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `tm_producto` -- CREATE TABLE `tm_producto` ( `prod_id` int(11) NOT NULL, `prod_nom` varchar(150) COLLATE utf8_spanish_ci NOT NULL, `prod_desc` varchar(500) COLLATE utf8_spanish_ci NOT NULL, `fech_crea` datetime NOT NULL, `fech_modi` datetime DEFAULT NULL, `fech_elim` datetime DEFAULT NULL, `est` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; -- -- Volcado de datos para la tabla `tm_producto` -- INSERT INTO `tm_producto` (`prod_id`, `prod_nom`, `prod_desc`, `fech_crea`, `fech_modi`, `fech_elim`, `est`) VALUES (1, 'Auriculares', 'Ninguna', '2021-10-22 23:45:36', NULL, NULL, 1), (15, 'Mouse', 'Ninguna', '2021-10-29 01:42:47', NULL, NULL, 1), (16, 'Teclado', 'Ninguna', '2021-10-29 01:42:55', NULL, NULL, 1), (17, 'Monitor', 'Ninguna', '2021-10-29 01:43:02', NULL, NULL, 1), (18, 'Test', 'Testing', '2021-10-29 01:55:20', '2021-10-29 01:55:30', NULL, 1); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `tm_producto` -- ALTER TABLE `tm_producto` ADD PRIMARY KEY (`prod_id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `tm_producto` -- ALTER TABLE `tm_producto` MODIFY `prod_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UHC
846
3.625
4
[]
no_license
package chap08; import java.util.Scanner; public class ExceptionTest04 { public static void main(String[] args) { Scanner key = new Scanner(System.in); try { System.out.print("迭 Էϼ:"); int size = key.nextInt(); String[] arr = new String[5]; System.out.println("step01"); if (size > 3) { arr[1] = new String("java"); //ڿ : 4 }System.out.println(arr[1].length()); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("迭 Ҹ ߸׼..."); }catch (NullPointerException e) { System.out.println("Դϴ."); }catch (Exception e) { System.out.println("Դϴ."); }finally { // System.out.println("ݵ ɹ - ǽ"); } } }
Java
UTF-8
506
2.109375
2
[]
no_license
package test.carros; import org.testng.Assert; import org.testng.annotations.Test; import pageObjects.CarroPage; import utils.BaseTest; import static utils.StaticValues.DELETE_SUCCESS; public class DeletarCarroTest extends BaseTest { @Test public void deveDeletarCarroExistente(){ CarroPage carroPage = new CarroPage(driver); carroPage.deletar(); String resultado = carroPage.resultadoInclusaoCarro(); Assert.assertEquals(resultado, DELETE_SUCCESS); } }
Java
UTF-8
1,080
3.109375
3
[]
no_license
package simulator; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileWrite { private String filePath; private BufferedWriter bw; public FileWrite(String filePath) { this.filePath=filePath; initial(); } private void initial() { File file = new File(filePath); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } FileWriter fw = null; try { fw = new FileWriter(file.getAbsoluteFile()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } bw = new BufferedWriter(fw); } public void write(String content) { try { bw.write(content); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void closeStream() { try { bw.close(); //System.out.print("file closed"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Markdown
UTF-8
709
3.71875
4
[]
no_license
## 两数之和 使用哈希表存`元素值-索引` 这样就能快速的定位到对应的位置。 ```java class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashMap = new HashMap<>(); for ( int i = 0; i < nums.length; i++ ) { if ( hashMap.containsKey(target - nums[i]) ) { return new int[]{i, hashMap.get(target - nums[i])}; } else { hashMap.put(nums[i], i); } } return new int[]{}; } } ``` - 记住HashMap的创建 - 记住HashMap的api:containsKey - 记住比较特殊的返回数组元素的方法: return new int[]{i, hashMap.get(target - nums[i])};
Java
UTF-8
10,846
2.15625
2
[]
no_license
package NewTours; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; public class TestNewTours { public static void main(String[] args) { // TODO Auto-generated method stub System.setProperty("webdriver.gecko.driver", "D://sujan/soft/geckodriver-v0.18.0/geckodriver.exe"); @SuppressWarnings("unused") FirefoxDriver driver = new FirefoxDriver(); driver.get("http://newtours.demoaut.com/"); //New Tours Login driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[4]/td/table/tbody/tr[2]/td[2]/input")).sendKeys("demo"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[4]/td/table/tbody/tr[3]/td[2]/input")).sendKeys("demo"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[4]/td/table/tbody/tr[4]/td[2]/div/input")).click(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //New Tours Second Page driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[2]/td[2]/b/font/input[2]")).click(); Select Passangers = new Select (driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[3]/td[2]/b/select"))); //Passangers.deselectAll(); Passangers.selectByIndex(1); Select DepartingFrom = new Select (driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[4]/td[2]/select"))); //DepartingFrom.deselectAll(); DepartingFrom.selectByIndex(2); Select On_Month = new Select (driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[5]/td[2]/select[1]"))); On_Month.selectByIndex(7); Select On_Day = new Select (driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[5]/td[2]/select[2]"))); On_Day.selectByIndex(26); Select Arriving_in = new Select (driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[6]/td[2]/select"))); Arriving_in.selectByIndex(3); Select Returning_Month = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[7]/td[2]/select[1]"))); Returning_Month.selectByIndex(7); Select Returning_Day = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[7]/td[2]/select[2]"))); Returning_Day.selectByIndex(30); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/font/font/input[1]")).click(); Select Airline = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[10]/td[2]/select"))); Airline.selectByIndex(1); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[14]/td/input")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //New Tours 3rd Page //Depart driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[1]/tbody/tr[5]/td[1]/input")).click(); //Return driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table[2]/tbody/tr[5]/td[1]/input")).click(); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/p/input")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //New Tours 4th Page //Passengers Credentials driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[4]/td/table/tbody/tr[2]/td[1]/input")).sendKeys("Md. Mosharof"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[4]/td/table/tbody/tr[2]/td[2]/input")).sendKeys("Hossain"); Select Pass_Meal = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[4]/td/table/tbody/tr[2]/td[3]/select"))); Pass_Meal.selectByIndex(8); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[5]/td/table/tbody/tr[2]/td[1]/input")).sendKeys("Md. Mozammal"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[5]/td/table/tbody/tr[2]/td[2]/input")).sendKeys("Hossain"); Select Pass_Meal2nd = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[5]/td/table/tbody/tr[2]/td[3]/select"))); Pass_Meal2nd.selectByIndex(8); //Credit Card Info Select CardType = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[7]/td/table/tbody/tr[2]/td[1]/select"))); CardType.selectByIndex(1); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[7]/td/table/tbody/tr[2]/td[2]/input")).sendKeys("123"); Select CardExpMonth = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[7]/td/table/tbody/tr[2]/td[3]/select[1]"))); CardExpMonth.selectByIndex(0); Select CardExpYear = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[7]/td/table/tbody/tr[2]/td[3]/select[2]"))); CardExpYear.selectByIndex(0); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[8]/td/table/tbody/tr[2]/td[1]/input")).sendKeys("Md"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[8]/td/table/tbody/tr[2]/td[2]/input")).sendKeys("Mosharof"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[8]/td/table/tbody/tr[2]/td[3]/input")).sendKeys("Hossain"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/input")).click(); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[10]/td[2]/input")).sendKeys("House-58, Road,06, Block-G"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[11]/td[2]/input")).sendKeys("newtown, New york"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[12]/td[2]/input")).sendKeys("newtown"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[13]/td[2]/input[1]")).sendKeys("New york"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[13]/td[2]/input[2]")).sendKeys("12345"); Select SelectCountry = new Select(driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[14]/td[2]/select"))); SelectCountry.selectByIndex(214); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[15]/td[2]/input")).click(); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[16]/td[2]/input")).sendKeys("House-58, Road,06, Block-G"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[17]/td[2]/input")).sendKeys("newtown, New york"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[18]/td[2]/input")).sendKeys("New york"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[19]/td[2]/input[1]")).sendKeys("newtown"); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[19]/td[2]/input[2]")).sendKeys("1250"); Select SelectDeliveryCountry = new Select (driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[20]/td[2]/select"))); SelectDeliveryCountry.selectByIndex(214); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[24]/td/input")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.xpath("html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr[1]/td[2]/table/tbody/tr[7]/td/table/tbody/tr/td[3]/a/img")).click(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } }
Java
UTF-8
1,231
2.203125
2
[]
no_license
package com.atguigu.cache.service.impl; import com.atguigu.cache.bean.Department; import com.atguigu.cache.bean.Employee; import com.atguigu.cache.mapper.DepartmentMapper; import com.atguigu.cache.service.base.BaseServiceMyBatis; import org.springframework.stereotype.Service; @Service public class DepartService extends BaseServiceMyBatis<Department, DepartmentMapper, Integer> { /** * 设置底层调用mybatis的mapper * * @return */ @Override public DepartmentMapper getMapper() { return null; } /** * 设置缓存的前缀,为了避免缓存覆盖,一般设置表的名称 * * @throws NoSuchFieldException * @throws IllegalAccessException */ @Override public void initCache() throws NoSuchFieldException, IllegalAccessException { setCacheNames(new String[]{"Depart"}); } @Override public Department deleteProxy(Integer id) { Department department = getProxy().findById(id); getProxy().delete(id); return department; } @Override public void insertProxy(Department bean) { } @Override public Department updateProxy(Department bean) { return null; } }
Java
UTF-8
762
2.109375
2
[]
no_license
package fr.inra.sad.bagap.apiland.analysis.matrix.process.metric.qualitative.value; import fr.inra.sad.bagap.apiland.analysis.VariableManager; import fr.inra.sad.bagap.apiland.analysis.matrix.process.counting.Counting; import fr.inra.sad.bagap.apiland.analysis.matrix.process.metric.MatrixMetric; import fr.inra.sad.bagap.apiland.analysis.process.metric.ValueMetric; import fr.inra.sad.bagap.apiland.core.space.impl.raster.Raster; public class BoundaryIndex extends MatrixMetric implements ValueMetric { public BoundaryIndex() { super(VariableManager.get("Bindex")); } @Override public void doCalculate(Counting co) { if(co.countValues() > 0){ value = 0; if(co.countClass() > 1){ value = 1; } } } }
Java
UTF-8
5,997
1.976563
2
[]
no_license
package com.example.cassio.alunouesb.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import com.example.cassio.alunouesb.dialog.DialogExcluir; import com.example.cassio.alunouesb.R; import com.example.cassio.alunouesb.adapter.AdapterDisciplina; import com.example.cassio.alunouesb.database.dao.DisciplinaDAO; import com.example.cassio.alunouesb.model.Disciplina; import com.example.cassio.alunouesb.model.Semestre; import com.example.cassio.alunouesb.model.Usuario; import com.google.firebase.firestore.FirebaseFirestore; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class DisciplinasActivity extends AppCompatActivity implements AdapterDisciplina.OnClick, AdapterDisciplina.OnLongClick, DialogExcluir.OnExcluir{ private Intent intent; private Usuario usuario = PrincipalActivity.usuario; private RecyclerView recyclerView; private AdapterDisciplina adapter; private ArrayList listaDisciplinas; public List<Disciplina> listaExclusao = new ArrayList<>(); private List<View> listaViewSelecionadas = new ArrayList<>(); private int REQUEST_NOVA_DISCIPLINA = 1; private int REQUEST_ABRIR_DISCIPLINA = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_disciplinas); setTitle("Minhas Disciplinas"); recyclerView = findViewById(R.id.recycler_view_disciplinas); listaDisciplinas = (ArrayList) usuario.getSemestreList().get(usuario.getIdSemestre()).getDisciplinaList(); adapter = new AdapterDisciplina(listaDisciplinas, this, this, this); recyclerView.setAdapter(adapter); RecyclerView.LayoutManager layout = new LinearLayoutManager(this, LinearLayout.VERTICAL,false); recyclerView.setLayoutManager(layout); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putSerializable("lista",(Serializable) listaExclusao); super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (listaExclusao.isEmpty()) { getSupportActionBar().setDisplayHomeAsUpEnabled(false); } else { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getMenuInflater().inflate(R.menu.menu_lembretes, menu); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_excluir) { DialogExcluir dialog = new DialogExcluir(); dialog.setOnExcluir(this); dialog.show(getSupportFragmentManager(), "Deseja excluir a disciplina?"); } else { listaExclusao.clear(); for (View view : listaViewSelecionadas) { view.setBackgroundResource(R.drawable.shape_cinza); } invalidateOptionsMenu(); } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { if (listaExclusao.isEmpty()) { intent = new Intent(this, DisciplinaActivity.class); intent.putExtra("disciplina", (Disciplina) adapter.getItem((int) view.getTag())); startActivityForResult(intent, REQUEST_ABRIR_DISCIPLINA); } else { adicionarParaExclusao(view); } } @Override public void onLongClick(View view) { adicionarParaExclusao(view); view.setBackgroundColor(getResources().getColor(R.color.colorAccent)); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Disciplina disciplina; //Caso adicionou um novo Item if (requestCode == REQUEST_NOVA_DISCIPLINA && data != null) { disciplina = (Disciplina) data.getSerializableExtra("disciplina"); adapter.addItem(disciplina); } //Caso editou um Item if (requestCode == REQUEST_ABRIR_DISCIPLINA && resultCode == 1) { disciplina = (Disciplina) data.getSerializableExtra("disciplina"); adapter.update(disciplina); } super.onActivityResult(requestCode, resultCode, data); } public void chamarTelaAdicionarDisciplina(View view) { listaExclusao.clear(); listaViewSelecionadas.clear(); invalidateOptionsMenu(); adapter.notifyDataSetChanged(); Intent telaAdicionarDisciplina = new Intent(this, AdicionarDisciplinaActivity.class); startActivity(telaAdicionarDisciplina); } private void adicionarParaExclusao(View view) { Disciplina disciplina = (Disciplina) adapter.getItem((int) view.getTag()); if (this.listaExclusao.contains(disciplina)) { listaViewSelecionadas.remove(view); listaExclusao.remove(disciplina); view.setBackgroundResource(R.drawable.shape_cinza); } else { listaViewSelecionadas.add(view); listaExclusao.add(disciplina); view.setBackgroundColor(getResources().getColor(R.color.colorAccent)); } invalidateOptionsMenu(); } @Override public void onExcluir() { for (Disciplina disciplina : listaExclusao) { adapter.removeItem(disciplina); usuario.getSemestreList().remove(disciplina); } listaExclusao.clear(); FirebaseFirestore.getInstance().collection("/users").document(usuario.getUid()).set(usuario); // apagar disciplinas selecionadas do banco de dados invalidateOptionsMenu(); } }
Markdown
UTF-8
4,784
3.140625
3
[ "BSD-3-Clause", "CC-BY-SA-4.0", "CC-BY-4.0" ]
permissive
--- id: 587d7fa7367417b2b2512bc5 title: Work with Dynamic Data in D3 required: - src: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js' challengeType: 6 videoUrl: '' localeTitle: Работа с динамическими данными в D3 --- ## Description <section id="description"> Последние две проблемы охватывают основы динамического отображения данных с помощью D3 с использованием методов <code>data()</code> и <code>enter()</code> . Эти методы берут набор данных и вместе с методом <code>append()</code> создают новый элемент DOM для каждой записи в наборе данных. В предыдущей задаче вы создали новый элемент <code>h2</code> для каждого элемента массива <code>dataset</code> , но все они содержали один и тот же текст «Новое название». Это связано с тем, что вы не использовали данные, привязанные к каждому из элементов <code>h2</code> . Метод D3 <code>text()</code> может принимать строку или функцию обратного вызова в качестве аргумента: <code>selection.text((d) =&gt; d)</code> В приведенном выше примере параметр <code>d</code> ссылается на одну запись в наборе данных, которая связана с выбором к. Используя текущий пример как контекст, первый элемент <code>h2</code> привязан к 12, второй элемент <code>h2</code> привязан к 31, третий элемент <code>h2</code> привязан к 22 и так далее. </section> ## Instructions <section id="instructions"> Измените метод <code>text()</code> чтобы каждый элемент <code>h2</code> отображал соответствующее значение из массива <code>dataset</code> с одним пробелом и «USD». Например, первый заголовок должен быть «12 долларов США». </section> ## Tests <section id='tests'> ```yml tests: - text: Первый <code>h2</code> должен иметь текст «12 USD». testString: 'assert($("h2").eq(0).text() == "12 USD", "The first <code>h2</code> should have the text "12 USD".");' - text: Второй <code>h2</code> должен иметь текст «31 USD». testString: 'assert($("h2").eq(1).text() == "31 USD", "The second <code>h2</code> should have the text "31 USD".");' - text: Третий <code>h2</code> должен иметь текст «22 USD». testString: 'assert($("h2").eq(2).text() == "22 USD", "The third <code>h2</code> should have the text "22 USD".");' - text: Четвертый <code>h2</code> должен иметь текст «17 USD». testString: 'assert($("h2").eq(3).text() == "17 USD", "The fourth <code>h2</code> should have the text "17 USD".");' - text: Пятый <code>h2</code> должен иметь текст «25 USD». testString: 'assert($("h2").eq(4).text() == "25 USD", "The fifth <code>h2</code> should have the text "25 USD".");' - text: Шестой <code>h2</code> должен иметь текст «18 USD». testString: 'assert($("h2").eq(5).text() == "18 USD", "The sixth <code>h2</code> should have the text "18 USD".");' - text: Седьмой <code>h2</code> должен иметь текст «29 USD». testString: 'assert($("h2").eq(6).text() == "29 USD", "The seventh <code>h2</code> should have the text "29 USD".");' - text: Восьмой <code>h2</code> должен иметь текст «14 USD». testString: 'assert($("h2").eq(7).text() == "14 USD", "The eighth <code>h2</code> should have the text "14 USD".");' - text: Девятый <code>h2</code> должен иметь текст «9 USD». testString: 'assert($("h2").eq(8).text() == "9 USD", "The ninth <code>h2</code> should have the text "9 USD".");' ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='html-seed'> ```html <body> <script> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9]; d3.select("body").selectAll("h2") .data(dataset) .enter() .append("h2") // Add your code below this line .text("New Title"); // Add your code above this line </script> </body> ``` </div> </section> ## Solution <section id='solution'> ```js // solution required ``` </section>
Ruby
UTF-8
564
3.375
3
[]
no_license
# Хэши по природе своей не упорядочены ни по ключам, ни по значениям. # Чтобы отсортировать хэш, Ruby преобразует его в массив, который затем сортирует. # Понятно, что и результатом является массив. names = {"Jack"=>"Ruby","Monty"=>"Python", "Blaise"=>"Pascal", "Minnie"=>"Perl"} p list = names.sort # list равно: # [["Blaise","Pascal"], ["Jack","Ruby"], ["Minnie","Perl"], ["Monty","Python"]]
Swift
UTF-8
2,671
2.828125
3
[]
no_license
// // LoginView.swift // gefen // // Created by or Leumi on 16/03/2018. // Copyright © 2018 Or. All rights reserved. // import UIKit import Cartography protocol LoginViewDelegate: class { func loginViewUserPressedLoginButton(withUserName UserName:String, andWithPassword password:String) } class LoginView: UIView { //MARK: - variables weak var delegate:LoginViewDelegate? let loginButton:UIButton let userNameTextField:TextFieldWithHintText let passwordTextField:TextFieldWithHintText //MARK: - initialozations init() { loginButton = UIButton() userNameTextField = TextFieldWithHintText() passwordTextField = TextFieldWithHintText() super.init(frame: CGRect.zero) initViews() setupConstraints() } func initViews() { loginButton.setTitle(NSLocalizedString("LoginButtonTitle", comment: ""), for: .normal) loginButton.backgroundColor = UIColor.blue loginButton.layer.cornerRadius = 5 loginButton.isUserInteractionEnabled = true loginButton.addTarget(self, action: #selector(didPressLoginButton(_:)), for: .touchUpInside) loginButton.setTitleColor(UIColor.gray, for: .highlighted) userNameTextField.setHintText(NSLocalizedString("userName", comment: "")) passwordTextField.isSecureTextEntry = true passwordTextField.setHintText(NSLocalizedString("password", comment: "")) addSubview(loginButton) addSubview(userNameTextField) addSubview(passwordTextField) clipsToBounds = true } func setupConstraints() { constrain(loginButton , userNameTextField, passwordTextField, self) {button, userNameTextField, passTextField, superView in userNameTextField.top == superView.top userNameTextField.left == superView.left userNameTextField.right == superView.right passTextField.top == userNameTextField.bottom + 20 passTextField.left == superView.left passTextField.right == superView.right button.top == passTextField.bottom + 20 button.centerX == superView.centerX button.bottom == superView.bottom } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - login Button @objc func didPressLoginButton(_ sender: UIButton!) { delegate?.loginViewUserPressedLoginButton(withUserName: userNameTextField.getText(), andWithPassword: passwordTextField.getText()) } }
Python
UTF-8
3,330
2.796875
3
[]
no_license
# removes genes and species from the results file that are no longer in the new markers cutoff file import json import os import argparse import re import csv def pathfinder(outpath): '''makes output dir''' if not os.access(outpath, os.F_OK): os.mkdir(outpath) def reader(path): '''opens the report file''' with open(path, 'r') as f: data = json.load(f) return data def glist(marker, testtypename): '''opens the new markers file and retrieves all the gene names''' with open(os.path.join(marker, testtypename)+'.markers', 'r') as f: try: # check to see if the marker is in json format genelist = [] for key in json.load(f).keys(): # iterates through all gene names in the markers file genelist.append(key) # collects all gene names in genelist except ValueError: f.seek(0) genelist=[] data = f.readlines()[1:] # skips the first header line and reads the data data = [line.split()[0] for line in data] # gets the names only of genes from new markers file if data != []: # skips empty names for line in data: # takes the name out from the list genelist.append(line) # adds names to genelist return genelist def gatherer(data, genelist): '''creates the new set of genes and genomes''' d = {} GenesMissingGenomes={} GenomesMissingGenes={} for gene in data["GenesMissingGenomes"]: if gene in genelist: #checks if the name of the gene is in the new markers file, if so, adds it to the dictionary for the gene portion GenesMissingGenomes[gene] = data["GenesMissingGenomes"][gene] for genome in data["GenomesMissingGenes"]: GenomesMissingGenes[genome] = [] for mgenes in data["GenomesMissingGenes"][genome]: if mgenes in genelist: GenomesMissingGenes[genome].append(mgenes) #adds every gene present in the markers file to a particular genome d['GenesMissingGenomes'] = GenesMissingGenomes#addes the two dictionaries into one larger dictionary for writing d['GenomesMissingGenes'] = GenomesMissingGenes return d def writer(outpath, outfile, d): with open(os.path.join(outpath, outfile), 'a') as f: json.dump(d, f, indent=4, sort_keys=True) def arguments(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--outpath', default='/home/cintiq/PycharmProjects/misty/mistreport/', help='output directory for the report') parser.add_argument('-n', '--outfile', default='refinedreport.json', help='output file name') parser.add_argument('--marker', default='/home/cintiq/PycharmProjects/misty/marker/', help='directory containing new .markers file of interest') parser.add_argument('--testtypename', required=True, help='the name of the test run') parser.add_argument('path') return parser.parse_args() def process(path, outpath, outfile, marker, testtypename): pathfinder(outpath) data = reader(path) genelist = glist(marker, testtypename) d = gatherer(data, genelist) writer(outpath, outfile, d) def main(): args = arguments() process(args.path, args.outpath, args.outfile, args.marker, args.testtypename) if __name__ == '__main__': main()
Markdown
UTF-8
983
2.625
3
[ "BSD-3-Clause" ]
permissive
# An MPI Contention Benchmark This repository contains a benchmark code that performs MPI communication and computation simultaneously. The computational kernel used in the code is the Triad kernel from the [STREAM Triad benchmark](https://www.cs.virginia.edu/stream/) originally developed by John D. McCalpin. ## Build In order to compile the system, it is sufficient to write the following on most Unix/Linux systems icpc -O3 -openmp -std=c++11 -o main.o -c main.cc mpicxx -o mpi_stream_ring main.o -O3 -openmp -std=c++11 ## Run The input to the application is the number of bytes (message size) to communicate between the different MPI processes. For example, in order to define a message size of 4 MB, the input should be 419430 . In order to execute the application on four nodes, using one MPI process per node on a system where SLURM is the default resource scheduler, please write: srun --ntaks 4 ./mpi_stream_ring 4194304 ## License Please see the LICENSE file.
Python
UTF-8
8,763
2.71875
3
[]
no_license
from bs4 import BeautifulSoup import datetime import requests import time def sign_coordinate(coordinate): if 'W' in coordinate or 'S' in coordinate: direction = -1 coordinate = coordinate.rstrip('S') coordinate = coordinate.rstrip('W') elif 'E' in coordinate or 'N' in coordinate: direction = 1 coordinate = coordinate.rstrip('N') coordinate = coordinate.replace('E', '') try: coordinate = float(coordinate) * direction except ValueError: coordinate = None return coordinate class Webpage: def __init__(self): self.soup = None self.html = None self.table1 = None def to_file(self): with open('page.html', 'w') as outfile: outfile.write(self.html) def from_file(self): with open('page.html', 'r') as infile: self.soup = BeautifulSoup(infile.read(), 'lxml') class VesselPage(Webpage): def __init__(self): super(VesselPage, self).__init__() self.vessel_params = dict() self.url = None def download(self, url): self.vessel_params['url'] = url session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0'}) download_success = False while download_success == False: try: ret = session.get(url=url) self.html = ret.text download_success = True except requests.exceptions.ConnectionError: print('Download Failed. Retrying in 5 Seconds') time.sleep(5) self.soup = BeautifulSoup(self.html, 'lxml') if ret.status_code == 200: return True else: return False def parse(self): self.get_name() self.get_report_date() self.get_type() self.get_country() self.get_location() self.get_speed() self.get_imo() self.get_mmsi() self.get_built_year() self.get_length() self.get_width() self.get_gt() def in_database(self): in_database = True error_tags = self.soup.find_all('p', 'col-md-8') if len(error_tags) > 0: error_string = error_tags[0].contents[0] if 'temporary not in our database' in error_string: in_database = False return in_database def get_name(self): name = self.soup.find('title').contents[0].split(' - ')[0] self.vessel_params['name'] = name def get_report_date(self): date_tag = self.soup.find(text='Last report') if date_tag is not None: date_string = date_tag.parent.next_sibling.contents[1].strip() try: string_format = '%b %d, %Y %H:%M UTC' timestamp = datetime.datetime.strptime(date_string, string_format) except: print('could not extract timestamp from {}'.format(date_string)) timestamp = None else: timestamp = None self.vessel_params['date'] = timestamp def get_type(self): ship_type_tag = self.soup.find(text='AIS Type') if ship_type_tag is None: ship_type_tag = self.soup.find(text='Ship type') ship_type = ship_type_tag.parent.next_sibling.contents[0].strip() self.vessel_params['ship_type'] = ship_type def get_country(self): country_tags = self.soup.find_all(text='Flag') if len(country_tags[0].parent.next_sibling.contents) > 0: country = country_tags[0].parent.next_sibling.contents[0].strip() elif len(country_tags[1].parent.next_sibling.contents) > 0: country = country_tags[1].parent.next_sibling.contents[0].strip() else: print('could not find country') country = None self.vessel_params['country'] = country def get_location(self): coordiantes_tag = self.soup.find(text='Coordinates') if coordiantes_tag is not None: coordiantes_string = coordiantes_tag.parent.next_sibling.contents[0].strip() latitude = coordiantes_string.split('/')[0] longitude = coordiantes_string.split('/')[1] latitude = sign_coordinate(latitude) longitude = sign_coordinate(longitude) else: latitude = None longitude = None self.vessel_params['latitude'] = latitude self.vessel_params['longitude'] = longitude def get_speed(self): speed_tag = self.soup.find(text='Course / Speed') if speed_tag is not None: speed_string = speed_tag.parent.next_sibling.contents[0].strip() speed = speed_string.split('/')[1].split('kn')[0].strip() try: speed = float(speed) except ValueError: print('could not extract speed from {}'.format(speed_string)) speed = None else: speed = None self.vessel_params['speed'] = speed def get_imo(self): if self.soup.find(text='IMO / MMSI') is not None: imo_tag = self.soup.find(text='IMO / MMSI') imo_string = imo_tag.parent.next_sibling.contents[0].strip() imo = imo_string.split('/')[0].strip() elif self.soup.find(text='IMO number') is not None: imo_tag = self.soup.find(text='IMO number') imo = imo_tag.parent.next_sibling.contents[0].strip() try: imo = int(imo) except ValueError: print('could not extract imo from {}'.format(imo_string)) imo = None self.vessel_params['imo'] = imo def get_mmsi(self): if self.soup.find(text='IMO / MMSI') is not None: mmsi_tag = self.soup.find(text='IMO / MMSI') mmsi_string = mmsi_tag.parent.next_sibling.contents[0].strip() mmsi = mmsi_string.split('/')[1].strip() try: mmsi = int(mmsi) except ValueError: print('could not extract mmsi from {}'.format(mmsi_string)) mmsi = None else: mmsi = None self.vessel_params['mmsi'] = mmsi def get_built_year(self): built_string = self.soup.find(text='Year of Built').parent.next_sibling.contents[0].strip() try: built = int(built_string) except ValueError: print('could not extract built year from {}'.format(built_string)) built = None self.vessel_params['built'] = built def get_length(self): if self.soup.find(text='Length / Beam') is not None: length_tag = self.soup.find(text='Length / Beam') length_string = length_tag.parent.next_sibling.contents[0].strip() length_string = length_string.split('/')[0].strip() elif self.soup.find(text='Length Overall (m)') is not None: length_tag = self.soup.find(text='Length Overall (m)') length_string = length_tag.parent.next_sibling.contents[0].strip() try: length = float(length_string) except ValueError: length = None print('could not extract length from {}'.format(length_string)) except AttributeError: length = None print('could not extract length from {}'.format(length_string)) self.vessel_params['length'] = length def get_width(self): if self.soup.find(text='Length / Beam') is not None: width_tag = self.soup.find(text='Length / Beam') width_string = width_tag.parent.next_sibling.contents[0].strip() if len(width_string.split('/')) > 1: width_string = width_string.split('/')[1].strip().split(' ')[0] else: width_string = None elif self.soup.find(text='Beam (m)') is not None: width_tag = self.soup.find(text='Beam (m)') width_string = width_tag.parent.next_sibling.contents[0].strip() try: width = float(width_string) except (IndexError, ValueError, AttributeError, TypeError) as e: print('could not extract width from {}'.format(width_string)) width = None self.vessel_params['width'] = width def get_gt(self): gt_string = self.soup.find(text='Gross Tonnage').parent.next_sibling.contents[0].strip() try: gt = float(gt_string) except ValueError: gt = None print('could not extract gt from {}'.format(gt_string)) self.vessel_params['gt'] = gt
Java
UTF-8
1,239
1.820313
2
[]
no_license
package biz.mercue.impactweb.util; import java.util.Map; public class YamlProperty { private String ip; private Map<String, String> jdbc; private Map<String, String> hibernate; private Map<String, String> path; private Map<String, String> url; private Map<String, String> mail; private Map<String, String> tuya; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Map<String, String> getJdbc() { return jdbc; } public void setJdbc(Map<String, String> jdbc) { this.jdbc = jdbc; } public Map<String, String> getHibernate() { return hibernate; } public void setHibernate(Map<String, String> hibernate) { this.hibernate = hibernate; } public Map<String, String> getPath() { return path; } public void setPath(Map<String, String> path) { this.path = path; } public Map<String, String> getUrl() { return url; } public void setUrl(Map<String, String> url) { this.url = url; } public Map<String, String> getMail() { return mail; } public void setMail(Map<String, String> mail) { this.mail = mail; } public Map<String, String> getTuya() { return tuya; } public void setTuya(Map<String, String> tuya) { this.tuya = tuya; } }
C++
UTF-8
1,815
2.546875
3
[ "MIT" ]
permissive
#include "letterboxedscreenbuffer.h" #include <QImage> #include <QPainter> class LetterboxedScreenBufferPrivate { public: ScreenBuffer *sourceBuffer; QSize size; QRect sourceRect; QTransform coordinateTransform; }; LetterboxedScreenBuffer::LetterboxedScreenBuffer(ScreenBuffer *source, QObject *parent) : QObject(parent), d_ptr(new LetterboxedScreenBufferPrivate) { Q_D(LetterboxedScreenBuffer); d->sourceBuffer = source; Q_ASSERT(d->sourceBuffer); } LetterboxedScreenBuffer::~LetterboxedScreenBuffer() { delete d_ptr; } QImage LetterboxedScreenBuffer::createImage() const { Q_D(const LetterboxedScreenBuffer); auto sourceImage = d->sourceBuffer->createImage(); if (!sourceImage.isNull()) { QImage image(d->size, sourceImage.format()); QPainter painter(&image); painter.fillRect(image.rect(), Qt::black); painter.drawImage(d->sourceRect, sourceImage); return image; } return QImage(); } QPoint LetterboxedScreenBuffer::mapToSource(const QPoint &point) const { Q_D(const LetterboxedScreenBuffer); QPoint p = d->coordinateTransform.map(point); p.setX(qMin(qMax(p.x(), 0), d->sourceRect.width() - 1)); p.setY(qMin(qMax(p.y(), 0), d->sourceRect.height() - 1)); return p; } void LetterboxedScreenBuffer::resize(const QSize &size) { Q_D(LetterboxedScreenBuffer); d->size = size; auto sourceImage = d->sourceBuffer->createImage(); if (!sourceImage.isNull()) { d->sourceRect.setSize(sourceImage.size()); d->sourceRect.moveCenter(QPoint(size.width() / 2, size.height() / 2)); d->coordinateTransform.reset(); d->coordinateTransform.translate(-d->sourceRect.left(), -d->sourceRect.top()); } }
Python
UTF-8
471
3.796875
4
[]
no_license
#!/usr/bin/env python3 import random # possible O(n) runtime! def bogo_sort(arr): def is_sorted(a): return all(a[i-1] <= a[i] for i in range(1, len(a))) while not is_sorted(arr): random.shuffle(arr) def main(): arr = [] size = input('How many numbers do you want to sort? ') for i in range(int(size)): arr.append(random.randint(0, 1000)) print(arr) bogo_sort(arr) print(arr) if __name__ == "__main__": main()
C#
UTF-8
540
3.25
3
[]
no_license
//Not my code public class Solution { public int MajorityElement(int[] nums) { Dictionary<int, int> count = new Dictionary<int, int>(); for(int i=0; i<nums.Length; i++){ if(count.ContainsKey(nums[i])){ count[nums[i]]++; } else{ count.Add(nums[i], 1); } if(count[nums[i]] > nums.Length/2){ return nums[i]; } } return Int32.MaxValue; } }
Java
UTF-8
908
2.953125
3
[]
no_license
/* * Employee.java * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package purchaseorder; import java.io.*; /** * * @author vincent */ public class Employee { // stores employee name public String fName = ""; //stores employees department name public String department = ""; //stores employees id public String empId = ""; //stores employees designation public String designation = ""; /** Creates a new instance of Employee */ public Employee() { } /** displays the details of employee */ public void displayEmployee() { System.out.println( "Employee Details: " ); System.out.println( " Name - " + fName); System.out.println( " Employee Id - " + empId); System.out.println( " Department - " + department); System.out.println( " Designation - " + designation); } }
C#
UTF-8
5,496
2.59375
3
[ "MIT" ]
permissive
using System; using System.Collections; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace 爬虫 { public partial class Form1 : Form { Hashtable hashtable = new Hashtable(); private string _url; public string Url { get { return _url; } set { if (value.StartsWith(@"http://")|value.StartsWith(@"https://")) { _url = value; } else { _url = @"http://" + value; } } } public Form1() { InitializeComponent(); } public delegate Hashtable GetMatchDelegate(string s); public delegate void DownloadMatchDelegate(string s,string fileName); //点击按钮时入口 private void button1_Click(object sender, EventArgs e) { GetMatchDelegate GetUrlMatchesDelegate = GetMatches; treeView1.Nodes.Add("正在下载首页..."); GetUrlMatchesDelegate.BeginInvoke(Url, getMatchCompleteCallback, GetUrlMatchesDelegate); } //被委托的获得hasttable的函数 private Hashtable GetMatches(string s) { Url = textBox1.Text; WebClient client = new WebClient(); byte[] pageData = client.DownloadData(Url); string Htmlpage = Encoding.Default.GetString(pageData); client.Dispose(); Regex rx = new Regex(@"(?:(?:http|ftp|https)://)(?:(?:[a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|(?:[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(?<fileName>/[a-zA-Z0-9\&%_\./-~-]*)?"); MatchCollection ms = rx.Matches(Htmlpage); foreach (Match m in ms) { try { hashtable.Add(m.Value, false); } catch (Exception e) { } } return hashtable; } private void DownloadMatchcompleteCallback(IAsyncResult ar) { (ar.AsyncState as DownloadMatchDelegate).EndInvoke(ar); } private void downloadMatchAction(string s,string fileName) { if (imagecontrol.Checked) { if (fileName.EndsWith("jpg")) { string msg = "下载完成:" + s; WebClient client = new WebClient(); try { if (fileName != "") { client.DownloadFile(s, fileName); client.Dispose(); } } catch (Exception e) { } if (InvokeRequired) { this.BeginInvoke(new AddMsgsDelegate(AddMsgs), new object[] { msg }); } else { this.AddMsgs(msg); } } } else { string msg = "下载完成:" + s; WebClient client = new WebClient(); try { if (fileName != "") { client.DownloadFile(s, fileName); client.Dispose(); } } catch (Exception e) { } if (InvokeRequired) { this.BeginInvoke(new AddMsgsDelegate(AddMsgs), new object[] { msg }); } else { this.AddMsgs(msg); } } } private string getFileName(string s) { if (s != null) { string fileName; Match m = Regex.Match(s, @"[0-9a-zA-Z&=-]{1,}?\.(png|php|html|xml|js|jpg)"); fileName = m.Value; return fileName; } else return null; } private void getMatchCompleteCallback(IAsyncResult iar) { Hashtable hashtable = (iar.AsyncState as GetMatchDelegate).EndInvoke(iar); string msg = hashtable.Count.ToString() + "个所有类型链接"; if (this.InvokeRequired) { this.BeginInvoke(new AddMsgsDelegate(AddMsgs),new object[] { msg }); } else { this.AddMsgs(msg); } string fileName; foreach(DictionaryEntry de in hashtable) { fileName = this.getFileName(de.Key as string); if (fileName == null) break; DownloadMatchDelegate downloadMatchdelegate = downloadMatchAction; downloadMatchdelegate.BeginInvoke(de.Key as string, fileName, DownloadMatchcompleteCallback, downloadMatchdelegate); } } private delegate void AddMsgsDelegate(String msg); private void AddMsgs(string msg) { treeView1.Nodes.Add(msg); } } }
Java
UTF-8
1,281
2.875
3
[]
no_license
package com.github.marceloleite2604.manager.util.configuration; import java.util.Enumeration; import java.util.Properties; public class Configuration { public static final String DEFAULT_CONFIGURATION_FILE_PATH = "src/main/resources/application.properties"; private static Configuration INSTANCE; private Properties properties; private Configuration(String configurationFilePath) { properties = new ConfigurationFileReader(configurationFilePath).readConfigurationFile(); } private Configuration() { this(DEFAULT_CONFIGURATION_FILE_PATH); } public static final Configuration getInstance() { if (INSTANCE == null) { INSTANCE = new Configuration(); } return INSTANCE; } public void loadConfigurationfile(String configurationFilePath) { INSTANCE = new Configuration(configurationFilePath); } public String getConfiguration(Property property) { Enumeration<Object> enumerationKeys = properties.keys(); while (enumerationKeys.hasMoreElements()) { String name = (String) enumerationKeys.nextElement(); if (property.getName().equals(name)) { return properties.getProperty(name); } } throw new RuntimeException("Property \"" + property + "\" not found on configuration file."); } }
Swift
UTF-8
2,629
2.859375
3
[]
no_license
// // PresentView.swift // Is This Your Card? // // Created by Kinney Kare on 7/29/21. // import SwiftUI struct PresentView: View { @State var contentView: ContentView @State var oneIsTapped = false @State var twoIsTapped = false @State var threeIsTapped = false @State var fourIsTapped = false @State var navTitleText = "Select Two Piles" @State var buttonText = "Continue" @State var show = false @Namespace var namespace var body: some View { ZStack { Image("coolBG") .ignoresSafeArea() VStack { if !show { FourPilesView(contentView: $contentView, oneIsTapped: $oneIsTapped, twoIsTapped: $twoIsTapped, threeIsTapped: $threeIsTapped, fourIsTapped: $fourIsTapped) // .matchedGeometryEffect(id: "4cards", in: namespace) .frame(width: UIScreen.screenWidth, height: UIScreen.screenHeight, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) } else { TwoPilesView(contentView: $contentView, oneIsTapped: $oneIsTapped, twoIsTapped: $twoIsTapped, navTitleText: navTitleText) // .matchedGeometryEffect(id: "4cards", in: namespace) .frame(width: UIScreen.screenWidth, height: UIScreen.screenHeight, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) } PreviewButtonView(buttonText: $buttonText, isPressed: $show, oneIsTapped: $oneIsTapped, twoIsTapped: $twoIsTapped, threeIsTapped: $threeIsTapped, fourIsTapped: $fourIsTapped, navTitle: $navTitleText) .padding(.bottom, 200) } } .navigationBarTitleDisplayMode(.inline) .navigationTitle(navTitleText) } } struct PresentView_Previews: PreviewProvider { static var previews: some View { PresentView(contentView: ContentView(theCard: Card(card: "spade11"), newDeck: [ Card(card: "club1"), Card(card: "club2"), Card(card: "club3"), Card(card: "club4"), Card(card: "diamond12"), Card(card: "diamond13"), Card(card: "heart1"), Card(card: "heart2"), Card(card: "heart12"), Card(card: "heart13"), Card(card: "spade1"), Card(card: "spade2"), Card(card: "diamond3"), Card(card: "club10"), Card(card: "spade11"), Card(card: "heart13") ])) } }
PHP
UTF-8
24,370
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class ControllerCarrito extends Controller { /* Carrito es un JSON de la siguiente estructura: {"carrito": { "items":[ { "id": "id1" "categoria": "vuelo", "cantidad" : "3", "precio" : "20000", "descuento" : "10", "subtotal" : "60000" }, ... ], "total" = "54000"; } } */ public function mostrarCarrito(){ $carrito = null; if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ $carrito = new \stdClass(); $carrito->items = []; $carrito->total = 0; } return view('carrito/carrito')->with("carrito", $carrito); } public function eliminarDelCarrito(Request $req){ $index = $req->input('index'); if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); $items = $carrito->items; $carrito->total = $carrito->total - $carrito->items[$index]->subtotal; array_splice($carrito->items, $index, 1); Session::put("carrito", json_encode($carrito)); return json_encode($carrito); } } public function addHabitacionAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } $id = $request->input("id"); $nombreHotel = $request->input("nombre"); $fecha_inicio_reserva = $request->input("fecha_inicio"); $fecha_fin_reserva = $request->input("fecha_fin"); $cantidad = $request->input("cantidad"); $habitacion = \App\Models\Habitacion::findOrFail($id); $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->categoria = 'Habitación'; $nuevoItem->subcategoria = 'Arriendos'; $nuevoItem->precio = $habitacion->precio_por_noche; $nuevoItem->nombre = $nombreHotel; $nuevoItem->fecha_inicio = $fecha_inicio_reserva; $nuevoItem->fecha_fin = $fecha_fin_reserva; $nuevoItem->cantidad = $cantidad; $nuevoItem->descuento = $habitacion->descuento; $nuevoItem->subtotal= $nuevoItem->precio * $cantidad; array_push($carrito->items, $nuevoItem); $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); } public function addAutoPaqueteAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } $id = $request->input("id"); $id_paquete = $request->input("id_paquete"); $nombreAuto = $request->input("nombre"); $cantidad = (int)$request->input("cantidad"); $inicio = $request->input("inicio"); $fin = $request->input("fin"); $auto = \App\Models\Auto::findOrFail($id); $paquete = \App\Models\Paquete::findOrFail($id_paquete); $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->id_paquete = $id_paquete; $nuevoItem->categoria = 'Paquete'; $nuevoItem->subcategoria = 'Auto'; $nuevoItem->tipo_paquete = 'Vuelo + Auto'; $nuevoItem->precio = $auto->precio_por_dia; $nuevoItem->nombre = $nombreAuto; $nuevoItem->cantidad = $cantidad; $nuevoItem->inicio_arriendo = $inicio; $nuevoItem->fin_arriendo = $fin; $nuevoItem->descuento = $auto->descuento; $nuevoItem->descuento_paquete = $paquete->descuento_paquete; $nuevoItem->subtotal= $nuevoItem->precio * $cantidad; array_push($carrito->items, $nuevoItem); $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); //return json_encode($carrito); } public function addAutoAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } $id = $request->input("id"); $nombreAuto = $request->input("nombre"); $cantidad = $request->input("cantidad"); $inicio = $request->input("inicio"); $fin = $request->input("fin"); $auto = \App\Models\Auto::findOrFail($id); $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->categoria = 'Auto'; $nuevoItem->subcategoria = 'Arriendos'; $nuevoItem->precio = $auto->precio_por_dia; $nuevoItem->nombre = $nombreAuto; $nuevoItem->cantidad = $cantidad; $nuevoItem->inicio_arriendo = $inicio; $nuevoItem->fin_arriendo = $fin; $nuevoItem->descuento = $auto->descuento; $nuevoItem->subtotal= $nuevoItem->precio * $cantidad; array_push($carrito->items, $nuevoItem); $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); } public function addActividadAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } $id = $request->input("id"); $nombreActividad = $request->input("nombre"); $cantidad = $request->input("cantidad"); $actividad = \App\Models\Actividad::findOrFail($id); $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->categoria = 'Actividad'; $nuevoItem->subcategoria = 'Reservas'; $nuevoItem->precio = $actividad->valor_entrada; $nuevoItem->nombre = $nombreActividad; $nuevoItem->cantidad = $cantidad; $nuevoItem->descuento = $actividad->descuento; $nuevoItem->subtotal= $nuevoItem->precio * $cantidad; array_push($carrito->items, $nuevoItem); $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); } public function addTrasladoAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } $id = $request->input("id_chofer"); $pais = $request->input("pais"); $ciudad = $request->input("ciudad"); $aeropuerto = $request->input("aeropuerto"); $hotel = $request->input("hotel"); $formato_traslado = $request->input("formato_traslado"); $num_pasajeros = $request->input("pasajeros"); $distancia = $request->input("distancia"); $fecha_traslado = $request->input("fecha_traslado"); $hora_traslado = $request->input("hora_traslado"); $minutos_traslado = $request->input("minutos_traslado"); $hora_formatted = \Carbon\Carbon::createFromTime($hora_traslado, $minutos_traslado,'00')->format('H:i:s'); $chofer = \App\Models\Chofer::findOrFail($id); $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->categoria = 'Traslado'; $nuevoItem->subcategoria = 'Compra'; $nuevoItem->formato_traslado = $formato_traslado; $nuevoItem->precio = $chofer->tarifa_por_kilometro; $nuevoItem->pais = $pais; $nuevoItem->ciudad = $ciudad; $nuevoItem->aeropuerto = $aeropuerto; $nuevoItem->hotel = $hotel; $nuevoItem->distancia = $distancia; $nuevoItem->fecha_traslado = $fecha_traslado; $nuevoItem->hora_traslado = $hora_formatted; $nuevoItem->nombre = 'Chofer: '.$chofer->name; $nuevoItem->num_pasajeros = $num_pasajeros; $nuevoItem->cantidad = 1; $nuevoItem->descuento = 0; $nuevoItem->subtotal= $nuevoItem->precio * $distancia; array_push($carrito->items, $nuevoItem); $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); } public function addVueloPaqueteAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } $id = $request->input("id"); $tempData = html_entity_decode($request->input("pasajes")); $pasajes = json_decode($tempData, true); $num_turista= $pasajes['turista']; $num_ejecutivo = $pasajes['ejecutivo']; $num_pc = $pasajes['pc']; $id_paquete = $request->input("id_paquete"); $vuelo = \App\Models\Vuelo::findOrFail($id); $paquete = \App\Models\Paquete::findOrFail($id_paquete); if($num_turista > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->id_paquete = $id_paquete; $nuevoItem->nombre = $vuelo->nombre_avion; $nuevoItem->categoria = 'Paquete'; $nuevoItem->tipo_paquete = 'Vuelo + Auto'; $nuevoItem->subcategoria = 'Vuelo'; $nuevoItem->tipo_pasaje = 'Turista'; $nuevoItem->precio = $vuelo->valor_turista; $nuevoItem->descuento = $vuelo->descuento; $nuevoItem->descuento_paquete = $paquete->descuento_paquete; $nuevoItem->cantidad = $num_turista; $nuevoItem->subtotal= round($nuevoItem->precio * $num_turista - $nuevoItem->precio * $num_turista * ($paquete->descuento/100) - $nuevoItem->precio * $num_turista * ($vuelo->descuento/100)); array_push($carrito->items, $nuevoItem); } if($num_ejecutivo > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->id_paquete = $id_paquete; $nuevoItem->nombre = $vuelo->nombre_avion; $nuevoItem->categoria = 'Paquete'; $nuevoItem->tipo_paquete = 'Vuelo + Auto'; $nuevoItem->subcategoria = 'Vuelo'; $nuevoItem->tipo_pasaje = 'Ejecutivo'; $nuevoItem->precio = $vuelo->valor_ejecutivo; $nuevoItem->descuento = $vuelo->descuento; $nuevoItem->descuento_paquete = $paquete->descuento_paquete; $nuevoItem->cantidad = $num_ejecutivo; $nuevoItem->subtotal= round($nuevoItem->precio * $num_ejecutivo - $nuevoItem->precio * $num_ejecutivo * ($paquete->descuento/100) - $nuevoItem->precio * $num_ejecutivo * ($vuelo->descuento/100)); array_push($carrito->items, $nuevoItem); } if($num_pc > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->id_paquete = $id_paquete; $nuevoItem->nombre = $vuelo->nombre_avion; $nuevoItem->categoria = 'Paquete'; $nuevoItem->tipo_paquete = 'Vuelo + Auto'; $nuevoItem->subcategoria = 'Vuelo'; $nuevoItem->tipo_pasaje = 'Primera Clase'; $nuevoItem->precio = $vuelo->valor_primera_clase; $nuevoItem->descuento = $vuelo->descuento; $nuevoItem->descuento_paquete = $paquete->descuento_paquete; $nuevoItem->cantidad = $num_pc; $nuevoItem->subtotal = round($nuevoItem->precio * $num_pc - $nuevoItem->precio * $num_ejecutivo * ($paquete->descuento/100) - $nuevoItem->precio * $num_pc * ($vuelo->descuento/100)); array_push($carrito->items, $nuevoItem); } $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); } public function addJointVueloAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } try{ $id_ida = $request->input("id_ida"); $id_vuelta = $request->input("id_vuelta"); $tempData = html_entity_decode($request->input("pasajes")); $pasajes = json_decode($tempData, true); $num_turista= $pasajes['turista']; $num_ejecutivo = $pasajes['ejecutivo']; $num_pc = $pasajes['pc']; $vuelo_ida = \App\Models\Vuelo::findOrFail($id_ida); $vuelo_vuelta = \App\Models\Vuelo::findOrFail($id_vuelta); if($num_turista > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id_ida; $nuevoItem->nombre = $vuelo_ida->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->subcategoria = 'Vuelo ida'; $nuevoItem->tipo_pasaje = 'Turista'; $nuevoItem->precio = $vuelo_ida->valor_turista; $nuevoItem->descuento = $vuelo_ida->descuento; $nuevoItem->cantidad = $num_turista; $nuevoItem->subtotal= round($nuevoItem->precio * $num_turista - $nuevoItem->precio * $num_turista * ($vuelo_ida->descuento/100)); $nuevoItem2 = clone $nuevoItem; array_push($carrito->items, $nuevoItem); $nuevoItem2->id = $id_vuelta; $nuevoItem2->nombre = $vuelo_vuelta->nombre_avion; $nuevoItem2->subcategoria = 'Vuelo vuelta'; $nuevoItem2->precio = $vuelo_vuelta->valor_turista; $nuevoItem2->subtotal= round($nuevoItem2->precio * $num_turista - $nuevoItem2->precio * $num_turista * ($vuelo_vuelta->descuento/100)); array_push($carrito->items, $nuevoItem2); } if($num_ejecutivo > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id_ida; $nuevoItem->nombre = $vuelo_ida->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->subcategoria = 'Vuelo ida'; $nuevoItem->tipo_pasaje = 'Ejecutivo'; $nuevoItem->precio = $vuelo_ida->valor_ejecutivo; $nuevoItem->descuento = $vuelo_ida->descuento; $nuevoItem->cantidad = $num_ejecutivo; $nuevoItem->subtotal= round($nuevoItem->precio * $num_ejecutivo - $nuevoItem->precio * $num_ejecutivo * ($vuelo_ida->descuento/100)); $nuevoItem2 = clone $nuevoItem; array_push($carrito->items, $nuevoItem); $nuevoItem2->id = $id_vuelta; $nuevoItem2->nombre = $vuelo_vuelta->nombre_avion; $nuevoItem2->subcategoria = 'Vuelo vuelta'; $nuevoItem2->precio = $vuelo_vuelta->valor_ejecutivo; $nuevoItem2->subtotal= round($nuevoItem2->precio * $num_ejecutivo - $nuevoItem2->precio * $num_ejecutivo * ($vuelo_vuelta->descuento/100)); array_push($carrito->items, $nuevoItem2); } if($num_pc > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id_ida; $nuevoItem->nombre = $vuelo_ida->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->subcategoria = 'Vuelo Ida'; $nuevoItem->tipo_pasaje = 'Primera Clase'; $nuevoItem->precio = $vuelo_ida->valor_primera_clase; $nuevoItem->descuento = $vuelo_ida->descuento; $nuevoItem->cantidad = $num_pc; $nuevoItem->subtotal = round($nuevoItem->precio * $num_pc - $nuevoItem->precio * $num_pc * ($vuelo_ida->descuento/100)); $nuevoItem2 = clone $nuevoItem; array_push($carrito->items, $nuevoItem); $nuevoItem2->id = $id_vuelta; $nuevoItem2->nombre = $vuelo_vuelta->nombre_avion; $nuevoItem2->subcategoria = 'Vuelo vuelta'; $nuevoItem2->precio = $vuelo_vuelta->valor_primera_clase; $nuevoItem2->subtotal= round($nuevoItem2->precio * $num_pc - $nuevoItem2->precio * $num_pc * ($vuelo_vuelta->descuento/100)); array_push($carrito->items, $nuevoItem2); } $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); }catch(Exception $e){ return redirect('/vuelos')->with('failure', 'Hubo un error al agregar al carrito'); } } public function addJointVueloPaqueteAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } try{ if(Session::has('tipo_paquete')){ $tipo_paquete = Session::get('tipo_paquete'); Switch($tipo_paquete){ case "2": $nombre_paquete = 'Vuelo + Auto'; break; case "1": $nombre_paquete = 'Vuelo + Hotel'; break; } }else{ return redirect('/paquetes')->with('failure', 'Hubo un error al procesar el paquete!'); } $id_ida = $request->input("id_ida"); $id_vuelta = $request->input("id_vuelta"); $tempData = html_entity_decode($request->input("pasajes")); $pasajes = json_decode($tempData, true); $num_turista= $pasajes['turista']; $num_ejecutivo = $pasajes['ejecutivo']; $num_pc = $pasajes['pc']; $vuelo_ida = \App\Models\Vuelo::findOrFail($id_ida); $vuelo_vuelta = \App\Models\Vuelo::findOrFail($id_vuelta); $id_paquete = $request->input('id_paquete'); if($num_turista > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id_ida; $nuevoItem->id_paquete = $id_paquete; $nuevoItem->nombre = $vuelo_ida->nombre_avion; $nuevoItem->categoria = 'Paquete'; $nuevoItem->tipo_paquete = $nombre_paquete; $nuevoItem->subcategoria = 'Vuelo ida'; $nuevoItem->tipo_pasaje = 'Turista'; $nuevoItem->precio = $vuelo_ida->valor_turista; $nuevoItem->descuento = $vuelo_ida->descuento; $nuevoItem->cantidad = $num_turista; $nuevoItem->subtotal= round($nuevoItem->precio * $num_turista - $nuevoItem->precio * $num_turista * ($vuelo_ida->descuento/100)); $nuevoItem2 = clone $nuevoItem; array_push($carrito->items, $nuevoItem); $nuevoItem2->id = $id_vuelta; $nuevoItem2->nombre = $vuelo_vuelta->nombre_avion; $nuevoItem2->subcategoria = 'Vuelo vuelta'; $nuevoItem2->precio = $vuelo_vuelta->valor_turista; $nuevoItem2->subtotal= round($nuevoItem2->precio * $num_turista - $nuevoItem2->precio * $num_turista * ($vuelo_vuelta->descuento/100)); array_push($carrito->items, $nuevoItem2); } if($num_ejecutivo > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id_ida; $nuevoItem->id_paquete = $id_paquete; $nuevoItem->nombre = $vuelo_ida->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->tipo_paquete = $nombre_paquete; $nuevoItem->subcategoria = 'Vuelo ida'; $nuevoItem->tipo_pasaje = 'Ejecutivo'; $nuevoItem->precio = $vuelo_ida->valor_ejecutivo; $nuevoItem->descuento = $vuelo_ida->descuento; $nuevoItem->cantidad = $num_ejecutivo; $nuevoItem->subtotal= round($nuevoItem->precio * $num_ejecutivo - $nuevoItem->precio * $num_ejecutivo * ($vuelo_ida->descuento/100)); $nuevoItem2 = clone $nuevoItem; array_push($carrito->items, $nuevoItem); $nuevoItem2->id = $id_vuelta; $nuevoItem2->nombre = $vuelo_vuelta->nombre_avion; $nuevoItem2->subcategoria = 'Vuelo vuelta'; $nuevoItem2->precio = $vuelo_vuelta->valor_ejecutivo; $nuevoItem2->subtotal= round($nuevoItem2->precio * $num_ejecutivo - $nuevoItem2->precio * $num_ejecutivo * ($vuelo_vuelta->descuento/100)); array_push($carrito->items, $nuevoItem2); } if($num_pc > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id_ida; $nuevoItem->id_paquete = $id_paquete; $nuevoItem->nombre = $vuelo_ida->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->tipo_paquete = $nombre_paquete; $nuevoItem->subcategoria = 'Vuelo Ida'; $nuevoItem->tipo_pasaje = 'Primera Clase'; $nuevoItem->precio = $vuelo_ida->valor_primera_clase; $nuevoItem->descuento = $vuelo_ida->descuento; $nuevoItem->cantidad = $num_pc; $nuevoItem->subtotal = round($nuevoItem->precio * $num_pc - $nuevoItem->precio * $num_pc * ($vuelo_ida->descuento/100)); $nuevoItem2 = clone $nuevoItem; array_push($carrito->items, $nuevoItem); $nuevoItem2->id = $id_vuelta; $nuevoItem2->nombre = $vuelo_vuelta->nombre_avion; $nuevoItem2->subcategoria = 'Vuelo vuelta'; $nuevoItem2->precio = $vuelo_vuelta->valor_primera_clase; $nuevoItem2->subtotal= round($nuevoItem2->precio * $num_pc - $nuevoItem2->precio * $num_pc * ($vuelo_vuelta->descuento/100)); array_push($carrito->items, $nuevoItem2); } $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); }catch(Exception $e){ return redirect('/vuelos')->with('failure', 'Hubo un error al agregar al carrito'); } } public function addVueloAlCarrito(Request $request){ if (Session::has("carrito")){ $carrito = json_decode(Session::get("carrito")); }else{ //Se crea una clase vacia y se llena como el formato de arriba $carrito = new \stdClass(); $carrito->precio = 0; $carrito->items = []; } $id = $request->input("id"); $num_turista = $request->input("turista"); $num_ejecutivo = $request->input("ejecutivo"); $num_pc = $request->input("primera_clase"); $vuelo = \App\Models\Vuelo::findOrFail($id); if($num_turista > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->nombre = $vuelo->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->subcategoria = 'Reservas'; $nuevoItem->tipo_pasaje = 'Turista'; $nuevoItem->precio = $vuelo->valor_turista; $nuevoItem->descuento = $vuelo->descuento; $nuevoItem->cantidad = $num_turista; $nuevoItem->subtotal= round($nuevoItem->precio * $num_turista - $nuevoItem->precio * $num_turista * ($vuelo->descuento/100)); array_push($carrito->items, $nuevoItem); } if($num_ejecutivo > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->nombre = $vuelo->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->tipo_pasaje = 'Ejecutivo'; $nuevoItem->precio = $vuelo->valor_ejecutivo; $nuevoItem->descuento = $vuelo->descuento; $nuevoItem->cantidad = $num_ejecutivo; $nuevoItem->subtotal= round($nuevoItem->precio * $num_ejecutivo - $nuevoItem->precio * $num_ejecutivo * ($vuelo->descuento/100)); array_push($carrito->items, $nuevoItem); } if($num_pc > 0){ $nuevoItem = new \stdClass(); $nuevoItem->id = $id; $nuevoItem->nombre = $vuelo->nombre_avion; $nuevoItem->categoria = 'Vuelo'; $nuevoItem->tipo_pasaje = 'Primera Clase'; $nuevoItem->precio = $vuelo->valor_primera_clase; $nuevoItem->descuento = $vuelo->descuento; $nuevoItem->cantidad = $num_pc; $nuevoItem->subtotal = round($nuevoItem->precio * $num_pc - $nuevoItem->precio * $num_pc * ($vuelo->descuento/100)); array_push($carrito->items, $nuevoItem); } $total = 0; foreach ($carrito->items as $item) { $total = $total + $item->subtotal; } $carrito->total = $total; Session::put("carrito", json_encode($carrito)); } }
Markdown
UTF-8
1,808
2.953125
3
[]
no_license
# <p align = 'center'>We Fire</p> ### <p align = 'center'>*"One man with a gun can control 100 without one. ~ Vladimir Lenin"* </p> # MANAN Using firearms(for non harming {**good word**} purposes obvoiusly!) is a thrilling luxury that isn't quite affordable for any general college student.Bbut for NCC cadets, it's just one of the many perks of being a part of the organisation. During the Annual Training Camp, all the cadets are trained by armymen in properly holding{**good word**} and firing rounds from a 0.22 mm Sporting Rifle. After initial briefing, every year the cadets are taken to the Pokhran firing range where most of them, for the very first time in their lives get to experience the sheer thrill of physically feeling the vibrations of a rifle's recoil. Cadets are allowed to fire several rounds on a target at a distance of 25m under proper supervision of designated Army Officers. # SHASHWAT A proximal relation with the firearms is a thrilling luxury that isn't quite affordable for any general college student. But for NCC cadets, it's just one of the many perks of being part of the organisation. During the Annual Training Camp, all the cadets savour first hand experience with the rifle after being trained by army personnel holding expertise in the same! Apart from handling, they also get to fire rounds from a delux or a sporting rifle of a calliber around 5.56mm. After initial briefing, every year the cadets are taken to the Pokhran firing range where most of them, for the very first time in their lives get to experience the sheer thrill of physically feeling the vibrations of a rifle's recoil. Cadets are allowed to fire several rounds on a target under proper supervision of designated Army Officers. A good grouping of bullets on the target fetches another set of rounds!
Rust
UTF-8
6,680
3.09375
3
[]
no_license
use std::ops; use crate::vector2::Vector2; #[derive(Debug, Clone, Copy, PartialEq)] pub struct Matrix2 { pub m11: f64, pub m12: f64, pub m21: f64, pub m22: f64, } impl Matrix2 { pub fn new(m11: f64, m12: f64, m21: f64, m22: f64) -> Matrix2 { Matrix2 { m11, m12, m21, m22 } } pub fn builder() -> Matrix2Build { Matrix2Build { result: Matrix2::unit() } } pub fn unit() -> Matrix2 { Matrix2 { m11: 1.0, m12: 0.0, m21: 0.0, m22: 1.0, } } pub fn transpose(self) -> Matrix2 { Matrix2 { m11: self.m11, m12: self.m21, m21: self.m12, m22: self.m22, } } pub fn rotate(a: f64) -> Matrix2 { Matrix2 { m11: a.cos(), m12: a.sin(), m21: -a.sin(), m22: a.cos(), } } pub fn scale(kx: f64, ky: f64) -> Matrix2 { Matrix2 { m11: kx, m12: 0.0, m21: 0.0, m22: ky, } } pub fn scale_n(n: Vector2, k: f64) -> Matrix2 { Matrix2 { m11: 1.0 + (k - 1.0) * n.x * n.x, m12: (k - 1.0) * n.x * n.y, m21: (k - 1.0) * n.x * n.y, m22: 1.0 + (k - 1.0) * n.y * n.y, } } pub fn project_x() -> Matrix2 { Matrix2 { m11: 1.0, m12: 0.0, m21: 0.0, m22: 0.0, } } pub fn project_y() -> Matrix2 { Matrix2 { m11: 0.0, m12: 0.0, m21: 0.0, m22: 1.0, } } pub fn assert_approx_eq(self, rhs: Matrix2) { use assert_approx_eq::assert_approx_eq; assert_approx_eq!(self.m11, rhs.m11); assert_approx_eq!(self.m12, rhs.m12); assert_approx_eq!(self.m21, rhs.m21); assert_approx_eq!(self.m22, rhs.m22); } pub fn project_n(n: Vector2) -> Matrix2 { Matrix2::scale_n(n, 0.0) } pub fn reflect_n(n: Vector2) -> Matrix2 { Matrix2::scale_n(n, -1.0) } pub fn shear_x(s: f64) -> Matrix2 { Matrix2 { m11: 1.0, m12: 0.0, m21: s, m22: 1.0, } } pub fn shear_y(s: f64) -> Matrix2 { Matrix2 { m11: 1.0, m12: s, m21: 0.0, m22: 1.0, } } pub fn determinant(self) -> f64 { self.m11 * self.m22 - self.m12 * self.m21 } pub fn adjoint(self) -> Matrix2 { Matrix2 { m11: self.m22, m12: -self.m12, m21: -self.m21, m22: self.m11, } } pub fn inverse(self) -> Matrix2 { self.adjoint() / self.determinant() } } impl ops::Add<Matrix2> for Matrix2 { type Output = Matrix2; fn add(self, rhs: Matrix2) -> Matrix2 { Matrix2 { m11: self.m11 + rhs.m11, m12: self.m12 + rhs.m12, m21: self.m21 + rhs.m21, m22: self.m22 + rhs.m22 } } } impl ops::Sub<Matrix2> for Matrix2 { type Output = Matrix2; fn sub(self, rhs: Matrix2) -> Matrix2 { self + (-rhs) } } impl ops::Mul<f64> for Matrix2 { type Output = Matrix2; fn mul(self, rhs: f64) -> Matrix2 { Matrix2 { m11: self.m11 * rhs, m12: self.m12 * rhs, m21: self.m21 * rhs, m22: self.m22 * rhs } } } impl ops::Neg for Matrix2 { type Output = Matrix2; fn neg(self) -> Matrix2 { Matrix2 { m11: -self.m11, m12: -self.m12, m21: -self.m21, m22: -self.m22 } } } impl ops::Div<f64> for Matrix2 { type Output = Matrix2; fn div(self, rhs: f64) -> Matrix2 { Matrix2 { m11: self.m11 / rhs, m12: self.m12 / rhs, m21: self.m21 / rhs, m22: self.m22 / rhs } } } impl ops::Mul<Matrix2> for f64 { type Output = Matrix2; fn mul(self, rhs: Matrix2) -> Matrix2 { Matrix2 { m11: rhs.m11 * self, m12: rhs.m12 * self, m21: rhs.m21 * self, m22: rhs.m22 * self } } } impl ops::Mul<Vector2> for Matrix2 { type Output = Vector2; fn mul(self, rhs: Vector2) -> Vector2 { Vector2 { x: self.m11 * rhs.x + self.m12 * rhs.y, y: self.m21 * rhs.x + self.m22 * rhs.y, } } } impl ops::Mul<Matrix2> for Vector2 { type Output = Vector2; fn mul(self, rhs: Matrix2) -> Vector2 { Vector2 { x: self.x * rhs.m11 + self.y * rhs.m21, y: self.x * rhs.m12 + self.y * rhs.m22, } } } impl ops::Mul<Matrix2> for Matrix2 { type Output = Matrix2; fn mul(self, rhs: Matrix2) -> Matrix2 { Matrix2 { m11: self.m11 * rhs.m11 + self.m12 * rhs.m21, m12: self.m11 * rhs.m21 + self.m12 * rhs.m22, m21: self.m21 * rhs.m11 + self.m22 * rhs.m21, m22: self.m21 * rhs.m12 + self.m22 * rhs.m22, } } } impl ops::MulAssign<Matrix2> for Matrix2 { fn mul_assign(&mut self, rhs: Matrix2) { *self = *self * rhs; } } pub struct Matrix2Build { result: Matrix2 } impl Matrix2Build { pub fn rotate(mut self, a: f64) -> Matrix2Build { self.result *= Matrix2::rotate(a); self } pub fn scale(mut self, kx: f64, ky: f64) -> Matrix2Build { self.result *= Matrix2::scale(kx, ky); self } pub fn scale_n(mut self, n: Vector2, k: f64) -> Matrix2Build { self.result *= Matrix2::scale_n(n, k); self } pub fn project_x(mut self) -> Matrix2Build { self.result *= Matrix2::project_x(); self } pub fn project_y(mut self) -> Matrix2Build { self.result *= Matrix2::project_y(); self } pub fn project_n(mut self, n: Vector2) -> Matrix2Build { self.result *= Matrix2::project_n(n); self } pub fn reflect_n(mut self, n: Vector2) -> Matrix2Build { self.result *= Matrix2::reflect_n(n); self } pub fn shear_x(mut self, s: f64) -> Matrix2Build { self.result *= Matrix2::shear_x(s); self } pub fn shear_y(mut self, s: f64) -> Matrix2Build { self.result *= Matrix2::shear_y(s); self } pub fn build(self) -> Matrix2 { self.result } } #[cfg(test)] mod test { use crate::matrix2::*; use assert_approx_eq::assert_approx_eq; #[test] fn identity() { let m = Matrix2::unit(); assert_eq!(m.inverse(), m); } #[test] fn inverse() { let m = Matrix2::new(4.0, 3.0, -1.0, 4.0); m.inverse().inverse().assert_approx_eq(m); assert_approx_eq!(m.inverse().determinant(), 1.0/m.determinant()); } }
Shell
UTF-8
316
3.171875
3
[]
no_license
#!/bin/bash #se guarda en una variable el texto a=`cat "$3"` #se define la posición de inicio, -1 porque la posicion de los caracteres inicia en 0 i=$(($1-1)) #cantidad de letras que le siguen a la posición inicial f=$(($2 - $1 +1)) #imprime los f caracteres que están después de la posición $1 echo ${a:$i:$f}
Java
UTF-8
214
1.742188
2
[]
no_license
package com.zipcodewilmington.froilansfarm.Storage; import com.zipcodewilmington.froilansfarm.Animal.Horse; import java.util.ArrayList; import java.util.List; public class Stable extends StorageUnit <Horse>{ }
Java
UTF-8
272
2.203125
2
[]
no_license
package dndapp; import java.util.ArrayList; public class userList { private static ArrayList<String> usernames; public userList(){ } public void addItem(String username){ usernames.add(username); } }
Java
UTF-8
34,320
1.640625
2
[ "Apache-2.0" ]
permissive
package com.mohyaghoub.calculator; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.speech.RecognizerIntent; import android.support.constraint.ConstraintLayout; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.LegendRenderer; import java.util.ArrayList; import java.util.Locale; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private Button Mic; private Button showEquation; private final int REQ_CODE = 1002; // private TextView showActual; //camera private Button camera,save, window,tools; // private TextView cameraText; private final int CAMERA_CODE = 9001; //clear private Button ClearEquation,Calculate; //calculator mode private final int CLASSIC_CODE = 5002; private Animation animScale; private Animation upToDown; // private Animation appear; public static Animation downToUp; // private Animation disappear; private Animation opposite; //graph private GraphView graph; private CardView toolbar; private MainControl mainControl; //banners private ImageView banner1; private ImageView banner2; private ImageView banner3; private ImageView banner4; //show answer private TextView showAnswer; //constraint layout box Calculator private ConstraintLayout boxCalculator; private TextView showFunctionBox; private Button mainY; private String mainYText; private Button mainX; private String mainXText; private final int MAINX_CODE = 2032; // private final int MAINY_CODE = 2049; private int focusListener; public static ExamMode examMode; public static Button ExamModeConfirm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // no status bar overlay createDrawerMenu(); initObjects(); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); } private void initObjects() { this.focusListener = 0; this.mainXText = ""; this.mainYText = ""; this.Mic = findViewById(R.id.Mic); this.showEquation = findViewById(R.id.showEquation); this.camera = findViewById(R.id.Camera); this.ClearEquation = findViewById(R.id.ClearEquation); this.Calculate = findViewById(R.id.calculate); this.animScale= AnimationUtils.loadAnimation(this,R.anim.scale); this.upToDown = AnimationUtils.loadAnimation(this,R.anim.uptodown); downToUp = AnimationUtils.loadAnimation(this,R.anim.downtoup); this.opposite = AnimationUtils.loadAnimation(this,R.anim.opposite); this.save = findViewById(R.id.saveMain); this.tools = findViewById(R.id.toolsMain); this.window = findViewById(R.id.WindowMain); this.showAnswer = findViewById(R.id.answerMain); this.graph = findViewById(R.id.graphMain); this.toolbar = findViewById(R.id.CardView); this.boxCalculator = findViewById(R.id.boxCalculator); this.mainX = findViewById(R.id.xMain); // this.mainX.setShowSoftInputOnFocus(false); this.mainY = findViewById(R.id.yMain); // this.mainY.setShowSoftInputOnFocus(false); this.showFunctionBox = findViewById(R.id.formulaMain); ExamModeConfirm = findViewById(R.id.ExamModeButtonConfirm); setUpGraphLayout(); this.Mic.startAnimation(upToDown); this.showEquation.startAnimation(upToDown); this.ClearEquation.startAnimation(upToDown); this.camera.startAnimation(upToDown); this.Calculate.startAnimation(upToDown); //banners this.banner1 = findViewById(R.id.banner1); this.banner2 = findViewById(R.id.banner2); this.banner3 = findViewById(R.id.banner3); this.banner4 = findViewById(R.id.banner4); this.banner1.startAnimation(this.upToDown); this.banner2.startAnimation(this.upToDown); this.banner3.startAnimation(downToUp); this.banner4.startAnimation(downToUp); examMode = new ExamMode(this); this.camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animScale); initCamera(); } }); this.Mic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.startAnimation(animScale); initVoiceRecognizer(); } }); this.ClearEquation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mainXText = ""; showEquation.setText(""); backToOriginal(opposite); } }); this.showEquation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this,CalculatorActivity.class); i.putExtra("leftOver",showEquation.getText().toString()); i.putExtra("savedFunctions",""); startActivityForResult(i,CLASSIC_CODE); } }); // this.showEquation.setOnFocusChangeListener(new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // if(hasFocus&&focusListener!=0) // { // Intent i = new Intent(MainActivity.this,CalculatorActivity.class); // i.putExtra("leftOver",showEquation.getText().toString()); // i.putExtra("savedFunctions",""); // startActivityForResult(i,CLASSIC_CODE); // } // else if(focusListener==0) // { // focusListener++; // } // } // }); MainActivity.ExamModeConfirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainActivity.ExamModeConfirm.setVisibility(View.GONE); } }); // this.showEquation.setShowSoftInputOnFocus(false); LoadHistory.LoadCurrentLauncher(this); LoadList.loadList(getBaseContext()); LoadList.loadWindowRatios(this); LoadHistory.LoadHistory(getBaseContext()); setOnClickListenerForCalculate(); setOnClickListenerForMainX(); setOnClickListenerForSave(); setOnClickListenerForTools(); setOnCLickListenerForWindow(); setOnClickListenerForAnswer(); setOnClickListenerForMainY(); if(LoadHistory.CurrentLauncher.equals("Calculator")) { Intent intent4 = new Intent(this,CalculatorActivity.class); intent4.putExtra("leftOver",""); intent4.putExtra("savedFunctions",""); this.startActivityForResult(intent4,CLASSIC_CODE); } this.showEquation.setText("sin(x)"); calculate(); } private void initCamera() { if(!MainActivity.examMode.isACTIVATED_EXAM_MODE()) { Intent i = new Intent(MainActivity.this,CameraActivity.class); startActivityForResult(i,CAMERA_CODE); } else { Toast.makeText(this,"Sorry, you can not use this feature during exam mode.",Toast.LENGTH_SHORT).show(); } } private void initVoiceRecognizer() { if(!MainActivity.examMode.isACTIVATED_EXAM_MODE()) { Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); i.putExtra(RecognizerIntent.EXTRA_PROMPT,"Say an expression..."); try{ startActivityForResult(i,REQ_CODE); }catch(ActivityNotFoundException a) { Toast.makeText(this,"Sorry, your device does not support voice input",Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this,"Sorry, you can not use this feature in exam mode.",Toast.LENGTH_SHORT).show(); } } protected void onActivityResult(int requestCode,int resultCode, Intent data) { super.onActivityResult(requestCode,resultCode,data); switch (requestCode) { case REQ_CODE: if(resultCode == RESULT_OK&&data!=null) { ArrayList<String> voiceInText = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); SmartMathText smt = new SmartMathText(voiceInText.get(0)); this.showEquation.setText(SmartParser.finalCheck(smt.getText(),false)); calculate(); MathFunctions.cleanBooleans(); } break; case CAMERA_CODE: if(resultCode == RESULT_OK && data!=null) { String d = data.getStringExtra("data"); SmartMathTextPicture smtp = new SmartMathTextPicture(d); this.createCameraDialog(smtp.getText()); } break; case CLASSIC_CODE: if(resultCode == RESULT_OK && data!=null) { String text = data.getStringExtra("classicData"); this.showEquation.setText(text); calculate(); } break; case MAINX_CODE: if(resultCode == RESULT_OK && data!=null) { String text = data.getStringExtra("classicData"); this.mainXText = text; performCalculationsForY(); this.mainX.setText(cropLength(text)); } break; } } private void performCalculationsForY() { if(LoadList.isAGoodFunction(this.mainXText,this)) { LoadList.calculator.setEquation(this.mainXText); String newY = mainControl.getValue(LoadList.calculator.getValue(1))+""; mainY.setText(cropLength(newY)); this.mainYText = newY; } else { this.mainY.setText("y"); } } private String cropLength(String text) { if(text.length()>10) { return text.substring(0,10)+"..."; } else { return text; } } private void createDrawerMenu() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_functions) { // Handle the camera action Intent i = new Intent(MainActivity.this,FunctionActivity.class); startActivity(i); } else if (id == R.id.nav_tool) { Intent i = new Intent(MainActivity.this,Tools_FunctionSelection.class); startActivity(i); } else if (id == R.id.nav_exam_mode) { AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE); if(examMode.isACTIVATED_EXAM_MODE()) { MainActivity.ExamModeConfirm.setVisibility(View.VISIBLE); MainActivity.ExamModeConfirm.startAnimation(downToUp); } else if(!am.isMusicActive()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { startLockTask(); } else { Toast.makeText(this,"Sorry your phone does not support Exam Mode.",Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this,"sorry something is wrong at this moment. Make sure to turn off any music that is playing!",Toast.LENGTH_SHORT).show(); } } else if (id == R.id.nav_lists) { Intent intent = new Intent(MainActivity.this,ShowListsActivity.class); startActivity(intent); } else if(id == R.id.nav_smart_room) { if(examMode.isACTIVATED_EXAM_MODE()) { Toast.makeText(this,"Sorry, the assistant is not available at this moment!",Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(MainActivity.this,SmartRoom.class); startActivity(intent); } } else if(id == R.id.nav_window_ratios) { Intent intent = new Intent(MainActivity.this,WindowActivity.class); startActivity(intent); } else if(id == R.id.nav_launcher) { launcherDialog(); } else if(id == R.id.clear_history) { this.createDialogToClearHistory(); } else if(id == R.id.nav_report_bug) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(FinalString.ReportBugLink)); startActivity(intent); } else if(id == R.id.nav_help) { Intent intent = new Intent(this,HelpActivity.class); startActivity(intent); } else if(id == R.id.nav_about) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(FinalString.about)); startActivity(intent); } else if(id == R.id.nav_privacypolicy) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(FinalString.privacypolicy)); startActivity(intent); } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void createCameraDialog(final String equation) { if(equation.length()>0) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage(String.format("Is this the equation %s?",equation)) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { showEquation.setText(showEquation.getText()+equation); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { initCamera(); } }); // Create the AlertDialog object and return it builder.create(); builder.show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage(String.format("Sorry we could not find an equation from the picture.")) .setPositiveButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }) .setNegativeButton("Try again", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { initCamera(); } }); // Create the AlertDialog object and return it builder.create(); builder.show(); } } private void setUpGraphLayout() { graph.getViewport().setXAxisBoundsManual(true); graph.getViewport().setMaxX(10); graph.getViewport().setMinX(-10); graph.getViewport().setYAxisBoundsManual(true); graph.getViewport().setMaxY(10); graph.getViewport().setMinY(-10); graph.setBackgroundColor(Color.WHITE); graph.setTitleTextSize(55.0f); graph.getLegendRenderer().setVisible(true); graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP); graph.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Loading the graph...", Toast.LENGTH_SHORT).show(); Intent i = new Intent(MainActivity.this, SplashGraph.class); i.putExtra("position", showEquation.getText().toString()); startActivity(i); } }); } public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { examMode.checkExamMode(); } else if(examMode.isAppInLockTaskMode()) { Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); sendBroadcast(closeDialog); } } private void setOnClickListenerForCalculate() { this.Calculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { calculate(); } }); } private void calculate() { String functionText = MainActivity.this.showEquation.getText().toString(); if (LoadList.isAGoodFunction(functionText, MainActivity.this)) { setUpMainControl(functionText); makeObjectsVisibleWithAnimation(downToUp); clearBoxCalculator(); } } private void clearBoxCalculator() { this.mainX.setText(""); this.mainY.setText(""); } private void backToOriginal(Animation animation) { this.focusListener =0; if(this.save.getVisibility()==View.VISIBLE) { this.graph.setVisibility(View.INVISIBLE); this.window.setVisibility(View.INVISIBLE); this.save.setVisibility(View.INVISIBLE); this.tools.setVisibility(View.INVISIBLE); this.toolbar.setVisibility(View.INVISIBLE); this.boxCalculator.setVisibility(View.GONE); this.showAnswer.setVisibility(View.GONE); this.graph.startAnimation(animation); this.window.startAnimation(animation); this.save.startAnimation(animation); this.tools.startAnimation(animation); this.toolbar.startAnimation(animation); this.boxCalculator.startAnimation(animation); this.showAnswer.startAnimation(animation); this.showEquation.setText("sin(x)"); calculate(); this.showEquation.setText(""); } //bring back the Banners // if(banner1.getVisibility()==View.INVISIBLE) // { // this.banner1.startAnimation(downToUp); // this.banner2.startAnimation(downToUp); // this.banner3.startAnimation(downToUp); // this.banner4.startAnimation(downToUp); // // this.banner1.setVisibility(View.VISIBLE); // this.banner2.setVisibility(View.VISIBLE); // this.banner3.setVisibility(View.VISIBLE); // this.banner4.setVisibility(View.VISIBLE); // } } private void makeObjectsVisibleWithAnimation(Animation animation) { this.graph.setVisibility(View.VISIBLE); this.window.setVisibility(View.VISIBLE); this.save.setVisibility(View.VISIBLE); this.tools.setVisibility(View.VISIBLE); this.toolbar.setVisibility(View.VISIBLE); this.window.startAnimation(animation); this.save.startAnimation(animation); this.tools.startAnimation(animation); this.graph.startAnimation(animation); this.toolbar.startAnimation(animation); if(!mainControl.isAFunction()) { double value = mainControl.getValue(1); LoadHistory.addHistory(value+"",MainActivity.this); LoadHistory.addHistory(mainControl.getFraction(),MainActivity.this); this.showAnswer.setText(value+""); this.showAnswer.setVisibility(View.VISIBLE); this.showAnswer.startAnimation(animation); this.boxCalculator.setVisibility(View.GONE); } else { this.boxCalculator.setVisibility(View.VISIBLE); this.boxCalculator.startAnimation(animation); this.showAnswer.setVisibility(View.GONE); this.showFunctionBox.setText(cropLength(mainControl.getEquation())); } //removeBanners if(banner1.getVisibility()==View.VISIBLE) { this.banner1.startAnimation(this.opposite); this.banner2.startAnimation(this.opposite); this.banner3.startAnimation(this.opposite); this.banner4.startAnimation(this.opposite); this.banner1.setVisibility(View.INVISIBLE); this.banner2.setVisibility(View.INVISIBLE); this.banner3.setVisibility(View.INVISIBLE); this.banner4.setVisibility(View.INVISIBLE); } } private void setUpMainControl(String function) { String formatFunction = String.format("Function|%s|false|false|5|0|10",function); this.mainControl = new MainControl(formatFunction,this); if(this.mainControl.isAFunction()) { this.graph.getViewport().setYAxisBoundsManual(true); this.graph.getViewport().setMinY(-10); this.graph.getViewport().setMaxY(10); this.graph.setTitle(String.format("y = %s",cropLength(function))); this.graph.removeAllSeries(); this.graph.addSeries(mainControl.getSeries()); this.graph.addSeries(mainControl.getSeriesPrime()); this.graph.refreshDrawableState(); this.graph.invalidate(); } else { this.graph.getViewport().setYAxisBoundsManual(false); this.graph.setTitle(String.format("y = %s",cropLength(function))); this.graph.removeAllSeries(); this.graph.addSeries(mainControl.getSeries()); this.graph.refreshDrawableState(); this.graph.invalidate(); } } private void setOnClickListenerForMainX() { this.mainX.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this,CalculatorActivity.class); i.putExtra("leftOver",mainXText); i.putExtra("savedFunctions",""); i.putExtra("KEYMODE","1"); startActivityForResult(i,MAINX_CODE); } }); // this.mainX.setOnFocusChangeListener(new View.OnFocusChangeListener() { // @Override // public void onFocusChange(View v, boolean hasFocus) { // if(hasFocus) // { // Intent i = new Intent(MainActivity.this,CalculatorActivity.class); // i.putExtra("leftOver",mainXText); // i.putExtra("savedFunctions",""); // i.putExtra("KEYMODE","1"); // startActivityForResult(i,MAINX_CODE); // } // } // }); } private void setOnClickListenerForSave() { this.save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(showEquation.getText().toString().isEmpty()){ Toast.makeText(MainActivity.this,"You need to enter an equation first",Toast.LENGTH_SHORT).show(); }else { createDialogToGetAName(); } } }); } public void createDialogToGetAName() { final AlertDialog dialog; final AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = MainActivity.this.getLayoutInflater(); final View view1 = inflater.inflate(R.layout.save_require_name, null); builder.setView(view1); builder.setTitle("To save, enter a name please") .setPositiveButton("save", null) .setNegativeButton("Cancel", null); dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialogInterface) { Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO Do something EditText text = view1.findViewById(R.id.enterANameSaveMain); String name = Calculator.removeSpaces(text.getText().toString()); String function = showEquation.getText().toString(); if(LoadList.isAGoodName(name,MainActivity.this)&&LoadList.isAGoodFunction(function,MainActivity.this)) { String text1 = String.format("%s|%s|false|false|5|0|10",name,function); LoadList.saveFile(FileNames.fileName,LoadList.getList()+"&"+text1,MainActivity.this); try{ FunctionCreator functionCreator = new FunctionCreator(text1); MathFunctions.savedFunctions.add(functionCreator); Function functionCal = new Function(functionCreator.getName(),functionCreator.getFunction()); LinkedFunctions.FUNCTIONS.add(functionCal); }catch(Exception e) { } Toast.makeText(MainActivity.this,String.format("Function '%s' was created",name),Toast.LENGTH_LONG).show(); dialog.dismiss(); } } }); } }); dialog.show(); } public void createDialogToClearHistory() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Are you sure you want to clear your history?") .setMessage("This completely clears the calculator history.") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LoadHistory.History.clear(); LoadHistory.addHistory("",MainActivity.this); Toast.makeText(MainActivity.this,"History cleared!",Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("No",null); builder.create(); builder.show(); } protected void setOnClickListenerForTools() { this.tools.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(showEquation.getText().toString().isEmpty()){ Toast.makeText(MainActivity.this,"You need to enter an equation first",Toast.LENGTH_SHORT).show(); }else{ Intent i = new Intent(MainActivity.this,ToolsActivity.class); i.putExtra("EQUATION",showEquation.getText().toString()); startActivity(i); } } }); } protected void setOnCLickListenerForWindow() { this.window.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,WindowActivity.class); startActivity(intent); } }); } protected void setOnClickListenerForAnswer() { this.showAnswer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(showAnswer.getText().toString().contains("/")) { showAnswer.setText(mainControl.getSavedValue()+""); } else { showAnswer.setText(mainControl.getFraction()); } } }); } private void setOnClickListenerForMainY() { this.mainY.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text = mainY.getText().toString(); if(text.contains("/")&&!text.isEmpty()) { mainY.setText(mainControl.getSavedValue()+""); } else if(!text.isEmpty()) { mainY.setText(mainControl.getFraction()); } } }); this.mainY.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus) { String text = mainY.getText().toString(); if(text.contains("/")&&!text.isEmpty()) { mainY.setText(mainControl.getSavedValue()+""); } else if(!text.isEmpty()) { mainY.setText(mainControl.getFraction()); } } } }); } //LAUNCHER private void launcherDialog() { final AlertDialog dialog; final AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = (LayoutInflater) getSystemService(android.app.Activity.LAYOUT_INFLATER_SERVICE); View view1 = inflater.inflate(R.layout.changecolorof_functions, null); builder.setView(view1); LinearLayout layout = view1.findViewById(R.id.linearLayoutColorChange); dialog = builder.create(); Button button1 = new Button(this); button1.setText("Current Launcher: "+ LoadHistory.CurrentLauncher); button1.setBackgroundColor(ContextCompat.getColor(this,ColorsInJava.colors[5])); button1.setTextColor(Color.WHITE); button1.setGravity(Gravity.CENTER); button1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); layout.addView(button1); for(int i = 0;i<LoadHistory.Launchers.length;i++) { final Button button = new Button(this); button.setText(LoadHistory.Launchers[i]+""); button.setBackgroundColor(ContextCompat.getColor(this,ColorsInJava.colors[5])); button.setTextColor(Color.WHITE); button.setGravity(Gravity.CENTER); final int position = i; button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LoadHistory.saveLauncher(position,MainActivity.this); dialog.dismiss(); Toast.makeText(MainActivity.this,"Launcher was saved. Next time the app will be opened in "+LoadHistory.CurrentLauncher,Toast.LENGTH_SHORT).show(); } }); button.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); layout.addView(button); } dialog.show(); } }
C++
UTF-8
995
3.015625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void insertionsort(int *input, int size, unsigned long long int &comparisons){ for(int i = 1;i < size;i++){ for(int j = i-1;j >= 0;j--){ comparisons++; if(input[j] > input[j+1]){ int temp = input[j]; input[j] = input[j+1]; input[j+1] = temp; }else{ break; } } } } int main(){ int size; unsigned long long comparisons = 0; int *input; char c; cin>>c; cin>>size; input = new int[size]; for(int i = 0;i < size;i++){ cin>>input[i]; } clock_t t1, t2; t1 = clock(); insertionsort(input, size, comparisons); t2 = clock(); long long int runtime = ((long long int)t2 - (long long int)t1); for(int i = 0;i < size;i++){ cout<<input[i]<<endl; } cerr<<"runtime,"<<runtime<<endl; cerr<<"comparisons,"<<comparisons<<endl; return 0; }
Java
UTF-8
170
1.742188
2
[]
no_license
package in.ernet.iitr.puttauec.sensorutil; import java.util.Random; public class RandomSingleton { public static final Random instance = new Random(2); // 2 is seed }
Java
UTF-8
544
1.695313
2
[]
no_license
package com.example.satish.widgetlistviewdemo.activity; import android.os.Bundle; import android.os.PersistableBundle; import android.support.v7.app.AppCompatActivity; import com.example.satish.widgetlistviewdemo.R; /** * Created by satish on 24/11/15. */ public class SearchActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); setContentView(R.layout.activity_note_voice); } }
JavaScript
UTF-8
1,367
2.5625
3
[]
no_license
module.exports = { createFolderStudied: (req, res, next) => { const db = req.app.get("db"); const { user_id } = req.params; const { folderName } = req.body; console.log(folderName); db.add_to_studied([user_id, folderName]) .then(studied => res.status(200).send(studied)) .catch(err => { res.status(400).send({ errorMessage: "didnt add a folder" }); }); }, updateFolderStudied: (req, res, next) => { const db = req.app.get("db"); const { user_id, folder_id } = req.params; const { folder_name } = req.body; db.update_to_studied([user_id, folder_id, folder_name]) .then(studied => res.status(200).send(studied)) .catch(err => { res.status(400).send({ errorMessage: "did not update" }); }); }, deleteFolderStudied: (req, res, next) => { const db = req.app.get("db"); console.log("delete_studied([user_id,folder_id])"); const { user_id, folder_id } = req.params; db.delete_studied([user_id, folder_id]) .then(studied => res.status(200).send(studied)) .catch(err => { res.status(400).send({ errorMessage: "did not delete" }); }); }, readFolder: async (req, res, next) => { const db = req.app.get("db"); const { user_id } = req.params; db.read_folder(user_id).then(studied => res.status(200).send(studied)); } };
Java
UTF-8
895
2.859375
3
[]
no_license
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.io.FileInputStream; public class Main_백준_1475_방번호 { public static void main(String[] args) throws Exception { System.setIn(new FileInputStream("res/input_방번호.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); char[] arr = new char[s.length()]; for(int z=0;z<s.length();z++) arr[z] = s.charAt(z); // System.out.println(Arrays.toString(arr)); int[] v = new int[10]; for(int z=0;z<s.length();z++) { v[arr[z]-'0']++; } int max = 0; int num6 = v[6]; int num9 = v[9]; for(int z=0;z<10;z++) { if(v[z]>max) { if(z==6 || z==9) continue; else max = v[z]; } } int sum = num6+num9; if(sum%2 == 1 ) sum++; System.out.println(max>sum/2 ? max:sum/2); } }
TypeScript
UTF-8
1,401
2.546875
3
[]
no_license
import { prismaClient } from "../../utils/types"; interface CreateComment { userId: number postId: number content: string } export async function createComment({ content, postId, userId }: CreateComment, prisma: prismaClient) { const comment = await prisma.comment.create({ data: { content, userId, postId } }) return comment } interface EditComment { userId: number, id: number, content: string } export async function editComment({ userId, content, id }: EditComment, prisma: prismaClient) { const commentToEdit = await prisma.comment.findFirst({ where: { id } }) if(commentToEdit?.userId !== userId) { throw new Error('This comment is not yours') } const comment = await prisma.comment.update({ where: { id }, data: { content } }) return comment } interface DeleteComment { userId: number id: number } export async function deleteComment({ id, userId }: DeleteComment, prisma: prismaClient) { const commentToDelete = await prisma.comment.findFirst({ where: { id } }) if(commentToDelete?.userId !== userId) { throw new Error('This comment is not yours') } const comment = await prisma.comment.delete({ where: { id } }) return comment }
Markdown
UTF-8
1,186
2.8125
3
[ "MIT" ]
permissive
# go-httpresource - simple HTTP end-point The go stdlib `net/http` library is quite good for providing a simple routing experience but some times you want just a bit more. This library is designed to work in conjuction and add a dispatch on HTTP methods to the mix. Some times it's nice to have APIs being a bit more REST-ful-y. ## Example [$ examples/simple.go](examples/simple.go) ```go package main import ( "net/http" "github.com/zimbatm/go-httpresource" ) func main() { // Only reply to GET and HEAD requests http.Handle("/hello", httpresource.GET(func (w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) })) // A more complex example http.Handle("/users", httpresource.Resource { GET: http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { // Return the list of all users }), POST: http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { // Create a new user }), }) err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } } ``` ## Related projects * [Gorilla Mux](https://github.com/gorilla/mux) - A more featureful all-in-one HTTP router ## License MIT (c) 2019 - zimbatm and contributors
JavaScript
UTF-8
2,920
3.296875
3
[]
no_license
import Rx from 'rx'; import Immutable from 'immutable'; var code = { //Monkeys and Coconuts https://youtu.be/U9qU20VmvaU?t=43s // //<n> sailors are stranded on a desert island with one monkey. //The sailors gather coconuts into a pile and go to sleep. // //That night (without the knowledge of the others) each sailor in turn //separates out equal shares of coconuts with one left over (which they throw to the monkey) //then they hide their own share and throw the rest back on the pile. // //The next morning, they all separate the remaining pile and there are no coconuts left for the monkey. //How many coconuts did they have in the pile the night before? monkeysAndCoconuts: function(sailors) { throw new Error("Not Implemented"); }, // A standard Sudoku puzzle contains 81 cells, in a 9 by 9 grid, and has 9 zones, each zone being the // intersection of 3 rows and 3 columns. Each cell may contain a number from one to nine; each number // can only occur once in each zone, row, and column of the grid. At the beginning of the game, many // cells begin with numbers in them, and the goal is to fill in the remaining cells. -- wikipedia // Solve any 9x9 Sudoku board that is input as an array. // Array values of 0 represent cells that must be solved for. // Array values > 0 must not be modified. // To solve: each number 1-9 must exist exactly 9 times, and never in the same row or same column as its self // The only valid values are 1-9 // The more elegant the approach the better solveSudoku: function (arrBoard) { throw new Error("Not Implemented"); }, // Little Alchemy https://littlealchemy.com/ // // Little Alchemy is a game where you combine elements to create other elements. For example, // earth + fire = lava; lava + earth = volcano. // Sometimes, combining two elements results in two or more elements. For example, // bird + rainbow = peacock, toucan; zombie + human = zombie, zombie. // You start with 4 base elements: earth, air, fire, water. // // The goal of this task is to produce a list of all possible elements that can be created by combining // two elements. Focus on calling combine() the fewest times possible. // There are 540 possible elements, but your code doesn't know that. // You are not allowed to access the Little Alchemy or Recipes libraries directly. // // baseElements: An array of earth, air, fire, water. // combine(element1, element2): Returns an array of elements resulting from combination. // Example: combine("earth", "fire") = ["lava"] // Example: combine("bird", "rainbow") = ["peacock", "toucan"] // Example: combine("peacock", "lava") = [] deriveAllElements: function(baseElements, combine) { throw new Error("Not Implemented"); } } module.exports = code;
C++
UTF-8
1,397
2.640625
3
[]
no_license
#include <string> #include <utility> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <iostream> using namespace std; class Request { private: string request; bool succes; public: Request(string r) { request = std::move(r); succes = true; } Request(const char *r) { request = string(r); succes = true; } Request() { } string getRequest() { return request; } int send(SSL* ssl) { int status; string test = getRequest(); const char *serialized = test.c_str(); int len = (int)getRequest().length(); status = SSL_write(ssl, &len, sizeof len); if (status < 0) { ERR_print_errors_fp(stderr); cerr << "Eroare la write() catre client.\n"; return 0; } status = SSL_write(ssl, serialized, len); if (status < 0) { ERR_print_errors_fp(stderr); cerr << "Eroare la write() catre client.\n"; return 0; } return status; } void setStatus(bool s) { succes = s; } bool getStatus() { return succes; } };
JavaScript
UTF-8
480
2.84375
3
[ "Apache-2.0" ]
permissive
/** * Triggered from a message on a Cloud Pub/Sub topic. * * @param {!Object} event The Cloud Functions event. * @param {!Function} The callback function. */ exports.subscribe = (event, callback) => { // The Cloud Pub/Sub Message object. const pubsubMessage = event.data; // We're just going to log the message to prove that // it worked. console.log(Buffer.from(pubsubMessage.data, 'base64').toString()); // Don't forget to call the callback. callback(); };
Java
UTF-8
505
2.765625
3
[]
no_license
package com.src; import java.util.ArrayList; public class Customer { private String name; private ArrayList<Double> trans=new ArrayList<>(); public Customer(String name, double initialAmount) { // super(); this.name = name; this.trans = trans; addTransaction(initialAmount); } public void addTransaction(double initialAmount) { // TODO Auto-generated method stub this.trans.add(initialAmount); } public String getName() { return name; } public ArrayList<Double> getTrans() { return trans; } }
Java
UTF-8
613
2.171875
2
[]
no_license
package pages; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.remote.RemoteWebDriver; import hooks.SelBase; public class MyHomePage extends SelBase { public MyHomePage(RemoteWebDriver driver) { SelBase.driver=driver; } public MyLeadsPage clickonLeads() { driver.findElementByLinkText("Leads").click(); return new MyLeadsPage((ChromeDriver) driver); } public MyHomePage MyHomecheckTitle() { String title1 = driver.getTitle(); System.out.println("The page title="+title1); return this; } }
Python
UTF-8
1,155
2.890625
3
[ "BSD-2-Clause" ]
permissive
import logging from . import SimConcretizationStrategy class SimConcretizationStrategyLogging(SimConcretizationStrategy): """ Concretization strategy that logs concretization results from another strategy. """ def __init__(self, strategy: SimConcretizationStrategy, is_read_strategy: bool): super().__init__() self._strategy = strategy self._is_read_strategy = is_read_strategy def _concretize(self, memory, addr, **kwargs): answers = self._strategy._concretize(memory, addr, **kwargs) if answers is not None: if self._is_read_strategy: logging.debug( "Read strategy %s on %s gave [%s]", type(self._strategy).__name__, addr, ", ".join([hex(answer) for answer in answers]), ) else: logging.debug( "Write strategy %s on %s gave [%s]", type(self._strategy).__name__, addr, ", ".join([hex(answer) for answer in answers]), ) return answers
C++
UTF-8
739
2.890625
3
[]
no_license
#pragma once #include "Grid.h" namespace dae { class GameObject; } class Level { public: Level(float Width, float Height, int rows, int cols); Level(BinaryReader& reader, const char* filename); ~Level(); Level(const Level& other) = delete; Level(Level&& other) = delete; Level& operator=(const Level& other) = delete; Level& operator=(Level && other) = delete; std::shared_ptr<dae::GameObject> CreateNewEnemy(float posX, float posY, GameObjectType type); Grid* GetGrid() { return m_pGrid; } std::vector<std::shared_ptr<dae::GameObject>>& GetEnemies() { return m_pEnemies; } void WriteToFile(BinaryWriter& writer, const char* filename); private: Grid* m_pGrid; std::vector<std::shared_ptr<dae::GameObject>> m_pEnemies{}; };
SQL
UTF-8
375
2.8125
3
[]
no_license
USE codeup_test_db; SELECT * FROM albums; UPDATE albums SET sales = (sales * 10); -- ////////////////////// SELECT * FROM albums WHERE release_date < 1980; UPDATE albums SET release_date = release_date - 100 WHERE release_date < 1980; -- ////////////////////// SELECT name FROM albums WHERE artist = 'Michael Jackson'; UPDATE albums SET name = 'Peter Jackson' WHERE name = 'Michael Jackson';
Java
UTF-8
1,339
2.546875
3
[]
no_license
package m1miage; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.SecureClassLoader; import java.util.ArrayList; public class MyClassLoader extends SecureClassLoader { private ArrayList<File> path = null; public MyClassLoader(ArrayList<File> p) { this.path = p; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] b = new byte[0]; return super.defineClass(name, b, 0, b.length); } private byte[] loadClassData(String name) throws ClassNotFoundException, IOException { File f = new File(name); DataInputStream input = new DataInputStream(new FileInputStream(f)); byte[] content = new byte[(int)f.length()]; input.readFully(content); return content; } public static void main(String[] args) throws ClassNotFoundException { ArrayList<File> al = new ArrayList<File>(); al.add(new File("File:///C:/Users/diazg/eclipse-workspace/m1miage.test")); MyClassLoader myCL = new MyClassLoader(al); try { myCL.loadClass("m1miage.test"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
Java
UTF-8
947
2.171875
2
[]
no_license
package com.fluent.job.handler; import com.alibaba.cola.dto.SingleResponse; import java.lang.reflect.InvocationTargetException; public abstract class JobHandler { /** success */ public static final SingleResponse<String> SUCCESS = SingleResponse.buildSuccess(); /** fail */ public static final SingleResponse<String> FAIL = SingleResponse.buildFailure("500", "执行失败!"); /** fail timeout */ public static final SingleResponse<String> FAIL_TIMEOUT = SingleResponse.buildFailure("502", "执行超时"); /** * 执行任务 * @param param * @return * @throws Exception */ public abstract SingleResponse<String> execute(String param) throws Exception; public void init() throws InvocationTargetException, IllegalAccessException { // do something } public void destroy() throws InvocationTargetException, IllegalAccessException { // do something } }
Python
UTF-8
712
3.703125
4
[]
no_license
from collections import Counter from itertools import combinations def get_strings(): with open('data/2.txt', 'r') as f: return [line.strip() for line in f] def get_checksum(strings): counts = [Counter(s) for s in strings] twos = sum(1 for x in counts if 2 in x.values()) threes = sum(1 for x in counts if 3 in x.values()) return twos * threes def distance(s, t): return sum(1 for x in zip(s, t) if x[0] != x[1]) def get_common_letters(strings): for s, t in combinations(strings, 2): if distance(s, t) == 1: return ''.join(x[0] for x in zip(s, t) if x[0] == x[1]) strings = get_strings() print(get_checksum(strings)) print(get_common_letters(strings))
C++
WINDOWS-1252
474
2.765625
3
[]
no_license
#pragma once #include "hand.h" class GenericPlayer : public Hand { friend ostream& operator <<(ostream& os, GenericPlayer& aGenericPlayer); public: GenericPlayer(const string& name = ""); virtual ~GenericPlayer(){} virtual bool IsHitting() ; bool IsBusted() const { return (GetTotal() > 21); } void Bust()const { cout << m_Name.c_str()<< "ը" << endl; } protected: string m_Name; }; ostream& operator <<(ostream& os, GenericPlayer& aGenericplayer);
Java
UTF-8
2,517
2.25
2
[]
no_license
package com.bupt.ims.common.filter; import com.bupt.ims.common.lang.ResultCode; import com.bupt.ims.entity.IMSUser; import com.bupt.ims.serviceImpl.DataUserDetailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @Component public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { @Autowired private DataUserDetailService dataUserDetailService; @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException { } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = String.valueOf(authentication.getName()); String password = String.valueOf(authentication.getCredentials()); if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { throw new BadCredentialsException(ResultCode.USER_OR_PASSWORD_ERROR.getCode().toString()); } IMSUser imsUser = (IMSUser)dataUserDetailService.loadUserByUsername(username); BCryptPasswordEncoder encode = new BCryptPasswordEncoder(); if (!encode.matches(password, imsUser.getPassword())) { throw new BadCredentialsException(ResultCode.USER_CREDENTIALS_ERROR.getCode().toString()); } // 将用户信息放入全局SecurityContext中 return this.createSuccessAuthentication(imsUser, authentication, imsUser); } @Override protected UserDetails retrieveUser(String s, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException { return null; } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } }
Markdown
UTF-8
1,261
2.671875
3
[ "MIT" ]
permissive
# API DOCUMENTATION ## Routes #### GET *Route:* `data/artist?artistId=<id>` *Output:* ``` { "message": "Successfully retrieved artist", "artist": [ { "artist_id": 1, "artist_name": "Djay Van Der Bent", "artist_img_url": "https://images.unsplash.com/photo-1530521787020-1c92aaf87aa3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1360&q=80" } ] } ``` *Route:* `data/artist?artistName=<name>` *Output:* ``` { "message": "Successfully retrieved artist", "artist": [ { "artist_id": 1, "artist_name": "Djay Van Der Bent", "artist_img_url": "https://images.unsplash.com/photo-1530521787020-1c92aaf87aa3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1360&q=80" } ] } ``` #### POST *Route:* `data/artist/` *Body:* Should include `artistName` and `artistImgUrl` keys *Output:* ``` { "message": "Successfully added new artist" } ``` #### PUT *Route:* `data/artist/` *Body:* Should include `artistID` `artistName` and `artistImgUrl` keys *Output* ``` { "message": "Successfully updated artist" } ``` #### DELETE *Route:* `data/artist?artistId=<id>` *Output* ``` { "message": "Successfully deleted artist" } ```
PHP
UTF-8
2,186
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2010, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ /** * This configures your session storage. The Cookie storage adapter must be connected first, since * it intercepts any writes where the `'expires'` key is set in the options array. */ use lithium\storage\Session; Session::config(array( 'minerva_cookie' => array('adapter' => 'Cookie'), 'default' => array('adapter' => 'Php'), 'minerva_default' => array('adapter' => 'Model', 'model' => 'minerva\models\Session'), 'flash_message' => array('adapter' => 'Php') )); /** * Session::config(array( * 'default' => array('adapter' => 'Model', 'model' => 'Session') * )); * */ /** * Uncomment this to enable forms-based authentication. The configuration below will attempt to * authenticate users against a `User` model. In a controller, run * `Auth::check('default', $this->request)` to authenticate a user. This will check the POST data of * the request (`lithium\action\Request::$data`) to see if the fields match the `'fields'` key of * the configuration below. If successful, it will write the data returned from `User::first()` to * the session using the default session configuration. Once the session data is written, you can * call `Auth::check('default')` to check authentication status or retrieve the user's data from the * session. Call `Auth::clear('default')` to remove the user's authentication details from the * session. This effectively logs a user out of the system. To modify the form input that the * adapter accepts, or how the configured model is queried, or how the data is stored in the * session, see the `Form` adapter API or the `Auth` API, respectively. * * @see lithium\security\auth\adapter\Form * @see lithium\action\Request::$data * @see lithium\security\Auth */ // use lithium\security\Auth; // Auth::config(array( // 'default' => array( // 'adapter' => 'Form', // 'model' => 'User', // 'fields' => array('username', 'password') // ) // )); ?>
Java
UTF-8
1,365
3.375
3
[]
no_license
/* 300. Longest Increasing Subsequence QuestionEditorial Solution My Submissions Total Accepted: 39482 Total Submissions: 110692 Difficulty: Medium Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. Your algorithm should run in O(n2) complexity. Follow up: Could you improve it to O(n log n) time complexity? Credits: Special thanks to @pbrother for adding this problem and creating all test cases. */ public class Solution { public int lengthOfLIS(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int[] f = new int[nums.length]; for (int i = 0; i < nums.length; i++) { f[i] = 1; } for (int i = 1; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[i] > nums[j]) { f[i] = Math.max(f[i], f[j] + 1); } } } int val = Integer.MIN_VALUE; for (int i = 0; i < f.length; i++) { val = Math.max(f[i], val); } return val; } }
Java
UTF-8
3,826
1.953125
2
[]
no_license
package com.example.attendance.ui.Other; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import com.example.attendance.R; import static android.app.Activity.RESULT_OK; public class monthCalendar extends Fragment { //private GalleryViewModel galleryViewModel; static final int REQUEST_ID_IMAGE_CAPTURE = 100; Button btn; ImageView anh; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // galleryViewModel = // ViewModelProviders.of(this).get(GalleryViewModel.class); View root = inflater.inflate(R.layout.activity_month_calendar, container, false); //final TextView textView = root.findViewById(R.id.text_gallery); btn = root.findViewById(R.id.button_permission_AI); anh = root.findViewById(R.id.image); //galleryViewModel.getText().observe(this, new Observer<String>() { //@Override //public void onChanged(@Nullable String s) { // textView.setText(s); //} //}); //final String[] permissions = {Manifest.permission.CAMERA}; btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { verifyPermission(); } }); return root; } private void verifyPermission() { final int permission_camera = ContextCompat.checkSelfPermission(getContext(),Manifest.permission.CAMERA); if(permission_camera != PackageManager.PERMISSION_GRANTED) { if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.CAMERA)) { requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_ID_IMAGE_CAPTURE); } else { requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_ID_IMAGE_CAPTURE); } } else { Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent1, REQUEST_ID_IMAGE_CAPTURE); } } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (requestCode == REQUEST_ID_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); anh.setImageBitmap(imageBitmap); } super.onActivityResult(requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case REQUEST_ID_IMAGE_CAPTURE: if(grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults.length>0){ verifyPermission(); }else{ Toast.makeText(getContext(),"Permission denied....",Toast.LENGTH_SHORT).show(); } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
C#
UTF-8
1,153
2.828125
3
[ "MIT" ]
permissive
using StankinsCommon; namespace Stankins.FileOps { public class ReceiverCSVText : ReceiveCSV<ReceiverStreamingText> { public ReceiverCSVText(CtorDictionary dataNeeded) : base(dataNeeded) { this.Name = nameof(ReceiverCSVText); this.Text = GetMyDataOrThrow<string>(nameof(Text)); } public ReceiverCSVText(string text) : this(text, true, ',', '\n') { } public ReceiverCSVText(string text, bool firstLineHasColumnNames, char columnSeparator, char lineSeparator) : this(new CtorDictionary() { {nameof(text),text}, {nameof(columnSeparator),columnSeparator }, {nameof(lineSeparator),lineSeparator}, {nameof(firstLineHasColumnNames),firstLineHasColumnNames } }) { } public string Text { get; } public override ReceiverStreamingText Create() { return new ReceiverStreamingText(Text, LineSeparator); } public override string NameTable() { return "Table1"; } } }
PHP
UTF-8
1,368
2.796875
3
[]
no_license
<?php namespace GraphQL\Application\Entity; use GraphQL\Utils\Utils; /** * Class User * Сущность пользователя. * (публичные GraphQL-методы см. в /src/graphql/Application/Type/UserType.php) * (поля объекта соответствуют полям таблицы, за которой прикреплена сущность - см. метод __getTable()) * * @package GraphQL\Application\Data */ class User extends EntityBase { public string $surname; public string $name; public string $midname; public int $sex; public string $phone_number; public string $email; public string $registration_adress; public string $residence_address; public string $job_place; public string $job_position; public string $relationship; public string $childids; public string $study_place; public string $study_class; public string $date_registered; public string $birthday; public string $status_email; public string $verification_key_email; public function __construct(array $data = null) { parent::__construct($data); } /** * Ассоциированная таблица * (таблица должна быть создана в базе данных) * * @return string */ public function __getTable() { return "user"; } }
Python
UTF-8
2,577
2.53125
3
[]
no_license
from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.python.ops import rnn_cell from tensorflow.python.ops import seq2seq import re import os import itertools import sys import time import math from tensorflow.models.rnn.translate import seq2seq_model PAD_ID = 0 GO_ID = 1 EOS_ID = 2 UNK_ID = 3 class VocabGenerator: def __init__(self, tokenizer=None, special_chars=['_PAD_ID', '_GO_ID', '_EOS_ID', '_UNK_ID']): if tokenizer is None: tokenizer = lambda s: [w for w in re.split(" +", s.lower()) if len(w.strip()) > 0] self.tokenizer = tokenizer self.special_chars = special_chars self.sent_set = set() self.word_counts = {} def processSent(self, sent): if hash(sent) in self.sent_set: return self.sent_set.add(hash(sent)) for word in self.tokenizer(sent): if len(word.strip()) > 0: self.word_counts[word] = 0 if word not in self.word_counts else self.word_counts[word]+1 def generateVocab(self, sents=[], vocab_size=10000): for sent in sents: self.processSent(sent) vocab_remaining = vocab_size - len(self.special_chars) top_word_counts = sorted([(w, self.word_counts[w]) for w in self.word_counts], key=lambda x: x[1], reverse=True)[:vocab_remaining] self.vocab = self.special_chars + [w for w,c in top_word_counts] self.vocab_lookup = {w: i for i,w in enumerate(self.vocab)} return self.vocab def setVocab(self, vocab): self.vocab = vocab self.vocab_lookup = {w: i for i,w in enumerate(self.vocab)} def saveVocab(self, vocab_file, vocab=None): vocab = vocab if vocab is not None else self.vocab with open(vocab_file, "w") as out: for w in vocab: print(w, file=out) def loadVocab(self, vocab_file): vocab = [line.strip("\n") for line in open(vocab_file)] self.setVocab(vocab) return vocab def sentToIndexes(self, sent): #return [self.vocab_lookup[w] if w in self.vocab_lookup else -1 for w in self.tokenizer(sent)] words = self.tokenizer(sent) indexes = [self.vocab_lookup[w] if w in self.vocab_lookup else self.vocab_lookup['_UNK_ID'] for w in words] return indexes if len(indexes) > 0 else [self.vocab_lookup['_UNK_ID']] def indexesToSents(self, indexes): return " ".join([self.vocab[i] for i in indexes])
Python
UTF-8
3,234
3.078125
3
[]
no_license
# driver.find_element_by_id() # driver.find_element_by_name() # driver.find_element_by_xpath() # driver.find_element_by_link_text() # driver.find_element_by_partial_link_text() # driver.find_element_by_tag_name() # driver.find_element_by_class_name() # driver.find_element_by_css_selector() # drive.find_element(By.XPATH. "xpath expression") # id, name, xpath, css_selector, tag_name, class_name, link_text, partial_link_text import os import time from selenium import webdriver class FindElementBy: def testFindElement(self): driverLocation_windows = "C:\\Users\\aparida\\OneDrive\\Code\\Selenium\\chromedriver.exe" driverLocation_mac = "anmolparida\OneDrive\Code\Selenium_Python\chromedriver.exe" # Update based on the System you are using driverLocation = driverLocation_windows # Important Steps os.environ["webdriver.chrome.driver"] = driverLocation driver = webdriver.Chrome(driverLocation); baseURL = "http://letskodeit.teachable.com/pages/practice" baseURL = "https://dhtmlx.com/docs/products/dhtmlxGrid/" driver.get(baseURL) driver.maximize_window() driver.get(baseURL) # using contains # //tag[contains(attribute,'value')] # //tag[starts-with(attribute,'value')] # //tag[ends-with(attribute,'value')] # elementByXpath = driver.find_element_by_xpath("//div[@class='homepage-hero']//a[text()='Enroll now']") # elementByXpath = driver.find_element_by_xpath("//div[@id='navbar']//a[contains(text(),'Login')]") # elementByXpath = driver.find_element_by_xpath("//div[@id='navbar']//a[contains(@class,'navbar-link fedora') and contains(@href,'sign_in')]") # Syntax: xpath - to - some - element // parent:: < tag > # Syntax: xpath - to - some - element // preceding - sibling:: < tag > # Syntax: xpath - to - some - element // following - sibling:: < tag > # elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li") # elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li//following-sibling::li") # elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li//preceding-sibling::li") # elementByXpath = driver.find_element_by_xpath("//a[@href='/sign_in']//parent::li//preceding-sibling::li//following-sibling::li[2]") # elemnentbyXpath = driver.find_elements_by_xpath("//div[@title='Catherine Johnson']//following-sibling::div[1]") ListOwners = driver.find_elements_by_xpath("//div[@class='dhx_grid_data']/div/div[4]/div[text()]") ListHours = driver.find_elements_by_xpath("//div[@class='dhx_grid_data']/div/div[5][text()]") if (ListOwners,ListHours) is not None: print('elementByXpath - We have a match \n') for owner, hours in zip(ListOwners, ListHours): print(owner.text + " - " + hours.text) else: print('elementByXpath - We Dont have a match') time.sleep(2); driver.quit(); oFindElement = FindElementBy() oFindElement.testFindElement()
C++
UTF-8
14,278
3.453125
3
[]
no_license
//functions file //define functions in this file //string library #include "class.h" //our own .h file //using namespace std; /* Function: one parameters: a string that is the first word in the current getline returns: 1 for label, 0 for instruction decription: checks to see if there is a colon next to the word. if there is, it's a label, otherwise it's an instruction should also save the label in the symbol table, somehow */ int one(string first) { int length; length=first.size(); if(first.at(length-1) == ':') { return 1; //label } else { return 0; //instruction } } /* Function: symbol::setLabel Parameters: string: label's name, string: Hex address of the label, int: the decimal line count desciption: This function builds one line of the symbol table */ void symbol::setLabel(string makeMeLabel, string hexLine, int linecount) { labelName = makeMeLabel + "\t\t" + hexLine; _count = linecount; //this will remember. return; } /*function: line::opCode Parameters: MIPS argument struct and the first mips argument. // opCode is a function inthe class line, it identifies the first 5 bits of binary for the current line of assembly // opCode expects the MIPS function and sets the opcode equal accordingly. */ void line::opCode(string arg, MIPS_arguments* args) { if(arg == "add" || arg == "addu" || arg == "and" || arg == "jr" || arg == "nor" || arg == "or" || arg == "slt" || arg == "sltu" || arg == "sll" || arg == "srl" || arg == "sub" || arg == "subu") { typeR(arg,args); } else if(arg == "addi" || arg == "addiu" || arg == "andi" || arg == "beq" || arg == "bne" || arg == "lw" || arg =="ori" || arg == "slti" || arg == "sltiu" || arg == "sw") typeI(arg,args); else if(arg == "j" || arg == "jal") typeJ(arg,args); else cout << "error, do not recognize command" + arg << endl; return; } /* funciton: line::typeR parameters: Mips primary argument, MIPS argument struct Description: The function will check the main argument and either immediately set some registers, or it will pass control to a different function. */ void line::typeR(string arg, MIPS_arguments* args) { opcode = "000000"; // the opcode for every rType is six zeroes. if(args->arg1 == "jr") { rs = registers(args->arg2); rt = "00000"; rd = "00000"; shamt = "00000"; funct = functions(args->arg1); } else if(args->arg1 == "sll" || args->arg1 == "srl") { rd = registers(args->arg2); rs = "00000"; rt = registers(args->arg3); shamt = convertBinary(args->arg4, 5); //CONVERT INTO 5 BIT BINARY funct = functions(args->arg1); } else { addressBasicR(args); //this will parse out some registers and set the result of register() = to the right reg } final = opcode + rs + rt + rd + shamt + funct; return; } /* function: typeI parameters description: Function will pass control to a more spceific function, or call immediate and register functions within its own if/else statemnt */ void line::typeI(string arg, MIPS_arguments* args) { if (arg == "addi" ) { opcode="001000"; addressBasicI(args); //this function should go get all the registers }//08 = 0000 1000 doing everything in line easier to read else if(arg == "addiu") { opcode="001001"; //cout << opcode <<endl;//this was for debugging addressBasicI(args); //this function should go get all the registers }//09 = 0000 1001 else if(arg == "andi" ) { opcode="001100"; addressBasicI(args); //this function should go get all the registers }//0c = 0000 1100 else if(arg == "beq" ) { opcode="000100"; branch(args); }//04 = 0000 0100 else if(arg == "bne" ) { opcode="000101"; branch(args); }//05 = 0000 0101 else if(arg == "lw" ) { opcode="100011"; rs = registers(args->arg4); rt = registers(args->arg2); immediate = convertBinary(args->arg3, 16); // NEEDS TO BE CONVERTED INTO 16 BIT BINARY FIRST }//23 = 0010 0011 else if(arg == "ori" ) { opcode="001101"; addressBasicI(args); //this function should go get all the registers }//0d = 0000 1101 else if(arg == "slti" ) { opcode="001010"; addressBasicI(args); //this function should go get all the registers }//0a = 0000 1010 else if(arg == "sltiu") { opcode="001011"; addressBasicI(args); //this function should go get all the registers }//0b = 0000 1011 else if(arg == "sw" ) { opcode="101011"; rs = registers(args->arg4); rt = registers(args->arg2); immediate = convertBinary(args->arg3, 16); // NEEDS TO BE CONVERTED INTO 16 BIT BINARY FIRST }//2b = 0010 1011 else cout << "error function not supported" + arg << endl; final = opcode + rs + rt + immediate; return; } /* function: typeJ paramenters: primary arg and the MIPS arg struct description: Will set opcodes for jump-type functions. will call memoryAddress for their proper jumps. */ void line::typeJ(string arg, MIPS_arguments* args) { int i; if (arg == "j") { opcode="000010"; }//02 = 0000 0010 else if(arg == "jal") { opcode="000011"; }//03 = 0000 0011 i = memoryAddress(args->arg2); address = convertBinaryDec(i, 26); final = opcode + address; //cout << final << endl; return; } /* Name: addressBasicR parameters: mips argument struct. returns: nothing description: parses through line to call registers function to set registers to binary values */ void line::addressBasicR(MIPS_arguments* args) { rd = registers(args->arg2); rs = registers(args->arg3); rt = registers(args->arg4); shamt = "00000"; funct = functions(args->arg1); final = opcode + rs + rt + rd + shamt + funct; return; } /* Name: addressBasicI parameters: mips argument struct. returns: nothing description: parses through line to call registers function to set registers to binary values */ void line::addressBasicI(MIPS_arguments* args) { rt = registers(args->arg2); //cout << rt <<endl; rs = registers(args->arg3); //cout << rs <<endl; immediate = convertBinary(args->arg4, 16); //NEED TO CONVERT THIS INTO 16 BIT BINARY FIRST return; } /* function: line::registers parameters: a single string representing the register as it appears in MIPS Will take in the MIPS register and return a binary string value equal to the register's basic value. */ string line::registers(string reg) { if (reg == "$zero"){reg="00000";}//00 = 0000 0000 else if (reg == "$at") {reg="00001";}//01 = 0000 0001 else if (reg == "$v0") {reg="00010";}//02 = 0000 0010 else if (reg == "$v1") {reg="00011";}//03 = 0000 0011 else if (reg == "$a0") {reg="00100";}//04 = 0000 0100 else if (reg == "$a1") {reg="00101";}//05 = 0000 0101 else if (reg == "$a2") {reg="00110";}//06 = 0000 0110 else if (reg == "$a3") {reg="00111";}//07 = 0000 0111 else if (reg == "$t0") {reg="01000";}//08 = 0000 1000 else if (reg == "$t1") {reg="01001";}//09 = 0000 1001 else if (reg == "$t2") {reg="01010";}//0a = 0000 1010 else if (reg == "$t3") {reg="01011";}//0b = 0000 1011 else if (reg == "$t4") {reg="01100";}//0c = 0000 1100 else if (reg == "$t5") {reg="01101";}//0d = 0000 1101 else if (reg == "$t6") {reg="01110";}//0e = 0000 1110 else if (reg == "$t7") {reg="01111";}//0f = 0000 1111 else if (reg == "$s0") {reg="10000";}//10 = 0001 0000 else if (reg == "$s1") {reg="10001";}//11 = 0001 0001 else if (reg == "$s2") {reg="10010";}//12 = 0001 0010 else if (reg == "$s3") {reg="10011";}//13 = 0001 0011 else if (reg == "$s4") {reg="10100";}//14 = 0001 0100 else if (reg == "$s5") {reg="10101";}//15 = 0001 0101 else if (reg == "$s6") {reg="10110";}//16 = 0001 0110 else if (reg == "$s7") {reg="10111";}//17 = 0001 0111 else if (reg == "$t8") {reg="11000";}//18 = 0001 1000 else if (reg == "$t9") {reg="11001";}//19 = 0001 1001 else if (reg == "$k0") {reg="11010";}//1a = 0001 1010 else if (reg == "$k1") {reg="11011";}//1b = 0001 1011 else if (reg == "$gp") {reg="11100";}//1c = 0001 1100 else if (reg == "$sp") {reg="11101";}//1d = 0001 1101 else if (reg == "$fp") {reg="11110";}//1e = 0001 1110 else if (reg == "$ra") {reg="11111";}//1f = 0001 1111 else cout << "register does not exist " << reg << endl; return reg; } /* name: functions parameters: the name of the function being used returns: a string that is the binary value for that function description: sets the funct value for R type */ string line::functions(string funct) { if (funct == "add") {funct="100000";} else if (funct == "addu") {funct="100001";} else if (funct == "and") {funct="100100";} else if (funct == "jr") {funct="001000";} else if (funct == "nor") {funct="100111";} else if (funct == "or") {funct="100101";} else if (funct == "slt") {funct="101010";} else if (funct == "sltu") {funct="101011";} else if (funct == "sll") {funct="000000";} else if (funct == "srl") {funct="000010";} else if (funct == "sub") {funct="100010";} else if (funct == "subu") {funct="100011";} else cout << "not r-type, doesn't have a funct value " << funct << endl; return funct; } /* name: branch parameters: one getline that has all the arguments for that line returns: nothing description: performs the branch operations by finding the correct immediate value, which is based on the offset */ void line::branch(MIPS_arguments* args) { int i = 0; int offset; i = memoryAddress(args->arg4); rs = registers(args->arg2); rt = registers(args->arg3); offset = myLine + 1; i = i - offset; immediate = convertBinaryDec(i,16); return; } /* name: memoryAddress parameters: a string that represents the argument that is a label name returns: an integer representing the program counter description: finds where a certain label was made, and tells you the program count there */ int line::memoryAddress(string arg) { ifstream fp2("mips.asm"); string str; int i = 0; int offset; int val1; int val2; arg = arg + ":"; while(getline(fp2, str)) { int spacePos1 = str.find(' '); // find 1st space string arg1 = str.substr(0, spacePos1); // from beginning to 1st space string str2 = str.substr(spacePos1 + 1); // from 1st space to the end int spacePos2 = str2.find(' '); string arg2 = str.substr(0, spacePos2); string str3 = str.substr(spacePos2 + 1); int commaPos1 = arg2.find(','); // find 1st comma arg2 = arg2.substr(0, commaPos1); if (arg1 == arg) { // cout << "label: " << arg << "found at: " << i << endl; return i; } else { val1 = one(arg1); val2 = one(arg2); if(!(val1) || !(val2)) { i++; } } } cout << "label not found: " << arg << endl; return 0; } /* name: convertFinalHex parameters: none returns: nothing description: this function takes the final binary number and converts 4 bits at a time into hex by calling the hexify function and then adding the hex together and setting final equal to the hex */ void line::convertFinalHex() { string word; string hex; int i, start, cap; start = 0; cap = 4; i =0; if(final.length() == 32) { while(i <= 7) { word = final.substr(0, 4); hex = hex + hexify(word); //start+=4; //cap+=4; final = final.substr(4, (final.length())+1); i++; } final = "0x" + hex; } return; } /* name: hexify parameters: a string of numbers that represents a 4 bit binary number returns: a character that represents the binary being converted into hex description: converts 4 bit binary into a hex digit */ char hexify(string word) { //cout << word << endl; char digit; if (word == "0000"){digit = '0';} else if (word == "0001"){digit = '1';} else if (word == "0010"){digit = '2';} else if (word == "0011"){digit = '3';} else if (word == "0100"){digit = '4';} else if (word == "0101"){digit = '5';} else if (word == "0110"){digit = '6';} else if (word == "0111"){digit = '7';} else if (word == "1000"){digit = '8';} else if (word == "1001"){digit = '9';} else if (word == "1010"){digit = 'a';} else if (word == "1011"){digit = 'b';} else if (word == "1100"){digit = 'c';} else if (word == "1101"){digit = 'd';} else if (word == "1110"){digit = 'e';} else if (word == "1111"){digit = 'f';} else {digit = 'x';} return digit; } /* Name: convertBinary parameters: a string decimal number and the number of bits to have for the binary conversion returns: a string of the binary conversion description: takes in a string of a decimal number and converts it to the right length of binary bits wanted */ string convertBinary(string decimal, int bits) { int quotient, dividend, divisor, remainder, i; int bi[bits]; // = {0}; string final; stringstream s; s.str(" "); bool flip=false; quotient = 1; dividend = atoi(decimal.c_str()); divisor = 2; remainder = 0; if(dividend<0) { flip=true; dividend*=-1; } //initialize bi[bits] to all zeros for(i=0; i < bits; i++) { bi[i] = 0; } i=(bits - 1); //i=15; while(quotient != 0) { quotient = dividend/divisor; remainder = dividend - (quotient*divisor); dividend = quotient; bi[i] = remainder; // cout << "bi[i]: " << bi[i] << endl; i--; } if(flip) { for(i=bits; i > 0; i--)//change all binary values to the opposite { if(bi[i]==1) { i--; while( i >= 0 ) { if(bi[i]==1) bi[i]=0; else bi[i]=1; i--; } } else { ; } } } for(i = 0; i < bits; i++) { s << bi[i]; } final = s.str(); // cout << "final: " << final << endl; return final; } /* Name: convertBinaryDec parameters: the decimal number given, the number of bits it needs to be converted into returns: the binary string description: this function converts a decimal number into a certain length binary number */ string convertBinaryDec(int decimal, int bits) { int quotient, dividend, divisor, remainder, i; int bi[bits]; // = {0}; string final; stringstream s; s.str(" "); quotient = 1; dividend = decimal; divisor = 2; remainder = 0; //initialize bi[bits] to all zeros for(i=0; i < bits; i++) { bi[i] = 0; } i=(bits - 1); //i=15; while(quotient != 0) { quotient = dividend/divisor; remainder = dividend - (quotient*divisor); dividend = quotient; bi[i] = remainder; // cout << "bi[i]: " << bi[i] << endl; i--; } for(i = 0; i < bits; i++) { s << bi[i]; } final = s.str(); //cout << "final: " << final << endl; return final; }
Java
UTF-8
1,959
2.78125
3
[ "MIT" ]
permissive
package com.web.program; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.web.tools.FormatingTools; public class Command { private final String aPath; private final List<String> aParsedPath; private final List<String> aArgs; private final List<String> aFile; public Command(String pPath) { aPath = pPath; aParsedPath = new ArrayList<String>(Arrays.asList(normalize(aPath).split(" "))); aArgs = new ArrayList<String>(); aFile = new ArrayList<String>(); findArgs(); findFile(); } public String toString() { StringBuilder aStrBuilder = new StringBuilder(); for (String s : aParsedPath) { aStrBuilder.append(s + " "); } return unnormalize(aStrBuilder.toString()); } private void findArgs() { int k = 0; for (String s : aParsedPath) { String[] tempStrings = s.split("@"); if (tempStrings.length > 1) { aArgs.add(tempStrings[tempStrings.length-1]); aParsedPath.set(k, "${" + tempStrings[tempStrings.length-1] + "}"); } k++; } } private void findFile() { int k = 0; for (String s : aParsedPath) { String[] tempStrings = s.split("%"); if (tempStrings.length > 1) { aFile.add(tempStrings[tempStrings.length-1]); aParsedPath.set(k,"${pathTo" + FormatingTools.capitalizeName(tempStrings[tempStrings.length-1]) + "}"); } k++; } } public String[] getFileParams () { return aFile.toArray(new String[aFile.size()]); } public String[] getArgsParams () { return aArgs.toArray(new String[aArgs.size()]); } private String normalize(String pCommand) { return pCommand.replaceAll("[&]|[*]|[']", " $0 "); } private String unnormalize(String pCommand) { String temp1 = pCommand.replaceAll(" & ", "&"); String temp2 = temp1.replaceAll(" \\* ", "*"); String temp3 = temp2.replaceAll(" ' ", "'"); return temp3; } }
Markdown
UTF-8
1,221
2.84375
3
[ "MIT" ]
permissive
<div align="center"> <img width="250" src="./public/logo-header.png" /> </div> > An online and open source platform <div align="center"> <img width="1000" src="./public/fenixproject.png"/> </div> # 📌 Table of Contents - [About](#speech_balloon-About) - [Purpose](#Purpose) - [Motivation](#love_letter-Motivation) - [LICENSE](#blue_book-LICENSE) --- ## :speech_balloon: About The Fênix project is a platform where its main objective is the connection between students and teachers. A free platform, aiming at free knowledge and valuing teachers who want to make classes available to other students registered on the platform. Where both (teacher and student) are totally free within the platform, our only goal is to connect them. ## Purpose The purpose of this project is for my personal study. ## :love_letter: Motivation Our biggest motivation is in relation to Covid-19, with schools closed, teachers and students at home, the idea came up to create a completely online platform where teachers can exercise their occupation at home. ## :blue_book: LICENSE Under development. Released in 2021. This project is under the MIT License Made with 💜 by [***Júlio César***](https://github.com/juliocesarfs)
Python
UTF-8
858
3.234375
3
[]
no_license
import pandas as pd #separate xls to three CSVs xls=pd.ExcelFile("dataset_original.xls") df1 = xls.parse(sheetname="People", index_col=None, na_values=['NA']) df2 = xls.parse(sheetname="Men", index_col=None, na_values=['NA']) df3 = xls.parse(sheetname="Women", index_col=None, na_values=['NA']) df1.drop([0,1,2,3,4,5,6,7],inplace=True) df2.drop([0,1,2,3,4,5,6,7],inplace=True) df3.drop([0,1,2,3,4,5,6,7],inplace=True) df1.to_csv('Employment.csv',index=False) df2.to_csv('Men.csv',index=False) df3.to_csv('Women.csv',index=False) #convert DATE form: Mar-May 1992 to 1992 Mar-May def covert(csv): df=pd.DataFrame(pd.read_csv(csv)) date=df["DATE"].str.split(" ",expand=True) df["MONTH"]=date[0] df["DATE"]=date[1] df["DATE"]=df["DATE"].str.cat(df["MONTH"],sep="-") df=df.drop(df.columns[7],axis=1) df.to_csv("Men.csv",index=False)
Java
UTF-8
327
2.875
3
[]
no_license
package moderate; public class NumberSwapper { public static void main(String[] args) { int a = -12; int b = 89; System.out.println(a); System.out.println(b); a = a * b; b = a/b; a = a/b; System.out.println(a); System.out.println(b); } }
Markdown
UTF-8
1,378
3.15625
3
[]
no_license
# Blogo ## Synopsis Blogo is an util to generate blog template, you give a blog title, and generates title and tile and category intelligent by your title. This is great when you write a blog and don't want to specific an category. Those features are provided for now: * Support hexo blog templates; * Support automatically generate different language templates, if you are writing English, **blogo** will generate English summary if you are writing Chinese, a Chinese version will be generate; Here is the screenshot of blogo. ![PicName](http://ofwzcunzi.bkt.clouddn.com/nYQZeGXPh6dFj1MS.png) ## Usage blogo is very simple to use, just give your title, all the things will be done! ``` mv blogo /usr/bin blogo -title "your title of blog" ``` That's it, and your *.md file will generates in your current directory. However, you can also specific your directory by given `-path` option. For more usage, type: ``` blogo -h ``` ## Future Work Maybe this tool will becomes more intelligent by applying AI classifier and divided your article into different categories. This could be a interesting work to explore AI in Golang! ## Terminate Goal Well, the final goal would be, I think, let blogo automatically generates a blog by your title given. This souds realy good, not only in blog, in the future, the writer, AI can helps them to structure a article in seconds!
Swift
UTF-8
896
2.640625
3
[]
no_license
// // Playlist.swift // E.Z Lean // // Created by Duy Anh on 3/13/17. // Copyright © 2017 E.Z Lean. All rights reserved. // import Foundation import RealmSwift import Firebase class Playlist: Object { dynamic var name = "" dynamic var imageLink = "" let song_ids = List<RealmString>() override static func primaryKey() -> String? { return "name" } static func create(snapshot: DataSnapshot) -> Playlist { let playlist = Playlist() playlist.name = snapshot.key playlist.imageLink = snapshot.childSnapshot(forPath: "image_link").value as! String (snapshot.childSnapshot(forPath: "song_ids").value as! [String]) .forEach { string in playlist.song_ids.append(RealmString.create(string: string)) } return playlist } deinit { print("deinit-Playlist") } }
TypeScript
UTF-8
416
2.65625
3
[]
no_license
import {colors} from '@constants' export const createHeaderColors = ( colScheme: options, ): { bg: string color: string } => { // dark by default const rets = { bg: colors.gray['900'], color: colors.white, } // if (colScheme === 'light') { // rets.bg = colors.gray['200'] // rets.color = colors.black // } return rets } type options = 'light' | 'dark' | 'no-preference'
Python
UTF-8
2,524
3.15625
3
[]
no_license
import unittest import math from decimal import Decimal from Calculator.Calculator import Calculator from CsvReader.CsvReader import CsvReader class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.calculator = Calculator() def test_Add(self): test_data = CsvReader('./Tests/Data/UnitTestAddition.csv').data for row in test_data: a= int(row['Value 1']) b= int(row['Value 2']) result = int(row['Result']) self.assertEqual(self.calculator.add(a,b), result) self.assertNotEqual(self.calculator.add(a,b), result-1) def test_Subtract(self): test_data = CsvReader('./Tests/Data/UnitTestSubtraction.csv').data for row in test_data: a= int(row['Value 1']) b= int(row['Value 2']) result = int(row['Result']) self.assertEqual(self.calculator.subtract(a,b), result) self.assertNotEqual(self.calculator.subtract(a,b), result-1) def test_Multiply(self): test_data = CsvReader('./Tests/Data/UnitTestMultiplication.csv').data for row in test_data: a= int(row['Value 1']) b= int(row['Value 2']) result = int(row['Result']) self.assertEqual(self.calculator.multiply(a,b), result) self.assertNotEqual(self.calculator.multiply(a,b), result-1) def test_Divide(self): test_data = CsvReader('./Tests/Data/UnitTestDivision.csv').data for row in test_data: a= int(row['Value 1']) b= int(row['Value 2']) result = float(row['Result']) self.assertAlmostEqual(self.calculator.divide(a,b), result) self.assertNotEqual(self.calculator.divide(a,b), result-1) def test_Square(self): test_data = CsvReader('./Tests/Data/UnitTestSquare.csv').data for row in test_data: a= int(row['Value 1']) result = int(row['Result']) self.assertEqual(self.calculator.square(a), result) self.assertNotEqual(self.calculator.square(a), result-1) def test_SquareRoot(self): test_data = CsvReader('./Tests/Data/UnitTestSquareRoot.csv').data for row in test_data: a= int(row['Value 1']) result = float(row['Result']) self.assertAlmostEqual(self.calculator.squareRoot(a), result) self.assertNotEqual(self.calculator.squareRoot(a), result-1) if __name__ == '__main__': unittest.main()
Java
UTF-8
2,883
2.90625
3
[]
no_license
package dbEntities; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JTable; import formsAndFrames.AnalysesDataFrame; /** * entity to perform sql requests * * @author DenRUS * */ public interface RequestExecutor { /** * return the result of the request as a JTable * * @param cn * connection to work with * @param sqlRequest * request to execute * @param storage a place to save rs and rsmd * @return JTable with the results * @throws ClassNotFoundException * if smth goes wrong * @throws SQLException * if smth goes wrong with SQL part */ public default JTable getResultAsTable(Connection cn, String sqlRequest, RSAndRSMDStorage storage) throws ClassNotFoundException, SQLException { String[] columnNames; Object[][] data; ResultSet rs = this.executeRequest(cn, sqlRequest); ResultSetMetaData metaData = rs.getMetaData(); storage.setResultSet(rs); storage.setResultSetMetaData(metaData); storage.setRequest(sqlRequest); columnNames = new String[metaData.getColumnCount()]; for (int i = 0; i < columnNames.length; i++) { columnNames[i] = metaData.getColumnName(i + 1); } ; int rowCount = 0; rs.last(); rowCount = rs.getRow(); rs.beforeFirst(); data = new String[rowCount][columnNames.length]; while (rs.next()) { rowCount--; for (int j = 0; j < columnNames.length; j++) { data[rowCount][j] = rs.getString(j + 1); } } JTable table = new JTable(data, columnNames); return table; } /** * execute the request * * @param sqlRequest * request to execute * @return ResultSet - the result * @throws SQLException * if smth is not ok */ public default ResultSet executeRequest(Connection cn, String sqlRequest) throws SQLException, ClassNotFoundException { return cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery(sqlRequest); } /** * printing a ResultSet * * @param rs * data to print * @throws SQLException * if smth is not ok =) */ public default void printResultSet(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); System.out.println(metaData.getTableName(1)); String[] columns = new String[metaData.getColumnCount()]; for (int i = 1; i <= metaData.getColumnCount(); i++) { columns[i - 1] = metaData.getColumnName(i); System.out.print(columns[i - 1] + " | "); } while (rs.next()) { System.out.println(); for (int j = 1; j <= metaData.getColumnCount(); j++) { System.out.print(rs.getString(j) + " | "); } } } }
JavaScript
UTF-8
690
3.75
4
[]
no_license
// Daniel Shiffman // https://www.kadenze.com/courses/the-nature-of-code // http://natureofcode.com/ // Session 1: Random Walker var w; function setup() { createCanvas(640, 360); // Make a Walker object w = new Walker(); } function draw() { background(51); // Update and display object w.update(); w.display(); } function Walker() { // Start Walker in center this.pos = createVector(width / 2, height / 2); this.update = function() { // Move Walker randomly var vel = createVector(random(-5, 5), random(-5, 5)); this.pos.add(vel); } this.display = function() { // Draw Walker as circle fill(255); ellipse(this.pos.x, this.pos.y, 48, 48); } }
Python
UTF-8
8,935
3.3125
3
[]
no_license
''' Created on Sep 16, 2021 @author joeypy ''' import os import sys import cfg import random import pygame # Check if game is over def is_game_over(board, size): assert isinstance(size, int) num_cells = size * size for i in range(num_cells - 1): if board[i] != i: return False return True # Move the piece to right def move_right(board, blank_cell_idx, num_cols): if blank_cell_idx % num_cols == 0: return blank_cell_idx board[blank_cell_idx - 1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx - 1] return blank_cell_idx - 1 # Move the piece to left def move_left(board, blank_cell_idx, num_cols): if (blank_cell_idx + 1) % num_cols == 0: return blank_cell_idx board[blank_cell_idx + 1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx + 1] return blank_cell_idx + 1 # Move the piece to down def move_down(board, blank_cell_idx, num_cols): if blank_cell_idx < num_cols: return blank_cell_idx board[blank_cell_idx - num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx - num_cols] return blank_cell_idx - num_cols # Move the piece to up def move_up(board, blank_cell_idx, num_rows, num_cols): if blank_cell_idx >= (num_rows - 1) * num_cols: return blank_cell_idx board[blank_cell_idx + num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx + num_cols] return blank_cell_idx + num_cols # Create the board game def create_board(num_rows, num_cols, num_cells): board = [] for i in range(num_cells): board.append(i) blank_cell_idx = num_cells - 1 board[blank_cell_idx] = -1 for i in range(cfg.RANDOM_NUM): direction = random.randint(0, 3) if direction == 0: blank_cell_idx = move_left(board, blank_cell_idx, num_cols) elif direction == 1: blank_cell_idx = move_right(board, blank_cell_idx, num_cols) elif direction == 2: blank_cell_idx = move_up(board, blank_cell_idx, num_rows, num_cols) elif direction == 3: blank_cell_idx = move_down(board, blank_cell_idx, num_cols) return board, blank_cell_idx # Read the image files def get_image_paths(root_dir): image_names = os.listdir(root_dir) assert len(image_names) > 0 return os.path.join(root_dir, random.choice(image_names)) # Show end interface of the game def show_end_interface(screen, width, height): screen.fill(cfg.BACKGROUND_COLOR) font = pygame.font.Font(cfg.FONT_PATH, width // 15) title = font.render('Good Job! You Won!', True, (233, 150, 122)) rectangle = title.get_rect() rectangle.midtop = (width / 2, height / 2) screen.blit(title, rectangle) pygame.display.update() while True: for event in pygame.event.get(): if(event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN: main() pygame.display.update() # Show the start menu interface def show_start_interface(screen, width, height): screen.fill(cfg.BACKGROUND_COLOR) t_font = pygame.font.Font(cfg.FONT_PATH, width // 4) c_font = pygame.font.Font(cfg.FONT_PATH, width // 22) title = t_font.render('Puzzle', True, cfg.RED) content_1 = c_font.render("Press H, M or L to choose your puzzle", True, cfg.BLUE) content_2 = c_font.render("H- 5x5, M- 4x4, L- 3x3 to choose your puzzle", True, cfg.BLUE) # rectangle t_rectangle = title.get_rect() t_rectangle.midtop = (width / 2, height / 10) # rectangle 1 c_rectangle_1 = content_1.get_rect() c_rectangle_1.midtop = (width / 2, height / 2.2) # rectangle 2 c_rectangle_2 = content_2.get_rect() c_rectangle_2.midtop = (width / 2, height / 1.8) screen.blit(title, t_rectangle) screen.blit(content_1, c_rectangle_1) screen.blit(content_2, c_rectangle_2) # Check the play mode: 3x3, 4x4, 5x5 while True: for event in pygame.event.get(): if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == ord('l'): return 3 elif event.key == ord('m'): return 4 elif event.key == ord('h'): return 5 pygame.display.update() # Main game function def main(): pygame.init() clock = pygame.time.Clock() game_img_used = pygame.image.load(get_image_paths(cfg.PICTURE_ROOT_DIR)) game_img_used = pygame.transform.scale(game_img_used, cfg.SCREENSIZE) game_img_used_rectangle = game_img_used.get_rect() screen = pygame.display.set_mode(cfg.SCREENSIZE) pygame.display.set_caption('Pokemon') size = show_start_interface(screen, game_img_used_rectangle.width, game_img_used_rectangle.height) assert isinstance(size, int) num_rows, num_cols = size, size num_cells = size * size cell_width = game_img_used_rectangle.width // num_cols cell_height = game_img_used_rectangle.height // num_rows while True: game_board, blank_cell_idx = create_board(num_rows, num_cols, num_cells) if not is_game_over(game_board, size): break is_running = True # The game logic while is_running: for event in pygame.event.get(): if(event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() sys.exit() # Check events from the arrows keyboard or letters elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT or event.key == ord('a'): blank_cell_idx = move_left(game_board, blank_cell_idx, num_cols) elif event.key == pygame.K_RIGHT or event.key == ord('d'): blank_cell_idx = move_right(game_board, blank_cell_idx, num_cols) elif event.key == pygame.K_UP or event.key == ord('w'): blank_cell_idx = move_up(game_board, blank_cell_idx, num_rows, num_cols) elif event.key == pygame.K_DOWN or event.key == ord('s'): blank_cell_idx = move_down(game_board, blank_cell_idx, num_cols) # Check events from the mouse elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: x, y = pygame.mouse.get_pos() x_position = x // cell_width y_position = y // cell_height idx = x_position + y_position * num_cols if idx == blank_cell_idx - 1: blank_cell_idx = move_right(game_board, blank_cell_idx, num_cols) elif idx == blank_cell_idx + 1: blank_cell_idx = move_left(game_board, blank_cell_idx, num_cols) elif idx == blank_cell_idx + num_cols: blank_cell_idx = move_up(game_board, blank_cell_idx, num_rows, num_cols) elif idx == blank_cell_idx - num_cols: blank_cell_idx = move_down(game_board, blank_cell_idx, num_cols) # Check if game finished if is_game_over(game_board, size): game_board[blank_cell_idx] = num_cells - 1 is_running = False screen.fill(cfg.BACKGROUND_COLOR) for i in range(num_cells): if game_board[i] == -1: continue x_position = i // num_cols y_position = i % num_cols rectangle = pygame.Rect( y_position * cell_width, x_position * cell_height, cell_width, cell_height ) img_area = pygame.Rect( (game_board[i] % num_cols) * cell_width, (game_board[i] // num_cols) * cell_height, cell_width, cell_height ) screen.blit(game_img_used, rectangle, img_area) for i in range(num_cols + 1): pygame.draw.line( screen, cfg.BLACK, (i * cell_width, 0), (i * cell_width, game_img_used_rectangle.height) ) for i in range(num_rows + 1): pygame.draw.line( screen, cfg.BLACK, (0, i * cell_height), (game_img_used_rectangle.width, i * cell_height) ) pygame.display.update() clock.tick(cfg.FPS) show_end_interface(screen, game_img_used_rectangle.width, game_img_used_rectangle.height) if __name__ == '__main__': main()
C#
UTF-8
535
2.546875
3
[]
no_license
using OrderService.DataAccessLayer.Daos; using OrderService.Model; using System; namespace OrderService.DataAccessLayer { public static class DaoFactory { public static IDao<TModel> Create<TModel>(IDataContext dataContext) { return typeof(TModel) switch { var dao when dao == typeof(Order) => new SqlServerOrderDao(dataContext) as IDao<TModel>, _ => throw new DaoException($"Unknown model: {typeof(TModel).FullName}") }; } } }
Java
UTF-8
2,046
1.921875
2
[]
no_license
package com.google.android.gms.internal; import java.util.List; import java.util.Map; public abstract interface zzblr { public abstract void initialize(); public abstract void interrupt(String paramString); public abstract boolean isInterrupted(String paramString); public abstract void purgeOutstandingWrites(); public abstract void refreshAuthToken(); public abstract void resume(String paramString); public abstract void shutdown(); public abstract void zza(List<String> paramList, zzblu paramzzblu); public abstract void zza(List<String> paramList, Object paramObject, zzblu paramzzblu); public abstract void zza(List<String> paramList, Object paramObject, String paramString, zzblu paramzzblu); public abstract void zza(List<String> paramList, Map<String, Object> paramMap); public abstract void zza(List<String> paramList, Map<String, Object> paramMap, zzblq paramzzblq, Long paramLong, zzblu paramzzblu); public abstract void zza(List<String> paramList, Map<String, Object> paramMap, zzblu paramzzblu); public abstract void zzb(List<String> paramList, Object paramObject, zzblu paramzzblu); public abstract void zzb(List<String> paramList, Map<String, Object> paramMap, zzblu paramzzblu); public abstract void zziO(String paramString); public static abstract interface zza { public abstract void onDisconnect(); public abstract void zzVP(); public abstract void zza(List<String> paramList, Object paramObject, boolean paramBoolean, Long paramLong); public abstract void zza(List<String> paramList, List<zzblt> paramList1, Long paramLong); public abstract void zzaX(boolean paramBoolean); public abstract void zzaw(Map<String, Object> paramMap); } } /* Location: H:\As A Bussines Man\confedince\App Dev Department\What's Fatora\Tawseel APK\Client\dex2jar-2.0\t-dex2jar.jar!\com\google\android\gms\internal\zzblr.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
C++
UTF-8
360
2.828125
3
[]
no_license
// HW6 13.18 Car.cpp // ZHUOZHAOJIN 12330443 #include <iostream> #include "Car.h" using namespace std; Car::Car( double g ) :gasCost( g ) { } double Car::getCarbonFootprint() const { return gasCost * 0.785; } double Car::getGasCost() const { return gasCost; } void Car::print() const { cout << "The carbonFootprint is about Car: \n" ; }
Python
UTF-8
310
3.59375
4
[]
no_license
# loop thru list cities = ['London','New York','Paris','Oslo','Helsinki' ] for city in cities: print(city) # output London New York Paris Oslo Helsinki # loop thru dict scores = {'Joe':95, 'Lou':86, 'Saman':91, 'Amin':75 } for s in scores: print(s, scores[s]) # output Amin 75 Lou 86 Saman 91 Joe 95
Java
UTF-8
1,145
2.9375
3
[]
no_license
package threadsstudy.future_task; import java.io.File; import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; /** * Created by OTBA}|{HbIu` on 19.11.16. */ public class FutureTest { public static void main(String[] args) { try(Scanner in=new Scanner(System.in)){ System.out.print("Enter base directory (e.g./usr/local/jdk5.0/src): "); String directory=in.nextLine(); System.out.print("Enter keyword (e.g. volatile): "); String keyword=in.nextLine(); MatchCounter counter=new MatchCounter(new File(directory),keyword, Executors.newCachedThreadPool()); FutureTask<Integer> task=new FutureTask<Integer>(counter); Thread t = new Thread(task); t.start(); try { System.out.println(task.get()+" matching files"); } catch (InterruptedException e) { // e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } }