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
|
---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 2,442 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
/**
* Copyright (c) 2017 by Botorabi. All rights reserved.
* https://github.com/botorabi/Meet4Eat
*
* License: MIT License (MIT), read the LICENSE text in
* main directory for more details.
*/
#ifndef M4E_RESPONSE_H
#define M4E_RESPONSE_H
#include <configuration.h>
#include <QJsonDocument>
namespace m4e
{
namespace webapp
{
/**
* @brief This base class is used for handling the response of an asynchronous REST requests.
*
* @author boto
* @date Sep 7, 2017
*/
class Meet4EatRESTResponse
{
public:
/**
* @brief Construct an instance of RESTResultsCallback
*/
Meet4EatRESTResponse() {}
/**
* @brief Destroy the callback instance.
*/
virtual ~Meet4EatRESTResponse() {}
/**
* @brief If this method returns true then the instance must be automatically deleted
* right after one of following callback methods was called. Override and return
* false in order to take control on the instance lifecycle yourself.
*
* @return Return true for automatic deletion of the response handler.
*/
virtual bool getAutoDelete() { return true; }
/**
* @brief Called on success this method delivers the request results in given JSON document.
*
* @param results The JSON document contains the response results.
*/
virtual void onRESTResponseSuccess( const QJsonDocument& /*results*/ ) {}
/**
* @brief This method is called if the server could not be contacted.
*
* @param reason The reason for the error.
*/
virtual void onRESTResponseError( const QString& /*reason*/ ) {}
/**
* @brief Check the request results.
*
* @param results Request results as received e.g. in method onRESTResultsSuccess
* @param data Extracted data from results
* @param errorCode Error code if the results status was not ok.
* @param errorString Error string if the results status was not ok.
* @return Return false if the results status was not ok.
*/
bool checkStatus( const QJsonDocument& results, QJsonDocument& data, QString& errorCode, QString& errorString );
};
} // namespace webapp
} // namespace m4e
#endif // M4E_RESPONSE_H
|
Java
|
UTF-8
| 1,247 | 3.625 | 4 |
[] |
no_license
|
class Empleado {
String rut;
String nombre;
boolean perfil;
String colorperfil;
Empleado() {
// Contructor vacio
}
Empleado(String nm) {
this.nombre = nm;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nm) {
this.nombre = nm;
}
}
public class Programador extends Empleado{
private String apellido;
// Constructor
Programador() {
super(); // Hereda del constructor de la clase Empleado
}
Programador(String nm) {
super(nm); // Hereda del constructor de la clase Empleado
}
public void setApellido(String ap) {
this.apellido = ap;
}
public String getNombre() {
return this.nombre + " " + this.apellido;
}
public static void main(String[] args) {
Programador programador = new Programador();
programador.setNombre("Pepe");
programador.setApellido("Gómez");
Programador programador2 = new Programador("Pepe");
programador2.setApellido("Pillos");
System.out.println("Programador 1 -->\t" + programador.getNombre());
System.out.println("Programador 2 -->\t" + programador2.getNombre());
}
}
|
Java
|
UTF-8
| 935 | 1.679688 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.spoofax.jsglr2.integrationtest.recovery;
import java.util.Arrays;
import java.util.stream.Stream;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.spoofax.jsglr2.integrationtest.BaseTestWithRecoverySdf3ParseTables;
import org.spoofax.jsglr2.integrationtest.MessageDescriptor;
import org.spoofax.jsglr2.messages.Severity;
import org.spoofax.terms.ParseError;
public class RecoveryInsertionMessagesTest extends BaseTestWithRecoverySdf3ParseTables {
public RecoveryInsertionMessagesTest() {
super("recovery-insertion.sdf3", false, false, false);
}
@TestFactory public Stream<DynamicTest> testInsertion() throws ParseError {
return testMessages("xz", Arrays.asList(
//@formatter:off
new MessageDescriptor("Y expected", Severity.ERROR, 1, 1, 2, 1)
//@formatter:on
), getTestVariants(isRecoveryVariant));
}
}
|
Java
|
UTF-8
| 151 | 2.40625 | 2 |
[] |
no_license
|
package com.hhd.patterns.bridge;
public class ColdAnimal extends Animal {
public ColdAnimal(AnimalImpl impl) {
super.impl = impl;
}
}
|
C#
|
UTF-8
| 1,566 | 3.53125 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WhileTry4
{
class Program
{
static void Main(string[] args)
{
//most of this one Works!!!!
Random rand1 = new Random();
int X;
int resultNum;
string Result = "";
int Guesses = 1; ;
int newRand;
do
{
Console.WriteLine("Guess a # Between 1 and 15");
// Console.WriteLine("Guess Again");
Result = Console.ReadLine();
newRand = rand1.Next(1, 15);
resultNum = int.Parse(Result);
while(resultNum < 1 || resultNum > 15 )
{
Console.WriteLine("That Choice is not valid");
Guesses++;
resultNum = int.Parse(Result);
Result = Console.ReadLine();
newRand++;
}
} while (resultNum != newRand);
{
Console.WriteLine("You Guessed The Mystery #!!!");
Guesses++;
resultNum = int.Parse(Result);
Result = Console.ReadLine();
newRand++;
}
Console.WriteLine("You guessed {0} times", Guesses);
//Console.WriteLine(X);
Console.WriteLine("We made it!!!");
Console.ReadLine();
}
}
}
|
Python
|
UTF-8
| 4,282 | 2.5625 | 3 |
[] |
no_license
|
from adventure.response import Response
from adventure.verb import Verb, BuiltInVerbs, ResponseVerb, VerbResponse
from adventure.util import MakeTuple
from adventure.target import Target
class PushVerb(ResponseVerb):
def __init__(self, name, abbreviation, responses=None, *args, **kwargs):
super().__init__(name, abbreviation, responses, *args, **kwargs)
def DoObject(self, target, game):
# The original game logic says that "BUT" always refers to the box button when it is possessed
if target is not None and target.IsObject() and target.value.abbreviation[:3] == "BUT":
if game.Has('BOX'):
target = Target(game.world.objects['A BUTTON ON A BOX'])
m, reward, result = Response.Respond(target.value.responses, self, game)
return m, reward, result
return super().DoObject(target, game)
customVerbs = (
PushVerb('PUSH', 'PUS', (
VerbResponse(ifNotHere=True, message="I DON'T SEE THAT HERE.", result=Response.IllegalCommand),
VerbResponse(ifNoObjectResponse=True, message="NOTHING HAPPENS.", result=Response.IllegalCommand))),
ResponseVerb('PULL', 'PUL', VerbResponse(ifNoObjectResponse=True, message="NOTHING HAPPENS.", result=Response.IllegalCommand)),
ResponseVerb('INSERT', 'INS',(
VerbResponse(ifNotHere=True, message="I DON'T SEE THAT HERE.", result=Response.IllegalCommand),
VerbResponse(ifNoObjectResponse=True, message="I CAN'T INSERT THAT!", result=Response.IllegalCommand)),
didntWorkMessage="NOTHING HAPPENED."),
ResponseVerb('OPEN', 'OPE', (
VerbResponse(ifNotHere=True, message="I CAN'T OPEN THAT!", result=Response.IllegalCommand),
VerbResponse(ifNoObjectResponse=True, message="I CAN'T OPEN THAT!", result=Response.IllegalCommand)),
didntWorkMessage="I CAN'T DO THAT......YET!"),
ResponseVerb('WEAR', 'WEA', (
VerbResponse(ifNotHas=True, message="I CAN'T WEAR THAT!", result=Response.IllegalCommand),
VerbResponse(ifNoObjectResponse=True, message="I CAN'T WEAR THAT!", result=Response.IllegalCommand))),
ResponseVerb('READ', 'REA', (
VerbResponse(ifNoObjectResponse=True, message="I CAN'T READ THAT!", result=Response.IllegalCommand),
VerbResponse(ifNotHere=True, message="I DON'T SEE THAT HERE.", result=Response.IllegalCommand))),
ResponseVerb('START', 'STA', (
VerbResponse(ifNotHere=True, message="I DON'T SEE THAT HERE.", result=Response.IllegalCommand),
VerbResponse(ifNoObjectResponse=True, message="I CAN'T START THAT.", result=Response.IllegalCommand))),
ResponseVerb('BREAK', 'BRE', (
VerbResponse(ifNoObjectResponse=True, message="I'M TRYING TO BREAK IT, BUT I CAN'T.", result=Response.IllegalCommand))),
ResponseVerb('CUT', 'CUT', VerbResponse(ifNoObjectResponse=True, message="I'M TRYING. IT DOESN'T WORK.", result=Response.IllegalCommand)),
ResponseVerb('THROW', 'THR', (
VerbResponse(ifNotHas=True, message="I CAN'T THROW THAT.", result=Response.IllegalCommand),
VerbResponse(ifNoObjectResponse =True, message="I CAN'T THROW THAT.", result=Response.IllegalCommand))),
ResponseVerb('CONNECT', 'CON', (
VerbResponse(ifNotHere=True, message="I CAN'T CONNECT THAT.", result=Response.IllegalCommand),
VerbResponse(ifNoObjectResponse=True, message="I CAN'T CONNECT THAT.", result=Response.IllegalCommand))),
ResponseVerb('BOND-007-', 'BON', (
VerbResponse(ifAtLocation='CAFETERIA', goTo='BASEMENT', message="WHOOPS! A TRAP DOOR OPENED UNDERNEATH ME AND\nI FIND MYSELF FALLING.\n"),
VerbResponse(message="NOTHING HAPPENED.", result=Response.IllegalCommand)),
targetOptional=True))
verbs = BuiltInVerbs(customVerbs)
push = verbs['PUSH'].MakeResponse
pull = verbs['PULL'].MakeResponse
go = verbs['GO'].MakeResponse
get = verbs['GET'].MakeResponse
insert = verbs['INSERT'].MakeResponse
open = verbs['OPEN'].MakeResponse
drop = verbs['DROP'].MakeResponse
wear = verbs['WEAR'].MakeResponse
read = verbs['READ'].MakeResponse
start = verbs['START'].MakeResponse
break_ = verbs['BREAK'].MakeResponse
cut = verbs['CUT'].MakeResponse
throw = verbs['THROW'].MakeResponse
connect = verbs['CONNECT'].MakeResponse
look = verbs['LOOK'].MakeResponse
|
Python
|
UTF-8
| 818 | 3.1875 | 3 |
[] |
no_license
|
#! env python
import pathlib
import shutil
"""
将子文件夹中所有文件剪切到当前目录下
"""
gROOT = pathlib.Path(".").absolute()
def expandFiles(paths):
for _ in paths:
if _.is_file():
try:
shutil.move(str(_.absolute()), str(gROOT.absolute()))
except shutil.Error:
print("文件 {} 已存在".format(_.name))
else:
new_path = list(_.iterdir())
expandFiles(new_path)
def removeDirs(paths):
for _ in paths:
if _.is_dir():
try:
_.rmdir()
except OSError:
removeDirs(list(_.iterdir()))
def main():
dirs = [_ for _ in gROOT.iterdir() if _.is_dir()]
expandFiles(dirs)
removeDirs(dirs)
if __name__ == "__main__":
main()
|
Markdown
|
UTF-8
| 1,331 | 2.65625 | 3 |
[] |
no_license
|
# Better Medium Stats
Get it at [Chrome Web Store](https://chrome.google.com/webstore/detail/better-medium-stats/pdehepohihkkmeclfnlnipieffkomajc)!

## What is Better Medium Stats?
Better Medium Stats is a chrome extension that help writers on Medium get more insights from the stats. You can add it to your chrome via [this link](https://chrome.google.com/webstore/detail/medium-stats-counter/pdehepohihkkmeclfnlnipieffkomajc).
## Features
- A quick summary contains total views, total followers, last 24 hours/ 7 days/ 30 days views
- Views of all articles in 4 different timespans: year, month, week, date, hour
- Sort your articles by different metrics
- Last 30 days new followers trend
- Export and download stats as csv file
### Summary

### Hour Views

### Day Views

### Stories Stats

### Follower Trend

## Contributing
Any suggestion, issue and PR is highly appreciated. Hope you enjoy it!
## Third Party
- [Feather Open Source Icons](https://github.com/feathericons/feather)
- [Chart.js](https://www.chartjs.org/)
|
Python
|
UTF-8
| 1,214 | 3.015625 | 3 |
[] |
no_license
|
# обработка нескольких соединений одновременно, процессы и потоки
import socket
import multiprocessing
import threading
import os
def process_requests(conn, addr):
print(f'connected client {addr}')
with conn:
while True:
data = conn.recv(1024)
if data:
print('Data =', data.decode("utf8"))
else:
break
# каждый worker запущен в отдельном процессе
def worker(sock):
while True:
conn, addr = sock.accept()
print(f'Pid = {os.getpid()}')
th = threading.Thread(target=process_requests, args=(conn, addr))
th.start()
if __name__ == '__main__':
with socket.socket() as sock:
sock.bind(("", 10001))
sock.listen()
# при создании нового процесса, мы полностью копируем socket
workers_count = 3
workers_list = [multiprocessing.Process(target=worker, args=(sock,))
for _ in range(workers_count)]
for w in workers_list:
w.start()
for w in workers_list:
w.join()
|
Markdown
|
UTF-8
| 3,925 | 3.046875 | 3 |
[] |
no_license
|
---
layout: post
title: "How I became an avid reader"
date: 2017-02-02 18:03:54 +0500
categories: Books
tags: books, reading, technology, mobile devices, phones, tablets, ipad, android, kindle, amazon
description: I have never been able to read books. But something helped me get over my reader's block, of 50 years. Find out what did the trick.
fq_featuredimage:
---
I could never read books, and that includes academic books. This incapability, was probably why I didn't do so well at school, among other unmentionable, and rather embarrassing, reasons (like laziness).
I know individuals who are always reading. Some of my friends even go to reading holidays. I know a couple who travel to exotic locations, just to lounge around, and read books. I envied such people who could continually consume the written word.
All my life I bought books hoping to read them one day. I even kept a few of them on my bedside table, thinking that would help me get started. As you can guess, it never happened. Luckily my life had a reading revolution in May 2016 - just before Ramadan.
Two things made me an avid reader:
1. I bought a Kindle
--
After buying paper books for decades, which I never read, I decided to order a Kindle, from Amazon. The moment I held the Paperwhite in my hand, I was a convert. The device invites you to read, and makes it a natural thing. Sadly, the Kindle E-reader is a horrible piece of technology, and the pleasure of owning one died within a few hours [Read about my Kindle E-reader experience]. Without a doubt, the Kindle had to go back, but before I could put it back in the box and return it to Amazon, the Kindle had done its magic. The E-reader made me realize that I too can read, like the people I had been envying - the only condition was that the book had to be glowing on a screen, instead of a bundle of paper. The Kindle was sent back, and my iPad mini resurrected. The otherwise useless iPad 1st Generation - 16GB, suddenly became my best friend. [Read - My Kindle Experience]
2. I needed answers about intermittent fasting
--
I had always wanted to understand the deeper spiritual, and scientific purpose of Ramadan and fasting. I didn't think God wanted us to starve all day, unless there was a deep-rooted advantage in doing so. There had to be a bigger purpose of fasting every day, for a month every year. Something bigger than just worship, or a lesson in discipline. There had to be a more spiritual, and physical, advantage to gain from the month of Ramadan. A few weeks earlier, I had seen a blog post about intermittent fasting for curing cancer. Armed with my Kindle app [Why I ditched my Kindle Paperwhite], I started looking for books on the subject. What I discovered, made an everlasting impact on my life. My whole lifestyle changed. I now eat mostly fruits and vegetables - and every free moment of my time is spent reading.
Conclusion
--
Thanks to spending a couple of days with a Kindle Paperwhite E-reader, I have now become a compulsive reader, to the extent that I can't go to sleep, at night, without reading for a while. Every free moment, I have, is used for reading. I almost always, carry my iPad mini with me.
So if you are having trouble getting into the reading habit, I would suggest setting up an electronic library. There are multiple platforms, and devices, that can get you going. I recommend the Kindle (Amazon) environment, and the Kindle app on any old iPad, or tablet. Apple's iBooks are just as good, but restricts you to the Apple ecosystem. Kindle is platform neutral, and accessible from just about everything - iPhone, iPad, Android, Web browser, etc. [Read - My Kindle Experience].
Related Links
Click here to have a look at my Bookshelf. It also has links to my book reviews and favorite quotations.
You can also read about my experience with Ramadan, intermittent fasting, non-mucous diet, and weight-loss [Coming Soon]
|
C++
|
UTF-8
| 665 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
class Solution {
public:
int minCost(string colors, vector<int>& neededTime) {
const int N = colors.length();
int res = 0;
int startPos = 0;
while(startPos < N){
int totalTime = 0;
int maxTime = 0;
int endPos = startPos;
while(endPos < N && colors[startPos] == colors[endPos]){
totalTime += neededTime[endPos];
maxTime = max(maxTime, neededTime[endPos]);
endPos += 1;
}
res += (totalTime - maxTime);
startPos = endPos;
}
return res;
}
};
|
C#
|
UTF-8
| 4,350 | 3.625 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecisionMakingStatements
{
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
obj.managingProgramFlow();
Console.ReadKey();
}
public void managingProgramFlow()
{
#region The null-coalescing operator
//int
int? n = null;
int y = n ?? -1;
Console.WriteLine("Int Type");
Console.WriteLine("Value of n: {0}", n);
Console.WriteLine("Value of y: {0}", n ?? -1);
int? a = 1;
int? b = 3;
int c = a ??
b ?? 10;
Console.WriteLine("value of a:{0}& b:{1}", a, b);
Console.WriteLine("value of c:{0}", c);
//string
string s = null;
string copyofs = s ?? "Hi";
Console.WriteLine("\nString Type");
Console.WriteLine("value of copyofs: {0}", copyofs);
#endregion
#region Switch statement
Console.WriteLine("\nSwtich: Char type");
char letter = 'i';
switch (letter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
{
Console.WriteLine("'{0}' is a vowels", letter);
break;
}
case 'y':
{
Console.WriteLine("'{0}' is sometimes a vowels", letter);
break;
}
default: Console.WriteLine("'{0}' is a Consonant", letter);
break;
}
#endregion
#region For loop
Console.WriteLine("\nfor loop");
int[] values = { 1, 2, 3, 4, 5, 6 };
for (int x = 0, yx = values.Length - 1;
((x < values.Length) && (yx >= 0));
x++, yx--)
{
Console.Write(values[x]);
Console.Write(values[yx]);
}
Console.WriteLine("\nfor loop with break");
int[] xvalues = { 1, 2, 3, 4, 5, 6 };
for (int index = 0; index < xvalues.Length; index++)
{
if (xvalues[index] == 4) break; //continue
Console.Write(xvalues[index]);
}
#endregion
#region Foreach
var Audi = new List<Car>()
{
new Car(){Break="Rear",Window="Rear"},
new Car(){Break="front ",Window="front "}
};
var replaceItem=new Car(){Break="",Window=""};
foreach (var carDetail in Audi)
{
//carDetail = replaceItem; //Error
replaceItem = carDetail;
}
//Enumerator
var enumeratedAudi = Audi.GetEnumerator();
enumeratedAudi.MoveNext();
Console.WriteLine(enumeratedAudi.ToString());
List<Car>.Enumerator e = Audi.GetEnumerator();
e.MoveNext();
Console.WriteLine(e.ToString());
#endregion
#region Jump(Goto)
int jump = 0;
goto customLabel;
jump++;
customLabel:
Console.WriteLine("value of jump is:{0}",jump);
#endregion
#region While
var Hundai = new List<Car>()
{
new Car(){Break="Rear",Window="Rear"},
new Car(){Break="front ",Window="front "}
};
int Iwhile=0;
while (Iwhile < Hundai.Count())
{
Iwhile++;
}
#endregion
}
}
public class Car
{
public string Window { get; set; }
public string Break { get; set; }
}
}
|
PHP
|
UTF-8
| 5,557 | 2.625 | 3 |
[] |
no_license
|
<?php
$servername = "localhost";//localhost for local PC or use IP address
$username = "root"; //database name
$password = "";//database password
$database = "adidas";//database name
session_start();
// Create connection #scawx
$conn = new mysqli($servername, $username, $password,$database);
// Check connection #scawx
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['delete'])){
if(empty($_REQUEST['item'])){ //No item checked
}
else{
foreach($_REQUEST['item'] as $deleteId){
//delete the item with the username
echo $sql="delete from product where id='$deleteId'";
$result=$conn->query($sql);
echo'<script type=text/javascript>';//add myself
echo 'window.alert("Delete Successfull !!!")';
echo '</script>';
}
}
}
if(isset($_POST['logout'])){
session_destroy();
header('location:login.php');
}
?>
<!doctype html>
<html lang="en">
<link rel="icon" href="adidas-favicon.ico" type="image/x-icon"/>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="project.css">
<title>Adidas Product Table</title>
</head>
<style>
.custab{
border: 1px solid #ccc;
padding: 5px;
margin: 5% 0;
box-shadow: 3px 3px 2px #ccc;
transition: 0.5s;
}
.custab:hover{
box-shadow: 3px 3px 0px transparent;
transition: 0.5s;
}
.footer {
/* position: fixed; */
left: 0;
bottom: 0;
width: 80%;
height:30px;
margin-top:20px;
background-color: Grey;
color: white;
text-align: center;
margin-right:20px;
}
.fooBtn{
font-size:1.2em;
padding-top:20px;
padding-right:20px;
color:white;
}
</style>
<body>
<form action="productTable.php" method="POST">
<div class="container" style="text-align:center;margin-left:160px">
<div class="row col-md-10 col-md-offset-2 custyle" >
<table class="table table-striped custab">
<h4 style="text-align:center;padding-left:350px;padding-top:20px">Product Table</h4>
<thead>
<a href="DBManagement.php" class="btn btn-primary" style="margin-left:50px;padding-top:15px;text-align:center"><b>+</b> Add new product</a>
<tr>
<th></th>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Image</th>
<th>color</th>
<!-- <th>title</th>
<th width="70px;">decripution</th> -->
<th>Quantity</th>
<th>Style</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
<?php
$sql="select * from product ";//id is database name
$result=$conn->query($sql);
if($result->num_rows > 0){ //over 1 database(record) so run
while($row = $result->fetch_assoc()){
//display result
$id=$row['id'];//[] inside is follow database
$name=$row['name'];
$color=$row['color'];
$price=$row['price'];
$image=$row['image'];
$quantity=$row['quantity'];
$style=$row['style'];
// $ProductTitle=$row['title'];
// $ProductDescription=$row['description'];
?>
<tr>
<td><input type="checkbox" name="item[]" value="<?php echo $id;?>"></td>
<td><?php echo $id; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $price; ?></td>
<td><?php echo $image; ?></td>
<td><?php echo $color; ?></td>
<!-- <td><?php echo $ProductTitle;?></td>
<td><?php echo $ProductDescription;?></td> -->
<td><?php echo $quantity; ?></td>
<td><?php echo $style; ?></td>
<td class="text-center">
<a class='btn btn-info btn-xs' href="DBManagement.php?id=<?php echo $id;?>"><span class="glyphicon glyphicon-edit"></span> Edit </a>
</td>
</tr>
<?php
}//end while
}//end if
?>
<tr>
<td colspan="11" style="text-align:center">
<button name="delete" type="submit" class="btn btn-danger btn-xs">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</form>
<div class="footer">
<!-- <P>footer</p> -->
<a class="fooBtn" href="DBManagement.php">Create New Product</a>
<a class="fooBtn" href="userTable.php">User Table</a>
<a class="fooBtn" href="orderTable.php">OrderList Table</a>
<a class="fooBtn" href="StaffLogin.php" onclick="return confirm('Are you sure logout?')">Logout</a>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
|
Python
|
UTF-8
| 4,060 | 2.6875 | 3 |
[] |
no_license
|
from orangecontrib.interactions.interactions import Interaction, Interactions
from orangecontrib.interactions.utils import load_mushrooms_data
from orangecontrib.bio.geo import GDS
from Orange.widgets import gui, settings, widget, highcharts
import Orange
class StackedBar(highcharts.Highchart):
"""
StackedBar extends Highchart and just defines chart_type:
"""
def __init__(self, **kwargs):
super().__init__(chart_type='bar',
**kwargs)
class OWInteractionGraph(widget.OWWidget):
"""Interactions visualization using Highcharts"""
name = 'An interaction graph'
description = 'An example stacked bar plot visualization using Highcharts.'
icon = "icons/mywidget.svg"
inputs = [("Interaction", Interaction, "set_interaction")]
outputs = []
graph_name = 'interaction'
def __init__(self):
super().__init__()
self.data = None
# Create an instance of StackedBar. Initial Highcharts configuration
# can be passed as '_'-delimited keyword arguments. See Highcharts
# class docstrings and Highcharts API documentation for more info and
# usage examples.
self.interaction_graph = StackedBar(title_text='Interactions graph',
plotOptions_series_stacking='normal',
yAxis_min=0,
yAxis_max=1,
yAxis_title_text='Relative information gain',
tooltip_shared=False)
# Just render an empty chart so it shows a nice 'No data to display'
# warning
self.interaction_graph.chart()
self.mainArea.layout().addWidget(self.interaction_graph)
def set_interaction(self, interactions_list):
self.data = interactions_list
categories_left = []
categories_right = []
info_gains_left = []
info_gains_right = []
interaction_gains = []
interaction_colors = []
for o in self.data:
categories_left.append(o.var_a.name)
categories_right.append(o.var_b.name)
ab = o.rel_ig_ab
if ab < 0:
a = o.rel_ig_a
b = o.rel_ig_b
ab = -ab
interaction_colors.append('#90ee7e') # #90ee7e #55BF3B
else:
a = o.rel_ig_a - ab
b = o.rel_ig_b - ab
interaction_colors.append('red') # #DF5353
info_gains_left.append(b)
interaction_gains.append(ab)
info_gains_right.append(a)
options = dict(series=[], xAxis=[])
options['series'].append(dict(data=info_gains_left, name='Isolated attribute info gain', color='#7cb5ec'))
options['series'].append(dict(data=interaction_gains,
name='Interaction info gain',
colorByPoint=True,
colors = interaction_colors))
options['series'].append(dict(data=info_gains_right, name='Isolated attribute info gain', color='#7cb5ec')) ##7798BF
options['xAxis'].append(dict(categories=categories_left,
labels = dict(step=1)))
options['xAxis'].append(dict(categories=categories_right,
opposite=True,
linkedTo=0,
labels = dict(step=1)))
self.interaction_graph.chart(options)
def main():
from PyQt4.QtGui import QApplication
app = QApplication([])
ow = OWInteractionGraph()
# d = Orange.data.Table('lenses')
d = load_mushrooms_data()
# gds = GDS("GDS1676")
# d = gds.getdata()
inter = Interactions(d)
inter.interaction_matrix()
int_object = inter.get_top_att(5)
ow.set_interaction(int_object)
ow.show()
app.exec_()
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 6,738 | 4.34375 | 4 |
[] |
no_license
|
# ------------------------------
# Python Lists and Dictionaries
# ------------------------------
# Exercise 1
zoo_animals = ["pangolin", "cassowary", "sloth", "panda" ];
# One animal is missing!
if len(zoo_animals) > 3:
print "The first animal at the zoo is the " + zoo_animals[0]
print "The second animal at the zoo is the " + zoo_animals[1]
print "The third animal at the zoo is the " + zoo_animals[2]
print "The fourth animal at the zoo is the " + zoo_animals[3]
# Exercise 2
numbers = [5, 6, 7, 8]
print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
# Your code here!
print numbers[1] + numbers [3]
# Exercise 3
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked
#the poor tiger and ate it whole.
# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
# What shall fill the void left by our dear departed tiger?
# Your code here!
zoo_animals[3] = "panda"
# Exercise 4
suitcase = []
suitcase.append("sunglasses")
# Your code here!
suitcase.append("shirts")
suitcase.append("shoes")
suitcase.append("pants")
list_length = len(suitcase) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase
# Exercise 5
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # The first and second items (index zero and one)
middle = suitcase[2:4] # Third and fourth items (index two and three)
last = suitcase[4:6] # The last two items (index four and five)
# Exercise 6
animals = "catdogfrog"
cat = animals[:3] # The first three characters of animals
dog = animals[3:6] # The fourth through sixth characters
frog = animals[6:] # From the seventh character to the end
#Exericse 7
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"
# Your code here!
animals.insert(duck_index, "cobra")
print animals # Observe what prints after the insert operation
# Exericse 8
my_list = [1,9,3,8,5,7]
for number in my_list: # "for" runs for how many items there are in a list
# Your code here
print 2 * number
# Exercise 9
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for numbers in start_list:
square_list.append(numbers**2)
print square_list.sort()
# Exercise 10
# Dictionaries are like lists, but they store stuff with a key
# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
# key value
# Used for name/password, name/phone number, etc.
print residents['Puffin'] # Prints Puffin's room number
# Your code here!
print residents['Sloth']
print residents['Burmese Python']
# Exercise 11
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
# Your code here: Add some dish-price pairs to menu!
menu['Pasta'] = 7.00
menu['Mozarella sticks'] = 4.00
menu['Garlic bread'] = 2.00
print "There are " + str(len(menu)) + " items on the menu."
print menu
# Exercise 12
# key - animal_name : value - location
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
# Your code here!
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Panda'
print zoo_animals
# ------------------------------
"""SuperMarket"""
# ------------------------------
#Exercise 1
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for n in names:
print n
# Exercise 2
webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the floor.",
"Dab": "A small amount."
}
# Add your code below!
for k in webster:
print webster[k]
# Exercise 3
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
for numbers in a:
if numbers%2==0:
print numbers
# Exercise 4
# Write your function below!
def fizz_count(x):
count = 0
for item in x:
if item == "fizz":
count = count+1
return count
# Exercise 5
for letter in "Codecademy":
print letter
# Empty lines to make the output pretty
print
print
word = "Programming is fun!"
for letter in word:
# Only print out the letter i
if letter == "i":
print letter
# Exercise 6
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Exercise 7
prices = {
"banana": 4, # Don't forget commas after values in the key
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
# Exercise 8
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15,
}
for key in prices:
print key
print "price: %s" % prices[key] # Make sure to use %s here.
print "stock: %s" % stock[key]
# Exercise 9
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = 0
for key in prices:
print prices[key] * stock[key]
total = total + prices[key] * stock[key]
print total
# Exercise 10
groceries = ['banana', 'orange', 'apple']
# Exercise 11
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
total = total + prices[item] # Kind of understand this one...
return total
#Exercise 12
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0: # Adding a conditional inside a loop inside a function inside a...
total = total + prices[item]
stock[item]=stock[item]-1
return total
|
JavaScript
|
UTF-8
| 1,136 | 2.609375 | 3 |
[] |
no_license
|
// элемент с классом with-popup-border
// за ним - popup-border
var z_base = 1;
var z_delta = 1;
function on_over_main() {
//если подключен shift-block, при выборе блока
//будет устанавливаться ему(блоку) такой атрибут
if (this.parentNode.parentNode._shift_block_selected) return;
var c1 = this.parentNode.children[1];
if (c1._popup_disabled) return;
c1.style.display = 'block';
c1.style.zIndex = z_base;
this.style.zIndex = z_base+z_delta;
}
function on_out_main(e) {
var c1 = this.parentNode.children[1];
if (e.toElement !== c1) c1.onmouseout();
}
function on_out_popup() {
var c0 = this.parentNode.children[0];
this.style.display = 'none';
this.style.zIndex = z_base;
c0.style.zIndex = z_base-z_delta;
}
var es = document.getElementsByClassName("with-popup-border");
for (var i=0; i<es.length; i++) {
var main_elem = es[i];
var popup_border = main_elem.parentNode.children[1];
if (!popup_border) continue;
main_elem.onmouseover = on_over_main;
main_elem.onmouseout = on_out_main;
popup_border.onmouseout = on_out_popup;
}
|
JavaScript
|
UTF-8
| 316 | 2.578125 | 3 |
[] |
no_license
|
import {foot} from '../read/readFooter.js';
import {addTask} from '../onclicks/addTask';
export const addButton = () =>
{
let add=document.createElement("button");
add.textContent="Add tasks to be done";
add.setAttribute("class","btn btn-success");
add.onclick=addTask;
foot.appendChild(add);
}
|
Java
|
UTF-8
| 1,078 | 2.171875 | 2 |
[] |
no_license
|
package com.hiperf.common.ui.client.event;
import com.google.gwt.event.shared.GwtEvent;
import com.hiperf.common.ui.client.IWrappedFlexTableEvent;
public class SwitchColumnsEvent extends GwtEvent<SwitchColumnsHandler> implements IWrappedFlexTableEvent {
private static final Type<SwitchColumnsHandler> TYPE = new Type<SwitchColumnsHandler>();
private int index1;
private String att1;
private int index2;
private String att2;
public SwitchColumnsEvent(int i1, String att1, int i2, String att2) {
this.index1 = i1;
this.att1 = att1;
this.index2 = i2;
this.att2 = att2;
}
public static Type<SwitchColumnsHandler> getType() {
return TYPE;
}
public int getIndex1() {
return index1;
}
public int getIndex2() {
return index2;
}
public String getAtt1() {
return att1;
}
public String getAtt2() {
return att2;
}
@Override
protected void dispatch(SwitchColumnsHandler handler) {
handler.onSwitchColumns(this);
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<SwitchColumnsHandler> getAssociatedType() {
return TYPE;
}
}
|
Java
|
UTF-8
| 223 | 1.695313 | 2 |
[] |
no_license
|
package com.yc.jianjiao.event;
/**
* Created by edison on 2019/3/15.
*/
public class DownloadSuccessInEvent {
public String name;
public DownloadSuccessInEvent(String name) {
this.name = name;
}
}
|
Java
|
UTF-8
| 2,430 | 2.328125 | 2 |
[] |
no_license
|
package dm.transform;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import static org.hamcrest.CoreMatchers.instanceOf;
import dm.transform.constants.TransformType;
import dm.transform.json.JsonDataTransform;
import dm.transform.DataTransform;
/**
*
* @author mannam
*
*/
public class DataTransformFactoryTest {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
private File specFile;
@Before
public void setUp() throws IOException {
// Create a temporary file.
specFile = testFolder.newFile("spec.json");
FileUtils.writeStringToFile(specFile, "[\n" +
" {\n" +
" \"operation\": \"shift\",\n" +
" \"spec\": {\n" +
" \"rating\": {\n" +
" \"primary\": {\n" +
" \"value\": \"Rating\"\n" +
" },\n" +
" \"*\": {\n" +
" \"value\": \"SecondaryRatings.&1.Value\",\n" +
" \"$\": \"SecondaryRatings.&.Id\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }]");
}
@Test(expected=RuntimeException.class)
public void testJsonTransformInstanceFailure() {
//throws RuntimeException because "TEST" passed in as spec file path
DataTransformFactory.getDataTransform(TransformType.JSON, "TEST");
}
@Test
public void testJsonTransformInstanceSuccess() throws IOException {
DataTransform transform = DataTransformFactory.getDataTransform(TransformType.JSON, specFile.getAbsolutePath());
assertThat(transform, instanceOf(JsonDataTransform.class));
}
@Test
public void testJsonTransformSameInstance() {
DataTransform transformOne = DataTransformFactory.getDataTransform(TransformType.JSON, specFile.getAbsolutePath());
DataTransform transformSecond = DataTransformFactory.getDataTransform(TransformType.JSON, specFile.getAbsolutePath());
assertSame(transformOne,transformSecond);
}
@After
public void tearDown() {
testFolder.delete();
}
}
|
Markdown
|
UTF-8
| 1,191 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
# Caching
API Umbrella provides a standard HTTP caching layer in front of your APIs (using [Apache Traffic Server](http://trafficserver.apache.org)). In order to utilize the cache, your API backend must set HTTP headers on the response. In addition to the standard `Cache-Control` or `Expires` HTTP headers, we also support the `Surrogate-Control` header.
## Surrogate-Control
The `Surrogate-Control` header will only have an effect on the API Umbrella cache. This header will be stripped before the response is delivered publicly.
```
Surrogate-Control: max-age=(time in seconds)
```
## Cache-Control: s-maxage
The `Cache-Control: s-maxage` header will be respected by the API Umbrella cache, as well as any other intermediate caches between us and the user.
```
Cache-Control: s-maxage=(time in seconds)
```
## Cache-Control: max-age
The `Cache-Control: max-age` header will be respected by the API Umbrella cache, intermediate caching servers, and the user's client.
```
Cache-Control: max-age=(time in seconds)
```
## Expires
The `Expires` header will be respected by the API Umbrella cache, intermediate caching servers, and the user's client.
```
Expires: (HTTP date)
```
|
Java
|
UTF-8
| 573 | 1.773438 | 2 |
[] |
no_license
|
package cn.storm.mapper;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Repository;
import cn.storm.pojo.EngageResume;
@Repository
public interface EngageResumeMapper {
public boolean saveEngageResume(EngageResume engageresume);
public List<EngageResume> selectAllEngageResume();
public EngageResume selectEngageResumeByresId(int resId);
public boolean deleteEngageResumeByresId(int resId);
public int updateEngageResume(EngageResume engageresume);
public List<EngageResume> selectByDiction(HashMap<String, Object> map);
}
|
Ruby
|
UTF-8
| 205 | 3.046875 | 3 |
[] |
no_license
|
puts "Salut, bienvenue dans ma super pyramide ! Combien d'étages veux-tu ?"
print "> "
etages = gets.chomp.to_i
puts "Voici la pyramide :"
etageX = "#"
etages.times do |i|
puts etageX
etageX += "#"
end
|
JavaScript
|
UTF-8
| 7,840 | 2.703125 | 3 |
[] |
no_license
|
import React, {useState, useEffect} from 'react';
import {v4 as uuid} from 'uuid';
import {DragDropContext, Droppable} from 'react-beautiful-dnd';
import Column from './components/Column.jsx';
import Header from './components/Header.jsx';
import axios from 'axios';
import AddColumn from './components/AddColumn.js';
/* random image */
const imageUrl = 'https://source.unsplash.com/random/?people/';
function getRandomColor() {
return '#'+Math.floor(Math.random()*16777215).toString(16);
}
/* imageurl needs uuid/number at the end to be random so browser don't cache the image */
const columnsFromServer =
{ [uuid()] : {
name: 'Backlog',
items: [{id: uuid(), content: "asdasdas asdasdas asdasdas asdasdas asdasdas asdasdas asdasdas asdasdas asdasdas ", assigned:imageUrl + uuid(), date: "as", color: getRandomColor(), image: ""}]
}
};
/* columns from the server, currently hard coded. */
/* function for when the drag ends, accounts for when dragging to other columns or to nowhere */
const dragEnd = (result, columns, setColumns) => {
if (!result.destination) return;
const {source, destination } = result;
if(source.droppableId !== destination.droppableId) {
const sourceColumn = columns[source.droppableId];
const destColumn = columns[destination.droppableId];
const sourceItems = [...sourceColumn.items];
const destItems = [...destColumn.items];
const [removed] = sourceItems.splice(source.index, 1);
destItems.splice(destination.index, 0, removed);
setColumns({
...columns,
[source.droppableId]: {
...sourceColumn,
items: sourceItems
},
[destination.droppableId]: {
...destColumn,
items: destItems
}
})
const savedDestination = {
tasks:destItems
}
const savedSource = {
tasks:sourceItems
}
console.log(result.destination)
axios.post('/exercises/update/' + result.destination.droppableId, savedDestination)
.then(res => console.log(res.data))
axios.post('/exercises/update/' + result.source.droppableId, savedSource)
.then(res => console.log(res.data))
}
else {
const column = columns[source.droppableId];
const copy = [...column.items];
const [removed] = copy.splice(source.index, 1);
copy.splice(destination.index, 0, removed);
setColumns({
...columns,
[source.droppableId]: {
...column,
items: copy
}
});
const savedSource = {
tasks:copy
}
axios.post('/exercises/update/' + result.source.droppableId, savedSource)
.then(res => console.log(res.data))
}
};
function App() {
const [columns, setColumns] = useState(columnsFromServer);
const [toggle, setToggle] = useState(false)
const [weather, setWeather] = useState({
temp:"",
weather:""
})
useEffect(() => {
const col = {
}
axios.get("/exercises")
.then(response => {
console.log(response.data.length)
if (response.data.length > 0) {
response.data.forEach((task) => {
col[task.id] = {
name : task.category,
items: task.tasks
}
}
)
}
setColumns(col)
})
},[]);
useEffect(() => {
console.log("asd")
axios.get("/api/weather")
.then(response => {
console.log(response.data)
setWeather(response.data)
})
console.log("yes")
}, [columns])
/* add to column the new task or update it */
function addToColumn(destination, id, task) {
const column = columns[destination]
var updated = [...column.items]
const object = {id: uuid(), content: task.title, assigned:imageUrl + uuid(), date: task.date, color: getRandomColor(), image: task.image}
if (id != null) {
var index = updated.findIndex( x => x.id === id)
updated[index] = object
}
else {
updated.push(object)
}
const serverColumn = {
tasks:updated
}
axios.post('/exercises/update/' + destination, serverColumn)
.then(res => console.log(res.data))
setColumns({
...columns,
[destination]: {
...column,
items: updated
}
});
}
function deleteFromColumn(destination, id) {
const column = columns[destination]
var updated = [...column.items]
var index = updated.findIndex( x => x.id === id)
updated.splice(index, 1)
setColumns({
...columns,
[destination]: {
...column,
items: updated
}
});
const serverColumn = {
tasks: updated
}
axios.post('/exercises/update/' + destination, serverColumn)
.then(res => console.log(res.data))
}
function addColumn(name){
// const data = {
// id: uuid(),
// category: name,
// tasks:[]
// }
// axios.post("/exercises/add", data)
// .then(res => console.log(res.data))
// setColumns({
// ...columns,
// [uuid()]: {
// name: name,
// items: []
// }
// });
// setToggle(false)
const data = {
title: "",
description: "",
url: ""
}
axios.post("/upload", data)
.then(res => {
console.log(res.data)
})
}
function deleteColumn(destination) {
}
function toggleAdd() {
setToggle(!toggle)
}
return (
<div>
<Header>
</Header>
<button onClick={toggleAdd} style={{width:"100px", height:"50px", margin:"20px", float:"left"}}>Add</button>
<h1 style={{width:"150px", height:"50px", margin:"20px", float:"right"}}>{weather.temp} °F <br></br> {weather.weather}</h1>
<div style={{ display: 'flex', justifyContent: 'center', height: '100%'}}>
<DragDropContext onDragEnd={result => dragEnd(result, columns, setColumns)}>
{Object.entries(columns).map(([id, column]) => {
return (
<div style={{display:'flex', flexDirection: 'column', alignItems: 'center'}} key={uuid()}>
<h2>{column.name}</h2>
<div style ={{margin: 8}}>
<Droppable droppableId={id} key={id}>
{(provided, snapshot) => {
return (
<Column key={id} provided={provided} snapshot={snapshot} column={column} addToColumn={addToColumn} id={id} editTask={addToColumn} deleteTask={deleteFromColumn}/>
)
}}
</Droppable>
</div>
</div>
)
})}
</DragDropContext>
</div>
{toggle ? <AddColumn addColumn={addColumn} toggleAdd={toggleAdd}></AddColumn> : null}
</div>
)
}
export default App
|
C++
|
UTF-8
| 708 | 2.875 | 3 |
[] |
no_license
|
// CodeJam2014.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <cstdio>
using namespace std;
int T;
double C, F, X;
int main()
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
scanf("%d", &T);
for (int i = 0; i < T; i++)
{
scanf("%lf%lf%lf", &C, &F, &X);
double time = 0, speed = 2;
while (true)
{
double buy_t;
double not_t;
buy_t = time + C / speed + X / (speed + F);
not_t = time + X / speed;
if (buy_t < not_t)
{
time = time + C / speed;
speed += F;
}
else
{
time = not_t;
break;
}
}
printf("Case #%d: %.7lf\n", i + 1, time);
}
}
|
C
|
UTF-8
| 300 | 3.328125 | 3 |
[] |
no_license
|
#include <stdio.h>
int fib(int N)
{
if (0 == N)
{
return 0;
}
if (1 == N)
{
return 1;
}
int f0 = 0;
int f1 = 1;
int f = 0;
for (int i = 2; i <= N; ++i)
{
f = f0 + f1;
f0 = f1;
f1 = f;
}
return f;
}
|
Shell
|
UTF-8
| 1,193 | 3.359375 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
if [ $# -eq 2 ]; then
geofile=$1
maxhe=$2
else
echo "Wrong input"
echo "Usage: generate_gmsh_mesh <geo-file> <scale>"
exit
fi
rm -f gmsh.mesh log
time gmsh $geofile -v 10 -3 -o gmsh.mesh -format mesh -clmax $maxhe -clscale $maxhe | tee log
echo "maxhe=$maxhe" >> log
if [ -f gmsh.mesh ]; then
nodes=`head -5 gmsh.mesh | tail -1`
dir=mesh`echo $nodes`
mkdir -p $dir
cd $dir
mv ../gmsh.mesh .
mv ../log gmsh.log
grep ille gmsh.log
echo =============================
grep ille gmsh.log | grep -v no
gmsh2tetgen_mprans_withtags gmsh.mesh
cp mesh.vtk ../$dir.vtk
echo =============================
ls -lhatr mesh.*
cp mesh.ele mesh_save.ele
cp mesh.node mesh_save.node
tetgen -Vfeen mesh.ele
echo =============================
ls -lhatr mesh.*
mv mesh.1.ele mesh.ele
mv mesh.1.node mesh.node
mv mesh.1.face mesh.face
mv mesh.1.neigh mesh.neigh
mv mesh.1.edge mesh.edge
echo =============================
ls -lhatr mesh.*
grep ille gmsh.log
echo =============================
grep ille gmsh.log | grep -v no
echo =============================
echo $nodes nodes
echo =============================
fi
|
JavaScript
|
UTF-8
| 1,841 | 3.625 | 4 |
[] |
no_license
|
import React, { useRef, useState } from 'react';
function Gugudan2() {
// 바뀌는 부분을 state로
const nameInput = useRef();
const [first, setFirst] = useState(Math.ceil(Math.random() * 9));
const [second, setSecond] = useState(Math.ceil(Math.random() * 9));
const [value, setValue] = useState('');
const [result, setResult] = useState('');
// (핵심)키입력을 위해 set이용
const onChange = e => {
setValue(e.target.value);
setResult('');
};
const onSubmit = e => {
e.preventDefault(); // 새로고침 방지
if (parseInt(value) === first * second) {
setFirst(Math.ceil(Math.random() * 9));
setSecond(Math.ceil(Math.random() * 9));
setValue('');
setResult('정답: ' + value);
nameInput.current.focus(); // current는 해당 요소의 DOM을 가르킴
} else {
setValue('');
setResult('땡');
nameInput.current.focus();
}
// setState({
// first: first, // input에 값 입력시 렌더링이 새롭게 되므로 값이 모두 초기화 됨
// second: second,
// value: '',
// result: '땡',
// })
};
console.log('렌더링'); // setState함수가 실행되면 다시 렌더링이 됨
return (
<div>
<div>
{first}곱하기{second}?
</div>
{/*태그사이에 중괄호를 넣으면 JS 사용가능*/}
<form onSubmit={onSubmit}>
<input
type="number"
value={value}
onChange={onChange}
ref={nameInput}
/>{' '}
{/* 현재 input에 상태는 키입력이 안되므로 set을 통하여 키 입력이 가능하도록 변경 */}
<button>입력!</button>
</form>
{/*<div>{`${multiply}은 ${result}`}</div>*/}
<div>{result}</div>
</div>
);
}
export default Gugudan2;
|
C++
|
UTF-8
| 962 | 4.0625 | 4 |
[] |
no_license
|
// Change.cpp using greedy algorithm
/* Given an input, n (user input), display the amount of coins they get in change.
For this problem coin denominations are simplified to 1, 5 and 10,
i.e. 29 = 10 + 10 + 5 + 1 + 1 + 1 + 1. Thus the change output is 7 */
#include<iostream>
using std::cout;
// Function Change accepts input, n, from user then using 'if' statements allocates change in 10's, 5's and 1's.
int Change(int n)
{
int change = 0;
int A = n;
while (A != 0)
{
// Give change in 10's
if (A % 10 == 0)
{
A = A - 10;
change += 1;
}
// Give change in 5's
else if (A % 5 == 0)
{
A = A - 5;
change += 1;
}
// Give change in 1's
else
{
A = A - 1;
change += 1;
}
}
return change;
}
// Function main allows user to input an integer, n, (1 <= n <= 10^3) and then outputs Change function
int main()
{
int n;
std::cin >> n;
cout << Change(n);
}
|
Go
|
UTF-8
| 1,300 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package gorm
import (
"errors"
uuid "github.com/satori/go.uuid"
"gorm.io/gorm"
"github.com/guanfantech/SubGameCenterService/domain"
)
type adminRepository struct {
db *gorm.DB
}
func NewAdminRepository(db *gorm.DB) domain.AdminRepository {
return &adminRepository{
db: db,
}
}
func (repo *adminRepository) ListAll() ([]*domain.Admin, error) {
var model []*domain.Admin
err := repo.db.Model(&Admin{}).Find(&model).Error
if err != nil {
return nil, err
}
return model, nil
}
func (repo *adminRepository) GetUserByAccount(account string) (*domain.Admin, error) {
var admin domain.Admin
err := repo.db.Where("account = ?", account).First(&admin).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &admin, nil
}
func (repo *adminRepository) GetUserByUUID(UUID uuid.UUID) (*domain.Admin, error) {
var admin domain.Admin
err := repo.db.Where("uuid = ?", UUID).First(&admin).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
if err != nil {
return nil, err
}
return &admin, nil
}
func (repo *adminRepository) UpdatePasswordByUUID(UUID uuid.UUID, password string) error {
var model Admin
return repo.db.Model(&model).
Where("uuid = ?", UUID).
Update("password", password).Error
}
|
Markdown
|
UTF-8
| 3,084 | 3.25 | 3 |
[] |
no_license
|
## 语法图
在下一节中,我们将了解解析表达式文法(PEG),一个EBNF的变种。使用语法图将有助于对PEG的理解。语法图是文法的图形化表示,它曾经被Niklaus Wirth在"Pascal用户手册"中被广泛使用。由于他们和流程图相似,语法图很容易被程序员理解。
图和函数的同构性使它们非常适合于表示递归下降解析器,递归下降解析器本质上是互递归函数。
历史上,PEG只用来为解析器描述语法(所以叫这个名字),在Spirit中,我们也同样为输出生成使用非常相似的记号。在这里描述的所有概念几乎都能在`Spirit.Qi`的解析器和`Spirit.Karma`的生成器中被同样地应用。
### 元素
所有语法图含有一个进入点和一个退出点,箭头链接所有从进入点到退出点的可能的语法路径

终端点用圆框表示。终端点是原子性的,通常用来表示普通的字符,字符串或者是单词。

非终端点用方框表示,图形可以用命名非终端点来模块化。一个复杂的图形能够分解成非终端点的集合。非终端点同样允许递归(比如一个非终端点能调用它自己)

### 结构
最基础的组合是序列,B跟在A之后

有序选择,我们只之后称他作选择(*alternatives*)。在PEG中,有序选择和选择并不完全一样。PEG允许有歧义的选择,这样一个或多个分支都能匹配成功。在PEG中出现歧义,第一个分支优先被匹配。

可选(零个或一个)

现在,在循环中,我们有**零个或多个**和**一个或多个**


注意,这些循环是贪婪的,如果在终止点前有另一个`A`,它将永远失败,因为前面的循环已经穷尽了所有的`A`,然后之后不应该还有`A`了。这个是PEG和通用上下文无关文法(CFG)的区别,这个行为在语法图中很明显,因为他们类似于流程图。
### 谓词
现在下面的是PEG谓词的语法图版本。这些在传统的语法图中是找不到的。这些是我们为了更好解释PEG而发明的特殊拓展。
首先,我们介绍一个新元素,他叫谓词

这和流程图中的条件框相似,但是`否`分支不用画出来,它总是表示解析失败
我们有两种谓词版本,**与谓词**和**非谓词**:


**与谓词**尝试断言P,当P成功时即为成功,否则就失败。**非谓词**和**与谓词**相反,它尝试断言P,当P失败时成功,否则为失败。两个版本都是超前的,他们不会消耗任何输入,不管P成功与否。
|
Shell
|
UTF-8
| 2,116 | 3.9375 | 4 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
SELENIUM_TAG=$1
BROWSER=$2
function short_version() {
local __long_version=$1
local __version_split=( ${__long_version//./ } )
echo "${__version_split[0]}.${__version_split[1]}"
}
echo "Tagging images for browser ${BROWSER}..."
case "${BROWSER}" in
chrome)
docker pull selenium/standalone-chrome:${SELENIUM_TAG}
CHROME_VERSION=$(docker run --rm selenium/standalone-chrome:${SELENIUM_TAG} google-chrome --version | awk '{print $3}')
echo "Chrome version -> "${CHROME_VERSION}
CHROME_SHORT_VERSION="$(short_version ${CHROME_VERSION})"
echo "Short Chrome version -> "${CHROME_SHORT_VERSION}
CHROME_TAGS=(
${CHROME_VERSION}
${CHROME_SHORT_VERSION}
)
for chrome_tag in "${CHROME_TAGS[@]}"
do
docker build -t saucelabs/stg-chrome:${chrome_tag} --build-arg SELENIUM_TAG=${SELENIUM_TAG} -f dockerfile_stg_chrome .
done
;;
edge)
docker pull selenium/standalone-edge:${SELENIUM_TAG}
EDGE_VERSION=$(docker run --rm selenium/standalone-edge:${SELENIUM_TAG} microsoft-edge --version | awk '{print $3}')
echo "Edge version -> "${EDGE_VERSION}
EDGE_SHORT_VERSION="$(short_version ${EDGE_VERSION})"
echo "Short Edge version -> "${EDGE_SHORT_VERSION}
EDGE_TAGS=(
${EDGE_VERSION}
${EDGE_SHORT_VERSION}
)
for edge_tag in "${EDGE_TAGS[@]}"
do
docker build -t saucelabs/stg-edge:${edge_tag} --build-arg SELENIUM_TAG=${SELENIUM_TAG} -f dockerfile_stg_edge .
done
;;
firefox)
docker pull selenium/standalone-firefox:${SELENIUM_TAG}
FIREFOX_VERSION=$(docker run --rm selenium/standalone-firefox:${SELENIUM_TAG} firefox --version | awk '{print $3}')
echo "Firefox version -> "${FIREFOX_VERSION}
FIREFOX_SHORT_VERSION="$(short_version ${FIREFOX_VERSION})"
echo "Short Firefox version -> "${FIREFOX_SHORT_VERSION}
FIREFOX_TAGS=(
${FIREFOX_VERSION}
${FIREFOX_SHORT_VERSION}
)
for firefox_tag in "${FIREFOX_TAGS[@]}"
do
docker build -t saucelabs/stg-firefox:${firefox_tag} --build-arg SELENIUM_TAG=${SELENIUM_TAG} -f dockerfile_stg_firefox .
done
;;
*)
echo "Unknown browser!"
;;
esac
|
Java
|
UTF-8
| 20,757 | 2.28125 | 2 |
[] |
no_license
|
// (jEdit options) :folding=explicit:collapseFolds=1:
//{{{ Package, imports
package king.tool.export;
import king.*;
import king.core.*;
import king.points.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.text.*;
import java.util.*;
//import java.util.regex.*;
import javax.swing.*;
import driftwood.gui.*;
import driftwood.util.SoftLog;
// XML stuff -- not 1.3 compatible unless JAXP is provided as a JAR.
import javax.xml.transform.*;
import javax.xml.transform.sax.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.xml.sax.ext.*;
import org.xml.sax.helpers.*;
//}}}
/**
* <code>XknWriter</code> writes out XML-format kinemage files.
*
* <p>Copyright (C) 2002 by Ian W. Davis. All rights reserved.
* <br>Begun on Thu Oct 3 09:51:11 EDT 2002
*/
public class XknWriter extends Plugin implements XMLReader
{
//{{{ Constants
static final DecimalFormat df = new DecimalFormat("0.####");
static final char[] newline = "\n".toCharArray();
//}}}
//{{{ Variable definitions
//##################################################################################################
ContentHandler cnHandler = null;
LexicalHandler lxHandler = null;
ErrorHandler errHandler = null;
String nsu = "";
JFileChooser fileChooser;
//}}}
//{{{ Constructor(s)
//##################################################################################################
/**
* Constructor
*/
public XknWriter(ToolBox tb)
{
super(tb);
fileChooser = new JFileChooser();
String currdir = System.getProperty("user.dir");
if(currdir != null) fileChooser.setCurrentDirectory(new File(currdir));
}
//}}}
//{{{ save()
//##################################################################################################
/** Writes out all the currently open kinemages */
public void save(OutputStream os)
{
try
{
BufferedOutputStream bos = new BufferedOutputStream(os);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
// Empty InputSource is OK, but it can't be null for some reason.
SAXSource source = new SAXSource(this, new InputSource());
StreamResult result = new StreamResult(bos);
transformer.transform(source, result); // calls parse()
}
catch(Throwable t)
{
System.err.println("*** Couldn't transform!");
t.printStackTrace(SoftLog.err);
}
}
//}}}
//{{{ parse()
//##################################################################################################
public void parse(InputSource input) throws IOException, SAXException
{
if(cnHandler == null) throw new SAXException("No content handler");
// Begin the document
String elName = "kinemages";
AttributesImpl atts = new AttributesImpl();
//atts.addAttribute(nsu, "x", "x", "CDATA", "this_is_x");
cnHandler.startDocument();
cnHandler.startElement(nsu, elName, elName, atts);
// Write out text
atts = new AttributesImpl();
atts.addAttribute(nsu, "mimetype", "mimetype", "CDATA", "text/plain");
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, "text", "text", atts);
if(lxHandler != null) lxHandler.startCDATA();
String kinText = kMain.getTextWindow().getText().trim();
cnHandler.characters(kinText.toCharArray(), 0, kinText.length());
if(lxHandler != null) lxHandler.endCDATA();
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, "text", "text");
// Write each kinemage
KinStable stable = kMain.getStable();
Kinemage kin;
int index = 1;
for(Iterator iter = stable.getKins().iterator(); iter.hasNext(); index++)
{
kin = (Kinemage)iter.next();
writeKinemage(kin, index);
}
// End the document
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endDocument();
}
//}}}
//{{{ writeKinemage()
//##################################################################################################
void writeKinemage(Kinemage kin, int index) throws SAXException
{
// Begin the element
String elName = "kinemage";
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(nsu, "index", "index", "CDATA", Integer.toString(index));
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
Iterator iter;
int idx = 1;
for(iter = kin.getViewList().iterator(); iter.hasNext(); idx++)
{
writeView((KView)iter.next(), idx);
}
for(iter = kin.masterList().iterator(); iter.hasNext(); )
{
writeMaster((MasterGroup)iter.next(), kin);
}
// etc.
KGroup group;
for(iter = kin.iterator(); iter.hasNext(); )
{
group = (KGroup)iter.next();
writeGroup(group, kin);
}
// End the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
//}}}
//{{{ writeGroup()
//##################################################################################################
void writeGroup(KGroup group, Kinemage kin) throws SAXException
{
Iterator iter;
String elName = "group";
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(nsu, "name", "name", "CDATA", group.getName());
if(! group.isOn()) atts.addAttribute(nsu, "off", "off", "CDATA", "true");
if(! group.hasButton()) atts.addAttribute(nsu, "nobutton", "nobutton", "CDATA", "true");
if( group.isDominant()) atts.addAttribute(nsu, "dominant", "dominant", "CDATA", "true");
if( group.isAnimate()) atts.addAttribute(nsu, "animate", "animate", "CDATA", "true");
if( group.is2Animate()) atts.addAttribute(nsu, "2animate", "2animate", "CDATA", "true");
// Begin the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
/*MasterGroup master;
for(iter = kin.masterIter(); iter.hasNext(); )
{
master = (MasterGroup)iter.next();
if(master.isTarget(group)) writeMasterReference(master);
}*/
for(iter = group.getMasters().iterator(); iter != null && iter.hasNext(); )
{
writeMasterReference(iter.next().toString());
}
KGroup subgroup;
for(iter = group.iterator(); iter.hasNext(); )
{
subgroup = (KGroup)iter.next();
writeSubgroup(subgroup, kin);
}
// End the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
//}}}
//{{{ writeSubgroup()
//##################################################################################################
void writeSubgroup(KGroup subgroup, Kinemage kin) throws SAXException
{
Iterator iter;
String elName = "subgroup";
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(nsu, "name", "name", "CDATA", subgroup.getName());
if(! subgroup.isOn()) atts.addAttribute(nsu, "off", "off", "CDATA", "true");
if(! subgroup.hasButton()) atts.addAttribute(nsu, "nobutton", "nobutton", "CDATA", "true");
if( subgroup.isDominant()) atts.addAttribute(nsu, "dominant", "dominant", "CDATA", "true");
// Begin the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
/*MasterGroup master;
for(iter = kin.masterIter(); iter.hasNext(); )
{
master = (MasterGroup)iter.next();
if(master.isTarget(subgroup)) writeMasterReference(master);
}*/
for(iter = subgroup.getMasters().iterator(); iter != null && iter.hasNext(); )
{
writeMasterReference(iter.next().toString());
}
KList list;
for(iter = subgroup.iterator(); iter.hasNext(); )
{
list = (KList)iter.next();
writeList(list, kin);
}
// End the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
//}}}
//{{{ writeList()
//##################################################################################################
void writeList(KList list, Kinemage kin) throws SAXException
{
Iterator iter;
String elName = "list";
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(nsu, "type", "type", "CDATA", list.getType());
atts.addAttribute(nsu, "name", "name", "CDATA", list.getName());
if(! list.isOn()) atts.addAttribute(nsu, "off", "off", "CDATA", "true");
if(! list.hasButton()) atts.addAttribute(nsu, "nobutton", "nobutton", "CDATA", "true");
atts.addAttribute(nsu, "color", "color", "CDATA", list.getColor().toString());
if(list.getType() == KList.VECTOR)
{ atts.addAttribute(nsu, "width", "width", "CDATA", Integer.toString(list.getWidth())); }
else if(list.getType() == KList.BALL || list.getType() == KList.SPHERE)
{
atts.addAttribute(nsu, "radius", "radius", "CDATA", df.format(list.getRadius()));
if(list.getNoHighlight())
{ atts.addAttribute(nsu, "highlight", "highlight", "CDATA", "false"); }
}
// Begin the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
/*MasterGroup master;
for(iter = kin.masterIter(); iter.hasNext(); )
{
master = (MasterGroup)iter.next();
if(master.isTarget(list)) writeMasterReference(master);
}*/
for(iter = list.getMasters().iterator(); iter != null && iter.hasNext(); )
{
writeMasterReference(iter.next().toString());
}
KPoint point;
for(iter = list.iterator(); iter.hasNext(); )
{
point = (KPoint)iter.next();
writePoint(point, list, kin);
}
// End the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
//}}}
//{{{ writePoint()
//##################################################################################################
void writePoint(KPoint point, KList list, Kinemage kin) throws SAXException
{
Iterator iter;
String elName = "t";
AttributesImpl atts = new AttributesImpl();
if(point.isBreak()) atts.addAttribute(nsu, "lineto", "lineto", "CDATA", "false");
atts.addAttribute(nsu, "name", "name", "CDATA", point.getName());
if(point.getPmMask() != 0) atts.addAttribute(nsu, "masters", "masters", "CDATA", kin.fromPmBitmask(point.getPmMask()));
if(point.getAspects() != null) atts.addAttribute(nsu, "aspects", "aspects", "CDATA", point.getAspects());
if(point.isUnpickable()) atts.addAttribute(nsu, "pickable", "pickable", "CDATA", "false");
if(point instanceof VectorPoint)
{
VectorPoint v = (VectorPoint)point;
if(v.getWidth() > 0 && v.getWidth() != list.getWidth())
{ atts.addAttribute(nsu, "width", "width", "CDATA", Integer.toString(v.getWidth())); }
}
else if(point instanceof BallPoint)
{
BallPoint b = (BallPoint)point;
{ atts.addAttribute(nsu, "radius", "radius", "CDATA", df.format(b.r0)); }
}
else if(point instanceof MarkerPoint)
{
MarkerPoint m = (MarkerPoint)point;
atts.addAttribute(nsu, "style", "style", "CDATA", Integer.toString(m.getStyle()));
}
if(point.getColor() != null)
{ atts.addAttribute(nsu, "color", "color", "CDATA", point.getColor().toString()); }
atts.addAttribute(nsu, "x", "x", "CDATA", df.format(point.getX()));
atts.addAttribute(nsu, "y", "y", "CDATA", df.format(point.getY()));
atts.addAttribute(nsu, "z", "z", "CDATA", df.format(point.getZ()));
// Begin the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
// End the element
//cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
//}}}
//{{{ writeView()
//##################################################################################################
void writeView(KView view, int index) throws SAXException
{
String elName = "view";
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(nsu, "name", "name", "CDATA", view.getName());
atts.addAttribute(nsu, "index", "index", "CDATA", Integer.toString(index));
float[] center = view.getCenter();
atts.addAttribute(nsu, "x", "x", "CDATA", df.format(center[0]));
atts.addAttribute(nsu, "y", "y", "CDATA", df.format(center[1]));
atts.addAttribute(nsu, "z", "z", "CDATA", df.format(center[2]));
atts.addAttribute(nsu, "span", "span", "CDATA", df.format(view.getSpan()));
atts.addAttribute(nsu, "zslab", "zslab", "CDATA", df.format(view.getClip()*200f));
// Writen out Mage-style, for a post-multiplied matrix
for(int i = 1; i < 4; i++)
{
for(int j = 1; j < 4; j++)
{ atts.addAttribute(nsu, "m"+i+j, "m"+i+j, "CDATA", df.format(view.xform[j-1][i-1])); }
}
// Begin the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
// End the element
//cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
//}}}
//{{{ writeMaster(Reference)()
//##################################################################################################
void writeMaster(MasterGroup master, Kinemage kin) throws SAXException
{
String elName = "master";
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(nsu, "name", "name", "CDATA", master.getName());
if(master.pm_mask != 0)
{ atts.addAttribute(nsu, "pointmaster", "pointmaster", "CDATA", kin.fromPmBitmask(master.pm_mask)); }
if(! master.isOn()) atts.addAttribute(nsu, "off", "off", "CDATA", "true");
if(! master.hasButton()) atts.addAttribute(nsu, "nobutton", "nobutton", "CDATA", "true");
// Begin the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
// End the element
//cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
void writeMasterReference(String master) throws SAXException
{
String elName = "master";
AttributesImpl atts = new AttributesImpl();
atts.addAttribute(nsu, "name", "name", "CDATA", master);
// Begin the element
cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.startElement(nsu, elName, elName, atts);
// End the element
//cnHandler.ignorableWhitespace(newline, 0, 1);
cnHandler.endElement(nsu, elName, elName);
}
///}}}
//{{{ get/set ContentHandler
//##################################################################################################
public ContentHandler getContentHandler()
{
return cnHandler;
}
public void setContentHandler(ContentHandler h)
{
cnHandler = h;
}
//}}}
//{{{ get/set ErrorHandler
//##################################################################################################
public ErrorHandler getErrorHandler()
{
return errHandler;
}
public void setErrorHandler(ErrorHandler h)
{
errHandler = h;
}
//}}}
//{{{ get/set Property
//##################################################################################################
public Object getProperty(String name)
{
if(( name.equals("http://xml.org/sax/properties/lexical-handler")
|| name.equals("http://xml.org/sax/handlers/LexicalHandler")))
{
return lxHandler;
}
else return null;
}
public void setProperty(String name, Object value)
{
if(( name.equals("http://xml.org/sax/properties/lexical-handler")
|| name.equals("http://xml.org/sax/handlers/LexicalHandler"))
&& value instanceof LexicalHandler)
{
lxHandler = (LexicalHandler)value;
}
}
//}}}
//{{{ other null methods for XMLReader
//##################################################################################################
public void parse(String systemID) throws IOException, SAXException
{}
public DTDHandler getDTDHandler()
{ return null; }
public void setDTDHandler(DTDHandler h)
{}
public EntityResolver getEntityResolver()
{ return null; }
public void setEntityResolver(EntityResolver e)
{}
public boolean getFeature(String name)
{ return false; }
public void setFeature(String name, boolean value)
{}
//}}}
//{{{ getToolsMenuItem, getHelpMenuItem, toString, onExport, isAppletSafe
//##################################################################################################
public JMenuItem getToolsMenuItem()
{
return new JMenuItem(new ReflectiveAction(this.toString()+"...", null, this, "onExport"));
}
/** Returns the URL of a web page explaining use of this tool */
public URL getHelpURL()
{
URL url = getClass().getResource("/extratools/tools-manual.html");
String anchor = getHelpAnchor();
if(url != null && anchor != null)
{
try { url = new URL(url, anchor); }
catch(MalformedURLException ex) { ex.printStackTrace(SoftLog.err); }
return url;
}
else return null;
}
public String getHelpAnchor()
{ return "#export-xml"; }
public String toString()
{ return "XML"; }
// This method is the target of reflection -- DO NOT CHANGE ITS NAME
public void onExport(ActionEvent ev)
{
if(fileChooser.showSaveDialog(kMain.getTopWindow()) == fileChooser.APPROVE_OPTION)
{
File f = fileChooser.getSelectedFile();
if( !f.exists() ||
JOptionPane.showConfirmDialog(kMain.getTopWindow(),
"This file exists -- do you want to overwrite it?",
"Overwrite file?", JOptionPane.YES_NO_OPTION)
== JOptionPane.YES_OPTION )
{
try
{
OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
this.save(os);
os.close();
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(kMain.getTopWindow(),
"An error occurred while saving the file.",
"Sorry!",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace(SoftLog.err);
}
catch(Throwable t)
{
JOptionPane.showMessageDialog(kMain.getTopWindow(),
"Your version of Java appears to be missing the needed XML libraries. File was not written.",
"Sorry!",
JOptionPane.ERROR_MESSAGE);
t.printStackTrace(SoftLog.err);
}
}
}
}
static public boolean isAppletSafe()
{ return false; }
//}}}
//{{{ empty_code_segment
//##################################################################################################
//}}}
}//class
|
C#
|
UTF-8
| 1,304 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.IO;
using MatterHackers.Agg.PlatformAbstract;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public abstract class SliceEngineInfo
{
public string Name
{
get;
set;
}
protected abstract string getWindowsPath();
protected abstract string getMacPath();
protected abstract string getLinuxPath();
public abstract SlicingEngineTypes GetSliceEngineType();
public SliceEngineInfo(string name)
{
Name = name;
}
public virtual bool Exists()
{
if (GetEnginePath() == null)
{
return false;
}
return File.Exists(GetEnginePath());
}
public string GetEnginePath()
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
//IL_0008: Unknown result type (might be due to invalid IL or missing references)
//IL_0022: Expected I4, but got Unknown
OSType operatingSystem = OsInformation.get_OperatingSystem();
return (operatingSystem - 1) switch
{
0 => getWindowsPath(),
1 => getMacPath(),
2 => getLinuxPath(),
4 => null,
_ => throw new NotImplementedException(),
};
}
}
}
|
C
|
UTF-8
| 5,890 | 3.125 | 3 |
[] |
no_license
|
#include "hw3.h"
#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
FILE *f;
int currIdx;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_buffer = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_i = PTHREAD_MUTEX_INITIALIZER;
void writeFile(void) {
int i = 0;
while (i < maxwords) {
fprintf(f, "%s\n", words[i]);
words[i][0] = '\0';
i++;
}
}
void writeBuffer(char *word, int i) {
fflush(NULL);
if (i == maxwords) {
pthread_mutex_lock(&mutex_buffer);
printf("MAIN: Buffer is full; writing %d words to output file\n", maxwords);
fflush(NULL);
writeFile();
i = 0;
currIdx = 0;
pthread_mutex_unlock(&mutex_buffer);
}
pthread_mutex_lock(&mutex_buffer);
strncpy(words[i], word, 80);
printf("TID %u: Stored \"%s\" in shared buffer at index [%d]\n",
(unsigned int)pthread_self(), word, i);
fflush(NULL);
pthread_mutex_unlock(&mutex_buffer);
}
void filesInfo(char ***directory, char *location, int *numFiles) {
DIR *dir = opendir(location);
printf("MAIN: Opened \"%s\" directory\n", location);
fflush(NULL);
struct dirent *file;
if (dir == NULL) {
perror("opendir() failed");
}
int ret = chdir(location);
if (ret == -1) {
perror("chdir() failed");
}
int i = 0;
while ((file = readdir(dir)) != NULL) {
struct stat buf;
int rc = lstat(file->d_name, &buf);
if (rc == -1) {
perror("lstat() failed");
}
if (S_ISREG(buf.st_mode)) {//check if it's a regular file
(*numFiles)++;
if (i == 0) {
*directory = (char **)calloc(1, sizeof(char *));
} else {
*directory = realloc(*directory, (i + 1) * sizeof(char *));
}
(*directory)[i] = (char *)calloc(80 + 1, sizeof(char));
strncpy((*directory)[i], file->d_name, 80);
i++;
}
}
printf("MAIN: Closed \"%s\" directory\n", location);
fflush(NULL);
closedir(dir);
}
void process(char *buff) {
char *tmpWord = (char *)calloc(80, sizeof(char));
int i = 0;
int j = 0;
int countWord = -1;
for (i = 0; i < strlen(buff); i++) {
if (isalpha(buff[i]) || isdigit(buff[i])) {
countWord += 1;
j = 0;
tmpWord[0] = buff[i];
while (1) {
j += 1;
if (isalpha(buff[i + j])) {
tmpWord[j] = buff[i + j];
} else if (isdigit(buff[i+j])) {
tmpWord[j] = buff[i + j];
} else {
break;
}
}
} else {
continue;
}
fflush(NULL);
if (j > 1) {
pthread_mutex_lock(&mutex);
writeBuffer(tmpWord, currIdx);
currIdx++;
pthread_mutex_unlock(&mutex);
} else {
countWord -= 1;
}
memset(tmpWord, 0, strlen(tmpWord));
i += j;
}
free(tmpWord);
tmpWord = NULL;
}
void *readFile(void *arg) {
char *file = (char *)arg;
char *buffer = NULL;
FILE *fp = fopen(file, "r");
printf("TID %u: Opened \"%s\"\n", (unsigned int)pthread_self(), file);
pthread_mutex_unlock(&mutex_i);
fflush(NULL);
if (fp != NULL) {
if (fseek(fp, 0L, SEEK_END) == 0) {
long bufsize = ftell(fp);
if (bufsize == -1) {
perror("ftell() failed");
}
buffer = (char *)calloc(bufsize + 1, sizeof(char));
if (fseek(fp, 0L, SEEK_SET) != 0) {
perror("fseek() failed");
}
size_t newLen = fread(buffer, sizeof(char), bufsize, fp);
if (newLen == 0) {
perror("fread() failed");
} else {
buffer[newLen] = '\0';
process(buffer);
}
}
fclose(fp);
printf("TID %u: Closed \"%s\"; and exiting\n", (unsigned int)pthread_self(),
file);
fflush(NULL);
}
free(buffer);
pthread_exit(NULL);
}
void multiThrd(char **directory, unsigned int numFiles) {
pthread_t tid[numFiles];
int i, rc;
i = 0;
for (i = 0; i < numFiles; i++) {
pthread_mutex_lock(&mutex_i);
rc = pthread_create(&tid[i], NULL, &readFile, (void *)(directory[i]));
printf("MAIN: Created child thread for \"%s\"\n", directory[i]);
fflush(NULL);
if (rc != 0) {
fprintf(stderr, "Could not create thread\n");
fflush(NULL);
}
}
for (i = 0; i < numFiles; i++) {
unsigned int *x;
rc = pthread_join(tid[i], (void **)&x);
if (rc != 0) {
fprintf(stderr, "Could not join thread\n");
fflush(NULL);
}
printf("MAIN: Joined child thread: %u\n", (unsigned int)tid[i]);
fflush(NULL);
free(x);
}
for (i = 0; i < currIdx; i++) {
fprintf(f, "%s\n", words[i]);
}
if (currIdx == maxwords) {
printf("MAIN: Buffer is full; writing %d words to output file\n", maxwords);
}
currIdx = currIdx % maxwords;
printf("MAIN: All threads are done; writing %d words to output file\n",
currIdx);
fflush(NULL);
}
int main(int argc, char *argv[]) {
int i;
if (argc != 4) {
fprintf(stderr, "ERROR: Invalid arguments\nUSAGE: ./a.out "
"<input-directory> <buffer-size> <output-file>\n");
return EXIT_FAILURE;
}
maxwords = atoi(argv[2]);
words = (char **)calloc(maxwords, sizeof(char *));
for (i = 0; i < maxwords; i++) {
words[i] = (char *)calloc(80, sizeof(char));
}
printf("MAIN: Dynamically allocated memory to store %d words\n", maxwords);
fflush(NULL);
f = fopen(argv[3], "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
printf("MAIN: Created \"%s\" output file\n", argv[3]);
fflush(NULL);
int numFiles = 0;
char **directory;
filesInfo(&directory, argv[1], &numFiles);
multiThrd(directory, numFiles);
for (i = 0; i < maxwords; i++) {
free(words[i]);
}
for (i = 0; i < numFiles; i++) {
free(directory[i]);
}
free(words);
free(directory);
fclose(f);
return EXIT_SUCCESS;
}
|
Java
|
UTF-8
| 498 | 1.570313 | 2 |
[
"MIT"
] |
permissive
|
package io.github.thesixonenine.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import io.github.thesixonenine.common.utils.PageUtils;
import io.github.thesixonenine.order.entity.OrderOperateHistoryEntity;
import java.util.Map;
/**
* 订单操作历史记录
*
* @author thesixonenine
* @date 2020-06-06 01:47:54
*/
public interface OrderOperateHistoryService extends IService<OrderOperateHistoryEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
Markdown
|
UTF-8
| 990 | 3.296875 | 3 |
[] |
no_license
|
---
title: 闭包
date: 2021-10-06 19:06
tags:
categories:
- 找工作
---
闭包是带数据的函数。
ECMAScript 只使用静态(词法)作用域(static scope, lexical scope)。 创建该函数的上层执行环境的数据是保存在函数的内部属性`[[Scope]]`中。 在 ECMAScript 中所有的函数都是闭包,因为它们都是在函数创建时保存了上层执行环境的作用域链(不管这个函数是否会被调用,`[[Scope]]` 属性在函数创建时就已存在)。
因为作用域链,使得所有函数都是闭包。 只有一类函数除外,那就是通过 Function 构造器创建的函数,因为其 `[[Scope]]` 只包含全局对象。 在 ECMAScript 中,闭包是指:
- 从理论角度:所有的函数在创建时都将其父级执行环境中的数据保存起来了。
- 从实践角度:
- 即使创建函数的执行环境已经销毁,但函数依旧存在(内部函数从父函数中返回)
- 在代码中使用了自由变量
|
Markdown
|
UTF-8
| 4,813 | 3.015625 | 3 |
[] |
no_license
|
# English class
## Review
### Complement
#### [informal](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/informal)
(of situations) not formal or official, or (of clothing, behaviour, speech) suitable when you are with friends and family but not for official occasions
非正式的,非正規的;(服裝)日常使用的;(言行)隨意的
- The two groups agreed to hold an informal meeting.
兩個集團同意舉行一次非正式會議。
- He's the ideal sort of teacher - direct, friendly, and informal.
他屬於那種理想的教師——坦率、友好且不拘禮節。
- "Hi" is an informal way of greeting people.
「喂」是一種隨意的問候方式。
#### [penalize](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/penalize)
penalize verb [ T ] (UK usually penalise)
to cause someone a disadvantage
使處於不利地位
- The present tax system penalizes poor people.
現行稅收制度對窮人不利。
- The system should ensure that borrowers are not penalized by sudden rises in mortgage rates.
該計劃應確保貸款者不會因分期貸款利率突然上升而陷入困境。
#### [slang](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/slang)
very informal language that is usually spoken rather than written, used especially by particular groups of people
俚語
- army slang
軍隊俚語
- a slang expression
一句俚語
- "Chicken" is slang for someone who isn't very brave.
chicken 是用來稱呼膽小者的俚語。
### Vocabulary
Make a sentence for each of the following words
- [guess](https://en.wiktionary.org/wiki/guess)
- [allow](https://en.wiktionary.org/wiki/allow)
- [shorten](https://en.wiktionary.org/wiki/shorten)
## Today's theme
### [Forehead detective](https://www.theguardian.com/lifeandstyle/2008/nov/17/party-games-guide)
AKA: The Post-it game, the Rizla game, take your partners
Aim: To work out who you are (and make friends)
#### How to play
There are many variants of this, but the principle remains the same. Everyone has the name of a famous person (fictional or real) stuck on to their back or forehead in a way that everyone can read the name except them. Cigarette papers and sticky memo notes are a good way of doing this. By asking questions with yes/no answers, everyone has to work out who they are.
As guests arrive, issue them with a name, either by pinning it on their back, or giving it to them in a sealed envelope for use later. When everyone is assembled, explain the concept and set them to find who they are.
#### Vocabulary
- [principle](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/principle)
- [famous](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/famous)
- [forehead](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/forehead)
- [sticky](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/sticky)
- [work out](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/work-sth-out)
- [guest](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/guest)
- [issue](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/issue)
- [seal](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/seal)
- [assemble](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/assemble)
- [concept](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/concept)
## Find the opposite
*A*
absent - <span style="color: white">present</span>
abundant - <span style="color: white">scarce</span>
accept - <span style="color: white">decline, refuse</span>
accurate - <span style="color: white">inaccurate</span>
admit - <span style="color: white">deny</span>
advantage - <span style="color: white">disadvantage</span>
against - <span style="color: white">for</span>
agree - <span style="color: white">disagree</span>
alive - <span style="color: white">dead</span>
all - <span style="color: white">none, nothing</span>
ally - <span style="color: white">enemy</span>
always - <span style="color: white">never</span>
ancient - <span style="color: white">modern</span>
answer - <span style="color: white">question</span>
antonym - <span style="color: white">synonym</span>
apart - <span style="color: white">together</span>
appear - <span style="color: white">disappear, vanish</span>
approve - <span style="color: white">disapprove</span>
arrive - <span style="color: white">depart</span>
artificial - <span style="color: white">natural</span>
ascend - <span style="color: white">descend</span>
attic - <span style="color: white">cellar</span>
attractive - <span style="color: white">repulsive</span>
awake - <span style="color: white">asleep</span>
|
TypeScript
|
UTF-8
| 503 | 2.75 | 3 |
[] |
no_license
|
/**
* Model para definição de propriedades do combo
*/
export interface ComboModel {
/**
* Propriedade para mostrar ao usuário
*/
selectedDisplay: string;
/**
* Propriedade para enviar ao servidor
*/
selectedValue: any;
/**
* Propriedade para filtro
*/
searchProperty: string;
/**
* Propriedade para ordenação
*/
oerderProperty: string;
/**
* Função para carregar os itend do combo
*/
onLoad: Function;
}
|
Java
|
UTF-8
| 688 | 1.90625 | 2 |
[] |
no_license
|
package com.turvo.bankingqueue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@ComponentScan(value = { "com.turvo.bankingqueue" })
@EnableJpaRepositories("com.turvo.bankingqueue.repository")
@EntityScan("com.turvo.bankingqueue.entity")
public class BankingQueueApplication {
public static void main(String[] args) {
SpringApplication.run(BankingQueueApplication.class, args);
}
}
|
Markdown
|
UTF-8
| 828 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
# eslint-plugin-emotion
Apply eslint rules to emotion.sh css-in-js
## Installation
You'll first need to install [ESLint](http://eslint.org):
```
$ npm i eslint --save-dev
```
Next, install `eslint-plugin-emotion`:
```
$ npm install eslint-plugin-emotion --save-dev
```
**Note:** If you installed ESLint globally (using the `-g` flag) then you must also install `eslint-plugin-emotion` globally.
## Usage
Add `emotion` to the plugins section of your `.eslintrc` configuration file. You can omit the `eslint-plugin-` prefix:
```json
{
"plugins": [
"emotion"
]
}
```
Then configure the rules you want to use under the rules section.
```json
{
"rules": {
"emotion/syntax-preference": [2, "string"]
}
}
```
## Supported Rules
* [syntax-preference](docs/rules/syntax-preference.md)
|
Python
|
UTF-8
| 1,591 | 3.109375 | 3 |
[
"Apache-2.0"
] |
permissive
|
def solution(food_times, k):
# 각 접시의 음식량과 인덱스를 저장 후 음식량 기준 오름차순 정렬
for i in range(len(food_times)):
food_times[i] = [food_times[i], i]
food_times.sort()
# 아직 음식이 남아있는 접시의 인덱스를 저장
remained = set([i for i in range(len(food_times))])
prev = 0
# 음식량이 적은 것부터 많은 것 순으로 탐색
for i in range(len(food_times)):
# 음식 먹는 방식은 한 바퀴를 쭉 도는 것이므로, 이전 접시를 다 비웠다면
# 현재 접시에 남은 음식 양은 원래 양과 이전 접시의 차이만큼 남아있다
delta = food_times[i][0] - prev
prev = food_times[i][0]
# 현재 접시에 남은 음식을 다 비운다고 하면 그 양만큼
# 다른 접시들의 음식도 먹어야한다. 모든 접시들에서 현재 접시의 양만큼을
# 먹을 수 있을만큼 시간이 남았으면 현재 상태에서 마지막 인덱스를 구할 수
# 없으므로 접시를 제거하고, 소요되는 시간을 빼준다.
if k >= delta * len(remained):
k -= delta * len(remained)
remained.remove(food_times[i][1])
else:
# 완전히 다 비우고도 한 바퀴를 다시 돌 수 없다면 마지막 위치를
# 나머지 연산으로 구할 수 있다.
answer = list(remained)[k % len(remained)]
# 접시의 인덱스가 1부터 시작하므로 보정
return answer + 1
return -1
|
Python
|
UTF-8
| 1,418 | 2.703125 | 3 |
[] |
no_license
|
from collections import defaultdict
def ncc(img, n, m):
lbl = [[None] * len(img[i]) for i in range(n)]
cc = 0
eqv = defaultdict(lambda: set())
for i in range(n):
for j in range(m):
if not img[i][j]: continue
if (
j>0 and lbl[i][j-1] is not None and
i>0 and lbl[i-1][j] is not None and
lbl[i-1][j] != lbl[i][j-1]
):
l1 = lbl[i][j-1]
l2 = lbl[i-1][j]
lbl[i][j] = l1
eqv[l2].add(l1)
eqv[l1].add(l2)
elif j>0 and lbl[i][j-1] is not None:
lbl[i][j] = lbl[i][j-1]
elif i>0 and lbl[i-1][j] is not None:
lbl[i][j] = lbl[i-1][j]
else:
eqv[cc].add(cc)
lbl[i][j] = cc
cc += 1
cc = [i for i in range(len(eqv.keys()))]
for i in eqv.keys():
if len(eqv[i]) == 1: continue
queue = [neig for neig in eqv[i] if cc[neig] != i]
while len(queue) > 0:
j = queue.pop()
if cc[j]!=i:
cc[j] = i
queue.extend([neig for neig in eqv[j] if cc[neig]!=i])
return len(set(cc))
while True:
try:
n, m = (int(v) for v in input().split(' '))
except: break
img = [[c=='.' for c in input()] for i in range(n)]
print(ncc(img, n, m))
|
PHP
|
UTF-8
| 1,201 | 2.546875 | 3 |
[] |
no_license
|
<?php
namespace SabaiApps\Directories\Component\Display\Statistic;
use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity;
abstract class AbstractStatistic implements IStatistic
{
protected $_application, $_name, $_info;
public function __construct(Application $application, $name)
{
$this->_application = $application;
$this->_name = $name;
}
public function displayStatisticInfo(Entity\Model\Bundle $bundle, $key = null)
{
if (!isset($this->_info)) {
$this->_info = (array)$this->_displayStatisticInfo($bundle);
}
return isset($key) ? (isset($this->_info[$key]) ? $this->_info[$key] : null) : $this->_info;
}
public function displayStatisticSettingsForm(Entity\Model\Bundle $bundle, array $settings, array $parents = [], $type = 'icon'){}
abstract protected function _displayStatisticInfo(Entity\Model\Bundle $bundle);
public function displayStatisticIsPreRenderable(Entity\Model\Bundle $bundle, array $settings)
{
return false;
}
public function displayStatisticPreRender(Entity\Model\Bundle $bundle, array $settings, array $entities){}
}
|
Java
|
UTF-8
| 10,553 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.ahc.codec;
import org.apache.ahc.HttpIoHandler;
import org.apache.ahc.util.NeedMoreDataException;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
/**
* The Class HttpResponseDecoder. This handles the decoding of raw bytes into a
* {@link HttpResponseMessage} object.
*/
public class HttpResponseDecoder extends CumulativeProtocolDecoder {
/** The http decoder. */
private HttpDecoder httpDecoder = new HttpDecoder();
/**
* Decodes the raw HTTP response from a server into a {@link HttpResponseMessage} object.
*
* @param ioSession the {@link IoSession} representing the connection to the server.
* @param in the <code>ByteBuffer</code> that contains the raw bytes from the server
* @param out {@link org.apache.mina.filter.codec.ProtocolDecoderOutput} used for output
*
* @return <code>true</code> if it can read all of the data, or <code>false</code> if not. A false tells the API to fetch more data.
*
*/
protected boolean doDecode(IoSession ioSession, IoBuffer in, ProtocolDecoderOutput out)
throws Exception {
try {
HttpResponseMessage response = (HttpResponseMessage)ioSession.getAttribute(HttpIoHandler.CURRENT_RESPONSE);
if (response == null) {
response = new HttpResponseMessage();
ioSession.setAttribute(HttpIoHandler.CURRENT_RESPONSE, response);
}
//Test if we need the response...
if (response.getState() == HttpResponseMessage.STATE_START) {
if (!processStatus(response, in)) {
throw new NeedMoreDataException();
}
//Handle HTTP/1.1 100 Continue
if (response.getStatusCode() == 100) {
response.setState(HttpResponseMessage.STATE_STATUS_CONTINUE);
} else {
response.setState(HttpResponseMessage.STATE_STATUS_READ);
}
}
//If we are in a 100 Continue, read until we get the real header
if (response.getState() == HttpResponseMessage.STATE_STATUS_CONTINUE) {
//Continue reading until we get a blank line
while (true) {
String line = httpDecoder.decodeLine(in);
//Check if the entire response has been read
if (line == null) {
throw new NeedMoreDataException();
}
//Check if the entire response headers have been read
if (line.length() == 0) {
response.setState(HttpResponseMessage.STATE_STATUS_READ);
//The next line should be a header
if (!processStatus(response, in)) {
throw new NeedMoreDataException();
}
break;
}
}
}
//Are we reading headers?
if (response.getState() == HttpResponseMessage.STATE_STATUS_READ) {
if (!processHeaders(response, in)) {
throw new NeedMoreDataException();
}
}
//Are we reading content?
if (response.getState() == HttpResponseMessage.STATE_HEADERS_READ) {
if (!processContent(response, in)) {
throw new NeedMoreDataException();
}
}
//If we are chunked and we have read all the content, then read the footers if there are any
if (response.isChunked() && response.getState() == HttpResponseMessage.STATE_CONTENT_READ) {
if (!processFooters(response, in)) {
throw new NeedMoreDataException();
}
}
response.setState(HttpResponseMessage.STATE_FINISHED);
out.write(response);
ioSession.removeAttribute(HttpIoHandler.CURRENT_RESPONSE);
return true;
} catch (NeedMoreDataException e) {
return false;
}
}
/**
* Reads the headers and processes them as header objects in the {@link HttpResponseMessage} object.
*
* @param response the {@link HttpResponseMessage} response object
* @param in the <code>ByteBuffer</code> that contains the raw bytes from the server
*
* @return <code>true</code> if it can read all of the data, or <code>false</code> if not.
*
* @throws Exception if any exception occurs
*/
private boolean processHeaders(HttpResponseMessage response, IoBuffer in) throws Exception {
if (!findHeaders(response, in)) {
return false;
}
response.setState(HttpResponseMessage.STATE_HEADERS_READ);
return true;
}
/**
* Reads the footers and processes them as header objects in the {@link HttpResponseMessage}
* object. This is only used in chunked transcoding.
*
* @param response the {@link HttpResponseMessage} response object
* @param in the <code>ByteBuffer</code> that contains the raw bytes from the server
*
* @return <code>true</code> if it can read all of the data, or <code>false</code> if not.
*
* @throws Exception if any exception occurs
*/
private boolean processFooters(HttpResponseMessage response, IoBuffer in) throws Exception {
if (!findHeaders(response, in)) {
return false;
}
response.setState(HttpResponseMessage.STATE_FOOTERS_READ);
return true;
}
/**
* Decodes the raw headers/footers.
*
* @param response the {@link HttpResponseMessage} response object
* @param in the <code>ByteBuffer</code> that contains the raw bytes from the server
*
* @return <code>true</code> if it can read all of the data, or <code>false</code> if not.
*
* @throws Exception if any exception occurs
*/
private boolean findHeaders(HttpResponseMessage response, IoBuffer in) throws Exception {
//Read the headers and process them
while (true) {
String line = httpDecoder.decodeLine(in);
//Check if the entire response has been read
if (line == null) {
return false;
}
//Check if the entire response headers have been read
if (line.length() == 0) {
break;
}
httpDecoder.decodeHeader(line, response);
}
return true;
}
/**
* Process and read the content.
*
* @param response the {@link HttpResponseMessage} response object
* @param in the <code>ByteBuffer</code> that contains the raw bytes from the server
*
* @return <code>true</code> if it can read all of the data, or <code>false</code> if not.
*
* @throws Exception if any exception occurs
*/
private boolean processContent(HttpResponseMessage response, IoBuffer in) throws Exception {
if (response.isChunked()) {
while (true) {
//Check what kind of record we are reading (content or size)
if (response.getExpectedToRead() == HttpResponseMessage.EXPECTED_NOT_READ) {
//We haven't read the size, so we are expecting a size
String line = httpDecoder.decodeLine(in);
//Check if the entire line has been read
if (line == null) {
return false;
}
response.setExpectedToRead(httpDecoder.decodeSize(line));
//Are we done reading the chunked content? (A zero means we are done)
if (response.getExpectedToRead() == 0) {
break;
}
}
//Now read the content chunk
//Be sure all of the data is there for us to retrieve + the CRLF...
if (response.getExpectedToRead() + 2 > in.remaining()) {
//Need more data
return false;
}
//Read the content
httpDecoder.decodeChunkedContent(in, response);
//Flag that it's time to read a size record
response.setExpectedToRead(HttpResponseMessage.EXPECTED_NOT_READ);
}
} else if (response.getContentLength() > 0) {
//Do we have enough data?
if ((response.getContentLength()) > in.remaining()) {
return false;
}
httpDecoder.decodeContent(in, response);
}
response.setState(HttpResponseMessage.STATE_CONTENT_READ);
return true;
}
/**
* Process and read the status header.
*
* @param response the {@link HttpResponseMessage} response object
* @param in the <code>ByteBuffer</code> that contains the raw bytes from the server
*
* @return <code>true</code> if it can read all of the data, or <code>false</code> if not.
*
* @throws Exception if any exception occurs
*/
private boolean processStatus(HttpResponseMessage response, IoBuffer in) throws Exception {
//Read the status header
String header = httpDecoder.decodeLine(in);
if (header == null) {
return false;
}
httpDecoder.decodeStatus(header, response);
return true;
}
}
|
PHP
|
UTF-8
| 2,703 | 2.515625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Periodo extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
if($this->session->userdata('logged_in') !== TRUE){
redirect('/');
}
}
/*=====================INICIO=LISTAR=PERIODO====================*/
// CHAMA A VIEW LISTAR periodo
public function listar_periodo()
{
$this->load->model("Periodo_Model");
$lista = $this->Periodo_Model->listarperiodo();
$dados = array("periodo" => $lista);
// CARREGA A VIZUALIZACAO DA VIEW LISTAR PERIODO
$this->load->view('layout/cabecalho');
$this->load->view('layout/menu_lateral');
$this->load->view('conteudo/_secretaria/_periodo/listar_periodo', $dados);
$this->load->view('layout/rodape');
$this->load->view('layout/script');
}
/*=====================INICIO=CRIAR=NOVo=PERIODO====================*/
// CARREGA AVIEW DO FURMULARIO
public function novo_periodo()
{
$this->load->view('layout/cabecalho');
$this->load->view('layout/menu_lateral');
$this->load->view('conteudo/_secretaria/_periodo/novo_periodo');
$this->load->view('layout/rodape');
$this->load->view('layout/script');
}
// INSERIR REGISTROS NA TABELA PERIODO
public function guardar()
{
$periodo = array(
"nome_periodo" => $this->input->post('nome_periodo')
);
$this->load->model("Periodo_Model");
$this->Periodo_Model->novoperiodo($periodo);
redirect('secretaria/periodo/novo_periodo','refresh');
}
/*=====================INICIO=APAGAR=PERIODO=====================*/
// APAGAR REGISTROS NA TABELA PERIODO
public function apagar($id)
{
$this->load->model("Periodo_Model");
$this->Periodo_Model->apagarperiodo($id);
redirect('secretaria/periodo/listar_periodo', 'refresh');
}
/*=====================INICIO=ACTUALIAZAR=PERIODO=====================*/
// ACTUALIZAR REGISTROS NA TABELA PERIODO
public function editar($id=NULL)
{
$this->db->where('id_periodo', $id);
$data['periodo'] = $this->db->get('periodo')->result();
// CARREGA A VIZUALIZACAO DA VIEW LISTA
$this->load->view('layout/cabecalho');
$this->load->view('layout/menu_lateral');
$this->load->view('conteudo/_secretaria/_periodo/editar_periodo', $data);
$this->load->view('layout/rodape');
$this->load->view('layout/script');
}
// SALVA A ACTUALIZACAO DO REGISTROS NA TABELA PERIODO
public function salvaractualizacao($id=NULL)
{
$periodo = array(
"nome_periodo" => $this->input->post('nome_periodo'),
);
$this->load->model("Periodo_Model");
$this->Periodo_Model->actualizar($periodo);
redirect('secretaria/periodo/listar_periodo', 'refresh');
}
}
|
Ruby
|
UTF-8
| 1,105 | 3.046875 | 3 |
[] |
no_license
|
require 'logger'
class Logger
@@logger = Logger.new(STDOUT)
@@logger.level = 0
methods = [:error, :warning, :info, :debug]
level = 0
methods.each do |method|
if @@logger.level >= level
class_eval %(class << self
def #{method.to_s} (message, params=nil)
params = self.format_params(params) unless params.nil?
@@logger.#{method.to_s}("\#{message}\#{params.to_s}")
end
end
)
else
class_eval %(class << self
def #{method.to_s} (message, params=nil)
end
end
)
end
level += 1
end
def self.level= (level)
@@logger.level = level
end
private
def self.format_params (parameters)
str = ""
if parameters.class == Hash
parameters.each do |key, value|
value = value.inspect if value.class != String
str += "#{key}='#{value}';"
end
end
str = ";#{str}" if str.length > 0
end
end
|
Java
|
UTF-8
| 330 | 1.90625 | 2 |
[] |
no_license
|
package com.dlw.bigdata.jvm.codecheck;
/**
* @author dengliwen
* @date 2019/8/18
* @desc 不和发的密码用例
*/
public class BadCodedemo {
enum color {
red,
black;
}
static final String a = "1";
public void Demo() {
}
public static void main(String[] args) {
}
}
|
Markdown
|
UTF-8
| 1,347 | 2.53125 | 3 |
[] |
no_license
|
[【返回目录】](../README.md)
# 会话共享
## livebos会话共享
>前提:
>1. Livebos系统参数system.session.cluster.enabled设置为true;
>2. web应用同Livebos使用同一个redis作为会话存储,且redis的database必须是同一个,默认0;
>3. 前端采用Nginx将Livebos和web应用映射到通一个IP地址和端口号;
参考配置
```yaml
spring:
session:
store-type: redis
redis:
host: localhost
port: 6379
password: apexsoft
pool:
max-active: 100
max-idle: 5
max-wait: 60000
aas:
session:
sharing: true #true表示开始会话共享,默认false
```
Nginx参考配置
```
server{
listen 9999;
server_name 127.0.0.1 localhost;
# http://127.0.0.1:8090/ 为livebos地址
# http://127.0.0.1:7070/dd为基于AAS的应用地址
location /dd {
proxy_pass http://127.0.0.1:7070/dd;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
proxy_pass http://127.0.0.1:8090/;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
[【返回目录】](../README.md)
|
PHP
|
UTF-8
| 1,681 | 2.921875 | 3 |
[] |
no_license
|
<?php
class ftp_session{
public $ftp_server = "localhost";
public $ftp_user_name = "sys_videoclub";
public $ftp_user_pass = "v1d30c!ub$";
public $conn_id = "";
public $mensaje = "";
function crear_session($ftp_server, $ftp_user_name, $ftp_user_pass){
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if ((!$conn_id) || (!$login_result)) {
$this->mensaje = "FTP connection has failed!\nAttempted to connect to $ftp_server for user $ftp_user_name\n";
exit;
}else{
$this->conn_id = $conn_id;
}
}
function crear_folder($dir){
if(ftp_mkdir($this->conn_id, $dir)){
return true;
}else{
return false;
}
}
function subir_ftp($destination_file, $source_file){
$upload = ftp_put($this->conn_id, $destination_file, $source_file, FTP_BINARY);
if (!$upload) {
$this->mensaje = "FTP upload has failed!";
} else {
$archivo = basename($destination_file);
$this->mensaje = "Se subió el archivo al servidor FTP";
}
ftp_close($this->conn_id);
}
function subir_imagen($source_file, $destination_file){
$dir = dirname($destination_file);
$this->crear_session($this->ftp_server, $this->ftp_user_name, $this->ftp_user_pass);
if(!is_dir("ftp://{$this->ftp_user_name}:{$this->ftp_user_pass}@{$this->ftp_server}{$dir}")){
$this->crear_folder($dir);
}
if(!is_file("ftp://{$this->ftp_user_name}:{$this->ftp_user_pass}@{$this->ftp_server}{$destination_file}")){
$this->subir_ftp($destination_file, $source_file);
}else{
$archivo = basename($destination_file);
$this->mensaje = "El archivo {$archivo} ya existe";
}
}
}
?>
|
Shell
|
UTF-8
| 375 | 3.34375 | 3 |
[
"X11"
] |
permissive
|
#!/bin/sh
set -e
BIN_DIR=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
. "${BIN_DIR}/../libexec/utils"
SRC="/data.tar.gz"
if [ -n "${DATA_TAG}" ]; then
data-io-registry unpack "${SRC}"
elif [ -n "${DATA_S3_DST}" ]; then
data-io-s3 unpack "${SRC}"
else
warn "Nowhere to send the packed data?"
fi
info "Unpacking data"
tar -xzf /data.tar.gz -C /
info "done."
success
|
Markdown
|
UTF-8
| 6,225 | 3.234375 | 3 |
[] |
no_license
|
---
layout: post
title: 系统设计知识(二)
subtitle: 好友关系服务设计
date: 2021-03-08
author: Jingming
header-img: img/post-bg-map.jpg
catalog: true
tags:
- 系统设计
---
参考九章friendshipService设计。
### 数据库设计
好友关系分为单向和双向。
单向好友是微博的关注机制,双向好友是微信好友机制(不存在单向好友,一旦成为好友,必然是双向好友)。
单向好友,是指例如A关注了B。单向好友存储:表friendship,其中有外键(用户的id, 被关注者的id)
双向好友有两种存储方法,一个是只存一个pair(较小的id,较大的id),这样查询的时候,就需要线性查,例如数据库存储(1,2),(2,3),当需要查出2的全部好友的时候,select的时候,不仅要看第一个值为2的pair,也要看pair的第二个值:把第二个值为2的pair选出来,然后在把其中第一个值取出来;或者两次查询,第一次查把pair的第一个值拿出来,第二次查把pair的第二个值拿出来。
另一个是存两份,这样存储空间消耗多,但是可以以第一个字段为key进行二分查找,所以更快。
PS. nosql存储的话只能拆成两条数据。
支持transaction的(也就是加锁机制)不能选nosql。
sql更成熟,以及帮你做了很多事,而nosql需要亲力亲为(序列化、第二索引)。硬盘型nosql效率比sql高10倍。
数据库索引:主键自带索引,如果对非主键属性进行索引,那就是建立一个额外的小表(看不见),里面对该属性排序,且指向到大表中对应的item地址。
index的坏处,太多index的话,插入修改效率降低,因为要修改index所对应的小表。
sql存储单位是行,nosql存储单位是格子(多了列id,剩余部分作为格子里的值,也就是以前的行,现在看作点),也就是三元组。
cassandra:
row_key是hash_key(hash后事无序的,因此不能做range query,也就是说例如查userId1到100的数据),决定分布式时候存放在的机器的位置;最常用的rowKey是userId,例如存newsfeed table,userId作为row_key。
column_key是排序的(partition key),支持range query。注意在表中column_key不唯一,意思是,之前的若干记录行,现在在表中记录为(userId,tweetId1)和(userId, tweetId2)....若干点。另外,column_key可以是组合key,例如创建的时间结合tweetId做column_key,这样在创建的时间相同的时候,按第二个tweetId进行排序。
how to scale: (1) 防止单点失效(例如一台机器短暂的挂或者彻底的挂,导致网站不可用),使用sharding,将数据拆分成不同部分,保存在不同机器上;replica是做数据备份(这同时也可以分摊读请求)。nosql自带sharding(sql不自带)。
垂直sharding:不同表放不同机器或一张表可以按列拆分成多个表并存于不同机器,例如一个表可以根据字段的更新频率切分成两个表(user profile table和user table,区别是user table比较核心,profile只是更多的介绍user的信息),垂直sharding优点是表有些分表部分挂了也没关系,坏处是有些表数据增加很多,垂直拆没有用。
水平sharding:按行拆分,按模固定数字(机器的数量)的方法,在新加机器的时候,由于之前mod数变化,之前数据放的位置不一样导致数据迁徙,成本太大,解决方法是一致性hash;按线性划分则不容易均匀切分,比如从3等份到4等份。
### 一致性哈希
之前每次加地址后,导致之前数据的模后地址变化了,大量数据需要迁移。
那么,为了减少迁移量:
1. 如何消除新增地址空间后hash变化?
答:为何不直接一开始就模一个足够大的固定的数,例如0-2^64-1。
2. 在1的解法基础上,如何均衡负载呢?
假设现在有n台机器,新增第n+1台机器。
首先,现在有n+1台机器,那么规定n+1个区间,每个区间的大小是2^64 / (n + 1),也就是机器平分全部空间。
第n+1台机器负责的区间是mod后的数在所有mod后的数中的排序来的。那么,存在一个问题,例如3台机器平分1/3,
第四台机器来了,怎么向除了自己邻居的那台机器要走数据从而达到每个机器都分1/4?
解决方法是:每台机器负责的区间大小不变,但是拆分成不连续不等的若干个小区间, 例如拆分成1000个,并随机hash到空间(看作一个环)中。
每个点都负责接收最近的顺时针环上的数据(数据的hash值沿环顺时针走发现的第一个点)。该算法的均匀性取决于随机的均匀性。回到之前的问题,
前3台机器的3000个点平均的分散在环上,此时第四台机器过来了,那么第4台机器的1000个点,就会"均匀的"向之前的3台机器的3000个要数据了。
具体来说,会向顺时针最近虚拟节点把那一段(下一个节点的负责的起点到新加节点)数据要过来,可能有若干个新增节点需要向同一个
虚拟节点要数据。
小结:hash到0-2^64-1环上,然后将每台实际机器M0看成是1000个虚拟结点(M0-0,M0-1,...),hash到环上。数据存入顺时针最近的虚拟机器上。
新机器加入后做迁移:每个虚拟结点向顺时针的不是自己机器的第一个node要数据。
### 访问网址发生什么
浏览器端输入网址后:
1. 访问最近的DNS服务器得到域名对应的IP
2. 浏览器向该IP发送http请求
3. 服务器接收到请求,将请求交给80端口的程序(也就是http server,例如Apache)去处理
4. http server把请求给部署的web application来处理
5. web application会:(1)根据路径"/"后的部分找到对应的处理模块
(2)根据http是get还是post决定如何获取/存放数据
(3)从数据库服务中读取数据
(4)将结果组织成html网页
web application框架:Django、Ruby on Rails、NodeJS。
6. 浏览器获得网页
|
Markdown
|
UTF-8
| 1,826 | 2.765625 | 3 |
[] |
no_license
|
# AppPokemon
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 11.0.4.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/pokemonMnt`. The app will automatically reload if you change any of the source files.
## Running AppPokemon
- Ao executar a aplicação os pokemons serão apresentados na table;
- Os botões de detalhe e limpar favoritos estarão desabilitados;
- Se algum pokemon for selecionado na table, o botão detalhes será habilitado no topo da tela;
- Também é possível acessar a opção detalhar nas ações da tabela, as mesmas ficam disponíveis em cada linha, no lado direito onde se encontra o ícone (...);
- Além da opção detalhar, é possível favoritar um ou mais Pokemons. A opção esta presente em cada linha da tabela ou acessando a tela de detalhe, estará no canto superior direito da tela;
- Para visualizar somente os Pokemons escolhidos como favoritos, marque a opção que fica acima da tabela "Mostrar Favoritos", com isso aparecerão apenas os marcados;
- Caso queira limpar os favoritos, pode-se usar o botão "Limpar Favoritos" onde todos os selecionados serão zerados, ou se desejar manter os mesmos selecionados e voltar a ver todos os pokemons, basta desmarcar a opção "Mostra Favoritos";
- O filtro que existe na tela princiapl é para buscar por nome do pokemon contido na lista, como a API não disponibiliza uma query por nome, a busca é feita pelos Pokemons que já estão na listagem mostrada, ou seja, contidos na table.
- Caso esteja na tela de detalhe e queira voltar para a tela principal, basta usar o botão voltar;
- A table sempre é carregada de 20 em 20 registros, para trazer os próximos 20, basta usar a opção "carrega mais resultados" contida no rodapé da table;
|
Python
|
UTF-8
| 1,290 | 2.65625 | 3 |
[] |
no_license
|
import io
import csv
import json
from flask import Flask
from flask import request, redirect
from flask import jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, support_credentials=True)
@app.route("/file_upload", methods=["POST"])
@cross_origin(supports_credentials=True)
def upload():
if request.method == "POST":
if "file" not in request.files:
return "fuck"
my_file = request.files["file"]
stream = io.StringIO(my_file.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
keys = []
for row in csv_input:
keys = row
break
my_data = []
for row in csv_input:
temp = dict()
for key, val in zip(keys, row):
temp[key] = val
my_data.append(temp)
with open("data.json", "w") as fo:
print("JSON FILE CREATED")
json.dump(my_data, fo)
return jsonify(my_data)
@app.route("/get_file", methods=["GET"])
def get_file():
try:
with open("data.json", "r") as rf:
data = json.load(rf)
return jsonify(data)
except Exception as e:
return ""
if __name__ == "__main__":
app.run(debug=True)
|
Python
|
UTF-8
| 2,361 | 3.25 | 3 |
[] |
no_license
|
from classes.Point import Point
from classes.Line import Line
from classes.helpers import prod
from typing import Iterator
class Triangle:
points: list[Point]
lines: list[Line]
name: str
def __init__(self, p1: Point, p2: Point, p3: Point):
self.points = [p1, p2, p3]
self.lines = [Line(p1, p2), Line(p2, p3), Line(p3, p1)]
self.name = p1.name + p2.name + p3.name
def __str__(self):
return f"{self.name}: {self.points}"
def perimeter(self) -> float:
return sum([x.len() for x in self.lines_iter()])
def __area2(self, name) -> float:
side = [l for l in self.lines if name in l.name]
return (side[0].invert().to_vector() * side[1].to_vector()).norm()
def get_height(self, name: str) -> float:
if name not in self.points_names():
raise ValueError("No such points in triangle")
base = next(l for l in self.lines_iter() if name not in l.name)
return self.__area2(name) / base.len()
def get_height_intersect(self, name: str) -> Point:
if name not in self.points_names():
raise ValueError("No such points in triangle")
base = next(l for l in self.lines if name not in l.name)
base_vector = base.to_vector()
side_point = base.start
side = next(l for l in self.lines if name in l.name and side_point.name in l.name)
cos = base_vector.cos_angle_between((side.invert() if side.name[0] == 'O' else side).to_vector())
return (cos * side.len() * base_vector.normalize()).end + base.start
def get_angle_cos(self, name: str) -> float:
if name not in self.points_names():
raise ValueError("No such points in triangle")
sides_len = [line.len() for line in self.lines if name in line.name]
sides_sum_2 = sum([side_len ** 2 for side_len in sides_len])
op_side_len_2 = next(line.len() for line in self.lines if name not in line.name) ** 2
return (sides_sum_2 - op_side_len_2) / (2 * prod(sides_len))
def points_names(self):
return [p.name for p in self.points].__iter__()
def lines_names(self):
return [l.name for l in self.lines].__iter__()
def lines_iter(self) -> Iterator:
return self.lines.__iter__()
def points_iter(self) -> Iterator:
return self.points.__iter__()
|
Java
|
UTF-8
| 1,459 | 3.015625 | 3 |
[] |
no_license
|
package com.luv2code.hibernate.demo;
import com.luv2code.hibernate.demo.entity.Address;
import com.luv2code.hibernate.demo.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CreateStudentAddressDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.addAnnotatedClass(Address.class)
.buildSessionFactory();
//create session
Session session = factory.getCurrentSession();
try {
//create the object
Student tempStudent = new Student("john","Doe","john@luv2code.com");
//create the address object
Address billingAddress = new Address("Moi avenue","Nairobi","43844");
//start a transaction
session.beginTransaction();
//save the object
System.out.println("Saving the student and billingAddress");
tempStudent.setBillingAddress(billingAddress);
session.persist(tempStudent);
//commit the transaction
session.getTransaction().commit();
System.out.println("Done!!");
}finally {
//clean up code
session.close();
factory.close();
}
}
}
|
Markdown
|
UTF-8
| 5,367 | 3.671875 | 4 |
[] |
no_license
|
# Web_application_to_convert_numeric_currency_to_text
## INTRODUCTION TO APPLICATION
Rocket is a web framework for Rust. It is used to design Web applications in the RUST programming languages.Rust is blazingly fast and memory-efficient with no runtime or garbage collector, it can power performance-critical services, run on embedded devices, and easily integrate with other languages. The project can rightly determine the textual output till 100 crore and a decimal precision up-to 2. Program will ask the user to enter a number and the expected output will be the text of corresponding currency. If a number is an integer then it will not return anything after decimal places whereas if the output is a double then it will return the paise corresponding to it divided by 100. The web application supports 5 different languages which includes Hindi,English,Bengali,Gujrati and Marathi and produces the corresponding output also a functionalty to copy the resulting output was added by providing a copy button.
## HOW TO GET STARTED
1. In your system install the nightly version of Rust using the command -> **rustup default nightly**
2. One can use per-directory overrides to use the nightly version only for your Rocket project by running the following command in the directory ->**rustup override set nightly**
3. After installing the nightly version we will create a new binary-based Cargo project using the command -> **cargo new my_web_app --bin**
4. Then we need to move our action to the created directory using the -> **cd my_web_app**
5. Now a cargo.toml file would be created by default we need to add:
---
`[dependencies] `
`rocket = "0.4.5"`
`htmlescape = "0.3.1"`
`serde = "1.0"`
`serde_derive = "1.0"`
`serde_json = "1.0"`
`[dependencies.rocket_contrib]`
`version = "* "`
`default-features = false`
`features = ["json","serve","tera_templates"]`
6.Create a template folder so as to store the index.html and index.html.tera file in the new package created.
7. After adding the files to the correct location. Just compile and execute the program my using the command **cargo run**.
8. If the cargo project runs succesfully , then just open the [Link](http://localhost:8000/) in any browser and a form will be displayed on the webpage which asks the user to enter the valid currency and the language in which the user expects the output.
## WHAT IS INDEX.HTML
This is the page where our initial form is available or the page where the user is made to enter the details. This is a basic html form with two input types namely the number and the language in which the user expects the output. Also some form validations are added as like the user has to enter the number else it generates a warning. another validation is that if the user enters the empty number then a validation runs which requests user to enter a number. Also the number must contain maximum of 9 digits before the decimal point and also it prohibits user to enter a negative value. One more validation is that the user must include maximum of 2 numbers after the decimal points. The user has to click the check button and the page gives the index.html.tera as the output.
## WHAT IS INDEX.TERA.HTML
A Tera template is just a text file where variables and expressions get replaced with values when it is rendered. the format for this tera file is similar to that of html file. The first entity that was added to the tera file was the currency textual output. This was done by the use of simple description list using the **"dl** tags in HTML and "items" was the textual output written inside **"{{items}}"**. Another functionality was added to the tera file which copied the textual output on a click for this a small css code was used which copied the data using the function named "myfunction()" and on succesfull copying it poped up a text showing "text copied !".All you need is to just click on the "Click me to copy to clipboard".
## LEARNING OUTCOMES FROM PROJECT
1.Designing of flowchart to understand the program flow approach.<br>
2.Importance of Source Control and why is it necessary to locally store your program status.<br>
3.Naming variables in a user understandable fashion so to make program more user friendly.<br>
4.Comments in code make the code more readable and understandable.<br>
5.Importance of unit tests.<br>
6.What is a code coverage and how to improve the code coverage.<br>
7.How to shift from one language to another keeping the semantic logic same.<br>
8.Basic syntax of RUST and advantages of RUST over other languages.<br>
9.Error handling and adding constraints to WEB API.<br>
10.File handling in RUST and C++.<br>
11.Designing a webpage or a page by the functionalities of HTML ,CSS and JavaScript.<br>
12.Working with UI Frameworks. I searched a lot about the web UI and found that Actix web and Rocket are useful for designing WEB API in RUST Language and came up with choosing Rocket framework.<br>
## USER PAGE TO ENTER THE INPUT

## OUTPUT AS EXPECTED

## ADDITION OF VALIDATION TO THE WEB APPLICATION

|
Java
|
UTF-8
| 5,545 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
*
* Copyright 2012-2015 Viant.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package voldemort.store.cachestore;
import voldemort.utils.ByteArray;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Arrays;
import static voldemort.store.cachestore.BlockUtil.KeyType;
/**
* Created by IntelliJ IDEA.
* User: mhsieh
* Date: 1/25/11
* Time: 11:38 AM
* Key support four different types - int, long, String, Bianry Array and Java Object
*
* To change this template use File | Settings | File Templates.
*/
public final class Key<T> implements Serializable, Comparable<T> {
// generic type
private T key;
/**
* @param key gerneral type
*/
private Key(T key) {
this.key =key;
}
public static Key createKey(int key) {
return new Key( new Integer(key));
}
public static Key createKey(long key) {
return new Key( new Long(key));
}
public static Key createKey(String key) {
return new Key( key);
}
public static Key createKey(ByteArray array) {
return new Key(array);
}
public static Key createKey(Object key) {
if ( key instanceof Array) throw new StoreException("Array type is not supported");
return new Key( key);
}
public static Key createKey(byte[] bytes) {
return new Key( bytes);
}
public T getKey() {
return key;
}
@Override
public int hashCode() {
if ( getKeyType (key) == KeyType.BYTEARY) {
return Arrays.hashCode( (byte[]) key);
}
else
return key.hashCode();
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if ( obj instanceof Key ){
if ( ((Key) obj).getKey() instanceof byte[] && key instanceof byte[])
return isEqual( (byte[]) key , (byte[]) ((Key) obj).getKey() );
else
return key.equals(((Key) obj).getKey());
}
else
return false;
}
private boolean isEqual(byte[] a, byte[] b) {
if ( a.length == b.length) {
for ( int i= 0; i < a.length; i++) {
if ( a[i] != b[i])
return false;
}
return true;
}
else
return false;
}
public BlockUtil.KeyType getType() {
return getKeyType(key);
}
@Override
public String toString() {
return key.toString()+" "+ getKeyType(key);
}
public static KeyType getKeyType(Object object) {
if ( object instanceof Integer) return KeyType.INT;
else if ( object instanceof Long ) return KeyType.LONG;
else if ( object instanceof String) return KeyType.STRING;
else if ( object instanceof ByteArray) return KeyType.BARRAY;
else if ( object instanceof byte[] ) return KeyType.BYTEARY;
else return KeyType.OBJECT;
}
/**
* compare current only support int, long, String and ByteArray
* anything else should use customize comparator
* @param o
* @return
*/
@Override
public int compareTo(T o) {
if ( this == o ) return 0;
if ( o instanceof Key) {
// check key type
Key oo = (Key) o;
KeyType type = getType();
if ( type != ((Key) o).getType()) return 0;
switch ( type ) {
case INT : return ((Integer) key).compareTo( (Integer) oo.getKey());
case LONG : return ( (Long) key).compareTo( (Long) oo.getKey());
case STRING : return ((String) key).compareTo( (String) oo.getKey());
case BARRAY : return compareByteArray( (ByteArray) key, (ByteArray) oo.getKey());
case BYTEARY: return compareArray( (byte[]) key, (byte[]) oo.getKey() );
default: return 1;
}
}
else return 1;
}
private int compareArray(byte[] a, byte[] b) {
int len = Math.max( a.length, b.length );
for ( int i = 0; i < len ; i++ ) {
if ( a.length >= i && b.length >= i) {
if ( a[i] < b[i] ) return -1;
else if ( a[i] > b[i] ) return 1;
}
else if ( a.length > i && b.length < i ) return 1;
else if ( a.length < i && b.length > i ) return -1;
}
// same length and content
return 0;
}
private int compareByteArray(ByteArray a, ByteArray b) {
int len = Math.max( a.length(), b.length() );
for ( int i = 0; i < len ; i++ ) {
if ( a.length() >= i && b.length() >= i) {
if ( a.get()[i] < b.get()[i] ) return -1;
else if ( a.get()[i] > b.get()[i] ) return 1;
}
else if ( a.length() > i && b.length() < i ) return 1;
else if ( a.length() < i && b.length() > i ) return -1;
}
// same length and content
return 0;
}
}
|
Python
|
UTF-8
| 597 | 3.765625 | 4 |
[] |
no_license
|
class Shape:
def __init__(self, name):
self.name = name
class FourSides(Shape):
def __init__(self, name,
a, b, c, d):
super().__init__(name)
self.a = a
self.b = b
self.c = c
self.d = d
def __str__(self):
return self.__str__() +\
f'{a} {b} {c} {d} Hekef: {self.getHekef()}'
def getHekef(self):
return a + b + c + d
class Rectangle(FourSides):
def __init__(self, name, a, b):
super.__init__(name, a, b, a, b)
def getHekef(self):
return self.a * 2 + self.b * 2
|
Shell
|
UTF-8
| 2,653 | 2.5625 | 3 |
[] |
no_license
|
# Maintainer: Arkham <arkham at archlinux dot us>
# Contributor: MacWolf <macwolf@archlinux.de>
pkgname=vlc-git
pkgver=20090716
pkgrel=1
pkgdesc="VideoLAN Client is a multi-platform MPEG, VCD/DVD, and DivX player.Development GIT Version."
arch=('i686' 'x86_64')
url="http://www.videolan.org/vlc/"
license=('GPL')
depends=('libmad' 'libmpeg2' 'ffmpeg' \
'hal' 'fluidsynth' 'lua' 'libass' \
'libdvbpsi' 'fribidi' 'sysfsutils' \
'libdvdnav' 'libnotify' 'libdvdread' \
'libmatroska' 'libcddb' 'libmpcdec'\
'faad2' 'qt' 'libmodplug' 'speex' 'sdl_image' \
'libxml2' 'libdca' 'libxv' 'avahi' 'taglib')
makedepends=('a52dec' 'make' 'm4' 'pkgconfig' 'automake' 'autoconf' 'git' 'live-media>=2008.09.02')
conflicts=('vlc' 'vlc-svn' 'vlc-nightly')
provides=('vlc' 'vlc-svn' 'vlc-nightly')
install=vlc.install
source=()
md5sums=()
_gitroot=git://git.videolan.org/vlc.git
_gitname=vlc
build() {
cd $startdir/src
if [ -d $_gitname ]; then
cd $_gitname && git pull origin
cd ..
else
git clone $_gitroot
fi
rm -rf $_gitname-build
git clone $_gitname $_gitname-build
msg "GIT checkout done or server timeout"
cd $_gitname-build
msg "Generating necessary files"
./bootstrap
msg "Generating done."
msg "Starting make..."
[ "${CARCH}" = "i686" ] && EXTRAFEATURES="--enable-loader --disable-live555 --with-live555-tree=/usr/lib/live-media"
[ "${CARCH}" = "x86_64" ] && EXTRAFEATURES="--enable-fast-install --enable-live555 --with-live555-tree=/usr/lib/live-media"
./configure --prefix=/usr --prefix=/usr \
--enable-dvdread \
--enable-dvdnav \
--disable-rpath \
--enable-qt4 \
--enable-faad \
--enable-alsa \
--enable-skins2 \
--enable-dvb \
--enable-v4l \
--enable-theora \
--enable-flac \
--enable-snapshot \
--enable-hal \
--enable-dbus \
--enable-ogg \
--enable-dbus-control \
--enable-shared \
--enable-nls \
--enable-lirc \
--enable-shout \
--enable-pvr \
--enable-release \
--enable-libass \
--disable-zvbi \
--program-suffix= \
--with-dv-raw1394=/usr/include/libraw1394 ${EXTRAFEATURES} || return 1
CFLAGS="$CFLAGS -fPIC"
make || return 1
make DESTDIR=$startdir/pkg install || return 1
for res in 16 32 48; do
install -D -m644 share/vlc${res}x${res}.png \
$startdir/pkg/usr/share/icons/hicolor/${res}x${res}/apps/vlc.png || return 1
done
rm -rf ${startdir}/pkg/usr/lib/mozilla
}
|
C#
|
UTF-8
| 1,707 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WeatherGrabber.WebClient.Services.WeatherGrabber;
using WeatherGrabber.WebClient.Services.WeatherGrabber.DTO;
using WeatherGrabber.WebClient.ViewModels;
namespace WeatherGrabber.WebClient.Pages
{
public class IndexModel : PageModel
{
private readonly IWeatherGrabberService _weatherService;
public IndexModel(IWeatherGrabberService weatherService)
{
_weatherService = weatherService;
Cities = new List<CityWeatherInfoViewModel>();
}
public IList<CityWeatherInfoViewModel> Cities { get; set; }
public CityWeatherInfoViewModel SelectedCity { get; set; }
public string ServiceStatus { get; set; }
public async Task OnGet(int? id)
{
try
{
var cities = await _weatherService.GetCitiesAsync();
Cities = cities.Select(c => new CityWeatherInfoViewModel
{
CityId = c.CityId,
Name = c.Name,
TempDay = c.TempDay,
TempNight = c.TempNight,
WeatherComment = c.WeatherComment
}).ToList();
}
catch (WeatherGrabberUnavailableException)
{
ServiceStatus = "Сервис с данными о погоде недоступен";
}
if (id != null)
{
SelectedCity = Cities.FirstOrDefault(c => c.CityId == id.Value);
}
}
}
}
|
Python
|
UTF-8
| 739 | 3.640625 | 4 |
[] |
no_license
|
#!/usr/bin/env python
import cv2
import numpy as np #assigning the name np to numpy
a = np.zeros((5,5)) #Creates array of all zeros of shape 5x5
b = np.ones((4,4)) #Creates array of all ones of shape 4x4
c = np.random.randint(20,size =(15,15)) #Creates a random 2D array of integers (between 0 to 19) of shape 15 x 15
t = np.transpose(c,(2, 0 ,1)) #do transpose operation on the array c
ba = np.bitwise_and(c > 3, c < 9)
print("From 3rd column: ")
print(c[:,3:]) #prints the Output columns from 3 to last column
print("From 3rd row: ")
print(c[2:,:]) #prints the Output starting from third row of array
print(a) #prints the created array
|
Java
|
WINDOWS-1258
| 123 | 2.0625 | 2 |
[
"MIT"
] |
permissive
|
package assignment3;
public interface IScore { //scoreҶ interface
public abstract char getGrade(int score);
}
|
PHP
|
UTF-8
| 2,010 | 3.1875 | 3 |
[] |
no_license
|
<!-- Имеется набор данных, описывающих изменение температуры воздуха в одном городе в течение нескольких суток. Данные представлены массивом, в котором каждый элемент - это массив, содержащий список температур в течение одних суток.
Допустим, у нас есть статистика температур (например, по состоянию на утро, день и вечер) за три дня. Для первого дня значения температур составляют: -5°, 7°, 1°; для второго дня: 3°, 2°, 3°; и для третьего дня: -1°, -1°, 10° . Массив, отражающий такую статистику, будет выглядеть так:
$data = [
[-5, 7, 1],
[3, 2, 3],
[-1, -1, 10],
]
src\Arrays.php
Реализуйте функцию getIndexOfWarmestDay, которая находит самый тёплый день (тот, в котором была зарегистрирована максимальная температура) и возвращает индекс этого дня в исходном массиве.
$data = [
[-5, 7, 1],
[3, 2, 3],
[-1, -1, 10],
];
getIndexOfWarmestDay($data); // 2
Если на вход поступил пустой массив, то функция должна вернуть null
Подсказки
Поиск максимального числа в массиве можно выполнить, используя функцию max-->
<?php
function getIndexOfWarmestDay($array)
{
if (empty($array)) {
return null;
}
$max = max($array[0]);
$maxKey = 0;
foreach ($array as $key => $value) {
if (max($value) > $max) {
$max = $value;
$maxKey = $key;
}
}
return $maxKey;
}
|
Python
|
UTF-8
| 609 | 3.03125 | 3 |
[] |
no_license
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
queue, dic, maxAns = [root], {}, 0
while queue:
node = queue.pop(0)
if not node: continue
dic[node.val] = dic.get(node.val, 0) + 1
maxAns = max(maxAns, dic[node.val])
queue.append(node.left)
queue.append(node.right)
return [k for k,v in dic.items() if v == maxAns]
|
C#
|
UTF-8
| 1,287 | 2.75 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinningTrap : PushBackTrap
{
Transform topPoint;
Transform bottomPoint;
bool movingDown = false;
[SerializeField]
[Range(5f, 20f)]
private float speed = 10f;
// Start is called before the first frame update
void Start()
{
topPoint = gameObject.transform.Find("TopPoint");
bottomPoint = gameObject.transform.Find("BottomPoint");
topPoint.SetParent(null, true);
bottomPoint.SetParent(null, true);
}
// Update is called once per frame
void Update()
{
float step = speed * Time.deltaTime; // calculate distance to move
if (!movingDown)
{
transform.position=Vector3.MoveTowards(transform.position, topPoint.position, step);
if (Vector3.Distance(transform.position, topPoint.position) < 0.0001f)
{
movingDown = true;
}
}
else
{
transform.position = Vector3.MoveTowards(transform.position, bottomPoint.position, step);
if (Vector3.Distance(transform.position, bottomPoint.position) < 0.0001f)
{
movingDown = false;
}
}
}
}
|
Java
|
UTF-8
| 474 | 2.65625 | 3 |
[] |
no_license
|
package core;
import java.util.ArrayList;
import java.util.List;
public class Mural
{
private String nome;
private String descricao;
private List<Post> posts;
public Mural(String nome) {
this.nome = nome;
this.posts = new ArrayList<>();
}
public void postar(Post post){
this.posts.add(post);
}
public void listarPosts(List<Post> Post){
for(Post post: this.posts){
System.out.println(post);
}
}
public void remover(Post post){
//TODO
}
}
|
Java
|
UTF-8
| 1,201 | 2.421875 | 2 |
[] |
no_license
|
/**
*
*/
package com.dineshonjava.prodos.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.dineshonjava.prodos.domain.Product;
import com.dineshonjava.prodos.repository.ProductRepository;
/**
* @author Dinesh.Rajput
*
*/
@RestController
public class ProductController {
private ProductRepository productRepository;
public ProductController(ProductRepository productRepository) {
super();
this.productRepository = productRepository;
}
@GetMapping(value = "/products", produces = {MediaType.APPLICATION_JSON_VALUE})
public List<Product> findAll(){
List<Product> products = new ArrayList<>();
productRepository.findAll().forEach(i -> products.add(i));
return products;
}
@GetMapping(value = "/products/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
public Product findProductById(@PathVariable String id){
return productRepository.findById(id).isPresent() ? productRepository.findById(id).get() : null;
}
}
|
C++
|
UTF-8
| 947 | 2.859375 | 3 |
[] |
no_license
|
#include <iostream>
#include<vector>
#include<unistd.h>
#include<cmath>
#include <csignal>
#include<queue>
#include<bitset>
#include<memory>
#include<stack>
#include<map>
#include<algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void traverse(TreeNode* root, vector<int> &tmp, vector<vector<int>> &rst, int now, int tar){
if(root){
tmp.push_back(root->val);
if(now+root->val == tar and !root->left and !root->right){ rst.push_back(tmp); }
traverse(root->left, tmp, rst, now+root->val, tar);
traverse(root->right, tmp, rst, now+root->val, tar);
tmp.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> rst(0, vector<int>());
vector<int> tmp(0);
traverse(root, tmp, rst, 0, sum);
return rst;
}
int main() {
return 0;
}
|
Markdown
|
UTF-8
| 6,328 | 2.640625 | 3 |
[] |
no_license
|
---
description: "Easiest Way to Prepare Any-night-of-the-week Spicy Tuna Tostada"
title: "Easiest Way to Prepare Any-night-of-the-week Spicy Tuna Tostada"
slug: 1107-easiest-way-to-prepare-any-night-of-the-week-spicy-tuna-tostada
date: 2020-08-14T00:17:23.919Z
image: https://img-global.cpcdn.com/recipes/ee8e81df5e5cee5a/751x532cq70/spicy-tuna-tostada-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/ee8e81df5e5cee5a/751x532cq70/spicy-tuna-tostada-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/ee8e81df5e5cee5a/751x532cq70/spicy-tuna-tostada-recipe-main-photo.jpg
author: Laura Fleming
ratingvalue: 3.2
reviewcount: 13
recipeingredient:
- " Tuna"
- "9 oz tuna steak"
- "2 tbsp soy sauce"
- "1/2 ginger root peeled and minced"
- "1 lime"
- "as needed olive oil"
- " Spicy mayo"
- "3 tbsp mayonnaise"
- "1 tsp Pequin pepper powder if available or substitute with Cayenne pepper"
- " Fried leek"
- "2 of the white part of a leek"
- "as needed frying oil of your choice do not use olive oil"
- " Tostadas"
- "4 tostadas"
- "1 ripe avocado"
recipeinstructions:
- "In a bowl, combine soy sauce, lime juice, and ginger. Marinate the tuna in this, turning ocassionally to fully impregnate."
- "For the spicy mayo: ideally, you'd use Pequin pepper powder, but that's not always easy to find, so you can substitute with Cayenne pepper, as we did here. Add the powder to the mayonnaise and mix well."
- "Next, cut the leek in half and slice it into half-moons, as thinly as possible."
- "In a skillet, heat frying oil on high and fry the leeks until golden brown. Be careful not to let them darken too much, as they will become bitter. Remove from heat and let cool on paper towels to absorb excess oil."
- "Using the same skillet (caution: very hot), heat the olive oil and sear the tuna. No more than one minute per side! Then, transfer to a cutting board and slice it as thinly as possible."
- "Spread the spicy mayo on each tostada and distribute the tuna slices on them."
- "Add 1/4 of the avocado on each tostada and top with a generous pinch of fried leek. Voilá! Enjoy!"
categories:
- Recipe
tags:
- spicy
- tuna
- tostada
katakunci: spicy tuna tostada
nutrition: 295 calories
recipecuisine: American
preptime: "PT25M"
cooktime: "PT45M"
recipeyield: "2"
recipecategory: Dinner
---

Hello everybody, it's John, welcome to our recipe site. Today, we're going to make a special dish, spicy tuna tostada. It is one of my favorites. For mine, I'm gonna make it a bit unique. This is gonna smell and look delicious.
Spiced Tuna Tostada with Blackberry Chipotle Sauce. Lunch Recipe: Healthy Tuna Salad Stuffed Avocado by Everyday Gourmet with Blakely. White albacore tuna, onion, and corn are mixed with the flavors of lime, cilantro, and piquant hot Stir to combine, then spoon onto tostada shells.
Spicy Tuna Tostada is one of the most favored of recent trending meals on earth. It is enjoyed by millions every day. It is easy, it's quick, it tastes delicious. They're nice and they look fantastic. Spicy Tuna Tostada is something that I've loved my whole life.
To begin with this recipe, we must prepare a few ingredients. You can have spicy tuna tostada using 15 ingredients and 7 steps. Here is how you cook it.
<!--inarticleads1-->
##### The ingredients needed to make Spicy Tuna Tostada:
1. Get Tuna:
1. Take 9 oz tuna steak
1. Prepare 2 tbsp soy sauce
1. Take 1/2 " ginger root, peeled and minced
1. Make ready 1 lime
1. Make ready as needed olive oil
1. Prepare Spicy mayo:
1. Take 3 tbsp mayonnaise
1. Make ready 1 tsp Pequin pepper powder, if available, or substitute with Cayenne pepper
1. Take Fried leek:
1. Make ready 2 " of the white part of a leek
1. Take as needed frying oil of your choice (do not use olive oil)
1. Prepare Tostadas:
1. Take 4 tostadas
1. Prepare 1 ripe avocado
These tuna tostadas by Gabriela Cámara of Mexico City's Contramar require a bare minimum of Tostadas, like tacos, are ostensibly simple affairs: a tortilla serving as an edible serving vessel for a. This Spicy Tuna Tostadas recipe is featured in the Fish feed along with many more. Taking canned tuna up a serious notch with Spicy Tuna Tostadas -@mykitchenlove. Brush tuna lightly with olive oil and season with salt and pepper.
<!--inarticleads2-->
##### Steps to make Spicy Tuna Tostada:
1. In a bowl, combine soy sauce, lime juice, and ginger. Marinate the tuna in this, turning ocassionally to fully impregnate.
1. For the spicy mayo: ideally, you'd use Pequin pepper powder, but that's not always easy to find, so you can substitute with Cayenne pepper, as we did here. Add the powder to the mayonnaise and mix well.
1. Next, cut the leek in half and slice it into half-moons, as thinly as possible.
1. In a skillet, heat frying oil on high and fry the leeks until golden brown. Be careful not to let them darken too much, as they will become bitter. Remove from heat and let cool on paper towels to absorb excess oil.
1. Using the same skillet (caution: very hot), heat the olive oil and sear the tuna. No more than one minute per side! Then, transfer to a cutting board and slice it as thinly as possible.
1. Spread the spicy mayo on each tostada and distribute the tuna slices on them.
1. Add 1/4 of the avocado on each tostada and top with a generous pinch of fried leek. Voilá! Enjoy!
Grill until seared on the outside, rare in the Divide equally among tostadas, sprinkle with crumbled feta and place a lime wedge alongside. The sweet and spicy pineapple and jalapeno slaw are a perfect topping for these tostadas. Canned Tuna Ceviche Tostadas, There are many recipes for ceviche, (also spelled cebiche), some of which use fish, shrimp, or a combination of seafood. There is even a jicama ceviche! Welcome to spicy tuna sushi bar & grill!
So that is going to wrap this up with this special food spicy tuna tostada recipe. Thanks so much for your time. I am confident that you will make this at home. There is gonna be interesting food in home recipes coming up. Remember to save this page in your browser, and share it to your family, friends and colleague. Thank you for reading. Go on get cooking!
|
JavaScript
|
UTF-8
| 18,741 | 2.515625 | 3 |
[] |
no_license
|
requirejs.config({
baseUrl:'js/lib'
});
requirejs(['jquery', 'modernizr'], function($, modernizr) {
////// shuffle function
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// pictures
var picz = ['../images/ad.jpg',
'../images/ad-2.jpg',
'../images/ad-3.jpg',
'../images/ad-4.jpg',
'../images/ad-5.jpg'];
// songs
var songs = ['beats/breathe.mp3',
'beats/everything.mp3',
'beats/jazz.mp3',
'beats/electric.mp3',
'beats/preservation.mp3',
'beats/88.mp3',
'beats/93.mp3',
'beats/cream.mp3',
'beats/drop.mp3',
'beats/far.mp3',
'beats/knock.mp3',
'beats/ny.mp3',
'beats/ready.mp3',
'beats/welcome.mp3',
'beats/what.mp3',
'beats/saliva.mp3',
'beats/vibe.mp3'];
shuffle(songs);
// Words to use in freestyle
var hype = ['about to break it down', 'about to drop some bars', 'lay down the beat', 'drop the beat', 'drop it', 'lets go', 'spin it', 'lay it down', 'pass the mic'];
var greetings = ['hello,', 'yo', 'yo,', 'what up', 'what up,', 'sup', 'sup', 'yep', 'hi', 'whats happening', 'whats happening,', 'whats up', 'whats up', 'yeah', 'yeah,', 'hey', 'hey,', 'uh', 'uh huh', 'yup'];
var be = ['is', 'was', 'will be', 'is not', 'was not', 'will not be', 'will never be', 'never was', 'never is', 'always is', 'always will be', 'I am', 'I be', 'we be', 'they be'];
var r1 = ['mic', 'like', 'spike', 'bike', 'pike', 'turnpike', 'ride', 'slide', 'tide', 'pie', 'my', 'cry', 'tie', 'sty', 'pry', 'dry'];
var r2 = ['tree', 'me', 'tee', 'see', 'plea', 'treat', 'meet', 'seat', 'feat', 'beat', 'beats', 'meats', 'pleat', 'treat', 'pee', 'dee', 'flee'];
var r3 = ['rock', 'mock', 'tock', 'sock', 'clock', 'knock', 'hard knock', 'socks', 'block', 'blocks', 'pot', 'trot', 'sought'];
var r4 = ['bark', 'mark', 'spark', 'stark', 'park', 'lark', 'dark', 'fart', 'part', 'apart', 'dart', 'mart', 'cart', 'tart'];
var r5 = ['thug', 'mug', 'tug', 'rug', 'snug', 'pug', 'slug', 'plug', 'sun', 'ton', 'run', 'spun', 'done', 'fun', 'won'];
var r6 = ['cat', 'tat', 'tats', 'mat', 'rat', 'splat', 'tap', 'nap', 'rap', 'rapping', 'pat', 'gnat', 'slap', 'trap', 'map', 'sap', 'dat', 'spat', 'bat', 'tap'];
var r7 = ['spit', 'knit', 'bit', 'sit', 'pit', 'mit', 'never quit', 'quit', 'tip', 'sip', 'dip', 'fit', 'equip', 'equipped', 'rip', 'ripped'];
var r8 = ['train', 'main', 'cane', 'rain', 'sane', 'plain', 'bane', 'dane', 'profane', 'propane', 'wane', 'sprain', 'crane', 'explain', 'twain'];
var r9 = ['got', 'rot', 'not', 'spot', 'pop', 'top', 'sop', 'mop', 'crop', 'bop', 'beep bop', 'beep', 'bought', 'caught', 'dot'];
var r10 = ['ready', 'steady', 'spaghetti', 'teddy', 'petty', 'yeti', 'many', 'confetti', 'penny', 'pennies', 'benny'];
var r11 = ['find', 'wind', 'rewind', 'kind', 'mind', 'bind', 'rind', 'blind', 'twine', 'mine', 'sign', 'wine', 'time', 'rhyme', 'rhymes'];
var r12 = ['rollin', 'bowlin', 'patrol', 'rovin', 'roving', 'rolling', 'riding', 'cruising', 'sliding', 'slipping', 'tripping', 'trip'];
var r13 = ['ballin', 'balling', 'balla', 'calling', 'callin', 'stallin', 'crawling', 'impala', 'falling', 'apalling', 'shot callin', 'folly', 'trolly'];
// themes
var sports = ['ball', 'dunk', 'shoot', 'sports', 'basket', 'basketball', 'baseball', 'football', 'quarterback', 'coach', 'player', 'game', 'points', 'score', 'play', 'playing', 'soccer', 'slam dunk'];
var fruits = ['banana', 'orange', 'apple', 'pineapple', 'tangerine', 'melon', 'watermelon', 'grape', 'fruit', 'grapefruit', 'lemon', 'lime', 'cherry', 'strawberry', 'raspberry', 'blueberry'];
var veggies = ['veggies', 'vegetable', 'carrot', 'tomato', 'lettuce', 'broccoli', 'asparagus', 'pepper', 'mushroom'];
var art = ['paint', 'paper', 'canvas', 'pen', 'pencil', 'collage', 'collab', 'piece', 'art', 'photo', 'photograph'];
var landscape = ['river', 'mountain', 'plain', 'hill', 'lake', 'stream', 'rock', 'tree', 'bush', 'plant', 'flower', 'valley'];
var mystical = ['dragon', 'werewolf', 'wizard', 'godzilla', 'zombie', 'witch', 'dinosaur', 't rex', 'monster', 'alien', 'u f o', 'lifeform'];
var cars = ['audi', 'porsche', 'benz', 'mercedes', 'land rover', 'range rover', 'ferrari', 'chevy', 'subaru', 'race car', 'dragster'];
var animals = ['monkey', 'aardvark', 'elephant', 'tiger', 'lion', 'gazelle', 'eagle', 'spider', 'bug', 'bird', 'fish', 'shark', 'whale', 'gorilla'];
var thug = ['boss', 'old school', 'bawse', 'gangsta', 'fly', 'amigo', 'homy', 'friend', 'hero', 'champion', 'dawg', 'bro', 'brother', 'sister', 'mister', 'pal', 'dude', 'unstoppable'];
var geo = ['USA', 'south america', 'north america', 'canada', 'mexico', 'chile', 'europe', 'africa', 'asia', 'polynesia', 'china', 'antarctica', 'states', 'region', 'country', 'city', 'town'];
var cities = ['salt lake', 'LA', 'los angeles', 'new york', 'NY', 'atlanta', 'chicago', 'toronto', 'tokyo', 'london', 'madrid', 'rome', 'berlin', 'sao paolo', 'seattle', 'san fran', 'paris', 'egypt', 'hong kong'];
var countries = ['united states', 'england', 'italy', 'france', 'argentina', 'germany', 'japan', 'korea', 'new zealand', 'australia', 'russia', 'south africa', 'ghana', 'colombia', 'brazil'];
var money = ['dollar', 'dollar bills', 'cash', 'yo', 'coins', 'cents', 'pounds', 'euros', 'green', 'yen', 'pesos', 'benjamins', 'franklins', 'millions', 'mill', 'paper'];
var colors = ['red', 'yellow', 'green', 'blue', 'purple', 'white', 'black', 'brown', 'orange', 'teal', 'burnt siena', 'yellow ochre', 'gray', 'navy', 'gold', 'silver', 'platinum', 'metallic', 'flourescent'];
var brands = ['google', 'facebook', 'twitter', 'nike', 'snapchat', 'insta', 'tumblr', 'adidas', 'jordan', 'supreme', 'undefeated', 'hundreds', 'vans', 'new era', 'levis', 'uni qlo', 'bape', 'ice cream', 'billionaire boys club'];
var shoes = ['air max', 'spizike', 'air force one', 'dunks', 'high tops', 'slip ons', 'sandals', 'foam posite', 'superstars', 'nikes', 'jordans'];
var bling = ['chain', 'necklace', 'two finger ring', 'piece', 'bling', 'jewels', 'watch', 'accessories', 'snap back', 'fitted', 'belt buckle', 'pin', 'rope'];
var teams = ['yankees', 'dodgers', 'red sox', 'lakers', 'yo', 'celtics', 'jazz', 'warriors', 'sonics', 'giants', 'mets', 'broncos', 'raiders', 'patriots', 'redskins', 'bills', 'cowboys'];
var mrthug = ['shorty', 'shawty', 'grill', 'dough', 'dime', 'bread', 'hustle', 'O G', 'beef', 'street cred', 'rep', 'ill', 'afro', 'cray'];
var marks = ['squiggle', 'circle', 'square', 'rectangle', 'pentagon', 'octogon', 'line', 'splotch', 'stain', 'cube', 'pyramid', 'box', 'crate'];
var chips = ['doritos', 'cheetos', 'lays', 'sour cream and onion', 'barbecue', 'tortilla chips', 'fritos', 'potato chips', 'cheddar', 'salt and vinegar', 'spicy nacho', 'nacho'];
var mrp = ['got money', 'got cheese', 'bling bling', 'yo', 'gold chain', 'gold and a pager', 'dont mess with me', 'i got it locked down', 'so fresh', 'so clean', 'i got it on lockdown', 'you cant believe this', 'half man half amazing'];
var days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'party', 'party time', 'hard in the paint', 'dance party', 'week', 'year', 'month', 'birthday'];
var months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
var exp = ['you wouldnt believe', 'cant compete', 'cant believe it', 'you better believe it', 'ahh yeahh', 'oh yeah', 'thats right', 'how I do', 'dont trip', 'on point', 'yes sir'];
var mrsports = ['pass', 'give and go', 'overlap', 'run', 'i got hops', 'jumping', 'layup', 'three pointer', 'jumpshot', 'fade away', 'buzzer beater', 'underdog', 'rainbow', 'home run', 'ground rule double'];
var comp = ['im like', 'im like a', 'like a', 'i be like', 'like im', 'like im gonna', 'comparable to a', 'im all like', 'i be all', 'like its gonna', 'like its a', 'its like'];
var disgust = ['yuck', 'ew', 'gross', 'phew', 'sick', 'nasty', 'sick nasty', 'disgusting', 'stinky', 'smelly', 'dirty', 'yo', 'yeahh man'];
var bounce = ['bounce with it', 'let it bump', 'let it bounce', 'stacking money', 'put your hands up', 'if you feeling the beat', 'bounce with the beat', 'put your hands up in the sky', 'get your hands up'];
var bounce2 = ['if you dig it', 'what you saying', 'let me know', 'if you feel the vibe', 'listen up', 'listen close', 'hear me', 'started from the bottom', 'can you dig it', 'can i kick it', 'kicking it', 'made it to the top'];
// random things
var gadgets = ['helicopter', 'airplane', 'up high', 'in the sky', 'flying', 'submarine', 'truck', 'motorcycle', 'rocket', 'spaceship', 'fighter jet', 'tank', 'bicycle', 'trike'];
var clothes = ['slippers', 'sweats', 'polo', 'button up', 'dress', 'skirt', 't shirt', 'tall tee', 'linen', 'cotton blend', 'socks', 'cleats', 'boots', 'bracelet', 'belt'];
var js = ['jordan ones', 'jordan twos', 'jordan threes', 'jordan fours', 'jordan fives', 'jordan sixes', 'jordan sevens', 'jordan eights', 'jordan nines', 'jordan tens', 'jordan elevens', 'jordan twelves', 'jordan thirteens', 'jordan fourteens'];
var jstype = ['true blue', 'elephant print', 'infared', 'original', 'on ice', 'mint condition', 'retro', 'colorway', 'deadstock', 'shrink wrapped', 'flight club', 'sneakers', 'sneaker head'];
var sneak = ['aglets', 'beaters', 'hype beast', 'flip flop', 'hype', 'jumpman', 'lows', 'mids', 'air jordan', 'player edition', 'sample', 'boutique', 'style', 'mags'];
var mexp = ['for real', 'for sure', 'of course', 'there it is', 'laid it down', 'seriously', 'are you kidding', 'for serious', 'dont mess', 'dont hate', 'haters', 'brush your shoulders off'];
var yuup = ['how gangster is that', 'limited quantity', 'wack', 'thats wack', 'thats dope', 'dope', 'rock it', 'lame', 'rope', 'posers', 'posters', 'hating', 'make it'];
var yuup2 = ['swag', 'swagger', 'steeze', 'cool', 'hard to believe', 'got game', 'graphics in your fade', 'flat top', 'loser', 'mustache', 'beard', 'sideburns', 'ear ring'];
var rapM = ['bars', 'on the beat', 'bass line', 'chorus', 'lines', 'rhymes', 'smooth flow', 'flow', 'rhythm', 'tempo', 'poet', 'poetry', 'poetic justice', 'space jam'];
var masfoods = ['salad', 'steak', 'bacon', 'eggs', 'almonds', 'cashews', 'berry', 'candy', 'chocolate', 'peanut butter', 'food', 'treats'];
var word = ['word up', 'in the hood', 'from the hood', 'hood forever', 'cops', 'neighborhood', 'broadway', 'courtside', 'concrete jungle', 'melting pot', 'hip hop'];
var word2 = ['gamble', 'got that cash', 'cash under the mattress', 'cars', 'gang', 'crew', 'holla', 'holla back', 'rap star', 'ball player', 'limelight'];
var blah = ['water bottle', 'butter', 'cash money', 'pringles', 'gym shorts', 'necklace', 'ring', 'rock on', 'so sick', 'holla at me', 'bro'];
var connect = ['its a', 'feeling like a', 'acting like a', 'got rhymes like a', 'got rhymes like', 'got skills like', 'so sick like im', 'you can call me', 'you can say im'];
var conn = ['make you wanna', 'if youre gonna', 'why not', 'freestyles', 'freestyle', 'I got rhymes like', 'I can rhyme like', 'my flow is like', 'my flow is so', 'syllables'];
var con = ['alright man', 'pay cut', 'bass line', 'turn up the bass', 'turn up the volume', 'hold the microphone', 'so cool', 'spit on the mic', 'spit on the microphone', 'spitting fast'];
var pup = ['rest assured', 'heaven', 'influence', 'running', 'take a guess', 'on the beat', 'lay it down', 'bust it', 'garbage', 'running in the streets', 'grocery shopping'];
var pu = ['messed up', 'determination', 'shower', 'dirt', 'toes', 'ankle', '22 rims', 'million bucks', 'coins', 'dread locks', 'pony tail', 'corn rows', 'flat top'];
var hair = ['mohawk', 'mullet', 'bleached tips', 'steps', 'fade', 'sideburns', 'handle bar mustache', 'goatee', 'haircut'];
var thanks = ['thanks tribe', 'thanks fabo', 'thanks kendrick', 'thanks mase', 'thanks yeezy', 'thanks del', 'thanks cool kids', 'thanks mikey and chuck', 'thanks wu tang', 'thanks souls of mischief', 'thanks nas', 'thanks jay', 'thanks T.I.', 'thanks doom', 'thanks snoop', 'thanks pharell', 'thanks the game', 'thanks fugees'];
var shoutout = ['let me give a shout out to', 'give props to', 'holding it down', 'shout out', 'featuring the', 'free styles', 'rap battle'];
var wordz = [greetings, be, r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13,
sports, fruits, veggies, art, landscape, mystical, cars, animals, thug,
geo, cities, countries, money, colors, brands, shoes, bling, teams, mrthug,
marks, chips, mrp, days, months, exp, mrsports, comp, disgust, bounce, bounce2,
gadgets, clothes, js, jstype, sneak, mexp, yuup, yuup2, rapM, masfoods, word, word2,
blah, connect, conn, con, pup, pu, hair, thanks, shoutout];
// rapperz
var synth = window.speechSynthesis;
var rapperz = [];
var len = songs.length - 1;
function loadVoices() {
window.speechSynthesis.onvoiceschanged = function() {
// synth.getVoices().forEach(function(voice) {
// console.log(voice.name, voice.default ? voice.default :'');
// rapperz.push(voice);
// });
rapperz = synth.getVoices();
console.log(rapperz);
};
}
// function that shuffles and plays songs
var audio = document.getElementById('audio');
var current = 0;
function run() {
$('#audio source').attr('src', songs[current]);
audio.load();
audio.play();
}
function playStuff() {
run();
audio.addEventListener('ended', function(e) {
if (current == len) {
current = 0;
} else {
current++;
}
run();
});
}
// rapping stuff
var barLen = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var swTm = [30000, 45000, 40000, 20000, 15000, 25000];
var timez = [500, 750, 1000, 1500, 1750];
var rates = ['1', '1', '.5', '1', '2', '1.5', '.7', '1', '2', '1', '1', '1']
var lead = [0, 1, 11, 29, 21, 26, 43, 44, 55, 56];
var who;
var spit;
var lines = document.getElementById('main');
var left = true;
var nleft = false;
var select;
// rapping function
function rap() {
var rando = barLen[Math.floor(Math.random() * barLen.length)];
var rando2;
var rando3;
var bar = '';
for (i = 0; i < rando; i++) {
rando2 = wordz[Math.floor(Math.random() * wordz.length)];
rando3 = rando2[Math.floor(Math.random() * rando2.length)];
bar += rando3 + ' ';
}
spit = new SpeechSynthesisUtterance();
spit.text = bar;
spit.rate = rates[Math.floor(Math.random() * rates.length)];
spit.voice = who;
synth.speak(spit);
spit.onend = function() {
if (left === true) {
var node = document.createElement('p');
var textnode = document.createTextNode(bar);
node.appendChild(textnode);
lines.appendChild(node);
} else {
var node = document.createElement('p');
node.className = 'right';
var textnode = document.createTextNode(bar);
node.appendChild(textnode);
lines.appendChild(node);
}
// if (nleft === false) {
//
// } else {
// who = rapperz[lead[Math.floor(Math.random() * lead.length)]];
// }
setTimeout(function() {
rap();
}, timez[Math.floor(Math.random() * timez.length)]);
}
}
function choozRapper() {
select = setTimeout(function() {
console.log('switching rappers');
who = rapperz[lead[Math.floor(Math.random() * lead.length)]];
setTimeout(function() {
$('.switch').css('display', 'block');
setTimeout(function() {
$('.switch').css('display', 'none');
}, 700);
}, 500);
if (left === true) {
left = false;
console.log('it was true so i made it false');
} else {
left = true;
console.log('it was false so i made it true');
}
// spit.onend = function() {
// nleft = true;
// setTimeout(function() {
// nleft = false;
// }, 300);
// }
// rap();
choozRapper();
}, swTm[Math.floor(Math.random() * swTm.length)]);
}
var images = ['../images/ad.jpg',
'../images/ad-5.jpg',
'../images/ad-3.jpg',
'../images/ad-4.jpg',
'../images/ad-2.jpg',
'../images/ad-6.jpg'];
///// switch images
var indexSw = 1;
function switchImage() {
setInterval(function() {
$('.image img').attr('src', images[indexSw % images.length]);
indexSw = indexSw + 1;
}, 4000);
}
/// starting voice
var starting;
function hypeIt() {
starting = new SpeechSynthesisUtterance(hype[Math.floor(Math.random() * hype.length)]);
synth.speak(starting);
starting.onend = function() {
setTimeout(function() {
playStuff();
choozRapper();
rap();
switchImage();
}, 500);
}
}
if (Modernizr.speechsynthesis && Modernizr.audio) {
window.console.log('you got both!');
loadVoices();
hypeIt();
} else {
alert('This isnt going to work! You need a newer version of your browser.');
}
});
|
Java
|
UTF-8
| 407 | 2 | 2 |
[] |
no_license
|
package com.ledavijeans.demo.repository;
import com.ledavijeans.demo.entity.Customer;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
* Created by arrai on 5/16/2018.
*/
public interface CustomerRepository extends PagingAndSortingRepository <Customer, Integer>{
public List<Customer> findAll();
List<Customer> findByNameLike (String name);
}
|
Java
|
UTF-8
| 7,140 | 2.46875 | 2 |
[] |
no_license
|
package cloudoer.su.service.impl;
import cloudoer.su.base.impl.BaseServiceImpl;
import cloudoer.su.entity.Classes;
import cloudoer.su.entity.Dormitory;
import cloudoer.su.entity.Student;
import cloudoer.su.exception.ServiceException;
import cloudoer.su.service.StudentService;
import cloudoer.su.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
@Service("studentService")
@Transactional
public class StudentServiceImpl extends BaseServiceImpl implements StudentService {
public List<Student> getAll() {
return studentDao.getAll();
}
public List<Student> getByPage(int pageNo, int pageSize) {
return studentDao.getByPage(pageNo,pageSize);
}
public Student getById(String id) {
return (Student) studentDao.getById(id);
}
public Student getByNumber(String number) {
return (Student) studentDao.getByNumber(number);
}
public String add(Student student, String classesId, String dormitoryId) throws Exception{
student.setClasses((Classes) classesDao.getById(classesId));
try {
student.setDormitory((Dormitory) dormitoryDao.getById(dormitoryId));
}catch (Exception e){
e.printStackTrace();
}
return studentDao.add(student);
}
public void update(Student student, String classesId, String dormitoryId) throws Exception {
Student s = (Student) studentDao.getById(student.getId());
if (s == null){
throw new ServiceException("修改失败,请检查参数");
}
s.setClasses((Classes) classesDao.getById(classesId));
try {
s.setDormitory((Dormitory) dormitoryDao.getById(dormitoryId));
}catch (Exception e){
e.printStackTrace();
}
s.setName(student.getName());
s.setNumber(student.getNumber());
s.setSex(student.getSex());
s.setIdCard(student.getIdCard());
s.setPhone(student.getPhone());
s.setQq(student.getQq());
s.setEmail(student.getEmail());
s.setState(student.getState());
}
public void delete(String id) {
Student s = (Student) studentDao.getById(id);
if (s == null){
throw new ServiceException("删除失败,请检查参数");
}
studentDao.delete(id);
}
public String importFile(File file) throws ServiceException {
HSSFWorkbook workbook = null;
StringBuffer msg = new StringBuffer();
try {
workbook = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = workbook.getSheetAt(0);
int cont = sheet.getLastRowNum()+1;
Student s = null;
int successCount = 0;
int errorCount = 0;
for (int i = 1; i < cont; i++){
try {
s = new Student();
s.setName(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(0)));
s.setNumber(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(1)));
s.setSex(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(2)));
s.setIdCard(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(3)));
s.setPhone(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(4)));
s.setQq(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(5)));
s.setEmail(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(6)));
s.setState(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(7)));
s.setClasses((Classes) classesDao.getByNumber(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(8))));
s.setDormitory((Dormitory) dormitoryDao.getByNumber(ExcelUtil.getCallValueToString(sheet.getRow(i).getCell(9))));
studentDao.add(s);
successCount ++ ;
if (i+1%20==0){
studentDao.getSession().flush();
studentDao.getSession().clear();
}
}catch (ServiceException e){
errorCount++;
msg.append("[第"+(i+1)+"行]原因:" + e.getErrorMsg());
msg.append("<br/>");
}catch (Exception e){
errorCount++;
msg.append("[第"+(i+1)+"行]原因:不明...<br/>");
}
}
msg.insert(0,"文件上传成功<br/>导入成功:"+ successCount +"条" + "<br/>导入失败:"+errorCount+ "条 <br/>记录<br/>");
} catch (IOException e) {
e.printStackTrace();
throw new ServiceException("导入失败,解析文件错误,请检查文件格式");
}
return msg.toString();
}
public void exportFile(OutputStream os) throws Exception {
List<Student> students = studentDao.getAll();
// 创建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建工作表
HSSFSheet sheet = workbook.createSheet("sheet1");
//创建一行
HSSFRow rows = sheet.createRow(0);
//创建这一行的一个单元格
rows.createCell(0).setCellValue("姓名");
rows.createCell(1).setCellValue("学号");
rows.createCell(2).setCellValue("性别");
rows.createCell(3).setCellValue("身份证号码");
rows.createCell(4).setCellValue("电话");
rows.createCell(5).setCellValue("qq号码");
rows.createCell(6).setCellValue("邮箱");
rows.createCell(7).setCellValue("状态");
rows.createCell(8).setCellValue("班级");
rows.createCell(9).setCellValue("寝室");
for (int i = 0; i < students.size(); i++){
rows = sheet.createRow(i+1);
rows.createCell(0).setCellValue(students.get(i).getName());
rows.createCell(1).setCellValue(students.get(i).getNumber());
rows.createCell(2).setCellValue(students.get(i).getSex());
rows.createCell(3).setCellValue(students.get(i).getIdCard());
rows.createCell(4).setCellValue(students.get(i).getPhone());
rows.createCell(5).setCellValue(students.get(i).getQq());
rows.createCell(6).setCellValue(students.get(i).getEmail());
rows.createCell(7).setCellValue(students.get(i).getState());
if (students.get(i).getClasses() != null){
rows.createCell(8).setCellValue(students.get(i).getClasses().getName());
}
if (students.get(i).getDormitory() != null){
rows.createCell(9).setCellValue(students.get(i).getDormitory().getName());
}
}
workbook.write(os);
}
}
|
Java
|
UTF-8
| 870 | 1.851563 | 2 |
[] |
no_license
|
package maxzawalo.c2.full.ui.pc.document;
import maxzawalo.c2.base.bo.DocumentBO;
import maxzawalo.c2.free.ui.pc.document.store.StoreDocListForm;
import maxzawalo.c2.full.bo.document.warrant_4_receipt.Warrant4Receipt;
import maxzawalo.c2.full.data.factory.document.Warrant4ReceiptFactory;
import maxzawalo.c2.full.ui.pc.form.AnaliticsForm;
import maxzawalo.c2.full.ui.pc.model.document.Warrant4ReceiptTableModel;
public class Warrant4ReceiptListForm extends StoreDocListForm<Warrant4Receipt, Warrant4ReceiptForm> {
public Warrant4ReceiptListForm() {
btnCommit.setBounds(370, 11, 45, 40);
factory = new Warrant4ReceiptFactory();
tableModel = new Warrant4ReceiptTableModel();
}
@Override
protected void ShowDocTransaction() {
AnaliticsForm form = new AnaliticsForm(this);
form.setVisible(true);
form.setRegistrator((DocumentBO) GetSelectedItem());
}
}
|
Ruby
|
UTF-8
| 1,802 | 2.828125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'minitest/autorun'
require_relative 'dominoes'
class DominoesTest < Minitest::Test
def test_empty_input_empty_output
# skip
dominoes = []
assert Dominoes.chain?(dominoes)
end
def test_singleton_input_singleton_output
skip
dominoes = [[1, 1]]
assert Dominoes.chain?(dominoes)
end
def test_singleton_that_cant_be_chained
skip
dominoes = [[1, 2]]
refute Dominoes.chain?(dominoes)
end
def test_three_elements
skip
dominoes = [[1, 2], [3, 1], [2, 3]]
assert Dominoes.chain?(dominoes)
end
def test_can_reverse_dominoes
skip
dominoes = [[1, 2], [1, 3], [2, 3]]
assert Dominoes.chain?(dominoes)
end
def test_cant_be_chained
skip
dominoes = [[1, 2], [4, 1], [2, 3]]
refute Dominoes.chain?(dominoes)
end
def test_disconnected_simple
skip
dominoes = [[1, 1], [2, 2]]
refute Dominoes.chain?(dominoes)
end
def test_disconnected_double_loop
skip
dominoes = [[1, 2], [2, 1], [3, 4], [4, 3]]
refute Dominoes.chain?(dominoes)
end
def test_disconnected_single_isolated
skip
dominoes = [[1, 2], [2, 3], [3, 1], [4, 4]]
refute Dominoes.chain?(dominoes)
end
def test_need_backtrack
skip
dominoes = [[1, 2], [2, 3], [3, 1], [2, 4], [2, 4]]
assert Dominoes.chain?(dominoes)
end
def test_separate_loops
skip
dominoes = [[1, 2], [2, 3], [3, 1], [1, 1], [2, 2], [3, 3]]
assert Dominoes.chain?(dominoes)
end
def test_nine_elements
skip
dominoes = [[1, 2], [5, 3], [3, 1], [1, 2], [2, 4], [1, 6], [2, 3], [3, 4], [5, 6]]
assert Dominoes.chain?(dominoes)
end
def test_separate_three_domino_loops
skip
dominoes = [[1, 2], [2, 3], [3, 1], [4, 5], [5, 6], [6, 4]]
refute Dominoes.chain?(dominoes)
end
end
|
Python
|
UTF-8
| 1,701 | 2.765625 | 3 |
[] |
no_license
|
import numpy as np
class MaxPool:
"""
Arguments -
1. filter_shape => (filter_height, filter_width)
2. stride
"""
def __init__(self, filter_shape, stride):
self.fh, self.fw = filter_shape
self.st = stride
def forward(self, inputs):
"""
Arguments -
1. inputs => inputs to maxpool forward are outputs from conv layer
"""
B, C, H, W = inputs.shape
self.grad = np.zeros(inputs.shape)
out = np.zeros((B, C, 1 + (H - self.fh) // self.st,
1 + (W - self.fw) // self.st))
for b in range(B):
for c in range(C):
for j, jj in enumerate(range(0, H-self.fh+self.st, self.st)):
for i, ii in enumerate(range(0, W-self.fw+self.st, self.st)):
block = inputs[b, c, jj:jj+self.fh, ii:ii+self.fw]
p, q = divmod(np.argmax(block.reshape(-1)), self.fw)
self.grad[b, c, jj+p, ii+q] = 1
out[b, c, j, i] = block[p, q]
return out
def backward(self, dloss):
"""
Arguments -
1. dloss => derivative loss wrt output
"""
B, C, H, W = self.grad.shape
for b in range(B):
for c in range(C):
for j, jj in enumerate(range(0, H-self.fh+self.st, self.st)):
for i, ii in enumerate(range(0, W-self.fw+self.st, self.st)):
block = self.grad[b, c, jj:jj+self.fh, ii:ii+self.fw]
self.grad[b, c, jj:jj+self.fh, ii:ii +
self.fw] *= dloss[b, c, j, i]
return self.grad
|
Python
|
UTF-8
| 268 | 4.25 | 4 |
[] |
no_license
|
text = input("Text: ").strip().split(" ")
word_to_count = {}
for word in text:
if word in word_to_count:
word_to_count[word] += 1
else:
word_to_count[word] = 1
for word in word_to_count:
print("{:5s}: {}".format(word, word_to_count[word]))
|
Go
|
UTF-8
| 412 | 2.796875 | 3 |
[] |
no_license
|
package parsers
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
)
const MODULES_FILE = "configs/modules.yaml"
type Module struct {
Config []string `yaml:"modules"`
}
func (m Module) Parse(dir string) []string {
config, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", dir, MODULES_FILE))
if err != nil {
panic(err)
}
err = yaml.Unmarshal(config, &m)
if err != nil {
panic(err)
}
return m.Config
}
|
Java
|
UTF-8
| 14,912 | 1.710938 | 2 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
/*
* Copyright(c) 2004 Concursive Corporation (http://www.concursive.com/) All
* rights reserved. This material cannot be distributed without written
* permission from Concursive Corporation. Permission to use, copy, and modify
* this material for internal use is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies. CONCURSIVE
* CORPORATION MAKES NO REPRESENTATIONS AND EXTENDS NO WARRANTIES, EXPRESS OR
* IMPLIED, WITH RESPECT TO THE SOFTWARE, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY PARTICULAR
* PURPOSE, AND THE WARRANTY AGAINST INFRINGEMENT OF PATENTS OR OTHER
* INTELLECTUAL PROPERTY RIGHTS. THE SOFTWARE IS PROVIDED "AS IS", AND IN NO
* EVENT SHALL CONCURSIVE CORPORATION OR ANY OF ITS AFFILIATES BE LIABLE FOR
* ANY DAMAGES, INCLUDING ANY LOST PROFITS OR OTHER INCIDENTAL OR CONSEQUENTIAL
* DAMAGES RELATING TO THE SOFTWARE.
*/
package org.aspcfs.apps.reportRunner.task;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import org.aspcfs.modules.admin.base.User;
import org.aspcfs.modules.reports.base.QueueCriteriaList;
import org.aspcfs.modules.reports.base.Report;
import org.aspcfs.modules.reports.base.ReportQueue;
import org.aspcfs.modules.reports.base.ReportQueueList;
import org.aspcfs.modules.system.base.Site;
import org.aspcfs.utils.*;
import org.w3c.dom.Element;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Class to compile and generate to PDF a JasperReport
*
* @author matt rajkowski
* @version $Id: ProcessJasperReports.java,v 1.6 2004/06/29 14:08:22
* mrajkowski Exp $
* @created October 3, 2003
*/
public class ProcessJasperReports {
public final static String fs = System.getProperty("file.separator");
public final static String CENTRIC_DICTIONARY = "CENTRIC_DICTIONARY";
public final static String SCRIPT_DB_CONNECTION = "SCRIPT_DB_CONNECTION";
public final static String REPORT_OUTPUT_TYPE = "REPORT_OUTPUT_TYPE";
/**
* Constructor for the ProcessJasperReports object
*
* @param db Description of the Parameter
* @param thisSite Description of the Parameter
* @param config Description of the Parameter
* @param dictionary Description of the Parameter
* @param scriptdb Description of the Parameter
* @throws Exception Description of the Exception
* @throws Exception Description of the Exception
*/
public ProcessJasperReports(Connection db, Connection scriptdb, Site thisSite, Map config, Map dictionary) throws Exception {
//Load the report queue for this site, unprocessed only
ReportQueueList queue = new ReportQueueList();
queue.setSortAscending(true);
queue.setUnprocessedOnly(true);
queue.buildList(db);
//Iterate the list
Iterator list = queue.iterator();
while (list.hasNext()) {
ReportQueue thisQueue = (ReportQueue) list.next();
if (ReportQueueList.lockReport(thisQueue, db)) {
try {
String reportDir = "";
String fontPath = "";
if (((String) config.get("FILELIBRARY")).indexOf("WEB-INF") > 0) {
reportDir = (String) config.get("FILELIBRARY") + ".." + fs + "reports" + fs;
fontPath = (String) config.get("FILELIBRARY") + ".." + fs + "fonts" + fs;
}
if (config.containsKey("WEB-INF")) {
reportDir = (String) config.get("WEB-INF") + "reports" + fs;
fontPath = (String) config.get("WEB-INF") + "fonts" + fs;
}
if (dictionary == null) {
dictionary = new LinkedHashMap();
}
//Load from the repository, save to the user's site
String destDir =
(String) config.get("FILELIBRARY") +
thisSite.getDatabaseName() + fs +
"reports-queue" + fs +
DateUtils.getDatePath(thisQueue.getEntered());
File destPath = new File(destDir);
destPath.mkdirs();
String filename = DateUtils.getFilename() + "-" + thisQueue.getId();
long size = processReport(
thisQueue,
db,
scriptdb,
reportDir,
destDir + filename,
fontPath,
dictionary);
thisQueue.setFilename(filename);
thisQueue.setSize(size);
thisQueue.setStatus(ReportQueue.STATUS_PROCESSED);
// To Email
if (thisQueue.getEmail()) {
User user = new User();
user.setBuildContact(true);
user.setBuildContactDetails(true);
user.buildRecord(db, thisQueue.getEnteredBy());
SMTPMessage message = new SMTPMessage();
message.setHost((String) config.get("MAILSERVER"));
message.setFrom((String) config.get("EMAILADDRESS"));
message.addReplyTo((String) config.get("EMAILADDRESS"));
message.addTo(user.getContact().getPrimaryEmailAddress());
thisQueue.buildReport(db);
message.setType("text/html");
String dbName = thisSite.getDatabaseName();
String templateFilePath = (String) config.get("FILELIBRARY") + fs + dbName + fs + "templates_" + thisSite.getLanguage() + ".xml";
if (!FileUtils.fileExists(templateFilePath)) {
templateFilePath = (String) config.get("FILELIBRARY") + fs + dbName + fs + "templates_en_US.xml";
}
File configFile = new File(templateFilePath);
XMLUtils xml = new XMLUtils(configFile);
Element mappings = xml.getFirstChild("mappings");
// Construct the subject
Template messageSubject = new Template();
messageSubject.setText(
XMLUtils.getNodeText(
XMLUtils.getElement(
mappings, "map", "id", "report.email.subject")));
String subject = messageSubject.getParsedText();
message.setSubject(subject);
// Construct the body
Template messageBody = new Template();
messageBody.setText(
XMLUtils.getNodeText(
XMLUtils.getElement(
mappings, "map", "id", "report.alert.email.body")));
String body = messageBody.getParsedText();
switch (thisQueue.getOutputTypeConstant()) {
case ReportQueue.REPORT_TYPE_HTML:
// Just place the HTML in the email body, not as an
// attachment...
message.setBody(body + StringUtils.loadText(destDir + filename));
break;
case ReportQueue.REPORT_TYPE_CSV:
// Attach the CSV
message.setBody(body);
message.addFileAttachment(destDir + filename, filename + ".csv");
break;
case ReportQueue.REPORT_TYPE_PDF:
//Attach the PDF
message.setBody(body);
message.addFileAttachment(destDir + filename, filename + ".pdf");
break;
case ReportQueue.REPORT_TYPE_EXCEL:
//Attach the PDF
message.setBody(body);
message.addFileAttachment(destDir + filename, filename + ".xls");
break;
}
message.send();
}
} catch (Exception e) {
thisQueue.setStatus(ReportQueue.STATUS_ERROR);
e.printStackTrace(System.out);
} finally {
thisQueue.updateStatus(db);
}
}
}
}
/**
* Description of the Method
*
* @param thisQueue Description of the Parameter
* @param db Description of the Parameter
* @param path Description of the Parameter
* @param destFilename Description of the Parameter
* @param localizationPrefs Description of the Parameter
* @param scriptdb Description of the Parameter
* @param fontPath Description of the Parameter
* @return Description of the Return Value
* @throws Exception Description of the Exception
*/
private static long processReport(ReportQueue thisQueue, Connection db, Connection scriptdb, String path, String destFilename, String fontPath, Map localizationPrefs) throws Exception {
Report thisReport = new Report(db, thisQueue.getReportId());
//Determine the path and load JasperReport
JasperReport jasperReport = JasperReportUtils.getReport(
path + thisReport.getFilename());
//Populate the criteria
QueueCriteriaList criteria = new QueueCriteriaList();
criteria.setQueueId(thisQueue.getId());
criteria.buildList(db);
Map parameters = criteria.getParameters(jasperReport, path);
parameters.put(CENTRIC_DICTIONARY, localizationPrefs);
parameters.put(SCRIPT_DB_CONNECTION, scriptdb);
parameters.put(REPORT_OUTPUT_TYPE, thisQueue.getOutputTypeConstant());
if (parameters.containsKey("configure_hierarchy_list")) {
configureHierarchyList(db, parameters);
}
//Modify pdf font and encoding properties of all text fields if not default language
String language = (String) parameters.get("language") + "_" + (String) parameters.get(
"country");
JasperReportUtils.modifyFontProperties(
jasperReport, path, fontPath, language);
//Export the pdf to fileLibrary for this site
/*
* JasperRunManager.runReportToPdfFile(
* path +
* thisReport.getFilename().substring(0, thisReport.getFilename().lastIndexOf(".xml")) + ".jasper",
* destFilename,
* parameters, db);
*/
if (thisQueue.getOutputTypeConstant() == ReportQueue.REPORT_TYPE_CSV ||
thisQueue.getOutputTypeConstant() == ReportQueue.REPORT_TYPE_EXCEL ||
thisQueue.getOutputTypeConstant() == ReportQueue.REPORT_TYPE_HTML) {
//disable paged output if csv or excel format
parameters.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
}
JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, db);
File reportFile = new File(destFilename);
switch (thisQueue.getOutputTypeConstant()) {
case ReportQueue.REPORT_TYPE_HTML:
JRHtmlExporter exporterHTML = new JRHtmlExporter();
exporterHTML.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporterHTML.setParameter(JRExporterParameter.OUTPUT_FILE, reportFile);
exporterHTML.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporterHTML.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
exporterHTML.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporterHTML.exportReport();
break;
case ReportQueue.REPORT_TYPE_CSV:
JRCsvExporter exporterCSV = new JRCsvExporter();
exporterCSV.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporterCSV.setParameter(JRExporterParameter.OUTPUT_FILE, reportFile);
exporterCSV.exportReport();
break;
case ReportQueue.REPORT_TYPE_EXCEL:
JRXlsExporter exporterXls = new JRXlsExporter();
exporterXls.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporterXls.setParameter(JRExporterParameter.OUTPUT_FILE, reportFile);
exporterXls.exportReport();
break;
default:
byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, parameters, db);
if (reportFile.exists()) {
return reportFile.length();
}
FileOutputStream destination = new FileOutputStream(reportFile);
destination.write(bytes, 0, bytes.length);
break;
}
//clean up
if (parameters.containsKey("configure_hierarchy_list")) {
removeHierarchyList(db, parameters);
}
//Determine the size
if (reportFile.exists()) {
return reportFile.length();
} else {
return -1;
}
}
/**
* Description of the Method
*
* @param db Description of the Parameter
* @param parameters Description of the Parameter
* @throws SQLException Description of the Exception
*/
private static void configureHierarchyList(Connection db, Map parameters) throws SQLException {
if (System.getProperty("DEBUG") != null) {
System.out.println("ProcessJasperReports-> configureHierarchyList: temp table");
}
StringBuffer sql = new StringBuffer();
int typeId = DatabaseUtils.getType(db);
if (typeId == DatabaseUtils.POSTGRESQL) {
sql.append(
"CREATE TEMPORARY TABLE search_order (" +
" id INT, " +
" user_id INT " +
")");
} else if (typeId == DatabaseUtils.DB2) {
sql.append(
"DECLARE GLOBAL TEMPORARY TABLE search_order (" +
" id INT, " +
" user_id INT " +
")" +
"ON COMMIT PRESERVE ROWS NOT LOGGED");
} else if (typeId == DatabaseUtils.MSSQL) {
sql.append(
"CREATE TABLE #search_order (" +
" id INT, " +
" user_id INT " +
")");
} else {
throw new SQLException("Database Support Missing for Report");
}
PreparedStatement pst = db.prepareStatement(sql.toString());
pst.execute();
sql = new StringBuffer();
sql.append(
"INSERT INTO ").append(
DatabaseUtils.getTempTableName(db, "search_order")).append(
" (id, user_id) VALUES (?, ?)");
pst = db.prepareStatement(sql.toString());
int counter = 0;
String userIdRange = (String) parameters.get("userid_range");
if (userIdRange != null) {
StringTokenizer st =
new StringTokenizer(userIdRange, ",");
while (st.hasMoreTokens()) {
String userId = st.nextToken().trim();
pst.setInt(1, ++counter);
pst.setInt(2, Integer.parseInt(userId));
pst.execute();
}
}
pst.close();
}
/**
* Description of the Method
*
* @param db Description of the Parameter
* @param parameters Description of the Parameter
* @throws SQLException Description of the Exception
*/
private static void removeHierarchyList(Connection db, Map parameters) throws SQLException {
PreparedStatement pst = db.prepareStatement(
"DROP TABLE " + DatabaseUtils.getTempTableName(db, "search_order"));
pst.execute();
pst.close();
}
}
|
PHP
|
UTF-8
| 1,055 | 2.8125 | 3 |
[] |
no_license
|
<?php
namespace model;
class Flickr{
private $apiKey = \Settings::FLICKR_KEY;
private $apiEntryPoint = \Settings::FLICKR_ENTRY_POINT;
private $apiUrl;
public function __construct($tag){
$this->apiUrl = $this->apiEntryPoint . $this->apiKey . "&tags=" . $tag . "&sort=interestingness-desc&per_page=20&page=1&format=json&nojsoncallback=1";
}
public function getResponse(){
return json_decode(file_get_contents($this->apiUrl), true);
}
public function getPhotoArray($response){
return $response["photos"]["photo"];
}
public function buildPhotoUrls($photoArray){
$photoUrls = Array();
foreach ($photoArray as $photo) {
$farm = $photo["farm"];
$server = $photo["server"];
$id = $photo["id"];
$secret = $photo["secret"];
$photoUrl = 'http://farm' . $farm . '.staticflickr.com/' . $server . '/' . $id . '_' . $secret . '_n.jpg';
array_push($photoUrls, $photoUrl);
}
return $photoUrls;
}
}
|
Java
|
UTF-8
| 362 | 1.671875 | 2 |
[] |
no_license
|
package com.api;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 一般存储在数据库
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ApiConfig {
private String apiKey;
private String serviceUrl;
private String partnerId;
private String shopId;
}
|
C++
|
UTF-8
| 14,045 | 2.96875 | 3 |
[] |
no_license
|
#include<fstream.h>
#include<conio.h>
#include<stdio.h>
#include<String.h>
class tollcal
{
int tno;
char ttype[20];
int ttotal;
public:
void getdata1();
void putdata1();
void caltoll();
int gettno();
};
class tollmem
{
int tno;
char tname[20];
int age;
public:
void getdata2();
void putdata2();
int gettno();
};
class vehdet
{
int vno;
char vname[20];
char vtype[20];
public:
void getdata3();
void putdata3();
int getvno();
};
class DAILYUSER
{
int uno;
char uname[20];
int vno;
public:
void GetD4();
void PutD4();
int Getuno();
};
class TAXDEPO
{
int txno;
char clname[20];
int totax;
public:
void GetD5();
void PutD5();
int Getcno();
};
void tollcal::getdata1()
{
cout<<"Enter toll no "<<endl;
cin>>tno;
cout<<"Enter toll type(Heavyvehicle,Cars,TwoWh) "<<endl;
gets(ttype);
}
void tollcal:: putdata1()
{
cout<<endl<<tno<<endl<<ttype<<endl<<ttotal<<endl;
}
int tollcal::gettno()
{
return(tno);
}
void tollcal::caltoll()
{
if(strcmp(ttype,"Heavyvehicle")==0)
ttotal=45;
else if(strcmp(ttype,"Cars")==0)
ttotal=30;
else if(strcmp(ttype,"TwoWh")==0)
ttotal=15;
}
void tollmem::getdata2()
{
cout<<"Enter toll member's name "<<endl;
gets(tname);
cout<<"Enter toll member's no "<<endl;
cin>>tno;
cout<<"Enter toll member's age "<<endl;
cin>>age;
}
void tollmem:: putdata2()
{
cout<<tno<<" "<<tname<<" "<<age<<endl;
}
int tollmem::gettno()
{
return(tno);
}
void vehdet::getdata3()
{
cout<<"Enter vehicle's name"<<endl;
gets(vname);
cout<<"Enter vehicle's no"<<endl;
cin>>vno;
cout<<"Enter vehicle's type(Heavyvehicle,Cars,TwoWh)"<<endl;
gets(vtype);
}
void vehdet:: putdata3()
{
cout<<vno<<" "<<vname<<" "<<vtype<<endl;
}
int vehdet::getvno()
{
return(vno);
}
void DAILYUSER:: GetD4()
{
cout<<"Enter the user no "<<endl;
cin>>uno;
cout<<"Enter user name"<<endl;
gets(uname);
cout<<"Enter Vech. No"<<endl;
cin>>vno;
}
void DAILYUSER:: PutD4()
{ cout<<uno<<"\t"<<uname<<"\t"<<vno<<"\t"<<endl;
}
int DAILYUSER:: Getuno()
{
return(uno);
}
void TAXDEPO:: GetD5()
{
cout<<"Enter the tax deposition reciept no."<<endl;
cin>>txno;
cout<<"Enter collecter officer name"<<endl;
gets(clname);
cout<<"Enter total tax collected"<<endl;
cin>>totax;
}
void TAXDEPO:: PutD5()
{
cout<<txno<<"\t"<<clname<<"\t"<<totax<<"\t"<<endl;
}
int TAXDEPO:: Getcno()
{
return(txno);
}
tollcal t;
tollmem m;
vehdet v;
DAILYUSER B;
TAXDEPO k;
void main3()
{
clrscr();
void enter_file1();
void display_file1();
void search1();
void modify1();
void Delete1();
int c;
do
{
cout<<"Main menu"<<endl;
cout<<"1.Add toll's record"<<endl;
cout<<"2.Display toll's record"<<endl;
cout<<"3.Search"<<endl;
cout<<"4.Modify"<<endl;
cout<<"5.Delete"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your choice ";
cin>>c;
switch(c)
{
case 1:enter_file1();
break;
case 2: display_file1();
break;
case 3:search1();
break;
case 4:modify1();
break;
case 5:Delete1();
break;
}
}while(c!=6);
getche();
}
void main1()
{
clrscr();
void enter_file2();
void display_file2();
void search2();
void modify2();
void Delete2();
int c;
do
{
cout<<"Main menu"<<endl;
cout<<"1.Add toll member's record"<<endl;
cout<<"2.Display toll member's record"<<endl;
cout<<"3.Search"<<endl;
cout<<"4.Modify"<<endl;
cout<<"5.Delete"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your choice "<<endl;
cin>>c;
switch(c)
{
case 1:enter_file2();
break;
case 2: display_file2();
break;
case 3:search2();
break;
case 4:modify2();
break;
case 5:Delete2();
break;
}
}while(c!=6);
getche();
}
void main2()
{
clrscr();
void enter_file3();
void display_file3();
void search3();
void modify3();
void Delete3();
int c;
do
{
cout<<"Mainmenu"<<endl;
cout<<"1.Add vehicle's record"<<endl;
cout<<"2.Display vehicle's record"<<endl;
cout<<"3.Search"<<endl;
cout<<"4.Modify"<<endl;
cout<<"5.Delete"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your choice "<<endl;
cin>>c;
switch(c)
{
case 1:enter_file3();
break;
case 2: display_file3();
break;
case 3:search3();
break;
case 4:modify3();
break;
case 5:Delete3();
break;
}
}while(c!=6);
getche();
}
void main4()
{
clrscr();
void enterdet4();
void displaydet4();
void searchdet4();
void modifydet4();
void deletedet4();
int c;
do
{
cout<<"\n Main menu "<<endl;
cout<<"1. Enter the details of daily users"<<endl;
cout<<"2. Display details of daily users "<<endl;
cout<<"3. Search a daily user by its pass no "<<endl;
cout<<"4. Modify user details "<<endl;
cout<<"5. Delete user details "<<endl;
cout<<"6.Exit "<<endl;
cout<<"Enter your choice"<<" ";
cin>>c;
switch(c)
{
case 1: enterdet4();
break;
case 2: displaydet4();
break;
case 3: searchdet4();
break;
case 4: modifydet4();
break;
case 5: deletedet4();
break;
}
}while(c!=6);
getche();
}
void main5()
{
clrscr();
void enterdet5();
void displaydet5();
void searchdet5();
void modifydet5();
void deletedet5();
int c;
do
{
cout<<"\n Main menu "<<endl;
cout<<"1. Enter the details of tax deposition"<<endl;
cout<<"2. Display details of tax deposition "<<endl;
cout<<"3. Search tax deposition by tax nO. "<<endl;
cout<<"4. Modify deposition details "<<endl;
cout<<"5. Delete deposition details "<<endl;
cout<<"6.exit "<<endl;
cout<<"Enter your choice"<<" ";
cin>>c;
switch(c)
{
case 1: enterdet5();
break ;
case 2: displaydet5();
break ;
case 3: searchdet5();
break ;
case 4: modifydet5();
break ;
case 5: deletedet5();
break ;
}
}while(c!=6);
getche();
}
void main()
{
int choic;
do
{
cout<<"Main Menu "<<endl;
cout<<"1 Toll Worker Credentials "<<endl;
cout<<"2 Vehicle Details "<<endl;
cout<<"3 Toll Calculation "<<endl;
cout<<"4 DailyUser details "<<endl;
cout<<"5 Tax Deposition "<<endl;
cout<<"6 Exit "<<endl;
cout<<"Enter your choice "<<endl;
cin>>choic;
switch(choic)
{
case 1:
main1();
break;
case 2:
main2();
break;
case 3:
main3();
break;
case 4:
main4();
break;
case 5:
main5();
break;
}
}while(choic!=6);
getche();
}
void enter_file1()
{
ofstream afile("tcal.dat",ios::binary||ios::app);
t.getdata1();
t.caltoll();
afile.write((char*)&t,sizeof(t));
afile.close();
cout<<endl;
getche();
}
void display_file1()
{
ifstream bfile("tcal.dat",ios::binary);
while(bfile.read((char*)&t,sizeof(t)))
{
t.putdata1();
}
bfile.close();
cout<<endl;
getche();
}
void search1()
{
int p=-1,z;
ifstream cfile("tcal.dat",ios::binary);
cout<<"Please enter toll's no to be searched "<<endl;
cin>>z;
while(cfile.read((char*)&t,sizeof (t)))
{
if(t.gettno()==z)
{
t.putdata1();
p++;
}
}
if(p==-1)
cout<<"Sorry! record not found "<<endl;
cout<<endl;
cfile.close();
getche();
}
void modify1()
{
int l,a,q=-1;
cout<<"Please enter the toll's no whose record to be modify "<<endl;
cin>>l;
fstream dfile("tcal.dat",ios::in|ios::out);
while(dfile.read((char*)&t,sizeof(t)))
{
a++;
if(t.gettno()==l)
{
t.getdata1();
dfile.seekp((a-1)*sizeof(t),ios::beg);
dfile.write((char*)&t,sizeof(t));
q++;
}
}
if(q==-1)
cout<<"Sorry!record not found "<<endl;
dfile.close();
getche();
}
void Delete1()
{
int b;
ifstream efile("tcal.dat",ios::binary||ios::in);
ofstream ffile("temp.dat",ios::binary||ios::out);
cout<<"Please enter the toll's no to be deleted "<<endl;
cin>>b;
while(efile.read((char*)&t,sizeof(t)))
{
if(t.gettno()!=b)
{
ffile.write((char*)&t,sizeof (t));
}
}
remove("tcal.dat");
rename("temp.dat","tcal.dat");
efile.close();
ffile.close();
cout<<endl;
getche();
}
void enter_file2()
{
ofstream afile("tmem.dat",ios::binary,ios::app);
m.getdata2();
afile.write((char*)&m,sizeof(m));
afile.close();
cout<<endl;
getche();
}
void display_file2()
{
ifstream bfile("tmem.dat",ios::binary);
while(bfile.read((char*)&m,sizeof(m)))
{
m.putdata2();
}
bfile.close();
cout<<endl;
getche();
}
void search2()
{
int p=-1,z;
ifstream cfile("tmem.dat",ios::binary);
cout<<"Please enter toll member's no to be searched"<<endl;
cin>>z;
while(cfile.read((char*)&m,sizeof(m)))
{
if(m.gettno()==z)
{
m.putdata2();
p++;
}
}
if(p==-1)
cout<<"Sorry! record not found"<<endl;
cout<<endl;
cfile.close();
getche();
}
void modify2()
{
int l,a,q=-1;
cout<<"Please enter the toll member's no take modify"<<endl;
cin>>l;
fstream dfile("tmem.dat",ios::in|ios::out|ios::binary);
while(dfile.read((char*)&m,sizeof(m)))
{
a++;
if(m.gettno()==l)
{
m.getdata2();
dfile.seekp((a-1)*sizeof(m),ios::beg);
dfile.write((char*)&m,sizeof(m));
q++;
}
if(q==-1)
cout<<"Sorry! record not found"<<endl;
dfile.close();
getche();
}
}
void Delete2()
{
int b;
ifstream efile("tmem.dat",ios::binary);
ofstream ffile("temp.dat",ios::binary);
cout<<"Please enter the toll member's no to be deleted"<<endl;
cin>>b;
while(efile.read((char*)&m,sizeof(m)))
{
if(m.gettno()!=b)
{
ffile.write((char*)&m,sizeof(m));
}
}
remove("tmem.dat");
rename("temp.dat","tmem.dat");
efile.close();
ffile.close();
cout<<endl;
getche();
}
void enter_file3()
{
ofstream afile("veh.dat",ios::binary,ios::app|ios::out);
v.getdata3();
afile.write((char*)&v,sizeof(v));
afile.close();
cout<<endl;
getche();
}
void display_file3()
{
ifstream bfile("veh.dat",ios::binary|ios::in);
while(bfile.read((char*)&v,sizeof (v)))
{
v.putdata3();
}
bfile.close();
cout<<endl;
getche();
}
void search3()
{
int p=-1,z;
ifstream cfile("veh.dat",ios::binary);
cout<<"Please enter vehicle's no to be searched"<<endl;
cin>>z;
while(cfile.read((char*)&v,sizeof (v)))
{
if(v.getvno()==z)
{
v.putdata3();
p++;
}
}
if(p==-1)
cout<<"Sorry! record not found"<<endl;
cout<<endl;
cfile.close();
getche();
}
void modify3()
{
int l,a,q=-1;
cout<<"Please enter the vehicle's no take modify"<<endl;
cin>>l;
fstream dfile("veh.dat",ios::in|ios::out);
while(dfile.read((char*)&v,sizeof(v)))
{
a++;
if(v.getvno()==l)
{
v.getdata3();
dfile.seekp((a-1)*sizeof (v),ios::beg);
dfile.write((char*)&v,sizeof (v));
q++;
}
if(q==-1)
cout<<"Sorry! record not found"<<endl;
dfile.close();
getche();
}
}
void Delete3()
{
int b;
ifstream efile("veh.dat",ios::binary);
ofstream ffile("temp.dat",ios::binary);
cout<<"please enter the vehicle's no to be deleted"<<endl;
cin>>b;
while(efile.read((char*)&v,sizeof(v)))
{
if(v.getvno()!=b)
{
ffile.write((char*)&v,sizeof(v));
}
}
remove("veh.dat");
rename("temp.dat","veh.dat");
efile.close();
ffile.close();
cout<<endl;
getche();
}
void enterdet4()
{
ofstream afile("Dusr.dat",ios::binary|ios::app);
B.GetD4();
afile.write((char*)& B, sizeof(B));
afile.close();
cout<<endl;
getche();
}
void displaydet4()
{
ifstream bfile("dusr.dat",ios::binary);
while(bfile.read((char*)& B, sizeof(B)))
{
B.PutD4();
}
bfile.close();
cout<<endl;
getche();
}
void searchdet4()
{
int p=-1,z;
ifstream cfile("dusr.dat",ios::binary);
cout<<"Please enter user pass no to be searched:\n";
cin>>z;
while(cfile.read((char*)& B,sizeof(B)))
{
if(B.Getuno()==z)
B.PutD4();
p++;
}
if(p==-1)
cout<<"Sorry! record not found\n";
cout<<endl;
cfile.close();
getche();
}
void modifydet4()
{
int g=-1,a=0,t;
cout<<"Please enter the user pass no to be modified:\n";
cin>>t;
fstream dfile("dusr.dat",ios::in|ios::binary|ios::out );
while(dfile.read((char*)& B,sizeof(B)))
{
a++;
if(B.Getuno()==t)
{
B.GetD4();
dfile.seekp((a-1)*sizeof(B),ios::beg);
dfile.write((char*)& B, sizeof(B));
g++;
}
}
if(g==-1)
cout<<"Sorry! record not found\n";
dfile.close();
getche();
}
void deletedet4()
{
int b;
ifstream efile("dusr.dat",ios::binary);
ofstream ffile("dusr1.dat",ios::binary);
cout<<"Please enter the user pass to be deleted\n";
cin>>b;
while(efile.read((char*)& B,sizeof(B)))
{
if(B.Getuno()!=b)
{
ffile.write((char*)& B,sizeof(B));
}
}
remove("dusr.dat");
rename("dusr1.dat","dusr.dat");
efile.close();
ffile.close();
cout<<endl;
getche();
}
void enterdet5()
{
ofstream afile("tdpo.dat",ios::binary|ios::app);
k.GetD5();
afile.write((char*)& k, sizeof(k));
afile.close();
cout<<endl;
getche();
}
void displaydet5()
{
ifstream Bfile("tdpo.dat",ios::binary);
while(Bfile.read((char*)& k, sizeof(k)))
{
k.PutD5();
}
Bfile.close();
cout<<endl;
getche();
}
void searchdet5()
{
int p=-1,z;
ifstream cfile("tdpo.dat",ios::binary);
cout<<"Please enter tax reciept no whose tax need to be searched:\n";
cin>>z;
while(cfile.read((char*)& k,sizeof(k)))
{
if(k.Getcno()==z)
{
k.PutD5();
p++;
}
}
if(p==-1)
cout<<"Sorry! record not found\n";
cout<<endl;
cfile.close();
getche();
}
void modifydet5()
{
int g=-1,a=0,t;
cout<<"Please enter the tax reciept no whose record need to Be modified:\n";
cin>>t;
fstream dfile("tdpo.dat",ios::in|ios::binary|ios::out );
while(dfile.read((char*)&k,sizeof(k)))
{
a++;
if(k.Getcno()==t)
{
k.GetD5();
dfile.seekp((a-1)*sizeof(k),ios::beg);
dfile.write((char*)&k,sizeof(k));
g++;
}
}
if(g==-1)
cout<<"Sorry! record not found\n";
dfile.close();
getche();
}
void deletedet5()
{
int B;
ifstream efile("tdpo.dat",ios::binary);
ofstream ffile("tdpo1.dat",ios::binary);
cout<<"Please enter the tax reciept no. whose record need to Be deleted\n";
cin>>B;
while(efile.read((char*)& k,sizeof(k)))
{
if(k.Getcno()!=B)
{
ffile.write((char*)& k,sizeof(k));
}
}
remove("tdpo.dat");
rename("tdpo1.dat","tdpo.dat");
efile.close();
ffile.close();
cout<<endl;
getche();
}
|
Go
|
UTF-8
| 3,730 | 2.8125 | 3 |
[] |
no_license
|
package shader
import (
"errors"
"fmt"
"math"
"strings"
"github.com/go-gl/gl/v3.3-core/gl"
"github.com/go-gl/mathgl/mgl32"
)
func DefaultShader() (*Program, error) {
program, err := NewProgram(DefaultVertexShader, DefaultFragmentShader)
return program, err
}
type Program struct {
ID uint32
}
func (p *Program) Use() {
gl.UseProgram(p.ID)
}
func (p *Program) AttributeLocation(name string) uint32 {
return uint32(gl.GetAttribLocation(p.ID, gl.Str(name+"\x00")))
}
func (p *Program) UniformLocation(name string) int32 {
return int32(gl.GetUniformLocation(p.ID, gl.Str(name+"\x00")))
}
func NewProgram(vertexShaderSource, fragmentShaderSource string) (*Program, error) {
p := &Program{}
vertexShader, err := compileShader(vertexShaderSource, gl.VERTEX_SHADER)
if err != nil {
return p, err
}
fragmentShader, err := compileShader(fragmentShaderSource, gl.FRAGMENT_SHADER)
if err != nil {
return p, err
}
program := gl.CreateProgram()
gl.AttachShader(program, vertexShader)
gl.AttachShader(program, fragmentShader)
gl.LinkProgram(program)
var status int32
gl.GetProgramiv(program, gl.LINK_STATUS, &status)
if status == gl.FALSE {
var logLength int32
gl.GetProgramiv(program, gl.INFO_LOG_LENGTH, &logLength)
log := strings.Repeat("\x00", int(logLength+1))
gl.GetProgramInfoLog(program, logLength, nil, gl.Str(log))
return p, errors.New(fmt.Sprintf("failed to link program: %v", log))
}
gl.DeleteShader(vertexShader)
gl.DeleteShader(fragmentShader)
p.ID = program
return p, nil
}
func compileShader(source string, shaderType uint32) (uint32, error) {
shader := gl.CreateShader(shaderType)
csource := gl.Str(source)
gl.ShaderSource(shader, 1, &csource, nil)
gl.CompileShader(shader)
var status int32
gl.GetShaderiv(shader, gl.COMPILE_STATUS, &status)
if status == gl.FALSE {
var logLength int32
gl.GetShaderiv(shader, gl.INFO_LOG_LENGTH, &logLength)
log := strings.Repeat("\x00", int(logLength+1))
gl.GetShaderInfoLog(shader, logLength, nil, gl.Str(log))
return 0, fmt.Errorf("failed to compile %v: %v", source, log)
}
return shader, nil
}
func SetupPerspective(width, height int, program *Program) {
program.Use()
fov := float32(60.0)
eyeX := float32(width) / 2.0
eyeY := float32(height) / 2.0
ratio := float32(width) / float32(height)
halfFov := (math.Pi * fov) / 360.0
theTan := math.Tan(float64(halfFov))
dist := eyeY / float32(theTan)
nearDist := dist / 10.0
farDist := dist * 10.0
projection := mgl32.Perspective(mgl32.DegToRad(fov), ratio, nearDist, farDist)
projectionUniform := program.UniformLocation("projection")
gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0])
camera := mgl32.LookAtV(mgl32.Vec3{eyeX, eyeY, dist}, mgl32.Vec3{eyeX, eyeY, 0}, mgl32.Vec3{0, 1, 0})
cameraUniform := program.UniformLocation("camera")
gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0])
//model := mgl32.Ident4()
//modelUniform := program.UniformLocation("model")
//gl.UniformMatrix4fv(modelUniform, 1, false, &model[0])
textureUniform := program.UniformLocation("tex")
gl.Uniform1i(textureUniform, 0)
gl.BindFragDataLocation(program.ID, 0, gl.Str("outputColor\x00"))
gl.Viewport(0, 0, int32(width), int32(height))
}
var DefaultVertexShader string = `
#version 330
uniform mat4 projection;
uniform mat4 camera;
uniform mat4 model;
in vec3 vert;
in vec2 vertTexCoord;
out vec2 fragTexCoord;
void main() {
fragTexCoord = vertTexCoord;
gl_Position = projection * camera * model * vec4(vert, 1);
}
` + "\x00"
var DefaultFragmentShader = `
#version 330
uniform sampler2D tex;
in vec2 fragTexCoord;
out vec4 outputColor;
void main() {
outputColor = texture(tex, fragTexCoord);
}
` + "\x00"
|
Java
|
UTF-8
| 785 | 3.140625 | 3 |
[] |
no_license
|
package com.test.modernization.Demo;
import static org.junit.Assert.*;
import org.junit.Test;
public class IterationTest {
@Test
public void test() {
//Test Multiply function
Iteration obj = new Iteration();
//Test for two positive numbers
assertEquals(10, obj.multiply(2, 5));
//Test for two negative numbers
assertEquals(10, obj.multiply(-2, -5));
//Test for one positive and one negative number
assertEquals(-10, obj.multiply(-2, 5));
//Test Addition function
//Test for two positive numbers
assertEquals(7, obj.addition(2, 5));
//Test for two negative numbers
assertEquals(-7, obj.addition(-2, -5));
//Test for one positive and one negative number
assertEquals(3, obj.addition(-2, 5));
}
}
|
C#
|
UTF-8
| 1,801 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace FlatRedBall.Content.AI.Pathfinding
{
#region XML Docs
/// <summary>
/// Save class for the PositionedNode class. This class is used in the
/// .nntx (Node Network XML) file type.
/// </summary>
#endregion
public class PositionedNodeSave
{
public string Name;
public float X;
public float Y;
public float Z;
[XmlElementAttribute("Link")]
public List<LinkSave> Links = new List<LinkSave>();
public static PositionedNodeSave FromPositionedNode(FlatRedBall.AI.Pathfinding.PositionedNode positionedNode)
{
PositionedNodeSave nodeSave = new PositionedNodeSave();
nodeSave.Name = positionedNode.Name;
nodeSave.X = positionedNode.Position.X;
nodeSave.Y = positionedNode.Position.Y;
nodeSave.Z = positionedNode.Position.Z;
foreach (FlatRedBall.AI.Pathfinding.Link link in positionedNode.Links)
{
nodeSave.Links.Add(
LinkSave.FromLink(link));
}
return nodeSave;
}
public FlatRedBall.AI.Pathfinding.PositionedNode ToPositionedNode()
{
FlatRedBall.AI.Pathfinding.PositionedNode positionedNode = new FlatRedBall.AI.Pathfinding.PositionedNode();
positionedNode.Name = Name;
positionedNode.Position.X = X;
positionedNode.Position.Y = Y;
positionedNode.Position.Z = Z;
// links will be established by the NodeNetworkSave.ToNodeNetwork method
// We've done all we can do here.
return positionedNode;
}
}
}
|
PHP
|
UTF-8
| 6,346 | 2.640625 | 3 |
[] |
no_license
|
<?php
namespace it\icosaedro\regex;
require_once __DIR__ . "/../../../../../stdlib/all.php";
use it\icosaedro\utils\TestUnit as TU;
use it\icosaedro\regex\Pattern;
use it\icosaedro\utils\Timer;
/*. string .*/ function test(/*. string .*/ $re, /*. string .*/ $s)
{
#echo "----\n";
$p = new Pattern($re);
if( $p->match($s) )
return $p->resultAsString(" ");
else
return NULL;
}
/*. string .*/ function getResult(/*. Pattern .*/ $p, /*. string .*/ $s){
if( $p->match($s) )
return $p->resultAsString(" ");
else
return NULL;
}
function genericTests(){
echo __FUNCTION__, "\n";
TU::test(test(".**ab", "aaaab"), '0 "aaaab"');
TU::test(test("^(a|aa|aaa|aaaa)ab", "aaaaab"), '0 "aaaaab" 0.0 "aaaa"');
TU::test(test("^a[1,9]?ab\$", "aaaaaab"), '0 "aaaaaab"');
TU::test(test("^(a[1,3]*)[1,2]*ab\$", "aaaaaab"), '0 "aaaaaab" 0.0 "aaa" 0.0 "aa"');
$p = new Pattern("^{-\\+}?*{0-9}+*\$");
TU::test(getResult($p, "0"), '0 "0"');
TU::test(getResult($p, "123"), '0 "123"');
TU::test(getResult($p, "+123"), '0 "+123"');
TU::test(getResult($p, "-123"), '0 "-123"');
TU::test(getResult($p, "-123x"), NULL);
TU::test(getResult($p, "-123x"), NULL);
TU::test(getResult($p, "x123x"), NULL);
TU::test(getResult($p, ""), NULL);
TU::test(getResult($p, " "), NULL);
# Compare greedy and reluctant:
$line = "This is a <EM>first</EM> test";
TU::test(test(".**(<.**>)", $line), '0 "This is a <EM>first</EM>" 0.0 "</EM>"');
TU::test(test(".*?(<.**>)", $line), '0 "This is a <EM>first</EM>" 0.0 "<EM>first</EM>"');
TU::test(test(".*?(<.*?>)", $line), '0 "This is a <EM>" 0.0 "<EM>"');
TU::test(test("{!<}*((<{!>}*>){!<}*)*", $line), '0 "This is a <EM>first</EM> test" 0.0 "<EM>first" 0.0.0 "<EM>" 0.0 "</EM> test" 0.0.0 "</EM>"');
TU::test(test("({!<}*)?((<{!>}*>)({!<}*))*", $line),
'0 "This is a <EM>first</EM> test" 0.0 "This is a " 0.1 "<EM>first" 0.1.0 "<EM>" 0.1.1 "first" 0.1 "</EM> test" 0.1.0 "</EM>" 0.1.1 " test"');
// 2014-01-21 Non-regression test on bug found today:
$p = new Pattern("(B|(C))*A");
$p->match("BCZ"); // should not crash
}
function testSubexpressions(){
echo __FUNCTION__, "\n";
$w = "{a-zA-Z0-9_}+";
$sp = "{ \t}*";
$re = "$sp($w)$sp(,$sp($w)$sp)*\$";
$p = new Pattern($re);
$s = " alfa , beta , gamma ";
TU::test("$p", $re);
TU::test(getResult($p, $s), '0 " alfa , beta , gamma " 0.0 "alfa" 0.1 ", beta " 0.1.0 "beta" 0.1 ", gamma " 0.1.0 "gamma"');
TU::test($p->value(), " alfa , beta , gamma ");
TU::test($p->group(0)->elem(0)->value(), "alfa");
TU::test($p->group(1)->elem(0)->value(), ", beta ");
TU::test($p->group(1)->elem(0)->group(0)->elem(0)->value(), "beta");
TU::test($p->group(1)->elem(1)->value(), ", gamma ");
TU::test($p->group(1)->elem(1)->group(0)->elem(0)->value(), "gamma");
TU::test($p->group(0)->count(), 1);
TU::test($p->group(1)->count(), 2);
TU::test($p->group(1)->elem(0)->group(0)->count(), 1);
TU::test($p->group(1)->elem(1)->group(0)->count(), 1);
$K = "{a-z}{a-zA-Z_0-9}*";
$V = "{-\\+}?{0-9}+";
$SP = "{ \t}*";
$re = "$SP($K)$SP=$SP($V)$SP(,$SP($K)$SP=$SP($V))*$SP\$";
$p = new Pattern($re);
TU::test("$p", $re);
$line = "alpha = 1, beta = 2, gamma = 3";
TU::test(getResult($p, $line), '0 "alpha = 1, beta = 2, gamma = 3" 0.0 "alpha" 0.1 "1" 0.2 ", beta = 2" 0.2.0 "beta" 0.2.1 "2" 0.2 ", gamma = 3" 0.2.0 "gamma" 0.2.1 "3"');
# Repeat latter test to check if internal stata had been properly reset:
TU::test(getResult($p, $line), '0 "alpha = 1, beta = 2, gamma = 3" 0.0 "alpha" 0.1 "1" 0.2 ", beta = 2" 0.2.0 "beta" 0.2.1 "2" 0.2 ", gamma = 3" 0.2.0 "gamma" 0.2.1 "3"');
}
function testResultAsString(){
echo __FUNCTION__, "\n";
# trim() implemented with regex:
$sp = "{ \t\n\r\0\x0b}";
$trim_regex = "$sp*(.*?)$sp*\$";
$p = new Pattern($trim_regex);
TU::test(getResult($p, ""), '0 "" 0.0 ""' );
TU::test(getResult($p, "a"), '0 "a" 0.0 "a"' );
TU::test(getResult($p, " a"), '0 " a" 0.0 "a"' );
TU::test(getResult($p, " a"), '0 " a" 0.0 "a"' );
TU::test(getResult($p, " a"), '0 " a" 0.0 "a"' );
TU::test(getResult($p, " a "), '0 " a " 0.0 "a"' );
TU::test(getResult($p, "\t a b "), '0 "\\t a b " 0.0 "a b"' );
# Counting recurrences of a given sub-string:
$sub = Pattern::escape("abc");
$p = new Pattern("(.*?$sub)*.*\$");
$p->match("");
TU::test($p->group(0)->count(), 0);
$p->match("$sub");
TU::test($p->group(0)->count(), 1);
$p->match("$sub$sub");
TU::test($p->group(0)->count(), 2);
$p->match(".");
TU::test($p->group(0)->count(), 0);
$p->match(".$sub.");
TU::test($p->group(0)->count(), 1);
$p->match(".$sub.$sub.");
TU::test($p->group(0)->count(), 2);
}
function performancesTest(){
echo __FUNCTION__, "\n";
$t = new Timer();
$subject = "+123456789";
$p = new Pattern("^{-\\+}?{0-9}+\$");
$t->reset();
$t->start();
$n = 0;
do {
for($i = 1000; $i >= 1; $i--){
if( ! $p->match($subject) )
echo "BAD Pattern\n";
$n++;
}
} while( $t->elapsedMilliseconds() < 500 );
$dt = $t->elapsedMilliseconds();
echo "Pattern class performance: ", (int) ($n * 1000 / $dt), " matches/s\n";
# ==> 7500 matches/s on my Pentium 4 at 1600 MHz
$t->reset();
$t->start();
$n = 0;
$re = "/^[-+][0-9]+\$/";
do {
for($i = 1000; $i >= 1; $i--){
if( preg_match($re, $subject) !== 1 )
echo "BAD pcre\n";
$n++;
}
} while( $t->elapsedMilliseconds() < 500 );
$dt = $t->elapsedMilliseconds();
echo "preg_match() function performance: ", (int) ($n * 1000 / $dt), " matches/s\n";
# ==> 276000 matches/s on my Pentium 4 at 1600 MHz
}
function countWords(){
echo __FUNCTION__, "\n";
$p = new Pattern("(.*?({a-zA-Z}+))*");
$p->match("");
TU::test($p->group(0)->count(), 0);
$p->match(" ");
TU::test($p->group(0)->count(), 0);
$p->match("Counting words, every word being a sequence of latin letters.");
TU::test($p->group(0)->count(), 10);
$words = /*. (string[int]) .*/ array();
for($i = 0; $i < $p->group(0)->count(); $i++)
$words[] = $p->group(0)->elem($i)->group(0)->elem(0)->value();
TU::test($words, array("Counting", "words", "every", "word", "being", "a",
"sequence", "of", "latin", "letters"));
}
class TestPattern extends TU {
public /*. void .*/ function run(){
genericTests();
testSubexpressions();
performancesTest();
testResultAsString();
countWords();
}
}
$tu = new TestPattern();
$tu->start();
|
Java
|
UTF-8
| 11,379 | 1.671875 | 2 |
[] |
no_license
|
package cn.paulpaulzhang.fair.sc.main.user.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.google.android.material.appbar.MaterialToolbar;
import com.gyf.immersionbar.ImmersionBar;
import com.zhihu.matisse.Matisse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import cn.paulpaulzhang.fair.activities.FairActivity;
import cn.paulpaulzhang.fair.constant.Api;
import cn.paulpaulzhang.fair.constant.Constant;
import cn.paulpaulzhang.fair.constant.UserConfigs;
import cn.paulpaulzhang.fair.net.RestClient;
import cn.paulpaulzhang.fair.net.callback.ISuccess;
import cn.paulpaulzhang.fair.sc.R;
import cn.paulpaulzhang.fair.sc.R2;
import cn.paulpaulzhang.fair.sc.database.Entity.LikeCache;
import cn.paulpaulzhang.fair.sc.database.Entity.LikeCache_;
import cn.paulpaulzhang.fair.sc.database.Entity.PostCache;
import cn.paulpaulzhang.fair.sc.database.Entity.PostCache_;
import cn.paulpaulzhang.fair.sc.database.Entity.UserCache;
import cn.paulpaulzhang.fair.sc.database.JsonParseUtil;
import cn.paulpaulzhang.fair.sc.database.ObjectBox;
import cn.paulpaulzhang.fair.sc.main.common.FeaturesUtil;
import cn.paulpaulzhang.fair.sc.main.common.PostAdapter;
import cn.paulpaulzhang.fair.sc.main.common.PostCommentUtil;
import cn.paulpaulzhang.fair.sc.main.common.PostItem;
import cn.paulpaulzhang.fair.sc.main.common.PostShareUtil;
import cn.paulpaulzhang.fair.sc.main.post.activity.ArticleActivity;
import cn.paulpaulzhang.fair.sc.main.post.activity.DynamicActivity;
import cn.paulpaulzhang.fair.util.storage.FairPreference;
import es.dmoral.toasty.Toasty;
import io.objectbox.Box;
/**
* 包名:cn.paulpaulzhang.fair.sc.main.user.activity
* 创建时间:9/21/19
* 创建人: paulpaulzhang
* 描述:
*/
public class LikeActivity extends FairActivity {
@BindView(R2.id.toolbar)
MaterialToolbar mToolbar;
@BindView(R2.id.srl_like)
SwipeRefreshLayout mSwipeRefresh;
@BindView(R2.id.rv_like)
RecyclerView mRecyclerView;
private PostAdapter mAdapter;
private long uid;
@Override
public int setLayout() {
return R.layout.activity_like;
}
@Override
public void init(@Nullable Bundle savedInstanceState) {
initToolbar(mToolbar, getString(R.string.my_like));
ImmersionBar.with(this).fitsSystemWindows(true).statusBarDarkFont(true).init();
uid = FairPreference.getCustomAppProfileL(UserConfigs.CURRENT_USER_ID.name());
Box<PostCache> postCacheBox = ObjectBox.get().boxFor(PostCache.class);
Box<UserCache> userCacheBox = ObjectBox.get().boxFor(UserCache.class);
Box<LikeCache> likeCacheBox = ObjectBox.get().boxFor(LikeCache.class);
postCacheBox.removeAll();
userCacheBox.removeAll();
likeCacheBox.removeAll();
initRecyclerView();
initSwipeRefresh();
mSwipeRefresh.setRefreshing(true);
loadData(Constant.REFRESH_DATA);
}
private void initSwipeRefresh() {
mSwipeRefresh.setColorSchemeResources(R.color.colorAccent,
android.R.color.holo_green_light);
mSwipeRefresh.setOnRefreshListener(() -> loadData(Constant.REFRESH_DATA));
}
private void initRecyclerView() {
mAdapter = new PostAdapter(new ArrayList<>());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mAdapter.setLoadMoreView(new SimpleLoadMoreView());
mAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
mAdapter.setPreLoadNumber(3);
mAdapter.setOnLoadMoreListener(() -> loadData(Constant.LOAD_MORE_DATA), mRecyclerView);
mAdapter.setOnItemClickListener((adapter, view, position) -> {
PostItem item = (PostItem) adapter.getItem(position);
if (item != null) {
if (item.getItemType() == PostItem.DYNAMIC) {
Intent intent = new Intent(this, DynamicActivity.class);
intent.putExtra("pid", item.getPostCache().getId());
intent.putExtra("uid", item.getPostCache().getUid());
intent.putExtra("isLike", item.isLike());
startActivity(intent);
} else {
Intent intent = new Intent(this, ArticleActivity.class);
intent.putExtra("pid", item.getPostCache().getId());
intent.putExtra("uid", item.getPostCache().getUid());
intent.putExtra("isLike", item.isLike());
startActivity(intent);
}
}
});
mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
PostItem item = (PostItem) adapter.getItem(position);
if (item == null) {
return;
}
if (view.getId() == R.id.ll_comment_dynamic || view.getId() == R.id.ll_comment_article) {
if (item.getPostCache().getCommentCount() == 0) {
PostCommentUtil.INSTANCE().comment(item.getPostCache().getId(), this, this, null);
FeaturesUtil.update(item.getPostCache().getId());
} else {
if (item.getItemType() == PostItem.DYNAMIC) {
Intent intent = new Intent(this, DynamicActivity.class);
intent.putExtra("pid", item.getPostCache().getId());
intent.putExtra("uid", item.getPostCache().getUid());
intent.putExtra("fold", true);
intent.putExtra("isLike", item.isLike());
startActivity(intent);
} else {
Intent intent = new Intent(this, ArticleActivity.class);
intent.putExtra("pid", item.getPostCache().getId());
intent.putExtra("uid", item.getPostCache().getUid());
intent.putExtra("fold", true);
intent.putExtra("isLike", item.isLike());
startActivity(intent);
}
}
} else if (view.getId() == R.id.ll_share_dynamic || view.getId() == R.id.ll_share_article) {
PostShareUtil
.INSTANCE()
.share(this,this, adapter.getViewByPosition(position, R.id.card_content), 400);
FeaturesUtil.update(item.getPostCache().getId());
RestClient.builder()
.url(Api.SHARE_POST)
.params("uid", FairPreference.getCustomAppProfileL(UserConfigs.CURRENT_USER_ID.name()))
.params("pid", item.getPostCache().getId())
.build()
.post();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQUEST_CODE_CHOOSE && resultCode == RESULT_OK && data != null) {
PostCommentUtil.INSTANCE().compressPhoto(Matisse.obtainResult(data).get(0), this, this);
}
}
private int page = 1;
public void loadData(int type) {
Box<PostCache> postBox = ObjectBox.get().boxFor(PostCache.class);
Box<LikeCache> likeBox = ObjectBox.get().boxFor(LikeCache.class);
if (type == Constant.REFRESH_DATA) {
requestData(1, Constant.REFRESH_DATA, response -> {
page = 1;
JsonParseUtil.parsePost(response, Constant.REFRESH_DATA);
List<PostCache> postCaches = postBox.query().orderDesc(PostCache_.time).build().find();
List<PostItem> items = new ArrayList<>();
for (PostCache post : postCaches) {
boolean isLike = Objects.requireNonNull(likeBox.query().equal(LikeCache_.pid, post.getId()).build().findUnique()).isLike();
items.add(new PostItem(post.getType(), post, isLike));
}
mSwipeRefresh.setRefreshing(false);
mAdapter.setNewData(items);
});
} else if (type == Constant.LOAD_MORE_DATA) {
long size = postBox.count();
if (size >= Constant.LOAD_MAX_SEVER) {
requestData(++page, Constant.LOAD_MORE_DATA, response -> {
JsonParseUtil.parsePost(response, Constant.LOAD_MORE_DATA);
List<PostItem> items = new ArrayList<>();
if (size == postBox.count()) {
mAdapter.loadMoreEnd(true);
return;
}
List<PostCache> postCaches = postBox.query().orderDesc(PostCache_.time).build().find(size, Constant.LOAD_MAX_DATABASE);
for (PostCache post : postCaches) {
boolean isLike = Objects.requireNonNull(likeBox.query().equal(LikeCache_.pid, post.getId()).build().findUnique()).isLike();
items.add(new PostItem(post.getType(), post, isLike));
}
mAdapter.addData(items);
mAdapter.loadMoreComplete();
});
} else {
mAdapter.loadMoreEnd(true);
}
}
}
/**
* 从服务器下载数据到数据库
*
* @param page 页数
* @param type 加载类型(刷新数据,加载更多)
*/
private void requestData(int page, int type, ISuccess success) {
if (type == Constant.REFRESH_DATA) {
RestClient.builder()
.url(Api.GET_POST_BY_UID_THUMBSUP)
.params("pageNo", page)
.params("pageSize", Constant.LOAD_MAX_SEVER)
.params("uid", uid)
.success(success)
.error((code, msg) -> {
Toasty.error(Objects.requireNonNull(this), "加载失败" + code, Toasty.LENGTH_SHORT).show();
mSwipeRefresh.setRefreshing(false);
})
.build()
.get();
} else if (type == Constant.LOAD_MORE_DATA) {
RestClient.builder()
.url(Api.GET_POST_BY_UID_THUMBSUP)
.params("pageNo", page)
.params("pageSize", Constant.LOAD_MAX_SEVER)
.params("uid", uid)
.success(success)
.error((code, msg) -> Toasty.error(Objects.requireNonNull(this), "加载失败" + code, Toasty.LENGTH_SHORT).show())
.build()
.get();
}
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
|
C
|
UTF-8
| 4,810 | 3.296875 | 3 |
[] |
no_license
|
/*
* day5.c
* Advent of Code - 2019 - Day 5
* https://adventofcode.com/2019/day/5
*
* Chad Gibbons
* December 9, 2019
*/
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INTCODE_BUFFER 1000
/* forward reference for internal functions */
static int read_intcode(const char* input_filename,
int** intcode_data, size_t* intcode_size);
static void run_intcode(int* intcode_data, size_t intcode_size);
int main(int argc, char* argv[])
{
int rc = EXIT_SUCCESS;
if (argc != 2) {
fprintf(stderr, "Usage: %s [input data]\n", argv[0]);
rc = EXIT_FAILURE;
} else {
const char* input_filename = argv[1];
int* intcode = NULL;
size_t intcode_size = 0;
if (read_intcode(input_filename, &intcode, &intcode_size) < 0) {
perror("unable to read intcode");
rc = EXIT_FAILURE;
} else {
printf("initial intcode data:\n");
for (int i = 0; i < intcode_size; i++) {
printf("%d", intcode[i]);
if (i < intcode_size-1) {
printf(",");
}
}
puts("\n");
run_intcode(intcode, intcode_size);
}
}
return rc;
}
static int read_intcode(const char* input_filename,
int** intcode_data, size_t* intcode_size)
{
assert(input_filename != NULL);
assert(intcode_data != NULL);
assert(intcode_size != NULL);
FILE* fp = fopen(input_filename, "r");
if (fp == NULL) {
perror(input_filename);
return errno;
}
int tmp_size = 0;
int* tmp_data = calloc(MAX_INTCODE_BUFFER, sizeof(int));
if (!tmp_data) {
return errno;
}
char buffer[BUFSIZ]; // TODO: BUFSIZ big enough for input? hmm
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
char* endptr = NULL;
char* ptr = buffer;
do {
long val = strtol(ptr, &endptr, 10);
if (*endptr == ',') endptr++;
if (isspace(*endptr)) endptr++;
tmp_data[tmp_size++] = (int)val;
ptr = endptr;
} while (endptr != NULL && *endptr != '\0' && tmp_size < MAX_INTCODE_BUFFER);
}
if (!feof(fp)) {
perror(input_filename);
return errno;
}
*intcode_data = tmp_data;
*intcode_size = tmp_size;
return 0;
}
static void run_intcode(int* intcode_data, size_t intcode_size)
{
int ip = 0;
printf("ip=%d intcode_data=%p intcode_size=%lu\n", ip, intcode_data, intcode_size);
while (ip < intcode_size) {
int raw_opcode = intcode_data[ip++];
printf("raw_opcode=%d\n", raw_opcode);
int opcode = raw_opcode % 100;
int param1_mode = raw_opcode / 100 % 10;
int param2_mode = raw_opcode / 1000 % 10;
int param3_mode = raw_opcode / 10000 % 10;
switch (opcode) {
case 1: // add
{
assert(param3_mode == 0);
int opa = intcode_data[ip++];
int opb = intcode_data[ip++];
int dest = intcode_data[ip++];
intcode_data[dest] =
(param1_mode ? opa : intcode_data[opa])
+ (param2_mode ? opb : intcode_data[opb]);
break;
}
case 2: // multiplies
{
assert(param3_mode == 0);
int opa = intcode_data[ip++];
int opb = intcode_data[ip++];
int dest = intcode_data[ip++];
intcode_data[dest] =
(param1_mode ? opa : intcode_data[opa])
* (param2_mode ? opb : intcode_data[opb]);
break;
}
case 3: // input
{
assert(param1_mode == 0);
char buffer[BUFSIZ];
printf("Input: ");
fflush(stdout);
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
abort();
} else {
long val = strtol(buffer, NULL, 10);
int dest = intcode_data[ip++];
intcode_data[dest] = (int)val;
printf("Stored %ld in [%d]\n", val, dest);
}
break;
}
case 4: // output
{
//assert(param1_mode == 0);
int dest = intcode_data[ip++];
int value = intcode_data[dest];
printf("value at [%d]=%d\n", dest, value);
break;
}
case 99:
{
printf("halt\n");
return;
}
}
}
}
|
Java
|
UTF-8
| 3,787 | 2.34375 | 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 Modelo;
import java.text.SimpleDateFormat;
/**
*
* @author scardonas
*/
public class Usuario {
private int id;
private int id_empresa;
private String tipo_perfil;
private String username;
private String pass;
private String nombres;
private String apellido1;
private String apellido2;
private String correo;
private String telefono;
private String direccion;
private String documento;
private String fecha_registro;
public Usuario() {
}
public Usuario(int id,int id_empresa, String tipo_perfil, String username, String pass, String nombres, String apellido1, String apellido2, String correo, String telefono, String direccion, String documento, String fecha_registro) {
this.id = id;
this.tipo_perfil = tipo_perfil;
this.username = username;
this.pass = pass;
this.nombres = nombres;
this.apellido1 = apellido1;
this.apellido2 = apellido2;
this.correo = correo;
this.telefono = telefono;
this.direccion = direccion;
this.documento = documento;
this.fecha_registro = fecha_registro;
}
public int getId_empresa() {
return id_empresa;
}
public void setId_empresa(int id_empresa) {
this.id_empresa = id_empresa;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTipo_perfil() {
return tipo_perfil;
}
public void setTipo_perfil(String tipo_perfil) {
this.tipo_perfil = tipo_perfil;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellido1() {
return apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
public String getFecha_registro() {
return fecha_registro;
}
public void setFecha_registro(String fecha_registro) {
this.fecha_registro = fecha_registro;
}
@Override
public String toString() {
return "Usuario{" + "id=" + id + ", tipo_perfil=" + tipo_perfil + ", username=" + username + ", pass=" + pass + ", nombres=" + nombres + ", apellido1=" + apellido1 + ", apellido2=" + apellido2 + ", correo=" + correo + ", telefono=" + telefono + ", direccion=" + direccion + ", documento=" + documento + ", fecha_registro=" + fecha_registro + '}';
}
}
|
Markdown
|
UTF-8
| 1,644 | 3.125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# How to Build the NGINX Router Image
In this guide we will build the NGINX Router image and upload it to the OpenShift private registry.
## Prerequisites
Before you can build the image, make sure that the following software is installed on your machine:
* [Docker](https://www.docker.com/products/docker)
* [git](https://git-scm.com/)
**Note**: the instructions assume that you run docker commands on one of the nodes of your OpenShift cluster. To be able to push the image to the `openshift` project, your user account must have admin access to the OpenShift cluster.
## Build the Image
1. Clone the NGINX Router repo and change your directory to `src/nginx`:
```
$ git clone https://github.com/nginxinc/nginx-openshift-router
$ cd nginx-openshift-router/src/nginx
```
1. Build the image:
```
$ docker build -t nginx-openshift-router:0.2 .
```
## Upload the Image to the OpenShift Private Registry
1. To upload the image to your private repository, you need to get login credentials for the private repository. Get those by logging into the registry portal, along with the correct URL syntax for the tag and push commands. Then, log in:
```
$ sudo docker login -p <your key> -e unused -u unused docker-registry-default.router.default.svc.cluster.local
```
1. Tag the image:
```
$ docker tag nginx-openshift-router:0.2 docker-registry-default.router.default.svc.cluster.local/openshift/nginx-openshift-router:0.2
```
1. Push the image to the registry:
```
$ docker push docker-registry-default.router.default.svc.cluster.local/openshift/nginx-openshift-router:0.2
```
|
Java
|
UTF-8
| 19,444 | 1.789063 | 2 |
[] |
no_license
|
package com.jmartinal.madridbusgps;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import com.jmartinal.madridbusgps.Fragments.AboutAppFragment;
import com.jmartinal.madridbusgps.Fragments.BusLinesRefreshFragment;
import com.jmartinal.madridbusgps.Fragments.BusRoutesFragment;
import com.jmartinal.madridbusgps.Fragments.BusRoutesMapFragment;
import com.jmartinal.madridbusgps.Fragments.BusScheduleTableFragment;
import com.jmartinal.madridbusgps.Fragments.BusSchedulesFragment;
import com.jmartinal.madridbusgps.Fragments.HomeFragment;
import com.jmartinal.madridbusgps.Fragments.NewRouteFragment;
import com.jmartinal.madridbusgps.Fragments.NewRouteListFragment;
import com.jmartinal.madridbusgps.Fragments.NewRouteMapFragment;
import com.jmartinal.madridbusgps.Model.BusLine;
import com.jmartinal.madridbusgps.Model.BusNetwork;
import com.jmartinal.madridbusgps.Model.BusSchedule;
import com.jmartinal.madridbusgps.Model.GeocodingLocation;
import com.jmartinal.madridbusgps.Model.Route;
import com.jmartinal.madridbusgps.Utils.Constants;
import com.jmartinal.madridbusgps.Utils.CreateBusNetworkTask;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnFragmentInteractionListener {
private String mTitle;
private Toolbar mToolbar;
private boolean mIsBackFromChildFragment;
private File mBusLinesFile;
private BusNetwork mBusNetwork;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mTitle = getResources().getString(R.string.section1);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_home);
onFragmentInteraction(1, mBusNetwork);
mIsBackFromChildFragment = false;
if (savedInstanceState == null || !savedInstanceState.containsKey("busLines")){
mBusLinesFile = new File(getExternalFilesDir(Constants.BUS_LINES_FILE_DIR), Constants.BUS_LINES_FILE_NAME);
if (mBusLinesFile.exists()){
new LoadingFileTask(this).execute();
} else {
new CreateBusNetworkTask(this, mBusNetwork).execute();
}
} else {
mBusNetwork = (BusNetwork) savedInstanceState.getSerializable("busNetwork");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("busNetwork", mBusNetwork);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.container);
if (currentFragment instanceof HomeFragment) {
RelativeLayout background = (RelativeLayout) findViewById(R.id.background);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
background.setBackgroundResource(R.drawable.emt_wallpaper_portrait);
} else {
background.setBackgroundResource(R.drawable.emt_wallpaper_landscape);
}
}
super.onConfigurationChanged(newConfig);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Fragment fragment = getFragmentManager().findFragmentById(R.id.container);
int position = fragment.getArguments().getInt("section_number");
boolean isChild = fragment.getArguments().getInt("child_number") != 0;
if (position == 1){
// Backing from HomeFragment
// Starting the "Desktop" activity instead of calling finish() will avoid the file load until we exit this app
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
} else {
/* Backing from other fragment.
- If backing from any drawerList fragment, redirect to HomeFragment
- If not backing from any drawerList fragment, redirect to it's parent fragment
*/
if (!isChild) {
position = 1;
} else {
mIsBackFromChildFragment = true;
}
getFragmentManager().beginTransaction().remove(fragment).commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
onFragmentInteraction(position, mBusNetwork);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
onFragmentInteraction(1, (BusNetwork) null);
} else
if (id == R.id.nav_new_route) {
onFragmentInteraction(2, mBusNetwork);
} else if (id == R.id.nav_routes) {
onFragmentInteraction(3, mBusNetwork);
} else if (id == R.id.nav_schedules) {
onFragmentInteraction(4, mBusNetwork);
} else if (id == R.id.nav_bus_refresh) {
onFragmentInteraction(5, mBusNetwork);
} else if (id == R.id.nav_about) {
onFragmentInteraction(6, (BusNetwork) null);
} else if (id == R.id.nav_exit) {
onFragmentInteraction(7, mBusNetwork);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
// onFragmentInteraction for app's side menu's options
@Override
public void onFragmentInteraction(int position, BusNetwork busNetwork) {
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.container);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
switch (position){
case 1: // Home
mTitle = getResources().getString(R.string.section1);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_home);
Fragment homeFragment = HomeFragment.newInstance(position);
FragmentTransaction homeTransaction = getFragmentManager().beginTransaction();
homeTransaction.replace(R.id.container, homeFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commitAllowingStateLoss();
break;
case 2: // New route
mTitle = getResources().getString(R.string.section2);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_new_route);
if (!(currentFragment instanceof NewRouteFragment) || mIsBackFromChildFragment) {
Fragment newRouteFragment = NewRouteFragment.newInstance(position, busNetwork);
FragmentTransaction newRouteTransaction = getFragmentManager().beginTransaction();
newRouteTransaction.replace(R.id.container, newRouteFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
mIsBackFromChildFragment = false;
}
break;
case 3: // Bus routes
mTitle = getResources().getString(R.string.section3);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_routes);
Fragment busRoutesFragment = BusRoutesFragment.newInstance(position, busNetwork);
FragmentTransaction busRoutesTransaction = getFragmentManager().beginTransaction();
busRoutesTransaction.replace(R.id.container, busRoutesFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
break;
case 4: // Bus schedules
mTitle = getResources().getString(R.string.section4);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_schedules);
Fragment schedulesFragment = BusSchedulesFragment.newInstance(position, busNetwork);
FragmentTransaction schedulesTransaction = getFragmentManager().beginTransaction();
schedulesTransaction.replace(R.id.container, schedulesFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
break;
case 5: // Refresh bus lines' file
mTitle = getResources().getString(R.string.section5);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_bus_refresh);
Fragment refreshBusLinesFragment = BusLinesRefreshFragment.newInstance(position, busNetwork);
FragmentTransaction refreshTransaction = getFragmentManager().beginTransaction();
refreshTransaction.replace(R.id.container, refreshBusLinesFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commitAllowingStateLoss();
break;
case 6: // About the app
mTitle = getResources().getString(R.string.section6);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_about);
Fragment aboutAppFragment = AboutAppFragment.newInstance(position);
FragmentTransaction aboutAppTransaction = getFragmentManager().beginTransaction();
aboutAppTransaction.replace(R.id.container, aboutAppFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
break;
case 7: // Exit
navigationView.setCheckedItem(R.id.nav_exit);
finish();
break;
}
}
// onFragmentInteraction for new route fragment's children
@Override
public void onFragmentInteraction(int childNumber, GeocodingLocation from, GeocodingLocation to, Route route) {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
switch (childNumber){
case 1: // Display route on map
mTitle = getResources().getString(R.string.section2_1);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_new_route);
Fragment newRouteMapFragment = NewRouteMapFragment.newInstance(2, childNumber, from, to, route);
FragmentTransaction newRouteMapTransaction = getFragmentManager().beginTransaction();
newRouteMapTransaction.replace(R.id.container, newRouteMapFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commitAllowingStateLoss();
break;
case 2: // Show route as list
mTitle = getResources().getString(R.string.section2_2);
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_new_route);
Fragment newRouteListFragment = NewRouteListFragment.newInstance(2, childNumber, from, to, route);
FragmentTransaction newRouteListTransaction = getFragmentManager().beginTransaction();
newRouteListTransaction.replace(R.id.container, newRouteListFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
break;
}
}
// onFragmentInteraction for bus routes fragment's children
@Override
public void onFragmentInteraction(int childNumber, BusLine busLine, boolean showDeparture, boolean showDetour, boolean showStops) {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
switch (childNumber) {
case 1: // Show bus route on map
mTitle = busLine.toString();
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_routes);
Fragment busRoutesMapFragment = BusRoutesMapFragment.newInstance(3, childNumber, busLine, showDeparture, showDetour, showStops);
FragmentTransaction busRoutesMapTransaction = getFragmentManager().beginTransaction();
busRoutesMapTransaction.replace(R.id.container, busRoutesMapFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
break;
}
}
// onFragmentInteraction for bus schedules fragment's children
@Override
public void onFragmentInteraction(int childNumber, BusSchedule busSchedule) {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
mTitle = "Línea " + busSchedule.getLineId() + ": " + busSchedule.getHeaderA() + " - " + busSchedule.getHeaderB();
mToolbar.setTitle(mTitle);
navigationView.setCheckedItem(R.id.nav_schedules);
Fragment busScheduleTableFragment = BusScheduleTableFragment.newInstance(4, childNumber, busSchedule);
FragmentTransaction busScheduleTableTransaction = getFragmentManager().beginTransaction();
busScheduleTableTransaction.replace(R.id.container, busScheduleTableFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commit();
}
private class LoadingFileTask extends AsyncTask<Void, Void, BusNetwork> {
private Dialog dialog;
private Activity activity;
private ArrayList<Exception> exceptions;
public LoadingFileTask(Activity activity) {
this.dialog = new Dialog(activity, R.style.LoadingDialogTheme);
this.activity = activity;
this.exceptions = null;
}
@Override
protected void onPreExecute() {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
dialog.getWindow();
dialog.setContentView(R.layout.loading_route_message);
dialog.setTitle(R.string.loading_file_title);
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(BusNetwork loadedNetwork) {
dialog.dismiss();
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
if (this.exceptions != null){
AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.ErrorDialogTheme);
builder.setTitle(R.string.loading_file_error_title);
builder.setMessage(R.string.loading_file_error_message);
builder.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
activity.finish();
}
});
dialog = builder.create();
dialog.show();
mBusLinesFile.delete();
} else {
mBusNetwork = loadedNetwork;
}
super.onPostExecute(loadedNetwork);
}
@Override
protected BusNetwork doInBackground(Void... params) {
BusNetwork loadedNetwork;
FileInputStream fis;
try {
fis = new FileInputStream(mBusLinesFile);
ObjectInputStream ois = new ObjectInputStream(fis);
loadedNetwork = (BusNetwork) ois.readObject();
ois.close();
} catch (Exception e) {
this.exceptions = new ArrayList<>();
exceptions.add(e);
return null;
}
return loadedNetwork;
}
}
public BusNetwork getmBusNetwork() {
return mBusNetwork;
}
public void setmBusNetwork(BusNetwork mBusNetwork) {
this.mBusNetwork = mBusNetwork;
}
}
|
Python
|
UTF-8
| 1,310 | 3.578125 | 4 |
[] |
no_license
|
import pygame
from sprite import Sprite
class Player(Sprite):
STEP = 0.5
def __init__(self, x, y):
self.dimension = 13
super().__init__(x, y)
def render(self, screen):
rx = self.x + self.dimension
ry = self.y + self.dimension
pygame.draw.circle(screen, (255,255,0), (rx, ry), self.dimension)
def checkWalls(self, walls):
for wall in walls:
if self.getRect().colliderect(wall):
print("wall collided with player")
return
def __isLecitMove(self, x, y, walls):
r = pygame.Rect(self.x + x, self.y + y, 2*self.dimension, 2*self.dimension);
for wall in walls:
if r.colliderect(wall):
return False
return True
def jumpTo(self, x, y):
self.x = x
self.y = y
def moveUpSafe(self, walls):
if self.__isLecitMove(0, -(self.STEP), walls):
self.moveUp()
def moveDownSafe(self, walls):
if self.__isLecitMove(0, self.STEP, walls):
self.moveDown()
def moveLeftSafe(self, walls):
if self.__isLecitMove(-(self.STEP), 0, walls):
self.moveLeft()
def moveRightSafe(self, walls):
if self.__isLecitMove(self.STEP, 0, walls):
self.moveRight()
|
Markdown
|
UTF-8
| 1,944 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
---
date: '2018-09-30'
user_name: 朱翔
user_intro: ''
upvote: 78
downvote: 0
comments:
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
- ''
---
说是党卫军都是在抬举它。因为其实党也是个虚化的概念。中共已经不是一个真正意义上的政党,因为没有真正的政治诉求,没有稳定的理念传承,没有落实的党章、规则、决策程序。这其实只是独裁者的白手套(虽然党这个白手套本身也是够黑的)。不仅民意是被强奸的,其实广大党员的党意也是被强奸的。归根到底,权力是在黑帮似的独裁利益集团手里。它以党的领导的名义控制党,再以党的名义控制国家,再以国家的名义控制人民。最大的邪恶就是经过这样一层层的包装洗白,才得以在国际上大言不惭地代表中国人民说什么人民的选择。这可以作为一个欺诈控制的心理学经典案例,值得好好分析。
解放军效忠的不是国家、人民,也不是党,而是把握了党权的黑老大。所以,不是党卫军,只是黑帮打手、私家军、黑老大的看门狗而已。
实例证明。在六四中,党的领导是赵紫阳,人大是万里,军委是邓小平。按党的纪律,应该是党领导枪,按照法律,军队进城需要中央军委中央军委第一副主席赵紫阳签字的书面调令(徐勤先因为这个原因拒绝执行)。但是,军队竟然可以没有赵紫阳签字而悍然进城开枪杀人,罢免党的总书记,性质上是犯罪、军事政变,不忠于党、人大、法律,更不要说是忠于枪口所指的街头抗议的人民。它效忠的是一个霸凌党领导的但是无权干政的军委老大,实质上的违法乱纪的实权黑老大。
|
PHP
|
UTF-8
| 1,186 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
namespace VeeWee\Tests\Xml\Writer\Builder;
use PHPUnit\Framework\TestCase;
use VeeWee\Tests\Xml\Writer\Helper\UseInMemoryWriterTrait;
use VeeWee\Xml\Writer\Writer;
use XMLWriter;
use function VeeWee\Xml\Writer\Builder\element;
use function VeeWee\Xml\Writer\Builder\value;
final class ElementTest extends TestCase
{
use UseInMemoryWriterTrait;
public function test_it_can_create_self_closing_element(): void
{
$result = $this->runInMemory(static function (XMLWriter $xmlWriter): void {
$writer = Writer::fromUnsafeWriter($xmlWriter);
$writer->write(
element('root')
);
});
static::assertXmlStringEqualsXmlString('<root />', $result);
}
public function test_it_can_create_element_with_value(): void
{
$result = $this->runInMemory(static function (XMLWriter $xmlWriter): void {
$writer = Writer::fromUnsafeWriter($xmlWriter);
$writer->write(
element('hello', value('world'))
);
});
static::assertXmlStringEqualsXmlString('<hello>world</hello>', $result);
}
}
|
JavaScript
|
UTF-8
| 730 | 2.59375 | 3 |
[] |
no_license
|
$(document).ready(function () {
$(".submit").click(function (event) {
event.preventDefault();
var user_name = $("input#name").val();
var password = $("input#pwd").val();
jQuery.ajax({
type: "POST",
url: " //echo base_url(); ?>" + "pages/user_data_submit",
dataType: 'json',
data: {name: user_name, pwd: password},
success: function (res) {
if (res) {
// Show Entered Value
jQuery("div#result").show();
jQuery("div#value").html(res.username);
jQuery("div#value_pwd").html(res.pwd);
}
}
});
});
});
|
C++
|
UHC
| 8,344 | 3.1875 | 3 |
[] |
no_license
|
#include "cBST.h"
#include "cNode.h"
#include <iostream>
#include <assert.h>
#include <stack>
cBST::cBST()
:m_pRoot(nullptr)
{
}
cBST::~cBST()
{
Clear();
}
#define RECURSIVE_CLEAR 1
void cBST::Clear()
{
#if RECURSIVE_CLEAR
if(m_pRoot)
m_pRoot->Destroy();
m_pRoot = nullptr;
#else
PostorderSearch([](cNode* node) {delete node; });
#endif
}
void cBST::Insert(int n)
{
if (m_pRoot == nullptr) {
m_pRoot = new cNode(n);
return;
}
m_pRoot->Insert(n);
}
#define DELETE_IMPL 2
void cBST::Delete(int n)
{
#if DELETE_IMPL==0
if (m_pRoot == nullptr)
return;
cNode * nodeToDelete = m_pRoot;
cNode * parentOfNodeToDelete = nullptr;
//ߵ 带 ã´.
do {
if (nodeToDelete->m_nData == n)
break;
parentOfNodeToDelete = nodeToDelete;
if (n < nodeToDelete->m_nData)
nodeToDelete = nodeToDelete->m_pLChild;
else
nodeToDelete = nodeToDelete->m_pRChild;
} while (nodeToDelete);
if (nodeToDelete) {
cNode* newNode = nullptr;
if (nodeToDelete->m_pLChild && nodeToDelete->m_pRChild) {
// 尡 ڽ ִ
cNode * parentOfReplacingNode = nodeToDelete;
cNode * replacingNode = nodeToDelete->m_pRChild;//ʿ ü 带 ã´.
// ڽ ã´.
while (replacingNode->m_pLChild) {
parentOfReplacingNode = replacingNode;
replacingNode = replacingNode->m_pLChild;
}
if (parentOfReplacingNode == nodeToDelete) {
//Ϸ ٷ ڽ ü ̴.
replacingNode->m_pLChild = nodeToDelete->m_pLChild;
//ü Ʈ ״ üȴ.
}
else {
//ü ( ) Ʈ ü θ ʿ Ѵ.
//ü ڽ ʱ ڽ Ű澲 ʾƵ ȴ.
parentOfReplacingNode->m_pLChild = replacingNode->m_pRChild;
//Ϸ ¿ ڽ ü 忡 ش.
replacingNode->m_pLChild = nodeToDelete->m_pLChild;
replacingNode->m_pRChild = nodeToDelete->m_pRChild;
}
//ü 带 Ϸ θ Ѵ.
if (parentOfNodeToDelete) {
if (parentOfNodeToDelete->m_pLChild == nodeToDelete)
parentOfNodeToDelete->m_pLChild = replacingNode;
else
parentOfNodeToDelete->m_pRChild = replacingNode;
}
else {
//Ϸ 尡 Ʈ
m_pRoot = replacingNode;
}
}
else if (nodeToDelete->m_pLChild) {
//Ϸ 尡 ڽĸ ִ
if (parentOfNodeToDelete) {
if (parentOfNodeToDelete->m_pLChild == nodeToDelete)
parentOfNodeToDelete->m_pLChild = nodeToDelete->m_pLChild;
else
parentOfNodeToDelete->m_pRChild = nodeToDelete->m_pLChild;
}
else {
//Ϸ 尡 Ʈ
m_pRoot = nodeToDelete->m_pLChild;
}
}
else if (nodeToDelete->m_pRChild) {
//Ϸ 尡 ڽĸ ִ
if (parentOfNodeToDelete) {
if (parentOfNodeToDelete->m_pLChild == nodeToDelete)
parentOfNodeToDelete->m_pLChild = nodeToDelete->m_pRChild;
else
parentOfNodeToDelete->m_pRChild = nodeToDelete->m_pRChild;
}
else {
//Ϸ 尡 Ʈ
m_pRoot = nodeToDelete->m_pRChild;
}
}
else {
//Ϸ 尡
if (parentOfNodeToDelete) {
if (parentOfNodeToDelete->m_pLChild == nodeToDelete)
parentOfNodeToDelete->m_pLChild = nullptr;
else
parentOfNodeToDelete->m_pRChild = nullptr;
}
else {
//Ϸ 尡 Ʈ
m_pRoot = nullptr;
}
}
delete nodeToDelete;
}
#elif DELETE_IMPL == 1
if (m_pRoot == nullptr)
return;
cNode * nodeToDelete = m_pRoot;
cNode * parentOfNodeToDelete = nullptr;
//ߵ 带 ã´.
do {
if (nodeToDelete->m_nData == n)
break;
parentOfNodeToDelete = nodeToDelete;
if (n < nodeToDelete->m_nData)
nodeToDelete = nodeToDelete->m_pLChild;
else
nodeToDelete = nodeToDelete->m_pRChild;
} while (nodeToDelete);
if (nodeToDelete) {
int countBefore = Count();
cNode * parentOfReplacingNode = nodeToDelete;
cNode * replacingNode = nodeToDelete->m_pRChild;//ʿ ü 带 ã´.
if (replacingNode == nullptr) {
//ʿ ڽ 尡 ϳ
if (parentOfNodeToDelete) {
// Ϸ θ Ϸ Ʈ Ѵ.
if (parentOfNodeToDelete->m_pLChild == nodeToDelete)
parentOfNodeToDelete->m_pLChild = nodeToDelete->m_pLChild;
else
parentOfNodeToDelete->m_pRChild = nodeToDelete->m_pLChild;
}
else {
//nodeToDelete Ʈ
// ڽ Ʈ ø.
m_pRoot = m_pRoot->m_pLChild;
}
}
else {
//ʿ ڽ ã´.
while (replacingNode->m_pLChild) {
parentOfReplacingNode = replacingNode;
replacingNode = replacingNode->m_pLChild;
}
// Ʈ θ ʿ Ѵ.
// ڽ ϱ Ű澵 ʿ .
if (parentOfReplacingNode != nodeToDelete)
parentOfReplacingNode->m_pLChild = replacingNode->m_pRChild;
else
parentOfReplacingNode->m_pRChild = replacingNode->m_pRChild;
// / ڽ üǴ 忡 ش.
replacingNode->m_pLChild = nodeToDelete->m_pLChild;
replacingNode->m_pRChild = nodeToDelete->m_pRChild;
if (parentOfNodeToDelete) {
// Ϸ θ ü Ų.
if (parentOfNodeToDelete->m_pLChild == nodeToDelete)
parentOfNodeToDelete->m_pLChild = replacingNode;
else
parentOfNodeToDelete->m_pRChild = replacingNode;
}
else {
m_pRoot = replacingNode;
}
}
assert(countBefore - 1 == Count());
delete nodeToDelete;
}
#elif DELETE_IMPL == 2
if (m_pRoot)
m_pRoot->Delete(&m_pRoot, n);
#endif
}
#define RECURSIVE_PRINT 0
void cBST::Print()
{
#if RECURSIVE_PRINT
if (m_pRoot)
m_pRoot->Print();
#else
if (m_pRoot == nullptr)
return;
InorderSearch([](cNode* node) {std::cout << node->m_nData<< std::endl; });
#endif
}
void cBST::InorderSearch(std::function<void(cNode*)> func)
{
std::stack<cNode*> nodes;
//Ʈ ÿ Ѵ.
//ÿ popǴ ش Ʈ 湮Ǿ Ѵ.
cNode* current = m_pRoot;
while (current) {
nodes.push(current);
current = current->m_pLChild;
}
while (nodes.empty() == false) {
cNode* top = nodes.top();
nodes.pop();
// Ʈ 湮ϱ 带 湮Ѵ.
func(top);
if (top->m_pRChild) {
// Ʈ Ʈ ÿ Ѵ.
cNode* current = top->m_pRChild;
while (current) {
nodes.push(current);
current = current->m_pLChild;
}
}
}
}
void cBST::PostorderSearch(std::function<void(cNode*)> func)
{
//std::stack<cNode*> nodes;
//cNode* root = m_pRoot;
//while (root != nullptr) {
// if (root->m_pRChild) {
// nodes.push(root->m_pRChild);
// }
// nodes.push(root);
// root = root->m_pLChild;
//}
//while (nodes.empty() == false) {
// root = nodes.top();
// nodes.pop();
//}
}
#define RECURSIVE_COUNT 0
int cBST::Count()
{
if (m_pRoot == nullptr)
return 0;
#if RECURSIVE_COUNT
int count = 0;
m_pRoot->Count(count);
return count;
#else
int count = 0;
InorderSearch([&count](cNode*) {++count; });
return count;
#endif
}
bool cBST::Find(int n)
{
return FindNode(n) != nullptr;
}
cNode * cBST::FindNode(int n)
{
if (m_pRoot == nullptr)
return nullptr;
cNode* node = m_pRoot;
do {
if (node->m_nData == n) {
return node;
}
if (n < node->m_nData)
node = node->m_pLChild;
else
node = node->m_pRChild;
} while (node);
return node;
}
|
Python
|
UTF-8
| 877 | 2.90625 | 3 |
[] |
no_license
|
from Tokenize import *
from ConvertTokensToPython import *
import sys
def main():
if len(sys.argv)>1:
interpreter(True)
else:
interpreter(False)
def interpreter(fileOrNot):
if fileOrNot:
inputFile=open(sys.argv[1])
inputFileLines=inputFile.readlines()
outputFileS='open(sys.argv[1][:len(sys.argv[1])-2]+".py", "w")'
for line in inputFileLines:
if line.startswith("//") or line=='':
continue
tokens=tokenize(line)
for token in tokens:
print(f"'{token}', ", end="")
print()
print ("Python:\n", ConvertTokensToPython(token for token in tokens))
print()
else:
command=''
while True:
command=input("MMM--> ")
if command in ['quit', 'quit()', 'q']:
exit()
if command=="":
continue
print(tokensToPython(tokenize(command)))
if __name__=="__main__":
# try:
main()
# except EOFError:
# print()
# exit()
|
PHP
|
UTF-8
| 10,407 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace Quartz\Connection;
/**
* Description of MysqliConnection
*
* @author paul
*/
class MysqliConnection extends Connection
{
protected $mysqli;
protected $rLastQuery;
protected $sLastQuery;
protected $isPersistant = false;
public function configure()
{
$this->registerConverter('Array', new \Quartz\Converter\MySQL\ArrayConverter($this), array());
$this->registerConverter('Boolean', new \Quartz\Converter\MySQL\BooleanConverter(), array('bool', 'boolean'));
$this->registerConverter('Number', new \Quartz\Converter\MySQL\NumberConverter(), array('int2', 'int4', 'int8', 'numeric', 'float4', 'float8', 'integer', 'sequence'));
$this->registerConverter('String', new \Quartz\Converter\MySQL\StringConverter(), array('varchar', 'char', 'text', 'uuid', 'tsvector', 'xml', 'bpchar', 'string', 'enum'));
$this->registerConverter('Timestamp', new \Quartz\Converter\MySQL\TimestampConverter(), array('timestamp', 'date', 'time', 'datetime', 'unixtime'));
$this->registerConverter('HStore', new \Quartz\Converter\MySQL\HStoreConverter(), array('hstore'));
//$this->registerConverter('Interval', new Converter\PgInterval(), array('interval'));
//$this->registerConverter('Binary', new Converter\PgBytea(), array('bytea'));
}
/* public function __construct($hostname, $user, $password, $dbname, $extra = array())
{
$this->hostname = $hostname;
$this->user = $user;
$this->password = $password;
$this->dbname = $dbname;
$this->extra = $extra;
} */
public function connect()
{
$host = $this->hostname;
$port = 3306;
if (preg_match('#^(.*?):([0-9]+)$#', $host, $m))
{
$host = $m[1];
$port = $m[2];
}
if (isset($this->extra['persistant']) && $this->extra['persistant'])
{
$host = 'p:' . $host;
$this->isPersistant = true;
}
$this->mysqli = new \mysqli($host, $this->user, $this->password, $this->dbname, $port);
if (\mysqli_connect_error())
{
throw new \RuntimeException("CONNECTION ERROR To(" . $this->hostname . ") : " . $this->error());
}
$this->closed = false;
}
public function close()
{
$this->closed = true;
if (!$this->isPersistant)
$this->mysqli->close();
}
public function isClosed()
{
return $this->closed;
}
public function &getConnection()
{
return $this->mysqli;
}
public function convertClassType($type)
{
$rootType = $type;
$extra = '';
if (preg_match('#^(.*?)(([\(\[])(.*?)([\)\]]))$#', $rootType, $m))
{
$rootType = $m[1];
$extra = $m[2];
}
switch ($rootType)
{
case 'string':
return 'varchar' . $extra;
default:
return $type;
}
}
protected function escapeBinary($value)
{
return $value;
}
protected function escapeString($value)
{
return $this->mysqli->real_escape_string($value);
}
public function getSequence($table, $key, array $options = array())
{
throw new \RuntimeException('Not implemented yet.');
}
public function command(array $options = array())
{
$query = isset($options['query']) ? $options['query'] : null;
$buffered = isset($options['buffered']) ? $options['buffered'] : false;
if (isset($options['fetch']) && $options['fetch'])
{
$res = $this->query($query, $buffered);
if (is_callable($options['fetch']))
{
return $this->fall($res, $options['fetch']);
}
return $this->fall($res);
}
return $this->query($query, $buffered);
}
public function count($table, array $criteria = array())
{
$tableName = ($table instanceof \Quartz\Object\Table) ? $table->getName() : $table;
$where = array();
foreach ($criteria as $k => $v)
{
if (is_int($k))
{
$where[] = $v;
} else
{
$where[] = "$k = " . $this->castToSQL($v);
}
}
if (count($where) == 0)
{
$where[] = "1 = 1";
}
$query = 'SELECT COUNT(*) as nb FROM ' . $tableName . ' WHERE ' . implode(' AND ', $where) . ';';
$res = $this->query($query);
$row = $this->farray($res);
$this->free($res);
return $row['nb'];
}
public function find($table, array $criteria = array(), $order = null, $limit = null, $offset = 0, $forUpdate = false)
{
$orderby = null;
if (!is_null($order))
{
if (is_array($order))
{
$orderby = array();
foreach ($order as $k => $sort)
{
$orderby[] = $k . ( ($sort === 1) ? ' ASC' : ' DESC');
}
$orderby = implode(', ', $orderby);
} else
{
$orderby = $order;
}
}
$where = array();
foreach ($criteria as $k => $v)
{
if (is_int($k))
{
$where[] = $v;
} else
{
$where[] = "$k = " . $this->castToSQL($v);
}
}
$tableName = ($table instanceof \Quartz\Object\Table) ? $table->getName() : $table;
$query = 'SELECT * FROM ' . $tableName
. (empty($where) ? '' : ' WHERE ' . implode(' AND ', $where) )
. (is_null($orderby) || empty($orderby) ? '' : ' ORDER BY ' . $orderby )
. (is_null($limit) ? '' : ' LIMIT ' . $limit . (is_null($offset) ? '' : ', ' . $offset));
if( $forUpdate )
{
$query .= ' FOR UPDATE';
}
$res = $this->query($query);
$rows = $this->fall($res);
$this->free($res);
return $rows;
}
public function insert(\Quartz\Object\Table $table, $object)
{
$query = 'INSERT INTO ' . $table->getName() . ' (' . implode(",", array_keys($object)) . ") VALUES (" . implode(",", $object) . ");";
$this->query($query);
return $object;
}
public function update($table, $query, $object, $options = array())
{
$self = $this;
$callback = function($k, $v) use($self)
{
return " $k = " . $v . " ";
};
$where = array();
foreach ($query as $k => $v)
{
if (is_int($k))
{
$where[] = $v;
} else
{
$where[] = "$k = " . $this->castToSQL($v);
}
}
$tableName = ($table instanceof \Quartz\Object\Table) ? $table->getName() : $table;
$query = "UPDATE " . $tableName . " SET ";
$query .= implode(", ", array_map($callback, array_keys($object), $object));
$query .= " WHERE " . implode(' AND ', $where) . ";";
return $this->query($query);
}
public function delete(\Quartz\Object\Table $table, $query, $options = array())
{
$where = array();
foreach ($query as $k => $v)
{
if (is_int($k))
{
$where[] = $v;
} else
{
$where[] = "$k = " . $this->castToSQL($v);
}
}
$tableName = ($table instanceof \Quartz\Object\Table) ? $table->getName() : $table;
$query = 'DELETE FROM ' . $tableName . ((count($where) > 0) ? ' WHERE ' . implode(' AND ', $where) : '' ) . ";";
return $this->query($query);
}
protected function __begin()
{
return $this->query('START TRANSACTION;');
}
protected function __commit()
{
return $this->query('COMMIT;');
}
protected function __rollback()
{
return $this->query('ROLLBACK;');
}
public function query($sQuery, $unbuffered = false)
{
if (is_null($sQuery))
{
return null;
}
if ($this->isClosed())
{
$this->connect();
}
$this->sLastQuery = $sQuery;
$this->rLastQuery = \mysqli_query($this->mysqli, $sQuery);
if ($this->error())
throw new \RuntimeException($sQuery . "\n" . $this->error());
return $this->rLastQuery;
}
/* iResultType:
* MYSQLI_NUM: les indices du tableau sont des entiers.
* MYSQLI_ASSOC: les indices du tableau sont les noms des clefs
*/
public function farray($rQuery = null, $callback = null, $iResultType = MYSQLI_ASSOC)
{
$iResultType = ($iResultType == null) ? MYSQLI_ASSOC : $iResultType;
if ($rQuery == null)
$rQuery = $this->rLastQuery;
$row = \mysqli_fetch_array($rQuery, $iResultType);
if ($row && !is_null($callback) && is_callable($callback))
{
$row = $callback($row);
}
return $row;
}
public function fall($rQuery = null, $callback = null, $iResultType = MYSQLI_ASSOC)
{
$iResultType = ($iResultType == null) ? MYSQLI_ASSOC : $iResultType;
$result = array();
while ($row = $this->farray($rQuery, $callback, $iResultType))
{
$result[] = $row;
}
return $result;
}
public function free($rQuery = null)
{
if ($rQuery == null)
$rQuery = $this->rLastQuery;
return \mysqli_free_result($rQuery);
}
/* Renvoie le dernier id de la requete INSERT */
public function lastid()
{
return @\mysqli_insert_id();
}
public function error()
{
if( $this->mysqli && \mysqli_connect_error() ){
return sprintf("[%s] %s", \mysqli_connect_errno(), \mysqli_connect_error() );
}
}
public function castToSQL($value)
{
if (is_null($value))
{
return 'null';
}
if (is_string($value))
{
return "'$value'";
}
if (is_bool($value))
{
return $value ? "1" : "0";
}
return $value;
}
}
|
Python
|
UTF-8
| 1,705 | 3.0625 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from PySide import QtCore, QtGui
FIRST_COLUMN = 0
class Example(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setGeometry(300, 300, 350, 250)
self.setWindowTitle('Sorting')
self.initData()
self.initUI()
def initData(self):
names = ['Jack', 'Tom', 'Lucy', 'Bill', 'Jane']
self.model = QtGui.QStringListModel(names)
def initUI(self):
self.ui_names_tablev = QtGui.QTableView(self)
self.ui_names_tablev.setModel(self.model)
self.ui_names_tablev.setSortingEnabled(True)
ui_sort_btn = QtGui.QPushButton('Sort', self)
ui_sort_btn.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
self.ui_sort_type_cbx = QtGui.QCheckBox('Ascending', self)
self.ui_sort_type_cbx.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
ui_sort_btn.clicked.connect(self.sortItems)
hbox_layout = QtGui.QHBoxLayout()
hbox_layout.addWidget(self.ui_sort_type_cbx)
hbox_layout.addWidget(ui_sort_btn)
main_layout = QtGui.QVBoxLayout()
main_layout.addWidget(self.ui_names_tablev)
main_layout.addLayout(hbox_layout)
self.setLayout(main_layout)
def sortItems(self):
if self.ui_sort_type_cbx.isChecked():
self.ui_names_tablev.sortByColumn(FIRST_COLUMN, QtCore.Qt.AscendingOrder)
else:
self.ui_names_tablev.sortByColumn(FIRST_COLUMN, QtCore.Qt.DescendingOrder)
if __name__ == '__main__':
import sys
app = QtGui.QApplication([])
root = Example()
root.show()
sys.exit(app.exec_())
|
TypeScript
|
UTF-8
| 2,071 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import { validateIsString } from '../../utils/validations'
import MessageID from './MessageID'
import MessageRef from './MessageRef'
import ValidationError from '../../errors/ValidationError'
import StreamMessage, { StreamMessageType } from './StreamMessage'
// TODO refactor deserialization to separate class (Serializer<GroupKeyMessage>)
//
type GroupKeyMessageType = Omit<typeof GroupKeyMessage, 'new'> // remove new, don't care about how to construct since we have from/to methods
export default abstract class GroupKeyMessage {
// messageType -> class mapping
static classByMessageType: {
[key: number]: GroupKeyMessageType
} = {}
streamId: string
messageType: StreamMessageType
constructor(streamId: string, messageType: StreamMessageType) {
validateIsString('streamId', streamId)
this.streamId = streamId
StreamMessage.validateMessageType(messageType)
this.messageType = messageType
}
serialize(): string {
return JSON.stringify(this.toArray())
}
static deserialize(serialized: string, messageType: StreamMessageType): GroupKeyMessage {
if (!GroupKeyMessage.classByMessageType[messageType]) {
throw new ValidationError(`Unknown MessageType: ${messageType}`)
}
return GroupKeyMessage.classByMessageType[messageType].fromArray(JSON.parse(serialized))
}
static fromStreamMessage(streamMessage: StreamMessage): GroupKeyMessage {
return GroupKeyMessage.deserialize(streamMessage.getSerializedContent()!, streamMessage.messageType)
}
toStreamMessage(messageId: MessageID, prevMsgRef: MessageRef | null): StreamMessage {
return new StreamMessage({
messageId,
prevMsgRef,
content: this.serialize(),
messageType: this.messageType,
})
}
abstract toArray(): any[]
static fromArray(_arr: any[]): GroupKeyMessage {
// typescript doesn't support abstract static so have to do this
throw new Error('must be overridden')
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.