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 | 778 | 2.375 | 2 | [] | no_license | package com.ssrn.test.support.ssrn.website.pagemodel;
import com.ssrn.test.support.browser.Browser;
public class CssSelectorLocatedPopupHyperlink<TVisit> extends UrlChangingHyperlink<TVisit>{
private final String cssSelector;
private final WebPageBase<TVisit> webPage;
private int visitTimeoutSeconds;
CssSelectorLocatedPopupHyperlink(String cssSelector, WebPageBase<TVisit> webPage, int visitTimeoutSeconds) {
this.cssSelector = cssSelector;
this.webPage = webPage;
this.visitTimeoutSeconds = visitTimeoutSeconds;
}
@Override
public TVisit clickWith(Browser browser) {
browser.clickElement(cssSelector);
browser.switchFocusToPopup();
return webPage.loadedIn(browser, visitTimeoutSeconds);
}
}
|
Java | WINDOWS-1252 | 629 | 2.1875 | 2 | [] | no_license | package com;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
/**
* Created with IntelliJ IDEA.
* User: ye
* Date: 13-3-17
* Time: 2:38
* To change this template use File | Settings | File Templates.
*/
public class TestClass {
static private final Log logger = LogFactory.getLog(TestClass.class);
@Test
public void test() {
logger.info(String.class.getCanonicalName());
logger.info(String.class.getName());
logger.info(String.class.getPackage().getName());
logger.info(String.class.getSimpleName());
}
}
|
Java | UTF-8 | 1,524 | 4.1875 | 4 | [] | no_license | package day38Review;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListCollections {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Arrays class is a class that have a lot of
// static methods to perform common array operation
// Arrays.sort(arrayObject)
// Collections is a class under java.util package
// to perform common collection object related operation
ArrayList <String> list = new ArrayList <>();
list.add("Umar");
list.add("Maryam");
list.add("Amir");
list.add("Sharif");
System.out.println(list);
Collections.sort(list);
System.out.println(list);
// sort method from ArrayList excect an object called Comparator we did not learn
// However even we don`t know this type of object
// we do know that any reference variable can be set to null
// so we can just pass null to this method
// and it will just work
//list.sort(null);
//BINARY SEARCH
// looking for the index of an item in the sorted list
int amirLoc = Collections.binarySearch(list, "Maryam");
System.out.println(amirLoc); //1 --> it is at index 1
int jovaLoc = Collections.binarySearch(list, "Jova");
System.out.println(jovaLoc); //-2 --> it must be at length 2
//REVERSE
Collections.reverse(list);
System.out.println(list);
//Shuffle Items Inside -- randomly changes places of items
Collections.shuffle(list);
System.out.println(list);
}
}
|
TypeScript | UTF-8 | 975 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | import { BaseModel } from './base.model';
/*export const enum ResourceType {
Instance, // Number of instances a user can create
IP, // Number of public IP addresses an account can own
Volume, // Number of disk volumes an account can own
Snapshot, // Number of snapshots an account can own
Template, // Number of templates an account can register/create
Project, // Number of projects an account can own
Network, // Number of networks an account can own
VPC, // Number of VPC an account can own
CPU, // Number of CPU an account can allocate for his resources
Memory, // Amount of RAM an account can allocate for his resources
PrimaryStorage, // Total primary storage space (in GiB) a user can use
SecondaryStorage // Total secondary storage space (in GiB) a user can use
}
*/
export interface ResourceCount extends BaseModel {
id?: string;
account: string;
domain: string;
domainid: string;
resourcecount: number;
resourcetype: number;
}
|
PHP | UTF-8 | 2,218 | 2.796875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
class syncMarsWeatherData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:sync_mars_weather_data';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$response = Http::get( 'https://api.nasa.gov/insight_weather/?api_key=DEMO_KEY&feedtype=json&ver=1.0' );
//TODO: check if response is valid
$solResponseDataArray = $response->json();
foreach( $solResponseDataArray as $solEntryKey => $solEntryData )
{
$this->info( $solEntryKey );
$this->info( json_encode( $solEntryData ) );
if( isset( $solEntryData[ 'AT' ] ) )
{
$insertDataArray = array(
'sol_key' => $solEntryKey,
'max_temp' => $solEntryData[ 'AT' ][ 'mx' ],
'min_temp' => $solEntryData[ 'AT' ][ 'mn' ],
'avg_temp' => $solEntryData[ 'AT' ][ 'av' ],
'max_windspeed' => $solEntryData[ 'HWS' ][ 'mx' ],
'min_windspeed' => $solEntryData[ 'HWS' ][ 'mn' ],
'avg_windspeed' => $solEntryData[ 'HWS' ][ 'av' ],
);
$insertResult = DB::table( 'sols' )->updateOrInsert( $insertDataArray );
if( $insertResult === true )
{
$this->info( 'Successfully inserted Sol key: ' . $solEntryKey );
}
else
{
$this->error( 'Error inserting Sol key: ' . $solEntryKey );
}
}
}
return 0;
}
}
|
Java | UTF-8 | 278 | 2.5625 | 3 | [] | no_license | package day0901;
public abstract class Shape {
volatile int age6;
public abstract void draw();
public void clear(){
System.out.println("/n/n/n/n/nnnnnn");
System.out.println("图形被擦除");
System.out.println("...............");
}
}
|
Java | UTF-8 | 2,050 | 2.1875 | 2 | [] | no_license | package com.smartflow.ievent.dao;
import com.smartflow.ievent.dto.FaultDistributionConditionInputDTO;
import com.smartflow.ievent.dto.PageConditionInputDTO;
import com.smartflow.ievent.model.EventSymptom;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
public interface EventSymptomDao {
/**
* 初始化症状下拉框
*
* @return
*/
public List<Map<String, Object>> getEventSymptomInit();
/**
* 初始化症状名称下拉框
*
* @return
*/
public List<Map<String, Object>> getEventSymptomNameInit();
/**
* 获取症状名称
* @return
*/
public List<Map<String, Object>> getEventSymptomNameList();
/**
* 获取症状分布图数据
*
* @param faultDistributionConditionDTO
* @return
*/
public List<Map<String, Object>> getSymptomDistributionChartData(FaultDistributionConditionInputDTO faultDistributionConditionDTO) throws ParseException;
/**
* 查询症状列表总条数
*
* @return
*/
public Integer getTotalCountEventSymptomList();
/**
* 查询症状列表
*
* @param pageConditionDTO 分页条件
* @return
*/
public List<EventSymptom> getEventSymptomList(PageConditionInputDTO pageConditionDTO);
/**
* 判断SymptomCode是否重复
*
* @param symptomCode
* @return
*/
public boolean isExistSymptomCode(String symptomCode);
/**
* 添加症状
*
* @param eventSymptom
*/
public void addEventSymptom(EventSymptom eventSymptom);
/**
* 根据症状id查询症状
*
* @param eventSymptomId
* @return
*/
public EventSymptom getEventSymptomById(Integer eventSymptomId);
/**
* 修改症状
*
* @param eventSymptom
*/
public void updateEventSymptom(EventSymptom eventSymptom);
/**
* 删除症状
*
* @param eventSymptom
*/
public void deleteEventSymptom(EventSymptom eventSymptom);
}
|
Java | UTF-8 | 785 | 3.734375 | 4 | [] | no_license | package Day_13;
import java.util.Scanner;
public class Bin2Dec11 {
public static void main(String[] args) {
start();
}
public static boolean checkBinStr(String str) {
return str.matches("[0-1]+");
}
public static int bin2Dec(String str) {
return Integer.parseInt(str,2);
}
public static void start() {
System.out.print("Enter a string :");
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
if(!checkBinStr(sentence)){
System.out.println("error: invalid binary string " + "\"" + sentence + "\"");
} else {
System.out.println("The equivalent decimal number for binary \""+ sentence + "\" is: " +bin2Dec(sentence));
}
}
}
|
Java | UTF-8 | 403 | 1.984375 | 2 | [] | no_license | package suit;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
/**
* @Author yuzhenni
* @Date 2020/9/5
*/
public class suitConfig {
@BeforeSuite
public void bs(){
System.out.println("suit运行了");
}
@AfterSuite
public void as(){
System.out.println("aftersuti运行了");
}
}
|
JavaScript | UTF-8 | 427 | 3.390625 | 3 | [] | no_license | setTimeout(function(hello) {
console.log('1000ms');
}, 1000, 'hello');
setTimeout(function() {
console.log('500ms');
}, 500);
setTimeout(function() {
setTimeout(function() {
}, 2000);
}, 2000);
Array.prototype.forEachAsync = function(cb) {
for (var i=0; i<this.length; i++) {
setTimeout(cb, 10 * i, this[i], i, this);
}
};
[1, 2, 3].forEachAsync(function (nb) {
console.log(nb);
});
console.log('End');
|
Markdown | UTF-8 | 205 | 2.765625 | 3 | [] | no_license | # Write a Python program to remove newline characters from a file.
Define a function that takes a string that contains a filepath. The function should remove all the newline characters('\n') in the file.
|
C++ | UTF-8 | 736 | 3.015625 | 3 | [] | no_license | //
// main.cpp
//
// Created by Auon Muhammad Akhtar on 2017-01-01.
// Copyright © 2017 Auon Muhammad Akhtar. All rights reserved.
//
#include "Python.h"
#include <iostream>
#include "Dijkstra.h"
int main(int argc, const char * argv[])
{
//Dijkstra myGR(int sg, float md), where sg = size_graph, md = maximum_distance
Dijkstra myGR; // <--------- Overloading constructor being used currently
myGR.draw_graph();
myGR.Dijkstra_algorithm();
int dest_vertex;
while(true)
{
std::cout << "Please enter vertex number to print shortest path or 100 to exit: ";
std::cin >> dest_vertex;
if (dest_vertex == 100)
{
break;
}
else
{
myGR.get_shortest_path(dest_vertex);
}
}
return 0;
}
|
Shell | UTF-8 | 532 | 3.859375 | 4 | [] | no_license | #!/bin/bash
if [ $# -eq 0 ]; then
recursive_clean.sh `pwd`
else
if [ ! -d $1 ]; then
echo "$1 is not a directory. Exiting."
exit 1
fi
file="$1/.AppleDouble"
if [ -d $file ]; then
echo "Found $file. Removing:"; rm -frv $file
fi
for file in `find $1 -type d -maxdepth 1 -mindepth 1 -not -name CVS 2>/dev/null`; do
recursive_clean.sh $file
done
if [ -f "$1/Makefile" ]; then
echo "Entering and cleaning $1"
make -C $1 clean
else
echo "No Makefile in $1. Nothing to do."
fi
fi
|
Java | UTF-8 | 548 | 3.125 | 3 | [] | no_license | package model;
import java.awt.Color;
import java.awt.Graphics2D;
/**
*
* @author tiwi
*/
public abstract class Shape {
protected final int x;
protected final int y;
protected final int breedte;
protected final int hoogte;
protected final Color kleur;
public Shape(Color kleur, int x, int y, int breedte, int hoogte){
this.x = x;
this.y = y;
this.breedte = breedte;
this.hoogte = hoogte;
this.kleur = kleur;
}
public abstract void draw(Graphics2D g);
}
|
PHP | UTF-8 | 1,598 | 2.625 | 3 | [] | no_license | <?php
require '../database/connect.php';
require '../session.php';
include '../function/formatTime.php';
if(isset($_POST['content']) && isset($_POST['id'])){
$content = $_POST['content'];
$id = $_POST['id'];
if(strlen(trim($content)) > 0){
$sql = "INSERT INTO comment (content, parent_id, user)
VALUES ('{$content}', '{$id}', '{$_SESSION['email']}')";
if ($conn->query($sql) === TRUE) {
$sql="select firstname, lastname, comment.reg_date, comment.content from comment, user where comment.id=(select max(id) from comment where user = '{$_SESSION['email']}') && comment.user= user.email;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { ?>
<div class='comment-container'>
<div id='comment-header'>
<span ><?php echo $row['firstname'] ?> <?php echo $row['lastname'] ?></span>
<span><?php echo formatTime($row['reg_date']); ?></span>
</div>
<div id='comment-content'>
<span><?php echo $row['content'] ?></span>
</div>
</div>
<?php
}
}
mysqli_free_result($result);
$conn->close();
}
}
}
?> |
PHP | UTF-8 | 36,015 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class InmateModel extends CI_Model
{
/**
* Model function to handle the inmate login
* @param array $credentials
* @return mixed[]
**/
public function getMedicineScheduleSearch($credentials)
{
$this->db->select('
medicine_schedule_history.id,
medicine_schedule_history.medicine_date,
medicine_schedule_history.staff_id,
medicine_schedule_history.inmate_id,
medicine_schedule_history.medicine_id,
staff.name as staff_name,
inmate.name,
medicines.medicine_name,
inmate_medicines.time
'
);
//$this->db->where('inmate_medicines.time >=', $credentials['time']);
$this->db->where('medicine_schedule_history.medicine_date >=', $credentials['from_date']);
$this->db->where('medicine_schedule_history.medicine_date <=', $credentials['to_date']);
$this->db->where('medicine_schedule_history.inmate_id', $credentials['id']);
$this->db->from('medicine_schedule_history');
$this->db->join('staff','staff.id=medicine_schedule_history.staff_id');
$this->db->join('medicines','medicines.id=medicine_schedule_history.medicine_id');
$this->db->join('inmate','inmate.id=medicine_schedule_history.inmate_id');
$this->db->join('inmate_medicines','inmate_medicines.id=medicine_schedule_history.inmate_medicine_id');
//$this->db->order_by('medicine_schedule_history.medicine_date ASC');
$this->db->order_by('inmate_medicines.time ASC');
$query=$this->db->get();
return $query->result();
}
public function getMedicineScheduleWithoutTime($credentials)
{
$this->db->select('
medicine_schedule_history.id,
medicine_schedule_history.medicine_date,
medicine_schedule_history.staff_id,
medicine_schedule_history.inmate_id,
medicine_schedule_history.medicine_id,
staff.name as staff_name,
inmate.name,
medicines.medicine_name,
inmate_medicines.time
'
);
//$this->db->where('inmate_medicines.time >=', $credentials['time']);
$this->db->where('medicine_schedule_history.medicine_date ', $credentials['date']);
$this->db->where('medicine_schedule_history.inmate_id', $credentials['id']);
$this->db->from('medicine_schedule_history');
$this->db->join('staff','staff.id=medicine_schedule_history.staff_id');
$this->db->join('medicines','medicines.id=medicine_schedule_history.medicine_id');
$this->db->join('inmate','inmate.id=medicine_schedule_history.inmate_id');
$this->db->join('inmate_medicines','inmate_medicines.id=medicine_schedule_history.inmate_medicine_id');
//$this->db->order_by('medicine_schedule_history.medicine_date ASC');
$this->db->order_by('inmate_medicines.time ASC');
$query=$this->db->get();
return $query->result();
}
public function isInmateExist($credentials)
{
$this->db->select('*');
$this->db->where('email', $credentials['email']);
$this->db->where('password_hash' , $credentials['password']);
$query=$this->db->get('inmate');
if($query->num_rows()==1){
return true;
}else{
return false;
}
}
/**
* Model function to get the name of the inmate
*/
public function getInmateDetails($credentials)
{
$this->db->where('email',$credentials['email']);
$query = $this->db->get('inmate')->result();
return $query;
}
/**
* Model function to get the inmate dashboard
*/
public function getMessage($credentials)
{
//var_dump($credentials);
// die;
$this->db->select('
message_table.id,
message_table.status,
message_table.to_id,
message_table.subject,
message_table.to_type,
message_table.from_id,
message_table.from_type,
message_table.date_created,
guardian.guardian_name,
admin.fullname,
staff.name,
inmate.name,
');
$this->db->from('message_table');
$this->db->where('message_table.to_id' , $credentials['id']);
$this->db->where('message_table.to_type' , $credentials['type']);
$this->db->join('inmate','message_table.from_id=inmate.id','left');
$this->db->join('staff','message_table.from_id=staff.id','left');
$this->db->join('guardian','message_table.from_id=guardian.id','left');
$this->db->join('admin','message_table.from_id=admin.id','left');
$this->db->order_by('date_created','DSC');
$query=$this->db->get();
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function getMessageCount($credentials)
{
//var_dump($credentials);
// die;
$this->db->select('
message_table.id,
message_table.to_id,
message_table.subject,
message_table.to_type,
message_table.from_id,
message_table.from_type,
message_table.date_created,
guardian.guardian_name,
staff.name,
inmate.name,
');
$this->db->from('message_table');
$this->db->where('message_table.to_id' , $credentials['id']);
$this->db->where('message_table.to_type' , $credentials['type']);
$this->db->where('message_table.status' , '0');
$this->db->join('inmate','message_table.from_id=inmate.id','left');
$this->db->join('staff','message_table.from_id=staff.id','left');
$this->db->join('guardian','message_table.from_id=guardian.id','left');
$this->db->order_by('date_created','ASC');
$query=$this->db->get();
return $query->num_rows();
}
public function getMessageDetailsStatus($messageId)
{
$this->db->set('status','1');
$this->db->where('id', $messageId);
if($this->db->update('message_table'))
{
}
}
public function getMessageDetails($messageId)
{
//var_dump($credentials);
// die;
$this->db->select('
message_table.id,
message_table.to_id,
message_table.subject,
message_table.to_type,
message_table.from_id,
message_table.from_type,
message_table.message,
message_table.date_created,
guardian.guardian_name,
staff.name,
inmate.name,
');
$this->db->from('message_table');
$this->db->where('message_table.id' , $messageId);
$this->db->join('inmate','message_table.from_id=inmate.id','left');
$this->db->join('staff','message_table.from_id=staff.id','left');
$this->db->join('guardian','message_table.from_id=guardian.id','left');
$query=$this->db->get();
return $query->result();
}
public function getStaffList()
{
$this->db->select('staff.id,staff.email,staff.date_of_joining,staff.mobile,staff_type.staff_type,staff.name');
$this->db->from('staff');
$this->db->join('staff_type','staff_type.id=staff.staff_type_id');
$query=$this->db->get();
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function medicineInmate($id)
{
$this->db->select('
inmate_medicines.id,
inmate_medicines.quantity,
inmate_medicines.time,
inmate_medicines.medicine_id,
inmate_medicines.inmate_id,
medicines.medicine_name,
inmate.name,
inmate_medicines.start_date
');
$this->db->from('inmate_medicines');
$this->db->where('inmate_medicines.inmate_id' , $id);
$this->db->join('inmate','inmate_medicines.inmate_id=inmate.id','left');
$this->db->join('medicines','inmate_medicines.medicine_id=medicines.id','left');
$query=$this->db->get();
return $query->result();
}
public function getMedicineSearch($search)
{
$this->db->select('*');
$this->db->from('medicines');
$this->db->like('medicine_name', $search, 'both');
$query=$this->db->get();
if($query->num_rows()==0)
{
return false;
}
else
{
return $query->result();
}
}
public function getMedicineSearchExist($search)
{
$this->db->select('*');
$this->db->from('medicines');
$this->db->like('medicine_name', $search, 'both');
$query=$this->db->get();
if($query->num_rows()==0)
{
return false;
}
else
{
foreach ($query->result() as $row)
{
$id=$row->id;
}
return $id;
}
}
public function getSearchMedicineList($search)
{
$this->db->select('*');
$this->db->from('medicines');
$this->db->like('medicine_name', $search, 'both');
$this->db->or_like('id', $search, 'both');
$this->db->or_like('medical_rep_name', $search, 'both');
$this->db->or_like('available_medicine_stock_count', $search, 'both');
$this->db->or_like('medical_rep_mobile', $search, 'both');
$query=$this->db->get();
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function getSearchGuardianList($search)
{
$this->db->select('
guardian.id,
guardian.email,
guardian.inmate_id,
guardian.mobile,
inmate.name,
guardian.guardian_name'
);
$this->db->from('guardian');
$this->db->join('inmate','guardian.inmate_id=inmate.id');
$this->db->or_like('guardian.id', $search, 'both');
$this->db->or_like('guardian.inmate_id', $search, 'both');
$this->db->or_like('inmate.name', $search, 'both');
$this->db->or_like('inmate.name', $search, 'both');
$this->db->or_like('guardian.guardian_name', $search, 'both');
$query=$this->db->get();
//var_dump($query->result());
//die;
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function getSearchStaffList($search)
{
$this->db->select('staff.id,staff.email,staff.date_of_joining,staff.mobile,staff_type.staff_type,staff.name');
$this->db->from('staff');
$this->db->join('staff_type','staff_type.id=staff.staff_type_id');
$this->db->like('staff.name', $search, 'both');
$this->db->or_like('staff_type.staff_type', $search, 'both');
$this->db->or_like('staff.email', $search, 'both');
$this->db->or_like('staff.id', $search, 'both');
$this->db->or_like('staff.mobile', $search, 'both');
$query=$this->db->get();
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function getSearchInmateList($search)
{
$this->db->select('*');
$this->db->from('inmate');
$this->db->like('name', $search, 'both');
$this->db->or_like('present_address', $search, 'both');
$this->db->or_like('permanent_address', $search, 'both');
$this->db->or_like('mobile', $search, 'both');
$this->db->or_like('email', $search, 'both');
$query=$this->db->get();
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function listAllStaffType()
{
$this->db->select('*');
$query=$this->db->get('staff_type');
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function registerSessionForAdmin($credentials)
{
$this->db->select('*');
$this->db->where('id' , $credentials['id']);
$query=$this->db->get('admin');
foreach ($query->result() as $row)
{
$credentials2['id']=$row->id;
$credentials2['name']=$row->fullname;
$credentials2['email']=$row->email;
$credentials2['type']="admin";
}
$this->session->set_userdata($credentials2);
return $credentials2;
}
public function checkReset($credentials)
{
$this->db->select('*');
$this->db->from('admin');
$this->db->where('email' ,$credentials['email']);
$this->db->where('password_reset' ,$credentials['message_new']);
$query=$this->db->get();
if($query->num_rows()==0)
{
return FALSE;
}
else
{
return TRUE;
}
}
public function adminChangePasswordLink($credentials)
{
$this->db->set('password',$credentials['password']);
$this->db->where('email', $credentials['email']);
if($this->db->update('admin'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function adminChangePassword($credentials)
{
$this->db->set('password',$credentials['password']);
$this->db->where('id', $credentials['id']);
if($this->db->update('admin'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function updateStaffType($credentials)
{
$this->db->set('staff_type',$credentials['staff_type']);
$this->db->where('id', $credentials['staff_type_id']);
if($this->db->update('staff_type'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function updateStaff($credentials)
{
$this->db->set($credentials);
$this->db->where('id', $credentials['id']);
if($this->db->update('staff'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function createStaff($credentials)
{
if($this->db->insert('staff',$credentials))
{
return true;
}
else
{
return false;
}
}
public function createMessage($credentials)
{
if($this->db->insert('message_table',$credentials))
{
return true;
}
else
{
return false;
}
}
public function notInAdmin($message)
{
$this->db->select('*');
$this->db->from('admin');
$this->db->where('password_reset' , $message);
$query=$this->db->get();
if($query->num_rows()==0)
{
return FALSE;
}
else
{
return TRUE;
}
}
public function updatePasswordReset($credentials)
{
$this->db->set('password_reset',$credentials['message']);
$this->db->where('email' , $credentials['email']);
$this->db->update('admin');
}
public function alreadySendAdmin($email)
{
$this->db->select('*');
$this->db->from('admin');
$this->db->where('email' , $email);
$this->db->where('password_reset is NOT NULL' ,NULL,FALSE);
$query=$this->db->get();
if($query->num_rows()==0)
{
return TRUE;
}
else
{
return FALSE;
}
}
public function passwordResetMessage($email)
{
$this->db->select('*');
$this->db->from('admin');
$this->db->where('email' , $email);
$query=$this->db->get();
if($query->num_rows()==1)
{
foreach ($query->result() as $row)
{
$message=$row->password_reset;
}
return $message;
}
else
{
return FALSE;
}
}
public function notEmailAdmin($email)
{
$this->db->select('*');
$this->db->from('admin');
$this->db->where('email' , $email);
$query=$this->db->get();
if($query->num_rows()==1)
{
return TRUE;
}
else
{
return FALSE;
}
}
public function editStaff($id)
{
$this->db->select('staff.id,
staff.email,
staff.date_of_joining,
staff.mobile,
staff_type.staff_type,
staff.name,
staff.staff_type_id,
staff.gender,
staff.date_of_birth,
staff.permanent_address,
staff.can_view_inmate_medicine_schedule,
staff.present_address'
);
$this->db->from('staff');
$this->db->join('staff_type','staff_type.id=staff.staff_type_id');
$this->db->where('staff.id' , $id);
$query=$this->db->get();
foreach ($query->result() as $row)
{
$credentials2['staff_id']=$row->id;
$credentials2['staff_name']=$row->name;
$credentials2['staff_email']=$row->email;
$credentials2['date_of_birth']=$row->date_of_birth;
$credentials2['mobile']=$row->mobile;
$credentials2['gender']=$row->gender;
$credentials2['date_of_joining']=$row->date_of_joining;
$credentials2['present_address']=$row->present_address;
$credentials2['staff_type_id']=$row->staff_type_id;
$credentials2['staff_type']=$row->staff_type;
$credentials2['permanent_address']=$row->permanent_address;
$credentials2['can_view_inmate']=$row->can_view_inmate_medicine_schedule;
}
return $credentials2;
}
public function editStaffType($id)
{
$this->db->select('*');
$this->db->where('id' , $id);
$query=$this->db->get('staff_type');
foreach ($query->result() as $row)
{
$credentials2['staff_id']=$row->id;
$credentials2['staff_type']=$row->staff_type;
}
return $credentials2;
}
public function getInmateList()
{
$this->db->select('*');
$this->db->from('inmate');
$query=$this->db->get();
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function getShiftList()
{
$this->db->select('*');
$this->db->from('shifts');
$query=$this->db->get();
return $query->result();
}
public function getMedicineList()
{
$this->db->select('*');
$this->db->from('medicines');
$query=$this->db->get();
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function createShift($credentials)
{
if($this->db->insert('shifts',$credentials))
{
return true;
}
else
{
return false;
}
}
public function createInmate($credentials)
{
if($this->db->insert('inmate',$credentials))
{
return true;
}
else
{
return false;
}
}
public function deleteShift($id)
{
$this->db->where('id', $id);
if($this->db->delete('shifts'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function deleteInmate($id)
{
$this->db->where('id', $id);
if($this->db->delete('inmate'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function editInmate($id)
{
$this->db->select('*');
$this->db->from('inmate');
$this->db->where('id' , $id);
$query=$this->db->get();
foreach ($query->result() as $row)
{
$credentials2['id']=$row->id;
$credentials2['name']=$row->name;
$credentials2['email']=$row->email;
$credentials2['payment_per_month']=$row->payment_per_month;
$credentials2['date_of_birth']=$row->date_of_birth;
$credentials2['date_of_joining']=$row->date_of_joining;
$credentials2['emergency_contact_person']=$row->emergency_contact_person;
$credentials2['emergency_contact_number']=$row->emergency_contact_number;
$credentials2['mobile']=$row->mobile;
$credentials2['gender']=$row->gender;
$credentials2['date_of_joining']=$row->date_of_joining;
$credentials2['present_address']=$row->present_address;
$credentials2['permanent_address']=$row->permanent_address;
}
return $credentials2;
}
public function editShift($id)
{
$this->db->select('*');
$this->db->from('shifts');
$this->db->where('id' , $id);
$query=$this->db->get();
foreach ($query->result() as $row)
{
$credentials2['id']=$row->id;
$credentials2['shift_name']=$row->shift_name;
$credentials2['shift_start_time']=$row->shift_start_time;
$credentials2['shift_end_time']=$row->shift_end_time;
}
return $credentials2;
}
public function updateShift($credentials)
{
$this->db->set($credentials);
$this->db->where('id', $credentials['id']);
if($this->db->update('shifts'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function updateInmate($credentials)
{
$this->db->set($credentials);
$this->db->where('id', $credentials['id']);
if($this->db->update('inmate'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function deleteMedicine($id)
{
$this->db->where('id', $id);
if($this->db->delete('medicines'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function editMedicine($id)
{
$this->db->select('*');
$this->db->where('id' , $id);
$query=$this->db->get('medicines');
foreach ($query->result() as $row)
{
$credentials2['medicine_id']=$row->id;
$credentials2['medicine_name']=$row->medicine_name;
$credentials2['available_medicine_stock_count']=$row->available_medicine_stock_count;
$credentials2['medical_rep_name']=$row->medical_rep_name;
$credentials2['medical_rep_mobile']=$row->medical_rep_mobile;
}
return $credentials2;
}
public function isAssigned($current_date)
{
$this->db->select('*');
$this->db->where('date' , $current_date);
$query=$this->db->get('duty_assigned');
if($query->num_rows()==1)
{
return TRUE;
}
else
{
return FALSE;
}
}
public function inmateMedicines()
{
$this->db->select('*');
$query=$this->db->get('inmate_medicines');
return $query->result();
}
public function inmateMedicinesDate($date)
{
$this->db->select('medicine_schedule_history.id,inmate_medicines.time');
$this->db->join('inmate_medicines','inmate_medicines.id=medicine_schedule_history.inmate_medicine_id');
$this->db->where('medicine_date' , $date);
$query=$this->db->get('medicine_schedule_history');
return $query->result();
}
public function staffCareTaker($staff_type)
{
$this->db->select('id');
$this->db->where('staff_type' , $staff_type);
$query=$this->db->get('staff_type');
foreach ($query->result() as $row)
{
return $row->id;
}
}
public function getMinStaff($credentials)
{
$this->db->select('staff_work_shift.staff_id,staff_work_shift.id');
$this->db->join('staff','staff.id=staff_work_shift.staff_id');
$this->db->join('staff_type','staff_type.id=staff.staff_type_id');
$this->db->join('shifts','shifts.id=staff_work_shift.shift_id');
$this->db->where('staff_work_shift.date' , $credentials['date']);
$this->db->where('staff_work_shift.date' , $credentials['date']);
$this->db->where('staff_type.id' , $credentials['careTakerId']);
$this->db->where('shifts.shift_start_time <=' , $credentials['time']);
$this->db->where('shifts.shift_end_time >=' , $credentials['time']);
$this->db->order_by('staff_work_shift.no_duty ASC');
$query=$this->db->get('staff_work_shift');
foreach ($query->result() as $row)
{
$data['staff_id']=$row->staff_id;
$data['id']=$row->id;
return $data;
}
}
public function updateNoDuty($id)
{
$this->db->select('no_duty');
$this->db->from('staff_work_shift');
$this->db->where('id' , $id);
$query=$this->db->get();
foreach ($query->result() as $row)
{
$count=$row->no_duty;
}
$count=$count+1;
$this->db->set('no_duty',$count);
$this->db->where('id', $id);
$this->db->update('staff_work_shift');
}
public function isDutyDateAssign($credentials)
{
$this->db->insert('duty_assigned',$credentials);
}
public function assignDuty($credentials)
{
$this->db->insert('staff_work_shift',$credentials);
}
public function medicineSchedule($credentials)
{
$this->db->insert('medicine_schedule_history',$credentials);
}
public function updateSchedule($credentials)
{
$this->db->set('staff_id',$credentials['staff_id']);
$this->db->where('id',$credentials['id']);
$this->db->update('medicine_schedule_history');
}
public function checkCurrentDate($date)
{
$this->db->set('status','1');
$this->db->where('date', $date);
$this->db->update('staff_work_shift');
$this->db->set('status','-1');
$this->db->where('date <', $date);
$this->db->update('staff_work_shift');
$this->db->set('status','0');
$this->db->where('date >', $date);
$this->db->update('staff_work_shift');
}
public function updateMedicine($credentials)
{
$this->db->set($credentials);
$this->db->where('id', $credentials['id']);
if($this->db->update('medicines'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function getStaffDuty($date)
{
$this->db->select('
shifts.shift_name,
staff_work_shift.id,
staff_work_shift.date,
staff_type.staff_type,
shifts.shift_start_time,
shifts.shift_end_time,
staff.name'
);
$this->db->from('staff_work_shift');
$this->db->where('staff_work_shift.date', $date);
$this->db->join('staff','staff.id=staff_work_shift.staff_id');
$this->db->join('staff_type','staff.staff_type_id=staff_type.id');
$this->db->join('shifts','staff_work_shift.shift_id=shifts.id');
$this->db->order_by('shifts.shift_start_time','ASC');
$query=$this->db->get();
return $query->result();
}
public function getGuardianList()
{
$this->db->select('
guardian.id,
guardian.email,
guardian.inmate_id,
guardian.mobile,
inmate.name,
guardian.guardian_name'
);
$this->db->from('guardian');
$this->db->join('inmate','guardian.inmate_id=inmate.id');
$query=$this->db->get();
//var_dump($query->result());
//die;
if(!empty($query->result()))
{
return $query->result();
}
else
{
return false;
}
}
public function getMedicineSchedule($credentials)
{
$this->db->select('
medicine_schedule_history.id,
medicine_schedule_history.medicine_date,
medicine_schedule_history.staff_id,
medicine_schedule_history.inmate_id,
medicine_schedule_history.medicine_id,
staff.name as staff_name,
inmate.name,
medicines.medicine_name,
inmate_medicines.time
'
);
$this->db->where('inmate_medicines.time >=', $credentials['time']);
$this->db->where('medicine_schedule_history.medicine_date', $credentials['date']);
$this->db->from('medicine_schedule_history');
$this->db->join('staff','staff.id=medicine_schedule_history.staff_id');
$this->db->join('medicines','medicines.id=medicine_schedule_history.medicine_id');
$this->db->join('inmate','inmate.id=medicine_schedule_history.inmate_id');
$this->db->join('inmate_medicines','inmate_medicines.id=medicine_schedule_history.inmate_medicine_id');
//$this->db->order_by('medicine_schedule_history.medicine_date ASC');
$this->db->order_by('inmate_medicines.time ASC');
$query=$this->db->get();
return $query->result();
}
public function createGuardian($credentials)
{
if($this->db->insert('guardian',$credentials))
{
return true;
}
else
{
return false;
}
}
public function deleteGuardian($id)
{
$this->db->where('id', $id);
if($this->db->delete('guardian'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function updateGuardian($credentials)
{
$this->db->set($credentials);
$this->db->where('id', $credentials['id']);
if($this->db->update('guardian'))
{
return TRUE;
}
else
{
return FALSE;
}
}
public function adminPasswordResetNull($credentials)
{
$this->db->set('password_reset', 'NULL', false);
$this->db->where('email', $credentials['email']);
$this->db->update('admin');
}
public function isValidReset($credentials)
{
$this->db->select('*');
$this->db->from('admin');
$this->db->where('email' , $credentials['email']);
$this->db->where('password_reset' , $credentials['reset']);
$query=$this->db->get();
if($query->num_rows()==0)
{
return FALSE;
}
else
{
return TRUE;
}
}
public function editGuardian($id)
{
$this->db->select('
guardian.id,
guardian.email,
guardian.inmate_id,
guardian.mobile,
guardian.gender,
guardian.date_of_birth,
guardian.permanent_address,
guardian.present_address,
inmate.name,
inmate.date_of_joining,
guardian.guardian_name'
);
$this->db->from('guardian');
$this->db->join('inmate','guardian.inmate_id=inmate.id');
$this->db->where('guardian.id' , $id);
$query=$this->db->get();
foreach ($query->result() as $row)
{
$credentials2['id']=$row->id;
$credentials2['guardian_name']=$row->guardian_name;
$credentials2['email']=$row->email;
$credentials2['date_of_birth']=$row->date_of_birth;
$credentials2['date_of_joining']=$row->date_of_joining;
$credentials2['mobile']=$row->mobile;
$credentials2['gender']=$row->gender;
$credentials2['present_address']=$row->present_address;
$credentials2['inmate_id']=$row->inmate_id;
$credentials2['permanent_address']=$row->permanent_address;
}
return $credentials2;
}
public function getInmateDashboardDetails($credentials)
{
$this->db->select('
medicine_schedule_history.id,
medicine_schedule_history.medicine_date,
medicine_schedule_history.staff_id,
medicine_schedule_history.inmate_id,
medicine_schedule_history.medicine_id,
staff.name as staff_name,
inmate.name,
medicines.medicine_name,
inmate_medicines.time
'
);
$this->db->where('inmate_medicines.time >=', $credentials['time']);
$this->db->where('medicine_schedule_history.inmate_id', $credentials['id']);
$this->db->where('medicine_schedule_history.medicine_date', $credentials['date']);
$this->db->from('medicine_schedule_history');
$this->db->join('staff','staff.id=medicine_schedule_history.staff_id');
$this->db->join('medicines','medicines.id=medicine_schedule_history.medicine_id');
$this->db->join('inmate','inmate.id=medicine_schedule_history.inmate_id');
$this->db->join('inmate_medicines','inmate_medicines.id=medicine_schedule_history.inmate_medicine_id');
//$this->db->order_by('medicine_schedule_history.medicine_date ASC');
$this->db->order_by('inmate_medicines.time ASC');
$query=$this->db->get();
return $query->result();
}
/**
* Model function to get the inmate profile
*/
public function getInmateProfileDetails($credentials)
{
$this->db->select("*");
$this->db->from('inmate');
$this->db->where('id',$credentials['id']);
$query = $this->db->get()->result();
foreach ($query as $row){
$credentials2['name']=$row->name;
$credentials2['mobile']=$row->mobile;
$credentials2['email']=$row->email;
$credentials2['permanent_address']=$row->permanent_address;
$credentials2['present_address']=$row->present_address;
$credentials2['gender']=$row->gender;
$credentials2['date_of_joining']=$row->date_of_joining;
$credentials2['payment_per_month']=$row->payment_per_month;
$credentials2['date_of_birth']=$row->date_of_birth;
$credentials2['emergency_contact_number']=$row->emergency_contact_number;
$credentials2['emergency_contact_person']=$row->emergency_contact_person;
}
return $credentials2;
}
/**
* Model function to edit the staff profile
*/
public function editProileDetails($credentials)
{
$this->db->select("*");
$this->db->from('inmate');
$this->db->where('id',$credentials['id']);
$query = $this->db->get()->result();
foreach ($query as $row){
$credentials2['name']=$row->name;
$credentials2['mobile']=$row->mobile;
$credentials2['email']=$row->email;
$credentials2['permanent_address']=$row->permanent_address;
$credentials2['present_address']=$row->present_address;
$credentials2['gender']=$row->gender;
$credentials2['date_of_joining']=$row->date_of_joining;
$credentials2['date_of_birth']=$row->date_of_birth;
}
return $credentials2;
}
/**
* Model function to update the inmate
*/
public function updateInmateProfileDetails($credentials)
{
$this->db->set( $credentials);
$this->db->where('email', $credentials['email']);
if($this->db->update('inmate',$credentials))
{
return true;
}else{
return false;
}
}
} |
C# | UTF-8 | 496 | 2.75 | 3 | [] | no_license | using UnityEngine;
public class RandomHelper
{
public static int Range(int x, int y, int key, int range)
{
uint hash = (uint)key;
hash ^= (uint)x;
hash *= 0x51d7348d;
hash ^= 0x85dbdda2;
hash = (hash << 16) ^ (hash >> 16);
hash *= 0x7588f287;
hash ^= (uint)y;
hash *= 0x487a5559;
hash ^= 0x64887219;
hash = (hash << 16) ^ (hash >> 16);
hash *= 0x63288691;
return (int)(hash % range);
}
} |
C# | UTF-8 | 8,656 | 2.53125 | 3 | [] | no_license | namespace Repository
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using IRepository;
using POCO;
public class DegreeAuditRepository : BaseRepository, IDegreeAuditRepository
{
// const string
private const string AddDegreeAudits = "spInsertStudentDegreeAudit";
private const string UpdateDegreeAudits = "spUpdateStudentDegreeAudit";
private const string DeleteDegreeAudits = "spDeleteStudentDegreeAudit";
private const string GetDegreeAudits = "spGetDegreeAudit";
// new method start from here (assignment #2)
public void InsertDegreeAudit(DegreeAudit degree_audit, ref List<string> errors)
{
var conn = new SqlConnection(ConnectionString);
try
{
var adapter = new SqlDataAdapter(AddDegreeAudits, conn)
{
SelectCommand =
{
CommandType = CommandType.StoredProcedure
}
};
adapter.SelectCommand.Parameters.Add(new SqlParameter("@student_id", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters.Add(new SqlParameter("@course_id", SqlDbType.Int));
adapter.SelectCommand.Parameters.Add(new SqlParameter("@course_grade", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters["@student_id"].Value = degree_audit.StudentId;
adapter.SelectCommand.Parameters["@course_id"].Value = degree_audit.CourseId;
adapter.SelectCommand.Parameters["@course_grade"].Value = degree_audit.CourseGrade;
var dataSet = new DataSet();
adapter.Fill(dataSet);
}
catch (Exception e)
{
errors.Add("Error: " + e);
}
finally
{
conn.Dispose();
}
}
public void UpdateDegreeAudit(DegreeAudit degree_audit, ref List<string> errors)
{
var conn = new SqlConnection(ConnectionString);
try
{
var adapter = new SqlDataAdapter(UpdateDegreeAudits, conn)
{
SelectCommand =
{
CommandType = CommandType.StoredProcedure
}
};
adapter.SelectCommand.Parameters.Add(new SqlParameter("@student_id", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters.Add(new SqlParameter("@course_id", SqlDbType.Int));
adapter.SelectCommand.Parameters.Add(new SqlParameter("@course_grade", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters["@student_id"].Value = degree_audit.StudentId;
adapter.SelectCommand.Parameters["@course_id"].Value = degree_audit.CourseId;
adapter.SelectCommand.Parameters["@course_grade"].Value = degree_audit.CourseGrade;
var dataSet = new DataSet();
adapter.Fill(dataSet);
}
catch (Exception e)
{
errors.Add("Error: " + e);
}
finally
{
conn.Dispose();
}
}
public void DeleteDegreeAudit(DegreeAudit degreeAudit, ref List<string> errors)
{
var conn = new SqlConnection(ConnectionString);
try
{
var adapter = new SqlDataAdapter(DeleteDegreeAudits, conn)
{
SelectCommand =
{
CommandType = CommandType.StoredProcedure
}
};
adapter.SelectCommand.Parameters.Add(new SqlParameter("@student_id", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters.Add(new SqlParameter("@course_id", SqlDbType.Int));
adapter.SelectCommand.Parameters["@student_id"].Value = degreeAudit.StudentId;
adapter.SelectCommand.Parameters["@course_id"].Value = degreeAudit.CourseId;
var dataSet = new DataSet();
adapter.Fill(dataSet);
}
catch (Exception e)
{
errors.Add("Error: " + e);
}
finally
{
conn.Dispose();
}
}
public List<DegreeAudit> GetDegreeAudit(string studentId, ref List<string> errors)
{
var conn = new SqlConnection(ConnectionString);
var degreeAuditList = new List<DegreeAudit>();
try
{
var adapter = new SqlDataAdapter(GetDegreeAudits, conn)
{
SelectCommand = { CommandType = CommandType.StoredProcedure }
};
adapter.SelectCommand.Parameters.Add(new SqlParameter("@student_id", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters["@student_id"].Value = studentId;
var dataSet = new DataSet();
adapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
for (var i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
var degreeAudit = new DegreeAudit
{
StudentId = dataSet.Tables[0].Rows[i]["studentId"].ToString(),
CourseId = dataSet.Tables[0].Rows[i]["course_id"].ToString(),
CourseGrade = dataSet.Tables[0].Rows[i]["course_grade"].ToString(),
Course = new Course
{
Title = dataSet.Tables[0].Rows[i]["course_title"].ToString(),
Description = dataSet.Tables[0].Rows[i]["course_description"].ToString(),
}
};
degreeAuditList.Add(degreeAudit);
////System.Diagnostics.Debug.Write(dataSet.Tables[0].Rows[0]["student_id"].ToString());
}
}
catch (Exception e)
{
errors.Add("Error: " + e);
}
finally
{
conn.Dispose();
}
return degreeAuditList;
}
public List<DegreeAudit> GetDegreeAuditPerId(string studentId, string courseId, ref List<string> errors)
{
var conn = new SqlConnection(ConnectionString);
var degreeAuditList = new List<DegreeAudit>();
try
{
var adapter = new SqlDataAdapter(GetDegreeAudits, conn)
{
SelectCommand = { CommandType = CommandType.StoredProcedure }
};
adapter.SelectCommand.Parameters.Add(new SqlParameter("@student_id", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters.Add(new SqlParameter("@course_id", SqlDbType.VarChar, 20));
adapter.SelectCommand.Parameters["@student_id"].Value = studentId;
adapter.SelectCommand.Parameters["@course_id"].Value = studentId;
var dataSet = new DataSet();
adapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
for (var i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
var degreeAudit = new DegreeAudit
{
CourseId = dataSet.Tables[0].Rows[i]["course_id"].ToString(),
CourseGrade = dataSet.Tables[0].Rows[i]["course_grade"].ToString(),
Course = new Course
{
Title = dataSet.Tables[0].Rows[i]["course_title"].ToString(),
Description = dataSet.Tables[0].Rows[i]["course_description"].ToString(),
}
};
degreeAuditList.Add(degreeAudit);
////System.Diagnostics.Debug.Write(dataSet.Tables[0].Rows[0]["student_id"].ToString());
}
}
catch (Exception e)
{
errors.Add("Error: " + e);
}
finally
{
conn.Dispose();
}
return degreeAuditList;
}
}
}
|
C++ | UTF-8 | 814 | 3.046875 | 3 | [] | no_license | #include "Action.hh"
#include "Board.hh"
using namespace std;
Action::Action (istream& is) {
ordres1.clear();
ordres2.clear();
ordres3.clear();
int id;
while (is >> id and id != -1) {
int x, y;
is >> x >> y;
ordres1[id] = Posicio(x, y);
}
while (is >> id and id != -1) {
int d;
is >> d;
ordres2[id] = d;
}
int x, y;
while (is >> x and x != -1) {
is >> y;
ordres3.push_back(Posicio(x, y));
}
}
void Action::print (ostream& os) const {
for (const auto& p : ordres1)
os << p.first << " " << p.second.x << " " << p.second.y << endl;
os << "-1" << endl;
for (const auto& p : ordres2)
os << p.first << " " << p.second << endl;
os << "-1" << endl;
for (const auto& p : ordres3)
os << p.x << " " << p.y << endl;
os << "-1" << endl;
}
|
PHP | UTF-8 | 1,434 | 2.609375 | 3 | [] | no_license | <?php ob_start();
require_once('header.php');
if (isset($_GET['id'])) {
$id = $_GET['id'];
try {
require_once('db.php');
$sql = "SELECT * FROM markers WHERE id = :id";
$cmd = $conn->prepare($sql);
$cmd->bindParam(':id', $id, PDO::PARAM_INT);
$cmd->execute();
$result = $cmd->fetchAll();
foreach ($result as $row) {
$name = $row['name'];
$date = $row['date'];
$city = $row['city'];
$address = $row['address'];
}
//disconnect
$conn = null;
}
catch (Exception $e) {
mail('pampsolutions@outlook.com', 'App Error', $e, 'From: pampsolutions@outlook.com');
header('location:error.php');
exit();
}
}
?>
<div class="card">
<form method="post" action="save-marker.php">
<div>
<label for="name">Name:</label>
<input name="name" required value="<?php echo $name; ?>" />
</div>
<div>
<label for="date">Date:</label>
<input name="date" required value="<?php echo $date; ?>" />
</div>
<div>
<label for="city">City:</label>
<input name="city" required value="<?php echo $city; ?>" />
</div>
<div>
<label for="address">Description:</label>
<input name="address" required value="<?php echo $address; ?>" />
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" class="waves-effect waves-light btn green" value="Save" />
</form>
</div>
<?php
//embed footer
require_once('footer.php');
ob_flush();
?> |
Go | UTF-8 | 2,052 | 2.671875 | 3 | [
"MIT",
"BSD-3-Clause",
"MPL-2.0",
"ISC",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | package dnsproxy
import (
"context"
"net"
"reflect"
"runtime"
"testing"
"time"
"github.com/miekg/dns"
"github.com/stretchr/testify/require"
"github.com/datawire/dlib/dlog"
"github.com/telepresenceio/telepresence/v2/pkg/iputil"
)
func TestLookup(t *testing.T) {
type tType struct {
qType uint16
qName string
}
tests := []tType{
{
dns.TypeA,
"google.com.",
},
{
dns.TypeCNAME,
"_smpp_._tcp.golang.org.",
},
{
dns.TypePTR,
"78.217.250.142.in-addr.arpa.",
},
{
dns.TypeMX,
"gmail.com.",
},
{
dns.TypeTXT,
"dns.google.",
},
{
dns.TypeSRV,
"_myservice._tcp.tada.se.",
},
}
// AAAA returns an error on Windows:
// "getaddrinfow: The requested name is valid, but no data of the requested type was found"
if runtime.GOOS != "windows" {
tests = append(tests, tType{
dns.TypeAAAA,
"google.com.",
})
}
for _, tt := range tests {
t.Run(dns.TypeToString[tt.qType], func(t *testing.T) {
ctx := dlog.NewTestContext(t, false)
got, _, err := Lookup(ctx, tt.qType, tt.qName)
require.NoError(t, err)
require.Greater(t, len(got), 0)
})
}
}
func TestPtrAddress_v4(t *testing.T) {
ip, err := PtrAddress("32.127.168.192.in-addr.arpa.")
require.NoError(t, err)
require.Equal(t, net.IP{192, 168, 127, 32}, ip)
}
func TestPtrAddress_v6(t *testing.T) {
ip, err := PtrAddress("b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.")
require.NoError(t, err)
require.Equal(t, iputil.Parse("2001:db8::567:89ab"), ip)
}
func TestTimedExternalLookup(t *testing.T) {
t.Skip("needs some more love, the diff between lookups is not predicable")
names := []string{
"google.com",
}
for _, name := range names {
t.Run(name, func(t *testing.T) {
wips, err := net.LookupIP(name)
require.NoError(t, err)
want := iputil.UniqueSorted(wips)
got := TimedExternalLookup(context.Background(), name, 2*time.Second).UniqueSorted()
if !reflect.DeepEqual(got, want) {
t.Errorf("TimedExternalLookup() = %v, want %v", got, want)
}
})
}
}
|
JavaScript | UTF-8 | 387 | 2.65625 | 3 | [] | no_license | /*module.exports = function(req, res, next){
console.log("Hello from the testmodule.js");
res.status(200).send("Hello from the testmodule.js");
next();
}*/
module.exports.testFunction = function(){
console.log("Hello from module.exports.testFunction ");
return "return from module.exports.testFunction!";
//res.status(200).send("Hello from module.exports.testFunction ");
}
|
Java | UTF-8 | 551 | 1.8125 | 2 | [] | no_license | package com.ywcjxf.mall.serviceinterface.feign.fallback;
import com.ywcjxf.mall.pojo.IndexAd;
import com.ywcjxf.mall.serviceinterface.feign.IndexAdServiceFeign;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class IndexAdServiceFeignFallback implements IndexAdServiceFeign {
@Override
public void insertImage(String imageLink) {
System.out.println("fallback:insertImage");
}
@Override
public List<IndexAd> getAllValidIndexAd(Integer categoryId) {
return null;
}
}
|
JavaScript | UTF-8 | 723 | 2.671875 | 3 | [] | no_license | // 导入 http 模块
const http = require('http');
const fs = require('fs');
const qs = require('querystring');
const urlM = require('url');
// 创建服务器
var server = http.createServer(function(req, res){
if (req.url == '/favicon.ico') {
return;
}
// 获取 POST 数据
// data 有一段数据到达(很多次)
var str = '';
var n = 1;
req.on('data', function(data){
str += data;
console.log(n++ + "次收到数据\n");
console.log("====================\n");
})
// end-数据全部到达(一次)
req.on('end', function(){
var POST = qs.parse(str);
console.log(POST);
});
res.end();
});
const port = 8000;
// 监听8000服务端口
server.listen(8000);
|
PHP | UTF-8 | 207 | 2.9375 | 3 | [] | no_license | <?php
declare(strict_types = 1);
namespace App\Comparable;
interface IntegerInterface
{
public function getIntegerValue(): int;
public function isMultipleOf(self $toCompare): bool;
}
|
Python | UTF-8 | 364 | 3.171875 | 3 | [] | no_license | import pickle
# my_tuple = (('hello stranger', 'naked cartoon character'), 'penguin meme', 'yo! mama meme')
# with open("my_pickle", 'wb') as my_pickle:
# pickle.dump(my_tuple, my_pickle)
with open("my_pickle", 'rb') as my_pickle:
tp = pickle.load(my_pickle)
print(tp)
first, second, third = tp
for i in first:
print(i)
print(second)
print(third)
|
C | UTF-8 | 5,611 | 2.5625 | 3 | [
"MIT"
] | permissive |
#include "../../include/header.h"
#include "../../include/monitor_queries.h"
#include "../../include/dir_queries.h"
#include "../../include/VaccinMonitor_Utilities.h"
extern struct monitor_info m_structs;
/* ========================================================================= */
bool Compare_vaccinationdates(char * date2, char *date1){
int day1 , day2, month1, month2,year1, year2;
char *date;
char _date1[11],_date2[11],_date3[11];
strcpy(_date1,date1);
date = strtok(_date1,"-");
day1 = atoi(date);
date = strtok(NULL,"-");
month1 = atoi(date);
date = strtok(NULL,"-");
year1 = atoi(date);
strcpy(_date2,date2);
date = strtok(_date2,"-");
day2 = atoi(date);
date = strtok(NULL,"-");
month2 = atoi(date);
date = strtok(NULL,"-");
year2 = atoi(date);
if(year1>year2)
return false;
if(year2==year1){
if(month2>month1)
return false;
else if(month1==month2){
if(day2>day1)
return false;
else
return true;
}
else if(month2-6<=month1<=month2)
return true;
else
return false;
}
if(year2 < year1){
//if user was vaccinated a year ago then we check month
if(month1<month2)
return false;
if(month1==month2)
return false;
if(month2>=month1+6){
if(month2 == month1 +6){
if(day2>day1)
return false;
else
return true;
}
return true;
}
}
if(year2>year1){
return false;
}
return true;
}
// Search in the database for a patient record with id <rec_id>.
// If found, send a message to the parent with the result (record).
void find_vaccination(char *msg, int write_fd, int bufferSize){
//Body of Message: virusname/citizen_id/date
//or Body of Message: no
if(strcmp(msg,"no")==0){
return;
}
char buf[256];
char answer[4];
char *token = strtok(msg,"/");
char *virus_name = malloc((strlen(token)+1)*sizeof(char));
strcpy(virus_name,token);
token = strtok(NULL, "/");
char *citizen_id = malloc((strlen(token)+1)*sizeof(char));
strcpy(citizen_id,token);
token = strtok(NULL, "/");
char *date = malloc((strlen(token)+1)*sizeof(char));
strcpy(date,token);
token = strtok(NULL, "/");
char *country_name = malloc((strlen(token)+1)*sizeof(char));
strcpy(country_name,token);
ListNode found = ListFind(m_structs.viruses,virus_name,1);
if(found==NULL){
printf("Virus doesn't exist\n");
return;
}
snode *found2=skiplist_search((*(filters *)found->info).vaccinated,atoi(citizen_id));
if(found2==NULL){
strcpy(answer,"NO");
printf("REQUEST REJECTED – YOU ARE NOT VACCINATED\n");
}
else{
bool ok = Compare_vaccinationdates(date,found2->date);
if(ok==true){
printf("REQUEST ACCEPTED – HAPPY TRAVELS\n");
strcpy(answer,"YES");
}
else{
printf("REQUEST REJECTED – YOU WILL NEED ANOTHER VACCINATION BEFORE TRAVEL DATE\n");
strcpy(answer,"NO");
}
}
snprintf(buf, 256, "%s/%s/%s/%s",answer,virus_name,date,country_name);
int total =strlen(virus_name) + strlen(answer) + strlen(date) + strlen(country_name) + 3;
buf[total] = '\0';
free(virus_name);
free(citizen_id);
free(date);
write_msg_to_pipe(write_fd,TRAVEL_REQUEST_RES,buf,bufferSize);
}
void m_searchVaccinationStatus(char *citizenID, int write_fd, int bufferSize)
{
//CHTSearch(char *key, struct C_Bucket *ht)
puts(citizenID);
int found = CHTSearch(citizenID,m_structs.citizen_ht);
if(found==-1)
return;
char _buf[128];
//printf("%s %s %s %s\n%sAGE %d\n",citizenID, (*( struct citizen_Record *)m_structs.citizen_ht[found].value).name,(*( struct citizen_Record *)m_structs.citizen_ht[found].value).surname,(*( struct Bucket *)m_structs.citizen_ht[found].value).key,(*( struct citizen_Record *)m_structs.citizen_ht[found].value).age);
snprintf(_buf, 128, "%s %s %s %s\nAGE %d\n", citizenID, (*( struct citizen_Record *)m_structs.citizen_ht[found].value).name,(*( struct citizen_Record *)m_structs.citizen_ht[found].value).surname,(*( struct Bucket *)m_structs.citizen_ht[found].value).key,(*( struct citizen_Record *)m_structs.citizen_ht[found].value).age);
int total = strlen(_buf);
char *res = malloc(total*sizeof(char));
memcpy(res,_buf,total*sizeof(char));
for(ListNode current = m_structs.viruses->dummy->Next; current != NULL; current = current->Next){
char buf[128];
snode *vac_found;
//snode *nonvac_found;
vac_found = skiplist_search((*(filters *)current->info).vaccinated,atoi(citizenID));
//nonvac_found = skiplist_search((*(filters *)current->info).non_vaccinated,atoi(citizenID));
if(vac_found!=NULL){
snprintf(buf,128, "%s VACCINATED ON %s\n", (*(filters *)current->info).virus_key,vac_found->date);
//printf("%s VACCINATED ON %s\n",(*(filters *)current->info).virus_key,vac_found->date);
}
else{
snprintf(buf,128, "%s NOT YET VACCINATED\n",(*(filters *)current->info).virus_key);
//printf("%s NOT YET VACCINATED\n",(*(filters *)current->info).virus_key);
}
char *tmp = malloc(total*sizeof(char));
memcpy(tmp,res,total*sizeof(char));
res = malloc((total+strlen(buf))*sizeof(char));
memcpy(res,tmp,total*sizeof(char));
memcpy(res+total,buf,strlen(buf)*sizeof(char));
total += strlen(buf);
free(tmp);
}
res[total-1] = '\0';
write_msg_to_pipe(write_fd, SEARCH_VAC_STAT_RESULT, res,bufferSize);
} |
Java | UTF-8 | 278 | 1.617188 | 2 | [] | no_license | package com.jumbo.wms.model.mongodb;
@SuppressWarnings("serial")
public class StaCartonLineCommand extends StaCartonLine {
private Long qty2;
public Long getQty2() {
return qty2;
}
public void setQty2(Long qty2) {
this.qty2 = qty2;
}
}
|
Java | UTF-8 | 1,506 | 2.1875 | 2 | [] | no_license | package kr.or.pets.notice.vo;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Date;
import org.springframework.stereotype.Component;
/*
noticeImageNo number(10) PRIMARY KEY
, noticeImageFileName varchar2(50)
, regDate DATE DEFAULT sysdate
, noNumber number(10)
, CONSTRAINT FKNoNumber FOREIGN key(noNumber)
REFERENCES noticePage(noNumber) on delete CASCADE
*/
@Component("noticeImageVO")
public class NoticeImageVO {
private int noticeImageNo;
private String noticeImageFileName;
private Date regDate;
private int noNumber;
public NoticeImageVO() {
// TODO Auto-generated constructor stub
}
public int getNoticeImageNo() {
return noticeImageNo;
}
public void setNoticeImageNo(int noticeImageNo) {
this.noticeImageNo = noticeImageNo;
}
public String getNoticeImageFileName() {
return noticeImageFileName;
}
public void setNoticeImageFileName(String noticeImageFileName) {
try {
if(noticeImageFileName != null && noticeImageFileName.length() != 0) {
this.noticeImageFileName = URLEncoder.encode(noticeImageFileName, "utf-8"); //파일이름에 특수문자가 있을 경우 인코딩합니다.
}
} catch (UnsupportedEncodingException e) {
e.getMessage();
}
}
public Date getRegDate() {
return regDate;
}
public void setRegDate(Date regDate) {
this.regDate = regDate;
}
public int getNoNumber() {
return noNumber;
}
public void setNoNumber(int noNumber) {
this.noNumber = noNumber;
}
}
|
Java | UTF-8 | 617 | 2.828125 | 3 | [] | no_license | /**
* @author Nastya
*
* This is a simple Microservice Application
* App uses Third Party API of Ice and Fire to find fellows of entered
* characters of the same house who are not dead.Yet.
*
* How to get specified data:
*
* GET + /characters - returns all data stored in database(paginated)
*
* GET + /characters/{id} - returns one character with specified id
*
* POST + /characters/{name} - returns id of stored entry in database if character is found by API
*
* Relationship between characters is solely based on API's information
* By dafault, relationship is stated as 'fellows'.
*
*
*
* **/ |
Java | UTF-8 | 177 | 1.585938 | 2 | [
"Apache-2.0"
] | permissive | package com.yundroid.kokpit.commands;
public enum FlyingMode {
FLYING_MODE_FREE_FLIGHT,
FLYING_MODE_HOVER_ON_TOP_OF_ROUNDEL,
FLYING_MODE_HOVER_ON_TOP_OF_ORIENTED_ROUNDEL;
}
|
Python | UTF-8 | 3,290 | 3.3125 | 3 | [
"MIT"
] | permissive | """
dictgen.py
The WPA2 password hint is as follows:
1) It contains two words/acronyms, one with 3 letters and the other with 4
letters. Each letter can be upper or lower case. The two words are separated.
2) It contains 4 consecutive digits.
3) It contains two special characters, the ones above the numbers on the
keyboard. The characters are separated.
4) The orders of the words, digits, and special characters can be arbitrary.
You need to generate a dictionary according to the hint.
1) One of the special character is @.
2) The four-letter word is cyse, but each letter can be upper or lower case.
3) You should be able to find the four digits on my personal website or ECE website. Note that there can be multiple possibilities of the four digits.
[~] => aircrack-ng seven-01.cap -w /home/dhaynes/development/dictgen/out.txt
[00:26:53] 3993012/5406699 keys tested (2511.41 k/s)
Time left: 9 minutes, 22 seconds 73.85%
KEY FOUND! [ CySE2017@GMu) ]
Master Key : 78 BC DE 0B 28 9E DA 47 E7 01 86 C2 83 0E 23 D8
17 45 0E DF 50 39 75 DE 4D 01 AA E9 A7 18 15 F5
Transient Key : 1C 91 9C DE 07 4F CB CB 5C FD 85 BC 7A 30 85 91
C0 71 E6 48 B2 7C E5 30 74 63 FF A5 35 CE 73 73
6C 31 88 A6 5D 79 FC 05 D2 B1 F1 34 58 B8 4C 16
B0 5F 51 C2 1C 75 8D 5E F6 01 C2 F1 BC 5A 2F AA
EAPOL HMAC : 3B A0 60 05 C7 A9 28 59 02 9F 38 E7 14 D5 21 A9
"""
# Future Imports for py2 backwards compat.
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Python std. lib.
import itertools
def main():
"""
Step through the functions and produce results, informing the user along
the way.
"""
# Every upper and lower case combination of 'cyse'
word_one = ['cyse', 'cysE', 'cySe', 'cySE', 'cYse', 'cYsE', 'cYSe', 'cYSE',
'Cyse', 'CysE', 'CySe', 'CySE', 'CYse', 'CYsE', 'CYSe', 'CYSE']
# Every permutation of GMU
word_two = ['gmu', 'gmU', 'gMu', 'gMU', 'Gmu', 'GmU', 'GMu', 'GMU']
# All 4 digit numbers from:
# https://ece.gmu.edu/people/full-time-faculty/kai-zeng
# http://ece.gmu.edu/~kzeng2/
digits = ['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013',
'2014', '2015', '2016', '2017', '3252', '1000', '1200', '5933',
'3100', '4400', '4444', '1569', '1601', '1981']
# Include the '@' character
special_char_one = ['@']
# Every possible single special character
special_char_two = ['~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(',
')', '-', '_', '=', '+']
# The dictionary text file we will write to
with open('out.txt', 'w') as outfile:
# For every product, also print out all permutations
for product in itertools.product(word_one,
word_two,
digits,
special_char_one,
special_char_two):
for permute in itertools.permutations(product, len(product)):
outfile.write(''.join(permute) + '\n')
if __name__ == "__main__":
main()
|
JavaScript | UTF-8 | 2,018 | 4.03125 | 4 | [] | no_license |
// Array of objects holding the 7 questions and answers
quizArray = [
{
question: "Which programming language is the basic backbone of all websites we browse online today?",
answer: "html"
},
{
question: "Which programming language is currently the most commonly used for front-end development?",
answer: "javascript"
},
{
question: "What does DOM stand for?",
answer: "document object model"
},
{
question: "Where can I find all the files that enable a website to function, so long as I have internet access and a URL?",
answer: "server"
},
{
question: "CSS allows programmers to develop the look and feel of a site, but what does it exactly stand for?",
answer: "cascading style sheets"
},
{
question: "How do programmers usually spend the majority of their time?",
answer: "debugging"
},
{
question: "With dedication, persistence, and hardwork, can you become a programming jedi?",
answer: "yes"
} ]
// For loop that pushes the above questions & answers from the array onto the page
for (var i=0; i<quizArray.length; i++) {
document.getElementById("question"+i).innerHTML = quizArray[i].question
}
// Function that checks if the inputted answers are correct or incorrect (& counts the total correct & incorrect)
var numCorrect = 0
var numIncorrect = 0
function checkAnswers() {
// for (every question)
for (var i = 0; i < quizArray.length; i++) {
if (document.getElementById("guess"+i).value.toLowerCase() == quizArray[i].answer) {
// add a classname (to turn it green)
$('#question'+i).addClass('turngreen');
// add it to the total CORRECT count
numCorrect = numCorrect + 1
} else {
// add classname to the question (to turn it red)
$('#question'+i).addClass('turnred');
// add it to the total INCORRECT count
numIncorrect = numIncorrect + 1
}
}
// push the total # correct & incorrect onto the HTML page
document.getElementById('numCor').innerHTML = numCorrect
document.getElementById('numInc').innerHTML = numIncorrect
}
|
Java | UTF-8 | 13,411 | 3.984375 | 4 | [] | no_license | package calculator;
import java.util.ArrayList;
import java.util.Stack;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.FileReader;
/**
* The Calculator class. Takes from a .txt file a mathematical expression consisting of the operators "+", "-", "*", "%", or "/", the unary
* operator "-", any integer, and left and right parenthesis. Evaluates the expression using two methods:
* recursion and stacks.
*
* It evaluates using recursion by first checking if the input is but a number with no binary operators (base case),
* and returns it if it is. it then iterates through the expression, keeping track
* of the last and highest priority binary operator (using PEMDAS), unless it is contained in parenthesis. If the whole expression is
* within parenthesis, then it removes the parenthesis and recursively calls itself using the resulting expression.
* If it was not in parenthesis, it splits the expression into two substrings: The expression before the last binary
* operator and the expression after the binary operator. It then recursively calls itself on each of these two
* substrings and solves the two resulting numbers using the binary operator.
*
* It evaluates using stacks by first converting the expression to postfix notation, then solving the postfix expression.
* it converts to postfix by iterating through the expression, adding any integers it finds to an output
* string and pushing any binary operators onto a stack. If the iterator comes across a binary operator whilst one
* more are already on the stack, it compares it to them. If the current operator is of greater priority than the first operator
* on the stack, the current is pushed onto the stack and the method continues to iterate through the expression.
* if the current is of lesser priority than the first operator on the stack, the stack is popped and added to the
* output array until an operator of lesser priority than the current operator is found on the top of
* the stack. The current operator is then pushed onto the stack and the iteration continues. If the
* iterator comes across a left parenthesis, it always pushes it onto the stack. If it comes across a
* right parenthesis, it pops the stack into the output array until it finds a left parenthesis, then
* continues iteration. Once the iterator reaches the end of the expression, all operators are popped
* and added to the output string, which now consists of the original expression in postfix.
* This output string is then converted to an array and fed into a different method, which solves it.
* It does so by iterating through the array, pushing any integer it finds onto a stack. If the iterator
* comes across an operator, it pops the first two integers off of the stack, solves them using the
* operator, then pushes the result back onto the stack. Once the iterator reaches the end of the array,
* the stack consists of one integer, the answer to the original expression.
*
* @author Laivi Malamut-Salvaggio
* @version 1.0
*
*/
public class Calculator {
private static String fileToUse = "calc_expressions.txt";
public static void main (String args[]){
if(args.length !=0){
fileToUse = args[0];
}
Scanner sc = null;
FileReader fr = null;
while(fr == null){
try{
fr = new FileReader(fileToUse);
}
catch(FileNotFoundException e){
System.out.println("Error! Input file not found. Using default file");
fileToUse = "calc_expressions.txt";
}
}
sc = new Scanner(fr);
String expression = "";
while (sc.hasNextLine()){
expression = sc.nextLine();
expression = expression.replaceAll("\\s","");
if (expression.length()>0 && expression.charAt(0) != '#'){
System.out.println("Using recursion:");
System.out.println(expression + " = " + iterator(expression));
System.out.println("Using stacks and postfix:");
System.out.println(expression + " = " + toPostfix(expression));
System.out.println("");
}
}
sc.close();
}
private static int iterator(String str){
int multdiv = 0; // this will hold the place of the rightmost "*", "/", or "%" operator
int plusminus = 0;// the rightmost "+" or "-" operator
int counter = 0; //counts the number of parenthesis. "(" == +1 ; ")" == -1
boolean isInt = true;
int intChecker = 0;
if (str.charAt(0) == '-'){
intChecker++;
}
while (isInt && intChecker<str.length()){ //checking if str is just one integer
if (isOperator(str, intChecker) != 0){
isInt = false;
}
intChecker++;
}
if(isInt){ // if it is an integer, return it
return Integer.parseInt(str);
}
if (str.charAt(0) == '-' && str.charAt(1) == '('){// if the string is preceded by a negative sign, then a parenthesis
return (-iterator(str.substring(1,str.length())));
}
for (int i = 0; i < str.length(); i++){
if (str.charAt(i) == '('){
counter++;
}
else if (str.charAt(i) == ')'){
counter--;
}
else if (counter == 0){ // there are no parenthesis, since the counter == 0 only outside of parenthesis
if (isOperator(str, i) == 1){
multdiv = i;
}
else if (isOperator(str, i) == 2){
if (i != 0 && isOperator(str, i-1) == 0)// if the last char was a number(ie, this char is not unary)
plusminus = i;
}
}
}
if (multdiv == 0 && plusminus == 0){ //didnt input any operators bc there are parenthesis around whole thing
String result = str.substring(1, str.length() - 1);
return iterator(result);
}
else if( plusminus > 0){ //first checks for plus or minus, which will be recursively called first, so used last
String first = str.substring(0, plusminus);
String last = str.substring(plusminus + 1, str.length());
char operator = str.charAt(plusminus);
if (operator == '+'){
return iterator(first) + iterator(last);
}
else {
return iterator(first) - iterator(last);
}
}
else { //if there was no plus or minus
String first = str.substring(0, multdiv);
String last = str.substring(multdiv + 1, str.length());
char operator = str.charAt(multdiv);
if (operator == '*') {
return iterator(first) * iterator(last);
}
else if(operator == '/') {
try{
return iterator(first) / iterator(last);
}catch(java.lang.ArithmeticException e){
System.out.println("Error! May not divide by zero!");
return 0;
}
}
else {
return iterator(first) % iterator(last);
}
}
}
/**
* checks whether the char at the specified index in the specified string is an operator or an int. If it is an operand, return
* zero. if operator, returns one of three numbers: number 1 if is the multiplication, division, or modulo sign, 2 if it is
* the plus or minus sign, and 3 if it is a left parenthesis.
*
* @param str The string in which the char is contained
* @param i The index of the char
* @return An int corresponding to operator, or zero if operand
*/
private static int isOperator(String str, int i){
int result = 0;
char compare = str.charAt(i);
if ( compare == '*' || compare == '/' || compare == '%'){
result = 1;
}
else if(compare == '+' || compare == '-') {
result = 2;
}
else if( compare == '('){
result = 3;
}
return result;
}
private static int isOperator(String[] str, int i){
int result = 0;
String compare = str[i];
if ( compare.equals("*") || compare.equals("/") || compare.equals("%")){
result = 1;
}
else if(compare.equals("+") || compare.equals("-")) {
result = 2;
}
else if( compare.equals("(")){
result = 3;
}
return result;
}
/**
* evaluates postfix expression contained within an array of strings, using "N" to denote a negative number
*
* @param str The postfix expression
* @return What the postfix expression equals.
*/
private static int evalPostfix(String[] str){
Stack<Integer> stack = new Stack<>();
for (int i = 0; i<str.length; i++){
if (str[i].charAt(0)== 'N'){// it is a negative number, push it
String toPush = str[i].substring(1, str[i].length());
stack.push(-Integer.parseInt(toPush));
}
else if (isOperator(str, i) == 0){ // is an operand, push it
stack.push(Integer.parseInt(str[i]));
}
else{// is an operator
int b = stack.pop();
int a = stack.pop();
int toPush = 0;
switch(str[i]) {
case "*":
toPush += (a*b);
break;
case "/":
try{
toPush += (a/b);
}catch(java.lang.ArithmeticException e){
System.out.println("Error! May not divide by zero!");
return 0;
}
break;
case "%":
toPush += (a%b);
break;
case "+":
toPush += (a+b);
break;
case "-":
toPush += (a-b);
break;
}
stack.push(toPush);
}
}
return stack.pop();
}
/**
* replaces all unary negative signs with "N". Useful to keep track of whether a minus sign is unary or binary
* @param str A string containing a mathematical expression
* @return The same string will all unary minus signs replaced with "N"
*/
private static String replaceN(String str){
for (int i = 0; i<str.length(); i++){
if (str.charAt(i) == '-'){
if (i == 0){ // is the first element
str = "N" + str.substring(1, str.length());
}
else if (isOperator(str, i-1)>0){ // the "-" sign is preceded by an operator or a left parenthesis
str = str.substring(0,i) + "N" + str.substring(i+1, str.length());
//else it is binary
}
}
}
return str;
}
/**
* used in the toPostFix method when pushing operators onto the stack. Priority numbering follows PEMDAS, with the expception
* that an operator on the stack always has greater priority than the same operator not on the stack. Left parenthesis is
* always pushed onto stack, so it has greater priority than all others. It is also always popped from the stack, so it has no
* priority when on the stack.
* @param operator The operator whose priority is to be determined
* @param onStack Whether or not that operator was derived from a stack
* @return A number corresponding to the operator's priority
*/
private static int priority(String operator, boolean onStack){
int result = 0;
if (operator.equals("+") || operator.equals("-")){
result = 10;
if (onStack){
result++;
}
}
else if(operator.equals("*") || operator.equals("/") || operator.equals("%")){
result = 20;
if (onStack){
result ++;
}
}
else{ // is left parenthesis
result = 30;
if (onStack){
result = 0;
}
}
return result;
}
/**
* converts an infix expression contained within a string to a postfix expression contained in an array of strings, using stacks.
* @param str The infix expression to be converted
* @return The postfix expression
*/
private static int toPostfix(String str){
Stack<String> stack = new Stack<>();
ArrayList<String> arr = new ArrayList<String>();
str = replaceN(str);
for (int i = 0; i< str.length(); i++){
if (str.charAt(i) == ')'){// need to pop all operators in stack, because any expression within parenthesis must be solved first
String onto = "";
while(!stack.isEmpty() && !onto.equals("(")){ // pop all until reach a right parenthesis
onto = stack.pop();
if(!onto.equals("(")){
arr.add(onto);
}
}
}
else if (isOperator(str, i) == 0 || str.charAt(i) == 'N'){ // if it is an operand, or "N" denoting a negative operand
int counter = i+1;
while (counter < str.length() && isOperator(str, counter) == 0 && str.charAt(counter) != ')'){ // the next i is still an int
counter++;
}
arr.add(str.substring(i,counter));
i = counter -1;
}
else { // it is an operator
if(stack.isEmpty()){ //nothing to compare it to, push it
stack.push(str.substring(i, i+1));
}
else{
String current = str.substring(i,i+1);
String prev = "";
int Pprev;
int Pcurrent;
boolean pushPrev = true;
do {
pushPrev = true;
prev = stack.pop();
Pprev = priority(prev, true);
Pcurrent = priority(current, false);
if (Pprev > Pcurrent){ //if the priority of the op on the stack is greater than the current, add it to output
arr.add(prev);
pushPrev = false;
}
} while((!(stack.isEmpty()) && Pprev > Pcurrent)); // keep on adding the prev op to output until an op of lesser priority is found
if (pushPrev){ // if the previous was not just added to the output, need to push it back onto the stack
stack.push(prev);
}
stack.push(current);
}
}
}
while (!stack.isEmpty()){ //reached end of iteration, pop everything onto output
arr.add(stack.pop());
}
return evalPostfix(arr.toArray(new String[arr.size()]));
}
}
|
Java | UTF-8 | 704 | 3.046875 | 3 | [] | no_license | public class Main {
public static void main(String[] args) {
//220 284
int sayi1 = 220;
int sayi2 = 284;
int toplam1 = 0;
int toplam2 = 0;
for (int i = 1; i < sayi1; i++) {
if (sayi1 % i == 0) {
toplam1 += i;
}
}
for (int i = 1; i < sayi2; i++) {
if (sayi2 % i == 0) {
toplam2 += i;
}
}
if (sayi1==toplam2 && sayi2==toplam1){
System.out.println("sayilariniz arkadas sayidir");
}
else {
System.out.println("maalesef sayilariniz arkadas değildir.");
}
}
}
|
Python | UTF-8 | 2,127 | 3 | 3 | [] | no_license | import unittest
from src.data_preprocessing.steps.row_bc_col import RemoveRowBcColStep
import pandas as pd
class RRCBRStepTests(unittest.TestCase):
def test__no_col__throws_error(self):
self.assertRaises(Exception, RemoveRowBcColStep(column_name=None, bad_values="some bad values"))
def test__no_bad_values__throws_error(self):
self.assertRaises(Exception, RemoveRowBcColStep(column_name="some column", bad_values=None))
def test__remove_rows_based_on_col__multiple_values__is_removed(self):
data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18], 'Type':[1, 0, 2, 1]}
expected_data = {'Name':['krish', 'jack'], 'Age':[19, 18], 'Type':[2, 1]}
expected_df = pd.DataFrame(expected_data)
original_df = pd.DataFrame(data)
step = RemoveRowBcColStep(column_name='Name', bad_values=['nick', 'Tom'])
returned_df = step.run_step(original_df)
self.assertTrue(returned_df.equals(expected_df))
def test__remove_rows_based_on_col_val__value_present__is_removed(self):
data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18], 'Type':[1, 0, 2, 1]}
expected_data = {'Name':['Tom', 'krish', 'jack'], 'Age':[20, 19, 18], 'Type':[1, 2, 1]}
expected_df = pd.DataFrame(expected_data)
original_df = pd.DataFrame(data)
step = RemoveRowBcColStep(column_name='Name', bad_values=['nick'])
returned_df = step.run_step(original_df)
self.assertTrue(returned_df.equals(expected_df))
def test__remove_rows_based_on_col_val__value_not_present__no_change(self):
data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18], 'Type':[1, 0, 2, 1]}
original_df = pd.DataFrame(data)
step = RemoveRowBcColStep(column_name='Name', bad_values='Farley')
returned_df = step.run_step(original_df)
self.assertTrue(returned_df.equals(original_df))
if __name__ == '__main__':
import xmlrunner
unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports')) |
JavaScript | UTF-8 | 3,413 | 2.75 | 3 | [
"MIT"
] | permissive | import { html, render } from "https://unpkg.com/lit-html?module";
/*global flyd, P, S, PS*/
var conditions = {
initialState: {
conditions: {
precipitations: false,
sky: "Sunny"
}
},
actions: function(update) {
return {
togglePrecipitations: function(value) {
update({ conditions: PS({ precipitations: value }) });
},
changeSky: function(value) {
update({ conditions: PS({ sky: value }) });
}
};
}
};
var skyOption = function({ state, actions, value, label }) {
return html`<label>
<input type="radio" id=${value} name="sky"
value=${value} .checked=${state.conditions.sky === value}
@change=${evt => actions.changeSky(evt.target.value)}/>
${label}
</label>`;
};
var Conditions = function(state, actions) {
return html`<div>
<label>
<input
type="checkbox"
.checked=${state.conditions.precipitations}
@change=${evt =>
actions.togglePrecipitations(evt.target.checked)
}/>
Precipitations
</label>
<div>
${skyOption({ state, actions, value: "SUNNY",
label: "Sunny"})}
${skyOption({ state, actions, value: "CLOUDY",
label: "Cloudy"})}
${skyOption({ state, actions, value: "MIX",
label: "Mix of sun/clouds"})}
</div>
</div>`;
};
var convert = function(value, to) {
return Math.round(
(to === "C") ? ((value - 32) / 9 * 5) : (value * 9 / 5 + 32)
);
};
var temperature = {
initialState: function(label) {
return {
label,
value: 22,
units: "C"
};
},
actions: function(update) {
return {
increment: function(id, amount) {
update({ [id]: PS({ value: S(x => x + amount) }) });
},
changeUnits: function(id) {
update({
[id]: S(state => {
var value = state.value;
var newUnits = state.units === "C" ? "F" : "C";
var newValue = convert(value, newUnits);
state.value = newValue;
state.units = newUnits;
return state;
})
});
}
};
}
};
var Temperature = function(state, id, actions) {
return html`<div>
${state[id].label} Temperature:
${state[id].value} ° ${state[id].units}
<div>
<button
@click=${() => actions.increment(id, 1)}>
Increment
</button>
<button
@click=${() => actions.increment(id,-1)}>
Decrement
</button>
</div>
<div>
<button
@click=${() => actions.changeUnits(id)}>
Change Units
</button>
</div>
</div>`;
};
var app = {
initialState: Object.assign({},
conditions.initialState,
{ air: temperature.initialState("Air") },
{ water: temperature.initialState("Water") }
),
actions: function(update) {
return Object.assign({},
conditions.actions(update),
temperature.actions(update)
);
}
};
var App = function(state, actions) {
return html`<div>
${Conditions(state, actions)}
${Temperature(state, "air", actions)}
${Temperature(state, "water", actions)}
<pre>${JSON.stringify(state, null, 4)}</pre>
</div>`;
};
var update = flyd.stream();
var states = flyd.scan(P, app.initialState, update);
var actions = app.actions(update);
var element = document.getElementById("app");
states.map(state => render(App(state, actions), element));
|
Java | UTF-8 | 1,621 | 2.59375 | 3 | [] | no_license | package com.jiuge;
import com.jiuge.storage.Storage;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;
/**
* @program:Server
* @author:Nine_odes
* @description:
* @create:2020-10-15 17:04
**/
public class UDPServer {
private static Thread worker;
public static void startWork(){
//1.按照预演阶段的成功,完成对数据的采集
//2.创建一个线程完成该工作
worker = new Thread(){
public void run(){
setName("收集上报的线程");
UDPServer server = new UDPServer();
server.start();
}
};
worker.start();
}
public void start(){
try(DatagramSocket socket = new DatagramSocket(8000)){
byte[] buffer = new byte[1024];
while(true){
Arrays.fill(buffer,(byte)0);
DatagramPacket receivePacket = new DatagramPacket(buffer,0,buffer.length);
socket.receive(receivePacket);
String message = new String(buffer,0,receivePacket.getLength(),"ASCII");
String[] group = message.split("\\$");
String hostname = group[0];
System.out.println("收到来自" + hostname + "上报的数据");
long timestamp = Long.parseLong(group[1]);
double percent = Double.parseDouble(group[2]);
Storage.put(hostname,timestamp,percent);
}
}catch (IOException e){
e.printStackTrace();
}
}
}
|
Python | UTF-8 | 1,228 | 3.0625 | 3 | [
"MIT"
] | permissive | import pytest
from inference_logic.data_structures import (
PrologList,
PrologListNull,
UnificationError,
construct,
)
def test__repr__():
assert repr(construct([1, [2, 3], 4])) == "[1, [2, 3], 4]"
def test__eq__fail():
with pytest.raises(UnificationError) as error:
PrologListNull() == 0
assert str(error.value) == "0 must be a PrologListNull"
with pytest.raises(UnificationError) as error:
PrologList(1, 2) == 0
assert str(error.value) == "0 must be a PrologList"
def test_list__repr__():
assert repr(construct([1, [2, 3], 4])) == "[1, [2, 3], 4]"
def test_list__len__():
assert len(construct([1, [2, 3], 4])) == 3
def test_list__add__():
a = construct([1, 2])
b = construct([3, 4])
assert a + b == construct([1, 2, 3, 4])
def test_list__add__fail():
a = construct([1, 2])
with pytest.raises(UnificationError) as error:
a + 3
assert str(error.value) == "3 must be a PrologList"
def test_list_in():
a = construct([1, 2])
assert 1 in a
assert 3 not in a
def test_list__iter__():
a = construct([1, 2])
assert list(a) == [1, 2]
def test_list_null_in():
a = construct([])
assert 1 not in a
|
C# | UTF-8 | 6,180 | 2.515625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MISA.Core.Entities;
using MISA.Core.Interfaces;
using MISA.Core.Interfaces.Services;
namespace MISA.EMIS.API.Controllers
{
[ApiController]
[Route("api/v1/Employees")]
public class EmployeeController : Controller
{
#region Field
IEmployeeRepository _employeeRepository;
IEmployeeService _employeeService;
#endregion
#region Constructure
public EmployeeController(IEmployeeService employeeService, IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
_employeeService = employeeService;
}
#endregion
#region Method
#region Get
/// <summary>
/// Lấy toàn bộ dữ liệu
/// </summary>
/// <returns>Lấy toàn bộ dữ liệu</returns>
/// CreateBy: NTDIEM(15/09/2021)
[HttpGet]
public IActionResult GetAll()
{
try
{
var employees = _employeeRepository.GetAll();
return Ok(employees);
}
catch (Exception e)
{
return StatusCode(500, e.Message);
}
}
/// <summary>
/// Lấy dữ liệu theo id
/// </summary>
/// <param name="id">employeeId</param>
/// <returns>Dữ liệu lấy được theo id nhân viên</returns>
/// CreateBy:NTDIEM(15/09/2021)
[HttpGet("{id}")]
public IActionResult GetId(Guid id)
{
try
{
var employee = _employeeRepository.GetById(id);
return employee != null ? Ok(employee) : NoContent();
}
catch (Exception e)
{
return StatusCode(500, _employeeService.ErrorException(e));
}
}
/// <summary>
/// Lấy mã nhân viên mới
/// </summary>
/// <returns>Mã nhân viên mới</returns>
/// CreateBy: NTDIEM(20/09/2021)
[HttpGet("NewEmployeeCode")]
public IActionResult GetNewEmployeeCode()
{
try
{
var newEmployeeCode = _employeeRepository.GetNewCode();
return newEmployeeCode != null ? Ok(newEmployeeCode) : NoContent();
}
catch (Exception e)
{
return StatusCode(500, _employeeService.ErrorException(e));
}
}
/// <summary>
/// Lọc nhân viên
/// </summary>
/// <param name="DepartmentId">id tổ bộ môn</param>
/// <param name="employeeFilter"></param>
/// <returns>Dữ liệu nhân viên sau khi lọc</returns>
/// CreateBy: NTDIEM(20/09/2021)
[HttpGet("EmployeeFilter")]
public IActionResult GetEmployeeFilter(Guid DepartmentId, string employeeFilter)
{
try
{
var res = _employeeRepository.GetEmployeeFilter(DepartmentId, employeeFilter);
return res != null ? Ok(res) : NoContent();
}
catch(Exception e)
{
return StatusCode(500, _employeeService.ErrorException(e));
}
}
#endregion
#region POST
/// <summary>
/// Thêm dữ liệu
/// </summary>
/// <param name="employee">Nhân viên</param>
/// <returns>trạng thái thêm mới</returns>
/// CreateBy:NTDIEM(15/09/2021)
[HttpPost]
public IActionResult Post([FromBody] Employee employee)
{
try
{
//Validate dữ liệu
var employeeResult = new ServiceResult();
employeeResult = _employeeService.Add(employee);
//Kiểm tra dữ liệu có bị bỏ trống không
return employeeResult.Success ? StatusCode(201, employeeResult) : StatusCode(200, employeeResult);
}
catch (Exception e)
{
return StatusCode(500, _employeeService.ErrorException(e));
}
}
#endregion
#region PUT
/// <summary>
/// Hàm sửa dữ liệu
/// </summary>
/// <param name="id">ID nhân viên</param>
/// <param name="employee">thông tin nhân viên</param>
/// <returns>Trạng thái sửa thông tin nhân viên</returns>
/// CreateBy:NTDIEM(15/09/2021)
[HttpPut("{id}")]
public IActionResult Put(Guid id, [FromBody] Employee employee)
{
try
{
//Validate dữ liệu
var employeeResult = new ServiceResult();
employeeResult = _employeeService.Put(employee, id);
return employeeResult.Success ? StatusCode(201, employeeResult) : StatusCode(200, employeeResult);
}
catch (Exception e)
{
return StatusCode(500, _employeeService.ErrorException(e));
}
}
#endregion
#region DELETE
/// <summary>
/// Xóa nhân viên theo id
/// </summary>
/// <param name="id">employeeId</param>
/// <param name="employee">Thông tin nhân viên</param>
/// <returns>Trạng thái xóa dữ liệu</returns>
/// CreateBy:NTDIEM(15/09/2021)
[HttpDelete("{id}")]
public IActionResult Delete(Guid id)
{
try
{
//Validate dữ liệu
var employeeResult = new ServiceResult();
employeeResult = _employeeService.Delete(id);
return employeeResult.Success ? StatusCode(200, employeeResult) : StatusCode(204, employeeResult);
}
catch (Exception e)
{
return StatusCode(500, _employeeService.ErrorException(e));
}
}
#endregion
#endregion
}
}
|
Java | UTF-8 | 1,927 | 2.03125 | 2 | [] | no_license | package testCases;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
import wdMethods.ProjectMethods;
public class DeleteLeads extends ProjectMethods{
//@Test(dependsOnMethods="testCases.CreateLeadsOOPS.createLead")
//@Test(groups = "regression",dependsOnGroups="sanity")
@Test(dataProvider="deleteLead")
public void deleteLead(int phone) throws InterruptedException
{
WebElement lead = locateElement("link", "Leads");
click(lead);
WebElement findLead = locateElement("link", "Find Leads");
click(findLead);
WebElement phoneTab = locateElement("xpath", "//span[text()='Phone']");
click(phoneTab);
WebElement phoneNum = locateElement("name", "phoneNumber");
type(phoneNum, phone+"");
WebElement findLeadsButton = locateElement("xpath", "//button[text()='Find Leads']");
click(findLeadsButton);
WebElement leadId = locateElement("xpath", "((//div[@class='x-grid3-cell-inner x-grid3-col-formatedPrimaryPhone'])[1])/preceding::td[14]");
String capturedLeadId = getText(leadId);
System.out.println(capturedLeadId);
Thread.sleep(3000);
//WebElement leadId1 = locateElement("xpath", "((//div[@class='x-grid3-cell-inner x-grid3-col-formatedPrimaryPhone'])[1])/preceding::td[14]");
WebElement leadId1 = locateElement("link",capturedLeadId);
click(leadId1);
WebElement deleteButton = locateElement("link", "Delete");
click(deleteButton);
WebElement findLead1 = locateElement("link", "Find Leads");
click(findLead1);
WebElement enterLeadId = locateElement("name", "id");
type(enterLeadId, capturedLeadId);
WebElement findLeadButton = locateElement("xpath", "//button[text()='Find Leads']");
click(findLeadButton);
Thread.sleep(3000);
WebElement errMsg = locateElement("xpath", "//div[@class='x-paging-info']");
verifyPartialText(errMsg, "No records");
closeBrowser();
}
}
|
Java | UTF-8 | 803 | 3.65625 | 4 | [] | no_license | package com.radostin.intro.hangman;
import java.util.Random;
/**
* Class which generates random word for hangman game. It contains array with
* words.
*
* @author Radostin Ivanov
*
*/
public class RandomWord {
private static String[] words = { "eggs", "apple", "banana", "cheese", "meat", "cereals", "noodles", "pie", "salad",
"sandwich", "sauce" };
private static final int minLength = 0;
private static Random rand = new Random();
/**
* Generates random number from 0 to array length-1. Then we use that number as
* a random index.
*
* @return word from the array with the specific index (random generated).
*/
public static String generate() {
int index = rand.nextInt(((words.length - 1) - minLength) + 1) + minLength;
return words[index];
}
}
|
Ruby | UTF-8 | 334 | 2.890625 | 3 | [] | no_license | lines = ARGF.read.split("\n")
num = lines[0].to_i
pyramid = []
def build_first_line(number)
str = []
number.times do |i|
str.push("#{i+1}")
end
return str.join + str.slice(0,str.length-1).reverse.join
end
num.times do |i|
pyramid.push(build_first_line(i+1))
end
puts pyramid + pyramid.slice(0,pyramid.length-1).reverse |
Python | UTF-8 | 18,827 | 2.578125 | 3 | [] | no_license | import re
from stdlib import *
def lex(fc):
lexlists = []
fc = fc.split("\n")
for fcl in fc:
lexlist = []
tok = ""
state = "undefined"
cache = ""
fcl = list(fcl)
fcl.append("<EOL>")
i = -1
while i < len(fcl) - 1:
i+=1
char = fcl[i]
tok += char
if char == "<EOL>":
if state == "string":
print("Parser error")
return
elif state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
elif state == "function_name":
lexlist += [Token("FUNCTION_CALL", cache)]
cache = ""
state = "undefined"
elif tok == "\"" and state == "undefined":
state = "string"
tok = ""
elif tok == "\"" and fcl[i-1] != "\\" and state == "string":
cache = cache.replace("\\n", "\n")
cache = cache.replace("\\r", "\r")
cache = cache.replace("\\t", "\t")
cache = cache.replace("\\\\", "\\")
lexlist += [Token("STRING", cache)]
cache = ""
state = "undefined"
tok = ""
elif state == "string":
if tok == "\"" and fcl[i-1] == "\\":
cache = cache[:-1]
cache += tok
tok = ""
elif tok == "#":
break
elif tok == "<" and fcl[i+1] == "<" and state == "undefined":
state = "cast"
cache = ""
tok = ""
i+=1
elif tok == ">" and fcl[i+1] == ">" and state == "cast":
state = "undefined"
lexlist += [Token("CAST", cache)]
cache = ""
tok = ""
i+=1
elif state == "cast":
cache += tok
tok = ""
elif tok == "[" and state == "undefined":
state = "index"
cache = ""
tok = ""
elif tok == "]" and state == "index":
state = "undefined"
lexlist += [Token("INDEX", cache)]
cache = ""
tok = ""
elif state == "index":
cache += tok
tok = ""
elif tok == "|" and state == "undefined":
state = "stream"
cache = ""
tok = ""
elif tok == "|" and state == "stream":
state = "undefined"
lexlist += [Token("STREAM", cache)]
cache = ""
tok = ""
elif state == "stream":
cache += tok
tok = ""
elif tok == "$" and state == "undefined":
state = "variable_name"
cache += tok
tok = ""
elif tok == "@" and state == "undefined":
state = "function_name"
cache += tok
tok = ""
elif tok == "&" and state == "undefined":
state = "struct_name"
cache += tok
tok = ""
elif state == "variable_name":
if (len(cache) == 1 and re.match("[a-zA-Z_]", tok)) or (len(cache) > 1 and re.match("[a-zA-Z0-9_]", tok)):
cache += tok
else:
lexlist += [Token("VARIABLE", cache)]
state = "undefined"
cache = ""
i-=1
tok = ""
continue
tok = ""
elif state == "function_name":
if (len(cache) == 1 and re.match("[a-zA-Z_]", tok)) or (len(cache) > 1 and re.match("[a-zA-Z0-9_]", tok)):
cache += tok
else:
lexlist += [Token("FUNCTION_CALL", cache)]
state = "undefined"
cache = ""
i-=1
tok = ""
continue
tok = ""
elif state == "struct_name":
if (len(cache) == 1 and re.match("[a-zA-Z_]", tok)) or (len(cache) > 1 and re.match("[a-zA-Z0-9_]", tok)):
cache += tok
else:
lexlist += [Token("STRUCT", cache)]
state = "undefined"
cache = ""
i-=1
tok = ""
continue
tok = ""
elif tok == "=" and fcl[i+1] == "=":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("EQUALITY_CHECK_SIGN")]
tok = ""
cache = ""
i+=1
elif tok == "!" and fcl[i+1] == "=":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("INEQUALITY_CHECK_SIGN")]
tok = ""
cache = ""
i+=1
elif tok == ":" and fcl[i+1] == ":":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("STRUCT_SUBITEM_SIGN")]
tok = ""
cache = ""
i+=1
elif tok == "=" and state == "undefined":
lexlist += [Token("EQUAL_SIGN")]
tok = ""
cache = ""
elif tok in ["true", "false"]:
lexlist += [Token("BOOLEAN", tok)]
tok = ""
elif tok == "say":
lexlist += [Token("OUTPUT_STMT")]
tok = ""
elif tok == "listen":
lexlist += [Token("INPUT_STMT")]
tok = ""
elif tok == "fwrite":
lexlist += [Token("FILE_WRITE_STMT")]
tok = ""
elif tok == "if":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("IF_START_STMT")]
tok = ""
elif tok == "then":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("THEN_STMT")]
tok = ""
elif tok == "sub":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("SUB_START_STMT")]
tok = ""
elif tok == "endsub":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("SUB_STOP_STMT")]
tok = ""
elif tok == "endif":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("IF_STOP_STMT")]
tok = ""
elif tok == "for":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("FOR_START_STMT")]
tok = ""
elif tok == "times":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("FOR_TIMES_STMT")]
tok = ""
elif tok == "endfor":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("FOR_STOP_STMT")]
tok = ""
elif tok == "struct":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("STRUCT_START_STMT")]
tok = ""
elif tok == "with":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("STRUCT_WITH_STMT")]
tok = ""
elif tok == "endstruct":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("STRUCT_STOP_STMT")]
tok = ""
elif tok == "use":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("USE_STMT")]
tok = ""
elif tok in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
cache += tok
if state == "undefined":
state = "expression"
tok = ""
elif tok == "." and state == "expression":
cache += tok
tok = ""
state = "concrete"
elif tok == "+":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("PLUS_SIGN"))
tok = ""
elif tok == "-":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("MINUS_SIGN"))
tok = ""
elif tok == "*":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("TIMES_SIGN"))
tok = ""
elif tok == "/":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("BY_SIGN"))
tok = ""
elif tok == "(":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("BRACK_START_SIGN"))
tok = ""
elif tok == ")":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("BRACK_STOP_SIGN"))
tok = ""
elif tok == "<":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("SMALLER_THAN_SIGN"))
tok = ""
elif tok == ">":
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist.append(Token("GREATER_THAN_SIGN"))
tok = ""
elif tok == " " or tok == "\t":
tok = ""
if state == "variable_name":
lexlist += [Token("VARIABLE", cache)]
if state == "string":
lexlist += [Token("STRING", cache)]
if state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
state = "undefined"
cache = ""
elif tok == "null":
if state == "string":
print("Parser error")
return
elif state == "expression":
lexlist.append(Token("NUMBER", cache))
cache = ""
state = "undefined"
elif state == "concrete":
lexlist.append(ConcreteWrapper.froms(cache))
cache = ""
state = "undefined"
lexlist += [Token("NULL", None)]
elif tok == ";":
if state == "variable_name":
lexlist += [Token("VARIABLE", cache)]
lexlists.append(lexlist)
lexlist=[]
tok = ""
if state == "variable_name":
lexlist += [Token("VARIABLE", cache)]
lexlists.append(lexlist)
return lexlists |
Markdown | UTF-8 | 585 | 3.125 | 3 | [] | no_license | # speech_say
## comment
Causes text to be spoken using a given voice.
Both the text parameter and the voice parameter are required.
Usually, the voice is obtained using "speechGetVoicesByLanguage", like this:
```kalzit
$voice = first: speechGetVoicesByLanguage: "en".
"This will be said" speechSay voice.
```
If you want to speak text that the user wrote, consider these two options:
1. Ask for the preferred language. This could be done using something like "uiPicker".
2. Assume that the user writes something in the system language and obtain that using "getSimpleUserLanguage". |
Swift | UTF-8 | 2,595 | 3.25 | 3 | [] | no_license |
//
// APIManager.swift
// AssignmentPeople
//
// Created by Palak jain on 18/05/20.
// Copyright © 2020 Palak jain. All rights reserved.
//
import Foundation
import UIKit
class APIManager {
static let instance = APIManager()
enum RequestMethod {
case get
}
//MARK: API calling
func makeGetCall(WSUrl:String,WSCompletionBlock:@escaping (_ data:AnyObject?,_ error:NSError?) -> ()){
let newurl = WSUrl
guard let url = URL(string: newurl) else {
print("Error")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error when calling GET request")
print(error!)
WSCompletionBlock(nil,error as NSError?)
return
}
guard let responseData = data else {
print("Error: did not receive data")
WSCompletionBlock(data as AnyObject?,nil)
return
}
let strISOLatin = String(data: responseData, encoding: .isoLatin1)
let dataUTF8 = strISOLatin?.data(using: .utf8)
var dict: Any? = nil
do {
if let dataUTF8 = dataUTF8 {
dict = try JSONSerialization.jsonObject(with: dataUTF8, options: [])
}
} catch {
print("error trying to convert data to JSON")
return
}
if dict != nil {
if let dict = dict {
WSCompletionBlock(dict as AnyObject,nil)
}
} else {
if let error = error {
print("Error: \(error)")
}
}
}
task.resume()
}
//MARK: This function will download the image from the url.
func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleToFill, img: UIImageView) {
img.contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
if let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
{
DispatchQueue.main.async() {
img.image = image
}
}
else {
DispatchQueue.main.async() {
img.image = UIImage(named: Constants.ImageName.placeholder) }
}
}.resume()
}
}
|
SQL | UTF-8 | 238 | 2.6875 | 3 | [] | no_license | use Pecuniaus;
drop procedure if exists avz_gen_spRetrieveUserTypes;
delimiter $$
Create procedure avz_gen_spRetrieveUserTypes()
begin
select usr.ID as keyId, usr.UserName as description
from tb_users usr Order By usr.UserName asc;
end;
|
C | UTF-8 | 3,751 | 2.53125 | 3 | [] | no_license | #include "csp_gpio.h"
#include "csp_tm4c.h"
#include "tm4c123gh6pm.h"
//initlize each pin
static uint8_t Csp_Gpio_Port(csp_gpio_pinout_t);
static uint8_t Csp_Gpio_Port_Pin(csp_gpio_pinout_t);
void Csp_Gpio_Init(csp_gpio_dev_instance_t* gpio_inst, csp_gpio_dev_config_t gpio_config)
{
uint8_t port;
uint8_t pin;
gpio_inst->gpio_name = gpio_config.name;
gpio_inst->gpio_pin = gpio_config.pin;
gpio_inst->gpio_dir = gpio_config.dir;
gpio_inst->port = Csp_Gpio_Port(gpio_config.pin);
gpio_inst->portpin = Csp_Gpio_Port_Pin(gpio_config.pin);
port = gpio_inst->port;
pin = gpio_inst->portpin;
//Enable Clock to the port by setting the appropriate bits in RCGCGPIO
SYSCTL_RCGCGPIO_R |= (1 << port); //Enable Clock for PORT
*PTR_PORT_LOCK[port] = GPIO_LOCK_KEY; //unlock port
*PTR_PORT_CR[port] |= (1 << pin); //unlock pin
//Enable GPIO pin as digital IO in GPIODEN
*PTR_PORT_DEN[port] |= (1 <<pin);
*PTR_PORT_AFSEL[port] &= ~(1 << pin); //not alternative function, GPIO function
switch(gpio_config.dir)
{
case CSP_GPIO_PIN_OUTPUT_NORMAL:
*PTR_PORT_DIR[port] |= (1 <<pin); //output
*PTR_PORT_ODR[port] &= ~(1<< pin); //clear open drain
*PTR_PORT_DR2R[port] &= ~(1 << pin); //clear 2 mA
*PTR_PORT_DR4R[port] &= ~(1 << pin); //clear 4 mA
*PTR_PORT_DR8R[port] &= ~(1 << pin); //clear 8 mA
*PTR_PORT_DATA[port] &= ~(1 << pin); //clear output;
break;
case CSP_GPIO_PIN_OUTPUT_OPENDR:
*PTR_PORT_DIR[port] |= (1 <<pin); //output
*PTR_PORT_ODR[port] |= (1<< pin); //set as open drain
*PTR_PORT_DATA[port] &= ~(1 << pin); //clear output;
break;
case CSP_GPIO_PIN_INPUT_NORMAL:
*PTR_PORT_DIR[port] &= ~(1 <<pin); //set as input
*PTR_PORT_PUR[port] &= ~(1 <<pin); //disable pullup
*PTR_PORT_PDR[port] &= ~(1 <<pin); //disable pulldown
break;
case CSP_GPIO_PIN_INPUT_PULLUP:
*PTR_PORT_DIR[port] &= ~(1 <<pin); //set as input
*PTR_PORT_PUR[port] |= (1 <<pin); //enable pullup
*PTR_PORT_PDR[port] &= ~(1 <<pin); //disable pulldown
break;
case CSP_GPIO_PIN_INPUT_PULLDN:
*PTR_PORT_DIR[port] &= ~(1 <<pin); //set as input
*PTR_PORT_PUR[port] &= ~(1 <<pin); //disable pullup
*PTR_PORT_PDR[port] |= (1 <<pin); //enable pullup
break;
}
*PTR_PORT_LOCK[port] = 0;
}
csp_gpio_pin_state_t Csp_Gpio_Read(csp_gpio_dev_instance_t* gpio_inst)
{
uint8_t port;
uint8_t pin;
port = gpio_inst->port;
pin = gpio_inst->portpin;
uint8_t state;
state = *PTR_PORT_DATA[port] & (1 << pin);
if (state == (1 << pin))
{
return (CSP_GPIO_STATE_HIGH);
}
else
{
return (CSP_GPIO_STATE_LOW);
}
}
void Csp_Gpio_Write(csp_gpio_dev_instance_t* gpio_inst, csp_gpio_pin_state_t gpio_out)
{
uint8_t port;
uint8_t pin;
port = gpio_inst->port;
pin = gpio_inst->portpin;
if (gpio_out == CSP_GPIO_STATE_HIGH)
{
*PTR_PORT_DATA[port] |= (1 << pin);
}
else if (gpio_out == CSP_GPIO_STATE_LOW)
{
*PTR_PORT_DATA[port] &= ~(1 << pin);
}
}
static uint8_t Csp_Gpio_Port(csp_gpio_pinout_t portpin)
{
uint8_t port;
port = (uint8_t)portpin;
port = ((port & 0xF0) >> 4) - 1;
return(port);
}
static uint8_t Csp_Gpio_Port_Pin(csp_gpio_pinout_t portpin)
{
uint8_t pin;
pin = (uint8_t)portpin;
pin = (pin & 0x0F) - 1;
return(pin);
}
|
Java | UTF-8 | 1,013 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package com.lepeng.fastjson.serializer;
import java.lang.reflect.Type;
import java.math.BigDecimal;
public class BigDecimalSerializer
implements ObjectSerializer
{
public static final BigDecimalSerializer instance = new BigDecimalSerializer();
public BigDecimalSerializer() {}
public void write(JSONSerializer paramJSONSerializer, Object paramObject1, Object paramObject2, Type paramType)
{
paramJSONSerializer = paramJSONSerializer.getWriter();
if (paramObject1 == null) {
if (paramJSONSerializer.isEnabled(SerializerFeature.WriteNullNumberAsZero)) {
paramJSONSerializer.write('0');
}
}
do
{
return;
paramJSONSerializer.writeNull();
return;
paramObject1 = (BigDecimal)paramObject1;
paramJSONSerializer.write(paramObject1.toString());
} while ((!paramJSONSerializer.isEnabled(SerializerFeature.WriteClassName)) || (paramType == BigDecimal.class) || (paramObject1.scale() != 0));
paramJSONSerializer.write('.');
}
}
|
Java | UTF-8 | 104 | 1.570313 | 2 | [] | no_license | package com.iscob.iscob.entities.enums;
public enum NewMemberType {
NUEVO_CONVERSO, MENOS_ACTIVO
}
|
C# | UTF-8 | 2,617 | 3.40625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Pictionary.Model
{
public class Comando : ICommand
{
private readonly Action execute;
private readonly Func<bool> canExecute;
/// <summary>
/// Se "levanta" cuando RaiseCanExecuteChanged es llamado.
/// </summary>
public event EventHandler CanExecuteChanged;
/// <summary>
/// Crea un comando que puede ser ejecutado siempre
/// </summary>
/// <param name="execute"></param>
public Comando(Action execute)
{
this.execute = execute;
//CanExecuteChanged += (ICommand, EventArgs) => Console.WriteLine("yo");
}
/// <summary>
/// Crea un nuevo comando.
/// </summary>
/// <param name="execute">La acción a ejecutar.</param>
/// <param name="canExecute">La lógica del estado de la ejecución (si puede ejecutar o no)</param>
public Comando(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
this.execute = execute;
this.canExecute = canExecute;
}
/// <summary>
/// Determina si la acción puede ejecutar o no
/// </summary>
/// <param name="parameter">Los datos usados por el comando, si no necesita datos, puede ser null.</param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return canExecute == null ? true : canExecute(); //Si es null, devuelve true, si no, consulta la función definida en "canExecute".
}
/// <summary>
/// Ejecuta la acción
/// </summary>
/// <param name="parameter">Los datos usados por el comando, si no necesita datos, puede ser null.</param>
public void Execute(object parameter)
{
execute();
}
//Método usado para "levantar" el evento CanExecuteChanged para indicar que el valor de retorno de CanExecute ha cambiado. <- Esto no lo entiendo muy bien
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
handler(this, EventArgs.Empty);
//Otra forma de realizar lo mismo:
//CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}
|
Java | UTF-8 | 1,134 | 2.390625 | 2 | [] | no_license | package pageObjects;
import common.SysUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By btnLogin = By.xpath("//button[@type='submit']");
By txtUser = By.xpath("//*[@placeholder='Email']");
By txtPass = By.xpath("//*[@placeholder='Password']");
By lblLogin = By.className("m-b-3");
By lblMessageError = By.xpath("//span[contains(text(),'Incorrect email or password')]");
public LoginPage(WebDriver driver){ this.driver = driver; }
public void waitLoginPageLoad(){
SysUtil util = new SysUtil();
util.waitElement(driver, lblLogin);
}
public void setUser(String user){
driver.findElement(txtUser).sendKeys(user);
}
public void setPass(String pass){
driver.findElement(txtPass).sendKeys(pass);
}
public void clickLogin(){
driver.findElement(btnLogin).click();
}
public String getErrorMessage(){
SysUtil util = new SysUtil();
util.waitElement(driver, lblMessageError);
return driver.findElement(lblMessageError).getText();
}
}
|
TypeScript | UTF-8 | 1,245 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | import {Injectable} from '@angular/core';
import {LogMessage, Type} from '../../utils/logMessage';
import { DatePipe } from '@angular/common';
import { LogUtils } from 'src/app/utils/LogUtils';
export interface LogMessageListener{
messageAdded(logMessage:LogMessage):void;
}
@Injectable({
providedIn: 'root'
})
export class MessageService {
dateFormat:string = 'y-MM-dd_HH:mm:ss';
messages: LogMessage[] = [];
listeners:LogMessageListener[] = [];
constructor(private datePipe:DatePipe,
private logger:LogUtils) {}
public addListener(newListener:LogMessageListener){
this.listeners.push(newListener);
}
informListeners(message:LogMessage):void{
this.listeners.forEach(lst => lst.messageAdded(message));
}
// Did not manage to pass the arguments in the call dynamically, hence the below lengthy iterated code lines !!
addMessage(msg:LogMessage){
this.messages.push(msg);
this.logger.logMessage(msg);
this.informListeners(msg);
}
info(text: string) {
this.addMessage(new LogMessage(text, Type.Info));
}
error(text: string) {
this.addMessage(new LogMessage(text, Type.Error));
}
warning(text: string) {
this.addMessage(new LogMessage(text, Type.Warning));
}
}
|
Markdown | UTF-8 | 3,088 | 3.25 | 3 | [] | no_license | ---
title: "[Daily Coding Problem] #12"
slug: daily-code-12
date: 2020-04-08
categories:
- Daily Code Problems
- Java
tags:
- daily code
- interview
- algorithms
- java
keywords:
- daily
- coding
- java
- problems
- algorithms
- tutorial
- intelij
autoThumbnailImage: true
thumbnailImagePosition: "left"
thumbnailImage: https://res.cloudinary.com/deop9ytsv/image/upload/v1585475653/daily-code.png
coverImage: https://res.cloudinary.com/deop9ytsv/image/upload/v1541273502/Black_flag.svg.png
metaAlignment: center
---
Chào các bạn.
Câu hỏi hôm nay như sau:
# Problem
>
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
>
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".__
# Method
Ý tưởng của bài này là:
- Bắt đầu một chuỗi substring đầu tiên là ký tự đầu, sau đó thêm dần các ký tự tiếp của chuỗi sao cho số lượng ký tự unique không vượt quá k.
- Nếu đến vị trí chuỗi substring có nhiều hơn k ký tự unique thì chúng ta ghi nhận kết quả độ dài chuỗi trước đó, sau đó kiểm tra chuỗi substring mới bằng cách loại bỏ dần các ký tự bên trái.
- Cuối cùng là so sánh các độ dài ghi nhận được và in kết quả lớn nhất.
# Code Implementation
```
private static int lengthOfLongestSubstring(String s, int k) {
Map<Character,Integer> map = new HashMap<>();
int begin = 0, end = 0;
// The number of distinct character.
int counter = 0;
// The length of longest substring.
int maxLen = 0;
while (end < s.length()) {
char cEnd = s.charAt(end);
map.put(cEnd, map.getOrDefault(cEnd, 0) + 1);
if (map.get(cEnd) == 1) {
counter++; //new char
}
end++;
// counter > k means that
// there are more than k distinct characters in the current window.
// So we should move the sliding window.
while (counter > k) {
char cBegin = s.charAt(begin);
map.put(cBegin, map.get(cBegin) - 1);
if (map.get(cBegin) == 0) {
counter--;
}
begin++;
}
// Pay attention here!
// We don't get/update the result in while loop above
// Because if the number of distinct character isn't big enough, we won't enter the while loop
// eg. s = "abc" (We'd better update the result here to avoid getting 0 length)
maxLen = Math.max(maxLen, end - begin);
}
return maxLen;
}
```
# Source code
https://github.com/tubean/dailycode/tree/master/src/day12
# Reference
[Link](https://github.com/cherryljr/LeetCode/blob/master/Longest%20Substring%20with%20At%20Most%20Two%20Distinct%20Characters.java)
|
C | UTF-8 | 6,277 | 3.09375 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include "thread.h"
#include "function.h"
#include "context.h"
#include "struct.h"
/*
** Function call information.
** Basically just acts as a stack frame.
** Stored in a linked list so they can be reused, avoiding dynamic allocations.
*/
struct Call {
Call* next;
Call* previous;
bt_Closure* closure;
Instruction* ip;
bt_Value* base;
};
bt_Thread* thread_new()
{
bt_Thread* t = malloc(sizeof(bt_Thread));
t->next = NULL;
t->timer = 0;
t->stack = malloc(sizeof(bt_Value) * 32);
t->stacksize = 32;
Call* c = malloc(sizeof(Call));
c->previous = NULL;
c->next = NULL;
c->base = t->stack;
t->call = c;
return t;
}
/*
** Prints a bt_Value to stdout
*/
static void printvalue(bt_Value* vl)
{
switch (vl->type)
{
case VT_NIL: printf("nil\n"); break;
case VT_NUMBER: printf("%g\n", vl->number); break;
case VT_BOOL: printf(vl->boolean ? "true\n" : "false\n"); break;
default: putchar('\n'); break;
}
}
/*
** Test for equality of two bt_Values
*/
static int equal(bt_Value* l, bt_Value* r)
{
if (l->type == r->type) // Have to be the same type to be equal
{
switch (l->type)
{
case VT_NIL: return 1;
case VT_BOOL: return l->boolean == r->boolean;
case VT_NUMBER: return l->number == r->number;
}
}
return 0;
}
/*
** Less than comparison
** Errors if values are incompatible
*/
static int less(bt_Value* l, bt_Value* r)
{
return l->number < r->number;
}
/*
** Less than or equal comparision
** Also errors for incompatible types
*/
static int lequal(bt_Value* l, bt_Value* r)
{
return l->number <= r->number;
}
/*
** Evaluates a bt_Value as a boolean
** nil - always false
** boolean - should be obvious :V
** number - false if 0
*/
static int test(bt_Value* vl)
{
switch (vl->type)
{
case VT_BOOL: return vl->boolean;
case VT_NUMBER: return vl->number != 0;
default: return 0;
}
}
/*
** ============================================================
** The interpreter, Bullet Train's heart and soul
** ============================================================
*/
// Shortcuts
#define arga(i) ((i >> 8) & 0xFF)
#define argb(i) ((i >> 16) & 0xFF)
#define argbx(i) (i >> 16)
#define argc(i) (i >> 24)
#define dest(i) reg[arga(i)]
#define rkb(i) (i & 0x40 ? &fn->constants[argb(i)] : ®[argb(i)])
#define rkc(i) (i & 0x80 ? &fn->constants[argc(i)] : ®[argc(i)])
#define number(n) ((bt_Value) { .number = (n), .type = VT_NUMBER })
#define boolean(b) ((bt_Value) { .boolean = (b), .type = VT_BOOL })
#define struc(b) ((bt_Value) { .struc = (b), .type = VT_STRUCT })
/*
** Main loop of the interpreter
*/
int thread_execute(bt_Context* bt, bt_Thread* t)
{
Call* c;
bt_Function* fn;
bt_Value* reg;
// Refresh:
c = t->call;
reg = c->base;
fn = c->closure->function;
for (;;)
{
Instruction i = *c->ip++;
switch (i & 0x3F)
{
case OP_LOAD: {
dest(i) = fn->constants[argbx(i)];
break;
}
case OP_LOADBOOL: {
dest(i) = boolean(argb(i));
c->ip += argc(i);
break;
}
case OP_NEWSTRUCT: {
dest(i) = struc(bt_newstruct(bt));
break;
}
case OP_GETSTRUCT: {
dest(i) = getstruct(reg[argb(i)].struc, fn->keys[argc(i)]);
break;
}
case OP_SETSTRUCT: {
setstruct(reg[arga(i)].struc, fn->keys[argb(i)], rkc(i));
break;
}
case OP_MOVE: {
dest(i) = reg[argbx(i)];
break;
}
case OP_ADD: {
bt_Value* lhs = rkb(i);
bt_Value* rhs = rkc(i);
dest(i) = number(lhs->number + rhs->number);
break;
}
case OP_SUB: {
bt_Value* lhs = rkb(i);
bt_Value* rhs = rkc(i);
dest(i) = number(lhs->number - rhs->number);
break;
}
case OP_MUL: {
bt_Value* lhs = rkb(i);
bt_Value* rhs = rkc(i);
dest(i) = number(lhs->number * rhs->number);
break;
}
case OP_DIV: {
bt_Value* lhs = rkb(i);
bt_Value* rhs = rkc(i);
dest(i) = number(lhs->number / rhs->number);
break;
}
case OP_NEG: {
bt_Value* vl = rkc(i);
dest(i) = number(-vl->number);
break;
}
case OP_NOT: {
bt_Value* vl = rkc(i);
dest(i) = boolean(!vl->boolean);
break;
}
case OP_EQUAL: {
if (equal(rkb(i), rkc(i)) == arga(i)) {
++c->ip;
}
break;
}
case OP_LEQUAL: {
if (lequal(rkb(i), rkc(i)) == arga(i)) {
++c->ip;
}
break;
}
case OP_LESS: {
if (less(rkb(i), rkc(i)) == arga(i)) {
++c->ip;
}
break;
}
case OP_TEST: {
if (test(rkc(i)) == arga(i)) {
++c->ip;
}
break;
}
case OP_JUMP: {
c->ip = fn->program + argbx(i);
break;
}
case OP_RETURN: {
return 1;
}
case OP_PRINT: {
printvalue(rkc(i));
break;
}
}
}
return 0;
}
// Temp?
BT_API void bt_call(bt_Context* bt, bt_Function* fn)
{
// return;
bt_Thread* t = ctx_getthread(bt);
Call* c = t->call;
bt_Closure* cl = malloc(sizeof(bt_Closure));
cl->function = fn;
c->closure = cl;
c->ip = fn->program;
thread_execute(bt, t);
free(cl);
} |
Python | UTF-8 | 6,700 | 2.59375 | 3 | [] | no_license | from .basic import _Basic_class
from .utils import mapping, is_installed
from .music import Music
from distutils.spawn import find_executable
class TTS(_Basic_class):
_class_name = 'TTS'
SUPPORTED_LANGUAUE = [
'zh-CN', # 普通话(中国)
'en-US', # 英语(美国)English-United States
'en-GB', # 英语(英国)English-United Kingdom
'de-DE', # 德语(德国)Germany-Deutsch
'es-ES', # 西班牙语(西班牙)España-Español
'fr-FR', # 法语(法国)France-Le français
'it-IT', # 意大利语(意大利)Italia-lingua italiana
]
def __init__(self, engine='espeak'):
super().__init__()
self._lang = "en-US" # 默认输入的语言为英语
self.engine = engine
if (engine == "espeak"):
if not is_installed("espeak"):
raise Exception("TTS engine: espeak is not installed.")
self._amp = 100
self._speed = 175
self._gap = 5
self._pitch = 50
elif engine == "gtts" or engine == "polly":
import urllib.request as request
import base64
import json
self.request = request
self.base64 = base64
self.json = json
def _check_executable(self, executable):
executable_path = find_executable(executable)
found = executable_path is not None
return found
def say(self, words): # 输入的文字
eval(f"self.{self.engine}(words)")
def espeak(self, words):
self._debug('espeak:\n [%s]' % (words))
if not self._check_executable('espeak'):
self._debug('espeak is busy. Pass')
cmd = 'espeak -a%d -s%d -g%d -p%d \"%s\" --stdout | aplay 2>/dev/null & ' % (self._amp, self._speed, self._gap, self._pitch, words)
self.run_command(cmd)
self._debug('command: %s' %cmd)
def gtts(self, words):
sound_file = "/opt/ezblock/output.mp3"
data = {
"text": words,
"language": self.lang(),
}
header = {
"Content-Type": "application/json",
}
data = self.json.dumps(data)
data = bytes(data, 'utf8')
url = 'http://192.168.6.224:11000/api/web/v2/ezblock/google/tts'
req = self.request.Request(url, data=data, headers=header, method='POST')
r = self.request.urlopen(req)
result = r.read()
result = result.decode("utf-8")
result = self.ast.literal_eval(result)
data = result["data"]
data = self.base64.b64decode(data)
# print(data)
with open(sound_file, "wb") as f:
f.write(data)
music = Music()
music.sound_play(sound_file)
def polly(self, words):
sound_file = "/opt/ezblock/output.mp3"
data = {
"text": words,
"language": self.lang(),
}
header = {
"Content-Type": "application/json",
}
data = self.json.dumps(data)
data = bytes(data, 'utf8')
for i in range(5):
url = 'https://test2.ezblock.com.cn:11000/api/web/v2/ezblock/aws/tts'
req = self.request.Request(url, data=data, headers=header, method='POST')
r = self.request.urlopen(req)
result = r.read()
result = result.decode("utf-8")
# print('"%s"'%result)
if result != "":
break
else:
print("Empty result")
else:
raise IOError("Network Error")
# result = ast.literal_eval(result)
result = self.json.loads(result)
data = result["data"]
data = self.base64.b64decode(data)
# print(data)
with open(sound_file, "wb") as f:
f.write(data)
music = Music()
music.sound_play(sound_file)
def lang(self, *value): # 切换语言,可识别5种语言
if len(value) == 0:
return self._lang
elif len(value) == 1:
v = value[0]
if v in self.SUPPORTED_LANGUAUE:
self._lang = v
return self._lang
raise ValueError("Arguement \"%s\" is not supported. run tts.supported_lang to get supported language type."%value)
def supported_lang(self): # 返回支持的语言类型
return self.SUPPORTED_LANGUAUE
def espeak_params(self, amp=None, speed=None, gap=None, pitch=None):
if amp == None:
amp=self._amp
if speed == None:
speed=self._speed
if gap == None:
gap=self._gap
if pitch == None:
pitch=self._pitch
if amp not in range(0, 200):
raise ValueError('Amp should be in 0 to 200, not "{0}"'.format(amp))
if speed not in range(80, 260):
raise ValueError('speed should be in 80 to 260, not "{0}"'.format(speed))
if pitch not in range(0, 99):
raise ValueError('pitch should be in 0 to 99, not "{0}"'.format(pitch))
self._amp = amp
self._speed = speed
self._gap = gap
self._pitch = pitch
def test_polly():
import urllib.request as request
import json, ast, base64
sound_file = "/opt/ezblock/output.mp3"
data = {
"text": "hello",
"language": "zh-CN",
}
header = {
"Content-Type": "application/json",
}
data = json.dumps(data)
data = bytes(data, 'utf8')
for i in range(5):
url = 'http://192.168.6.223:11000/api/web/v2/ezblock/aws/tts'
req = request.Request(url, data=data, headers=header, method='POST')
r = request.urlopen(req)
print(r.status)
result = r.read()
result = result.decode("utf-8")
# print('"%s"'%result)
if result != "":
break
else:
print("Empty result")
# result = ast.literal_eval(result)
result = self.json.loads(result)
data = result["data"]
data = base64.b64decode(data)
# print(data)
with open(sound_file, "wb") as f:
f.write(data)
music = Music()
music.sound_play(sound_file)
def test():
# tts = TTS(engine="espeak")
# tts.lang("en-US")
# tts.say('Hallo')
tts = TTS(engine="polly")
tts.lang("zh-CN")
# tts.say('你好, 我是小爱同学')
count = 0
while True:
tts.say('你好')
count +=1
print(count)
# tts.speaker_volume(100)
# tts.espeak_params(amp=50, speed=80, gap=0, pitch=10)
# tts.say('Ich liebe dich')
# tts.say('hello nice to meet you')
if __name__ == "__main__":
test() |
C++ | UTF-8 | 1,061 | 3.625 | 4 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
struct Rect{
double x,y,w,h;
};
double overlap(Rect *r1,Rect *r2){
double area;
if((r1->x + r1->w<=r2->x and r1->y + r1->h>=r2->h) or (r2->x + r2->w <= r1->x and r2->y + r2->h >= r1->y)){
return 0;
}
else if(((r1->x +r1->w <= r2->x +r2->w)and r2->x<r1->x)){
area=r1->w*r1->h;
return area;
}
else if(((r2->x +r2->w <= r1->x +r1->w)and r1->x<r2->x)){
area=r2->w*r2->h;
return area;
}
else if (r1->x < r2->x) {
double ovw = abs(r2->x-(r1->x+r1->w));
double ovh = abs(r2->y-(r1->y +r1->h));
area=ovw*ovh;
return area;
}
else if (r1->x>r2->x) {
double ovw = abs(r1->x-(r2->x+r2->w));
double ovh = abs(r1->y-(r2->y +r2->h));
area=ovw*ovh;
return area;
}
}
int main(){
double x,y,w,h,x2,y2,w2,h2;
cout << "Please input Rect 1 (x y w h): ";
cin>>x>>y>>w>>h;
Rect Rect1 = {x,y,w,h};
cout << "Please input Rect 2 (x y w h): ";
cin>>x2>>y2>>w2>>h2;
Rect Rect2 = {x2,y2,w2,h2};
cout << "Overlap area = ";
cout<<overlap(&Rect1,&Rect2);
return 0;
}
|
Swift | UTF-8 | 1,328 | 2.640625 | 3 | [] | no_license | //
// TitleTableViewCell.swift
// FinPlus
//
// Created by nghiendv on 20/06/2018.
// Copyright © 2018 Cao Van Hai. All rights reserved.
//
import UIKit
enum TextCellType {
case TitleType
case DesType
}
class TitleTableViewCell: UITableViewCell {
@IBOutlet weak var leftConstraint: NSLayoutConstraint!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var rightConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var label: UILabel!
private var textCellType: TextCellType = .TitleType
func setTextCellType(type: TextCellType) {
self.textCellType = type
if textCellType == .TitleType {
label.font = UIFont(name: FONT_FAMILY_BOLD, size: FONT_SIZE_BIG)
label.textColor = .black
} else {
label.font = UIFont(name: FONT_FAMILY_REGULAR, size: FONT_SIZE_SEMIMALL)
label.textColor = UIColor(hexString: "#4D6678")
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
Python | UTF-8 | 3,665 | 2.8125 | 3 | [] | no_license | import boto3
import os
import logging
from dotenv import load_dotenv
from code.boto_factory import BotoFactory
load_dotenv()
logging.basicConfig(level=logging.WARNING)
class DDBToHTML():
def __init__(self, session):
self.ddb = BotoFactory().get_capability(
boto3.client, session, 'dynamodb'
)
def table_to_list(self):
paginator = self.ddb.get_paginator('scan')
itr = paginator.paginate(
TableName=os.environ['TABLE_NAME'],
Select='ALL_ATTRIBUTES'
)
all_items = list()
for i in itr:
all_items = i['Items'] + all_items
return all_items
def get_all_attributes(self, list_ddb_items):
"""expects a list of dictionaries where each dictionary is a single item
from DynamoDB"""
attributes = set()
for i in list_ddb_items:
attributes = attributes.union(i.keys())
return attributes
def make_order_of_columns(self, attributes, desired_order_list):
"""takes input of attributes set and a partial or complete list of
attributes in the desired order for the columns, e.g. should AccountId
be first column
then
desired_order_list=['AccountId']
If the desired order has fewer items than the attributes they will be
added randomly depending on the order of the set returns list of order
which can be used for HTML table generation
"""
order_list = list()
for attr in desired_order_list:
try:
attributes.remove(attr)
order_list.append(attr)
except Exception as e:
raise(e)
if len(attributes) > 0:
for i in range(len(attributes)):
order_list.append(attributes.pop())
return order_list
def make_table_head(self, ordered_list):
thead = '<thead>\n\t\t\t<tr>\n'
th_row = '\t\t\t\t<th>\n\t\t\t\t\t<p>%s\n\t\t\t\t</th>\n'
for i in range(len(ordered_list)):
thead += th_row % ordered_list[i]
thead += '\t\t\t</tr>\n\t\t</thead>\n'
return thead
def make_table_row(self, ordered_list, account_info):
tr = '\t\t<tr>\n'
tr_td = "\t\t\t<td>\n\t\t\t\t<p>%s\n\t\t\t</td>\n"
for i in range(len(ordered_list)):
data = account_info.get(ordered_list[i])['S']
if data.startswith('https://'):
data = "<a href=\"%s\" target=_blank>%s</a>" % (data, data)
tr += tr_td % data
tr += '\t\t</tr>\n'
return tr
def make_html_file(self, column_order='', filename=''):
if column_order == '':
self.logging.warning('No column order specified')
column_order = []
if filename == '':
filename = os.environ['DEFAULT_FILENAME']
items = self.table_to_list()
attributes = self.get_all_attributes(items)
ordered_list = self.make_order_of_columns(
attributes, column_order)
thead = self.make_table_head(ordered_list)
html_rows = str()
for item in items:
html_rows += self.make_table_row(ordered_list, item)
params = {
'TITLE': 'Account Roleswitching and Metadata',
'THEAD_VALS': thead,
'TR_VALS': html_rows
}
with open('html_templating/table_template.html', 'r') as f:
template = f.read()
path = filename
with open(path, 'w') as out:
out.write(
template % params
)
return({'Status': 'OK', 'Path': path})
|
Shell | UTF-8 | 315 | 3.71875 | 4 | [] | no_license | # this script is for checking disk usage
#For testing
#!/bin/bash
MAX=25
EMAIL=server@127.0.0.1
PART=xvda
USE=$(df -h | grep $PART | awk '{ print $5 }' | cut -d'%' -f1)
if [ $USE -gt $MAX ]; then
echo "Percent used: $USE" | mail -s "Running out of disk space" $EMAIL
else
echo "Disk usage is normal"
fi
|
Java | UTF-8 | 4,515 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.dmelnyk.workinukraine.ui.vacancy_list.core;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import android.view.ViewGroup;
import com.dmelnyk.workinukraine.ui.vacancy_list.business.IVacancyListInteractor;
import com.dmelnyk.workinukraine.models.VacancyModel;
import com.dmelnyk.workinukraine.utils.SiteUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by d264 on 7/31/17.
*/
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private final SitesTabFragment mFragment0;
private Fragment mFragment1;
private Fragment mFragment2;
private Fragment mFragment3;
private String[] mTitles;
private final Map<String, List<VacancyModel>> mSitesData;
private final List<VacancyModel> mNewFragmentData;
private final List<VacancyModel> mResentFragmentData;
private List<VacancyModel> mFavoriteFragmentData;
public ScreenSlidePagerAdapter(
FragmentManager fm,
String[] mTitles,
Map<String, List<VacancyModel>> mAllVacancies) {
super(fm);
this.mTitles = mTitles;
this.mSitesData = SiteUtil.convertToSiteMap(mAllVacancies.get(IVacancyListInteractor.DATA_ALL));
this.mNewFragmentData = mAllVacancies.get(IVacancyListInteractor.DATA_NEW);
this.mResentFragmentData = mAllVacancies.get(IVacancyListInteractor.DATA_RECENT);
this.mFavoriteFragmentData = mAllVacancies.get(IVacancyListInteractor.DATA_FAVORITE);
mFragment0 = SitesTabFragment.getNewInstance(mSitesData);
if (!mNewFragmentData.isEmpty() && mResentFragmentData.isEmpty()) {
mFragment1 = BaseTabFragment.getNewInstance(
(ArrayList<VacancyModel>) mNewFragmentData,
BaseTabFragment.FRAGMENT_NEW);
mFragment2 = new FavoriteTabFragment();
((FavoriteTabFragment) mFragment2).updateData(mFavoriteFragmentData);
}
if (!mNewFragmentData.isEmpty() && !mResentFragmentData.isEmpty()) {
mFragment1 = BaseTabFragment.getNewInstance(
(ArrayList<VacancyModel>) mNewFragmentData,
BaseTabFragment.FRAGMENT_NEW);
mFragment2 = BaseTabFragment.getNewInstance(
(ArrayList<VacancyModel>) mResentFragmentData,
BaseTabFragment.FRAGMENT_RECENT);
mFragment3 = new FavoriteTabFragment();
((FavoriteTabFragment) mFragment3).updateData(mFavoriteFragmentData);
}
if (mNewFragmentData.isEmpty()) {
mFragment1 = BaseTabFragment.getNewInstance(
(ArrayList<VacancyModel>) mResentFragmentData,
BaseTabFragment.FRAGMENT_RECENT);
mFragment2 = new FavoriteTabFragment();
((FavoriteTabFragment) mFragment2).updateData(mFavoriteFragmentData);
}
}
@Override
public int getItemPosition(Object object) {
int itemPosition;
if (object instanceof FavoriteTabFragment) {
itemPosition = POSITION_NONE;
} else {
itemPosition = POSITION_UNCHANGED;
}
return itemPosition;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return mFragment0;
case 1:
return mFragment1;
case 2:
return mFragment2;
case 3:
if (mFragment3 != null) {
return mFragment3;
} else {
return null;
}
}
return null;
}
@Override
public int getCount() {
return mTitles.length;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
public void updateFavoriteData(List<VacancyModel> vacancies) {
if (ScreenSlidePagerAdapter.this == null) {
Log.e(getClass().getSimpleName(), "adapter isn't created");
return;
}
mFavoriteFragmentData = vacancies;
if (mFragment2 instanceof FavoriteTabFragment) {
((FavoriteTabFragment) mFragment2).updateData(vacancies);
} else {
((FavoriteTabFragment) mFragment3).updateData(vacancies);
}
}
}
|
JavaScript | UTF-8 | 304 | 3.046875 | 3 | [] | no_license | var newColor = document.getElementsByClassName("invoer");
var kleuren = ["red", "blue", "yellow"]
function colorChange(){
newColor[0].style.backgroundColor = kleuren[Math.floor(Math.random()*kleuren.length)];
newColor[1].style.backgroundColor = kleuren[Math.floor(Math.random()*kleuren.length)];
}
|
C# | UTF-8 | 3,567 | 2.671875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace MASClassLibrary
{
[Serializable]
// public, because it can't be catched in the ActionInterpeter, if its private.
public class WrongTeamException : System.Exception
{
private string _failedString;
public List<WrongTeamException> containedExceptions = new List<WrongTeamException>();
public WrongTeamException()
{ }
public WrongTeamException(string message)
: base(message)
{ }
public WrongTeamException(string message, Exception innerException)
: base(message, innerException)
{ }
protected WrongTeamException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
this._failedString = info.GetString("_failedString");
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
if (info != null)
{
info.AddValue("_failedString", this._failedString);
}
}
public string FailedString
{
get { return this._failedString; }
set { this._failedString = value; }
}
public List<string> PrintExceptions()
{
List<string> output = new List<string>();
output.Add(this.Message);
foreach (WrongTeamException exc in this.containedExceptions)
{
output.Add(exc.Message);
}
return output;
}
}
[Serializable]
// public, because it can't be catched in the ActionInterpeter, if its private.
public class InvalidMoveOptionException : System.Exception
{
private string _failedString;
public List<InvalidMoveOptionException> containedExceptions = new List<InvalidMoveOptionException>();
public InvalidMoveOptionException()
{ }
public InvalidMoveOptionException(string message)
: base(message)
{ }
public InvalidMoveOptionException(string message, Exception innerException)
: base(message, innerException)
{ }
protected InvalidMoveOptionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
this._failedString = info.GetString("_failedString");
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
if (info != null)
{
info.AddValue("_failedString", this._failedString);
}
}
public string FailedString
{
get { return this._failedString; }
set { this._failedString = value; }
}
public List<string> PrintExceptions()
{
List<string> output = new List<string>();
output.Add(this.Message);
foreach (InvalidMoveOptionException exc in this.containedExceptions)
{
output.Add(exc.Message);
}
return output;
}
}
}
|
JavaScript | UTF-8 | 387 | 2.734375 | 3 | [] | no_license | // 2-global.js
// 내장된 전역변수에 대한 이해
// GLOBALS - NO WINDOW !!!
// __dirname - 최근 디렉토리 경로
// __filename - 파일 이름
// require - 모듈을 사용하기 위한 함수
// module - 최근 모듈의 정보
// process - 실행중인 프로그램의 환경 정보
console.log(__dirname)
setInterval(() => {
console.log("hello World!");
},1000);
|
JavaScript | UTF-8 | 4,220 | 2.75 | 3 | [] | no_license | // requiring packages needed for liri.js
var keys = require("./keys.js");
var request = require("request");
require("dotenv").config();
var fs = require("file-system");
var Twitter = require("twitter");
var Spotify = require("node-spotify-api");
var instruction = process.argv[3];
//log the liriCommand and userEntry history
var liriCommand = process.argv[2];
function commandLog(){
var log = "log.txt";
if(liriCommand === undefined){
liriCommand = "Liri wasn't told to do anything";
}
if(instruction === undefined){
instruction = "Liri doesn't recognize this command.";
}
fs.appendFile(log, liriCommand + ": " + instruction + ". \n", function(err) {
if (err) {
console.log(err);
}
});
};
//TWITTER ===============
var client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});
// function for retrieving tweets
var getTweets = function() {
var params = { screen_name: "harold91929100" };
client.get("statuses/user_timeline", params, function(
error,
tweets,
response
) {
if (!error) {
for (var i = 0; i < 20; i++) {
console.log(tweets[i].created_at);
console.log(tweets[i].text);
console.log("============================================================================================");
}
} else {
console.log(error);
}
});
};
//SPOTIFY ==================
var spotify = new Spotify({
id: process.env.SPOTIFY_ID,
secret: process.env.SPOTIFY_SECRET
});
// function for retrieving song from spotify
spotify.getSong = function(instruction) {
if (instruction === undefined) {
instruction = "The Sign";
}
spotify.search({ type: "track", limit: 1, query: instruction }, function(
err,
data
) {
if (err) {
return console.log("Error occurred: " + err);
}
console.log("Artist: " + data.tracks.items[0].album.artists[0].name);
console.log(
"Song preview: " +
data.tracks.items[0].album.artists[0].external_urls.spotify
);
console.log("Album name: " + data.tracks.items[0].album.name);
console.log("Song title: " + data.tracks.items[0].name);
});
};
//OMDB =============
//function for retrieving information from OMDB
var movieThis = function() {
if (instruction == undefined) {
instruction = "Mr. Nobody";
}
request("http://www.omdbapi.com/?apikey=trilogy&t=" + instruction, function(
error,
response,
body
) {
if (error) {
return console.log(error);
} else if (response.statusCode !== 200) {
return console.log("Error: returned " + response.statusCode);
}
var data = JSON.parse(body);
if (data.Error) {
return console.log(data.Error);
}
console.log("Title: " + data.Title);
console.log("Year: " + data.Year);
console.log("Rating: " + data.Rated);
console.log("Rotten Tomatoes: " + data.Ratings[0].Value);
console.log("Country Produced: " + data.Country);
console.log("Language: " + data.Language);
console.log("Plot: " + data.Plot);
console.log("Actors: " + data.Actors);
});
};
//function for do-what-it-says command
var doIt = function() {
fs.readFile("random.txt", "UTF8", function(err, data) {
if (err) {
return console.log(err);
}
// Data from file is in <cmd>,<song-or-movie>
var ranArr = data.split(",");
var cmd = ranArr[0];
var val = data.replace(cmd + ",", "");
runCommand(cmd, val);
});
};
//switch statement for commands given
var runCommand = function(command, value) {
switch (command) {
case "my-tweets":
commandLog();
getTweets();
break;
case "spotify-this-song":
commandLog();
spotify.getSong(value);
break;
case "movie-this":
commandLog();
movieThis(value);
break;
case "do-what-it-says":
commandLog();
doIt();
break;
default:
commandLog();
console.log("I don't know that, but I'm always learning. Check back later.");
}
};
runCommand(process.argv[2], process.argv[3]); |
Java | UTF-8 | 327 | 2.078125 | 2 | [
"MIT"
] | permissive | package com.groupname.game.controllers;
import org.junit.Test;
import static org.junit.Assert.*;
public class TitleControllerTests {
@Test(expected = NullPointerException.class)
public void gameCannotBeNull() {
TitleController controller = new TitleController();
controller.init(null, null);
}
}
|
Java | UTF-8 | 6,013 | 2.375 | 2 | [] | no_license | package com.currency.exchange.rest;
import com.currency.exchange.advice.CurrencyExchangeErrorResponse;
import com.currency.exchange.exception.CurrencyNotFoundException;
import com.currency.exchange.exception.InvalidCurrencyException;
import com.currency.exchange.service.CurrencyExchangeService;
import com.currency.exchange.service.bo.CurrencyConversion;
import com.currency.exchange.service.bo.CurrencyExchange;
import com.currency.exchange.service.bo.CurrencySupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@RestController
public class CurrencyExchangeResource {
private CurrencyExchangeService service;
public CurrencyExchangeResource(CurrencyExchangeService service) {
this.service = service;
}
@ApiOperation(
value="Retrieves currency exchange rate from other currencies to EURO, For example 1 USD is 0.843 EUR approximately",
notes = "Make a GET request to retrieve currency exchanges",
response = CurrencyExchange.class,
httpMethod = "GET"
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved", response = CurrencyExchange.class),
@ApiResponse(code = 400, message = "If any inputs are missing", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 404, message = "If no currencies found for inputs", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 500, message = "Unexpected Internal Error", response = CurrencyExchangeErrorResponse.class)})
@GetMapping("/currency/exchange/rate/from/{from}/to/EUR")
public CurrencyExchange getExchangeRateToEuro(@PathVariable String from) throws InvalidCurrencyException, CurrencyNotFoundException {
return service.getExchangeRateToEuro(from);
}
@ApiOperation(
value="Retrieves currency exchange rate from two different currency pairs",
notes = "Make a GET request to retrieve currency exchanges",
response = CurrencyExchange.class,
httpMethod = "GET"
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved", response = CurrencyExchange.class),
@ApiResponse(code = 400, message = "If any inputs are missing", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 404, message = "If no currencies found for inputs", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 500, message = "Unexpected Internal Error", response = CurrencyExchangeErrorResponse.class)})
@GetMapping("/currency/exchange/rate/from/{from}/to/{to}")
public CurrencyExchange getExchangeRateForCurrencyPairs(@PathVariable String from, @PathVariable String to) throws InvalidCurrencyException, CurrencyNotFoundException {
return service.getExchangeRateFromCurrencyPairs(from,to);
}
@ApiOperation(
value="Retrieves the supported currencies and number of times those currencies are requested",
notes = "Make a GET request to retrieve supported currencies",
response = List.class,
httpMethod = "GET"
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved", response = CurrencySupport.class),})
@GetMapping("/currency/exchange/supported/currencies")
public List<CurrencySupport> getSupportedCurrencies(){
return service.getSupportedCurrenciesAndNoOfTimesRequested();
}
@ApiOperation(
value="Calculates the currency conversion based on the exchange rate",
notes = "Make a GET request to retrieve currency conversions",
response = CurrencySupport.class,
httpMethod = "GET"
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved", response = CurrencySupport.class),
@ApiResponse(code = 400, message = "If any inputs are missing", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 404, message = "If no currencies found for inputs", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 500, message = "Unexpected Internal Error", response = CurrencyExchangeErrorResponse.class)})
@GetMapping("/exchange/conversion/from/{from}/to/{to}/quantity/{quantity}")
public CurrencyConversion getCurrencyConversion(@PathVariable String from, @PathVariable String to, @PathVariable BigDecimal quantity) throws InvalidCurrencyException, CurrencyNotFoundException {
CurrencyConversion currencyConversion = service.getCurrencyConversion(from, to, quantity);
return currencyConversion;
}
@ApiOperation(
value="Retrieves the currency chart url",
notes = "Make a GET request to retrieve urls",
response = Map.class,
httpMethod = "GET"
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved", response = Map.class),
@ApiResponse(code = 400, message = "If any inputs are missing", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 404, message = "If no currencies found for inputs", response = CurrencyExchangeErrorResponse.class),
@ApiResponse(code = 500, message = "Unexpected Internal Error", response = CurrencyExchangeErrorResponse.class)})
@GetMapping("/exchange/linkTo/{currencyPair}")
public Map<String, String> getCurrencyPairLink(@PathVariable String currencyPair) throws CurrencyNotFoundException {
return service.getCurrencyPairLink(currencyPair);
}
}
|
C# | UTF-8 | 7,526 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entidades;
using CapaAccesoDatos;
using System.Data;
namespace CapaNegocio
{
public class negMesa
{
#region singleton
private static readonly negMesa _instancia = new negMesa();
public static negMesa Instancia
{
get
{
return negMesa._instancia;
}
}
#endregion singleton
#region MESAS
public List<entMesa> ActExtraerMesas(int id)
{
try
{
List<entMesa> Lista = null;
Lista = datMesa.Instancia.ActExtraerMesas(id);
if (Lista.Count == 0) throw new ApplicationException("Lista de mesas vacia");
else if (Lista == null) throw new ApplicationException("Se produjo un error en la carga de la lista de productos");
return Lista;
}
catch (Exception)
{
throw;
}
}
public int insertarMesa(entMesa m)//LISTO
{
try
{
String cadXml = "";//se creara la cadena del xml
cadXml += "<mesa ";
cadXml += "idtipo='" + m.id_tipo.Id_Tipo + "' ";
cadXml += "iddisponibilidad='" + m.Id_disponibilidad.Id_Disponibilidad + "'/>";
cadXml = "<root>" + cadXml + "</root>";
int result = datMesa.Instancia.insertarMesa(cadXml);
if (result == 0) throw new ApplicationException("Ocurrio un error al registrar, intentelo nuevamente");
return result;
}
catch (Exception)
{
throw;
}
}
public List<entTipo> ListarTipo()//--listo
{
try
{
return datMesa.Instancia.ListarTipo();
}
catch (Exception)
{
throw;
}
}
public int ObtenerIdMesa()//--listo
{
try
{
return datMesa.Instancia.ObtenerIdMesa();
}
catch (Exception)
{
throw;
}
}
public int insertarTipoMesa(string tp)
{
try
{
int result = datMesa.Instancia.insertarTipoMesa(tp);
if (result == 0) throw new ApplicationException("Ocurrio un error al registrar, intentelo nuevamente");
return result;
}
catch (Exception)
{
throw;
}
}
public int EliminarMesa(int id_mesa)
{
try
{
int retorno = datMesa.Instancia.EliminarMesa(id_mesa);
if (retorno == 0) throw new ApplicationException("No se pudo completar la acción");
//Excepción en caso de no haberse eliminado
return retorno;//en caso contrario regresa el valor
}
catch (Exception)
{
throw;
}
}
public int actualizarMesa(entMesa m)
{
try
{
String cadXml = "";//se creara la cadena del xml
cadXml += "<actMesa ";
cadXml += "idmesa='" + m.Id_Mesa + "' ";
cadXml += "idtipo='" + m.id_tipo.Id_Tipo + "' ";
cadXml += "iddisponibilidad='" + m.Id_disponibilidad.Id_Disponibilidad + "'/>";
cadXml = "<root>" + cadXml + "</root>";
int result = datMesa.Instancia.actualizarMesa(cadXml);
if (result == 0) throw new ApplicationException("Ocurrio un error al actualizar, intentelo nuevamente");
return result;
}
catch (Exception)
{
throw;
}
}
public DataTable CargarMesas()
{
try
{
DataTable dt = datMesa.Instancia.CargarMesas();
if (dt.Rows.Count == 0)
{
throw new ApplicationException("No se encontraron registros");
}
return dt;
}
catch (Exception)
{
throw;
}
}
public DataTable BuscarMesa(string busqueda)
{
try
{
DataTable dt = datMesa.Instancia.BuscarMesa(busqueda);
if (dt.Rows.Count == 0)
{
throw new ApplicationException("No se encontraron registros");
}
return dt;
}
catch (Exception)
{
throw;
}
}
#endregion
#region CobroMESA
public int GuardarCobroMesa(entCobroMesa co)
{
//tratar o devolver expeción
try
{
String cadXml = "";//se crea la cadena del xml
cadXml += "<cobroMesa ";//Datos a tratar
cadXml += "idusuario='" + co.Id_Usuario.Id_Usuario + "' ";
cadXml += "fecha='" + co.fecha + "' ";
cadXml += "idmesa='" + co.Id_mesa.Id_Mesa + "' ";
cadXml += "tiempoInicio='" + co.Tiempo_inicio + "' ";
cadXml += "tiempoFinal='" + co.Tiempo_fin + "' ";
cadXml += "tiempoTotal='" + co.Tiempo_total + "' ";
cadXml += "pagoTotal='" + co.PagoTotal + "'/>";
cadXml = "<root>" + cadXml + "</root>";
int result = datMesa.Instancia.GuardarCobroMesa(cadXml);//Conexión con la BD
if (result == 0) throw new ApplicationException("Ocurrio un error al registrar, intentelo nuevamente");
return result;
}
catch (Exception)
{
throw;
}
}
public List<entMesa> ListarMesas()//--listo
{
try
{
return datMesa.Instancia.ListarMesa();
}
catch (Exception)
{
throw;
}
}
public string ListarTipoMesa(Int32 idMesa)//--listo
{
try
{
return datMesa.Instancia.ListarTipoMesa(idMesa);
}
catch (Exception)
{
throw;
}
}
public DataTable BuscarCobro(int id)
{
try
{
DataTable dt = datMesa.Instancia.BuscarCobro(id);
if (dt.Rows.Count == 0)
{
//throw new ApplicationException("No se encontraron registros");
}
return dt;
}
catch (Exception)
{
throw;
}
}
public DataTable CargarCobros()
{
try
{
DataTable dt = datMesa.Instancia.CargarCobros();
if (dt.Rows.Count == 0)
{
//throw new ApplicationException("No se encontraron registros");
}
return dt;
}
catch (Exception)
{
throw;
}
}
#endregion
}
}
|
Python | UTF-8 | 917 | 4.34375 | 4 | [] | no_license | def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n - 1): #if I have an array with 6 elements, why do I only need to make 5 iterations? https://stackoverflow.com/questions/47529349/why-do-we-make-n-1-iterations-in-bubble-sort-algorithm
#Because a swap requires at least two elements. So if you have 6 elements, you only need to consider 5 consecutive pairs
# traverse the array from 0 to n-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Driver code to test above
return arr
arr = [64, 34, 25, 12, 22, 11, 90]
print(bubbleSort(arr))
|
Python | UTF-8 | 423 | 3.625 | 4 | [] | no_license | #获取对象信息
class MyObject(object):
ca = 8888
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
print(hasattr(obj,'x'))
print(hasattr(obj,'y'))
setattr(obj,'y',19)
print(getattr(obj,'y'))
fn = getattr(obj,'power')
print(fn())
# obj.ca = 999
MyObject.ca = 666
print(MyObject.ca)
print(obj.ca)
print(getattr(obj,'ca'))
print(getattr(MyObject,'ca')) |
Markdown | UTF-8 | 8,824 | 2.875 | 3 | [
"Unlicense"
] | permissive |
# Is the global quest to end plastic waste a circular firing squad?
Published at: **2019-11-04T02:11:00+00:00**
Author: **Joel Makower**
Original: [GreenBiz](https://www.greenbiz.com/article/global-quest-end-plastic-waste-circular-firing-squad)
It’s been roughly three years since the world’s attention turned to the environmental perils of plastic waste, especially from single-use packaging. And while intense media attention on the topic has inevitably moved on to other issues, the action behind the scenes has been progressing at a steady clip.
According to the New Plastics Economy Global Commitment 2019 Progress Report (PDF), released last month by the Ellen MacArthur Foundation, which tracks the commitments of more than 400 businesses, governments and others around the world, there is "promising progress on two fronts": the number of organizations "laying the foundations to scale and accelerate action"; and a quantitative baseline that can be used to measure such progress across a significant group of businesses between now and 2025.
"These are important steps forward," says the foundation.
Not so much, say environmental activists.
And there, in a compostable nutshell, is the heart of the challenge companies face as they seek to transform their products to adopt circular models. Simply put: There’s no agreed-upon end game, and incremental solutions simply won’t cut it, in the eyes of plastics activists.
For most packaged-goods companies, the stated goal is to eliminate waste — closing the loop by implementing compostable, reusable and recyclable versions of single-use plastic packaging — and then to work with local communities, waste haulers and others to ensure that their used packaging actually gets composted, reused or recycled. It often means working simultaneously at internal (package design), value chain (suppliers and consumers) and external (recycling infrastructure) scales, often in collaboration with peer companies, municipalities and others. In other words, a systemic approach.
For many environmentalists, that’s not good enough. Indeed, they say, most solutions companies are pursuing are just plain wrong. They want to do away with plastics altogether, and anything short of that is, well, just packaging.
That’s my take from comparing the aforementioned Ellen MacArthur progress report with another report released last month, from Greenpeace, "Throwing Away Our Future: How Companies Still Have It Wrong on Plastic Pollution 'Solutions'" (PDF).
Together, they frame the complexity facing companies and supply chains as they seek to transition to circularity, as well as the apparent misalignment between companies and their activist critics.
First, the corporate side. According to the Ellen MacArthur Foundation, "Businesses representing over 20 percent of all plastic packaging globally have for the first time united behind a common vision for a circular economy for plastics, together with 19 forward-thinking governments."
Moreover, it reports, about 60 percent of brands, retailers and packaging producers in the signatory group that have used polystyrene, extruded polystyrene or polyvinylidene chloride "have eliminated or have concrete plans to phase out these materials from their portfolio."
The number is even higher — 70 percent — for single-use straws, carrier bags and "undetectable carbon black plastics," used primarily in fast food trays and other plastic pots, tubs and containers.
Other findings:
Concludes the foundation: "There remains large potential for businesses to make greater strides on elimination by moving beyond these commonly identified problematic items towards more fundamental innovation-led elimination." It cites technologies that keep produce fresh without packaging or integrated labels on plastic bottles that minimize multi-material packaging or technologies that greatly improve materials sorting in landfill operations.
All that potential aside, the progress achieved in a relatively short time frame is significant, if not remarkable, given the packaged goods industry’s historic recalcitrance at changing packaging designs in the name of sustainability.
Of course, there’s still a long way to go before circularity becomes the norm, not the exception, among consumer goods. Some companies and products likely never will get there. Still, the pace of change is undeniably faster than almost anyone expected.
So, how is all this playing in the world of environmental activists? Not so well, according to Greenpeace.
The nonprofit acknowledges that companies are switching from plastic to other forms of single-use packaging, investing in partnerships to improve recycling and waste management, and looking to emerging technologies. But these solutions, it says, "enable these companies to continue business as usual rather than reducing demand for plastic." It criticizes what it calls "false solutions that fail to move us away from single-use plastic, diverting attention away from better systems, perpetuating the throwaway culture and confusing people in the process."
The Greenpeace report focuses on a subset of products called fast-moving consumer goods, or FMCG. These include low-cost, non-durable household products such as packaged foods, beverages, toiletries, over-the-counter drugs and other consumables.
Says Greenpeace:
In Greenpeace’s world, many avenues being pursued by FMCGs are dead-ends, or worse. Switching from plastic to paper endangers forests. Biobased and compostable plastics are greenwash. Chemical recycling — an umbrella term for several emerging technologies that return plastics to their molecular state to be converted back into new plastics — is "toxic tech."
The activist group was similarly dismissive of an announcement last month by BP Petrochemicals about Infinia, "a game-changing recycling technology" that holds the promise of diverting "billions of colored PET bottles and food trays from landfill and incineration." The company said it plans to construct a $25 million pilot plant in the United States to prove the technology, before progressing to full-scale commercialization.
Greenpeace dismissed BP’s announcement as "a desperate attempt from a plastic polluter to ensure it can continue making profits off of plastics."
So, then, what passes the activists’ muster?
"We need a reuse revolution," the group flatly declares:
(Greenpeace is hosting "Global Refill Day" this week "to demonstrate the change we wish to see from companies.")
All good, of course, although an actual "reuse revolution" is likely a ways off, at least at the scale Greenpeace likely would find acceptable. The Loop partnership, launched earlier this year, which involves brands such as Procter & Gamble, Nestlé, PepsiCo, Unilever, Mars and Coca-Cola, is barely six months old and operates in just two geographic markets. It is far too early to tell whether consumers will embrace it or brands will find it profitable, and how far and wide it will expand.
Such subtleties don’t typically concern activists, who want change now, never mind the cost or disruption. And their concerns are real and urgent, as we see what the scourge of single-use plastic packaging has done to the world's rivers, oceans and landscapes, as well as the concomitant metastasis of toxicity it has brought to the global environment.
So, how do we get from here to circularity — quickly, affordably and effectively — in a way that feels more collaborative than combative? It’s an open question.
The challenge is hardly unique to plastics and packaging. It's common to sustainability: Activists name a bold goal and set a high bar while holding companies accountable for making progress. End of story. It rarely involves the recognition that societal shifts are expensive, time-consuming and messy propositions, and that consumers don’t always embrace the requisite changes, even if they're good for the planet.
Something’s gotta give — on both sides of the equation.
Companies are really good at saying, "We’re doing the best we can," even when their efforts may be timid, half-hearted or inadequate. They might get further, faster by being more forthcoming about the challenges they face in making these shifts and by inviting consumers (and activists) to be a bigger part of designing innovative solutions.
Activists, for their part, need to embrace partial measures on the road to what is likely to be a decade-long shift to their ideal state. They are really good at telling companies, “Nope, that’s not good enough." They might get further, faster by saying, "Thank you. Now do more."
For more on these topics, I invite you to follow me on Twitter, subscribe to my Monday morning newsletter, GreenBuzz, and listen to GreenBiz 350, my weekly podcast.
|
JavaScript | UTF-8 | 4,267 | 3.734375 | 4 | [] | no_license |
// //Home page
var weightButton = document.getElementById("weight-button");
var tempButton = document.getElementById("temp-button");
var homeButton = document.getElementById("home");
// //Hide the categories and back button by default
document.getElementById("weight-converter").style.display = "none";
document.getElementById("temp-converter").style.display = "none";
// //Add Event listener as to when the buttons are clicked.
var weightConverter = document.getElementById("weight-converter");
weightButton.addEventListener("click", function(){
document.getElementById("home-message").style.display = "none";
tempConverter.style.display = "none";
weightConverter.style.display = "inline";
});
var tempConverter = document.getElementById("temp-converter");
tempButton.addEventListener("click", function(){
document.getElementById("home-message").style.display = "none";
weightConverter.style.display = "none";
tempConverter.style.display = "inline";
});
// Home button
homeButton.addEventListener("click", function(){
//Clear weight input and output values
document.getElementById("select-weight").selectedIndex = 0;
document.getElementById("input").value = "";
document.getElementById("poundsOutput").innerHTML = "";
document.getElementById("gramsOutput").innerHTML = "";
document.getElementById("kgOutput").innerHTML = "";
document.getElementById("ozOutput").innerHTML = "";
//Clear temperature input and output values
document.getElementById("select-temp").selectedIndex = 0;
document.getElementById("tempinput").value = "";
document.getElementById("celciusOutput").innerHTML = "";
document.getElementById("faOutput").innerHTML = "";
document.getElementById("kelvinOutput").innerHTML = "";
weightConverter.style.display = "none";
tempConverter.style.display = "none";
document.getElementById("home-message").style.display = "inline";
});
//Weight Converter
document.getElementById("input").addEventListener("input", function(e){
var input = e.target.value;
//Weight Index
switch(document.getElementById("select-weight").selectedIndex){
case 0:
return alert("Please select unit");
break;
case 1: //Pounds
var pounds = input;
var grams = input/0.0022046;
var kg = input/2.2046;
var oz = input * 16;
break;
case 2: //Grams
var pounds = input * 0.0022046;
var grams = input;
var kg = input/1000;
var oz = input/28.35;
break;
case 3: //Kilograms
var pounds = input * 2.20;
var grams = input * 1000;
var kg = input;
var oz = input * 35.27;
break;
case 4: //Ounce
var pounds = input/16;
var grams = input * 28.35;
var kg = input/35.27;
var oz = input * input;
break;
}
document.getElementById("poundsOutput").innerHTML = pounds;
document.getElementById("gramsOutput").innerHTML = grams;
document.getElementById("kgOutput").innerHTML = kg;
document.getElementById("ozOutput").innerHTML = oz;
});
//Temperature converter
document.getElementById("tempinput").addEventListener("input", function(event){
var tempinput = event.target.value;
// Temterature Index
switch(document.getElementById("select-temp").selectedIndex){
case 0:
return alert("Please select unit");
break;
case 1: //Celcius
var celcius = tempinput;
var fahrenheit = (tempinput * 1.8)+32;
var kelvin = tempinput + 273;
break;
case 2: //Farenheit
var celcius = (tempinput - 32)*0.5556;
var fahrenheit = tempinput;
var kelvin = 0.56*(tempinput-32)+273;
break;
case 3: //Kelvin
var celcius = tempinput - 273;
var fahrenheit = 1.8*(tempinput-273)+32;
var kelvin = tempinput;
break;
}
document.getElementById("celciusOutput").innerHTML = celcius;
document.getElementById("faOutput").innerHTML = fahrenheit;
document.getElementById("kelvinOutput").innerHTML = kelvin;
});
|
Java | UTF-8 | 6,268 | 3.203125 | 3 | [] | no_license | import obj_lib.AquaProcess;
import obj_lib.Aquarium;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
AquaProcess process;
// имя для файла с игровым полем
String filename = "aquarium.txt";
File file = new File(filename);
// проверяем наличие файла
if (!file.exists()) {
// если не существует - пытаемся сгенерировать и записать
try {
FileWriter fileWriter = new FileWriter(filename);
Random random = new Random();
// записываем на лету случайные числа в пределах индексов статических объектов
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 80; j++) {
fileWriter.write(String.valueOf(random.nextInt(4)));
}
if (i < 19) {
fileWriter.write("\n");
}
}
// закрываем поток записи
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// массив для инициализации игрового поля
byte[][] arr = new byte[20][80];
// пытаемся прочитать файл, ведь он гарантированно существует
try {
FileReader fileReader = new FileReader(filename);
Scanner scanner = new Scanner(fileReader);
// читаем посимвольно в массив
for (int i = 0; i < 20; i++) {
char[] sym = scanner.nextLine().toCharArray();
for (int j = 0; j < sym.length; j++) {
arr[i][j] = Byte.parseByte(String.valueOf(sym[j]));
}
}
// закрываем поток чтения
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
// пытаемся получить экземпляр игрового поля, если его нет оно создается на основе прочтенного файла
// игровое поле может существовать только в елдиничном экземпляре, потому применен паттерн Singleton
Aquarium aquarium = Aquarium.getInstance(arr);
// читаем наши "программы" в процессы и инициируем их выполнение
//создаем нашу очередь
Queue<AquaProcess> processes = new LinkedList<>();
// Получаем список файлов "программ"
File programFolder = new File("programFolder");
File[] programs = programFolder.listFiles();
assert programs != null;
// для каждого файла создаем процесс и добавляем его в конец очереди
for (File program: programs) {
process = new AquaProcess();
process.readProgram(program, aquarium);
processes.add(process);
}
// бесконечный цикл работы
// стартуем с первой программы в очередии и 1 тика
int tick = 1;
AquaProcess currentProc;
byte priority;
String currentCode;
while (tick <= 1000) {
currentCode = "";
// берем программу из очереди
currentProc = processes.peek();
// Стереть все что на экране
System.out.println("\033[2J");
// Какой тик
System.out.println("Tick:" + tick);
if (currentProc != null && currentProc.getCommandCounter() < currentProc.getCode().size()) {
// Какая программа
System.out.println("Name: " + currentProc.getName() + "(" + currentProc.getX() + ", " + currentProc.getY() + ")");
// узнаем ее приоритет
priority = currentProc.getPriority();
// Какой у программы приоритет
System.out.println("Priority: " + priority);
// выполняем инструкции согласно приоритета
int size = currentProc.getCode().size();
for (int i = 0; i < size && i < priority; i++) {
byte commandIndex = currentProc.getCommandCounter();
if (commandIndex < size) {
currentCode = currentCode + currentProc.getCode().get(commandIndex) + " ";
currentProc.runCode(aquarium);
} else {
processes.remove(currentProc);
currentProc = null;
break;
}
}
// Какое действие
System.out.println("CODE: " + currentCode);
System.out.println("Coordinates (" + currentProc.getX() + ", " + currentProc.getY() + ")");
if (currentProc != null) {
// этот процесс уже отработал, нужно его убрать из головы очереди
processes.remove(currentProc);
//задаем переход к другому процессу в конце тика
processes.add(currentProc);
}
}
// Выводим поле
aquarium.showField();
tick++;
// замораживаем программу на 2 секунды для наглядности
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
C# | UTF-8 | 341 | 3.375 | 3 | [] | no_license | using System;
class MainClass
{
static void Main()
{
Console.Write("Skriv ett tal mellan 0 och 100: ");
int i = int.Parse(Console.ReadLine());
for (int e = i; e < 101; e++) //Får inte använda samma varaible som redan är tilldelad
{
Console.WriteLine(e);
}
}
}
|
Java | UTF-8 | 403 | 1.828125 | 2 | [] | no_license | package com.hs.reptilian.model;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "fx_system_config")
public class SystemConfig {
@Id
@GeneratedValue
private Integer id;
private String key;
private String value;
private String remark;
}
|
SQL | UTF-8 | 3,951 | 3.125 | 3 | [] | no_license | /*
Navicat MySQL Data Transfer
Source Server : 1234
Source Server Version : 50633
Source Host : localhost:3306
Source Database : zf_foodie
Target Server Type : MYSQL
Target Server Version : 50633
File Encoding : 65001
Date: 2016-10-13 10:16:03
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for eat_food_category
-- ----------------------------
DROP TABLE IF EXISTS `eat_food_category`;
CREATE TABLE `eat_food_category` (
`pk_id` varchar(40) NOT NULL DEFAULT '',
`category_name` varchar(40) DEFAULT NULL,
`category_code` varchar(40) DEFAULT NULL,
`parent_pkid` varchar(40) DEFAULT NULL,
`remark` varchar(4000) DEFAULT NULL,
`flag_status` decimal(1,0) DEFAULT NULL,
`flag_sort` decimal(10,0) DEFAULT NULL,
`user_pkid` varchar(40) DEFAULT NULL,
`make_emp` varchar(40) DEFAULT NULL,
`make_date` datetime DEFAULT NULL,
`modify_emp` varchar(40) DEFAULT NULL,
`modify_date` datetime DEFAULT NULL,
PRIMARY KEY (`pk_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of eat_food_category
-- ----------------------------
INSERT INTO `eat_food_category` VALUES ('2A9EB532-8010-49BB-B729-A1D6E9557699', '广东小吃', null, null, null, '0', null, null, null, null, null, null);
INSERT INTO `eat_food_category` VALUES ('N82E71E48-F478-4C47-96B2-DD2AFC0D9311', '北京小吃', null, null, null, '0', null, null, null, null, null, null);
-- ----------------------------
-- Table structure for eat_food_list
-- ----------------------------
DROP TABLE IF EXISTS `eat_food_list`;
CREATE TABLE `eat_food_list` (
`pk_id` varchar(40) NOT NULL,
`food_category` varchar(40) DEFAULT NULL,
`food_code` varchar(40) DEFAULT NULL,
`food_name` varchar(40) DEFAULT NULL,
`short_name` varchar(40) DEFAULT NULL,
`food_name_eng` varchar(40) DEFAULT NULL,
`food_price` decimal(16,6) DEFAULT NULL,
`user_pkid` varchar(40) DEFAULT NULL,
`remark` varchar(4000) DEFAULT NULL,
`flag_status` decimal(1,0) DEFAULT NULL,
`flag_sort` decimal(10,0) DEFAULT NULL,
`make_emp` varchar(40) DEFAULT NULL,
`make_date` datetime DEFAULT NULL,
`modify_emp` varchar(40) DEFAULT NULL,
`modify_date` datetime DEFAULT NULL,
PRIMARY KEY (`pk_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of eat_food_list
-- ----------------------------
INSERT INTO `eat_food_list` VALUES ('NC05254E2-1A5F-4B57-8CF6-F2339DEC1BA6', '2A9EB532-8010-49BB-B729-A1D6E9557699', null, '广东2', null, null, null, null, null, '0', null, null, null, null, null);
INSERT INTO `eat_food_list` VALUES ('ND1D03D89-8687-4FD8-A46C-9AC23B1FF5C2', '2A9EB532-8010-49BB-B729-A1D6E9557699', null, '广东1', null, null, null, null, null, '0', null, null, null, null, null);
INSERT INTO `eat_food_list` VALUES ('NE4F4A286-AD2F-4B92-8EF5-2F83CAC7F86B', 'N82E71E48-F478-4C47-96B2-DD2AFC0D9311', null, '北京1', null, null, null, null, null, null, null, null, null, null, null);
-- ----------------------------
-- Table structure for eat_system_user_info
-- ----------------------------
DROP TABLE IF EXISTS `eat_system_user_info`;
CREATE TABLE `eat_system_user_info` (
`pk_id` varchar(40) NOT NULL,
`user_password` varchar(40) DEFAULT NULL,
`user_nick_name` varchar(40) DEFAULT NULL,
`remark` varchar(4000) DEFAULT NULL,
`flag_status` decimal(1,0) DEFAULT NULL,
`flag_sort` decimal(10,0) DEFAULT NULL,
`make_emp` varchar(40) DEFAULT NULL,
`make_date` datetime DEFAULT NULL,
`modify_emp` varchar(40) DEFAULT NULL,
`modify_date` datetime DEFAULT NULL,
`login_state` varchar(40) DEFAULT NULL,
`flag_power` decimal(1,0) DEFAULT NULL,
PRIMARY KEY (`pk_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of eat_system_user_info
-- ----------------------------
INSERT INTO `eat_system_user_info` VALUES ('admin', '1234', null, null, '0', null, null, null, null, null, null, null);
|
Java | UTF-8 | 1,596 | 2.390625 | 2 | [] | no_license | package com.example.bluecloudmedicalclinic.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by HP on 12/24/2019.
*/
public class SQLitePrescriptionHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME= "Bluecloud.db";
// private static final String DATABASE_NAME= "Bluecloud_medical.db";
private static final String TABLE_NAME= "New_Prescription_Table";
private static final String COLUMN_ID = "id";
private static final String COLUMN_MEDICATION = "medication";
private static final String COLUMN_DOSAGE = "dosage";
private static final String COLUMN_INSTRUCTION = "instruction";
private static final String COLUMN_PRESCRIPTION = "prescription";
public SQLitePrescriptionHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +"("
+ COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_MEDICATION + "TEXT,"
+ COLUMN_DOSAGE + "VARCHAR,"
+ COLUMN_INSTRUCTION + "VARCHAR,"
+ COLUMN_PRESCRIPTION + "VARCHAR" +")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
|
C++ | UTF-8 | 2,388 | 3.75 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct elem
{
int dane;
elem * nast;
};
void add(elem* &pocz_kolejki, elem* &kon_kolejki, int x)
{
if(!pocz_kolejki)
{
pocz_kolejki = new elem;
pocz_kolejki->dane = x;
kon_kolejki = pocz_kolejki;
}
else
{
kon_kolejki->nast = new elem;
kon_kolejki->nast->dane = x;
kon_kolejki = kon_kolejki->nast;
}
}
int next(elem* &pocz_kolejki, elem* &kon_kolejki)
{
int x;
if(!pocz_kolejki)
{
cout << "Kolejka jest pusta!\n";
return 0;
}
else
{
if(!(pocz_kolejki->nast))
{
x = pocz_kolejki->dane;
delete pocz_kolejki;
pocz_kolejki = NULL;
return x;
}
else
{
elem* temp;
x = pocz_kolejki->dane;
temp = pocz_kolejki;
pocz_kolejki = pocz_kolejki->nast;
delete temp;
return x;
}
}
}
int firstEl(elem* pocz_kolejki)
{
if(!pocz_kolejki)
{
cout << "Kolejka jest pusta!\n";
return 0;
}
else
return pocz_kolejki->dane;
}
bool isEmpty(elem* pocz_kolejki)
{
return !pocz_kolejki;
}
int main()
{
elem * pocz_kolejki = NULL;
elem * kon_kolejki = NULL;
cout << "Czy kolejka jest pusta? >> " << isEmpty(pocz_kolejki) << endl;
cout << "Wprowadzam do kolejki kolejno liczby:\n";
cout << "1\n";
add(pocz_kolejki, kon_kolejki, 1);
cout << "2\n";
add(pocz_kolejki, kon_kolejki, 2);
cout << "3\n";
add(pocz_kolejki, kon_kolejki, 3);
cout << "4\n";
add(pocz_kolejki, kon_kolejki, 4);
cout << "5\n";
add(pocz_kolejki, kon_kolejki, 5);
cout << "Czy kolejka jest pusta? >> " << isEmpty(pocz_kolejki) << endl;
cout << "Co jest na poczatku? >> " << firstEl(pocz_kolejki) << endl;
cout << "Wprowadzam z kolejki kolejno liczby:\n";
cout << next(pocz_kolejki, kon_kolejki) << endl;
cout << next(pocz_kolejki, kon_kolejki) << endl;
cout << next(pocz_kolejki, kon_kolejki) << endl;
cout << next(pocz_kolejki, kon_kolejki) << endl;
cout << next(pocz_kolejki, kon_kolejki) << endl;
cout << firstEl(pocz_kolejki) << endl;
cout << next(pocz_kolejki, kon_kolejki) << endl;
cout << "Czy kolejka jest pusta? >> " << isEmpty(pocz_kolejki) << endl;
return 0;
}
|
Python | UTF-8 | 966 | 3.75 | 4 | [] | no_license | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def count_paths(t, target):
if t is None:
return 0
count = dfs(t, target, 0)
if t.left is not None:
count += count_paths(t.left, target)
if t.right is not None:
count += count_paths(t.right, target)
return count
def dfs(n, target, running_sum):
if n is None:
return 0
running_sum += n.data
num_paths = 0 if running_sum != target else 1
num_paths += dfs(n.left, target, running_sum)
num_paths += dfs(n.right, target, running_sum)
return num_paths
# Let's test it!
r = Node(7)
r.left, r.right = Node(3), Node(4)
r.left.left, r.left.right = Node(2), Node(0)
r.right.right = Node(6)
r.left.left.left, r.left.left.right = Node(-2), Node(1)
r.left.left.right.right = Node(-3)
r.right.right.left, r.right.right.right = Node(-7), Node(3)
print('target 10:', count_paths(r, 10))
print('target 3:', count_paths(r, 3))
print('target 0:', count_paths(r, 0))
|
Java | UTF-8 | 1,903 | 1.867188 | 2 | [] | no_license | package com.yipeng.bill.bms.dao;
import com.yipeng.bill.bms.domain.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Long id);
User selectByPrimaryKeySelective(User user);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
User selectByUserName(String userName);
List<User> selectList(int limit, int offset);
Long getUserListCount();
List<User> userCreater(Long createId);
/**
* 获取角色
*
* @param params
* @return
*/
List<User> getQueryUserAll(Map<String, Object> params);
/**
* 搜索框的客户
*
* @param userId
* @return
*/
List<User> getUserByCreateId(Long userId);
//待审核客户
List<User> selectByReviewUser(Map<String, Object> params);
//待审核客户数量
Long selectByReviewUserCount();
//用户权限
List<User> getUserRoleByCreateId(Map<String, Object> params);
//用户权限个数
Long getUserRoleByCreateIdCount(Map<String, Object> params);
List<User> getUserBillAscription(Map<String, Object> params);
Long getUserBillAscriptionCount(Map<String, Object> params);
List<User> getSearchUserBillAscription(Map<String, Object> params);
List<User> selectAllUsers(String role);
List<User> selectAddressee(String currentid);
//获取已开通权限的渠道商
List<User> selectDistributor();
//根据用户id得到角色名称
String selectRoleName(String currentId);
List<User> selectUserNameById(Map<String, Object> map);
List<Map<String, Object>> selectCustomer(Long userId);
//查询客户详细
List<Map<String, Object>> selectByCustomerList(Map<String, Object> params);
} |
Go | UTF-8 | 1,035 | 3.484375 | 3 | [] | no_license | import "math"
func nievePrimeSlice(n int) []int {
knownPrimes := []int{}
number := 2
var aux func(n int)
aux = func(n int) {
if n != 0 {
primeFound := true
for _, prime := range knownPrimes {
if float64(prime) > math.Sqrt(float64(number)) {
break
}
if number % prime == 0 {
primeFound = false
break
}
}
if primeFound {
knownPrimes = append(knownPrimes, number)
n -= 1
}
number += 1
aux(n)
}
}
aux(n)
return knownPrimes
}
func primesWhile(continueCondition func(int)bool, op func(int)) []int {
knownPrimes := []int{}
number := 2
var aux func()
aux = func() {
sqrtNum := math.Sqrt(float64(number))
primeFound := true
for _, prime := range knownPrimes {
if float64(prime) > sqrtNum {
break
}
if number % prime == 0 {
primeFound = false
break
}
}
if primeFound {
if !continueCondition(number) { return }
op(number)
knownPrimes = append(knownPrimes, number)
}
number += 1
aux()
}
aux()
return knownPrimes
}
|
Java | UTF-8 | 928 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | package org.ihiw.management.service.mapper;
import org.ihiw.management.domain.IhiwLab;
import org.ihiw.management.domain.User;
import org.ihiw.management.service.dto.LabDTO;
import org.ihiw.management.service.dto.UserDTO;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Mapper for the entity {@link User} and its DTO called {@link UserDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
* support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class LabMapper {
public List<LabDTO> labToLabDTO(List<IhiwLab> labs) {
return labs.stream()
.filter(Objects::nonNull)
.map(this::labToLabDTO)
.collect(Collectors.toList());
}
public LabDTO labToLabDTO(IhiwLab lab) {
return new LabDTO(lab);
}
}
|
C# | UTF-8 | 1,303 | 3.65625 | 4 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
namespace p0053MaximumSubarray.cs
{
public class Solution
{
public int MaxSubArray(int[] nums)
{
if (nums.All(num => num >= 0))
return nums.Sum();
else if (nums.All(num => num < 0))
return nums.Max();
else
{
int currentSum = 0;
int maxSum = nums[0];
for (int i = 0; i < nums.Length; i++)
{
currentSum += nums[i];
if (currentSum < 0)
currentSum = 0;
else
maxSum = currentSum > maxSum ? currentSum : maxSum;
}
return maxSum;
}
}
//O(n2)
/*
public int MaxSubArray(int[] nums)
{
int candidate = nums[0];
for (int i = 0; i < nums.Length; i++)
{
int sum = 0;
for (int j = i; j < nums.Length; j++)
{
sum += nums[j];
candidate = sum > candidate ? sum : candidate;
}
}
return candidate;
}
*/
}
}
|
PHP | UTF-8 | 4,158 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Actions;
use App\Calculator\CollectibleFoundCalculator;
use App\Calculator\WorkBuildingCalculator;
use App\Exceptions\GameException;
use App\Models\Character;
use App\Models\CharacterBuilding;
use App\Models\Item;
use Illuminate\Support\Facades\DB;
class WorkBuildingAction
{
use BuildingGuards;
use EnergyGuards;
use SupplyGuards;
public function __construct(
private WorkBuildingCalculator $calculator,
private CollectibleFoundCalculator $collectibleFoundCalculator,
)
{
}
public function __invoke(Character $character, string $buildingType): string
{
$this->guardAgainstInvalidBuildingType($buildingType);
$building = $character->getBuilding($buildingType);
$this->guardAgainstNonConstructedBuilding($character, $building, $buildingType);
$energyCost = $this->calculator->getEnergyCost($character, $buildingType);
$this->guardAgainstInsufficientEnergy($character, $energyCost);
/** @noinspection NullPointerExceptionInspection */
$this->guardAgainstWorkCooldown($building);
DB::transaction(function () use ($character, $buildingType, $building, $energyCost, &$supplyGains, &$collectibleFound, &$collectible) {
$character->energy -= $energyCost;
$character->addExperience($energyCost);
$character->save();
$supplyGains = $this->calculator->getSupplyGains($buildingType, $building->level, $building->getHealthPercentage());
foreach ($supplyGains as $supplyType => $amount) {
/** @var Item $itemType */
$itemType = Item::query()
->where('name', snake_case_to_words($supplyType)) // todo: I don't like this :( need slug or other identifier or sth
->firstOrFail();
if ($character->hasItem($itemType)) {
$characterItem = $character->items()
->where('name', snake_case_to_words($supplyType))
->firstOrFail();
$character->items()->updateExistingPivot($itemType, [
'qty' => $characterItem->pivot->qty + $amount,
]);
} else {
$character->items()->attach($itemType, [
'qty' => $amount,
]);
}
}
$collectible = Item::availableCollectible($character->location)->first();
if ($collectible) {
$collectibleFound = $this->collectibleFoundCalculator->calculateIfCollectibleIsFound($collectible);
if ($collectibleFound) {
$character->addCollectible($collectible);
session()->flash('collectibleStatus', "You managed to find a collectible: {$collectible->name}!");
}
}
$building->work_started_at = now();
$building->next_work_at = now()->addSeconds(
$this->calculator->getCooldownInSeconds($character, $building)
);
$building->save();
});
$buildingName = snake_case_to_words($buildingType);
$gainedSuppliesString = [];
foreach ($supplyGains as $supplyType => $amount) {
$supplyName = snake_case_to_words($supplyType);
$gainedSuppliesString[] = "{$amount} {$supplyName}";
}
$gainedSuppliesString = implode(', ', $gainedSuppliesString);
if ($collectibleFound) {
return "While working at the {$buildingName} you found a collectible: {$collectible->name} and gain {$gainedSuppliesString}.";
} else {
return "You work at the {$buildingName} and gain {$gainedSuppliesString}.";
}
}
private function guardAgainstWorkCooldown(CharacterBuilding $building): void
{
if (($building->next_work_at !== null) && ($building->next_work_at > now())) {
$buildingName = snake_case_to_words($building->type);
throw new GameException("You cannot work your {$buildingName} yet.");
}
}
}
|
Swift | UTF-8 | 260 | 3.46875 | 3 | [] | no_license | import UIKit
// 赋值运算符
let b = 10
var a = 5
a = b
// a 现在等于 10
let (x, y) = (1, 2)
// 现在 x 等于 1, y 等于 2
// 此句错误, 因为 x = y 并不返回任何值
//if x = y {
//
//}
// 复合赋值
var m = 1
m += 2 // m 现在是 3
|
Java | UTF-8 | 4,066 | 2.703125 | 3 | [] | no_license | package edudcball.wpi.users.enotesandroid.AsyncTasks;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import edudcball.wpi.users.enotesandroid.NoteManager.NoteManager;
import edudcball.wpi.users.enotesandroid.Settings;
/**
* An abstract class for managing communication with the enotes server
* Overrides AsyncTask
* Each subclass from this class should override onPostExecute to call the callback function
*/
public abstract class HttpConnectionTask extends AsyncTask<String, Integer, String> {
// URL of the server
protected static final String baseURL = Settings.baseURL;
protected static final String apiURL = "/api"; // path that all note requests are sent to
protected static final String COOKIES_HEADER = "Set-Cookie"; // header to look for new cookies to save
private static final int TIMEOUT = 5000; // Timeout time for connection in milliseconds
protected HttpURLConnection connection; // active http connection
/**
* Creates a connection with the server
* @param urlStr the path to connect to
* @param doInput true if the connection will expect a response
* @param doOutput true if the app will send a message to the server
* @param method HTTP method that will be used (GET, POST, PUT, or DELETE)
*/
protected void connect(String urlStr, boolean doInput, boolean doOutput, String method) throws Exception{
try {
// connect
URL url = new URL(baseURL + urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(TIMEOUT);
connection.setDoOutput(doOutput);
connection.setDoInput(doInput);
// add any cookies that are saved
if (NoteManager.getCookies().getCookies().size() > 0) {
connection.setRequestProperty("Cookie", TextUtils.join(";", NoteManager.getCookies().getCookies()));
}
// set method
connection.setRequestMethod(method);
}
catch(Exception e){
throw e;
}
}
/**
* Sends a message to the server
* @param msg the message to send
*/
protected void writeMessage(String msg) throws Exception{
try {
// fail if connection isnt open
if (connection == null) {
Log.d("ERROR", "No open connection");
throw new Exception("Lost connection to server.");
}
// Write message
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(msg);
out.close();
}catch(IOException e){
throw e;
}
}
/**
* Reads a response from the server
* @return the response body as a string
*/
protected String readResponse() throws Exception{
try {
// read until the message is finished
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String input;
String response = "";
while ((input = in.readLine()) != null) {
response += input;
}
in.close();
return response;
}
catch(IOException e){
throw e;
}
}
/**
* Save cookies set by the server
*/
protected void saveCookies(){
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
NoteManager.getCookies().add(null, HttpCookie.parse(cookie).get(0));
}
}
}
}
|
C# | UTF-8 | 3,393 | 2.53125 | 3 | [] | no_license | using DesktopApp.Reports;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DesktopApp
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO: Close the program/form
}
private void regionsToolStripMenuItem_Click(object sender, EventArgs e)
{
// TODO: Open a form as a dialog box
ViewRegions frm = new ViewRegions();
frm.ShowDialog(); // Execution of this method will PAUSE here until the dialog box (ViewRegions) is closed
// resume after the dialog box is closed
}
private void MainForm_Load(object sender, EventArgs e)
{
//Set the applications startup date/time in the status bar
StartTimeStatus.Text = "App Started on " + DateTime.Now.ToString();
}
private void productsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void shippersToolStripMenuItem_Click(object sender, EventArgs e)
{
LaunchOrActivate<ViewShippers>();
//ViewShippers shippersfrm = new ViewShippers();
//shippersfrm.MdiParent = this;
//shippersfrm.WindowState = FormWindowState.Maximized;
//shippersfrm.Show(); // we do NOT pause here as we show the form..
//MessageBox.Show("Here's the ViewShopper's Form");
}
private void customerOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void productSalesToolStripMenuItem_Click(object sender, EventArgs e)
{
LaunchOrActivate<ProductSalesForm>();
//ProductSalesForm frm = new ProductSalesForm();
//frm.MdiParent = this;
//frm.WindowState = FormWindowState.Maximized;
//frm.Show();
}
private void errorLogsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void aboutThisAppToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO: 1) Open the AboutApp form as a dialog window.
AboutApp aboutApp = new AboutApp();
aboutApp.ShowDialog();
}
#region Support Methods using C# Generics
private void LaunchOrActivate<T>() where T : Form, new()
{
T theForm = GetChildForm<T>();
if (theForm == null)
{
theForm = new T();
theForm.MdiParent = this;
theForm.WindowState = FormWindowState.Maximized;
theForm.Show();
}
else
{
theForm.WindowState = FormWindowState.Maximized;
theForm.Focus();
}
}
private T GetChildForm<T>() where T: Form
{
foreach (var childForm in MdiChildren)
{
if (childForm is T)
{
return (T)childForm;
}
}
return null;
}
#endregion
}
}
|
C# | UTF-8 | 2,164 | 2.8125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace MadeInHouse.Dictionary
{
class ExcelUtiles
{
private static string Path;
private static string constr;
public static DataTableReader Importar(string name)
{
BuscarPath();
MessageBoxResult r = MessageBox.Show("Desea Importar el Archivo ? \n" + Path, "Importar", MessageBoxButton.YesNo);
if (r == MessageBoxResult.Yes)
{
if (Path != "")
{
constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
DataTableReader ds = data.CreateDataReader();
return ds;
}
}
return null;
}
private static void BuscarPath()
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.xlsx)|*.xlsx";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
Path = filename;
}
}
}
}
|
JavaScript | UTF-8 | 858 | 3.1875 | 3 | [] | no_license | function solution(msg) {
let answer = [];
const dict = {};
let cnt = 26;
// 사전에 A ~ Z 등록
for(let i = 65; i <= 90; i++) {
dict[String.fromCharCode(i)] = i - 64;
}
const msgLen = msg.length;
for(let i = 0; i < msgLen;){ // msg의 첫번째 idx부터 끝까지
for(let j = msgLen; j >= i; j--){ // i번째 idx부터 j번째 idx까지의 부분문자열을 구한다
const substr = msg.substring(i,j);
if(dict[substr]) { // 부분문자열이 사전에 존재한다면
answer.push(dict[substr]);
const newstr = msg.substring(i,j+1); // 다음 글자를 포함한 부분문자열을 사전에 등록
dict[newstr] = ++cnt;
i += substr.length;
break;
}
}
}
return answer;
}
|
Java | UTF-8 | 1,641 | 2.890625 | 3 | [] | no_license | package Entities;
import Game.InputHandler;
import Game.Level;
import Game.Debugger;
import Graphics.Screen;
import Graphics.Colors;
import Graphics.Font;
import java.net.InetAddress;
import java.awt.Graphics;
/**
* Write a description of class PlayerMP here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class PlayerMP extends Player
{
public InetAddress ipAddress;
public int port;
private String username;
/**
* Constructor for objects of class PlayerMP
*/
public PlayerMP(Level level, int x, int y, InputHandler input, Screen screen, String name,
String username, InetAddress ipAddress, int port)
{
super(level, x, y, input, screen, name);
this.username = username;
this.ipAddress = ipAddress;
this.port = port;
Debugger.sendMsg(String.format("created a player at (%d, %d)", x, y));
}
public PlayerMP(Level level, int x, int y, Screen screen, String name,
String userName, InetAddress ipAddress, int port)
{
super(level, x, y, null, screen, name);
this.username = username;
this.ipAddress = ipAddress;
this.port = port;
}
public void render(Screen screen, Graphics g)
{
super.render(screen, g);
if(username != null)
Font.render(username, screen, x-4 -(username.length()-2)*8/2, y-22, Colors.get(-1,-1,-1,000), 1);
}
public String getUsername()
{
return username;
}
public void tick()
{
super.tick();
}
}
|
Python | UTF-8 | 1,061 | 3.203125 | 3 | [] | no_license | import random
import datetime
import time
def source(second=1):
while True:
yield {
'datetime': datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))),
'value': random.randint(1,100)
}
time.sleep(second)
def window(iterator, handler, width:int, interval:int):
start = datetime.datetime.strptime('20170101 000000 +0800', '%Y%m%d %H%M%S %z')
current = datetime.datetime.strptime('20170101 010000 +0800', '%Y%m%d %H%M%S %z')
buffer = []
delta = datetime.timedelta(seconds=width-interval)
while True:
data = next(iterator)
if data:
buffer.append(data)
current = data['datetime']
if (current-start).total_seconds() >= interval:
ret = handler(buffer)
print('{:.2f}'.format(ret))
start = current
buffer = [x for x in buffer if x['datetime'] > current - delta]
def handler(iterable):
return sum(map(lambda x:x['value'], iterable)) / len(iterable)
window(source(),handler,10,5) |
Markdown | UTF-8 | 1,674 | 2.625 | 3 | [] | no_license |
This is another of my big projects called Mini-Campaign. It showcases my ability to work more with redux-forms, and adds in elements that were not seen in previous projects.
In this coding masterpiece I work with Google OAuth, Stripe payments, and the Send Grid API. Basically, it allows you to send large survey emails to as many people as you want using the SendGrid API. Because i have to pay...the feedback from the surveys (WebHook data) is not hooked up. Mayber in the future I will hook it up, however, you can receive feedback from your surveys.
This Web Application is currently hosted on Heroku:
https://ancient-plateau-92232.herokuapp.com/ ... check it out
Best regards,
Noah Kreiger
## HTTP is stateless, which is why we need redux to keep the state, for example to know that a user is still logged in
## MongoDB Storage
Collections -> Mongoose Model Class includes an entire collection
* User -> profile... -> Model Instance
* Posts -> Model Instance
* Payments -> Model Instance
one class is one collection
one instance is one component of collection
# schemaless, so inside every collection, each part can have different properties instead of the exact same in other databases like mysql...
## REDUX EXPLANATION
Redux is all about holding all the state or data inside of our application
Redux Store => // where all of our state exists
// we call an action in an action creator to change our state which dispatches an action that is then sent to all of our reducers which are combined to use to update the state in our redux store causing them to re-render
CombineReducers = 1. authReducer 2. surveysReducer
|
C++ | UTF-8 | 666 | 2.953125 | 3 | [] | no_license | /***************************************************************
dfs序
其实就是从根节点进行搜索,
然后向下dfs遍历树,依次进行编号,
同时能保证子树的编号一定大于父节点的编号,
同时借用两个数组,L[_],R[_]
分别表示这个节点u的子树的节点编号在(L[u],R[u]),开区间内。
这样在进行对子树进行的操作的时候可以借助数据结构对区间进行查找,
***************************************************************/
vector<int >G[N];
int cnt = 0;
void dfs(int u,int f){
L[u]=cnt++;
for(int i=0;i<G[u].size();i++)if(G[u][i]!=f)
dfs(G[u][i]);
R[u]=cnt;
} |
C | UTF-8 | 2,484 | 2.578125 | 3 | [] | no_license | #include <stddef.h>
#include <stdint.h>
#include <stdio.h>
/* int t[] = { */
/* #define B1(x) x, !x, !x, x */
/* #define B2(x) B1(x), B1(!x), B1(!x), B1(x) */
/* #define B3(x) B2(x), B2(!x), B2(!x), B2(x) */
/* #define B4(x) B3(x), B3(!x), B3(!x), B3(x) */
/* B4(0) */
/* } */
/* */
/* */
/* int t[] = { */
/* #define B1(x) x, !x, !x, x */
/* #define B2(x) B1(+x), B1(!x), B1(!x), B1(+x) */
/* #define B3(x) B2(+x), B2(!x), B2(!x), B2(+x) */
/* #define B4(x) B3(+x), B3(!x), B3(!x), B3(+x) */
/* B4(0) */
/* } */
#define SBI(x, n) ((x) | (1 << n))
#define CBI(x, n) ((x) & ~(1 << n))
#define GET(x, n) (((x) & (1 << n)) >> n)
// **********************************
#define FORALL(GEN) \
GEN(u8, uint8_t) \
GEN(u16, uint16_t) \
GEN(u32, uint32_t) \
GEN(u64, uint64_t)
#define GENERIC_FORALL(prefix, x) \
_Generic(x, \
uint8_t: prefix##_u8, \
uint16_t: prefix##_u16, \
uint32_t: prefix##_u32, \
uint64_t: prefix##_u64)(x)
// **********************************
#define DEF_POPCNT(suffix, type) \
int popcnt_##suffix(type x) { \
size_t n = sizeof(x); \
int cnt = 0; \
while (n--) { \
cnt += GET(x, n); \
} \
\
return cnt; \
}
// *********************************
#define popcnt(x) GENERIC_FORALL(popcnt, x)
FORALL(DEF_POPCNT);
// 1.
#define MOCNINA2(x) ({ int cnt = popcnt(x); cnt == 0 || cnt == 1; })
uint8_t tab[] = {
0xF, 0xE, 0xD, 0xC, 0xB, 0xA, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
};
// 2.
uint8_t zrcadleni(uint8_t x) {
uint8_t res = 0;
res |= tab[(x & 0x0F)] << 4;
res |= tab[(x & 0xF0) >> 4];
return res;
}
// 3.
#define P2(x) (((x) & 0b01) ^ (((x) & 0b10) >> 1))
#define P4(x) P2 (((x) & 0b11) ^ (((x) & 0b1100) >> 2))
#define P8(x) P4 (((x) & 0xf) ^ (((x) & 0xf0) >> 4))
#define P16(x) P8 (((x) & 0xff) ^ (((x) & 0xff00) >> 8))
#define P32(x) P16(((x) & 0xffff) ^ (((x) & 0xffff0000) >> 16))
// nebo posunu o 1 doprava a vyxorim
// pak posunu o 2 doprava a vyxorim
// pak posunu o 4 doprava a vyxorim
/* uint32_t parita(uint32_t x) { */
/* (x & 0xffff) ^ ((x & 0xffff0000) >> 16) */
/* } */
int main() {
int x = SBI(8, 2);
int y = CBI(6, 2);
printf("%x, %x", 123, zrcadleni(123));
for (uint32_t i = 0; i < 10; i++) {
printf("%d, je mocnina 2: %d, parita: %d\n", i, MOCNINA2(i), P32(i));
}
printf("%d\n", popcnt(7u));
}
|
Java | UTF-8 | 417 | 2.5625 | 3 | [] | no_license | package net.game.playstaff;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* @author Olga_Zlobina
*/
public class PlayerATest{
private static final int rounds = 100;
@Test
public void playTest() {
Player playerA = new PlayerA();
for (int i=0;i<rounds;i++) {
assertEquals(playerA.play(), FigureType.PAPER);
}
}
}
|
Ruby | UTF-8 | 928 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | module Moonshot
module Plugins
class DynamicTemplate
def initialize(source:, parameters:, destination:)
@dynamic_template = ::Moonshot::DynamicTemplate.new(
source: source,
parameters: parameters,
destination: destination
)
end
def run_hook
@dynamic_template.process
end
def cli_hook(parser)
parser.on('-sPATH', '--destination-path=PATH',
'Destination path for the dynamically generated template', String) do |value|
@dynamic_template.destination = value
end
end
# Moonshot hooks to trigger this plugin.
alias setup_create run_hook
alias setup_update run_hook
alias setup_delete run_hook
# Moonshot hooks to add CLI options.
alias create_cli_hook cli_hook
alias delete_cli_hook cli_hook
alias update_cli_hook cli_hook
end
end
end
|
Python | UTF-8 | 1,288 | 3.125 | 3 | [] | no_license | from matplotlib import pyplot
import numpy as np
# x = (c-b*y)/a
def f(x, c1, c2, b):
return (b - c1*x)/c2
def graficar(k, solucion):
n = 2
fig, (ax, tabax) = pyplot.subplots(nrows=2)
# Definiciones para la gráfica
x = np.arange(0.0, 2.0, 0.01)
i = 0
while i < n:
y = f(x, k[i][0], k[i][1], k[i][2])
ax.plot(x, y)
i += 1
#y1 = f(x, k[0][0], k[0][1], k[0][2])
#ax.plot(x, y1)
#y2 = f(x, k[1][0], k[1][1], k[1][2])
#ax.plot(x, y2)
#y3 = f(x, k[2][0], k[2][1], k[2][2])
#ax.plot(x, y3)
# Marcamos el optimo
ax.plot([solucion[1]], [solucion[2]], marker='o', markersize=3, color="red")
# Titulo de la gráfica
s = "{0} | Z = {1} | x1 = {2} | x2 = {3}".format(solucion[3], solucion[0], solucion[1], solucion[2])
ax.set_title(s)
# Definiciones para la tabla
columns = ("x1", "x2", "x3", "x4", "x5", "z")
rows = ["A", "B", "C"]
data = [
[11, 12, 13, 14, 15, "z1"],
[21, 22, 23, 24, 25, "z2"],
[31, 32, 33, 34, 35, "z3"]
]
tabax.axis("off")
tabax.table(cellText=data, rowLabels=rows, colLabels=columns, loc="center") #, bbox=[0.0,-0.5,1,0.3])
pyplot.tight_layout()
pyplot.show()
|
C# | UTF-8 | 989 | 2.6875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleTaskManagerWpf.Models
{
public class TaskManagerProcess
{
public string TMProcessId { get; set; }
public string TMProcessName { get; set; }
public string TMProcessCpuUsage { get; set; }
public string TMProcessMemoryUsage { get; set; }
public string TMPriority { get; set; }
public string TMPath { get; set; }
public TaskManagerProcess()
{
TMProcessId = "Process Id";
TMProcessName = "Process Name";
TMProcessCpuUsage = "Cpu Usage";
TMProcessMemoryUsage = "Memory Usage";
TMPriority = "Priority";
TMPath = "Path";
}
public override string ToString()
{
return TMProcessId + TMProcessName + TMProcessCpuUsage + TMProcessMemoryUsage + TMPriority + TMPath;
}
}
}
|
Java | UTF-8 | 780 | 1.945313 | 2 | [] | no_license | package com.katkada.Activity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.katkada.GetDataUsage.Fragment.ProcessListFragment;
import com.katkada.R;
public class MyDataUsage extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_data_usage);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_root, new ProcessListFragment()).commit();
}
}
|
Java | UTF-8 | 1,904 | 2.359375 | 2 | [] | no_license | package com.cabbage.sdpjournal.Model;
import java.util.Random;
/**
* Created by Junwen on 30/8/17.
*/
public class Constants {
//Database
public final static String Users_End_Point = "users";
public final static String Entries_End_Point = "entries";
public final static String Journals_End_Point = "journals";
public final static String Attachments_End_Point = "attachments";
//User
public static final String AUTH_IN = "onAuthStateChanged:signed_in:";
public static final String AUTH_OUT = "onAuthStateChanged:signed_out";
//other Strings
public static final String Reset_Password = "Reset Password";
public static final String journalID = "journalID";
public static final String Default_Color = "defualt";
public static final String Select_Color = "Select your cover color";
public static final String New_Journal = "New Journal";
//entry status
public static final String Entry_Status_Normal = "normal";
public static final String Entry_Status_Hidden = "hidden";
public static final String Entry_Status_Deleted = "deleted";
public static final String Entry_Status_Modified = "modified";
//gallery
public static final int Gallery_Request = 1;
//some helper functions
public String randomString(){
Random gen = new Random(474587); //put in random seed
int min = 6;
int max = 10;
// we want 20 random strings
int len = min+gen.nextInt(max-min+1);
StringBuilder s = new StringBuilder(len);
for(int i=0; i < 20; i++){
while(s.length() < len){
//97 is ASCII for character 'a', and 26 is number of alphabets
s.append((char)(97+gen.nextInt(26)));
}
}
return s.toString();
}
public long removeLastNDigits(long x, long n) {
return (long) (x / Math.pow(10, n));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.