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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 1,316 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
# element 阅读知识点储备
## node 知识
### fs.resolve()
### fs.readFileSync()
### fs.writeFile()
### os.EOL
表示当前操作系统的行末标志。 `window` 系统为 `\r\n`; `linux` 系统上为 `\n`
## npm 包
### postcss.parse 一个 css 语法解析器
### json-templater/string 字符串替换
`json-templater/string` 是一个字符串替换的方法, 他接受2个参数,分别为为字符串模板、模板中需要替换的变量 `key` 组成的对象, 使用方法为
```js
const render = require('json-template/string')
const string = render(`first name:{{firstname}}, last name: {{lastname}}`, {firstname: 'Tom', lastname: 'Hellen'})
// string = "first name: Tom, last name: Hellen"
```
> `json-templater` 还包含 `json-templater/object` 方法, 它接受两个对象作为参数, 可以用第二个对象中的值替换到第一个参数中。
```js
const render = require('json-template/object')
const template ={
"magic_key_{{magic}}": {
"key": "interpolation is nice {{value}}"
}
}
const obj = render(template, {magic: 'key', value: 'value'})
/** result
obj = {
magic_key_key: {
key: 'interpolation is nice value'
}
} */
```
### uppercamelcase
将破折号、点、下划线、空格分割的字符串转换成 `驼峰写法`
|
Java
|
UTF-8
| 13,547 | 2.5 | 2 |
[] |
no_license
|
package view;
import controller.DbUtils;
import java.util.ArrayList;
import model.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
/*
* 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.
*/
/**
*
* @author Monkey.TNT
*/
public class InsetUpdateDelete extends javax.swing.JFrame {
/**
* Creates new form Demo
*/
private PreparedStatement stmt;
private ResultSet rs;
private Connection conn;
public InsetUpdateDelete(){
initComponents();
try{
conn=DbUtils.getConnection();
}catch(Exception e){
e.printStackTrace();
}
showTable();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtfID = new javax.swing.JTextField();
txtfFirstname = new javax.swing.JTextField();
txtflastName = new javax.swing.JTextField();
txtfAge = new javax.swing.JTextField();
btninsert = new javax.swing.JButton();
btnupdate = new javax.swing.JButton();
btndelete = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("ID");
jLabel2.setText("FirstName");
jLabel3.setText("LastName");
jLabel4.setText("Age");
btninsert.setText("Insert");
btninsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btninsertActionPerformed(evt);
}
});
btnupdate.setText("Update");
btnupdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnupdateActionPerformed(evt);
}
});
btndelete.setText("Delete");
btndelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btndeleteActionPerformed(evt);
}
});
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "firstname", "lastname", "age"
}
));
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(table);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtfID, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE)
.addComponent(txtfFirstname)
.addComponent(txtfAge)
.addComponent(txtflastName))
.addGap(58, 58, 58)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnupdate, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
.addComponent(btninsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btndelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtfID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btninsert))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtfFirstname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnupdate)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(txtflastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel4))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(txtfAge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(btndelete))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
int row = table.getSelectedRow();
TableModel model = (TableModel) table.getModel();
txtfID.setText(model.getValueAt(row, 0).toString());
txtfFirstname.setText(model.getValueAt(row, 1).toString());
txtflastName.setText(model.getValueAt(row, 2).toString());
txtfAge.setText(model.getValueAt(row, 3).toString());
}//GEN-LAST:event_tableMouseClicked
private void btninsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btninsertActionPerformed
String sql = "INSERT INTO userr (ID, firstname, lastname, age) "
+ "VALUES ('"+txtfID.getText()+"','" + txtfFirstname.getText() + "', '" + txtflastName.getText() + "', '" + txtfAge.getText() + "')";
queryUpdate(sql, "Insert");
}//GEN-LAST:event_btninsertActionPerformed
private void btnupdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnupdateActionPerformed
String sql = "UPDATE userr SET firstname='" + txtfFirstname.getText() + "', lastname='" + txtflastName.getText() + "', age='" + txtfAge.getText() + "' WHERE ID='" + txtfID.getText() + "'";
queryUpdate(sql, "Update");
}//GEN-LAST:event_btnupdateActionPerformed
private void btndeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btndeleteActionPerformed
String sql = "DELETE FROM userr WHERE ID='" + txtfID.getText() + "'";
queryUpdate(sql, "Delete");
}//GEN-LAST:event_btndeleteActionPerformed
public ArrayList<User> getArrayList() {
ArrayList<User> list = new ArrayList<>();
try {
String sql = "select * from userr";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
User user = new User(rs.getInt("ID"), rs.getString("firstname"), rs.getString("lastname"), rs.getInt("age"));
list.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public void showTable() {
ArrayList<User> list = getArrayList();
DefaultTableModel model = (DefaultTableModel) table.getModel();
Object[] cols = new Object[4];
for (int i = 0; i < list.size(); i++) {
cols[0] = list.get(i).getId();
cols[1] = list.get(i).getFirstname();
cols[2] = list.get(i).getLastnaem();
cols[3] = list.get(i).getAge();
model.addRow(cols);
}
}
public void queryUpdate(String sql, String message) {
try {
stmt = conn.prepareStatement(sql);
if (stmt.executeUpdate() == 1) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
showTable();
JOptionPane.showMessageDialog(null, message + " Successfully!");
}
conn.close();
stmt.close();
rs.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(InsetUpdateDelete.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InsetUpdateDelete.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InsetUpdateDelete.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InsetUpdateDelete.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InsetUpdateDelete().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btndelete;
private javax.swing.JButton btninsert;
private javax.swing.JButton btnupdate;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
private javax.swing.JTextField txtfAge;
private javax.swing.JTextField txtfFirstname;
private javax.swing.JTextField txtfID;
private javax.swing.JTextField txtflastName;
// End of variables declaration//GEN-END:variables
}
|
JavaScript
|
UTF-8
| 5,290 | 2.75 | 3 |
[] |
no_license
|
var Objet = function () {
this.room;
this.x = 0;
this.y = 0;
this.cx = 0;
this.cy = 0;
this.rx = 0;
this.ry = 0;
this.dx = 0;
this.dy = 0;
this.radius = 1;
this.rapport = 1;
this.acceleration = 1;
this.positions = []; //{timestamp, x, y}
}
Objet.prototype.setCoordinate = function (x, y) {
var tilesize = this.room.map.tilesize;
this.x = x;
this.y = y;
this.cx = Math.floor(x / tilesize);
this.cy = Math.floor(y / tilesize);
this.rx = (x - this.cx * tilesize) / tilesize;
this.ry = (y - this.cy * tilesize) / tilesize;
}
Objet.prototype.physic = function () {
var delta = 0.016;
var tilesize = this.room.map.tilesize;
var tiles = this.room.map.tiles;
this.rx += this.dx;
this.onGround = false;
var walling = this.hisWalling ;
this.hisWalling = 0;
this.dy += this.gravity / tilesize * delta;
if (this.dy > this.maxgravity / tilesize * delta) {
this.dy = this.maxgravity / tilesize * delta;
}
this.ry += this.dy;
this.dy = parseFloat(this.dy.toFixed(4));
this.newWallContact = false;
if (!(this.hasWallCollision(this.cx, this.cy) && this.cx > 0 && this.cx < tiles.length - 1)) {
if (this.hasWallCollision(this.cx - 1, this.cy) && this.rx <= this.rapport) {
if (walling != -1) {
this.newWallContact = true;
}
if (this.dx < 0) {
this.rx = this.rapport;
}
if(!this.onGround){
this.hisWalling = -1;
}
}
if (this.hasWallCollision(this.cx + 1, this.cy) && this.rx >= 1 - this.rapport) {
if (walling != 1) {
this.newWallContact = true;
}
if (this.dx > 0) {
this.rx = 1 - this.rapport;
}
if(!this.onGround){
this.hisWalling = 1;
}
}
}
while (this.rx < 0) { this.rx++; this.cx--; }
while (this.rx > 1) { this.rx--; this.cx++; }
var gap = 1;
if (this.ry < this.rapport && this.dy < 0 &&
(this.hasWallCollision(this.cx, this.cy - 1)
|| (this.hasWallCollision(this.cx + 1, this.cy - 1) && this.rx > 1 - this.rapport * gap)
|| (this.hasWallCollision(this.cx - 1, this.cy - 1) && this.rx < this.rapport * gap))
) {
this.dy = 0;
this.ry = this.rapport;
}
if (this.dy > 0 && this.ry > 1 - this.rapport &&
((this.hasWallCollision(this.cx, this.cy + 1))
|| (this.hasWallCollision(this.cx + 1, this.cy + 1) && this.rx > 1 - this.rapport * gap)
|| (this.hasWallCollision(this.cx - 1, this.cy + 1) && this.rx < this.rapport * gap)
)) {
this.onGround = true;
this.dy = 0;
this.ry = 1 - this.rapport;
}
if (this.hasFinishCollision(this.cx, this.cy)) {
this.finished();
}
//On met les bonnes valeurs pour ry/cy
while (this.ry < 0) { this.ry++; this.cy--; }
while (this.ry > 1) { this.ry--; this.cy++; }
//On arrondi
this.rx = parseFloat(this.rx.toFixed(3));
this.ry = parseFloat(this.ry.toFixed(3));
this.x = Math.floor((this.cx + this.rx) * tilesize);
this.y = Math.floor((this.cy + this.ry) * tilesize);
}
Objet.prototype.hasWallCollision = function (cx, cy) {
var tiles = this.room.map.tiles;
if (cx < 0 || cx >= tiles.length || cy < 0 || cy >= tiles[cx].length) {
return false;
}
return (tiles[cx][cy] === 1);
}
Objet.prototype.hasFinishCollision = function (cx, cy) {
var tiles = this.room.map.tiles;
if (cx < 0 || cx >= tiles.length || cy < 0 || cy >= tiles[cx].length) {
return false;
}
return (tiles[cx][cy] === 2);
}
Objet.prototype.hasObjectCollision = function (obj) {
var distance = Math.sqrt(Math.pow(obj.x - this.x, 2) + Math.pow(obj.y - this.y, 2));
if (distance <= this.radius + obj.radius) {
var d = parseFloat(this.d.toFixed(2));
return d > 0 ? d : 1
}
return false;
}
Objet.prototype.isOutsideMap = function () {
var tilesize = this.room.map.tilesize;
var tiles = this.room.map.tiles;
if (this.x < 0 || this.x > tiles.length * tilesize || this.y > tiles[0].length * tilesize) {
return true;
}
return false;
}
Objet.prototype.interpolate = function (tps, delta) {
var value = ["x", "y"];
var pos = {};
if (this.positions.length == 0) {
return false;
}
if (this.positions.length == 1) {
for (var k in value) {
pos[value[k]] = this.positions[0][value[k]];
}
return pos;
}
var time = tps - delta;
for (var i = 0; i < this.positions.length - 1; i++) {
if (this.positions[i].t < time && time <= this.positions[i + 1].t) {
var ratio = (time - this.positions[i].t) / (this.positions[i + 1].t - this.positions[i].t);
for (var k in value) {
pos[value[k]] = this.positions[i][value[k]] + ratio * (this.positions[i + 1][value[k]] - this.positions[i][value[k]]);
}
if (i > 0) {
this.positions.splice(0, i);
}
return pos;
}
}
return false;
}
|
Markdown
|
UTF-8
| 860 | 3.015625 | 3 |
[] |
no_license
|
# Getting-and-cleaning-Data-
The course proyect include a script called run_analysis.R, and after loading the data set "UCI HAR Dataset" the following steps were performed:
1. Merges the training and the test sets to create one data set.
2. Extracts only the measurements on the mean and standard deviation for each measurement.
3. Uses descriptive activity names to name the activities in the data set
4. Appropriately labels the data set with descriptive variable names.
5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
Finally, two data were obtained, the first "tidydata" that considers the instructions contained in the first four steps, "datafinal" that is a independent tidy data set with the average of each variable for each activity and each subject.
|
Python
|
UTF-8
| 2,126 | 3.265625 | 3 |
[] |
no_license
|
#import RPi.GPIO as GPIO #Importamos la libreria RPi.GPIO
import time #Importamos time para poder usar time.sleep #Importamos time para poder usar time.sleep
import random
class Comunicador(object):
def __init__(self, pinBase, pinLateral):
self.servoBase = pinBase
self.servoLateral = pinLateral
GPIO.setmode(GPIO.BOARD) # Ponemos la Raspberry en modo BOARD
GPIO.setup(self.servoBase, GPIO.OUT) # Ponemos el pin 21 como salida
GPIO.setup(self.servoLateral, GPIO.OUT) # Ponemos el pin 21 como salida
self.pulsoBase = GPIO.PWM(self.servoBase, 50) # Ponemos el pin 21 en modo PWM y enviamos 50 pulsos por segundo
self.pulsoLateral = GPIO.PWM(self.servoLateral, 50) # Ponemos el pin 21 en modo PWM y enviamos 50 pulsos por segundo
self.delay = 0.2
self.anterior = None
def enviarOrientacion(self, h, v):
pBase = convertirAngulo(h)
pLateral = convertirAngulo(v)
self.pulsoBase.start(pBase)
time.sleep(self.delay)
self.pulsoLateral.start(pLateral)
#self.pulsoBase.ChangeDutyCycle(pBase)
#self.pulsoLateral.ChangeDutyCycle(pLateral)
time.sleep(self.delay)
def detenerOrientacion(self):
self.pulsoBase.stop()
self.pulsoLateral.stop()
GPIO.cleanup()
def detenerOrientacion2(self):
self.pulsoBase.stop()
self.pulsoLateral.stop()
def iniciarOrientacion(self):
GPIO.setmode(GPIO.BOARD) # Ponemos la Raspberry en modo BOARD
GPIO.setup(self.servoBase, GPIO.OUT) # Ponemos el pin 21 como salida
GPIO.setup(self.servoLateral, GPIO.OUT) # Ponemos el pin 21 como salida
self.pulsoBase = GPIO.PWM(self.servoBase, 50) # Ponemos el pin 21 en modo PWM y enviamos 50 pulsos por segundo
self.pulsoLateral = GPIO.PWM(self.servoLateral, 50) # Ponemos el pin 21 en modo PWM y enviamos 50 pulsos por segund
def convertirAngulo(angulo):
resultado = (3+angulo/180.0*9)
#resultado = (1./18.*(angulo))+2
return resultado
|
PHP
|
UTF-8
| 5,548 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
//added
use DB;
use Carbon\Carbon;
# Include the Autoloader (see "Libraries" for install instructions)
use Mailgun\Mailgun;
use Mail;
use App\User;
use App\Winners;
class testController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$awnsers= DB::table('users')
->join('awnsers', 'users.id', '=', 'awnsers.FK_user')
->where('awnsers.created_at','>=',Carbon::today())
->select('users.name','users.surname')
->get();
$file = fopen('file.csv', 'w');
$csv = array();
foreach ($awnsers as $row) {
$csv[]=array("name" => $row->name,"surname" => $row->surname);
}
foreach ($csv as $row) {
fputcsv($file, $row);
}
fclose($file);
/* Mail::raw('Laravel with Mailgun is easy!', function($message)
{
$message->to('jonasvanreeth@gmail.com');
});*/
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function selectWinner()
{
echo Carbon::today();
//get the question of the last period not checked for winners
$inquiry = DB::table('inquiries')
->whereNull('deleted_at')
->orderBy('stop', 'asc')
->first();
//check if the question has ended
if($inquiry->stop == Carbon::today())
{
//count all the ones who got it correct
$countCorrect = DB::table('awnsers')
->where('FK_inquiry',$inquiry->id)
->where('awnser',$inquiry->awnser)
->count();
//check the shifting question
$first = DB::table('awnsers')
->select('FK_user','shifting')
->where('shifting','<',$countCorrect)
->orderBy('shifting','DESC')
->take(3);
$winners = DB::table('awnsers')
->select('FK_user','shifting')
->where('shifting','>=',$countCorrect)
->orderBy('shifting','DESC')
->take(3)
->union($first)
->orderBy('shifting','DESC')
->take(3)
->get();
//write away
$file = fopen('winners.csv', 'w');
$ids = array();
foreach ($winners as $row) {
$ids[]=$row->FK_user;
$newWinners = new Winners;
$newWinners->FK_inquiry = 1;
$newWinners->FK_user = 1;
$newWinners->save();
}
//get names
$names = DB::table('users')
->select('name','surname')
->whereIn('id', $ids)
->get();
foreach ($names as $row) {
$csv=array("name" => $row->name,"surname" => $row->surname);
fputcsv($file,$csv);
}
fclose($file);
//close period
$inquiry->delete();
}
//send mail-----------------
$users = DB::table('users')
->whereNotNull('admin')
->get();
foreach($users as $user)
{
$data = ['user' => $user];
$pathToFile = "public/winners.csv";
Mail::send('mail', $data, function ($message) {
$message->from('contest@stuff.com', 'contest.stuff');
$message->attach("winners.csv");
$message->to('jonasvanreeth@gmail.com')->cc('bar@example.com');
});
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function mail(Request $request)
{
$users = DB::table('users')
->whereNotNull('admin')
->get();
foreach($users as $user)
{
$data = ['user' => $user];
$pathToFile = "public/winners.csv";
Mail::send('mail', $data, function ($message) {
$message->from('contest@stuff.com', 'contest.stuff');
$message->attach("winners.csv");
$message->to('jonasvanreeth@gmail.com')->cc('bar@example.com');
});
}
}
public function winner(Request $request)
{
$newWinners = new Winners;
$newWinners->FK_inquiry = 1;
$newWinners->FK_user = 1;
$newWinners->save();
}
}
// zet in route
// Route::get('/test', ['as' => 'test', 'uses' => 'testController@index']);
// Route::get('/winner', ['as' => 'winner', 'uses' => 'testController@winner']);
// Route::get('/mail', ['as' => 'mail', 'uses' => 'testController@mail']);
|
Java
|
UTF-8
| 2,527 | 2.859375 | 3 |
[] |
no_license
|
package optics.raytrace.sceneObjects;
import math.Vector3D;
import optics.raytrace.core.SceneObject;
import optics.raytrace.core.Studio;
import optics.raytrace.core.SurfaceProperty;
/**
* A ray-trajectory cone made from simpler ray trajectories
*/
public class SimplerRayTrajectoryCone extends RayTrajectoryCone
{
private static final long serialVersionUID = -2181945095014084720L;
/**
* creates a cone of ray trajectories
*
* @param description
* @param startPoint
* @param startTime
* @param axisDirection
* @param coneAngle
* @param numberOfRays
* @param rayRadius
* @param surfaceProperty any surface properties
* @param maxTraceLevel
*/
public SimplerRayTrajectoryCone(String description, Vector3D startPoint, double startTime, Vector3D axisDirection, double coneAngle, int numberOfRays, double rayRadius, SurfaceProperty surfaceProperty, int maxTraceLevel, SceneObject parent, Studio studio)
{
super(description, startPoint, startTime, axisDirection, coneAngle, numberOfRays, rayRadius, surfaceProperty, maxTraceLevel, parent, studio);
}
public SimplerRayTrajectoryCone(SimplerRayTrajectoryCone original)
{
super(original);
}
/* (non-Javadoc)
* @see optics.raytrace.sceneObjects.SceneObject#clone()
*/
@Override
public SimplerRayTrajectoryCone clone()
{
return new SimplerRayTrajectoryCone(this);
}
@Override
public void addRayTrajectories()
{
// get rid of anything already in this SceneObjectContainer
clear();
Double sin = Math.sin(getConeAngle());
// Three vectors which form an orthogonal system.
// a points in the direction of the axis and is of length cos(coneAngle);
// u and v are both of length sin(coneAngle).
Vector3D
a = getAxisDirection().getWithLength(Math.cos(getConeAngle())),
u = Vector3D.getANormal(getAxisDirection()).getWithLength(sin),
v = Vector3D.crossProduct(getAxisDirection(), u).getWithLength(sin);
for(int i=0; i<getNumberOfRays(); i++)
{
Double phi = 2*Math.PI*i/getNumberOfRays();
addSceneObject(
new SimplerRayTrajectory(
"trajectory of ray #" + i,
getConeApex(),
getStartTime(),
Vector3D.sum(
a,
u.getProductWith(Math.cos(phi)),
v.getProductWith(Math.sin(phi))
),
getRayRadius(),
getSurfaceProperty(),
getMaxTraceLevel(),
false, // reportToConsole
this, // parent
getStudio()
)
);
}
}
@Override
public String getType()
{
return "Ray-trajectory cone";
}
}
|
C++
|
UTF-8
| 676 | 2.734375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string line;
int iCase = 0;
while(true) {
getline(cin, line);
int n;
sscanf(line.c_str(), "%d", &n);
if (n == 0)
break;
vector<string> v(n);
for(int i = 0; i < n; i++)
getline(cin, v[i]);
vector<string> u(n);
for(int i = 0; i < n; i++) {
int j = (i%2 == 0 ? i/2 : n-i/2-1);
u[j] = v[i];
}
cout << "SET " << ++iCase << endl;
for(int i = 0; i < n; i++)
cout << u[i] << endl;
}
return 0;
}
|
JavaScript
|
UTF-8
| 996 | 2.671875 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
var sessionName ;
var sessionUser;
function check_user()
{
var check = window.sessionStorage.getItem("has_logged_in");
if(check==null)
{
console.log("you haven't Logged in!")
}
else{
window.location.replace("http://vigneashsundar.in/post");
}
}
function check_user_session()
{
var check = window.sessionStorage.getItem("has_logged_in");
if(check==null)
{
window.location.replace("http://vigneashsundar.in/login");
}
else{
console.log("Things are fine to GO dude")
sessionName=sessionStorage.getItem("sessionName");
sessionUser=sessionStorage.getItem("sessionUser");
}
}
function set_session()
{
sessionStorage.setItem("has_logged_in","true")
sessionStorage.setItem("sessionName",session_name)
sessionStorage.setItem("sessionUser",session_user)
}
function redirect_user()
{
window.location.replace("http://vigneashsundar.in/post")
}
|
Java
|
UTF-8
| 618 | 2.265625 | 2 |
[] |
no_license
|
package l2r.gameserver.network.serverpackets;
import gr.sr.network.handler.ServerTypeConfigs;
public class ExNevitAdventEffect extends L2GameServerPacket
{
private final int _timeLeft;
public ExNevitAdventEffect(int timeLeft)
{
_timeLeft = timeLeft;
}
@Override
protected void writeImpl()
{
switch (ServerTypeConfigs.SERVER_TYPE)
{
case IL:
case GF:
case EPILOGUE:
case FREYA:
return;
}
writeC(0xFE);
switch (ServerTypeConfigs.SERVER_TYPE)
{
case H5:
writeH(0xE0);
break;
case GC:
case SL:
writeH(0xE4);
break;
}
writeD(_timeLeft);
}
}
|
Python
|
UTF-8
| 1,972 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
import streamlit as st
from .fixed_params import emoji_text_dict
def main(
# Case 1:
mean_mRS_treated_case1,
mean_mRS_change_case1,
mean_util_treated_case1,
mean_util_change_case1,
case1_time_to_ivt,
case1_time_to_mt,
# Case 2:
mean_mRS_treated_case2,
mean_mRS_change_case2,
mean_util_treated_case2,
mean_util_change_case2,
case2_time_to_ivt,
case2_time_to_mt,
):
st.subheader('Case 1')
draw_metrics(
case1_time_to_ivt,
case1_time_to_mt,
mean_mRS_treated_case1,
mean_mRS_change_case1,
mean_util_treated_case1,
mean_util_change_case1
)
# st.write('-'*20)
st.subheader('Case 2')
draw_metrics(
case2_time_to_ivt,
case2_time_to_mt,
mean_mRS_treated_case2,
mean_mRS_change_case2,
mean_util_treated_case2,
mean_util_change_case2
)
def draw_metrics(
time_to_ivt,
time_to_mt,
mean_mRS_treated,
mean_mRS_change,
mean_util_treated,
mean_util_change
):
# Put the metrics in columns:
cols = st.columns(3)
# Column 0: Times
cols[0].caption('Treatment times')
cols[0].write(
emoji_text_dict['ivt_arrival_to_treatment'] +
f' IVT: {time_to_ivt//60}hr {time_to_ivt%60}min'
)
cols[0].write(
emoji_text_dict['mt_arrival_to_treatment'] +
f' MT: {time_to_mt//60}hr {time_to_mt%60}min'
)
# Column 1: mRS
cols[1].metric(
'Population mean mRS',
f'{mean_mRS_treated:0.2f}',
f'{mean_mRS_change:0.2f} from no treatment',
delta_color='inverse' # A negative difference is good.
)
# Column 2: utility
cols[2].metric(
'Population mean utility',
f'{mean_util_treated:0.3f}',
f'{mean_util_change:0.3f} from no treatment',
)
|
Markdown
|
UTF-8
| 3,243 | 2.625 | 3 |
[] |
no_license
|
---
title: “营养又美味”的金属“汉堡”
date: 2020-11-09T18:10:02+08:00
tags:
- 金属
categories:
- 新闻
abbrlink:
---
来源:中科院之声
汉堡由面包、蔬菜、肉饼和芝士堆叠而成,因美味且提供丰富的营养成为了人们重要的食物形式之一。其中,面包提供了碳水化合物,蔬菜贡献了丰富的维生素,肉饼提供了蛋白质,而芝士则含有大量的脂肪。因此,这小小的汉堡满足了我们人类日常所需的各项营养物质。

图1 含有丰富食材的汉堡
金属材料是工业发展不可或缺的重要“食材”,尤其是在面向核聚变能的应用中,其不仅要支撑聚变装置的主体结构,更要具备一定功能性。
倘若一种或多种金属“食材”被制备成具有“汉堡”一样的结构,那是否能发挥更大的作用呢?

图2 聚变实验堆内部金属构件
中国科学院合肥物质科学研究院方前锋研究员课题组利用特殊的制备工艺,创造性的“编码”铜铌纳米叠层材料的微观结构尺度分布,实现了类似于“条形码”形貌的多尺度、多级特征结构。
其中,不同尺度分布的单元可以扮演“汉堡”中“面包、蔬菜、芝士”等角色。
即多尺度结构实现了多级强化机制的配合,如细晶强化、位错强化、裂纹阻碍等,因此极大地提高了材料的强度和可加工性。

图3 纳米叠层金属中类似“汉堡”的多尺度结构及其强化机制
此外,多级结构还能调控“汉堡”口味。
即通过控制加工过程中材料内部应力场的变化构建出不同的界面类型,利用不断累积的失配位错与界面发生相互作用,可控地形成有序共格、化学混合以及无序非晶界面。
研究人员通过氦离子辐照实验及分子动力学模拟分析得出,正是这种具有化学混合和非晶结构特征的三维界面(3D)有效抑制了聚变反应产生的辐照缺陷对材料性能的不利影响。

图4 不同界面的原子结构以及对辐照缺陷的反馈
此外,这种高密度的化学混合界面结构增强了对磁通线的钉扎效应,提高了材料的超导电流负载能力。该项研究基于实验设计与理论模拟相结合,验证了构造多级特征结构以实现高性能材料的有效策略,同时利用特殊界面调控氦泡生长的动力学过程,最终使铜铌叠层材料具有优异的机械、超导和抗辐照性能,并有望应用于核聚变领域。
相关论文发表在金属材料领域国际期刊 Acta Materialia 上,论文链接:https://www.sciencedirect.com/science/article/abs/pii/S1359645420305371。
来源:中国科学院合肥物质科学研究院
|
Python
|
UTF-8
| 619 | 3.46875 | 3 |
[] |
no_license
|
from tkinter import *
n = 10
size = 600
root = Tk()
canvas = Canvas(root, width=size, height=size)
canvas.pack()
a = [[0,1,2], [3,4], [6], [5,7,8], [9]]
points = []
h = size / (len(a) + 1)
pos_y = size - h
for i in range(len(a)):
w = size / (len(a[i]) + 1)
pos_x = w
p = []
for j in range(len(a[i])):
canvas.create_oval(pos_x - 3, pos_y - 3, pos_x + 3, pos_y + 3, fill = "black")
pi = [pos_x, pos_y]
p.append(pi)
pos_x += w
pos_y -= h
points.append(p)
canvas.create_line(points[0][0][0], points[0][0][1], points[1][0][0], points[1][0][1], width = 2)
mainloop()
|
Java
|
UTF-8
| 6,077 | 1.84375 | 2 |
[] |
no_license
|
package com.fh.entity.bo;
/**
* Created by Administrator on 2016/11/3 0003.
*/
public class AmountRecordBo {
private String token;
private int eid;
private int member_id;
private int uid;
private int type;
private String date;
private float amount;
private int status;
private String bankcard;
private String operatorid;
private String recordTime;
private String banktransaction;
private String bankName;
private float margin;
private float equity;
private String declaration_date;
private String declaration_price;//报单金额
private int declaration_num;//积分数
private int insurance_order_id;
private int real_num;
private String remark;
private String source;
private int unit;
private int isdelete;
private String poundage;
private String management;
private int integral;
private int box;
private int pid;
private int boxtotal;
private String price;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public int getMember_id() {
return member_id;
}
public void setMember_id(int member_id) {
this.member_id = member_id;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getBankcard() {
return bankcard;
}
public void setBankcard(String bankcard) {
this.bankcard = bankcard;
}
public String getOperatorid() {
return operatorid;
}
public void setOperatorid(String operatorid) {
this.operatorid = operatorid;
}
public String getRecordTime() {
return recordTime;
}
public void setRecordTime(String recordTime) {
this.recordTime = recordTime;
}
public String getBanktransaction() {
return banktransaction;
}
public void setBanktransaction(String banktransaction) {
this.banktransaction = banktransaction;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public float getMargin() {
return margin;
}
public void setMargin(float margin) {
this.margin = margin;
}
public float getEquity() {
return equity;
}
public void setEquity(float equity) {
this.equity = equity;
}
public String getDeclaration_date() {
return declaration_date;
}
public void setDeclaration_date(String declaration_date) {
this.declaration_date = declaration_date;
}
public String getDeclaration_price() {
return declaration_price;
}
public void setDeclaration_price(String declaration_price) {
this.declaration_price = declaration_price;
}
public int getDeclaration_num() {
return declaration_num;
}
public void setDeclaration_num(int declaration_num) {
this.declaration_num = declaration_num;
}
public int getInsurance_order_id() {
return insurance_order_id;
}
public void setInsurance_order_id(int insurance_order_id) {
this.insurance_order_id = insurance_order_id;
}
public int getReal_num() {
return real_num;
}
public void setReal_num(int real_num) {
this.real_num = real_num;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public int getUnit() {
return unit;
}
public void setUnit(int unit) {
this.unit = unit;
}
public int getIsdelete() {
return isdelete;
}
public void setIsdelete(int isdelete) {
this.isdelete = isdelete;
}
public String getPoundage() {
return poundage;
}
public void setPoundage(String poundage) {
this.poundage = poundage;
}
public String getManagement() {
return management;
}
public void setManagement(String management) {
this.management = management;
}
public int getIntegral() {
return integral;
}
public void setIntegral(int integral) {
this.integral = integral;
}
public int getBox() {
return box;
}
public void setBox(int box) {
this.box = box;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getBoxtotal() {
return boxtotal;
}
public void setBoxtotal(int boxtotal) {
this.boxtotal = boxtotal;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
|
JavaScript
|
UTF-8
| 100 | 2.65625 | 3 |
[] |
no_license
|
var arrProm = [Promise.resolve('a'), Promise.resolve('b')];
Promise.all(arrProm).then(console.log);
|
Java
|
UTF-8
| 10,351 | 1.9375 | 2 |
[] |
no_license
|
package adhd.sirikan.pimpicha.adhdform;
import android.graphics.Color;
import android.icu.util.Calendar;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class SnapActivity extends AppCompatActivity implements View.OnClickListener {
// explicit
private Button button;
Spinner spinnerView, spinnerView2, spinnerView3, spinnerView4, spinnerView5, spinnerView6, spinnerView7, spinnerView8, spinnerView9, spinnerView10,
spinnerView11, spinnerView12, spinnerView13, spinnerView14, spinnerView15, spinnerView16, spinnerView17, spinnerView18, spinnerView19, spinnerView20, spinnerView21, spinnerView22, spinnerView23, spinnerView24, spinnerView25, spinnerView26;
String spn, spn2, spn3, spn4, spn5, spn6, spn7, spn8, spn9, spn10, spn11, spn12, spn13, spn14, spn15, spn16, spn17, spn18, spn19, spn20, spn21, spn22, spn23, spn24, spn25, spn26;
String[] spinnerValue = {"-", "0", "1", "2", "3"};
private static String tag = "30MarchV1",tag2 = "16AprilV1";
String idString, loginString[];
TextView textView;
private java.util.Calendar calendar;
private String currentDateString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snap);
//Get value from Intent
getValueFromIntent();
//initial view
initialSpinner();
initialView();
//find currentDate
findCurrentDate();
textView = (TextView) findViewById(R.id.qsnap1);
//btn controller
button.setOnClickListener(SnapActivity.this);
}//main method
private void getValueFromIntent() {
idString = getIntent().getStringExtra("tmpIndex");
loginString = getIntent().getStringArrayExtra("Login");
for(int i = 0 ;i<loginString.length;i++) {
Log.d("tag2", "loginString(" + i + ")==>" + loginString[i]);
}
}
private void findCurrentDate() {
calendar = java.util.Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
currentDateString = dateFormat.format(calendar.getTime());
Log.d("10AprilV1", "currentDate" + currentDateString);
}
private void initialSpinner() {
spinnerView = (Spinner) findViewById(R.id.spinner1);
spinnerView2 = (Spinner) findViewById(R.id.spinner2);
spinnerView3 = (Spinner) findViewById(R.id.spinner3);
spinnerView4 = (Spinner) findViewById(R.id.spinner4);
spinnerView5 = (Spinner) findViewById(R.id.spinner5);
spinnerView6 = (Spinner) findViewById(R.id.spinner6);
spinnerView7 = (Spinner) findViewById(R.id.spinner7);
spinnerView8 = (Spinner) findViewById(R.id.spinner8);
spinnerView9 = (Spinner) findViewById(R.id.spinner9);
spinnerView10 = (Spinner) findViewById(R.id.spinner10);
spinnerView11 = (Spinner) findViewById(R.id.spinner11);
spinnerView12 = (Spinner) findViewById(R.id.spinner12);
spinnerView13 = (Spinner) findViewById(R.id.spinner13);
spinnerView14 = (Spinner) findViewById(R.id.spinner14);
spinnerView15 = (Spinner) findViewById(R.id.spinner15);
spinnerView16 = (Spinner) findViewById(R.id.spinner16);
spinnerView17 = (Spinner) findViewById(R.id.spinner17);
spinnerView18 = (Spinner) findViewById(R.id.spinner18);
spinnerView19 = (Spinner) findViewById(R.id.spinner19);
spinnerView20 = (Spinner) findViewById(R.id.spinner20);
spinnerView21 = (Spinner) findViewById(R.id.spinner21);
spinnerView22 = (Spinner) findViewById(R.id.spinner22);
spinnerView23 = (Spinner) findViewById(R.id.spinner23);
spinnerView24 = (Spinner) findViewById(R.id.spinner24);
spinnerView25 = (Spinner) findViewById(R.id.spinner25);
spinnerView26 = (Spinner) findViewById(R.id.spinner26);
ArrayAdapter<String> adapter = new ArrayAdapter<>(SnapActivity.this, android.R.layout.simple_list_item_1, spinnerValue);
spinnerView.setAdapter(adapter);
spinnerView2.setAdapter(adapter);
spinnerView3.setAdapter(adapter);
spinnerView4.setAdapter(adapter);
spinnerView5.setAdapter(adapter);
spinnerView6.setAdapter(adapter);
spinnerView7.setAdapter(adapter);
spinnerView8.setAdapter(adapter);
spinnerView9.setAdapter(adapter);
spinnerView10.setAdapter(adapter);
spinnerView11.setAdapter(adapter);
spinnerView12.setAdapter(adapter);
spinnerView13.setAdapter(adapter);
spinnerView14.setAdapter(adapter);
spinnerView15.setAdapter(adapter);
spinnerView16.setAdapter(adapter);
spinnerView17.setAdapter(adapter);
spinnerView18.setAdapter(adapter);
spinnerView19.setAdapter(adapter);
spinnerView20.setAdapter(adapter);
spinnerView21.setAdapter(adapter);
spinnerView22.setAdapter(adapter);
spinnerView23.setAdapter(adapter);
spinnerView24.setAdapter(adapter);
spinnerView25.setAdapter(adapter);
spinnerView26.setAdapter(adapter);
}
private void initialView() {
button = (Button) findViewById(R.id.snap4);
}
@Override
public void onClick(View v) {
if (v == button) {
//get value from edidtex
spn = spinnerView.getSelectedItem().toString();
spn2 = spinnerView2.getSelectedItem().toString();
spn3 = spinnerView3.getSelectedItem().toString();
spn4 = spinnerView4.getSelectedItem().toString();
spn5 = spinnerView5.getSelectedItem().toString();
spn6 = spinnerView6.getSelectedItem().toString();
spn7 = spinnerView7.getSelectedItem().toString();
spn8 = spinnerView8.getSelectedItem().toString();
spn9 = spinnerView9.getSelectedItem().toString();
spn10 = spinnerView10.getSelectedItem().toString();
spn11 = spinnerView11.getSelectedItem().toString();
spn12 = spinnerView12.getSelectedItem().toString();
spn13 = spinnerView13.getSelectedItem().toString();
spn14 = spinnerView14.getSelectedItem().toString();
spn15 = spinnerView15.getSelectedItem().toString();
spn16 = spinnerView16.getSelectedItem().toString();
spn17 = spinnerView17.getSelectedItem().toString();
spn18 = spinnerView18.getSelectedItem().toString();
spn19 = spinnerView19.getSelectedItem().toString();
spn20 = spinnerView20.getSelectedItem().toString();
spn21 = spinnerView21.getSelectedItem().toString();
spn22 = spinnerView22.getSelectedItem().toString();
spn23 = spinnerView23.getSelectedItem().toString();
spn24 = spinnerView24.getSelectedItem().toString();
spn25 = spinnerView25.getSelectedItem().toString();
spn26 = spinnerView26.getSelectedItem().toString();
if (checkSpinner()) {
//have space
myAlert objMyAlert = new myAlert(SnapActivity.this);
objMyAlert.myDialog(getResources().getString(R.string.title_havespace),
getResources().getString(R.string.message_havespece));
} else {
// check special
checkSpecial(idString, loginString[3]);
uploadValueToServer();
}
}
}
private void checkSpecial(String childID, String doType) {
try {
MyConstant myConstant = new MyConstant();
String urlPhp = myConstant.getUrlEditSpecial();
EditSpecial editSpecial = new EditSpecial(SnapActivity.this);
editSpecial.execute(childID, doType, urlPhp);
Log.d("16AprilV2", "Result ==>" + editSpecial.get());
} catch (Exception e) {
Log.d(tag2, "e checkSpecial ==>" + e.toString());
}
}
private boolean checkSpinner() {
if (spn.equals("-") || spn2.equals("-")||spn3.equals("-") ||
spn4.equals("-")||spn5.equals("-") || spn6.equals("-")||
spn7.equals("-")||spn8.equals("-") || spn9.equals("-")||
spn10.equals("-") || spn11.equals("-")||spn12.equals("-") ||
spn13.equals("-")||spn14.equals("-") || spn15.equals("-")||
spn16.equals("-") || spn17.equals("-")||spn18.equals("-") ||
spn19.equals("-")||spn20.equals("-") || spn21.equals("-")||
spn22.equals("-") || spn23.equals("-")||spn24.equals("-") ||
spn25.equals("-")|| spn26.equals("-") ) {
return true;
} else {
return false;
}
}
private void uploadValueToServer() {
//wait type string
try {
MyConstant myConstant = new MyConstant();
String strURL = myConstant.getUrlAddTest();
PostTest postTest = new PostTest(SnapActivity.this);
postTest.execute(spn, spn2, spn3, spn4, spn5,
spn6, spn7, spn8, spn9, spn10,
spn11, spn12, spn13, spn14, spn15,
spn16, spn17, spn18, spn19, spn20,
spn21, spn22, spn23, spn24, spn25,
spn26, loginString[0], idString, strURL,
"10", "20", "30", loginString[3], currentDateString);
Log.d(tag, "Result ==>" + postTest.get());
if (Boolean.parseBoolean((postTest.get()))) {
finish();
} else {
Toast.makeText(SnapActivity.this, "Cannot save user", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.d(tag, "e upload ==>" + e.toString());
}
}
}//main class
|
Markdown
|
UTF-8
| 2,371 | 3.359375 | 3 |
[] |
no_license
|
---
layout: surf
name: empathy
title: What is Empathy?
permalink: /emxpathy
published: false
description: >
"Humanity's future depends on empathy" - Stephen Hawking
image: https://chaz.co/assets/images/empathy_houses.jpg
---
# **Empathy**
The best way to understand something is to approach it from many different angles. Since empathy is all about understanding, let's find as many approaches as we can.
# 📖
Let's start by looking at the dictionary definition of **empathy.**
`One's capacity to understand another person.`
Let's keep going and look at the definition of **capacity**
`the maximum amount of something.`
and let's make sure we understand **understanding**
`the ability to comprehend. `
We now have the building blocks to figure out what it takes to make empathy.
# 🥪
Capacity is your willingness. Understanding = Imagination + Listening`
# 🌧
#### Bucket Analogy
Imagine yourself holding a bucket trying to catch rain where water is empathy. *Maximizing* the amount of water you collect depends on:
1. The size of your bucket.
2. Holding where the most water drips.
You could have the biggest bucket in the world, but if you don't stand next to the gutter it won't help much. And standing next to the gutter is no good with a tiny little baby bucket.
Empathy works the same way.
## Examples
### Capacity, but no understanding
You could be super willing (huge bucket) to understand Stephen Hawking, but he lives in a wheel chair and can't speak. It's probably really hard to understand that experience. And that's ok. **Even though you can't understand, Stephen will appreciate your willingness.**
### Understanding, but no capacity
You could easily understand (standing under the gutter) the reason someone left a nasty comment on the internet is because they hate themselves, but if you aren't willing to understand, there's not much empathy.
#### Capacity and Understanding
You could understand that someone with racist parents might have racist tendancies. That doesn't mean you support their racist tendancies.
> Empathy does not require agreement.
#### **More math**
`Understanding = Imagination + Listening`
It's hard to imagine someone else's experience if you haven't shared a similar experience.
---
<!--
> *"The future of humanity depends on empathy."*
### Why is empathy important? -->
[email]: mailto:khabich@gmail.com
|
C++
|
UTF-8
| 1,849 | 3.203125 | 3 |
[] |
no_license
|
//============================================================================
// Name : p0105.cpp
// Author : Zhengwei
// Version :
// Copyright : Your copyright notice
// Description : string compression
//============================================================================
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include "boost/lexical_cast.hpp"
using namespace std;
template <typename T>
int numDigits(T num){
int digits(0);
if(num<0)
return 1;
while(num){
++digits;
num /= 10;
}
return digits;
}
size_t compressedLength(char* str){
size_t len(0);
if(strlen(str)==0)
return 0;
else if(strlen(str)==1)
return 2;
char pre = str[0];
size_t count = 1;
for(size_t i=1; str[i]!='\0'; ++i)
{
if( str[i]==pre )
++count;
else{
len += numDigits(count) + 1;
count = 1;
pre = str[i];
}
}
len += numDigits(count) + 1;
return len;
}
void compression(char* str)
{
size_t len(0), repeat(0), comLen(0);
len = strlen(str);
if( len<compressedLength(str) )
return;
char* newP = new char[compressedLength(str)];
char* newP2 = newP;
char pre = str[0];
size_t count = 1;
for(size_t i=1; str[i]!='\0'; ++i)
{
if( str[i]==pre )
++count;
else{
strcpy( newP2, (boost::lexical_cast<string>(count)).c_str() );
newP2 += numDigits(count);
*newP2++ = pre;
count = 1;
pre = str[i];
}
}
strcpy( newP2, (boost::lexical_cast<string>(count)).c_str() );
newP2 += numDigits(count);
*newP2++ = pre;
*newP2 = '\0';
strcpy(str,newP);
return;
}
int main() {
char p1[] = "aabbbcdddd";
cout<<"The original string is: "<<p1<<endl;
cout<<"The numDigits of 23 is: "<<numDigits(23)<<endl;
cout<<"The compressedLength of p1 is: "<<compressedLength(p1)<<endl;
compression(p1);
cout<<"The compressed string is: "<<p1<<endl;
return 0;
}
|
Ruby
|
UTF-8
| 1,365 | 2.546875 | 3 |
[] |
no_license
|
class TestPassage < ApplicationRecord
belongs_to :user
belongs_to :test
belongs_to :current_question, class_name: "Question", optional: true
before_save :before_save_set_current_question
PASSING_SCORE = 85
def completed?
current_question.nil?
end
def accept!(answer_ids)
self.correct_questions += 1 if correct_answer?(answer_ids)
self.successfull = true if passed?
save!
end
def question_number
test.questions.order(:id).where('id < ?', current_question.id).count + 1
end
def questions_count
test.questions.count
end
def score
correct_questions * 100.00 / test.questions.count
end
def passed?
score >= PASSING_SCORE
end
def time_is_up?
sec = created_at + test.timer - Time.now
sec < 0 if time_limited?
end
def sec_left
(created_at + test.timer - Time.current).round
end
def time_limited?
test.timer != 0
end
private
def before_save_set_current_question
self.current_question = next_question
end
def next_question
if current_question.nil?
test.questions.first
else
test.questions.order(:id).where("id > ?", current_question.id).first
end
end
def correct_answer?(answer_ids)
correct_answers.ids.sort == Array(answer_ids).map(&:to_i).sort
end
def correct_answers
current_question.answers.correct
end
end
|
Python
|
UTF-8
| 389 | 3.0625 | 3 |
[] |
no_license
|
from typing import List
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0] * (amount + 1)
dp[0] = 1
for i in coins:
for j in range(amount+1):
if j - i >= 0 and dp[j-i] > 0:
dp[j] += dp[j-i]
return dp[amount]
test = Solution()
coins = [10]
print(test.change(10, coins))
|
PHP
|
UTF-8
| 553 | 2.609375 | 3 |
[] |
no_license
|
<?php
use Illuminate\Database\Seeder;
class FolloweesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$users = \App\Models\User::all();
foreach ($users as $user)
{
$followees = $users->random(10)
->filter(
function ($id) use ($user)
{
return $id != $user;
});
$user->followees()->sync($followees);
}
}
}
|
Python
|
UTF-8
| 220 | 3.390625 | 3 |
[] |
no_license
|
""" e-Judge """
def main():
""" The box """
number_square = int(input())
number_dokjun = "* " * number_square
square = ((number_dokjun + "\n") * (number_square-1) + number_dokjun)
print(square)
main()
|
Python
|
UTF-8
| 21,402 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
import copy
import logging
from vector import (Vector3D, baseVectors, baseDirections, rotx, roty, rotz,
multiply, mirror_yz, mirror_zx, mirror_xy)
logging.basicConfig(format='%(levelname)s:%(name)s: %(message)s',
level=logging.WARNING)
logger = logging.getLogger(__name__)
def _makeJointDirections():
"""Generate a lookup table for the backtracking head.
It contains lists of all possible new directions at a joint element. When
the backtracking head encounters a joint element, it can lookup possible
new directions in this dict. With our snake cube we only have one
interesting kind of joint element (the 90 degree joint), thus one lookup
table suffices.
Returns:
dict: The generated lookup table.
key = The current direction.
value = The list of all possible new directions for a given key.
"""
# number of base directions (base vectors and their inverse) in a 3D plane
N_PLANE_BASEDIR = 4
# number of base vectors in 3D space
N_BASEVEC = 3
mapVtoRM = dict()
mapVtoRM[str(Vector3D(1,0,0))] = rotx
mapVtoRM[str(Vector3D(0,1,0))] = roty
mapVtoRM[str(Vector3D(0,0,1))] = rotz
jointDirections = dict()
for i, vector in enumerate(baseVectors):
newDirections = []
rotmat = mapVtoRM[str(vector)]
# add one other (random) base vector which is perpendicular ...
newDirections.append(baseVectors[(i+1)%N_BASEVEC])
# ... and include all other base directions in that plane (+/-)
for j in range(N_PLANE_BASEDIR):
newDirections.append(multiply(rotmat, newDirections[-1]))
jointDirections[str(vector)] = newDirections
jointDirections[str(-1*vector)] = newDirections
return jointDirections
jointDirections = _makeJointDirections()
"""A lookup table for the backtracking head containing new joint directions.
See documentation for _makeJointDirections() for more info.
"""
# number of unique joint states for the 90 degree dual-joint element
N_JNTS = 4
# possible joint states for the 90 degree dual-joint element
JOINT0 = 0
JOINT1 = 1
JOINT2 = 2
JOINT3 = 3
# cube: position occupied by some other chain element
POS_USED = -1
# cube: position free
POS_FREE = -2
class BacktrackHead:
"""A class implementing the "head" (or tip) of the backtracking algorithm.
It basically consists of two vectors, one describing the current position
of the head, the other describing the direction in which the head is
"looking". In general, the direction vector and "joint state" mean the
same thing here.
Args:
base (Vector3D): Current position of the backtracking head.
direction (Vector3D): Current direction of the backtracking head.
Possible values are b and (-b), where b is one of the three cartesian
unit vectors (only unit vectors are supported as base vectors).
Attributes:
base (Vector3D): Current position of the backtracking head.
direction (Vector3D): Current direction of the backtracking head.
"""
__slots__ = ['base', 'direction', '_old_direction']
def __init__(self, base, direction):
self.base = base
self.direction = direction
self._old_direction = None
def __repr__(self):
return f"BacktrackHead({self.base!r}, {self.direction!r})"
def get_sign(self):
"""Return the current sign of the backtracking head's direction."""
if max(self.direction.to_list()) == 1:
return 1
else:
return -1
def move(self, nsteps):
"""Move the backtracking head nsteps forward.
Move the backtracking head's base vector nsteps steps into the
direction of the backtracking head's direction vector.
Args:
nsteps (int): The number of steps the backtracking head shall move.
"""
self.base += nsteps * self.direction
def change_direction(self):
"""Change the backtracking head's direction by 90 degree (new joint).
Change the backtracking head's direction vector to a new direction
vector parallel to one of the base axes so that the new direction
vector is perpendicular to the current direction vector. This
typically occurs after moving the head forward, when a new joint
element is encountered. The new direction vector (i.e. the state of the
joint) is chosen arbitrarily to the first of the four possible values.
The current direction vector is saved in the internal variable
self._old_direction prior to the change, which is used by
self.rotate_to().
"""
self._old_direction = self.direction
joint_state = JOINT0
self.direction = jointDirections[str(self._old_direction)][joint_state]
def rotate_to(self, joint_state):
"""Change the backtracking head's direction by 90 degree (same joint).
Change the backtracking head's direction vector to a new direction
vector parallel to one of the base axes so that the new direction
vector is perpendicular (1) to the current direction vector and also
(2) to the old direction vector self._old_direction as saved by
self.change_direction().
This typically is done when the backtracking algorithm is "backing up"
(going backwards) because there are no (or no more) solutions with the
current joint state at the backtracking head.
The new direction vector (i.e. the state of the joint) is explicitly
specified by the argument joint_state.
Args:
joint_state (int): The new state of the joint element.
The value should be specified using one of the constants JOINTx,
where x is a number in range(N_JNTS).
"""
assert self._old_direction is not None
self.direction = jointDirections[str(self._old_direction)][joint_state]
class Backtrack:
"""A class containing the core algorithm for backtracking the snake cube.
After creating an object of this class, the backtracking problem can be
solved by simply calling self.solve() on it, which returns self._paths,
containing all possible solutions.
Args:
chain (list(int)): Representation of the snake cube chain to be solved.
cubesize (int): Edge length of the snake cube.
head (BacktrackHead): Starting position for the backtracking algorithm.
Attributes:
chain (list(int)): Representation of the snake cube chain to be solved.
cubesize (int): Edge length of the snake cube.
head (BacktrackHead): Current position of the backtracking algorithm.
_pos (int): Current position in the chain. Starts at 0.
_chainlength (int): Length of the chain.
_cube (list(list(list(int)))): A matrix representing the snake cube.
The matrix represents the available space in the cube that can be
"occupied" by the chain.
Each field in the matrix is set one of the following values:
JOINTx (where x is a number in range(N_JNTS)): The value indicates
the state of the 90 degree dual-joint element which is currently
present at this field.
POS_USED: The field is currently occupied by another chain element.
POS_FREE: The field is unoccupied and free for use.
_paths (list(list(int))): List of the solutions so far found.
Each element in this variable represents a solution, i.e. a "chain
folding" that "fits" the chain into the cube.
"""
__slots__ = ['chain', 'cubesize', 'head', '_pos', '_chainlength', '_cube',
'_paths']
def __init__(self, chain, cubesize, head):
self.chain = chain
self.cubesize = cubesize
self.head = head
self._pos = 0
self._chainlength = len(chain)
self._cube = [[[POS_FREE for i in range(cubesize)]
for j in range(cubesize)] for k in range(cubesize)]
self._paths = []
def solve(self):
"""Run backtracking algorithm in a loop until all solutions are found.
This method calls self._backtrack() until it returns no more solutions.
All solutions are gathered in the internal variable self._paths, which
is returned when there are no more solutions to be found.
Returns:
list(list(int)): List of all possible solutions.
"""
if self._paths == []:
path = self._backtrack()
while path is not None:
logger.info('new solution found: %s', path)
self._paths.append(path)
path = self._backtrack()
logger.info('backtracking exhausted (no more solutions for the '
'specified starting point and direction)')
else:
# already solved
pass
return self._paths
def _joint_wrapped(self, joint_state):
"""Check if a given joint "wrapped around".
There are N_JNTS (4) possible states for a 90 degree joint, which all
have to be tried during the backtracking. When a given joint wrapps
around (i.e. it takes a value which was already taken earlier), the
algorithm should "back up" (go backwards) and change the join prior to
the current joint to find any new solutions.
Returns:
bool: True if joint wrapped around, False otherwise.
"""
return joint_state >= N_JNTS
def _backtrack(self):
"""Core implementation of the backtracking algorithm.
The method instantly returns if it finds a new solution, returning that
solution. When it is called again, it will resume the backtracking
process from where it stopped to find another new solution. This
continues until there are no more new solutions available, at which
point None is returned, signalling that the backtracking process is
exhausted.
Returns:
list(int)/None: A new solution to the backtracking problem, or None
if no more solutions are available, i.e. the backtracking is
exhausted.
"""
if self._pos == 0: # first run
logger.info('>> starting backtracking...')
path = []
self._cube_set_offset(0, POS_USED)
else: # subsequent run
logger.info('>> restarting backtracking...')
path = copy.deepcopy(self._paths[-1])
# restore _pos, head, and path
self._pos -= 1
self.head = path.pop()
# restore _cube
steps_to_delete = self.chain[self._pos]
for i in range(1, steps_to_delete + 1):
self._cube_set_offset(i, POS_FREE)
# pick new direction
joint_state = self._cube_get_offset(0)
self.head.rotate_to((joint_state+1)%N_JNTS)
self._cube_set_offset(0, joint_state+1)
logger.debug('>> going back to pos %s...', self._pos)
debug_counter = 0
while self._pos < self._chainlength:
# In every cycle, self._pos points to that slice in self.chain
# which has no yet been put into path (the current solution), i.e.
# the slice has not yet been "walked over". Note that after a slice
# has been walked over and recorded into path (in form of a record
# of the backtracking head's state), it can be removed therefrom
# again.
#
# The backtracking head self.head determines the position of the
# current slice in the cube. head.base points to the beginning of
# the current slice (== end of the last slice), and head.direction
# points to the end of the current slice (== start of the next
# slice).
logger.debug(f'======== CYCLE NO: {debug_counter} ========')
debug_counter += 1
logger.debug('_pos: %d', self._pos)
logger.debug('path: %s', path)
logger.debug('head: %s', self.head)
joint_state = self._cube_get_offset(0)
logger.debug('joint_state: %s', joint_state)
if not self._joint_wrapped(joint_state): # joint_state okay
logger.debug('>> joint okay: joint not wrapped')
steps_needed = self.chain[self._pos]
steps_allowed = self._nsteps()
logger.debug('steps_needed: %s', steps_needed)
logger.debug('steps_allowed: %s', steps_allowed)
if steps_allowed < steps_needed: # the way is free...
logger.debug('>> steps_allowed < steps_needed')
try:
self.head.rotate_to((joint_state+1)%N_JNTS)
except AssertionError:
# This happens when the backtracking head tries to
# rotate before any forward movement, i.e. at the very
# beginning of the backtracking process. In this case,
# there is no valid solution for the specified
# backtracking head (starting point + direction).
return None
self._cube_set_offset(0, joint_state + 1)
logger.debug('>> trying new joint %s of direction %s '
'which maps to %s', joint_state + 1,
self.head._old_direction.to_list(),
self.head.direction.to_list())
else: # the way is not free...
logger.debug('>> moving %d steps forward...', steps_needed)
new_joint_state = JOINT0
# cube: record new joint direction and set fields between
# joints to POS_USED, indicating occupation
for i in range(1, steps_needed):
self._cube_set_offset(i, POS_USED)
self._cube_set_offset(steps_needed, new_joint_state)
# path: record current state of head
path.append(copy.deepcopy(self.head))
self.head.move(steps_needed)
self.head.change_direction()
self._pos += 1
logger.debug('>> trying new joint %s of direction %s '
'which maps to %s', new_joint_state,
self.head._old_direction.to_list(),
self.head.direction.to_list())
else: # joint_state wrapped around
logger.debug('>> joint wrapped around! joint_state >= %d',
N_JNTS)
if self._pos == 1:
# backtracking exhausted (no more solutions for the
# specified starting point and direction)
return None
# restore _pos, head, and path
self._pos -= 1
self.head = path.pop()
# restore cube
steps_to_delete = self.chain[self._pos]
for i in range(1, steps_to_delete + 1):
self._cube_set_offset(i, POS_FREE)
# pick new direction
joint_state = self._cube_get_offset(0)
self.head.rotate_to((joint_state+1)%N_JNTS)
self._cube_set_offset(0, joint_state+1)
logger.debug('>> going back to pos %s...', self._pos)
# path now contains len(self.chain) copies of the backtracking head
# (BacktrackHead objects). Each element's head attribute points to the
# beginning of a slice, and each element's direction attribute points
# to the beginning of the next slice.
return path
def _cube_get_offset(self, offset):
"""Return the value at the backtracking head after moving offset steps.
Args:
offset (int): Number of steps to make before retrieving the value.
Returns:
int: The value in the internal cube matrix at the postion of the
backtracking head, after walking offset steps into the current
direction of the backtracking head.
"""
pos = self.head.base + (offset * self.head.direction)
return self._cube[pos.x][pos.y][pos.z]
def _cube_set_offset(self, offset, value):
"""Set the value at the backtracking head after moving offset steps.
Args:
offset (int): Number of steps to make before setting the value.
value (int): The value to be set in the internal cube matrix at the
postion of the backtracking head, after walking offset steps into
the current direction of the backtracking head.
"""
pos = self.head.base + (offset * self.head.direction)
self._cube[pos.x][pos.y][pos.z] = value
def _nsteps(self):
"""Return the number of valid steps the backtracking head could make.
Returns:
int: The current number of straight steps the backtracking head can
make, while (1) staying within the cube's bounds and (2) not
colliding with any "previous" parts of the chain. Depends on
self._cube, self.head, and self.cubesize.
"""
nsteps = 0
pos = self.head.base
if self.head.get_sign() == 1:
while ((max((pos + self.head.direction).to_list()) < self.cubesize)
and (self._cube_get_offset(nsteps+1) == POS_FREE)):
pos += self.head.direction
nsteps += 1
else: # self.head.get_sign() == -1
while ((min((pos + self.head.direction).to_list()) >= 0)
and (self._cube_get_offset(nsteps+1) == POS_FREE)):
pos += self.head.direction
nsteps += 1
return nsteps
def main():
"""Demonstrate usage of the Backtrack class with an example chain."""
logger.debug('jointDirections:')
for key in jointDirections:
logger.debug("\t%s: %s", key, jointDirections[key])
# Unique (except for start/end orientation) representation of the chain.
# Every element is assigned a number, based on the number and configuration
# of its joints.
# 0 = element with only one joint (start/end of the chain)
# 1 = element with two joints on opposite sides (straight joint element)
# 2 = element with two joints on adjacent sides (90 degree joint element)
chain_elements = [0, 1, 2, 2, 2, 1, 2, 2, 1, 2, 2, 2, 1, 2, 1, 2, 2, 2, 2,
1, 2, 1, 2, 1, 2, 1, 0]
# Unique (except for start/end orientation) representation of the chain.
# Every slice is assigned a number, based on its length. All slices are
# assumed to be connected by the same type of joint: a 90 degree dual-joint
# element. Every 90 degree dual-joint element is part of two slices.
# 1 = slice with 2 elements (backtracking head can be incremented by 1).
# 2 = slice with 3 elements (backtracking head can be incremented by 2).
chain_slices = [2, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2]
# Use a 3x3x3 cube.
cubesize = 3
#
# Backtracking
#
# These are all the interesting starting points and directions.
btheads = [
BacktrackHead(Vector3D(0, 0, 0), Vector3D(1, 0, 0)),
BacktrackHead(Vector3D(1, 0, 0), Vector3D(1, 0, 0)),
BacktrackHead(Vector3D(1, 0, 0), Vector3D(0, 1, 0)),
BacktrackHead(Vector3D(1, 1, 0), Vector3D(1, 0, 0)),
BacktrackHead(Vector3D(1, 1, 0), Vector3D(0, 0, 1)),
BacktrackHead(Vector3D(1, 1, 1), Vector3D(1, 0, 0)),
]
all_solutions = []
for bthead in btheads:
backtrack = Backtrack(chain_slices, cubesize, bthead)
print(f'>> start backtracking with starting point {bthead}')
solutions = backtrack.solve()
# print solutions
print('==== solutions ====')
for i, path in enumerate(solutions):
all_solutions.append(path)
path_bases = list(map(lambda x: x.base.to_list(), path))
path_directions = list(map(lambda x: x.direction.to_list(), path))
print(f'solution {i} (as base points): {path_bases}')
#print(f'solution {i} (as directions): {path_directions}')
if len(solutions) == 0:
print('no solutions')
print()
# Demonstrate that the only two solutions found are similar.
path0points = list(map(lambda x: x.base.to_list(), all_solutions[0]))
path1points = list(map(lambda x: x.base.to_list(), all_solutions[1]))
f = lambda x: multiply(rotz, multiply(rotz, multiply(rotx,
multiply(mirror_yz, x)))).to_list()
if path1points == list(map(f, path0points)):
print('The two solutions are similar! Just mirror one solution at the '
'yz-plane, rotate 90 degree about the x axis and 180 degree '
'about the z axis, and you got the other solution.')
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 153 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
# https://programmers.co.kr/learn/courses/30/lessons/12944
def soultion(arr):
sum = 0
for i in arr:
sum += i
return(sum / len(arr))
|
Java
|
GB18030
| 2,222 | 2.34375 | 2 |
[] |
no_license
|
package com.blacknife.mobliesafe.activity;
import com.blacknife.mobliesafe.R;
import com.blacknife.mobliesafe.db.dao.AddressDao;
import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;
/**
* زѯ
* @author Blacknife
*
*/
public class AddressActivity extends Activity {
private EditText etNumber;
private TextView tvResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address);
etNumber = (EditText) findViewById(R.id.et_number);
tvResult = (TextView) findViewById(R.id.tv_result);
//EditTextı仯
etNumber.addTextChangedListener(new TextWatcher() {
//ed仯ʱĻٵ
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String address = AddressDao.getAddress(s.toString());
tvResult.setText(address);
}
//仯ǰĻص
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
//ֱ仯Ļص
@Override
public void afterTextChanged(Editable s) {
}
});
}
/**
* ʼѯ
*/
public void query(View view){
String number = etNumber.getText().toString().trim();
if(!TextUtils.isEmpty(number)){
String address = AddressDao.getAddress(number);
tvResult.setText(address);
}else{
//ÿؼЧ
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
etNumber.startAnimation(shake);
vibrate();
}
}
/**
* ֻ,ҪȨ android.permission.VIBRATE
*/
private void vibrate(){
Vibrator vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrate.vibrate(2000);
/**
* int repeat -1 ʾִһ,ѭ,0 ʾѭ
*/
vibrate.vibrate(new long[]{1000, 2000,3000,4000},-1);//Ъ
//ȡ vibrate.cancel();
}
}
|
Java
|
UTF-8
| 1,091 | 4 | 4 |
[] |
no_license
|
package unit_testing;
/**
* @author Mpatziakoudi Katerina
* Applied Software Engineering
* Unit Testing Assignment
* April 2018
*/
public class MyMath {
/**Performs a division between two numbers and returns the result.
* Zero denominator cause an {@link IllegalArgumentException}
* @param num the integer input number for the first part of the division(numerator)
* @param denom the integer input number for the second part of the division(denominator)
* @exception IllegalArgumentException when denominator is equals to zero
* @return
* A double value with the result of division
*/
public double divide(int num, int denom){
if(denom != 0) {
return num / denom;
} else {
throw new IllegalArgumentException("'denominator' cannot be zero");
}
}
/**Get an integer as input and returns its reverse number.
* Zero denominator cause an {@link IllegalArgumentException}
* @param number the integer input number which we want to reverse
* @return
* An integer value with the result of reverse
*/
public int reverseNumber(int number) {
return -number;
}
}
|
Python
|
UTF-8
| 2,005 | 2.8125 | 3 |
[] |
no_license
|
#** This line is 79 characters long. The 80th character should wrap. ***\
#imports:
import os, re
import json
import warnings
import codecs
import pdfplumber
#define:
class extractor(object):
def __init__(self, filePath):
self.filePath = filePath
def extract(self, pageNumber, percents):
with pdfplumber.open(self.filePath) as pdf:
page = pdf.pages[int(pageNumber)]
crop = [float(p) for p in percents]
width = float(page.width)
height = float(page.height)
subset = page.crop((crop[0]*width,
crop[1]*height,
crop[2]*width if len(crop)>2 else page.width,
crop[3]*height if len(crop)>3 else page.height))
everything = subset.extract_text()
return everything
def reformat(agglomerateString):
lines = agglomerateString.split(os.linesep)
prefix = ' '*12 + '"'
suffix = '",'
reformatted = [f'{prefix}{l}{suffix}' for l in lines]
return reformatted
#run:
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--file', '-f', required=True,
help='path to pdf')
parser.add_argument('--page', '-p', required=True,
help='page in pdf')
parser.add_argument('--cropping', '-c', nargs='+',
required=False, help='')
args = parser.parse_args()
if args.cropping:
extracted = extractor(args.file).extract(args.page, args.cropping)
else:
extracted = ''
for crops in ([0,0,0.36,1], [0.36,0,0.65,1], [0.65,0,1,1]):
extracted += extractor(args.file).extract(args.page, crops)
extracted += os.linesep
with open(os.path.join(os.path.dirname(args.file),
'extractedText.txt'),'w') as extraction:
extraction.write(os.linesep.join(reformat(extracted)))
|
C++
|
UTF-8
| 1,507 | 4.09375 | 4 |
[] |
no_license
|
/* Question 1:
* The Fibonacci numbers sequence, Fn, is defined as follows:
* F1 is 1, F2 is 1, and Fn = Fn-1 + Fn-2 for n = 3, 4, 5, ...
* In other words, each number is the sum of the previous two numbers. The first 10 numbers
* in Fibonacci sequence are: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
* Note: Background of Fibonacci sequence: https://en.wikipedia.org/wiki/Fibonacci_number
* 1. Write a function int fib(int n) that returns the n-th element of the Fibonacci
* sequence.
* 2. Write a program that prompts the user to enter a positive integer num, and then
* prints the num’s elements in the Fibonacci sequence.
*
* */
#include <iostream>
using namespace std;
int fib(int num);
int getInt ();
int main() {
int inputInt;
inputInt = getInt();
cout << fib(inputInt) << endl;
return 0;
}
int fib(int num){
int f1 = 1;
int f2 = 1;
int fibNum = 0;
int count;
if (num == 1 || num == 2)
return 1;
else{
for(count = 3; count <= num; count += 1){
fibNum = f1 + f2;
f2 = f1;
f1 = fibNum;
}
return fibNum;
}
}
int getInt (){
int input = 0;
while(true){
cout << "Please enter a positive integer: ";
cin >> input;
if(cin.fail() || input < 1) {
cout << "Invalid input. Please try again\n";
cin.clear();
cin.ignore(256, '\n');
continue;
}
else
break;
}
return input;
}
|
Ruby
|
UTF-8
| 388 | 3.65625 | 4 |
[
"MIT"
] |
permissive
|
story = "Once upon a time in a land far, far away..."
p story[5, 4]
#output:
#upon
p story.slice(5,4)
#output:
#upon
p story[-7, 5]
# output:
# away.
puts puts
p story[27..39]
# output:
# far, far away
p story.slice(27..39)
# output:
# far, far away
p story[27...39]
# output:
# far, far awa
p story[32..1000]
# output:
# far away...
puts
p story[25..-9]
# output:
# d far, far
|
Markdown
|
UTF-8
| 665 | 3 | 3 |
[] |
no_license
|
# ch4-`String`类型
`String`类型
* 被分配在堆上, 因此可以存储编译时未知的字符串
* 在运行时可以改变字符串
* 创建
* `String::from(string_literal)`
# C: Derivable Traits派生特征
`derive`属性
* 在有`derive`注解的类型上, 生成给定特征的默认实现的代码
以下是标准库中所有可以用于`derive`的特征
## `Debug`: 用于程序员输出
* 作用: 能够在格式化字符串中使用调试格式; 用`{:?}`表示某个值使用调式格式
* 意义: 为了调试, 允许打印某个类型的实例, 使得在程序执行时能够观察实例
## `PartialEq`和`Eq`: 相等性比较
|
Python
|
UTF-8
| 2,456 | 2.890625 | 3 |
[] |
no_license
|
import os.path
import sys
import json
from PIL import Image, ExifTags
from datetime import datetime
import shutil
from calendar import month_name
import argparse
def get_date(filename):
image_exif = Image.open(filename)._getexif()
if image_exif:
# Make a map with tag names
exif = {ExifTags.TAGS[k]: v for k, v in image_exif.items(
) if k in ExifTags.TAGS and type(v) is not bytes}
#print(json.dumps(exif, indent=4))
# Grab the date
date_obj = datetime.strptime(
exif['DateTimeOriginal'], '%Y:%m:%d %H:%M:%S')
else:
print("could not get a date!")
date_obj = datetime.ctime()
return date_obj
"""
if os.path.exists("%soutput" % folder):
pass
else:
os.mkdir("%soutput"%folder)
"""
def folder_mode(folder,move):
names = os.listdir(folder)
pics = [name for name in names if name.endswith(
'.png') or name.endswith('.jpg') or name.endswith('.JPG')]
folder_out = folder
#folder_out = folder + "output/"
for pic in pics:
pic_date = get_date("%s\%s" % (folder, pic))
print(pic," : ",pic_date)
# make directories
if os.path.exists("%s%s" % (folder_out, pic_date.year)):
pass
#print("already a folder for that year!")
else:
os.mkdir("%s%s" % (folder_out, pic_date.year))
if os.path.exists("%s%s/%s" % (folder_out, pic_date.year, month_name[pic_date.month])):
pass
#print("already a folder for that month!")
else:
os.mkdir("%s%s/%s" %
(folder_out, pic_date.year, month_name[pic_date.month]))
#copy files to folder
if move is True:
shutil.move("%s%s" % (folder, pic), "%s%s/%s" %
(folder_out, pic_date.year, month_name[pic_date.month]))
os.remove("%s%s" % (folder, pic))
else:
shutil.copy("%s%s" % (folder, pic), "%s%s/%s" %
(folder_out, pic_date.year, month_name[pic_date.month]))
def main():
parser = argparse.ArgumentParser(description="A Python program that sorts photo files into year and month directories.")
parser.add_argument('--f',default=os.curdir+"/")
parser.add_argument('--m', default =False)
args, leftovers = parser.parse_known_args()
print(args.m)
folder_mode(args.f,args.m)
if __name__ == "__main__":
main()
|
Rust
|
UTF-8
| 297 | 2.84375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use futures::{self, executor};
async fn move_block() {
let my_string = "Hello".to_string();
let f = async move {
println!("{}", my_string);
};
// 必须要f.await,否则不会执行完线程就结束
f.await
}
fn main() {
executor::block_on(move_block());
}
|
C++
|
WINDOWS-1252
| 1,316 | 3.265625 | 3 |
[] |
no_license
|
#pragma once
std::string clear_the_text(std::string data)
{
std::string data_ptr;
for (int i = 0; i < data.length(); i++)
{
if (data[i] >= '' && data[i] <= '' || data[i] >= '' && data[i] <= '')
{
data_ptr += data[i];
}
}
boost::to_lower(data_ptr, std::locale(".1251"));
boost::replace_all(data_ptr, "", "");
boost::replace_all(data_ptr, "", "");
return data_ptr;
}
std::wstring toUNICODE(void* buffer, int64_t buffer_size)
{
int64_t unicode_buffer_size = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)buffer, buffer_size, 0, 0) * sizeof(wchar_t) + 2;
wchar_t* unicode_data_ptr = (wchar_t*)malloc(unicode_buffer_size);
ZeroMemory(unicode_data_ptr, unicode_buffer_size);
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)buffer, buffer_size, unicode_data_ptr, unicode_buffer_size);
std::wstring unicode_wstring(unicode_data_ptr);
return unicode_wstring;
}
std::string to1251(std::wstring unicode_data)
{
int64_t mb_buffer_size = WideCharToMultiByte(1251, 0, unicode_data.c_str(), unicode_data.length(), 0, 0, 0, 0) + 1;
char* mb_data_ptr = (char*)malloc(mb_buffer_size);
ZeroMemory(mb_data_ptr, mb_buffer_size);
WideCharToMultiByte(1251, 0, unicode_data.c_str(), unicode_data.length(), mb_data_ptr, mb_buffer_size, 0, 0);
std::string mb_string(mb_data_ptr);
return mb_string;
}
|
Markdown
|
UTF-8
| 2,756 | 3.1875 | 3 |
[] |
no_license
|
# Laravel Passwordless Login
### A simple, safe magic login link generator for Laravel
[](https://packagist.org/packages/grosv/laravel-passwordless-login)
[](https://github.styleci.io/repos/243858945)

This package provides a temporary signed route that logs in a user. What it does not provide is a way of actually sending the link to the route to the user. This is because I don't want to make any assumptions about how you communicate with your users.
### Installation
```shell script
composer require grosv/laravel-passwordless-login
```
### Usage
```php
use App\User;
use Grosv\LaravelPasswordlessLogin\LoginUrl;
function sendLoginLink()
{
$user = User::find(1);
$generator = new LoginUrl($user);
$url = $generator->generate();
//OR Use a Facade
$url = PasswordlessLogin::forUser($user)->generate();
// Send $url in an email or text message to your user
}
```
The biggest mistake I could see someone making with this package is creating a login link for one user and sending it to another. Please be careful and test your code. I don't want anyone getting mad at me for somoene else's silliness.
### Configuration
You can publish the config file or just set the values you wan to use in your .env file:
```dotenv
LPL_USER_MODEL=App\User
LPL_REMEMBER_LOGIN=false
LPL_LOGIN_ROUTE=/magic-login
LPL_LOGIN_ROUTE_NAME=magic-login
LPL_LOGIN_ROUTE_EXPIRES=30
LPL_REDIRECT_ON_LOGIN=/
```
LPL_USER_MODEL is the the authenticatable model you are logging in (usually App\User)
LPL_REMEMBER_LOGIN is whether you want to remember the login (like the user checking Remember Me)
LPL_LOGIN_ROUTE is the route that points to the login function this package provides. Make sure you don't collide with one of your other routes.
LPL_LOGIN_ROUTE_NAME is the name of the LPL_LOGIN_ROUTE. Again, make sure it doesn't collide with any of your existing route names.
LPL_LOGIN_ROUTE_EXPIRES is the number of minutes you want the link to be good for. I recommend you set the shortest value that makes sense for your use case.
LPL_REDIRECT_ON_LOGIN is where you want to send the user after they've logged in by clicking their magic link.
### Reporting Issues
For security issues, please email me directly at ed@gros.co. For any other problems, use the issue tracker here.
### Contributing
I welcome the community's help with improving and maintaining all my packages. Just be nice to each other. Remember we're all just trying to do our best.
|
Python
|
UTF-8
| 4,322 | 2.703125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
import os
from . import recordtypes as rt
from .recordreader import RecordReader
from .records import FormatRecord
class Format(object):
__slots__ = ('code', 'is_builtin', '_is_date_format')
def __init__(self, code):
self.code = code
self.is_builtin = False
self._is_date_format = None
@property
def is_date_format(self):
if self._is_date_format is None:
self._is_date_format = False
if self.code is not None:
# TODO Implement an actual parser
in_color = 0
for c in self.code:
if c == '[':
in_color += 1
elif c == ']' and in_color > 0:
in_color -= 1
elif in_color > 0:
continue
elif c in ('y', 'm', 'd', 'h', 's'):
self._is_date_format = True
break
return self._is_date_format
def __repr__(self):
return 'Format(code={}, is_builtin={})' \
.format(self.code, self.is_builtin)
class BuiltinFormat(Format):
__slots__ = ()
def __init__(self, *args, **kwargs):
super(BuiltinFormat, self).__init__(*args, **kwargs)
self.is_builtin = True
class Styles(object):
_general_format = BuiltinFormat(None)
# See: ISO/IEC29500-1:2016 section 18.8.30
_builtin_formats = {
1: BuiltinFormat('0'),
2: BuiltinFormat('0.00'),
3: BuiltinFormat('#,##0'),
4: BuiltinFormat('#,##0.00'),
9: BuiltinFormat('0%'),
10: BuiltinFormat('0.00%'),
11: BuiltinFormat('0.00E+00'),
12: BuiltinFormat('# ?/?'),
13: BuiltinFormat('# ??/??'),
14: BuiltinFormat('mm-dd-yy'),
15: BuiltinFormat('d-mmm-yy'),
16: BuiltinFormat('d-mmm'),
17: BuiltinFormat('mmm-yy'),
18: BuiltinFormat('h:mm AM/PM'),
19: BuiltinFormat('h:mm:ss AM/PM'),
20: BuiltinFormat('h:mm'),
21: BuiltinFormat('h:mm:ss'),
22: BuiltinFormat('m/d/yy h:mm'),
37: BuiltinFormat('#,##0;(#,##0)'),
38: BuiltinFormat('#,##0;[Red](#,##0)'),
39: BuiltinFormat('#,##0.00;(#,##0.00)'),
40: BuiltinFormat('#,##0.00;[Red](#,##0.00)'),
45: BuiltinFormat('mm:ss'),
46: BuiltinFormat('[h]:mm:ss'),
47: BuiltinFormat('mmss.0'),
48: BuiltinFormat('##0.0E+0'),
49: BuiltinFormat('@')
}
def __init__(self, fp):
self._fp = fp
self._parse()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def _parse(self):
self._formats = dict()
self._cell_style_xfs = list()
self._cell_xfs = list()
self._fp.seek(0, os.SEEK_SET)
reader = RecordReader(self._fp)
for rectype, rec in reader:
if rectype == rt.FMT:
self._formats[rec.fmtId] = Format(rec.fmtCode)
elif rectype == rt.BEGIN_CELL_STYLE_XFS:
self._cell_style_xfs = [None] * rec.count
i = 0
for rectype, rec in reader:
if rectype == rt.XF:
self._cell_style_xfs[i] = rec
i += 1
elif rectype == rt.END_CELL_STYLE_XFS:
break
elif rectype == rt.BEGIN_CELL_XFS:
self._cell_xfs = [None] * rec.count
i = 0
for rectype, rec in reader:
if rectype == rt.XF:
self._cell_xfs[i] = rec
i += 1
elif rectype == rt.END_CELL_XFS:
break
elif rectype == rt.END_STYLE_SHEET:
break
def get_style(self, idx):
# TODO
del idx
def _get_format(self, idx):
if idx < len(self._cell_xfs):
fmt_id = self._cell_xfs[idx].numFmtId
if fmt_id in self._formats:
return self._formats[fmt_id]
elif fmt_id in self._builtin_formats:
return self._builtin_formats[fmt_id]
return self._general_format
def close(self):
self._fp.close()
|
PHP
|
UTF-8
| 454 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: cesar
* Date: 11/04/17
* Time: 09:35
*/
namespace Api\Repositories;
use Api\Entities\Login;
use Doctrine\ORM\EntityRepository;
/**
* Class LoginRepository
* @package Api\Repositories
*/
class LoginRepository extends EntityRepository
{
/**
* @param Login $login
*/
public function save(Login $login)
{
$this->_em->persist($login);
$this->_em->flush($login);
}
}
|
Java
|
UTF-8
| 569 | 2.171875 | 2 |
[] |
no_license
|
package com.griddynamics.appiumexample.screens;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AndroidFindBy;
public class ItemDetailsScreen extends AddItemScreen {
@AndroidFindBy(id = "delete_item")
private AndroidElement deleteButton;
@Override
public boolean isShown() {
return super.isShown() && deleteButton.isDisplayed();
}
public MainScreen deleteItem(){
deleteButton.click();
return new MainScreen();
}
}
|
Java
|
UTF-8
| 2,848 | 2.140625 | 2 |
[] |
no_license
|
package com.techelevator.fbn.controller;
import java.time.LocalDate;
import javax.servlet.http.HttpSession;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.techelevator.fbn.model.CheckingAccountApplication;
@Controller
@RequestMapping("/checkingApplication")
public class CheckingApplicationController {
@RequestMapping(path = { "/", "/personalInformationInput" }, method = RequestMethod.GET)
public String displayPersonalInformationInput() {
return "checkingApplication/personalInformationInput";
}
@RequestMapping(path = "/thankYou", method = RequestMethod.GET)
public String displayThankYou() {
return "checkingApplication/thankYou";
}
@RequestMapping("/test")
public String test(HttpSession session) {
session.invalidate();
return "checkingApplication/test";
}
@RequestMapping (path = "/personalInformationInput", method = RequestMethod.POST)
public String openCheckingAccount (@RequestParam String firstName, @RequestParam String lastName, @DateTimeFormat(pattern = "MM/dd/yyyy") @RequestParam LocalDate dateOfBirth, @RequestParam String stateOfBirth, @RequestParam String emailAddress, @RequestParam String phoneNumber, HttpSession session) {
CheckingAccountApplication account = new CheckingAccountApplication();
account.setFirstName(firstName);
account.setLastName(lastName);
account.setDateOfBirth(dateOfBirth);
account.setStateOfBirth(stateOfBirth);
account.setEmailAddress(emailAddress);
account.setPhoneNumber(phoneNumber);
session.setAttribute("Application", account);
return "redirect:/checkingApplication/addressInput";
}
@RequestMapping (path= "/addressInput", method = RequestMethod.GET)
public String accountNextStep() {
return "checkingApplication/addressInput";
}
@RequestMapping (path = "/addressInputUrl", method = RequestMethod.POST)
public String processAddressInput(@RequestParam String streetAddress, @RequestParam String apartmentNumber, @RequestParam String city, @RequestParam String state, @RequestParam String zipCode, HttpSession session) {
CheckingAccountApplication account = (CheckingAccountApplication) session.getAttribute("Application");
account.setAddressStreet(streetAddress);
account.setAddressApartment(apartmentNumber);
account.setAddressCity(city);
account.setAddressState(state);
account.setAddressZip(zipCode);
return "redirect:/checkingApplication/summary";
}
@RequestMapping (path = "/summary")
public String displaySummary() {
return "checkingApplication/summary";
}
}
|
C
|
UTF-8
| 2,150 | 3.46875 | 3 |
[] |
no_license
|
/*
* Função para remover uma locadora baseada no id.
* A remoção é feita no arquivo arqFisicoLocadoras.
*/
#include "libLocadoras.h"
void removerLocadora(char arqFisicoLocadoras[], int idLocadora){
FILE *arqLocadora = fopen(arqFisicoLocadoras, "r+b");
Locadora tmp;
int verificadorLocadora = 0;
//Verifica se o arquivo foi aberto corretamente
if (arqLocadora == NULL){
printf("\nERRO: Erro ao abrir arquivo de locadoras na funcao removerLocadora.\n");
return;
}
//Abre/cria o arquivo tmp.bin para modo de escrita (w) e o associa a variável arqTmp, que é utilizada como backup, ou seja, para copiar as informações que não devem ser removidas (ou seja, aquela cujo id é diferente do id a ser removido) do arqFisicoLocadoras.
FILE *arqTmp = fopen("tmp.bin", "wb");
//Verifica se o arquivo foi aberto corretamente
if (arqTmp == NULL){
printf("\nErro ao abrir arquivo temporário auxiliar em removerLocadora.\n");
return;
}
while (fread(&tmp, sizeof(Locadora), 1, arqLocadora) !=0 ){
//Caso o id lido seja o mesmo que deve ser removido, ele não é copiado para o arquivo temporário
if (idLocadora == tmp.id)
{
//Para verificar se o id existe, utilizamos o verificadorLocadora, caso não exista retorna erro depois
verificadorLocadora = 1;
}
//Caso o id não seja o que já foi cadastrado, ele é copiado para o arquivo temporário
else
{
fwrite(&tmp, sizeof(Locadora), 1, arqTmp);
}
}
//Fecha os arquivos fisicos
fclose(arqLocadora);
fclose(arqTmp);
//Caso não tenha encontrado essa locadora, imprime erro e retorna para a logAsRoot
if (verificadorLocadora == 0)
{
printf("ERRO: Locadora nao cadastrada.\n");
return;
}
//remove do diretório o arquivo arqFisicoLocadoras, pois este arquivo contém a locadora removida
remove(arqFisicoLocadoras);
//renomeia o arquivo auxiliar tmp.bin (que não contém a locadora removida) para arqFisicoLocadoras. Assim, tem-se o arquivo arqFisicoLocadoras com a locadora removida
rename("tmp.bin", arqFisicoLocadoras);
printf("\n***Locadora Removida***");
return;
}
|
C#
|
UTF-8
| 3,196 | 2.953125 | 3 |
[] |
no_license
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Status.cs" company="Gorba AG">
// Copyright © 2011-2014 Gorba AG. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Gorba.Common.Protocols.Ctu.Notifications
{
using System.IO;
using System.Text;
using Gorba.Common.Protocols.Ctu.Datagram;
/// <summary>
/// Object tasked to represent the notification
/// CTU datagram regarding the "Status",
/// uniquely identified by the tag number 1.
/// </summary>
public class Status : Triplet
{
/// <summary>
/// Initializes a new instance of the <see cref="Status"/> class.
/// </summary>
/// <param name="code">The current status code</param>
/// <param name="statusMsg">The string to be inserted into the CTU datagram's triplet payload.</param>
public Status(StatusCode code, string statusMsg)
: base(TagName.Status)
{
this.Code = code;
this.StatusMsg = statusMsg;
}
/// <summary>
/// Initializes a new instance of the <see cref="Status"/> class.
/// </summary>
/// <param name="length">
/// The length.
/// </param>
/// <param name="reader">
/// The reader.
/// </param>
internal Status(int length, BinaryReader reader)
: base(TagName.Status)
{
this.Code = (StatusCode)reader.ReadInt32();
length -= 4;
this.StatusMsg = Triplet.ReadString(reader, length);
}
/// <summary>
/// Gets or sets the value's code.
/// </summary>
public StatusCode Code { get; set; }
/// <summary>
/// Gets or sets the value's status message.
/// </summary>
public string StatusMsg { get; set; }
/// <summary>
/// Gets the triplet's payload length.
/// </summary>
public override int Length
{
get
{
return sizeof(int) + (this.StatusMsg.Length * 2);
}
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return string.Format("{0}: {1}", this.Code, this.StatusMsg);
}
/// <summary>
/// Writes the payload to the given writer.
/// </summary>
/// <param name="writer">
/// The writer.
/// </param>
protected override void WritePayload(BinaryWriter writer)
{
writer.Write((int)this.Code);
if (!string.IsNullOrEmpty(this.StatusMsg))
{
writer.Write(Encoding.Unicode.GetBytes(this.StatusMsg));
}
}
}
}
|
Java
|
UTF-8
| 2,625 | 2.5 | 2 |
[] |
no_license
|
package com.spring_boot_backend.product.adapter.in.stub;
import com.spring_boot_backend.product.application.ports.in.ProductRepository;
import com.spring_boot_backend.product.domain.Product;
import java.util.*;
import static java.util.stream.Collectors.toList;
public class ProductRepositoryMemory implements ProductRepository {
Map<String, Product> productDB = new HashMap<>();
@Override
public List<Product> findAll() {
return productDB.values().stream().collect(toList());
}
@Override
public Optional<Product> findById(String id) {
return Optional.ofNullable(productDB.get(id));
}
@Override
public List<Product> findAllByFiltering(ProductFilter productFilter) {
return productDB.values().stream().filter(product ->
product.getProductName().toLowerCase().contains(productFilter.getName().toLowerCase())
&& product.getTargetMarketStack().containsAll(productFilter.getTargetMarketStack())
&& product.getTechnologiesStack().containsAll(productFilter.getTechnologiesStack())
).collect(toList());
}
@Override
public List<Product> findAllByProductNameLikeAndTargetMarketStackIn(ProductFilter productFilter) {
return productDB.values().stream().filter(product ->
product.getProductName().toLowerCase().contains(productFilter.getName().toLowerCase())
&& product.getTargetMarketStack().containsAll(productFilter.getTargetMarketStack())
).collect(toList());
}
@Override
public List<Product> findAllByProductNameLikeAndTechnologiesStackIn(ProductFilter productFilter) {
return productDB.values().stream().filter(product ->
product.getProductName().toLowerCase().contains(productFilter.getName().toLowerCase())
&& product.getTechnologiesStack().containsAll(productFilter.getTechnologiesStack())
).collect(toList());
}
@Override
public List<Product> findAllByProductNameLike(ProductFilter productFilter) {
return productDB.values().stream().filter(product ->
product.getProductName().toLowerCase().contains(productFilter.getName().toLowerCase())
).collect(toList());
}
@Override
public Product save(Product product) {
if(product.getId() == null) {
product.setId(UUID.randomUUID().toString());
}
this.productDB.put(product.getId(), product);
return product;
}
@Override
public void delete(String id) {
this.productDB.remove(id);
}
}
|
Python
|
UTF-8
| 1,143 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
"""
Train Model
"""
import datetime
from fl33t.exceptions import InvalidTrainIdError
from fl33t.models.base import BaseModel
from fl33t.models.mixins import (
ManyBuildsMixin,
ManyFleetsMixin
)
# pylint: disable=no-member
class Train(BaseModel, ManyFleetsMixin, ManyBuildsMixin):
"""
The fl33t Train model
"""
_invalid_id = InvalidTrainIdError
_timestamps = ['upload_tstamp']
_defaults = {
'train_id': '',
'name': '',
'upload_tstamp': datetime.datetime.utcnow()
}
def __str__(self):
return 'Train {}: {}'.format(self.train_id, self.name)
def __repr__(self):
return '<Train id={} name={} latest_build={}>'.format(
self.train_id,
self.name,
self.upload_tstamp
)
@property
def id(self):
"""
Get this train's unique ID
:returns: str
"""
return self.train_id
@property
def self_url(self):
"""
The full URL for this particular train in fl33t
:returns: str
"""
return '/'.join((self.base_url, self.train_id))
|
C++
|
GB18030
| 1,169 | 3.5625 | 4 |
[] |
no_license
|
/*Accepted
1
ԭϤmap ʹãͼ쳣
˼·
mapkeyӦֵۼӼ
õ-------------------------36~39(ҪϤ)
ע⣺
1mapúʵ֣ѾkeyȻ˳
2mapӼֵԿֱ multinomial[y] = x;
3ۼӿԲøֵ0----------------32
*/
#include<iostream>
#include<map>
using namespace std;
static map<int,int> multinomial;
void group() {
int line = 2;
while (true)
{
if (line <= 0)break;
int x = 0, y = 0;
cin >> x; cin >> y;
if (y < 0) {
--line;
continue;
}
else
{
multinomial[y] += x;
}
}
for (map<int, int>::reverse_iterator iter = multinomial.rbegin(); iter != multinomial.rend(); ++iter) {//rbeginһԪ
if (iter->second != 0) {
cout << "[ " << iter->second << " " << iter->first << " ] ";
}
}
cout << endl;
//map
multinomial.clear();
}
//int main() {
//
// int n = 0;
// cin >> n;
// for (int i = 0; i < n;++i) {
// group();
// }
// system("pause");
// return 0;
//}
|
Markdown
|
UTF-8
| 52,819 | 3.15625 | 3 |
[] |
no_license
|
---
author:
name: "Hector Mu\xF1oz"
picture: 110313
body: "I, as most mexicans have family working in the United States, so I decided
to make this post as a mean to support them asking all north american typophiles
to reject and help to stop the HR 4437 bill.\r\n\r\nThere are about 41 million hispanic
inmigrants working in the united states, doing an honest life trough hard work on
duties most north americans are not willing to do. It's true many of them (about
11 million) reached the United States ilegally, but it is also true that ilegal
workers are hired under very unfair conditions like up to 14 or 16 hour working
days, not medical or social assitence, unjustified dismissal and very low payments.\r\n\r\nTrying
to turn this people into criminals is not fair, and is not going to fix the problem,
it\xB4s just going to make it worse. A wall in the desert is not going to stop illegal
inmigration and treating people like animals (denying medial assitance) is the real
crime. There are also some illegal north americans in mexico (many of them in San
Miguel de Allende, about 40 km from here), and I can assure you they are well treated.\r\n\r\nThe
real solution is to have a fair treat for temporal inmigrant workers, because we
all know you need the workers and we need the work, this radical position is an
hipocresy that only benefits the ones who explode and violate the human rights of
workers."
comments:
- author:
name: pattyfab
picture: 109929
body: I'll second that and add that unless you are 100% Native American you are
no doubt the descendent of immigrants who may or may not have come here legally.
It makes me crazy the entitlement that so many Americans seem to feel over what
is truly an accident of birth. I am so profoundly unimpressed by my countrymen
at this point that I welcome some new blood!
created: '2006-05-01 19:04:40'
- author:
name: Chris Keegan
picture: 110432
body: If you want to live in America, you need to come here legally. PERIOD.
created: '2006-05-01 19:15:52'
- author:
name: dezcom
picture: 109959
body: "H\xE9ctor,\r\n\r\nMy family came here from Greece in early 20th century.
\ We are a nation of immigrants who all came here for a chance to live a better
life. In the process, we made this country what it is today (for better or worse).
\ Each new generation of immigrants has something new to offer and should be welcomed
as much as all that came before. I welcome your family and any other to become
part of us.\r\n\r\nChrisL"
created: '2006-05-01 19:33:17'
- author:
name: Nick Shinn
picture: 110193
body: "<em>you need to come here legally.</em>\r\n\r\nIf that was the case Chris,
wouldn't the law have been been more firmly enforced?\r\nThe theory is that a
large underground workforce enables US businesses to compete with cheap labour
in China etc., so the situation is allowed to continue."
created: '2006-05-01 19:35:14'
- author:
name: canderson
picture: 111096
body: "I agree, with Nick. We've sent some very mixed messages to people entering
this country illegally. That said, one of the things that makes the US great is
that, for the most part, we obey the law. Personally, I welcome people who want
to come here to adopt our laws and customs, and pay taxes. I also feel that its
important for people who live and work here to vote, so I'm not sure I like the
'guest worker' idea. \r\n\r\nWe also might want to think about why so many people
want to leave Mexico. "
created: '2006-05-01 19:50:09'
- author:
name: fontplayer
picture: 111445
body: "I wonder if you can answer honestly how Mexico treats Guatemalans that are
illegally crossing that border?\r\n\r\nFact is, the hypocrisy is astounding. \r\n\r\nI
almost wish this topic could be deleted, since if I get going on this, some politically
correct people will have their day ruined."
created: '2006-05-01 19:52:12'
- author:
name: dezcom
picture: 109959
body: "We have to ask ourselves if we would have welcomed our own grandparents or
great grandparents here to this country? Someone before us did so we should welcome
the newest generation to start a life for their grandchildren-to-come.\r\n\r\nChrisL\r\n\r\n(Sorry
Nick, I see you now meant the other Chris)"
created: '2006-05-01 20:01:03'
- author:
name: pattyfab
picture: 109929
body: "It's similar to the debate about adoption - prospective adoptive parents
are put thru the ringer for children they really want (and can provide for) and
yet any idiot can bear a child or two or three and end up being a drain on our
resources.\r\n\r\nThe harsh anti-immigration bills will threaten parents who have
children who were born here and are therefore American citizens, and also a lot
of law abiding tax payers.\r\n\r\nI ain't saying there shouldn't be limits and
regulations but that they should be humane and reasonable.\r\n\r\nI'd be quite
happy in fact to kick out some of our homegrown folks at this point, starting
with the current admin."
created: '2006-05-01 20:03:20'
- author:
name: Chris Keegan
picture: 110432
body: Nick, one of the reasons the U.S. government has not cracked down on illegal
immigration is that they will lose voters by taking up that issue. Most of the
jobs supposedly performed by illegals are service industries, not manufacturing,
so they aren't in direct competition with China. This isn't about immigration,
this is about illegal immigration. We are a nation of immigrants, and anyone is
welcome in America as long as they are here legally, obey the laws, pay taxes,
etc. Businesses that hire illegals should be fined. Workers deserve a fair wage,
and while illegals may be making more money here, they still aren't being paid
a decent wage by American standards.
created: '2006-05-01 20:05:07'
- author:
name: dezcom
picture: 109959
body: "\"...how Mexico treats Guatemalans that are illegally crossing that border\"\r\n\r\nGovernments
are different than people. Because one government has a policy which we may not
approve of, does not allow us to apply that same logic to our own. I don't speak
for my government and it rarely speaks for me. The U.S. is far from the only country
with failings and it isn't even the worse of the lot. That does not give us license
to say, \"Oh, well, we are still doing better than Rwanda, so what we do is OK
until we do worse than the others.\" \r\n\r\nChrisL"
created: '2006-05-01 20:12:12'
- author:
name: pattyfab
picture: 109929
body: "True enough but aren't these new laws designed to keep out a certain type
of immigrant? Read: not white, or not white enough. \r\n\r\nIf laws were designed
in order to make it easier to obtain legal immigration and then pay taxes, vote,
etc instead of creating criminals out of hard working citizens we'd all be better
off."
created: '2006-05-01 20:14:20'
- author:
name: fontplayer
picture: 111445
body: "<cite>I\u2019d be quite happy in fact to kick out some of our homegrown folks
at this point, starting with the current admin.</cite>\r\n\r\nWhich is where much
of the support is rooted. The Democratic party sees it as a way to garner votes
and are milking it for all it's worth.\r\n\r\nSo many who don't live near the
border don't know that many Mexican women sneak across the border to have babies
here, so they can have the benefits. When people are coming, not to be assimilated,
but to simply milk the system, this is a big difference from the immigration issues
of previous generations."
created: '2006-05-01 20:16:07'
- author:
name: pattyfab
picture: 109929
body: "> Governments are different than people. Because one government has a policy
which we may not approve of, does not allow us to apply that same logic to our
own.\r\n\r\nDon't get me started. How many corrupt or dictatorial governments
has the US propped up or helped install because it served our \"national interest\"?
And then we try to export our \"values\" abroad through force instead of example
- and wonder why we're pissing everybody off.\r\n\r\nHow can ANYBODY justify Guantanamo
by any standard?"
created: '2006-05-01 20:18:18'
- author:
name: pattyfab
picture: 109929
body: "> The Democratic party sees it as a way to garner votes and are milking it
for all it\u2019s worth.\r\n\r\nThe Democrats SHOULD milk this for all it's worth.
I only wish they could figure out how to get more mileage from the unbelievable
incompetence, corruption and misguided policies both foreign and domestic of this
admin.\r\n\r\nAnd am I the only one here who grew up thinking the national anthem
started \"Jos\xE9 can you see?\""
created: '2006-05-01 20:21:12'
- author:
name: dan_reynolds
picture: 110440
body: "All nations have the right to set and protect their own borders, and to regulate
who comes in.\r\n\r\nHowever, the United States of America is also the same nation
that once agreed that \"all men are created equal, that they are endowed by their
Creator with certain unalienable Rights, that among these are Life, Liberty and
the pursuit of Happiness.\"\r\n\r\nWhat is morally untenable, to me is not that
people come to the US to seek a better life (illegally, if necessary), but rather
that so many Americans seem to be willing to look the other way while individuals
living in their midst are mistreated and paid substandard wages.\r\n\r\nWe talk
about all the individuals being here illegally. How come more people don't talk
about the individuals, companies, and corporations who pay these immigrants illegally-low
wages? That is criminal behavior! <strong>That</strong> should be stopped. In
fact, if these crimes would be stopped, the illegal immigration issue might flare-down
a bit as well. But no one seems interested in that dialogue. We want to have it
both ways as Americans\u2026 cheap goods and services, and only legal immigration.
\r\n\r\nPeople come to the US because they know that they will have a better life.
Illegal immigrants know that millions of Americans are willing to pay them under
the table.\r\n\r\nAs a caveat, it should also be pointed out that the US allows
more legal immigrants across its borders than any other nation in the world. But
then again, even these people are not treated well. I live as a foreign national
in another country, and my situation clearly cannot be compared with that of those
who have come from Central America to the US, but I have had a few hurdles of
my own to jump through here in Germany. Nevertheless, I feel ashamed when I hear
what problems my government back home puts *legal* immigrants through. In comparison
with that, my problems are nothing. Since September 11, it seems as if all immigrants
to the US are viewed as potential terrorists, people who would rather tear the
country down rather than build it up, in order that they get to have a better
life, too. Maybe it would be for the best if we as Americans would totally rethink
how we thought about immigration altogether so that we can finally be honest with
ourselves again.\r\n\r\nJust my opinion."
created: '2006-05-01 20:28:24'
- author:
name: fontplayer
picture: 111445
body: "<cite> only wish they could figure out how to get more mileage from...,</cite>\r\n\r\nBecause
they have nothing better to offer they flounder around looking ridiculous. And
if most Americans who are Democrat because their parents were, knew how far left
the party really is these days...well, actually they are starting to find out,
and it doesn't look good. My wife's best friend is bailing because of your stance
on the border issue. \r\n\r\nSo I have to remember to be delighted you think the
way you do, because it is working out all right, I think.\r\n\r\nBtw, you avoided
the more relevant point of my previous post, I see.\r\n\r\nI can't believe politics
aren't off-limits here, since it tends to be too emotional a subject and can lead
to hard feelings."
created: '2006-05-01 20:28:56'
- author:
name: dan_reynolds
picture: 110440
body: "apropos Guantanamo\u2026 rereading the Declaration of Independence for my
last post, I found this: \r\n\"For depriving us in many cases, of the benefit
of Trial by Jury: \r\nFor transporting us beyond Seas to be tried for pretended
offences:\"\r\n\r\nHmm. For the Founders, these actions of King George warranted
revolution! \r\n\r\nAnd I thought *I* was conservative\u2026 :("
created: '2006-05-01 20:37:23'
- author:
name: terryw
picture: 109820
body: "<em>....how far left the party really is these days\u2026</em>\r\n\r\nThis
diagram should demonstrate the average.\r\n\r\nL..................................................Center....................................................R\r\n................................................Dem...........................................Rep............\r\n\r\n\r\n\r\n"
created: '2006-05-01 20:38:13'
- author:
name: Chris Keegan
picture: 110432
body: 'Dan, very thoughtful post. And you are absolutely correct that the companies
and corporations that use illegal labor should be held accountable. People are
talking about it, at least where I am. '
created: '2006-05-01 20:40:21'
- author:
name: fontplayer
picture: 111445
body: "<cite>This diagram should demonstrate the average.</cite>\r\n\r\nWhich only
proves the polarization occuring these days, since I would make the same chart
the other way around.\r\n"
created: '2006-05-01 20:41:16'
- author:
name: dan_reynolds
picture: 110440
body: It all depends on where you define the center.
created: '2006-05-01 20:41:24'
- author:
name: dan_reynolds
picture: 110440
body: "<em>People are talking about it, at least where I am.</em>\r\n\r\nI don't
believe that Congress will take action on that issue. I wish that they would,
but I just don't believe it anymore."
created: '2006-05-01 20:42:45'
- author:
name: fontplayer
picture: 111445
body: "<cite>It all depends on where you define the center.</cite>\r\n\r\nReality,
I think we can agree on that, but it is also where the problem lurks. \r\n\r\nIdealism
can work great in design, so I shouldn't be surprised that typophile would be
dominated by liberals. Even I wish I could live in La-la-landia where there were
no borders, everyone was as concerned for my welfare as I am (and visa-versa)
and there were no people who want to blow me up because I am an infidel, and all
things really <cite>are</cite> equal for everyone. For starters, I woulda been
be more handsome.\r\n: )"
created: '2006-05-01 20:59:45'
- author:
name: Si_Daniels
picture: 110446
body: "> Even I wish I could live in La-la-landia \r\n\r\nI'll chip in for your
ticket - providing of course they don't have internet access over there ;-)\r\n\r\nCheers,
Si \r\n\r\nBritish Citizen, US Permanent Resident, ATypI country delegate for
the USA \r\n\r\n"
created: '2006-05-01 21:16:43'
- author:
name: "Hector Mu\xF1oz"
picture: 110313
body: "Patty and Crhis, thanks a lot.\r\n\r\nI really think that a temporal worker
program would be a fine solution, it makes legal and easier to control and regulate
something that is already happening in a very chaotic and unfair way and that
will not be stopped with a wall and a threat.\r\n\r\nIt would also make clear
for the people that goes to work there that they must return to their homes after
certain time.\r\n\r\nH\xE9ctor"
created: '2006-05-01 21:19:01'
- author:
name: dan_reynolds
picture: 110440
body: "<em>It would also make clear for the people that goes to work there that
they must return to their homes after certain time.</em>\r\n\r\nI don't like the
idea of a Guest Worker program. I'm in favor of real immigration. Allow more people
in, and let them become citizens if they want to. I'm afraid that Guest Workers
will be seen as second-class residents. That's not fair.\r\n\r\nDecades ago, European
nations created Guest Worker programs. The workers came, but they were not guests.
They stayed, had children, and now their children have had children. But too many
of these residents are still treated like they don't belong, even though many
of them are just as German, Dutch, or French as the German, Dutch, or French themselves\u2026
not culturally, but before the eyes of the law. "
created: '2006-05-01 21:25:57'
- author:
name: fontplayer
picture: 111445
body: "<cite>I\u2019ll chip in for your ticket - providing of course they don\u2019t
have internet access over there ;-)</cite>\r\n\r\nThat's the spirit. I guess I
didn't think that one through. If it existed, it would be where San Fransico's
bounderies are, and I can't afford to live there. But if it were on the ballot
to change their name to La-la-landia, I would be their biggest supporter.\r\n:
)\r\n\r\n"
created: '2006-05-01 21:26:42'
- author:
name: Si_Daniels
picture: 110446
body: "> If it existed, it would be where San Fransico\u2019s bounderies are\r\n\r\nAh,
that's a bit too close to Seattle. Sorry, my offer is off the table. ;-)\r\n\r\nCheers,
Si"
created: '2006-05-01 21:29:39'
- author:
name: canderson
picture: 111096
body: 'I don''t want a guest worker program either. If any group lacks the right
to vote, they will surely be treated poorly. Also, immigrants need access to
education and other services if they want to get ahead. When people have a stake
in making our country work, everyone benefits. '
created: '2006-05-01 21:33:30'
- author:
name: fontplayer
picture: 111445
body: "<cite>When people have a stake in making our country work, everyone benefits.</cite>\r\n\r\nOk,
to clarify: One problem is many don't have an interest in making it work. They
don't know or care what the people here think, or they wouldn't violate our laws.
In general, they are the uneducated class, and are here to take advantage of our
system, which they don't have in Mexico. Read the end of my post below for more
details on this."
created: '2006-05-01 21:44:18'
- author:
name: dan_reynolds
picture: 110440
body: "<em>The problem is they don\u2019t have an interest in making it work. </em>\r\n\r\nThat
is a very simplistic point of view. Can one really make generalizations about
a group of people 11 million large? Think about how many countries don't even
have 11 million people living inside them\u2026 11 million is too big a number
for blanket statements like that."
created: '2006-05-01 21:47:59'
- author:
name: terryw
picture: 109820
body: Dan, don't you get Fox News in Germany?
created: '2006-05-01 21:56:02'
- author:
name: dan_reynolds
picture: 110440
body: Nope, at least I don't. Is that a bad thing?
created: '2006-05-01 21:59:29'
- author:
name: canderson
picture: 111096
body: "<cite>The problem is they don\u2019t have an interest in making it work.</cite>
\r\n\r\nI don't agree either. Some immigrants don't ever completely assimilate,
but their kids do. Its important to provide the same basic opportunities for everyone. "
created: '2006-05-01 22:05:08'
- author:
name: "Hector Mu\xF1oz"
picture: 110313
body: "Well, that's a better response than I would have waited, a guest worker program
isn't really the best thing to do as pointed out, but maybe it's a short term
acceptable solution, full citizenship of course would be the best thing to get.\r\n\r\nH\xE9ctor"
created: '2006-05-01 22:41:07'
- author:
name: fontplayer
picture: 111445
body: "<cite>it\u2019s a short term acceptable solution, full citizenship of course
would be the best thing to get.</cite>\r\n\r\nI guess one big problem I have with
the whole thing is do we ever draw a line? Is the American taxpayer expected to
be Mexico's welfare system, with no limit? As a rule we don't get the cream of
the crop sneaking across the border. There are parts of OC where you can see all
these little Mexican baby machines cranking them out as fast as they possibly
can. (partly because of the Catholic beliefs on birth-control, I imagine), while
all their brood is orbiting them as they cross at the intersections \r\n\r\nMeanwhile
I can't seem to get ahead here, even though I am making what some people think
is decent money. We can't afford to buy a house, let alone provide for retirement
at my current income levels. \r\n\r\nIf there is no limit to letting the poor
of Mexico flood into California, then no amount of taxation will ever be enough.\r\n\r\nIf
the bleeding-hearts are so concerned about the poor Mexicans crossing our border
looking for opportunity, they should be ultra-concerned about the Guatemalans,
who are even worse off, who are raped, have their money stolen, usually by soldiers
or police. Since they have no right to be there, no one cares how they are treated.\r\n\r\n<a
href=\"http://hosted.ap.org/dynamic/stories/M/MEXICO_MISTREATING_MIGRANTS?SITE=AP&SECTION=HOME&TEMPLATE=DEFAULT&CTIME=2006-04-18-18-08-31\"
\ target=\"_blank\">Check this AP news story</a>\r\n\r\nVincente Fox's hypocrisy
reaches new levels of irony.\r\n\r\nPlease keep in mind I am married to a Mexican
citizen who feels much the same way I do, only she is more cynical about the Mexican
government. And I love much of the Mexican culture and music. I probably have
the biggest collection of trios, rondallas, and female ranchera singers of any
white person in California. Lucha Villa, Chelo (Mejor Me Voy, Si Ya Te Vas: Si
algun dia las penas de la vida te hacen da\xF1o, no pretendas buscarme, etc.),
Lola Beltran, Flor Silvestre, Beatriz Adriana (echele ganas) etc. are the part
of my music collection I would grab if the house were burning down. Too much effort
went into getting them all, and many are out of print. \r\n\r\nSo I can say I
love Mexicans, I don't don't think I should be taken advantage of by the ones
who don't respect our laws.\r\n\r\n<cite> There are also some illegal north americans
in mexico (many of them in San Miguel de Allende, about 40 km from here), and
I can assure you they are well treated.</cite>\r\n\r\nFrom my experience, it would
only be because they have money. I have family in Mexico, I have traveled in Mexico,
and I know how it works. Please don't paint a picture as if ghetto occupants started
sneaking into Mexico and down to San Miguel de Allende, they would be welcome
with open arms. I have been in San Miguel. I bought some nice Huichol art there,
fortunately before the price started skyrocketing. \r\n\r\nThe city is very pretty.
And I imagine they want to keep it that way.\r\n\r\nAnd another thing, why in
the flying blankety-blank shouldn't we be able to decide our own laws, or enforce
the ones we have without extortion from people with no right to be here. The whole
thing is ludicrous.\r\n\r\nNow to balance my position, I am in favor (as I think
is a majority of Americans) of a program that legally allows workers to be here.
There is no doubt they make a valuable contribution. \r\n\r\nBut not without restrictions
or guidelines.\r\n\r\nAnd now a story we personally know about. A Mexican women
(cousin of a friend of my wife) crossed the border illegally, then started having
babies here (now she is at four), so now all the kids are US citizens, and she
is getting benefits; Money for a place to stay (using forged Social Security docs)
and since the fourth son is deaf, she is given money for special education, and
hearing aids. She doesn't work, because if she did she wouldn't be elegible for
all the benefits. \r\n\r\nAnd I could go on for quite a while about things like
this, because of the work my wife does. She is trusted by many of them to hear
the details of all the stories the working ones have concerning their relatives.\r\n\r\nAll
courtesy of the unknowing Californian taxpayers.\r\n\r\nAnd Ricardo, you make
a valid point about my wording which I have amended above.\r\n\r\n<cite>Ah, that\u2019s
a bit too close to Seattle. Sorry, my offer is off the table. ;-)</cite>\r\n\r\nHey,
I have asked to be transferred to develop that area for my company. I'll look
you up if it happens. From the conversations I overheard at Starbucks in Enumclaw,
you guys could use a few more people there whose political viewpoints aren't in
the clouds.\r\n; )"
created: '2006-05-02 00:13:49'
- author:
name: Ricardo Cordoba
picture: 110715
body: "<em>The problem is they don\u2019t have an interest in making it work. They
don\u2019t know or care what the people here think, or they wouldn\u2019t violate
our laws. In general,they are the uneducated class, and are here to take advantage
of our system, which they don\u2019t have in Mexico.</em>\r\n\r\nIt's always nice
to read open-minded, non-judgmental assessments such as this, in which things
are neither black nor white. ;-)"
created: '2006-05-02 03:32:20'
- author:
name: pattyfab
picture: 109929
body: "Dennis, I think it's kinda interesting you'd choose to live in SF where you'd
be surrounded by -horrors! - homosexuals and other people whose viewpoints are
as you put it \"in the clouds\". I'm not surprised to see you're in Orange County,
I have relatives there and know what the politics are like. Luckily California
is a big state.\r\n\r\n>In general, they are the uneducated class, and are here
to take advantage of our system\r\n\r\nOur country is in the sorry state it's
in because our OWN citizens are uneducated, xenophobic and only interested in
protecting their own interests, not to mention taking advantage of the system.
\r\n\r\nFor the record I'm a Democrat not because my parents are (altho I'm proud
that they are and raised me in the bluest district of the bluest city in the country)
but because they are right now the party of morality and values. Invading another
country for oil (and lying about why) and giving tax breaks to the rich, not to
mention devastating the environment and trying to govern this country with a Christian
form of Shariah (can't they see the hypocrisy!) does not strike me as moral, or
frankly, Christian at all. And as a Jew I find the sancimonious false piety of
the religious right both alienating and terrifying. \r\n\r\nThank god for Jon
Stewart."
created: '2006-05-02 04:34:56'
- author:
name: fontplayer
picture: 111445
body: "<cite>And as a Jew I find the sancimonious false piety of the religious right
both alienating and terrifying.</cite>\r\n\r\nSame here. But among the Christians
I know are some of the staunchest supporters of Israel that I know of. And now
it is becoming clear we share a common enemy that wants to wipe us from existance.
\r\n\r\nGranted the right you speak of probably wants to wipe them from the earth
also. This is why it is increasingly clear that the world needs a benevolent dictator
who is omnipotent, and can put the sanctimonius pious bastards of both sides in
their place, so the creative types can work and live in a world without bloodshed
and pain. \r\nAmen.\r\n\r\nBut for a while it doesn't look good, sorry to say.
And don't get me wrong, I'd probably agree with you on several key issues, like
Iraq being a quagmire whose repercussions could well be far-reaching, and only
compounding the terrorist dimlemna. Oh well, any sane solution to anything will
be thrown out because it offends Jesse Jackson and the ACLU, or the pious religious
right. I think it is a Murphy's Law corrolary."
created: '2006-05-02 04:59:35'
- author:
name: NigellaL
picture: 111493
body: "<cite>Meanwhile I can\u2019t seem to get ahead here, even though I am making
what some people think is decent money. We can\u2019t afford to buy a house, let
alone provide for retirement at my current income levels.</cite>\r\n\r\nOne can't
help but notice that you've been one of the top 3 posters around here lately,
and I wonder if perhaps there's some sort of correlation between time spent posting
to online bulletin boards and money earned?\r\n\r\nYou Yanks are lucky you haven't
got anything like the BNP. they make all but your worst Republicans look quite
tolerant indeed."
created: '2006-05-02 05:12:16'
- author:
name: pattyfab
picture: 109929
body: ">But among the Christians I know are some of the staunchest supporters of
Israel that I know of.\r\n\r\nI'm a Jew but not necessarily a Zionist. I support
a two state solution. Both sides need to make sacrifices but I don't see that
happening with Hamas in power and invading Iran which seems to be our gov't's
next step will only flame the anti-Israel fire.\r\n\r\nThe Christians only support
Israel anyway because that's where the Messiah is supposed to turn up for the
rapture, innit? At which point the Jews will end up in hell anyway because we
weren't baptized.\r\n\r\nSorry I'm getting way off topic here... just glad to
be living in my little island off the coast of America.\r\n\r\nNigella: What's
the BNP? You're not Nigella Lawson, are you ;-)"
created: '2006-05-02 05:35:29'
- author:
name: NigellaL
picture: 111493
body: "<cite>Nigella: What\u2019s the BNP? You\u2019re not Nigella Lawson, are you
;-)</cite>\r\n\r\nJust a fan who happens to share her first name... I'm rubbish
in the kitchen, unfortunately.\r\n\r\nthe BNP is the British National Party. horrible
racists, that lot. \"England for the English\", etc.\r\n\r\nhttp://en.wikipedia.org/wiki/British_National_Party"
created: '2006-05-02 05:45:23'
- author:
name: pattyfab
picture: 109929
body: Yeah, Europe has it's own problems re immigration.
created: '2006-05-02 05:46:57'
- author:
name: fontplayer
picture: 111445
body: "<cite>and invading Iran which seems to be our gov\u2019t\u2019s next step
will only flame the anti-Israel fire.</cite>\r\n\r\nActually I am sort of surprised
that Israel hasn't done anything themselves. I don't see how they can allow Iran
(and that freak that is in charge) get nuclear weapons to stick on all the missles
aimed at them. \r\n\r\n<cite>...I wonder if perhaps there\u2019s some sort of
correlation between time spent posting to online bulletin boards and money earned?</cite>\r\n\r\nThis
has been a sort of stress reliever for me lately. No correlation about the income
thing, but my music practicing has suffered. "
created: '2006-05-02 06:07:17'
- author:
name: Don McCahill
picture: 111486
body: "> I\u2019ll second that and add that unless you are 100% Native American
you are no doubt the descendent of immigrants \r\n\r\nActually, natives were also
immigrants as well. However they were the only ones who came to an uninhabited
area."
created: '2006-05-02 14:04:18'
- author:
name: Isaac
picture: 110579
body: "\"\u2026unless you are 100% Native American you are no doubt the descendent
of immigrants\u2026\"\r\n\r\nIs there a statute of limitations on this one? How
far back do you want to go? Because I'm pretty ticked off about the invaders from
the land bridge who wiped out the woolly mammoths. No respect for the ecosystem!
And the way they just took over the entire continent was just rude. I mean, have
some respect. Suddenly it's <em>their</em> continent? Sheesh. They weren't even
born here, unlike me."
created: '2006-05-02 14:11:00'
- author:
name: michaelbrowers
picture: 111225
body: "I consider myself pro-immigration. It is one of the things that makes this
country great. That said, I fervently support LEGAL immigration. Allowing illegal
immigration hurts those that follow the proper channels. \r\n\r\nMy wife is Azeri
and immigrated here on a fiance visa last year to marry me. The process of the
fiance visa and adjusting her status after we married to allow her to stay took
about a year. Additionally, we had to wait two years for her 212(e) residency
restriction to expire prior to the fiance visa process. I speak from personal
experience when I say that the legal process of immigration takes time and can
be filled with anxiety. BUT the process exists for a reason and should be respected.
My wife and I were treated with the utmost respect throughout the process by USCIS
officials and in the end we were rewarded for following proper procedures.\r\n\r\nThe
issue of illegal immigration touches my wife and I personally as we followed the
rules and waited over two years to be married and together. To reward illegal
immigration in many ways punishes those of that follow the rules. I am in favor
of more open immigration policies, but at the same time I believe that whatever
immigration policies/laws are in place should be enforced."
created: '2006-05-02 15:12:15'
- author:
name: fontplayer
picture: 111445
body: "<cite>To reward illegal immigration in many ways punishes those of that follow
the rules. I am in favor of more open immigration policies, but at the same time
I believe that whatever immigration policies/laws are in place should be enforced.</cite>\r\n\r\nA
perfect and concise summation of my feelings. Thank you for sharing that.\r\n"
created: '2006-05-02 15:17:12'
- author:
name: caboume
picture: 110905
body: "The issue here is specifically the politics regarding\r\nillegal immigration
not the general meaning of immigration.\r\n\r\nThe bottom line is, we need to
have some type of control system.\r\n\r\nMy parents immigrated to this country
in the 1970s not by dodging\r\nborder patrols, but through the established legal
process.\r\n\r\nI'm concerned w/ the illegal immigrants who come and try to abuse\r\nthe
loopholes of our laws and \"milk\" it as much as they can.\r\n\r\nAs was pointed
out, even if most illegal immigrants who come to this\r\ncountry are living and
working an honest life, are they paying\r\ntaxes? How are they contributing to
the welfare of our nation?\r\n\r\nFurthermore, does our nation have the economic
resources to sustain\r\nan ever expanding illegal immigration population?\r\n\r\nEven
if we support the mental determination of illegal immigrants\r\nto carve out a
better life, it is simply unrealistic in the long\r\nrun to remain stagnant in
our border policies.\r\n\r\nDoes that sound too unreasonable or right wing?\r\n\r\nI'm
a Democrat btw."
created: '2006-05-02 15:24:08'
- author:
name: pattyfab
picture: 109929
body: "The problem with the proposed new law is that it does not discriminate between
hard working tax paying \"illegals\" and those abusing the system. It criminalizes
all of them. If it were easier for dedicated hard-working would-be immigrants
to gain legal - even if temporary - worker status then it might free up resources
to deal with those who really shouldn't be here. And I reiterate that these new
laws seem particularly aimed at certain groups.\r\n\r\nMy personal pet peeve is
foreigners living here who complain about America. I complain very loudly about
our government but as an American who votes I feel I have that right. But when
my (mostly European) friends start grousing my response is \"don't let the door
hit you on the way out\". If Europe's so bloody great, why'd they leave?"
created: '2006-05-02 15:44:50'
- author:
name: fontplayer
picture: 111445
body: "Patty, That certainly makes sense. I think most people would agree with that.
So, this bill should be shelved as too flawed, or is there a way to amend it,
I wonder?\r\n\r\n<cite>Dennis, I think it\u2019s kinda interesting you\u2019d
choose to live in SF where you\u2019d be surrounded by -horrors!</cite>\r\n\r\nI
guess that all got miscommunicated. Basically I was saying *if* there was a place
that should be called La-lalandia, it would be SF. I love SF. There is few things
that compare to the fog rolling into Golden Gate Park, or the percussionists just
inside Stanyon on a pretty summer day (do they still do that?), but my memories
are all from the late '60s. But even from then I could tell some stories that
would make everyone here cringe a little. I came out of there having gone from
naive to not trusting anyone. It took a long time to get over that, but probably
served me well until I was ready to settle down."
created: '2006-05-02 15:53:54'
- author:
name: caboume
picture: 110905
body: "I'm being lazy here:\r\n\r\nDoes anybody have a link which lists the details
of HR-4437?"
created: '2006-05-02 16:29:46'
- author:
name: caboume
picture: 110905
body: "http://en.wikipedia.org/wiki/HR_4437\r\n\r\nFrom what I've read, it's an
attempt to do something..\r\n\r\nIt seems like this situation may be too complex
for 1 bill to solve.\r\n\r\nAn excerpt:\r\n\r\n\"Detractors say the bill includes
measures that will infringe on the human rights of asylum seekers by stripping
important due process protections, criminalizing status over which they may have
no control, and dramatically limiting their access to essential services. It would
also redefine undocumented illegal immigrants as felons, and punish anyone guilty
of providing them assistance. It also would create several new mandatory minimum
penalties for a variety of offenses, including some that would expose humanitarian
workers, public schoolteachers, church workers, and others whose only object is
to provide relief and aid to five-year mandatory minimum prison sentences.\r\n\r\nOn
the opposite side of the issue it is argued that living illegally in the United
States is a crime, and that this bill merely aims at recementing US immigration
codes that have for so long been neglected. Supporters of the bill argue that
it will increase border security by providing more US Immigration and Customs
Enforcement agents to the border, thereby helping to curtail any possible entry
to the country by terrorists, and that the passage of this bill may help curtail
drug trafficking and human trafficking from Mexico to the US by depriving smugglers
of sources and contacts on the US side of the border.\""
created: '2006-05-02 16:38:02'
- author:
name: timd
picture: 110125
body: "<em>may help curtail drug trafficking and human trafficking from Mexico to
the US</em>\r\nWhere there is a market, there is a way\r\n\r\n<em>thereby helping
to curtail any possible entry to the country by terrorists</em>\r\nCome off it\r\n\r\nTim"
created: '2006-05-02 17:12:06'
- author:
name: pattyfab
picture: 109929
body: "It's just so extreme. Plus immigration in general got so much more difficult
after 9/11, I have several friends (hardworking, tax paying, etc) in limbo. \r\n\r\nWhatever
the laws are, there will always be people trying to break them, take advantage,
etc.\r\n\r\nThere has to be a more humane and reasonable (and enforcable) solution
than this law.\r\n\r\n>, thereby helping to curtail any possible entry to the
country by terrorists\r\n\r\nseems like closing the barn door after the horse
has left..."
created: '2006-05-02 17:17:38'
- author:
name: "Hector Mu\xF1oz"
picture: 110313
body: "The truth is that if even the actual US legislation could be enforced to
full accomplishment both sides would suffer severely: the US would loose more
than 11 million of cheap, efficient and very hard to replace employees and latin
american countries would loose more than 11 million jobs (mainly Mexico).\r\n\r\nA
law that recognizes the need of both countries of this laboral relationship is
the healthiest way to go, giving the US the control and security they need, and
M\xE9xico the humanitarian guarantees their workers deserve.\r\n\r\nAltough many
inmigrants look for the US citizenship, the fact is that more than a half of the
work inmigrants return to their countries after some years, so it's not neccesary
to make a citizen of every inmigrant worker, just respect their rights and play
clean with them.\r\n\r\nH\xE9ctor"
created: '2006-05-02 21:37:57'
- author:
name: jlg4104
picture: 111297
body: "This is one of those issues on which so many of us feel compelled to have
an opinion, but which very, very few of us really grasps at all. I mean, I can
sit here in Ohio and watch the marches, and then listen to Lou Dobbs, and then
read some posts here, and maybe I'll have an opinion. And maybe my opinion will
roll around and re-shape itself over and over, as I reflect on the fact that my
own great-grandparents were immigrants, but they came through Ellis Island, and
their whole life situation was really not like that of the southwest-border immigrants
at all. \r\n\r\nOn top of that, I don't think much of the political \"debate\"
we see is about much of anything susbtantial. We have a kind of sprawling and
fairly active border patrol, as far as I can tell, but people come streaming in
anyway. They'll get themselves woven into American society if they want to, and
these bits and pieces of legislation won't end up meaning much. We're not gonna
close our borders in any significant way, and we're not gonna open them up much
either. We're just gonna keep muddling along. We can pontificate about the supposed
obnoxiousness of people marching with Mexican (not American!) flags, or we can
pontificate about the ways in which immigrant labor (illegals or not) is an essential
part of our economy, so \"illegal\" must be considered in context. It just doesn't
matter.\r\n\r\nMy own \"opinion\" is that a lot of this brouhaha is election-season
politics, nothing more. And another opinion would be that we in America just need
to acknowledge we can't have it both ways: free trade worldwide, but limited circulation
of human beings. Globalization is just gonna happen, like it or not. These are
perhaps some of the growing pains, but it's mostly just a whole lot of nothing."
created: '2006-05-03 01:55:51'
- author:
name: dewitt
body: I just don't see that, our of all of this, there is only one comment on Dan
Reynolds' post. I thought, for those skimming through this, I'd direct them to
that particular segment as it is thought filled.
created: '2006-05-03 06:53:32'
- author:
name: Giordano
picture: 111222
body: "The only thing I have to say to those who are against illegal immigrants
is this:\r\n\r\nDid the Pilgrims came to America legally? For a country built
by illegal immigrants, you certainly are neglecting your roots.\r\n\r\nAnd for
those who claim immigrants should learn English because the English speakers were
here first, then I have another question:\r\n\r\nIn that case, shouldn't the official
languages should be various Native American ones and not any European ones."
created: '2006-05-03 16:46:26'
- author:
name: fontplayer
picture: 111445
body: "<cite>In that case, shouldn\u2019t the official languages should be various
Native American ones and not any European ones.</cite>\r\n\r\nWhile we're at it,
let's turn back the clock on all the ways we can kill each other...oh, I guess
we can't. Seems this line of thinking isn't productive at all, unless we are just
looking to maximize guilt. But since some people have enough of that to go around,
I guess we're good to go.\r\n"
created: '2006-05-03 19:19:14'
- author:
name: pattyfab
picture: 109929
body: "I do think immigrants should learn English not because it's my way or the
highway, but because English is the official language in use in this country right
now and in order to advance your interests in American society, culture, and economics
you need to learn it. Period. For your own good, not because the Brits were here
first.\r\n\r\nI'd do the same if I moved to another country."
created: '2006-05-03 19:45:18'
- author:
name: fontplayer
picture: 111445
body: "<cite>I\u2019d do the same if I moved to another country.</cite>\r\n\r\nExactly!
\r\n\r\nI have to say though, I'd hate to have to learn English. What a mess of
rules and exceptions for usage and pronunciation. We take it for granted, but
if you ever try and teach it to foreigners, you quickly become apologetic.\r\n\r\nIf
you add in that many of the people we are talking about can hardly read or write
in their own language, it becomes more difficult."
created: '2006-05-03 19:52:17'
- author:
name: Giordano
picture: 111222
body: "You say you'd do the same if you moved to another country. That makes sense.
And yes, it does make sense for someone living in the US to learn English. But
in areas where Hispanophones are paying large parts of the tax bill, it isn't
fair <cite>not</cite> to be bilingual. America isn't like other countries. It
isn't the motherland that Italy, China, or most Old World countries are. And,
unlike other American countries, it has never become one. You can be American,
but most Americans are something else as well, be it Italian, German, Dutch, Chinese,
or whatever.\r\n\r\nAnyway, it's about time North Americans start learning more
than one language. It seems to me that most of the negative feelings towards these
people come from simple ignorance. Most Americans don't speak their language or
understand their culture. If you remove yourself a bit and think of the reality,
what would it change to allow these immigrants into the US legally and accept
Spanish as a de facto official language alongside English in the places they live?
It would mean more taxpayers. Besides that, not much would change. I don't understand
what everyone's problem is..\r\n\r\n<cite>If you add in that many of the people
we are talking about can hardly read or write in their own language, it becomes
more difficult.</cite>\r\n\r\nDon't get so self-righteous. My grandparents from
Italy weren't well-educated. It takes my grandmother 15 minutes to write a birthday
card and I don't think she's ever read a book besides maybe from a small Missal
from when she was a girl that she has by her bed. She finished grade 6 (which
means she was more educated than most people her age from my region) and my grandfather
only finished grade 4. Meanwhile, they are better off, no, <cite>much</cite> better
off than most native-born Canadians. Why? They worked their asses off and saved
every penny, like all immigrants. Immigrants tend to be more driven, ambitious,
and successful than most people. Just think: they saw a problem and went to such
great lengths to overcome it as moving to a foreign country, learning a new language
(or several), finding a place to live and a job all over again, etc...\r\n\r\nWould
you have the wherewithal to do something like that? I don't mean moving to a new
country because you can afford to do something new (my grandparents had to raise
and sell a runt pig their neighbor gave them to afford the ticket to come here),
but overcoming your conditions to do it. Acknowledge that in business, there are
many entrepreneurs who never had much schooling but who had an idea that made
them very rich.\r\n\r\nNext, acknowedge that the rich pay more taxes. "
created: '2006-05-03 23:55:47'
- author:
name: fontplayer
picture: 111445
body: "<cite>Don\u2019t get so self-righteous.</cite> \r\n\r\nDon't get so judgemental.
I know *many* of these people. Some have lived here for many years and can barely
speak a sentence you would understand. \r\n\r\nGranted, someone who is driven
by self-motivation can do practically anything. I'd say your grand-parents were
motivated, and I notice you say they did learn the language. I'll bet it is because
they wanted to, which made up for their lack of education. When you want to do
something, it is all the difference in the world.\r\n\r\nBut looking up a word
to see the meaning, can be a big help. I know because I have traveled through
many parts of Mexico, speaking their language. And my dictionary was never further
away than my pocket."
created: '2006-05-04 03:25:29'
- author:
name: pattyfab
picture: 109929
body: "I couldn't agree more that Americans should learn more than one language
and was lucky enough myself to go to a school that started language ed pretty
young. Hence I'm fluent in French and also basically functional in Spanish and
Italian. But unfortunately not enough emphasis is placed on language ed in most
schools here, especially spanish.\r\n\r\nHowever there are so many different immigrant
groups, thru history & all over the country, that bilingual education isn't that
practical - besides it further marginalizes immigrants not to speak English. I
understand it isn't easy for a 65 year old immigrant to learn a new language,
but kids in school can and should if they want to get anywhere. Again, I'm not
being rah rah rah USA here but practical. English is the lingua franca here (and
a LOT of places) and is likely to remain so. "
created: '2006-05-04 04:32:07'
- author:
name: vinceconnare
picture: 110591
body: ">if Europe is so nice why did they leave.\r\n\r\nGive me your tired, your
poor and earning to be free... Bye Gdubya.. nob... So I left the USA to be FREE!!!!!
UK let's Euro citizens, all Commonweath countries (Canada, Australia, NZ, etc)
Irish, to vote in local elections. \r\n\r\nUSA you can't go to Cuba because the
US is stuck in the past... you can't do nothing right...But where the president,\r\nIs
never black, female or gay (or Jewish, Muslim, Catholic (oops once but shot) )
\r\nAnd until that day\r\nYou\u2019ve got nothing to say to me\r\nTo help me believe\r\n\r\nAmerica
your head's too big,\r\nBecause America,\r\nYour belly's too big\r\nAnd I love
you,\r\nI just wish you'd stay where you is\r\nIn America, The land of the free,
they said\r\nAnd of opportunity\r\nIn a just and a truthful way\r\nBut where the
president,\r\nIs never black female or gay\r\nAnd until that day\r\nYou\u2019ve
got nothing to say to me\r\nTo help me believe\r\n\r\nIn America, It brought you
the hamburger\r\nWell America you know where,\r\nYou can shove your hamburger\r\nAnd
don't you wonder\r\nWhy in Estonia they say\r\nHey you, Big fat pig\r\nYou fat
pig, You fat pig\r\nSteely Blue eyes with no love in them, Scan The World, And
a humourless smile\r\nWith no warmth within Greets the world\r\n\r\nAnd I, I have
got nothing\r\nTo offer you\r\nNo-no-no-no-no\r\nJust this heart deep and true,
Which you say you don't need\r\nSee with your eyes, Touch with your hands, please\r\nHear
through your ears, Know in your soul, please\r\nFor haven't you me with you now?\r\nAnd
I love you, I love youI love you, And I love you\r\nI love you, I love you"
created: '2006-05-04 15:29:58'
- author:
name: Choison
body: If the US would just get it over with and Annex the Globe then there would
only be state and territory borders and hopefully we could all just go where we
please. Wouldn't that be grand? Of course we would have to deal with a wee bit
of global war etc. but we are already well on our way in getting that started.
Nevermind my sarcastic ramblings. I think that we should allow anyone who is willing
to work, follow our laws, and pay taxes to come to the USA. It was immigrants
that built our country to what it is today... Good luck with the struggle Donsata!
We are with you.
created: '2006-05-05 22:11:43'
date: '2006-05-01 18:57:42'
node_type: forum
title: 'WARNING: Not Type Related Topic'
---
|
C#
|
UTF-8
| 1,454 | 2.921875 | 3 |
[] |
no_license
|
using System;
using System.IO;
using System.Net;
using System.Xml.Serialization;
namespace Comercialon.Classes
{
public static class Cep
{
public static Xmlcep CepRetornado { get; set; }
public static Xmlcep Obter(string cep)
{
string[] dados = new string[7];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://viacep.com.br/ws/" + cep + "/xml/");
request.AllowAutoRedirect = false;
HttpWebResponse ChecaServidor = (HttpWebResponse)request.GetResponse();
if (ChecaServidor.StatusCode != HttpStatusCode.OK)
{
dados[5] = "Servidor indisponível";
}
using (Stream webStream = ChecaServidor.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
XmlSerializer serializer = new XmlSerializer(typeof(Xmlcep));
using (StringReader reader = new StringReader(response))
{
CepRetornado = (Xmlcep)serializer.Deserialize(reader);
}
}
}
}
return CepRetornado;
}
}
}
|
Swift
|
UTF-8
| 1,407 | 3.015625 | 3 |
[] |
no_license
|
//
// Copyright (C) 2015 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
//
import Foundation
let Unknown = "Author Unknown"
public class Book: ModelObject
{
enum Keys: String {
case Title = "title"
case Year = "year"
case Author = "author"
static var allKeys: [String] {
return [Title.rawValue, Year.rawValue, Author.rawValue]
}
}
public var title = ""
public var year = ""
public var author: Author?
public override var description: String {
return "\(title), \(year), \(author ?? Unknown)"
}
override class func keys() -> [String]
{
return [Keys.Title.rawValue, Keys.Year.rawValue, Keys.Author.rawValue];
}
public required init(var dictionary: [String : AnyObject])
{
if let dict = dictionary[Keys.Author.rawValue] as? [String: AnyObject] {
dictionary[Keys.Author.rawValue] = Author(dictionary: dict)
}
super.init(dictionary: dictionary)
}
public override func dictionaryRepresentation() -> [String: AnyObject]
{
var dict = super.dictionaryRepresentation()
if let author = dict[Keys.Author.rawValue] as? Author {
dict[Keys.Author.rawValue] = author.dictionaryRepresentation()
}
return dict
}
}
|
Java
|
UTF-8
| 1,552 | 2.6875 | 3 |
[] |
no_license
|
package bgu.spl.mics.application.services;
import bgu.spl.mics.MicroService;
import bgu.spl.mics.application.messages.*;
import bgu.spl.mics.application.passiveObjects.*;
/**
* InventoryService is in charge of the book inventory and stock.
* Holds a reference to the {@link Inventory} singleton of the store.
* This class may not hold references for objects which it is not responsible for:
* {@link ResourcesHolder}, {@link MoneyRegister}.
*
* You can add private fields and public methods to this class.
* You MAY change constructor signatures and even add new public constructors.
*/
public class InventoryService extends MicroService{
//FIELDS:
private Inventory inventory;
public InventoryService(int serviceID) {
super("InventoryService "+serviceID);
this.inventory = Inventory.getInstance();
}
@Override
protected void initialize() {
subscribeEvent(CheckAvailabilityEvent.class, ev -> {
Integer bookPrice = inventory.checkAvailabiltyAndGetPrice(ev.getBookTitle());
if (bookPrice == -2) {
complete(ev, null);
}
complete(ev,bookPrice); //resolve the result to 'bookExistFuture' from SellingService.
});
subscribeEvent(TakeFromInventoryEvent.class, ev ->{
synchronized (inventory.getInventoryMap().get(ev.getBookTitle())) {
OrderResult result = inventory.take(ev.getBookTitle());
complete(ev, result); //resolve the result to 'bookTaken' from SellingService.
}
});
//Terminate Broadcast Callback
subscribeBroadcast(TerminateBroadcast.class, cb->{
terminate();
});
}
}
|
JavaScript
|
UTF-8
| 837 | 2.6875 | 3 |
[] |
no_license
|
export const betDescFormat = (betType, betAmount, gameData) => {
let rValue = new String();
if (betType === "HOME") {
rValue =
gameData.homeAbbreviation +
(betAmount == 0
? " Moneyline"
: betAmount > 0
? " +" + betAmount
: " " + betAmount);
} else if (betType === "AWAY") {
rValue =
gameData.awayAbbreviation +
(betAmount == 0
? " Moneyline"
: betAmount > 0
? " +" + betAmount
: " " + betAmount);
} else if (betType === "UNDER") {
rValue = "Under " + betAmount;
} else if (betType === "OVER") {
rValue = "Over " + betAmount;
}
return rValue;
};
export const betMatchFormat = (gameData) => {
let rValue = new String();
rValue = gameData.awayAbbreviation + " @ " + gameData.homeAbbreviation;
return rValue;
};
|
Java
|
UTF-8
| 4,066 | 2.203125 | 2 |
[] |
no_license
|
package com.howbuy.trade.dto;
/**
* 好买交易DTO
* @author LuanYi
*/
public class TradeDTO {
//交易id
private Integer tradeId;
//与custId字段关联
private Integer tradeCustId;
//基金代码
private String fundCode;
//购买金额
private String amount;
//委托号
private String contractNo;
//基金简称
private String fundAbbr;
//交易类型
private String busiType;
//交易状态
private String tradeStatus;
//基金份额
private String tradeVol;
//交易金额
private String tradeAmt;
//手续费
private String fee;
//银行卡号
private String bankAcct;
//申请日期
private String appDt;
//银行编号
private String bankCode;
//净值
private String nav;
//申请时间
private String appTm;
//分红方式
private String divMode;
//确认份额
private String ackVol;
//确认金额
private String ackAmt;
//付款状态
private String txPmtFlag;
//撤单标志
private String cancelFlag;
//确认日期
private String ackDt;
public Integer getTradeId() {
return tradeId;
}
public void setTradeId(Integer tradeId) {
this.tradeId = tradeId;
}
public Integer getTradeCustId() {
return tradeCustId;
}
public void setTradeCustId(Integer tradeCustId) {
this.tradeCustId = tradeCustId;
}
public String getFundCode() {
return fundCode;
}
public void setFundCode(String fundCode) {
this.fundCode = fundCode;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getContractNo() {
return contractNo;
}
public void setContractNo(String contractNo) {
this.contractNo = contractNo;
}
public String getFundAbbr() {
return fundAbbr;
}
public void setFundAbbr(String fundAbbr) {
this.fundAbbr = fundAbbr;
}
public String getBusiType() {
return busiType;
}
public void setBusiType(String busiType) {
this.busiType = busiType;
}
public String getTradeStatus() {
return tradeStatus;
}
public void setTradeStatus(String tradeStatus) {
this.tradeStatus = tradeStatus;
}
public String getTradeVol() {
return tradeVol;
}
public void setTradeVol(String tradeVol) {
this.tradeVol = tradeVol;
}
public String getTradeAmt() {
return tradeAmt;
}
public void setTradeAmt(String tradeAmt) {
this.tradeAmt = tradeAmt;
}
public String getFee() {
return fee;
}
public void setFee(String fee) {
this.fee = fee;
}
public String getBankAcct() {
return bankAcct;
}
public void setBankAcct(String bankAcct) {
this.bankAcct = bankAcct;
}
public String getAppDt() {
return appDt;
}
public void setAppDt(String appDt) {
this.appDt = appDt;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getNav() {
return nav;
}
public void setNav(String nav) {
this.nav = nav;
}
public String getAppTm() {
return appTm;
}
public void setAppTm(String appTm) {
this.appTm = appTm;
}
public String getDivMode() {
return divMode;
}
public void setDivMode(String divMode) {
this.divMode = divMode;
}
public String getAckVol() {
return ackVol;
}
public void setAckVol(String ackVol) {
this.ackVol = ackVol;
}
public String getAckAmt() {
return ackAmt;
}
public void setAckAmt(String ackAmt) {
this.ackAmt = ackAmt;
}
public String getTxPmtFlag() {
return txPmtFlag;
}
public void setTxPmtFlag(String txPmtFlag) {
this.txPmtFlag = txPmtFlag;
}
public String getCancelFlag() {
return cancelFlag;
}
public void setCancelFlag(String cancelFlag) {
this.cancelFlag = cancelFlag;
}
public String getAckDt() {
return ackDt;
}
public void setAckDt(String ackDt) {
this.ackDt = ackDt;
}
}
|
Java
|
UTF-8
| 698 | 2.828125 | 3 |
[] |
no_license
|
package com.day0209;
import java.util.Scanner;
public class SWEA_5688_D3_세제곱근을찾아라 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc = new Scanner(src);
int T = sc.nextInt();
for(int t = 1; t<= T; t++){
long result = -1;
long n = sc.nextLong();
for(long i = 1; i*i*i <= n; i++){
if(i*i*i == n){
result = i;
break;
}
}
System.out.println("#"+t+" "+result);
}
}
private static String src = "3\n" +
"27\n" +
"7777\n" +
"64";
}
|
C#
|
UTF-8
| 1,744 | 3.328125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace actividad3_SentenciasControl
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("MENU DE OPCIONES");
Console.WriteLine("");
Console.WriteLine("1. Validar Suma");
Console.WriteLine("2. Salir");
Console.WriteLine("");
Console.WriteLine("Ingrese el Numero de su Opcion:");
int opc = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
switch (opc)
{
case 1:
int sum1, sum2, sum3, a, b, c; //declarando mis variables//
Console.WriteLine("Capture numero 1");
a = int.Parse(Console.ReadLine());
Console.WriteLine("Capture numero 2");
b = int.Parse(Console.ReadLine());
Console.WriteLine("Capture numero 3");
c = int.Parse(Console.ReadLine());
sum1 = a + b; sum2 = b + c; sum3 = a + c; //sumando y asignando
if ((sum1 == sum2) && (sum2 == sum3)) //comparando si la Sum1 es
{
Console.WriteLine("SON IGUALES");
}
else
{
Console.WriteLine("SON DISTINTOS");
}
break;
case 2:
Console.WriteLine("HASTA LUEGO, BY SILVESTRE SANTIAGO CORONADO");
break;
default:
Console.WriteLine("Opcion no Valida");
break;
}
Console.ReadKey();
}
}
}
|
PHP
|
UTF-8
| 1,729 | 3.046875 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* Date: 2/19/2019
* Time: 9:19 AM
*/
namespace App\Kernel;
class Connection
{
private $host;
private $dbName;
private $user;
private $password;
/** @var mysqli */
private $connection;
public function __construct($host, $dbName, $user, $password = '')
{
$this->host = $host;
$this->dbName = $dbName;
$this->user = $user;
$this->password = $password;
}
public function insert($tableName, $data)
{
$fields = array_keys($data);
$values = array_map(function($value) {
return "'" . $value . "'";
}, array_values($data));
$statement = sprintf(
'INSERT INTO %s (%s) VALUES (%s)',
$tableName,
implode(', ', $fields),
implode(', ', $values)
);
$this->query($statement);
$lastInsertIdResult = $this->query('SELECT LAST_INSERT_ID()')->fetch_all();
return $lastInsertIdResult[0][0];
}
public function query($statement)
{
if (null === $this->connection) {
$this->connect();
}
$result = $this->connection->query($statement);
if (false === $result) {
throw new \RuntimeException(sprintf('Error executing query: [%s] [%s]', $statement, $this->connection->error));
}
return $result;
}
private function connect()
{
if (null !== $this->connection) {
return;
}
$this->connection = new \mysqli($this->host, $this->user, $this->password, $this->dbName);
if (!$this->connection) {
throw new \RuntimeException('Connection error!');
}
}
}
|
Python
|
UTF-8
| 245 | 2.921875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# @Time : 2020/1/29 11:45
# @Author : LiChao
# @File : C-4.12.py
def mutiply_m_n(m,n):
if m == 1:
return n
if n==1:
return m
return mutiply_m_n(m,n-1)+m
result=mutiply_m_n(8,7)
print(result)
|
C#
|
UTF-8
| 4,517 | 2.828125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Components
{
class Program
{
static void Main(string[] args)
{
//This is an example of a testing code that you should run for all the gates that you create
//Create a gate
AndGate and = new AndGate();
//Test that the unit testing works properly
if (!and.TestGate())
Console.WriteLine("bugbug");
//Create a gate
OrGate or = new OrGate();
//Test that the unit testing works properly
if (!or.TestGate())
Console.WriteLine("bugbug");
//Create a gate
XorGate xor = new XorGate();
//Test that the unit testing works properly
if (!xor.TestGate())
Console.WriteLine("bugbug");
//Create a gate
MultiBitAndGate multiAnd = new MultiBitAndGate(10);
//Test that the unit testing works properly
if (!multiAnd.TestGate())
Console.WriteLine("bugbug");
//Create a gate
MultiBitOrGate multiOr = new MultiBitOrGate(10);
//Test that the unit testing works properly
if (!multiOr.TestGate())
Console.WriteLine("bugbug");
/* WireSet omri = new WireSet(4);
omri[0].Value = 1;
omri[1].Value = 1;
omri[2].Value = 0;
omri[3].Value = 1;
omri.SetValue(10);
Console.WriteLine(omri.Get2sComplement());
Console.WriteLine(omri.GetValue());
omri.Set2sComplement(-4);*/
//Create a gate
MuxGate mux = new MuxGate();
//Test that the unit testing works properly
if (!mux.TestGate())
Console.WriteLine("bugbug");
//Create a gate
Demux demux = new Demux();
//Test that the unit testing works properly
if (!demux.TestGate())
Console.WriteLine("bugbug");
//Create a gate
BitwiseAndGate BWAndGate = new BitwiseAndGate(10);
//Test that the unit testing works properly
if (!BWAndGate.TestGate())
Console.WriteLine("bugbug");
//Create a gate
BitwiseNotGate BWNotGate = new BitwiseNotGate(10);
//Test that the unit testing works properly
if (!BWNotGate.TestGate())
Console.WriteLine("bugbug");
//Create a gate
BitwiseOrGate BWOrGate = new BitwiseOrGate(10);
//Test that the unit testing works properly
if (!BWOrGate.TestGate())
Console.WriteLine("bugbug");
//Create a gate
BitwiseMux BWMux = new BitwiseMux(6);
//Test that the unit testing works properly
if (!BWMux.TestGate())
Console.WriteLine("bugbug");
//Create a gate
BitwiseDemux BWDemux = new BitwiseDemux(10);
//Test that the unit testing works properly
if (!BWDemux.TestGate())
Console.WriteLine("bugbug");
//Create a gate
BitwiseMultiwayMux BWMultiMux = new BitwiseMultiwayMux(10,3);
//Test that the unit testing works properly
if (!BWMultiMux.TestGate())
Console.WriteLine("bugbug");
/* BitwiseMultiwayDemux BWMultiDemux2 = new BitwiseMultiwayDemux(4, 4);
for (int i = 0; i < BWMultiDemux2.ControlBits; i++)
BWMultiDemux2.Control[i].Value = 0;
BWMultiDemux2.Input[0].Value = 0;
BWMultiDemux2.Input[1].Value = 1;
BWMultiDemux2.Input[2].Value = 1;
BWMultiDemux2.Input[3].Value = 1;
Console.WriteLine(BWMultiDemux2.Outputs[0][2].Value);*/
//Create a gate
BitwiseMultiwayDemux BWMultiDemux = new BitwiseMultiwayDemux(4, 4);
//Test that the unit testing works properly
if (!BWMultiDemux.TestGate())
Console.WriteLine("bugbug");
//Now we ruin the nand gates that are used in all other gates. The gate should not work properly after this.
NAndGate.Corrupt = true;
if (and.TestGate())
Console.WriteLine("bugbug");
Console.WriteLine("done");
Console.ReadLine();
}
}
}
|
C#
|
UTF-8
| 1,949 | 2.734375 | 3 |
[] |
no_license
|
using System.Configuration;
using System.Data.SqlClient;
using System.Threading;
using System.Windows.Forms;
namespace AttachedMode.Services_HomeWork2
{
public class CreatedDB
{
public static void Create()
{
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["DataBase"];
var connectionString = settings.ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
try
{
connection.Open();
}
catch (SqlException exeption)
{
if (exeption.Number == 4060)
{
MessageBox.Show("Подождите идет создание базы данных");
connection.Close();
settings = ConfigurationManager.ConnectionStrings["tmpDataBase"];
connectionString = settings.ConnectionString;
connection = new SqlConnection(connectionString);
SqlCommand cmdCreateDataBase = new SqlCommand(string.Format("CREATE DATABASE [{0}]", "Database"), connection);
connection.Open();
MessageBox.Show("Посылаем запрос");
cmdCreateDataBase.ExecuteNonQuery();
connection.Close();
Thread.Sleep(2000);
settings = ConfigurationManager.ConnectionStrings["DataBase"];
connectionString = settings.ConnectionString;
connection = new SqlConnection(connectionString);
connection.Open();
}
}
finally
{
MessageBox.Show("Соединение успешно произведено");
connection.Close();
connection.Dispose();
}
}
}
}
|
Java
|
UTF-8
| 8,143 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
package com.jnape.palatable.lambda.adt.hlist;
import com.jnape.palatable.lambda.adt.Maybe;
import com.jnape.palatable.lambda.adt.hlist.HList.HCons;
import com.jnape.palatable.lambda.adt.product.Product3;
import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.builtin.fn2.Into;
import com.jnape.palatable.lambda.functions.recursion.RecursiveResult;
import com.jnape.palatable.lambda.functions.specialized.Pure;
import com.jnape.palatable.lambda.functor.Applicative;
import com.jnape.palatable.lambda.functor.Bifunctor;
import com.jnape.palatable.lambda.functor.builtin.Lazy;
import com.jnape.palatable.lambda.monad.Monad;
import com.jnape.palatable.lambda.monad.MonadRec;
import com.jnape.palatable.lambda.traversable.Traversable;
import static com.jnape.palatable.lambda.functions.builtin.fn1.Constantly.constantly;
import static com.jnape.palatable.lambda.functions.builtin.fn1.Uncons.uncons;
import static com.jnape.palatable.lambda.functions.recursion.Trampoline.trampoline;
/**
* A 3-element tuple product type, implemented as a specialized HList. Supports random access.
*
* @param <_1> The first slot element type
* @param <_2> The second slot element type
* @param <_3> The third slot element type
* @see Product3
* @see HList
* @see SingletonHList
* @see Tuple2
* @see Tuple4
* @see Tuple5
*/
public class Tuple3<_1, _2, _3> extends HCons<_1, Tuple2<_2, _3>> implements
Product3<_1, _2, _3>,
MonadRec<_3, Tuple3<_1, _2, ?>>,
Bifunctor<_2, _3, Tuple3<_1, ?, ?>>,
Traversable<_3, Tuple3<_1, _2, ?>> {
private final _1 _1;
private final _2 _2;
private final _3 _3;
Tuple3(_1 _1, Tuple2<_2, _3> tail) {
super(_1, tail);
this._1 = _1;
_2 = tail._1();
_3 = tail._2();
}
/**
* {@inheritDoc}
*/
@Override
public <_0> Tuple4<_0, _1, _2, _3> cons(_0 _0) {
return new Tuple4<>(_0, this);
}
/**
* Snoc an element onto the back of this {@link Tuple3}.
*
* @param _4 the new last element
* @param <_4> the new last element type
* @return the new {@link Tuple4}
*/
public <_4> Tuple4<_1, _2, _3, _4> snoc(_4 _4) {
return tuple(_1, _2, _3, _4);
}
/**
* {@inheritDoc}
*/
@Override
public _1 _1() {
return _1;
}
/**
* {@inheritDoc}
*/
@Override
public _2 _2() {
return _2;
}
/**
* {@inheritDoc}
*/
@Override
public _3 _3() {
return _3;
}
/**
* {@inheritDoc}
*/
@Override
public Tuple3<_2, _3, _1> rotateL3() {
return tuple(_2, _3, _1);
}
/**
* {@inheritDoc}
*/
@Override
public Tuple3<_3, _1, _2> rotateR3() {
return tuple(_3, _1, _2);
}
/**
* {@inheritDoc}
*/
@Override
public Tuple3<_2, _1, _3> invert() {
return tuple(_2, _1, _3);
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3Prime> fmap(Fn1<? super _3, ? extends _3Prime> fn) {
return (Tuple3<_1, _2, _3Prime>) MonadRec.super.<_3Prime>fmap(fn);
}
/**
* {@inheritDoc}
*/
@Override
public <_2Prime> Tuple3<_1, _2Prime, _3> biMapL(Fn1<? super _2, ? extends _2Prime> fn) {
return (Tuple3<_1, _2Prime, _3>) Bifunctor.super.<_2Prime>biMapL(fn);
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3Prime> biMapR(Fn1<? super _3, ? extends _3Prime> fn) {
return (Tuple3<_1, _2, _3Prime>) Bifunctor.super.<_3Prime>biMapR(fn);
}
/**
* {@inheritDoc}
*/
@Override
public <_2Prime, _3Prime> Tuple3<_1, _2Prime, _3Prime> biMap(Fn1<? super _2, ? extends _2Prime> lFn,
Fn1<? super _3, ? extends _3Prime> rFn) {
return new Tuple3<>(_1(), tail().biMap(lFn, rFn));
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3Prime> pure(_3Prime _3Prime) {
return tuple(_1, _2, _3Prime);
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3Prime> zip(
Applicative<Fn1<? super _3, ? extends _3Prime>, Tuple3<_1, _2, ?>> appFn) {
return biMapR(appFn.<Tuple3<_1, _2, Fn1<? super _3, ? extends _3Prime>>>coerce()._3()::apply);
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Lazy<Tuple3<_1, _2, _3Prime>> lazyZip(
Lazy<? extends Applicative<Fn1<? super _3, ? extends _3Prime>, Tuple3<_1, _2, ?>>> lazyAppFn) {
return MonadRec.super.lazyZip(lazyAppFn).fmap(Monad<_3Prime, Tuple3<_1, _2, ?>>::coerce);
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3Prime> discardL(Applicative<_3Prime, Tuple3<_1, _2, ?>> appB) {
return MonadRec.super.discardL(appB).coerce();
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3> discardR(Applicative<_3Prime, Tuple3<_1, _2, ?>> appB) {
return MonadRec.super.discardR(appB).coerce();
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3Prime> flatMap(
Fn1<? super _3, ? extends Monad<_3Prime, Tuple3<_1, _2, ?>>> f) {
return pure(f.apply(_3).<Tuple3<_1, _2, _3Prime>>coerce()._3);
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime> Tuple3<_1, _2, _3Prime> trampolineM(
Fn1<? super _3, ? extends MonadRec<RecursiveResult<_3, _3Prime>, Tuple3<_1, _2, ?>>> fn) {
return fmap(trampoline(x -> fn.apply(x).<Tuple3<_1, _2, RecursiveResult<_3, _3Prime>>>coerce()._3()));
}
/**
* {@inheritDoc}
*/
@Override
public <_3Prime, App extends Applicative<?, App>, TravB extends Traversable<_3Prime, Tuple3<_1, _2, ?>>,
AppTrav extends Applicative<TravB, App>> AppTrav traverse(
Fn1<? super _3, ? extends Applicative<_3Prime, App>> fn,
Fn1<? super TravB, ? extends AppTrav> pure) {
return fn.apply(_3).fmap(_3Prime -> fmap(constantly(_3Prime))).<TravB>fmap(Applicative::coerce).coerce();
}
/**
* Returns a <code>{@link Tuple2}<_1, _2></code> of all the elements of this
* <code>{@link Tuple3}<_1, _2, _3></code> except the last.
*
* @return The {@link Tuple2}<_1, _2> representing all but the last element
*/
public Tuple2<_1, _2> init() {
return rotateR3().tail();
}
/**
* Given a value of type <code>A</code>, produced an instance of this tuple with each slot set to that value.
*
* @param a the value to fill the tuple with
* @param <A> the value type
* @return the filled tuple
* @see Tuple2#fill
*/
public static <A> Tuple3<A, A, A> fill(A a) {
return tuple(a, a, a);
}
/**
* Return {@link Maybe#just(Object) just} the first three elements from the given {@link Iterable}, or
* {@link Maybe#nothing() nothing} if there are less than three elements.
*
* @param as the {@link Iterable}
* @param <A> the {@link Iterable} element type
* @return {@link Maybe} the first three elements of the given {@link Iterable}
*/
public static <A> Maybe<Tuple3<A, A, A>> fromIterable(Iterable<A> as) {
return uncons(as).flatMap(Into.into((head, tail) -> Tuple2.fromIterable(tail).fmap(t -> t.cons(head))));
}
/**
* The canonical {@link Pure} instance for {@link Tuple3}.
*
* @param _1 the head element
* @param _2 the second element
* @param <_1> the head element type
* @param <_2> the second element type
* @return the {@link Pure} instance
*/
public static <_1, _2> Pure<Tuple3<_1, _2, ?>> pureTuple(_1 _1, _2 _2) {
return new Pure<Tuple3<_1, _2, ?>>() {
@Override
public <_3> Tuple3<_1, _2, _3> checkedApply(_3 _3) throws Throwable {
return tuple(_1, _2, _3);
}
};
}
}
|
Java
|
UTF-8
| 5,777 | 2.09375 | 2 |
[] |
no_license
|
package rmhub.mod.trafficlogger.service;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.modelmapper.ModelMapper;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import rmhub.common.exception.BusinessException;
import rmhub.mod.trafficlogger.dto.request.UpdateTrafficAlertDto;
import rmhub.mod.trafficlogger.dto.response.TrafficAlertDto;
import rmhub.mod.trafficlogger.entity.TrafficAlert;
import rmhub.mod.trafficlogger.repository.TrafficAlertRepo;
@ExtendWith(SpringExtension.class)
class TrafficAlertServiceImplTest {
@Mock
private TrafficAlertRepo repository;
@InjectMocks
private TrafficAlertServiceImpl serviceImpl;
@Mock
private ModelMapper modelMapper;
private final TrafficAlert trafficAlert = TrafficAlert.builder()
.id(1L)
.deploymentId(1)
.description("123")
.externalId("123")
.cause("abc")
.isHandled(false)
.handledBy("132")
.trafficMeasurementId(123L)
.build();
private final TrafficAlert trafficAlert1 = TrafficAlert.builder()
.id(2L)
.deploymentId(1)
.description("123")
.externalId("123")
.cause("abc")
.isHandled(false)
.handledBy("132")
.trafficMeasurementId(123L)
.createdDate(new Date())
.build();
private final TrafficAlert trafficAlert2 = TrafficAlert.builder()
.id(3L)
.deploymentId(1)
.description("123")
.externalId("123")
.cause("abc")
.isHandled(false)
.handledBy("132")
.trafficMeasurementId(123L)
.createdDate(new Date())
.build();
private final TrafficAlertDto trafficAlertDto = TrafficAlertDto.builder()
.id(1L)
.physicalDeviceId(1L)
.trafficMeasurementId(1L)
.deploymentId(1L)
.description("123")
.externalId(123L)
.cause("abc")
.isHandled(false)
.handledBy("132")
.build();
private final UpdateTrafficAlertDto updateTrafficAlertDto = UpdateTrafficAlertDto.builder()
.description("abc")
.isHandled(false)
.build();
@BeforeEach
void set() {
when(repository.findById(Mockito.anyLong())).thenReturn(Optional.of(trafficAlert));
}
@Test
void test() {
var trafficAlert = TrafficAlert.builder().deploymentId(1).build();
Mockito.when(repository.save(ArgumentMatchers.any(TrafficAlert.class))).thenReturn(trafficAlert);
var result = serviceImpl.create(trafficAlert);
Assertions.assertNotNull(result);
}
@Test
void create_trafficAlert() {
when(repository.save(trafficAlert)).thenReturn(trafficAlert);
TrafficAlert actual = serviceImpl.create(trafficAlert);
assertEquals(trafficAlert, actual);
}
@Test
void update_trafficAlert() {
when(repository.save(trafficAlert)).thenReturn(trafficAlert);
TrafficAlert actual = serviceImpl.update(trafficAlert);
assertEquals(trafficAlert, actual);
}
@Test
void deleteTrafficAlert_byId() {
doNothing().when(repository).deleteById(Mockito.anyLong());
serviceImpl.delete(1L);
verify(repository, Mockito.only()).deleteById(1L);
}
@Test
void findAll_trafficAlert() {
List<TrafficAlert> trafficAlertList = new ArrayList<>();
trafficAlertList.add(trafficAlert);
trafficAlertList.add(trafficAlert1);
trafficAlertList.add(trafficAlert2);
when(repository.findAll()).thenReturn(trafficAlertList);
List<TrafficAlert> result = serviceImpl.findAll();
assertEquals(3, result.size());
assertEquals(trafficAlert, trafficAlertList.get(0));
assertEquals(trafficAlert1, trafficAlertList.get(1));
assertEquals(trafficAlert2, trafficAlertList.get(2));
}
@Test
void findById() {
TrafficAlert actual = serviceImpl.findById(1L);
Assertions.assertEquals(trafficAlert, actual);
}
@Test
void findById_null() {
BusinessException exception = assertThrows(BusinessException.class, () -> serviceImpl.findById(null));
assertEquals(exception.getMessage(), "Not found!");
}
@Test
void getList_trafficAlertDto() {
List<TrafficAlert> trafficAlertList = new ArrayList<>();
trafficAlertList.add(trafficAlert);
when(repository.findAll()).thenReturn(trafficAlertList);
when(modelMapper.map(Mockito.any(TrafficAlert.class), any())).thenReturn(trafficAlertDto);
Assertions.assertEquals(1, serviceImpl.list().size());
verify(modelMapper, Mockito.atLeastOnce()).map(Mockito.any(TrafficAlert.class), any());
}
@Test
void get_trafficAlertDto() {
when(modelMapper.map(Mockito.any(TrafficAlert.class), eq(TrafficAlertDto.class))).thenReturn(trafficAlertDto);
assertEquals(serviceImpl.get(1L), trafficAlertDto);
}
@Test
void update_trafficAlertDto() {
when(modelMapper.map(Mockito.any(TrafficAlertDto.class), Mockito.any())).thenReturn(trafficAlert);
when(repository.save(Mockito.any(TrafficAlert.class))).thenReturn(trafficAlert);
when(modelMapper.map(Mockito.any(TrafficAlert.class), Mockito.any())).thenReturn(trafficAlertDto);
var actual = serviceImpl.update(1L, updateTrafficAlertDto);
assertEquals(trafficAlertDto, actual);
}
}
|
Java
|
UTF-8
| 1,036 | 1.992188 | 2 |
[] |
no_license
|
package com.hackathon_sg.sg_hackathon_lendingAppRest;
import java.sql.Date;
import org.springframework.stereotype.Component;
public class UserVO {
private Integer user_id;
private String userName;
private String email;
private String contact_no;
private Date dob;
private String password;
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContact_no() {
return contact_no;
}
public void setContact_no(String contact_no) {
this.contact_no = contact_no;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
Java
|
UTF-8
| 4,346 | 2.828125 | 3 |
[] |
no_license
|
package scxml2svg.svgcomposer;
import org.w3c.dom.*;
import java.util.List;
import scxml2svg.scxmlmodel.State;
import scxml2svg.scxmlmodel.FinalState;
import scxml2svg.scxmlmodel.HistoryState;
import scxml2svg.scxmlmodel.ParallelState;
import scxml2svg.scxmlmodel.Transition;
/**
* Layout that represents a state.
* @author peping
*/
public class StateContainer extends StateLayout {
public StateContainer(State state, List<Transition> transitions)
{
super((State[]) state.getChildren().toArray(new State[0]), transitions);
thisState = state;
}
/**
* Represent this State as a Node.
*
* @param doc Document where to create nodes
* @return Node representing the State
*/
@Override public Node toNode(Document doc)
{
if (doc == null) return null;
Element group = doc.createElement("g");
group.setAttribute("class", "state-group");
group.setAttribute("transform", "translate("+(getX()-width/2)+","+(getY()-height/2)+")");
// Add another rectangle if this state is final
if (thisState instanceof FinalState)
{
Element finalRect = doc.createElement("rect");
finalRect.setAttribute("x", Double.toString(-2));
finalRect.setAttribute("width", Double.toString(width+4));
finalRect.setAttribute("y", Double.toString(-2));
finalRect.setAttribute("height", Double.toString(height+4));
finalRect.setAttribute("class", "final-rect");
group.appendChild(finalRect);
}
Element rect;
{
double w = width, h = height;
String className = "state-rect";
if (thisState instanceof FinalState)
className = "final-rect";
else if (thisState instanceof ParallelState)
className = "parallel-rect";
else if (thisState instanceof HistoryState)
className = "history-rect";
rect = doc.createElement("rect");
rect.setAttribute("x", Double.toString(0));
rect.setAttribute("width", Double.toString(w));
rect.setAttribute("y", Double.toString(0));
rect.setAttribute("height", Double.toString(h));
rect.setAttribute("class", className);
}
group.appendChild(rect);
Element layoutElement = doc.createElement("g");
layoutElement.setAttribute("transform", "translate("+(getWidth()/2)+","+((height+10)/2)+")");
for (StateContainer c : stateContainers)
{
layoutElement.appendChild(c.toNode(doc));
}
for (TransitionArrow c : transitionArrows)
{
layoutElement.appendChild(c.toNode(doc));
}
group.appendChild(layoutElement);
Element idText;
{
idText = doc.createElement("text");
Size size = TextUtils.getTextSize(thisState.getId(),true,14);
idText.setAttribute("width", Double.toString(size.getWidth()));
idText.setAttribute("height", Double.toString(size.getHeight()));
idText.setAttribute("class", "id-caption");
idText.setAttribute("x", Double.toString(padding));
idText.setAttribute("y", Double.toString(size.getHeight()));
Node text = doc.createTextNode(thisState.getId());
idText.appendChild(text);
}
group.appendChild(idText);
return group;
}
/**
* Extends StateLayout's layout and adds deals with the caption's dimensions.
*/
@Override public void layout()
{
super.layout();
Size size = TextUtils.getTextSize(thisState.getId(),true,14);
width = Math.max(width, size.getWidth()+padding*2);
height += size.getHeight() + padding;
}
/**
* Returns the SCXMLModel state this layout represents.
* @return state
*/
public State getState()
{
return thisState;
}
private State thisState;
private double padding = 5;
}
|
Python
|
UTF-8
| 2,089 | 2.640625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
from __future__ import division, absolute_import
from __future__ import print_function, unicode_literals
import treeano
def to_shared_dict(network):
network.build()
if not network.is_relative():
network = network[network.root_node.name]
vws = network.find_vws_in_subtree(is_shared=True)
name_to_shared = {}
for vw in vws:
assert vw.name not in name_to_shared
# if vw.name != vw.variable.name, preallocated init will break
assert vw.name == vw.variable.name
name_to_shared[vw.name] = vw.variable
return name_to_shared
def to_value_dict(network):
shared_dict = to_shared_dict(network)
return {k: v.get_value() for k, v in shared_dict.items()}
def load_value_dict(network,
value_dict,
strict_keys=True,
ignore_different_shape=False):
"""
strict_keys:
whether or not the network must have the exact same set of keys as the
value_dict
"""
shared_dict = to_shared_dict(network)
value_keys = set(value_dict.keys())
network_keys = set(shared_dict.keys())
if strict_keys:
assert value_keys == network_keys
keys = value_keys
else:
keys = set(value_dict.keys()) & set(shared_dict.keys())
loaded = 0
for k in keys:
shared = shared_dict[k]
old_val = shared.get_value()
new_val = value_dict[k]
if ignore_different_shape:
if old_val.shape != new_val.shape:
continue
else:
assert old_val.shape == new_val.shape
shared.set_value(new_val)
loaded += 1
print("loaded %d keys (out of %d in value dict, %d in network)"
% (loaded, len(value_dict), len(shared_dict)))
def to_preallocated_init(network):
return treeano.inits.PreallocatedInit(to_shared_dict(network))
def num_parameters(network):
"""
returns the number of "parameter"s in a network
"""
vws = network.relative_network().find_vws_in_subtree(tags=["parameter"])
return sum(vw.value.size for vw in vws)
|
Java
|
UTF-8
| 508 | 1.890625 | 2 |
[] |
no_license
|
package com.tangchaoke.electrombilechargingpile.thread;
import okhttp3.Call;
public abstract class MApiResultCallback {
public void inProgress(float progress){};
public abstract void onSuccess(String result);//获取成功
public abstract void onFail(String response);//联网成功,返回的不是成功数据。eg 注册时已存在
public abstract void onError(Call call, Exception exception);//请求出错 OKHTTP 的回调
public abstract void onTokenError(String response);
}
|
Markdown
|
UTF-8
| 14,458 | 2.78125 | 3 |
[] |
no_license
|
# Spark Cluster in Docker / Docker Swarm
This part is to deploy a spark cluster using docker swarm. Implemented in following steps.
1. Deploy spark cluster in docker containers
2. Deploy spark cluster in docker swarm (VM)
3. Using NFS to do the file sharing in all docker machines.
4. Submit and run tasks
5. Support start jupyter notebook in master / manager node.
Code Repository: [spark-in-docker](https://github.com/cchencool/spark-in-docker)
## File Structure:
| directory | description |
| :-----------------------: | :----------------------------------------------------------: |
| bin | docker container mode scripts. All images startup in local machine. |
| sbin | Docker **swarm** deployment scripts. Spark nodes are deployed on docker machines |
| code | some test code |
| docker | files to build docker image and docker-compose.yml |
| docker/config | configuration files for image building and services. |
| docker/pkg | install packages for image building. Including spark / java / hadoop |
| docker/setup.sh | Script for manually setup other configurations. such as jupyter-notebook etc. |
| docker/build-image.sh | Script for image building |
| docker/Dockerfile | Spark image. Base on Ubunut:18.04 |
| docker/docker-compose.yml | spark services in docker swarm |
## Detail
#### 1. Docker Image & Dockerfile
1. The image is based on ubuntu:18.04
2. Install some sofewares: vim, ssh, python3.6, jupyter
3. Configurate ssh trust with self
4. Install JDK & Spark thought local file. (Can also through internet.)
The install packages should be placed in `docker/pkg` directory according to `required_files.txt` in the same directory.
5. Configurate environment variables.
6. Configurate Spark slaves. (This is only necessary when start multiple containers of this image in single machine)
7. Install necessary python packages according to file `docker/config/requirements.txt`.
8. Configurate SSH service.
9. Start SSH and waiting for further instructions.
#### 2. Service Stacks & docker-compose.yml
1. There are 2 services: master & worker. And they use the same image which compiled by the Dockerfile above.
2. Adjust the number of workers by change field `services-worker-deploy-replicas`
3. There an overlay network.
4. There is an docker volume: `/nfsshare:/root/nfsshare` which maps local `/nsfshare` folder to container `/root/nfsshare` folder.
5. To ensure the spark can work base on docker swarm, there are 2 options:
1. - [ ] Using Hadoop with HDFS in docker swarm cluster.
2. - [x] Using NFS to sync files in the cluster.
6. The container resources are configurable in `cpus` & `memory` fild.
7. The Spark resources are configurable by setting environment variables in `environment` fild. The variables' name can be found in [offical documents of Spark](https://spark.apache.org/docs/latest/spark-standalone.html)
#### 3. Scripts
**Scripts under `bin/`**
Scripts under this folder manage containers directly. And all images startup in local machine.
| Script | Usage |
| -------------------------- | ------------------------------------------------------------ |
| get-master-ip.sh | Aquire the spark master node IP address. |
| resize-cluster.sh | Change cluster size. Need to stop **ALL** containers before resize. |
| spark-container-service.sh | Entrance for service control. Follow command start, stop, status, usage. |
| spark-containers-start.sh | Script for **start up** the container mode of spark cluster. |
| spark-containers-status.sh | Script for **checking status** of the container mode of spark cluster. |
| spark-containers-stop.sh | Script for **stop** the container mode of spark cluster. |
**Scripts under `sbin/`**
| Script | Usage |
| ------------------------ | ------------------------------------------------------------ |
| config-swarm.sh | Configurate docker swarm environments. [*1]() |
| spark-cluster-service.sh | Entrance for service control. Commands: deploy, remove, status, usage. |
| spark-cluster-deploy.sh | Script for **start up** the spark cluster in docker swarm mode. |
| spark-cluster-status.sh | Script for **checking status** of the spark cluster in docker swarm mode. |
| spark-cluster-remove.sh | Script for **stop** the spark cluster in docker swarm mode. |
*1: For now, the config-swarm script only support create docker machine in virtual box. If you want to run this on a real cluster of physical machines. You should manually configurate the docker machines on these machine, and adjust the script about the IP addresses.
*2: Normally, only need to use the entrance script to manage the spark cluster service (stacks).
#### 4. Guide of Usage
1. Normally, to take the advantage of Spark computation ability, you should run the spark in a real cluser. In this case, please using the script under `sbin/` to manage your cluster as docker swarm mode.
2. Running command `./config-swarm.sh --create --num=3 --prefix=myvm` to create a virtual environment of 3 machine cluster with [virtualbox](https://www.virtualbox.org/wiki/Downloads) as driver.

3. Configurate share folder (NFS, if physical machine) for **ALL** your docker machines.

4. Run commad `docker-machine restart myvm1 myvm2 myvm3` to restart you docker machines. Making the shared folder effective.
5. By running command `docker-machine ls`, you can check the docker machines you created.
```
➜ sbin git:(master) docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
myvm1 - virtualbox Running tcp://192.168.99.100:2376 v18.09.6
myvm2 - virtualbox Running tcp://192.168.99.101:2376 v18.09.6
myvm3 - virtualbox Running tcp://192.168.99.102:2376 v18.09.6
```
6. By runing the command `eval $(docker-machine env myvm1)`, you can manage your docker machines easier. Or connect your docker machine with command `docker-machine ssh myvm1`
```shell
➜ sbin git:(master) docker-machine env myvm1
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/Users/Chen/.docker/machine/machines/myvm1"
export DOCKER_MACHINE_NAME="myvm1"
# Run this command to configure your shell:
# eval $(docker-machine env myvm1)
➜ sbin git:(master) ✗ eval $(docker-machine env myvm1)
```
7. By running the command `./spark-cluster-service.sh deploy`, the service stacks should be startup and running now. The first time may cost some time for downloading the image.
```shell
➜ sbin git:(master) ✗ ./spark-cluster-service.sh deploy
deploying spark...
Creating network spark_spark-net
Creating service spark_master
Creating service spark_worker
getting information...
spark-master : 192.168.99.100:7077
web UI : 192.168.99.100:8080
data-dir-host : ./../nfsshare
data-dir-master : /root/nfsshare
to start jupyter notebook, run 'docker container exec -it spark_master.1* bash'; then run 'sh /root/install/setup.sh'
jupyter-noteboo : 192.168.99.100:8888
```
8. Using commands `./spark-cluster-service.sh status` or `docker stack ls` or `docker stack ps spark` or `docker service ls` to check the services do startup.
Please notice ***REPLICAS*** field shows ***0/1*** or ***0/2*** and the CURRENT ***STATE*** is ***Preparing n minutes ago***. This is because it takes some time to **download the images** . The image size is **around 1GB**. And all docker machines will need to download the image respectively.
```shell
➜ sbin git:(master) ✗ ./spark-cluster-service.sh status
check spark status...
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
y98c8ywnckl9 spark_worker.1 cchencool/spark:latest myvm3 Running Preparing 7 minutes ago
nf1gzikfybcw spark_master.1 cchencool/spark:latest myvm1 Running Preparing 7 minutes ago
twtjuuqdh8qj spark_worker.2 cchencool/spark:latest myvm2 Running Preparing 7 minutes ago
done
➜ sbin git:(master) ✗ docker stack ls
NAME SERVICES ORCHESTRATOR
spark 2 Swarm
➜ sbin git:(master) ✗ docker stack ps spark
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
y98c8ywnckl9 spark_worker.1 cchencool/spark:latest myvm3 Running Preparing 8 minutes ago
nf1gzikfybcw spark_master.1 cchencool/spark:latest myvm1 Running Preparing 8 minutes ago
twtjuuqdh8qj spark_worker.2 cchencool/spark:latest myvm2 Running Preparing 8 minutes ago
➜ sbin git:(master) ✗ docker service ls
ID NAME MODE REPLICAS IMAGE PORTS
ot7ucdk904ne spark_master replicated 0/1 cchencool/spark:latest *:4040->4040/tcp, *:6066->6066/tcp, *:7077->7077/tcp, *:8080->8080/tcp, *:8888->8888/tcp
f3k81ebll3ny spark_worker replicated 0/2 cchencool/spark:latest *:8081->8081/tcp
```
9. When the spark cluster successfully deployed, you should see ***DESIRED STATE*** becomes to ***Running*** and ***REPLICAS*** becomes to ***1/1*** and ***2/2***:
```shell
➜ sbin git:(master) ✗ ./spark-cluster-service.sh status
check spark status...
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
czie0i2ky43v spark_worker.1 cchencool/spark:latest myvm3 Running Running 5 seconds ago
khcidid7d44m spark_master.1 cchencool/spark:latest myvm1 Running Running 11 seconds ago
yw58robszmo9 spark_worker.2 cchencool/spark:latest myvm2 Running Running 5 seconds ago
done
➜ sbin git:(master) ✗ docker service ls
ID NAME MODE REPLICAS IMAGE PORTS
n3u9w9ej1u12 spark_master replicated 1/1 cchencool/spark:latest *:4040->4040/tcp, *:6066->6066/tcp, *:7077->7077/tcp, *:8080->8080/tcp, *:8888->8888/tcp
ruufeky42eqi spark_worker replicated 2/2 cchencool/spark:latest *:8081->8081/tcp
```
10. Using the infomation printted out by the script to connect spark cluster. Checking the web UI.

11. You can connect to your container using commands below:
```shell
➜ sbin git:(master) ✗ ➜ sbin git:(master) ✗ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4239569e16e0 cchencool/spark:latest "sh -c 'source ~/.ba…" 3 minutes ago Up 3 minutes 7077/tcp spark_master.1.khcidid7d44m32kcfdo8jf7ya
➜ sbin git:(master) ✗ docker container exec -it spark_master.1.khcidid7d44m32kcfdo8jf7ya bash
root@master:~/workspace# ls -al
total 16
drwxr-xr-x 1 root root 4096 May 27 08:59 .
drwx------ 1 root root 4096 May 27 09:03 ..
-rw-r--r-- 1 root root 133 May 27 08:59 log
root@master:~/workspace# pwd
/root/workspace
root@master:~/workspace# cat log
starting org.apache.spark.deploy.master.Master, logging to /opt/spark/logs/spark--org.apache.spark.deploy.master.Master-1-master.out
```
12. When you want to shut down the cluster, using the script `./spark-cluster-service.sh remove`.
```shell
➜ sbin git:(master) ✗ ./spark-cluster-service.sh remove
removing spark...
Removing service spark_master
Removing service spark_worker
Removing network spark_spark-net
success
```
## Notice:
**Data upload**
1. For this demo implementation, just using docker-machine virtualBox as driver. You can directly shareing folder `/nfsshare` with host in the virtual box configuration to simulate the well configurated NFS environment.
2. Should use NFS in production. Shareing `/nfsshare` accross the hosts. This folder is also changeable by modifying the `volumes` of 2 services in the `docker-compose.yml` file.
**Task submission**
1. When use the `spark-cluster-service.sh deploy` command start the spark cluster in docker swarm, it should print out the spark-master, spark web UI addresses.
2. To run a task, no matter in Jupyter Notebook or a single driver program, simply follow the [Spark documentation](https://spark.apache.org/docs/latest/spark-standalone.html) to connect your driver to the spark master.
3. You should be aware and manage the CPU & Memory resources by yourself. To ensure multiple drivers are not blocked when running at same time, you should carefully configurate those resource limitation parameters of you driver programs to avoid running out of resources.
## References:
* [hadoop-cluster-docker](https://github.com/kiwenlau/hadoop-cluster-docker)
* [spark-docker-swarm](https://github.com/testdrivenio/spark-docker-swarm)
|
Python
|
UTF-8
| 282 | 3.4375 | 3 |
[] |
no_license
|
# 09_flush.py
import time
f = open('infos.txt', 'w')
f.write('hello')
f.flush() # 强制清空缓冲区
# for i in range(10000):
# f.write('helloooooo')
# time.sleep(0.01)
print("程序开始睡觉...zzz")
time.sleep(15)
print("程序睡醒了,继续执行")
f.close()
|
Java
|
UTF-8
| 1,723 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package org.robotics.car.examples;
/*
* Copyright 2016 Autonomous Open Source Project
*
*
* 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.
*
*/
import org.robotics.car.controller.MotorController;
/**
* Created by maurice on 3/18/17.
*/
public class TestMotorController {
static MotorController motorController = null;
public static void main(String[] args) throws InterruptedException {
// Get first argument
String terrain = "carpet";
if (args.length > 1 )
terrain = args[1];
System.out.println("Terrain: " + terrain);
motorController = new MotorController(terrain, "M1", "M2", "M3", "M4");
System.out.println("Move forward for a second ..");
motorController.forward();
Thread.sleep(1000);
System.out.println("Turn left for 180 degrees ..");
motorController.left(180);
System.out.println("Move forward for a second ..");
motorController.forward();
Thread.sleep(1000);
System.out.println("Turn right for 180 degrees ..");
motorController.right(180);
motorController.stop();
motorController.uninitialize();
}
}
|
Shell
|
UTF-8
| 521 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
prog=tomcat
JAVA_HOME=${JAVA_HOME}
export JAVA_HOME
CATALANA_HOME=${CATALANA_HOME}
export CATALINA_HOME
case "$1" in
start)
echo "Starting Tomcat..."
$CATALANA_HOME/bin/startup.sh
;;
stop)
echo "Stopping Tomcat..."
$CATALANA_HOME/bin/shutdown.sh
;;
restart)
echo "Stopping Tomcat..."
$CATALANA_HOME/bin/shutdown.sh
sleep 2
echo
echo "Starting Tomcat..."
$CATALANA_HOME/bin/startup.sh
;;
*)
echo "Usage: $prog {start|stop|restart}"
;;
esac
exit 0
|
TypeScript
|
UTF-8
| 523 | 2.734375 | 3 |
[] |
no_license
|
import {Beer, Drink, Wine} from './Drink';
import {Garlic, Onion, Vegetable} from './Vegetable';
export interface RecipeFactory {
create(): Vegetable;
pick(): Drink;
}
export class OnionRecipeFacotry implements RecipeFactory {
public create(): Vegetable {
return new Onion();
}
public pick(): Drink {
return new Wine();
}
}
export class GarlicRecipeFacotry implements RecipeFactory {
public create(): Vegetable {
return new Garlic();
}
public pick(): Drink {
return new Beer();
}
}
|
Go
|
UTF-8
| 282 | 3.296875 | 3 |
[] |
no_license
|
package two_sum
import "fmt"
func twoSum(nums []int, target int) []int {
for k, v := range nums {
for j := k + 1; j < len(nums); j++ {
if v+nums[j] == target {
return []int{k, j}
}
}
}
return nil
}
func main() {
a := twoSum([]int{3, 2, 4}, 6)
fmt.Println(a)
}
|
C
|
ISO-8859-1
| 1,044 | 3.859375 | 4 |
[] |
no_license
|
#include<stdio.h>
#include "fonctions_TP3.h"
void Ecriture(int tab[], int n)
{
int i;
for(i = 0; i < n; i++)
{
printf("%d ", tab[i]);
}
printf("\n");
}
/** On se sert du tableau construit. On sait que 2 est premier.
Puis pour chaque case, on part de la case precedente, et on regarde les entiers suivants.
*/
void nombres_premiers(int premiers[], int n)
{
int i = 2;
int j;
int a;
int k;
for (j = 0; j < n; j++ )
{
a = 1;
for (k = 0; k < j; k++)
{
if( i%premiers[k] == 0)
{
a = 0;s
}
}
if(a)
{
premiers[j] = i;
j++;
}
i++;
}
}
int main()
{
int n;
printf("Entrez un entier suprieur ou egal a 1.\n");
do
{
scanf("%d", &n);
}
while(n < 1);
int premiers[n];
nombres_premiers(premiers, n);
Ecriture(premiers, n);
return 0;
}
|
Python
|
UTF-8
| 362 | 3.875 | 4 |
[] |
no_license
|
# create HTML List
items = ['first string', 'second string']
html_str = "<ul>\n"
for i in range(len(items)):
html_str += "<li>" + items[i] + "</li>\n"
html_str += "</ul>"
print(html_str)
print()
# Udacity Solution
html_str1 = "<ul>\n"
for item in items:
html_str1 += "<li>{}</li>\n".format(item)
html_str1 += "</ul>"
print(html_str1)
|
PHP
|
UTF-8
| 701 | 2.671875 | 3 |
[] |
no_license
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePastQuestionsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('past_questions', function(Blueprint $table)
{
$table->increments('id');
$table->integer('department_id');
$table->integer('level');
$table->integer('semester');
$table->integer('course_code');
$table->integer('type');
$table->date('date');
$table->string('file_path');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('past_questions');
}
}
|
PHP
|
UTF-8
| 2,667 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
<?php
return [
'issuer' => env('PASSPORT_ISSUER', 'passport'),
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour.
|
| You can also set this to null, to yield a never expiring token.
| Some people may want this behaviour for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'ttl' => env('PASSPORT_TTL', 120),
/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks.
|
| You can also set this to null, to yield an infinite refresh time.
| Some may want this instead of never expiring tokens for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
//'refresh_ttl' => env('PASSPORT_REFRESH_TTL', 20160),
'secret' => env('PASSPORT_SECRET', env('APP_KEY','!@#r41T23^$')),
/*
|--------------------------------------------------------------------------
| Fields allowed to be registered
|--------------------------------------------------------------------------
|
| Set validation rules for fields that are allowed to be registered
| Field range: [name,mobile,email]
| Where name, email, mobile must be unique
|
*/
'register_rules' => [
'name' => 'required|string|max:15|unique:passport_users',
'mobile' => 'required|string|max:11|min:11|unique:passport_users',
'email' => 'required|string|email|max:50|unique:passport_users',
],
/*
|--------------------------------------------------------------------------
| Fields allowed to be login
|--------------------------------------------------------------------------
|
| Set validation rules for fields that are allowed to be login
| Field range: [name,mobile,email,'password']
|
*/
'login_rules' => [
'name' => ['required'],
'password' => ['required'],
],
];
|
Python
|
UTF-8
| 12,775 | 2.625 | 3 |
[] |
no_license
|
import torch
import torch.nn as nn
from torch.nn import Parameter
import torch.nn.functional as F
from torch import tanh, sigmoid
from torch.nn.utils.rnn import pad_sequence,pack_padded_sequence,pack_sequence,pad_packed_sequence
class Encoder(nn.Module):
"""
Encoder class for Pointer-Net
"""
def __init__(self, embedding_dim,
hidden_dim,
n_layers,
dropout,
bidir):
"""
Initiate Encoder
:param Tensor embedding_dim: Number of embbeding channels
:param int hidden_dim: Number of hidden units for the LSTM
:param int n_layers: Number of layers for LSTMs
:param float dropout: Float between 0-1
:param bool bidir: Bidirectional
"""
super(Encoder, self).__init__()
self.hidden_dim = hidden_dim//2 if bidir else hidden_dim
self.n_layers = n_layers*2 if bidir else n_layers
self.bidir = bidir
self.lstm = nn.LSTM(embedding_dim,
self.hidden_dim,
n_layers,
dropout=dropout,
bidirectional=bidir)
# Used for propagating .cuda() command
self.h0 = Parameter(torch.zeros(1), requires_grad=False)
self.c0 = Parameter(torch.zeros(1), requires_grad=False)
def forward(self, embedded_inputs, masks,
hidden):
"""
Encoder - Forward-pass
:param Tensor embedded_inputs: Embedded inputs of Pointer-Net
:param Tensor hidden: Initiated hidden units for the LSTMs (h, c)
:return: LSTMs outputs and hidden units (h, c)
"""
# bsz * seq_len * embedding_dim
# embedded_inputs = embedded_inputs.permute(1, 0, 2)
outputs, hidden = self.lstm(embedded_inputs, hidden)
outputs = pad_packed_sequence(outputs, batch_first=True)
return outputs[0], hidden, outputs[1]
def init_hidden(self, embedded_inputs):
"""
Initiate hidden units
:param Tensor embedded_inputs: The embedded input of Pointer-NEt
:return: Initiated hidden units for the LSTMs (h, c)
"""
batch_size = embedded_inputs.batch_sizes[0]
# Reshaping (Expanding)
h0 = self.h0.unsqueeze(0).unsqueeze(0).repeat(self.n_layers,
batch_size,
self.hidden_dim)
c0 = self.h0.unsqueeze(0).unsqueeze(0).repeat(self.n_layers,
batch_size,
self.hidden_dim)
nn.init.uniform_(h0, -1, 1)
nn.init.uniform_(c0, -1, 1)
return h0, c0
class Attention(nn.Module):
"""
Attention model for Pointer-Net
"""
def __init__(self, input_dim,
hidden_dim):
"""
Initiate Attention
:param int input_dim: Input's diamention
:param int hidden_dim: Number of hidden units in the attention
"""
super(Attention, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.input_linear = nn.Linear(input_dim, hidden_dim)
self.context_linear = nn.Conv1d(input_dim, hidden_dim, 1, 1)
self.V = Parameter(torch.FloatTensor(hidden_dim), requires_grad=True)
self._inf = Parameter(torch.FloatTensor([float('-inf')]), requires_grad=False)
self.tanh = tanh
self.softmax = nn.Softmax(dim=-1)
# Initialize vector V
nn.init.uniform_(self.V, -1, 1)
def forward(self, input,
context,
mask):
"""
Attention - Forward-pass
:param Tensor input: Hidden state h
:param Tensor context: Attention context
:param ByteTensor mask: Selection mask
:return: tuple of - (Attentioned hidden state, Alphas)
"""
# (batch, hidden_dim, seq_len)
inp = self.input_linear(input).unsqueeze(2).expand(-1, -1, context.size(1))
seq_len = inp.size(2)
# (batch, hidden_dim, seq_len)
context = context.permute(0, 2, 1)
ctx = self.context_linear(context)
# (batch, 1, hidden_dim)
V = self.V.unsqueeze(0).expand(context.size(0), -1).unsqueeze(1)
# (batch, seq_len)
att = torch.bmm(V, self.tanh(inp + ctx)).squeeze(1)
self.inf = self._inf.expand(*mask.size())
attn = self.softmax(att)
if len(att[mask]) > 0:
att[mask] = self.inf[mask]
alpha = self.softmax(att)
# smooth
# alpha = torch.where(torch.isnan(alpha), torch.full_like(alpha, 0), alpha)
hidden_state = torch.bmm(ctx, alpha.unsqueeze(2)).squeeze(2)
return hidden_state, alpha, attn
def init_inf(self, mask_size):
self.inf = self._inf.expand(mask_size[1])
class Decoder(nn.Module):
"""
Decoder model for Pointer-Net
"""
def __init__(self, embedding_dim,
hidden_dim):
"""
Initiate Decoder
:param int embedding_dim: Number of embeddings in Pointer-Net
:param int hidden_dim: Number of hidden units for the decoder's RNN
"""
super(Decoder, self).__init__()
self.embedding_dim = embedding_dim
self.hidden_dim = hidden_dim
self.input_to_hidden = nn.Linear(embedding_dim, 4 * hidden_dim)
self.hidden_to_hidden = nn.Linear(hidden_dim, 4 * hidden_dim)
self.hidden_out = nn.Linear(hidden_dim * 2, hidden_dim)
self.att = Attention(hidden_dim, hidden_dim)
# Used for propagating .cuda() command
# self.mask = Parameter(torch.ones(1), requires_grad=False)
self.runner = Parameter(torch.arange(500), requires_grad=False)
def forward(self,
embedded_inputs,
decoder_input,
hidden,
context,
masks):
"""
Decoder - Forward-pass
:param Tensor embedded_inputs: Embedded inputs of Pointer-Net
:param Tensor decoder_input: First decoder's input
:param Tensor hidden: First decoder's hidden states
:param Tensor context: Encoder's outputs
:return: (Output probabilities, Pointers indices), last hidden state
"""
batch_size = embedded_inputs.batch_sizes[0]
seq_lens = masks.sum(dim=1)
seq_idx = torch.Tensor([seq_lens[:i].sum().item() for i in range(batch_size + 1)]).to(seq_lens.device)
input_length = max(seq_lens)
# # (batch, seq_len)
# mask = self.mask.repeat(input_length).unsqueeze(0).repeat(batch_size, 1)
self.att.init_inf(masks.size())
# Generating arange(input_length + 1), broadcasted across batch_size
runner = self.runner[:input_length].unsqueeze(0).long()
# runner = runner.unsqueeze(0).expand(batch_size, -1).long()
def step(x, hidden, cxt, msk):
"""
Recurrence step function
:param Tensor x: Input at time t
:param tuple(Tensor, Tensor) hidden: Hidden states at time t-1
:return: Hidden states at time t (h, c), Attention probabilities (Alpha)
"""
# Regular LSTM
h, c = hidden
gates = self.input_to_hidden(x) + self.hidden_to_hidden(h)
input, forget, cell, out = gates.chunk(4, 1)
input = sigmoid(input)
forget = sigmoid(forget)
cell = tanh(cell)
out = sigmoid(out)
c_t = (forget * c) + (input * cell)
h_t = out * tanh(c_t)
# Attention section
hidden_t, output, attn = self.att(h_t, cxt, torch.eq(msk, 0))
# output is softmaxed attn score
hidden_t = tanh(self.hidden_out(torch.cat((hidden_t, h_t), 1)))
return hidden_t, c_t, output, attn
# Recurrence loop
outputs = []
pointers = []
atts = []
for idx in range(batch_size):
output = []
pointer = []
att = []
inp = decoder_input[idx].unsqueeze(0)
hid = (hidden[0][idx].unsqueeze(0), hidden[1][idx].unsqueeze(0))
length = seq_lens[idx].item()
cxt = context[idx][:length].unsqueeze(0)
msk = masks[idx][:length].unsqueeze(0)
# import pdb; pdb.set_trace()
emb = embedded_inputs.data[int(seq_idx[idx].item()) : int(seq_idx[idx + 1].item())].unsqueeze(0)
for _ in range(seq_lens[idx]):
h_t, c_t, outs, attn = step(inp, hid, cxt, msk)
hid = (h_t, c_t)
# Masking selected inputs
masked_outs = outs * msk
# Get maximum probabilities and indices
max_probs, indices = masked_outs.max(1)
one_hot_pointers = (runner[0][:length] == indices.unsqueeze(1).expand(-1, outs.size()[1])).float()
# Update mask to ignore seen indices
msk = msk * (1 - one_hot_pointers)
# Get embedded inputs by max indices
embedding_mask = one_hot_pointers.unsqueeze(2).expand(-1, -1, self.embedding_dim).byte()
inp = emb[embedding_mask.bool()].unsqueeze(0)
# warning: may cause problem because outs is the total softmax rather than softmax over unseened indices
output.append(outs)
att.append(attn)
pointer.append(indices)
outputs.append(torch.stack(output).permute(1, 0, 2))
atts.append(torch.stack(att).permute(1, 0, 2))
pointers.append(torch.stack(pointer).transpose(0, 1))
assert len(outputs) == batch_size
# add another assert
return (outputs, pointers), atts, hidden
class PointerNet(nn.Module):
"""
Pointer-Net
"""
def __init__(self, embedding_dim,
hidden_dim,
lstm_layers,
dropout,
bidir=False):
"""
Initiate Pointer-Net
:param int embedding_dim: Number of embbeding channels
:param int hidden_dim: Encoders hidden units
:param int lstm_layers: Number of layers for LSTMs
:param float dropout: Float between 0-1
:param bool bidir: Bidirectional
"""
super(PointerNet, self).__init__()
self.embedding_dim = embedding_dim
self.bidir = bidir
# self.embedding = nn.Linear(2, embedding_dim)
self.encoder = Encoder(embedding_dim,
hidden_dim,
lstm_layers,
dropout,
bidir)
self.decoder = Decoder(embedding_dim, hidden_dim)
# change decoder_input into history item embedding
# decoder_input0 <go>
# requires_grad = True or False ?
self.decoder_input0 = Parameter(torch.FloatTensor(embedding_dim), requires_grad=True)
# Initialize decoder_input0
nn.init.uniform_(self.decoder_input0, -1, 1)
def forward(self, inputs, masks, history=None):
"""
PointerNet - Forward-pass
:param Tensor inputs: Input sequence
:param Tensor history: History sequence
:return: Pointers probabilities and indices
"""
batch_size = inputs.batch_sizes[0]
decoder_input0 = self.decoder_input0.unsqueeze(0).expand(batch_size, -1)
# decoder_input0 = torch.mean(history, dim=1)
embedded_inputs = inputs.to(decoder_input0.device)
# embedded_inputs = self.embedding(inputs).view(batch_size, input_length, -1)
masks = masks.to(decoder_input0.device)
encoder_hidden0 = self.encoder.init_hidden(embedded_inputs)
encoder_outputs, encoder_hidden, seq_lens = self.encoder(embedded_inputs, masks, encoder_hidden0)
if self.bidir:
decoder_hidden0 = (torch.cat([_ for _ in encoder_hidden[0][-2:]], dim=-1),
torch.cat([_ for _ in encoder_hidden[1][-2:]], dim=-1))
else:
decoder_hidden0 = (encoder_hidden[0][-1],
encoder_hidden[1][-1])
(outputs, pointers), atts, decoder_hidden = self.decoder(embedded_inputs,
decoder_input0,
decoder_hidden0,
encoder_outputs,
masks)
return outputs, pointers, atts
|
Ruby
|
UTF-8
| 1,275 | 2.671875 | 3 |
[] |
no_license
|
require 'rails_helper'
RSpec.describe Competition do
describe 'relationships' do
it {should have_many(:entries)}
it {should have_many(:teams).through(:entries)}
end
before(:each) do
@competition1 = Competition.create!(name: 'Big Bowl', location: 'Atlanta', sport: 'Soccer')
@competition2 = Competition.create!(name: 'Big Trophy', location: 'Alberta', sport: 'Tennis')
@team1 = Team.create!(nickname: 'Buzzers', hometown: 'Miami')
@team2 = Team.create!(nickname: 'Hawks', hometown: 'Chicago')
@team3 = Team.create!(nickname: 'Mustangs', hometown: 'Cleveland')
@player1 = @team1.players.create!(name: 'Bob', age: 12)
@player2 = @team1.players.create!(name: 'Hannah', age: 14)
@player3 = @team1.players.create!(name: 'Bert', age: 16)
@player4 = @team2.players.create!(name: 'Lou', age: 13)
@player5 = @team2.players.create!(name: 'Carrie', age: 15)
@player6 = @team2.players.create!(name: 'Sam', age: 14)
@player7 = @team3.players.create!(name: 'Tori', age: 14)
@competition1.teams << [@team1, @team2]
@competition2.teams << [@team1, @team3]
end
describe 'instance methods' do
it 'can calculate average age of entered players' do
expect(@competition1.average_age).to eq(14.0)
end
end
end
|
Java
|
UTF-8
| 3,526 | 2.140625 | 2 |
[] |
no_license
|
package com.zte.html5.sysman.roleresource;
import java.util.*;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.zte.html5.sysman.resource.ResourceService;
/**
*服务类
*/
@Service
public class RoleResourceService implements IRoleResourceService{
@Autowired
private RoleResourceMapper roleResourceDAO = null;
public void setRoleResourceDAO(RoleResourceMapper roleResourceDAO)
{
this.roleResourceDAO = roleResourceDAO;
}
/**
* 根据主键获取实体对象
*/
public RoleResource get(java.lang.Long id) throws Exception
{
return roleResourceDAO.get(id);
}
/**
* 获取符合条件的实体列表,按指定属性排序
*/
public List<RoleResource> getList(Map<String, Object> map,String orderField,String order) throws Exception
{
List<RoleResource> list = null;
map.put("orderField", orderField);
map.put("order", order);
list = roleResourceDAO.getList(map);
return list;
}
/**
* 获取符合条件的实体列表,按指定属性排序
*/
public List<RoleResource> getRoleResource(Map<String, Object> map,String orderField,String order) throws Exception
{
List<RoleResource> list = null;
map.put("orderField", orderField);
map.put("order", order);
list = roleResourceDAO.getRoleResource(map);
return list;
}
/**
* 删除指定记录
*/
@Transactional(propagation = Propagation.SUPPORTS,isolation=Isolation.READ_UNCOMMITTED)
public int delete(java.lang.Long id) throws Exception
{
return roleResourceDAO.delete(id);
}
/**
* 删除指定角色权限
*/
@Transactional(propagation = Propagation.SUPPORTS,isolation=Isolation.READ_UNCOMMITTED)
public int deleteRole(java.lang.Long roleId) throws Exception
{
return roleResourceDAO.deleteRole(roleId);
}
/**
* 新增指定记录
*/
@Transactional(propagation = Propagation.SUPPORTS,isolation=Isolation.READ_UNCOMMITTED)
public int insert(RoleResource entity) throws Exception
{
return roleResourceDAO.insert(entity);
}
/**
* 修改指定记录
*/
@Transactional(propagation = Propagation.SUPPORTS,isolation=Isolation.READ_UNCOMMITTED)
public int update(RoleResource entity) throws Exception
{
return roleResourceDAO.update(entity);
}
/**
* 获取符合条件的记录数量
*/
public long getCount(Map<String, Object> map,String orderField,String order) throws Exception
{
long count = 0L;
//map.put("orderField", orderField);
//map.put("order", order);
count = roleResourceDAO.getCount(map);
return count;
}
/**
* 获取符合条件的记录列表,先按指定属性排序,在分页
*/
public List<RoleResource> getPage(Map<String, Object> map,String orderField,String order,Long page,Long rows) throws Exception
{
List<RoleResource> list = null;
map.put("orderField", orderField);
map.put("order", order);
map.put("startRow", (page-1)*rows);
map.put("rowSize", rows);
list = roleResourceDAO.getPage(map);
return list;
}
}
|
Java
|
UTF-8
| 2,528 | 2.71875 | 3 |
[] |
no_license
|
package com.lucevent.newsup.backend.utils;
import com.lucevent.newsup.data.util.News;
import com.lucevent.newsup.data.util.NewsArray;
import com.lucevent.newsup.data.util.Site;
import com.lucevent.newsup.data.util.SiteLanguage;
import com.lucevent.newsup.data.util.Tags;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
public class UpdateMessageCreator {
private static final String applink = "https://play.google.com/store/apps/details?id=com.lucevent.newsup";
public static void generateUpdateNews(Site site, HttpServletResponse resp) throws IOException
{
StringBuilder title = new StringBuilder();
StringBuilder description = new StringBuilder();
String content = generateContent(site);
switch (site.getLanguage() << SiteLanguage.shift) {
case SiteLanguage.SPANISH:
title.append("Actualiza ya a la \u00FAltima versi\u00F3n de NewsUp");
description.append("Click para m\u00E1s informaci\u00F3n");
break;
case SiteLanguage.CATALAN:
title.append("Actualitza ja a la \u00FAltima versi\u00F3 de NewsUp");
description.append("Click per a m\u00E9s informaci\u00F3");
break;
default:
title.append("Update to the latest version of NewsUp");
description.append("Click for more info");
}
News news = new News(title.toString(), applink, description.toString(), System.currentTimeMillis(), null, new Tags(), -1, -1, -1);
news.content = content;
NewsArray na = new NewsArray();
na.add(news);
resp.getWriter().println(BackendParser.toEntry(na).toString());
}
public static String generateContent(Site site)
{
switch (site.getLanguage() << SiteLanguage.shift) {
case SiteLanguage.SPANISH:
return "<p>Es necesario que actualizes la aplicaci\u00F3n para poder seguir utiliz\u00E1ndola.</p>"
+ "<p><a href='" + applink + "'>Puedes actualizarla directamente desde este enlace</a><p>";
case SiteLanguage.CATALAN:
return "<p>Es necessari que actualitzis la aplicaci\u00F3 per poder seguir utilitzant-la.</p>"
+ "<p><a href='" + applink + "'>Pots actualitzar-la directament des d'aquest enlla\u00E7</a></p>";
default:
return "<p>To keep using this app is necessary that you update to the last version.</p>"
+ "<p><a href='" + applink + "'>You can directly update it through this link</a></p>";
}
}
public static boolean needsUpdate(String version)
{
if (version != null && !version.isEmpty()) {
String[] vs = version.split("\\.");
return !vs[0].equals("2");
}
return true;
}
}
|
PHP
|
UTF-8
| 3,845 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
<?php
class Kohana_Migration_Column {
protected $name;
protected $type;
protected $traits;
protected $size;
protected $default;
protected $null;
protected $comment;
//:float, :decimal, :time, :date, :binary, :boolean.
protected static $types = array(
'string' => array(
'type' => 'VARCHAR(%d)',
'size' => 255,
'null' => true,
'default' => null,
'comment' => null,
'traits' => array(),
'default_traits' => array()
),
'integer' => array(
'type' => 'INTEGER(%d)',
'size' => 10,
'null' => true,
'default' => null,
'comment' => null,
'traits' => array(
'unsigned' => 'UNSIGNED',
'auto_increment' => 'AUTO_INCREMENT',
),
'default_traits' => array()
),
// TODO: http://www.ispirer.com/doc/sqlways39/Output/SQLWays-1-211.html
'text' => array(
'type' => 'TEXT',
'size' => null,
'null' => true,
'default' => null,
'comment' => null,
'traits' => array(),
'default_traits' => array()
),
'blob' => array(
'type' => 'TEXT',
'size' => null,
'null' => true,
'default' => null,
'comment' => null,
'traits' => array(),
'default_traits' => array()
),
'datetime' => array(
'type' => 'DATETIME',
'size' => null,
'null' => true,
'default' => null,
'comment' => null,
'traits' => array(),
'default_traits' => array()
),
'timestamp' => array(
'type' => 'INTEGER(10)', // Why not TIMESTAMP? Because Kohana defaults to INT(10)
'size' => null,
'null' => false,
'default' => '0',
'comment' => null,
'traits' => array(
'unsigned' => 'UNSIGNED',
),
'default_traits' => array(
'unsigned' => true
)
),
'decimal' => array(
'type' => 'DECIMAL(%d,%d)',
'size' => array( 5, 2 ),
'null' => true,
'default' => null,
'comment' => null,
'traits' => array(),
'default_traits' => array()
),
'float' => array(
'type' => 'FLOAT(%d,%d)',
'size' => array( 5, 2 ),
'null' => true,
'default' => null,
'comment' => null,
'traits' => array(),
'default_traits' => array()
),
);
public static function isType ( $name ) {
return array_key_exists( $name, self::$types );
}
public function __construct( $name, $type, $traits = null ) {
$this->name = $name;
$this->type = $type;
$this->size = self::$types[$type]['size'];
$this->null = self::$types[$type]['null'];
$this->default = self::$types[$type]['default'];
$this->comment = self::$types[$type]['comment'];
$this->traits = array();
if( ! is_null( $traits ) ) {
foreach( $traits as $key => $trait ) {
switch( $key ) {
case 'size':
$this->size = intval( $trait );
break;
case 'null':
$this->null = $trait;
break;
case 'default':
$this->default = $trait;
break;
case 'comment':
$this->comment = $trait;
break;
default:
$this->traits[$key] = $trait;
break;
}
}
}
}
public function toSQL () {
$chunks = array(
"`{$this->name}`",
vsprintf( self::$types[$this->type]['type'], $this->size )
);
$requested_traits = array_merge( self::$types[$this->type]['default_traits'], $this->traits );
foreach( $requested_traits as $key => $trait ) {
if( ( $trait === true && array_key_exists( $key, self::$types[$this->type]['traits'] ) ) ) {
$chunks[] = self::$types[$this->type]['traits'][$key];
}
}
if( ! $this->null ) { $chunks[] = 'NOT NULL'; }
if( ! is_null( $this->default ) ) { $chunks[] = "DEFAULT '{$this->default}'"; } //! TODO: Escaping here?
if( ! is_null( $this->comment ) ) { $chunks[] = "COMMENT '{$this->comment}'"; } //! TODO: Escaping here?
return implode( ' ', $chunks );
}
}
|
Java
|
UTF-8
| 663 | 2.484375 | 2 |
[] |
no_license
|
package br.com.server_rmi;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import br.com.calculator.Calculator;
import br.com.calculator.CalculatorImpl;
public class CalculatorServer implements Remote {
public CalculatorServer(){
try {
Calculator calculator = new CalculatorImpl();
LocateRegistry.createRegistry(1021);
Naming.rebind("//localhost:1021/CalculatorService", calculator);
} catch (Exception e) {
System.out.println("Deu ruim!" + e);
}
}
public static void main(String[] args) {
new CalculatorServer();
}
}
|
Python
|
UTF-8
| 26,222 | 2.734375 | 3 |
[] |
no_license
|
#! /usr/bin/env python
#
# Copyright 2018 (c) Pointwise, Inc.
# All rights reserved.
#
# This sample Python script is not supported by Pointwise, Inc.
# It is provided freely for demonstration purposes only.
# SEE THE WARRANTY DISCLAIMER AT THE BOTTOM OF THIS FILE.
#
"""
This module provides a wrapper around TCP communication of a client with
a Glyph Server.
Example:
from pointwise import GlyphClient, GlyphError
glf = GlyphClient()
if glf.connect():
try:
result = glf.eval('pw::Application getVersion')
print('Pointwise version is {0}'.format(result))
except GlyphError as e:
print('Error in command {0}\n{1}'.format(e.command, e))
elif glf.is_busy():
print('The Glyph Server is busy')
elif glf.auth_failed():
print('Glyph Server authentication failed')
else:
print('Failed to connect to the Glyph Server')
"""
import os, time, socket, struct, errno, sys, re, platform
class GlyphError(Exception):
""" This exception is raised when a command passed to the Glyph Server
encounters an error.
"""
def __init__(self, command, message, *args, **kwargs):
Exception.__init__(self, message, *args, **kwargs)
self.command = command
class NoLicenseError(Exception):
""" This exception is raised when a Glyph server subprocess could
not acquire a valid Pointwise license.
"""
def __init__(self, message, *args, **kwargs):
Exception.__init__(self, message, *args, **kwargs)
class GlyphClient(object):
""" This class is a wrapper around TCP client communications with a
Glyph Server. Optionally, it can start a batch Glyph Server process
as a subprocess (which consumes a Pointwise license). To start
a server subprocess, initialize the GlyphClient with port = 0.
For Windows platforms, the default program to run is 'tclsh'. For
Linux and Mac OS platforms, the default program is 'pointwise -b'.
(Optionally, the 'prog' argument may be specified to indicate the
program or shell script to run as the batch Glyph server process.
This is typically used in environments where multiple versions of
Pointwise are installed.)
"""
def __init__(self, port=None, auth=None, version=None, host='localhost', \
callback=None, prog=None, timeout=10):
""" Initialize a GlyphClient object
Args:
port (str): the port number of the Glyph Server to connect to.
If the port is not given, it defaults to the environment
variable PWI_GLYPH_SERVER_PORT, or 2807 if not defined.
If port is 0, a Pointwise batch subprocess will be started
if a license is available.
auth (str): the authorization code of the Glyph Server. If the
auth is not given, it defaults to the environment variable
PWI_GLYPH_SERVER_AUTH, or an empty string if not defined.
version (str): the Glyph version number to use for
compatibility. The string should be of the form X.Y.Z
where X, Y, and Z are positive integer values. The Y and
Z values are optional and default to a zero value. A blank
value always uses the current version.
host (str): the host name of the Glyph Server to connect to.
The default value is 'localhost'.
callback (func): a callback function that takes a string
parameter that represents the response messages from the
Glyph Server. The default callback is None.
prog (str): The batch executable program to use when port is 0.
If prog is None, 'tclsh' will be used on Windows platforms
and 'pointwise -b' will be used for Linux/macOS platforms.
Otherwise the given program will be used to execute the
Pointwise batch mode.
timeout (float): The number of seconds to continue to try to
connect to the server before giving up. The default timeout
is 10 seconds.
"""
self._port = port
self._auth = auth
self._host = host
self._version = version
self._timeout = timeout
self._socket = None
self._busy = False
self._auth_failed = False
self._serverVersion = None
if self._port is None:
self._port = os.environ.get('PWI_GLYPH_SERVER_PORT', '2807')
if self._auth is None:
self._auth = os.environ.get('PWI_GLYPH_SERVER_AUTH', '')
if self._port == 0:
self._startServer(callback, prog)
def __del__(self):
if hasattr(self, "_server") and self._server is not None:
self._server.stdout = None
self._server.stderr = None
self._server.stdin = None
self.close()
def __eq__(self, other):
return self is other
def __enter__(self):
""" When using GlyphClient as a context manager, connect and return self
"""
if not self.connect():
if self._auth_failed:
raise GlyphError('connect', 'Glyph Server AUTH failed')
elif self._busy:
raise GlyphError('connect', 'Glyph Server BUSY')
else:
raise GlyphError('connect', 'Could not connect to Glyph Server')
return self
def __exit__(self, *args):
""" When using GlyphClient as a context manager, disconnect """
self.close()
def __str__(self):
s = 'GlyphClient(' + str(self._host) + '@' + str(self._port) + \
') connected=' + str(self.is_connected())
if self.is_connected():
s = s + ' Server=' + self._serverVersion
return s
def connect(self, retries=None):
""" Connect to a Glyph server at the given host and port.
Args:
retries (int): the number of times to retry the connection
before giving up. DEPRECATED: if not None, retries will be
used to determine a suitable value for timeout.
Returns:
bool: True if successfully connected, False otherwise. If an
initial connection is made, but the Glyph Server is busy,
calling is_busy() will return True.
"""
self._closeSocket()
self._busy = False
self._auth_failed = False
timeout = self._timeout
if retries is not None:
timeout = 0.1 * retries
start = time.time()
while self._socket is None and time.time() - start < timeout:
try:
self._socket = self._connect(self._host, self._port)
except:
self._socket = None
if self._socket is None:
time.sleep(0.1) # sleep for a bit before retry
if self._socket is None:
return False
self._send('AUTH', self._auth)
response = self._recv()
if response is None:
self._socket.close()
self._socket = None
return False
rtype, payload = response
self._auth_failed = (rtype == 'AUTHFAIL')
self._busy = (rtype == 'BUSY')
if rtype != 'READY':
self.close()
else:
problem = None
if self._version is not None:
try:
self.control('version', self._version)
except Exception as excCode:
problem = excCode
self._serverVersion = self.eval('pw::Application getVersion')
if problem is not None:
m = re.search('Pointwise V(\d+).(\d+)', self._serverVersion)
if len(m.groups()) == 2:
try:
serverVers = int(m.groups()[0]) * 10 + \
int(m.groups()[1])
except:
serverVers = 0
if serverVers >= 183:
self.close()
raise problem
return self._socket is not None
def is_busy(self):
""" Check if the reason for the last failed attempt to connect() was
because the Glyph Server is busy.
Returns:
bool: True if the last call to connect failed because the
Glyph Server was busy, False otherwise.
"""
return self._busy
def auth_failed(self):
""" Check if the reason for the last failed attempt to connect() was
because the Glyph Server authentication failed.
Returns:
bool: True if the last call to connect failed because the
Glyph Server authentication failed, False otherwise.
"""
return self._auth_failed
def eval(self, command):
""" Evaluate a Glyph command on the Glyph Server, including nested
commands and variable substitution.
Args:
command (str): A Glyph command to be evaluated on the
Glyph Server.
Returns:
str: The result from evaluating the command on the Glyph Server.
Raises:
GlyphError: If the command evaluation on the Glyph Server
resulted in an error.
"""
return self._sendcmd('EVAL', command)
def command(self, command):
""" Execute a Glyph command on the Glyph Server, with no support
for nested commands and variable substitution.
Args:
command (str): A JSON encoded string of an array of a
Glyph command and the parameters to be executed.
Returns:
str: The JSON encoded string result from executing the
command on the Glyph Server.
Raises:
GlyphError: If the command execution on the Glyph Server
resulted in an error.
"""
return self._sendcmd('COMMAND', command)
def control(self, setting, value=None):
""" Send a control message to the Glyph Server
Args:
setting (str): The name of the control setting
value (str): The value to set the setting to. If none the value
will only be queried.
Returns:
str: The current value of the control setting
Raises:
GlyphError: If the control setting or the value is invalid.
"""
command = setting
if value is not None:
command += '=' + value
return self._sendcmd('CONTROL', command)
def get_glyphapi(self):
""" Creates and returns a GlyphAPI object for this client
Returns:
GlyphAPI object for automatic Glyph command execution
through this client connection
"""
from pointwise import glyphapi
if not self.is_connected():
self.connect()
if self.is_connected():
return glyphapi.GlyphAPI(glyph_client=self)
else:
raise GlyphError('GlyphAPI',
'The client is not connected to a Glyph Server')
def is_connected(self):
""" Check if there is a connection to the Glyph Client
Returns:
True if there is a valid connection, False otherwise.
"""
result = False
try:
result = self._socket is not None and self.ping()
except:
result = False
return result
def ping(self):
""" Ping the Glyph Server
Returns:
bool: True if the the Glyph Server was successfully pinged,
False otherwise.
"""
result = False
try:
result = self._sendcmd('PING', '') == "OK"
except:
result = False
return result
def close(self):
""" Close the connection with the Glyph server """
if hasattr(self, "_server") and self._server is not None and \
hasattr(self, "_socket") and self._socket is not None:
try:
# request graceful shutdown of server
self.eval("exit")
except socket.error as err:
pass
self._closeSocket()
if hasattr(self, "_server") and self._server is not None:
# safe to call even if server has already shut down
self._server.terminate()
self._server.wait()
# resource warnings may occur if pipes are not closed from the
# client side (typically on Windows)
if self._server.stdout is not None:
try:
self._server.stdout.close()
self._server.stdout = None
except IOError:
pass
# wait for the pipe reader thread to finish
if self._othread is not None:
self._othread.join(0.5)
del self._othread
self._othread = None
if self._server.stdin is not None:
try:
self._server.stdin.close()
self._server.stdin = None
except IOError:
pass
if self._server.stderr is not None:
try:
self._server.stderr.close()
self._server.stderr = None
except IOError:
pass
self._server = None
def disconnect(self):
""" Close the connection with the Glyph server """
self.close()
def _connect(self, host, port):
""" Helper function for connecting a socket to the given host and port
"""
# try to connect using both IPv4 and IPv6
s = None
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except (socket.error, OSError) as msg:
s = None
continue
try:
s.connect(sa)
except (socket.error, OSError) as msg:
s.close()
s = None
continue
break
return s
def _sendcmd(self, type, command):
""" Helper function for sending a command to the Glyph Server """
if self._socket is None:
raise GlyphError(command,
'The client is not connected to a Glyph Server')
try:
self._send(type, command)
response = self._recv()
except socket.error as e:
# Python 3: BrokenPipeError
if e.errno == errno.EPIPE:
raise GlyphError(command,
'The Glyph Server connection is closed')
else:
raise
if response is None:
if not self._socket.fileno() == -1:
# socket is closed, assume command ended server session
return None
raise GlyphError(command, 'No response from the Glyph Server')
type, payload = response
if type != 'OK':
raise GlyphError(command, payload)
return payload
def _send(self, type, payload):
""" Helper function for sending a message on the socket """
message_bytes = type.encode('utf-8').ljust(8) + payload.encode('utf-8')
message_length = struct.pack('!I', len(message_bytes))
self._socket.sendall(message_length)
self._socket.sendall(message_bytes)
def _recv(self):
""" Helper function for receiving a message on the socket """
message_length = self._recvall(4)
if message_length is None:
return None
# Python 2: 'bytes' is an alias for 'str'
# Python 3: 'bytes' is an immutable bytearray
message_length = struct.unpack('!I', bytes(message_length))[0]
if message_length == 0:
return ('', '')
message_bytes = self._recvall(message_length)
if message_bytes is None:
return None
# Python 2: convert decoded bytes (type 'unicode') to string (type
# 'str')
type = str(message_bytes[0:8].decode('utf-8')).strip()
payload = str(message_bytes[8:].decode('utf-8'))
return (type, payload)
def _recvall(self, size):
""" Helper function to recv size bytes or return None if EOF is hit """
data = bytearray()
while len(data) < size:
packet = self._socket.recv(size - len(data))
if not packet:
return None
data.extend(packet)
return data
def puts(self, *args):
self.eval("puts {%s}" % ' '.join(args))
def _closeSocket(self):
""" Close the connection with the Glyph server """
if self._socket:
if not self._socket.fileno() == -1:
try:
self._socket.shutdown(socket.SHUT_RDWR)
except:
None
self._socket.close()
del self._socket
self._socket = None
def _startServer(self, callback, prog):
""" Create a server if possible on any open port """
self._server = None
self._othread = None
try:
if prog is None:
if platform.system() == 'Windows':
prog = ['tclsh']
else:
prog = ['pointwise', '-b']
elif isinstance(prog, tuple):
prog = list(prog)
elif not isinstance(prog, list):
prog = [prog]
import shutil
if not hasattr(shutil, 'which'):
# Python 3: shutil.which exists
shutil.which = __which__
target = shutil.which(prog[0])
if target is None:
raise GlyphError('server', '%s not found in path' % prog[0])
prog[0] = target
# find an open port
try:
tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tsock.settimeout(0)
tsock.bind(('', 0))
self._port = tsock.getsockname()[1]
finally:
tsock.close()
time.sleep(0.1)
if callback is None:
def __default_callback__(*args):
pass
callback = __default_callback__
# start the server subprocess
import subprocess
self._server = subprocess.Popen(prog, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
self._server.stdin.write(bytearray((
"if [catch {package require PWI_Glyph} server_ver] {\n" +
" puts {Could not load Glyph package. Ensure that the " +
"Pointwise version of tclsh is the only one in your PATH.}\n" +
" puts $server_ver\n" +
" exit\n" +
"}\n" +
"if { [package vcompare $server_ver 2.18.2] < 0 } {" +
" puts {Server must be 18.2 or higher}\n"
" exit\n"
"}\n" +
"puts \"GLYPH_SERVER_VERSION: $server_ver\"\n" +
"pw::Script setServerPort %d\n" +
"puts \"Server: [pw::Application getVersion]\"\n" +
"pw::Script processServerMessages -timeout %s\n" +
"puts \"Server: Subprocess completed.\"\n") %
(self._port, str(int(self._timeout))), "utf-8"))
self._server.stdin.flush()
ver_re = re.compile(r"GLYPH_SERVER_VERSION: (\d+\.\d+\.\d+)")
lic_re = re.compile(r".*unable to obtain a license.*")
# process output from the server until we can determine
# that the server is running and a valid license was obtained
ver = str(self._server.stdout.readline().decode('utf-8'))
ver_match = ver_re.match(ver)
lic_match = lic_re.match(ver)
# Read the server output, looking for a special line with the
# server version, or a line with a known license failure message,
# or until EOF. Print all output preceding any of these conditions.
if ver_match is None and lic_match is None:
# Note: not strictly Python 2 compatible, but deemed acceptable
print(ver)
for ver in iter(self._server.stdout.readline, b''):
ver = str(ver.decode('utf-8'))
ver_match = ver_re.match(ver)
if ver_match is not None:
break
lic_match = lic_re.match(ver)
if lic_match is not None:
break
print(ver)
if lic_match is not None or ver_match is None:
# license or other failure
for line in iter(self._server.stdout.readline, b''):
callback(str(line.decode('utf-8')))
self.close()
if lic_match is not None:
raise NoLicenseError(ver)
else:
raise GlyphError('server', ver)
# capture stdout/stderr from the server
import threading
class ReaderThread(threading.Thread):
def __init__(self, ios, callback):
threading.Thread.__init__(self)
self._ios = ios
self._error = None
self._cb = callback
self.daemon = True
def run(self):
try:
for line in iter(self._ios.readline, b''):
# Python 2: convert decoded bytes to 'str'
self._cb(str(line.decode('utf-8')))
except Exception as ex:
self._error = str(ex)
self._ios = None
self._othread = ReaderThread(self._server.stdout, callback)
self._othread.start()
except Exception as ex:
if self._server is not None:
self._server.kill()
self._server.wait()
self._server = None
if self._othread is not None:
self._othread.join(0.5)
if self._othread._error is not None:
callback(self._othread._error)
raise
def __which__(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
Courtesy Python 3.3 source code, for Python 2.x backward compatibility.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def __access_check__(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode) and
not os.path.isdir(fn))
# Short circuit. If we're given a full path which matches the mode
# and it exists, we're done here.
if __access_check__(cmd, mode):
return cmd
path = (path or os.environ.get("PATH", os.defpath)).split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if os.curdir not in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
matches = [cmd for ext in pathext if cmd.lower().endswith(ext.lower())]
# If it does match, only test that one, otherwise we have to try
# others.
files = [cmd] if matches else [cmd + ext.lower() for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
dir = os.path.normcase(dir)
if dir not in seen:
seen.add(dir)
for thefile in files:
name = os.path.join(dir, thefile)
if __access_check__(name, mode):
return name
return None
#
# DISCLAIMER:
# TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, POINTWISE DISCLAIMS
# ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED
# TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE, WITH REGARD TO THIS SCRIPT. TO THE MAXIMUM EXTENT PERMITTED
# BY APPLICABLE LAW, IN NO EVENT SHALL POINTWISE BE LIABLE TO ANY PARTY
# FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES
# WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF
# BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE
# USE OF OR INABILITY TO USE THIS SCRIPT EVEN IF POINTWISE HAS BEEN
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND REGARDLESS OF THE
# FAULT OR NEGLIGENCE OF POINTWISE.
#
|
C
|
UTF-8
| 205 | 3.625 | 4 |
[] |
no_license
|
#include<stdio.h>
int main()
{
int n,n1;
printf("enter the number:");
scanf("%d",&n);
printf("nearest greatest number is");
n=n-1;
n1=pow(2,n);
printf("the power of number is %d",n1);
return 0;
}
|
Python
|
UTF-8
| 3,345 | 3.5 | 4 |
[] |
no_license
|
# class Mammals:
# def __init__(self, name, habitat, food, properties):
# self.name = name
# self.habitat = habitat
# self.food = food
# self.properties = properties
# def eat(self, food):
# res = "{0.name} поел(а) {1}".format(self, food)
# print(res)
# class Cat(Mammals):
# def say(self):
# print("Мяу мифоу нгеонг")
# def __init__(self, name, habitat, food, properties):
# self.name = name
# self.habitat = habitat
# self.food = food
# self.properties = properties
# def eat(self, food):
# res = "{0.name} поел(а) {1}".format(self, food)
# print(res)
# class Dog(Mammals):
# super().__init__(name, habitat, food, properties,bark_loughtness)
# self.bark_loughtness = bark_loughtness
# def __init__(self, name, habitat, food, properties,bark_loughtness):
# self.name = name
# self.habitat = habitat
# self.food = food
# self.properties = properti
# def say(delf):
# if bark_loughtness < 100:
# print("Гав-гав")
# elif:
# print("Граааааааааар")
# def __init__(self, name, habitat, food, properties):
# self.name = name
# self.habitat = habitat
# self.food = food
# self.properties = properties
# def eat(self, food):
# res = "{0.name} поел(а) {1}".format(self, food)
# print(res)
# def say(self):
# print("Однако здравствуйте")
# def bark(self):
# print("Гав-гав")
# def eat(self,food):
# super().eat(food)
# print("И разорвала " + food + "на куски")
# selectipon = input("""Выберите вид:
# Домосед
# Мусорщик\n""")
# name = input("Введите имя:\n")
# cat = Cat(name = name, habitat = selectipon, food = "Рыба", properties = "Дом")
# print(cat.name)
# cat.eat("мясо")
# cat.say()
# dog = Dog(name = "Саид", habitat = "Каспийск", food = "картошка",properties = "общяга",bark_loughtness = )
# dog.bark()
# dog.say()
class Mammals:
def __init__(self, name, habitat, food, properties):
self.name = name
self.habitat = habitat
self.food = food
self.properties = properties
def eat(self, food):
res = "{0.name} поел(а) {1}".format(self, food)
print(res)
def say(self):
print("Однако здравствуйте")
class Cat(Mammals):
def say(self):
print("Мяу миаоу ня нгеонг")
class Dog(Mammals):
def __init__(self, name, habitat, food, properties, bark_loughtness):
super().__init__(name, habitat, food, properties)
self.bark_loughtness = bark_loughtness
def bark(self):
if self.bark_loughtness < 1000:
print("Гав-Гав")
else:
print("Граааааааар")
def eat(self,food):
super().eat(food)
print("И разорвала " + food + " на куски")
selection = input("""Выберите вид:
Домосед
Мусорщик\n""")
name = input("""Выберите имя:""")
cat = Cat(name=name,habitat=selection,food="рыба",properties="дом")
print(cat.name)
cat.eat("Мясо")
cat.say()
dog = Dog(name="Саид",habitat="Каспийск",food="Картошка",properties="общага", bark_loughtness=5000)
dog.bark()
dog.say()
dog.eat("Шаурму,Виски")
|
Java
|
UTF-8
| 746 | 3.09375 | 3 |
[] |
no_license
|
import java.util.Scanner;
public class Main
{
public static void main (String args[])
{
Robot Codsworth = new Robot("Codsworth", 100);
Drone Drone1 = new Drone("Drone 1", 100, 5);
IronMan IronMan = new IronMan("Iron Man", 100, 10);
Codsworth.TurnOn();
Drone1.TurnOn();
IronMan.TurnOn();
System.out.println();
Codsworth.DisplayPowerLevel();
System.out.println();
Codsworth.ReadEnemy(Drone1);
System.out.println();
Drone1.Move(500);
System.out.println();
Codsworth.ReadEnemy(Drone1);
System.out.println();
IronMan.AvengersAssemble(Drone1);
System.out.println();
Codsworth.ReadEnemy(Drone1);
System.out.println();
Drone1.Recharge();
}
}
|
Java
|
UTF-8
| 4,790 | 2.484375 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sg.superherosightingsspringmvc.service;
import com.sg.superherosightingsspringmvc.dao.SightingDao;
import com.sg.superherosightingsspringmvc.model.Location;
import com.sg.superherosightingsspringmvc.model.Sighting;
import com.sg.superherosightingsspringmvc.model.SuperPerson;
import com.sg.superherosightingsspringmvc.viewmodel.SightingViewModel;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author matt
*/
public class SightingServiceImpl implements SightingService {
SightingDao sightingDao;
SuperPersonService superPersonService;
LocationService locationService;
public SightingServiceImpl(SightingDao sightingDao, SuperPersonService superPersonService, LocationService locationService) {
this.sightingDao = sightingDao;
this.superPersonService = superPersonService;
this.locationService = locationService;
}
@Override
public Sighting createSighting(Sighting sighting) {
return sightingDao.createSighting(sighting);
}
@Override
public Sighting getSightingById(Integer sightingId) {
return sightingDao.getSightingById(sightingId);
}
@Override
public List<Sighting> getAllSightings(int offset, int limit) {
return sightingDao.getAllSightings(offset, limit);
}
@Override
public Sighting updateSighting(Sighting sighting) {
return sightingDao.updateSighting(sighting);
}
@Override
public Sighting deleteSighting(Sighting sighting) {
List<SuperPerson> superPersonsAtSighting = superPersonService.
getAllSuperPersonsBySighting(sighting, 0, Integer.MAX_VALUE);
for (SuperPerson currentSuperPerson : superPersonsAtSighting) {
superPersonService.deleteSightingFromSuperPerson(currentSuperPerson, sighting);
}
return sightingDao.deleteSighting(sighting);
}
@Override
public List<Sighting> getAllSightingsByDate(LocalDate date, int offset, int limit) {
return sightingDao.getAllSightingsByDate(date, offset, limit);
}
@Override
public List<Sighting> getAllSightingsBySuperPerson(SuperPerson sp, int offset, int limit) {
return sightingDao.getAllSightingsBySuperPerson(sp, offset, limit);
}
@Override
public List<SightingViewModel> getSightingViewModels(int offset, int limit) {
List<SightingViewModel> svmList = new ArrayList();
List<Sighting> viewSightings = getAllSightings(offset, limit);
for (int i = 0; i < viewSightings.size(); i++) {
// Make new Model object for each iteration
SightingViewModel currentModel = new SightingViewModel();
// Get the current sighting and set it on the model
Sighting currentSighting = viewSightings.get(i);
currentModel.setSighting(currentSighting);
// Get the current LocationID
Integer currentLocationId = currentSighting.getLocation().getLocationId();
// Get the current Location and set it on the model
Location currentLocation = locationService.getLocationById(currentLocationId);
currentModel.setLocation(currentLocation);
// Get a list of super persons at the sighting and set it on the model
List<SuperPerson> superPersonsAtSighting = superPersonService.getAllSuperPersonsBySighting(
currentModel.getSighting(), 0, 10);
currentModel.setSuperPersons(superPersonsAtSighting);
// add the current model to the list of models
svmList.add(currentModel);
}
// return the list of models
return svmList;
}
@Override
public SightingViewModel getSightingViewModelBySightingId(Integer sightingId) {
SightingViewModel svm = new SightingViewModel();
Sighting sighting = getSightingById(sightingId);
svm.setSighting(sighting);
Integer locationId = sighting.getLocation().getLocationId();
Location location = locationService.getLocationById(locationId);
svm.setLocation(location);
List<SuperPerson> superPersonsAtSighting = superPersonService.getAllSuperPersonsBySighting(
svm.getSighting(), 0, 10);
svm.setSuperPersons(superPersonsAtSighting);
svm.setDescription(sighting.getDescription());
return svm;
}
@Override
public List<Sighting> getAllSightingsByLocation(Location location, int offset, int limit) {
return sightingDao.getAllSightingsByLocation(location, offset, limit);
}
}
|
Java
|
UTF-8
| 446 | 1.617188 | 2 |
[] |
no_license
|
package com.l9e.transaction.service;
import java.util.List;
import java.util.Map;
import com.l9e.transaction.vo.AreaVo;
public interface CommonService {
public String query();
/**
* 获取省份
* @return
*/
public List<AreaVo> getProvince();
/**
* 获取城市
* @return
*/
public List<AreaVo> getCity(String provinceid);
/**
* 获取区县
* @return
*/
public List<AreaVo> getArea(String cityid);
}
|
Markdown
|
UTF-8
| 5,053 | 3.03125 | 3 |
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
---
---
title: 三
---
米哈伊尔·伊万内奇拿着信回到书房时,公爵坐在打开的写字台前,戴着眼镜和眼罩,蜡烛也罩上了罩子,他把拿着文件的手伸得远远的,摆着几分得意的架势读着自己的文件(他称之为书面意见),这些文件应当在他死后呈交皇上。
米哈伊尔·伊万内奇进去时,他正回忆着当初起草此刻在朗读的这些文件的那个时代而热泪盈眶。他从米哈伊尔·伊万内奇的手里接过信,放进口袋里,又把文件放好,于是叫来了早在等候的阿尔帕特奇。
他有一张纸片,上面记着需要在斯摩棱斯克办的事,阿尔帕特奇等在门口,于是公爵在他身旁踱来踱去,开始发出指示。
“首先是信笺,听着,要八刀,这个样子的;要裁口喷金……这是样品,务必要和它一样;清漆、火漆,照米哈伊尔·伊万内奇的清单买。”
他在房间里走动了一会,看了看备忘的清单。
“然后将一封关于书面意见的信面呈省长。”
然后是买新房子的门闩,务必要公爵亲自设计的那种式样。
然后是订购存放遗嘱的匣子。
向阿尔帕特奇发指示用了两个多钟头。公爵还是没有放他走。他坐下,沉思起来,接着闭上眼睛打盹。阿尔帕特奇稍微动了动。
“好了,去吧,去吧;要是还需要什么,我派人找你。”
阿尔帕特奇出去了。公爵又走到写字台前,往桌子里面瞧瞧,用手碰碰自己的文件,又锁上了,随即坐到桌子跟前给省长写信。
已经很晚了,他站起来把信封好。他想睡了,但他知道是睡不着的,躺在被窝里会产生极其苦恼的想法。他叫来了吉洪,和他到几个房间去,要告诉他,今夜要把床铺放在哪里。他走来走去,打量着每个角落。
他觉得哪里都不好,不过最差的是书房里他睡惯的那张沙发。这张沙发使他害怕,也许是因为他躺在这张沙发上有过太多沉痛的思绪。哪里都不好,但休息室的钢琴后面的一角毕竟比哪里都好:他还不曾在这里睡过。
吉洪和一个侍仆拿来卧具,开始铺床。
“不是这样,不是这样!”公爵大声说道,亲自把床从角落移开四分之一俄尺,然后又往里移一点。
“好,事情终于办完了,现在我要休息了,”公爵想,他让吉洪给自己脱衣服。
他因为脱长衫和裤子很费劲而懊丧地皱着眉头,公爵脱了衣服,在床上沉重地坐下,轻蔑地望着自己干瘦发黄的双腿,仿佛陷入了沉思。他不是在沉思,而是在迟疑,因为要把这双腿抬起来移到床上是很艰难的。“噢,多么沉重!噢,但愿这些麻烦事儿赶快、赶快结束!你们就不再纠缠我了!”他想,他抿着嘴唇,使劲了二十回,总算躺下了。可是他刚躺下,整个床就突然在他身下有节奏地前后摆动,仿佛在喘着粗气晃来晃去。这种情况几乎每夜都有。他睁开了刚闭上的眼睛。
“不得安宁,该死的家伙!”他恼怒地埋怨着谁。“对了,对了,还有一件重要的事情,我准备夜里躺在床上做的一件很重要的事情。门闩?不,这已经讲过了。不,是在客厅里发生的那件事。玛丽亚公爵小姐瞎说什么来着。德萨尔这个笨蛋说过什么东西。口袋里的什么东西,不记得了。”
“吉什卡!吃午饭时谈什么来着?”
“说到公爵,米哈伊尔……”
“住嘴,住嘴。”公爵一拍桌子。“对!我知道了,安德烈公爵的信。玛丽亚公爵小姐读过。德萨尔谈到了维捷布斯克。现在我要看信。”
他吩咐把口袋里的信拿来,把放着柠檬水和螺旋形蜡烛的小桌子移到床跟前,他戴上眼镜看信了。他在寂静的深夜,借助绿色灯罩下的微弱光线看了信,这时他才第一次顿时明白了信里的意思。
“法国人在维捷布斯克,经过四天的行程他们可能到达斯摩棱斯克;也许,他们已经到了那里。”
“吉什卡!”吉洪一跃而起。“不,不用了,不用了!”他大声叫道。
他把信藏在烛台底下,闭上了眼睛。于是他的想象中出现了多瑙河、阳光明媚的中午、大片的芦苇、俄军营地,而他,一位年轻的将军,脸上没有一丝皱纹,朝气蓬勃、心情愉快、面色红润,走进了波将金的彩绘的营帐,于是对由衷爱戴的人的炽热的羡慕之情依然那样强烈地使他激动不已。他的想象中又出现了一个面色微微泛黄的矮胖女人——女皇陛下,她第一次亲切接待他时的微笑、言谈,回忆起她躺在灵柩台上的遗容,以及当时他和祖波夫在灵柩旁为争取亲吻她的手的权利而引起的冲突。
“噢,快些、快些回到那个时代吧,但愿眼前的一切快些、快些结束,但愿他们能让我得到安宁!”
|
Java
|
UTF-8
| 389 | 2.28125 | 2 |
[] |
no_license
|
package ch.ltouroumov.heig.amt.project1.api.dto;
public class CreateUserDTO extends UserDTO {
private String password;
public CreateUserDTO(){
super();
}
public CreateUserDTO(String username){
super(username);
}
public String getPassword() { return this.password; }
public void setPassword(String password) { this.password = password; }
}
|
JavaScript
|
UTF-8
| 758 | 2.625 | 3 |
[] |
no_license
|
const escape = require('../utils/reEscape');
const { prefix } = require('../config');
const JsonFileManager = require('../utils/JsonFileManager');
const re = new RegExp(`^${escape(prefix)}setweight (\\d+(\\.\\d+)?)$`);
module.exports = {
cmdRe: re,
description: `\`${prefix}setweight <weight>\` - sets your current weight in pounds`,
exec: msg => {
const jfm = new JsonFileManager('bodyweight.json');
let weights = jfm.load();
if (msg.author.id in weights){
weights[msg.author.id].current_weight = re.exec(msg.content)[1];
} else {
weights[msg.author.id] = {
current_weight: re.exec(msg.content)[1],
goal_weight: null
}
}
jfm.save(weights);
msg.reply(`set your weight to ${weights[msg.author.id].current_weight} lbs`);
}
}
|
Python
|
UTF-8
| 503 | 3.0625 | 3 |
[] |
no_license
|
import logging
'''
列表合并成一个字符串
'''
logging.basicConfig(
level=logging.DEBUG,
format="\033[34m[%(asctime)s] [%(filename)s] (%(levelname)s-第%(lineno)d行)\n%(message)s\033[0m"),
def tostr(self):
if type(self) == list:
#print("OK")
s = ""
#logging.info("OK")
for i in self:
#logging.info(i)
s=s+str(i)+"<br>"
#logging.info(s)
return s
else:
logging.info("错误")
return ""
|
C#
|
UTF-8
| 4,464 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using YetAnotherTwitchBot.Interfaces;
using YetAnotherTwitchBot.Models;
namespace YetAnotherTwitchBot.Services
{
public class ExecutiveOrderService : IExecutiveOrderService
{
private ILogger<ExecutiveOrderService> _logger;
private HttpClient _client;
private const string _searchUrlPattern = "https://www.federalregister.gov/api/v1/documents?fields%5B%5D=abstract&fields%5B%5D=document_number&fields%5B%5D=executive_order_number&fields%5B%5D=html_url&fields%5B%5D=pdf_url&fields%5B%5D=public_inspection_pdf_url&fields%5B%5D=publication_date&fields%5B%5D=signing_date&fields%5B%5D=title&fields%5B%5D=type&conditions%5Bpresident%5D%5B%5D={1}&conditions%5Bpresidential_document_type%5D%5B%5D=executive_order&conditions%5Btype%5D%5B%5D=PRESDOCU&format=json&page={0}&per_page=1000";
private Dictionary<string,string> _presidents = new Dictionary<string, string>()
{
{"william-j-clinton","Bill Clinton"},
{"george-w-bush","George W. Bush"},
{"barack-obama","Barack Obama"},
{"donald-trump","Donald Trump"},
{"joe-biden","Joe Biden"}
};
private List<ExecutiveOrder> _executiveOrders;
private Random random = new Random();
private int _minOrderID;
private int _maxOrderID;
public ExecutiveOrderService(
ILogger<ExecutiveOrderService> Logger,
HttpClient Client)
{
_logger = Logger;
_client = Client;
var task = Init();
}
public ExecutiveOrder GetRandom()
{
int orderId = random.Next(0,_executiveOrders.Count -1);
_logger.LogInformation($"Random id: {orderId}");
return _executiveOrders[orderId];
}
public async Task Init()
{
_logger.LogInformation("Initializing Executove Order list...");
_executiveOrders = new List<ExecutiveOrder>();
foreach (var key in _presidents.Keys)
{
int page = 1;
int totalPages = 100;
var searchResults = new List<ExecutiveOrder>();
while (page <= totalPages)
{
_logger.LogInformation($"Fetching Executive Order Page {page} for President {_presidents[key]}...");
var url = string.Format(_searchUrlPattern, 1, key);
var response = await _client.GetAsync(url);
var result = await response.Content.ReadAsAsync<ExecutiveOrderResponse>();
totalPages = result.TotalPages;
searchResults.AddRange(result.Results);
page++;
}
foreach (var searchResult in searchResults)
{
searchResult.President = _presidents[key];
_executiveOrders.Add(searchResult);
}
}
_logger.LogInformation($"Initialized Executove Order list with {_executiveOrders.Count} items.");
SetOrderIDRange();
}
public ExecutiveOrder Get(string OrderID)
{
try
{
return _executiveOrders.First( order => order.ExecutiveOrderNumber == OrderID);
}
catch (System.Exception)
{
throw new KeyNotFoundException($"OrderID '{OrderID}' notfound");
}
}
public int GetMinOrderId()
{
return _minOrderID;
}
public int GetMaxOrderId()
{
return _maxOrderID;
}
private void SetOrderIDRange()
{
var orderIds = new List<int>();
foreach (var order in _executiveOrders)
{
if(int.TryParse(order.ExecutiveOrderNumber, out int orderId))
{
orderIds.Add(orderId);
}
else
{
_logger.LogError($"Unable to parse EO '{order.ExecutiveOrderNumber}' for Document {order.DocumentNumber}");
}
}
_minOrderID = orderIds.Min();
_maxOrderID = orderIds.Max();
_logger.LogInformation($"Min: {_minOrderID}, Max: {_maxOrderID}");
}
}
}
|
Java
|
UTF-8
| 627 | 2.6875 | 3 |
[] |
no_license
|
package jspbook.ch14;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogTest {
private static final Logger LOG = LoggerFactory.getLogger(LogTest.class);
public static void main(String[] args) {
LOG.trace("main()");
String msg = "Hello Log";
// Logger logger = LoggerFactory.getLogger(LogTest.class);
// logger.info("test log");
// logger.warn("test log : {}", msg);
LOG.debug(msg);
LOG.info("test log");
LOG.warn("test log : {}", msg);
LOG.error(msg);
int i = methodeA();
}
static int methodeA() {
// TODO Auto-generated method stub
LOG.trace("methodeA()");
return 0;
}
}
|
TypeScript
|
UTF-8
| 523 | 2.953125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
"use strict";
export default class ImageLink {
title: string;
altText: string;
uri: string;
constructor(title: string, altText: string, uri: string) {
this.title = title;
this.altText = altText;
this.uri = uri;
}
static create(title: string, uri: string): ImageLink {
const r = new ImageLink(title, title, uri);
return r;
}
clone(): ImageLink {
const r = new ImageLink(this.title, this.altText, this.uri);
return r;
}
}
|
C
|
UTF-8
| 2,555 | 2.90625 | 3 |
[] |
no_license
|
/******************************************************************************
* This is the main application for the project, it repuses most of the
* code from the test applikations
*****************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include "platform.h"
#include "xil_printf.h"
#include "xparameters.h"
#include "xgpio.h"
#include "xstatus.h"
#include "Delay.h"
#include "SPI.h"
#include "LCD_Driver.h"
#include "LCD_GUI.h"
#include "htu21d.h"
/* Create instances for both GPIO and SPI */
extern XGpio gpio0;
extern XSpi SpiInstance;
#define DELAY 30000 // 30 second wait
int main()
{
int Status;
htu21d_status stat;
float temperature;
float humidity;
char tempbuffer[16];
char humibuffer[16];
//Initialize MiniZed board
init_platform();
xil_printf("---------------------------------------------------\n");
xil_printf("- MiniZed Temperature and Humidity monitor -\n");
xil_printf("---------------------------------------------------\n");
/* Initialize AXI GPIO 0 */
Status = XGpio_Initialize(&gpio0, XPAR_AXI_GPIO_0_DEVICE_ID);
if (Status != XST_SUCCESS) {
xil_printf("GPIO 0 Initialization Failed\n");
return XST_FAILURE;
}
// Initialize AXI SPI Controller
Status = XSpi_Init(&SpiInstance,SPI_DEVICE_ID);
if (Status != XST_SUCCESS) {
xil_printf("SPI Mode Failed\n");
return XST_FAILURE;
}
// Initialize the AXI I2C interface
htu21d_init(XPAR_AXI_IIC_0_BASEADDR);
// Set relative humidity resolution to 12-bit and temperature to 14-bit
stat = htu21d_set_resolution(htu21d_resolution_t_14b_rh_12b);
// Initialize LCD display
LCD_SCAN_DIR LCD_ScanDir = SCAN_DIR_DFT; // Scan direction U2D_R2L
LCD_Init(LCD_ScanDir);
// Start of program loop
while(1){
// Read temperature and humidity
stat = htu21d_read_temperature_and_relative_humidity(&temperature, &humidity);
// Format readings in a string for use with display string command
sprintf(tempbuffer, "%2.2fC ", temperature);
sprintf(humibuffer, "%2.2f%%", humidity);
// Update LCD to display new reading
LCD_Clear(BLACK);
GUI_DrawRectangle(0,0,159,127,BLACK,DRAW_EMPTY,DOT_PIXEL_2X2);
GUI_DisString_EN(10,10,"Temperatur",&Font20,GUI_BACKGROUND,CYAN);
GUI_DisString_EN(10,40,tempbuffer,&Font24,GUI_BACKGROUND,YELLOW);
GUI_DisString_EN(10,70,"Fugtighed",&Font20,GUI_BACKGROUND,CYAN);
GUI_DisString_EN(10,100,humibuffer,&Font24,GUI_BACKGROUND,YELLOW);
delay_ms(DELAY);
}
return 0;
}
|
Python
|
UTF-8
| 722 | 4.65625 | 5 |
[] |
no_license
|
def fn(a, b):
print(a, b)
# 实参:
# 1.位置实参: 按位置先后进行传参,a, b不能被颠倒位置进行传参,a永远比b先接受受值
fn(10, 20)
fn(20, 10)
a = 100
b = 200
fn(a, b)
fn(b, a)
#传参两种方式: 实参名 | 实参值
# 2. 关键字参数: 指名道姓进行传参, a,b能被颠倒位置进行传参,名字指向谁,就是谁接受值
c = 1000
fn(a = 10, b = c)
fn(b = 20, a = 10)
# 传参两种方式: 形参名 = 实参名 | 形参名 = 实参值
# 结合传参
def func(a, b, c):
print(a, b, c)
# func(10, b=20, 200) 报错:SyntaxError: positional argument follows keyword argument
# 两种实参在一起传参时:必须位置在前,关键字在后
|
PHP
|
UTF-8
| 915 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Models\Surveys;
use Illuminate\Database\Eloquent\Model;
use App\Traits\ModelScopes;
class Target extends Model
{
use ModelScopes;
public $timestamps = false;
protected $fillable = [
'age',
'gender',
];
//jobs테이블 targets테이블 N-N (중간테이블 job_target)
public function job(){
return $this->belongsToMany('App\Models\Users\Job','job_target');
}
//forms테이블 targets테이블 1-1
public function form(){
return $this->hasOne('App\Models\Surveys\Form');
}
//나이 저장시 json속성 포맷 변환
public function setAgeAttribute($value) {
$this->attributes['age'] = json_encode($value,JSON_UNESCAPED_UNICODE);
}
//나이 추출시 배열 속성 포맷 변환
public function getAgeAttribute($value)
{
return json_decode($value,true);
}
}
|
Shell
|
UTF-8
| 1,357 | 3.28125 | 3 |
[
"MIT-0",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
#!/usr/bin/env bash
GROUP_ID=$1
if [ -f "/greengrass/config/group-id.txt" ]; then
GROUP_ID=$(cat /greengrass/config/group-id.txt)
fi
if [ -z "$GROUP_ID" ]; then
echo "Group ID required";
exit 1
fi
REGION=$(cat /greengrass/config/region.txt)
THING_NAME=$(cat /greengrass/config/thing-name.txt)
CREDENTIAL_PROVIDER_URL="https://"$(cat /greengrass/config/credential-provider-url.txt)"/"
ROLE_ALIAS_NAME=$(cat /greengrass/config/role-alias-name.txt)
FULL_URL=$CREDENTIAL_PROVIDER_URL"role-aliases/"$ROLE_ALIAS_NAME"/credentials"
# No longer using the AWS IoT Verisign root CA. If the distro doesn't have certificate authorities installed this command will probably fail
CREDENTIALS=$(curl -s --cert /greengrass/certs/core.crt --key /greengrass/certs/core.key -H "x-amzn-iot-thingname: $THING_NAME" $FULL_URL)
export AWS_DEFAULT_REGION=$REGION
export AWS_ACCESS_KEY_ID=$(jq --raw-output .credentials.accessKeyId <(echo $CREDENTIALS))
export AWS_SECRET_ACCESS_KEY=$(jq --raw-output .credentials.secretAccessKey <(echo $CREDENTIALS))
export AWS_SESSION_TOKEN=$(jq --raw-output .credentials.sessionToken <(echo $CREDENTIALS))
GROUP_VERSION_ID=$(aws greengrass get-group --group-id $GROUP_ID --query LatestVersion --output text)
aws greengrass create-deployment --group-id $GROUP_ID --group-version-id $GROUP_VERSION_ID --deployment-type NewDeployment
|
PHP
|
UTF-8
| 1,064 | 2.515625 | 3 |
[] |
no_license
|
<?php
/**
* Part of flower project.
*
* @copyright Copyright (C) 2018 ${ORGANIZATION}.
* @license __LICENSE__
*/
namespace Flower\View\sakuras;
use Windwalker\Core\DateTime\Chronos;
use Windwalker\Core\View\HtmlView;
/**
* The SakurasHtmlView class.
*
* @since __DEPLOY_VERSION__
*/
class SakurasHtmlView extends HtmlView
{
/**
* Property renderer.
*
* @var string
*/
protected $renderer = 'edge';
/**
* prepareData
*
* @param \Windwalker\Data\Data $data
*
* @return void
*
* @since __DEPLOY_VERSION__
*/
protected function prepareData($data)
{
parent::prepareData($data);
foreach ($data->sakuras as $sakura) {
$sakura->viewlink = $this->router->route('sakura', ['id' => $sakura->id]);
$sakura->editlink = $this->router->route('sakura', ['id' => $sakura->id, 'layout' => 'edit']);
$sakura->date = Chronos::toLocalTime($sakura->created,'Y/m/d');
}
}
}
|
Python
|
UTF-8
| 1,634 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
from docx import Document
from docx.shared import Inches
from docx.opc.constants import RELATIONSHIP_TYPE as RT
def save_link():
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A hyperlink paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
p._insert_hyperlink_after('www.baidu.com','hyperlink')
document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')
document.add_paragraph(
'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
'first item in ordered list', style='ListNumber'
)
document.save('hltest.docx')
def iter_hyperlink_rels(rels):
for rel in rels.values():
if rel.reltype == RT.HYPERLINK:
yield rel
def is_hyperlink_p(p):
if not p._element is None:
if not p._element.hl_lst.__len__() is 0:
if p._element.hl_lst[0].rId in hls.keys():
return True
return False
def get_link():
document = Document("hltest.docx")
hls = {}
rels = document.part.rels
for rel in iter_hyperlink_rels(rels):
hls[rel.rId] = rel._target
for p in document.paragraphs:
if not p._element is None:
print("P:",p.text.strip())
if not p._element.hl_lst.__len__() is 0:
if p._element.hl_lst[0].rId in hls.keys():
print( p.text, ":", hls[p._element.hl_lst[0].rId])
if __name__ == '__main__':
# save_link()
get_link()
|
C#
|
UTF-8
| 978 | 2.5625 | 3 |
[] |
no_license
|
using DnDTool2.Model;
using DnDTool2.View;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace DnDTool2.ViewModel
{
public class MonsterManualVM : ViewModel
{
private ObservableCollection<Creature> creatures;
public ObservableCollection<Creature> Creatures { get => creatures; set => creatures = value; }
public RelayCommand OpenAddCreatureCommand { get; set; }
public MonsterManualVM(Window window) : base(window)
{
Creatures = new ObservableCollection<Creature>
{
new Creature("Dragon", 10, 10, 10, 10, 10, 10)
};
OpenAddCreatureCommand = new RelayCommand(OpenAddCreature);
}
private void OpenAddCreature(object parameter)
{
(new AddCreatureWindow(creatures)).Show();
}
}
}
|
Java
|
UTF-8
| 1,800 | 2.265625 | 2 |
[] |
no_license
|
package org.drools.workbench.screens.guided.rule.client.editor.validator;
import org.drools.workbench.models.datamodel.rule.CompositeFactPattern;
import org.drools.workbench.models.datamodel.rule.IPattern;
import org.drools.workbench.models.datamodel.rule.RuleModel;
import org.drools.workbench.screens.guided.rule.client.resources.i18n.Constants;
public class GuidedRuleEditorValidator {
private final RuleModel model;
private final Constants constants;
private String errorMessage = "";
public GuidedRuleEditorValidator(RuleModel model, Constants constants) {
this.model = model;
this.constants = constants;
}
public boolean isValid() {
if (model.lhs.length == 0) {
return true;
} else {
return validateCompositeFactPatterns();
}
}
private boolean validateCompositeFactPatterns() {
for (int i = 0; i < model.lhs.length; i++) {
IPattern iPattern = model.lhs[i];
if (iPattern instanceof CompositeFactPattern) {
if (!hasPatterns((CompositeFactPattern) iPattern)) {
return false;
}
}
}
return true;
}
private boolean hasPatterns(CompositeFactPattern iPattern) {
if (iPattern.getPatterns() == null) {
setMandatoryFieldsError();
return false;
} else if (iPattern.getPatterns().length == 0) {
setMandatoryFieldsError();
return false;
} else {
return true;
}
}
private void setMandatoryFieldsError() {
errorMessage = constants.AreasMarkedWithRedAreMandatoryPleaseSetAValueBeforeSaving();
}
public String getErrorMessage() {
return errorMessage;
}
}
|
C#
|
UTF-8
| 3,886 | 3.53125 | 4 |
[] |
no_license
|
using System;
namespace InfiniteLanguageDFA
{
/**
*
*
* Testing the DFS algorithm
*
*
*/
class TestDFS
{
Node[] DFA;
public TestDFS(Node[] d)
{
this.DFA = d;
}
//Old method used to test DFAs before the File Converter was finished.
public bool Test()
{
bool b;
Node[] testNodes = new Node[2];
testNodes[0] = new Node("loopTest", true, true, null, null);
testNodes[0].SetATransition(testNodes[0]);
testNodes[0].SetBTransition(testNodes[0]);
testNodes[1] = new Node("noLoop", false, true, null, null);
testNodes[1].SetATransition(testNodes[1]);
testNodes[1].SetBTransition(testNodes[1]);
b = DFS(testNodes[1]);
return b;
}
//Our algorithm uses a part of the algorithm described here:
//https://www.geeksforgeeks.org/detect-cycle-in-a-graph/
public bool DFS(Node n)
{
Console.WriteLine("visiting " + n.GetName());
//We are keeping track of two things:
//The recursion stack (marked2)
//And if we have visited the node.
//If it is on the recursion stack, then we have
//reached this node from itself
//And we have found a node in a cycle
if (n.IsMarked2())
{
//Marked3 controls the marking for the accept finding
//algorithm. We can set these to false here.
foreach (Node t in DFA)
{
t.SetMarked3(false);
}
//We can now look to see if that node
//Reaches an accepting state.
Console.WriteLine("Cycle Found, looking for an accept path");
return FindAccept(n);
}
//If we have reached a node that is marked, we do not
//Return true because it is a node that
//is not on the recursion stack but we have seen.
if (n.IsMarked())
{
return false;
}
//Set both values to true because we have seen them
n.SetMarked(true);
n.SetMarked2(true);
//Recursive calls
if (DFS(n.GetATransition()))
{
return true;
}
if (DFS(n.GetBTransition()))
{
return true;
}
//Base case (all paths have been examined for a
//particular branch, so we take this node
//off of the recursive stack and return false.
n.SetMarked2(false);
return false;
}
//Perform another DFS on n.
//If it returns true, then we have found an accepting state
public bool FindAccept(Node n)
{
Console.WriteLine("Finding a path to an accept state for " + n.GetName());
//Base case #1: n is an accepting state
if (n.IsAccepting())
{
Console.WriteLine(n.GetName() + " accepted");
return true;
}
//Base case #2: n is not an accepting state and we have been here before.
if (n.IsMarked3())
{
Console.WriteLine("Did not find an accepting state on this path");
return false;
}
//Recursive case: set marked as true; call findAccept on all neighbors.
else
{
Console.WriteLine("Marking this node, still looking for an accepting node");
n.SetMarked3(true);
return FindAccept(n.GetATransition())
|| FindAccept(n.GetBTransition());
}
}
}
}
|
Java
|
UTF-8
| 1,907 | 2.046875 | 2 |
[] |
no_license
|
package main.project.admin.board.dao;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import main.project.admin.board.vo.AdminBoardNoticeVO;
@Repository("adminIBoardNoticeDAO")
public class adminIBoardNoticeDAOImpl implements adminIBoardNoticeDAO {
@Inject
private SqlSessionTemplate sqlSessionTemplate;
@Override
public void insertAbnVO(AdminBoardNoticeVO abnVO) {
sqlSessionTemplate.insert("main.project.admin.board.dao.adminIBoardNoticeDAO.insertAbnVO",abnVO);
}
@Override
public List<AdminBoardNoticeVO> selectListAdminBoardNotice(int displayPost, int postNum) throws Exception {
HashMap<String, Integer> data = new HashMap<String, Integer>();
data.put("displayPost", displayPost);
data.put("postNum", postNum);
return sqlSessionTemplate.selectList("main.project.admin.board.dao.adminIBoardNoticeDAO.selectListAdminBoardNotice", data);
}
@Override
public List<AdminBoardNoticeVO> selectListAdminBoardNotice() {
return sqlSessionTemplate.selectList("main.project.web.notice.dao.INoticeDAO.noticePage");
}
@Override
public Integer selectBoardNoticeNumber() {
return sqlSessionTemplate.selectOne("main.project.admin.board.dao.adminIBoardNoticeDAO.selectBoardNoticeNumber");
}
@Override
public AdminBoardNoticeVO adminBoardNotice_Detail(String boardNum) {
return sqlSessionTemplate.selectOne("main.project.admin.board.dao.adminIBoardNoticeDAO.adminBoardNotice_Detail",boardNum);
}
@Override
public void updateBoardNotice(AdminBoardNoticeVO abnVO) {
sqlSessionTemplate.update("main.project.admin.board.dao.adminIBoardNoticeDAO.updateBoardNotice", abnVO);
}
@Override
public void deleteBoardNotice(String boardNum) {
sqlSessionTemplate.delete("main.project.admin.board.dao.adminIBoardNoticeDAO.deleteBoardNotice", boardNum);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.