language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 6,126 | 1.875 | 2 |
[] |
no_license
|
package se.skl.skltpservices.takecare.takecareintegrationcomponent.updatebooking;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.math.BigInteger;
import org.junit.Test;
import org.soitoolkit.commons.mule.jaxb.JaxbUtil;
import org.soitoolkit.commons.mule.util.MiscUtil;
import se.skl.skltpservices.takecare.TakeCareUtil;
import se.skl.skltpservices.takecare.JaxbHelper;
import se.skl.skltpservices.takecare.booking.RescheduleBooking;
import se.skl.skltpservices.takecare.booking.reschedulebookingrequest.ProfdocHISMessage;
public class UpdateBookingRequestTransformerTest {
private static final JaxbUtil jaxbUtil_outgoing = new JaxbUtil(RescheduleBooking.class);
private static final JaxbUtil jaxbUtil_message = new JaxbUtil(ProfdocHISMessage.class);
@Test
public void testTransformerWithMandatoryRivTaFields() throws Exception {
// Specify input and expected result
String input = MiscUtil.readFileAsString("src/test/resources/testfiles/UpdateBooking/request-input.xml");
UpdateBookingRequestTransformer transformer = new UpdateBookingRequestTransformer();
String result = (String) transformer.pojoTransform(null, input, "UTF-8");
/* RescheduleBookings */
RescheduleBooking rebBookings = (RescheduleBooking) jaxbUtil_outgoing.unmarshal(result);
String careunitId = rebBookings.getCareunitid();
String careunitType = rebBookings.getCareunitidtype();
String externalUser = rebBookings.getExternaluser();
String tcPassword = rebBookings.getTcpassword();
String tcUsername = rebBookings.getTcusername();
String xml = rebBookings.getXml();
assertEquals(TakeCareUtil.HSAID, careunitType);
assertEquals("HSA-VKK123", careunitId);
assertEquals(TakeCareUtil.EXTERNAL_USER, externalUser);
assertEquals("", tcPassword);
assertEquals("", tcUsername);
/* ProfdocHISMessage */
ProfdocHISMessage message = new ProfdocHISMessage();
message = (ProfdocHISMessage) JaxbHelper.transform(message, "urn:ProfdocHISMessage:RescheduleBooking:Request", xml);
String msgCareunitId = message.getCareUnitId();
String msgCareunitIdType = message.getCareUnitIdType();
String msgInvokingSystem = message.getInvokingSystem();
String msgMessageType = message.getMsgType();
BigInteger msgTime = message.getTime();
String patientReason = message.getPatientReason();
BigInteger endTime = message.getEndTime();
BigInteger patientId = message.getPatientId();
BigInteger resourceId = message.getResourceId();
BigInteger startTime = message.getStartTime();
int timeTypeId = message.getTimeTypeId();
String bookingId = message.getBookingId();
assertEquals("HSA-VKK123", msgCareunitId);
assertEquals(TakeCareUtil.HSAID, msgCareunitIdType);
assertEquals(TakeCareUtil.INVOKING_SYSTEM, msgInvokingSystem);
assertEquals(TakeCareUtil.REQUEST, msgMessageType);
assertEquals("191414141414", patientId.toString());
assertEquals("Only phone, no reason specified", "", patientReason);
assertEquals("111222333", bookingId);
assertNotNull(endTime);
assertNotNull(startTime);
assertNull(resourceId);
assertEquals(0, timeTypeId);
assertNotNull(msgTime);
}
@Test
public void testTransformerWithAllTakeCareFields() throws Exception {
// Specify input and expected result
String input = MiscUtil
.readFileAsString("src/test/resources/testfiles/UpdateBooking/request-input-all-takecare-fields.xml");
UpdateBookingRequestTransformer transformer = new UpdateBookingRequestTransformer();
String result = (String) transformer.pojoTransform(null, input, "UTF-8");
/* RescheduleBookings */
RescheduleBooking reBookings = (RescheduleBooking) jaxbUtil_outgoing.unmarshal(result);
String careunitId = reBookings.getCareunitid();
String careunitType = reBookings.getCareunitidtype();
String externalUser = reBookings.getExternaluser();
String tcPassword = reBookings.getTcpassword();
String tcUsername = reBookings.getTcusername();
String xml = reBookings.getXml();
assertEquals(TakeCareUtil.HSAID, careunitType);
assertEquals("HSA-VKK123", careunitId);
assertEquals(TakeCareUtil.EXTERNAL_USER, externalUser);
assertEquals("", tcPassword);
assertEquals("", tcUsername);
/* ProfdocHISMessage */
ProfdocHISMessage message = new ProfdocHISMessage();
message = (ProfdocHISMessage) JaxbHelper.transform(message, "urn:ProfdocHISMessage:RescheduleBooking:Request", xml);
String msgCareunitId = message.getCareUnitId();
String msgCareunitIdType = message.getCareUnitIdType();
String msgInvokingSystem = message.getInvokingSystem();
String msgMessageType = message.getMsgType();
BigInteger msgTime = message.getTime();
String patientReason = message.getPatientReason();
BigInteger endTime = message.getEndTime();
BigInteger patientId = message.getPatientId();
BigInteger resourceId = message.getResourceId();
BigInteger startTime = message.getStartTime();
int timeTypeId = message.getTimeTypeId();
String bookingId = message.getBookingId();
assertEquals("HSA-VKK123", msgCareunitId);
assertEquals(TakeCareUtil.HSAID, msgCareunitIdType);
assertEquals(TakeCareUtil.INVOKING_SYSTEM, msgInvokingSystem);
assertEquals(TakeCareUtil.REQUEST, msgMessageType);
assertEquals("191414141414", patientId.toString());
assertEquals("1234567890", bookingId);
assertEquals("Reason", patientReason);
assertNotNull(endTime);
assertNotNull(startTime);
assertEquals(new BigInteger("2"), resourceId);
assertEquals(1, timeTypeId);
assertNotNull(msgTime);
}
}
|
JavaScript
|
UTF-8
| 1,097 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<script type="text/javascript">
function popUp(path,title) {
var popwin;
if (title!="view") {
leftval=(screen.width)?(screen.width-400)/2:100;
topval=(screen.height)?(screen.height-500)/2:100;
popwin=window.open(path, title, "width=400,height=500,top=" + topval + ",left=" + leftval + ",toolbar=0,scrollbars=1,directories=no,location=0,statusbar=0,menubar=0,resizable=0");
} else {
leftval=(screen.width)?(screen.width-750)/2:100;
topval=(screen.height)?(screen.height-750)/2:100;
popwin=window.open(path, title, "width=750,height=750,top=" + topval + ",left=" + leftval + ",toolbar=0,scrollbars=1,directories=no,location=0,statusbar=0,menubar=0,resizable=1");
}
popwin.focus();
}
function setSelect(form_name, select_name) {
var select_field=document.forms[form_name].elements[select_name];
for (var i = 0; i < select_field.length; i++) select_field.options[i].selected = true;
return true;
}
function confirmClick(title,path) {
var input=confirm(title);
if (input) window.location.href=path;
}
</script>
|
JavaScript
|
UTF-8
| 722 | 2.578125 | 3 |
[] |
no_license
|
const axios = require('axios');
function validate(array) {
const promises = array.map((item) => axios.get(item.href)
.then((response) => ({
href: item.href,
text: item.text,
file: item.file,
statusText: response.statusText,
status: response.status,
}))
.catch((error) => {
if (error.response) {
return ({
href: item.href,
text: item.text,
file: item.file,
statusText: error.response.statusText,
status: error.response.status,
});
} else if (error.request) {
return ('Error request');
} else {
return ('Error');
}
}));
return promises;
}
module.exports = validate;
|
JavaScript
|
UTF-8
| 482 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
module.exports = function(path, sep){
var bits,
hasLeading;
// allow the user to specify any kind of path: /path/to/share or \path\to\share
if(path.indexOf('/') > -1){
hasLeading = path.charAt(0) === '/';
bits = path.split('/');
}
else {
hasLeading = path.charAt(0) === '\\';
bits = path.split('\\');
}
bits = bits.filter(function(v){ return v !== '';});
return (hasLeading ? sep : '') + bits.join(sep);
};
|
PHP
|
UTF-8
| 1,393 | 2.953125 | 3 |
[
"Unlicense"
] |
permissive
|
<?php
class ValueRemapper
{
protected static $_inst;
protected $_maps=array();
protected $_cimaps=array();
protected $_curmap=null;
public function __construct()
{
}
static public function getInstance()
{
if(self::$_inst==null)
{
self::$_inst=new ValueRemapper();
}
return self::$_inst;
}
public static function use_csv($csv)
{
$inst=self::getInstance();
$inst->setMap($csv);
$inst->_curmap=$csv;
return $inst;
}
public function map($val,$ci=false)
{
$tval=trim($val);
//remapper case insensitive fix
if($ci)
{
$tval=strtoupper($val);
$targetmap=$this->_cimaps[$this->_curmap];
}
else
{
$targetmap=$this->_maps[$this->_curmap];
}
return isset($targetmap[$tval])?$targetmap[$tval]:$val;
}
/*
* Map a multivalue given a separator
*/
public function mapmulti($val,$sep=',',$ci=false)
{
$vals=explode($sep,$val);
for($i=0;$i<count($vals);$i++)
{
$vals[$i]=$this->map($vals[$i],$ci);
}
return implode($sep,$vals);
}
public function setMap($csv)
{
if(!isset($this->_maps[$csv]))
{
$this->_maps[$csv]=array();
$this->_cimaps[$csv] =array();
if(file_exists($csv))
{
$lines=file($csv);
foreach($lines as $line)
{
$kv=explode(";",trim($line));
$this->_maps[$csv][$kv[0]]=$kv[1];
$this->_cimaps[$csv][strtoupper($kv[0])]=$kv[1];
}
}
}
}
}
|
Swift
|
UTF-8
| 2,887 | 2.828125 | 3 |
[] |
no_license
|
//
// ViewController.swift
// Contacts
//
// Created by José Inácio Athayde Ferrarini on 9/10/14.
// Copyright (c) 2014 José Inácio Athayde Ferrarini. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, SyncServerDelegate {
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var contactTypeLabel: UILabel!
@IBOutlet weak var contactNameText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
println("View ficará visível")
// Do any additional setup after loading the view, typically from a nib.
// var nameLabel = UILabel()
// nameLabel.text = "Nome"
// nameLabel.frame = CGRectMake(120, 30, 200, 30)
// self.view.addSubview(nameLabel)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println("View carregada na tela")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func stepperChanged(sender: UIStepper) {
ageLabel.text = "\(Int(sender.value))"
}
@IBAction func setFormaContato(sender: AnyObject) {
var actionSheet = UIAlertController (title: "Contato",
message: "Escolha uma forma de contato",
preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Email",
style: UIAlertActionStyle.Default,
handler: { _ in
self.contactTypeLabel.text = "Email"
}))
actionSheet.addAction(UIAlertAction(title: "Telefone",
style: UIAlertActionStyle.Default,
handler: { _ in
self.contactTypeLabel.text = "Telefone"
}))
actionSheet.addAction(UIAlertAction(title: "Cancelar",
style: UIAlertActionStyle.Cancel,
handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
@IBAction func saveContact(sender: AnyObject) {
var actionSheet = UIAlertController (title: "Confirmação",
message: "Deseja gravar este contato?",
preferredStyle: UIAlertControllerStyle.Alert)
actionSheet.addAction(UIAlertAction(title: "Sim",
style: UIAlertActionStyle.Default,
handler: { _ in
println("Alert - Sim")
let sync = SyncServer(delegate: self)
sync.saveInfo()
}))
actionSheet.addAction(UIAlertAction(title: "Não",
style: UIAlertActionStyle.Cancel,
handler: { _ in
println("Alert - Não")
}))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
contactNameText.resignFirstResponder()
return false;
}
func infoSaved() {
var actionSheet = UIAlertController (title: "Salvo",
message: "Salvo com Sucesso!",
preferredStyle: UIAlertControllerStyle.Alert)
actionSheet.addAction(UIAlertAction(title: "OK",
style: UIAlertActionStyle.Cancel,
handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
}
|
Java
|
UTF-8
| 7,760 | 1.914063 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2021 Oracle and/or its affiliates.
*
* 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 io.helidon.build.maven.cache;
import java.util.List;
import java.util.Objects;
import io.helidon.build.common.SourcePath;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.MojoExecution;
import org.codehaus.plexus.util.xml.Xpp3Dom;
/**
* Execution entry.
*/
final class ExecutionEntry {
private static final List<String> DEFAULT_INCLUDES = List.of("*");
static final String XML_ELEMENT_NAME = "execution";
private final String groupId;
private final String artifactId;
private final String version;
private final String goal;
private final String executionId;
private final ConfigNode configuration;
/**
* Create a new execution entry instance.
*
* @param groupId plugin groupId
* @param artifactId plugin artifactId
* @param version plugin version
* @param goal goal
* @param executionId executionId
* @param configuration configuration
*/
ExecutionEntry(String groupId,
String artifactId,
String version,
String goal,
String executionId,
ConfigNode configuration) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.goal = goal;
this.executionId = executionId;
this.configuration = configuration;
}
/**
* Get the groupId.
*
* @return groupId
*/
String groupId() {
return groupId;
}
/**
* Get the artifactId.
*
* @return artifactId
*/
String artifactId() {
return artifactId;
}
/**
* Get the version.
*
* @return version
*/
String version() {
return version;
}
/**
* Get the executionId.
*
* @return executionId
*/
String executionId() {
return executionId;
}
/**
* Get the goal.
*
* @return goal
*/
String goal() {
return goal;
}
/**
* Get the execution configuration.
*
* @return configuration
*/
ConfigNode config() {
return configuration;
}
/**
* Test if this execution matches an other execution.
* Matching executions are identical except for the configuration.
*
* @param execution execution
* @return {@code true} if matches, {@code false} otherwise
*/
boolean matches(ExecutionEntry execution) {
return groupId.equals(execution.groupId)
&& artifactId.equals(execution.artifactId)
&& version.equals(execution.version)
&& goal.equals(execution.goal)
&& executionId.equals(execution.executionId);
}
/**
* Test if this execution matches a plugin execution.
*
* @param plugin plugin
* @param goal plugin execution goal
* @param id plugin execution id
* @return {@code true} if matches, {@code false} otherwise
*/
boolean matches(Plugin plugin, String goal, String id) {
return groupId.equals(plugin.getGroupId())
&& artifactId.equals(plugin.getArtifactId())
&& version.equals(plugin.getVersion())
&& this.goal.equals(goal)
&& executionId.equals(id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ExecutionEntry execution = (ExecutionEntry) o;
return groupId.equals(execution.groupId)
&& artifactId.equals(execution.artifactId)
&& version.equals(execution.version)
&& goal.equals(execution.goal)
&& executionId.equals(execution.executionId)
&& Objects.equals(configuration, execution.configuration);
}
@Override
public int hashCode() {
return Objects.hash(groupId, artifactId, version, goal, executionId, configuration);
}
/**
* Get the name of this execution.
*
* @return name
*/
String name() {
return groupId + ":" + artifactId + ":" + version + ":" + goal + "@" + executionId;
}
/**
* Match the execution name with the given include and exclude patterns.
*
* @param includes include patterns
* @param excludes exclude patterns
* @return {@code true} if matched, {@code false} otherwise
*/
boolean match(List<String> includes, List<String> excludes) {
if (includes == null || includes.isEmpty()) {
includes = DEFAULT_INCLUDES;
}
String execName = name();
for (String include : includes) {
if (!SourcePath.wildcardMatch(execName, include)) {
return false;
}
}
if (excludes != null) {
for (String exclude : excludes) {
if (SourcePath.wildcardMatch(execName, exclude)) {
return false;
}
}
}
return true;
}
@Override
public String toString() {
return "ExecutionEntry{"
+ "groupId='" + groupId + '\''
+ ", artifactId='" + artifactId + '\''
+ ", version='" + version + '\''
+ ", goal='" + goal + '\''
+ ", executionId='" + executionId + '\''
+ ", configuration='" + configuration + '\''
+ '}';
}
/**
* Convert this instance to an XML DOM element.
*
* @return Xpp3Dom
*/
Xpp3Dom toXml() {
Xpp3Dom elt = new Xpp3Dom(XML_ELEMENT_NAME);
elt.setAttribute("groupId", groupId);
elt.setAttribute("artifactId", artifactId);
elt.setAttribute("version", version);
elt.setAttribute("goal", goal);
elt.setAttribute("id", executionId);
if (configuration != null) {
elt.addChild(configuration.toXpp3Dom());
}
return elt;
}
/**
* Create an instance from an XML DOM element.
*
* @param elt XML DOM element
* @return ExecutionEntry
*/
static ExecutionEntry fromXml(Xpp3Dom elt) {
ConfigNode config = new ConfigNode(ConfigAdapters.create(elt.getChild("configuration")), null);
return new ExecutionEntry(
elt.getAttribute("groupId"),
elt.getAttribute("artifactId"),
elt.getAttribute("version"),
elt.getAttribute("goal"),
elt.getAttribute("id"),
config);
}
/**
* Create an execution entry from a mojo execution.
*
* @param execution mojo execution
* @param configuration config node root
* @return ExecutionEntry
*/
static ExecutionEntry create(MojoExecution execution, ConfigNode configuration) {
return new ExecutionEntry(execution.getGroupId(), execution.getArtifactId(), execution.getVersion(),
execution.getGoal(), execution.getExecutionId(), configuration);
}
}
|
Markdown
|
UTF-8
| 9,824 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
# Assignment 4
Before working on this assignment please read these instructions fully. In the submission area, you will notice that you can click the link to **Preview the Grading** for each step of the assignment. This is the criteria that will be used for peer grading. Please familiarize yourself with the criteria before beginning the assignment.
This assignment requires that you to find **at least** two datasets on the web which are related, and that you visualize these datasets to answer a question with the broad topic of **sports or athletics** (see below) for the region of **Ann Arbor, Michigan, United States**, or **United States** more broadly.
You can merge these datasets with data from different regions if you like! For instance, you might want to compare **Ann Arbor, Michigan, United States** to Ann Arbor, USA. In that case at least one source file must be about **Ann Arbor, Michigan, United States**.
You are welcome to choose datasets at your discretion, but keep in mind **they will be shared with your peers**, so choose appropriate datasets. Sensitive, confidential, illicit, and proprietary materials are not good choices for datasets for this assignment. You are welcome to upload datasets of your own as well, and link to them using a third party repository such as github, bitbucket, pastebin, etc. Please be aware of the Coursera terms of service with respect to intellectual property.
Also, you are welcome to preserve data in its original language, but for the purposes of grading you should provide english translations. You are welcome to provide multiple visuals in different languages if you would like!
As this assignment is for the whole course, you must incorporate principles discussed in the first week, such as having as high data-ink ratio (Tufte) and aligning with Cairo’s principles of truth, beauty, function, and insight.
Here are the assignment instructions:
* State the region and the domain category that your data sets are about (e.g., **Ann Arbor, Michigan, United States** and **sports or athletics**).
* You must state a question about the domain category and region that you identified as being interesting.
* You must provide at least two links to available datasets. These could be links to files such as CSV or Excel files, or links to websites which might have data in tabular form, such as Wikipedia pages.
* You must upload an image which addresses the research question you stated. In addition to addressing the question, this visual should follow Cairo's principles of truthfulness, functionality, beauty, and insightfulness.
* You must contribute a short (1-2 paragraph) written justification of how your visualization addresses your stated research question.
What do we mean by **sports or athletics**? For this category we are interested in sporting events or athletics broadly, please feel free to creatively interpret the category when building your research question!
## Tips
* Wikipedia is an excellent source of data, and I strongly encourage you to explore it for new data sources.
* Many governments run open data initiatives at the city, region, and country levels, and these are wonderful resources for localized data sources.
* Several international agencies, such as the [United Nations](http://data.un.org/), the [World Bank](http://data.worldbank.org/), the [Global Open Data Index](http://index.okfn.org/place/) are other great places to look for data.
* This assignment requires you to convert and clean datafiles. Check out the discussion forums for tips on how to do this from various sources, and share your successes with your fellow students!
## Example
Looking for an example? Here's what our course assistant put together for the **Ann Arbor, MI, USA** area using **sports and athletics** as the topic. [Example Solution File](./readonly/Assignment4_example.pdf)
### I wrote code to scrape data from the websites on my local machine because it did not work for the server notebook.
<br>
I scraped the data from these websites on December 5, 2017. The webpages may change in the future.
<br>
* Basketball (Los Angeles Lakers) https://en.wikipedia.org/wiki/List_of_Los_Angeles_Lakers_seasons
* Hockey (Los Angeles Kings) https://en.wikipedia.org/wiki/List_of_Los_Angeles_Kings_seasons
* Baseball (Los Angeles Dodgers) https://en.wikipedia.org/wiki/List_of_Los_Angeles_Dodgers_seasons
* Football (Los Angeles Rams) https://en.wikipedia.org/wiki/List_of_Los_Angeles_Rams_seasons
<br>
<br>
I cleaned the data and saved them as .csv files. For the assignment, I uploaded the cleaned .csv files into my work area and loaded from there.
### Import Modules
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```
### Load Data
```python
df_lakers_cleaned = pd.read_csv( 'lakers_data_cleaned.csv', index_col = 0)
df_kings_cleaned = pd.read_csv( 'kings_data_cleaned.csv', index_col = 0)
df_dodgers_cleaned = pd.read_csv( 'dodgers_data_cleaned.csv', index_col = 0)
df_rams_cleaned = pd.read_csv( 'Rams_data_cleaned.csv', index_col = 0)
```
### Prep data for consumption
```python
# NOTE: I Googled the team color.
list_prepped_data = \
[
('Lakers', 'purple', df_lakers_cleaned),
('Kings', 'grey', df_kings_cleaned),
('Dodgers', 'blue', df_dodgers_cleaned),
('Rams', 'orange', df_rams_cleaned)
]
```
### Plot Moving Average (Rolling Mean) Graph.
```python
#---------------------- Functions (Start)--------------------------
def build_graph( plt = None,
df = None,
team_name = None,
team_color = None ):
"""
Description: Creates plot on same figure.
# TODO
#
# -Set title
# -Set x label
# -Set y lable
# -Set x-axis to be the whole data but only show 10 year intervals
# -Set y-axis for 0.0 to 1.0 but have dotted lines from 0.0, 0.25, 0.75, 1.0 BUT only use the highest that contain data.
# -Set thick lines.
# -Set dotted lines at y-axis intervals
# -Set annotations for names of team next to plot lines
# -Set annotations for win%
# -Remove plot box
# -Change the name of the figure to be generic for all teams and the save image.
"""
# Create graph
plot_current_graph = plt.plot( df['Season'],
df['Rolling_Mean'],
c=team_color,
label='Lakers')
# Set line thickness and style (like dotted)
# https://matplotlib.org/examples/pylab_examples/set_and_get.html
# plt.setp(plot_current_graph,
# linestyle='--')
plt.setp( plot_current_graph,
linewidth=4 )
# x the year after the last year recorded
x_pos = 2017
# y is the height of the last value in the dataframe.
y_pos = df['Rolling_Mean'].iloc[-1]
font_size = 10
plt.text(x_pos,
y_pos,
team_name,
color = team_color,
fontsize = font_size)
#---------------------- Functions (End)--------------------------
#--------------------------------------
# Setup static features of graph.
# (Start)
#--------------------------------------
# Create new figure
fig_teams = plt.figure(figsize = (16,8))
ax = fig_teams.add_subplot(111)
# Remove axis
#plt.axis('off')
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Title
plt.title('Los Angeles Sports Teams Win %'
'\n(10 Year Moving Average)',
fontsize=20 )
# Labels for x and y axes
plt.xlabel( 'Season',
fontsize=15 )
plt.ylabel( '10 Year Moving Average Win %',
fontsize=15 )
# Set limit on x-axis
#ax.set_xlim([datetime.date(2016, 1, 1), datetime.date(2016, 12, 31)])
ax.set_ylim(0.0, 0.85)
# https://stackoverflow.com/questions/24943991/matplotlib-change-grid-interval-and-specify-tick-labels
#
# Set x-axis to be the whole data but only show 10 year intervals
x_major_ticks = np.arange(1980, 2020, 10)
#x_minor_ticks = np.arange(1980, 2020, 1)
#
ax.set_xticks(x_major_ticks)
# ax.set_xticks(x_minor_ticks, minor=True)
#
# Set y-axis for 0.0 to 1.0 but have dotted lines from 0.0, 0.25, 0.75, 1.0 BUT only use the highest that contain data.
y_major_ticks = np.arange(0.0, 1.1, 0.25)
#
# Slice to exclude the first and last entry.
y_major_ticks = y_major_ticks[:-1]
ax.set_yticks(y_major_ticks)
# Draw horizontal lines
for num in y_major_ticks:
plt.axhline(y = num,
linestyle = '--',
color = 'grey',
alpha = 0.2 )
# Legend
plt.text(1980,
0.1,
#'Win % = Games Won\(Games Won + Games Lost)',
#r'$\frac{5 - \frac{1}{x}}{4}$',
r'Win % = $\frac{Games Won}{Games Won + Games Lost}$',
fontsize = 15,
bbox={'facecolor':'lightgrey', 'alpha':0.5, 'pad':5})
#--------------------------------------
# Setup static features of graph.
# (End)
#--------------------------------------
# Cycle through the data and graph.
for i in range( len(list_prepped_data) ):
# Current Data
team_name, team_color, df = list_prepped_data[i]
# Build the graph.
build_graph( # Pass the plot being worked on
plt = plt,
# Pass the dataframe being worked on.
df = df,
# The name of the team
team_name = team_name,
# The team color
team_color = team_color)
# Show the graph.
plt.show()
```

### Save graph to .png
```python
fig_teams.savefig( 'Los_Angeles_Sports_Teams_Percent_Wins.png' )
```
|
Java
|
UTF-8
| 3,046 | 2.203125 | 2 |
[] |
no_license
|
package com.huatu.ztk.backend.mysql.dao;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* Created by huangqp on 2018\4\5 0005.
*/
@Repository
public class QuestionSqlDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void updateChildQuestion(Map<Integer, Integer> changeChildMap) {
Connection con = null;
PreparedStatement ps = null;
try {
con = jdbcTemplate.getDataSource().getConnection();
con.setAutoCommit(false);
ps = con.prepareStatement("");
for(Map.Entry<Integer,Integer> entry:changeChildMap.entrySet()){
String sql = "UPDATE v_obj_question SET multi_id = "+ entry.getValue() +",EB103 = 'multi20180405' where pukey = " +entry.getKey();
ps.addBatch(sql);
}
ps.executeBatch();
con.commit();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(ps!=null){
try {
ps.clearBatch();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public List<Map<String,Integer>> findByMulti(int multiId) {
String sql = "select * from v_obj_question where multi_id = ?";
Object[] param = {multiId};
return jdbcTemplate.query(sql,param,(rs,i)->{
Map<String,Integer> map = Maps.newHashMap();
map.put("id",rs.getInt("pukey"));
map.put("flag",rs.getString("eb103").equals("multi20180405")?1:0);
map.put("is_answer_true",rs.getInt("is_ture_answer"));
map.put("status",rs.getInt("bb102"));
return map;
});
}
public List<Integer> findIdByMulti(int multiId) {
String sql = "select pukey from v_obj_question where multi_id = ?";
Object[] param = {multiId};
return jdbcTemplate.queryForList(sql,param,Integer.class);
}
public List<Map<Integer,Integer>> findUpdate() {
String sql = "select * from v_obj_question where eb103 = 'multi20180405'";
return jdbcTemplate.query(sql,(rs,i)->{
Map<Integer,Integer> map = Maps.newHashMap();
map.put(rs.getInt("pukey"),rs.getInt("multi_id"));
return map;
});
}
public List<Map<Integer,Integer>> findCount() {
String sql =" select multi_id,count(1) msize from v_obj_question group by multi_id";
return jdbcTemplate.query(sql,(rs,i)->{
Map<Integer,Integer> map = Maps.newHashMap();
map.put(rs.getInt("multi_id"),rs.getInt("msize"));
return map;
});
}
}
|
Java
|
UTF-8
| 4,053 | 2.6875 | 3 |
[] |
no_license
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import static java.lang.Math.abs;
/* class used to define what is happening in your robot drive base. */
public class RobotDriveBase {
private DcMotor motFrontLeftMotor = null;
//private Servo serDiskPusher = null;
private FTCRobotConfig config = null;
private Telemetry telemetry = null;
private Gyro gyro = null;
private ApplyPower appPower = null;
public RobotDriveBase(FTCRobotConfig mPassedConfig, Telemetry mPassedTelemetry, HardwareMap hardwareMap, Gyro mPassedGyro ) {
telemetry = mPassedTelemetry;
config = mPassedConfig;
loadConfig(); // Load the local configs if there are any
gyro = mPassedGyro;
appPower = new ApplyPower(telemetry);
motFrontLeftMotor = hardwareMap.get(DcMotor.class, "LeftFrontMotor");
// Most robots need the motor on one side to be reversed to drive forward
// Reverse the motor that runs backwards when connected directly to the battery
motFrontLeftMotor.setDirection(DcMotor.Direction.FORWARD);
motFrontLeftMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
//serDiskPusher = hardwareMap.get(Servo.class, "DiskPusherServo");
// Tell the driver that initialization is complete.
telemetry.addData("RobotBase", "Initialize Complete");
}
public void loadConfig() {
//dDiskThrowerPower = config.getDouble("base.dDiskThrowerPower", 1.0);
}
//public void zeroCrabEncoder() {
// iFrontMotorZeroPosition = this.motFrontMotor.getCurrentPosition();
// iFrontMotorCurrentPosition = abs(this.motFrontMotor.getCurrentPosition()-iFrontMotorZeroPosition) ;
//}
//public void zeroPowerEncoder() {
// iLeftMotorZeroPosition = this.motLeftMotor.getCurrentPosition();
// iLeftMotorCurrentPosition = abs(this.motLeftMotor.getCurrentPosition() - iLeftMotorZeroPosition) ;
//}
/* Use this if we need to get value from the base so we cna have other code make decisions.
For example in autonomouas we may want robot base to get use motor encoder data so we know how far we have gone.
*/
//public void readValues() {
//iEncoderCurrentPosition = this.motEncoderMotor.getCurrentPosition() - this.iEncoderStartPosition ;
//iLeftMotorCurrentPosition = abs(this.motLeftMotor.getCurrentPosition() - iLeftMotorZeroPosition) ;
//telemetry.addLine( String.format("ANG: %- 4.2f ",gyro.getAngle() ) );
//telemetry.addLine( String.format("Encod STR: %- 5d | CUR: %- 5d ", iEncoderStartPosition, iEncoderCurrentPosition));
//resetEncoderStartPosition();
//}
/* Use this to tell the robot base to update its values from data provided in inputs.
*/
public void updateValues(Inputs inputs) {
// Are we gyro navigating
//double dGyroAdjust = 0.0;
//if (inputs.bGyroNavigate == true) {
// dGyroAdjust = gyro.steerToDesiredHeading(); // no heading means to stay on current heading
// inputs.dDriverTurnPower += dGyroAdjust;
//}
this.motFrontLeftMotor.setPower(inputs.dLeftDriverPower);
//telemetry.addLine( String.format("DRV: %- 4.2f |", dFrontLeftMotorPower);
//telemetry.addLine( String.format("GNav: %-6.6s | GAdj %- 5.2f ", inputs.bGyroNavigate, dGyroAdjust));
//telemetry.addLine( String.format("Disk PSH: %-12.12s | INT: %-12.12s | THR: %-12.12s", sPusherState, sIntakeState, sDiskThrowerState));
//telemetry.addLine( String.format("Motor FRN: %- 5.2f | %- 5.2f ", dFrontLeftMotorPower, dFrontRightMotorPower));
//telemetry.addLine( String.format("Motor REA: %- 5.2f | %- 5.2f ", dRearLeftMotorPower, dRearRightMotorPower));
}
}
|
Java
|
UHC
| 4,205 | 2.875 | 3 |
[] |
no_license
|
package com.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.domain.Member;
import com.domain.Subject;
@Controller
@RequestMapping("/user/*")
public class HelloController {
///user/sample û ҵ ȣ
@RequestMapping("/sample")
public String sample(Model model) {
model.addAttribute("result", "Hello, Sample World!");
return "sample";
}
///user/test û ҵ ȣ
@RequestMapping("/test")
public String test(Model model) {
model.addAttribute("result", "Hello, Test World!");
return "test";
}
//Ŭ̾Ʈ ڷῡ Ʈ
//->
//->/user/param?name=hong&age=20 ּ û
@RequestMapping("/param")
public void param(HttpServletRequest request) {
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println(name);
System.out.println(age);
//) ȯڷ void
//WEB-INF/views/ûּ.jsp ڵ
}
//Ŭ̾Ʈ ڷῡ Ʈ
//->ڷ Ŭ ڵ
//->/user/member?name=hong&age=20 ּ û
@RequestMapping("/member")
public void member(Member m) {
System.out.println(m.getName());
System.out.println(m.getAge());
//) ȯڷ void
//WEB-INF/views/ûּ.jsp ڵ
}
//Ŭ̾Ʈ ڷῡ Ʈ
//ڷ Ŭ ڷ
//->/user/user?name=hong&age=20 ּ û
@RequestMapping("/user")
public void user(@RequestParam("name") String name
,@RequestParam("age") int age) {
System.out.println(name);
System.out.println(age);
//) ȯڷ void
//WEB-INF/views/ûּ.jsp ڵ
}
//Ŭ̾Ʈ ڷῡ Ʈ
// ĺ, ٷ ڷ
//->/user/instructor?sub=java&sub=oracle ּ û
@RequestMapping("/instructor")
public void instructor(@RequestParam("sub") String[] sub) {
System.out.println(Arrays.toString(sub));
//) ȯڷ void
//WEB-INF/views/ûּ.jsp ڵ
}
// ڷḦ JSP Ʈ
//->/user/data ּ û
@RequestMapping("/data")
public String data(Model model) {
// ڷ غ
//String a = "Hello, SpringMVC World!";
//int a = 10;
//String a = null;
//Date a = new Date();
//
List<Subject> a = new ArrayList<Subject>();
a.add(new Subject("JAVA", 0));
a.add(new Subject("ORACLE", 0));
a.add(new Subject("JSP", 0));
//Ư
List<String> b = new ArrayList<String>();
b.add("JAVA");
b.add("ORACLE");
// Ư
for (Subject s : a) {
String subject = s.getTitle();
if (b.contains(subject)) {
s.setChecked(1);
}
}
model.addAttribute("a", a);
//WEB-INF/views/data.jsp
return "data";
}
//Ŭ̾Ʈ ڷῡ
//+ ڷḦ JSP Ʈ
//->/user/search?key=name&value=hong ּ û
@RequestMapping("/search")
public String search(Model model, @RequestParam String key
,@RequestParam String value) {
System.out.println(key);
System.out.println(value);
model.addAttribute("key", key);
model.addAttribute("value", value);
//WEB-INF/views/search.jsp
return "search";
}
}
|
Markdown
|
UTF-8
| 2,745 | 2.984375 | 3 |
[] |
no_license
|
+++
title = "Umlauts again"
date = 2019-03-17
[taxonomies]
tags = ["year of the linux desktop",
"xkb",
"linux",
"sway"]
+++
Since December I am on Linux with my main machine again. I always wanted to do a rant post about the year
of the linux desktop but instead I am posting something useful.
<!-- more -->
I am using US keyboards on my laptop and whenever I have to type some german umlauts I mostly just don't care.
However for the rare cases when I care (writing serious german emails) I was super annoyed. I was mostly opening
this page here https://learn-german-easily.com/german-umlauts and copy-pasted the characters. Obviously I tried
avoiding using umlauts all together because this is super annoying.
Today I finally fixed it and it was a lot easier than I thought.
Apparently xkb (X Keyboard Extension) already provides everything you need. When you enable the xkb variant "altgr-intl"
you are able to type special characters using the so called "Compose" Key.
Most examples you find will tell you how to configure it in X11.
My setup is using wayland via sway. My `~/.config/sway/config`:
```
[...]
input "1:1:AT_Translated_Set_2_keyboard" {
xkb_layout us
xkb_variant altgr-intl
xkb_options compose:ralt
}
input "1241:41265:HOLTEK_USB-HID_Keyboard" {
xkb_layout us
xkb_variant altgr-intl
xkb_options compose:ralt
}
```
This will enable everything for both of the keyboards (I am using an external keyboard most of the time).
To find out the identifier do the following:
```
[mop@konrad-georg ~]$ sudo libinput debug-events
```
This will print out a list of input devices. When you press a key you will see an eventid which you can map
to the input device:
```
[...device list]
-event4 DEVICE_ADDED AT Translated Set 2 keyboard seat0 default group13 cap:k
[...more devices]
[...pressing a key]
-event4 KEYBOARD_KEY +1.31s *** (-1) pressed
```
Now we know the name of our keyboard. Unfortunately sway needs the identifier.
```
[mop@konrad-georg ~]$ swaymsg -t get_inputs
[...]
Input device: AT Translated Set 2 keyboard
Type: Keyboard
Identifier: 1:1:AT_Translated_Set_2_keyboard
Product ID: 1
Vendor ID: 1
Active Keyboard Layout: English (intl., with AltGr dead keys)
Libinput Send Events: enabled
[...]
```
Finally after restarting sway we can type german umlauts again:
```
Press RAlt, Release RAlt, Press a, Release a, Press ", Release " => ä
Press RAlt, Release RAlt, Press o, Release o, Press ", Release " => ö
Press RAlt, Release RAlt, Press u, Release u, Press ", Release " => ü
Press RAlt, Release RAlt, Press s, Release s, Press s, Release s => ß
Press RAlt, Release RAlt, Press C, Release C, Press =, Release = => €
```
There is probably more :)
|
Markdown
|
UTF-8
| 13,012 | 3.609375 | 4 |
[] |
no_license
|
# Part 1: The Mystery :mag:
This is a _mystery_ lab! That means that solving one task will lead to solving the next task, and the end result will be a **surprise**! Good luck!
## Task 0: Create a Gatsby site
The rest of this lab assumes that you have a Gatsby site set up and that you are in that project directory. Run `gatsby new [the path you want to create the new project]` to get started.
After that, use `gatsby develop` to start serving your project from a development server.
:checkered_flag: **Finish:** Make sure you can see the default Gatsby page at `localhost:8000`.
## Task 1: A React refresher
### Building Components :hammer:
The first exercise for this task will be a walkthrough for building a React component, as a review of the last couple weeks' React content. Then, I'll provide you a high-level specification for what other components need to be built, and you will build them!
**Walkthrough: Contact Form `<ContactForm />`**
The walkthrough will take you through building a common feature you'll be implementing in React sites: forms. There are libraries to reduce some of the complexity that this walkthrough delves into, but it's important to understand how it works to take advantage of React's component methodology and lifecycle hooks.
Let's start with a rough wireframe of how we want our contact form to look:
```
------------------
Name | |
------------------
------------------
Email | |
------------------
------------------
Message | |
| |
| |
------------------
*----------*
| Submit |
*----------*
```
---
:question: **Answer before continuing:** Where in the React component that renders this form would we store _the input of the user_ (name, email, message)?
:one: `this.state`
:two: `this.props`
:three: `window`
---
If you answered **state**, you'd be correct! Here's why:
- **State** is for managing this _current component's_ data at a certain point in time.
- **Props**, on the other hand, is for passing this current component data from a _parent_ component.
- We never want to store data on the global namespace (`window`).
Let's start off with a basic React component. You can create this in `src/pages/contact.js` - _recall that all components exported within the `src/pages` directory also become routes!_ In other words, this new component at `src/pages/contact.js` will be served at `/contact` on your website.
> **Note:** This might seem like an odd suggestion, but _don't_ copy and paste code from here to your files! Type it out - make sure you understand what's going on.
**`src/pages/contacts.js`**
```jsx
import React from 'react';
class ContactForm extends React.Component {
}
export default ContactForm;
```
The beginning of our contact form! Only a few things are happening here:
- Importing React - required for _all_ React components (even if you're not using the `class` syntax!
- Creating a class called `ContactForm` that inherits from React's `Component` class.
- Exporting our new class as the `default` export.
> <sub>**Hi, this is an optional sub-note. You can ignore this!** Curious as to what this `default` thing is? This is what allows us to import components from others as `import ContactForm from './ContactForm'` - this is actually identical to `import Duck from './ContactForm'` because it looks for the `default` export, not the name. [More information at MDN,](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) for the interested.</sub>
### :pencil: Adding form elements
Let's now add our text boxes and labels for the form into this component. Remember that to _display_ things from our React component, we need a `render` method implemented:
**`src/pages/contacts.js`**
```jsx
render() {
return (
<form>
<label for="name">Name</label>
<input type="text" id="name" />
</form>
);
}
```
Let's break down what's happening here, too:
- We created a `render` method, which is called every time React sees that this component's `props` or `state` has changed. This method tells us how to display this component in your browser.
- We rendered a `<form>` that includes a single `<label>` and `<input>` HTML element.
**Navigate to `localhost:8000/contact` to make sure this shows up!**
Nothing too exciting just yet - and not from React's perspective either.
Notice that we have nothing here that would inform React of what the _contents_ of this `<input>` are - we can't tell what the user typed in.
**Before you continue,** create two more sets of `<label>` and text box elements for Email and Message, as in our wireframe above. Set your `id` and `for` attributes appropriately!
> **A Handy Hint :tm:**: Use a `<textarea>` element instead of an `<input>` if you want a larger text box. `<textarea>` elements don't need a `type` attribute!
### :boom: Using event handlers
> **Before starting this section,** you should have a complete form as represented in the wireframe at `/contact` of your Gatsby site.
To now inform React of changes to our text boxes, we need to set "event handlers" on our `<input>` and `<textarea>` elements.
What does this mean? - it means that we need a **function** that responds to events emitted by these elements and is able to get some information about them (like their contents!). In this case, we are responding to an event called `onchange`, which is emitted by elements that take user input every time they are changed by a user. Let's start by defining one for our Name text box:
**`src/pages/contacts.js`**
```jsx
class ... {
onChangeEmail(event) {
console.log(event.target.value);
}
render() {
return (
...
// This is NOT a new input - change your
// existing Name text box and add this onChange
// prop.
<input
type="text"
id="name"
onChange={(event) => this.onChangeEmail(event)}
/>
...
// You should have more than this input
// here, but it is omitted to save space!
);
}
}
export ...
```
Let's talk about what's happening again here:
- We define a function called `onChangeEmail` within the `ContactForm` component. It takes a single argument called `event` that represents the [Event object](https://developer.mozilla.org/en-US/docs/Web/API/Event) that we receive from the emitted `onchange` event referenced above.
- `onChangeEmail` was defined to just log the value of `event.target.value`, which represents the current value of the `<input>` element that emitted this event.
- We added a prop called `onChange` to the `input` element (our Name text box). We passed in a **_function_** that takes an `event` parameter and passes it to the `onChangeEmail` function we defined.
Now, open DevTools in Chrome (by right-clicking and clicking "Inspect Element" or keying `Ctrl [Windows] / Command [Mac] -Shift - J`). Click into the Console tab if you aren't already in it.
Try typing into your Name text box, and see that what you typed in is logging inside the Console. We now see that React is being informed of changes to our Name text box!
**Before continuing, create event handlers for all of your text boxes.** You should see the value of each box log to the console.
### :aerial_tramway: Storing input values
We now have event handlers on our text boxes, which means we get updated every time our text boxes gets typed into. That's a great first step, but now, we need to do something beyond logging to the console. We need to _store_ the values of our inputs within the `state` of the `ContactForm` component (_remember the question asked at the beginning?_).
This is how we'll store it inside of the `state` object:
```javascript
// this.state is:
{
name: "John Denero",
email: "denero@berkeley.edu",
message: "How do I join Web Team?"
}
```
To do this, change the implementation of your `onChangeX` functions to look like:
**`src/pages/contacts.js`**
```jsx
onChangeEmail(event) {
this.setState({
email: event.target.value
});
}
```
Notice here that we're not directly modifying `this.state = [something]`! To change state from **_anywhere_** in our component (except for the `constructor`, which we're not using), we need to call `setState` so that the component knows to re-render using a new version of `state`.
Verify that `state` inside of your `ContactForm` is updating while you type by inspecting with the React tab inside of DevTools (don't have it? install [here](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en)).
**Hint:** you can use the eyedropper tool (shown below) to click on the `ContactForm` and see the `state` object in the sidebar:

**One last thing**: you might have thought that our `onChange` functions look awfully similar to define it for every one of our inputs. We can generalize this by using the ID of the `event.target` as the key to update in state! That looks like this:
```jsx
onChange(event) {
this.setState({
[event.target.id]: event.target.value
});
}
```
Don't forget to update the `onChange` props of your `<input>`s and `<textarea>` if you decide to do this!
### :cloud: Sending form contents
One last thing to make our form functional: actually allowing it to be submitted!
To accomplish this, first add a submit button within your form:
```jsx
<input type="submit" value="Send message" />
```
We will use another event handler to respond to the `onsubmit` event of our `<form>` element. Define that as follows:
**`src/pages/contacts.js`**
```jsx
class ... {
onSubmit(event) {
event.preventDefault();
fetch('https://untitled-7u6istdb7h9e.runkit.sh/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
})
.then((response) => {
if (!response.ok) throw new Error(response);
return response.json();
})
.then((response) => {
console.log(response);
alert('Sent successfully!');
})
.catch(err => console.error(err));
}
...
}
export ...
```
This is a lot of new code. Let's break down what we've done here:
- We've created a method inside of the `ContactForm` component called `onSubmit`. We intend it to be an event handler (for the `onsubmit` event), so we have it take an event object in parameters.
- We call `event.preventDefault()` to change the default behavior of what `onsubmit` causes. Try removing this line. What happens?
- In the method we define, we use `fetch` to send an external `POST` request to some endpoint (I defined the behavior of this endpoint beforehand).
- Within this request, we send a String representation of `this.state` (_what is in `this.state`_? Your form contents!)
- If the request succeeds, we parse the response as a JavaScript object with `response.json()` and then we log this object to the console and show an alert dialog to the user (saying "Sent successfully!").
- If the request fails, we also log the failure response to the console.
The next step is to call your `onSubmit` function in the `onSubmit` prop of your `<form>` element. Take a look at how we did that with `<input>`s and `onChange` if you're stuck.
**Finally, make sure that your request works!** You should be able to fill out a form, submit it, and see the response log successfully to the console. The response should be a mystery.
:mag: **Before you finish,** follow the mystery!
**_This is required to complete the rest of this lab._**
Place the mystery inside of the root of your project directory.
## Task 2: Pulling in dynamic data
Let's switch gears a little bit. Now, we want to use what we've learned about GraphQL to pull in data from a _mysterious_ source (Google Sheets) and render it in our site.
Begin by running `npm install --save gatsby-source-google-sheets` in your terminal (you may have to open another window if your Gatsby server is still active).
Edit `gatsby-config.js` to include this object in the `plugins` array:
```javascript
plugins: [
'gatsby-plugin-react-helmet',
// add this object:
{
resolve: 'gatsby-source-google-sheets',
options: {
spreadsheetId: '1J9tJQNVYoN64QbZjOMwpSmA62GWOehcUpgVeTDv6jNA',
worksheetTitle: 'mystery',
credentials: require("./InnoD\ Mystery-975d82e0c439.json")
}
}
]
```
Restart your Gatsby server (Ctrl-C will exit the running process) and head to `localhost:8000/___graphql` to access GraphiQL, an interface for browsing GraphQL data.
On the left is a box for typing in queries and getting responses back. Try writing one - here's a hint: Start with the following:
```jsx
{
googleSheetMysteryRow {
name
email
message
}
}
```
and play with it from here!
_... to be continued_
|
Python
|
UTF-8
| 293 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
import pygame
class Sprite:
def __init__(self, surface, bounds=None):
self.surface = surface
if bounds == None:
bounds = surface.get_rect()
bounds = pygame.Rect(bounds.left, bounds.top, bounds.width, bounds.height)
self.bounds = bounds
|
Python
|
UTF-8
| 1,635 | 2.828125 | 3 |
[] |
no_license
|
import sys
sys.setrecursionlimit(4100000)
import math
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
from itertools import permutations
def resolve():
N = [int(x) for x in sys.stdin.readline().split()][0]
p_list = [int(x) for x in sys.stdin.readline().split()]
q_list = [int(x) for x in sys.stdin.readline().split()]
logger.debug('{}'.format([N, p_list, q_list]))
perm = list(permutations(range(1, N + 1)))
a = perm.index(tuple(p_list))
b = perm.index(tuple(q_list))
print(abs(a - b))
if __name__ == "__main__":
resolve()
# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_入力例_1(self):
input = """3
1 3 2
3 1 2"""
output = """3"""
self.assertIO(input, output)
def test_入力例_2(self):
input = """8
7 3 5 4 2 1 6 8
3 8 2 5 4 6 7 1"""
output = """17517"""
self.assertIO(input, output)
def test_入力例_3(self):
input = """3
1 2 3
1 2 3"""
output = """0"""
self.assertIO(input, output)
|
Markdown
|
UTF-8
| 9,713 | 2.78125 | 3 |
[] |
no_license
|
# AzureCredentials
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Metadata** | Pointer to [**ConfigurationMetadata**](ConfigurationMetadata.md) | | [optional]
**Id** | Pointer to **string** | The Dynatrace entity ID of the Azure credentials configuration. | [optional] [readonly]
**Label** | **string** | The unique name of the Azure credentials configuration. Allowed characters are letters, numbers, and spaces. Also the special characters `.+-_` are allowed. |
**AppId** | **string** | The Application ID (also referred to as Client ID) The combination of Application ID and Directory ID must be unique. | [readonly]
**DirectoryId** | **string** | The Directory ID (also referred to as Tenant ID) The combination of Application ID and Directory ID must be unique. | [readonly]
**Key** | Pointer to **string** | The secret key associated with the Application ID. For security reasons, GET requests return this field as `null`. Submit your key on creation or update of the configuration. If the field is omitted during an update, the old value remains unaffected. | [optional]
**Active** | Pointer to **bool** | The monitoring is enabled (`true`) or disabled (`false`). If not set on creation, the `true` value is used. If the field is omitted during an update, the old value remains unaffected. | [optional]
**AutoTagging** | **bool** | The automatic capture of Azure tags is on (`true`) or off (`false`). |
**MonitorOnlyTaggedEntities** | **bool** | Monitor only resources that have specified Azure tags (`true`) or all resources (`false`). |
**MonitorOnlyTagPairs** | [**[]CloudTag**](CloudTag.md) | A list of Azure tags to be monitored. You can specify up to 10 tags. A resource tagged with *any* of the specified tags is monitored. Only applicable when the **monitorOnlyTaggedEntities** parameter is set to `true`. |
**SupportingServices** | Pointer to [**[]AzureSupportingService**](AzureSupportingService.md) | A list of Azure supporting services to be monitored. For each service there's a sublist of its metrics and the metrics' dimensions that should be monitored. All of these elements (services, metrics, dimensions) must have corresponding static definitions on the server. | [optional]
## Methods
### NewAzureCredentials
`func NewAzureCredentials(label string, appId string, directoryId string, autoTagging bool, monitorOnlyTaggedEntities bool, monitorOnlyTagPairs []CloudTag, ) *AzureCredentials`
NewAzureCredentials instantiates a new AzureCredentials object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed
### NewAzureCredentialsWithDefaults
`func NewAzureCredentialsWithDefaults() *AzureCredentials`
NewAzureCredentialsWithDefaults instantiates a new AzureCredentials object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set
### GetMetadata
`func (o *AzureCredentials) GetMetadata() ConfigurationMetadata`
GetMetadata returns the Metadata field if non-nil, zero value otherwise.
### GetMetadataOk
`func (o *AzureCredentials) GetMetadataOk() (*ConfigurationMetadata, bool)`
GetMetadataOk returns a tuple with the Metadata field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMetadata
`func (o *AzureCredentials) SetMetadata(v ConfigurationMetadata)`
SetMetadata sets Metadata field to given value.
### HasMetadata
`func (o *AzureCredentials) HasMetadata() bool`
HasMetadata returns a boolean if a field has been set.
### GetId
`func (o *AzureCredentials) GetId() string`
GetId returns the Id field if non-nil, zero value otherwise.
### GetIdOk
`func (o *AzureCredentials) GetIdOk() (*string, bool)`
GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetId
`func (o *AzureCredentials) SetId(v string)`
SetId sets Id field to given value.
### HasId
`func (o *AzureCredentials) HasId() bool`
HasId returns a boolean if a field has been set.
### GetLabel
`func (o *AzureCredentials) GetLabel() string`
GetLabel returns the Label field if non-nil, zero value otherwise.
### GetLabelOk
`func (o *AzureCredentials) GetLabelOk() (*string, bool)`
GetLabelOk returns a tuple with the Label field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetLabel
`func (o *AzureCredentials) SetLabel(v string)`
SetLabel sets Label field to given value.
### GetAppId
`func (o *AzureCredentials) GetAppId() string`
GetAppId returns the AppId field if non-nil, zero value otherwise.
### GetAppIdOk
`func (o *AzureCredentials) GetAppIdOk() (*string, bool)`
GetAppIdOk returns a tuple with the AppId field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetAppId
`func (o *AzureCredentials) SetAppId(v string)`
SetAppId sets AppId field to given value.
### GetDirectoryId
`func (o *AzureCredentials) GetDirectoryId() string`
GetDirectoryId returns the DirectoryId field if non-nil, zero value otherwise.
### GetDirectoryIdOk
`func (o *AzureCredentials) GetDirectoryIdOk() (*string, bool)`
GetDirectoryIdOk returns a tuple with the DirectoryId field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetDirectoryId
`func (o *AzureCredentials) SetDirectoryId(v string)`
SetDirectoryId sets DirectoryId field to given value.
### GetKey
`func (o *AzureCredentials) GetKey() string`
GetKey returns the Key field if non-nil, zero value otherwise.
### GetKeyOk
`func (o *AzureCredentials) GetKeyOk() (*string, bool)`
GetKeyOk returns a tuple with the Key field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetKey
`func (o *AzureCredentials) SetKey(v string)`
SetKey sets Key field to given value.
### HasKey
`func (o *AzureCredentials) HasKey() bool`
HasKey returns a boolean if a field has been set.
### GetActive
`func (o *AzureCredentials) GetActive() bool`
GetActive returns the Active field if non-nil, zero value otherwise.
### GetActiveOk
`func (o *AzureCredentials) GetActiveOk() (*bool, bool)`
GetActiveOk returns a tuple with the Active field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetActive
`func (o *AzureCredentials) SetActive(v bool)`
SetActive sets Active field to given value.
### HasActive
`func (o *AzureCredentials) HasActive() bool`
HasActive returns a boolean if a field has been set.
### GetAutoTagging
`func (o *AzureCredentials) GetAutoTagging() bool`
GetAutoTagging returns the AutoTagging field if non-nil, zero value otherwise.
### GetAutoTaggingOk
`func (o *AzureCredentials) GetAutoTaggingOk() (*bool, bool)`
GetAutoTaggingOk returns a tuple with the AutoTagging field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetAutoTagging
`func (o *AzureCredentials) SetAutoTagging(v bool)`
SetAutoTagging sets AutoTagging field to given value.
### GetMonitorOnlyTaggedEntities
`func (o *AzureCredentials) GetMonitorOnlyTaggedEntities() bool`
GetMonitorOnlyTaggedEntities returns the MonitorOnlyTaggedEntities field if non-nil, zero value otherwise.
### GetMonitorOnlyTaggedEntitiesOk
`func (o *AzureCredentials) GetMonitorOnlyTaggedEntitiesOk() (*bool, bool)`
GetMonitorOnlyTaggedEntitiesOk returns a tuple with the MonitorOnlyTaggedEntities field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMonitorOnlyTaggedEntities
`func (o *AzureCredentials) SetMonitorOnlyTaggedEntities(v bool)`
SetMonitorOnlyTaggedEntities sets MonitorOnlyTaggedEntities field to given value.
### GetMonitorOnlyTagPairs
`func (o *AzureCredentials) GetMonitorOnlyTagPairs() []CloudTag`
GetMonitorOnlyTagPairs returns the MonitorOnlyTagPairs field if non-nil, zero value otherwise.
### GetMonitorOnlyTagPairsOk
`func (o *AzureCredentials) GetMonitorOnlyTagPairsOk() (*[]CloudTag, bool)`
GetMonitorOnlyTagPairsOk returns a tuple with the MonitorOnlyTagPairs field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetMonitorOnlyTagPairs
`func (o *AzureCredentials) SetMonitorOnlyTagPairs(v []CloudTag)`
SetMonitorOnlyTagPairs sets MonitorOnlyTagPairs field to given value.
### GetSupportingServices
`func (o *AzureCredentials) GetSupportingServices() []AzureSupportingService`
GetSupportingServices returns the SupportingServices field if non-nil, zero value otherwise.
### GetSupportingServicesOk
`func (o *AzureCredentials) GetSupportingServicesOk() (*[]AzureSupportingService, bool)`
GetSupportingServicesOk returns a tuple with the SupportingServices field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.
### SetSupportingServices
`func (o *AzureCredentials) SetSupportingServices(v []AzureSupportingService)`
SetSupportingServices sets SupportingServices field to given value.
### HasSupportingServices
`func (o *AzureCredentials) HasSupportingServices() bool`
HasSupportingServices returns a boolean if a field has been set.
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
Markdown
|
UTF-8
| 751 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
# HAgnostic News
HAgnostic News is an Hacker News reader which is available for the Web and as React Native app (Android / iOS)

From the same codebase you can render apps for the platform Web and natively for Android and iOS. Thanks to [React Native](https://facebook.github.io/react-native/) and [React Native Web](https://github.com/necolas/react-native-web).
### Web
```
npm run start
```
or [Live](https://grigio.github.io/HAgnostic-News/)
### Android
```
react-native run-android
```
or Download from the [Play Store](https://play.google.com/store/apps/details?id=com.hagnosticnews)
### iOS
```
react-native run-ios
```
|
PHP
|
UTF-8
| 1,455 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
namespace app\common\model;
class VipPayLogModel extends BaseModel
{
/**
* 定义别名字段
* @var array
*/
public static $alia = [
'pay_type'=>[
1=>'微信',
2=>'支付宝',
3=>'其他',
],
];
public function getPayTypeAttr($value)
{
return isset(self::$alia['pay_type'])?self::$alia['pay_type'][$value]:'';
}
/**
*获取列表信息
* @param $input
* @param string $field
* @return array
*/
public static function getList($input,$field=''){
try{
$default = [
'sort'=>'id',
'order'=>'desc',
'offset'=>0,
'limit'=>null,
];
$input = array_merge($default,$input);
$field = !empty($field)?$field:'*';
$customer = self::field($field);
if(isset($input['customer_id'])){
$customer->where(['customer_id'=>$input['customer_id']]);
}
$customer->order($input['sort'],$input['order']);
$customer->limit($input['offset'],$input['limit']);
$rows = $customer->select();
$count = $customer->count();
return ['code'=>1,'total' => $count,'rows'=>$rows];
}catch(\Exception $e) {
return array('code' => 0, 'rows' => [], 'msg' => $e->getMessage());
}
}
}
|
Java
|
UTF-8
| 903 | 2.03125 | 2 |
[] |
no_license
|
package com.fsd.stock.exchange.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.fsd.stock.exchange.entity.StockExchange;
@Mapper
public interface ExchangeMapper {
@Insert("insert into fsdsba.stockexchange(stockExchangesId,stockExchangeBrief,contactAddress,remarks) values(#{stockExchangesId},#{stockExchangeBrief},#{contactAddress},#{remarks})")
void addExchange(StockExchange exchange);
@Select("SELECT count(*) FROM fsdsba.stockexchange where stockExchangesId=#{stockExchangesId}")
Integer checkExchange(@Param("stockExchangesId") String stockExchangesId);
@Select("SELECT stockExchangesId,stockExchangeBrief,contactAddress,remarks FROM fsdsba.stockexchange")
List<StockExchange> getStockExchangesList();
}
|
Java
|
UTF-8
| 544 | 3.015625 | 3 |
[] |
no_license
|
import java.util.Scanner;
public class UVAOJ10963 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int T=sc.nextInt();
while(T>0) {
int col=sc.nextInt();
int a=sc.nextInt();
int b=sc.nextInt();
int dY=Math.abs(a-b);
boolean flag=true;
for(int i=1; i<col; i++) {
a=sc.nextInt();
b=sc.nextInt();
if(dY!=Math.abs(a-b)) flag=false;
}
if(flag)System.out.println("yes");
else System.out.println("no");
T--;
if(T!=0) System.out.println();
}
sc.close();
}
}
|
Python
|
UTF-8
| 1,314 | 3.15625 | 3 |
[] |
no_license
|
from math import pi, cos, sin, sqrt, radians
import matplotlib.pyplot as plt
class Particle:
def __init__(self, v0, alfa, x0, y0):
self.v0 = v0
self.alfa = radians(alfa)
self.x = x0
self.y = y0
self.x_ = []
self.y_ = []
self.x_.append(x0)
self.y_.append(y0)
self.vx = v0 * cos(self.alfa)
self.vy = v0 * sin(self.alfa)
self.t = 0
self.vy_ = []
def printInfo(self):
print(self.v0,self.alfa,self.x,self.y)
def reset(self):
self.v0 = 0
self.alfa = 0
self.x0 = 0
self.y0 = 0
self.x_ = []
self.y_ = []
self.vy_ = []
def __move(self, dt):
self.x = self.x + self.vx * dt
self.vy = self.vy - 9.81 * dt
self.y = self.y + self.vy * dt
self.x_.append(self.x)
self.y_.append(self.y)
self.vy_.append(self.vy)
def range(self,dt):
x = self.x
while True:
self.__move(dt)
if self.y <= 0:
break
return self.x - x
def plotTrajectory(self):
plt.plot(self.x_,self.y_)
plt.show()
def analitickoRacunanje(self):
domet = (self.v0**2*sin(2*self.alfa))/9.81
return domet
|
Python
|
UTF-8
| 696 | 3.28125 | 3 |
[] |
no_license
|
import time
# Sums from bottom are same as sums from top
# Do partial sums from second to last row, get largest sum when you reach the top.
def largestSum(tri, rowIndex):
for i, val in enumerate(tri[rowIndex]):
tri[rowIndex][i] += max([tri[rowIndex + 1][i], tri[rowIndex + 1][i + 1]])
if rowIndex == 0:
return tri[rowIndex][0]
else:
return largestSum(tri, rowIndex - 1)
start = time.time()
triang = []
with open('p18.txt') as f:
d = f.read().splitlines()
for line in d:
triang.append([int(i) for i in line.split()])
l = largestSum(triang, len(triang) - 2)
elapsed = time.time() - start
print l
print "%s seconds elapsed" % elapsed
|
Python
|
UTF-8
| 984 | 3.296875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 20:28:43 2020
@author: Niranch
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
inputlist=[]
mydict={}
for line in sys.stdin:
if 'Exit' == line.rstrip():
break
else:
inputlist.append(line.rstrip())
if(len(inputlist)>=1):
itemsCnt=int(inputlist[0])
inputlist.pop(0)
j=1
#Creating and Adding values to the dictionary Object
if itemsCnt>=1 and itemsCnt<=100000:
if len(inputlist)<=100000 and len(inputlist)>=1:
for i in inputlist:
if(j<=itemsCnt):
s=i.split(" ")
mydict[s[0]]=s[1]
j+=1
#Getting values from dictionary Object for given input
checklist = inputlist[itemsCnt:]
for i in checklist:
if i in mydict:
print(i+"="+mydict[i])
else:
print("Not found")
|
Python
|
UTF-8
| 7,478 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import webbrowser
import os
import re
# Styles and scripting for the page
# Note the sized up YT vids, with extra parameters (like
# removing related videos) for a more cinematic feel
main_page_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sagar's Top 6 Media</title>
<!-- Bootstrap 3 -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<style type="text/css" media="screen">
body {
padding-top: 80px;
background-color: #464646;
font-family: serif;
}
#trailer .modal-dialog {
margin-top: 100px;
width: 960px;
height: 720px;
}
.hanging-close {
position: absolute;
top: -13px;
right: -13px;
z-index: 9001;
}
#trailer-video {
width: 100%;
height: 100%;
}
.media-tile {
margin-bottom: 20px;
padding-top: 20px;
color: #ABAAAA;
}
.media-tile:hover {
background-color: #7F7E7E;
cursor: pointer;
color: #464646;
}
.scale-media {
padding-bottom: 56.25%;
position: relative;
}
.scale-media iframe {
border: none;
height: 100%;
position: absolute;
width: 100%;
left: 0;
top: 0;
background-color: #464646;
}
</style>
<script type="text/javascript" charset="utf-8">
// Pause the video when the modal is closed
$(document).on('click',
'.hanging-close, .modal-backdrop, .modal',
function (event) {
// Remove the src so the player itself gets removed, as this is
// the only reliable way to ensure the video stops playing in IE
$("#trailer-video-container").empty();
});
// Start playing the video whenever the trailer modal is opened
$(document).on('click', '.media-tile', function (event) {
var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')
var parametersYouTube = '?autoplay=1&html5=1&controls=1'
+ '&disablekb=1&modestbranding=1'
+ '&rel=0&showinfo=0'
var sourceUrl = 'http://www.youtube.com/embed/'
+ trailerYouTubeId
+ parametersYouTube;
$("#trailer-video-container").empty().append($("<iframe></iframe>", {
'id': 'trailer-video',
'type': 'text-html',
'src': sourceUrl,
'frameborder': 0
}));
});
// Animate in the media when the page loads
$(document).ready(function () {
$('.media-tile').hide().first().show("medium", function showNext() {
$(this).next("div").show("medium", showNext);
});
});
</script>
</head>
'''
# Main page layout + extra navbar links
main_page_content = '''
<body>
<!-- Trailer Video Modal -->
<div class="modal" id="trailer">
<div class="modal-dialog">
<div class="modal-content">
<a href="#" class="hanging-close"
data-dismiss="modal" aria-hidden="true">
<img src="https://goo.gl/jYv1iy"/>
</a>
<div class="scale-media" id="trailer-video-container">
</div>
</div>
</div>
</div>
<!-- Main Page Content -->
<div class="container">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="{movie_link}">Top 6 Movies</a>
<a class="navbar-brand" href="{game_link}">Top 6 Games</a>
</div>
</div>
</div>
</div>
<div class="container">
{media_tiles}
</div>
</body>
</html>
'''
# Template for each movie/game tile
media_tile_content = '''
<div class="col-md-6 col-lg-4 media-tile text-center"
data-trailer-youtube-id="{trailer_youtube_id}"
data-toggle="modal" data-target="#trailer">
<img src="{poster_image_url}" width="220" height="342">
<h2>{media_title}</h2>
</div>
'''
# This function is subordinate to render_content()
def create_media_tiles_content(media):
# The HTML content for this section of the page
content = ''
# 1st half == grabbing the YT ID for each movie or game
for item in media:
youtube_id_match = re.search(
r'(?<=v=)[^&#]+', item.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(
r'(?<=be/)[^&#]+', item.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match
else None)
# 2nd half == Filling in cover art for each movie or game, appending
# each one to the previous to make a monster-sized 'content' var
content += media_tile_content.format(
media_title=item.title,
poster_image_url=item.poster_image_url,
trailer_youtube_id=trailer_youtube_id)
return content # This sends ALL media tiles back
# This function is subordinate to main()
def render_content(media, holder):
# Easier to understand and remember if I replicate the 'name'
# variable here rather than set as global variable at top of file
name = media[0].__class__.__name__.lower()
# This fills in the guts of the site with all media tiles, plus the
# two navbar links, which need to be on each page for, well, navigation
rendered_content = main_page_content.format(
media_tiles=create_media_tiles_content(media),
movie_link=holder['movie']['url'],
game_link=holder['game']['url'])
# Recreates the page each time, closing it when complete
holder[name]['output_file'].write(main_page_head + rendered_content)
holder[name]['output_file'].close()
return # No need to send holder back, as it hasn't been changed
# This function is subordinate to main()
def build_dict(media, holder):
# Defining critical variables
name = media[0].__class__.__name__.lower()
output_file = open(name + '.html', 'w')
url = 'file://' + os.path.abspath(output_file.name)
# Placing those vars in a dict of dicts for easy (and,
# more importantly, simple) access later on.
holder[name] = {}
holder[name]['output_file'] = output_file
holder[name]['url'] = url
return holder
# The big mama function
def main(movies, games):
# Set up dict outside build_dict function so it keeps growing
holder = {}
build_dict(movies, holder)
build_dict(games, holder)
# Need two calls to create two separate pages
render_content(movies, holder)
render_content(games, holder)
# The site is now built. This last line just uses our good friend
# webbrowser to open it in a new tab, defaulting to the movies page
webbrowser.open(holder['movie']['url'], new=2)
|
Markdown
|
UTF-8
| 799 | 2.546875 | 3 |
[] |
no_license
|
# Graph Theory Comprehensive Notes
This repository contains a collection of theorems and sample problems
for the graph theory originally targetting the comprehensive exam at
Arizona State University. Most of the theorems are found in Diestel's
Graph Theory and when a theorem number is mentioned, that number
refers to the 3rd edition. Most of the proofs that are provided are
generally similar to proofs in Diestel's Graph Theory or West's
Introduction to Graph Theory. This document is somewhat incomplete,
some proofs are missing, some proofs are better described as proof
summaries, and the occasional proof may be
incorrect. Corrections/additions/improvements to this document are
welcome and can be submitted to this documents GitHub page located at
https://github.com/rjoursler/graph_notes.
|
Java
|
UTF-8
| 1,872 | 4.3125 | 4 |
[] |
no_license
|
package hw5;
/**
* RPN calculator supporting addition, subtraction and multiplication
* of anything that implements the CalculatorOperand interface
*/
public class RPNCalculator<T extends CalculatorOperand<T>> {
ListStack<T> stack; // the stack holding the operands
/**
* Defines the operations the calculator can perform
*/
static public enum OperationType {ADD, SUBTRACT, MULTIPLY}; //enum: lets the user decide its own type.
/**
* Constructor
*/
public RPNCalculator () {
stack = new ListStack<T>();
}
/**
* Pushes the operand on the calculator stack
*/
public void operand (T value) {
// TODO: IMPLEMENT
stack.push(value);
}
/**
* Performs an operation on the two topmost elements of the stack
* If t2 is topmost and t1 is second topmost, then t1 and t2 will be removed
* from the stack and (t1 op t2) will be placed on top of the stack.
* Does not modify the stack if it contains fewer than two elements.
*/
public void operation (OperationType operation) {
// TODO: IMPLEMENT
if(stack.isEmpty()){
return; //no need to return anything since its void.
}
T operand2= stack.pop();
if(stack.isEmpty()) {
stack.push(operand2);
return;
}
T operand1= stack.pop();
T result = null;
if (operation== OperationType.ADD) {
result = operand1.add(operand2);
}
else if(operation== OperationType.SUBTRACT) {
result= operand1.subtract(operand2);
}
else if(operation== OperationType.MULTIPLY) {
result= operand1.multiply(operand2);
}
stack.push(result);
}
/**
* Prints the calculator stack
*/
public String toString() {
if (stack.isEmpty()) {
return "Empty stack\n";
}
else {
return stack.toString();
}
}
}
|
C++
|
UTF-8
| 5,519 | 2.734375 | 3 |
[] |
no_license
|
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class Robot_part{
public:
Robot_part(string part_name, int model_number, double cost, string description, string image_filename, double head_power, double loco_max_power,
int battery_comp, int max_arms, double arm_max_power, double bat_power, double max_energy)
: name(part_name), number(model_number), price(cost), descript(description), file(image_filename), h_pow(head_power), loco_pow(loco_max_power),
bat_com(battery_comp), max_arm(max_arms), arm_pow(arm_max_power), bat_pow(bat_power), energy(max_energy) {}
Robot_part() : name("unknown"), number(0), price(0.00), descript("unknown"), file("unknown"), h_pow(0), loco_pow(0), bat_com(0),
max_arm(0), arm_pow(0), bat_pow(0), energy(0) {}
string get_name();
string get_descript();
string get_file();
int get_number();
double get_price();
string head_to_string();
private:
string name;
string descript;
string file;
int number;
double price;
double h_pow;
double loco_pow;
int bat_com;
int max_arm;
double arm_pow;
double bat_pow;
double energy;
};
string Robot_part::get_name() {return name;}
string Robot_part::get_descript() {return descript;}
string Robot_part::get_file() {return file;}
int Robot_part::get_number() {return number;}
double Robot_part::get_price() {return price;}
string Robot_part::head_to_string(){
string part = "part name: " + name +"\n"+ "part number: " + std::to_string(number) +"\n" + "price: " + std::to_string(price) +"\n"+
"description: " + descript +"\n"+ "filename: " + file +"\n"+ "Head power: " + std::to_string(h_pow) +"\n" /*+ "locomotor power:"+
std::to_string(loco_pow) + std::to_string(bat_com) + std::to_string(max_arm) + std::to_string(arm_pow) +
std::to_string(bat_pow) + std::to_string(energy)*/;
return part;
}
/*class Head{
public:
Head(double h_power, Robot_part& Headpart) : power(h_power), Headpart(Headpart) { }
string to_string();
private:
double power;
Robot_part& Headpart;
};
*/
// /////////////////////////////////////
// L I B R A R Y
// /////////////////////////////////////
class Library {
public:
void add_part(Robot_part part);
void easter_egg();
int number_of_models();
string hed_to_string(int part_index);
private:
vector<Robot_part> parts;
};
void Library::add_part(Robot_part part) {
parts.push_back(part);
}
string Library::hed_to_string(int part_index) {
return parts[part_index].head_to_string();
}
void Library::easter_egg() {
}
int Library::number_of_models() {
return parts.size();
}
// /////////////////////////////////////
// V I E W
// /////////////////////////////////////
class View {
public:
View(Library& lib) : library(lib) { }
string get_menu();
string get_model_list();
private:
Library& library;
};
string View::get_menu() {
string menu = R"(
===============================
Robot Parts Shop
===============================
Robots
------------
(1) Create Part
(2) Create Model
(3) Print Model
(0) Exit
)";
return menu;
}
string View::get_model_list() {
string list = R"(
----------------------------
List of Models
----------------------------
)";
for (int i=0; i<library.number_of_models(); ++i) {
list += std::to_string(i) + ") " + library.hed_to_string(i) + '\n';
}
return list;
}
// /////////////////////////////////////
// C O N T R O L L E R
// /////////////////////////////////////
class Controller {
public:
Controller (Library& lib, View& view) : library(lib), view(view) { }
void cli();
void execute_cmd(int cmd);
private:
int get_int(string prompt);
double get_double(string prompt);
Library& library;
View& view;
};
void Controller::cli() {
int cmd = -1;
while (cmd != 0) {
cout << view.get_menu() << endl;
cout << "Command? ";
cin >> cmd;
cin.ignore(); // consume \n
execute_cmd(cmd);
}
}
int Controller::get_int(string prompt) {
int result;
cout << prompt;
cin >> result;
cin.ignore(); // consume \n
return result;
}
double Controller::get_double(string prompt) {
double result;
while(true) {
cout << prompt;
cin >> result;
cin.ignore(); // consume \n
if (0 <= result) break;
cout << "Please enter a double greater than 0 " << endl;
}
return result;
}
void Controller::execute_cmd(int cmd) {
if (cmd == 1) { // Add part
string part_name, description, filename;
int number, type, bat_com, max_arm;
double cost, h_pow, loco_pow, arm_pow, bat_pow, energy;
type = get_int("1: Head \n2: locomotor\n3: torso\n4: Battery\n5: Arm\nPart Type:");
cout << "Part Name? ";
getline(cin, part_name);
cout << "Description? ";
getline(cin, description);
cout << "Image filename? ";
getline(cin, filename);
number = get_int("Part number? ");
cost = get_double("Cost? ");
if(type == 1){
h_pow = get_double("Head Power? ");
Robot_part part(part_name, number, cost, description, filename, h_pow, 0, 0, 0, 0, 0, 0);
library.add_part(part);
}
} else if (cmd == 3) { // List all models
cout << view.get_model_list();
}
}
int main() {
Library library;
View view{library};
Controller controller(library, view);
controller.cli();
/*
Robot_part part("test part", 1100001, 4.20, "this is a test part", "testpart.file");
Head head(2.50, part);
cout << head.to_string(); */
}
|
Python
|
UTF-8
| 166 | 3.140625 | 3 |
[] |
no_license
|
# import heap class
from 03-min_heap import MinHeap
min_heap = MinHeap()
print(min_heap.heap_list)
# testing out .add()
min_heap.add(42)
print(min_heap.heap_list)
|
Shell
|
UTF-8
| 984 | 3.78125 | 4 |
[] |
no_license
|
# alias-tips 太慢了, you-shoudle-use 不会展开已有别名
ALIAS_TIPS_BUFFER=''
function init_alias_list() {
typeset -g -A alias_list
(( $#alias_list != 0 )) && return
local k v cmds
for k v (${(kv)aliases}) {
expand_alias cmds ${(z)v}
alias_list[$k]=$cmds
}
}
function _check_alias() {
local expand="${(z)3}"
local result tmp k v
init_alias_list
for k v (${(kv)alias_list}) {
if [[ $expand == "$v "* || $expand == $v ]] {
tmp=${expand/$v/$k}
if (( $#tmp < $#result || ! $#result )) {
result=$tmp
}
}
}
if (( ${#${1%% #}} > $#result )) {
ALIAS_TIPS_BUFFER=$result
}
}
function _show_alias_tips() {
if [[ -n $ALIAS_TIPS_BUFFER ]] {
print -P "%B%F{yellow}Tips: you can use %f%K{011}%F{016}\$ALIAS_TIPS_BUFFER%f%k%b"
}
ALIAS_TIPS_BUFFER=
}
add-zsh-hook preexec _check_alias
add-zsh-hook precmd _show_alias_tips
|
C#
|
UTF-8
| 1,066 | 3.421875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GOTI
{
class Program
{
static void Main(string[] args)
{
string phrase = "cdefghmnopqrstuvw";
string result = GameOfThrones(phrase);
Console.WriteLine("The result is {0}", result);
Console.ReadLine();
}
static string GameOfThrones(string phrase)
{
string result = "YES";
int[] letterCounts = new int[26];
foreach (char c in phrase)
{
letterCounts[c - 'a']++;
}
int numberOfOdds = 0;
foreach (int count in letterCounts)
{
if (count % 2 != 0)
numberOfOdds++;
if (numberOfOdds > 1)
{
result = "NO";
break;
}
}
return result;
}
}
}
|
JavaScript
|
UTF-8
| 359 | 2.53125 | 3 |
[] |
no_license
|
const http = require('http');
const through = require('through2');
const uppercaser = through(function(buf, _, next){
this.push(buf.toString().toUpperCase());
next();
});
const port = Number(process.argv[2]);
const server = http.createServer((req, res)=>{
if(req.method === 'POST')
req.pipe(uppercaser).pipe(res);
});
server.listen(port);
|
Java
|
UTF-8
| 805 | 3.375 | 3 |
[] |
no_license
|
package com.wsss.basic.common;
class A {
public static void show() {
System.out.println("Class A show() function");
}
}
class B extends A {
public static void show() {
System.out.println("Class B show() function");
}
}
public class ClassDemo {
public static void main(String[] args) {
ClassDemo cls = new ClassDemo();
Class c = cls.getClass();
System.out.println("1:" + c);
Object obj = new A();
B b1 = new B();
b1.show();
// casts object
Object a = B.class.cast(obj);
System.out.println("2:" + obj.getClass());
System.out.println("3:" + b1.getClass());
System.out.println("4:" + a.getClass());
}
}
|
Markdown
|
UTF-8
| 5,064 | 3.921875 | 4 |
[
"MIT"
] |
permissive
|
### Solution
The prize is always undefined!
#### The Problem
The anonymous method we're assigning to the buttons' onclicks has access to variables in the scope
outside of it (this is called a closure). In this case, it has access to btnNum.
When a method accesses a variable outside its scope, it accesses that variable, not a frozen copy.
So when the value held by the variable changes, the method gets that new value. By the time the
user starts pressing buttons, our loop will have already completed and btnNum will be 3, so this
is what each of our anonymous methods will get for btnNum!
Why 3? The for loop will increment btnNum until the conditional in the middle is no longer met —
that is, until it's not true that btnNum < prizes.length. So the code in the for loop won't run
with btnNum = 3, but btnNum will be 3 when the loop is done.
Why undefined? prizes has 3 elements, but they are at indices 0, 1, 2. Array indices start at 0,
remember? In JavaScript, accessing a nonexistent index in an array returns undefined.
#### The Solution
We can solve this by wrapping our anonymous method in another anonymous method that takes btnNum as
an argument. Like so:
```html
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<script type="text/javascript">
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
// for each of our buttons, when the user clicks it...
document.getElementById('btn-' + btnNum).onclick = function(frozenBtnNum){
return function() {
// tell her what she's won!
alert(prizes[frozenBtnNum]);
};
}(btnNum); // LOOK! We're passing btnNum to our anonymous function here!
}
</script>
```
This "freezes" the value of btnNum. Why? Well...
#### Primitives vs. Objects
btnNum is a number, which is a primitive type in JavaScript.
Primitives are "simple" data types (string, number, boolean, null, and undefined in JavaScript).
Everything else is an object in JavaScript (methods, arrays, Date() values, etc).
#### Arguments Passed by Value vs. Arguments Passed by Reference
One important property of primitives in JS is that when they are passed as arguments to a method,
they are copied ("passed by value"). So for example:
```javascript
var threatLevel = 1;
function inspireFear(threatLevel){
threatLevel += 100;
}
inspireFear(threatLevel);
console.log(threatLevel); // Whoops! It's still 1!
```
The threatLevel inside inspireFear() is a new number, initialized to the same value as the
threatLevel outside of inspireFear(). Giving these different variables the same name might cause
confusion here. If we change the two variables to have different names we get the exact same
behavior:
```javascript
var threatLevel = 1;
function inspireFear(theThreatLevel){
theThreatLevel += 100;
}
inspireFear(threatLevel);
console.log(threatLevel); // Whoops! It's still 1!
```
In contrast, when a method takes an object, it actually takes a reference to that very object. So
changes you make to the object in the method persist after the method is done running. This is
sometimes called a side effect.
```javascript
var scaryThings = ['spiders', 'Cruella de Vil'];
function inspireFear(scaryThings){
scaryThings.push('nobody ever using Interview Cake');
scaryThings.push('i should have gotten a real job');
scaryThings.push('why am i doing this to myself');
}
inspireFear(scaryThings);
console.log(scaryThings);
// ['spiders', 'Cruella de Vil', 'nobody ever using Interview Cake', 'i should have gotten a real job', 'why am i doing this to myself']
```
#### Bringing it home
Back to our solution:
```html
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<script type="text/javascript">
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
// for each of our buttons, when the user clicks it...
document.getElementById('btn-' + btnNum).onclick = function(frozenBtnNum){
return function() {
// tell her what she's won!
alert(prizes[frozenBtnNum]);
};
}(btnNum);
}
</script>
```
So when we pass btnNum to the outer anonymous method as its one argument, we create a new number
inside the outer anonymous method called frozenBtnNum that has the value that btnNum had at that
moment (0, 1, or 2).
Our inner anonymous method is still a closure because it still reaches outside its scope, but now
it closes over this new number called frozenBtnNum, whose value will not change as we iterate
through our for loop.
### What We Learned
Like several common Javascript interview questions, this question hinges on a solid understanding
of closures and pass by reference vs pass by value. If you're shaky on either of those, look back
at the examples in the solution.
|
Shell
|
UTF-8
| 472 | 3.484375 | 3 |
[] |
no_license
|
#!/usr/bin/env bash
if [[ $UID != 0 ]]; then
echo "Please run this script with sudo:"
echo "sudo $0 $*"
exit 1
fi
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
apt update
apt install software-properties-common
apt-add-repository --yes --update ppa:ansible/ansible
apt install ansible
chown -R $SUDO_USER:$SUDO_USER $DIR
find $DIR -type d -exec chmod 0755 {} \;
find $DIR -type f -exec chmod 0644 {} \;
chmod 0744 $DIR/bootstrap.sh
|
Markdown
|
UTF-8
| 1,174 | 3.09375 | 3 |
[] |
no_license
|
---
_id: "luogu-P1082"
title: "P1082 同余方程"
date: 2020-01-05 15:56
update: 2020-01-05 15:56
author: Rainboy
tags:
- exgcd
- 数论
- 同余
- 提高组
- noip
- 2012
catalog: 数论
source:
-
oj: luogu
url: https://www.luogu.com.cn/problem/P1082
---
## 解析
题目地址:[luogu P1082 同余方程](https://www.luogu.org/problemnew/show/P1082)
**解析:**
$a \cdot x \equiv 1 (\bmod b)$推导出$a \cdot x \% b = 1$,这就是**乘法逆元**,进而推导出:$a \cdot x - b \cdot y = 1$,
也就是$a \cdot x + b \cdot y =1$,让我们求出最小正整数解.
**代码**
```c
#include <cstdio>
#include <cstring>
#include <cmath>
int exgcd(int a,int b,int &x,int &y){//ax+by=gcd(a,b)
if(b==0){x=1,y=0;return a;}
int gcd=exgcd(b,a%b,x,y);
int _x=x;
x=y;
y=_x-(a/b)*y;
/*
int gcd=exgcd(b,a%b,y,x);
y-=(a/b)*x;
*/
return gcd;
}
int main(){
int n,m;
scanf("%d%d",&n,&m);
int x,y;
int t = exgcd(n,m,x,y);
int m1 = m / t; //根据题意,m1 一定是正数
if( x >= 0)
printf("%d\n",x % m1);
else
printf("%d\n",(x % m1) + m1);
return 0;
}
```
|
Markdown
|
UTF-8
| 6,402 | 3.5 | 4 |
[] |
no_license
|
# 如何用余弦定理来进行文本相似度的度量 - Magician的博客 - CSDN博客
2018年06月22日 16:27:00[春雨里de太阳](https://me.csdn.net/qq_16633405)阅读数:612
在做文本分析的时候,**经常会到说将文本转化为对应的向量,之后利用余弦定理来计算文本之间的相似度**。但是最近在面试时,重复上面这句话,却被面试官问到:“什么是余弦定理?”当时就比较懵逼,于是把余弦定理求文本相似度的过程叙述了一遍:“**将样本转化为对应的空间中的两个向量,然后计算两个向量余弦值,之后根据余弦值的大小来判断两个样本相似度有多少**”,但是话音刚落就被面试官否定了,当时感觉自己说的是正确的,但是由于自己的确记不记得余弦定理的数学含义以及公式,所以也就没有和面试官辩论,当时想请教下面试官他理解的余弦定理是什么,却被一句“回去自己查”给堵死。。。之后对这件事一直耿耿于怀,不过又一想,也是,面试官问的是余弦定理,但是我说的是余弦定理在空间向量中如何计算相似度,好像是有点跑题。。。anyway,过去的已经过去了,只要有收获就行。于是回来查了一下余弦定理是怎么应用于文本相似的度量的,下面是整个过程,其实很简单,只不过当时把余弦定理的公式忘了,不然很容易就能解释通(数学知识全还给老师了)。。。
相似度度量(Similarity),即计算个体间的相似程度,相似度度量的值越小,说明个体间相似度越小,相似度的值越大说明个体差异越大。
对于多个不同的文本或者短文本对话消息要来计算他们之间的相似度如何,一个好的做法就是将这些文本中词语,映射到向量空间,形成文本中文字和向量数据的映射关系,通过计算几个或者多个不同的向量的差异的大小,来计算文本的相似度。下面介绍一个详细成熟的向量空间余弦相似度方法计算相似度
**向量空间余弦相似度(Cosine Similarity)**
余弦相似度用向量空间中两个向量夹角的余弦值作为衡量两个个体间差异的大小。余弦值越接近1,就表明夹角越接近0度,也就是两个向量越相似,这就叫”余弦相似性”。

上图两个向量a,b的夹角很小可以说a向量和b向量有很高的的相似性,极端情况下,a和b向量完全重合。如下图:

如上图二:可以认为a和b向量是相等的,也即a,b向量代表的文本是完全相似的,或者说是相等的。如果a和b向量夹角较大,或者反方向。如下图

如上图三: 两个向量a,b的夹角很大可以说a向量和b向量有很底的的相似性,或者说a和b向量代表的文本基本不相似。那么是否可以用两个向量的夹角大小的函数值来计算个体的相似度呢?
向量空间余弦相似度理论就是基于上述来计算个体相似度的一种方法。下面做详细的推理过程分析。
想到余弦公式,最基本计算方法就是初中的最简单的计算公式,计算夹角θ的余弦定值公式为:
[ ](https://img-blog.csdn.net/20180622161657666?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2NjMzNDA1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)

但是这个是只适用于直角三角形的,而在非直角三角形中,余弦定理的公式是

三角形中边a和b的夹角 的余弦计算公式为:

在向量表示的三角形中,假设a向量是(x1, y1),b向量是(x2, y2),那么可以将余弦定理改写成下面的形式:

向量a和向量b的夹角 的余弦计算如下

扩展,如果向量a和b不是二维而是n维,上述余弦的计算法仍然正确。假定a和b是两个n维向量,a是 ,b是 ,则a与b的夹角 的余弦等于:

余弦值越接近1,就表明夹角越接近0度,也就是两个向量越相似,夹角等于0,即两个向量相等,这就叫”余弦相似性”。
## 总结:
其实只要知道余弦定理余弦值的计算公式,然后转化为空间中的两个向量后,直接就能代入余弦定理来得到对应的余弦值,毕竟你知道两个向量的坐标,也就意味着你知道了余弦定理公式中三角形的三条边a、b、c的值。
参考:[https://blog.csdn.net/u012160689/article/details/15341303](https://blog.csdn.net/u012160689/article/details/15341303)
|
Java
|
UTF-8
| 2,745 | 1.9375 | 2 |
[
"MIT"
] |
permissive
|
package edu.wpi.first.gradlerio.simulation;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import org.gradle.api.GradleException;
import org.gradle.api.tasks.AbstractExecTask;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;
import org.gradle.nativeplatform.NativeBinarySpec;
import org.gradle.nativeplatform.NativeExecutableBinarySpec;
import org.gradle.nativeplatform.tasks.InstallExecutable;
import edu.wpi.first.gradlerio.wpi.WPIExtension;
import edu.wpi.first.gradlerio.wpi.simulation.SimulationExtension;
public class NativeSimulationTask extends AbstractExecTask<NativeSimulationTask> {
private final List<NativeBinarySpec> binaries = new ArrayList<>();
@Internal
public List<NativeBinarySpec> getBinaries() {
return binaries;
}
private InstallExecutable getInstallForBinary(NativeBinarySpec binary) {
if (binary instanceof NativeExecutableBinarySpec) {
return (InstallExecutable)((NativeExecutableBinarySpec)binary).getTasks().getInstall();
} else {
throw new GradleException("Unknown binary type");
}
}
private final Callable<Object[]> cbl;
@Inject
public NativeSimulationTask() {
super(NativeSimulationTask.class);
getOutputs().upToDateWhen(spec -> false);
cbl = () -> binaries.stream().map(this::getInstallForBinary).toArray();
dependsOn(cbl);
}
@TaskAction
@Override
protected void exec() {
if (binaries.size() != 1) {
throw new GradleException("Must have 1 and only 1 binary");
}
NativeExecutableBinarySpec binary = (NativeExecutableBinarySpec)binaries.get(0);
InstallExecutable install = (InstallExecutable)binary.getTasks().getInstall();
setExecutable(install.getRunScriptFile().get().getAsFile());
List<File> libpaths = new ArrayList<>(Arrays.asList(install.getInstallDirectory().get().getAsFile().listFiles(f -> f.isDirectory())));
libpaths.add(install.getInstallDirectory().get().getAsFile());
SimulationExtension sim = getProject().getExtensions().getByType(WPIExtension.class).getSim();
List<HalSimPair> extensions = sim.getHalSimLocations(libpaths, binary.getBuildType().getName().contains("debug"));
Optional<String> extensionString = extensions.stream().filter(x -> x.defaultEnabled).map(x -> x.libName).reduce((a, b) -> a + File.pathSeparator + b);
if (extensionString.isPresent()) {
environment("HALSIM_EXTENSIONS", extensionString.get());
}
super.exec();
}
}
|
Java
|
UTF-8
| 568 | 3.875 | 4 |
[] |
no_license
|
public class BasicJava{
//Print 1-255
public void print1To255(){
for(int i=1;i<=255;i++){
System.out.println("print1To255 : "+i);
}
}
//Print odd numbers between 1-255
public void printOddNum1To255(){
for(int i=1;i<=255;i++){
if(i%2 == 1){
System.out.println("printOddNum1To255 : "+i);
}
}
}
//Print Sum 0-255
public void printSumOfNums0To255(){
int sum=0;
for(int i=0;i<=255;i++){
sum += i;
System.out.println(sum);
}
}
}
|
Markdown
|
UTF-8
| 1,280 | 2.609375 | 3 |
[] |
no_license
|
# Characters
## Zedek
A convicted murderer. After a questionable jury over his sister's murder, he took the killer's life in cold-blood. Shortly after, he confessed to his village. He feels he must make his own hope in this world as god seems quiet.
## Cahira
A warrior prisoner brought over from the war. Instead of dying in glory like her other peers, she chose to go the path of her enemy's faith for her life. In shame, she now wishes to die, but cannot pull herself to.
## Otho
Born the second son to a wealthy trader. His brother's success left him in the dust, so he tried a different trade, counterfeit printing. Words of his trade reached to divine ears, and they quickly sentenced him. Getting past his constantly complaints, he feels as if he is being judged by the shadow of his father and brother.
## Anzel
The grand templar of the Divinious. Eccentric and loyal, he leads the ceremony of the retribution exodus. He lost his lower jaw during his exodus.
# Deceased Soldiers
## X - Cahira
Farmgirl with a large family.
## Y - Otho
Noble with a small family, and numerous servants.
## Z - Zedik
Mountain recluse, no family.
## W - Cahira
Craftswoman, no blood-related family, but guildmates.
## Q - Zedik
Beggar with a sibling.
## N - Otho
Fisher with a son.
|
Shell
|
UTF-8
| 531 | 3.125 | 3 |
[] |
no_license
|
#!/bin/bash
# Bootstrap a vanilla ubuntu machine
# Update the machine
echo "Updating machine"
sudo apt-get update -y
sudo apt-get upgrade -y
# Install core tools
echo "Installing tools"
sudo apt-get install -y vim git tree tmux
# configure git
echo "Configuring git"
git config --global user.name "Toby W"
git config --global user.email "toby@wilkins.io"
git config --global core.editor "vim"
echo "Sourcing files"
tmux source ~/.tmux.conf
source ~/.bashrc
echo "!! DONE !!"
# Now go into a tmux session, eg with 'tmux new -s main'
|
Java
|
UTF-8
| 1,657 | 1.976563 | 2 |
[] |
no_license
|
package com.general.dto;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.jtransfo.NotMapped;
import lombok.Data;
@Data
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class IngredientCourse {
@NotMapped
String libelleIngredient;
@NotMapped
int idIngredient;
@NotMapped
String categorie;
@NotMapped
List<RelationUniteQuantiteDto> lstRelationUniteDto;
public String getLibelleIngredient() {
return libelleIngredient;
}
public void setLibelleIngredient(String libelleIngredient) {
this.libelleIngredient = libelleIngredient;
}
public int getIdIngredient() {
return idIngredient;
}
public void setIdIngredient(int idIngredient) {
this.idIngredient = idIngredient;
}
public String getCategorie() {
return categorie;
}
public void setCategorie(String categorie) {
this.categorie = categorie;
}
public List<RelationUniteQuantiteDto> getLstRelationUniteDto() {
return lstRelationUniteDto;
}
public void setLstRelationUniteDto(List<RelationUniteQuantiteDto> lstRelationUniteDto) {
this.lstRelationUniteDto = lstRelationUniteDto;
}
public IngredientCourse(String libelleIngredient, int idIngredient, String categorie,
List<RelationUniteQuantiteDto> lstRelationUniteDto) {
super();
this.libelleIngredient = libelleIngredient;
this.idIngredient = idIngredient;
this.categorie = categorie;
this.lstRelationUniteDto = lstRelationUniteDto;
}
//ok
public IngredientCourse() {
super();
// TODO Auto-generated constructor stub
}
}
|
Swift
|
UTF-8
| 523 | 2.671875 | 3 |
[] |
no_license
|
//
// SnapImage.swift
// SnapchatClone
//
// Created by Max Miranda on 9/18/18.
// Copyright © 2018 ___MaxAMiranda___. All rights reserved.
//
import UIKit
class SnapImage {
var sender: String
var sentTo: String
var timeSent: Date
var opened: Bool
var image: UIImage
init(sentBy: String, sentTo: String, timeSent: Date, image: UIImage) {
self.sender = sentBy
self.sentTo = sentTo
self.timeSent = timeSent
self.image = image
self.opened = false
}
}
|
Markdown
|
UTF-8
| 12,074 | 3.203125 | 3 |
[] |
no_license
|
# Folha de Pagamento

During the first part of the project (AB1) there were some problems that made it impossible to build the system in OOP. During the second part of the project (AB2) the system was made in OOP already following the Model-View-Controller.
---------
O objetivo do projeto é construir um sistema de folha de pagamento. O sistema consiste do gerenciamento de pagamentos dos empregados de uma empresa. Além disso, o sistema deve gerenciar os dados destes empregados, a exemplo os cartões de pontos. Empregados devem receber o salário no momento correto, usando o método que eles preferem, obedecendo várias taxas e impostos deduzidos do salário.
+ Alguns empregados são horistas. Eles recebem um salário por hora trabalhada. Eles submetem "cartões de ponto" todo dia para informar o número de horas trabalhadas naquele dia. Se um empregado trabalhar mais do que 8 horas, deve receber 1.5 a taxa normal durante as horas extras. Eles são pagos toda sexta-feira.
+ Alguns empregados recebem um salário fixo mensal. São pagos no último dia útil do mês (desconsidere feriados). Tais empregados são chamados "assalariados".
+ Alguns empregados assalariados são comissionados e portanto recebem uma comissão, um percentual das vendas que realizam. Eles submetem resultados de vendas que informam a data e valor da venda. O percentual de comissão varia de empregado para empregado. Eles são pagos a cada 2 sextas-feiras; neste momento, devem receber o equivalente de 2 semanas de salário fixo mais as comissões do período.
+ Empregados podem escolher o método de pagamento.
+ Podem receber um cheque pelos correios.
+ Podem receber um cheque em mãos.
+ Podem pedir depósito em conta bancária
+ Alguns empregados pertencem ao sindicato (para simplificar, só há um possível sindicato). O sindicato cobra uma taxa mensal do empregado e essa taxa pode variar entre empregados. A taxa sindical é deduzida do salário. Além do mais, o sindicato pode ocasionalmente cobrar taxas de serviços adicionais a um empregado. Tais taxas de serviço são submetidas pelo sindicato mensalmente e devem ser deduzidas do próximo contracheque do empregado. A identificação do empregado no sindicato não é a mesma da identificação no sistema de folha de pagamento.
+ A folha de pagamento é rodada todo dia e deve pagar os empregados cujos salários vencem naquele dia. O sistema receberá a data até a qual o pagamento deve ser feito e calculará o pagamento para cada empregado desde a última vez em que este foi pago.
---------
## Running the system
```
To run the project, you must run the main.py file
```
The system menu includes 9 features: 1 - Add employee, 2 - Employee removal, 3 - Add a card, 4 - Add sales, 5 - Apply service fee, 6 - Change details, 7 - Payroll for today, 8 - Show Employees and 9 - Change payment period
```
PAYROLL
Menu:
1 - Add employee
2 - Employee removal
3 - Add a card
4 - Add sales
5 - Apply service fee
6 - Change details
7 - Payroll for today
8 - Show Employees
9 - Change payment period
Options:
```
Showing some examples:
**Add employee**
When option 1 (Add employee) is selected, the user must provide the following data: RG, Name, Address, Types employee [0: Salaried, 1: Hourly, 2: Commissioned], Salary, Select method payment [0: Bank account deposit, 1: Check card in hand, 2: Check card by post] and Start date
The Star_date input refers to the employee's registration date, to facilitate testing. After the employee is added to the system, a registration table is shown containing all employees.
```
Add employee
RG: 9786
Name: Guilherme Monteiro
Address: Maceio
Types employee :
0: Salaried
1: Hourly
2: Commissioned
Option: 0
Salary: 3000
Select method payment:
0: Bank account deposit
1: Check card in hand
2: Check card by post
Option: 0
Start date: 2021-05-25
Id RG Name Address Types employee Payment Scheduled (in hours) Worked hours Salary Commission percent Payment method Paycheck Last Payment Start date
0 1233 Jose Fernando Maceio Salaried 720 0 2000 0 Bank account deposit 0 2020-10-10
1 4567 Juliana Fernanda Recife Hourly 144 0 20 0 Check card in hand 0 2020-10-20
2 3546 Jenet Alves Aracaju Commissioned 336 0 1800 5 Check card by post 0 2020-10-20
3 9786 Guilherme Monteiro Maceio Salaried 336 0 3000 0 Bank account deposit 0 2021-05-25
Operation performed successfully
Do you want to perform one more operation? (Y/N)
```
**Employee removal**
When option 2 (Employee removal) is selected, the system shows the table with all registered employees and asks for the employee ID that will be removed. Then the table returns (without the employee) and a warning message.
```
Select employe
Id RG Name Address Types employee Payment Scheduled (in hours) Worked hours Salary Commission percent Payment method Paycheck Last Payment Start date
0 1233 Jose Fernando Maceio Salaried 720 0 2000 0 Bank account deposit 0 2020-10-10
1 4567 Juliana Fernanda Recife Hourly 144 0 20 0 Check card in hand 0 2020-10-20
2 3546 Jenet Alves Aracaju Commissioned 336 0 1800 5 Check card by post 0 2020-10-20
3 9786 Guilherme Monteiro Maceio Salaried 336 0 3000 0 Bank account deposit 0 2021-05-25
Employee removal
Id: 3
Id RG Name Address Types employee Payment Scheduled (in hours) Worked hours Salary Commission percent Payment method Paycheck Last Payment Start date
0 1233 Jose Fernando Maceio Salaried 720 0 2000 0 Bank account deposit 0 2020-10-10
1 4567 Juliana Fernanda Recife Hourly 144 0 20 0 Check card in hand 0 2020-10-20
2 3546 Jenet Alves Aracaju Commissioned 336 0 1800 5 Check card by post 0 2020-10-20
Operation performed successfully
Do you want to perform one more operation? (Y/N)
```
**Add a card**
When option 3 (Add a card) is selected, the system shows the table with all registered employees and asks for the ID of the employee who will have a time card added. If the employee is an hourly worker, the number of hours of work will be requested.
```
Select employe
Id RG Name Address Types employee Payment Scheduled (in hours) Worked hours Salary Commission percent Payment method Paycheck Last Payment Start date
0 1233 Jose Fernando Maceio Salaried 720 0 2000 0 Bank account deposit 0 2020-10-10
1 4567 Juliana Fernanda Recife Hourly 144 0 20 0 Check card in hand 0 2020-10-20
2 3546 Jenet Alves Aracaju Commissioned 336 0 1800 5 Check card by post 0 2020-10-20
Id: 1
Work hours: 8
Id RG Name Address Types employee Payment Scheduled (in hours) Worked hours Salary Commission percent Payment method Paycheck Last Payment Start date
0 1233 Jose Fernando Maceio Salaried 720 0 2000 0 Bank account deposit 0 2020-10-10
1 4567 Juliana Fernanda Recife Hourly 144 8 20 0 Check card in hand 0 2020-10-20
2 3546 Jenet Alves Aracaju Commissioned 336 0 1800 5 Check card by post 0 2020-10-20
Operation performed successfully
Do you want to perform one more operation? (Y/N)
```
**Add sales**
When option 4 (Add sales) is selected, the system shows the table with all registered employees and asks for the Id of the employee who will have an added sale. If the employee is commissioned, the sale price will be requested.
```
Add sales
Sale price: 1200
Id RG Name Address Types employee Payment Scheduled (in hours) Worked hours Salary Commission percent Payment method Paycheck Last Payment Start date
0 1233 Jose Fernando Maceio Salaried 720 0 2000 0 Bank account deposit 0 2020-10-10
1 4567 Juliana Fernanda Recife Hourly 144 8 20 0 Check card in hand 0 2020-10-20
2 3546 Jenet Alves Aracaju Commissioned 336 0 1800 5 Check card by post 0 2020-10-20
Id: 2
Operation performed successfully
Do you want to perform one more operation? (Y/N)
```
## Code Smells
It is important to note that the project avoided Rigidity, Fragility, Complexity and Duplication in the code. Therefore, not many limitations were found (bad smells).
**Long Parameter List:** There is no single rule for how many is too many parameters. Usually more than three or four is considered too many. In the code written in PANDAS there were many Long parameter lists but the OOP version of the system has already been built thinking about not building methods with Long Parameter List. But, we have inputs_add_update(self, cols, cast, count, others_form).
**Feature Envy:** One method can access data of another type to do some operation. When this becomes common, it means that the object itself should perform this operation and deliver the result. In this code there is no Feature Envy method because encapsulation and MVC were used.
**Lazy Class:** There is no class that simply has an empty constructor and a getter and setter for each variable. Exactly because the OOP version of the system has already been built thinking about not building Lazy Class.
**Long Method** The only long method in the code is the menu() method present in class PanelMenu.
**Large Class:** refers to the classes that tend to centralize the intelligence of the system. Large Class indicates weaknesses in design that can possibly slow down the development or increase the chance of failures in the future. In addition, it makes the system more difficult to understand, read and develop. PanelMenu is a large class with many methods.
## Refactoring
To refactor is to restructure a software system by applying a series of transformations without modifying its observable behavior, in order to make it easier to understand and modify. However, the previous system was made in pandas without OOP and a new version of the system was made using OOP and MVC.
1. Replacement of pandas storage for common list (stopped storing data on dataframe) but still left the pandas print feature active through the _iter_ method on each model.
2. The inputs_add_update() method of the PanelMenu class is used to insert values (as a form) in any type of model. This is because two methods are defined within the models: columns_ () and types_cast_ ().
3. Two specific Controllers were made which are ManageEmployee and ManageTransaction. ManageCommons is general and used by all other models that are not specific, avoiding duplication of code.
|
JavaScript
|
UTF-8
| 699 | 2.90625 | 3 |
[] |
no_license
|
'use strict'
import axios from 'axios'
import config from './config.json'
setInterval(func, config.interval * 1000)
async function func () {
console.log('Func started: ' + new Date().toLocaleString())
let request = await axios.get(config.get.url)
const data = request.data
console.log('Price: ' + parse(data, config.get.price))
console.log('Time: ' + parse(data, config.get.timestamp))
await axios.put(
config.put.url,
{
value: Number(parse(data, config.get.price).replace(',', '')),
timestamp: parse(data, config.get.timestamp)
}
)
}
function parse (data, sequence) {
let obj = data
sequence.forEach((element) => obj = obj[element])
return obj
}
|
Python
|
UTF-8
| 1,448 | 3.3125 | 3 |
[
"Apache-2.0"
] |
permissive
|
import sublime, sublime_plugin
class ExampleCommand(sublime_plugin.TextCommand):
def run(self, edit):
self.view.insert(edit, 0, "Hello, World! xxxxxx\n")
class Rot13Command(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if not region.empty():
# Get the selected text
s = self.view.substr(region)
# Transform it via rot13
s = s.encode('rot13')
# Replace the selection with transformed text
self.view.replace(region, s)
# Extends TextCommand so that run() receives a View to modify.
class DuplicateCommand(sublime_plugin.TextCommand):
def run(self, edit):
# Walk through each region in the selection
for region in self.view.sel():
# Only interested in empty regions, otherwise they may span multiple
# lines, which doesn't make sense for this command.
print(region)
if region.empty():
# Expand the region to the full line it resides on, excluding the newline
line = self.view.line(region)
# Extract the string for the line, and add a newline
lineContents = self.view.substr(line) + '\n'
# Add the text at the beginning of the line
self.view.insert(edit, line.begin(), lineContents)
|
TypeScript
|
UTF-8
| 10,230 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
// Type definitions for cookie 0.5
// Project: https://github.com/jshttp/cookie
// Definitions by: Pine Mizune <https://github.com/pine>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Basic HTTP cookie parser and serializer for HTTP servers.
*/
/**
* Additional serialization options
*/
interface CookieSerializeOptions {
/**
* Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no
* domain is set, and most clients will consider the cookie to apply to only
* the current domain.
*/
domain?: string | undefined;
/**
* Specifies a function that will be used to encode a cookie's value. Since
* value of a cookie has a limited character set (and must be a simple
* string), this function can be used to encode a value into a string suited
* for a cookie's value.
*
* The default function is the global `encodeURIComponent`, which will
* encode a JavaScript string into UTF-8 byte sequences and then URL-encode
* any that fall outside of the cookie range.
*/
encode?(value: string): string;
/**
* Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. By default,
* no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete
* it on a condition like exiting a web browser application.
*
* *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
* states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
* possible not all clients by obey this, so if both are set, they should
* point to the same date and time.
*/
expires?: Date | undefined;
/**
* Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}.
* When truthy, the `HttpOnly` attribute is set, otherwise it is not. By
* default, the `HttpOnly` attribute is not set.
*
* *Note* be careful when setting this to true, as compliant clients will
* not allow client-side JavaScript to see the cookie in `document.cookie`.
*/
httpOnly?: boolean | undefined;
/**
* Specifies the number (in seconds) to be the value for the `Max-Age`
* `Set-Cookie` attribute. The given number will be converted to an integer
* by rounding down. By default, no maximum age is set.
*
* *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
* states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
* possible not all clients by obey this, so if both are set, they should
* point to the same date and time.
*/
maxAge?: number | undefined;
/**
* Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}.
* By default, the path is considered the "default path".
*/
path?: string | undefined;
/**
* Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1].
*
* - `'low'` will set the `Priority` attribute to `Low`.
* - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
* - `'high'` will set the `Priority` attribute to `High`.
*
* More information about the different priority levels can be found in
* [the specification][rfc-west-cookie-priority-00-4.1].
*
* **note** This is an attribute that has not yet been fully standardized, and may change in the future.
* This also means many clients may ignore this attribute until they understand it.
*/
priority?: 'low' | 'medium' | 'high' | undefined;
/**
* Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`SameSite` `Set-Cookie` attribute}.
*
* - `true` will set the `SameSite` attribute to `Strict` for strict same
* site enforcement.
* - `false` will not set the `SameSite` attribute.
* - `'lax'` will set the `SameSite` attribute to Lax for lax same site
* enforcement.
* - `'strict'` will set the `SameSite` attribute to Strict for strict same
* site enforcement.
* - `'none'` will set the SameSite attribute to None for an explicit
* cross-site cookie.
*
* More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}.
*
* *note* This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
*/
sameSite?: true | false | 'lax' | 'strict' | 'none' | undefined;
/**
* Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the
* `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
*
* *Note* be careful when setting this to `true`, as compliant clients will
* not send the cookie back to the server in the future if the browser does
* not have an HTTPS connection.
*/
secure?: boolean | undefined;
}
/**
* {@link https://wicg.github.io/cookie-store/#dictdef-cookielistitem CookieListItem}
* as specified by W3C.
*/
interface CookieListItem extends Pick<CookieSerializeOptions, 'domain' | 'path' | 'secure' | 'sameSite'> {
/** A string with the name of a cookie. */
name: string;
/** A string containing the value of the cookie. */
value: string;
/** A number of milliseconds or Date interface containing the expires of the cookie. */
expires?: number | CookieSerializeOptions['expires'];
}
/**
* Superset of {@link CookieListItem} extending it with
* the `httpOnly`, `maxAge` and `priority` properties.
*/
type ResponseCookie = CookieListItem & Pick<CookieSerializeOptions, 'httpOnly' | 'maxAge' | 'priority'>;
/**
* Subset of {@link CookieListItem}, only containing `name` and `value`
* since other cookie attributes aren't be available on a `Request`.
*/
type RequestCookie = Pick<CookieListItem, 'name' | 'value'>;
/**
* A class for manipulating {@link Request} cookies (`Cookie` header).
*/
declare class RequestCookies {
constructor(requestHeaders: Headers);
[Symbol.iterator](): IterableIterator<[string, RequestCookie]>;
/**
* The amount of cookies received from the client
*/
get size(): number;
get(...args: [name: string] | [RequestCookie]): RequestCookie | undefined;
getAll(...args: [name: string] | [RequestCookie] | []): RequestCookie[];
has(name: string): boolean;
set(...args: [key: string, value: string] | [options: RequestCookie]): this;
/**
* Delete the cookies matching the passed name or names in the request.
*/
delete(
/** Name or names of the cookies to be deleted */
names: string | string[]): boolean | boolean[];
/**
* Delete all the cookies in the cookies in the request.
*/
clear(): this;
toString(): string;
}
/**
* A class for manipulating {@link Response} cookies (`Set-Cookie` header).
* Loose implementation of the experimental [Cookie Store API](https://wicg.github.io/cookie-store/#dictdef-cookie)
* The main difference is `ResponseCookies` methods do not return a Promise.
*/
declare class ResponseCookies {
constructor(responseHeaders: Headers);
/**
* {@link https://wicg.github.io/cookie-store/#CookieStore-get CookieStore#get} without the Promise.
*/
get(...args: [key: string] | [options: ResponseCookie]): ResponseCookie | undefined;
/**
* {@link https://wicg.github.io/cookie-store/#CookieStore-getAll CookieStore#getAll} without the Promise.
*/
getAll(...args: [key: string] | [options: ResponseCookie] | []): ResponseCookie[];
has(name: string): boolean;
/**
* {@link https://wicg.github.io/cookie-store/#CookieStore-set CookieStore#set} without the Promise.
*/
set(...args: [key: string, value: string, cookie?: Partial<ResponseCookie>] | [options: ResponseCookie]): this;
/**
* {@link https://wicg.github.io/cookie-store/#CookieStore-delete CookieStore#delete} without the Promise.
*/
delete(...args: [key: string] | [options: Omit<ResponseCookie, 'value' | 'expires'>]): this;
toString(): string;
}
declare function stringifyCookie(c: ResponseCookie | RequestCookie): string;
/** Parse a `Cookie` header value */
declare function parseCookie(cookie: string): Map<string, string>;
/** Parse a `Set-Cookie` header value */
declare function parseSetCookie(setCookie: string): undefined | ResponseCookie;
/**
* @source https://github.com/nfriedly/set-cookie-parser/blob/master/lib/set-cookie.js
*
* Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
* that are within a single set-cookie field-value, such as in the Expires portion.
* This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
* Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
* React Native's fetch does this for *every* header, including set-cookie.
*
* Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
* Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
*/
declare function splitCookiesString(cookiesString: string): string[];
export { CookieListItem, RequestCookie, RequestCookies, ResponseCookie, ResponseCookies, parseCookie, parseSetCookie, splitCookiesString, stringifyCookie };
|
Markdown
|
UTF-8
| 2,438 | 2.796875 | 3 |
[] |
no_license
|
---
type: post
title: "Baked Chicken & Brussels Sprouts"
author: "USA WEEKEND columnist Jean Carper"
category: lunch
photo: "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fimages.media-allrecipes.com%2Fuserphotos%2F1088675.jpg"
prep_time:
cook_time:
recipe_yield: "8 servings"
rating_value: 3.5555555555555554
review_count: 45
calories: "134.5 calories"
date_published: 02/29/2020 06:26 AM
description: "New research says cruciferous vegetables--cabbage and its cousins broccoli and Brussels sprouts--may cut risk of type 2 diabetes and cancer."
recipe_ingredient: ['1 tablespoon extra virgin olive oil', '1\u2009¼ pounds boneless, skinless chicken breast, cut into 8 pieces ', '1 pound fresh Brussels sprouts', '1\u2009½ cups chopped yellow onion', '2\u2009½ tablespoons fresh rosemary', '1\u2009½ cups 99% fat-free chicken broth ', 'Salt and black pepper to taste']
recipe_instructions: [{'@type': 'HowToStep', 'text': 'Preheat oven to 375 degrees. In a skillet, heat oil and brown chicken. Lay chicken in a shallow baking dish and surround with Brussels sprouts. Sprinkle onions and rosemary over chicken. Add broth, salt and pepper. Bake, covered, for 20 minutes. Uncover, increase oven temperature to 400 degrees, and bake 30 to 40 minutes, until sprouts are cooked firm, not mushy. Serve\n'}]
---
New research says cruciferous vegetables--cabbage and its cousins broccoli and Brussels sprouts--may cut risk of type 2 diabetes and cancer.
{{< boldheading >}}
{{< checkbox "1 tablespoon extra virgin olive oil" >}}
{{< checkbox "1 ¼ pounds boneless, skinless chicken breast, cut into 8 pieces" >}}
{{< checkbox "1 pound fresh Brussels sprouts" >}}
{{< checkbox "1 ½ cups chopped yellow onion" >}}
{{< checkbox "2 ½ tablespoons fresh rosemary" >}}
{{< checkbox "1 ½ cups 99% fat-free chicken broth" >}}
{{< checkbox "Salt and black pepper to taste" >}}
{{< direction >}}
**Step: 1**
Preheat oven to 375 degrees. In a skillet, heat oil and brown chicken. Lay chicken in a shallow baking dish and surround with Brussels sprouts. Sprinkle onions and rosemary over chicken. Add broth, salt and pepper. Bake, covered, for 20 minutes. Uncover, increase oven temperature to 400 degrees, and bake 30 to 40 minutes, until sprouts are cooked firm, not mushy. Serve{{< span >}}
{{< nutrition >}}
**Per Serving:** 135 calories; protein 17.2g; carbohydrates 8.3g; fat 3.7g; cholesterol 41.5mg; sodium 264.4mg.
|
C++
|
GB18030
| 813 | 2.875 | 3 |
[] |
no_license
|
#pragma once
class Kernel
{
public:
Kernel( int w, int h );
~Kernel(void);
float getKernelValue(int x,int y )const;
float getTransKernelValue( int x, int y ) const;//תúKERNELֵEROSIONʱõ
void setKernelValue( const float* ptr );
public:
inline bool AssertValid( int x, int y ) const{
if ( x >=0 && x < width && y>=0 && y< height ) return true;
return false;
}
void setCenter( int x, int y ){
if( !AssertValid( x,y ) ) return;
centerX = x;
centerY = y;
}
public:
static Kernel getDefaultKernel();
static Kernel getDiskKernel();
static Kernel getDiamondKernel();
static Kernel getR10DiskKernel();
//int KernelSize;
private:
float* data;
public:
int width;
int height;
int centerX;
int centerY;
};
|
Ruby
|
UTF-8
| 3,002 | 4.3125 | 4 |
[] |
no_license
|
class TowerOfHanoi
# display rules
def show_rules
line_width = 60
puts ""
puts "Welcome to Tower of Hanoi!\n".center line_width
puts "The object of the game is to move all of your disks from the left rod"
puts "to either the middle rod or the right rod - one disk at a time.\n\n"
puts "Here are the rules:\n\n"
puts "1. Only one disk can be moved at a time."
puts "2. Each move consists of taking the upper disk from one of the stacks and"
puts " placing it on top of another stack i.e. a disk can only be moved if it is"
puts " the uppermost disk on a stack."
puts "3. No disk may be placed on top of a smaller disk.\n\n"
puts "You may type QUIT at any time to exit the game.\n".center line_width
end
# begin game with user input for disk number
def initialize_game
@rods = {1=>[],2=>[],3=>[]}
@moves = 0
puts "How many disks would you like to play with?"
@disks = gets.chomp.to_i
@rods[1] = (1..@disks).to_a # [1,2,3,4 <-- top to bottom -->]
puts "Game starting. Good luck!"
@rods.each {|rod,disk_number|puts "Rod #{rod}: #{disk_number}"}
end
# display game board
def print_rods
@rods.each {|rod,disk_number|puts "Rod #{rod}: #{disk_number}"}
end
# get user "move from" input + quit/validate
def move_from
@move_from = nil
while @move_from == nil
puts "Which rod would you like to move a disk FROM?"
from = gets.chomp
if from.upcase == "QUIT"
exit
elsif @rods.key?(from.to_i)
@move_from = @rods[from.to_i]
else
puts "Please select a valid rod."
end
end
end
# get user "move to" input + quit/validate
def move_to
@move_to = nil
while @move_to == nil
puts "Which rod would you like to move the selected disk TO?"
to = gets.chomp
if to.upcase == "QUIT"
exit
elsif @rods.key?(to.to_i)
@move_to = @rods[to.to_i]
else
puts "Please select a valid rod."
end
end
end
# validate entire move based on current rods
def validate_move
if @move_from.empty?
puts "Please enter a valid move."
elsif @move_to.none? || @move_from.first < @move_to.first
@move_to.unshift(@move_from.first)
@move_from.shift
@moves += 1
else @move_from.first > @move_to.first
puts "You cannot place a larger disk on a smaller disk."
end
end
# determine after each move if the game has been won
def game_won
if @rods[2].length == @disks || @rods[3].length == @disks
puts "You win!"
if @moves == 1
puts "You got it on the first try!"
else
puts "It only took you #{@moves} tries!"
end
exit
end
end
# play the darn thing
def play_game
show_rules
initialize_game
while true
move_from
move_to
validate_move
print_rods
game_won
end
end
end
# let's do this!
game = TowerOfHanoi.new
game.play_game
|
Java
|
UTF-8
| 504 | 1.75 | 2 |
[] |
no_license
|
public final class acg
{
private final int aw;
private final dEE cQV;
private final int[] cQW;
private final doV cQX;
acg(int paramInt, dEE paramdEE, doV paramdoV, int[] paramArrayOfInt)
{
this.aw = paramInt;
this.cQV = paramdEE;
this.cQW = paramArrayOfInt;
this.cQX = paramdoV;
}
public int getId() {
return this.aw;
}
public dEE aoq() {
return this.cQV;
}
public int[] aor() {
return this.cQW;
}
public doV aos() {
return this.cQX;
}
}
|
JavaScript
|
UTF-8
| 4,598 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
'use strict';
angular.module('myApp.split', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/split', {
templateUrl: 'split/split.template.html',
controller: 'SplitCtrl'
});
}])
.controller('SplitCtrl', function($scope, Friends, Bill) {
$scope.friends = Friends.getAll();
$scope.bill = Bill.getBill();
$scope.assigneditems = [];
$scope.items = $scope.bill.items;
/******************************************/
/* THIS IS STRUCTURE OF bill, item, friend
/* bill: {name: string, items:[], priceBeforeTip: number, taxRate: number, tipRate: number}
/* item: [id, itemname, price, people.name];
/* friend: {name: string, items: []}
/*****************************************/
/**
* This function calculate the grand total price for a single friend. Grand total
* includes total price, tax and tip.
* @param {object} input a friend object
*/
$scope.grandTotal = function(friend) {
var totalBeforeTip = 0;
friend.items.forEach(function(singleitem) {
totalBeforeTip += singleitem[2];
});
friend.tip = Number.parseFloat((totalBeforeTip * $scope.bill.tipRate).toFixed(2));
friend.tax = Number.parseFloat((totalBeforeTip * $scope.bill.taxRate).toFixed(2));
friend.total = Number.parseFloat((totalBeforeTip + friend.tip + friend.tax).toFixed(2));
Friends.getAll();
}
/**
* This function assign an item to a friend, add this item to $scope.assignedItems,
* and update the grand total for this friend
* @params {array} item, {object} friend
*/
$scope.assign = function(item, friend) {
item[3] = friend.name;
friend.items.push(item); // add item for friend
$scope.assigneditems.push(item); // add item into assigneditems list
$scope.grandTotal(friend);
}
/**
* This function unassign an item from a friend, remove this item from $scope.assignedItems,
* and update the total grand for this friend.
* @params {array} item to be unassigned, {object} friend
*/
$scope.unassign = function(item, friend) {
var indexforFriend = friend.items.indexOf(item);
friend.items.splice(indexforFriend, 1);
var indexForAllAssigned = $scope.assigneditems.indexOf(item);
$scope.assigneditems.splice(indexForAllAssigned, 1); // remove item from assigneditems list
item[3] = "";
$scope.grandTotal(friend);
}
/**
* This function check if this item is already been assigned.
* If this item is not assigned, it will call 'assign function'.
* If this item is assigned to the same person, it will unassign from this person.
* If this item is assigned to a different person, it will unassign the item from
* the origin person, and assign the item to the new person.
* @param {array} input an item object, {object} input a friend object.
*/
$scope.checkAssign = function(item, friend) {
var needReassign = false;
for (var i = 0; i < $scope.assigneditems.length; i++) {
if ($scope.assigneditems[i][0] === item[0]) {
needReassign = true;
// if the item belongs to the 'friend'
if ($scope.assigneditems[i][3] === friend.name) {
// unassign this item from 'friend's item list
$scope.unassign(item, friend);
} else { // if the item belongs to another friend
// find the ANOTHER friend by friend.name
var anotherFriend;
$scope.friends.forEach(function(singlefriend) {
if (singlefriend.name === item[3]) {
anotherFriend = singlefriend;
}
})
console.log('another friend', anotherFriend.name);
$scope.unassign(item, anotherFriend); // unassign this item from the ANOTHER friend
$scope.assign(item, friend); // assign this item to THIS friend
}
break;
}
}
if (!needReassign) {
$scope.assign(item, friend);
}
}
$scope.changeClass = function() {
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i][3]) {
$scope.class = "table-success"
} else {
$scope.class = "";
}
}
}
}
);
|
Python
|
UTF-8
| 138 | 2.578125 | 3 |
[] |
no_license
|
def find_max_min(A):
if min(A)== max(A):
return [len(A)]
else:
return [min(A),max(A)]
find_max_min([2,3,5,7,1,10])
|
Java
|
UTF-8
| 1,791 | 2.40625 | 2 |
[] |
no_license
|
package platform.view;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.UTF_8;
@Component
public class ViewComponent {
private final ResourceLoader resourceLoader;
public ViewComponent(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public <T> String getAllCode(String fileName, T model) {
Resource resource = resourceLoader.
getResource("classpath:/views/" + fileName + ".html");
String code;
try (Reader reader = new InputStreamReader(resource.getInputStream(), UTF_8)) {
code = FileCopyUtils.copyToString(reader);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
Pattern pattern = Pattern.compile("\\{\\{\\w+}}");
code = pattern.matcher(code).replaceAll(matchResult -> {
String bind = matchResult.group().replace("{", "")
.replace("}", "");
String methodName = "get" + bind.substring(0,1).toUpperCase()
+ bind.substring(1);
// System.out.println(methodName);
Class<?> t = model.getClass();
try {
Method method = t.getMethod(methodName);
return method.invoke(model).toString();
} catch (Exception e) {
return "";
}
});
System.out.println(code);
return code;
}
}
|
C#
|
UTF-8
| 2,497 | 2.703125 | 3 |
[] |
no_license
|
using CZGL.Roslyn;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
namespace CZGL.RoslynTool
{
public class AttributeTool
{
/// <summary>
/// 构建 AttributeListSyntax
/// </summary>
/// <param name="syntaxes"></param>
/// <returns></returns>
public static AttributeListSyntax CreateAttributeListSyntax(AttributeSyntax[] syntaxes)
{
var attributeList = new SeparatedSyntaxList<AttributeSyntax>();
foreach (var item in syntaxes)
{
attributeList = attributeList.Add(item);
}
var list = SyntaxFactory.AttributeList(attributeList);
return list;
}
/// <summary>
/// 字符串生成特性
/// </summary>
/// <param name="attrCode"></param>
/// <returns></returns>
/// <example>
/// <code>
/// "[Display(Name = \"a\")]"
/// </code>
/// </example>
public static AttributeListSyntax CreateAttributeList(string attrCode)
{
var result = CodeSyntax.CreateAttribute(attrCode);
return SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(result.BuildSyntax()));
}
/// <summary>
/// 字符串生成特性列表
/// <para>
/// <example>
/// <code>
/// string[] code = new string[]
/// {
/// "[Display(Name = \"a\")]",
/// "[Display(Name = \"b\")]"
/// };
/// Cbuilder.reateAttributeList(code);
/// </code>
/// </example>
/// </para>
/// </summary>
/// <param name="attrCode"></param>
/// <returns></returns>
public static SyntaxList<AttributeListSyntax> CreateAttributeList(params string[] attrsCode)
{
List<AttributeListSyntax> syntaxes = new List<AttributeListSyntax>();
foreach (var item in attrsCode)
{
var tmp = CodeSyntax.CreateAttribute(item);
syntaxes.Add(
SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(tmp.BuildSyntax())));
}
return SyntaxFactory.List<AttributeListSyntax>(syntaxes.ToArray());
}
}
}
|
Markdown
|
UTF-8
| 665 | 3.25 | 3 |
[] |
no_license
|
# Restaurant-Wait-List-Program
A program that mimics the wait list for a restaurant that I wrote for a school project. You're in charge of a restaurant that has a wait list for it's customers. Customers are given an option of either calling in to place themselves in the waitlist or directly waiting in the restaurant.
This project taught me how to break a program down into separate modules as well as how a data structure such as a priority queue can be implemented in real life.
Download the files and run the makefile to run the program. The program requires no input files since you can use any of the commands such as add a group, display the list, etc.
|
Ruby
|
UTF-8
| 518 | 2.640625 | 3 |
[] |
no_license
|
require 'rgeo-geojson'
require 'rgeo'
require 'json'
class Calendar
attr_reader :events
def initialize(events)
@events = events
geocode_events
end
def feature_collection
@feature_collection ||= RGeo::GeoJSON::EntityFactory.
new.
feature_collection(@events.map(&:rgeo_object))
end
def as_geojson
@geojson ||= RGeo::GeoJSON.encode(feature_collection)
end
def to_geojson
as_geojson.to_json
end
private
def geocode_events
@events.each(&:geocode!)
end
end
|
Shell
|
UTF-8
| 487 | 2.859375 | 3 |
[] |
no_license
|
#!/bin/bash
curl -sfL https://get.k3s.io | sh -
sudo hostnamectl set-hostname k3s-master
sudo apt-get install -y pkg-config bash-completion
rm -rf ~/.kubectx
git clone https://github.com/ahmetb/kubectx.git ~/.kubectx
COMPDIR=$(pkg-config --variable=completionsdir bash-completion)
sudo ln -sf ~/.kubectx/completion/kubens.bash $COMPDIR/kubens
sudo ln -sf ~/.kubectx/completion/kubectx.bash $COMPDIR/kubectx
cat << EOF >> ~/.bashrc
#kubectx and kubens
export PATH=~/.kubectx:\$PATH
EOF
|
Java
|
UTF-8
| 1,451 | 2.515625 | 3 |
[] |
no_license
|
package com.bayer.salonmanagement.model;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@Entity
@Table
@Getter
@Setter
public class Appointment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private Date appointmentDate;
@Pattern(regexp = "^(0[0-9])|(1[0-2]):[0-5][0-9] (A|P)M",
message = "Enter time in 00:00 AM/PM format")
private String appointmentTime;
private String customerFirstName;
private String customerLastName;
@OneToMany
List<SalonService> services;
double total;
@Override
public String toString() {
return "Appointment{" +
"id=" + id +
", appointmentDate=" + appointmentDate +
", Name='" + Name + '\'' +
", services=" + services +
", total=" + total +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Appointment that = (Appointment) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
|
Java
|
UTF-8
| 3,874 | 2.515625 | 3 |
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
package org.jzy3d.plot3d.primitives.vbo;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import org.jzy3d.colors.Color;
import org.jzy3d.colors.ColorMapper;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.GLBuffers;
public class ColormapTexture {
private int texID;
private ByteBuffer image;
private int[] shape;
private boolean isUpdate = false;
private String name = null;
private int id;
public ColormapTexture(ColorMapper mapper, String name, int id) {
this(mapper);
this.name = name;
this.id = id;
}
public ColormapTexture(ColorMapper mapper) {
double min = mapper.getMin();
double max = mapper.getMax();
int nColors = 256;
image = GLBuffers.newDirectByteBuffer(4 * nColors * 4);
double step = (max - min) / nColors;
for (int i = 0; i < nColors; i++) {
Color c = mapper.getColor(min + (i * step));
image.putFloat(c.r);
image.putFloat(c.g);
image.putFloat(c.b);
image.putFloat(c.a);
}
image.rewind();
}
public void updateColormap(ColorMapper mapper) {
double min = mapper.getMin();
double max = mapper.getMax();
int nColors = 256;
double step = (max - min) / nColors;
for (int i = 0; i < nColors; i++) {
Color c = mapper.getColor(min + (i * step));
image.putFloat(c.r);
image.putFloat(c.g);
image.putFloat(c.b);
image.putFloat(c.a);
}
image.rewind();
isUpdate = true;
}
public void update(GL gl) {
if (!isUpdate)
return;
setTextureData(gl, image, shape);
isUpdate = false;
}
public void bind(final GL gl) throws GLException {
gl.glEnable(GL2.GL_TEXTURE_1D);
validateTexID(gl, true);
gl.glBindTexture(GL2.GL_TEXTURE_1D, texID);
if (name != null) {
gl.glActiveTexture(GL.GL_TEXTURE1);
}
gl.glTexParameteri(GL2.GL_TEXTURE_1D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_EDGE);
// gl.glTexParameteri(GL2.GL_TEXTURE_3D, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP);
// gl.glTexParameteri(GL2.GL_TEXTURE_3D, GL2.GL_TEXTURE_WRAP_R, GL2.GL_CLAMP);
gl.glTexParameteri(GL2.GL_TEXTURE_1D, GL2.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL2.GL_TEXTURE_1D, GL2.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
setTextureData(gl, image, shape);
}
public void setTextureData(final GL gl, Buffer buffer, int[] shape) {
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);
gl.getGL2().glTexImage1D(GL2.GL_TEXTURE_1D, 0, GL.GL_RGBA32F, 256, 0, GL2.GL_RGBA, GL.GL_FLOAT,
buffer);
// gl.getGL2().glTexSubImage3D(GL2.GL_TEXTURE_3D,0,0, 0,0, shape[0], shape[1], shape[2],
// GL2ES2.GL_RGBA, GL.GL_UNSIGNED_BYTE, buffer);
// gl.glTexParameteri(GL2.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
// gl.glTexParameteri(GL2.GL_TEXTURE_3D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
// gl.glTexParameteri(GL2.GL_TEXTURE_3D, GL2.GL_TEXTURE_WRAP_R, GL.GL_CLAMP_TO_EDGE);
}
public int getID() {
return id;
}
private boolean validateTexID(final GL gl, final boolean throwException) {
if (name != null) {
gl.glActiveTexture(GL.GL_TEXTURE1);
gl.glEnable(GL2.GL_TEXTURE_1D);
int id = gl.getGL2().glGetUniformLocation(this.id, name);
if (id >= 0) {
texID = id;
}
} else if (0 == texID) {
if (null != gl) {
final int[] tmp = new int[1];
gl.glGenTextures(1, tmp, 0);
texID = tmp[0];
if (0 == texID && throwException) {
throw new GLException("Create texture ID invalid: texID " + texID + ", glerr 0x"
+ Integer.toHexString(gl.glGetError()));
}
} else if (throwException) {
throw new GLException("No GL context given, can't create texture ID");
}
}
return 0 != texID;
}
}
|
Java
|
UTF-8
| 28,274 | 2.03125 | 2 |
[] |
no_license
|
package app.visual;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import core.algorithm.DWT2D_HL_LH_Algorithm;
import core.algorithm.KeyPointImageAlgorithm;
import core.message.CacheMessage;
import core.message.FileMessage;
import core.message.ICoverMessage;
import core.message.IMessage;
import core.message.MatImage;
import core.transform.FastDiscreteBiorthogonal_CDF_9_7;
import core.transform.Transform2d;
import core.transform.Transform2dBasic;
import core.utils.ImageFactory;
import core.utils.Utils;
public class UIApp {
private JFrame frmStegoApplication;
private JTextField tfCoverMessage;
private JTextField tfMessage;
// Create a file chooser
final JFileChooser fc = new JFileChooser();
private JLabel lblMessageInfo;
private JScrollPane pCoverMessage;
private ImageFilter imageFilter;
private JLabel lblCoverMessage;
private JLabel lblMessage;
private ICoverMessage coverMessage;
private FileMessage message;
private final ButtonGroup buttonGroup = new ButtonGroup();
private JTextField tfImage;
private JScrollPane pImage;
private JLabel lblImageMessage;
private JLabel lblMessageExtracted;
protected ICoverMessage imageMessage;
protected ICoverMessage stegoObject;
protected ICoverMessage originalMessage;
private JButton btnSave;
protected final double visibilityfactor = 7;
protected final int keyPointSize = 128;
protected final int howManyPoints = 2;
private JTextField tfOriginalImage;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIApp window = new UIApp();
window.frmStegoApplication.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UIApp() {
initialize();
System.loadLibrary("opencv_java249");
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
imageFilter = new ImageFilter();
fc.addChoosableFileFilter(imageFilter);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmStegoApplication = new JFrame();
final String title = "Stegano Application 0.0.5";
frmStegoApplication.setTitle(title);
frmStegoApplication.setBounds(100, 100, 654, 489);
frmStegoApplication.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmStegoApplication.setMinimumSize(new Dimension(500, 400));
SpringLayout springLayout = new SpringLayout();
frmStegoApplication.getContentPane().setLayout(springLayout);
JPanel basePanel = new JPanel();
SpringLayout baseLayout = new SpringLayout();
basePanel.setLayout(baseLayout);
springLayout.putConstraint(SpringLayout.NORTH, basePanel, 0,
SpringLayout.NORTH, frmStegoApplication.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, basePanel, 0,
SpringLayout.SOUTH, frmStegoApplication.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, basePanel, 0,
SpringLayout.WEST, frmStegoApplication.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, basePanel, 0,
SpringLayout.EAST, frmStegoApplication.getContentPane());
frmStegoApplication.getContentPane().add(basePanel);
final JPanel statusPanel = new JPanel();
SpringLayout statusLayout = new SpringLayout();
statusPanel.setLayout(statusLayout);
baseLayout.putConstraint(SpringLayout.WEST, statusPanel, 0,
SpringLayout.WEST, basePanel);
baseLayout.putConstraint(SpringLayout.NORTH, statusPanel, -20,
SpringLayout.SOUTH, basePanel);
baseLayout.putConstraint(SpringLayout.SOUTH, statusPanel, 0,
SpringLayout.SOUTH, basePanel);
baseLayout.putConstraint(SpringLayout.EAST, statusPanel, 0,
SpringLayout.EAST, basePanel);
basePanel.add(statusPanel);
final JPanel extractPanel = new JPanel();
SpringLayout extractLayout = new SpringLayout();
extractPanel.setLayout(extractLayout);
baseLayout.putConstraint(SpringLayout.WEST, extractPanel, 0,
SpringLayout.WEST, basePanel);
baseLayout.putConstraint(SpringLayout.NORTH, extractPanel, 0,
SpringLayout.NORTH, basePanel);
baseLayout.putConstraint(SpringLayout.SOUTH, extractPanel, 0,
SpringLayout.NORTH, statusPanel);
baseLayout.putConstraint(SpringLayout.EAST, extractPanel, 0,
SpringLayout.EAST, basePanel);
basePanel.add(extractPanel);
extractPanel.setVisible(false);
final JPanel hiddenPanel = new JPanel();
SpringLayout hiddenLayout = new SpringLayout();
hiddenPanel.setLayout(hiddenLayout);
baseLayout.putConstraint(SpringLayout.WEST, hiddenPanel, 0,
SpringLayout.WEST, basePanel);
baseLayout.putConstraint(SpringLayout.NORTH, hiddenPanel, 0,
SpringLayout.NORTH, basePanel);
baseLayout.putConstraint(SpringLayout.SOUTH, hiddenPanel, 0,
SpringLayout.NORTH, statusPanel);
baseLayout.putConstraint(SpringLayout.EAST, hiddenPanel, 0,
SpringLayout.EAST, basePanel);
basePanel.add(hiddenPanel);
hiddenPanel.setVisible(false);
final JPanel attackPanel = new ReportPanel();
baseLayout.putConstraint(SpringLayout.WEST, attackPanel, 0,
SpringLayout.WEST, basePanel);
baseLayout.putConstraint(SpringLayout.NORTH, attackPanel, 0,
SpringLayout.NORTH, basePanel);
baseLayout.putConstraint(SpringLayout.SOUTH, attackPanel, 0,
SpringLayout.NORTH, statusPanel);
baseLayout.putConstraint(SpringLayout.EAST, attackPanel, 0,
SpringLayout.EAST, basePanel);
basePanel.add(attackPanel);
attackPanel.setVisible(false);
JPanel hidden_top1_panel = new JPanel();
hiddenLayout.putConstraint(SpringLayout.NORTH, hidden_top1_panel, 5,
SpringLayout.NORTH, hiddenPanel);
hiddenLayout.putConstraint(SpringLayout.WEST, hidden_top1_panel, 10,
SpringLayout.WEST, hiddenPanel);
hiddenLayout.putConstraint(SpringLayout.SOUTH, hidden_top1_panel, 35,
SpringLayout.NORTH, hiddenPanel);
hiddenLayout.putConstraint(SpringLayout.EAST, hidden_top1_panel, -10,
SpringLayout.EAST, hiddenPanel);
hiddenPanel.add(hidden_top1_panel);
JPanel hidden_bottom_panel = new JPanel();
hiddenLayout.putConstraint(SpringLayout.NORTH, hidden_bottom_panel,
-31, SpringLayout.SOUTH, hiddenPanel);
hiddenLayout.putConstraint(SpringLayout.WEST, hidden_bottom_panel, 10,
SpringLayout.WEST, hiddenPanel);
hiddenLayout.putConstraint(SpringLayout.SOUTH, hidden_bottom_panel, -5,
SpringLayout.SOUTH, hiddenPanel);
hiddenLayout.putConstraint(SpringLayout.EAST, hidden_bottom_panel, -10,
SpringLayout.EAST, hiddenPanel);
hiddenPanel.add(hidden_bottom_panel);
JSplitPane hidden_splitPanel = new JSplitPane();
hiddenLayout.putConstraint(SpringLayout.NORTH, hidden_splitPanel, 6, SpringLayout.SOUTH, hidden_top1_panel);
hiddenLayout.putConstraint(SpringLayout.WEST, hidden_splitPanel, 10,
SpringLayout.WEST, hiddenPanel);
hiddenLayout.putConstraint(SpringLayout.SOUTH, hidden_splitPanel, -6, SpringLayout.NORTH, hidden_bottom_panel);
hiddenLayout.putConstraint(SpringLayout.EAST, hidden_splitPanel, -10,
SpringLayout.EAST, hiddenPanel);
hidden_splitPanel.setResizeWeight(0.5);
hiddenPanel.add(hidden_splitPanel);
SpringLayout sl_hidden_top1_panel = new SpringLayout();
hidden_top1_panel.setLayout(sl_hidden_top1_panel);
JLabel lblLabel1 = new JLabel("Cover Message:");
sl_hidden_top1_panel.putConstraint(SpringLayout.NORTH, lblLabel1, 2,
SpringLayout.NORTH, hidden_top1_panel);
sl_hidden_top1_panel.putConstraint(SpringLayout.WEST, lblLabel1, 0,
SpringLayout.WEST, hidden_top1_panel);
sl_hidden_top1_panel.putConstraint(SpringLayout.SOUTH, lblLabel1, 27,
SpringLayout.NORTH, hidden_top1_panel);
lblLabel1.setAlignmentX(1.0f);
lblLabel1.setHorizontalAlignment(SwingConstants.LEFT);
hidden_top1_panel.add(lblLabel1);
tfCoverMessage = new JTextField();
sl_hidden_top1_panel.putConstraint(SpringLayout.WEST, tfCoverMessage, 26, SpringLayout.EAST, lblLabel1);
tfCoverMessage.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
coverMessage = showImage(tfCoverMessage.getText(),
lblCoverMessage);
}
});
sl_hidden_top1_panel.putConstraint(SpringLayout.NORTH, tfCoverMessage,
2, SpringLayout.NORTH, hidden_top1_panel);
sl_hidden_top1_panel.putConstraint(SpringLayout.SOUTH, tfCoverMessage,
27, SpringLayout.NORTH, hidden_top1_panel);
tfCoverMessage.setAlignmentX(Component.RIGHT_ALIGNMENT);
tfCoverMessage.setHorizontalAlignment(SwingConstants.LEFT);
hidden_top1_panel.add(tfCoverMessage);
tfCoverMessage.setColumns(10);
JButton btnCoverMessageBrowser = new JButton("...");
sl_hidden_top1_panel.putConstraint(SpringLayout.EAST, tfCoverMessage, -6, SpringLayout.WEST, btnCoverMessageBrowser);
sl_hidden_top1_panel.putConstraint(SpringLayout.NORTH, btnCoverMessageBrowser, 1, SpringLayout.NORTH, lblLabel1);
btnCoverMessageBrowser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnOpenShowDialogActionPerformed(tfCoverMessage);
}
});
hidden_top1_panel.add(btnCoverMessageBrowser);
JLabel lblLabel2 = new JLabel("Identifier:");
sl_hidden_top1_panel.putConstraint(SpringLayout.EAST, btnCoverMessageBrowser, -6, SpringLayout.WEST, lblLabel2);
sl_hidden_top1_panel.putConstraint(SpringLayout.NORTH, lblLabel2, 2, SpringLayout.NORTH, hidden_top1_panel);
sl_hidden_top1_panel.putConstraint(SpringLayout.WEST, lblLabel2, -100, SpringLayout.EAST, hidden_top1_panel);
sl_hidden_top1_panel.putConstraint(SpringLayout.SOUTH, lblLabel2, 27, SpringLayout.NORTH, hidden_top1_panel);
hidden_top1_panel.add(lblLabel2);
tfMessage = new JTextField();
sl_hidden_top1_panel.putConstraint(SpringLayout.NORTH, tfMessage, 2, SpringLayout.NORTH, hidden_top1_panel);
sl_hidden_top1_panel.putConstraint(SpringLayout.WEST, tfMessage, -40, SpringLayout.EAST, hidden_top1_panel);
sl_hidden_top1_panel.putConstraint(SpringLayout.SOUTH, tfMessage, 27, SpringLayout.NORTH, hidden_top1_panel);
hidden_top1_panel.add(tfMessage);
tfMessage.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
String text = tfMessage.getText();
if(text.length() > 3)
tfMessage.setText(text.substring(0, 3));
}
});
tfMessage.setHorizontalAlignment(SwingConstants.LEFT);
tfMessage.setColumns(3);
lblMessageInfo = new JLabel("");
statusLayout.putConstraint(SpringLayout.NORTH, lblMessageInfo, -0,
SpringLayout.NORTH, statusPanel);
statusLayout.putConstraint(SpringLayout.WEST, lblMessageInfo, 0,
SpringLayout.WEST, statusPanel);
statusLayout.putConstraint(SpringLayout.SOUTH, lblMessageInfo, 0,
SpringLayout.SOUTH, statusPanel);
statusLayout.putConstraint(SpringLayout.EAST, lblMessageInfo, 0,
SpringLayout.EAST, statusPanel);
lblMessageInfo.setVerticalAlignment(SwingConstants.BOTTOM);
statusPanel.add(lblMessageInfo);
JButton btn_hidden_Apply = new JButton("Apply");
btn_hidden_Apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySteganographyMethod();
}
});
hidden_bottom_panel.setLayout(new BorderLayout(0, 0));
hidden_bottom_panel.add(btn_hidden_Apply, BorderLayout.WEST);
btnSave = new JButton("Save");
btnSave.setEnabled(false);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveStegoObject();
}
});
hidden_bottom_panel.add(btnSave, BorderLayout.EAST);
pCoverMessage = new JScrollPane();
hidden_splitPanel.setLeftComponent(pCoverMessage);
lblCoverMessage = new JLabel("");
pCoverMessage.setViewportView(lblCoverMessage);
JScrollPane pMessage = new JScrollPane();
hidden_splitPanel.setRightComponent(pMessage);
lblMessage = new JLabel("");
pMessage.setViewportView(lblMessage);
JMenuBar menuBar = new JMenuBar();
frmStegoApplication.setJMenuBar(menuBar);
JMenu mnSteganogrphy = new JMenu("Steganography");
menuBar.add(mnSteganogrphy);
JRadioButtonMenuItem rdbtnmntmHiddenMessage = new JRadioButtonMenuItem(
"Hide Message");
rdbtnmntmHiddenMessage.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
JRadioButtonMenuItem source = (JRadioButtonMenuItem) arg0
.getSource();
boolean selected = source.isSelected();
if (selected) {
frmStegoApplication.setTitle(title + " - "
+ source.getText());
}
hiddenPanel.setVisible(selected);
}
});
buttonGroup.add(rdbtnmntmHiddenMessage);
mnSteganogrphy.add(rdbtnmntmHiddenMessage);
JRadioButtonMenuItem rdbtnmntmExtractMessage = new JRadioButtonMenuItem(
"Extract Message");
rdbtnmntmExtractMessage.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
JRadioButtonMenuItem source = (JRadioButtonMenuItem) arg0
.getSource();
boolean selected = source.isSelected();
if (selected) {
frmStegoApplication.setTitle(title + " - "
+ source.getText());
}
extractPanel.setVisible(selected);
}
});
buttonGroup.add(rdbtnmntmExtractMessage);
mnSteganogrphy.add(rdbtnmntmExtractMessage);
JMenu mnSteganoanalisys = new JMenu("Steganalysis");
menuBar.add(mnSteganoanalisys);
JRadioButtonMenuItem rdbtnmntmNewRadioItem = new JRadioButtonMenuItem(
"Analysis");
rdbtnmntmNewRadioItem.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
JRadioButtonMenuItem source = (JRadioButtonMenuItem) arg0
.getSource();
boolean selected = source.isSelected();
if (selected) {
frmStegoApplication.setTitle(title + " - "
+ source.getText());
}
attackPanel.setVisible(source.isSelected());
}
});
buttonGroup.add(rdbtnmntmNewRadioItem);
mnSteganoanalisys.add(rdbtnmntmNewRadioItem);
JPanel extract_top_panel = new JPanel();
extractLayout.putConstraint(SpringLayout.NORTH, extract_top_panel, 5,
SpringLayout.NORTH, extractPanel);
extractLayout.putConstraint(SpringLayout.SOUTH, extract_top_panel, 70,
SpringLayout.NORTH, extractPanel);
extractLayout.putConstraint(SpringLayout.WEST, extract_top_panel, 10,
SpringLayout.WEST, extractPanel);
extractLayout.putConstraint(SpringLayout.EAST, extract_top_panel, -10,
SpringLayout.EAST, extractPanel);
extractPanel.add(extract_top_panel);
SpringLayout sl_extract_top_panel = new SpringLayout();
extract_top_panel.setLayout(sl_extract_top_panel);
JLabel lblExtratedLabel1 = new JLabel("Image");
sl_extract_top_panel.putConstraint(SpringLayout.NORTH,
lblExtratedLabel1, 2, SpringLayout.NORTH, extract_top_panel);
sl_extract_top_panel.putConstraint(SpringLayout.WEST,
lblExtratedLabel1, 0, SpringLayout.WEST, extract_top_panel);
sl_extract_top_panel.putConstraint(SpringLayout.SOUTH,
lblExtratedLabel1, 27, SpringLayout.NORTH, extract_top_panel);
lblExtratedLabel1.setHorizontalAlignment(SwingConstants.LEFT);
extract_top_panel.add(lblExtratedLabel1);
tfImage = new JTextField();
sl_extract_top_panel.putConstraint(SpringLayout.WEST, tfImage, 10,
SpringLayout.EAST, lblExtratedLabel1);
tfImage.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
imageMessage = showImage(tfImage.getText(), lblImageMessage);
}
});
sl_extract_top_panel.putConstraint(SpringLayout.NORTH, tfImage, 2,
SpringLayout.NORTH, extract_top_panel);
sl_extract_top_panel.putConstraint(SpringLayout.SOUTH, tfImage, 27,
SpringLayout.NORTH, extract_top_panel);
tfImage.setHorizontalAlignment(SwingConstants.LEFT);
extract_top_panel.add(tfImage);
tfImage.setColumns(10);
JButton btnImageBrowser = new JButton("...");
sl_extract_top_panel.putConstraint(SpringLayout.EAST, tfImage, -10,
SpringLayout.WEST, btnImageBrowser);
btnImageBrowser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnOpenShowDialogActionPerformed(tfImage);
}
});
sl_extract_top_panel.putConstraint(SpringLayout.EAST, btnImageBrowser,
0, SpringLayout.EAST, extract_top_panel);
extract_top_panel.add(btnImageBrowser);
JLabel lblOriginal = new JLabel("Original");
sl_extract_top_panel.putConstraint(SpringLayout.NORTH, lblOriginal, 2, SpringLayout.SOUTH, lblExtratedLabel1);
sl_extract_top_panel.putConstraint(SpringLayout.WEST, lblOriginal, 0, SpringLayout.WEST, lblExtratedLabel1);
sl_extract_top_panel.putConstraint(SpringLayout.SOUTH, lblOriginal, 27, SpringLayout.SOUTH, lblExtratedLabel1);
lblOriginal.setHorizontalAlignment(SwingConstants.LEFT);
extract_top_panel.add(lblOriginal);
tfOriginalImage = new JTextField();
sl_extract_top_panel.putConstraint(SpringLayout.NORTH, tfOriginalImage, 0, SpringLayout.NORTH, lblOriginal);
sl_extract_top_panel.putConstraint(SpringLayout.WEST, tfOriginalImage, 0, SpringLayout.WEST, tfImage);
sl_extract_top_panel.putConstraint(SpringLayout.SOUTH, tfOriginalImage, 0, SpringLayout.SOUTH, lblOriginal);
sl_extract_top_panel.putConstraint(SpringLayout.EAST, tfOriginalImage, 0, SpringLayout.EAST, tfImage);
extract_top_panel.add(tfOriginalImage);
tfOriginalImage.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
originalMessage = getOriginalImage(tfOriginalImage.getText());
}
});
JButton btnOriginalImage = new JButton("...");
btnOriginalImage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnOpenShowDialogActionPerformed(tfOriginalImage);
}
});
sl_extract_top_panel.putConstraint(SpringLayout.WEST, btnOriginalImage, 0, SpringLayout.WEST, btnImageBrowser);
sl_extract_top_panel.putConstraint(SpringLayout.SOUTH, btnOriginalImage, 0, SpringLayout.SOUTH, lblOriginal);
extract_top_panel.add(btnOriginalImage);
JPanel extract_bottom_panel = new JPanel();
extractLayout.putConstraint(SpringLayout.NORTH, extract_bottom_panel,
-31, SpringLayout.SOUTH, extractPanel);
extractLayout.putConstraint(SpringLayout.WEST, extract_bottom_panel,
10, SpringLayout.WEST, extractPanel);
extractLayout.putConstraint(SpringLayout.SOUTH, extract_bottom_panel,
-5, SpringLayout.SOUTH, extractPanel);
extractLayout.putConstraint(SpringLayout.EAST, extract_bottom_panel,
-10, SpringLayout.EAST, extractPanel);
extractPanel.add(extract_bottom_panel);
SpringLayout sl_extract_bottom_panel = new SpringLayout();
extract_bottom_panel.setLayout(sl_extract_bottom_panel);
JButton btn_extract_Apply = new JButton("Apply");
sl_extract_bottom_panel.putConstraint(SpringLayout.NORTH,
btn_extract_Apply, 0, SpringLayout.NORTH, extract_bottom_panel);
sl_extract_bottom_panel
.putConstraint(SpringLayout.WEST, btn_extract_Apply, 140,
SpringLayout.WEST, extract_bottom_panel);
sl_extract_bottom_panel.putConstraint(SpringLayout.EAST,
btn_extract_Apply, -140, SpringLayout.EAST,
extract_bottom_panel);
btn_extract_Apply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applySteganoAnalisysMethod();
}
});
extract_bottom_panel.add(btn_extract_Apply);
JSplitPane extract_splitPanel = new JSplitPane();
extractLayout.putConstraint(SpringLayout.NORTH, extract_splitPanel, 70, SpringLayout.NORTH, extractPanel);
extractLayout.putConstraint(SpringLayout.WEST, extract_splitPanel, 10,
SpringLayout.WEST, extractPanel);
extractLayout.putConstraint(SpringLayout.SOUTH, extract_splitPanel, -6, SpringLayout.NORTH, extract_bottom_panel);
extractLayout.putConstraint(SpringLayout.EAST, extract_splitPanel, -10,
SpringLayout.EAST, extractPanel);
extract_splitPanel.setResizeWeight(0.5);
extractPanel.add(extract_splitPanel);
pImage = new JScrollPane();
extract_splitPanel.setLeftComponent(pImage);
lblImageMessage = new JLabel("");
pImage.setViewportView(lblImageMessage);
JScrollPane pMessageExtracted = new JScrollPane();
extract_splitPanel.setRightComponent(pMessageExtracted);
lblMessageExtracted = new JLabel("");
pMessageExtracted.setViewportView(lblMessageExtracted);
}
private ICoverMessage showImage(String address, JLabel lblImage) {
File file = new File(address);
if (file.exists() && imageFilter.accept(file)) {
showMessage("Opening: " + file.getName());
try {
FileInputStream stream = new FileInputStream(file);
if (loadImage(stream, lblImage)){
Mat original = Highgui.imread(address);
return new MatImage(original, Utils.getExtension(address));
}
} catch (IOException e) {
showMessage("Sorry, cannot load the file");
}
} else {
showMessage("It's a wrong file");
}
return null;
}
private ICoverMessage getOriginalImage(String address) {
File file = new File(address);
if (file.exists() && imageFilter.accept(file)) {
showMessage("Reading: " + file.getName());
Mat original = Highgui.imread(address);
if(original.size().width == 0)
showMessage("Sorry, cannot load the file");
else
return new MatImage(original, Utils.getExtension(address));
} else {
showMessage("It's a wrong file");
}
return null;
}
protected void tfMessageTextChange(String address, JLabel elementToShow) {
File file = new File(address);
if (!file.exists()) {
showMessage("It's a wrong file");
return;
}
showMessage("Opening: " + file.getName());
try{
message = new FileMessage(file);
if (imageFilter.accept(file))
{
loadImage(new FileInputStream(file), elementToShow);
}
else
{
loadTextFile(message, elementToShow);
showMessage("");
}
}catch(IOException ex){
showMessage("Sorry, cannot load the file");
}
}
private void loadTextFile(FileMessage file, JLabel elementToShow) {
lblMessage.setText("<html>" + new String(message.getAllBytes()) + "</html>");
lblMessage.setIcon(null);
lblMessage.revalidate();
}
private boolean loadImage(InputStream stream, JLabel canvas) {
try {
Image image = ImageIO.read(stream);
ImageIcon imageIcon = new ImageIcon(image);
canvas.setText("");
canvas.setIcon(imageIcon);
showMessage("");
} catch (Exception e) {
showMessage("Sorry, cannot show the image.");
}
return true;
}
private void btnOpenShowDialogActionPerformed(JTextField textField) {
fc.setAcceptAllFileFilterUsed(false);
try{
int returnVal = fc.showOpenDialog(frmStegoApplication);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
textField.setText(file.getPath());
} else {
showMessage("Open command cancelled by user.");
}
}catch(Exception e){
showMessage("Error showing the image");
}
}
private void showMessage(String message) {
lblMessageInfo.setText(message);
}
private void applySteganographyMethod() {
stegoObject = null;
if (coverMessage == null) {
showMessage("Please, select the cover message file.");
return;
}
String identifier = tfMessage.getText();
if (identifier.length() == 0) {
showMessage("Please, enter the identifier.");
return;
}
Transform2d alg = new Transform2dBasic(new FastDiscreteBiorthogonal_CDF_9_7());
DWT2D_HL_LH_Algorithm steganoAlgorithm = new DWT2D_HL_LH_Algorithm(null, alg, visibilityfactor, 1);
KeyPointImageAlgorithm algorithm = new KeyPointImageAlgorithm(coverMessage,
steganoAlgorithm, visibilityfactor, keyPointSize, howManyPoints, null);
IMessage embeddedData = new CacheMessage(identifier.getBytes());
MatImage stegoObject = (MatImage)algorithm.getStegoObject(embeddedData);
setStegoObject(stegoObject);
}
private void setStegoObject(ICoverMessage stego) {
stegoObject = stego;
btnSave.setEnabled(stego != null);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
stegoObject.save(stream);
InputStream in = new ByteArrayInputStream(stream.toByteArray());
loadImage(in, lblMessage);
} catch (IOException e) {
showMessage("Error, showing stego-object");
}
}
protected void saveStegoObject() {
if(stegoObject == null)
{
showMessage("There is nothing to save");
return;
}
fc.setAcceptAllFileFilterUsed(true);
int returnVal = fc.showSaveDialog(frmStegoApplication);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
String path = fc.getSelectedFile().getPath();
stegoObject.save(new FileOutputStream(path));
showMessage("File was saved successfully.");
} catch (IOException e) {
showMessage("Error, saving file.");
}
} else {
showMessage("Open command cancelled by user.");
}
}
private void applySteganoAnalisysMethod() {
if (imageMessage == null) {
showMessage("Please, select the image message file.");
return;
}
if (originalMessage == null) {
showMessage("Please, select the original image file.");
return;
}
Transform2d alg = new Transform2dBasic(new FastDiscreteBiorthogonal_CDF_9_7());
DWT2D_HL_LH_Algorithm steganoAlgorithm = new DWT2D_HL_LH_Algorithm(null, alg, visibilityfactor, 1);
KeyPointImageAlgorithm algorithm = new KeyPointImageAlgorithm(imageMessage,
steganoAlgorithm, visibilityfactor, keyPointSize, howManyPoints, originalMessage);
try {
byte[] embeddedData = algorithm.getEmbeddedData();
ImageFactory factory = new ImageFactory();
BufferedImage image = factory.createImage(keyPointSize >> 1, keyPointSize >> 1, embeddedData);
String outfile = "message.bmp";
FileOutputStream file = new FileOutputStream(outfile);
ImageIO.write(image, "bmp", file);
file.close();
tfMessageTextChange(outfile, lblMessageExtracted);
} catch (IOException e) {
showMessage("Error, saving file.");
}
}
}
|
Java
|
UTF-8
| 3,979 | 2.578125 | 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 Graphics;
import Math.CoordinateTranslator;
import Math.Point2D;
import Math.PointManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import java.awt.Point;
/**
*
* @author Bakuryu
*/
public class TowerButton
{
private Sprite towerSpr;
private String towerType;
private Point2D position;
private ShapeDrawer sDraw;
private SpriteBatch sBatch;
private CoordinateTranslator corT2;
private Rectangle buttonOutline;
private Point2D mouseWP;
private Point mouseSP;
private boolean isSelected;
private PointManager pointM;
public TowerButton(double x, double y, String type, CoordinateTranslator corT2, PointManager pM)
{
buttonOutline = new Rectangle();
pointM = pM;
this.corT2 = corT2;
sBatch = new SpriteBatch();
sDraw = new ShapeDrawer();
position = new Point2D(x, y);
mouseWP = new Point2D();
mouseSP = new Point();
towerType = type;
isSelected = false;
createButton();
}
public void render()
{
if (isSelected)
{
sDraw.drawRect((int) (buttonOutline.x - 10), (int) (buttonOutline.y - 10), (int) buttonOutline.width, (int) buttonOutline.height, 3, Color.BLUE);
}
mouseSP = new Point(Gdx.input.getX(), 560 - Gdx.input.getY());
mouseWP = new Point2D(corT2.screenToWorld(mouseSP));
if (Gdx.input.isButtonPressed(Input.Buttons.LEFT))
{
if (buttonOutline.contains(mouseSP.x, mouseSP.y))
{
if (towerType == "reg" && pointM.getPoints() >= 3 || towerType == "sup" && pointM.getPoints() >= 8)
{
isSelected = true;
}
}
}
}
private void createButton()
{
if (towerType == "reg")
{
towerSpr = new Sprite(new Texture("graphics/RegTower.png"));
buttonOutline = new Rectangle(corT2.worldToScreen(position).x, corT2.worldToScreen(position).y, (int) (towerSpr.getWidth() * 1.5) + 3, (int) (towerSpr.getHeight() * 1.5) + 3);
}
if (towerType == "sup")
{
towerSpr = new Sprite(new Texture("graphics/SupTower.png"));
buttonOutline = new Rectangle(corT2.worldToScreen(position).x, corT2.worldToScreen(position).y, (int) (towerSpr.getWidth() * 1.5) + 3, (int) (towerSpr.getHeight() * 1.5) + 3);
}
// sBatch.begin();
// sBatch.draw(towerSpr, corT2.worldToScreen(position).x, corT2.worldToScreen(position).y, towerSpr.getWidth() / 2, towerSpr.getHeight() / 2, towerSpr.getWidth(), towerSpr.getHeight(), (float) 1.5, (float) 1.5, 0);
// sBatch.end();
//sDraw.drawRect(buttonOutline.x - 10, buttonOutline.y - 10, (int) (buttonOutline.width * 1.5) + 3, (int) (buttonOutline.height * 1.5) + 3, 3, Color.RED);
//sDraw.drawRect((int)(corT2.worldToScreen(position).x-10), (int)(corT2.worldToScreen(position).y-10), (int)(towerSpr.getWidth()*1.5)+3, (int)(towerSpr.getHeight()*1.5)+3, 3, Color.BLACK);
}
public void deselectButton()
{
isSelected = false;
}
public boolean getIsSelected()
{
return isSelected;
}
public Sprite getSprite()
{
return towerSpr;
}
public Point2D getPosition()
{
return position;
}
public String getTButtonType()
{
return towerType;
}
}
|
C++
|
UTF-8
| 2,422 | 2.6875 | 3 |
[] |
no_license
|
//*******************************************************************
//
// License: See top level LICENSE.txt file.
//
// Author: Garrett Potts (gpotts@imagelinks.com)
//
//*************************************************************************
// $Id: rspfColorProperty.cpp 13667 2008-10-02 19:59:55Z gpotts $
#include <sstream>
#include <rspf/base/rspfColorProperty.h>
RTTI_DEF1(rspfColorProperty, "rspfColorProperty", rspfProperty);
rspfColorProperty::rspfColorProperty(const rspfString& name,
const rspfRgbVector& value)
:rspfProperty(name),
theValue(value)
{
}
rspfColorProperty::rspfColorProperty(const rspfColorProperty& rhs)
:rspfProperty(rhs),
theValue(rhs.theValue)
{
}
rspfColorProperty::~rspfColorProperty()
{
}
rspfObject* rspfColorProperty::dup()const
{
return new rspfColorProperty(*this);
}
const rspfProperty& rspfColorProperty::assign(const rspfProperty& rhs)
{
rspfProperty::assign(rhs);
rspfColorProperty* rhsPtr = PTR_CAST(rspfColorProperty, &rhs);
if(rhsPtr)
{
theValue = rhsPtr->theValue;
}
else
{
setValue(rhs.valueToString());
}
return *this;
}
bool rspfColorProperty::setValue(const rspfString& value)
{
bool result = false;
std::vector<rspfString> splitArray;
value.split(splitArray, " ");
if(splitArray.size() == 3)
{
int r,g,b;
r = splitArray[0].toInt32();
g = splitArray[1].toInt32();
b = splitArray[2].toInt32();
result = true;
theValue = rspfRgbVector(r,g,b);
}
return result;
}
void rspfColorProperty::valueToString(rspfString& valueResult)const
{
ostringstream out;
out << (int)theValue.getR() << " " << (int)theValue.getG() << " " << (int)theValue.getB() << endl;
valueResult = out.str().c_str();
}
const rspfRgbVector& rspfColorProperty::getColor()const
{
return theValue;
}
void rspfColorProperty::setColor(const rspfRgbVector& value)
{
theValue = value;
}
rspf_uint8 rspfColorProperty::getRed()const
{
return theValue.getR();
}
rspf_uint8 rspfColorProperty::getGreen()const
{
return theValue.getG();
}
rspf_uint8 rspfColorProperty::getBlue()const
{
return theValue.getB();
}
void rspfColorProperty::setRed(rspf_uint8 r)
{
theValue.setR(r);
}
void rspfColorProperty::setGreen(rspf_uint8 g)
{
theValue.setG(g);
}
void rspfColorProperty::setBlue(rspf_uint8 b)
{
theValue.setB(b);
}
|
Markdown
|
UTF-8
| 1,580 | 2.984375 | 3 |
[] |
no_license
|
# 后台访问权限控制 \|
## 需求 <a id="需求"></a>
* 解决普通用户登录之后直接访问后台具体的视图函数的问题
* 如果是普通用户访问后台的视图函数,直接跳转到项目主页,不再执行后续的逻辑判断
* 后台后续要实现多个视图函数,如果每一个函数内部都去判断用户权限,那么代码重复率高,冗余代码较多
* 所以得有一个统一判断入口,后台模块中,除了登录页面,后台的其他页面都要判断是否具有管理员权限
* 采用的方式为:请求勾子中的 before\_request,来请求之前进行判断
## 代码实现 <a id="代码实现"></a>
* 在 `modules/admin/__init__.py` 文件中,添加请求勾子函数
```text
@admin_blu.before_request
def before_request():
if not request.url.endswith(url_for("admin.admin_login")):
user_id = session.get("user_id")
is_admin = session.get("is_admin", False)
if not user_id or not is_admin:
return redirect('/')
```
* 完善退出登录相关代码,在退出登录时候,也要清空是否是管理员的相关数据
* 在 `modules/passport/views.py` 中
```text
@passport_blu.route("/logout", methods=['POST'])
def logout():
"""
清除session中的对应登录之后保存的信息
:return:
"""
session.pop('user_id', None)
session.pop('nick_name', None)
session.pop('mobile', None)
session.pop('is_admin', None)
return jsonify(errno=RET.OK, errmsg="OK")
```
|
C#
|
UTF-8
| 2,139 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace NoIPClient.NoIPApi
{
internal static class UpdateManager
{
public static async Task<UpdateResult> Update(NoIPApiSettings settings)
{
var ip = await NoIPApiWebRequest.DetectIp();
if (ip != null)
{
return await NoIPApiWebRequest.Update(settings.UserName, settings.Password, settings.UpdateHosts, ip.ToString());
}
return null;
}
public static async Task UpdateLoop(TimeSpan delay, NoIPApiSettings settings)
{
var currentDelay = delay;
var ip = IPAddress.None;
while (true)
{
var newIP = await NoIPApiWebRequest.DetectIp();
if (newIP != null && newIP != ip)
{
ip = newIP;
var result = await NoIPApiWebRequest.Update(settings.UserName, settings.Password, settings.UpdateHosts, ip.ToString());
if (result.Exception != null) throw result.Exception;
if (!result.IsOkay)
{
currentDelay = TimeSpan.FromMinutes(30);
bool fatal = false;
switch (result.State)
{
case UpdateResultState.BadAuth:
case UpdateResultState.BadAgent:
case UpdateResultState.Abuse:
case UpdateResultState.NoDonator:
fatal = true;
break;
default:
break;
}
if (fatal) break; // end loop
}
else
{
currentDelay = delay;
}
}
await Task.Delay(currentDelay);
}
}
}
}
|
Java
|
UTF-8
| 1,414 | 2.1875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com).
*
* 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.igormaznitsa.jcp.containers;
/**
* The enumeration contains flags describe inside special preprocessor states
*
* @author Igor Maznitsa (igor.maznitsa@igormaznitsa.com)
*/
public enum PreprocessingFlag {
/**
* This flag shows that it is allowed to print texts into an output stream
*/
TEXT_OUTPUT_DISABLED,
/**
* This flag shows that we must comment the next line (one time flag)
*/
COMMENT_NEXT_LINE,
/**
* This flag shows that the current //#if construction in the passive state
*/
IF_CONDITION_FALSE,
/**
* This flag shows that //#break has been met
*/
BREAK_COMMAND,
/**
* This flag shows that preprocessing must be ended on the next string
*/
END_PROCESSING,
/**
* This flag allows to stop preprocessing immediately
*/
ABORT_PROCESSING
}
|
JavaScript
|
UTF-8
| 5,299 | 3.296875 | 3 |
[] |
no_license
|
// need to add local storage in this program
class budget {
constructor() {
this.expenseAmount = 0;
this.budgetAmount = 0;
this.balanceAmount = 0;
this.expenseCollection = [];
this.id = 0;
}
showBudget(budget) {
this.budgetAmount = budget;
this.balanceAmount = budget;
document.querySelector("#budget-amount").innerHTML = budget;
document.querySelector("#balance-amount").innerHTML = budget;
}
showAlert(message, status) {
let alertDiv = document.createElement("div");
alertDiv.className = `alert alert-${status}`;
alertDiv.appendChild(document.createTextNode(message))
let container = document.querySelector(".mainContainer");
console.log(container);
let heading = document.querySelector(".heading");
container.insertBefore(alertDiv, heading);
setTimeout(() => {
alertDiv.style.display = "none";
}, 3000);
}
showExpensesInTable(name, amount) {
let tableBody = document.querySelector("#expenseBody");
let tableRow = document.createElement("tr");
tableRow.innerHTML = `<td>${name}</td>
<td>${amount}</td>
<td><a href="" class="edit"><i class="fas fa-edit edit"></i></a></td>
<td><a href = "" class ="trash"> <i class="fas fa-trash trash"></a></td>`
tableBody.appendChild(tableRow);
this.addingExpenses(amount);
}
addingExpenses(amount) {
this.expenseCollection.push(parseInt(amount));
let reducer = (accumulator, currentValue) => accumulator + currentValue
this.expenseAmount = this.expenseCollection.reduce(reducer);
document.querySelector("#expense-amount").innerHTML = this.expenseAmount;
this.balanceAfterAddingExpense(parseInt(amount))
}
balanceAfterAddingExpense(amount) {
this.budgetAmount = this.budgetAmount - amount;
document.querySelector("#balance-amount").innerHTML = this.budgetAmount;
}
updatingExpenseAndBalanceAfterDeletion(expense) {
expense = parseInt(expense);
this.expenseAmount = this.expenseAmount - expense;
this.budgetAmount = this.budgetAmount + expense;
document.querySelector("#balance-amount").innerHTML = this.budgetAmount;
document.querySelector("#expense-amount").innerHTML = this.expenseAmount;
}
clearFields() {
document.querySelector("#budget-input").value = "";
document.querySelector("#expense-input").value = "";
document.querySelector("#amount-input").value = "";
}
editingTable(expenseAmount, expenseName) {
// document.querySelector(".expense-title").contentEditable = "true";
expenseAmount.contentEditable = "true";
expenseAmount.style.color = "red";
expenseName.contentEditable = "true";
expenseName.stylecolor = "red";
}
}
function eventlisteners() {
let budgetForm = document.querySelector("#budget-form");
let expenseForm = document.querySelector("#expense-form");
let icons = document.querySelector(".icon-collector");
// instantiate class
let budget1 = new budget();
budgetForm.addEventListener("submit", (e) => {
e.preventDefault();
let budgetInput = document.querySelector("#budget-input").value;
if (budgetInput == "" || budgetInput < 0) {
budget1.showAlert("dont keep the budget empty", "danger");
}
budget1.showBudget(budgetInput);
budget1.clearFields();
})
expenseForm.addEventListener("submit", (e) => {
e.preventDefault();
let expenseInput = document.querySelector("#expense-input").value;
let amountInput = document.querySelector("#amount-input").value;
let budgetAmount = document.querySelector("#budget-amount").textContent;
console.log(budgetAmount);
if (expenseInput == "" || amountInput == "" || amountInput < 0) {
budget1.showAlert("dont keep the expense empty", "danger");
} else if (budgetAmount == 0) {
alert("please enter the budget first");
}
else {
budget1.showExpensesInTable(expenseInput, amountInput);
budget1.clearFields();
}
})
icons.addEventListener("click", (e) => {
e.preventDefault();
if (e.target.classList.contains("trash")) {
let expense = e.target.parentElement.parentElement.parentElement.children[1].textContent;
console.log("deleted");
// expense = parseInt(expense);
let rowToBeRemoved = e.target.parentElement.parentElement.parentElement
rowToBeRemoved.remove();
budget1.updatingExpenseAndBalanceAfterDeletion(expense);
}
if (e.target.classList.contains("edit")) {
console.log("edited");
let expenseAmount = e.target.parentElement.parentElement.previousElementSibling;
let expenseName = expenseAmount.previousElementSibling;
console.log(expenseName);
budget1.editingTable(expenseAmount, expenseName);
}
})
}
document.addEventListener("DOMContentLoaded", () => {
eventlisteners();
})
|
PHP
|
UTF-8
| 2,896 | 2.703125 | 3 |
[] |
no_license
|
<?php
namespace App\Services;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
class OAuthProxy extends Proxy
{
const REFRESH_TOKEN = 'refreshToken';
public function __construct(){
parent::__construct(app());
}
/**
* Attempt to create an access token using user credentials
*
* @param string $email
* @param string $password
* @throws \App\Exceptions\Festigeek\FailedInternalRequestException
*/
public function attemptLogin($email, $password)
{
return $response = $this->request('password', [
'username' => $email,
'password' => $password
]);
}
/**
* Attempt to refresh the access token used a refresh token that
* has been saved in a cookie.
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function attemptRefresh(Request $request)
{
return $this->proxy('refresh_token', [
'refresh_token' => $request->cookie(self::REFRESH_TOKEN)
]);
}
/**
* Request a proxy call to the OAuth server.
*
* @param string $grantType what type of grant type should be proxied
* @param array $data the data to send to the server
* @throws \App\Exceptions\Festigeek\FailedInternalRequestException
*/
private function request($grantType, array $data = [])
{
$data = array_merge($data, [
'client_id' => env('OAUTH_PASSWORD_CLIENT_ID'),
'client_secret' => env('OAUTH_PASSWORD_CLIENT_SECRET'),
'grant_type' => $grantType
]);
$proxyResponse = parent::doRequest('post', '/oauth/token', $data);
$data = json_decode($proxyResponse->content());
$response = response()->json([
'success' => 'Authenticated.',
'token' => $data->access_token,
'token_type' => 'bearer',
'expires_in' => $data->expires_in
])->cookie(
self::REFRESH_TOKEN,
$data->refresh_token,
864000, // 10 days
null,
null,
false,
true // HttpOnly
);
return $response;
}
/**
* Logs out the user. We revoke access token and refresh token.
* Also instruct the client to forget the refresh cookie.
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function logout(Request $request)
{
$accessToken = $request->user()->token();
DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update(['revoked' => true]);
$accessToken->revoke();
Cookie::queue(Cookie::forget(self::REFRESH_TOKEN));
return response()->json(['Logout successful'], 204);
}
}
|
Ruby
|
UTF-8
| 2,236 | 2.625 | 3 |
[] |
no_license
|
require 'spec_helper'
describe Table do
let(:retro) { create :retro }
context "setup" do
it "has no seats to begin with" do
retro.seats.count.should eq 0
end
it "has a valid factory" do
retro.should be_valid
end
end
context "creation" do
it "creates the record in the database" do
expect {
retro.save.should be_true
}.to change(Table, :count).by(1)
end
end
context "validations" do
it "has a name" do
build(:retro, :name => "Elephant").should be_valid
end
it "is invalid without a name" do
build(:retro, :name => nil).should_not be_valid
end
end
context "with a team" do
let(:team) { create :team }
let(:retro_with_team) { create(:retro, :team => team) }
it "has a team" do
retro_with_team.team.should eq team
end
end
it "allows voting by default"
context "editing" do
let(:team) { create(:team) }
let(:team_two) { create(:team) }
before do
create(:retro, :name => "First Table",
:date => Date.today,
:voting_allowed => false,
:team_id => team.id
)
end
it "allows changing the name" do
retro.update_attributes!({:name => "Nemo"})
retro.name.should eq("Nemo")
end
it "allows editing of date" do
retro.update_attributes!({:date => Date.tomorrow})
retro.date.should eq(Date.tomorrow)
end
it "allows toggling of 'voting allowed'" do
retro.update_attributes!({:voting_allowed => true})
retro.voting_allowed.should be_true
end
it "allows you to change team" do
retro.update_attributes!({:team_id => team_two.id})
retro.team.id.should eq team_two.id
end
end
context "deleting a retro with seats" do
let(:retro_with_seats) { create(:retro_with_seats) }
it "deletes the retro" do
retro_with_seats.seats.count.should eq 3
expect {
retro_with_seats.destroy
}.to change(Seat, :count).by(-3)
end
end
describe "connotations" do
it "returns the connotations relevant to the retro" do
retro.connotations.map do |c|
c.name
end.should eq ["Positive", "Neutral", "Negative"]
end
end
end
|
Ruby
|
UTF-8
| 442 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'little_lisp'
require 'Trollop'
require 'pry'
opts = Trollop.options do
version "v#{LittleLisp::VERSION}"
opt :source_file, 'Path to source file', type: :string
end
file_name = File.expand_path(opts[:source_file])
Trollop.die :source_file, 'must exist' unless File.exist?(file_name)
File.open(file_name) do |f|
tokens = LittleLisp::Parser.parse(f.read)
LittleLisp::Interpreter.interpret(tokens)
end
|
Python
|
UTF-8
| 427 | 3.359375 | 3 |
[] |
no_license
|
class Father():
def gardening(self):
print("I like gardening")
class Mother():
def cooking(self):
print("I like cooking")
class Child1(Father,Mother):
def art(self):
print("I like art")
class Child2(Father,Mother):
def sports(self):
print("I like sports")
c1 = Child1()
c1.gardening()
c1.art()
c1.cooking()
c2 = Child2()
c2.cooking()
c2.gardening()
c2.sports()
c2.art()
|
Java
|
UTF-8
| 438 | 1.914063 | 2 |
[
"MIT"
] |
permissive
|
package com.onevgo.bookstore.domain;
import lombok.Data;
import java.sql.Date;
import java.util.LinkedHashSet;
import java.util.Set;
@Data
public class Trade {
//Trade 对象对应的 id
private Integer tradeId;
//交易的时间
private Date tradeTime;
//Trade 关联的多个 TradeItem
private Set<TradeItem> items;
//和 Trade 关联的 User 的 userId
private Integer userId;
}
|
Java
|
UTF-8
| 603 | 2.390625 | 2 |
[] |
no_license
|
package es.igae.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import es.igae.entities.Cliente;
import es.igae.persistence.ClienteDao;
@Service
public class ServicioImpl implements Servicio {
@Autowired
private ClienteDao clienteDao;
@Override
public String getSaludo(String nombre) {
clienteDao.insertar(new Cliente(1, "Victor", "Herrero", "123456789"));
return getPrefijo() + nombre + getSufijo();
}
private String getPrefijo() {
return "Hola ";
}
private String getSufijo() {
return " !!!";
}
}
|
Java
|
UTF-8
| 288 | 1.742188 | 2 |
[] |
no_license
|
package leadme.dao;
import leadme.domain.CourseEnrollment;
import leadme.domain.Tour;
public interface CourseEnrollmentDao {
int courseerolltour(Tour tour);
int coursedetail(CourseEnrollment courseEnrollment);
int coursephotodetail(CourseEnrollment courseEnrollment);
}
|
Go
|
UTF-8
| 1,277 | 2.921875 | 3 |
[] |
no_license
|
package main
import (
"net/http"
"strconv"
"github.com/labstack/echo/v4"
)
type User struct {
Id int `json "id"`
Name string `json "name"`
Age int `json "age"`
}
var users = map[int]*User{}
func getAllUsers(c echo.Context) error {
return c.JSON(http.StatusOK, users)
}
func getUser(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
return c.JSON(http.StatusOK, users[id])
}
func createUser(c echo.Context) error {
user := &User{}
if err := c.Bind(user); err != nil {
return err
}
users[user.Id] = user
return c.JSON(http.StatusOK, user)
}
func updateUser(c echo.Context) error {
user := new(User)
id, _ := strconv.Atoi(c.Param("id"))
if err := c.Bind(user); err != nil {
return err
}
users[id] = user
return c.JSON(http.StatusOK, user)
}
func deleteUser(c echo.Context) error {
id, _ := strconv.Atoi(c.Param("id"))
delete(users, id)
return c.JSON(http.StatusOK, "Delete Users")
}
func main() {
e := echo.New()
// e.Use(middleware.Logger())
// e.Use(middleware.Recover())
group := e.Group("/k")
group.GET("/users", getAllUsers)
group.GET("/users/:id", getUser)
group.POST("/users", createUser)
group.PUT("/users/:id", updateUser)
group.DELETE("/users/:id", deleteUser)
e.Logger.Fatal(e.Start(":1323"))
}
|
C#
|
UTF-8
| 1,256 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace POCS
{
public class DPDetails
{
private decimal deliveryPointId;
public decimal DeliveryPointId
{
get
{
return deliveryPointId;
}
set
{
deliveryPointId = value;
}
}
private string deliveryPointName;
public string DeliveryPointName
{
get
{
return deliveryPointName;
}
set
{
deliveryPointName = value;
}
}
private string deliveryPointAddress;
public string DeliveryPointAddress
{
get
{
return deliveryPointAddress;
}
set
{
deliveryPointAddress = value;
}
}
public DPDetails(decimal DeliveryPointId, string DeliveryPointName, string DeliveryPointAddress)
{
this.DeliveryPointId = DeliveryPointId;
this.DeliveryPointName = DeliveryPointName;
this.DeliveryPointAddress = DeliveryPointAddress;
}
}
}
|
Java
|
UTF-8
| 694 | 4.21875 | 4 |
[] |
no_license
|
//Create Ninja class that extends from the Human class.
public class Ninja extends Human{
public Ninja(){
//Ninja: Set default stealth to 10
this.stealth = 10;
}
//Ninja: Add a method steal(Human) that takes the amount of stealth the ninja has, removes it from the other human's health, and adds it to the ninja's
public void steal(Human target){
target.health -= this.stealth; //takes health from another human by their stealth level
this.health += this.stealth;
}
//Ninja: Add a method runAway() that decreases their health by 10
public void runAway(){
this.health -= 10; //run away decreases ninja's health by 10
}
}
|
Markdown
|
UTF-8
| 8,841 | 2.8125 | 3 |
[] |
no_license
|
# INE5416 - Paradigmas de Programação
# Trabalho VI - Programação Lógica - Prolog
# Sistema Especialista para Diagnósticos de Doenças Transmitidas pelo Aedes Aegypti
### Aluno: Daniel de Souza Baulé (16200639)
Realização das consultas ao sistema especialista para cada regra descrita no artigo *"Utilização de Sistema Especialista para Diagnósticos de Doenças
Transmitidas pelo Aedes Aegypti"*.
Algumas consultas utilizam chamadas especiais que verificam apenas as regras relacionadas com a consulta em particular, isso se dá devido ao sistema chegar a uma conclusão antes de realizar todas as consultas no caso da consulta principal `doenca(X).`. Logo, é necessário ir direto para as consultas relacionadas para validar as regras, através de chamadas como `doencaManchas(X).` e `doencaDorMuscular(X).`, por exemplo.
### REGRA 1
**SE** temperatura corporal = acima de 38 ºC **E** duração febre = 2 a 3 dias **ENTÃO** chikungunya
```Prolog
?- doenca(X).
Temperatura corporal acima de 38 graus?
|: s.
Febre durou de 2 a 3 dias?
|: s.
X = chikungunya .
```
### REGRA 2
**SE** temperatura corporal = acima de 38 ºC **E** duração febre = 4 a 7 dias **ENTÃO** dengue
```Prolog
?- doenca(X).
Temperatura corporal acima de 38 graus?
|: s.
Febre durou de 2 a 3 dias?
|: n.
Febre durou de 4 a 7 dias?
|: s.
X = dengue .
```
### REGRA 3
**SE** temperatura corporal = abaixo de 38 ºC **ENTÃO** zika
```Prolog
?- doenca(X).
Temperatura corporal acima de 38 graus?
|: n.
X = zika .
```
### REGRA 4
**SE** dia de aparecimento de manchas na pele = 1º ou 2º **ENTÃO** zika
```Prolog
?- doencaManchas(X).
Aparecimento de manchas na pele?
|: s.
A partir do 1o ou 2o dia?
|: s.
X = zika.
```
### REGRA 5
**SE** dia de aparecimento de manchas na pele = 2º ao 5º **ENTÃO** chikungunya
```Prolog
?- doencaManchas(X).
Aparecimento de manchas na pele?
|: s.
A partir do 1o ou 2o dia?
|: n.
A partir do 2o ao 5o dia?
|: s.
X = chikungunya.
```
### REGRA 6
**SE** dia de aparecimento de manchas na pele = a partir do 4º **ENTÃO** dengue
```Prolog
?- doencaManchas(X).
Aparecimento de manchas na pele?
|: s.
A partir do 1o ou 2o dia?
|: n.
A partir do 2o ao 5o dia?
|: n.
A partir do 4o dia?
|: s.
X = dengue.
```
### REGRA 7
**SE** dia de aparecimento de manchas na pele = não tem manchas **ENTÃO** dengue
```Prolog
?- doencaManchas(X).
Aparecimento de manchas na pele?
|: n.
X = dengue.
```
### REGRA 8
**SE** dor nos músculos = com dor **E** intensidade = intensa **ENTÃO** dengue
```Prolog
?- doencaDorMuscular(X).
Sofre dor muscular?
|: s.
A dor eh intensa?
|: s.
X = dengue.
```
### REGRA 9
**SE** dor nos músculos = com dor **E** intensidade = moderada **ENTÃO** zika
```Prolog
?- doencaDorMuscular(X).
Sofre dor muscular?
|: s.
A dor eh intensa?
|: n.
A dor eh moderada?
|: s.
X = zika.
```
### REGRA 10
**SE** dor nos músculos = com dor **E** intensidade = leve **ENTÃO** chikungunya
```Prolog
?- doencaDorMuscular(X).
Sofre dor muscular?
|: s.
A dor eh intensa?
|: n.
A dor eh moderada?
|: n.
A dor eh leve?
|: s.
X = chikungunya.
```
### REGRA 11
**SE** dor nos músculos = sem dor **ENTÃO** não tem doença
```Prolog
?- doencaDorMuscular(X).
Sofre dor muscular?
|: n.
false.
```
### REGRA 12
**SE** dor nas articulações = com dor **E** intensidade = intensa **ENTÃO** chikungunya
```Prolog
?- doencaDorNasArticulacoes(X).
Sofre de dor nas articulacoes?
|: s.
A dor eh intensa?
|: s.
X = chikungunya.
```
### REGRA 13
**SE** dor nas articulações = sem dor **ENTÃO** não tem doença
```Prolog
?- doencaDorNasArticulacoes(X).
Sofre de dor nas articulacoes?
|: n.
false.
```
### REGRA 14
**SE** dor nas articulações = com dor **E** intensidade = leve **ENTÃO** dengue
```Prolog
?- doencaDorNasArticulacoes(X).
Sofre de dor nas articulacoes?
|: s.
A dor eh intensa?
|: n.
A dor eh moderada?
|: n.
A dor eh leve?
|: s.
X = dengue.
```
### REGRA 15
**SE** dor nas articulações = com dor **E** intensidade = moderada **ENTÃO** zika
```Prolog
?- doencaDorNasArticulacoes(X).
Sofre de dor nas articulacoes?
|: s.
A dor eh intensa?
|: n.
A dor eh moderada?
|: s.
X = zika.
```
### REGRA 16
**SE** Edema nas articulações = não tenho **ENTÃO** dengue
```Prolog
Aparicao de edema nas articulacoes?
|: n.
X = dengue.
```
### REGRA 17
**SE** Edema nas articulações = leve intensidade **ENTÃO** zika
```Prolog
?- doencaEdemaNasArticulacoes(X).
Aparicao de edema nas articulacoes?
|: s.
Edema de intensidade leve?
|: s.
X = zika.
```
### REGRA 18
**SE** Edema nas articulações = moderada ou intensa **ENTÃO** chikungunya
```Prolog
?- doencaEdemaNasArticulacoes(X).
Aparicao de edema nas articulacoes?
|: s.
Edema de intensidade leve?
|: n.
Edema de intensidade moderada ou intensa?
|: s.
X = chikungunya.
```
### REGRA 19
**SE** conjuntivite = tenho **ENTÃO** zika **E** chikungunya
```Prolog
?- doencaConjuntivite(X).
Sofre de conjuntivite?
|: s.
X = zika_e_chikungunya.
```
### REGRA 20
**SE** conjuntivite = não tenho **E** intensidade nas dores articulares = intensa **ENTÃO** chikungunya
```Prolog
?- doencaConjuntivite(X).
Sofre de conjuntivite?
|: n.
Sofre de dor intensa nas articulacoes?
|: s.
X = chikungunya.
```
### REGRA 21
**SE** conjuntivite = não tenho **E** intensidade nas dores articulares = leve **ENTÃO** dengue
```Prolog
?- doencaConjuntivite(X).
Sofre de conjuntivite?
|: n.
Sofre de dor intensa nas articulacoes?
|: n.
Sofre de dor leve nas articulacoes?
|: s.
X = dengue.
```
### REGRA 22
**SE** dor de cabeça = sem dor **ENTÃO** não tem doença
```Prolog
?- doencaDorDeCabeca(X).
Sofre de dor de cabeca?
|: n.
false.
```
### REGRA 23
**SE** dor de cabeça = com dor **E** intensidade = leve **ENTÃO** chikungunya **E** zika
```Prolog
?- doencaDorDeCabeca(X).
Sofre de dor de cabeca?
|: s.
Dor de cabeca leve?
|: s.
X = zika_e_chikungunya.
```
### REGRA 24
**SE** dor de cabeça = com dor **E** intensidade = moderada **E** intensidade nas dores articulares = intensa **ENTÃO** chikungunya
```Prolog
?- doencaDorDeCabeca(X).
Sofre de dor de cabeca?
|: s.
Dor de cabeca leve?
|: n.
Dor de cabeca moderada?
|: s.
Sofre de dor intensa nas articulacoes?
|: s.
X = chikungunya
```
### REGRA 25
**SE** dor de cabeça = com dor **E** intensidade = intensa **ENTÃO** dengue
```Prolog
?- doencaDorDeCabeca(X).
Sofre de dor de cabeca?
|: s.
Dor de cabeca leve?
|: n.
Dor de cabeca moderada?
|: n.
Dor de cabeca intensa?
|: s.
X = dengue.
```
### REGRA 26
**SE** dor de cabeça = com dor **E** intensidade = moderada **E** intensidade nas dores articulares = moderada **ENTÃO** zika
```Prolog
?- doencaDorDeCabeca(X).
Sofre de dor de cabeca?
|: s.
Dor de cabeca leve?
|: n.
Dor de cabeca moderada?
|: s.
Sofre de dor intensa nas articulacoes?
|: n.
Sofre de dor moderada nas articulacoes?
|: s.
X = zika.
```
### REGRA 27
**SE** coceira = não tenho **ENTÃO** não tem doença
```Prolog
?- doencaCoceira(X).
Sofre de Coceira?
|: n.
false.
```
### REGRA 28
**SE** coceira = tenho **E** intensidade coceira = leve **E** intensidade das dores musculares = intensa **ENTÃO** dengue
```Prolog
?- doencaCoceira(X).
Sofre de Coceira?
|: s.
Coceira de intensidade leve?
|: s.
Sofre de dor muscular intensa?
|: s.
X = dengue.
```
### REGRA 29
**SE** coceira = tenho **E** intensidade coceira = leve **E** intensidade das dores musculares = leve **ENTÃO** chikungunya
```Prolog
?- doencaCoceira(X).
Sofre de Coceira?
|: s.
Coceira de intensidade leve?
|: s.
Sofre de dor muscular intensa?
|: n.
Sofre de dor muscular leve?
|: s.
X = chikungunya
```
### REGRA 30
**SE** coceira = tenho **E** intensidade coceira = moderada **ENTÃO** zika
```Prolog
?- doencaCoceira(X).
Sofre de Coceira?
|: s.
Coceira de intensidade leve?
|: n.
Coceira de intensidade moderada?
|: s.
X = zika.
```
### REGRA 31
**SE** coceira = tenho **E** intensidade coceira = intensa **ENTÃO** zika
```Prolog
?- doencaCoceira(X).
Sofre de Coceira?
|: s.
Coceira de intensidade leve?
|: n.
Coceira de intensidade moderada?
|: n.
Coceira intensa?
|: s.
X = zika.
```
### REGRA 32
**SE** alterações no sistema nervoso = sim **ENTÃO** zika
```Prolog
?- doencaAlteracoesSistemaNervoso(X).
Sofreu alteracoes no sistema nervoso?
|: s.
X = zika.
```
### REGRA 33
**SE** alterações no sistema nervoso = não **E** intensidade nas dores articulares = leve **ENTÃO** dengue
```Prolog
?- doencaAlteracoesSistemaNervoso(X).
Sofreu alteracoes no sistema nervoso?
|: n.
Sofreu dor articular intensa?
|: n.
Sofreu dor articular leve?
|: s.
X = dengue.
```
### REGRA 34
**SE** alterações no sistema nervoso = não **E** intensidade nas dores articulares = intensa **ENTÃO** chikungunya
```Prolog
?- doencaAlteracoesSistemaNervoso(X).
Sofreu alteracoes no sistema nervoso?
|: n.
Sofreu dor articular intensa?
|: s.
X = chikungunya.
```
|
Java
|
UTF-8
| 2,067 | 3.515625 | 4 |
[] |
no_license
|
package itea.lsn3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DZ_Array4_math { //программа для подсчета значения математического выражения, введенного из консоли
public static void main(String[] args) throws IOException {
BufferedReader RL = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Введите строку: ");
String str = RL.readLine();
int i = 0, strLength = str.length();
String st1 = new String();
do {
st1 += str.charAt(i++);
} while (!checkMath(str.charAt(i)));
float rezlt = Integer.parseInt(st1);
st1 = "";
for (int j = i + 1; j < strLength; j++) {
if (!checkMath(str.charAt(j))) {
st1 += str.charAt(j);
}
if (j == strLength - 1 || checkMath(str.charAt(j))) {
float ft1 = Integer.parseInt(st1);
if (str.charAt(i) == '*') {
rezlt = rezlt * ft1;
} else if (str.charAt(i) == '/') {
rezlt = rezlt / ft1;
} else if (str.charAt(i) == '+') {
rezlt = rezlt + ft1;
} else rezlt = rezlt - ft1;
st1 = "";
i = j;
}
}
System.out.print("Решение математического выражения = " + rezlt);
}
static boolean checkMath(char s) {
boolean charMath = false;
switch (s) {
case '+':
charMath = true;
break;
case '-':
charMath = true;
break;
case '*':
charMath = true;
break;
case '/':
charMath = true;
break;
default:
charMath = false;
break;
}
return charMath;
}
}
|
Java
|
UTF-8
| 818 | 2 | 2 |
[] |
no_license
|
package com.nhb.nb.dataaccess.dao.rate;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.nhb.nb.dataaccess.entity.UnitRate;
@Repository
public interface UnitRateDao extends MongoRepository<UnitRate, String> {
List<UnitRate> findByAreaId(String areaId, Sort sort);
List<UnitRate> findByAreaIdAndStartDateAfterAndEndDateBefore(String areaId, String today, String today2, Sort sort);
List<UnitRate> findByAreaIdAndStartDateLessThanAndEndDateGreaterThan(String areaId, String today, String today2,
Sort sort);
List<UnitRate> findByAreaIdIn(List<String> areaIds);
List<UnitRate> findByStartDateLessThanEqualAndEndDateGreaterThan(String day, String day2);
}
|
Python
|
UTF-8
| 815 | 3.640625 | 4 |
[] |
no_license
|
'''
Created by Basanta Phuyal
'''
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = int(input("What is your encryption key? (1-9) ")) #key that aids with encryption
user_input= input("Message: ") #stores user's message
mail_input= input("Gmail: ") #stores user's gmail address
password_input= input("Password:") #stores user's gmail password
to_input= input("Email to send to: ")
message=''
user_message= user_input.lower()
'''for loop where the encryption takes place'''
for letter in user_message:
if letter in alphabet:
position= alphabet.find(letter)
new_position = (position+key) % 26
new_character = alphabet[new_position]
message += new_character
else:
message += letter
encrypted_message = message #final encrypted message
|
Java
|
UTF-8
| 3,778 | 2.1875 | 2 |
[] |
no_license
|
package com.example.yu.mhc.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.yu.mhc.R;
import com.example.yu.mhc.bean.WeekBean;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import java.util.List;
/**
* Created by YU on 2017/6/28.
*/
public class Weekadapter extends BaseAdapter{
private List<WeekBean.DataBean.ComicsBean> list;
private Context context;
private final ImageLoader imageloader;
private final DisplayImageOptions options;
public Weekadapter(List<WeekBean.DataBean.ComicsBean> list, Context context) {
this.list = list;
this.context = context;
//创建默认的ImageLoader配置参数
ImageLoaderConfiguration configuration = ImageLoaderConfiguration
.createDefault(context);
//将configuration配置到imageloader中
imageloader = ImageLoader.getInstance();
imageloader.init(configuration);
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.ARGB_8888)
.showImageOnLoading(R.mipmap.ic_launcher)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.showImageOnFail(R.mipmap.ic_launcher)
.imageScaleType(ImageScaleType.EXACTLY)
.build();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView==null){
holder=new ViewHolder();
convertView=View.inflate(context, R.layout.week_item,null);
holder.label_text=(TextView)convertView.findViewById(R.id.label_text);
holder.title=(TextView)convertView.findViewById(R.id.title);
holder.ztitle=(TextView)convertView.findViewById(R.id.ztitle);
holder.nickname=(TextView)convertView.findViewById(R.id.nickname);
holder.cover_image_url=(ImageView) convertView.findViewById(R.id.cover_image_url);
convertView.setTag(holder);
}else{
holder= (ViewHolder) convertView.getTag();
}
WeekBean.DataBean.ComicsBean bean=list.get(position);
holder.label_text.setText(bean.getLabel_text());
holder.ztitle.setText(bean.getTitle());
holder.title.setText(bean.getTopic().getTitle());
holder.nickname.setText("作者:"+bean.getTopic().getUser().getNickname());
imageloader.displayImage(bean.getCover_image_url(),holder.cover_image_url,options);
return convertView;
}
class ViewHolder{
TextView label_text,title,nickname,ztitle;
ImageView cover_image_url;
}
}
|
Java
|
UTF-8
| 2,531 | 2.78125 | 3 |
[] |
no_license
|
package restaurant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Restaurant {
@Autowired
private HotDrink hotDrink;
@Autowired
// @Qualifier("hotDrinkQualifier")
private HotDrink hotDrinkQuali;
public HotDrink getHotDrinkQuali() {
return hotDrinkQuali;
}
@Autowired
public void setHotDrinkQuali(@Qualifier("hotDrinkQualifierMethod") HotDrink hotDrinkQuali) {
this.hotDrinkQuali = hotDrinkQuali;
}
public Restaurant() {
}
@Autowired
public Restaurant( @Qualifier("hotDrinkQualifierConstructor") HotDrink hotDrink) {
this.hotDrink = hotDrink;
}
public HotDrink getHotDrink() {
return hotDrink;
}
//Uncomment line 29 for 8th answer
// @Required
public void setHotDrink(HotDrink hotDrink) {
this.hotDrink = hotDrink;
}
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
//getting hotDrink restaurnat
Restaurant tea = (Restaurant) ctx.getBean("teaRestaurant");
tea.hotDrink.prepareHotDrink();
//getting expressTeaRestaurant , inner bean
Restaurant expressTea = (Restaurant) ctx.getBean("expressTeaRestaurant");
expressTea.hotDrink.prepareHotDrink();
//ANSWER 6
//byName
Restaurant byNameTea = (Restaurant) ctx.getBean("restaurantName");
byNameTea.hotDrink.prepareHotDrink();
//byType
Restaurant byTypeTea = (Restaurant) ctx.getBean("restaurantType");
byNameTea.hotDrink.prepareHotDrink();
// byConstructor
Restaurant byConsTea = (Restaurant) ctx.getBean("teaConstructor");
byNameTea.hotDrink.prepareHotDrink();
// END---------END ANSWER 6
//After prototype
System.out.println("After Prototype");
Restaurant tea1 = (Restaurant) ctx.getBean("teaRestaurant");
System.out.println(tea);
System.out.println(tea1);
//Answer 9
//Using Qualifier
// Uncomment "@Qualifier" at different places to see different result
Restaurant byQuali = (Restaurant) ctx.getBean("resQualifier");
byNameTea.hotDrinkQuali.prepareHotDrink();
}
}
|
Java
|
UTF-8
| 2,907 | 2.59375 | 3 |
[] |
no_license
|
package ie.cex.handlers;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class UserHandler {
private static final String URL = "url";
private static final String NAME = "name";
private static final String BARCODE = "barcode";
private static final String TABLE_NAME = "user";
private static final String DATA_BASE_NAME = "myDB";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE = "create table user (url text not null," + "name text not null," + "barcode text not null);";
private DataBaseHelper dbhelper;
private SQLiteDatabase db;
public UserHandler(Context ctx)
{
dbhelper = new DataBaseHelper(ctx);
}
private static class DataBaseHelper extends SQLiteOpenHelper
{
DataBaseHelper(Context ctx)
{
super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
Log.e("Error", e.getMessage());
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXIST user");
onCreate(db);
}
}
public UserHandler open()
{
db = dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(String url, String name, String barcode)
{
ContentValues content = new ContentValues();
content.put(URL,url);
content.put(NAME, name);
content.put(BARCODE, barcode);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public int returnAmount()
{
return (int)DatabaseUtils.queryNumEntries(db, TABLE_NAME);
}
public Cursor returnData()
{
return db.query(TABLE_NAME, new String[]{URL, NAME, BARCODE}, null, null, null, null, null);
}
public boolean updateName(String oldName, String newName)
{
ContentValues content = new ContentValues();
content.put(NAME, newName);
db.update(TABLE_NAME, content, NAME + " = ?", new String[]{oldName});
return true;
}
public boolean updateBarcode(String oldBarcode,String newBarcode)
{
ContentValues content = new ContentValues();
content.put(BARCODE,newBarcode);
db.update(TABLE_NAME, content, BARCODE + " = ?", new String[]{oldBarcode});
return true;
}
}
|
Python
|
UTF-8
| 172 | 3.625 | 4 |
[] |
no_license
|
word = ["av","cs","ef", "gh"]
# word内の3つまでをプリントする
for i in range(3):
print word[i]
# word内の全てをプリントする
for w in word:
print w
|
Shell
|
UTF-8
| 194 | 2.859375 | 3 |
[] |
no_license
|
#!/bin/sh
# remove songs NOT matching PATTERN from playlist
pattern="$1"
mpc --format "%position% %artist% %album% %title%" playlist \
| ngrep $pattern \
| awk '{print $1}' \
| mpc del
|
Java
|
UTF-8
| 795 | 3.546875 | 4 |
[] |
no_license
|
package swing2019_11_16;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends JFrame {
public JFrameDemo(){
//设置窗口标题
setTitle("Java 第一个GUI程序");
//设置窗口显示尺寸
setSize(400,200);
//设置窗口是否可以关闭
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建一个标签
JLabel jLabel = new JLabel("这是一个JFrame类创建的窗口");
//获取当前窗口的内容窗格
Container contentPane = getContentPane();
//将标签组件添加到内容窗格上
contentPane.add(jLabel);
//设置窗口是否可见
setVisible(true);
}
public static void main(String[] args) {
new JFrameDemo();
}
}
|
Python
|
UTF-8
| 1,047 | 3.84375 | 4 |
[] |
no_license
|
def calc_power(x,y):
"""xのy乗を計算する"""
result = x **y
return result
print(calc_power(2,10))
def show_args(*args):
"""位置引数のタプル化の例"""
print("Positional args:",args)
return args
show_args("a","b","c","d","e","f")
def show_kwargs(**kwargs):
"""キーワード引数の辞書化の例"""
print("Keyword args:", kwargs)
return kwargs
show_kwargs(a="パスタ", b="赤ワイン", c="肉料理")
animal = "cat"
print("animal in global:",animal)
def my_func():
vegetable = "carot"
print("animal in my_func:",animal)
print("vegetable in my_func:",animal)
my_func()
#print("vegetable:", vegetable)
animal = "cat"
print("animal in global:", animal)
def my_func():
global animal
animal = "dog"
print("animal in my_fucn()", animal)
my_func()
print("animal global after my_func:", animal)
def print_upto(num):
"""与えられた数未満の数を表示"""
num_str=""
for i in range (num):
#
num_str = ""+ str(i)
print(num_str)
if __name__== "__main__":
print_upto(10)
|
Java
|
UTF-8
| 524 | 2.359375 | 2 |
[] |
no_license
|
package adrianromanski.restschool.model.event;
import adrianromanski.restschool.model.person.TeacherDTO;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDate;
@Getter
@Setter
@NoArgsConstructor
public class PaymentDTO extends EventDTO {
private Double amount;
private TeacherDTO teacherDTO;
@Builder
public PaymentDTO(String name, LocalDate date, Double amount) {
super(name, date);
this.amount = amount;
}
}
|
Go
|
UTF-8
| 2,036 | 2.640625 | 3 |
[] |
no_license
|
package search
import (
"testing"
"github.com/bx5a/minstrel-server/track"
)
func TestYoutubeEngine_Search(t *testing.T) {
searchEngine := MakeYoutubeEngine()
idList, err := searchEngine.Search("adele", "US", "")
if err != nil {
t.Fatal(err)
}
ids := idList.IDs
if len(ids) == 0 {
t.Errorf("Obtained ID array is empty")
}
if idList.NextPageToken == "" {
t.Errorf("Invalid next page token")
}
if testing.Short() {
t.Skip("Skipping search result test in shot mode.")
return
}
if ids[0].Source != youtubeEngineSourceName {
t.Errorf("ids[0].Source == %s, want %s", ids[0].Source, youtubeEngineSourceName)
}
expectedID := "nufFvjKPNI4"
if ids[0].ID != expectedID {
t.Errorf("ids[0].ID == %s, want %s", ids[0].ID, expectedID)
}
}
func TestYoutubeEngine_Detail(t *testing.T) {
searchEngine := MakeYoutubeEngine()
adeleFirstTrack := track.ID{ID: "fk4BbF7B29w", Source: youtubeEngineSourceName}
adeleSecondTrack := track.ID{ID: "YQHsXMglC9A", Source: youtubeEngineSourceName}
ids := []track.ID{adeleFirstTrack, adeleSecondTrack}
tracks, err := searchEngine.Detail(ids)
if err != nil {
t.Fatal(err)
}
if testing.Short() {
t.Skip("Skipping detail result test in shot mode.")
return
}
if len(tracks) != len(ids) {
t.Errorf("len(tracks) != len(ids)")
}
if tracks[0].ID.ID != ids[0].ID {
t.Errorf("tracks[0].ID.ID != ids[0].ID")
}
expectedTitle := "Adele - Send My Love (To Your New Lover)"
if tracks[0].Title != expectedTitle {
t.Errorf("tracks[0].Title == %s, want %s", tracks[0].Title, expectedTitle)
}
if tracks[0].Thumbnail.Default == "" {
t.Errorf("Thumnail default url empty")
}
expectedDuration := "226000"
if tracks[0].Duration != expectedDuration {
t.Errorf("Unexpected duration: %s, want %s", tracks[0].Duration, expectedDuration)
}
}
func TestYoutubeEngine_Category(t *testing.T) {
searchEngine := MakeYoutubeEngine()
ID, err := searchEngine.queryMusicCategoryID()
if err != nil {
t.Fatal(err)
}
if ID == "" {
t.Errorf("Obtained ID is empty")
}
}
|
TypeScript
|
UTF-8
| 1,337 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2020 Angus.Fenying <fenying@litert.org>
*
* 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
*
* https://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.
*/
import { Events } from '../../lib';
interface IEventDefinitions extends Events.ICallbackDefinitions {
timer(t: number): void;
walk(a: string, g: number): void;
}
const eh: Events.IEmitter<IEventDefinitions> = new Events.EventEmitter<IEventDefinitions>();
eh
.on('timer', function(t): void {
console.log(new Date(t));
})
.on('walk', function(t, g): void {
console.log(new Date(t), g);
})
.on('gg', function(): false {
return false;
})
.once('timer', function(): void {
console.log('This should be called once only.');
});
setInterval(() => eh.emit('timer', Date.now()), 1000);
eh.emit('walk', '2019-11-11', 123);
eh.emit('gg', '2019-11-11', 123);
|
Python
|
UTF-8
| 1,988 | 2.8125 | 3 |
[] |
no_license
|
#!/usr/bin/python
import sys
from itertools import islice
file1 = sys.argv[1]
mydir = sys.argv[2]
njobs = sys.argv[3]
set_1 = set(line.strip() for line in open (file1, 'r'))
#create BC barcode files
output1a = open(mydir+"bar4.txt", "w")
output1b = open(mydir+"bar5.txt", "w")
output1c = open(mydir+"bar6.txt", "w")
output1d = open(mydir+"bar7.txt", "w")
output1e = open(mydir+"bar8.txt", "w")
output1f = open(mydir+"bar9.txt", "w")
seqs = {}
for line in set_1:
line = line.split("\t")
a = line[0]
b = line[1]
seqs[a] = b
for line1 in seqs.items():
barid = line1[0]
barsq = line1[1]
barsqsize = len(barsq)
if barsqsize == 4:
output1a.write(barid+"\t"+barsq+"\n"); #write in output1a
if barsqsize == 5:
output1b.write(barid+"\t"+barsq+"\n"); #write in output1b
if barsqsize == 6:
output1c.write(barid+"\t"+barsq+"\n"); #write in output1c
if barsqsize == 7:
output1d.write(barid+"\t"+barsq+"\n"); #write in output1d
if barsqsize == 8:
output1e.write(barid+"\t"+barsq+"\n"); #write in output1e
if barsqsize == 9:
output1f.write(barid+"\t"+barsq+"\n"); #write in output1f
output1a.close()
output1b.close()
output1c.close()
output1d.close()
output1e.close()
output1f.close()
#create list of individuals based on barcode file
individuals = set(seqs.keys())
outputind = open(mydir+"list_individuals.txt", "w")
for i in individuals:
outputind.write(i+"\n");
outputind.close()
#creating files for parallel processing in 10 processors
def chunk(it, size):
it = iter(it)
return iter(lambda: tuple(islice(it, size)), ())
indprocess = int(len(individuals) / int(njobs)) + 1 #calc the amount of individuals each of sublist should have for 10 processors
myplist = list(chunk(individuals, indprocess)) #use chunk function to split individuals list based on indprocess
nprocess = 0
for i in myplist:
nprocess += 1
output1z = open(mydir+"process"+str(nprocess)+".tmpp", "w")
for j in i:
output1z.write(j+"\n");
output1z.close()
|
Python
|
UTF-8
| 5,108 | 2.828125 | 3 |
[] |
no_license
|
import csv
""" Модуль для работы с csv-файлами"""
from itertools import cycle
"""Создать бесконечный итератор"""
with open('script-for-alice.csv', 'r', encoding='utf8') as csvfile:
""" Читать сценарий, записанный в csv-файле"""
data = csv.DictReader(csvfile, delimiter=';', quotechar=' ')
events = {x['event']: [x['action'], x['branch'], x['image']] for x in data}
def handle_dialog(request, response, user_storage):
""" Работать с диалогом
Обрабатывает диалог
Выводит сообщение Алисы, картинку и текст кнопок для продолжения игры
В случае выбора кнопки 'конец игры' завершает сессию
В случае выбора кнопки 'подождать еще день' вызывает первую ветку истории
В случае выбора кнопки 'выбираться самой' вызывает вторую ветку истории
Настраивает очередь сообщений из csv-файла и очередь картинок
Возвращает ответ для пользователя"""
if request.is_new_session:
user_storage = {}
response.set_text('Для завершения игры скажите "конец игры".\n')
response.set_buttons([{'title': 'подождать еще день', 'hide': True},
{'title': 'выбираться самой', 'hide': True}])
response.set_image('1030494/2e21639ad34cd97d8c9c', 'Милой Элитии исполнилось уже 20 лет, она стояла '
'у окна и рассматривала плывущие по небу облака.'
'Красавица думала про себя: '
'“Подождать мне еще один день или стоит уже '
'выбираться самой?'
'Для завершения игры скажите "конец игры".\n')
return response, user_storage
else:
if request.command.lower() == 'конец игры':
response.set_text('Спасибо за игру!\n' + 'До встречи!')
response.set_end_session(True)
user_storage = {}
return response, user_storage
elif request.command in ['подождать еще день']:
user_storage = choose_branch('подождать еще день')
user_storage, image, event = response_to_user()
response.set_text(user_storage['event'])
response.set_buttons(user_storage['buttons'])
response.set_image(image, event)
return response, user_storage
elif request.command in ['выбираться самой']:
user_storage = choose_branch('выбираться самой')
user_storage, image, event = response_to_user()
response.set_text(user_storage['event'])
response.set_buttons(user_storage['buttons'])
response.set_image(image, event)
return response, user_storage
elif request.command == user_storage['action']:
user_storage, image, event = response_to_user()
response.set_text(user_storage['event'])
response.set_buttons(user_storage['buttons'])
response.set_image(image, event)
return response, user_storage
response.set_text(user_storage['event'])
return response, user_storage
def get_buttons(action):
""" Функция для создания кнопок """
actions = list(action)
actions = ''.join(actions)
buttons = [{'title': actions, 'hide': True}]
return buttons
def choose_branch(branch):
""" Функция выбора сюжета для ветки """
a = []
b = []
for x in events.keys():
if events[x][1] == branch:
a.append(x)
b.append(events[x][2])
inf_list = cycle(a)
image_list = cycle(b)
user_storage = globals()
user_storage['episodes'], user_storage['pictures'] = inf_list, image_list
return user_storage
def response_to_user():
""" Функция ответа пользователя"""
user_storage = globals()
event = next(user_storage['episodes'])
action = events[event][0]
image = events[event][2]
buttons = get_buttons(action)
user_storage['event'] = event
user_storage['action'] = action
user_storage['buttons'] = buttons
return user_storage, image, event
|
Java
|
UTF-8
| 254 | 2.6875 | 3 |
[] |
no_license
|
class largest
{
public static void main(String... a)
{
int d,b,c;
d=10;b=30;c=27;
if(d>b && d>c)
System.out.println("a is largest");
else if(b>d && b>c)
System.out.println("b is largest");
else
System.out.println("c is largest");
}
}
|
Java
|
UTF-8
| 788 | 3.140625 | 3 |
[] |
no_license
|
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
static void staircase(int n) {
int k = 0;
while (k < n) {
if (n - k - 1 > 0)
System.out.printf("%" + (n - k - 1) + "s", "");
for (int i = 0; i <= k; i++) {
System.out.print("#");
}
System.out.println();
k++;
}
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
staircase(n);
scanner.close();
}
}
|
Python
|
UTF-8
| 2,767 | 2.828125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/4/6 23:53'
"""
Python网络爬虫--从入门到实践 P42-44
解析真实地址抓取
http://www.santostang.com/2017/03/02/hello-world/
抓取来必力评论:
"https://api-zero.livere.com/v1/comments/list?callback=jQuery1124025451041961429377_1523032354340&limit=10&repSeq=3871836&requestPath=%2Fv1%2Fcomments%2Flist&consumerSeq=1020&livereSeq=28583&smartloginSeq=5154&_=1523032354342"
"https://api-zero.livere.com/v1/comments/list?callback=jQuery1124025451041961429377_1523032354340&limit=10&offset=2&repSeq=3871836&requestPath=%2Fv1%2Fcomments%2Flist&consumerSeq=1020&livereSeq=28583&smartloginSeq=5154&_=1523032354345"
"https://api-zero.livere.com/v1/comments/list?callback=jQuery1124025451041961429377_1523032354340&limit=10&offset=3&repSeq=3871836&requestPath=%2Fv1%2Fcomments%2Flist&consumerSeq=1020&livereSeq=28583&smartloginSeq=5154&_=1523032354346"
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
关于find link:
应该点JS,然后看里面的Preview或者Response,里面响应的是Ajax的内容,然后如果去爬网站的评论的话,点开js那个请求后点Headers -->在General里面拷贝 RequestURL
"""
import json
import requests
from bs4 import BeautifulSoup
# TARGET_URL = "https://api-zero.livere.com/v1/comments/list?callback=jQuery1124025451041961429377_1523032354340&limit=10&offset=2&repSeq=3871836&requestPath=%2Fv1%2Fcomments%2Flist&consumerSeq=1020&livereSeq=28583&smartloginSeq=5154&_=1523032354345"
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
# print(r.text)
# print(type(r.text)) 'str'
def single_page_comment(link):
r = requests.get(link, headers=headers)
# 从 json数据中提取评论。上述的结果比较杂乱,但是它其实是 json 数据,可以使用 json 库解析数据,从中提取想要的数据。
# get json string
json_string = r.text
# 提取字符串中符合json格式的部分
json_string = json_string[json_string.find('{'):-2] # 提取数据,因为返回的数据不是直接的标准json格式
json_data = json.loads(json_string) # Deserialize a json str -> Python Object
comment_list = json_data['results']['parents']
for each in comment_list:
comment = each['content']
print(comment)
def bs4_get(link):
r = requests.get(link, headers=headers)
json_string = r.text
soup = BeautifulSoup(json_string, 'lxml')
# print(soup)
if __name__ == '__main__':
bs4_get("http://www.santostang.com/2017/03/02/hello-world/")
|
Java
|
UTF-8
| 1,411 | 2.84375 | 3 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.test.gof.design.patterns.creational;
import com.gof.design.patterns.creational.singleton.Singleton;
import java.util.Date;
import static org.testng.Assert.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
*
* @author Azariahs
*/
public class SingletonTest {
public SingletonTest() {
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
// @Test
// public void hello() {}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod
public void setUpMethod() throws Exception {
}
@AfterMethod
public void tearDownMethod() throws Exception {
}
@Test
public void testForSingleton() {
Singleton a = Singleton.instance();
Singleton b = Singleton.instance();
assertEquals(a, b);
Date date1 = a.getDate();
Date date2 = b.getDate();
assertEquals(date1, date2);
}
}
|
Shell
|
UTF-8
| 4,206 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
#set -x
### BEGIN INIT INFO
# Provides: ComprehensiveIT
# Required-Start: $syslog
# Required-Stop: $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Interactive: true
# Short-Description: Jenkins server
# Description: Start the Jenkins server
# This script will start Jenkins
### END INIT INF
ENV="env -i LANG=C PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
DESC="Jenkins server"
NAME=jenkins
EXTPKG=war
DAEMON="/usr/bin/java"
WAR=${NAME}.${EXTPKG}
XMIN="256m"
XMAX="512m"
PID=/var/run/jenkins.pid
SCRIPTNAME="${0##*/}"
SCRIPTNAME="${SCRIPTNAME##[KS][0-9][0-9]}"
if [ -z "$JENKINS_CONFDIR" ] ; then
JENKINS_CONFDIR=/opt/jenkins
fi
if grep -q "^logfile=" $JENKINS_CONFDIR/envvars
then
LOGFILE=$(grep "^logfile=" $JENKINS_CONFDIR/envvars|awk -F'=' '{print $2}')
else
LOGFILE=/var/log/jenkins.log
fi
DAEMON_OPTS="-Xms${XMIN} -Xmx${XMAX} -jar ${JENKINS_CONFDIR}/${WAR} --daemon"
USAGE="$SCRIPTNAME {start|stop|restart|status}"
VERBOSE=no
. /lib/lsb/init-functions
#
# Function that starts the daemon/service
#
print_error_msg() {
log_failure_msg "$1"
echo "$1" >> $LOGFILE
exit 1
}
get_args(){
#Set the jenkins as daemon by default
if [ -r ${JENKINS_CONFDIR}/envvars ]
then
for i in $(grep -v "^#" ${JENKINS_CONFDIR}/envvars)
do
DAEMON_OPTS="${DAEMON_OPTS} --${i}"
done
return 0
else
print_error_msg "${JENKINS_CONFDIR}/envvars not found or not readable"
return 1
fi
}
do_start()
{
#Backup the daemon file if it exists
[ -f $PID ] && print_error_msg "$DESC is already running"
if [ -f /var/run/daemon.pid ]; then
[ -w /var/run/daemon.pid ] || print_error_msg "The file /var/run/daemon.pid cannot be written. Please ensure another deamon is not locking it"
TOKEN=$(date +%Y%m%d-%H%M%s)
mv /var/run/daemon.pid /var/run/daemon.pid.$TOKEN
fi
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
#start-stop-daemon --start --quiet --pidfile $PID --exec $DAEMON -S -- "$DAEMON_OPTS" --test > /dev/null \
# || return 1
start-stop-daemon --start --quiet --pidfile $PID --exec $DAEMON -S -- $DAEMON_OPTS >> $LOGFILE 2>&1 \
|| return 1
sleep 10
mv /var/run/daemon.pid $PID
[ -f /var/run/daemon.pid.$TOKEN ] && mv /var/run/daemon.pid.$TOKEN /var/run/daemon.pid
return 0
}
do_stop()
{
if [ ! -f $PID ]; then
PROC_ID=$(jcmd -l|grep $NAME|awk -F' ' '{print $1}')
[ -z $PROC_ID ] && print_error_msg "$DESC is not running"
#if $(grep -q $NAME <<< $(ps -e -o cmd))
#then
# PROC_ID=$(ps -e -o pid,cmd|grep $NAME|awk -F' ' '{print $1}')
#else
# print_error_msg "$DESC has been stopped unexpectedly. Please remove $PID"
#fi
kill $PROC_ID || print_error_msg "$DESC cannot be stopped"
else
PROC_ID=$(cat $PID)
kill $PROC_ID || print_error_msg "$DESC cannot be stopped"
rm $PID
fi
return 0
}
do_status()
{
if [ -f $PID ]; then
if $(grep -q $NAME <<< $(ps -fp $(cat $PID) -o cmd))
then
PROC_ID=$(cat $PID)
else
print_error_msg "$DESC has been stopped unexpectedly. Please remove $PID"
fi
log_success_msg "$DESC is running on PID $PROC_ID"
else
PROC_ID=$(jcmd -l|grep $NAME|awk -F' ' '{print $1}')
[ -z $PROC_ID ] && log_success_msg "$DESC is stopped"
print_error_msg "$DESC is running but no $PID has been created"
fi
return 0
}
case "$1" in
start)
log_daemon_msg "Starting $DESC"
get_args || print_error_msg "Error while reading the configuration file"
do_start || print_error_msg "Failed to start"
log_success_msg "$DESC started"
;;
stop)
log_daemon_msg "Stoping $DESC"
do_stop || print_error_msg "Failed to stop"
log_success_msg "$DESC stopped"
;;
restart)
log_daemon_msg "Stoping $DESC"
do_stop || print_error_msg "Failed to stop"
log_success_msg "$DESC stopped"
log_daemon_msg "Starting $DESC"
get_args || print_error_msg "Error while reading the configuration file"
do_start || print_error_msg "Failed to start"
log_success_msg "$DESC started"
;;
status)
do_status || print_error_msg "Failed to get the status"
;;
*)
echo -e "$USAGE"
exit 1
;;
esac
exit 0
|
Java
|
UTF-8
| 2,925 | 3.609375 | 4 |
[] |
no_license
|
package fr.umlv.labfour;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Random;
public class Example1 {
/*
*
*
* 1 - 4) Si l'on ajoute pas un second run, le fait de placer un yield bloquera l'exécution du code
*
* 1 - 5) yield enregistre sur la pile le pointeur de l'opération à traiter en cours et run relance l'exécution à partir de ce pointeur
*
* 1 - 8) Thread.currentThread() retournera le thread courant. Meme dans le main celui ci sera dans un thread. Alors que pour le continuous,
* le main n'est présent dans aucun continuous donc celui ci retourne null (celui ci n'est pas une continuation).
*
* 1 - 9) Il y a un état étrange car le synchronised vérouille une fonction sauf que yield sort de cet état de vérou
* pour éxécuter une autre portion de code, il y a alors une "java.lang.IllegalStateException" qui est jetée.
*
* 1 - 11) Continuation => Permet d'exécuter du code et de pouvoir le pause pour reprendre plus tard. Tout cela en mono thread et en
* pouvant exécuter plusieurs code les uns après les autres.
* Les threads eux, s'exécutent sur du multi core.
*
*
* */
static enum SchedulerMode{
STACK{
public void getData() {
}
},
FIFO{
public void getData() {
}
},
RANDOM{
public void getData() {
}
};
}
static class Scheduler {
private final ArrayList<Continuation> continuations = new ArrayList<>();
private final SchedulerMode sm ;
public Scheduler(SchedulerMode sm){
this.sm = sm ;
}
void enqueue(ContinuationScope cs){
/*get continuation*/
if(c == null)
throw new IllegalStateException("######## Pas de continuation courante ########") ;
continuations.add(c) ;
Continuation.yield(cs) ;
}
void runLoop() {
while(!continuations.isEmpty()) {
Continuation continuation;
switch (this.sm) {
case STACK : continuation = continuations.remove(continuations.size() - 1) ; break ;
case FIFO : continuation = continuations.remove(0) ; break ;
case RANDOM : continuation = continuations.remove((int) (Math.random() * continuations.size()) ) ; break;
default: throw new IllegalArgumentException("######## Pas de SchedulerMode renseigné ########") ;
}
continuation.run() ;
}
}
}
public static void main() {
var scheduler = new Scheduler(SchedulerMode.STACK) ;
var scope = new ContinuationScope("scope") ;
Runnable runnable = () -> {
/*if(Continuation.getCurrentContinuation(scope1).isDone())*/
System.out.println(Continuation.getCurrentContinuation(scope)) ;
System.out.println("hello continuation") ;
} ;
for(int i = 0 ; i < 10 ; i++) {
var continuation = new Continuation(scope, runnable) ;
continuation.run();
scheduler.enqueue(continuation, scope);
}
scheduler.runLoop();
}
}
|
C#
|
UTF-8
| 2,420 | 2.90625 | 3 |
[] |
no_license
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace Exercises.Tests
{
[TestClass]
public class NonStartTest
{
[TestMethod]
public void NonStartHelloThereTest()
{
NonStart stringpart = new NonStart();
NonStart stringpart2 = new NonStart();
NonStart stringpart3 = new NonStart();
string partialstring = stringpart.GetPartialString("Hello", "There");
string partialstring2 = stringpart2.GetPartialString("", "There");
string partialstring3 = stringpart3.GetPartialString("Hello", "");
Assert.AreEqual("ellohere", partialstring);
Assert.AreEqual("here", partialstring2);
Assert.AreEqual("ello", partialstring3);
}
[TestMethod]
public void NonStartJavaCodeTest()
{
NonStart stringpart = new NonStart();
NonStart stringpart2 = new NonStart();
NonStart stringpart3 = new NonStart();
string partialstring = stringpart.GetPartialString("java", "code");
string partialstring2 = stringpart2.GetPartialString("", "code");
string partialstring3 = stringpart3.GetPartialString("java", "");
Assert.AreEqual("avaode", partialstring);
Assert.AreEqual("ode", partialstring2);
Assert.AreEqual("ava", partialstring3);
}
[TestMethod]
public void NonStartShotlJavaTest()
{
NonStart stringpart = new NonStart();
NonStart stringpart2 = new NonStart();
NonStart stringpart3 = new NonStart();
string partialstring = stringpart.GetPartialString("shotl", "java");
string partialstring2 = stringpart2.GetPartialString("", "java");
string partialstring3 = stringpart3.GetPartialString("shotl", "");
Assert.AreEqual("hotlava", partialstring);
Assert.AreEqual("ava", partialstring2);
Assert.AreEqual("hotl", partialstring3);
}
}
}
/*
Given 2 strings, return their concatenation, except omit the first char of each. The strings will
be at least length 1.
GetPartialString("Hello", "There") → "ellohere"
GetPartialString("java", "code") → "avaode"
GetPartialString("shotl", "java") → "hotlava"
*/
|
JavaScript
|
UTF-8
| 782 | 3.359375 | 3 |
[] |
no_license
|
var Stack = (function(){
function _Stack(){
this._init.apply(this, arguments);
}
_Stack.prototype = {
_init : function(){
this.stack = [];
this.size = 0;
},
push : function(data){
this.stack[this.size++] = data;
},
pop : function(){
if(this.isEmpty()) return -1;
return this.stack[this.size--];
},
isEmpty : function(){
if(this.size === 0) return true;
return false;
},
top : function(){
if(this.isEmpty()) return -1;
return this.stack[this.size-1];
},
println : function(){
console.log(this.stack.join(''));
}
}
return _Stack;
})();
var stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(1);
stack.pop();
stack.println();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.