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
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 2,079 | 4.34375 | 4 |
[
"Giftware"
] |
permissive
|
# Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recursive solutions will not be
accepted.
Returns: a list of all permutations of sequence
Example:
>>> get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Note: depending on your implementation, you may return the permutations in
a different order than what is listed here.
'''
# if string list is 1, return single character
if len(sequence) == 1:
return [sequence]
# create empty list
perm_list = []
# slice list from 2nd character to end
for permutation in get_permutations(sequence[1:]):
# iterate through each character in string
for index in range(len(sequence)):
# assemble permutation list
perm_list.append(permutation[:index] + sequence[0:1] + permutation[index:])
# pass list to next function call or return result
return perm_list
if __name__ == '__main__':
# #EXAMPLE
# example_input = 'abc'
# print('Input:', example_input)
# print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
# print('Actual Output:', get_permutations(example_input))
# Test cases
example_1 = "cat"
print("Input:", example_1)
print("Expected Output:", ['cat', 'act', 'atc', 'cta', 'tca', 'tac'])
print("Actual Output:", get_permutations(example_1))
example_2 = "tag"
print("Input:", example_2)
print("Expected Output:", ['tag', 'tga', 'atg', 'agt', 'gta', 'gat'])
print("Actual Output:", get_permutations(example_2))
example_3 = "bad"
print("Input:", example_3)
print("Expected Output:", ['bad', 'bda', 'abd', 'adb', 'dab', 'dba'])
print("Actual Output:", get_permutations(example_3))
|
Swift
|
UTF-8
| 3,274 | 2.6875 | 3 |
[] |
no_license
|
//
// collect.swift
// TestProject
//
// Created by Anysa Manhas on 2018-10-24.
// Copyright © 2018 Anysa Manhas. All rights reserved.
import Foundation
import CoreMotion
class DataRun {
let motionManager : CMMotionManager
fileprivate var rot_rate : [(Double, Double, Double)] = []
fileprivate var user_accel: [(Double, Double, Double)] = []
fileprivate var rot_curr: (Double, Double, Double) = (0,0,0)
fileprivate var accel_curr: (Double, Double, Double) = (0,0,0)
fileprivate var isSuspended : Bool = false
fileprivate var dataTimer: Timer!
fileprivate var data_timestamp : Date?
//MARK: Public
init()
{
motionManager = CMMotionManager()
initMotionEvents()
}
func config() //refresh rate, reinit timer
{
// not sure if this is needed?
}
func suspend()
{
isSuspended = true
}
func resume()
{
isSuspended = false
}
func start() //start the timer
{
data_timestamp = Date()
dataTimer = Timer.scheduledTimer(timeInterval: 1.0/100.0, target: self, selector: #selector(DataRun.get_data), userInfo: nil, repeats: true)
}
func end() //stop timer, write to DB
{
dataTimer.invalidate()
}
func return_accel() -> [(Double, Double, Double)]//function so that accel data can be accessed after a run
{
let rtn_accel = user_accel;
return rtn_accel
}
func return_rotation() -> [(Double, Double, Double)]//function so that rotation data can be accessed after a run
{
let rtn_gyro = rot_rate;
return rtn_gyro
}
func get_last_entry() -> [(Double, Double, Double)]{
var rtn_val:[(Double, Double, Double)] = [];
rtn_val.append(accel_curr);
rtn_val.append(rot_curr);
return rtn_val
}
//MARK: Private
fileprivate func initMotionEvents()
{
//make sure deviceMotion is available
//initialize deviceMotion parameters
if motionManager.isDeviceMotionAvailable
{
self.motionManager.deviceMotionUpdateInterval = 1.0 / 100.0 //frequency of 100 Hz
self.motionManager.showsDeviceMovementDisplay = true //for now (testing purposes)
//not sure if we need a reference frame???
self.motionManager.startDeviceMotionUpdates(using: .xMagneticNorthZVertical)
}
else
{
print("deviceMotion not available")
}
}
@objc fileprivate func get_data() //gets sensor data when not suspended, push to array
{
if let data = self.motionManager.deviceMotion
{
//print("getTimer: %lf,%lf,%lf\n", data.userAcceleration.x, data.userAcceleration.y, data.userAcceleration.z)
accel_curr = (data.userAcceleration.x, data.userAcceleration.y, data.userAcceleration.z)
rot_curr = (data.rotationRate.x, data.rotationRate.y, data.rotationRate.z)
user_accel.append((data.userAcceleration.x, data.userAcceleration.y, data.userAcceleration.z))
rot_rate.append((data.rotationRate.x, data.rotationRate.y, data.rotationRate.z))
}
}
}
|
Python
|
UTF-8
| 166 | 2.96875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
n=int(input('n:'))
soma=0
for i in range(1,n+1,1):
idade=int(input('idade:'))
soma=soma+idade
media=soam/n
print('%.2f' % media)
|
C#
|
UTF-8
| 1,056 | 3.546875 | 4 |
[] |
no_license
|
using System;
using System.Linq;
namespace QuestionOne
{
class Program
{
public static Func<int, bool> isEven = (i) => i % 2 == 0;
public static Func<int[], int> howManyEvens = (l) => l.Count(i => i % 2 == 0);
static void Main(string[] args)
{
int[] arr = new int[] { 1,2,3,4,5,6,7,8,9,10 };
// Console.WriteLine(howManyEvens(arr));
Console.WriteLine(howManyEvensRec(arr,0));
// Console.WriteLine(howManyEvensFiltEq(arr, isEven));
Console.WriteLine(arr.Where(i => isEven(i)).Count());
// Console.WriteLine(arr.Where(i => i % 2 == 0).Select(i => i ).Count());
Console.WriteLine(arr.Select(i => i % 2 == 0 ? 1 : 0).Sum());
}
public static int howManyEvensRec(int[] array, int n) =>
array.Length == 0 ? n : howManyEvensRec(array.Skip(1).ToArray(), array[0] % 2 == 0 ? 1 +n : n);
public static int howManyEvensFiltEq(int[] array, Func<int, bool> pred) => array.Count(i => pred(i));
}
}
|
Java
|
UTF-8
| 3,211 | 2.28125 | 2 |
[] |
no_license
|
package com.isp.controller;
import com.isp.entity.License;
import com.isp.entity.School;
import com.isp.service.SchoolsService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Geminit
* @create 2016-9-12
*/
@Controller
@RequestMapping("/isp")
public class SchoolsController {
//添加一个日志器
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(IndexController.class);
@Autowired
private SchoolsService schoolsService;
//映射一个action
@RequestMapping("/schools")
public String schools(Model model, HttpServletRequest request){
//输出日志文件
logger.info("Visit page Schools.");
List<Map> goodSchoolList = new ArrayList<Map>();
Map map;
int totle = schoolsService.getGoodSchoolNumber();
List<School> schools = schoolsService.getGoodSchoolByPage(1);
for(int i = 0; i<schools.size(); i++){
map = new HashMap();
map.put("schoolId",schools.get(i).getId());
map.put("schoolName",schools.get(i).getName());
goodSchoolList.add(map);
}
model.addAttribute("goodSchoolList", goodSchoolList);
model.addAttribute("totle", totle);
model.addAttribute("page", 1);
model.addAttribute("pages", (totle/10)+1);
//返回一个index.jsp这个视图
return "schools";
}
//映射一个action
@RequestMapping("/toSchools")
public String toSchools(Model model, HttpServletRequest request){
//输出日志文件
logger.info("Visit page Schools.");
int page = Integer.parseInt(request.getParameter("page"));
List<Map> goodSchoolList = new ArrayList<Map>();
Map map;
int totle = schoolsService.getGoodSchoolNumber();
List<School> schools = schoolsService.getGoodSchoolByPage(page);
for(int i = 0; i<schools.size(); i++){
map = new HashMap();
map.put("schoolId",schools.get(i).getId());
map.put("schoolName",schools.get(i).getName());
goodSchoolList.add(map);
}
model.addAttribute("goodSchoolList", goodSchoolList);
model.addAttribute("totle", totle);
model.addAttribute("page", page);
model.addAttribute("pages", (totle/10)+1);
//返回一个index.jsp这个视图
return "schools";
}
//映射一个action
@RequestMapping("/toSchool")
public String toSchool(Model model, HttpServletRequest request){
//输出日志文件
logger.info("Visit page school.");
int schoolId = Integer.parseInt(request.getParameter("id"));
School school = schoolsService.getSchoolById(schoolId);
model.addAttribute("school",school);
//返回一个index.jsp这个视图
return "school";
}
}
|
Markdown
|
UTF-8
| 1,371 | 3.84375 | 4 |
[] |
no_license
|
An integer N is given, representing the area of some rectangle.
The area of a rectangle whose sides are of length A and B is A * B, and the perimeter is 2 * (A + B).
The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers.
For example, given integer N = 30, rectangles of area 30 are:
(1, 30), with a perimeter of 62,
(2, 15), with a perimeter of 34,
(3, 10), with a perimeter of 26,
(5, 6), with a perimeter of 22.
Write a function:
function solution(N);
that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N.
For example, given an integer N = 30, the function should return 22, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..1,000,000,000].
```javascript
function solution(N) {
// write your code in JavaScript (Node.js 8.9.4)
let per = 0;
let min_per = 2*(1 + N);
let A = 1;
for(let A = 1; A < N / 2; A++){
let B = N / A;
if(Number.isInteger(B)){
// console.log('B = ', B)
per = 2*(A + B);
if(min_per > per){
min_per = per;
}
}
if(A > B) return min_per;
}
// console.log('per = ', per, 'min per = ', min_per)
return min_per;
}
```
|
Java
|
UTF-8
| 6,431 | 1.703125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.sas.transform.v20181203;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.sas.model.v20181203.DescribeContainerInstancesResponse;
import com.aliyuncs.sas.model.v20181203.DescribeContainerInstancesResponse.ContainerInstance;
import com.aliyuncs.sas.model.v20181203.DescribeContainerInstancesResponse.PageInfo;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeContainerInstancesResponseUnmarshaller {
public static DescribeContainerInstancesResponse unmarshall(DescribeContainerInstancesResponse describeContainerInstancesResponse, UnmarshallerContext _ctx) {
describeContainerInstancesResponse.setRequestId(_ctx.stringValue("DescribeContainerInstancesResponse.RequestId"));
PageInfo pageInfo = new PageInfo();
pageInfo.setCurrentPage(_ctx.integerValue("DescribeContainerInstancesResponse.PageInfo.CurrentPage"));
pageInfo.setPageSize(_ctx.integerValue("DescribeContainerInstancesResponse.PageInfo.PageSize"));
pageInfo.setTotalCount(_ctx.integerValue("DescribeContainerInstancesResponse.PageInfo.TotalCount"));
pageInfo.setCount(_ctx.integerValue("DescribeContainerInstancesResponse.PageInfo.Count"));
describeContainerInstancesResponse.setPageInfo(pageInfo);
List<ContainerInstance> containerInstanceList = new ArrayList<ContainerInstance>();
for (int i = 0; i < _ctx.lengthValue("DescribeContainerInstancesResponse.ContainerInstanceList.Length"); i++) {
ContainerInstance containerInstance = new ContainerInstance();
containerInstance.setImageRepoTag(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ImageRepoTag"));
containerInstance.setAppName(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].AppName"));
containerInstance.setPodIp(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].PodIp"));
containerInstance.setVulCount(_ctx.integerValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].VulCount"));
containerInstance.setHcStatus(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].HcStatus"));
containerInstance.setImageId(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ImageId"));
containerInstance.setClusterId(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ClusterId"));
containerInstance.setImageRepoName(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ImageRepoName"));
containerInstance.setHostIp(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].HostIp"));
containerInstance.setPod(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].Pod"));
containerInstance.setRiskStatus(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].RiskStatus"));
containerInstance.setVulStatus(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].VulStatus"));
containerInstance.setAlarmStatus(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].AlarmStatus"));
containerInstance.setImage(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].Image"));
containerInstance.setImageRepoNamespace(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ImageRepoNamespace"));
containerInstance.setImageDigest(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ImageDigest"));
containerInstance.setNamespace(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].Namespace"));
containerInstance.setInstanceId(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].InstanceId"));
containerInstance.setNodeInfo(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].NodeInfo"));
containerInstance.setImageUuid(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ImageUuid"));
containerInstance.setRegionId(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].RegionId"));
containerInstance.setUpdateMark(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].UpdateMark"));
containerInstance.setContainerId(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ContainerId"));
containerInstance.setNodeName(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].NodeName"));
containerInstance.setHcCount(_ctx.integerValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].HcCount"));
containerInstance.setClusterName(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ClusterName"));
containerInstance.setRiskCount(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].RiskCount"));
containerInstance.setAlarmCount(_ctx.integerValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].AlarmCount"));
containerInstance.setCreateTimestamp(_ctx.longValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].CreateTimestamp"));
containerInstance.setExposed(_ctx.integerValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].Exposed"));
containerInstance.setExposedDetail(_ctx.stringValue("DescribeContainerInstancesResponse.ContainerInstanceList["+ i +"].ExposedDetail"));
containerInstanceList.add(containerInstance);
}
describeContainerInstancesResponse.setContainerInstanceList(containerInstanceList);
return describeContainerInstancesResponse;
}
}
|
JavaScript
|
UTF-8
| 778 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
SessionVar = function(key, initialValue){
if (! (this instanceof SessionVar))
// called without `new`
return new SessionVar(key, initialValue);
this.key = key;
// check if already defined
if( SessionVar.keys.indexOf(key) !== -1 )
console.warn('SessionVar(' + key + ') defined twice!');
SessionVar.keys.push(key);
// set initial value
if( typeof initialValue !== 'undefined' && typeof this.get() === 'undefined' )
this.set(initialValue);
}
SessionVar.prototype.get = function (){
return Session.get(this.key);
}
SessionVar.prototype.set = function (value){
return Session.set(this.key, value);
}
SessionVar.prototype.toString = function () {
return 'SessionVar{' + this.get() + '}';
};
SessionVar.keys = [];
|
Java
|
UTF-8
| 3,199 | 1.882813 | 2 |
[] |
no_license
|
package br.com.j4business.saga.fornecedorcontrato.repository;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import br.com.j4business.saga.contrato.model.Contrato;
import br.com.j4business.saga.fornecedor.model.Fornecedor;
import br.com.j4business.saga.fornecedorcontrato.model.FornecedorContrato;
@Repository("fornecedorContratoRepository")
public interface FornecedorContratoRepository extends PagingAndSortingRepository<FornecedorContrato, Long>{
/* @Query("SELECT ea FROM FornecedorContrato ea where ea.contrato.contratoPK = :id")
List<FornecedorContrato> findByContratoPK(@Param("id") Long id);
*/
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.contrato p WHERE p = :contrato")
public List<FornecedorContrato> findByContrato(@Param("contrato")Contrato contrato);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.contrato p INNER JOIN ep.fornecedor e WHERE p = :contrato AND s = :fornecedor")
public FornecedorContrato findByFornecedorAndContrato( @Param("fornecedor") Fornecedor fornecedor, @Param("contrato")Contrato contrato);
@Query("SELECT ep FROM FornecedorContrato ep")
public List<FornecedorContrato> findFornecedorContratoAll(Pageable pageable);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.fornecedor e WHERE e.pessoaPK = :fornecedorPK")
public List<FornecedorContrato> findByFornecedorPK(@Param("fornecedorPK")long fornecedorPK,Pageable pageable);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.contrato p WHERE p.contratoPK = :contratoPK")
public List<FornecedorContrato> findByContratoPK(@Param("contratoPK")long contratoPK,Pageable pageable);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.fornecedor e WHERE e.pessoaPK = :fornecedorPK")
public List<FornecedorContrato> findByFornecedorPK(@Param("fornecedorPK")long fornecedorPK);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.contrato p WHERE p.contratoPK = :contratoPK")
public List<FornecedorContrato> findByContratoPK(@Param("contratoPK")long contratoPK);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.fornecedor e WHERE e.pessoaNome like :fornecedorNome%")
public List<FornecedorContrato> findByFornecedorNome(@Param("fornecedorNome")String fornecedorNome,Pageable pageable);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.contrato p WHERE p.contratoNome like :contratoNome%")
public List<FornecedorContrato> findByContratoNome(@Param("contratoNome")String contratoNome,Pageable pageable);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.fornecedor e WHERE e.pessoaNome like :fornecedorNome%")
public List<FornecedorContrato> findByFornecedorNome(@Param("fornecedorNome")String fornecedorNome);
@Query("SELECT ep FROM FornecedorContrato ep INNER JOIN ep.contrato p WHERE p.contratoNome like :contratoNome%")
public List<FornecedorContrato> findByContratoNome(@Param("contratoNome")String contratoNome);
}
|
Java
|
UTF-8
| 348 | 3.03125 | 3 |
[] |
no_license
|
package com.maurofokker.design.patterns.creational.abstractfactory.products;
/**
* Concrete Product
*/
public class CaliforniaOilSauce implements Sauce {
public CaliforniaOilSauce() {
prepareSauce();
}
@Override
public void prepareSauce() {
System.out.println("Preparing california oil sauce type...");
}
}
|
Java
|
UTF-8
| 1,516 | 2.3125 | 2 |
[] |
no_license
|
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.filewatch;
import org.gradle.api.file.DirectoryTree;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Implementation of {@link FileWatchInputs}
*/
public class DefaultFileWatchInputs implements FileWatchInputs {
Set<DirectoryTree> directories = new LinkedHashSet<DirectoryTree>();
Set<File> files = new LinkedHashSet<File>();
@Override
public FileWatchInputs watch(DirectoryTree directoryTree) {
directories.add(directoryTree);
return this;
}
@Override
public FileWatchInputs watch(File file) {
files.add(file.getAbsoluteFile());
return this;
}
@Override
public Collection<DirectoryTree> getDirectoryTrees() {
return directories;
}
@Override
public Collection<File> getFiles() {
return files;
}
}
|
Java
|
UTF-8
| 343 | 1.867188 | 2 |
[] |
no_license
|
package com.lz.mapper;
import com.lz.entity.Product;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CartMapper {
List<Product> list(int uid);
void add(@Param("uid") int uid,@Param("pid") int pid, @Param("quantity") int quantity);
void delete (@Param("uid") int uid,@Param("pid") int pid);
}
|
Shell
|
ISO-8859-4
| 17,223 | 3.46875 | 3 |
[] |
no_license
|
##############################
# PsyTools #
# #
# Copyright 2006-2008 Psyjo #
##############################
#
# Parts by Gentoo Foundation
#
# Distributed under the terms of the GNU General Public License v2
#:begin_version
#Version 1.2.9
#:end_version
#!begin_version
#Version 1.2.9
#!end_version
#Variablen:
#
# VERBOSE - grosszuegige Ausgaben der Psytools aktivieren
# Jrun_Debug - Debugmodus von jrun aktivieren
# JRUN_PARAMETER- Argumente bei dem Aufruf der tmp-Funktion in jrun
# FORCE - Erzwingt das Ueberschreiben von Dateien in jinstall
#
# monochrom is bloed ;)
# deswegen hier ein paar Farben by Gentoo
GOOD=$'\e[32;01m'
GREEN=$'\e[32;01m'
WARN=$'\e[33;01m'
YELOW=$'\e[33;01m'
BAD=$'\e[31;01m'
RED=$'\e[31;01m'
HILITE=$'\e[36;01m'
HIBLUE=$'\e[36;01m'
BRACKET=$'\e[34;01m'
BLUE=$'\e[34;01m'
NORMAL=$'\e[0m'
jline() # Linie ueber volle Shellbreite | $1 leerzeile vor line, $2 leerzeile nach line
{
getcols
[[ $1 ]] && echo
for (( n = 0; n < ${COLS}; n++ )); do echo -n -; done; echo
[[ $2 ]] && echo
}
inline() # beginnt einen vorgang in Linien | anzeige wenn $VERBOSE
{
[[ $VERBOSE ]] && jline "x"
jbegin "$*"
[[ $VERBOSE ]] && jline "" "x"
}
still() # fuehrt $* &> /dev/null aus | anzeige wenn $VERBOSE
{
if [ $VERBOSE ] || [ ${Jrun_Debug} ]
then eval "$*"
else eval "$*" &> /dev/null
fi
}
jinfo() # original by Gentoo Foundation modded by Psyjo
{
jinfon "$*\n"
LAST_CMD="jinfo"
return 0
}
jinfon()# original by Gentoo Foundation modded by Psyjo
{
[[ ${LAST_CMD} == "jbegin" ]] && echo
echo -ne " ${GOOD}*${NORMAL} $*"
LAST_CMD="jinfon"
return 0
}
jwarn()# original by Gentoo Foundation modded by Psyjo
{
[[ ${LAST_CMD} == "jbegin" ]] && echo
echo -e " ${WARN}*${NORMAL} $*"
LAST_CMD="jwarn"
return 0
}
jerror()# original by Gentoo Foundation modded by Psyjo
{
[[ ${LAST_CMD} == "jbegin" ]] && echo
echo -e " ${BAD}*${NORMAL} $*"
return 0
}
jexit()
{
jerror "$*"
exit
}
jbegin() #beginnt einen Vorgang # original by Gentoo Foundation modded by Psyjo
{
msg="$* ..."
jinfon "${msg}"
echo
LAST_LEN="$(( 3 + ${#msg} ))"
LAST_CMD="jbegin"
return 0
}
# private
_end() ## original by Gentoo Foundation modded by Psyjo
{
getcols
local retval="${1:-0}" efunc="${2:-eerror}" msg
shift 2
if [[ ${retval} == "0" ]] ; then
msg="${BRACKET}[ ${GOOD}ok${BRACKET} ]${NORMAL}"
else
if [[ -n $* ]] ; then
${efunc} "$*"
fi
msg="${BRACKET}[ ${BAD}!!${BRACKET} ]${NORMAL}"
fi
echo -e "${ENDLN} ${msg}"
return ${retval}
}
# less private
_jend() # beendet einen Vorgang # original by Gentoo Foundation modded by Psyjo
{
local retval="${1:-0}"
shift
_end "${retval}" jerror "$*"
LAST_CMD="jend"
return ${retval}
}
jend(){ _jend $?; } # beendet einen Vorgang mit stderr-auswertung
jwend()# original by Gentoo Foundation modded by Psyjo
{
local retval="${1:-0}"
shift
_end "${retval}" jwarn "$*"
LAST_CMD="jwend"
return ${retval}
}
############ selftest ####
tt()
{
for Tool in `echo $* | tr "," "\n"`; do
if ! which "${Tool}" &> /dev/null
then
jwarn "${BAD} tt: Tool \"${Tool}\" nicht gefunden !${NORMAL}"
_TT_ERROR=1
fi
done
return ${_TT_ERROR}
}
# sicherstellen das FreeBSD GNU Getopt benutzt
[[ "$(uname -s)" == "FreeBSD" ]] && getopt() { /usr/local/bin/getopt "$@"; }
[[ "$1" == "selftest" ]]&&{
which echo &> /dev/null || jexit "error loading PsyTools (cannot find echo)"
which tr &> /dev/null || jexit "error loading PsyTools (cannot find tr)"
[[ "$(getopt 2> /dev/null)" == " --" ]] && jexit "error loading PsyTools (cannot find GNU getopt)"
tt cat,tail,head,stty,grep,sed,rm,wc,cp,chmod,date,printf || jexit "unable to locate neccesary files, exit"
}
############ /selftest ####
tab() { echo -en "\t"; }
warnsig() { echo -e "${BRACKET}[ ${BAD}!!${BRACKET} ]${NORMAL}"; }
kaysig() { echo -e "${BRACKET}[ ${GOOD}OK${BRACKET} ]${NORMAL}"; }
jgetline() # <int> <file/vari>
{
[[ ! `echo $1 | sed 's/^[^0-9]*$//g'` ]] && jerror "Zielennummer muss ${BAD}integer${NORMAL} sein" && return 1
if [[ -r $2 ]];then
sed -n "$1p" $2
else
echo -e "$2" | sed "$2p" || echo -e "${BAD}jgetline: fixme!${NORMAL}"
fi
unset FILE
}
fex() # <file> <comment> # fehler wenn datei nicht vorhanden
{
if [[ ! -e $1 ]]
then
jerror "$2 Datei $1 existiert nicht!"
return 1
else
return 0
fi
}
xor() # return 0 wenn 1 parameter uebergeben wird z.B. <leer> <!leer> <leer>
{
if [ $# -eq 1 ]
then return 0;else return 1;
fi
}
xnor() # return 0 wenn nicht 1 parameter uebergeben wird z.B. <leer> <!leer> <!leer>
{
if [ $# -ne 1 ]
then return 0;else return 1;
fi
}
getcols() # Shellbreite in $COLS; Escapesequenz ENDLN (an zeilenende -8 springen)
{
COLS="${COLUMNS:-0}" # bash's internal COLUMNS variable
(( COLS == 0 )) && COLS="$(set -- `stty size 2>/dev/null` ; echo "$2")"
(( COLS > 0 )) || (( COLS = 80 )) # width of [ ok ] == 7
ENDLN=$'\e[A\e['$(( COLS - 8 ))'C'
ENDLNs=$'\e[A\e['80'C'
}
getcols
###################################################
# needed for deprecated jtestpara
_jtestpara_list() # private
{
JTestparameter=`echo "$1" | sed 's/^-//'` #
JTestparaAmount=`echo "${JTestparameter}" | wc -c` #
JTestparaCount=1 #
while [ ${JTestparaCount} -lt ${JTestparaAmount} ]; do # ... listen #
JTestparaTmp=`echo "${JTestparameter}" | head -c ${JTestparaCount} | tail --bytes=1` # parameter vereinzeln
JTestparameterListed=`echo -e "${JTestparameterListed} -${JTestparaTmp}"` #
let JTestparaCount++ #
done
}
_jtestpara_split() # private
{
unset JTestparaTmp JTestparameter JTestparaTmp JTestparaItem JTestparaCount JTestparaAmount
for JTestparaItem
do
if [[ `echo ${JTestparaItem} | grep ^-` ]]
then
if [[ `echo ${JTestparaItem} | grep ^--` ]]
then
[[ `echo ${JTestparaItem}` == "--" ]] && { JTestparameterListed=`echo -e $JTestparameterListed $@`; break; }
JTestparameterListed=`echo -e "$JTestparameterListed ${JTestparaItem}"`
else
_jtestpara_list "${JTestparaItem}"
fi
else
JTestparameterListed=`echo -e "$JTestparameterListed \"${JTestparaItem}\""`
fi
shift
done
}
########################################
##### deprecated - use getArgs insted
jtestpara() # <file> <"$@"> addinfo in script
{
local JTestparameterListed JTestParaResults JTestParaResultsLine OLD_IFS
# erwartete Notation(kommentiert notieren!):
#:begin_jpara
# <eingabe> [| <eingabe>]... : <variable> # <info>
# ...
# ex:
#-v | --verbose : VERBOSE # auskunftsfreudig
#:end_jpara
fex ${1} "jtestpara:" || return 1
jextract jpara ${1}
[[ ! ${JExtracted} ]] && jerror "${BAD}nichts extrahiert!${NORMAL}"
shift
# extrahierte elemente fuer case zuschneiden
# #-v | --verbose : VERBOSE # auskunftsfreudig
# zu
#-v|--verbose)[[ ! `printf %s "$2" | grep ^-` ]]&&[[ $# > 1 ]]&&shift;echo "VERBOSE=\"$1\"";;
JExtracted="`echo -e "${JExtracted}" |\
cut -d "#" -f 1 | tr -d "\t" | tr -d " " |\
sed -e 's/:/)[[ ! \`printf %s \"$2\" | grep ^-\` ]]\&\&[[ $# > 1 ]]\&\&shift;echo \"/' -e 's/$/=\\\\\"\$1\\\\\"\";;/';`"
# geklumpte parameter als einzelne splitten
_jtestpara_split "$@" # hier wird $TestparameterListed gesetzt
# eingegebene Parameter die jrun nutzen soll
JRUN_PARAMETER=$JTestparameterListed
#den ganzen gelump in einer subshell ausfuehren und die ergebnisse in einer variablen speichern
JTestParaResults=$(jrun "while [[ \$# -gt 0 ]]
do
case \${1} in
${JExtracted}
--) break;;
*) echo \"JParaErrorUnknownArgument \${1}\";;
esac;
shift
done")
#die ergebnisse auswerten uns anwenden
OLD_IFS=${IFS}
IFS=$'\012'
for JTestParaResultsLine in `echo -e "$JTestParaResults"`
do
[[ `printf "%s" "${JTestParaResultsLine}" | grep JParaErrorUnknownArgument` ]] &&
{
echo "${BAD}ungueltiges Argument - `printf "%s" "${JTestParaResultsLine}"|cut -d " " -f 2`${NORMAL}"
Jtestpara_Error=1
continue
}
eval ${JTestParaResultsLine}
done
IFS=${OLD_IFS}
return ${Jtestpara_Error}
}
getArgs() # file "$@"
{
local ArgLine Args Longargs Opts Error Default Var Opt
Name=$1
jextract args $1
shift
for ArgLine in $(printf "%s" "${JExtracted}" | cut -d : -f 1 | tr "|" "\n")
do
if [[ $(printf "%s" "${ArgLine}" | grep -o ^--) ]]
then
Longargs="${Longargs},$(printf "%s" "${ArgLine}" | sed 's/^--//' | tr "+" ":")"
else
Args="${Args}$(printf "%s" "${ArgLine}" | sed 's/^-//' | tr "+" ":" )"
fi
done
Opts=$(getopt -n getArgs -o "${Args}" -l "${Longargs}" -- "$@")
Error=$?
set -- $Opts
while [[ $# > 0 ]]
do
# printf "%s\n" "$*"
[[ "$1" == "--" ]] && break
Var="$(printf "%s" "${JExtracted}" | sed 's/^/|/;s/ *//g' | grep -- "|$1" | cut -d : -f 2 | cut -d "#" -f 1 )"
Default=$(printf "%s" "${Var}" | cut -d "=" -f 2)
Var=$(printf "%s" "${Var}" | cut -d "=" -f 1)
if [[ $(printf "%s" "$2" | grep "'") ]]
then
shift # shift Var away
# printf "\$1 = %s\n" "$1"
if [[ "$1" != "''" ]]
then
Opt=""
while [[ ! $(printf "%s" "${Opt}" | egrep -o "'$") ]]
do
# echo -- "loop: $1"
Opt="${Opt} $1"
shift
done
else
Opt=""
shift
fi
Opt=$(printf "%s" "${Opt}" | sed 's/^ *//g')
# printf "===\n${Var}=${Opt:=${Default}}\nDefault = ${Default}\n===\n"
eval "${Var}=${Opt:=${Default}}"
else
# echo "${Var}=$1"
eval "${Var}=$1"
shift
fi
done
unset JExtracted
return ${Error}
}
jextract() # <keyword> <file> [-print] addinfo in script
{
# erwartete Notation(kommentiert notieren!):
#:begin_<keyword>
# ...<whatever>...
#:end_<keyword>
unset JExtracted
local ExtractFile
#local JExtractTMP
#local JExtractCapture
local ExtractKeyword
local JExtractPrint
#local OLD_IFS
ExtractKeyword=$1
shift
ExtractFile=${1}
fex ${ExtractFile} "jextract:" || return 1
shift
[[ "${1}" == "-print" ]] && JExtractPrint=1
shift
[[ $* ]] && jerror "jextract: zu viele Parameter!" && return 1
# OLD_IFS=${IFS}
# IFS=$'\n'
# for JExtractTMP in `cat ${ExtractFile} | grep ^#`
# do
# [[ "${JExtractTMP}" == "#:end_${ExtractKeyword}" ]] && unset JExtractCapture
# [[ ${JExtractCapture} ]]&& { JExtractTMP=`echo "$JExtractTMP" | sed 's/^#*//'`;JExtracted=`echo "${JExtracted}\n${JExtractTMP}"`; }
# [[ "${JExtractTMP}" == "#:begin_${ExtractKeyword}" ]] && JExtractCapture="1"
# done
# IFS=${OLD_IFS}
JExtracted="$(sed -n "/^#:begin_${ExtractKeyword}/,/^#:end_${ExtractKeyword}/p" ${ExtractFile})"
JExtracted=$(echo "${JExtracted}" | sed '$d;1d') # delete first and last line
JExtracted=$(echo "${JExtracted}" | sed 's/^#//') # and remove the leading '#'
if [ ${JExtractPrint} ]
then
echo "${JExtracted}"
unset JExtracted
else
export JExtracted
fi
}
get_ver() #<file> [<file>]... - extrahiert dateinamen und version notation : #!begin_version\n#<datei-version>\n#!end_version
{
local FillLen File Flist
FillLen=$(longest_string $(
for File in $*
do
[[ -f ${File} ]] && basename ${File}
done
))
Flist=$(
for File in $*
do
[[ -f ${File} ]] && echo ${File}
done
)
for File in ${Flist}
do
jextract version ${File}
[[ ${JExtracted} ]] &&{ # ignore files with no version
printf "%-${FillLen}s: %s\n" "$(basename ${File})" "${JExtracted}"
}
unset JExtracted
done
}
jrun() #<cmd[/s]> fuehrt $* aus einer subshell aus | Parameter fuer die tmpfkt in JRUN_PARAMETER angeben !
{
[[ ${Jrun_Debug} ]] &&
{
jline 1>&2
echo " Debug_jrun" 1>&2
jline 1>&2
echo -e "\nParameter: $JRUN_PARAMETER\n" 1>&2
echo -e "tmpfunc()\n{\n$*\nreturn \$?\n}\ntmpfunc ${JRUN_PARAMETER}\n" 1>&2
jline 1>&2
echo " /Debug_jrun"1>&2
jline 1>&2
read
}
echo -e "tmpfunc()\n{\n$*\nreturn \$?\n}\ntmpfunc ${JRUN_PARAMETER}" | bash
return $?
}
juninstall() # <datei1> [<datei2> ...]
{
for juninstall_item in $*
do
jbegin "loesche ${juninstall_item}"
rm ${juninstall_item}
jend
done
unset juninstall_item
}
_get_version_strings() # private
{
unset jinstall_update
jextract version `echo ${1} | sed 's/.*\///'` && jinstall_installed_ver=${JExtracted}
if [ ! -e ${1} ]
then
unset jinstall_local_ver
else
jextract version ${1} && jinstall_local_ver=${JExtracted}
jinstall_update=1
fi
}
_jinstall_do() # private
{
if [ ${jinstall_update} ]
then
jbegin "update ${1} ${jinstall_local_ver} -> ${jinstall_installed_ver} "
else
jbegin "installiere $1 ${jinstall_installed_ver}"
fi
cp $2 $3
jend
}
_jinstall_inf() # private
{
if [ $FORCE ]
then
jwarn "${1} ${jinstall_local_ver} ueberschreiben mit ${jinstall_installed_ver}"
cp $2 $3
jend
else
jwarn "$1 ${jinstall_local_ver} bereits aktuell"
fi
}
jinstall() # <Anzeigename> <QuellDatei> <InstallationsDatei> // FORCE erzwingt dasueberschreiben
{
_get_version_strings "$3"
jinstall_destination=`echo $3 | grep -o '^.*/'` # Zielpfad ermitteln
if [[ ${jinstall_installed_ver} > ${jinstall_local_ver} ]]
then
_jinstall_do $1 $2 ${jinstall_destination}
else
_jinstall_inf $1 $2 ${jinstall_destination}
fi
chmod 644 $3
unset jinstall_update jinstall_installed_ver jinstall_local_ver jinstall_destination
}
jset_time() # <name> setzt die zeit in einer variablen + den bezeichner
{
eval "JTime_$1=`date +%s`"
}
jget_time() # <name> holt die zeit aus der variablen + den bezeichner
{
date -u -d @$(( `date +%s` - `eval echo \$\{JTime_$1\}` )) +%T
}
_jdo()
{
local TmpVerbose
JdoError=0
[[ $# < 1 ]] && { jerror "_jdo: zu wenige Parameter angegeben!"; return 1; }
jrun "$*"
# { $* ; } # better ?
# ( $* ) # better ?
if [[ $? -eq 0 ]] ; then JdoError=0; else JdoError=1; fi
[[ ${VERBOSE} ]] && TmpVerbose=${VERBOSE}
unset VERBOSE
_jend ${JdoError}
[[ ${TmpVerbose} ]] && VERBOSE=${TmpVerbose}
unset TmpVerbose
return ${JdoError}
}
jdo() # <bezeichner> <2do>
{
jbegin "$1"
shift
_jdo "$*"
}
jido() # <bezeichner> <2do>
{
jinfo "$1"
shift
_jdo "$*"
}
jldo () # <bezeichner> <2do> # verbose if VERBOSE!=""
{
inline "$1"
shift
_jdo "$*"
}
humanreadable() # <int[Ext][,int[Ext]...]>
{
local Value Ext InExt Cnt
while [[ $# -gt 0 ]]
do
Value=$1
InExt=$(echo ${Value} | tr -d "[0-9]*")
Value=$(echo ${Value} | tr -d "[BKMGTPEZYbkmgtpezy]*")
InExt=$(echo ${InExt} | sed 'y/kmgtpezy/KMGTPEZY/') # uppercase input
[[ ! ${InExt} ]] && InExt="B"
for Ext in B K M G T P E Z Y
do
[[ "${Ext}" == "${InExt}" ]] && break
let Cnt++
done
for Ext in B K M G T P E Z Y
do
[[ ${Cnt} -gt 0 ]] && { let Cnt--; continue; }
if [[ $(echo ${Value} | awk -F. '{print $1}') -lt 1024 ]]
then
break 1
else
# let 'Value/=1024'
Value=$(echo "scale=3; ${Value} / 1024" | bc -l)
fi
done
echo "${Value}${Ext}"
shift
done
}
revhumanreadable() # <size[Ext] [-o <OExt>] [size[Ext] [-o OExt]]>
{
local Value Ext InExt Trgr OExt
while [[ $# -gt 0 ]]
do
unset Trgr
Value=$1
[[ "$2" == "-o" ]] && { OExt=$3; shift 2; }
InExt=$(echo ${Value} | tr -d "[0-9]*")
InExt=$(echo ${InExt} | sed 'y/bkmgtpezy/BKMGTPEZY/') # uppercase input
OExt=$(echo ${OExt} | sed 'y/bkmgtpezy/BKMGTPEZY/') # uppercase output
Value=$(echo ${Value} | tr -d "[BKMGTPEZYbkmgtpezy]*")
[[ ! ${InExt} ]] && InExt="B"
[[ ! ${OExt} ]] && OExt="B"
for Ext in Y Z E P T G M K B
do
[[ ${Trgr} ]] && {
let 'Value*=1024'
}
[[ ${InExt} == ${Ext} ]] && Trgr=1
[[ ${Ext} == ${OExt} ]] && break
done
echo "${Value}${Ext}"
shift
done
}
genarghelp() # <File to extract from> # generate HelpText from Argumentdeclaration (jtestpara)
{
local OLD_IFS Len1 FillLen
jextract "args" $1
[[ ! "${JExtracted}" ]] && jextract "jpara" $1
OLD_IFS=${IFS}
IFS=$'\012'
FillLen=$(longest_string $(echo -e "${JExtracted}" | cut -d : -f 1 | tr -d " " | tr -d "\t" | sed 's/|/ /g'))
for Line in ${JExtracted}
do
printf "%-${FillLen}s " "$(echo ${Line} | cut -d : -f 1 | tr -d " " | tr -d "\t" | sed 's/|/, /g')"
if [[ $(echo ${Line} | grep "#") ]] ##
then #
echo ${Line} | cut -d "#" -f 2 # print info if available
else #
echo #
fi ##
done #
IFS=${OLD_IFS}
}
longest_string()
{
local TmpLineLen MaxLen
while [ $# -gt 0 ]
do
TmpLineLen=$(echo $1 | wc -c)
[[ ${TmpLineLen} -gt ${MaxLen} ]] && MaxLen=${TmpLineLen}
shift
done
echo $(( ${MaxLen} - 1 ))
}
sec2hms(){
local Itm h m s
for Itm in $*
do
h=$(echo "${Itm} / 3600" | bc )
m=$(echo "( ${Itm} - $h * 3600 ) / 60" | bc )
s=$(echo "( ${Itm} - $h * 3600 - $m * 60 )" | bc )
echo "$h h, $m m, $s s."
done
}
doCmd()
{
if [[ $Dbg ]]
then echo "Debug: $*"
else eval "$*"
fi
}
|
Ruby
|
UTF-8
| 2,239 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
require 'socket'
require 'cloudbridge'
module CloudBridge
# This class emulates the behaviour of TCPServer, but 'listens' on a cloudbridge
# server rather than a local interface. Otherwise attempts to have an identical
# interface to TCPServer. At least as far as mongrel uses it.
class Server
def initialize(cloud_host, cloud_port, listen_hosts = ['*'], listen_keys = [])
@cloud_host = cloud_host
@cloud_port = cloud_port
@listen_hosts = listen_hosts
@listen_keys = listen_keys
@sockopts = []
end
def setsockopt(*args)
@sockopts.push(args)
end
def accept()
# Connect to the cloudbridge and let it know we're available for a connection.
# This is all entirely syncronous.
begin
socket = TCPSocket.new(@cloud_host, @cloud_port)
@sockopts.each {|opt| socket.setsockopt(*opt) }
rescue Errno::ECONNREFUSED
sleep(0.5)
retry
end
socket.write("BRIDGE / HTTP/1.1\r\n")
@listen_hosts.each {|host|
socket.write("Host: #{host}\r\n")
}
@listen_keys.each {|key|
socket.write("Host-Key: #{key}\r\n")
}
socket.write("\r\n")
code = nil
name = nil
headers = []
while (line = socket.gets())
line = line.strip
if (line == "")
case code.to_i
when 100 # 100 Continue, just a ping. Ignore.
code = name = nil
headers = []
next
when 101 # 101 Upgrade, successfuly got a connection.
socket.write("HTTP/1.1 100 Continue\r\n\r\n") # let the server know we're still here.
return socket
when 504 # 504 Gateway Timeout, just retry.
socket.close()
return accept()
else
raise "HTTP BRIDGE error #{code}: #{name} waiting for connection."
end
end
if (!code && !name) # This is the initial response line
if (match = line.match(%r{^HTTP/1\.[01] ([0-9]{3,3}) (.*)$}))
code = match[1]
name = match[2]
next
else
raise "Parse error in BRIDGE request reply."
end
else
if (match = line.match(%r{^(.+?):\s+(.+)$}))
headers.push({match[1] => match[2]})
else
raise "Parse error in BRIDGE request reply's headers."
end
end
end
end
def close()
# doesn't need to do anything. Yet.
end
end
end
|
C
|
ISO-8859-1
| 15,199 | 3.09375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "utn.h"
#include "menu.h"
#include "empleados.h"
#define LIBRE 0
#define OCUPADO 1
void initEmpleados(eEmpleado lista[], int limite)
{
int i;
for(i = 0 ; i < limite ; i++)
{
lista[i].isEmpty = LIBRE;
}
}
void hardcodeoEmpleados(eEmpleado lista[], int limite)
{
int i;
eEmpleado nuevo[5] =
{
{1, "Juan", "Gomez", 'm', 10500.50, {12, 3, 2011}, 1, OCUPADO},
{2, "Lucas", "Diaz", 'm', 12000.25, {3, 5, 1999}, 3, OCUPADO},
{3, "Sofia", "Goux", 'f', 25000.80, {30, 2, 2002}, 2, OCUPADO},
{4, "Jose", "Lopez", 'm', 14500, {14, 5, 2015}, 3, OCUPADO},
{5, "Lucia", "Diaz", 'f', 21000, {23, 11, 2006}, 5, OCUPADO}
};
for(i = 0 ; i < limite ; i++)
{
lista[i] = nuevo[i];
}
}
void mostrarInitEmpleados(eEmpleado lista[], int limite)
{
int i;
printf("\tInicializacion de Empleados\n");
for(i = 0 ; i < limite ; i++)
{
printf("\n#%d ---> %d",i+1,lista[i].isEmpty);
}
wait();
system("cls");
}
int buscarEspacioLibreE(eEmpleado lista[], int limite)
{
int i;
int retorno = -1; // Retorta -1 si no encontr un espacio
for(i = 0 ; i < limite ; i++)
{
if(lista[i].isEmpty == LIBRE)
{
retorno = i;
break;
}
}
return retorno;
}
int mostrarEmpleados(eEmpleado lista[], int limite)
{
int i, vacio = -1;
int titulo = 0;
for(i = 0 ; i < limite ; i++)
{
if(lista[i].isEmpty == OCUPADO)
{
if(titulo == 0)
{
printf("LEGAJO APELLIDO NOMBRE SEXO SALARIO FECHA INGRESO IDSECTOR");
titulo = -1;
}
printf("\n %d \t %s %s %c \t $%.2f \t %d/%d/%d \t %d",lista[i].legajo, lista[i].apellido, lista[i].nombre, lista[i].sexo, lista[i].salary, lista[i].fIngreso.dia, lista[i].fIngreso.mes, lista[i].fIngreso.anio, lista[i].idSector);
vacio = 0;
}
}
if(vacio == -1)
{
printf(">>> NADA QUE MOSTRAR.\n\n");
system("pause");
system("cls");
}
return vacio;
}
int getFecha(int* inputD, int* inputM, int* inputA, char messageD[], char messageM[], char messageA[])
{
int retorno = 0;
// Variables string para comprobar que sea nmeros y no letras
char auxD[3];
int validarD;
char auxM[3];
int validarM;
char auxA[5];
int validarA;
// Variables para establecer mnimos y mximos permitidos en las fechas
int maxDia = 31;
int minDia = 1;
int maxMes = 12;
int minMes = 1;
int maxAnio = 2018;
int minAnio = 1990;
// Variables para convertir los string a int
int diaNumero;
int mesNumero;
int anioNumero;
// Ingresamos y Validamos DIA
printf("%s",messageD);
fflush(stdin);
gets(auxD);
validarD = esEntero(auxD);
diaNumero = atoi(auxD);
while((diaNumero < minDia || diaNumero > maxDia) || validarD == 0)
{
printf("\nError... Para DIA solo se permiten numeros (1 al 31)\nRe%s ",messageD);
fflush(stdin);
gets(auxD);
validarD = esEntero(auxD);
diaNumero = atoi(auxD);
}
// Ingresamos y Validamos MES
printf("%s",messageM);
fflush(stdin);
gets(auxM);
validarM = esEntero(auxM);
mesNumero = atoi(auxM);
while((mesNumero < minMes || mesNumero > maxMes) || validarM == 0)
{
printf("\nError... Para MES solo se permiten numeros (1 al 12)\nRe%s ",messageM);
fflush(stdin);
gets(auxM);
validarM = esEntero(auxM);
mesNumero = atoi(auxM);
}
// Ingresamos y Validamos AO
printf("%s",messageA);
fflush(stdin);
gets(auxA);
validarA = esEntero(auxA);
anioNumero = atoi(auxA);
while((anioNumero < minAnio || anioNumero > maxAnio) || validarA == 0)
{
printf("\nError... Para ANIO solo se permiten numeros (1990 al 2018)\nRe%s ",messageA);
fflush(stdin);
gets(auxA);
validarA = esEntero(auxA);
anioNumero = atoi(auxA);
}
*inputD = diaNumero;
*inputM = mesNumero;
*inputA = anioNumero;
return retorno;
}
int altaEmpleado(eEmpleado lista[], int limite, eSector sectores[], int limiteS)
{
int retorno = -1;
int r;
int indice;
eEmpleado aux;
indice = buscarEspacioLibreE(lista, limite);
if(indice == -1)
{
system("cls");
printf("\tALTA DE EMPLEADOS\n\n");
printf("\n>>> NO HAY ESPACIO DISPONIBLE\n");
wait();
}
else
{
system("cls");
printf("\tALTA DE EMPLEADOS\n\n");
r = getStringV(aux.nombre, "Ingresa nombre: ", "Error", 0, 51);
if( r == 0)
{
r = getStringV(aux.apellido, "Ingresa apellido: ", "Error", 0, 51);
if( r == 0)
{
r = confirmaSexo(&aux.sexo, "Ingresa sexo [m/f]: ");
if( r == 0)
{
r = getFlotanteV(&aux.salary, "Ingresa salario: ", "Error");
if( r == 0)
{
printf("\n\n>>> FECHA DE INGRESO\n\n");
r = getFecha(&aux.fIngreso.dia, &aux.fIngreso.mes, &aux.fIngreso.anio, "ingresa dia: ","ingresa mes: ","ingresa anio: ");
if(r == 0)
{
aux.idSector = elegirSector(sectores, limiteS);
aux.legajo = buscarEspacioLibreE(lista, limite);
aux.legajo++;
aux.isEmpty = OCUPADO;
lista[indice] = aux;
}
}
}
}
}
}
return retorno;
}
int buscarPorLegajo(eEmpleado lista[], int limite, int legajo)
{
int i;
for(i = 0 ; i < limite ; i++)
{
if(lista[i].legajo == legajo && lista[i].isEmpty == OCUPADO)
{
return i;
}
}
return -1;
}
void mostrarUnEmpleado(eEmpleado lista[], int i)
{
printf("\nLEGAJO:%d \nAPELLIDO: %s \nNOMBRE: %s\nSEXO: %c\nSALARIO: %.2f\nFECHA INGRESO: %d/%d/%d\nIDSECTOR: %d\n",lista[i].legajo, lista[i].apellido, lista[i].nombre, lista[i].sexo, lista[i].salary, lista[i].fIngreso.dia, lista[i].fIngreso.mes, lista[i].fIngreso.anio, lista[i].idSector);
}
int bajaEmpleado(eEmpleado lista[], int limite)
{
int retorno;
char confirma;
int encontrado;
system("cls");
printf("\tBAJA EMPLEADO\n");
int auxLegajo, flag;
system("cls");
printf("\tBAJA EMPLEADO\n\n");
flag = mostrarEmpleados(lista, limite);
if(flag != -1)
{
printf("\n\nIngrese legajo del empleado: ");
scanf("%d",&auxLegajo);
encontrado = buscarPorLegajo(lista, limite, auxLegajo);
if(encontrado != -1)
{
printf("\n\n");
mostrarUnEmpleado(lista, encontrado);
do
{
printf("\n\nConfirma Baja? [S|N]: ");
fflush(stdin);
scanf("%c", &confirma);
confirma = tolower(confirma);
}
while(confirma != 's' && confirma != 'n');
if(confirma == 's')
{
lista[encontrado].isEmpty = LIBRE;
retorno = 0;
}
else
{
printf("\n\n>>> SE AH CANCELADO LA BAJA\n");
retorno = -1;
wait();
}
}
else
{
printf("\n\n\n>>> NO SE ENCONTRO EL LEGAJO EN EL SISTEMA\n\n");
system("pause");
system("cls");
}
}
return retorno;
}
int modificarEmpleados(eEmpleado lista[], int limite, eSector sectores[], int limiteS)
{
int retorno = -1;
int hay;
int encontrado;
int auxLegajo;
char auxSexo;
int auxIDSector;
float AuxSalario;
char auxApellido[51];
char auxNombre[51];
int r, opcion;
char confirma;
int salir = 0;
system("cls");
printf("\tMODIFICAR EMPLEADO\n\n");
hay = mostrarEmpleados(lista, limite);
if(hay != -1)
{
printf("\n\nIngrese Legajo del Empleado: ");
scanf("%d",&auxLegajo);
encontrado = buscarPorLegajo(lista, limite, auxLegajo);
if(encontrado != -1)
{
system("cls");
printf("\tMODIFICAR EMPLEADO\n\n\n");
mostrarUnEmpleado(lista, encontrado);
do
{
printf("\n\nConfirma Modificacion? [S|N]: ");
fflush(stdin);
scanf("%c", &confirma);
confirma = tolower(confirma);
}
while(confirma != 's' && confirma != 'n');
if(confirma == 's')
{
do
{
system("cls");
printf("\tMODIFICAR EMPLEADO\n\n");
printf("1- Modificar Apellido.\n");
printf("2- Modificar Nombre.\n");
printf("3- Modificar Sexo.\n");
printf("4- Modificar Salario.\n");
printf("5- Modificar Fecha de Ingreso.\n");
printf("6- Modificar Sector.\n");
printf("7- Salir.\n\n");
printf("Ingrese opcion: ");
scanf("%d",&opcion);
switch(opcion)
{
case 1:
r = getStringV(auxApellido,"\nIngresa nuevo Apellido: ", "\n>>> Error! superaste el largo del nombre\n",0,51);
if(r == 0)
{
strcpy(lista[encontrado].apellido, auxApellido);
salir = 1;
printf("\n\n>>> Se ha realizado la modificacion\n");
wait();
break;
}
case 2:
r = getStringV(auxNombre,"\nIngresa nuevo Nombre: ", "\n>>> Error! superaste el largo del nombre\n",0,51);
if(r == 0)
{
strcpy(lista[encontrado].nombre, auxNombre);
salir = 1;
printf("\n\n>>> Se ha realizado la modificacion\n");
wait();
break;
}
case 3:
r = confirmaSexo(&auxSexo, "Ingresa nuevo Sexo [m/f]: ");
if(r == 0)
{
lista[encontrado].sexo = auxSexo;
salir = 1;
printf("\n\n>>> Se ha realizado la modificacion\n");
wait();
break;
}
case 4:
r = getFlotanteV(&AuxSalario,"\nIngresa nuevo Salario: ", "\nError!\n");
if(r == 0)
{
lista[encontrado].salary = AuxSalario;
salir = 1;
printf("\n\n>>> Se ha realizado la modificacion\n");
wait();
break;
}
case 5:
printf("\n>>> FECHA DE INGRESO\n\n");
r = getFecha(&lista[encontrado].fIngreso.dia, &lista[encontrado].fIngreso.mes, &lista[encontrado].fIngreso.anio, "ingresa nuevo dia: ", "ingresa nuevo mes: ", "ingresa nuevo anio: ");
if(r == 0)
{
salir = 1;
printf("\n\n>>> Se ha realizado la modificacion\n");
wait();
break;
}
case 6:
auxIDSector = elegirSector(sectores, limiteS);
r = buscarPorSector(sectores, limiteS, auxIDSector);
if(r == 0)
{
salir = 1;
lista[encontrado].idSector = auxIDSector;
printf("\n\n>>> Se ha realizado la modificacion\n");
wait();
break;
}else if(r == -1)
{
salir = 1;
printf("\n\n>>> EL IDSECTOR NO EXISTE\n");
wait();
break;
}
case 7:
printf("\n\n>>> SALIENDO DEL SISTEMA...");
wait();
salir = 1;
break;
}
}
while(salir != 1);
}
else
{
printf("\n\n>>> Se ha cancelado la modificacion\n");
wait();
}
}
else
{
printf("\n\n\n>>> NO SE ENCONTRO EL IDSECTOR EN EL SISTEMA\n\n");
system("pause");
system("cls");
}
}
return retorno;
}
int ordenarXApellidoYNombre(eEmpleado lista[], int limite) // Importe (descendente) - Descripcion (Ascendente)
{
int retorno = -1;
int i, j;
eEmpleado aux;
for(i=0; i<limite -1; i++)
{
for(j = i+1 ; j < limite; j++)
{
if( strcmp(lista[i].apellido, lista[j].apellido) > 0)
{
aux = lista[i];
lista[i] = lista[j];
lista[j] = aux;
}
else if((strcmp(lista[i].apellido, lista[j].apellido) == 0) && strcmp(lista[i].nombre, lista[j].nombre) > 0)
{
aux = lista[i];
lista[i] = lista[j];
lista[j] = aux;
retorno = 0;
}
}
}
return retorno;
}
void listarEmpleados(eEmpleado lista[], int limite)
{
int r;
system("cls");
printf("\tLISTAR EMPLEADOS\n\n");
printf("Ordenados por apellido (ascendente) y nombre (ascendente)\n\n");
ordenarXApellidoYNombre(lista, limite);
r = mostrarEmpleados(lista, limite);
if(r != -1)
{
wait();
}
}
|
C++
|
UTF-8
| 468 | 3.09375 | 3 |
[] |
no_license
|
#ifndef LINK_H
#define LINK_H
#include <cstddef>
class Link
{
public:
Link() = default;
Link(const std::size_t firstVertex, const std::size_t secondVertex);
Link(const Link &link) = default;
~Link() = default;
std::size_t getFirst() const;
std::size_t getSecond() const;
void setFirst(const std::size_t index);
void setSecond(const std::size_t index);
private:
std::size_t _first;
std::size_t _second;
};
#endif //LINK_H
|
Python
|
UTF-8
| 2,105 | 3.34375 | 3 |
[] |
no_license
|
def is_integer(n):
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer()
def extract_colours(bag_list):
extracted = {}
for lst in bag_list:
lst = lst.split(' ')
i = 0
colour = ""
main_colour = ""
num = 0
while i < len(lst):
if i == 0:
while "bag" not in lst[i] and i < len(lst):
main_colour += lst[i]
i += 1
extracted[main_colour] = {}
if num > 0 and i < len(lst):
while "bag" not in lst[i] and i < len(lst):
colour += lst[i]
i += 1
extracted[main_colour][colour] = num
colour = ''
num = 0
if is_integer(lst[i]):
num = int(lst[i])
i += 1
return extracted
def count_bags_contain_tgt(bag_list, target):
target = target.replace(' ', '')
bag_dic = extract_colours(bag_list)
res = []
waiting = [target,]
while waiting:
target = waiting.pop()
res.append(target)
for k, v in bag_dic.items():
if target in v and (k not in waiting and k not in res):
waiting.append(k)
return len(res) - 1
def count_bags_hold(bag_list, target):
target = target.replace(' ', '')
bag_dic = extract_colours(bag_list)
return count_recur(bag_dic, target)
def count_recur(bag_dic, target):
if target not in bag_dic:
return 1
elif bag_dic[target] == {}:
return 1
else:
count = 0
for k, v in bag_dic[target].items():
count += (count_recur(bag_dic, k) * v)
if count_recur(bag_dic, k) > 1:
count += v
return count
if __name__ == '__main__':
r = open(r"C:\Users\USER\Pictures\Advent-of-Code-2020\/Day7.txt").read()
inp = r.split("\n")
target = "shiny gold"
# part 1
print(count_bags_contain_tgt(inp, target))
# part 2
print(count_bags_hold(inp, target))
|
Python
|
UTF-8
| 11,904 | 2.921875 | 3 |
[] |
no_license
|
#from odlib import *
import numpy as np
import math
obs1 = 1 #ENTER WHICH OBSERVATIONS YOU WANT TO USE HERE -- USE LINE NUMBERS ON LakhaniInput.txt FILE, NOT INDEX IN ARRAY
obs2 = 2
obs3 = 3
num_root = 1 #ENTER NUMBER OF ROOT YOU WISH TO USE HERE (first, second, third, etc.)
def magnitude(vector):
return (vector[0] ** 2 + vector[1] ** 2 + vector[2] ** 2) ** 0.5
def quadrantCheck(cos_angle, sin_angle):
if sin_angle > 0 and cos_angle > 0:
return math.asin(sin_angle) * 180 / math.pi
if sin_angle > 0 and cos_angle < 0:
return 180 - math.asin(sin_angle) * 180 / math.pi
if sin_angle < 0 and cos_angle < 0:
return 180 - math.asin(sin_angle) * 180 / math.pi
if sin_angle < 0 and cos_angle > 0:
return 360 - math.acos(cos_angle) * 180 / math.pi
k = 0.01720209895 #Gaussian gravitational constant
cAU = 173.144632674240 #speed of light in au/(mean solar)day
eps = math.radians(23.4366) #Earth's obliquity
mu = 1
def convert_angle_dec(string, radians):
dec_val = string.split(":")
for k in range(len(dec_val)):
dec_val[k] = float(dec_val[k])
degrees = dec_val[0]
minutes = dec_val[1]
seconds = dec_val[2]
negative = math.copysign(1.0, degrees)
angle = degrees + negative * minutes / 60 + negative * seconds / 3600
if radians:
angle *= math.pi / 180
return angle
def convert_angle_ra(string, radians):
ra_val = string.split(":")
for k in range(len(ra_val)):
ra_val[k] = float(ra_val[k])
hours = ra_val[0]
minutes = ra_val[1]
seconds = ra_val[2]
negative = math.copysign(1.0, hours)
angle = 360 * (hours + negative * minutes / 60 + negative * seconds / 3600) / 24
if radians:
angle *= math.pi / 180
return angle
def fileReader(filename):
f = open(filename, "r")
arr = []
numlines = 0
for line in f.readlines():
numlines += 1
arr.append(line.split())
f.close()
arr = np.array(arr)
for m in range(numlines):
arr[m,1] = convert_angle_ra(arr[m,1], True)
arr[m,2] = convert_angle_dec(arr[m,2], True)
for k in range(numlines):
obs = arr[k,:].astype(np.float)
data1 = arr[obs1 - 1]
data2 = arr[obs2 - 1]
data3 = arr[obs3 - 1]
return data1, data2, data3
o1, o2, o3 = fileReader("LakhaniInput2020.txt")
o1 = o1[:].astype(np.float)
o2 = o2[:].astype(np.float)
o3 = o3[:].astype(np.float)
t1 = float(o1[0])
t2 = float(o2[0])
t3 = float(o3[0])
tau = [k * (t3 - t2), k * (t1 - t2), k * (t3 - t1)] #(tau1, tau3, tau)
sun1 = [o1[3], o1[4], o1[5]] #read from input file
sun2 = [o2[3], o2[4], o2[5]] #read from input file
sun3 = [o3[3], o3[4], o3[5]] #read from input file
def get_rhohat(ra, dec):
rhohat = [math.cos(ra) * math.cos(dec), math.sin(ra) * math.cos(dec), math.sin(dec)]
return rhohat
rhohat1 = get_rhohat(o1[1], o1[2])
rhohat2 = get_rhohat(o2[1], o2[2])
rhohat3 = get_rhohat(o3[1], o3[2])
def getD(observation_number):
if observation_number == 1:
sun = sun1
elif observation_number == 2:
sun = sun2
else:
sun = sun3
D1 = np.dot(np.cross(sun, rhohat2), rhohat3)
D2 = np.dot(np.cross(rhohat1, sun), rhohat3)
D3 = np.dot(rhohat1, np.cross(rhohat2, sun))
D = [D1, D2, D3]
return D
D0 = np.dot(rhohat1, np.cross(rhohat2, rhohat3))
D1j = getD(1)
D2j = getD(2)
D3j = getD(3)
def SEL():
rhos = [] #range values for each real, positive root
Tau = tau[2]
A1 = tau[1] / Tau
B1 = A1 * (Tau ** 2 - tau[1] ** 2) / 6
A3 = -1 * tau[0] / Tau
B3 = A3 * (Tau ** 2 - tau[0] ** 2) / 6
A = (A1 * D2j[0] - D2j[1] + A3 * D2j[2]) / (-1 * D0)
B = (B1 * D2j[0] + B3 * D2j[2]) / (-1 * D0)
E = -2 * (np.dot(rhohat2, sun2))
F = (sun2[0] ** 2 + sun2[1] ** 2 + sun2[2] ** 2)
a = -1 * (A ** 2 + A * E + F)
b = -1 * mu * (2 * A * B + B * E)
c = -1 * mu ** 2 * B ** 2
coeff = [c,0,0,b,0,0,a,0,1]
roots = np.real(np.polynomial.polynomial.polyroots(coeff))
positive_roots = roots[roots>0] # Daniel told me about this built in function in Python
for elem in positive_roots:
Rho = A + mu * B / elem ** 3
rhos.append(Rho)
return(positive_roots, rhos)
roots, rhos = SEL()
using_root = roots[num_root - 1]
def fg(tau, r2, r2dot, flag):
if flag == 0: #function
delta_E = newtonRaphson(tau, e, tol, a, n)
f = 1 - a * (1 - math.cos(delta_E)) / magnitude(r2)
g = tau + (math.sin(delta_E) - delta_E) / n
if flag == 2: #second order
f = 1 - mu / (2 * r2 ** 3) * tau ** 2
g = tau - mu * tau ** 3 / (6 * r2 ** 3)
if flag == 3: #third order
f = 1 - mu / (2 * magnitude(r2) ** 3) * tau ** 2 + mu * np.dot(r2, r2dot) / (2 * magnitude(r2) ** 5) * tau ** 3
g = tau - mu * tau ** 3 / (6 * magnitude(r2) ** 3)
if flag == 4: #fourth order
u = 1 / magnitude(r2) ** 3
z = np.dot(r2, r2dot) / magnitude(r2) ** 2
q = np.dot(r2, r2dot) / magnitude(r2) ** 2 - u
f = 1 - mu / (2 * magnitude(r2) ** 3) * tau ** 2 + mu * np.dot(r2, r2dot) / (2 * magnitude(r2) ** 5) * tau ** 3 + (3 * u * q - 15 * u * z ** 2 + u ** 2) / 24 * tau ** 4
g = tau - mu * tau ** 3 / (6 * magnitude(r2) ** 3) + 6 * u * z * tau ** 4 / 24
return f, g
def c_calculator(r2, r2dot, flag):
f1, g1 = fg(tau[0], r2, r2dot, flag)
f3, g3 = fg(tau[1], r2, r2dot, flag)
c1 = g3 / (f1 * g3 - g1 * f3)
c2 = -1
c3 = -g1 / (f1 * g3 - g1 * f3)
return c1, c2, c3
c_initial = c_calculator(using_root, 0, 2)
#print("c:",c_initial)
def get_rho(c, obs_num):
if obs_num == 1:
D = D1j
elif obs_num == 2:
D = D2j
else:
D = D3j
rho = (c[0] * D[0] + c[1] * D[1] + c[2] * D[2]) / (D0 * c[obs_num - 1])
return rho
rho1 = get_rho(c_initial, 1)
rho2 = get_rho(c_initial, 2)
rho3 = get_rho(c_initial, 3)
#print("rho2:",rho2)
def get_r(obs_num):
if obs_num == 1:
rho = rho1
rhohat = rhohat1
sun = sun1
elif obs_num == 2:
rho = rho2
rhohat = rhohat2
sun = sun2
else:
rho = rho3
rhohat = rhohat3
sun = sun3
r = []
for n in range(3):
rho_vec = rho * rhohat[n]
r.append(rho_vec - sun[n])
return r
r1 = get_r(1)
r2 = get_r(2)
r3 = get_r(3)
#print("r2:",r2)
def central_velocity_vector(r2, r2dot, flag):
f1, g1 = fg(tau[0], r2, r2dot, flag)
f3, g3 = fg(tau[1], r2, r2dot, flag)
r2dot = []
d1 = -f3 / (f1 * g3 - f3 * g1)
d3 = f1 / (f1 * g3 - f3 * g1)
for k in range(3):
r2dot.append(d1 * r1[k] + d3 * r3[k])
return r2dot
#r1dot = central_velocity_vector(magnitude(r1), 0, 2)
r2dot = central_velocity_vector(magnitude(r2), 0, 2)
#r3dot = central_velocity_vector(magnitude(r3), 0, 2)
def new_time_obs(obs_num):
if obs_num == 1:
rho = rho1
t_og = t1
elif obs_num == 2:
rho = rho2
t_og = t2
else:
rho = rho3
t_og = t3
t = t_og - rho/ cAU
return t
t1_updated = new_time_obs(1)
t2_updated = new_time_obs(2)
t3_updated = new_time_obs(3)
#a = (2 / magnitude(r2) - magnitude(r2dot) ** 2 / mu) ** -1
r2_mag = magnitude(r2)
r2dot_mag = magnitude(r2dot) / 365.2563835 * 2 * math.pi
a = (2 / r2_mag - r2dot_mag ** 2 / mu) ** -1
#a = 1.5
#print("a:",a)
n = (mu / a ** 3) ** 0.5
#print(n)
def f(x, tau, r2, r2dot):
return x - (1 - magnitude(r2) / a) * math.sin(x) + np.dot(r2, r2dot) / (n * a ** 2) * (1 - math.cos(x)) - n * tau
def df(x, tau, r2, r2dot):
return 1 - (1 - magnitude(r2) / a) * math.cos(x) + np.dot(r2, r2dot) / (n * a ** 2) * math.sin(x)
def newtonRaphson(tau, e, tol, a, n):
sign = np.dot(r2, r2dot) / (n * a ** 2) * math.cos(n * tau - np.dot(r2, r2dot) / (n * a ** 2)) + (1 - magnitude(r2) / a) * math.sin(n * tau - np.dot(r2, r2dot) / (n * a ** 2))
plus_minus = math.copysign(1, sign)
x = n * tau + plus_minus * 0.85 * e - np.dot(r2, r2dot) / (n * a ** 2)
diff = f(x, tau, r2, r2dot) / df(x, tau, r2, r2dot)
while(abs(diff) >= tol):
diff = f(x, tau, r2, r2dot) / df(x, tau, r2, r2dot)
x = x - diff
return x #delta E
def get_r_new(obs_num, rho):
if obs_num == 1:
rhohat = rhohat1
sun = sun1
elif obs_num == 2:
rhohat = rhohat2
sun = sun2
else:
rhohat = rhohat3
sun = sun3
r = []
for n in range(3):
rho_vec = rho * rhohat[n]
r.append(rho_vec - sun)
return r
def new_time_obs_ITERATIVE(rho, t_og):
t = t_og - rho/ cAU
return t
def main():
rho2_new = 0
diff = rho2 - rho2_new
#print(diff)
r2_new = r2
r2dot_new = r2dot
t1_new = t1
t2_new = t2
t3_new = t3
tau = [k * (t3_new - t2_new), k * (t1_new - t2_new), k * (t3_new - t1_new)] #(tau1, tau3, tau)
diff = rho2 - rho2_new
#print(abs(diff) >= tol)
while(abs(diff.any()) >= 1E-12):
old_rho = rho2_new
print("PASS")
#f, g = fg(tau, r2_new, r2dot_new, 4)
f1, g1 = fg(tau[0], r2, r2dot, 3)
f3, g3 = fg(tau[1], r2, r2dot, 3)
#delta_E = newtonRaphson(tau, e, tol, a, n)
c_new = c_calculator(r2_new, r2dot_new, 3)
rho1_new = get_rho(c_new, 1)
rho2_new = get_rho(c_new, 2)
rho3_new = get_rho(c_new, 3)
r1_new = get_r_new(1, rho1_new)
r2_new = get_r_new(2, rho2_new)
r3_new = get_r_new(3, rho3_new)
#r1dot_new = central_velocity_vector(r1_new, 0, 4)
r2dot_new = central_velocity_vector(r2_new, 0, 3)
#r3dot_new = central_velocity_vector(r3_new, 0, 4)
t1_new = new_time_obs_ITERATIVE(rho1_new, t1_new)
t2_new = new_time_obs_ITERATIVE(rho2_new, t2_new)
t3_new = new_time_obs_ITERATIVE(rho3_new, t3_new)
tau = [k * (t3_new - t2_new), k * (t1_new - t2_new), k * (t3_new - t1_new)] #(tau1, tau3, tau)
diff = old_rho - rho2_new
return rho2_new, r2_new, r2dot_new
range_2, x2, v2 = main()
#print(main())
def ecliptic(vec):
new_vec = [[vec[0]], [vec[1]], [vec[2]]]
new_vec = np.array(new_vec)
arr = [[1, 0, 0], [0, math.cos(eps), math.sin(eps)], [0, -math.sin(eps), math.cos(eps)]]
arr = np.array(arr)
ecliptic_coord = np.dot(arr, vec)
return ecliptic_coord[0], ecliptic_coord[1], ecliptic_coord[2]
def angularMomentum():
h = np.cross(x2, v2) * 365.2563835 / 2 / math.pi
return h
h = angularMomentum()
def eccentricity():
return (1 - magnitude(h) ** 2 / (mu * a)) ** 0.5
e = eccentricity()
def inclination():
z = [0, 0, 1]
return math.acos(np.dot(h, z) / magnitude(h)) * 180 / math.pi
i = inclination()
def LoAN():
sin_i = math.sin(i * math.pi / 180)
#print(sin_i)
x = [1, 0, 0]
y = [0, 1, 0]
sin_omega = np.dot(h, x) / (magnitude(h) * sin_i)
#print(sin_omega)
cos_omega = -1 * np.dot(h, y) / (magnitude(h) * sin_i)
#print(cos_omega)
return quadrantCheck(cos_omega, sin_omega)
loan = LoAN()
def AoP():
cos_U = (x2[0] * math.cos(loan * math.pi / 180) + x2[1] * math.sin(loan * math.pi / 180)) / (magnitude(x2))
sin_U = x2[2] / magnitude(r) / math.sin(i * math.pi / 180)
cos_nu = (a * (1 - e ** 2) / magnitude(x2) - 1) / e
sin_nu = (a * (1 - e ** 2) * np.dot(x2, v2) / magnitude(x2) / magnitude(h)) / e
#print(cos_U)
#print(sin_U)
return (quadrantCheck(cos_U, sin_U) - quadrantCheck(cos_nu, sin_nu)) % 360
aop = AoP()
def meanAnomaly():
cos_E = (1 - magnitude(x2) / a) / e
E = math.acos(cos_E)
M = (E - e * math.sin(E)) * 180 / math.pi
return M
M = meanAnomaly()
ecliptic_r2 = ecliptic(x2)
ecliptic_r2dot = ecliptic(v2)
print("range: ",range_2)
print("position: ",ecliptic_r2)
print("velocity: ",ecliptic_r2dot)
print("semimajor axis: ",a)
print("eccentricity: ",e)
print("orbit inclination: ", i)
print("LoAN: ",loan)
print("AoP: ",aop)
print("mean anomaly: ",M)
|
Java
|
UTF-8
| 1,993 | 2.953125 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package colabancariadelasuerte;
/**
*
* @author ederj
*/
public class Cola {
Nodo inicio=null;
Nodo fin=null;
void C (String N,int P){
Nodo nuevo=new Nodo();
nuevo.N=N;
nuevo.P=P;
nuevo.anterior=null;
nuevo.siguiente=null;
if (inicio==null){
inicio=nuevo;
fin=nuevo;
}else{
Nodo aux=fin;
aux.siguiente=nuevo;
nuevo.anterior=aux;
fin=nuevo;}
}
void S(char L,int I){
Nodo aux=inicio;
if(aux==null)return;
else{
while(aux!=null){
char L1=aux.N.charAt(0);
if(L==L1)aux.P=aux.P+I;
aux=aux.siguiente;
}
}
}
boolean isEmpty(){
if (inicio==null) return true;
return false;
}
String A (){
String salida;
Nodo aux=inicio;
Nodo aux2=aux.siguiente;
if ((aux.anterior==null)&&(aux.siguiente==null)){
salida=aux.N;
inicio=null;
}
else{
while(aux2!=null){
if(aux.P<aux2.P){
aux=aux2;
aux2=aux2.siguiente;
}else{
aux2=aux2.siguiente;
}}
salida=aux.N;
if(aux.anterior==null){
aux2=aux.siguiente;
aux2.anterior=null;
inicio=aux2;
aux.siguiente=null;
}else{
aux2=aux.anterior;
if(aux.siguiente!=null){
aux=aux.siguiente;
aux2.siguiente=aux;
aux.anterior=aux2;}
else{
aux2.siguiente=null;
aux.anterior=null;
}
}
}
return salida;
}
void recorrer(){
Nodo aux=inicio;
while(aux!=null){
System.out.println(aux.N+" "+aux.P);
aux=aux.siguiente;
}
}
}
|
C++
|
UTF-8
| 341 | 3.703125 | 4 |
[] |
no_license
|
#include<iostream>
using namespace std;
int sum_n(int num, int sum=0) //tail recursion.
{
if (num==0)
return sum;
return sum_n(num-1, sum+num);
}
int sums(int num)
{
if (num==0)
return 0;
return (num + sums(num-1));
}
int main()
{
cout<<sum_n(10)<<endl; // shows sum of first 10 terms from 1 to 10.
cout<<sums(10);
return 0;
}
|
Swift
|
UTF-8
| 1,744 | 2.765625 | 3 |
[] |
no_license
|
//
// DeviceSelectItemViewModel.swift
// rxswiftExampleApp
//
// Created by Serhiy on 2/15/18.
// Copyright © 2018 Serhiy. All rights reserved.
//
import Foundation
import RxSwift
protocol DeviceSelectItemViewModelType {
var id: Int { get }
var description: String { get }
var isChecked: Bool { get }
}
class DeviceSelectItemViewModel: DeviceSelectItemViewModelType {
var isChecked: Bool = false
var id: Int = 0
var description: String = ""
var model: TankMainInfoViewModelType!
init(with profile: DefaultProfile, and device: Device) {
switch device.type {
case .Engine:
if let id = profile.modules.engineId {
isChecked = id == device.deviceId
self.id = id
self.description = profile.engine.name
}
case .Gun:
if let id = profile.modules.gunId {
isChecked = id == device.deviceId
self.id = id
self.description = profile.gun.name
}
case .Suspension:
if let id = profile.modules.suspensionId {
isChecked = id == device.deviceId
self.id = id
self.description = profile.suspension.name
}
case .Turret:
if let id = profile.modules.turretId {
isChecked = id == device.deviceId
self.id = id
self.description = profile.turret.name
}
case .Radio:
if let id = profile.modules.radioId {
isChecked = id == device.deviceId
self.id = id
self.description = profile.radio.name
}
}
}
}
|
Java
|
UTF-8
| 1,907 | 3.1875 | 3 |
[] |
no_license
|
package controller;
import cs3500.animator.view.IView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import model.IAnimatorModel;
/**
* Represents the controller of the interactive animation. It also implements the ActionListener in
* order to register button clicks from user. Each button click will alter how the timer operates.
*/
public class InteractiveController implements IController, ActionListener {
private IView view;
private Timer t;
/**
* Constructs the interactive animation controller.
*
* @param model represents the animations model
* @param view represents the view of the animation
*/
public InteractiveController(IAnimatorModel model, IView view) {
if (model == null || view == null) {
throw new IllegalArgumentException("model or view is null");
}
this.view = view;
this.t = new Timer(view.getTempo(), new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
view.actionPerformed(e);
//model.incrementTick();
}
});
}
/**
* sets the the ActionListner and makes the panel visible.
*/
@Override
public void run() {
this.view.setActionListener(this);
this.view.makeVisible();
}
/**
* changes the animation accordingly by each button click.
*
* @param e the button that was clicked by the user
*/
@Override
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
switch (s) {
case "start button":
t.start();
break;
case "pause button":
t.stop();
break;
case "resume button":
if (t.isRunning()) {
break;
}
t.start();
break;
case "restart button":
view.setTick(0);
t.start();
break;
default:
return;
}
}
}
|
Swift
|
UTF-8
| 1,372 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
//
// CreatedManager.swift
// awesome_notifications
//
// Created by Rafael Setragni on 15/09/20.
//
import Foundation
public class CreatedManager {
static let shared:SharedManager = SharedManager(tag: Definitions.SHARED_CREATED)
public static func removeCreated(id:Int) -> Bool {
return shared.remove(referenceKey: String(id));
}
static func listCreated() -> [NotificationReceived] {
var returnedList:[NotificationReceived] = []
let dataList = shared.getAllObjects()
for data in dataList {
let received:NotificationReceived = NotificationReceived(nil).fromMap(arguments: data) as! NotificationReceived
returnedList.append(received)
}
return returnedList
}
static func saveCreated(received:NotificationReceived) {
shared.set(received.toMap(), referenceKey: String(received.id!))
}
static func getCreatedByKey(id:Int) -> NotificationReceived? {
guard let data:[String:Any?] = shared.get(referenceKey: String(id)) else {
return nil
}
return NotificationReceived(nil).fromMap(arguments: data) as? NotificationReceived
}
public static func cancelAllCreated() {
shared.removeAll()
}
public static func cancelCreated(id:Int) {
_ = shared.remove(referenceKey: String(id))
}
}
|
Python
|
UTF-8
| 2,006 | 4.0625 | 4 |
[] |
no_license
|
"""
# Evolutionary Computation HW #06
# Binary tournament selection experiment
- Student ID: 7110064490
- Name: Huang Sin-Cyuan(黃新荃)
- Email: dec880126@icloud.com
"""
from random import Random
import matplotlib.pyplot as plt
# A few useful constants
#
pop_size = 20
generations = 10
fit_range = 40
# Init the random number generator
#
prng = Random()
prng.seed(123)
# Let's suppose we have an imaginary problem that generates
# integer fitness values on some fixed range. We'll start by randomly
# initializing a population of fitness values
#
pop = [prng.randrange(0,fit_range) for i in range(pop_size)]
def plt_hist(pop, bin_limit=fit_range):
"""
Plot histogram of population fitness values
"""
plt.hist(pop, bins=range(0,bin_limit+1))
plt.grid(True)
plt.title('Distribution of Population')
plt.show()
def binary_tournament(pop_in: list, prng: Random):
"""
Binary tournament operator:
- Input: population of size N (pop_size)
- Output: new population of size N (pop_size), the result of applying selection
- Tournament pairs should be randomly selected
- All individuals from input population should participate in exactly 2 tournaments
"""
print(f"[>]{pop_in[0]} v.s {pop_in[1]} -> Winner is {max(pop_in)}")
pop_in.remove(min(pop_in))
return pop_in
# Let's iteratively apply our binary selection operator
# to the initial population and plot the resulting fitness histograms.
# This is somewhat like having a selection-only EA without any stochastic variation operators
#
competitors = []
print(f'[*]Initial Population: {pop}')
for gen in range(generations):
grouped_competitor = prng.choices(pop, k = 2)
competitors.append(grouped_competitor)
for value in grouped_competitor:
pop.remove(value)
print(f"[>]Competitor Group: {competitors}")
plt_hist(competitors)
new_pop = []
for _competitors in competitors:
new_pop.append(binary_tournament(_competitors, prng)[0])
plt_hist(new_pop)
print(new_pop)
|
Java
|
UTF-8
| 1,234 | 2.421875 | 2 |
[] |
no_license
|
package com.u2d.model;
import com.u2d.pattern.Onion;
import java.util.Map;
import java.util.HashMap;
/**
* Created by IntelliJ IDEA.
* User: eitan
* Date: Sep 22, 2005
* Time: 10:30:36 AM
*/
public class AtomicType
{
private static transient Map<Class, AtomicType> _typeCache = new HashMap<Class, AtomicType>();
public static AtomicType forClass(Class targetClass)
{
if (!(AtomicEObject.class.isAssignableFrom(targetClass)))
{
throw new RuntimeException("Cannot create Atomic Type for "+targetClass.getName());
}
if (_typeCache.get(targetClass) == null)
_typeCache.put(targetClass, new AtomicType(targetClass));
return (AtomicType) _typeCache.get(targetClass);
}
public static AtomicType forObject(AtomicEObject targetObject)
{
return forClass(targetObject.getClass());
}
// ====
private transient Onion _commands;
private AtomicType(Class instanceClass)
{
_commands = Harvester.simpleHarvestCommands(instanceClass,
new Onion(),
false, null);
}
public Onion commands() { return _commands; }
}
|
Python
|
UTF-8
| 1,551 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
"""Post messages to a specific queue dependent on their load."""
from celery_queue_rabbit.queues import custom_exchange, my_queues
import celery_queue_rabbit.celery_app as app
import celery
def send_custom_message(producer=None):
"""Send a custom message to our exchange with routing key high."""
id = celery.uuid()
message = {
"Body": {"Type": "environment", "Alias": "{{alias}}", "Properties": {}},
"Topic": "{{alias}}.environment.{{action}}",
"CallContext": {},
}
with app.queue_broker.producer_or_acquire(producer) as producer:
producer.publish(
message,
serializer="json",
exchange=custom_exchange,
declare=[custom_exchange],
routing_key="high_load",
retry=True)
return id
def send_to_text_reverse(producer=None):
"""Send a reverse_text task to our exchange with routing key low."""
id = celery.uuid()
message = {
"task": "celery_queue_rabbit.tasks.text.slowly_reverse_string",
"id": id,
"args": ["reverse me"],
"kwargs": {},
"retries": 0
}
with app.queue_broker.producer_or_acquire(producer) as producer:
producer.publish(
message,
serializer="json",
exchange=custom_exchange,
declare=[custom_exchange], # declares exchange, queue and binds.
routing_key="low_load")
return id
if __name__ == "__main__":
id = send_to_text_reverse()
print(f"task {id} on queue")
|
TypeScript
|
UTF-8
| 2,090 | 2.734375 | 3 |
[] |
no_license
|
import {Component,OnInit} from "@angular/core";
import {Response} from "@angular/http";
import {HttpService} from "./http.service";
import {User} from './user';
@Component({
selector:'htt',
template:`<div>
<ul>
<li *ngFor="let user of users" >
<p> Name of user : {{user?.name}}</p>
<p>Age of user {{user?.age}}</p>
</li>
</ul>
</div>`,
providers:[HttpService]
})
export class HttpComponent implements OnInit{
// podkluchaemsya k nashemu user-u
////едставления данных в папку app
users: User[] = [];
//pishem variable k provideru to est peremennoe i tip Providera chto bi mi mogli podkluchitsya k nemu
constructor( private _httpService :HttpService){}
ngOnInit(){
// return this._httpService.getData().subscribe((data: Response) => this.users =data.json());
// .subscribe proslushivaet sobitiya iz potoka
this._httpService.getData().subscribe((resp: Response) =>{
//Поскольку в json-файле данные
// располагаются непосредственно в элемента data, то в коде используем свойство data для получения данных
let userList = resp.json().data;
console.log(userList);
//See what we have inside of data
for(let index in userList){
console.log(userList[index]);
let user = userList[index];
// adding to array
this.users.push({name: user.userName, age: user.userAge});
}
} );
// this._httpService.getData()
// .subscribe((resp: Response) => {
// let usersList = resp.json().data;
// for(let index in usersList){
// console.log(usersList[index]);
// let user = usersList[index];
// this.users.push({name: user.userName, age: user.userAge});
// }
// });
}//ngOnInit
}
|
PHP
|
UTF-8
| 2,317 | 3.375 | 3 |
[] |
no_license
|
<?php
namespace classes\towns;
session_start();
session_destroy();
class Country
{
private $listTown = [];
public function __construct()
{
if(!empty($_SESSION['country']) && $_SESSION['country'] = []){
foreach ($_SESSION['country'] as $item){
$this->listTown[] = unserialize($_SESSION[$item]);
}
}
}
public function addTown(Town $town)
{
$this->listTown[] = $town;
$_SESSION['country'][] = serialize($town);
}
public function getCountryList()
{
if(empty($listTown)){
echo '<div>';
foreach ($this->listTown as $country){
echo '<p> Город: ' . $country->name . '.</p>';
echo '<p> Был основан в ' . $country->foundation . ' году.</p>';
echo '<p> Численность населения ' . $country->population . ' человек.</p>';
}
echo '</div>';
}else{
echo "<div>Города пока не добавлены.</div>";
}
}
}
//Конструктор класса Country должен проверить содержится ли что-либо в массиве $_SESSION['country']
// если это массив, то нужно перебрать его в цикле и используя функцию unserialize() восстановить объекты
// и записать их в listTown
//Реализовать метод добавления города addTown. Параметром передать объект класса Town (метод не должен
// принимать что-то другое) переданный объект записать в конец массива listTown а так же сериализованный объект
// записать в конец $_SESSION['country'].
//Реализовать метод getCountryList. Метод должен проверить содержится ли что-либо в массиве listTown
// если да то вывести используя html-разметку (можно по минимуму) ели нет, то выдать сообщение что города пока не добавлены
|
Java
|
UTF-8
| 287 | 1.789063 | 2 |
[] |
no_license
|
package by.deniskruglik.soapwebservice.dao;
import by.deniskruglik.soapwebservice.service.models.Message;
import org.springframework.stereotype.Component;
@Component
public class MessageDAO extends AbstractDAO<Message> {
public MessageDAO() {
super(Message.class);
}
}
|
Python
|
UTF-8
| 1,525 | 3.5 | 4 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
#!/usr/bin/env python
"""
SimpleMatcherModel.py: (part of speech, spelling) probability model
Usage:
from SimpleMatcherModel import SimpleMatcherModel as Model
m = Model("hillary_train")
m2 = Model("trump_train")
score = m.score(m2, test_file.read())
"""
__author__ = "Prakhar Sahay"
__date__ = "December 19th, 2016"
# import statements
import nltk
class SimpleMatcherModel():
def __init__(self, file):
self.word_transition_cfd = nltk.ConditionalFreqDist()
self.analyze(file)
# build a probability model from the training file
def analyze(self, file):
bigrams = []
# analyze each line as separate sample
for sample in file:
for sentence in nltk.sent_tokenize(sample):
words = nltk.word_tokenize(sentence)
bigrams.extend(nltk.bigrams(words))
# update distributions
self.word_transition_cfd += nltk.ConditionalFreqDist(bigrams)# word -> next word
# return positive number if self is better match for sample text
# return negative number if other model is better match
def score(self, other, sample):
pos_score = 0
neg_score = 0
for sentence in nltk.sent_tokenize(sample):
words = nltk.word_tokenize(sentence)
pos_score += self.count(words)
neg_score += other.count(words)
return pos_score - neg_score
def count(self, words):
# walk num_words-1 times
score = 0
for idx in range(1, len(words)):
fd = self.word_transition_cfd[words[idx - 1]]# most likely words to follow the previous word
score += words[idx] in fd.keys()
return score
|
PHP
|
UTF-8
| 293 | 2.890625 | 3 |
[] |
no_license
|
<?php namespace App\Model;
class Product {
public $name = '';
public $price = 0;
public $image = '';
public function __construct($name, $price = 0, $image = 'https://picsum.photos/200'){
$this->name = $name;
$this->price = $price;
$this->image = $image;
new \Exception();
}
}
|
Java
|
UTF-8
| 18,358 | 1.78125 | 2 |
[] |
no_license
|
package com.sketchproject.scheduler.fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.sketchproject.scheduler.R;
import com.sketchproject.scheduler.library.ConnectionDetector;
import com.sketchproject.scheduler.library.SessionManager;
import com.sketchproject.scheduler.util.AlertDialogManager;
import com.sketchproject.scheduler.util.Constant;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Scheduler Android App
* Created by Angga on 10/7/2015.
*/
public class ScreenSetting extends Fragment {
public static final String TAG = ScreenSetting.class.getSimpleName();
private final String KEY_ID = "id";
private final String KEY_TOKEN = "token";
private final String KEY_NAME = "name";
private final String KEY_WORK = "work";
private final String KEY_ABOUT = "about";
private final String KEY_USERNAME = "username";
private final String KEY_PASSWORD = "password";
private final String KEY_PASSWORD_NEW = "password_new";
private final String DATA_STATUS = "status";
private final String DATA_USER = "user";
private JSONObject settingData;
private Button buttonSave;
private EditText textName;
private EditText textWork;
private EditText textAbout;
private EditText textPassword;
private EditText textNewPassword;
private EditText textConfirmPassword;
private TextView infoName;
private TextView infoWork;
private TextView infoAbout;
private TextView infoPassword;
private TextView infoConfirmPassword;
private LinearLayout loadingScreen;
private ImageView loadingIcon;
private AnimationDrawable loadingAnimation;
private SessionManager session;
private AlertDialogManager alert;
private ConnectionDetector connectionDetector;
private String name;
private String work;
private String about;
private String password;
private String newPassword;
private String confirmPassword;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_menu_setting, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
alert = new AlertDialogManager();
connectionDetector = new ConnectionDetector(getContext());
session = new SessionManager(getActivity());
buttonSave = (Button) getActivity().findViewById(R.id.buttonSave);
textName = (EditText) getActivity().findViewById(R.id.name);
textWork = (EditText) getActivity().findViewById(R.id.work);
textAbout = (EditText) getActivity().findViewById(R.id.about);
textPassword = (EditText) getActivity().findViewById(R.id.password);
textNewPassword = (EditText) getActivity().findViewById(R.id.newPassword);
textConfirmPassword = (EditText) getActivity().findViewById(R.id.confirmPassword);
infoName = (TextView) getActivity().findViewById(R.id.infoName);
infoWork = (TextView) getActivity().findViewById(R.id.infoWork);
infoAbout = (TextView) getActivity().findViewById(R.id.infoAbout);
infoPassword = (TextView) getActivity().findViewById(R.id.infoPassword);
infoConfirmPassword = (TextView) getActivity().findViewById(R.id.infoConfirmPassword);
loadingScreen = (LinearLayout) getActivity().findViewById(R.id.loadingScreen);
loadingIcon = (ImageView) getActivity().findViewById(R.id.loadingIcon);
loadingIcon.setBackgroundResource(R.drawable.loading_animation);
loadingAnimation = (AnimationDrawable) loadingIcon.getBackground();
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
loadingScreen.setMinimumHeight(size.y);
buttonSave.setOnClickListener(new SaveSettingHandler());
retrieveUser();
}
/**
* Retrieving user account data
*/
private void retrieveUser(){
if (connectionDetector.isNetworkAvailable()) {
RetrieveSettingHandler scheduleTask = new RetrieveSettingHandler();
scheduleTask.execute();
} else {
Toast.makeText(getContext(), getString(R.string.disconnect), Toast.LENGTH_LONG).show();
}
}
/**
* Async task to retrieve user by id and token from database
* this method will passing JSON object as [status] and [user]
*/
private class RetrieveSettingHandler extends AsyncTask<Object, Void, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingScreen.setVisibility(View.VISIBLE);
loadingAnimation.start();
}
@Override
protected JSONObject doInBackground(Object[] params) {
JSONObject jsonResponse = null;
try {
URL scheduleUrl = new URL(Constant.URL_ACCOUNT);
HttpURLConnection connection = (HttpURLConnection) scheduleUrl.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter(KEY_TOKEN, session.getUserDetails().get(SessionManager.KEY_TOKEN))
.appendQueryParameter(KEY_ID, session.getUserDetails().get(SessionManager.KEY_ID));
String query = builder.build().getEncodedQuery();
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String responseData = sb.toString();
jsonResponse = new JSONObject(responseData);
} else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
} catch (MalformedURLException e) {
Log.e(TAG, "Exception caught: " + e);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONObject result) {
settingData = result;
loadingScreen.setVisibility(View.GONE);
loadingAnimation.stop();
populateSettingResponse();
}
}
/**
* Populating data from database to input text
* check if data null or not
* catch exception if json cannot parsed
*/
public void populateSettingResponse() {
if (settingData == null) {
alert.showAlertDialog(getContext(), getString(R.string.error_title), getString(R.string.error_message));
} else {
try {
if (settingData.getString(DATA_STATUS).equals(Constant.STATUS_SUCCESS)) {
JSONObject setting = new JSONObject(settingData.getString(DATA_USER));
textName.setText(setting.getString(KEY_NAME));
textWork.setText(setting.getString(KEY_WORK));
textAbout.setText(setting.getString(KEY_ABOUT));
} else {
alert.showAlertDialog(getContext(), getString(R.string.restrict_title), getString(R.string.restrict_message));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}
/**
* form validation
* check length and required data
*
* @return boolean
*/
private boolean isValidated() {
boolean checkName = true;
boolean checkWork = true;
boolean checkAbout = true;
boolean checkPassword = true;
boolean checkConfirmPassword = true;
name = textName.getText().toString();
if (name.trim().isEmpty()) {
infoName.setText(getString(R.string.validation_name_empty));
infoName.setVisibility(View.VISIBLE);
checkName = false;
} else if (name.length() > 100) {
infoName.setText(getString(R.string.validation_name_maxlength));
infoName.setVisibility(View.VISIBLE);
checkName = false;
}
work = textWork.getText().toString();
if (work.trim().isEmpty()) {
infoWork.setText(getString(R.string.validation_work_empty));
infoWork.setVisibility(View.VISIBLE);
checkWork = false;
} else if (name.length() > 100) {
infoWork.setText(getString(R.string.validation_work_maxlength));
infoWork.setVisibility(View.VISIBLE);
checkWork = false;
}
about = textAbout.getText().toString();
if (about.trim().isEmpty()) {
infoAbout.setText(getString(R.string.validation_about_empty));
infoAbout.setVisibility(View.VISIBLE);
checkAbout = false;
} else if (about.length() > 300) {
infoAbout.setText(getString(R.string.validation_about_maxlength));
infoAbout.setVisibility(View.VISIBLE);
checkAbout = false;
}
password = textPassword.getText().toString();
if (password.trim().isEmpty()) {
infoPassword.setText(getString(R.string.validation_password_empty));
infoPassword.setVisibility(View.VISIBLE);
checkPassword = false;
}
newPassword = textNewPassword.getText().toString();
confirmPassword = textConfirmPassword.getText().toString();
if (!newPassword.trim().equals(confirmPassword.trim())) {
infoConfirmPassword.setText(getString(R.string.validation_password_new_mismatch));
infoConfirmPassword.setVisibility(View.VISIBLE);
checkConfirmPassword = false;
}
return checkName && checkWork && checkAbout && checkPassword && checkConfirmPassword;
}
/**
* Listener for button save
* check connection, reset validation info and revalidate
* passing params to Async task
*/
private class SaveSettingHandler implements View.OnClickListener {
@Override
public void onClick(View v) {
if (connectionDetector.isNetworkAvailable()) {
infoName.setVisibility(View.GONE);
infoWork.setVisibility(View.GONE);
infoAbout.setVisibility(View.GONE);
infoPassword.setVisibility(View.GONE);
infoConfirmPassword.setVisibility(View.GONE);
if (isValidated()) {
new UpdateSettingHandler().execute(name, work, about, password, newPassword);
} else {
alert.showAlertDialog(getContext(), getString(R.string.validation), getString(R.string.validation_message));
}
} else {
Toast.makeText(getContext(), getString(R.string.disconnect), Toast.LENGTH_LONG).show();
}
}
}
/**
* Async task to update user by id and token to database
* this method will receive status transaction from REST API
*/
private class UpdateSettingHandler extends AsyncTask<String, String, JSONObject> {
private ProgressDialog progress;
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage(getString(R.string.loading_setting_update));
progress.setIndeterminate(false);
progress.setCancelable(false);
progress.show();
}
@Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonResponse = null;
try {
URL accountUrl = new URL(Constant.URL_ACCOUNT_UPDATE);
HttpURLConnection connection = (HttpURLConnection) accountUrl.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter(KEY_NAME, params[0])
.appendQueryParameter(KEY_WORK, params[1])
.appendQueryParameter(KEY_ABOUT, params[2])
.appendQueryParameter(KEY_PASSWORD, params[3])
.appendQueryParameter(KEY_PASSWORD_NEW, params[4])
.appendQueryParameter(KEY_ID, session.getUserDetails().get(SessionManager.KEY_ID))
.appendQueryParameter(KEY_USERNAME, session.getUserDetails().get(SessionManager.KEY_USERNAME))
.appendQueryParameter(KEY_TOKEN, session.getUserDetails().get(SessionManager.KEY_TOKEN));
String query = builder.build().getEncodedQuery();
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String responseData = sb.toString();
jsonResponse = new JSONObject(responseData);
} else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
} catch (Exception e) {
Log.e(TAG, "Exception caught: " + e);
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONObject result) {
settingData = result;
progress.dismiss();
handleSaveSettingResponse();
}
}
/**
* Handle transaction status from database after update the setting
* [RESTRICT] the token had sent is not available on server
* [MISMATCH] the current password is mismatch with database which related with account
* [SUCCESS] the request update and transaction has been completing successfully
* [FAILED] something is getting wrong on server or nothing data changes sent
*/
public void handleSaveSettingResponse() {
if (settingData == null) {
alert.showAlertDialog(getContext(), getString(R.string.error_title), getString(R.string.error_message));
} else {
try {
textPassword.setText("");
String status = settingData.getString(DATA_STATUS);
switch (status) {
case Constant.STATUS_RESTRICT:
alert.showAlertDialog(getContext(), getString(R.string.restrict_title), getString(R.string.restrict_message));
break;
case Constant.STATUS_MISMATCH:
infoPassword.setText(getString(R.string.validation_password_mismatch));
infoPassword.setVisibility(View.VISIBLE);
alert.showAlertDialog(getContext(), getString(R.string.action_failed), getString(R.string.message_setting_password_mismatch));
break;
case Constant.STATUS_SUCCESS:
alert.showAlertDialog(getContext(), getString(R.string.action_updated), getString(R.string.message_setting_update_success));
break;
case Constant.STATUS_FAILED:
alert.showAlertDialog(getContext(), getString(R.string.action_failed), getString(R.string.message_setting_update_failed));
break;
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}
}
|
TypeScript
|
UTF-8
| 560 | 2.5625 | 3 |
[] |
no_license
|
export declare type GoogleErrorType = 'InvalidGrant' | 'UnauthorizedClient' | 'NotACalendarUser';
export interface InvalidGrant {
kind: 'InvalidGrant';
err: Error;
}
export interface UnauthorizedClient {
kind: 'UnauthorizedClient';
err: Error;
}
export interface NotACalendarUser {
kind: 'NotACalendarUser';
err: Error;
}
export declare type GoogleError = InvalidGrant | UnauthorizedClient | NotACalendarUser;
export declare function createGoogleError<T extends GoogleErrorType>(kind: T, err?: Error): {
kind: T;
err: Error;
};
|
Java
|
UTF-8
| 5,464 | 1.953125 | 2 |
[] |
no_license
|
package com.example.covidtracker;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.razerdp.widget.animatedpieview.AnimatedPieView;
import com.razerdp.widget.animatedpieview.AnimatedPieViewConfig;
import com.razerdp.widget.animatedpieview.callback.OnPieSelectListener;
import com.razerdp.widget.animatedpieview.data.IPieInfo;
import com.razerdp.widget.animatedpieview.data.SimplePieInfo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView deathcount;
TextView recoveredcount;
TextView confirmedcount;
TextView todaycases;
TextView todaydeath;
String confirmed;
ArrayList<String>arrayList;
String recovered;
String Death;
String cases_today;
String cases_death;
JSONArray array;
Arrays arrays;
ArrayList<String> images;
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<>();
images = new ArrayList<String>();
spinner = findViewById(R.id.spinner);
todaycases = findViewById(R.id.todaycasescount);
todaydeath = findViewById(R.id.todaydeathcount);
confirmedcount = findViewById(R.id.deathscount);
recoveredcount = findViewById(R.id.recoveredcount);
deathcount = findViewById(R.id.confirmedcount);
spinner.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
cases();
}
void pie()
{
AnimatedPieView mAnimatedPieView = findViewById(R.id.pie);
AnimatedPieViewConfig config = new AnimatedPieViewConfig();
config.startAngle(-90)// Starting angle offset
.addData(new SimplePieInfo(Integer.parseInt(confirmed) ,Color.parseColor("#FFBB86FC"), "Cases"))//Data (bean that implements the IPieInfo interface)
.addData(new SimplePieInfo(Integer.parseInt(Death), Color.parseColor("#FF6200EE"), "Deaths")).drawText(true)
.duration(2000);// draw pie animation duration
// The following two sentences can be replace directly 'mAnimatedPieView.start (config); '
mAnimatedPieView.applyConfig(config);
mAnimatedPieView.start();
}
void cases ()
{
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
final String url = "https://corona.lmao.ninja/v2/countries";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url,null ,new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
array = response;
for(int i=0;i<response.length();i++)
{
try {
JSONObject responseObj1 = response.getJSONObject(i);
JSONObject response2 = responseObj1.getJSONObject("countryInfo");
arrayList.add(responseObj1.getString("country"));
images.add(response2.getString("flag"));
Customadapter customAdapter=new Customadapter(getApplicationContext(),images,arrayList);
spinner.setAdapter(customAdapter);
//pie();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
deathcount.setText("akshat");
}
});
queue.add(jsonArrayRequest);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
try {
JSONObject responseObj = array.getJSONObject(position);
Death = (responseObj.getString("deaths"));
recovered = (responseObj.getString("recovered"));
confirmed = (responseObj.getString("cases"));
cases_today = responseObj.getString("todayCases");
cases_death = responseObj.getString("todayDeaths");
recoveredcount.setText(String.valueOf(recovered));
confirmedcount.setText(String.valueOf(confirmed));
todaycases.setText(cases_today);
todaydeath.setText(cases_death);
deathcount.setText(String.valueOf(Death));
pie();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
Java
|
UTF-8
| 1,433 | 2.328125 | 2 |
[] |
no_license
|
package com.hotniao.live.model;
import com.hn.library.http.BaseResponseModel;
import java.util.List;
/**
* 首页分类
* 作者:Mr.X
* 时间:11:06
*/
public class HnHomeLiveCateModel extends BaseResponseModel {
/**
* d : [{"icon":"3","id":"3","is_food":"0","name":"第一个类型"},{"icon":"4","id":"4","is_food":"0","name":"第2个类型"}]
*/
private List<DEntity> d;
public void setD(List<DEntity> d) {
this.d = d;
}
public List<DEntity> getD() {
return d;
}
public static class DEntity {
/**
* icon : 3
* id : 3
* is_food : 0
* name : 第一个类型
*/
private String icon;
private String id;
private String is_food;
private String name;
public void setIcon(String icon) {
this.icon = icon;
}
public void setId(String id) {
this.id = id;
}
public void setIs_food(String is_food) {
this.is_food = is_food;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public String getId() {
return id;
}
public String getIs_food() {
return is_food;
}
public String getName() {
return name;
}
}
}
|
Shell
|
UTF-8
| 1,575 | 4.28125 | 4 |
[] |
no_license
|
#!/bin/bash
##################
# ============== #
# Volume Control #
# ============== #
##################
# Raises or lowers volume of default sink with pactl, but also clamps it to an upper/lower limit
# Useage:
# volume.sh <up|down>
# Config file stored in ~/.config/volume.conf
config_dir=~/.config/sound/
config_file='volume.conf'
config="${config_dir}${config_file}"
# Volume is saved to config file
cur_vol=""
cur_vol_file='current-volume'
# Creates file if none
function startup {
mkdir -p "$config_dir"
touch "$config"
chmod 666 "$config"
echo 'max="100"' >> "$config"
echo 'min="0"' >> "$config"
echo 'step="5"' >> "$config"
echo 'init_sink_vol="50"' >> "$config"
echo '' >> "$config"
}
function create_conf {
touch "${config_dir}${cur_vol_file}.conf"
chmod 666 "${config_dir}${cur_vol_file}.conf"
echo '25' > "${config_dir}${cur_vol_file}.conf"
}
# Raises/lowers volume and clamps it to max/min
function change_volume {
if [[ "$1" == 'up' ]]; then
let cur_vol+="$step"
if (( cur_vol > max )); then
let cur_vol="$max"
fi
elif [[ "$1" == 'down' ]]; then
let cur_vol-="$step"
if (( cur_vol < min )); then
let cur_vol="$min"
fi
elif [[ "$1" == "change-sink" ]]; then
let cur_vol="$init_sink_vol"
else
exit 1
fi
pactl set-sink-volume @DEFAULT_SINK@ "$cur_vol"%
}
# main:
if ! [ -e "$config" ]; then
startup
fi
source "$config"
if ! [ -e "${config_dir}${cur_vol_file}" ]; then
create_conf
fi
cur_vol="$(<${config_dir}${cur_vol_file})"
change_volume "$1"
echo "$cur_vol" > "${config_dir}${cur_vol_file}"
exit 0
|
C
|
UTF-8
| 1,902 | 3.125 | 3 |
[] |
no_license
|
/*
* Copyright (C) 1986,1987,1988,1989,1990 Sun Microsystems, Inc.
* All rights reserved.
*/
#ident "@(#)getname.c 1.5 96/04/25 SMI" /* SMI4.1 1.3 */
#include <stdio.h>
#include <string.h>
#define iseol(c) (c == 0 || c == '\n' || strchr(com, c) != NULL)
#define issep(c) (strchr(sep, c) != NULL)
#define isignore(c) (strchr(ignore, c) != NULL)
/*
* getline()
* Read a line from a file.
* What's returned is a cookie to be passed to getname
*/
char **
getline(line, maxlinelen, f, lcount, com)
char *line;
int maxlinelen;
FILE *f;
int *lcount;
char *com;
{
char *p;
static char *lp;
do {
if (! fgets(line, maxlinelen, f)) {
return (NULL);
}
(*lcount)++;
} while (iseol(line[0]));
p = line;
for (;;) {
while (*p) {
p++;
}
if (*--p == '\n' && *--p == '\\') {
if (! fgets(p, maxlinelen, f)) {
break;
}
(*lcount)++;
} else {
break;
}
}
lp = line;
return (&lp);
}
/*
* getname()
* Get the next entry from the line.
* You tell getname() which characters to ignore before storing them
* into name, and which characters separate entries in a line.
* The cookie is updated appropriately.
* return:
* 1: one entry parsed
* 0: partial entry parsed, ran out of space in name
* -1: no more entries in line
*/
getname(name, namelen, ignore, sep, linep, com)
char *name;
int namelen;
char *ignore;
char *sep;
char **linep;
char *com;
{
register char c;
register char *lp;
register char *np;
lp = *linep;
do {
c = *lp++;
} while (isignore(c) && !iseol(c));
if (iseol(c)) {
*linep = lp - 1;
return (-1);
}
np = name;
while (! issep(c) && ! iseol(c) && np - name < namelen) {
*np++ = c;
c = *lp++;
}
lp--;
if (np - name < namelen) {
*np = 0;
if (iseol(c)) {
*lp = 0;
} else {
lp++; /* advance over separator */
}
} else {
*linep = lp;
return (0);
}
*linep = lp;
return (1);
}
|
JavaScript
|
UTF-8
| 1,458 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
function drawCoordinates(P, pointSize=1)
{
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(P[0], P[1], pointSize, 0, Math.PI * 2, true);
ctx.fill();
}
function findMidPoint(P1, P2)
{
var MP = [0,0]
MP[0] = Math.floor((P1[0]+P2[0])/2);
MP[1] = Math.floor((P1[1]+P2[1])/2);
return MP;
}
function initSystem(array)
{
for (var i = array.length - 1; i >= 0; i--) {
drawCoordinates(array[i])
}
makeFractal()
}
function drawNextPoint()
{
var randIdx = Math.floor(Math.random() * Figure.length);
while(PrevVertex == randIdx)
{
randIdx = Math.floor(Math.random() * Figure.length);
}
PrevVertex = randIdx
MP = findMidPoint(Figure[randIdx], MP)
drawCoordinates(MP)
PointCount = PointCount + 1
if(PointCount == DepthLevel)
{
clearTimeout(timer)
}
}
function makeFractal()
{
timer = setInterval(drawNextPoint, 0.25)
}
var timer
var canvas = document.createElement("CANVAS");
canvas.width = 750
canvas.height = 750
ctx = canvas.getContext('2d')
var MP = [Math.floor((canvas.width-50)/2), Math.floor((canvas.height-50)/2)]
var Triangle = [[Math.floor((canvas.width-50)/2), 25], [25, canvas.height-25], [canvas.width-25, canvas.height-25]]
var Square = [[25, 25], [canvas.width-25, 25], [25, canvas.height-25], [canvas.width-25, canvas.height-25]]
var PrevVertex = -1
var Figure = Square
DepthLevel = 50000
PointCount = 0
document.body.appendChild(canvas)
ctx.clearRect(0, 0, 500, 500);
initSystem(Figure)
|
C
|
UTF-8
| 2,756 | 2.578125 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rev_algorithm1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oyenyi- <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/14 15:34:06 by oyenyi- #+# #+# */
/* Updated: 2018/08/20 16:18:52 by oyenyi- ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/filler.h"
#include "../libft/libft.h"
void place_token_rev(t_map_info *info, t_player *me)
{
while (info->piece_y >= info->p_top_start)
{
info->place_flag = (info->y_place - (info->p_bottom_end -
info->p_top_start + 1) < 0 ? 2 : 0);
if (info->place_flag == 2)
return ;
info->map_x = info->x_place1;
info->piece_x = info->p_left_start;
while (info->piece_x <= info->p_right_end)
{
info->place_flag = (info->x_place1 + (info->p_right_end -
info->p_left_start + 1) > info->x_col ? 1 : 0);
if (info->place_flag == 1)
return ;
if (info->piece[info->piece_y][info->piece_x] != '.')
info->tmp_map[info->map_y][info->map_x] = me->letter;
info->place_coord_x = info->x_place1 - info->p_left_start;
info->place_coord_y = info->map_y - info->p_top_start;
info->map_x++;
info->piece_x++;
}
info->map_y--;
info->piece_y--;
}
}
int rev_move(t_map_info *info)
{
if (info->place_flag == 1)
{
info->y_place--;
info->x_place1 = 0;
}
else if (info->place_flag == 2)
return (1);
else
info->x_place1++;
return (0);
}
void rev_algo2(t_map_info *info, t_player *me)
{
save_map_tmp(info);
get_shape_nbr(info);
initial_piece(info);
place_token_rev(info, me);
letter_nbr(info);
letter_tmp_nbr(info);
}
void rev_algo4(t_map_info *info, t_player *me)
{
rev_algo2(info, me);
if (!(check_placement(info, me)))
{
send_coord(info);
info->modulo++;
info->y_place = info->y_row - 1;
map_algo(info);
}
else
{
if (!rev_move(info))
save_map_tmp(info);
else
{
ft_putendl("0 0");
return ;
}
}
}
void algorithm1(t_map_info *info, t_player *me)
{
if (me->letter == 'X')
{
if (info->modulo % 2)
place_token_algo(info, me);
else
place_token_algo1(info, me);
}
else
{
if (info->modulo % 2)
rev_algo4(info, me);
else
rev_algo4_1(info, me);
}
}
|
C#
|
UTF-8
| 1,232 | 3.875 | 4 |
[] |
no_license
|
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace MatchPhoneNumber
{
class Program
{
static void Main(string[] args)
{
// A valid phone number from Sofia has the following characteristics:
// - It starts with "+359"
// - Then, it is followed by the area code (always 2)
// - After that, it’s followed by the number itself:
// - The number consists of 7 digits (separated in two groups of 3 and 4 digits respectively).
// - The different parts are separated by either a space or a hyphen('-').
string phoneNumbers = Console.ReadLine();
string pattern = @"(?:^|\s)\+359(\s|-)2\1\d{3}\1\d{4}\b";
Regex regex = new Regex(pattern);
MatchCollection matchedPhoneNumbers = regex.Matches(phoneNumbers);
var phoneNumberMatches = matchedPhoneNumbers
.Cast<Match>()
.Select(x => x.Value.Trim())
.ToArray();
// Print the valid phone numbers on the console, separated by a comma and a space “, ”
Console.WriteLine(string.Join(", ", phoneNumberMatches));
}
}
}
|
JavaScript
|
UTF-8
| 6,265 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
var csvStringState;
async function readTextFile()
{
await fetch('http://34.69.40.232:5000/prueba2.txt', {mode: 'no-cors'})
//35.188.134.148
.then(response => response.text())
.then(data=> {
var someText = data.replace(/(\r\n|\n|\r)/gm, "\n" );
csvStringState = someText.split("`");
console.log(typeof (csvStringState));
console.log(csvStringState);
})
.catch(error => console.error(error));
}
// var csvStringState = readTextFile();
var objeto = {};
var csvConfig = {
noheader:false,
trim:true}
function createPro(nProces)
{
for (let index = 0; index < nProces; index++)
{
$(".bolas").append("<div id = 'procesador' class = 'bola_p1'></div>");
}
}
function createMat(n)
{
for (let index = 0; index < n; index++) {
$(".matrices").append("<span class='dot'></span>");
}
}
function writeNum(clase,n, tag1, tag2)
{
$( clase ).replaceWith( tag1+ n + tag2 );
}
function resolveAfter1Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 1000);
});
}
async function Simulation() {
await readTextFile();
console.log(csvStringState[0])
const stateArrayInit=await csv(csvConfig).fromString(csvStringState[0]);
console.log("stateArrayInit " + stateArrayInit[0].procesT);
var nProces = stateArrayInit[0].procesT;
console.log("nProces " + nProces);
createPro(nProces);
createMat(100);
for (let index = 0; index < csvStringState.length; index++) {
console.log("State it: " + index);
const stateArray=await csv(csvConfig).fromString(csvStringState[index]);
//console.log(stateArray);
if(stateArray.length != 0 )
{
console.log(stateArray);
nodeList = document.querySelectorAll("div.bola_p1");
nodeListM = document.querySelectorAll(".dot");
for (let k = 0; k < stateArrayInit.length; k++) {
await resolveAfter1Seconds();
if(stateArray[k].matrizCreada == "0" || stateArray[k].matrizCreada == "1")
{
if (stateArray[k].hold == "1") {
var id = stateArray[k].idMatriz;
console.log("Hold:" + stateArray[k].idMatriz);
nodeListM[id].style.backgroundColor = "purple";
countH++;
hold = true;
writeNum(".numT",countH,"<h4 class=numT>","</h4>" );
}else if (stateArray[k].mult == "1") {
var id = stateArray[k].idMatriz;
nodeListM[id].style.backgroundColor = "blue";
await resolveAfter1Seconds() - .5;
nodeListM[id].style.backgroundColor = "black";
if(hold == true)
{
countH-=1;
hold = false
writeNum(".numT",countH,"<h4 class=numT>","</h4>" );
}
console.log("Mult:" + stateArray[k].idMatriz);
console.log("borrar " + stateArray[k].idMatriz);
}else{
}
}
await resolveAfter1Seconds();
if (fail == true) {
var num = countF;
writeNum(".numF",num,"<h4 class=numF>","</h4>");
fail = false;
}
var status = stateArray[k].working;
console.log("STATUS: " + status);
if (status == 0) {
var id = stateArray[k].nProces;
console.log("Este es el id:" + id);
console.log("Estoy en NO TRABAJO:");
// let idx = stateArray.findIndex(i => i.nProces === id);
// console.log("Este es su indice de id " + idx);
nodeList[id].style.backgroundColor = "red";
}else if(status == 1){
var id = stateArray[k].nProces;
console.log("Estoy en TRABAJANDO:");
nodeList[id].style.backgroundColor = "green";
}else if(status == 3){
var id = stateArray[k].nProces;
console.log("Estoy en RC:");
nodeList[id].style.backgroundColor = "yellow";
writeNum(".sign","RC","<div class = sign>","</div>");
await resolveAfter1Seconds();
writeNum(".sign","","<div class = sign>","</div>");
//nodeList[id].style.backgroundColor = "red";
fail = true;
++countF;
}else if(status == 2){
var id = stateArray[k].nProces;
console.log("Estoy en RB:");
nodeList[id].style.backgroundColor = "yellow";
writeNum(".sign","RB","<div class = sign>","</div>");
await resolveAfter1Seconds();
writeNum(".sign","","<div class = sign>","</div>");
//nodeList[id].style.backgroundColor = "red";
fail = true;
++countF;
}else{}
var num = stateArray[k].nFinish;
writeNum(".numC",num,"<h4 class=numC>","</h4>");
}
}else{
console.log("nada");
}
}
}
Simulation();
var n = 6;
var holdList;
var nodeList;
var nodeListM;
var fail = false;
var hold = false;
var temp = 0;
var countH = 0;
var countF = 0;
var countC = 0;
var arr = new Array();
|
PHP
|
UTF-8
| 2,662 | 2.765625 | 3 |
[] |
no_license
|
<?php
// Create connection
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
// this function get the tasks count and echo the message and control render table
function echo_allocate_count($db){
$check_empty_task = "SELECT COUNT(*) AS count FROM `allocate_resources`";
$empty_task = $db->query($check_empty_task);
$len_task = $empty_task->fetch_assoc()['count'];
if ($len_task > 1){
$taskortasks = ($len_task == 1) ? " Recored In The allocate resources table" : " Recoreds allocate resources table.";
echo 'Found: ' . $len_task . $taskortasks;
return true;
} else {
echo 'Found: ' . $len_task . $taskortasks;
return false;
}
}
function render_allocate_table($db){
$sql = "SELECT * FROM `allocate_resources` ORDER BY id DESC";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output main table data
$html_data = '<button id="excel_allocate_download" class="excelbtn" data-task="4" data-table="allocate" >Download Excel Report</button>
<table id="allocate_table" class="styled_table table2" data-table="allocate" >
<tr >
<th data-table="allocate" class="taskname_allocate" >Task Name</th>
<th data-table="allocate" class="duration_allocate" >duration</th>
<th data-table="allocate" class="start_allocate" >Start Date</th>
<th data-table="allocate" class="finish_allocate" >Finish Date</th>
<th data-table="allocate" class="resource_allocate" >Resource Name</th>
</tr>
<tr>';
// output data of each row
while($row = $result->fetch_assoc()) {
$html_data .= '<tr class="datarow" data-table="allocate" data-row-id="' . $row["id"] .'">';
$html_data .= '<td class="taskname_allocate" data-table="allocate" >' . $row["task_name"] .'</td>';
$html_data .= '<td class="duration_allocate" data-table="allocate" >'. $row["duration"] .' days</td>';
$html_data .= '<td class="start_allocate" data-table="allocate" >'. $row["start"] .'</td>';
$html_data .= '<td class="finish_allocate" data-table="allocate" >'. $row["finish"] .'</td>';
$html_data .= '<td class="resource_allocate" data-table="allocate" >'. $row["resource_name"] .'</td></tr>';
}
$html_data .= '</table>';
echo $html_data;
} else {
echo "0 results";
}
$db->close();
}
?>
|
Java
|
UTF-8
| 2,099 | 2.078125 | 2 |
[] |
no_license
|
package io.anotherwise.tarefarealm;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import io.anotherwise.tarefarealm.model.Tarefa;
import io.anotherwise.tarefarealm.model.TarefaAdapter;
import io.realm.Realm;
import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
ListView listView;
TarefaAdapter adapter;
RealmResults<Tarefa> tarefas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tarefa tarefa = tarefas.get(position);
Intent intent = new Intent(MainActivity.this, TarefaActivity.class);
intent.putExtra("id", tarefa.getId());
startActivity(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
loadListView();
}
private void loadListView() {
Realm realm = Realm.getInstance(this);
tarefas = realm.where(Tarefa.class).findAll();
adapter = new TarefaAdapter(this, tarefas);
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_nova) {
Intent intent = new Intent(MainActivity.this, TarefaActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
|
Java
|
UTF-8
| 800 | 2.078125 | 2 |
[] |
no_license
|
package com.huang.springbootdemo.service.Pro_Choice.Impl;
import com.huang.springbootdemo.entity.Pro_Choice;
import com.huang.springbootdemo.mapper.Pro_ChoiceMapper;
import com.huang.springbootdemo.service.Pro_Choice.Pro_ChoiceService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class Pro_ChoiceServiceImpl implements Pro_ChoiceService {
@Resource
Pro_ChoiceMapper pro_choiceMapper;
@Override
public Pro_Choice getChoiceProById(int pro_no) {
Pro_Choice pro_choice = pro_choiceMapper.getChoiceProById(pro_no);
return pro_choice;
}
@Override
public List<Integer> getAllChoiceId() {
List<Integer> list = pro_choiceMapper.getAllChoiceId();
return list;
}
}
|
Python
|
UTF-8
| 205 | 2.59375 | 3 |
[] |
no_license
|
from unittest import TestCase
from vit import *
class TestVat(TestCase):
def test_vat(self):
list = [0.2, 0.5, 4.59, 6]
self.assertAlmostEqual(vat_faktura(list),vat_paragon(list),1)
|
C++
|
UTF-8
| 2,486 | 2.5625 | 3 |
[] |
no_license
|
#ifndef CAR_H__
#define CAR_H__
#include "V2XDataSource.hpp"
namespace v2x {
class Car : public V2XDataSource
{
public:
Car();
virtual ~Car();
virtual const CTempId getTempId() const override;
virtual const CLatitude getLatitude() const override;
virtual const CLongitude getLongitude() const override;
virtual const CElevation getElevation() const override;
virtual const CPositionAccuracy getPositionAccuracy() const override;
virtual const CTransmissionState getTransmissionState() const override;
virtual const CSpeed getSpeed() const override;
virtual const CHeading getHeading() const override;
virtual const CSteeringWheelAngle getSteeringWheelAngle() const override;
virtual const CAccelerationSet4Way getAccelerationSet4Way() const override;
virtual const CBrakeSystemStatus getBrakeSystemStatus() const override;
virtual const CVehicleSize getVehicleSize() const override;
virtual const CVehicleType getVehicleType() const override;
virtual CDSecond getDsecond() const override;
void setTempId(const CTempId& tempId) override;
void setLatitude(const CLatitude& latitude) override;
void setLongitude(const CLongitude& longitude) override;
void setElevation(const CElevation& elevation) override;
void setPositionAccuracy(const CPositionAccuracy& positionAccuracy) override;
void setTransmissionState(const CTransmissionState& transmissionState) override;
void setSpeed(const CSpeed& speed) override;
void setHeading(const CHeading& heading) override;
void setSteeringWheelAngle(const CSteeringWheelAngle& steeringWheelAngle) override;
void setAccelerationSet4Way(const CAccelerationSet4Way& accelerationSet4Way) override;
void setBrakeSystemStatus(const CBrakeSystemStatus& brakeSystemStatus) override;
void setVehicleSize(const CVehicleSize& vehicleSize) override;
void setVehicleType(const CVehicleType& vehicleType) override;
void setDSecond(const CDSecond & dsecond) override;
private:
CTempId tempId_;
CLatitude latitude_;
CLongitude longitude_;
CElevation elevation_;
CPositionAccuracy positionAccuracy_;
CTransmissionState transmissionState_;
CSpeed speed_;
CHeading heading_;
CSteeringWheelAngle steeringWheelAngle_;
CAccelerationSet4Way accelerationSet4Way_;
CBrakeSystemStatus brakeSystemStatus_;
CVehicleSize vehicleSize_;
CVehicleType vtype_;
CDSecond dsecond_;
};
} //v2x
#endif
|
Markdown
|
UTF-8
| 1,078 | 3.59375 | 4 |
[] |
no_license
|
# Android-hangman-game
The application is developed for the course Application Development for Android at NTNU.
### Game description
This is a hangman word game. The game generates a word for the player to guess.
The player guesses the word by choosing one and one letter. If guessed letter is in the word,
then the letter will appear in the word and taken out the guessing board with all letters from the alphabet.
But if the letter is not in the word, then a body part will be added to the gallows. The player wins if they
guess the word before the person is hung and loses if the full body is hanging from the gallows.
### Features
* Language: English and Norwegian.
* Placeholders for the generated word which shows how many letter it is in the word.
* Game rule available for the player before and during the game.
* Displays all guessed letters.
* User gives input guesses by choosing a letter from board.
* Popup after ended game which shows game status(won/lost).
* Option to go back to game menu during the game.
### Technologies
* Android Studio
* Java
|
Java
|
UTF-8
| 170 | 1.734375 | 2 |
[
"MIT"
] |
permissive
|
package io.lansing.mcjslib;
public abstract class RunningModule {
public abstract void onEnable();
public abstract void onDisable();
public abstract void onLoad();
}
|
PHP
|
UTF-8
| 655 | 2.609375 | 3 |
[] |
no_license
|
<?php
namespace ModuleInstaller;
use Privilege\Privilege;
class ModuleInstallerModule
{
public static function decorateUri2PagesMap(array &$uri2pagesMap)
{
$uri2pagesMap[ModuleInstallerConfig::getUri()] = ModuleInstallerConfig::getPage();
}
public static function displayToolsLeftMenuLinks()
{
$ll = "modules/moduleInstaller/moduleInstaller";
if (Privilege::has('moduleInstaller.access')):
?>
<li>
<a href="<?php echo ModuleInstallerConfig::getUri(); ?>"><?php echo __("Module Installer", $ll); ?></a>
</li>
<?php
endif;
}
}
|
C++
|
UTF-8
| 154 | 2.53125 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
int counter = 1;
while( counter <=10 )
{
cout<<counter<< " ";
++counter;
}
cout<<endl;
}
|
Java
|
UTF-8
| 5,325 | 2.3125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.dcsa.api_validator.ovs.v1.schedules;
import org.dcsa.api_validator.conf.Configuration;
import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import spark.Request;
import spark.Spark;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
public class ScheduleSubscriptionsTest {
//Don't reuse request objects to reduce risk of other unrelated events affecting the tests
private Request scheduleRequest1;
private Request scheduleRequest2;
private CountDownLatch lock = new CountDownLatch(1); //Initialize countdown at 1, when count is 0 lock is released
private CountDownLatch lock2 = new CountDownLatch(1); //Initialize countdown at 1, when count is 0 lock is released
@BeforeMethod
void setup() {
cleanUp();
Spark.port(4567);
Spark.post("v1/webhook/receive-schedule-2", (req, res) -> {
if(req.body()==null) return "Ignoring null callback received"; //Not sure why this sometimes happens. May be a problem in the API, for now we ignore it to avoid tests failing sporadically
this.scheduleRequest1 = req;
lock.countDown(); //Release lock
return "Callback received!";
});
Spark.post("v1/webhook/receive-schedule-1", (req, res) -> {
if(req.body()==null) return "Ignoring null callback received"; //Not sure why this sometimes happens. May be a problem in the API, for now we ignore it to avoid tests failing sporadically
this.scheduleRequest2 = req;
lock2.countDown(); //Release lock
return "Callback received!";
});
Spark.awaitInitialization();
}
private void cleanUp() {
this.scheduleRequest1 = null;
this.scheduleRequest2 = null;
lock = new CountDownLatch(1); //Initialize countdown at 1, when count is 0 lock is released
lock2 = new CountDownLatch(1); //Initialize countdown at 1, when count is 0 lock is released
}
@AfterMethod
void shutdown() {
Spark.stop();
Spark.awaitStop();
}
@Test
public void testCallbacks() throws InterruptedException, IOException, JSONException {
given().
auth().
oauth2(Configuration.accessToken).
contentType("application/json").
body(" {\n" +
" \"vesselOperatorCarrierCode\": \"MAEU\",\n" +
" \"vesselOperatorCarrierCodeListProvider\": \"NMFTA\",\n" +
" \"vesselPartnerCarrierCode\": \"MSCU,HLCU\",\n" +
" \"vesselPartnerCarrierCodeListProvider\": \"NMFTA\",\n" +
" \"startDate\": \"2020-04-06\",\n" +
" \"dateRange\": \"P28D\"\n" +
" }").
post(Configuration.ROOT_URI + "/schedules");
lock.await(20000, TimeUnit.MILLISECONDS); //Released immediately if lock countdown is 0
Assert.assertNotNull(scheduleRequest1, "The callback request should not be null");
Assert.assertNotNull(scheduleRequest1.body(), "The callback request body should not be null");
String jsonBody = scheduleRequest1.body();
System.out.println("The testCallbacks() test received the body: " + jsonBody);
//Validate that the callback body is a Shipment Event
JSONObject jsonSubject = new JSONObject(jsonBody);
try (InputStream inputStream = getClass().getResourceAsStream("/ovs/v1/ScheduleSchema.json")) {
JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
Schema schema = SchemaLoader.load(rawSchema);
schema.validate(jsonSubject); // throws a ValidationException if this object is invalid
}
}
//Disabled until filters work
@Test(enabled = false)
public void testCallbackFilter() throws InterruptedException, JSONException {
given().
auth().
oauth2(Configuration.accessToken).
contentType("application/json").
body(" {\n" +
" \"vesselOperatorCarrierCode\": \"MAEU\",\n" +
" \"vesselOperatorCarrierCodeListProvider\": \"NMFTA\",\n" +
" \"vesselPartnerCarrierCode\": \"MSCU,HLCU\",\n" +
" \"vesselPartnerCarrierCodeListProvider\": \"NMFTA\",\n" +
" \"startDate\": \"2020-04-06\",\n" +
" \"dateRange\": \"P4W\"\n" +
" }").
post(Configuration.ROOT_URI + "/schedules");
lock2.await(3000, TimeUnit.MILLISECONDS); //Released immediately if lock countdown is 0
Assert.assertNull(scheduleRequest2, "The callback request should be null"); //The body should be null, since only transport events must be sent to this endpoint
}
}
|
JavaScript
|
UTF-8
| 1,778 | 2.8125 | 3 |
[] |
no_license
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { getCityName } from "./../../../actions/actions";
import "./Search.scss";
class Search extends Component {
state = { value: "" };
/**
* Store the user-entered value in the state value
*/
handleChange = () => {
this.setState({ value: event.target.value });
};
/**
* Remove the extra spaces entered by the user
* Transfer data to the reducer
* Zero input state
*/
handleSend = () => {
this.props.dispatch(getCityName("q=" + this.state.value.trim()));
this.setState({ value: "" });
};
enterKeySend = event => {
if (event.keyCode === 13) {
this.handleSend();
}
};
componentDidMount() {
document.addEventListener("keydown", this.enterKeySend, false);
}
componentWillUnmount() {
document.removeEventListener("keydown", this.enterKeySend, false);
}
render() {
const placeholder = this.props.lang
? "Enter the name of the city or zip code"
: "Введите название города или почтовый индекс";
const errorMessage = this.props.lang ? "Enter a valid city or zip code" : "Введите правильное название города";
const renderPlaceholder = this.props.error ? errorMessage : placeholder;
const errorClassName = this.props.error ? "search-error-info" : "";
return (
<div className="container-search">
<input
type="text"
placeholder={renderPlaceholder}
onChange={this.handleChange}
value={this.state.value}
className={errorClassName}
/>
<button onClick={this.handleSend}>➜</button>
</div>
);
}
}
export default connect()(Search);
|
Markdown
|
UTF-8
| 2,779 | 3.109375 | 3 |
[] |
no_license
|
# 一、实验目标
1. 掌握数据库操作方法
2. 掌握界面设计方法
# 二、实验内容
1. 更新页面组件
# 三、实验步骤
1. 修饰界面
```java
package edu.hzuapps.myapplication;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ListviewAdapter extends BaseAdapter {
ArrayList<ArrayList<String>> studentList;
Database db;
MainActivity1 that;
ListviewAdapter(MainActivity1 t,ArrayList<ArrayList<String>> st,Database DB){
studentList = st;
that=t;
db=DB;
}
@Override
public int getCount() {
return studentList.size();
}
@Override
public Object getItem(int position) {
return studentList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder viewHolder;
if(convertView==null) {
view = LayoutInflater.from(that).inflate(R.layout.activity_main1_item, null);
viewHolder = new ViewHolder();
viewHolder.xuehao = (TextView) view.findViewById(R.id.xuehao);
viewHolder.xingming = (TextView) view.findViewById(R.id.xingming);
viewHolder.banji = (TextView) view.findViewById(R.id.banji);
viewHolder.deleteBtn = (Button) view.findViewById(R.id.deleteBtn);
view.setTag(viewHolder);
}else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
init(position,viewHolder);
return view;
}
protected void init(final int position, ViewHolder viewHolder){
final ArrayList<String> temp = studentList.get(position);
viewHolder.xuehao.setText("学号:"+temp.get(0));
viewHolder.xingming.setText("姓名:"+temp.get(1));
viewHolder.banji.setText("班级:"+temp.get(2));
viewHolder.deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
studentList.remove(position);
notifyDataSetChanged();
db.delete(temp.get(0));
}
});
}
}
class ViewHolder{
TextView xuehao;
TextView xingming;
TextView banji;
Button deleteBtn;
}
```
# 四、实验结果

# 五、实验心得
本次实验继续修改APP的结构,对数据库进行操作。
|
Python
|
UTF-8
| 2,381 | 3.09375 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
from math import sqrt
import sys
import time
start_Time = time.time()
def main():
PointArray = []
buildArray(PointArray)
BruteForce(PointArray)
def buildArray(PointArray):
openFile = open(sys.argv[1], "r+")
value = openFile.read().split()
for i in value:
if i != ' ' and i != '\n': # only accept things that are not a space or new line
PointArray.append(float(i))
def getDistance(Point_x1, Point_y1, Point_x2, Point_y2):
return sqrt(((Point_x2 - Point_x1) ** 2) + ((Point_y2 - Point_y1) ** 2))
def BruteForce(PointArray):
minimum = getDistance(PointArray[0], PointArray[
1], PointArray[2], PointArray[3])
i = 4
minPoints = []
while(i + 4 <= len(PointArray)):
j = i + 2
while (j + 2 <= len(PointArray)):
# If the new set of points is less than the current minimum,
# overwrite the minimum
if ((getDistance(PointArray[i], PointArray[i + 1],
PointArray[j], PointArray[j + 1])) < minimum):
minimum = getDistance(PointArray[i], PointArray[i + 1],
PointArray[j], PointArray[j + 1])
# delete the previous list if new minimum is found
del minPoints[:]
# add the points of the minimum distance
minPoints.append([[PointArray[i], PointArray[
i + 1]], [PointArray[j], PointArray[j + 1]]])
# If there is a tie between the minimum and the new points output
# it to a file
elif ((getDistance(PointArray[i], PointArray[i + 1],
PointArray[j], PointArray[j + 1])) == minimum):
# add the points that tie with the minimum
minPoints.append([[PointArray[i], PointArray[
i + 1]], [PointArray[j], PointArray[j + 1]]])
j += 2
i += 2
timelog = open("timelog_bruteforce.txt", "a")
current_Time = abs(start_Time - time.time())
timelog.write(str(current_Time))
timelog.write("\n")
timelog.close()
writeTie = open("output_bruteforce.txt", "a")
writeTie.write(str(minimum) + "\n")
minPoints.sort()
for i in minPoints:
writeTie.write(str(i))
writeTie.write('\n')
main()
|
Java
|
UTF-8
| 808 | 2.015625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.github.mostroverkhov.r2.autoconfigure.server.endpoints;
import com.github.mostroverkhov.r2.autoconfigure.internal.server.endpoints.EndpointResult;
import java.util.Objects;
import reactor.core.publisher.Flux;
public class ServerControls {
private final Flux<EndpointResult> endpointStarts;
private final Flux<EndpointResult> endpointStops;
public ServerControls(
Flux<EndpointResult> endpointStarts,
Flux<EndpointResult> endpointStops) {
Objects.requireNonNull(endpointStarts);
Objects.requireNonNull(endpointStops);
this.endpointStarts = endpointStarts;
this.endpointStops = endpointStops;
}
public EndpointLifecycle endpoint(String name) {
Objects.requireNonNull(name);
return new EndpointLifecycle(name, endpointStarts, endpointStops);
}
}
|
Shell
|
UTF-8
| 220 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
###
#
# Author: Pierre Gilet
# Version: 1.0
# Date: 2012-01-19
#
# Description:
# Print to stdout the total disk space.
#
###
df -h --block-size=M | grep "/$" | tr -s " " " " | cut -d " " -f 2 | sed "s/M$/ MB/"
|
Java
|
UTF-8
| 1,238 | 3.5 | 4 |
[] |
no_license
|
package divide_etc_0807;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class QuickSort2 {
// static int L, R, pivot;
static int a[];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = st.countTokens();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
quicksort(a,0,n-1);
for (int i : a) {
System.out.print(i+" ");
}
}
/*
* L : 피봇보다 같거나 큰값 찾기 R : 피봇보다 작은값 찾기
*/
public static void quicksort(int a[], int begin, int end) {
if(end <= begin) return;
int tmp=0;
int pivot = (begin + end) / 2;
int L = begin;
int R = end;
while (L<R) {
if (a[L]<=a[pivot]) {
L++;
}
if(a[R]>=a[pivot]) {
R--;
}
if(a[L]>a[pivot] && a[R]<a[pivot]) {
if(L<R) {
tmp = a[L];
a[L] = a[R];
a[R] = tmp;
}
}
if(L==R) {
tmp = a[pivot];
a[pivot] = a[R];
a[R] = tmp;
break;
}
}
quicksort(a, begin, R-1);
quicksort(a, R+1, end);
}
}
|
Python
|
UTF-8
| 357 | 3.484375 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-20, 20)
y = x**2
px = np.array([-5, 15])
py = px**2
print(px)
print(py)
a = (py[1] - py[0]) / (px[1] - px[0])
b = py[0] - a * px[0]
y2 = a * x + b
print(a)
plt.figure(0)
plt.plot(x, y, 'b-', label='f1')
plt.plot(px, py, 'ro')
plt.plot(x, y2, 'r-', label='f2')
plt.legend()
plt.show()
|
Java
|
UTF-8
| 6,970 | 2.21875 | 2 |
[] |
no_license
|
package cs4620.framework;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLPbuffer;
import javax.media.opengl.GLProfile;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;
public class GLFourViewPanel extends JPanel implements GLEventListener, ActionListener, ViewsCoordinator {
private static final long serialVersionUID = 1L;
protected int initialFrameRate;
protected GLView topView;
protected GLView frontView;
protected GLView perspectiveView;
protected GLView rightView;
protected PerspectiveCamera perspectiveCamera;
protected OrthographicCamera frontCamera;
protected OrthographicCamera rightCamera;
protected OrthographicCamera topCamera;
protected PickingController perspectiveController;
protected PickingController frontController;
protected PickingController rightController;
protected PickingController topController;
protected Timer timer;
protected GLProfile glProfile;
protected GLCapabilities glCapabilities;
protected GLPbuffer sharedDrawable;
protected boolean disposed = false;
protected GLSceneDrawer drawer;
protected boolean[] viewsUpdated = new boolean[4];
public GLFourViewPanel(int frameRate, GLSceneDrawer drawer)
{
super();
initLayout();
initGLCapabilities();
initTimer(frameRate);
this.drawer = drawer;
initCameras();
initViews(drawer);
}
private void initViews(GLSceneDrawer drawer) {
sharedDrawable = GLDrawableFactory.getFactory(glProfile).createGLPbuffer(null, glCapabilities, null, 1, 1, null);
topController = new PickingController(new OrthographicCameraController(topCamera, drawer, this, 0));
topView = createView(topController, sharedDrawable.getContext());
perspectiveController = new PickingController(new PerspectiveCameraController(perspectiveCamera, drawer, this, 1));
perspectiveView = createView(perspectiveController, sharedDrawable.getContext());
frontController = new PickingController(new OrthographicCameraController(frontCamera, drawer, this, 2));
frontView = createView(frontController, sharedDrawable.getContext());
rightController = new PickingController(new OrthographicCameraController(rightCamera, drawer, this, 3));
rightView = createView(rightController, sharedDrawable.getContext());
}
private void initCameras() {
topCamera = new OrthographicCamera(
new Point3f(0, 10, 0), new Point3f(0,0,0), new Vector3f(0,0,-1),
0.1f, 100.0f, 45.0f);
frontCamera = new OrthographicCamera(
new Point3f(0, 0, 10), new Point3f(0,0,0), new Vector3f(0,1,0),
0.1f, 100.0f, 45.0f);
rightCamera = new OrthographicCamera(
new Point3f(10, 0, 0), new Point3f(0,0,0), new Vector3f(0,1,0),
0.1f, 100.0f, 45.0f);
perspectiveCamera = new PerspectiveCamera(
new Point3f(5,5,5), new Point3f(0,0,0), new Vector3f(0,1,0),
0.1f, 100, 45);
}
private GLView createView(PickingController controller, GLContext sharedWith) {
GLView view;
if (sharedWith == null)
view = new GLView(glCapabilities);
else
view = new GLView(glCapabilities, sharedWith);
add(view);
view.addGLController(controller);
view.addGLEventListener(this);
return view;
}
private void initTimer(int frameRate) {
initialFrameRate = frameRate;
timer = new Timer(1000 / frameRate, this);
}
private void initGLCapabilities() {
glProfile = GLProfile.getDefault();
glCapabilities = new GLCapabilities( glProfile );
}
private void initLayout() {
GridLayout layout = new GridLayout(2,2,5,5);
setLayout(layout);
}
public void dispose()
{
if (!disposed)
{
disposed = true;
}
}
protected void finalize()
{
dispose();
}
@Override
public void init(GLAutoDrawable arg0)
{
startAnimation();
}
@Override
public void display(GLAutoDrawable drawable) {
// NOP
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
((Component)drawable).setMinimumSize(new Dimension(0,0));
}
@Override
public void dispose(GLAutoDrawable drawable) {
// NOP
}
public void startAnimation() {
timer.start();
}
public void stopAnimation() {
timer.stop();
}
public PerspectiveCamera getPerspectiveCamera() {
return perspectiveCamera;
}
public OrthographicCamera getFrontCamera() {
return frontCamera;
}
public OrthographicCamera getRightCamera() {
return rightCamera;
}
public OrthographicCamera getTopCamera() {
return topCamera;
}
protected void repaintViews()
{
topView.repaint();
frontView.repaint();
rightView.repaint();
perspectiveView.repaint();
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == timer)
{
repaintViews();
}
}
public void immediatelyRepaint()
{
repaintViews();
}
public GLContext getSharedContext()
{
return sharedDrawable.getContext();
}
public void addPickingEventListener(PickingEventListener listener)
{
perspectiveController.addPickingEventListener(listener);
frontController.addPickingEventListener(listener);
topController.addPickingEventListener(listener);
rightController.addPickingEventListener(listener);
}
public void removePickingEventListener(PickingEventListener listener)
{
perspectiveController.removePickingEventListener(listener);
frontController.removePickingEventListener(listener);
topController.removePickingEventListener(listener);
rightController.removePickingEventListener(listener);
}
public void addPrioritizedObjectId(int id)
{
perspectiveController.addPrioritizedObjectId(id);
frontController.addPrioritizedObjectId(id);
topController.addPrioritizedObjectId(id);
rightController.addPrioritizedObjectId(id);
}
public void removePrioritizedObjectId(int id)
{
perspectiveController.removePrioritizedObjectId(id);
frontController.removePrioritizedObjectId(id);
topController.removePrioritizedObjectId(id);
rightController.removePrioritizedObjectId(id);
}
public void captureNextFrame()
{
perspectiveController.getCameraController().captureNextFrame();
}
public void resetUpdatedStatus()
{
for (int i = 0; i < 4; i++)
viewsUpdated[i] = false;
}
public boolean checkAllViewsUpdated()
{
return viewsUpdated[0] && viewsUpdated[1] && viewsUpdated[2] && viewsUpdated[3];
}
@Override
public void setViewUpdated(int viewId)
{
viewsUpdated[viewId] = true;
}
}
|
C++
|
UTF-8
| 1,072 | 2.6875 | 3 |
[] |
no_license
|
#include "acquisitionconverter.h"
AcquisitionConverter::AcquisitionConverter(QObject *parent) : QObject(parent)
{
}
void AcquisitionConverter::processFrame(const cv::Mat &frame)
{
if (m_processAll) process(frame); else queue(frame);
}
void AcquisitionConverter::setProcessAll(bool all)
{
m_processAll = all;
}
void AcquisitionConverter::queue(const cv::Mat & frame)
{
if (!m_frame.empty()) qDebug() << "Converter dropped frame!";
m_frame = frame;
if (! m_timer.isActive()) m_timer.start(0, this);
}
void AcquisitionConverter::process(cv::Mat frame)
{
cv::resize(frame, frame, cv::Size(), 0.3, 0.3, cv::INTER_AREA);
cv::cvtColor(frame,frame,CV_BGR2RGB);
const QImage image(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888, &matDeleter, new cv::Mat(frame) );
Q_ASSERT(image.constBits() == frame.data);
emit imageReady(image);
}
void AcquisitionConverter::timerEvent(QTimerEvent * ev)
{
if (ev->timerId() != m_timer.timerId()) return;
process(m_frame);
m_frame.release();
m_timer.stop();
}
|
TypeScript
|
UTF-8
| 390 | 2.53125 | 3 |
[] |
no_license
|
import { Pipe, PipeTransform } from '@angular/core';
import { IFighter } from '../../models/fighter.model';
@Pipe({
name: 'dateRanking',
})
export class DateRankingPipe implements PipeTransform {
transform(fighters: IFighter[], date: string | Date): IFighter[] {
if (date === 'all') return fighters;
return fighters.filter((fighter) => fighter.date.toString() === date);
}
}
|
PHP
|
UTF-8
| 4,927 | 3.09375 | 3 |
[] |
no_license
|
<?php
/**
* Project : OPEN ADMIN
* File Author : BryZe NtZa
* File Description : Application utilities functions
* Date : Mai 2018
* Copyright XDEV WORKGROUP
* */
namespace OpenAdmin\Library;
Class DateLib {
public static function getIDDate($date) {
try {
if ($date == '') {
return 0;
exit();
}
list($day, $month, $year) = explode('/', $date);
if ($year < 100) {
$year = '20' . $year; // Provisoire
}
$timestamp = mktime(0, 0, 0, $month, $day, $year);
$timestamp1 = $timestamp - mktime(0, 0, 0, 1, 1, $year) + (3600 * 24);
$result = round($timestamp1 / (3600 * 24)) + 366 * (date('Y', $timestamp) - 1);
return $result;
} catch (Exception $e) {
echo 'Exception reçue : ', $e->getMessage(), '\n';
}
}
public static function getIDTime($time) {
try {
if ($time == '') {
return 0;
exit();
}
list($hour, $minute, $second) = explode(':', $time);
$result = $hour * 60 + $minute;
return $result;
} catch (Exception $e) {
echo 'Exception reçue : ', $e->getMessage(), '\n';
}
}
public static function getIDDateTime($dateTime){
list($date, $time) = explode(' ', $dateTime);
list($day, $mois, $year) = explode('-', $date);
list($hour, $min, $second) = explode(':', $time);
$strTimeInput = $month.'/'.$day.'/'.$year;
$dayOfYear = date('z', strtotime($strTimeInput))+1;
$yearOfDate = 366 * (date('Y', strtotime($strTimeInput)) - 1);
$result = ($dayOfYear + $yearOfDate); // Yesterday Days after JC
$result *= 1440; // Yesterday Minutes after JC
$result += self::GetIDTime($time); // Instant Minutes after JC
$result *= 60; // Instant Seconds after JC
$result += $second; // Instant Seconds after JC
return $result;
}
// Conversion de la date dans le format demandé
public static function dateConvert($dateTime, $formatBefore, $formatAfter, $to='hour'){
$date = substr($dateTime, 0, 10);
$time = (strlen($date) > 10) ? substr($dateTime, 11, 8) : '00:00:00';
switch ($formatBefore) {
case 'd/m/Y': list($day, $month, $year) = explode('/', $date); break;
case 'd/Y/m': list($day, $year, $month) = explode('/', $date); break;
case 'Y/m/d': list($year, $month, $day) = explode('/', $date); break;
case 'Y/d/m': list($year, $day, $month) = explode('/', $date); break;
case 'm/d/Y': list($month, $day, $year) = explode('/', $date); break;
case 'm/Y/d': list($month, $year, $day) = explode('/', $date); break;
case 'd-m-Y': list($day, $month, $year) = explode('-', $date); break;
case 'd-Y-m': list($day, $year, $month) = explode('-', $date); break;
case 'Y-m-d': list($year, $month, $day) = explode('-', $date); break;
case 'Y-d-m': list($year, $day, $month) = explode('-', $date); break;
case 'm-d-Y': list($month, $day, $year) = explode('-', $date); break;
case 'm-Y-d': list($month, $year,$day) = explode('-', $date); break;
case 'd.m.Y': list($day, $month, $year) = explode('.', $date); break;
case 'd.Y.m': list($day, $year, $month) = explode('.', $date); break;
case 'Y.m.d': list($year, $month, $day) = explode('.', $date); break;
case 'Y.d.m': list($year, $day, $month) = explode('.', $date); break;
case 'm.d.Y': list($month, $day, $year) = explode('.', $date); break;
case 'm.Y.d': list($month, $year, $day) = explode('.', $date); break;
}
switch ($formatAfter){
case 'd/m/Y': $date = $day.'/'.$month.'/'.$year; break;
case 'd/Y/m': $date = $day.'/'.$year.'/'.$month; break;
case 'Y/m/d': $date = $year.'/'.$month.'/'.$day; break;
case 'Y/d/m': $date = $year.'/'.$day.'/'.$month; break;
case 'm/d/Y': $date = $month.'/'.$day.'/'.$year; break;
case 'm/Y/d': $date = $month.'/'.$year.'/'.$day; break;
case 'd-m-Y': $date = $day.'-'.$month.'-'.$year; break;
case 'd-Y-m': $date = $day.'-'.$year.'-'.$month; break;
case 'Y-m-d': $date = $year.'-'.$month.'-'.$day; break;
case 'Y-d-m': $date = $year.'-'.$day.'-'.$month; break;
case 'm-d-Y': $date = $month.'-'.$day.'-'.$year; break;
case 'm-Y-d': $date = $month.'-'.$year.'-'.$day; break;
case 'd.m.Y': $date = $day.'.'.$month.'.'.$year; break;
case 'd.Y.m': $date = $day.'.'.$year.'.'.$month; break;
case 'Y.m.d': $date = $year.'.'.$month.'.'.$day; break;
case 'Y.d.m': $date = $year.'.'.$day.'.'.$month; break;
case 'm.d.Y': $date = $month.'.'.$day.'.'.$year; break;
case 'm.Y.d': $date = $month.'.'.$year.'.'.$day; break;
case 'Ymd': $date = $year.$month.$day; break;
}
if (!$to) return $date;
$dateTime = $date . ' ' . $time;
switch ($to) {
case 'hours': $dateTime = substr($dateTime, 0, 13); break;
case 'minutes': $dateTime = substr($dateTime, 0, 16); break;
case 'seconds': $dateTime = substr($dateTime, 0, 19); break;
}
return $dateTime;
}
function showDateHeuresMinsJMY($dateTime) {
return self::dateConvert($dateTime, 'Y-m-d', 'd/m/Y', 16);
}
}
|
Markdown
|
UTF-8
| 11,097 | 2.578125 | 3 |
[] |
no_license
|
# NVIDIA-Position
**2018.05.06 Carra Zhou in Shanghai**
##### 不定期更新NV部分职位,有想了解更多可以follow me,或者发邮件给我,carraz@nvidia.com
## Web Development Position
### Frontend Developer(Jupyter)
waiting for update
### Architecture Data Engineer
- We are looking for an extraordinary data engineer to help us build a next-generation internal platform for analyzing Deep Learning and HPC application performance.
- As the data engineering expert within our team, your role would span across our whole stack and include data modeling, API design, performance optimization, and development of visualization tools.
#### What you'll be doing: ####
- Designing and implementing APIs for accessing and analyzing GPU performance data
- Creating GUIs and data visualization tools using javascript and Python
- Optimizing performance across the analysis and visualization stack
- Working closely with multiple teams to identify and plan new requirements
#### What we need to see: ####
- BS or higher degree in computer science with 3+ years of relevant experience
- Adept programming skills in Python, Javascript, and C++
- Strong background in databases, data modeling, and data visualization
- Passion for efficiency and enabling others
- Excellent communication skills
- Desire to be part of a global team with diverse technical backgrounds
## Management Positon
### Senior QA Manager
- We are looking for a phenomenal leader to build and lead a world-class QA team working with NVIDIA’s global engineering teams.
- As a senior Quality Manager for NVIDIA SW group, you will be responsible for the development of overall objectives and long-term goals of a significant function of the organization.
- In this role, you will develop an actionable goal commitment strategy that ensures the goals set for the quality organization at your site are achieved.
- You will delegate assignments to subordinate managers.
- You will provide guidance to subordinates within the latitude of established company policies.
- You will be in one of the following product families: Enterprise GPU, Embedded GPU and Cloud product.
#### What You’ll Be Doing:
- You will build a high performing enterprise SWQA organization by driving and implementing changes for continuous improvement
- Cultivate leadership in others
- Be responsible for driving quality assurance on NVIDIA enterprise products, such as Tesla GPUs, CUDA and NVIDIA Cloud.
- Architect the Test Methodology, create the Quality KPI and take actions to drive the teams to deliver perfect quality enterprise product
- Architect and maintain an automated testing framework that enables high quality work
- Guide your team to acquire skills, train on new technologies for quality assurance.
- Collaborate with Development, PM, marketing and engineering teams, negotiate requirements and deriving test solutions and proposals
- Drive a “Zero Defect” culture by constantly thriving for test plan improvement and perfectio.
#### What We Need to See:
- BS or higher degree in CS/EE/CE or equivalent practical experience
- 10+ years in SQA or software testing background, and at least 5 years’ experience in managerial role with good track record.
- Proficiency in software and/or operating systems environments.
- Strong analytic, communication and interpersonal skills
- Strong mentoring/coaching skills
- Experienced in using quality mindset to drive improvements.
- Fluent oral and written English
#### Ways to Stand Out from The Crowd:
- Familiarity with NVIDIA GPU hardware and CUDA is a strong plus
- Comfortable in at least one programming language (C, C++) and scripting (Python/Bash/Perl
- Compute frameworks and HPC cluster
- Be an instrument of change
- Passionate about quality, demonstrate high standards
- You should have with strong analytical, trouble shooting skills, and should have high capability in driving issues to close
### Service Software Supervisor
- (Java)-Shanghai (Management)
#### Requirements:
- You have 8 or more years of software development experience.
- You have 5 or more years of service development experience.
- You have expert knowledge of Java & online service frameworks.
- You have experience with real time & stateless REST services.
- You have solid programming skills and passion.
- You have strong English & Mandarin written & verbal communication skills.
#### Responsibility:
- You will design, develop, test, and maintain server-side components.
- You will manage a team of service & web developers in our Shanghai office
- You will review and give feedback on business requirements.
- You will research and evaluate 3rd party technologies.
## Test/Test Development Position
### CUDA Test Development Engineer
- (CUDA Safety/Code Coverage)
#### Requirements:
- Strong programming and debugging skills with C/C++, Python and Makefile
- Rich experience in test cases development, tests automation and failure analysis
- Good QA sense, knowledge and experience in software testing
- Experience in parallel programming, ideally CUDA C/C++, is a plus
- Experience in VectorCAST, Bullyseye, Gcov or Coverity is a plus
#### Responsibility:
- Implement API, integration and unit tests for CUDA driver and library
- Automate CUDA tests and enable them in testing infrastructure
- Triage test results, isolate test failures and improve test coverage
### Senior CUDA Automation Triage Software Engineer
- Belong to Test development
#### Requirements:
- Excellent trouble shooting skill, logical thinking and inference capability
- Excellent QA sense, knowledge and experience in software testing
- Strong Linux/Windows/Mac/Mobile OS knowledge
- Strong Python scripting is a must, Shell/Perl is a plus
- Good C/Makefile/Compiler/Debug knowledge and develop experience under Linux
#### Responsibility:
- Triage build/test failures from nightly/weekly automation infrastructure
- GPU testing for CUDA product to ensure functionality, compatibility and performance
- Root cause the failure, assist developer to fix and drive the bug to close
- Develop scripts/tools and optimize workflow to improve efficiency
### Deep Learning Software QA Engineer
- Belong to Deep Learning positon,need deep learning related experience
#### Requirements:
- BS or higher degree in CS/EE/CE or equivalent;
- 5+ years of software development or SQA background;
- Script languages (Python, Perl, bash) knowledge and Linux/UNIX experience is required;
- Good C/C++ skillsets and development experience is required;
- Have background or experiences in machine learning or deep learning fields;
- Excellent communicator, both written and verbal;
#### Responsibility:
- Quality assurance for NVIDIA Deep Learning Softwares (cuDNN, TensorRT, Frameworks, etc);
- Regression, functionality, performance testing and code coverage testing, etc;
- Implement test development, enhancement and test automation;
- Triage, isolate failures, tracking SW bugs and verify fixes, do root cause analysis;
### CUDA Software QA Engineer
- Tesla GPUs, CUDA release and NVIDIA Cloud
#### Requirements:
- Be responsible for validating compute testing of NVIDIA enterprise products, such as.
- Collaborate with Development, PM, marketing and engineering teams on designing test plan and implementing validation.
- You will assist in the architecture, crafting and implementing of SWQA test frameworks.
#### Responsibility:
- BS or higher degree in CS/EE/CE or equivalent practical experience
- 6+ years of SQA or software testing background; test infrastructure and strong analysis skills
- Be proficient in scripting language (Python, bash)
- UNIX/Linux experience required
- Windows experience required
- Ability to work independently and leadership skills
### Graphics Developer Tools QA Software Engineer
- Need basic Graphics experience
#### Requirements:
- BS+:4+ years in an engineering discipline.
- Proficient in Windows and Linux environments.
- Basic knowledge of native programming and shell programming.
- Basic knowledge of graphics.
- Experience as a QA role in a released product.
#### Responsibility:
- Test Graphics developer tools on different systems and platforms under associated SQA processes.
- Design, develop and optimize new or existing test plans.
## Game Position
### Game Performance Analyst
waiting for update
### Performance Analyst – Virtual Reality
- Need basic graphics experience and good spoken english
#### What you’ll be doing:
- You will analyze the data to draft reports and charts to visualize the results.
- You will also identify performance issues, and corroborate with other teams to find possible solutions.
- You will work with product development engineers to tune our products for maximum performance and help define the next generation GPUs.
- Study and analyze the performance on various computing systems including graphics, CPU, memory, storage, networking, etc
- Develop, implement and maintain automation tools to improve testing efficiency.
- Create, tune, run and analyze latency using internal tools with gaming benchmarks.
- Work with multiple teams to understand and develop latency guidelines and testing methodologies.
#### What we need to see:
- A Bachelor’s degree, Master’s degree, or equivalent in a technical or business marketing field.
- A minimum of 2 years’ experience in a testing/developing of software and computers position that included performance analysis of computer systems.
- You have thorough knowledge of PC components. You have an expertise working with all Windows operating systems. You are knowledgeable with low level system configurations (BIOS, memory timings, system clocking, latency). You have experience in developing code using Perl, C, C++, or Python. You have a passion for working with large datasets and good techniques for data visualization.
- Good communication skill, fluently written and oral English.
#### Ways to stand out from the crowd:
- Good at team playing, able to work under pressure to deadlines.
- Technically sound.
- Experience working with single-board computer like Arduino.
- Knowledge of Deep Learning and neural networks.
- Eager and passionate about joining NVIDIA.
## Designer Position
### ID CAD Designer-Shenzhen
- Need PTC Creo CAD experience and good spoken english
#### Requirements:
- Advanced knowledge of material properties, fabrication process and structural analysis knowledge.
- Expert capability in PTC-Creo3.0 or later CAD
- 3 years’ experience creating product.
- Mandarin and English proficiency
- Ability to check 3D models/drawings
#### Responsibility:
- Modify industrial design concepts from various 3-D formats into Pro-E
- Collaborate with mechanical engineering to modify and adjust CAD files for DFM
- Create parametric master models in PTC-Creo.
- Assist engineering and industrial design in determining and employing proper specifications for materials, finishes and processes.
- Assist in the creation of design documentation, CMF, artwork specification and release of related documentation.
- Communicates updates with USA industrial design team.
|
Markdown
|
UTF-8
| 6,028 | 2.625 | 3 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
## Project Description
The Scalable Vector Graphics (SVG) is an XML-based standard file format for creating graphics on the web,
and is supported by most modern browsers.
This project provides a C# library for parsing, converting and viewing the SVG files in WPF applications.
The [Scalable Vector Graphics (SVG)](http://en.wikipedia.org/wiki/Scalable_Vector_Graphics) is now natively
supported in most internet browsers, including the IE 9. With the HTML5, the use of the SVG as graphics
format on the web is increasing.
For .NET application developers, there is currently no library complete enough to handle SVG files.
Even the commercial tools are either not available or not complete enough to handle most uses of
the SVG in Windows Presentation Foundation (WPF) applications.
The project does not aim to provide a complete implementation of the SVG file format, but will
support the features required in an average graphics application.
The SVG specification is available in [HTML](https://www.w3.org/TR/SVG11/) format or the [PDF](https://www.w3.org/TR/SVG11/REC-SVG11-20110816.pdf) format.
## Features and Uses
In general, the following features are implemented:
* Parsing of the SVG files to create the SVG DOM
* SVG to XAML conversion
* A small runtime library to handle font URI, embedded images and others when using the XAML files directly from disk.
* An optimized XAML output.
* A simple and basic SVG viewer (an advanced viewer is planned).
* Interaction with the conversion process (by a visitor pattern) to allow for custom hyper-link implementations, font substitutions etc.
**NOTE**: Only Geometry/Drawing level elements are exported, which will not work with Silverlight.
See the [Documentation](https://elinamllc.github.io/SharpVectors) section for more information on the features.
## Installation
The SharpVectors library targets the following frameworks
* .NET Framework, Version 4.0
* .NET Framework, Version 4.5
* .NET Framework, Version 4.6
* .NET Framework, Version 4.7
* .NET Framework, Version 4.8
* .NET Standard, Version 2.1
* .NET Core, Version 3.1
* .NET 5.0
* .NET 6.0
The library can be used in WPF and Windows Forms applications.
### For the Library
The library can be downloaded from the following sources
* **NuGet (WPF Only Package)**, [Version 1.8.1 - SharpVectors.Wpf](https://www.nuget.org/packages/SharpVectors.Wpf/).
* **NuGet (Full Package - WPF/GDI++)**, [Version 1.8.1 - SharpVectors](https://www.nuget.org/packages/SharpVectors/).
* **NuGet (Full Package - WPF/GDI++)**, [Version 1.8.1 - SharpVectors.Reloaded](https://www.nuget.org/packages/SharpVectors.Reloaded/).
* **GitHub Releases Page**, [Version 1.8.1](https://github.com/ElinamLLC/SharpVectors/releases).
> * The **SharpVectors.Reloaded** package is the same as the **SharpVectors**, which is the recommended package if you need the full package.
> * The **SharpVectors.Reloaded** name was used for the Nuget package at the time the **SharpVectors** package name was not available.
> * The **SharpVectors.Reloaded** package name will be retired in Version 2.0.
> * The **SharpVectors.Wpf** is the recommended package, for `WPF` only application.
> * As outlined in the [roadmap](https://github.com/ElinamLLC/SharpVectors/issues/147), other packages such as the **SharpVectors.Gdi** for the `GDI+`, will be available as the renderers mature.
## Documentation
An introduction and a tutorial with sample are available. See the [Documentation](https://elinamllc.github.io/SharpVectors) section for more information.
## Sample Applications
The library includes a number of sample application for both WPF and GDI+. Here are some of them:
### WPF Test Application
This is an application for browsing directory (recursively) of SVG files.

### WPF W3C Test Suite
This is an application for viewing the W3C Test Suite compliant results. It has two panes: top and bottom.
The top pane is the generated WPF output, the bottom pane is the W3C expected output image.
By the test results, this is the most complete SVG reader for WPF!

### GDI+ W3C Test Suite
This is an application for viewing the W3C Test Suite compliant results. It has two panes: top and bottom.
The top pane is the generated GDI+ output, the bottom pane is the W3C expected output image.

## Tutorial Samples
A number of tutorial samples are available in the [TutorialSamples](https://github.com/ElinamLLC/SharpVectors/tree/master/TutorialSamples) folder.
## Credits
SharpVectors uses source codes from articles and other open source projects. We wish to acknowledge and thank
the authors of these great articles and projects
* [SharpVectorGraphics (aka SVG#)](https://sourceforge.net/projects/svgdomcsharp/) by SVG# Team of Developers (SourceForge)
* [WPF Zooming and Panning Control](https://www.codeproject.com/KB/WPF/zoomandpancontrol.aspx) by Ashley Davis (CodeProject)
* [Render Text On A Path With WPF](https://msdn.microsoft.com/en-us/magazine/dd263097.aspx) by Charles Petzold (MSDN Magazine - December 2008)
* [MinIoC](https://github.com/microsoft/MinIoC) by Microsoft (Single-file minimal C# IoC container)
* [.NET ZLib Implementation](https://www.codeproject.com/Tips/830793/NET-ZLib-Implementation) by Alberto M (CodeProject)
* [Brotli compression format](https://github.com/google/brotli) by Google (C# Decoder)
## Related Projects
The following are related SVG viewer projects for the .NET platforms
* [SVG](https://github.com/vvvv/SVG) for GDI+
* [SVGImage](https://github.com/dotnetprojects/SVGImage) for WPF
## Related Repositories
The following are related SharpVectors repositories
* [SvgTestSuites](https://github.com/ElinamLLC/SvgTestSuites) : The W3C Test Suite files used by the SharpVectors for testing.
* [SvgXaml](https://github.com/ElinamLLC/SvgXaml) : SharpVectors based SVG to XAML converter application.
* [SvgViewer](https://github.com/ElinamLLC/SvgViewer) : SharpVectors based SVG viewer application.
|
Markdown
|
UTF-8
| 1,888 | 3.796875 | 4 |
[] |
no_license
|
#include <iostream>
#include <string>
#include<iomanip>
using namespace std;
void Menu();
float Area(const float R); //วงกลม
int Area(const int w,int l,int h); //ปริมาตร
float Area(const float L,const float W); //สี่เหลี่ยม
double Area(const double based1,double based2, double h); //คางหมู
int main(){
char C;
bool Flag=true;
do{
Menu();
cin >> C;
if(C=='1'){
float R;
cout << "Enter Radius :: " <<endl;
cin >> R;
cout << "Area of Circle = "<< fixed <<endl;
cout << setprecision(2) << Area(R)<< endl;
}
else if(C=='2'){
float L,W;
cout << "Enter Length & Width :: " <<endl;
cin >> L>>W;
cout << "Area of Rectangle = "<< fixed <<endl;
cout << setprecision(2) << Area(L,W)<< endl;
}
else if(C=='3'){
float w,l,h;
cout << "Enter Width & Length & Height :: " <<endl;
cin >> w>>l>>h;
cout << "Area of Trapezium = "<< fixed <<endl;
cout << setprecision(2) << Area(w,l,h)<< endl;
}
else if(C=='4'){
float l,h;
cout << "Enter Length & sum :: " <<endl;
cin >>l>>h;
cout << "Area of Capacity = "<< fixed <<endl;
cout << setprecision(2) << Area(l,h)<< endl;
}
else if(C=='5'){
Flag = false;
}else
cout << "not process";
}while (Flag);
cout << "Exit Program"<< endl;
return 0;
}
float Area(const float R) //วงกลม
{
return (3.14159F*R*R);
}
float Area(const float L,const float W) //สี่เหลี่ยม
{
return(L*W);
}
int Area(const int w,int l,int h)//ปริมาตร
{
return(w*l*h);
}
double Area(const double based1,double based2, double h) //คางหมู
{
return(0.5*h*(based1+based2));
}
void Menu()
{
cout << "Program Calculate Area"<<endl;
cout << "1.Circle"<<endl;
cout << "2.Rectangle"<<endl;
cout << "3.Trapezium"<<endl;
cout << "4.Capacity"<<endl;
cout << "5.Exit"<<endl;
}
|
Swift
|
UTF-8
| 298 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
import UIKit
internal extension Presenter {
internal func addController(presentation:PresentationProtocol) {
guard
let controller:UIViewController = presentation.controller
else {
return
}
self.addChildViewController(controller)
}
}
|
C++
|
UTF-8
| 1,249 | 3.03125 | 3 |
[] |
no_license
|
#ifndef GRAAL_H
#define GRAAL_H
#include <utility>
using std::pair;
#include <iterator>
using std::distance;
#include <algorithm>
using std::sort;
#include <iostream>
using std::cout;
namespace graal {
/*!
* Exemplo de documentação seguindo o formato Doxygen
*
* @tparam Itr iterator para o range.
* @tparam Compare o tipo de uma função bool(const T &a, const T &b)
*
* @param first Ponteiro para o primeiro elemento do range
* @param last Ponteiro para a posição logo após o último elemento do range
* @param cmp A função de comparação que retorna true quando o primeiro parâmetro é menor do que o segundo
*
* @return Um std::pair contendo o menor e maior elemento, nesta ordem
*
*/
/*
coloquei aqui, pois foi o que vc enviou no pdf, no entanto essa é a resposta da minmax da lista 1, ela não cabe aqui.
*/
std::pair<size_t, size_t> min_max (int v[], size_t n){
std::pair<size_t, size_t> p;
int minIdx = 0;
int maxIdx = 0;
for (size_t i=0; i<n; i++){
if (v[maxIdx] < v[i])
maxIdx = i;
if (v[minIdx] > v[i])
minIdx = i;
}
p.first = minIdx;
p.second = maxIdx;
return p;
}
/*float af,bf,cf;
float max_f = max3<float>(af,bf,cf);*/
}
#endif
|
Python
|
UTF-8
| 2,419 | 2.703125 | 3 |
[] |
no_license
|
import torch
from src.utils import fit_shape
def calc_stats(features, labels):
grams = []
for k_cluster in range(0, int(labels.max().item() + 1)):
arr = features[:, labels == k_cluster]
grams.append(torch.mm(arr, arr.T)/arr.shape[1])
return grams
def calc_dist(content_grams, style_grams):
dist = torch.zeros((len(content_grams), len(style_grams)))
for i in range(len(content_grams)):
for j in range(len(style_grams)):
dist[i, j] = torch.nn.functional.mse_loss(content_grams[i], style_grams[j])
return dist
def calc_penalty(arr, mode="max"):
assert mode in {"max", "mean"}, "Active penalty mode is not supported."
if (mode == "mean"):
arr_sorted = arr.sort().values
penalty = (arr_sorted[:, 1:] - arr_sorted[:, :-1]).mean(dim=1)
elif (mode == "max"):
penalty = arr.amax(dim=1)
return penalty
def softmax(vec, T):
softmax_score = torch.exp(-T*(vec - vec.min()))
softmax_score = softmax_score/softmax_score.sum()
return softmax_score
def generate_style_scores(dist_style, T=None, target_max_score=0.85):
if not(T is None):
# Softmax with temperature T
return softmax(dist_style, T)
# Auto Temperature Tuning
T = 0.0
max_score = 0.0
diff_criterion = 1.0
while ((max_score <= target_max_score) and (diff_criterion > 1e-3)):
T += 0.1
style_scores = softmax(dist_style, T)
max_score_new = style_scores.max()
diff_criterion = torch.abs(max_score_new - max_score)
max_score = max_score_new
return style_scores
def match_clusters(cf, sf, cl, sl, target_shape):
cf_fit = fit_shape(cf.squeeze(0), target_shape)
sf_fit = fit_shape(sf.squeeze(0), target_shape)
cl_fit = fit_shape(cl.unsqueeze(0), target_shape, renumerate=True)
sl_fit = fit_shape(sl.unsqueeze(0), target_shape, renumerate=True)
content_grams = calc_stats(cf_fit, cl_fit)
style_grams = calc_stats(sf_fit, sl_fit)
# Calculate L2-distance between content and style clusters along spatial dim
dist = calc_dist(content_grams, style_grams)
# Order content clusters by their distance to style clusters, the lower distance the higher priority
content_priority_order = torch.argsort(dist.amin(dim=1)).tolist()
W = {}
penalty = calc_penalty(dist)
for content_ind in content_priority_order:
style_ind = int(torch.argmin(dist[content_ind, :]))
style_scores = generate_style_scores(dist[content_ind, :])
W[content_ind] = style_scores
dist[:, style_ind] += penalty
return W
|
C++
|
UTF-8
| 548 | 2.6875 | 3 |
[] |
no_license
|
#ifndef _FLYING_OBJECT_H_
#define _FLYING_OBJECT_H_
class flyingObject{
public:
flyingObject();
flyingObject(float* s);
flyingObject(float* s, float* axis);
flyingObject(float* s, float* axis, float* v);
flyingObject(float* s, float* axis, float* v, float* a);
~flyingObject();
void setPosition(float*);
void setOrientation(float*);
void setVelocity(float*);
void setAcceleration(float*);
void print(void);
private:
float* position;
float* velocity;
float* acceleration;
float* orientation;
};
#endif
|
Python
|
UTF-8
| 598 | 3 | 3 |
[] |
no_license
|
from typing import List
class Solution:
def combination(self, A, sum_, i, cur_sum):
if sum(cur_sum) > sum_:
return 0
if i == len(A):
if sum(cur_sum) == sum_:
self.ans.append(cur_sum)
return
take = self.combination(A, sum_, i, cur_sum + [A[i]])
dont = self.combination(A, sum_, i + 1, cur_sum)
return take and dont
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
self.ans = []
self.combination(candidates, target, 0, [])
return self.ans
|
C#
|
UTF-8
| 5,167 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace System
{
/// <summary>
/// 模型类接口,在类中实现时包含一个签名为ID的公用自增量属性
/// </summary>
public interface IModelID<T>
{
/// <summary>
/// 获取或者设置一个值,该值表示自增量ID
/// </summary>
T ID { get; set; }
}
/// <summary>
/// 模型类接口,在类中实现时用于指定该类拥有一个名称为:Name的字段
/// </summary>
public interface IModelName
{
/// <summary>
/// 获取或者设置一个值,该值表示名称
/// </summary>
String Name { get; set; }
}
/// <summary>
/// 模型类接口,在类中实现时用于指定该类拥有一个名称为:ImageUrl的字段
/// </summary>
public interface IModelImageUrl
{
/// <summary>
/// 获取或者设置一个值,该值表示图片路径
/// </summary>
String ImageUrl { get; set; }
}
/// <summary>
/// 模型类接口,在类中实现时用于指定一个父ID属性
/// </summary>
/// <typeparam name="T">表示在主要接口中的名称为ID的字段类型和其父ID的类型</typeparam>
public interface IModelParentID<T> : IModelID<T>
{
/// <summary>
/// 获取或者设置一个值,该值表示父ID
/// </summary>
T PID { get; set; }
}
/// <summary>
/// 模型类接口,在类中实现时用于指定一个类别ID属性
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IModelItemID<T>
{
/// <summary>
/// 获取或者设置一个值,该值表示类别ID
/// </summary>
T ItemID { get; set; }
}
/// <summary>
/// 描述性接口,该接口指定如果使用扩展类实现生成树形下拉表,则该类型必须实现此接口
/// </summary>
/// <typeparam name="T">表示在主要接口中的名称为ID的字段类型</typeparam>
public interface IModelDropDown<T> : IModelName, IModelParentID<T> { }
#region [废弃的部分API功能]
///// <summary>
///// 模型类接口,在类中实现时包含一个签名为ID的公用自增量属性
///// </summary>
//[Obsolete("新的类型访问请参考System.OverLoad名称空间")]
//public interface IModel
//{
// /// <summary>
// /// 获取或者设置一个值,该值表示自增量ID
// /// </summary>
// [Display(Name = "ID")]
// [Column(IsDbGenerated = true, IsPrimaryKey = true, CanBeNull = false)]
// Int64 ID { get; set; }
//}
///// <summary>
///// 模型类接口,在类中实现时包含一个签名为ID的公用自增量属性,增加一个带有名称的属性类
///// </summary>
//[Obsolete("新的类型访问请参考System.OverLoad名称空间")]
//public interface IModelWithName : IModel
//{
// /// <summary>
// /// 获取或者设置一个值,该值表示名称
// /// </summary>
// String Name { get; set; }
//}
///// <summary>
///// 模型类接口,在类中实现时用于包含一个签名为ImageUrl的属性
///// </summary>
//[Obsolete("新的类型访问请参考System.OverLoad名称空间")]
//public interface IModelWithImageUrl : IModelWithName
//{
// String ImageUrl { get; set; }
//}
///// <summary>
///// 定义一个模型接口,该接口在类中实现时用于增加一个带有父类别的属性
///// </summary>
///// <typeparam name="T">任意类型</typeparam>
//[Obsolete("新的类型访问请参考System.OverLoad名称空间")]
//public interface IModelWithPID<T> : IModelWithName
//{
// T PID { get; set; }
//}
///// <summary>
///// 定义一个接口,在类中实现时用于指定该类型具有一个类别ID
///// </summary>
///// <typeparam name="T"></typeparam>
//[Obsolete("新的类型访问请参考System.OverLoad名称空间")]
//public interface IModelWithItemID<T> : IModelWithName
//{
// T ItemID { get; set; }
//}
///// <summary>
///// 生成下拉列表的接口,在类中实现时用于生成前台绑定的DropDownListFor
///// </summary>
///// <typeparam name="T">任意类型,一般为SelectListItem</typeparam>
//public interface IDropDown<T>
//{
// /// <summary>
// /// 生成下拉列表
// /// </summary>
// /// <returns>IEnumerable</returns>
// IEnumerable<T> GetSelectList();
// /// <summary>
// /// 生成下拉列表,并将selectIndex设置为选择的ID
// /// </summary>
// /// <typeparam name="TObj">任意类型的对象</typeparam>
// /// <param name="ID">选定的ID</param>
// /// <returns>IEnumerable</returns>
// IEnumerable<T> GetSelectList(object ID);
//}
#endregion
}
|
JavaScript
|
UTF-8
| 781 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
const serialize = (item) => {
if (typeof item.toJSON === 'function') {
return item.toJSON();
}
return item;
};
export default () => {
return function (hook) {
switch (hook.method) {
case 'find':
if (hook.result.data) {
hook.result.data = hook.result.data.map(serialize);
} else {
hook.result = hook.result.map(serialize);
}
break;
case 'get':
case 'update':
hook.result = serialize(hook.result);
break;
case 'create':
case 'patch':
if (Array.isArray(hook.result)) {
hook.result = hook.result.map(serialize);
} else {
hook.result = serialize(hook.result);
}
break;
}
return Promise.resolve(hook);
};
};
|
PHP
|
UTF-8
| 1,211 | 2.859375 | 3 |
[] |
no_license
|
<?php
require_once 'inc/constants.php';
function get_user($value, $key){
$users = get_users();
foreach ($users as $user) {
if ($user[$key] === $value) {
return $user;
}
}
return false;
}
function get_users(){
return get_db()['users'];
}
function store_user($user_details){
$current_db_data = get_db();
$current_db_data['users'][] = $user_details;
if (user_exists($user_details)) {
$error_msg = "User with such email exists";
redirect(SIGN_UP_PAGE, ['error' => $error_msg]);
exit;
return false;
}
return set_db($current_db_data);
}
function user_exists($user_details){
return email_exists($user_details['email']);
}
function email_exists($email){
$current_db_data = get_db();
$users = $current_db_data['users'];
foreach ($users as $key => $user) {
if ($user['email'] === $email) {
return true;
}
}
return false;
}
function set_db($db_data){
try {
set_json(DB_PATH, $db_data);
return true;
} catch (Exception $e) {
return false;
}
}
function set_json($path, $data){
$json_data_string = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($path, $json_data_string);
}
function get_db(){
return json_decode(file_get_contents(DB_PATH), true);
}
|
C
|
UTF-8
| 1,305 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
/*
*
* MPI Scatter and Gather examples.
*
*/
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
int rank;
int size;
int sendcount = 1;
int recvcount = sendcount;
int sendbuf[4];
int recvbuf;
int finalbuf[4];
int ROOT = 0;
MPI_Init(NULL, NULL);
MPI_Comm_size (MPI_COMM_WORLD, &size);
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
if (rank == 0){
sendbuf[0] = 3;
sendbuf[1] = 5;
sendbuf[2] = 7;
sendbuf[3] = 9;
}
// Send array to all processes
MPI_Scatter (sendbuf, sendcount, MPI_INT, &recvbuf, recvcount, MPI_INT, ROOT, MPI_COMM_WORLD);
// Multiply the received value to its rank
int local_value = recvbuf * rank;
printf("Rank: %d, value: %d\n", rank, local_value);
// Gathering values to ROOT process
MPI_Gather(&local_value, 1, MPI_INT, finalbuf, 1, MPI_INT, ROOT,
MPI_COMM_WORLD);
if (rank==0){
printf ("Rank: %d, Final_buf array: %d %d %d %d\n", rank,
finalbuf[0], finalbuf[1], finalbuf[2], finalbuf[3]);
}
int final_sum;
MPI_Reduce(&local_value, &final_sum, 1, MPI_INT, MPI_SUM, 0,MPI_COMM_WORLD);
printf("Rank: %d, Final sum: %d\n", rank, final_sum);
MPI_Finalize();
return 0;
}
|
Markdown
|
UTF-8
| 3,240 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
---
id: reference_form
title: <form>
sidebar_label: <form>
---
The `<form>` element represents a group of input elements that should be serialized into the request. Any behaviors within the `<form>` that result in a remote request will include the form's input values. This applies to both update and navigation actions.
The encoding of the input values depend on the request method:
- For **POST** requests, the body will be encoded as `multipart/form-data`.
- For **GET** requests, the input values will be added as query parameters.
```xml
<screen>
<form id="feedbackForm">
<text-field
name="email"
keyboard-type="email-address"
placeholder="Email"
value="bob@example.com"
/>
<text-area
name="feedback"
placeholder="Please leave your feedback"
value="Great work!"
/>
<text verb="post" href="/feedback" target="feedbackForm">Submit</text>
</form>
</screen>
```
In the example above, when the user presses the "Submit" label, Hyperview will make the following request (with headers and body):
```
POST /feedback
X-Hyperview-Version: 0.4
Content-Type: multipart/form-data; boundary=123
Content-Length: 400
--123
Content-Disposition: form-data; name="email"
bob@example.com
--123
Content-Disposition: form-data; name="feedback"
Great work!
```
## Structure
A `<form>` element can appear anywhere within a `<screen>` element. It can contain any type of element, but it should contain some input elements to serve as a grouping.
## Attributes
- [`style`](#style)
- [`id`](#id)
- [`hide`](#hide)
- [`scroll`](#scroll)
- [`scroll-orientation`](#scroll-orientation)
- [`shows-scroll-indicator`](#shows-scroll-indicator)
#### `style`
| Type | Required |
| ------ | -------- |
| string | No |
A space-separated list of styles to apply to the element. See [Styles](/docs/reference_style). Note that text style rules cannot be applied to a `<form>`.
#### `id`
| Type | Required |
| ------ | -------- |
| string | No |
A global attribute uniquely identifying the element in the whole document.
#### `hide`
| Type | Required |
| ------------------------- | -------- |
| **false** (default), true | No |
If `hide="true"`, the element will not be rendered on screen. If the element or any of the element's children have a behavior that triggers on "load" or "visible", those behaviors will not trigger while the element is hidden.
#### `scroll`
| Type | Required |
| ------------------------- | -------- |
| true, **false** (default) | No |
An attribute indicating whether the content in the can be scrollable. The style rules of the body will determine the viewport size.
#### `scroll-orientation`
| Type | Required |
| ---------------------------------- | -------- |
| **vertical** (default), horizontal | No |
An attribute indicating the direction in which the body will scroll.
#### `shows-scroll-indicator`
| Type | Required |
| ------------------------- | -------- |
| **true** (default), false | No |
An attribute indicating whether the scroll bar should be shown. Attribute `scroll` should be set in for this to have any effect.
|
Python
|
UTF-8
| 911 | 2.84375 | 3 |
[] |
no_license
|
from database.repository import db
from marshmallow import Schema, fields, post_load
class Employee(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=False)
surname = db.Column(db.String(255), nullable=False)
age = db.Column(db.Integer, nullable=False)
def __init__(self, name, surname, age):
self.name = name
self.surname = surname
self.age = age
def json(self):
return {
"id":self.id,
"name": self.name,
"surname": self.surname,
"age": self.age
}
def save(self):
db.session.add(self)
db.session.commit()
return self
class EmployeeSchema(Schema):
name = fields.Str()
surname = fields.Str()
age = fields.Integer()
@post_load
def make_user(self, data, **kwargs):
return Employee(**data)
|
Java
|
UTF-8
| 371 | 2.15625 | 2 |
[] |
no_license
|
package Gauss;
import java.util.Arrays;
public class App
{
public static void main( String[] args )
{
double[][] matrix = {{ 3, 4, -9, 5},
{-15, -12, 50, -16},
{-27, -36, 73, 8},
{ 9, 12,-10, -16}};
InverseMatrix.getInverseMatrix(matrix);
}
}
|
Java
|
UTF-8
| 11,057 | 2.140625 | 2 |
[] |
no_license
|
package mock02.dao;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import mock02.model.Assignment;
import mock02.model.Member;
import mock02.model.Score;
import mock02.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* @author: ThaiHa
* @verision:1.0 Dec 26, 2015
**/
@Repository("scoreDAO")
@Transactional
public class ScoreDAO {
@Autowired
SessionFactory sessionFactory;
// get score from by user and assignemnt
@SuppressWarnings("unchecked")
public List<Integer> getPointbyMemberAndAssignment(Assignment assignment, Member member) {
Session session = sessionFactory.getCurrentSession();
List<Integer> result = (List<Integer>) session.createCriteria(Score.class)
.add(Restrictions.eq("member", member)).add(Restrictions.eq("assignment", assignment))
.setProjection(Projections.property("score")).list();
return result;
}
public Score getScorebyMemberAndAssignment(Assignment assignment, Member member) {
Session session = sessionFactory.getCurrentSession();
Score result = (Score) session
.createCriteria(Score.class)
.add(Restrictions.eq("member", member))
.add(Restrictions.eq("assignment", assignment))
.setProjection(
Projections.projectionList().add(Projections.property("score").as("score"))
.add(Projections.property("answer").as("answer"))
.add(Projections.property("attachFileName").as("attachFileName"))
.add(Projections.property("comment").as("comment"))
.add(Projections.property("timeStore").as("timeStore"))
.add(Projections.property("countUpdate").as("countUpdate")))
.setResultTransformer(Transformers.aliasToBean(Score.class)).uniqueResult();
return result;
}
@SuppressWarnings({ "unchecked" })
public List<Score> getListAnswerByAssignment(Assignment assignment) throws ParseException {
Session session = sessionFactory.getCurrentSession();
List<Object[]> result = (List<Object[]>) session
.createCriteria(Score.class)
.add(Restrictions.eq("assignment", assignment))
.createAlias("member", "mem")
.createAlias("member.user", "u")
.setProjection(
Projections.distinct(Projections.projectionList()
.add(Projections.property("idScore")).add(Projections.property("score"))
.add(Projections.property("timeStore"))
.add(Projections.property("u.fullName")))).list();
List<Score> listScore = new ArrayList<Score>();
Score score;
Assignment assign;
Member member;
User user;
SimpleDateFormat sdf = new SimpleDateFormat("yyy-M-dd HH:mm:ss");
for (Object[] obj : result) {
score = new Score();
assign = new Assignment();
member = new Member();
user = new User();
score.setIdScore(Integer.parseInt(String.valueOf(obj[0])));
if ("null".compareTo(String.valueOf(obj[1])) != 0)
score.setScore(Integer.parseInt(String.valueOf(obj[1])));
score.setTimeStore(sdf.parse(String.valueOf(obj[2])));
user.setFullName(String.valueOf(obj[3]));
member.setUser(user);
score.setMember(member);
score.setAssignment(assign);
listScore.add(score);
}
return listScore;
}
public Score getAnswerById(Integer idScore) throws ParseException {
Session session = sessionFactory.getCurrentSession();
Object[] result = (Object[]) session
.createCriteria(Score.class)
.add(Restrictions.eq("idScore", idScore))
.createAlias("member", "mem")
.createAlias("member.user", "u")
.createAlias("assignment", "a")
.setProjection(
Projections.distinct(Projections.projectionList()
.add(Projections.property("idScore")).add(Projections.property("score"))
.add(Projections.property("timeStore"))
.add(Projections.property("u.fullName")).add(Projections.property("comment"))
.add(Projections.property("attachFileName"))
.add(Projections.property("a.idAssignment"))
.add(Projections.property("a.deadline")).add(Projections.property("answer"))
.add(Projections.property("a.assignmentName")))).uniqueResult();
Score score = new Score();
Member member = new Member();
User user = new User();
Assignment assignment = new Assignment();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd HH:mm:ss");
member.setUser(user);
score.setMember(member);
score.setAssignment(assignment);
score.setIdScore(Integer.parseInt(String.valueOf(result[0])));
if ("null".compareTo(String.valueOf(result[1])) != 0)
score.setScore(Integer.parseInt(String.valueOf(result[1])));
score.setTimeStore(sdf.parse(String.valueOf(result[2])));
user.setFullName(String.valueOf(result[3]));
if ("null".compareTo(String.valueOf(result[4])) != 0)
score.setComment(String.valueOf(result[4]));
if ("null".compareTo(String.valueOf(result[5])) != 0)
score.setAttachFileName(String.valueOf(result[5]));
if ("null".compareTo(String.valueOf(result[6])) != 0)
assignment.setIdAssignment(Integer.parseInt(String.valueOf(result[6])));
assignment.setDeadline(sdf.parse(String.valueOf(result[7])));
score.setAnswer(String.valueOf(result[8]));
assignment.setAssignmentName(String.valueOf(result[9]));
return score;
}
public void markAnswer(Score score) {
Session session = sessionFactory.getCurrentSession();
session.createQuery("update Score set score = :score, comment = :comment where idScore = :id")
.setInteger("score", score.getScore()).setString("comment", score.getComment())
.setInteger("id", score.getIdScore()).executeUpdate();
}
public boolean hasDone(Assignment assignment, Member member) {
Session session = sessionFactory.getCurrentSession();
Integer result = (Integer) session.createCriteria(Score.class)
.add(Restrictions.eq("assignment", assignment))
.add(Restrictions.eqOrIsNull("member", member))
.setProjection(Projections.property("idScore")).setMaxResults(1).uniqueResult();
if (result != null)
return true;
return false;
}
@SuppressWarnings("unchecked")
public Integer getCountUpdate(Assignment assignment, Member member) {
Session session = sessionFactory.getCurrentSession();
Integer result = null;
if (assignment.getType().equals("test")) {
result = (Integer) session.createCriteria(Score.class)
.add(Restrictions.eq("assignment", assignment))
.add(Restrictions.eqOrIsNull("member", member))
.setProjection(Projections.property("countUpdate")).setMaxResults(1).uniqueResult();
} else if (assignment.getType().equals("quiz")) {
List<Integer> listScore = (List<Integer>) session.createCriteria(Score.class)
.add(Restrictions.eq("assignment", assignment))
.add(Restrictions.eqOrIsNull("member", member))
.setProjection(Projections.property("idScore")).list();
result = listScore.size();
}
return result;
}
public Integer getIdScoreByIdAssignmentAndIdMember(Integer idAssignment, Integer idMember) {
Session session = sessionFactory.getCurrentSession();
Integer result = (Integer) session
.createQuery(
"select idScore from Score where idAssignment =:idAssignment and idMember =:idMember")
.setInteger("idMember", idMember).setInteger("idAssignment", idAssignment).setMaxResults(1)
.uniqueResult();
return result;
}
public void saveAnswerTestWithFile(Assignment assignment, Member member, String answer, Blob file,
String fileName) {
Session session = sessionFactory.getCurrentSession();
Date now = new Date();
Score score = new Score(assignment, member, now, answer, fileName, file);
score.setCountUpdate(1);
session.save(score);
session.flush();
}
public void saveAnswerTestWithoutFile(Assignment assignment, Member member, String answer) {
Session session = sessionFactory.getCurrentSession();
Date now = new Date();
Score score = new Score(assignment, member, now, answer);
score.setCountUpdate(1);
session.save(score);
session.flush();
}
public void updateAnswerTestNotChangeFile(String answer, Integer idScore, Integer redoTime) {
Session session = sessionFactory.getCurrentSession();
Integer countUpdate = (Integer) session
.createQuery("select countUpdate from Score where idScore =:id").setInteger("id", idScore)
.uniqueResult();
//prevent cheat update
if(redoTime == countUpdate)
return;
countUpdate = countUpdate + 1;
Date now = new Date();
session.createQuery(
"update Score set answer =:answer, timeStore =:timeStore, countUpdate =:count where idScore =:idScore")
.setString("answer", answer).setTimestamp("timeStore", now).setInteger("idScore", idScore)
.setInteger("count", countUpdate).executeUpdate();
}
public void updateAnswerTestChangeFile(String answer, Blob file, String fileName, Integer idScore,
Integer redoTime) throws SQLException {
Session session = sessionFactory.getCurrentSession();
Integer countUpdate = (Integer) session
.createQuery("select countUpdate from Score where idScore =:id").setInteger("id", idScore)
.uniqueResult();
//prevent cheat update
if(redoTime == countUpdate)
return;
countUpdate = countUpdate + 1;
Date now = new Date();
if (file != null)
session.createQuery(
"update Score set answer =:answer, timeStore =:timeStore, attachFile =:file, attachFileName =:fileName, countUpdate =:count "
+ "where idScore =:idScore").setString("answer", answer)
.setTimestamp("timeStore", now).setInteger("idScore", idScore)
.setInteger("count", countUpdate)
.setBinary("file", file.getBytes(1, (int) file.length())).setString("fileName", fileName)
.executeUpdate();
else
session.createQuery(
"update Score set answer =:answer, timeStore =:timeStore, attachFile =:file, attachFileName =:fileName, countUpdate =:count "
+ "where idScore =:idScore").setString("answer", answer)
.setTimestamp("timeStore", now).setInteger("idScore", idScore)
.setInteger("count", countUpdate).setBinary("file", null).setString("fileName", null)
.executeUpdate();
session.flush();
}
public String getAnswerFileNameById(Integer id) {
Session session = sessionFactory.getCurrentSession();
String result = (String) session.createCriteria(Score.class).add(Restrictions.eq("idScore", id))
.setProjection(Projections.projectionList().add(Projections.property("attachFileName")))
.uniqueResult();
return result;
}
public Blob getAnswerFileById(Integer id) {
Session session = sessionFactory.getCurrentSession();
Blob result = (Blob) session.createCriteria(Score.class).add(Restrictions.eq("idScore", id))
.setProjection(Projections.projectionList().add(Projections.property("attachFile")))
.uniqueResult();
return result;
}
}
|
Markdown
|
UTF-8
| 700 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
This repo contains the source code for a talk on bash scripting.
## dependencies
- unpaper
- tesseract
- libtiff
- poppler
- netpbm
## usage
./process_document_dir.sh ~/documents/pdfs
The script takes a single directory as an argument, expecting its structure to be:
pdfs:
pdfname:
1.pdf
a.pdf
b.pdf
secondpdfname:
aasdjsad.pdf
asdsafsafasfsa.pdf
The script will collate the pdfs in each directory, combine them, ocr them, and add the ocr text to the pdf. The above example will output two pdfs into "pdfs" named pdfname.pdf and secondpdfname.pdf, each containing the pdfs from their respective directories.
|
C++
|
UTF-8
| 952 | 2.765625 | 3 |
[] |
no_license
|
#include<iostream>
int gray[101][101];
int map[101][101];
int n;
int min;
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,-1,1 };
bool isInMap(int x, int y)
{
if (x < 1 || y>n || x > n || y < 1)
{
return false;
}
else
return true;
}
void solve(int x, int y, int t)
{
if (x == n && y == n)
{
if (min > t)
{
min = t;
}
return;
}
if (min < t)
return;
else
{
int cx;
int cy;
gray[x][y] = 1;
for (int i = 0; i < 4; i++)
{
cx = x + dx[i];
cy = y + dy[i];
if (isInMap(cx, cy))
{
if (!gray[cx][cy])
{
solve(cx, cy, map[cx][cy] + t);
gray[cx][cy] = 0;
}
continue;
}
else
continue;
}
}
}
int main()
{
int test_case;
scanf("%d", &test_case);
for (int i = 1; i <= test_case; i++)
{
scanf("%d", &n);
min = 100000000;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
scanf("%1d", &map[i][j]);
}
}
solve(1, 1, 0);
printf("%d\n", min);
}
}
|
Markdown
|
UTF-8
| 2,661 | 2.625 | 3 |
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
# 说明
这是我在空闲时间用yii2-basic来练手的项目,目前还在学习中,在此分享给大家,希望能得到些指点和建议,多学到点东西,也希望有同样热爱yii2的同学和我多多交流,互相学习,我的QQ是494364222。
写了很多注释,主要的都在`Music`相关的代码里了,如果哪里看不懂或者代码还有更好的写法的话,就多多和我交流吧。
另外就是我强迫症很严重,所以有可能会经常把代码简化,或者把一些封装方式和方法的顺序以及一些命名会经常改来改去的,请见谅。
除了框架本身的**入口文件**/web/index.php和**配置文件**/config/web.php以及**数据库配置文件**/config/db.php以外(这句话写给初学者的),其他你只需关注的地方如下:
目录 | 说明
---|---
/models | model
/modules | 模块,主要的东西都在这里了,模块的注释在**配置文件**里
/views | 只是放一个布局文件而已
# 项目部署
## 安装
1. yii2需要开启的PHP的openssl,我用的是mysql,要开pdo_mysql扩展,弄了文件上传的功能,需要fileinfo扩展。(因为还没开始学缓存什么的,所以可以用php7,速度很快)
2. 你要有[composer](http://docs.phpcomposer.com/),以及创建一个utf8数据库,在**数据库配置文件**配置好相关参数后,执行以下命令:
```
composer install
yii migrate --migrationPath=@yii/rbac/migrations
yii migrate/to m140602_111327_create_menu_table --migrationPath=@mdm/admin/migrations
yii migrate
```
## 使用
1. 需要开启apache的rewrite并把站点根目录设置为`/web`,因为后台菜单需要,以后再解决这个问题。
2. 用户名和密码如下:
身份 | 用户名 | 密码 |
---|---|---
超级管理员 | hu | hbw12345
普通用户 | test | qwer1234
## 安装遇到问题怎么办?
1. 我只测试过migration能正常导入数据而已,项目刚传上来还没测试过别人拿到手之后能不能跑,有问题加QQ联系吧。
2. 可能有些同学执行`composer install`后vendor目录里没有bower目录,尝试执行以下命令再重新执行一次`composer install`,[参考链接](https://segmentfault.com/q/1010000004047286)
```
composer global require "fxp/composer-asset-plugin:~1.1.1"
```
# 打赏
如果觉得我的项目做的好的话,就给我打赏吧,以后我会用这些钱来学习以及购买服务器。


|
C#
|
UTF-8
| 3,144 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
// AudioAnchor - Audio Management and Playing Singleton
public class AudioAnchorScript : MonoBehaviour
{
public static AudioAnchorScript inst = null; // The singleton instance
[HideInInspector] public AudioSource sfxSource; // SFX AudioSource component
[HideInInspector] public AudioSource musicSource; // Music AudioSource
public bool playSoundEffectsBetweenScenes = true;
public bool playMusicBetweenScenes = true;
// In-editor dictionary pair AudioClip->float equivalent
[System.Serializable]
public struct ClipIntensityPair
{
public AudioClip clip;
public float intensity;
}
public ClipIntensityPair[] SFXIntensityPairArray; // Sound FX
public ClipIntensityPair[] MusicIntensityPairArray; // Musical Tracks
void Awake ()
{
InitializeSingletonInstance();
sfxSource = gameObject.AddComponent<AudioSource>();
sfxSource.loop = true;
sfxSource.playOnAwake = false;
musicSource = gameObject.AddComponent<AudioSource>();
musicSource.loop = true;
musicSource.playOnAwake = false;
}
// Performs functions required when transitioning between scenes.
// MUST BE CALLED BEFORE CHANGING SCENES OR AUDIO WILL MAY PERFORM INCORRECTLY
public void TransitionScenes()
{
if (!playSoundEffectsBetweenScenes)
{
// Stop the source sound effects
sfxSource.enabled = false;
sfxSource.enabled = true;
}
if (!playMusicBetweenScenes)
{
// Stop the source music
musicSource.enabled = false;
musicSource.enabled = true;
}
}
// Play a sound via this GameObjects AudioSource via given AudioClip name
public void PlaySound(string clipName)
{
for (int i = 0; i < SFXIntensityPairArray.Length; i++)
{
if ( clipName == SFXIntensityPairArray[i].clip.name )
{
sfxSource.PlayOneShot(SFXIntensityPairArray[i].clip, SFXIntensityPairArray[i].intensity);
return;
}
}
Debug.LogError("AudioAnchor: " + clipName
+ " AudioClip name not found. Are you sure it's been added to the AudioAnchorScript component SFX array?");
}
// Play looping music via this GameObject's AudioSource via given AudioClip name
public void PlayMusic(string musicName)
{
for (int i = 0; i < MusicIntensityPairArray.Length; i++)
{
if ( musicName == MusicIntensityPairArray[i].clip.name )
{
if (musicSource.isPlaying) return;
musicSource.clip = MusicIntensityPairArray[i].clip;
musicSource.volume = MusicIntensityPairArray[i].intensity;
musicSource.Play();
return;
}
Debug.LogError("AudioAnchor: " + musicName
+ " AudioClip name not found. Are you sure it's been added to the AudioAnchorScript component Music array?");
}
}
// Attempt initialization of the instance of this singleton
private void InitializeSingletonInstance()
{
// Delete the older instance if it exists and isn't this
if (inst == null)
{
inst = this;
DontDestroyOnLoad(this.gameObject);
}
else if (inst != this) Destroy(this.gameObject);
}
}
|
Rust
|
UTF-8
| 634 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
use my_des;
fn main() {
let sample_inp: Vec<u64> = vec![
0x0123456789ABCDEF,
0x0123456789ABCDEF,
0x0123456789ABCDEF
];
let sample_key: u64 = 0x85E813540F0AB405;
println!("Sample input: {:?}", sample_inp);
let mut mode: Box<dyn my_des::Cipher> = Box::new(my_des::ECB::new());
let ciphertext = my_des::encrypt(sample_inp, sample_key, &mut mode);
println!("ECB cipher: {:?}", ciphertext);
let mut mode: Box<dyn my_des::Cipher> = Box::new(my_des::ECB::new());
let plaintext = my_des::decrypt(ciphertext, sample_key, &mut mode);
println!("Plaintext: {:?}", plaintext);
}
|
Java
|
UTF-8
| 951 | 2.078125 | 2 |
[] |
no_license
|
package com.example.calender;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class eventPage extends AppCompatActivity {
public static final String msg = "com.example.calender.MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_page);
}
public void addEvent2(View view){
Intent intent = getIntent();
String dt = intent.getStringExtra(MainActivity.date);
EditText event = findViewById(R.id.event);
String message = dt+" -- "+event.getText().toString();
Intent intent2 = new Intent(this,MainActivity.class);
intent2.putExtra(msg,message);
startActivity(intent2);
}}
|
PHP
|
UTF-8
| 1,291 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace NoMoreWar\Casualties\Commands;
use Dotenv\Dotenv;
use NoMoreWar\Casualties\Exceptions\DatabaseException;
use PDO;
use PDOException;
use Symfony\Component\Console\Command\Command;
class BaseCommand extends Command
{
/**
* Connection variable for the database server.
*
* @var PDO $pdo;
*/
public $pdo;
/**
* Parent function for the Command classes.
*
* @return PDO
*/
public function __construct()
{
parent::__construct(); // Call the construct from the command class first.
$dotenv = new Dotenv(__DIR__ . '/../../'); // Locate the environment file.
$dotenv->load(); // Load the environment file.
try { // To connection with the database server.
$dsn = 'mysql: dbname=' . getenv('DB_NAME') . ';host=' . getenv('DB_HOST') . ';port=' . getenv('DB_PORT');
$this->pdo = new PDO($dsn, getenv('DB_USER'), getenv('DB_PASS'), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_LOCAL_INFILE => true
]);
return $this->pdo;
} catch (PDOException $databaseException) { // Could not connect to the server.
throw new DatabaseException($databaseException);
}
}
}
|
Swift
|
UTF-8
| 464 | 3.015625 | 3 |
[] |
no_license
|
//
// Question.swift
// QuizApp
//
// Created by yumi on 2020/06/02.
// Copyright © 2020 Yumi Takahashi. All rights reserved.
//
import Foundation
// クイズの構成を記載
struct Question {
let text: String
var answers: [String]
let rightAnswer: String
let label: Int
init(q: String, a: [String], correctAnswer: String, l: Int) {
text = q
answers = a
rightAnswer = correctAnswer
label = l
}
}
|
Markdown
|
UTF-8
| 5,121 | 3.375 | 3 |
[] |
no_license
|
# 表单校验
> 校验都是必须的过程, 只是具体该怎么校验才比较好,是值得深掘的过程, 现在一般分两种。
- 提交前校验,在每个字段下方进行校验,及时提示
- 在提交时校验,不通过再进行提示(谷歌在注册账号时,用的是后端校验,直接将错误信息展现在对应的输入框位置)
> ==============
- 录入数据是进行表单校验
- 已有数据,初步不进行表单校验,等有数据再进行表单校验, 输入框颜色变化
- 动态创建表单 进行校验
- 表单非必填是 表单校验
- 表单依据状态动态 变为 必填项 非必填项
### 新知
- 红色星号 `el-form-item`这个组件的类名中 添加 `is-required`
- 同时校验多个表单
```
var p1=new Promise(function(resolve, reject) {
this.$refs[form1].validate((valid) => {
if(valid){
resolve();
}
})
});
var p2=new Promise(function(resolve, reject) {
this.$refs[form2].validate((valid) => {
if(valid){
resolve();
}
})
});
Promise.all([p2,p1]).then(function(){
alert("验证通过了");
});
```
> 遇到的问题 数据是从服务器请求回来时,会触发校验,而且显示的颜色明显有问题,一些变色(显示成功), 可是有一些却没有,显得很怪异
> 从后台请求数据,为何会触发校验
- input 输入框 不会触发校验
- select 会触发校验 (可能是因为 select 需要进行计算显示具体值,因而会触发 change 或 blur 事件)
> 验证对象的某个具体属性
```
// template
<el-form-item prop="object.key"></el-form-item>
// javascript
rules: {
'object.key': [
{required: true ...}
]
}
```
### `async-validator`
- [知乎](https://zhuanlan.zhihu.com/p/32306570)
> 细节点
- 内置校验
- `required` 进行校验是否非空 _false_ 只是不进行非空校验
- `enum`校验器校验 rule 为{ type: 'enum', required: true, enum: ['male', 'female'] }的数据 value 非空,且其值为 rule.enum 中的一个
- `pattern`校验器校验 rule 为{ pattern: /\s/, required: true }的数据 value 非空、且匹配正则表达式或正则字符串
- `string`校验器校验 rule 为{ type: 'string', pattern: /\s/, required: true, min: 1, whitespace: true }的数据 value 非空、且为字符串、且其长度匹配校验条件、且匹配正则表达式或正则字符串、且不是空字符串。
- 自定义校验
- `rule = { validator: function(rule, value, callback, source, options){} }或rule = function(rule, value, callback, source, options){}`
- 假使多个字段共用同一个自定义校验器时,要怎样才能区分当前的校验字段是哪一个呢?在 async-validator 源码的实现中,开发者配置的 rule 数据会添加 field、fullField 属性,其中 field 就是当前校验的字段名。fullField 是当前校验字段的全名,这在深度校验的时候用到。值得说明的是,参数 source 是整个待校验的数据,value 也是 source 的一个属性。这样,async-validator 模块就为开发者提供了关联校验的能力。假使有字段 min、max 需要校验,对 min 字段,需要校验其数值不大于 max 字段的值,开发者就可以通过 source[max]属性获取到 max 字段的值,从而实现关联校验。
- Test
- `name: [{type: 'string', validator: function() {}, field: 'name'}]` **field **
-
### 问题
> 各种杂七杂八的思路
- 从后台请求回的数据,为何会触发校验
- input 不会触发校验,因而只是单纯展示,没有颜色变化
- select 却会触发校验,且颜色有变化(是否是因为 select 内部进行运行过程中,触发了校验)
- 可以验证对象的某一个属性
- `prop="object.name" --------------- rules: { 'object.name': [.......] }`
- 控制校验
- `this.$refs[ruleForm].clearValidate()` 可以清楚校验规则,但是却也无法再次唤醒校验了???
- 字段变化时,是否触发校验或者去除校验
```
watch: { dialogFormVisible : function( val, oldVla) { this. $refs[ "form"]. resetFields(); } }
```
- validate 中代码不执行[参考](https://www.jianshu.com/p/e356dd26583e)
```
在自定义验证里面每一个判断都要有callback(),就是要保证callback()一定会执行到
```
### 经过许久的各种表单校验困惑,逼我再次寻找其他校验插件
- [element-ui-verify](https://github.com/aweiu/element-ui-verify) 目前看起来还不错
## 产品角度探讨
> 目前就问题而言,重点在于数据返显时,是否校验问题(颜色变化问题)
- 不需要校验,这样校验后的颜色便不会存在
- 校验,这样用户可以一眼知道错误信息在哪?
个人见解:就当前阐述问题而言,都是站在返显并需要编辑的角度进行考虑(若不是编辑也就不需要进行 input 了)
|
JavaScript
|
UTF-8
| 445 | 2.859375 | 3 |
[] |
no_license
|
function displayPage(){
var param = document.getElementsByTagName("param");
for(var i = 0; i < param.length; i++){
param[i].value = "";
}
}
//another stop load time
//若載入影片失效時,可以註解上面的方法,改用這個方法。
/* jQuery(document).ready(function(){
var param = document.getElementsByTagName("param");
alert("Video is ready!");
for(var i = 0; i < param.length; i++){
param[i].value = "";
}
}) */
|
Python
|
UTF-8
| 4,985 | 2.546875 | 3 |
[] |
no_license
|
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True # 不全部占满显存,按需分配
# config.gpu_options.per_process_gpu_memory_fraction = 0.3
session = tf.Session(config=config)
import numpy as np
from sklearn import metrics
from keras.models import load_model
from keras.utils import to_categorical
# 说明: 性能评估函数
# 输入: predictions 预测结果,Y_test 实际标签,verbose 日志显示,0为不在标准输出流输出日志信息,1为输出进度条记录,2为每个epoch输出一行记录
# 输出: [sn, sp, acc, pre, f1, mcc, gmean, auroc, aupr] 验证指标结果
def perform_eval_2(predictions, Y_test, verbose=0):
# class_label = np.uint8([round(x) for x in predictions[:, 0]]) # round()函数进行四舍五入
# R_ = np.uint8(Y_test)
# R = np.asarray(R_)
class_label = np.uint8(np.argmax(predictions, axis=1))
R = np.asarray(np.uint8([sublist[1] for sublist in Y_test]))
CM = metrics.confusion_matrix(R, class_label, labels=None)
CM = np.double(CM) # CM[0][0]:TN,CM[0][1]:FP,CM[1][0]:FN,CM[1][1]:TP
# 计算各项指标
sn = (CM[1][1]) / (CM[1][1] + CM[1][0]) # TP/(TP+FN)
sp = (CM[0][0]) / (CM[0][0] + CM[0][1]) # TN/(TN+FP)
acc = (CM[1][1] + CM[0][0]) / (CM[1][1] + CM[0][0] + CM[0][1] + CM[1][0]) # (TP+TN)/(TP+TN+FP+FN)
pre = (CM[1][1]) / (CM[1][1] + CM[0][1]) # TP/(TP+FP)
f1 = (2 * CM[1][1]) / (2 * CM[1][1] + CM[0][1] + CM[1][0]) # 2*TP/(2*TP+FP+FN)
mcc = (CM[1][1] * CM[0][0] - CM[0][1] * CM[1][0]) / np.sqrt((CM[1][1] + CM[0][1]) * (CM[1][1] + CM[1][0]) * (CM[0][0] + CM[0][1]) * (CM[0][0] + CM[1][0])) # (TP*TN-FP*FN)/((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))^1/2
gmean = np.sqrt(sn * sp)
auroc = metrics.roc_auc_score(y_true=R, y_score=np.asarray(predictions)[:, 1], average="macro")
aupr = metrics.average_precision_score(y_true=R, y_score=np.asarray(predictions)[:, 1], average="macro")
if verbose == 1:
print("Sn(Recall):", "{:.4f}".format(sn), "Sp:", "{:.4f}".format(sp), "Acc:", "{:.4f}".format(acc),
"Pre(PPV):", "{:.4f}".format(pre), "F1:", "{:.4f}".format(f1), "MCC:", "{:.4f}".format(mcc),
"G-mean:", "{:.4f}".format(gmean), "AUROC:", "{:.4f}".format(auroc), "AUPR:", "{:.4f}".format(aupr))
return [sn, sp, acc, pre, f1, mcc, gmean, auroc, aupr]
# 说明: 实验结果保存到文件
# 输入: 文件标识符和结果
# 输出: 无
def write_res_2(filehandle, res):
filehandle.write("Sn(Recall): %s Sp: %s Acc: %s Pre(PPV): %s F1: %s MCC: %s G-mean: %s AUROC: %s AUPR: %s\n" %
("{:.4f}".format(res[0]),
"{:.4f}".format(res[1]),
"{:.4f}".format(res[2]),
"{:.4f}".format(res[3]),
"{:.4f}".format(res[4]),
"{:.4f}".format(res[5]),
"{:.4f}".format(res[6]),
"{:.4f}".format(res[7]),
"{:.4f}".format(res[8]))
)
filehandle.flush()
return
if __name__ == '__main__':
# 超参数设置
WINDOWS = 25
# 打开保存结果的文件
res_file = open("./result/test/yan_res_Cov1D_SE_softmax_early_3_elu.txt", "w", encoding='utf-8')
# 创建空列表,保存预测结果
res = []
# 提取序列片段(阳性+阴性)
# 打开阴阳数据集文件
f_r = open("./dataset/human/after_CD-HIT(0.4)/test/%s/Acetylation_Pos_Neg.txt" % str(2 * WINDOWS + 1), "r", encoding='utf-8')
# 正确打开文件后,读取文件内容
Test_data = f_r.readlines()
f_r.close()
# 数据编码
from information_coding import one_hot, Phy_Chem_Inf, Structure_Inf
# one_hot编码序列片段
test_X_1, test_Y = one_hot(Test_data, windows=WINDOWS)
test_Y = to_categorical(test_Y, num_classes=2)
# 理化属性信息
test_X_2 = Phy_Chem_Inf(Test_data, windows=WINDOWS)
# 蛋白质结构信息
test_X_3 = Structure_Inf(Test_data, windows=WINDOWS)
# 加载模型
model = load_model(filepath='./model/yan_model_Cov1D_SE_softmax_early_3_elu_fold5.h5')
model.summary()
# 任务预测
predictions = model.predict(x=[test_X_1, test_X_2, test_X_3], verbose=0)
result = []
for i in range(len(Test_data)):
result.append(predictions[i][1])
index_value = sorted(enumerate(result), reverse=True, key=lambda x: x[1])
for i in range(len(index_value)):
data = Test_data[index_value[i][0]].split()
res_file.write(data[0] + "\t" + str(int(data[3]) + 1) + "\t" + str(index_value[i][1]) + "\t" + data[1] + "\n")
res_file.flush()
# 验证预测结果
res = perform_eval_2(predictions, test_Y, verbose=1)
# 将测试集预测结果写入文件
write_res_2(res_file, res)
res_file.close()
print("Test data predicted Successfully!!")
|
Java
|
GB18030
| 13,002 | 2.484375 | 2 |
[] |
no_license
|
package com.lixh.basecode.util;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import com.lixh.basecode.app.BaseApplication;
public class FileUtil {
static String message = null;
/***
* ȡĿļ
*
* @return
*/
public static File getDir() {
String packname = BaseApplication.getInstance().getPackageName();
String name = packname.substring(packname.lastIndexOf(".") + 1,
packname.length());
File dir = null;
if ((!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))) {
dir = BaseApplication.getInstance().getCacheDir();
} else {
dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + name);
}
dir.mkdirs();
return dir;
}
/**
* ȡĿļ
*
* @return
*/
public static String getCacheDir() {
File file = new File(getDir().getAbsolutePath() + "/cache");
if (!file.exists()) {
file.mkdirs();
}
return file.getAbsolutePath();
}
/**
* ȡĿʹùвͼƬļ
*
* @return
*/
public static String getImageDir() {
File file = new File(getDir().getAbsolutePath() + "/image");
file.mkdirs();
return file.getAbsolutePath();
}
/**
* ǷSDcard
*
* @return
*/
public static boolean isExistsSdcard() {
return Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
}
/**
* ȡĿʹõݿ
*
* @return
*/
public static String getdbDir() {
File file = new File(getDir().getAbsolutePath() + "/db");
file.mkdirs();
return file.getAbsolutePath();
}
/**
* uriװļ
*
* @param context
* @param uri
* @return
*/
public static File uriToFile(Activity context, Uri uri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor actualimagecursor = context.managedQuery(uri, proj, null, null,
null);
int actual_image_column_index = actualimagecursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor
.getString(actual_image_column_index);
File file = new File(img_path);
return file;
}
/**
* дļ
*
* @param in
* @param file
*/
public static void write(InputStream in, File file) {
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while (in.read(buffer) > -1) {
out.write(buffer);
}
out.flush();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* дļ
*
* @param in
* @param file
*/
public static void write(String in, File file, boolean append) {
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileWriter fw = new FileWriter(file, append);
fw.write(in);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
*
* @param file
* @return
*/
public static String read(File file) {
if (!file.exists()) {
return "";
}
try {
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
StringBuffer buffer = new StringBuffer();
String s;
while ((s = br.readLine()) != null) {
buffer.append(s);
}
return buffer.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* ַΪλȡļдıֵ͵ļ
*
* @param fileDir
* ļĿ¼
* @param fileName
* ļ
* @param is
* @return
* @throws IOException
*/
public static boolean wirteFileByChars(String fileDir, String fileName,
FileInputStream is) throws IOException {
boolean isSuccess = false;
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(fileDir);// Ŀ¼
if (!directory.exists()) {// ڣĿ¼
directory.mkdirs();
}
File file = new File(fileDir, fileName);
if (!file.exists()) // ڣļ
file.createNewFile();
PrintWriter pWriter = null;
if (is != null) {
pWriter = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(file)));
BufferedReader bReader = new BufferedReader(
new InputStreamReader(is));
String lineContent;
while ((lineContent = bReader.readLine()) != null) {
pWriter.println(lineContent);
}
pWriter.flush();
bReader.close();
pWriter.close();
isSuccess = true;
}
}
return isSuccess;
}
/**
* ַΪλȡļдıֵ͵ļ
*
* @param fileDir
* ļĿ¼
* @param fileName
* ļ
* @param is
* @return
* @throws IOException
*/
public static boolean wirteFileByChars(String fileDir, String fileName,
String content) throws IOException {
boolean isSuccess = false;
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(fileDir);// Ŀ¼
if (!directory.exists()) {// ڣĿ¼
directory.mkdirs();
}
File file = new File(fileDir, fileName);
if (!file.exists()) // ڣļ
file.createNewFile();
PrintWriter pWriter = null;
if (content != null) {
pWriter = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(file)));
pWriter.write(content, 0, content.length());
pWriter.flush();
pWriter.close();
isSuccess = true;
}
}
return isSuccess;
}
/**
* ַΪλȡļڶıֵ͵ļ
*
* @param filePath
* ļ·
* @return
* @throws IOException
*/
public static String readFileByChars(String filePath) throws IOException {
if (isExistsSdcard()) {// жSDcardǷ
File direstory = new File(filePath);
if (direstory.exists()) {
BufferedReader bReader = new BufferedReader(
new InputStreamReader(new FileInputStream(direstory)));
StringBuffer sb = new StringBuffer();
String lineContent;
while ((lineContent = bReader.readLine()) != null) {
sb.append(lineContent);
}
bReader.close();
return sb.toString();
}
}
return null;
}
/**
* ֽΪλдļڶļͼƬӰļ
*
* @param fileDir
* ļĿ¼
* @param fileName
* ļ
* @param is
* @return
* @throws IOException
*/
public static boolean wirteFileByBytes(String fileDir, String fileName,
InputStream is) throws IOException {
boolean isSuccess = false;
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(fileDir);// Ŀ¼
if (!directory.exists()) {// ڣĿ¼
directory.mkdirs();
}
File file = new File(fileDir, fileName);
if (!file.exists()) // ڣļ
file.createNewFile();
FileOutputStream fileOutPutStream = null;
if (is != null) {
fileOutPutStream = new FileOutputStream(file);
byte[] b = new byte[1024];
int size = -1;
while ((size = is.read(b)) != -1) {
fileOutPutStream.write(b, 0, size);
}
fileOutPutStream.flush();
is.close();
fileOutPutStream.close();
isSuccess = true;
}
}
return isSuccess;
}
/**
* ֽΪλдļڶļͼƬӰļ
*
* @param filePath
* ļ·
* @return
* @throws IOException
*/
@SuppressWarnings("resource")
public static byte[] readFileByBytes(String filePath) throws IOException {
if (isExistsSdcard()) {// жSDcardǷ
File direstory = new File(filePath);
if (direstory.exists()) {
FileInputStream fileInputStream = new FileInputStream(direstory);
ByteBuffer buffer = ByteBuffer.allocate(fileInputStream
.available());
byte[] b = new byte[1024];
int size = -1;
while ((size = fileInputStream.read(b)) != -1) {
buffer.put(b, 0, size);
}
return buffer.array();
}
}
return null;
}
/**
* ͼƬдSDcard
*
* @param fileName
* @param mBitmap
* @return
*/
public static boolean wirteBitmap(String fileDir, String fileName,
Bitmap mBitmap) {
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(fileDir);// Ŀ¼
if (!directory.exists()) {// ڣĿ¼
directory.mkdirs();
}
File file = new File(fileDir + fileName);// ļ
if (!file.exists()) {
try {
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(file));// ļд
boolean isSuccess = mBitmap.compress(
Bitmap.CompressFormat.PNG, 100, stream);
if (!isSuccess) {
message = "ʧܣ";
} else {
message = "ɹ";
}
stream.flush();
stream.close();
return isSuccess;
} catch (IOException e) {
e.printStackTrace();
}
} else {
message = "ѱ棡";
return false;
}
} else {
message = "SDcardڣ";
}
return false;
}
/**
* ȡSDcardָĿ¼µָļ·
*
* @param path
* Ŀ¼
* @param postfix
*
* @return
*/
public static ArrayList<String> readFiles(String dir, String postfix) {
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(dir);// Ŀ¼
if (!directory.exists()) {
message = "ĿǰûͼƬ";
return null;
}
File[] files = directory.listFiles();
ArrayList<String> filesPath = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
String path = files[i].getAbsolutePath();
if (path.endsWith(postfix)) {
filesPath.add(path);
}
}
return filesPath;
} else {
message = "SDcardڣ";
}
return null;
}
/**
* ɾָļ
*/
public static boolean deleteFile(String filePath) {
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(filePath);
if (directory.exists()) {
return directory.delete();
}
}
return false;
}
/**
* ɾָļ
*/
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
dir.delete();
return true;
}
/**
* ɾָĿ¼еļ
*/
public static boolean deleteDirFile(String delPath) {
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(delPath);
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirFile(files[i].getAbsolutePath());
files[i].delete();
} else {
files[i].delete();
}
}
return true;
}
return false;
}
/**
* жļǷ
*
* @param file
* @return
*/
public static boolean isExistsFile(String filePath) {
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(filePath);
if (directory.exists()) {
return true;
}
}
return false;
}
/**
* ش˳·ʾļһαĵʱ
*
* @param filePath
* @return
*/
public static long lastModified(String filePath) {
if (isExistsSdcard()) {// жSDcardǷ
File directory = new File(filePath);
if (directory.exists()) {
return directory.lastModified();
}
}
return System.currentTimeMillis();
}
}
|
Python
|
UTF-8
| 41,974 | 3.703125 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|

<a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/IntervalsAndInequalities/intervals-and-inequalities.ipynb&depth=1" target="_parent"><img src="https://raw.githubusercontent.com/callysto/curriculum-notebooks/master/open-in-callysto-button.svg?sanitize=true" width="123" height="24" alt="Open in Callysto"/></a>
%%html
<script>
function code_toggle() {
if (code_shown){
$('div.input').hide('500');
$('#toggleButton').val('Show Code')
} else {
$('div.input').show('500');
$('#toggleButton').val('Hide Code')
}
code_shown = !code_shown
}
$( document ).ready(function(){
code_shown=false;
$('div.input').hide()
});
</script>
<p> Code is hidden for ease of viewing. Click the Show/Hide button to see. </>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>')
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, Math, Latex, Markdown, HTML, clear_output, Javascript
import matplotlib as mpl
import ipywidgets as widgets
from ipywidgets import interact, interactive, Layout, Label,interact_manual,Text, HBox
from ipywidgets import IntSlider as slid
import time
import matplotlib.image as mpimg
from ipywidgets import IntSlider
# Intervals and inequalities
In this notebook, we will review some basics about polynomial functions such as
- the general form of a polynomial
- what terms make up a polynomial
- what defines the degree or order of a polynomial
We will then examine solving inequalities involving polynomials of degree 3 or less, both analytically and graphically, and briefly look over how to display the solutions on a number line, and how to represent solutions in interval notation.
Finally, we will visualize how changing certain parameters of polynomials can change the shape of its graph, which results in a different interval, satisfying a given inequality.
At the end of this notebook, there will be a small section covering some basics of `python` syntax and coding. This optional section will show the user how to create simple plots of polynomials in `python`, which can be used to help solve some of the extra problems.
## Polynomials
A polynomial is a function comprised of constants and variables. The constants and variables can be related to each other by addition, multiplication and exponentiation to a non-negative integer power ( https://en.wikipedia.org/wiki/Polynomial ). In this notebook, we will let $P(x)$ denote a general polynomial, and we will only deal with polynomials of a single variable $x$.
In general, a polynomial is expressed as:
$P(x) = c_0 \, + \,c_1x \, + ... +\, c_{n-2}x^{n-2} + c_{n-1}x^{n-1} + c_nx^n = \sum^n_{k=0}c_kx^k$
where $c_k$ are *constant terms*, $x$ is the variable. The largest value of $n$ ( i.e. the largest exponent of the polynomial) determines the *degree* of the polynomial. For example, some polynomials of degree *three* ($n=3$) could be:</br>
$P(x) = x^3 + 2x^2 + 5x + 4$
$P(x) = 3x^3 + 8x $
$P(x) = x^3 + x^2 + 4$
Note how the number of terms **does not** affect the degree of the polynomial, only the value of the largest exponent does.
A polynomial with degree 0 is called a *constant polynomial*, or just a *constant*. This is because of the mathematical identity
$x^0 = 1$,
so if we have any polynomail of degree 0, we have
$P(x) = c_1x^0 + c_2 = c_1 + c_2 = C$,
which of course is just a constant (i.e. some number, $C$).
While we will only be dealing with singe variable polynomials, it is worth noting that they can exist with *multiple variables*, i.e.
$P(x,y,z) = x^3 - xy^2 + z^6 -3x^2y^6z^4 +2$
#display(Latex('...')) will print the string in the output cell, in a nice font, and allows for easily inputing Math symbos and equations
display(Latex('From the list of functions below, check which ones are polynomials:'))
#define a series of checkboxes to test knowledge of polynomial forms
style = {'description_width': 'initial'}
a=widgets.Checkbox(
# description= '$\ x^2+5x-8x^3$',
description= r'$x^2$'+r'$+5x$'+r'$-8x^3$',
value=False, #a false value means unchecked, while a checked value will be "True'"
style = style
)
b=widgets.Checkbox(
value=False,
description=r'$x$'+r'$+3$',
# description=r'$\ x+3$',
style = style
)
c=widgets.Checkbox(
value=False,
# description=r'$\ \sin(x) + \cos(x)$',
description=r'$\sin$'+'('+r'$x$'+')'+r'$+\cos$'+'('+r'$x$'+')',
style = style
)
d=widgets.Checkbox(
value=False,
# description=r'$\ x^5-2$',
description=r'$x^5$'+r'$-2$',
disabled=False,
style = style
)
e=widgets.Checkbox(
value=False,
# description=r'$\ \ln(x)$',
description=r'$\ln$'+r'$(x)$',
disabled=False,
style = style
)
f=widgets.Checkbox(
value=False,
# description= r'$\ 100$',
description= r'$100$',
disabled=False,
style = style
)
#to actually display the buttons, we need to use the IPython.display package, and call each button as the argument
display(a,b,c,d,e,f)
#warning
text_warning = widgets.HTML()
#create a button widget to check answers, again calling the button to display
button_check = widgets.Button(description="Check Answer")
display(button_check)
#a simple funciton to determine if user inputs are correct
def check_button(x):
if a.value==True and b.value==True and c.value==False and d.value==True and e.value==False and f.value==True: #notebook will display 'correct' message IF (and only if) each of the boxes satisfy these value conditions
text_warning.value="Correct - these are all polynomials! Let's move on to the next cell."
else: #if any of the checkboxes have the incorrect value, output will ask user to try again
text_warning.value="Not quite - either some of your selections aren't polynomials, or some of the options that you didn't select are. Check your answers again!"
button_check.on_click(check_button)
display(text_warning)
## Intervals of Inequalities
### Interval Notation
Interval notation is a way of representing an interval of numbers by the two endpoints of the interval. Parentheses ( ) and brackets [ ] are used to represent whether the end points are included in the interval or not.
For example, consider the interval between $-3$ and $4$, including $-3$, but **not** including $4$, i.e. $-3 \leq x < 4$. We can represent this on a number line as follows:

In **interval notation**, we would simply write: $[-3,4)$
If, however, the interval extended from $-3$ to **all** real numbers larger than $-3$, i.e. $-3 \leq x$, the number line would look like this:

and our interval notation representation would be: $[-3, \infty)$, where $\infty$ (infinity) essentially means all possible numbers beyond this point.
Sometimes it is also necessary to include multiple intervals. Consider an inequality in which the solution is $-3\leq x <0$ and $4 \leq x$. We can represent this solution in interval notation with the **union** symbol, which is just a capital U, and means that both intervals satisfy the inequality: $[-3,0)$ U $[4,\infty)$
### Solving Inequalities
Given a polynomial $P(x)$, we can determine the range in which that polynomial satisfies a certain inequality. For example, consider the polynomial function
$P(x) = x^2 + 4x$.
For which values of $x$ is the ploynomial $P(x)$ less than three? Or, in a mathematical representations, on which interval is the inequality $P(x) \leq -3$ satisfied?
We can solve this algebraically, as follows:
1. Write the polynomial in standard form: $x^2 + 4x + 3 \leq 0 $
2. Factor the polynomial: $(x+1)(x+3) \leq 0$
What this new expression is essential telling us is that the product of two numbers (say $a=(x+1)$ and $b=(x+3)$) is equal to zero, or negative, i.e. $a\cdot b\leq 0 $. The only way this is possible is if $a=0$, $b=0$, or $a$ and $b$ have **opposite** signs. So the inequality $P(x) \leq -3$ is satisfied if:
- $(x+1) = 0$
- $(x+3) = 0$
- $(x+1)>0$ and $(x+3)<0$
- $(x+1)<0$ and $(x+3)>0$
From these possibilities, we can see the possible solutions are:
- $x=-1$
- $x=-3$
- $x>-1$ and $x<-3$
- $x<-1$ and $x>-3$
If we consider the solution $x>-1$ and $x<-3$, what are the possible values of $x$? If we say $x=1$ we satisfy the first inequality, but not the second, since $1$ is **not** less than $-3$. We can see that there is no possible $x$ value that will result in $(x+1)>0$ and $(x+3)<0$, so we can eliminate this as a possible solution.
However, we can find values of $x$ that satisfy $x<-1$ and $x>-3$. For example, $x=-2$
Thus, the solution to the inequality is $x=-1$, $x=-3$, and $x<-1$ and $x>-3$. We can plot this solution set on a number line:

or in *interval notation*, the solution is : **[-3,-1]**
## Let's work through an example together
std_form1 = "-4x^2+8x+96<=0"
display(Latex('1.Consider the inequality $(-x)(4x - 8) \leq -96$.'))
display(Latex(' Re-write the inequality in standard form (use the symbol ^ to indicate an exponent and <= for the inequality sign).'))
inpt1 = widgets.Text(placeholder='Enter inequality')
text_warning1 = widgets.HTML()
button_check1 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt1,button_check1]))
def check_button1(x):
inpt1.value = inpt1.value.replace(" ","")
if inpt1.value==std_form1 :
text_warning1.value="Very good!"
else:
text_warning1.value="Not quite - please try again!"
button_check1.on_click(check_button1)
display(text_warning1)
std_form2 = "x^2-2x-24>=0"
display(Latex('2.Consider the inequality we obtained in the first step.'))#: $-4x^2+8x+96\leq0$'))
display(Latex('We can simplify this further by reducing the leading coefficient to 1.'))
display(Latex('This can be done by simply dividing both sides by $-4$. If we do this, what does our expression become?'))
inpt2 = widgets.Text(placeholder='Enter inequality')
text_warning2 = widgets.HTML()
button_check2 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt2,button_check2]))
def check_button2(x):
inpt2.value = inpt2.value.replace(" ","")
if inpt2.value==std_form2 :
text_warning2.value="Very good!"
else:
text_warning2.value="Almost! It's important to remember that if we divide or multiply an inequality by a negative number, we flip the inequality sign."
button_check2.on_click(check_button2)
display(text_warning2)
std_form3_1 = '(x-6)(x+4)>=0'
std_form3_2 = '(x+4)(x-6)>=0'
display(Latex('3.The next step is to factor our simplified polynomial expression.')) #: $x^2 - 2x - 24 \geq 0$.'))
display(Latex('Input the factored expression below:'))
inpt3 = widgets.Text(placeholder='Enter inequality')
text_warning3 = widgets.HTML()
button_check3 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt3,button_check3]))
def check_button3(x):
inpt3.value = inpt3.value.replace(" ","")
if inpt3.value==std_form3_1 or inpt3.value==std_form3_2:
text_warning3.value="Correct!"
else:
text_warning3.value="Not quite - please try again!"
button_check3.on_click(check_button3)
display(text_warning3)
display(Latex('Since we have $(x-6)(x+4)\geq 0$, there are the two sign possibilities; either'))
display(Latex('$1. ~ (x-6)\geq 0$ and $(x+4)\geq 0$'))
display(Latex('or'))
display(Latex('$2. ~ (x-6)\leq 0$ and $(x+4)\leq 0$'))
std_form4 = 'x>=6'
display(Latex('4. Consider expression $1.$'))
display(Latex(' Can you see what solution satisfies both $(x-6)\geq 0$ and $(x+4)\geq 0$? Enter your answer below in the form "x>= _"'))
inpt4 = widgets.Text(placeholder='Enter interval')
text_warning4 = widgets.HTML()
button_check4 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt4,button_check4]))
def check_button4(x):
inpt4.value = inpt4.value.replace(" ","")
if inpt4.value==std_form4 :
text_warning4.value="Very good! Since we are looking for values of x that are larger than 6 and -4, and 6>-4, the first expresssion gives us one simple solution interval: x>=6"
else:
text_warning4.value="Not quite - please try again!"
button_check4.on_click(check_button4)
display(text_warning4)
std_form5 = 'x<=-4'
display(Latex('5.Now consider expression $2$ What is the interval satsfying these inequalities?'))
inpt5 = widgets.Text(placeholder='Enter interval')
text_warning5 = widgets.HTML()
button_check5 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt5,button_check5]))
def check_button5(x):
inpt5.value = inpt5.value.replace(" ","")
if inpt5.value==std_form5 :
text_warning5.value="Very good! Since we are looking for values of x that are less than -4 and 6 and 6>-4, this expresssion also gives us one simple solution interval: x<=-4"
else:
text_warning5.value="Not quite - please try again!"
button_check5.on_click(check_button5)
display(text_warning5)
std_form6 = '(-inf,-4]U[6,inf)'
display(Latex('6. So, what is our final solution interval for the inequality $(-x)(4x - 8) \leq -96$?'))
display(Latex("Enter your answer in interval notation, using the following notations if necessary: 'U' for union symbol and 'inf' for infinity"))
inpt6 = widgets.Text(placeholder='Enter interval')
text_warning6 = widgets.HTML()
button_check6 = widgets.Button(description="Check Answer")
display(widgets.HBox([inpt6,button_check6]))
def check_button6(x):
inpt6.value = inpt6.value.replace(" ","")
if inpt6.value==std_form6 :
text_warning6.value="Excellent! Now let's see how the solution looks like on the number line"
else:
text_warning6.value="Not quite - please try again!"
button_check6.on_click(check_button6)
display(text_warning6)
button7 = widgets.Button(description="Display solution on a number line",layout=Layout(width='40%', height='50px'))
display(button7)
def display_button7(x):
img = mpimg.imread('images/ex_soln.png')
fig, ax = plt.subplots(figsize=(18, 3))
imgplot = ax.imshow(img, aspect='auto')
ax.axis('off')
plt.show()
button7.disabled=True
button7.on_click(display_button7)
## Graphical visualization of inequality solutions
%matplotlib inline
display(Latex('Click on the button below to graph the polynomial $P(x) = x^2 + 4x$'))
button_graph = widgets.Button(description="Graph the ploynomial")
display(button_graph)
def display_graph(t):
x = np.linspace(-10,10,1000); #define a vector space for the variable x
plt.figure(3,figsize=(11,8)) #define the figure window size
plt.plot(x,x**2 + 4*x, linewidth=2, label=r'$P(x) = x^2 + 4x$'); #plot the polynomial as a function of x
plt.ylabel('P(x)', fontsize=20) #label the axes
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7) #place a grid on the figure for readability; alpha defines the opacity
plt.xticks(np.arange(-10,11)) #define the xticks for easier reading
plt.ylim([-20,40]) #adjust the limits of the y and x axes of the figure for readability
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1) #plot solid lines along origin for easier reading
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.legend(loc='best', fontsize = 18) #add a legend
button_graph.disabled=True
button_graph.on_click(display_graph)
display(Latex("Let's try to solve where this polynomial is $\leq -3$, or $x^2 + 4x \leq -3$."))
display(Latex("Let's draw a line at $y=-3$ to help visualize this."))
button_draw = widgets.Button(description="Draw a line")
display(button_draw)
def draw_line(t):
x = np.linspace(-10,10,1000); #define a vector space for the variable x
plt.figure(3,figsize=(11,8)) #define the figure window size
plt.plot(x,x**2 + 4*x, linewidth=2, label=r'$P(x) = x^2 + 4x$'); #plot the polynomial as a function of x
plt.ylabel('P(x)', fontsize=20) #label the axes
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7) #place a grid on the figure for readability; alpha defines the opacity
plt.xticks(np.arange(-10,11)) #define the xticks for easier reading
plt.ylim([-20,40]) #adjust the limits of the y and x axes of the figure for readability
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1) #plot solid lines along origin for easier reading
plt.plot(x,np.ones(len(x))*-3, linewidth=2, label = r'$y = -3$'); #plot the y=0 line
plt.legend(loc='best', fontsize = 18) #add a legend
button_draw.disabled=True
button_draw.on_click(draw_line)
display(Latex('Can you see where the inequality is satisfied?'))
display(Latex('Click the button to shade the area where the inequality is satisfied'))
button_shade = widgets.Button(description="Shade")
display(button_shade)
def shade(t):
x = np.linspace(-10,10,1000); #define a vector space for the variable x
plt.figure(3,figsize=(11,8)) #define the figure window size
plt.plot(x,x**2 + 4*x, linewidth=2, label=r'$P(x) = x^2 + 4x$'); #plot the polynomial as a function of x
plt.ylabel('P(x)', fontsize=20) #label the axes
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7) #place a grid on the figure for readability; alpha defines the opacity
plt.xticks(np.arange(-10,11)) #define the xticks for easier reading
plt.ylim([-20,40]) #adjust the limits of the y and x axes of the figure for readability
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1) #plot solid lines along origin for easier reading
plt.plot(x,np.ones(len(x))*-3, linewidth=2, label = r'$y = -3$'); #plot the y=0 line
plt.legend(loc='best', fontsize = 18) #add a legend
plt.axvspan(-3,-1,facecolor='#2ca02c', alpha=0.5)
display(Latex("We can see that the interval for which $P(x) \leq -3$ is again [-3,-1], agreeing with our algebraic solution."))
button_shade.disabled=True
button_shade.on_click(shade)
## Changing Parameters
### Constant term
The **constant term** of a polynomial is the term in which the variable does not appear (i.e. the degree $0$ term). For example, the constant term for the polynomial
$P(x) = x^3 + 2x^2 + 5x + 4$,</br>
is $4$.
Let's look at how changing the constant term changes the graph of the polynomial. We will consider the same polynomial as before, but this time we will let $k$ be an arbitrary value for the constant term.
display(Latex('Adjust the value of $k$ using the slider. What do you notice about the graph as the value changes?'))
x = np.linspace(-10,10, 1000)
#define function to create a graph of a polynomial
def Plot_poly(k=0): #we make the python function a function of the variable 'k', which we will use as the constant term in the polynomial
plt.figure(figsize=(11,8))
plt.plot(x,x**3 + 2*x**2 + 5*x + k, linewidth = 2) #here is the variable k
plt.title(r'Graph of $P(x) = x^3 + 2x^2 + 5x + k$', fontsize = 20)
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.show()
#interact(Plot_poly,k=(-10,10)); #use the IPython interact function to create a slider to adjust the value of 'k' for the plot
interact(Plot_poly, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
#interact_manual(Plot_poly,k=widgets.IntSlider(min=-10,max=10,step=1,value=0))
display(Latex('Try doing the same with other polynomials. Is there a similar, or different behaviour?'))
display(Markdown('**Order 1 Polynomials:**'))
display(Latex('Provide a value for $a$ in the polynomial $P(x) = ax + k$:'))
inpt_a = widgets.Text(placeholder='Enter a')
text_warning_a = widgets.HTML()
button_check_a = widgets.Button(description="Graph")
display(widgets.HBox([inpt_a,button_check_a]))
button_check_a.disabled=False
inpt_a.disabled=False
def check_button_a(b):
inpt_a.value = inpt_a.value.replace(" ","")
if inpt_a.value.isdigit():
text_warning_a.value=""
button_check_a.disabled=True
inpt_a.disabled=True
x = np.linspace(-10,10,1000)
custom_poly = int(inpt_a.value)* x
def plot_poly1(k=0):
plt.figure(figsize=(11,8))
plt.plot(x,custom_poly + k, linewidth=2) #plot the polynomial with the constant term k
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.title('Graph of polynomial $P(x) ='+str(inpt_a.value) + 'x+ k$', fontsize=20)
plt.show()
#interact(plot_poly1,k=(-10,10));
interact(plot_poly1, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
else:
text_warning_a.value="Please enter numeric value"
button_check_a.on_click(check_button_a)
display(text_warning_a)
display(Markdown('**Order 2 Polynomials:**'))
display(Latex('Provide values for $a$ and $b$ in the polynomial $P(x) = ax^2 +bx + k$ using format a,b:'))
inpt_ab = widgets.Text(placeholder='Enter a,b')
text_warning_ab = widgets.HTML()
button_check_ab = widgets.Button(description="Graph")
display(widgets.HBox([inpt_ab,button_check_ab]))
button_check_ab.disabled=False
inpt_ab.disabled=False
def check_button_ab(b):
inpt_ab.value = inpt_ab.value.replace(" ","")
list_ab = inpt_ab.value.split(',')
if not len(list_ab)==2:
text_warning_ab.value="Please enter two numbers in format a,b"
else:
if list_ab[0].isdigit() and list_ab[1].isdigit():
text_warning_ab.value=""
button_check_ab.disabled=True
inpt_ab.disabled=True
x = np.linspace(-10,10,1000)
custom_poly = int(list_ab[0]) * x**2 + int(list_ab[1])*x
def plot_poly2(k=0):
plt.figure(figsize=(11,8))
plt.plot(x,custom_poly + k, linewidth=2) #plot the polynomial with the constant term k
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.title('Graph of polynomial $P(x) ='+str(list_ab[0]) + 'x^2 +' + str(list_ab[1]) + 'x + k$', fontsize=20)
plt.show()
#interact(plot_poly2,k=(-10,10))
interact(plot_poly2, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
else:
text_warning_ab.value="Please enter numeric values"
button_check_ab.on_click(check_button_ab)
display(text_warning_ab)
display(Markdown('**Order 3 Polynomials:**'))
display(Latex('Provide values for $a$, $b$, and $c$ in the polynomial $P(x) = ax^3 +bx^2 + cx + k$ using format a,b,c:'))
inpt_abc = widgets.Text(placeholder='Enter a,b,c')
text_warning_abc = widgets.HTML()
button_check_abc = widgets.Button(description="Graph")
display(widgets.HBox([inpt_abc,button_check_abc]))
button_check_abc.disabled=False
inpt_abc.disabled=False
def check_button_abc(b):
inpt_abc.value = inpt_abc.value.replace(" ","")
list_abc = inpt_abc.value.split(',')
if not len(list_abc)==3:
text_warning_abc.value="Please enter three numbers in format a,b,c"
else:
if list_abc[0].isdigit() and list_abc[1].isdigit() and list_abc[2].isdigit():
text_warning_abc.value=""
button_check_abc.disabled=True
inpt_abc.disabled=True
x = np.linspace(-10,10,1000)
custom_poly = int(list_abc[0]) * x**3 + int(list_abc[1])*x**2 + int(list_abc[2])*x
def plot_poly3(k=0):
plt.figure(figsize=(11,8))
plt.plot(x,custom_poly + k, linewidth=2) #plot the polynomial with the constant term k
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,40])
plt.xlim([-9,9])
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.title('Graph of polynomial $P(x) ='+str(list_abc[0]) + 'x^3 +' + str(list_abc[1]) + 'x^2+'+ str(list_abc[2]) + 'x+ k$', fontsize=20)
plt.show()
#interact(plot_poly3,k=(-10,10));
interact(plot_poly3, k=slid(min=-10,max=10,step=1,value=0,continuous_update=False))
else:
text_warning_abc.value="Please enter numeric values"
button_check_abc.on_click(check_button_abc)
display(text_warning_abc)
In the next exercise, we will quantify how the constant term can change the interval satisfying an inequality.
**Note**: Please press the enter key after typing in a value for the intercepts.
display(Latex("Where are the x intercepts for the polynomial $x^2-4x+3$?"))
#widgets for interactive cell input
guess1_in= widgets.Text(disabled = False, description = r'$x_1$')
guess2_in = widgets.Text(disabled = False, description = r'$x_2$')
check = widgets.Button(description = 'Check Answer')
change_c = widgets.Button(description = 'Change Constant')
text_warning_check = widgets.HTML()
display(guess1_in)
display(guess2_in)
display(check)
def check_answr(b):
int_1 = str(1)
int_2 = str(3)
if (guess1_in.value == int_1 and guess2_in.value == int_2) or (guess1_in.value == int_2 and guess2_in.value == int_1):
text_warning_check.value='Correct!'
check.disabled=True
guess1_in.disabled=True
guess2_in.disabled=True
plt.figure(1,figsize=(11,8))
plt.plot(x,x**2 - 4*x + 3, linewidth=2, label=r'$P(x) = x^2 -4x+3$');
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.plot(3,0,'ro',markersize=10)
plt.plot(1,0,'ro',markersize=10)
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,20])
plt.xlim([-9,9])
plt.legend(loc='best', fontsize = 18)
plt.show()
display(Latex('Based on the previous cell, what do you think will happen if we change the constant term from $3$ to $-3$? Press the button to find out if you are correct.'))
display(change_c)
else:
text_warning_check.value='Try Again!'
return
check.on_click(check_answr)
def change_const(b):
change_c.disabled=True
plt.figure(1,figsize=(11,8))
plt.plot(x,x**2 - 4*x - 3, linewidth=2, label=r'$P(x) = x^2 -4x-3$');
plt.plot([-75,75],[0,0],'k-',alpha = 1,linewidth = 1)
plt.plot([0,0],[-75,75],'k-',alpha = 1,linewidth = 1)
plt.plot(2-np.sqrt(7),0,'yo',markersize=10)
plt.plot(2+np.sqrt(7),0,'yo', markersize=10)
plt.ylabel('P(x)', fontsize=20)
plt.xlabel('x', fontsize=20)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-20,20])
plt.xlim([-9,9])
plt.legend(loc='best', fontsize = 18)
plt.show()
display(Latex('As we can see, changing the constant term shifts the graph of a polynomial up or down. This results in different x-intercepts, and therefore a different interval. '))
change_c.on_click(change_const)
display(text_warning_check)
Another way to think about this is that changing the constant term is the same as solving for a different interval of inequality. Take, for example the polynomials we just used above.
We know that
$x^2-4x+3 \leq 0$
is **not** the same as
$x^2-4x-3\leq 0$.
However, consider a new inequality:
$x^2 - 4x - 3 \leq -6$.
If we simplify this expression, we find
$x^2 - 4x +3 \leq 0$
which is indeed equivalent to the first polynomial (plotted in blue in the cell above).
## Extra Problems
### Practice solving graphically
First, we will practice how to solve inequalities graphically. Below is a plot of the polynomial $P(x) = x^3 - x^2 - 22x + 40$. Using the graph, find the values of the three x intercepts. Based on this, determine the interval where $P(x) \leq 0 $.
This can method can be used to solve almost any polynomial inequality, provided that the x-intercepts are rational numbers which can be easily read off of the axes of the graph.
text_check_intvl = widgets.HTML()
intvl_1=widgets.Checkbox(
value=False,
description=r'$[$'+r'$-5$'+r'$,4$'+r'$]$',
disabled=False
)
intvl_2=widgets.Checkbox(
value=False,
description='['+'$-5$'+'$,3$'+']'+'$U$'+'['+r'$4,$'+r'$\infty$'+r')',
disabled=False
)
intvl_3=widgets.Checkbox(
value=False,
description=r'$[$'+r'$-5$'+r'$,2$'+r'$]$',
disabled=False
)
intvl_4=widgets.Checkbox(
value=False,
description=r'$($'+r'$-\infty$'+r'$,$'+r'$-5$'+'$]$'+'$U$'+ r'$[$' + r'$2$'+'$,$'+'$4$'+'$]$',
#description=r'$(-\infty,-5] \rm U [2,4]$',
disabled=False
)
def check_button2(x):
if intvl_2.value == False and intvl_1.value==False and intvl_3.value==False and intvl_4.value==True:
text_check_intvl.value='Correct!'
else:
text_check_intvl.value="Not quite - Check your answer again!"
button_check2 = widgets.Button(description="Check Answer")
button_check2.on_click(check_button2)
def slider(x1,x2,x3):
xx = np.linspace(-10,10,300)
p1 = plt.figure(1,figsize = (11,8))
hold = True
plt.plot(xx,xx**3 - 1*xx**2 - 22*xx + 40, linewidth = 2, label = r'$P(x) = x^3 - x^2 - 22x + 40$')
plt.axhline(y=0, color = 'k', linewidth=1)
plt.axvline(x=0, color = 'k', linewidth=1)
plt.plot(x1,0,'ro',markersize=10)
plt.plot(x2,0,'mo',markersize=10)
plt.plot(x3,0,'go',markersize=10)
if sorted([x1,x2,x3]) == sorted([-5,2,4]):
plt.text(-7,20,'VERY GOOD!', fontsize = 25, fontweight = 'bold',color = 'r')
plt.fill_between(xx,xx**3 - 1*xx**2 - 22*xx + 40,np.zeros(len(xx)), where=xx**3 - 1*xx**2 - 22*xx + 40<0, interpolate = True, alpha=0.5, color='g' )
display(Latex('What interval then satisfies $P(x) \leq 0$?'))
display(intvl_1)
display(intvl_2)
display(intvl_3)
display(intvl_4)
display(button_check2)
display(text_check_intvl)
plt.xlabel('$x$',fontsize = 14)
plt.ylabel('$y$',fontsize = 14)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-75,75])
plt.xlim([-9,9])
plt.legend(loc = 'best', fontsize = 18)
plt.show()
interact(slider, x1=slid(min = -10,max = 10,step = 1,continuous_update = False), x2=slid(min = -10,max = 10,step = 1,continuous_update = False), x3=slid(min = -10,max = 10,step = 1,continuous_update = False))
### Solve the inequalities
In the next two cells, we have a function that will generate a random polynomial of degree 2 and 3. Using the analytic steps shown above, try to solve the intervals of inequalities for a few polynomials. Since we can always rearrange the polynomial into standard form, without loss of generality we can always take the inequality to be $\leq 0 $ or $\geq 0 $. Re-run this function as many times as you would like, until you are comfortable with solving polynomial inequalities.
If you have trouble solving the inequality analytically, you can try to find the solution graphically, following the method in the cell above. At the bottom of this notebook, there will be some instructions on how to make basic plots with Python. Follow these steps and try to solve the inequality.
**Note**: you will need to scroll to the top of the notebook and press the '**show code**' button to be able to write your own code in a cell.
def find_interval2():
C = np.random.randint(-5,5,2)
C1 = -1*np.sum(C)
C2 = C[0]*C[1]
if C1>0:
str1 = '+' + str(C1) + 'x'
elif C1== 0:
str1 = ''
else:
str1= str(C1) + 'x'
if C2>0:
str2 = '+' + str(C2)
elif C2== 0:
str2=''
else:
str2= str(C2)
a = 'P(x) = x^2 ' + str1 + str2
def poly(x):
return x**2 + C1*x + C2
Max = max(C)
Min = min(C)
M = [Min, Max]
V = np.sort(C)
eps = 0.1
if Max == Min and poly(Max+eps)>0:
interval = '(-inf,'+str(Min)+')U('+str(Min)+',inf)' #one root, convex
elif poly(Max+eps)<0:
interval = '('+str(Min)+','+str(Max)+')' #Two distinct roots, Concave
elif poly(Max + eps)>0:
interval = '(-inf,'+str(Min)+')U(' + str(Max)+',inf)' #Two distinct roots, convex
else:
interval = 'Nowhere' #one root, concave
x = np.linspace(-100,100,10000)
p = poly(x)
y = poly(x)
return interval,y,a
def find_interval3():
C = np.random.randint(-5,5,3)
C1 = -1*np.sum(C)
C2 = C[0]*C[1] + C[2]*(C[0]+C[1])
C3 = -1*C[0]*C[1]*C[2]
if C1>0:
str1 = '+' + str(C1) + 'x^2'
elif C1== 0:
str1 = ''
else:
str1= str(C1) + 'x^2'
if C2>0:
str2 = '+' + str(C2) + 'x'
elif C2== 0:
str2=''
else:
str2= str(C2) + 'x'
if C3>0:
str3 = '+' + str(C3)
elif C3== 0:
str3=''
else:
str3= str(C3)
a = "P(x)= x^3" + str1 + str2 + str3
def poly(x):
return x**3 + C1*x**2 + C2*x + C3
Max = max(C)
Min = min(C)
M = [Min, Max]
V = np.sort(C)
eps = 0.1
v = V[1]
if Max == Min and poly(Max +eps) > 0:
interval = '('+str(Max)+',inf)' #One single root, increasing
if Max == Min and poly(Max +eps) < 0:
interval = '(-inf,' + str( Max)+')' #One single root, decreasing
if poly(Max + eps) >0:
if v != Max and v!= Min:
interval = '('+str(Min) + ',' + str(v) + ')U(' + str(Max) + ',inf)'
if v == Max:
interval = '(' + str(Min) + ',inf)'
if v== Min:
interval = '(' + str(Max) + ',inf)'
if poly(Max + eps) <0:
if v != Max and v != Min:
interval = '(-inf,' + str(Min) + 'U('+str(v) + ','+str(Max) + ')'
if v == Max:
interval = '(-inf,' + str( Max) + ')'
if v == Min:
interval = '(-inf,' + str(Min) + ')'
x = np.linspace(-100,100,10000)
y = poly(x)
return interval, y,a
def check_answer(answer,interval,y,a,hwidget):
if answer == interval:
hwidget.value="Correct! Here's a visualization of the solution:"
x=np.linspace(-100,100,10000)
plt.figure(figsize=(11,8))
plt.plot(x,y, linewidth = 2, label = '$' + str(a) + '$')
plt.xlabel('$x$',fontsize = 14)
plt.ylabel('$y$',fontsize = 14)
plt.axhline(y=0, color = 'k', linewidth=1)
plt.axvline(x=0, color = 'k', linewidth=1)
plt.grid(alpha = 0.7)
plt.xticks(np.arange(-10,11))
plt.ylim([-75,75])
plt.xlim([-9,9])
plt.legend(loc = 'best', fontsize = 18)
plt.fill_between(x,y,0, where=y>0, interpolate=True, alpha = 0.5, color='g')
return True
elif answer != interval:
hwidget.value="That's not quite right, try again."
return False
interval2,y_values2,polynom_string2=find_interval2()
display(Markdown('**Order 2 Polynomials:**'))
display(Latex("Find the interval where $P(x) > 0$ , using 'inf' for infinity and 'U' for union:"))
display(Math(polynom_string2))
text_poly2 = widgets.Text(placeholder='Enter Interval')
display(text_poly2)
gen_button2 = widgets.Button(description="Re-generate polynomial", layout = Layout(width='30%', height='40px'))
check_button2 = widgets.Button(description="Check your answer", layout = Layout(width='30%', height='40px'),visible=False)
display(widgets.HBox([check_button2,gen_button2]))
text_check_ans2 = widgets.HTML()
display(text_check_ans2)
def generate_polynomial2(b):
display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index(), IPython.notebook.get_selected_index()+1)'))
gen_button2.on_click(generate_polynomial2)
def check_answer2(b):
text_poly2.value = text_poly2.value.replace(" ","")
result=check_answer(text_poly2.value,interval2,y_values2,polynom_string2,text_check_ans2)
if result:
check_button2.disabled=True
check_button2.on_click(check_answer2)
interval3,y_values3,polynom_string3=find_interval3()
display(Markdown('**Order 3 Polynomials:**'))
display(Latex("Find the interval where $P(x) > 0$ , using 'inf' for infinity and 'U' for union:"))
display(Math(polynom_string3))
text_poly3 = widgets.Text(placeholder='Enter Interval')
display(text_poly3)
gen_button3 = widgets.Button(description="Re-generate polynomial", layout = Layout(width='30%', height='40px'))
check_button3 = widgets.Button(description="Check your answer", layout = Layout(width='30%', height='40px'),visible=False)
display(widgets.HBox([check_button3,gen_button3]))
text_check_ans3 = widgets.HTML()
display(text_check_ans3)
def generate_polynomial3(b):
display(Javascript('IPython.notebook.execute_cell_range(IPython.notebook.get_selected_index(), IPython.notebook.get_selected_index()+1)'))
gen_button3.on_click(generate_polynomial3)
def check_answer3(b):
text_poly3.value = text_poly3.value.replace(" ","")
result=check_answer(text_poly3.value,interval3,y_values3,polynom_string3,text_check_ans3)
if result:
check_button3.disabled=True
check_button3.on_click(check_answer3)
## Plotting in Python
To create a simple plot of a polynomial, we can run the following code:
First, we have to import the necessary libraries to create the plot. We can call the matplotlib library in the code by using the 'plt.' prefix.
We will use the Python `matplotlib` library to plot the polynomials.
The` numpy` library is used to create an object called a 'vector' -- we use this to plot the polynomial over some range of x:
```python
import matplotlib.pyplot as plt
import numpy as np
```
From the `numpy` library, we call the 'linspace' function, which creates a list of linearly spaced numbers. The numbers in the brackets are the starting number, the final number, and the number of points between the two. In this case, we create a list of 1000 numbers equally spaced between `-10` and `10`. We will define this list as the variable `x` by typing `x=` before we call the `numpy` function:
```python
x = np.linspace(-10,10,1000)
```
Now we can use `matplotlib` functions to create the graph. Calling the `figure()` function creates a figure box to make the graph. We can enter arguments in the brackets to specify the size of the figure window to make it easier to read. To actually draw the graph, we call `plot(x,y)`, draws the graph of y as a function of x.
```python
plt.figure(figsize=(11,8))
plt.plot(x,y)
```
When you write the code for yourself, instead of typing 'y' in the brackets, write out the actual polynomial you wish to plot. For example, if we wanted to plot $y = x^2 + 2x - 3$, our code may look like:
```python
plt.figure(figsize=(11,8))
plt.plot(x,x**2 + 2*x - 3)
```
Notice the *syntax* of the polynomial. Double asterisks `**` are used to exponentiate variables (i.e. $x^2$ = `x**2`), while a single asterisk `*` means multiplication in Python. Addition and subtraction are the usual `+` and `-` symbols.
We can make the intercepts easier to read by placing a grid on the figure with
```python
plt.grid(alpha=0.7)
```
and making the origin lines solid by using
```python
plt.axhline(y=0, color = 'k', linewidth=1)
plt.axvline(x=0, color = 'k', linewidth=1)
```
In the cell below, write out this code block, entering the polynomial you wish to solve as 'y'.
## Conclusion
In this notebook, we reviewed some basics of polynomial functions:
- what is the general form of a polynomial
- what are some examples of polynomials
- what defines the order (or degree) of a polynomial
- what is the constant term of a polynomial, and what is it's role on the graph of a polynomial
We explored who to solve inequalities involving polynomials analytically, and demonstrated how we can search for solutions graphically as well.
You should also be familiar with some basic Python syntax and plotting routines to create simple plots of polynomial functions with the `matplotlib` library.
[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)
|
JavaScript
|
UTF-8
| 2,679 | 3.859375 | 4 |
[] |
no_license
|
/*
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
*/
function generatePotentials (beginWord, dict) {
const result = [];
const chars = beginWord.split('');
for (let i = 0 ; i < beginWord.length; i++) {
const char = chars[i];
for (let j = 0; j < 26; j++) {
const tempChar = String.fromCharCode(97 + j);
if (tempChar === char) {
continue;
}
chars[i] = tempChar;
const newString = chars.join('');
if (dict.has(newString)) {
result.push(newString);
}
}
chars[i] = char;
}
return result;
}
var findLadders = function(beginWord, endWord, wordList) {
const dict = new Set(wordList);
let start = new Set();
dict.delete(beginWord);
start.add(beginWord);
const map = new Map();
const res = [];
while (start.size > 0) {
if (start.has(endWord)) {
break;
}
const set = new Set();
for (const w of start) {
const po = generatePotentials(w, dict);
if (po.length > 0) {
map.set(w, po);
for (const p of po) {
set.add(p);
}
}
}
for (const s of set) {
dict.delete(s);
}
start = set;
}
dfs(beginWord, endWord, map, res, [beginWord]);
return res;
};
function dfs (beginWord, endWord, map, res, temp) {
if (beginWord === endWord) {
res.push(temp.slice());
return;
}
if (map.has(beginWord)) {
for (const w of map.get(beginWord)) {
temp.push(w);
dfs(w, endWord, map, res, temp);
temp.pop();
}
}
}
|
JavaScript
|
UTF-8
| 1,144 | 3.609375 | 4 |
[] |
no_license
|
/**
* title: 解构赋值
* date: 2017/12/07
* author: Silvester
*/
// destructuring(解构赋值)
// 1.数组
// 匹配模式
{
let [a, b, c] = [1, 2, 3]
let [foo, [[bar], baz]] = [1, [[2], 3]]
let [, , third] = ['foo', 'bar', 'baz']
let [d, , e] = [1, 2, 3]
let [head, ...tail] = [1, 2, 3, 4, 5]
let [x, y, ...z] = ['a']
}
// 不完全解构
{
let [x, y] = [1, 2, 3]
let [a, [b], d] = [1, [2, 3], 4]
let [e, f, g] = new Set(['a', 'b', 'c'])
}
// 默认值
{
let [d = true] = []
}
// 2.对象
{
let { foo, bar } = { foo: 'aa', bar: 'bb' }
}
// 变量的解构赋值
// 1 数组的解构赋值
// 1.1 基本用法
// ES6允许按照一定模式,从数组和对象中提取值,对变量进行赋值
let a = 1
let b = 2
let c = 3
let [a, b, c] = [1, 2, 3]
let [foo, [[bar], baz]] = [, [[2], 3]]
let [, , third] = ['foo', 'bar', 'baz']
let [x, , y] = [1, 2, 3]
let [head, ...tail] = [1, 2, 3, 4]
let [i, j, ...k] = ['a']
// 2 对象的解构赋值
// 3 字符串的解构赋值
// 4 数值和布尔值的解构赋值
// 5 函数参数的解构赋值
// 6 圆括号问题
// 7 用途
|
Markdown
|
UTF-8
| 15,170 | 3.28125 | 3 |
[] |
no_license
|
# Local-Help-Centre
Assignment Instructions:
Assignment 2: A Help Centre Queueing System
Due: October 17, 2018 4 p.m.
Introduction
The Department of Computer Science has an undergraduate help centre where students can ask questions about their course work. Students swipe their T-cards to enter a software queue and wait their turn to see a TA. In this assignment, you will build an interactive system that could manage a similar help centre. Your program will not provide identical functionality to the current (or past) DCS help centre systems. You need to use this handout as the specification for your assignment (not the behaviour of the working system in DCS.)
Data structures
Most of your task is to complete the API for the data structures which are the basis for the help centre queue system. The header file hcq.h, provided in the starter code, defines the data structures you must use to build your program. Spend some time examining the code and this figure hcqfig.pdfPreview the document and make sure that you understand the structure you are trying to build before you begin to code. Ask questions at office hours or in the actual help centre or on Piazza.
The hcq data strutures include two linked structures (one for students and one for TAs) and one array (for courses.)
The array of courses has elements of type struct course and is created at the start of your program using initial values read from a configuration file. Each course struct has information about the course (not all of it shown in the figure) and pointers that reference the first and last students waiting in the queue for this course.
The TA list is a singly-linked list of struct ta elements kept in reverse order on arrival. The TA who arrived most-recently is at the head of the list. Each ta struct contains a pointer to the struct student representing the student who is currently being helped by this TA. These students are no longer in any queue. Notice that the middle TA in the list does not currently have a student.
The data structure of struct student objects that represents students waiting for help contains two linked-lists. Each student has a pointer to the next_overall student and the next_course student. Consider student s who asked a question about course c. At any point in time, s's next_overall pointer, points to the student remaining in the queue who arrived most recently after s. s's next_course pointer, points to the next student still in the queue who has a question about course c. Either of these pointers can be null if there is no student after s or no student after s from the same course.
One important thing to notice about a student, is the arrival_time field of the struct. For students currently waiting in the queue, this represents the time that they arrived in the queue to ask a question. For students who are being helped by a TA, this field should hold the time that the TA started to help the student. You will need these values in order to calculate the total amount of time students from a particular course spent waiting to be helped and also the total amount of time TAs spent helping students from a particular course. Your textbook has a nice discussion of how time is represented in C that will help you understand the type time_t.
The variables shown in the figure in orange are the statically-allocated pointers to these data structures. They are declared in the main function of helpcentre.c. Spend some time exploring the starter code, looking at the figure and rereading this description until you are certain that you understand the data structures you need to create and maintain.
Queue Operations
The program itself is divided into two main components: a basic hcq API that provides functions to manipulate the hcq data structures and a user-interface that parses command-line instructions and calls the appropriate functions from the API. We are providing the user-interface code in the file helpcentre.c, which you are not allowed to change. Read it carefully to understand how it works.
Your help centre queue will be manipulated through a boring (but simple) command line interface that supports the following operations. These operations are not fully specified here. You will need to read the starter code including comments to see the full required behaviour.
Command Description
stats_by_course course Prints the current stats for a course: how many students are waiting, how many are currently being served, how many have already served, how many students were waiting for this course and gave up, and the total time that has been spent waiting for this course and answering questions for this course. Much of this function is provided so that the formatting of the output is consistent. Do not change the provided code; Only add to it.
add_student name course Adds a new student by this name to the data structure and records that the student has a question for this course.
add_ta name Adds a TA by this name.
remove_ta name Removes the TA by this name.
print_all_queues Prints the full list of courses. For each course, prints the total number and names (in order) of students queued up for that course. We have provided print statements so that you can get the formatting correct for testing. You can change the variable names in the print statements, but don't change the format strings. Students currently being served by a TA are no longer in a queue and so are not shown.
give_up student_name Removes the student from the waiting queue and adjusts any stats as needed because this student is giving up before they are called for their turn. The time the student spent waiting before giving up is including in the total waiting time for this course.
print_currently_serving Prints the complete list of TAs. For each TA, prints the student being helped and for which course.
next TA_name The TA is assigned to the next student in the overall queue. If the TA was helping a student when this command is given, it means they are finished with that student. If there is no student waiting, it isn't an error but simply means that the TA no longer has a current student.
next TA_name [Course] If the next command has two arguments, then the second is a course code. In this case, the TA gets the next student from this particular course. If the course has nobody waiting or the course number is invalid, the TA does not take a student from another course but instead has no current student.
print_full_queue This function prints a list of each student in the entire queue in overall order. Each student is shown with their name and course. This function will not be tested for A2, so you do not need to implement it. However, you might find that it is helpful for testing and debugging your solution to other functions. You might also find it helpful to print the arrival time of each waiting student.
help Lists the commands available.
sleep Pauses the program for 2 seconds. Useful for testing with batch file.
quit Closes the helpcentre program.
The helpcentre executable can be started from the command line with either one or two arguments as follows:
./helpcentre config_file [filename]
If helpcentre is run with only one argument (the name of the configuration file), it starts in interactive mode where it displays a prompt and waits for one of the above commands from standard input. When run with two arguments, helpcentre expects the second argument to be the name of a file that contains one helpcentre command per line. The commands are those from the list above. The program will execute those commands from the file. When run with commands from a file, execution happens quickly - so quickly that the waiting times and service times are almost all zero. To simulate time passing, we have included a sleep() command in the API.
Starter code
Log into MarkUs and navigate to the A2: Pointers and Memory. In the same way as for A1, this triggers the starter code for this assignment to be committed to your repository. You will be working alone on this assignment, and the URL for your Git repository can be found on the right hand side of the page. Pull your git repository. There should be a new directory named A2. All of your code for this assignment should be located in this directory.
This directory contains a Makefile and three files called helpcentre.c, hcq.h, and hcq.c that provide the implementation of a skeleton of the help centre data structures. helpcentre.c provides the code to read and parse the user commands described above, and then calls the corresponding C function for each user command. Read the starter code carefully to familiarize yourself with how it works.
Function prototypes for all functions implementing the various user commands are provided in hcq.h. So that the starter code compiles without errors, these functions are currently implemented in hcq.c as stubs (i.e. functions whose body is empty except for a return statement). In addition, there are prototypes and stub implementations for some helper functions that you will use to implement the user-command functions. Your task will be to complete the implementation of all these functions. You are encouraged to create additional helper functions to avoid duplicate code.
We have also provided a sample configuration file courses.config and a sample input file batch_commands.txt that contains a series of commands that will execute in batch mode.
Your tasks
You will complete the functions defined in hcq.c. The comment above each function stub further explains the behaviour of the function.
Note that you are not allowed to modify helpcentre.c or hcq.h. The only C file you are modifying is hcq.c. You may add new functions to hcq.c, but do not change the names or prototypes of the functions we have given you. To add helper functions to hcq.c you should not be adding their declarations into hcq.h which you are not allowed to change. Either add the declarations at the top of hcq.c or define the helper functions before you call them.
Part I: Configuring the Array of Courses
Start by implementing and testing the function config_course_list which sets up the array of courses. The format of the configuration file is as follows:
The first line is a single integer and is the number of courses.
Each subsequent line represents a course.
Each course line begins with a 6 character code followed by a single space. The rest of the line is the course description. The entire line (including newline characters and null terminators) will fit into a buffer of length INPUT_BUFFER_SIZE.
Complete the function find_course and now you can complete and call stats_by_course to partially test your work so far. Of course the stats won't be very interesting since you haven't added any students yet.
Once you have these three functions completed, you should be able to run your helpcentre executable from the commandline and call stats_by_course, help, and quit.
Part II: Adding students and TAs and giving up
Next, write the code for the functions that are called for the user commands add_student and remove_ta and print_all_queues. Once you've done that, complete the functions needed when a student gives up waiting and then another one of the printing functions so that you can see the effects of working functions. We recommend you implement functions in this order:
Student *find_student(Student *stu_list, char *student_name)
Course *find_course(Course *courses, int num_courses, char *course_code)
int add_student(Student **stu_list_ptr, char *student_name, char *course_num, Course *courses, int num_courses)
void release_current_student(Ta *ta)
int give_up_waiting(Student **stu_list_ptr, char *student_name)
void print_all_queues(Student *stu_list, Course *courses, int num_courses)
At this point, you may want to implement print_full_queue. Although it will not be marked (and so you don't have to carefully match an output specification), it might help with the testing and debugging of your other functions.
Part III: Calling students for help
Next implement the functions needed for the two user commands that let TAs call a student to begin helping them: next_student and next_student_by_course. Notice that the API functions have very similar descriptions which suggests that they probably have some common functionality that may motivate the use of a helper function.
For this part you should also implement the function print_currently_serving perhaps doing this first in this section in order to have it available to help debug your other functions.
The API functions you need here are:
void print_currently_serving(Ta *ta_list)
TA *find_ta(Ta *ta_list, char *ta_name)
int take_next_overall(char *ta_name, Ta **ta_list_ptr, Student **stu_list_ptr)
int take_next_course(char *ta_name, Ta **ta_list_ptr, Student **stu_list_ptr, char *course_code, Course *courses, int num_courses)
Carefully read the docstrings on these functions to understand how they behave.
Part IV: Checking your statistics
At the time that you implemented stats_by_course, you didn't have any students or TAs in the system to check your numbers. You may find that you need to go back and add code to your already-implemented functions to correctly compute the required statistics. Pay particular attention to the fact that when a TA leaves, the current student should be counted as served and the time spent serving that student should contribute to the total helping time for the appropriate course. When a student gives up, the time they spent waiting for service (even though they were never served) should be included in the total waiting time for the course.
Error handling
The comments for the functions you are to implement define nearly all the error conditions you might encounter and tell you how to handle them. The main additional expectation is that you check the return value from malloc and terminate the program if malloc fails.
You should assume that the configuration file is correctly formatted.
What to hand in
Commit to your repository in the A2 directory your revised hcq.c file. Since you are not allowed to change hcq.h, helpcentre.c, and the provided Makefile, we will use the original versions for compiling and testing your code. The markers must be able to run make such that helpcentre is compiled with no warnings.
Coding style and comments are just as important in CSC209 as they were in previous courses. Use good variable names, appropriate functions, descriptive comments, and blank lines. Remember that someone needs to read your code. You should write extra helper functions.
Please remember that if you submit code that does not compile, it will receive a grade of 0. The best way to avoid this potential problem is to write your code incrementally. The starter code compiles without warnings and runs. As you solve each small piece of the problem make sure that your new version continues to compile without warnings and runs. Get a small piece working, commit it, and then move on to the next piece. This is a much better approach than writing a whole bunch of code and then spending a lot of time debugging it step by step.
|
Java
|
UTF-8
| 1,746 | 2.34375 | 2 |
[] |
no_license
|
package com.strangeiron.endoftheline.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.strangeiron.endoftheline.EotlInputManager;
import com.strangeiron.endoftheline.EotlNetwork;
import com.strangeiron.endoftheline.EotlWorld;
import com.strangeiron.endoftheline.entity.EotlEntityManager;
import com.strangeiron.endoftheline.entity.EotlLocalPlayer;
public class EotlGameScreen extends EotlScreen {
public static ShapeRenderer shapeRenderer;
@Override
public void postInit() {
EotlEntityManager.localPlayer = new EotlLocalPlayer();
EotlEntityManager.addEntity(EotlEntityManager.localPlayer, 0);
EotlNetwork.init();
EotlWorld.init();
EotlNetwork.connect("127.0.0.1", 12345); // @TODO: Debug shit ;/
EotlNetwork.sendLoginPacket();
EotlWorld.loadMap("test");
}
@Override
public void tick (EotlInputManager input)
{
/** По факту это лучше делать не тут, но т.к. мир должен обновляться ТОЛЬКО
* непосредственно во время игры (т.к. EotlWorld управляет игровой тайл-картой
* и обновлениями физики), то думаю это ок.
*/
EotlWorld.update();
// Аналогично и с энтитями
EotlEntityManager.tick(Gdx.graphics.getDeltaTime(), input);
}
@Override
public void render()
{
// Аналогично с update()
EotlWorld.render(spriteBatch);
EotlEntityManager.render();
}
}
|
Java
|
UTF-8
| 3,153 | 2.328125 | 2 |
[] |
no_license
|
package com.udacity.jwdnd.course1.cloudstorage.pages;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Credentials {
private WebDriverWait wait;
@FindBy(css = "#nav-credentials-tab")
private WebElement credentialsTab;
@FindBy(css = "#showCredentialForm")
private WebElement showCredentialForm;
@FindBy(css = "#credential-url")
private WebElement credentialUrl;
@FindBy(css = "#credential-username")
private WebElement credentialUsername;
@FindBy(css = "#credential-password")
private WebElement credentialPassword;
@FindBy(css = "#credentialSubmit")
private WebElement credentialSubmit;
@FindBy(xpath = "//*[@id='credentialTable']/tbody/tr/td[1]/button")
private WebElement editButton;
@FindBy(xpath = "//*[@id='credentialTable']/tbody/tr/td[1]/a")
private WebElement deleteButton;
@FindBy(css = "note-title-text")
private WebElement noteTitleText;
@FindBy(css = "note-description-text")
private WebElement noteDescriptionText;
public Credentials(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void addCredential(String url, String username, String password,WebDriver driver) throws InterruptedException {
this.wait = new WebDriverWait(driver, 1);
Thread.sleep(1000);
credentialsTab.click();
wait.until(ExpectedConditions.elementToBeClickable(showCredentialForm));
Assertions.assertNotNull(showCredentialForm);
showCredentialForm.click();
wait.until(ExpectedConditions.visibilityOf(credentialUrl));
credentialUrl.sendKeys(url);
credentialUsername.sendKeys(username);
credentialPassword.sendKeys(password);
credentialSubmit.submit();
}
public void editCredential(String changeUrl, String changeUsername, String changePassword, WebDriver driver) throws InterruptedException {
this.wait = new WebDriverWait(driver, 1);
Thread.sleep(1000);
credentialsTab.click();
wait.until(ExpectedConditions.elementToBeClickable(editButton));
Assertions.assertNotNull(editButton);
editButton.click();
wait.until(ExpectedConditions.visibilityOf(credentialUrl));
credentialUrl.clear();
credentialUrl.sendKeys(changeUrl);
credentialUsername.clear();
credentialUsername.sendKeys(changeUsername);
credentialPassword.clear();
credentialPassword.sendKeys(changePassword);
credentialSubmit.submit();
}
public void deleteCredential(WebDriver driver) throws InterruptedException {
this.wait = new WebDriverWait(driver, 1);
Thread.sleep(1000);
credentialsTab.click();
wait.until(ExpectedConditions.visibilityOf(deleteButton));
Thread.sleep(1000);
deleteButton.click();
}
}
|
Python
|
UTF-8
| 459 | 2.640625 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import os
import sys
if len(sys.argv) < 2:
print("Find files in current directory")
print("Usage: f ([directory]) [reg-exp] ([reg-exp] ..)")
sys.exit("")
if "-name" in sys.argv:
sys.argv.remove("-name")
directory = "."
if os.path.isdir(sys.argv[1]):
directory = sys.argv[1]
del sys.argv[1]
for regexp in sys.argv[1:]:
cmd = 'find %(directory)s -name "%(regexp)s"' % locals()
#print(cmd)
os.system(cmd)
|
C#
|
UTF-8
| 2,101 | 3.21875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Cell_Phone_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool InputExists()
{
bool isValid = false;
if (brandTextBox.Text != "" && modelTextBox.Text != "" && priceTextBox.Text != "")
if (brandTextBox.Text != null && modelTextBox.Text != null && priceTextBox.Text != null)
isValid = true;
return isValid;
}
private bool GetPhoneData(CellPhone phone)
{
bool isValid = false;
decimal price;
phone.Brand = brandTextBox.Text;
phone.Model = modelTextBox.Text;
if (decimal.TryParse(priceTextBox.Text, out price) && price >= 0m)
{
phone.Price = price;
isValid = true;
}
else
{
MessageBox.Show("Price is invalid.");
priceTextBox.Clear();
priceTextBox.Focus();
}
return isValid;
}
private void DisplayPhoneData(CellPhone phone)
{
brandLabel.Text = phone.Brand;
modelLabel.Text = phone.Model;
priceLabel.Text = phone.Price.ToString("c");
}
private void createObjectButton_Click(object sender, EventArgs e)
{
CellPhone phone = new CellPhone();
if (InputExists())
{
if (GetPhoneData(phone))
{
DisplayPhoneData(phone);
}
}
else
{
MessageBox.Show("Please make sure all textboxes are filled.");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
Python
|
UTF-8
| 1,084 | 3.71875 | 4 |
[] |
no_license
|
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
node = head
stack = []
start = None
tail = None
index = 1
while node is not None:
if index == left:
while index != right:
stack.append(node)
node = node.next
index += 1
stack.append(node)
tail = node.next
break
else:
start = node
node = node.next
index += 1
while len(stack) > 0:
stack_node = stack.pop(-1)
if start is None:
start = stack_node
head = start
else:
start.next = stack_node
start = stack_node
start.next = tail
return head
s = ListNode(5)
s1 = ListNode(3, s)
print(Solution().reverseBetween(s1, 1, 2))
|
JavaScript
|
UTF-8
| 2,634 | 2.859375 | 3 |
[] |
no_license
|
var backdrop, jungle, monkey, monkeyAnimation, rock, rockImage, banana, bananaImage, ground, invisibleGround, bananaGroup, rockGroup, score;
function preload(){
jungle = loadImage("jungle.jpg");
rockImage = loadImage("stone.png");
bananaImage = loadImage("banana.png");
monkeyAnimation = loadAnimation ("Monkey_01.png",
"Monkey_02.png","Monkey_03.png","Monkey_04.png",
"Monkey_05.png","Monkey_06.png","Monkey_07.png",
"Monkey_08.png","Monkey_09.png","Monkey_10.png");
}
function setup() {
createCanvas(600,200);
text(mouseX + "," + mouseY, mouseX, mouseY);
backdrop = createSprite(300,10,50,50);
backdrop.addAnimation("background",jungle);
backdrop.scale = 1.1
monkey = createSprite (40,160,50,50);
monkey.addAnimation("monkeyRun",monkeyAnimation);
monkey.scale = 0.1;
ground = createSprite(300,190,600,10);
ground.visible = false;
//backdrop.visible = false;
bananaGroup = new Group();
rockGroup = new Group();
score = 0
stroke("white");
textSize(20);
fill("white");
text("Score: " + score, 10, 25 );
}
function draw() {
background(220);
drawSprites();
//console.log(monkey.scale);
text.depth = backdrop.depth + 5;
//text(mouseX + "," + mouseY, mouseX, mouseY);
backdrop.velocityX = -2;
if (backdrop.x < 60
){
backdrop.x = 300;
}
if (keyDown ("space")){
monkey.velocityY = -10
}
monkey.velocityY = monkey.velocityY + 0.5;
monkey.collide(ground);
if(bananaGroup.isTouching(monkey)){
bananaGroup.destroyEach();
score = score + 2;
if(monkey.scale< 0.13){
monkey.scale = monkey.scale + 0.01
}
}
if(rockGroup.isTouching(monkey)){
rockGroup.destroyEach();
if(score > 0){
score = score -2;
}
if(monkey.scale > 0.1){
monkey.scale = monkey.scale - 0.01
}
}
stroke("white");
textSize(20);
fill("white");
text("Score: " + score, 260, 25 );
banana();
rock();
}
function banana(){
if (World.frameCount % 90 === 0) {
var banana = createSprite(600,50,40,10);
banana.y = Math.round(random(30,100));
banana.addImage(bananaImage);
banana.scale = 0.03;
banana.velocityX = -3;
banana.lifetime = 200;
banana.depth = monkey.depth;
monkey.depth = monkey.depth + 1;
bananaGroup.add(banana);
}
}
function rock() {
if(World.frameCount % 60 === 0) {
var rock = createSprite(600,170,10,40);
rock.addImage(rockImage);
rock.velocityX = - (6);
rock.scale = 0.1;
rock.lifetime = 100;
rockGroup.add(rock);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.